From 224935e0a0af5313f1c63dbf1e11854162272eff Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:00:21 -0600 Subject: [PATCH 1/9] docs(ui): define reasoning title and body display rule for 1.6.1 Co-Authored-By: Claude Opus 5.5 --- docs/ui/v4-chat-turn-render-units.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/ui/v4-chat-turn-render-units.md b/docs/ui/v4-chat-turn-render-units.md index d72e2892ef4..7affda13a21 100644 --- a/docs/ui/v4-chat-turn-render-units.md +++ b/docs/ui/v4-chat-turn-render-units.md @@ -148,6 +148,14 @@ reasoning row visible -> streaming state updates preserve the user's choice ``` +### Reasoning 标题与正文显示(1.6.1) + +Codex ACP 推理摘要每段以 `\n\n` 开头、以单独一行 `**标题**` 起始;存储原样保留,只在显示层(`reasoning.tsx`,消息流与分享页共用)处理: + +- 收起的触发器标题取正文中最后一个“整行即 `**标题**`”的行,去掉星号:运行中显示「正在思考 · 标题」,完成后显示「思考 · 标题 · 持续了 N 秒」(耗时文案不变)。 +- 运行中没有标题行时沿用旧规则,滚动显示最后一个非空行;完成后没有标题行时不显示标题(Claude 等引擎的长思考不把末行塞进标题)。 +- 展开正文仍按纯文本渲染(不引入 Markdown 解析,保证长思考流式性能):去掉首尾空行,连续 3 个以上换行折叠为一个空行;整行 `**标题**` 去掉星号并以加粗显示,其他 Markdown 记号保持原文。 + ## 状态面板 v4 聊天右上角恢复旧 ChatView status panel 语义,不使用摘要 pills: From f65f7febc383221c74190f652db7bdbb0bae9580 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:00:23 -0600 Subject: [PATCH 2/9] fix(ui): show codex reasoning titles without asterisks and trim body gaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit codex-acp starts every reasoning summary part with a blank line and a **Title** line. The plain-text body rendered those blank lines as a large gap and the running header showed the raw asterisks. Display layer only: headers now use the last bold title (running: 正在思考 · title; completed: 思考 · title · duration), and the body trims edge whitespace, collapses 3+ newlines and renders whole-line titles bold without asterisks. Co-Authored-By: Claude Opus 5.5 --- .../src/components/ai-elements/reasoning.tsx | 124 +++++++++++------- packages/ui/test/reasoningLayout.test.ts | 30 ++++- 2 files changed, 106 insertions(+), 48 deletions(-) diff --git a/packages/ui/src/components/ai-elements/reasoning.tsx b/packages/ui/src/components/ai-elements/reasoning.tsx index d665a859a5d..6ecf3f9517f 100644 --- a/packages/ui/src/components/ai-elements/reasoning.tsx +++ b/packages/ui/src/components/ai-elements/reasoning.tsx @@ -13,7 +13,7 @@ import { TID_CHAT_REASONING_CONTENT, TID_CHAT_REASONING_TRIGGER } from "@zcode/s import { BrainIcon, ChevronRightIcon } from "lucide-react"; import { useZCodeIntl } from "@/i18n/IntlProvider.js"; import { QueuedSummaryContent } from "@/ToolCallBlocks/QueuedSummaryContent.js"; -import type { ComponentProps, CSSProperties, ReactNode } from "react"; +import type { ComponentProps, CSSProperties } from "react"; import { EMPTY_SCROLL_MASK_STATE, getVerticalScrollMaskStyle, @@ -235,7 +235,6 @@ export const Reasoning = memo( ); export type ReasoningTriggerProps = ComponentProps & { - getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode; streamingText?: string; }; @@ -252,17 +251,44 @@ export function isReasoningSummaryOverflowing({ return scrollWidth > clientWidth + 1; } +// Codex ACP 推理摘要以单独一行 **标题** 开始每一段;只认整行,避免误吞正文里的行内加粗。 +const REASONING_TITLE_LINE = /^\*\*([^*\n]+)\*\*[ \t]*$/mu; +const REASONING_TITLE_LINES = new RegExp(REASONING_TITLE_LINE.source, "gmu"); + +/** + * 1.6.1:优先取最后一个 **标题** 行并去掉星号(修复前运行态直接显示带星号的原始行)。 + * 没有标题行时,运行态沿用“最后一个非空行”;完成态传 titleOnly,不把长思考末行塞进标题。 + */ export function resolveReasoningStreamingSummary( streamingText: string, + titleOnly = false, ): { key: string; text: string } | null { const lines = streamingText.replace(/\r\n?/gu, "\n").split("\n"); + let lastLine: { key: string; text: string } | null = null; for (let index = lines.length - 1; index >= 0; index -= 1) { const text = lines[index]?.trim() ?? ""; - if (text.length > 0) { - return { key: String(index), text }; + if (text.length === 0) { + continue; } + const title = REASONING_TITLE_LINE.exec(text)?.[1]?.trim(); + if (title) { + return { key: String(index), text: title }; + } + lastLine ??= { key: String(index), text }; } - return null; + return titleOnly ? null : lastLine; +} + +/** + * Bug 原因:codex-acp 每段推理摘要都以 "\n\n" 开头,存储层原样拼接, + * whitespace-pre-wrap 正文因此出现开头空白和段间大空隙。只在显示层去掉首尾空白、 + * 把 3 个以上换行折叠成一个空行,不改存储数据。 + */ +export function formatReasoningBody(text: string): string { + return text + .replace(/\r\n?/gu, "\n") + .trim() + .replace(/\n[ \t]*(?:\n[ \t]*){2,}/gu, "\n\n"); } const REASONING_SUMMARY_MASK = @@ -283,17 +309,13 @@ export function getReasoningSummaryMaskStyle(isOverflowing: boolean): CSSPropert } export const ReasoningTrigger = memo( - ({ - className, - children, - getThinkingMessage, - streamingText = "", - ...props - }: ReasoningTriggerProps) => { + ({ className, children, streamingText = "", ...props }: ReasoningTriggerProps) => { const { isStreaming, isOpen, duration } = useReasoning(); const { intl } = useZCodeIntl(); - const streamingSummary = - isStreaming && !isOpen ? resolveReasoningStreamingSummary(streamingText) : null; + const isRunningCollapsed = isStreaming && !isOpen; + const streamingSummary = isOpen + ? null + : resolveReasoningStreamingSummary(streamingText, !isStreaming); const streamingSummaryRef = useRef(null); const streamingSummaryTextRef = useRef(null); const [isStreamingSummaryOverflowing, setIsStreamingSummaryOverflowing] = useState(false); @@ -326,38 +348,25 @@ export const ReasoningTrigger = memo( return () => resizeObserver.disconnect(); }, [streamingSummary?.text]); - const thinkingMessage = - getThinkingMessage?.(isStreaming, duration) ?? - (isStreaming && !isOpen ? ( - - {intl.formatMessage({ id: "chat.reasoning.thinking" })} - - ) : duration === undefined ? ( - - {/* 完成态“思考”单独使用 semibold,比同列工具类型标签更粗。 - 统一为 medium,保持对话时间线的视觉层级一致。 */} - - {intl.formatMessage({ id: "chat.reasoning.thought" })} - - · - - {intl.formatMessage({ id: "chat.reasoning.durationFewSeconds" })} - - - ) : ( - - - {intl.formatMessage({ id: "chat.reasoning.thought" })} - - · - - {intl.formatMessage( - { id: "chat.reasoning.durationSeconds" }, - { seconds: String(duration) }, - )} - - - )); + const thinkingMessage = isRunningCollapsed ? ( + + {intl.formatMessage({ id: "chat.reasoning.thinking" })} + + ) : ( + // 完成态“思考”统一为 medium,保持对话时间线的视觉层级一致。 + + {intl.formatMessage({ id: "chat.reasoning.thought" })} + + ); + // 1.6.1:完成态标题位于“思考”与耗时之间:思考 · 标题 · 持续了 N 秒。 + const durationText = isRunningCollapsed + ? null + : duration === undefined + ? intl.formatMessage({ id: "chat.reasoning.durationFewSeconds" }) + : intl.formatMessage( + { id: "chat.reasoning.durationSeconds" }, + { seconds: String(duration) }, + ); return ( ) : null} + {durationText ? ( + <> + · + + {durationText} + + + ) : null} { const { isOpen, shouldRenderContent } = useReasoning(); const shouldRenderChildren = isOpen || shouldRenderContent || Boolean(forceMount); + // split 的捕获组落在奇数位:整行 **标题** 去星号后轻量加粗,其余保持纯文本。 + const bodyParts = useMemo( + () => formatReasoningBody(children).split(REASONING_TITLE_LINES), + [children], + ); const scrollRef = useRef(null); const contentRef = useRef(null); const autoFollowBottomRef = useRef(true); @@ -562,7 +584,15 @@ export const ReasoningContent = memo( ref={contentRef} className="min-w-0 whitespace-pre-wrap break-words text-foreground-subtlest" > - {children} + {bodyParts.map((part, index) => + index % 2 === 1 ? ( + + {part.trim()} + + ) : ( + part + ), + )} diff --git a/packages/ui/test/reasoningLayout.test.ts b/packages/ui/test/reasoningLayout.test.ts index 4d81338bbb6..44283950cd8 100644 --- a/packages/ui/test/reasoningLayout.test.ts +++ b/packages/ui/test/reasoningLayout.test.ts @@ -9,6 +9,7 @@ import { describe, expect, it } from "vitest"; import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js"; import { StoreProvider } from "@/store/StoreProvider.js"; import { + formatReasoningBody, getReasoningBottomDistance, getReasoningSummaryMaskStyle, isReasoningScrollAtBottom, @@ -93,7 +94,9 @@ describe("Reasoning layout", () => { it("renders expanded thought content as plain text instead of Markdown", () => { const html = renderReasoningContent("**阶段一**\n\n# 计划\n`命令`"); - expect(html).toContain("**阶段一**"); + // 1.6.1:整行 **标题** 去掉星号(仅加粗),其余 Markdown 记号仍保持原文。 + expect(html).not.toContain("**阶段一**"); + expect(html).toContain("阶段一"); expect(html).toContain("# 计划"); expect(html).toContain("`命令`"); expect(html).not.toContain(""); @@ -171,6 +174,31 @@ describe("Reasoning layout", () => { expect(resolveReasoningStreamingSummary(" \n\t ")).toBeNull(); }); + it("uses the last bold summary title without asterisks", () => { + const text = "\n\n**读取配置**\n\n先看入口。\n\n**定位根因**\n\n继续检查实现。"; + expect(resolveReasoningStreamingSummary(text)).toEqual({ key: "6", text: "定位根因" }); + expect(resolveReasoningStreamingSummary("没有标题。", true)).toBeNull(); + + const running = renderReasoningContent(text, { defaultOpen: false, isStreaming: true }); + expect(running).toContain("正在思考"); + expect(running).toContain("定位根因"); + expect(running).not.toContain("**"); + + const completed = renderReasoningContent(text, { + defaultOpen: false, + duration: 5, + isStreaming: false, + }); + expect(completed.indexOf("思考")).toBeLessThan(completed.indexOf("定位根因")); + expect(completed.indexOf("定位根因")).toBeLessThan(completed.indexOf("持续了 5 秒")); + }); + + it("trims and collapses blank lines in the expanded body", () => { + expect(formatReasoningBody("\n\n**标题**\n\n\n\n正文\n \n\n下一段\n\n")).toBe( + "**标题**\n\n正文\n\n下一段", + ); + }); + it("shows elapsed duration instead of the inline summary while streaming is expanded", () => { const html = renderReasoningContent("正在分析输入。", { defaultOpen: true, From 3b3426483cb4a9a00f74c735fd80ad38153b8107 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:03:46 -0600 Subject: [PATCH 3/9] docs(chat): spec for bold around bare autolinks Co-Authored-By: Claude Opus 5.5 --- docs/chat/markdown-bold-autolink.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 docs/chat/markdown-bold-autolink.md diff --git a/docs/chat/markdown-bold-autolink.md b/docs/chat/markdown-bold-autolink.md new file mode 100644 index 00000000000..88053619372 --- /dev/null +++ b/docs/chat/markdown-bold-autolink.md @@ -0,0 +1,23 @@ +# 加粗包裹裸 URL(当前事实) + +Assistant 正文中 `**http://127.0.0.1:21500/docs**。` 这类“加粗裸链接后紧跟中文标点”的写法,必须渲染为 `` 内的链接,链接地址不含 `**`。 + +## 规则 + +- GFM autolink literal 只剥离结尾的 `*`;`**` 后紧跟 `。`、`,`、`)` 等非空白字符时,`**` 会被吞进 URL。`@streamdown/cjk` 只在中文标点处截断链接,无法去掉 `**`。 +- `autolinkStrongRemarkPlugin`(`packages/ui/src/components/ai-elements/message.tsx`)只处理裸链接字面量(唯一文本子节点即 URL,含 `www.` 形式):在第一个 `**` 处截断链接文本与 URL,剩余部分作为后续文本;若链接前紧邻未配对的 `**`,把链接包成 `strong`。 +- 插件挂在 `messageCjkPlugin.remarkPluginsAfter` 末尾。Streamdown 的 remark 顺序为 cjk before → 应用 `remarkPlugins` → cjk after → math,修复必须在 cjk 的链接拆分之后执行。 +- 普通 `[text](url)` 链接、行内代码和代码块不受影响;流式中间态由 Streamdown 的未闭合 Markdown 补全后走同一插件。 + +## 验收 + +`packages/ui/test/messageMarkdownStrongAutolink.test.ts` 通过真实 `MessageResponse` 渲染覆盖: + +| 输入 | 期望 | +| ---------------------------------------- | --------------------------------------- | +| `**http://127.0.0.1:21500/docs**。` | strong 内链接 `…/docs`,后接 `。` | +| `**http://x.test/a**,后文` | strong 内链接 `http://x.test/a` | +| `(**https://example.com/p**)` | strong 内链接 `https://example.com/p` | +| `**www.example.com**。` | strong 内链接 `http://www.example.com/` | +| `**http://a.test/x** 后文` | 保持原有正确渲染 | +| `这是**加粗:**文字`、`**“引用”**的说明` | CJK 加粗保持正确 | From 46561d358cf81765343a2f92db606125f49c6b48 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:03:49 -0600 Subject: [PATCH 4/9] fix(ui): keep ** out of bare autolinks so bold URLs render GFM autolink literal swallows a closing ** when a CJK punctuation follows, leaving ** in the href and the opening ** unmatched. A remark step after the cjk link splitter cuts the link at ** and restores the strong node. Co-Authored-By: Claude Opus 5.5 --- .../ui/src/components/ai-elements/message.tsx | 78 +++++++++++++++++-- .../messageMarkdownStrongAutolink.test.ts | 72 +++++++++++++++++ 2 files changed, 145 insertions(+), 5 deletions(-) create mode 100644 packages/ui/test/messageMarkdownStrongAutolink.test.ts diff --git a/packages/ui/src/components/ai-elements/message.tsx b/packages/ui/src/components/ai-elements/message.tsx index 04c15296451..e56a00aa106 100644 --- a/packages/ui/src/components/ai-elements/message.tsx +++ b/packages/ui/src/components/ai-elements/message.tsx @@ -40,7 +40,7 @@ import { } from "react"; import type { BundledTheme } from "shiki"; import { defaultRehypePlugins, defaultRemarkPlugins, Streamdown } from "streamdown"; -import type { Pluggable, PluggableList } from "unified"; +import type { Pluggable, PluggableList, Plugin } from "unified"; import { CodeBlock, CodeBlockHeader } from "@/components/ai-elements/code-block.js"; import { collectClosedMarkdownFences } from "@/components/ai-elements/mermaid-rendering/index.js"; import { @@ -428,10 +428,78 @@ function disableSingleTilde(plugin: Pluggable): Pluggable { ]; } -const messageCjkRemarkPluginsAfter = cjk.remarkPluginsAfter.map((plugin) => { - const attacher = Array.isArray(plugin) ? plugin[0] : plugin; - return attacher === remarkCjkFriendlyGfmStrikethrough ? disableSingleTilde(plugin) : plugin; -}); +interface AutolinkMarkdownNode { + children?: AutolinkMarkdownNode[]; + type: string; + url?: string; + value?: string; +} + +const isAutolinkTextNode = ( + node: AutolinkMarkdownNode | undefined, +): node is AutolinkMarkdownNode & { value: string } => + node?.type === "text" && typeof node.value === "string"; + +/** GFM 裸链接字面量:唯一文本子节点就是 URL 本身(www 形式补了 `http://`)。 */ +function autolinkText(node: AutolinkMarkdownNode): string | null { + const child = node.children?.length === 1 ? node.children[0] : undefined; + if (node.type !== "link" || !isAutolinkTextNode(child) || typeof node.url !== "string") return null; + return node.url === child.value || node.url === `http://${child.value}` ? child.value : null; +} + +function fixStrongAutolinks(children: AutolinkMarkdownNode[]): void { + for (let i = 0; i < children.length; i++) { + const link = children[i]!; + const text = autolinkText(link); + const cut = text?.indexOf("**") ?? -1; + if (text === null || cut <= 0) continue; + + // 把 `**` 及其后的内容移出链接,URL 同步截断。 + const tail = text.slice(cut); + link.children![0]!.value = text.slice(0, cut); + link.url = link.url!.slice(0, link.url!.length - tail.length); + const next = children[i + 1]; + if (isAutolinkTextNode(next)) next.value = tail + next.value; + else children.splice(i + 1, 0, { type: "text", value: tail }); + + // 紧邻的开头 `**` 因结尾被吞进链接而未配对,这里补成 strong。 + const prev = children[i - 1]; + const after = children[i + 1] as AutolinkMarkdownNode & { value: string }; + if (isAutolinkTextNode(prev) && prev.value.endsWith("**")) { + prev.value = prev.value.slice(0, -2); + after.value = after.value.slice(2); + children[i] = { type: "strong", children: [link] }; + } + } +} + +/** + * 修复 `**http://x/docs**。`:GFM autolink literal 只剥离结尾的 `*`,后面紧跟 + * `。`/`,`/`)` 等非空白字符时会把 `**` 连同标点吞进 URL;@streamdown/cjk 的链接 + * 拆分只在中文标点处截断,`**` 仍留在 href 里,开头的 `**` 也失配成字面量。 + * 依据:URL 中出现 `**` 几乎只可能来自 Markdown 强调标记,因此在 `**` 处截断链接, + * 并在紧邻开头 `**` 时还原 strong。必须排在 cjk 链接拆分之后执行。 + */ +const autolinkStrongRemarkPlugin: Plugin = function autolinkStrongRemarkPlugin() { + return (tree: unknown) => { + const visit = (node: AutolinkMarkdownNode): void => { + if (!node.children) return; + fixStrongAutolinks(node.children); + node.children.forEach(visit); + }; + visit(tree as AutolinkMarkdownNode); + }; +}; + +// Streamdown 顺序为 cjk before → app remarkPlugins → cjk after;加粗裸链接修复依赖 +// cjk 的中文标点链接拆分先执行,所以只能挂在 cjk after 末尾。 +const messageCjkRemarkPluginsAfter = [ + ...cjk.remarkPluginsAfter.map((plugin) => { + const attacher = Array.isArray(plugin) ? plugin[0] : plugin; + return attacher === remarkCjkFriendlyGfmStrikethrough ? disableSingleTilde(plugin) : plugin; + }), + autolinkStrongRemarkPlugin, +]; const messageCjkPlugin: typeof cjk = { ...cjk, remarkPlugins: [...cjk.remarkPluginsBefore, ...messageCjkRemarkPluginsAfter], diff --git a/packages/ui/test/messageMarkdownStrongAutolink.test.ts b/packages/ui/test/messageMarkdownStrongAutolink.test.ts new file mode 100644 index 00000000000..11ed32460b8 --- /dev/null +++ b/packages/ui/test/messageMarkdownStrongAutolink.test.ts @@ -0,0 +1,72 @@ +/** @vitest-environment jsdom */ +import { createElement } from "react"; +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import { MessageResponse } from "@/components/ai-elements/message.js"; +import { TooltipProvider } from "@/components/ui/tooltip.js"; +import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js"; + +afterEach(cleanup); + +function renderMarkdown(markdown: string, streaming = false): HTMLElement { + const view = render( + createElement( + TooltipProvider, + null, + createElement( + ZCodeIntlProvider, + { initialLocale: "zh-CN" }, + createElement(MessageResponse, { theme: "light", streaming }, markdown), + ), + ), + ); + return view.container; +} + +describe("加粗包裹裸 URL(真实 Streamdown 渲染)", () => { + it.each([ + ["Swagger 地址是 **http://127.0.0.1:21500/docs**。", "http://127.0.0.1:21500/docs", "。"], + ["**http://x.test/a**,后文", "http://x.test/a", ",后文"], + ["(**https://example.com/p**)", "https://example.com/p", ")"], + // 链接经 Streamdown URL 规范化后会补出根路径 `/`。 + ["**www.example.com**。", "http://www.example.com/", "。"], + ["**http://a.test/x** 后文", "http://a.test/x", " 后文"], + ])("%s", (markdown, href, after) => { + for (const streaming of [false, true]) { + const container = renderMarkdown(markdown, streaming); + const link = container.querySelector("strong [title]"); + expect(link?.getAttribute("title")).toBe(href); + expect(container.textContent).not.toContain("**"); + expect(container.textContent?.endsWith(after)).toBe(true); + cleanup(); + } + }); + + it.each(["地址 **http://127.0.0.1:21500/do", "地址 **http://127.0.0.1:21500/docs**"])( + "流式中间态不露出 **:%s", + (markdown) => { + const container = renderMarkdown(markdown, true); + expect(container.textContent).not.toContain("**"); + expect(container.querySelector("strong [title]")?.getAttribute("title")).toMatch( + /^http:\/\/127\.0\.0\.1:21500\/do/, + ); + }, + ); + + it.each([ + ["这是**加粗:**文字", "加粗:"], + ["**“引用”**的说明", "“引用”"], + ["**Title**\n\nBody", "Title"], + ])("CJK 加粗保持正确:%s", (markdown, strongText) => { + const container = renderMarkdown(markdown); + expect(container.textContent).not.toContain("**"); + const strong = container.querySelector("strong"); + expect(strong?.textContent).toBe(strongText); + }); + + it("普通链接与行内代码不受影响", () => { + const container = renderMarkdown("[文档](http://a.test/x) 与 `http://a.test/x**`。"); + expect(container.querySelector("[title]")?.getAttribute("title")).toBe("http://a.test/x"); + expect(container.querySelector("code")?.textContent).toBe("http://a.test/x**"); + }); +}); From dea79e3696ef4f9f39c81f0d4e2e39643343b2c4 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:12:19 -0600 Subject: [PATCH 5/9] fix(ui): remove deliverable excerpt rows and text-fence link line The 1.4.1 "deliverable excerpt" projection copied history paragraphs, single-URL text fences and typed media into extra "Open / View original context" rows appended at the end of a running turn's open history, so complete paragraphs/code blocks showed up below the still-streaming block. Per user decision (Q41=A) remove the projection, its identity/key helpers and the extra link line rendered under single-URL text fences. The pure reference extraction stays for inline media. Co-Authored-By: Claude Opus 5.5 --- .../ui/src/components/ai-elements/message.tsx | 70 ++--- packages/ui/src/v4/ConversationRowView.tsx | 6 - .../v4/ConversationShareReadonlyTimeline.tsx | 60 +--- packages/ui/src/v4/ConversationTurnGroup.tsx | 8 +- packages/ui/src/v4/ConversationTurnRow.tsx | 84 +---- .../v4/conversation-presentation/CONTRACT.md | 15 +- .../contract.example.ts | 2 +- .../contract.test.ts | 6 +- .../v4/conversation-presentation/contract.ts | 33 +- .../conversationTurnDeliverables.ts | 102 +------ .../src/v4/conversation-presentation/index.ts | 7 +- packages/ui/src/v4/conversationCuaGroups.ts | 6 - .../ui/src/v4/conversationTurnFlowItems.ts | 123 +------- .../conversationShareReadonlyTimeline.test.ts | 85 +----- .../test/conversationTurnDeliverables.test.ts | 289 ++---------------- .../v4ConversationTurnRenderUnits.test.ts | 237 +------------- 16 files changed, 109 insertions(+), 1024 deletions(-) diff --git a/packages/ui/src/components/ai-elements/message.tsx b/packages/ui/src/components/ai-elements/message.tsx index 04c15296451..36fa1d97678 100644 --- a/packages/ui/src/components/ai-elements/message.tsx +++ b/packages/ui/src/components/ai-elements/message.tsx @@ -362,7 +362,6 @@ export const MessageBranchPage = ({ className, ...props }: MessageBranchPageProp export type MessageResponseProps = { media?: readonly AssistantMediaRef[]; - suppressTextFenceActions?: boolean; /** 公开分享关闭自动媒体加载;已认证只读会话仍使用默认展示。 */ allowAutomaticMedia?: boolean; /** 办公模式的正式回答固定换行,不覆盖用户保存的代码预览设置。 */ @@ -1308,7 +1307,6 @@ export const messageResponsePropsAreEqual = ( ): boolean => prevProps.children === nextProps.children && prevProps.media === nextProps.media && - prevProps.suppressTextFenceActions === nextProps.suppressTextFenceActions && prevProps.allowAutomaticMedia === nextProps.allowAutomaticMedia && prevProps.forceCodeWrap === nextProps.forceCodeWrap && nextProps.streaming === prevProps.streaming && @@ -1329,7 +1327,6 @@ export const messageResponsePropsAreEqual = ( export const MessageResponse = memo( ({ media, - suppressTextFenceActions = false, allowAutomaticMedia = true, className, streaming = false, @@ -1355,17 +1352,6 @@ export const MessageResponse = memo( () => assistantPresentationReferences(rawMarkdown, streaming), [rawMarkdown, streaming], ); - const textFenceTargets = useMemo( - () => - new Set( - references.filter((ref) => ref.sourceFormat === "textFence").map((ref) => ref.target), - ), - [references], - ); - // 流式正文每次更新都会重建目标 Set;若它参与 renderer 依赖,内联组件类型会换代, - // 导致 Mermaid 与 Markdown 媒体卸载。保持类型稳定,同时在本轮渲染读取最新目标。 - const textFenceTargetsRef = useRef(textFenceTargets); - textFenceTargetsRef.current = textFenceTargets; const deliveredMedia = useMemo(() => { if (!allowAutomaticMedia) return []; const typed = (media ?? []).map((ref) => ({ @@ -1668,42 +1654,29 @@ export const MessageResponse = memo( const codeText = trimCodeFenceTrailingNewlines(extractCodeText(children)); const language = getCodeLanguage(codeClassName); + // 1.6.1 不再在单 URL text fence 下追加链接行:用户反馈代码块下多出一行令人困惑。 return ( - <> - + - - - {!suppressTextFenceActions && - textFenceTargetsRef.current.has(codeText.trim()) && - onOpenExternalUrl ? ( - - {codeText.trim()} - - ) : null} - + showWrapButton={!forceCodeWrap} + /> + ); }, blockquote: MarkdownBlockquote, @@ -1727,7 +1700,6 @@ export const MessageResponse = memo( onOpenCodeViewer, onOpenExternalUrl, openMediaSource, - suppressTextFenceActions, readAttachment, renderStreaming, sessionId, diff --git a/packages/ui/src/v4/ConversationRowView.tsx b/packages/ui/src/v4/ConversationRowView.tsx index f0c92f0b0d4..44d5b11eb53 100644 --- a/packages/ui/src/v4/ConversationRowView.tsx +++ b/packages/ui/src/v4/ConversationRowView.tsx @@ -232,7 +232,6 @@ export interface EditWorkspaceRewindAvailability { } export interface ConversationRowViewProps { - suppressTextFenceActions?: boolean; row: ConversationRow; /** 渲染上下文(theme/codePreviewSettings/workspacePath);宿主保证引用稳定。 */ context: ConversationRowRenderContext; @@ -1640,7 +1639,6 @@ export const ConversationAssistantTextActions = memo(function ConversationAssist }); const AssistantTextRowView = memo(function AssistantTextRowView({ - suppressTextFenceActions, row, context, onFork, @@ -1653,7 +1651,6 @@ const AssistantTextRowView = memo(function AssistantTextRowView({ codeCommentCards, codeCommentProjectionEnabled, }: { - suppressTextFenceActions?: boolean; row: AssistantTextRow; context: ConversationRowRenderContext; onFork?: (target: ConversationRowTarget) => void; @@ -1687,7 +1684,6 @@ const AssistantTextRowView = memo(function AssistantTextRowView({ selectable 语义必须放在稳定的 DOM 包装层上,完成态和 streaming 共用同一路径。 */}
; } else if (item.kind === "assistantText") { content = ( -
- - {( - item.deliverable?.textFenceTargets ?? - (item.deliverable?.sourceFormat === "textFence" ? [item.deliverable.target] : []) - ).map((href) => ( - - ))} - {item.deliverable ? ( - - ) : null} -
+ ); } else if (item.kind === "cuaGroup") { const group = ( @@ -1193,13 +1149,11 @@ function ConversationShareReadonlyTimelineContent({ }, []); const labels: ReadonlyLabels = { history: intl.formatMessage({ id: "conversationShare.readonly.history" }), - showSourceContext: intl.formatMessage({ id: "chat.deliverable.showSourceContext" }), computerUse: intl.formatMessage({ id: "conversationShare.readonly.computerUse" }), explore: intl.formatMessage({ id: "conversationShare.readonly.explore" }), execute: intl.formatMessage({ id: "conversationShare.readonly.execute" }), changes: intl.formatMessage({ id: "conversationShare.readonly.changes" }), artifactPreview: intl.formatMessage({ id: "conversationShare.readonly.artifactPreview" }), - open: intl.formatMessage({ id: "common.open" }), markerCompact: intl.formatMessage({ id: "conversationShare.readonly.markerCompact" }), markerModelChange: intl.formatMessage({ id: "conversationShare.readonly.markerModelChange" }), unsupportedRows: intl.formatMessage({ id: "conversationShare.readonly.unsupportedRows" }), diff --git a/packages/ui/src/v4/ConversationTurnGroup.tsx b/packages/ui/src/v4/ConversationTurnGroup.tsx index f4da91d9e5a..49dc57e6256 100644 --- a/packages/ui/src/v4/ConversationTurnGroup.tsx +++ b/packages/ui/src/v4/ConversationTurnGroup.tsx @@ -98,7 +98,6 @@ import type { import { formatConversationWorkDuration } from "@/v4/conversationWorkDuration.js"; import { ConversationTurnRow, resolveAssistantCopyText } from "@/v4/ConversationTurnRow.js"; import { ConversationHookDetailsAction } from "@/v4/ConversationHookDetailsAction.js"; -import { resolveConversationDeliverableKey } from "@/v4/conversation-presentation/index.js"; import { toolCallRowToLegacyNode } from "@/v4/toolCallRowAdapter.js"; interface ConversationTurnGroupProps { @@ -762,10 +761,7 @@ function ConversationWorkSegmentFlow({ (item.kind === "assistantHistory" || item.kind === "assistantWork"); const showHistoryStatus = shouldShowHistoryStatus && index === firstAssistantFlowItemIndex; // 段首多行 item 用位置 key:HLP01 前插更早行时不能整段卸载重挂(见 resolveConversationFlowItemKey)。 - const itemKey = - item.kind === "assistantText" && item.deliverable - ? resolveConversationDeliverableKey(item.deliverable, context, item.row.turnId) - : resolveConversationFlowItemKey(item, index, firstAssistantFlowItemIndex); + const itemKey = resolveConversationFlowItemKey(item, index, firstAssistantFlowItemIndex); let content: React.ReactNode; if (item.kind === "userInput") { @@ -812,8 +808,6 @@ function ConversationWorkSegmentFlow({ content = ( setHistoryOpen(true) : undefined} context={context} onFork={item.latest && canForkLatestAssistant ? onFork : undefined} onRetry={item.latest && canRetryLatestAssistant ? onRetry : undefined} diff --git a/packages/ui/src/v4/ConversationTurnRow.tsx b/packages/ui/src/v4/ConversationTurnRow.tsx index c5c0b6a8930..f86caf2d6db 100644 --- a/packages/ui/src/v4/ConversationTurnRow.tsx +++ b/packages/ui/src/v4/ConversationTurnRow.tsx @@ -12,11 +12,6 @@ import type { EditWorkspaceRewindAvailability } from "@/v4/ConversationRowView.j import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js"; import type { ConversationTurnRenderUnit } from "@/v4/conversationTurnRenderUnits.js"; import { toolCallRowToLegacyNode } from "@/v4/toolCallRowAdapter.js"; -import type { ConversationDeliverable } from "@/v4/conversation-presentation/index.js"; -import { useZCodeIntl } from "@/i18n/IntlProvider.js"; -import { Button } from "@/components/ui/button.js"; -import { useOptionalPlatform } from "@/hooks/usePlatform.js"; -import { resolveMessageLinkOpenTarget } from "@/embeddedBrowserHelpers.js"; interface ConversationTurnRowProps { row: ConversationRow; @@ -39,8 +34,6 @@ interface ConversationTurnRowProps { assistantCodeCommentProjectionEnabled?: boolean; reasoningContentVariant?: "default" | "nested"; userInputStatus?: string; - deliverable?: ConversationDeliverable; - onShowSourceContext?: () => void; } export function ConversationTurnRow({ @@ -59,87 +52,26 @@ export function ConversationTurnRow({ assistantCodeCommentProjectionEnabled, reasoningContentVariant, userInputStatus, - deliverable, - onShowSourceContext, }: ConversationTurnRowProps) { - const { intl } = useZCodeIntl(); - const platform = useOptionalPlatform(); - const content = ( + return ( ); - if (!deliverable) return content; - return ( -
- {content} - {( - deliverable.textFenceTargets ?? - (deliverable.sourceFormat === "textFence" ? [deliverable.target] : []) - ).map((href) => ( - - ))} - -
- ); } export function resolveAssistantCopyText(unit: ConversationTurnRenderUnit): string | undefined { diff --git a/packages/ui/src/v4/conversation-presentation/CONTRACT.md b/packages/ui/src/v4/conversation-presentation/CONTRACT.md index c05713dbccc..b2ff33ff682 100644 --- a/packages/ui/src/v4/conversation-presentation/CONTRACT.md +++ b/packages/ui/src/v4/conversation-presentation/CONTRACT.md @@ -2,20 +2,11 @@ Renderer 展示派生的唯一边界;输入是已经收到的 V4 行,输出是带来源区间的纯投影。 -- UX05 纯 helper 按已收到的 MIME 或识别扩展名分类 image/audio/video,提取闭合正文引用;未知 MIME/无扩展名 URL 保持网页,不发起探测。资源读取、重试、blob URL 生命周期由既有 renderer 消费方负责,公开入口不引入组件或服务。 -- UX05 已类型化 `row.media` 同样投影为常显成果,空正文也有效。每个媒体保留独立 `typedMedia` 引用和源 row/id,不与文本区间合并;正文缓存不缓存媒体,媒体增量不得被相同正文吞掉。派生行只包含该单项 media,不复制整行媒体列表。 -- 类型化媒体挂载身份包含类型、MIME 和完整目标,与普通链接区分,并继续隔离完整 scope;来源行/id仅用于溯源。最终或更早已展示的同类媒体才覆盖,最终普通网页卡不等于已内嵌媒体。一行多媒体逐项覆盖,部分覆盖保留其余媒体,原历史及最终正文不改写。 -- 匿名分享仅呈现类型化媒体的 HTTP 来源按钮或本地附件名称/MIME,不自动请求 URL、不读取 artifact、不把本地 URI 放进可点击入口;认证正文沿既有 scoped reader 渲染。成果投影不新增 action 或自动打开。 - +- UX05 纯 helper 按已收到的 MIME 或识别扩展名分类 image/audio/video,并从正文提取闭合 Markdown 链接/图片与以换行确认完整的独立 URL,供既有 MessageResponse 内嵌媒体;未知 MIME/无扩展名 URL 保持普通链接,不发起探测。资源读取、重试、blob URL 生命周期由既有 renderer 消费方负责,公开入口不引入组件或服务。 +- 1.6.1 已移除“成果摘录”投影(UX04)与 text fence 打开动作:本模块不再生成折叠外摘录行、上下文区间、挂载身份或 typedMedia 引用;flow 只按原行序渲染。 +- 代码块、行内代码、缩进代码与命令中的 URL 不会成为引用;`text` fence 同样只作为代码展示。 - 不写回行、协议、业务状态或媒体事实,不做网络、文件 IO,不持有服务。 -- 成果只接纳明确闭合引用,保留完整目标和说明段落;代码和命令不会变为成果。 -- 完整原段只展示一次;最终正文覆盖该段全部目标时省略,部分覆盖时保留完整原句,不能为删重裁剪上下文。 -- 来源 key/range 描述实际选中来源,前插重复目标时允许诚实更新代表来源;React 挂载身份按去重及最终覆盖前的完整目标组排序生成,并补齐 workspace identity、remote session、session、epoch、turn,不包含被选中来源的位置。 - 五件套与公开 index 只依赖 shared 类型与纯媒体格式注册表;本模块属于共享只读时间线的安全依赖闭包。 -- 原历史、最终正文 action、预览卡片验证和 scoped 打开均由既有 renderer/hook 继续拥有。 -- 单 URL text fence 保留原代码块,由消费方原生按钮将完整 target 直接交给既有打开回调,禁止手拼 Markdown 改写目标。 -- 同 row 相交的 context 区间合并为原文切片,首引用 key/start/end/target 保持锚点;不跨 row 拼接。最终覆盖对整组合并目标判断,全部覆盖才省略;textFenceTargets 保留所有未被最终正文覆盖的完整目标并去重,按钮以目标作 key。该数组可选,旧的单 fence 引用仍可由 sourceFormat/target 渲染打开动作。 -- 提取阶段保留全部有效来源引用,先形成原段完整目标集合/首锚,再按来源顺序省略目标全被已展示来源或最终正文覆盖的组;部分覆盖保留原文和原始目标组。identityTargets 只为纯派生完整目标集合,省略时兼容单 target;不新增可写代表缓存或持久化状态。 - UX06 `buildConversationMcpGroups` 是只读连续投影:保留非成员行及原生父子身份,专用 Node REPL/CUA/插件交互不接管。同服务组只能跨相邻同 turn、同 parent 的 MCP 行。 - 服务比较使用完整身份而非展示短名:discovery 的完整配置 serverName 与 legacy 未缩短 encoded server 段分别处于独立身份域。旧 envelope 无法无损映射 discovery 键,跨来源保守断组,允许混合格式的真实同服务多一组;不猜标签、不新增映射缓存,既有机械短名显示不变。 diff --git a/packages/ui/src/v4/conversation-presentation/contract.example.ts b/packages/ui/src/v4/conversation-presentation/contract.example.ts index cee33dbe4ec..c950a2ee790 100644 --- a/packages/ui/src/v4/conversation-presentation/contract.example.ts +++ b/packages/ui/src/v4/conversation-presentation/contract.example.ts @@ -12,7 +12,7 @@ export function exampleConversationPresentation( extract: ExtractConversationDeliverables, rows: readonly AssistantTextRow[], ): readonly string[] { - return extract(rows).map((reference) => reference.contextText); + return extract(rows).map((reference) => reference.target); } /** 无 React/Host 的连续服务投影消费方。 */ diff --git a/packages/ui/src/v4/conversation-presentation/contract.test.ts b/packages/ui/src/v4/conversation-presentation/contract.test.ts index e671a535ed6..334dffda063 100644 --- a/packages/ui/src/v4/conversation-presentation/contract.test.ts +++ b/packages/ui/src/v4/conversation-presentation/contract.test.ts @@ -33,13 +33,9 @@ describe("conversation-presentation contract", () => { kind: "link", sourceFormat: "markdown", target: "https://example.invalid", - identityTargets: ["https://example.invalid"], - contextStart: 0, - contextEnd: 1, - contextText: "打开入口", }; const extract: ExtractConversationDeliverables = () => [reference]; - expect(exampleConversationPresentation(extract, [])).toEqual(["打开入口"]); + expect(exampleConversationPresentation(extract, [])).toEqual(["https://example.invalid"]); }); }); diff --git a/packages/ui/src/v4/conversation-presentation/contract.ts b/packages/ui/src/v4/conversation-presentation/contract.ts index 6bb8a31f199..56c4e03559e 100644 --- a/packages/ui/src/v4/conversation-presentation/contract.ts +++ b/packages/ui/src/v4/conversation-presentation/contract.ts @@ -16,36 +16,19 @@ export type AssistantPresentationReferences = ( streaming?: boolean, ) => readonly ConversationDeliverable[]; -/** 仅引用已收到的正文/媒体;文本区间为 UTF-16 半开区间,typedMedia 用文尾零宽锚点。 */ +/** 仅引用已收到正文中的闭合链接/图片与独立 URL;区间为 UTF-16 半开区间。 */ export interface ConversationDeliverable { - /** 实际来源锚点,只承担溯源;不能直接用作 React 挂载身份。 */ + /** 来源锚点,仅用于溯源。 */ readonly key: string; readonly sourceRowId: number; readonly start: number; readonly end: number; readonly kind: "link" | "image" | "file"; - readonly sourceFormat: "markdown" | "standaloneUrl" | "textFence" | "typedMedia"; + readonly sourceFormat: "markdown" | "standaloneUrl"; readonly target: string; - /** 同源单项媒体引用;消费方不得把原行全部 media 复制到每个成果。 */ - readonly media?: AssistantMediaRef; - /** 跨来源去重和最终覆盖前的完整原始目标组;省略时为单 target。 */ - readonly identityTargets?: readonly string[]; - /** 合并来源片段中仍需独立打开的 text fence 目标;省略时兼容单引用。 */ - readonly textFenceTargets?: readonly string[]; - readonly contextStart: number; - readonly contextEnd: number; - readonly contextText: string; } -export interface ConversationDeliverableScope { - readonly workspacePath: string; - readonly workspaceIdentity?: string; - readonly workspaceRemoteSessionId?: string; - readonly sessionId?: string | null; - readonly logEpoch?: string; -} - -/** 确定性、无 IO、无事件和持久化;保留已加载行的全部有效来源,供分组后去重。 */ +/** 确定性、无 IO、无事件和持久化。 */ export type ExtractConversationDeliverables = ( rows: readonly AssistantTextRow[], ) => readonly ConversationDeliverable[]; @@ -61,7 +44,13 @@ export type ConversationMcpGroupItem = export type BuildConversationMcpGroups = ( rows: readonly ConversationRow[], ) => readonly ConversationMcpGroupItem[]; -export interface ConversationDisclosureScope extends ConversationDeliverableScope {} +export interface ConversationDisclosureScope { + readonly workspacePath: string; + readonly workspaceIdentity?: string; + readonly workspaceRemoteSessionId?: string; + readonly sessionId?: string | null; + readonly logEpoch?: string; +} export interface DisclosureState { readonly defaultOpen: boolean; readonly userOverride?: boolean; diff --git a/packages/ui/src/v4/conversation-presentation/conversationTurnDeliverables.ts b/packages/ui/src/v4/conversation-presentation/conversationTurnDeliverables.ts index 12db267fcdb..ca28c415c46 100644 --- a/packages/ui/src/v4/conversation-presentation/conversationTurnDeliverables.ts +++ b/packages/ui/src/v4/conversation-presentation/conversationTurnDeliverables.ts @@ -1,5 +1,5 @@ import type { AssistantTextRow } from "@zcode/shared/zcode-protocol-v4"; -import type { ConversationDeliverable, ConversationDeliverableScope } from "./contract.js"; +import type { ConversationDeliverable } from "./contract.js"; interface SourceRange { start: number; @@ -9,7 +9,6 @@ interface Candidate extends SourceRange { target: string; image?: boolean; standalone?: boolean; - textFence?: boolean; } // 仅缓存原行派生,WeakMap 不拥有历史生命周期,也不形成第二份会话事实。 @@ -50,9 +49,8 @@ function cleanTarget(raw: string): string | undefined { return target; } -function protectedCode(text: string): { ranges: SourceRange[]; candidates: Candidate[] } { +function protectedCode(text: string): SourceRange[] { const ranges: SourceRange[] = []; - const candidates: Candidate[] = []; const opening = /^ {0,3}(`{3,}|~{3,})([^\n\r]*)(?:\r?\n|$)/gm; for (let match = opening.exec(text); match; match = opening.exec(text)) { if (overlaps(match.index, match.index + 1, ranges)) continue; @@ -66,16 +64,6 @@ function protectedCode(text: string): { ranges: SourceRange[]; candidates: Candi const close = closing.exec(text); const end = close ? close.index + close[0].length : text.length; ranges.push({ start: match.index, end }); - const target = close ? text.slice(bodyStart, close.index).trim() : ""; - if (match[2]!.trim().toLowerCase() === "text" && httpTarget(target)) { - candidates.push({ - start: match.index, - end: close!.index + close![0].trimEnd().length, - target, - standalone: true, - textFence: true, - }); - } opening.lastIndex = end; } for (const match of text.matchAll(/^(?: {4}|\t).*$/gm)) { @@ -84,7 +72,7 @@ function protectedCode(text: string): { ranges: SourceRange[]; candidates: Candi for (const match of text.matchAll(/(`+)([\s\S]*?)(\1)(?!`)/g)) { ranges.push({ start: match.index, end: match.index + match[0].length }); } - return { ranges, candidates }; + return ranges; } function markdownCandidates(text: string, ranges: readonly SourceRange[]): Candidate[] { @@ -121,34 +109,12 @@ function markdownCandidates(text: string, ranges: readonly SourceRange[]): Candi return candidates; } -function sourceContext( - text: string, - candidate: Candidate, - ranges: readonly SourceRange[], -): SourceRange { - const boundaries = [...text.matchAll(/\r?\n[ \t]*\r?\n/g)]; - const previous = boundaries.findLast((match) => match.index + match[0].length <= candidate.start); - let start = previous ? previous.index + previous[0].length : 0; - const next = boundaries.find((match) => match.index >= candidate.end); - let end = next?.index ?? text.length; - if (candidate.standalone && start > 0) { - const previousEnd = previous!.index; - const beforePrevious = boundaries.findLast((match) => match.index < previousEnd); - const from = beforePrevious ? beforePrevious.index + beforePrevious[0].length : 0; - // 独立 URL 的用途常在前一个段落;不把前一段代码示例当作说明带出。 - if (!overlaps(from, previousEnd, ranges)) start = from; - } - while (start < candidate.start && /\s/.test(text[start]!)) start += 1; - while (end > candidate.end && /\s/.test(text[end - 1]!)) end -= 1; - return { start, end }; -} - function extractRow(row: AssistantTextRow): readonly ConversationDeliverable[] { const cached = rowCache.get(row); const streaming = row.state === "streaming"; if (cached?.text === row.text && cached.streaming === streaming) return cached.references; - const { ranges, candidates } = protectedCode(row.text); - candidates.push(...markdownCandidates(row.text, ranges)); + const ranges = protectedCode(row.text); + const candidates = markdownCandidates(row.text, ranges); for (const match of row.text.matchAll(/^[ \t]*(https?:\/\/[^\s<>`]+)[ \t]*(?:\r?\n|$)/gm)) { const target = match[1]!; const start = match.index + match[0].indexOf(target); @@ -164,7 +130,6 @@ function extractRow(row: AssistantTextRow): readonly ConversationDeliverable[] { const references = candidates .sort((a, b) => a.start - b.start) .map((candidate): ConversationDeliverable => { - const context = sourceContext(row.text, candidate, ranges); const kind = candidate.image ? "image" : httpTarget(candidate.target) ? "link" : "file"; return { key: `${row.rowId}:${candidate.start}:${candidate.end}:${kind}`, @@ -172,15 +137,8 @@ function extractRow(row: AssistantTextRow): readonly ConversationDeliverable[] { start: candidate.start, end: candidate.end, kind, - sourceFormat: candidate.textFence - ? "textFence" - : candidate.standalone - ? "standaloneUrl" - : "markdown", + sourceFormat: candidate.standalone ? "standaloneUrl" : "markdown", target: candidate.target, - contextStart: context.start, - contextEnd: context.end, - contextText: row.text.slice(context.start, context.end), }; }); rowCache.set(row, { text: row.text, streaming, references }); @@ -190,51 +148,5 @@ function extractRow(row: AssistantTextRow): readonly ConversationDeliverable[] { export function extractConversationDeliverables( rows: readonly AssistantTextRow[], ): readonly ConversationDeliverable[] { - // 必须先保留原段的所有引用再分组,过早跨来源去重会把仍在的 A/B 段错误改锚到 B。 - return rows.flatMap((row) => [ - ...extractRow(row), - // 文本未变时仍可能收到 media 增量;只缓存文字解析,不缓存第二份媒体事实。 - ...(row.media ?? []).map( - (media): ConversationDeliverable => ({ - key: `${row.rowId}:media:${media.id}`, - sourceRowId: row.rowId, - start: row.text.length, - end: row.text.length, - kind: media.mediaType === "image" ? "image" : "file", - sourceFormat: "typedMedia", - target: media.source.kind === "artifact" ? media.source.uri : media.source.url, - media, - contextStart: row.text.length, - contextEnd: row.text.length, - contextText: "", - }), - ), - ]); -} - -export function resolveConversationDeliverableIdentity(reference: ConversationDeliverable): string { - if (reference.media) - return JSON.stringify([ - "typedMedia", - reference.media.mediaType, - reference.media.mimeType, - reference.target, - ]); - return JSON.stringify([...new Set(reference.identityTargets ?? [reference.target])].sort()); -} - -export function resolveConversationDeliverableKey( - reference: ConversationDeliverable, - scope: ConversationDeliverableScope, - turnId: string, -): string { - return JSON.stringify([ - scope.workspaceIdentity?.trim() || scope.workspacePath, - scope.workspaceRemoteSessionId ?? "", - scope.sessionId ?? "", - scope.logEpoch ?? "", - turnId, - // 来源 key 只负责溯源;前插相同目标时代表来源会变,但逻辑片段不能因此重新挂载。 - resolveConversationDeliverableIdentity(reference), - ]); + return rows.flatMap(extractRow); } diff --git a/packages/ui/src/v4/conversation-presentation/index.ts b/packages/ui/src/v4/conversation-presentation/index.ts index 8b6b386b23f..b7cd9ad1e8e 100644 --- a/packages/ui/src/v4/conversation-presentation/index.ts +++ b/packages/ui/src/v4/conversation-presentation/index.ts @@ -1,15 +1,10 @@ // 共享只读时间线会消费此入口;保持纯函数/类型,不导出带服务或平台依赖的组件。 export { classifyAssistantMedia, assistantPresentationReferences } from "./assistantMedia.js"; -export { - extractConversationDeliverables, - resolveConversationDeliverableIdentity, - resolveConversationDeliverableKey, -} from "./conversationTurnDeliverables.js"; +export { extractConversationDeliverables } from "./conversationTurnDeliverables.js"; export type { ClassifyAssistantMedia, AssistantPresentationReferences, ConversationDeliverable, - ConversationDeliverableScope, ExtractConversationDeliverables, } from "./contract.js"; diff --git a/packages/ui/src/v4/conversationCuaGroups.ts b/packages/ui/src/v4/conversationCuaGroups.ts index b69fe5b6d4e..129fbf38370 100644 --- a/packages/ui/src/v4/conversationCuaGroups.ts +++ b/packages/ui/src/v4/conversationCuaGroups.ts @@ -233,12 +233,6 @@ export function prepareCuaGroupFlowItems( continue; } if (item.kind === "assistantText") { - if (item.deliverable) { - // 来源片段是额外展示引用,不是新的 assistant response,不能再吸入 CUA 折叠组。 - closeGroup(); - prepared.push(item); - continue; - } handleAssistantMessage(item.row, "assistantWork", () => prepared.push(item)); continue; } diff --git a/packages/ui/src/v4/conversationTurnFlowItems.ts b/packages/ui/src/v4/conversationTurnFlowItems.ts index e91a2873adc..b9a94e886db 100644 --- a/packages/ui/src/v4/conversationTurnFlowItems.ts +++ b/packages/ui/src/v4/conversationTurnFlowItems.ts @@ -5,24 +5,13 @@ import type { UserInputRow, } from "@zcode/shared/zcode-protocol-v4"; import type { ConversationCuaGroupRenderItem } from "@/v4/conversationCuaGroups.js"; -import { - extractConversationDeliverables, - classifyAssistantMedia, - resolveConversationDeliverableIdentity, - type ConversationDeliverable, -} from "@/v4/conversation-presentation/index.js"; export type AssistantWorkRow = Exclude; export type ConversationTurnFlowItem = | { kind: "userInput"; row: UserInputRow } | { kind: "assistantHistory"; rows: AssistantWorkRow[] } - | { - kind: "assistantText"; - row: AssistantTextRow; - latest: boolean; - deliverable?: ConversationDeliverable; - } + | { kind: "assistantText"; row: AssistantTextRow; latest: boolean } | { kind: "assistantWork"; rows: AssistantWorkRow[] } | ConversationCuaGroupRenderItem; @@ -66,110 +55,9 @@ export function buildConversationFlowItems(options: { const followingRowIds = new Set(options.assistantFollowingRows.map((row) => row.rowId)); const tailRowIds = new Set(options.assistantTailRows.map((row) => row.rowId)); const items: ConversationTurnFlowItem[] = []; - const visibleReferences = extractConversationDeliverables( - [options.visibleAssistantTextRow, options.latestAssistantTextRow].filter( - (row): row is AssistantTextRow => row !== undefined, - ), - ); - const visibleTargets = new Set( - visibleReferences.filter((reference) => !reference.media).map((reference) => reference.target), - ); - const sourceRows = options.orderedRows.filter( - (row): row is AssistantTextRow => - isAssistantTextRow(row) && (historyRowIds.has(row.rowId) || followingRowIds.has(row.rowId)), - ); - const sourceById = new Map(sourceRows.map((row) => [row.rowId, row])); - const referencesByRow = new Map(); - for (const reference of options.timelineOnly ? [] : extractConversationDeliverables(sourceRows)) { - const references = referencesByRow.get(reference.sourceRowId) ?? []; - references.push(reference); - referencesByRow.set(reference.sourceRowId, references); - } - type SourceContext = { - reference: ConversationDeliverable; - targets: Set; - textFenceTargets: Set; - }; - const contexts: SourceContext[] = []; - for (const references of referencesByRow.values()) { - let context: SourceContext | undefined; - for (const reference of references.toSorted( - (a, b) => a.contextStart - b.contextStart || a.start - b.start, - )) { - if (reference.media) { - // 类型化媒体没有正文区间;每个成果只引用当前媒体,不能合并成整行再重复渲染。 - contexts.push({ - reference, - targets: new Set([reference.target]), - textFenceTargets: new Set(), - }); - context = undefined; - continue; - } - if (!context || reference.contextStart >= context.reference.contextEnd) { - context = { reference, targets: new Set(), textFenceTargets: new Set() }; - contexts.push(context); - } else { - // 独立入口会借前段说明;合并相交区间,避免 A 段单列后又在 B 的上下文里重复。 - const contextStart = context.reference.contextStart; - const contextEnd = Math.max(context.reference.contextEnd, reference.contextEnd); - const anchor = context.reference.start <= reference.start ? context.reference : reference; - context.reference = { - ...anchor, - contextStart, - contextEnd, - contextText: sourceById.get(reference.sourceRowId)!.text.slice(contextStart, contextEnd), - }; - } - context.targets.add(reference.target); - if (reference.sourceFormat === "textFence") context.textFenceTargets.add(reference.target); - } - } - // 先合并来源区间再判最终覆盖,首引用锚点不因部分覆盖而跳到另一目标。 - const representedTargets = new Set(visibleTargets); - const representedMedia = [...visibleReferences]; - const deliverables = contexts.flatMap((context) => { - if (context.reference.media) { - const reference = context.reference; - const media = reference.media!; - // 普通无扩展网页链接没有媒体展示能力,不能覆盖 MIME 明确的原生媒体。 - const covered = representedMedia.some((candidate) => { - if (candidate.target !== reference.target) return false; - if (candidate.media) - return ( - resolveConversationDeliverableIdentity(candidate) === - resolveConversationDeliverableIdentity(reference) - ); - const classification = classifyAssistantMedia(candidate.target); - if (classification) - return ( - classification.mediaType === media.mediaType && - classification.mimeType === media.mimeType - ); - return candidate.kind === "image" && media.mediaType === "image"; - }); - representedMedia.push(reference); - return covered ? [] : [reference]; - } - const identityTargets = [...context.targets]; - const hasNewTarget = identityTargets.some((target) => !representedTargets.has(target)); - const textFenceTargets = [...context.textFenceTargets].filter( - (target) => !representedTargets.has(target), - ); - for (const target of identityTargets) representedTargets.add(target); - representedMedia.push(context.reference); - return hasNewTarget ? [{ ...context.reference, identityTargets, textFenceTargets }] : []; - }); - let appendedDeliverables = false; - const appendDeliverables = () => { - if (appendedDeliverables) return; - appendedDeliverables = true; - for (const deliverable of deliverables) { - const row = sourceById.get(deliverable.sourceRowId); - if (row) items.push({ kind: "assistantText", row, latest: false, deliverable }); - } - }; + // 1.6.1 移除“成果摘录”投影:它把历史段落/代码块复制追加到运行中 turn 的末尾, + // 导致完整段落出现在仍在流式输出的正文下方(流式不再自上而下)。flow 只按原行序输出。 for (const row of options.orderedRows) { if (isUserInputRow(row)) { items.push({ kind: "userInput", row }); @@ -187,8 +75,6 @@ export function buildConversationFlowItems(options: { !tailRowIds.has(row.rowId) && !options.timelineOnly ) { - // 原历史原位保留;仅在外置正文之前投影完整来源段,不能因“已工作”收起而丢失成果。 - appendDeliverables(); items.push({ kind: "assistantText", row, @@ -202,7 +88,6 @@ export function buildConversationFlowItems(options: { row, ); } - appendDeliverables(); return items; } @@ -226,8 +111,6 @@ export function resolveConversationFlowItemKey( index: number, firstAssistantFlowItemIndex: number, ): string { - if (item.kind === "assistantText" && item.deliverable) - return `deliverable:${resolveConversationDeliverableIdentity(item.deliverable)}`; if (item.kind === "userInput" || item.kind === "assistantText") { return `${item.kind}:${item.row.rowId}`; } diff --git a/packages/ui/test/conversationShareReadonlyTimeline.test.ts b/packages/ui/test/conversationShareReadonlyTimeline.test.ts index e7dda4da1be..ea3b82b592b 100644 --- a/packages/ui/test/conversationShareReadonlyTimeline.test.ts +++ b/packages/ui/test/conversationShareReadonlyTimeline.test.ts @@ -93,10 +93,10 @@ const buildArtifactRow = (rowId: number, artifactVersionId: string) => ({ }); describe("ConversationShareReadonlyTimeline", () => { - it("UX05 分享媒体成果常显但不自动加载URL或暴露本地artifact入口", () => { + it("UX05 分享媒体不自动加载URL或暴露本地artifact入口", () => { const source = { ...rows[2]!, - text: "", + text: "完成", media: [ { id: "url", @@ -116,11 +116,10 @@ describe("ConversationShareReadonlyTimeline", () => { }; const html = renderToStaticMarkup( createElement(ConversationShareReadonlyTimeline, { - rows: [...rows.slice(0, 2), source, rows[3]!, { ...rows[2]!, rowId: 5, text: "完成" }], + rows: [...rows.slice(0, 2), source], locale: "zh-CN", }), ); - expect(html.match(/data-conversation-deliverable=/g)).toHaveLength(2); expect(html).toContain("公开音频"); expect(html).toContain("本地图片"); expect(html).toContain("https://example.invalid/media"); @@ -129,88 +128,20 @@ describe("ConversationShareReadonlyTimeline", () => { expect(html).not.toContain("v4-retry"); expect(html).not.toContain("v4-fork"); }); - it("UX04 共享页前插早A后保留A/B原段首来源锚,既不裁剪原文也不重复整个目标组", () => { + it("1.6.1 共享页不再在已工作外追加成果摘录或 text fence 打开入口", () => { const source = { ...rows[2]!, - rowId: 20, - text: "当前说明:[A](https://example.invalid/a) [B](https://example.invalid/b)", + text: "入口说明:[继续](https://example.invalid/login)\n\n```text\nhttps://example.invalid/b\n```", }; - const earlier = { ...source, rowId: 10, text: "更早说明:[A](https://example.invalid/a)" }; - const html = renderToStaticMarkup( - createElement(ConversationShareReadonlyTimeline, { - rows: [ - ...rows.slice(0, 2), - earlier, - source, - { ...rows[3]!, rowId: 30 }, - { ...source, rowId: 40, text: "完成" }, - ], - locale: "zh-CN", - }), - ); - expect(html).toContain('data-conversation-deliverable="20:5:'); - expect(html.match(/data-conversation-deliverable=/g)).toHaveLength(2); - expect(html).toContain("当前说明"); - expect(html).toContain("更早说明"); - }); - it("UX04 合并 Markdown与两个fence来源,只渲染一次原段并保留每个未覆盖完整打开目标", () => { - const a = "https://example.invalid/a"; - const b = "https://example.invalid/b(step)?next=(done)&label=%20path"; - const c = "https://example.invalid/c?next=%3Cdone%3E"; - const source = { - ...rows[2]!, - text: `[A](${a})\n\n\`\`\`text\n${b}\n\`\`\`\n\`\`\`text\n${c}\n\`\`\``, - }; - const render = (finalText: string) => - renderToStaticMarkup( - createElement(ConversationShareReadonlyTimeline, { - rows: [...rows.slice(0, 2), source, rows[3]!, { ...source, rowId: 5, text: finalText }], - locale: "zh-CN", - }), - ); - const html = render("完成"); - expect(html.match(/data-conversation-deliverable=/g)).toHaveLength(1); - expect(html.match(/data-deliverable-open-link="true"/g)).toHaveLength(2); - expect(html).toContain(`title="${b.replaceAll("&", "&")}"`); - expect(html).toContain(`title="${c}"`); - const coveredB = render(`[B](${b})`); - expect(coveredB.match(/data-conversation-deliverable=/g)).toHaveLength(1); - expect(coveredB.match(/data-deliverable-open-link="true"/g)).toHaveLength(1); - expect(coveredB).toMatch( - new RegExp( - `data-deliverable-open-link="true"[^>]*title="${c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"`, - ), - ); - }); - it("UX04 保留 text fence 原文并提供可点击的原始 URL 打开入口", () => { - const target = - "https://example.invalid/login(step)?next=(done)&label=%E4%B8%AD%E6%96%87%20path&angle=%3Cdone%3E"; - const source = { ...rows[2]!, text: `继续操作:\n\n\`\`\`text\n${target}\n\`\`\`` }; - const html = renderToStaticMarkup( - createElement(ConversationShareReadonlyTimeline, { - rows: [...rows.slice(0, 2), source, rows[3]!, { ...source, rowId: 5, text: "完成" }], - locale: "zh-CN", - }), - ); - expect(html).toContain("data-deliverable-open-link"); - expect(html).toContain(`title="${target.replaceAll("&", "&")}"`); - expect(html).toMatch(/]*data-deliverable-open-link/); - expect(html).toContain("继续操作"); - expect(html).toContain('data-language="text"'); - }); - it("UX04 共享只读时间线在已工作外保留原段落与上下文入口", () => { - const source = { ...rows[2]!, text: "入口说明:[继续](https://example.invalid/login)" }; const html = renderToStaticMarkup( createElement(ConversationShareReadonlyTimeline, { rows: [...rows.slice(0, 2), source, rows[3]!, { ...source, rowId: 5, text: "完成" }], locale: "zh-CN", }), ); - expect(html).toContain('data-conversation-deliverable="3:'); - expect(html).toContain("入口说明"); - expect(html).toContain("查看原始上下文"); - expect(html).not.toContain("v4-retry"); - expect(html).not.toContain("v4-fork"); + expect(html).not.toContain("data-conversation-deliverable"); + expect(html).not.toContain("data-deliverable-open-link"); + expect(html).not.toContain("查看原始上下文"); }); beforeEach(() => { openActionProps.values = []; diff --git a/packages/ui/test/conversationTurnDeliverables.test.ts b/packages/ui/test/conversationTurnDeliverables.test.ts index cefd389144a..ff4b386c79b 100644 --- a/packages/ui/test/conversationTurnDeliverables.test.ts +++ b/packages/ui/test/conversationTurnDeliverables.test.ts @@ -1,13 +1,7 @@ import { describe, expect, it } from "vitest"; import type { AssistantTextRow } from "@zcode/shared/zcode-protocol-v4"; -import { - extractConversationDeliverables, - resolveConversationDeliverableKey, -} from "@/v4/conversation-presentation/index.js"; -import { - buildConversationFlowItems, - resolveConversationFlowItemKey, -} from "@/v4/conversationTurnFlowItems.js"; +import { extractConversationDeliverables } from "@/v4/conversation-presentation/index.js"; +import { buildConversationFlowItems } from "@/v4/conversationTurnFlowItems.js"; function row( text: string, @@ -25,124 +19,40 @@ function row( }; } -describe("UX04 source deliverables", () => { - const audio = { - id: "audio-1", - mediaType: "audio" as const, - mimeType: "audio/wav", - source: { kind: "url" as const, url: "https://example.invalid/download?id=1" }, - name: "音频成果", - }; - const image = { - id: "image-1", - mediaType: "image" as const, - mimeType: "image/png", - source: { kind: "url" as const, url: "https://example.invalid/image" }, - name: "图片成果", - }; - const mediaFlow = (source: AssistantTextRow, final: AssistantTextRow) => - buildConversationFlowItems({ - orderedRows: [source, final], +describe("1.6.1 移除成果摘录", () => { + it("历史中的链接、text fence 与类型化媒体不再复制为额外行,flow 只按原行序输出", () => { + const source = { + ...row( + "请打开:\n\nhttps://example.invalid/login\n\n```text\nhttps://example.invalid/b\n```\n", + ), + media: [ + { + id: "audio-1", + mediaType: "audio" as const, + mimeType: "audio/wav", + source: { kind: "url" as const, url: "https://example.invalid/a.wav" }, + }, + ], + }; + const streaming = row("正在输出", "streaming", 20); + const items = buildConversationFlowItems({ + orderedRows: [source, streaming], assistantHistoryRows: [source], assistantFollowingRows: [], assistantTailRows: [], - latestAssistantTextRow: final, - visibleAssistantTextRow: final, + latestAssistantTextRow: streaming, + visibleAssistantTextRow: streaming, timelineOnly: false, }); - - it("UX05 空正文媒体保留单项原引用,正文缓存不吞掉媒体增量", () => { - const source = row("", "streaming"); - expect(extractConversationDeliverables([source])).toEqual([]); - source.media = [audio, image]; - const refs = extractConversationDeliverables([source]); - expect(refs).toHaveLength(2); - expect(refs[0]).toMatchObject({ - sourceFormat: "typedMedia", - sourceRowId: 12, - media: audio, - contextText: "", - start: 0, - end: 0, - }); - expect(refs[1]?.media).toBe(image); - expect(refs[0]?.key).toContain(audio.id); - }); - - it("UX05 媒体之后的最终摘要不隐藏成果,每项独立且原行不变", () => { - const source = { ...row("原说明"), media: [audio, image] }; - const final = row("完成", "complete", 20); - const items = mediaFlow(source, final); - const refs = items.flatMap((item) => - item.kind === "assistantText" && item.deliverable ? [item.deliverable] : [], - ); - expect(refs.map((ref) => ref.media)).toEqual([audio, image]); - expect(items[0]).toEqual({ kind: "assistantHistory", rows: [source] }); - expect(source.text).toBe("原说明"); - expect(items.at(-1)).toMatchObject({ row: final, latest: true }); - }); - - it("UX05 最终普通同URL链接不吞typed媒体,最终嵌入只逐项覆盖", () => { - const source = { - ...row("[网页](https://example.invalid/download?id=1)"), - media: [audio, image], - }; - const final = row("[网页](https://example.invalid/download?id=1)", "complete", 20); - const refs = (target: AssistantTextRow) => - mediaFlow(source, target).flatMap((item) => - item.kind === "assistantText" && item.deliverable ? [item.deliverable] : [], - ); - expect(refs(final).map((ref) => ref.media)).toEqual([audio, image]); - expect(refs({ ...final, media: [audio] }).map((ref) => ref.media)).toEqual([image]); - expect(refs({ ...final, media: [audio, image] })).toEqual([]); - expect( - refs({ - ...final, - text: `${final.text}\n\n![图片](https://example.invalid/image)`, - media: [audio], - }), - ).toEqual([]); - const changedMime = { ...audio, mimeType: "audio/mpeg" }; - expect(refs({ ...final, media: [changedMime] }).map((ref) => ref.media)).toEqual([ - audio, - image, + expect(items).toEqual([ + { kind: "assistantHistory", rows: [source] }, + { kind: "assistantText", row: streaming, latest: true }, ]); }); +}); - it("UX05 同目标网页与媒体key区分,来源变化稳定且完整scope隔离", () => { - const source = { ...row("[网页](https://example.invalid/download?id=1)"), media: [audio] }; - const items = mediaFlow(source, row("完成", "complete", 20)).filter( - (item) => item.kind === "assistantText" && item.deliverable, - ); - expect( - new Set(items.map((item, index) => resolveConversationFlowItemKey(item, index, 0))).size, - ).toBe(2); - const reference = extractConversationDeliverables([source]).find((ref) => ref.media)!; - const earlier = extractConversationDeliverables([ - { ...source, rowId: 1, media: [{ ...audio, id: "earlier" }] }, - ]).find((ref) => ref.media)!; - const scope = { - workspacePath: "/same", - workspaceIdentity: "ssh:a", - workspaceRemoteSessionId: "r", - sessionId: "s", - logEpoch: "e", - }; - const key = resolveConversationDeliverableKey(reference, scope, "t"); - expect(resolveConversationDeliverableKey(earlier, scope, "t")).toBe(key); - expect(earlier.key).not.toBe(reference.key); - for (const changed of [ - { workspaceIdentity: "ssh:b" }, - { workspaceRemoteSessionId: "r2" }, - { sessionId: "s2" }, - { logEpoch: "e2" }, - ]) - expect(resolveConversationDeliverableKey(reference, { ...scope, ...changed }, "t")).not.toBe( - key, - ); - expect(resolveConversationDeliverableKey(reference, scope, "t2")).not.toBe(key); - }); - it("保留独立入口完整用途段落、授权参数和准确来源区间", () => { +describe("正文引用提取(供媒体内嵌)", () => { + it("独立 URL 保留授权参数和准确来源区间", () => { const source = row( "请打开以下入口完成操作:\n\nhttps://example.invalid/authorize?code=fixture&next=%2Fdone\n", ); @@ -150,13 +60,10 @@ describe("UX04 source deliverables", () => { expect(reference).toMatchObject({ sourceRowId: 12, kind: "link", + sourceFormat: "standaloneUrl", target: "https://example.invalid/authorize?code=fixture&next=%2Fdone", - contextText: source.text.trim(), }); expect(source.text.slice(reference!.start, reference!.end)).toBe(reference!.target); - expect(source.text.slice(reference!.contextStart, reference!.contextEnd)).toBe( - reference!.contextText, - ); }); it.each(["complete", "streaming", "interrupted", "failed"] as const)( @@ -188,41 +95,19 @@ describe("UX04 source deliverables", () => { ]); }); - it("闭合且仅含一个 URL 的 text fence 保留前置说明", () => { - const source = row("完成登录后继续:\n\n```text\nhttps://example.invalid/login\n```\n"); - expect(extractConversationDeliverables([source])).toEqual([ - expect.objectContaining({ - target: "https://example.invalid/login", - sourceFormat: "textFence", - contextText: source.text.trim(), - }), - ]); - }); - - it("text fence 保留括号、查询参数与编码字符的完整目标,不裁切或重建", () => { - const target = - "https://example.invalid/login(step)?next=(done)&label=%E4%B8%AD%E6%96%87%20path&angle=%3Cdone%3E"; - expect( - extractConversationDeliverables([row(`\`\`\`text\n${target}\n\`\`\``)])[0], - ).toMatchObject({ target, sourceFormat: "textFence" }); - expect( - extractConversationDeliverables([row("```text\nhttps://example.invalid/a b\n```")]), - ).toEqual([]); - }); - it.each([ "curl https://example.invalid/login", "执行 `https://example.invalid/login`", " https://example.invalid/login\n", "```sh\ncurl https://example.invalid/login\n```", "```js\n[示例](https://example.invalid/login)\n```", - "```text\nhttps://example.invalid/a\nhttps://example.invalid/b\n```", + "```text\nhttps://example.invalid/login\n```", "```text\nhttps://example.invalid/login", "[入口](https://example.invalid/login", "![图](https://example.invalid/qr.png", "[入口](javascript:alert(1))", '[入口]("输出/未闭合.pdf)', - ])("不提升代码/命令/未闭合/无效目标 %j", (text) => { + ])("不提升代码/命令/text fence/未闭合/无效目标 %j", (text) => { expect(extractConversationDeliverables([row(text, "streaming")])).toEqual([]); }); @@ -241,86 +126,12 @@ describe("UX04 source deliverables", () => { ).toEqual([]); }); - it("CRLF 段落保留说明,并且跨行 inline code 不提升", () => { - const source = row("请继续授权:\r\n\r\nhttps://example.invalid/login\r\n"); - expect(extractConversationDeliverables([source])[0]?.contextText).toBe(source.text.trim()); + it("跨行 inline code 不提升", () => { expect( extractConversationDeliverables([row("`示例\n[入口](https://example.invalid/login)\n`\n")]), ).toEqual([]); }); - it("提取保留原文顺序的全部真实来源,跨来源去重必须晚于完整原段分组", () => { - const references = extractConversationDeliverables([ - row("[首](https://example.invalid/a) [次](https://example.invalid/b)"), - row("[重复](https://example.invalid/a)", "complete", 14), - ]); - expect(references.map((reference) => reference.target)).toEqual([ - "https://example.invalid/a", - "https://example.invalid/b", - "https://example.invalid/a", - ]); - expect(references[0]?.sourceRowId).toBe(12); - expect(references[2]?.sourceRowId).toBe(14); - }); - - it("前插同目标允许真实来源更新,但同 scope/turn 的逻辑挂载身份不变", () => { - const current = row("当前说明:[入口](https://example.invalid/a)", "complete", 20); - const earlier = row("更早说明:[入口](https://example.invalid/a)", "complete", 10); - const before = extractConversationDeliverables([current])[0]!; - const after = extractConversationDeliverables([earlier, current])[0]!; - expect(after.sourceRowId).toBe(10); - expect(after.key).not.toBe(before.key); - expect(after.contextText).toBe(earlier.text); - expect( - resolveConversationDeliverableKey(after, { workspacePath: "/same", sessionId: "s" }, "t"), - ).toBe( - resolveConversationDeliverableKey(before, { workspacePath: "/same", sessionId: "s" }, "t"), - ); - }); - - it("完整原始目标组的顺序、重复和来源代表不参与挂载身份,目标集合与scope仍隔离", () => { - const reference = extractConversationDeliverables([row("[A](https://example.invalid/a)")])[0]!; - const group = { - ...reference, - identityTargets: ["https://example.invalid/a", "https://example.invalid/b"], - }; - const scope = { - workspacePath: "/same", - workspaceIdentity: "ssh:a", - workspaceRemoteSessionId: "r", - sessionId: "s", - logEpoch: "e", - }; - const key = resolveConversationDeliverableKey(group, scope, "t"); - expect( - resolveConversationDeliverableKey( - { - ...group, - key: "other-source", - sourceRowId: 8, - target: "https://example.invalid/b", - identityTargets: [ - "https://example.invalid/b", - "https://example.invalid/a", - "https://example.invalid/a", - ], - }, - scope, - "t", - ), - ).toBe(key); - expect( - resolveConversationDeliverableKey( - { ...group, identityTargets: ["https://example.invalid/a", "https://example.invalid/c"] }, - scope, - "t", - ), - ).not.toBe(key); - expect( - resolveConversationDeliverableKey(group, { ...scope, workspaceIdentity: "ssh:b" }, "t"), - ).not.toBe(key); - }); - it("秒表刷新和相同内容重建行不会重复解析,前插历史与状态终止不改来源 key", () => { const source = row("[入口](https://example.invalid/a)", "streaming"); const first = extractConversationDeliverables([source])[0]; @@ -332,40 +143,4 @@ describe("UX04 source deliverables", () => { first?.key, ); }); - - it("挂载 key 隔离同路径的不同 Host/session/epoch/turn,identity trim 与本地 fallback 一致", () => { - const reference = extractConversationDeliverables([row("[入口](报告.pdf)")])[0]!; - const scope = { - workspacePath: "/same", - workspaceIdentity: " ssh:a ", - workspaceRemoteSessionId: "r1", - sessionId: "s1", - logEpoch: "e1", - }; - const key = resolveConversationDeliverableKey(reference, scope, "turn"); - for (const changed of [ - { workspaceIdentity: "ssh:b" }, - { workspaceRemoteSessionId: "r2" }, - { sessionId: "s2" }, - { logEpoch: "e2" }, - ]) - expect( - resolveConversationDeliverableKey(reference, { ...scope, ...changed }, "turn"), - ).not.toBe(key); - expect(resolveConversationDeliverableKey(reference, scope, "other")).not.toBe(key); - expect( - resolveConversationDeliverableKey( - reference, - { ...scope, workspaceIdentity: "ssh:a" }, - "turn", - ), - ).toBe(key); - expect(resolveConversationDeliverableKey(reference, { workspacePath: "/same" }, "turn")).toBe( - resolveConversationDeliverableKey( - reference, - { workspacePath: "/same", workspaceIdentity: " " }, - "turn", - ), - ); - }); }); diff --git a/packages/ui/test/v4ConversationTurnRenderUnits.test.ts b/packages/ui/test/v4ConversationTurnRenderUnits.test.ts index def07c39574..8f22e1feb88 100644 --- a/packages/ui/test/v4ConversationTurnRenderUnits.test.ts +++ b/packages/ui/test/v4ConversationTurnRenderUnits.test.ts @@ -20,7 +20,6 @@ import { } from "@/v4/conversationProjectionStore.js"; import { resolveAssistantCopyText } from "@/v4/ConversationTurnRow.js"; import { resolveConversationFlowItemKey } from "@/v4/conversationTurnFlowItems.js"; -import { buildConversationTurnWorkSegments } from "@/v4/conversationTurnWorkSegments.js"; function baseRow( row: Omit & { @@ -214,14 +213,12 @@ function goalVerifyMarker(rowId: number): TimelineMarkerRow { } describe("buildConversationTurnRenderUnits", () => { - it("UX04 非最终正文成果常显,原文保留、段落只展示一次、最终正文同目标去重", () => { + it("1.6.1 历史中的链接/text fence 不再追加成果摘录,flow 只含原行", () => { const source = assistantText( 3, - "用于登录:[入口](https://example.invalid/login) 与 [说明](文档/操作 说明.pdf)。", + "用于登录:[入口](https://example.invalid/login)\n\n```text\nhttps://example.invalid/b\n```", ); - const final = assistantText(5, "完成,另见 [入口](https://example.invalid/login)。", { - actions: { canFork: true, canRetry: true }, - }); + const final = assistantText(5, "完成"); const [unit] = buildConversationTurnRenderUnits([ turnHeader(1), userInput(2, "开始"), @@ -229,233 +226,9 @@ describe("buildConversationTurnRenderUnits", () => { toolCall(4), final, ]); - const excerpts = unit!.flowItems.filter( - (item) => item.kind === "assistantText" && item.deliverable, - ); - expect(excerpts).toHaveLength(1); - expect(excerpts[0]).toMatchObject({ - row: source, - latest: false, - deliverable: { target: "https://example.invalid/login", contextText: source.text }, - }); + const texts = unit!.flowItems.filter((item) => item.kind === "assistantText"); + expect(texts).toEqual([{ kind: "assistantText", row: final, latest: true }]); expect(unit!.assistantHistoryRows).toContain(source); - expect(unit!.latestAssistantTextRow).toBe(final); - const [deduped] = buildConversationTurnRenderUnits([ - turnHeader(1), - source, - toolCall(4), - assistantText(5, "[入口](https://example.invalid/login) [说明](文档/操作 说明.pdf)"), - ]); - expect( - deduped!.flowItems.filter((item) => item.kind === "assistantText" && item.deliverable), - ).toEqual([]); - const [bothNew] = buildConversationTurnRenderUnits([ - turnHeader(1), - source, - toolCall(4), - assistantText(5, "完成"), - ]); - expect( - bothNew!.flowItems.filter((item) => item.kind === "assistantText" && item.deliverable), - ).toHaveLength(1); - const beforeCovered = bothNew!.flowItems.find( - (item) => item.kind === "assistantText" && item.deliverable, - )!; - expect(resolveConversationFlowItemKey(beforeCovered, 0, 0)).toBe( - resolveConversationFlowItemKey(excerpts[0]!, 3, 0), - ); - }); - - it.each([ - ["独立 B", "https://example.invalid/b", []], - ["fence B", "```text\nhttps://example.invalid/b\n```", ["https://example.invalid/b"]], - [ - "同上下文 B/C fences", - "```text\nhttps://example.invalid/b\n```\n```text\nhttps://example.invalid/c\n```", - ["https://example.invalid/b", "https://example.invalid/c"], - ], - ] as const)( - "UX04 合并 A Markdown 段与%s的相交上下文并保留全部未覆盖打开动作", - (_label, suffix, fenceTargets) => { - const source = assistantText(3, `[A](https://example.invalid/a)\n\n${suffix}`); - const select = (finalText: string) => - buildConversationTurnRenderUnits([ - turnHeader(1), - source, - toolCall(4), - assistantText(5, finalText), - ])[0]!.flowItems.filter((item) => item.kind === "assistantText" && item.deliverable); - const initial = select("完成"); - expect(initial).toHaveLength(1); - const first = initial[0]!; - expect(first).toMatchObject({ - deliverable: { - sourceRowId: 3, - start: 0, - target: "https://example.invalid/a", - contextText: source.text, - textFenceTargets: fenceTargets, - }, - }); - const partial = select("[A](https://example.invalid/a)"); - expect(partial).toHaveLength(1); - expect(partial[0]).toMatchObject({ - deliverable: { contextText: source.text, textFenceTargets: fenceTargets }, - }); - expect(resolveConversationFlowItemKey(partial[0]!, 8, 0)).toBe( - resolveConversationFlowItemKey(first, 1, 0), - ); - if (fenceTargets.length > 0) { - const coveredB = select("[B](https://example.invalid/b)"); - expect(coveredB[0]).toMatchObject({ - deliverable: { - contextText: source.text, - textFenceTargets: fenceTargets.filter( - (target) => target !== "https://example.invalid/b", - ), - }, - }); - expect(resolveConversationFlowItemKey(coveredB[0]!, 2, 0)).toBe( - resolveConversationFlowItemKey(first, 1, 0), - ); - } - expect( - select( - "[A](https://example.invalid/a) [B](https://example.invalid/b) [C](https://example.invalid/c)", - ), - ).toEqual([]); - }, - ); - - it("UX04 相同上下文来自不同 row 时不拼接原文", () => { - const first = assistantText(3, "[A](https://example.invalid/a)"); - const second = assistantText(4, "https://example.invalid/b"); - const unit = buildConversationTurnRenderUnits([ - turnHeader(1), - first, - second, - toolCall(5), - assistantText(6, "完成"), - ])[0]!; - expect( - unit.flowItems - .filter((item) => item.kind === "assistantText" && item.deliverable) - .map((item) => (item.kind === "assistantText" ? item.deliverable?.contextText : "")), - ).toEqual([first.text, second.text]); - }); - - it("UX04 streaming→failed、中断、前插历史和强制展开都保留同一来源 key", () => { - const source = assistantText(3, "[入口](https://example.invalid/login)", { - state: "streaming", - }); - const select = (rows: ConversationRow[], forceOpenHistory = false) => { - const unit = buildConversationTurnRenderUnits(rows).at(-1)!; - return buildConversationTurnWorkSegments({ - key: unit.key, - header: unit.header, - orderedRows: unit.renderRows, - assistantTailRows: unit.assistantTailRows, - latestAssistantTextRow: unit.latestAssistantTextRow, - isRunning: unit.isRunning, - isLastTurn: unit.isLastTurn, - isInterrupted: false, - forceOpenHistory, - timelineOnly: false, - })[0]!; - }; - const running = [ - turnHeader(1, { state: "running" }), - source, - toolCall(4, "Bash", { status: "running" }), - ]; - const item = select(running).flowItems.find( - (entry) => entry.kind === "assistantText" && entry.deliverable, - )!; - const key = resolveConversationFlowItemKey(item, 1, 0); - for (const rows of [ - running, - [userInput(0, "更早", { turnId: "old" }), ...running], - [ - turnHeader(1, { state: "failed" }), - { ...source, state: "failed" } as AssistantTextRow, - toolCall(4), - ], - ]) { - for (const forceOpen of [false, true]) { - const unit = select(rows, forceOpen); - const excerpt = unit.flowItems.find( - (entry) => entry.kind === "assistantText" && entry.deliverable, - )!; - expect(excerpt).toBeDefined(); - expect(resolveConversationFlowItemKey(excerpt, 7, 0)).toBe(key); - if (forceOpen) expect(unit.assistantHistoryDefaultOpen).toBe(true); - } - } - }); - - it("UX04 同目标来源前插只更新真实代表来源,不重建单A片段的挂载身份", () => { - const source = assistantText(20, "当前说明:[入口](https://example.invalid/a)"); - const earlier = assistantText(10, "更早说明:[入口](https://example.invalid/a)"); - const select = (sources: AssistantTextRow[]) => - buildConversationTurnRenderUnits([ - turnHeader(1), - ...sources, - toolCall(30), - assistantText(40, "完成"), - ])[0]!.flowItems.filter((item) => item.kind === "assistantText" && item.deliverable); - const before = select([source]); - const after = select([earlier, source]); - expect(before).toHaveLength(1); - expect(after).toHaveLength(1); - expect(after[0]).toMatchObject({ deliverable: { sourceRowId: 10, contextText: earlier.text } }); - expect(resolveConversationFlowItemKey(after[0]!, 1, 0)).toBe( - resolveConversationFlowItemKey(before[0]!, 1, 0), - ); - }); - - it("UX04 A/B原段在跨来源A去重前固定首锚与完整目标组,前插及部分最终覆盖不跳key", () => { - const source = assistantText( - 20, - "当前说明:[A](https://example.invalid/a) [B](https://example.invalid/b)", - ); - const earlier = assistantText(10, "更早说明:[A](https://example.invalid/a)"); - const select = (sources: AssistantTextRow[], finalText = "完成") => - buildConversationTurnRenderUnits([ - turnHeader(1), - ...sources, - toolCall(30), - assistantText(40, finalText), - ])[0]!.flowItems.filter((item) => item.kind === "assistantText" && item.deliverable); - const before = select([source]); - const originalKey = resolveConversationFlowItemKey(before[0]!, 1, 0); - for (const items of [ - select([earlier, source]), - select([earlier, source], "[A](https://example.invalid/a)"), - select([source], "[B](https://example.invalid/b)"), - ]) { - const retained = items.find( - (item) => item.kind === "assistantText" && item.deliverable?.sourceRowId === 20, - )!; - expect(retained).toMatchObject({ - deliverable: { - key: before[0]!.kind === "assistantText" ? before[0]!.deliverable!.key : "", - target: "https://example.invalid/a", - contextText: source.text, - identityTargets: ["https://example.invalid/a", "https://example.invalid/b"], - }, - }); - expect(resolveConversationFlowItemKey(retained, 7, 0)).toBe(originalKey); - const keys = items.map((item, index) => resolveConversationFlowItemKey(item, index, 0)); - expect(new Set(keys).size).toBe(keys.length); - } - expect( - select([earlier, source], "[A](https://example.invalid/a) [B](https://example.invalid/b)"), - ).toEqual([]); - const duplicateGroup = assistantText(10, source.text); - const deduped = select([duplicateGroup, source]); - expect(deduped).toHaveLength(1); - expect(deduped[0]).toMatchObject({ deliverable: { sourceRowId: 10 } }); - expect(resolveConversationFlowItemKey(deduped[0]!, 1, 0)).toBe(originalKey); }); it("尾轮 token 不访问历史行并保留历史派生;历史修订和新轮仍与全窗构建相等", () => { From e4b2db4d82307a04783238d07472474aaff2490f Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:12:20 -0600 Subject: [PATCH 6/9] fix(ui): stop generating website preview cards from body URLs Localhost, public, closed-Markdown, text-fence and bare-URL links no longer produce website cards (Q41=A); they stay clickable inline. HTML file, Markdown, Office, PDF and media cards are unchanged, and a localhost URL no longer suppresses the HTML file card. Co-Authored-By: Claude Opus 5.5 --- packages/ui/src/AssistantPreviewCards.tsx | 70 ++----- packages/ui/src/i18n/locales/en-US.ts | 2 - packages/ui/src/i18n/locales/zh-CN.ts | 2 - packages/ui/src/lib/assistantPreviewCards.ts | 133 +----------- .../ui/test/assistantFilePreviewV2.test.ts | 23 -- .../ui/test/assistantMediaRendering.test.ts | 198 +----------------- .../ui/test/assistantPreviewCards.test.ts | 165 +++------------ .../ui/test/v4AssistantPreviewCards.test.ts | 30 +-- 8 files changed, 72 insertions(+), 551 deletions(-) diff --git a/packages/ui/src/AssistantPreviewCards.tsx b/packages/ui/src/AssistantPreviewCards.tsx index 1e7721a44fe..eea41ce5c21 100644 --- a/packages/ui/src/AssistantPreviewCards.tsx +++ b/packages/ui/src/AssistantPreviewCards.tsx @@ -1,4 +1,4 @@ -import { FileTextIcon, GlobeIcon } from "lucide-react"; +import { FileTextIcon } from "lucide-react"; import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react"; import type { MessageFileLinkTarget } from "@/components/ai-elements/message.js"; import { useWorkspaceServices } from "@/hooks/useWorkspaceServices.js"; @@ -24,7 +24,7 @@ export interface AssistantPreviewCardValidationResult { } export function buildAssistantPreviewCardFileSource( - card: Extract, + card: { title: string; path: string }, scope: { workspacePath?: string; workspaceIdentity?: string; @@ -79,11 +79,6 @@ interface AssistantPreviewCardsProps { onAutoOpenPptx?: (request: AssistantPreviewCardsAutoOpenRequest) => void; } -export function shouldRenderAssistantPreviewCardAsFile(card: AssistantPreviewCard): boolean { - const filePath = getAssistantPreviewCardFilePath(card); - return card.type !== "website" || (card.url.startsWith("file://") && filePath !== null); -} - export function useAssistantPreviewCardValidation( cards: AssistantPreviewCard[], scope: { @@ -254,20 +249,9 @@ function AssistantPreviewCardRow({ onOpenFileLink?: (target: MessageFileLinkTarget) => void; onOpenCodeViewer?: (source: CodeViewerSource) => void; }) { - const filePath = getAssistantPreviewCardFilePath(card); - const renderAsFile = shouldRenderAssistantPreviewCardAsFile(card); - const descriptor = filePath ? resolveFileDisplayDescriptor(filePath) : null; - const fileSource = - renderAsFile && filePath - ? { - type: "file" as const, - title: card.title, - path: filePath, - ...(workspacePath ? { workspacePath } : {}), - ...(workspaceIdentity ? { workspaceIdentity } : {}), - ...(workspaceRemoteSessionId ? { workspaceRemoteSessionId } : {}), - } - : null; + // 1.6.1 起只生成文件卡(含本地 HTML 文件卡),不再有 http(s) 网站卡分支。 + const filePath = getAssistantPreviewCardFilePath(card)!; + const descriptor = resolveFileDisplayDescriptor(filePath); return ( ( @@ -282,9 +266,7 @@ function AssistantPreviewCardRow({ } >
- {!renderAsFile && card.type === "website" ? ( - - ) : descriptor ? ( + {descriptor ? ( ) : ( @@ -299,34 +281,18 @@ function AssistantPreviewCardRow({ {button}
)} - target={ - !renderAsFile && card.type === "website" - ? { - type: "website", - url: card.url, - // website 卡有两个来源——html 引用卡(file://)与 localhost - // 预览卡(http(s) 活服务)。localPath 直开只对前者生效;localhost 卡 - // 必须继续把 URL 交给浏览器,否则丢路由/动态内容。 - workspacePath, - localPath: card.url.startsWith("file:") ? card.filePath : undefined, - } - : { - type: "file", - path: filePath!, - title: card.title, - label: card.title, - // Preview Card 以前没有 CodeViewer scope,远程 Linux path - // 会被 OpenSplitButton 当成本地路径交给宿主编辑器。 - previewSource: - card.type === "website" - ? fileSource! - : buildAssistantPreviewCardFileSource(card, { - workspacePath, - workspaceIdentity, - workspaceRemoteSessionId, - }), - } - } + target={{ + type: "file", + path: filePath, + title: card.title, + label: card.title, + // Preview Card 以前没有 CodeViewer scope,远程 Linux path + // 会被 OpenSplitButton 当成本地路径交给宿主编辑器。 + previewSource: buildAssistantPreviewCardFileSource( + { title: card.title, path: filePath }, + { workspacePath, workspaceIdentity, workspaceRemoteSessionId }, + ), + }} onOpenBrowserUrl={onOpenBrowserUrl} onOpenFileLink={onOpenFileLink} onOpenCodeViewer={onOpenCodeViewer} diff --git a/packages/ui/src/i18n/locales/en-US.ts b/packages/ui/src/i18n/locales/en-US.ts index a6042233d8f..ef7160f2d33 100644 --- a/packages/ui/src/i18n/locales/en-US.ts +++ b/packages/ui/src/i18n/locales/en-US.ts @@ -2213,7 +2213,6 @@ const enUS: Record = { "chat.codeComments.many": "{count} comments", "chat.codeComments.remove": "Remove code comments", "chat.codeCommentCards.expandAll": "Show {count} comments", - "chat.deliverable.showSourceContext": "View original context", "chat.codeCommentCards.collapseAll": "Collapse comments", "chat.codeCommentCards.openReview": "Open code review for {title}", "chat.webElements.one": "1 web element", @@ -3076,7 +3075,6 @@ const enUS: Record = { "chat.edit.workspaceConflict.description": "No conversation history was changed. Review the conflicting or ignored files, then reset only the conversation or cancel.", "chat.edit.workspaceConflict.conversationOnly": "Reset chat only and send", - "chat.previewCards.website": "Website", "chat.previewCards.htmlWebsite": "Website · HTML", "chat.previewCards.markdown": "Document · MD", "chat.previewCards.text": "Text · TXT", diff --git a/packages/ui/src/i18n/locales/zh-CN.ts b/packages/ui/src/i18n/locales/zh-CN.ts index a58c2d9daf4..681ed230208 100644 --- a/packages/ui/src/i18n/locales/zh-CN.ts +++ b/packages/ui/src/i18n/locales/zh-CN.ts @@ -2029,7 +2029,6 @@ const zhCN: Record = { "chat.codeComments.many": "{count} 条评论", "chat.codeComments.remove": "移除代码评论", "chat.codeCommentCards.expandAll": "展开 {count} 条评论", - "chat.deliverable.showSourceContext": "查看原始上下文", "chat.codeCommentCards.collapseAll": "收起评论", "chat.codeCommentCards.openReview": "打开 {title} 的代码审查", "chat.webElements.one": "1 个网页元素", @@ -2854,7 +2853,6 @@ const zhCN: Record = { "chat.edit.workspaceConflict.description": "对话尚未裁剪。请检查冲突或忽略的文件,然后仅重置对话并发送,或取消。", "chat.edit.workspaceConflict.conversationOnly": "仅重置对话并发送", - "chat.previewCards.website": "网站", "chat.previewCards.htmlWebsite": "网站 · HTML", "chat.previewCards.markdown": "文档 · MD", "chat.previewCards.text": "文本 · TXT", diff --git a/packages/ui/src/lib/assistantPreviewCards.ts b/packages/ui/src/lib/assistantPreviewCards.ts index 7caf91cef4d..99713529164 100644 --- a/packages/ui/src/lib/assistantPreviewCards.ts +++ b/packages/ui/src/lib/assistantPreviewCards.ts @@ -12,17 +12,12 @@ import { parseAssistantFileUrlPath, resolveAssistantRawFilePath, type AssistantFileReference, - type AssistantFilePathResolveOptions, type AssistantPreviewFileKind, type AssistantPreviewFileSubtitleId, } from "@/lib/assistantFileReferences.js"; -import { decodeFilePathUriEscapes, getPathLeaf, toFileUrl } from "@/lib/path.js"; +import { getPathLeaf, toFileUrl } from "@/lib/path.js"; import type { CodeViewerSource } from "@/lib/codeViewer.js"; import { collectGenUiSourcePaths, matchesGenUiSourcePath } from "@/gen-ui/contract.js"; -import { - assistantPresentationReferences, - classifyAssistantMedia, -} from "@/v4/conversation-presentation/index.js"; export { extractAssistantFileReferences, @@ -47,7 +42,7 @@ export type AssistantPreviewCard = id: string; type: "website"; title: string; - subtitleId: "chat.previewCards.website" | "chat.previewCards.htmlWebsite"; + subtitleId: "chat.previewCards.htmlWebsite"; url: string; filePath?: string; } @@ -75,13 +70,8 @@ export interface AssistantPreviewCardFileStatService { checkFilesExist(params: { paths: string[] }): Promise>; } -const LOCALHOST_URL_RE = - /\bhttps?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?(?:[/?#][^\s<>()\]`"'*,。!?;:、]*)?/gi; -const STRICT_LOCALHOST_URL_RE = - /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d{1,5})?(?:[/?#][^\s<>()\]`"'*,。!?;:、]*)?$/i; const STRICT_FILE_HTML_URL_RE = /^file:\/\/(?:localhost\/|\/|[^/\s<>()\]`"'*,。!?;:、]+\/)[^\s<>()\]`"'*,。!?;:、]+\.html?(?:[?#][^\s<>()\]`"'*,。!?;:、]*)?$/i; -const MARKDOWN_LINK_RE = /\[([^\]\n]*)\]\(([^)\n]+)\)/g; interface AssistantPreviewCardOptions { changedFilePaths?: readonly string[]; @@ -122,25 +112,6 @@ export function isValidAssistantPreviewWebsiteUrl(url: string): boolean { } } -function normalizeMarkdownHref(href: string): string { - return href.trim().replace(/^<|>$/g, ""); -} - -function cleanMarkdownLinkTitle(title: string): string | null { - const normalizedTitle = title.replace(/\s+/g, " ").trim(); - if ( - !normalizedTitle || - normalizedTitle.length > 80 || - /^https?:\/\//i.test(normalizedTitle) || - /[*_`[\]<>]/.test(normalizedTitle) || - /^[)"'`,.;:!?,。!?;:、)】》]+/.test(normalizedTitle) || - !/[a-zA-Z0-9\u4e00-\u9fff]/.test(normalizedTitle) - ) { - return null; - } - return normalizedTitle; -} - export function shouldOpenAssistantHtmlInBrowser(params: { compactForRemoteControl?: boolean; path: string; @@ -191,47 +162,6 @@ function findMatchingChangedFilePath( return leafMatches.length === 1 ? leafMatches[0]!.path : null; } -function getWebsiteTitleFromMarkdownLink(content: string, url: string): string | null { - for (const match of content.matchAll(MARKDOWN_LINK_RE)) { - const label = match[1] ? cleanMarkdownLinkTitle(match[1]) : null; - const href = match[2] ? normalizeTrailingUrlText(normalizeMarkdownHref(match[2])) : ""; - if (label && href === url && !/^https?:\/\//i.test(label)) return label; - } - return null; -} - -function getWebsiteFallbackTitle(url: string): string { - try { - const parsedUrl = new URL(url); - const pathLeaf = getPathLeaf(decodeURI(parsedUrl.pathname)); - return pathLeaf && pathLeaf !== "/" ? pathLeaf : parsedUrl.host; - } catch { - return url; - } -} - -function resolveLocalhostHtmlChangedPath( - url: string, - workspacePath: string, - changedFilePaths: readonly string[], - options: AssistantFilePathResolveOptions = {}, -): string | null { - try { - const parsedUrl = new URL(url); - const pathname = decodeFilePathUriEscapes(parsedUrl.pathname).replace(/^\/+/, ""); - if (!isAssistantPreviewHtmlPath(pathname)) return null; - const path = resolveAssistantRawFilePath(workspacePath, pathname, options); - if (!path) return null; - return findMatchingChangedFilePath( - { start: 0, end: 0, kind: "html", path, raw: pathname }, - changedFilePaths, - workspacePath, - ); - } catch { - return null; - } -} - function buildFileCard(reference: AssistantFileReference): AssistantPreviewCard { const definition = getAssistantPreviewFileTypeDefinition(reference.path)!; if (reference.kind === "markdown") { @@ -269,15 +199,7 @@ function buildFileCard(reference: AssistantFileReference): AssistantPreviewCard function getCardSeenKey(card: AssistantPreviewCard): string { const filePath = getAssistantPreviewCardFilePath(card); - if (filePath) return `file:${normalizePathForCompare(filePath)}`; - try { - const parsedUrl = new URL(card.type === "website" ? card.url : ""); - return parsedUrl.pathname === "/" && !parsedUrl.search && !parsedUrl.hash - ? `url:${parsedUrl.origin}` - : `url:${parsedUrl.href}`; - } catch { - return card.id; - } + return filePath ? `file:${normalizePathForCompare(filePath)}` : card.id; } export function buildAssistantPreviewCards( @@ -305,56 +227,11 @@ export function buildAssistantPreviewCardsFromReferences( const changedFilePaths = options.changedFilePaths ?? []; const genUiSources = collectGenUiSourcePaths(content); const positionedCards: PositionedCard[] = []; - let hasLocalHttpPreview = false; - - // 既有 localhost 行内地址语义保持;普通公网卡仅来自闭合的收到引用。 - const closedReferences = assistantPresentationReferences(content); - const websiteReferences = [ - ...closedReferences, - // 闭合引用已保留完整括号/查询;旧行内正则不能再从同一原文切出截断的第二张卡。 - ...Array.from(content.matchAll(LOCALHOST_URL_RE)) - .filter( - (match) => - !closedReferences.some( - (reference) => match.index >= reference.start && match.index < reference.end, - ), - ) - .map((match) => ({ target: normalizeTrailingUrlText(match[0]), start: match.index })), - ]; - for (const reference of websiteReferences) { - const url = reference.target; - if (!isValidAssistantPreviewWebsiteUrl(url)) continue; - if (classifyAssistantMedia(url)) continue; - const isLocal = STRICT_LOCALHOST_URL_RE.test(url); - // Web 远控没有本地端口转发或 HTML 运行环境;在候选上限前过滤,避免隐藏卡片占位。 - if (options.suppressWebRemoteCards && isLocal) continue; - const filePath = isLocal - ? resolveLocalhostHtmlChangedPath(url, workspacePath, changedFilePaths, { - homePath: options.homePath, - }) - : null; - if (filePath && matchesGenUiSourcePath(filePath, genUiSources)) continue; - hasLocalHttpPreview ||= isLocal; - positionedCards.push({ - position: reference.start, - card: { - id: `website:${url}`, - type: "website", - title: - filePath !== null - ? getPathLeaf(filePath) - : (getWebsiteTitleFromMarkdownLink(content, url) ?? getWebsiteFallbackTitle(url)), - subtitleId: "chat.previewCards.website", - url, - ...(filePath ? { filePath } : {}), - }, - }); - } - + // 1.6.1 起不再从正文 URL(localhost / 闭合链接 / text fence / 裸 URL)生成网站卡: + // 用户反馈正文已有可点链接,额外的网站卡与之重复且令人困惑(Q41=A);HTML 文件卡保留。 const fileReferences: AssistantFileReference[] = []; for (const reference of references) { if (options.suppressWebRemoteCards && reference.kind === "html") continue; - if (reference.kind === "html" && hasLocalHttpPreview) continue; let resolvedReference = reference; if (reference.kind === "markdown" || reference.kind === "html") { diff --git a/packages/ui/test/assistantFilePreviewV2.test.ts b/packages/ui/test/assistantFilePreviewV2.test.ts index f5f39ebf409..a029af4f0d9 100644 --- a/packages/ui/test/assistantFilePreviewV2.test.ts +++ b/packages/ui/test/assistantFilePreviewV2.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it, vi } from "vitest"; -import { shouldRenderAssistantPreviewCardAsFile } from "@/AssistantPreviewCards.js"; import { ASSISTANT_PREVIEW_CARD_CANDIDATE_LIMIT, ASSISTANT_PREVIEW_CARD_VISIBLE_LIMIT, @@ -437,26 +436,4 @@ describe("assistant HTML open target", () => { }), ).toBe(false); }); - it("HTML 文件使用静态 Preview Pane,localhost HTTP 仍使用 Browser", () => { - expect( - shouldRenderAssistantPreviewCardAsFile({ - id: "website:file:///workspace/page.html", - type: "website", - title: "page.html", - subtitleId: "chat.previewCards.htmlWebsite", - url: "file:///workspace/page.html", - filePath: "/workspace/page.html", - }), - ).toBe(true); - expect( - shouldRenderAssistantPreviewCardAsFile({ - id: "website:http://localhost:5173/page.html", - type: "website", - title: "page.html", - subtitleId: "chat.previewCards.website", - url: "http://localhost:5173/page.html", - filePath: "/workspace/page.html", - }), - ).toBe(false); - }); }); diff --git a/packages/ui/test/assistantMediaRendering.test.ts b/packages/ui/test/assistantMediaRendering.test.ts index cd4b0020eee..d763114bf4f 100644 --- a/packages/ui/test/assistantMediaRendering.test.ts +++ b/packages/ui/test/assistantMediaRendering.test.ts @@ -9,13 +9,7 @@ import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js"; import { ServiceProvider } from "@/hooks/useServices.js"; import type { IServiceAccessor } from "@zcode/services"; import { buildAssistantPreviewCards } from "@/lib/assistantPreviewCards.js"; -import type { AssistantMediaRef, AssistantTextRow } from "@zcode/shared/zcode-protocol-v4"; -import { ConversationTurnRow } from "@/v4/ConversationTurnRow.js"; -import { - extractConversationDeliverables, - resolveConversationDeliverableKey, -} from "@/v4/conversation-presentation/index.js"; -import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js"; +import type { AssistantMediaRef } from "@zcode/shared/zcode-protocol-v4"; // CodeViewer 正文位于第三方 shadow DOM;这里只观察传入的原文,真实渲染由 E2E 覆盖。 vi.mock("@/components/ui/code-viewer.js", () => ({ @@ -44,86 +38,6 @@ const ref = ( }); describe("UX05 已送达媒体", () => { - it.each([ - ["image", "image/png", "img"], - ["audio", "audio/wav", "audio"], - ["video", "video/mp4", "video"], - ] as const)( - "%s 成果前插较早来源不重挂真实叶子、不重读或重置 Blob", - async (kind, mimeType, selector) => { - const reader = vi.fn().mockResolvedValue({ bytes: new Uint8Array([1]), mediaType: mimeType }); - const createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:original"); - const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); - const source: AssistantTextRow = { - rowId: 12, - turnId: "t", - createdAt: 1, - createdAtSeq: 12, - kind: "assistantText", - text: "", - state: "complete", - media: [ - { - id: "latest", - name: "较晚来源", - mediaType: kind, - mimeType, - source: { kind: "artifact", uri: "zcode-artifact://session-a/result" }, - }, - ], - }; - const context = { - workspacePath: "/same", - workspaceIdentity: "ssh:host-a", - workspaceRemoteSessionId: "r-a", - sessionId: "session-a", - logEpoch: "epoch-a", - theme: "light" as const, - codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS, - readAttachment: reader, - }; - const renderRow = (row: AssistantTextRow) => { - const deliverable = extractConversationDeliverables([row])[0]!; - return wrap( - createElement(ConversationTurnRow, { - key: resolveConversationDeliverableKey(deliverable, context, row.turnId), - row, - deliverable, - context, - }), - ); - }; - const view = render(renderRow(source)); - await waitFor(() => - expect(view.container.querySelector(selector)?.getAttribute("src")).toBe("blob:original"), - ); - const original = view.container.querySelector(selector)!; - if (original instanceof HTMLMediaElement) original.currentTime = 0.75; - view.rerender( - renderRow({ - ...source, - rowId: 1, - createdAtSeq: 1, - media: [{ ...source.media![0]!, id: "earlier", name: "较早来源" }], - }), - ); - await waitFor(() => - expect(view.container.querySelector(selector)?.getAttribute("src")).toBe("blob:original"), - ); - expect(view.container.querySelector('[data-source-row-id="1"]')).not.toBeNull(); - expect(view.container.querySelector('[data-source-row-id="12"]')).toBeNull(); - expect(view.container.querySelector(selector)).toBe(original); - if (original instanceof HTMLMediaElement) expect(original.currentTime).toBe(0.75); - else expect(original.getAttribute("alt")).toBe("较早来源"); - expect(reader).toHaveBeenCalledTimes(1); - expect(reader).toHaveBeenCalledWith({ - sessionId: "session-a", - ref: "zcode-artifact://session-a/result", - }); - expect(createUrl).toHaveBeenCalledTimes(1); - expect(revoke).not.toHaveBeenCalled(); - }, - ); it.each([ "target", "MIME", @@ -192,53 +106,6 @@ describe("UX05 已送达媒体", () => { view.unmount(); expect(revoke).toHaveBeenCalledWith("blob:after"); }); - it("类型化成果每个excerpt只渲染当前媒体,并保留准确来源和上下文按钮", () => { - const source = { - rowId: 12, - turnId: "t", - createdAt: 1, - createdAtSeq: 12, - kind: "assistantText" as const, - text: "", - state: "complete" as const, - media: [ - ref("audio", { kind: "url", url: "https://example.com/audio" }), - ref("video", { kind: "url", url: "https://example.com/video" }), - ], - actions: { canRetry: true, canFork: true }, - }; - const showSource = vi.fn(); - const references = extractConversationDeliverables([source]); - render( - wrap( - createElement( - "div", - null, - references.map((deliverable) => - createElement(ConversationTurnRow, { - key: deliverable.key, - row: source, - deliverable, - context: { - workspacePath: "/same", - theme: "light", - codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS, - }, - onShowSourceContext: showSource, - }), - ), - ), - ), - ); - expect(document.querySelectorAll("audio")).toHaveLength(1); - expect(document.querySelectorAll("video")).toHaveLength(1); - expect(document.querySelectorAll('[data-source-row-id="12"]')).toHaveLength(2); - fireEvent.click(screen.getAllByRole("button", { name: "查看原始上下文" })[0]!); - expect(showSource).toHaveBeenCalledTimes(1); - expect( - document.querySelector('[data-testid^="v4-retry"], [data-testid^="v4-fork"]'), - ).toBeNull(); - }); it("Markdown 媒体写法按音视频扩展名复用原生控件", () => { render( wrap( @@ -312,72 +179,27 @@ describe("UX05 已送达媒体", () => { expect(revoke).toHaveBeenCalledWith("blob:audio"); expect(revoke).toHaveBeenCalledWith("blob:video"); }); - it("流式 text fence 闭合及目标更新读取当前完整目标", () => { - const first = "https://example.com/first?next=(a)&x=1"; - const second = "https://example.com/second?next=(b)&x=2"; - const open = vi.fn(); - const response = (body: string) => - wrap( - createElement(MessageResponse, { - children: body, - streaming: true, - theme: "light", - onOpenExternalUrl: open, - }), - ); - const view = render(response(`\`\`\`text\n${first}`)); - expect(view.container.querySelector("[data-assistant-text-fence-link]")).toBeNull(); - view.rerender(response(`\`\`\`text\n${first}\n\`\`\``)); - const firstAction = view.container.querySelector( - "[data-assistant-text-fence-link]", - ); - expect(firstAction?.getAttribute("title")).toBe(first); - fireEvent.click(firstAction!); - expect(open).toHaveBeenLastCalledWith(first); - view.rerender(response(`\`\`\`text\n${second}\n\`\`\``)); - const secondAction = view.container.querySelector( - "[data-assistant-text-fence-link]", - ); - expect(secondAction?.getAttribute("title")).toBe(second); - fireEvent.click(secondAction!); - expect(open).toHaveBeenLastCalledWith(second); - }); - it("无 MIME 的普通网页按收到的标题成卡且手机仍可打开", () => { - const cards = buildAssistantPreviewCards( - "[成果说明](https://example.com/result)", - "/workspace", - { suppressWebRemoteCards: true }, - ); - expect(cards).toContainEqual( - expect.objectContaining({ - type: "website", - title: "成果说明", - url: "https://example.com/result", - }), - ); - }); - it("完整闭合的 localhost URL 不再派生一张截断卡片", () => { + it("1.6.1 普通网页与 localhost URL 不再生成网站卡", () => { + expect( + buildAssistantPreviewCards("[成果说明](https://example.com/result)", "/workspace"), + ).toEqual([]); const url = "http://localhost:3000/result?next=(step)&x=1"; - expect(buildAssistantPreviewCards(`\`\`\`text\n${url}\n\`\`\``, "/workspace")).toEqual([ - expect.objectContaining({ type: "website", url }), - ]); + expect(buildAssistantPreviewCards(`\`\`\`text\n${url}\n\`\`\``, "/workspace")).toEqual([]); + expect(buildAssistantPreviewCards(`访问 ${url}`, "/workspace")).toEqual([]); }); - it("最终正文保留单 URL text fence 并可打开完整目标", () => { + it("1.6.1 单 URL text fence 只保留代码块,下方不再追加链接行", () => { const href = "https://example.com/result?q=(a)&x=1"; - const open = vi.fn(); render( wrap( createElement( MessageResponse, - { theme: "light", onOpenExternalUrl: open }, + { theme: "light", onOpenExternalUrl: vi.fn() }, `说明\n\n\`\`\`text\n${href}\n\`\`\``, ), ), ); - const button = screen.getByRole("button", { name: href }); - fireEvent.click(button); - expect(open).toHaveBeenCalledWith(href); expect(document.querySelector('[data-language="text"]')?.textContent).toContain(href); + expect(screen.queryByRole("button", { name: href })).toBeNull(); }); it.each(["audio", "video"] as const)( "显式 MIME 的无扩展名 %s 使用原生控件且不自动播放", diff --git a/packages/ui/test/assistantPreviewCards.test.ts b/packages/ui/test/assistantPreviewCards.test.ts index 142b2e2a588..5ba6051ca55 100644 --- a/packages/ui/test/assistantPreviewCards.test.ts +++ b/packages/ui/test/assistantPreviewCards.test.ts @@ -87,33 +87,16 @@ describe("buildAssistantPreviewCards", () => { }); }); - it("builds website cards for localhost links with markdown labels", () => { - const cards = buildAssistantPreviewCards( + it("1.6.1 不再从 localhost / 127.0.0.1 / 公网链接生成网站卡", () => { + for (const content of [ "Open [Neon Snake](http://localhost:5173/play) when ready.", - "/workspace", - ); - - expect(cards).toEqual([ - { - id: "website:http://localhost:5173/play", - type: "website", - title: "Neon Snake", - subtitleId: "chat.previewCards.website", - url: "http://localhost:5173/play", - }, - ]); - }); - - it("builds website cards for 127.0.0.1 links", () => { - const cards = buildAssistantPreviewCards("Preview: http://127.0.0.1:3000.", "/workspace"); - - expect(cards).toMatchObject([ - { - type: "website", - title: "127.0.0.1:3000", - url: "http://127.0.0.1:3000", - }, - ]); + "Preview: http://127.0.0.1:3000.", + "[说明](https://example.com/result)", + "```text\nhttp://localhost:3000/a\n```", + "服务地址是 **http://localhost:8765/dashboard/index.html**,可以打开。", + ]) { + expect(buildAssistantPreviewCards(content, "/workspace")).toEqual([]); + } }); it("builds markdown cards from links and raw paths without duplicates", () => { @@ -203,7 +186,7 @@ describe("buildAssistantPreviewCards", () => { expect(cards).toHaveLength(1); }); - it("does not build html file cards when a local http preview exists", () => { + it("localhost URL 不再抑制 HTML 文件卡", () => { const cards = buildAssistantPreviewCards( [ "Preview http://localhost:5173.", @@ -217,14 +200,8 @@ describe("buildAssistantPreviewCards", () => { ); expect(cards).toMatchObject([ - { - type: "markdown", - path: "/workspace/docs/notes.md", - }, - { - type: "website", - url: "http://localhost:5173", - }, + { type: "markdown", path: "/workspace/docs/notes.md" }, + { type: "website", url: "file:///workspace/game/index.html" }, ]); expect(cards).toHaveLength(2); }); @@ -245,93 +222,8 @@ describe("buildAssistantPreviewCards", () => { ]); }); - it("trims markdown emphasis and CJK punctuation from localhost URLs", () => { - const cards = buildAssistantPreviewCards( - "服务地址是 **http://localhost:8765/dashboard/index.html**,你现在可以在浏览器打开试试。", - "/workspace", - { - changedFilePaths: ["/workspace/dashboard/index.html"], - }, - ); - - expect(cards).toEqual([ - { - id: "website:http://localhost:8765/dashboard/index.html", - type: "website", - title: "index.html", - subtitleId: "chat.previewCards.website", - url: "http://localhost:8765/dashboard/index.html", - filePath: "/workspace/dashboard/index.html", - }, - ]); - expect(cards.map((card) => requiresAssistantPreviewCardFileStat(card))).toEqual([true]); - }); - - it("treats localhost html URL paths as workspace files before rendering", () => { - const cards = buildAssistantPreviewCards( - "服务地址是 http://localhost:8765/dashboard/index.html。", - "/workspace", - { changedFilePaths: ["/workspace/dashboard/index.html"] }, - ); - - expect(cards).toEqual([ - { - id: "website:http://localhost:8765/dashboard/index.html", - type: "website", - title: "index.html", - subtitleId: "chat.previewCards.website", - url: "http://localhost:8765/dashboard/index.html", - filePath: "/workspace/dashboard/index.html", - }, - ]); - expect(cards.map((card) => requiresAssistantPreviewCardFileStat(card))).toEqual([true]); - }); - - it("deduplicates localhost cards and ignores polluted markdown link labels", () => { - const cards = buildAssistantPreviewCards( - [ - "[** (kernel](http://127.0.0.1:8781)", - "[) 。完整](http://127.0.0.1:8781)", - "也可以直接打开 http://127.0.0.1:8781。", - ].join("\n"), - "/workspace", - ); - - expect(cards).toEqual([ - { - id: "website:http://127.0.0.1:8781", - type: "website", - title: "127.0.0.1:8781", - subtitleId: "chat.previewCards.website", - url: "http://127.0.0.1:8781", - }, - ]); - }); - it("classifies cards that require file stat", () => { const cards: AssistantPreviewCard[] = [ - { - id: "website:http://localhost:5173", - type: "website", - title: "localhost:5173", - subtitleId: "chat.previewCards.website", - url: "http://localhost:5173", - }, - { - id: "website:http://localhost:70000", - type: "website", - title: "localhost:70000", - subtitleId: "chat.previewCards.website", - url: "http://localhost:70000", - }, - { - id: "website:http://localhost:8765/dashboard/index.html", - type: "website", - title: "index.html", - subtitleId: "chat.previewCards.website", - url: "http://localhost:8765/dashboard/index.html", - filePath: "/workspace/dashboard/index.html", - }, { id: "website:file:///workspace/index.html", type: "website", @@ -372,9 +264,6 @@ describe("buildAssistantPreviewCards", () => { }, ]; expect(cards.map((card) => requiresAssistantPreviewCardFileStat(card))).toEqual([ - false, - false, - true, true, true, true, @@ -384,24 +273,18 @@ describe("buildAssistantPreviewCards", () => { }); it("returns stat-free preview cards synchronously", () => { - const cards: AssistantPreviewCard[] = [ - { - id: "website:http://localhost:5173", - type: "website", - title: "localhost:5173", - subtitleId: "chat.previewCards.website", - url: "http://localhost:5173", - }, - { - id: "website:http://localhost:70000", - type: "website", - title: "bad localhost", - subtitleId: "chat.previewCards.website", - url: "http://localhost:70000", - }, - ]; - - expect(resolveAssistantPreviewCardsWithoutFileStat(cards)).toEqual([cards[0]]); + expect(resolveAssistantPreviewCardsWithoutFileStat([])).toEqual([]); + expect( + resolveAssistantPreviewCardsWithoutFileStat([ + { + id: "website:file:///workspace/index.html", + type: "website", + title: "index.html", + subtitleId: "chat.previewCards.htmlWebsite", + url: "file:///workspace/index.html", + }, + ]), + ).toBeNull(); }); it("waits for all file-backed preview checks before returning renderable cards", async () => { diff --git a/packages/ui/test/v4AssistantPreviewCards.test.ts b/packages/ui/test/v4AssistantPreviewCards.test.ts index 30b093c984a..532e61bfaeb 100644 --- a/packages/ui/test/v4AssistantPreviewCards.test.ts +++ b/packages/ui/test/v4AssistantPreviewCards.test.ts @@ -456,33 +456,33 @@ function unitWithWorkRows( } describe("v4 assistant preview cards helper", () => { - it("builds a website card for a completed latest assistant row", () => { - const row = assistantText(1, "Preview http://localhost:5173."); + it("builds a file card for a completed latest assistant row", () => { + const row = assistantText(1, "Generated report.pdf."); expect(buildForRow(row, [row])).toMatchObject([ { - type: "website", - url: "http://localhost:5173", + type: "file", + path: "/workspace/report.pdf", }, ]); }); it("builds interrupted turn cards from early assistant text but only for the latest row", () => { - const early = assistantText(1, "Preview http://localhost:5173."); + const early = assistantText(1, "Generated report.pdf."); const latest = assistantText(2, "已停止。", "interrupted"); expect(buildForRow(early, [early, latest])).toEqual([]); expect(buildForRow(latest, [early, latest])).toMatchObject([ { - type: "website", - url: "http://localhost:5173", + type: "file", + path: "/workspace/report.pdf", }, ]); }); it("does not build cards for streaming, failed, or non-latest rows", () => { - const streaming = assistantText(1, "Preview http://localhost:5173.", "streaming"); - const failed = assistantText(2, "Preview http://localhost:5173.", "failed"); + const streaming = assistantText(1, "Generated report.pdf.", "streaming"); + const failed = assistantText(2, "Generated report.pdf.", "failed"); const latest = assistantText(3, "done"); expect(buildForRow(streaming, [streaming])).toEqual([]); @@ -491,12 +491,12 @@ describe("v4 assistant preview cards helper", () => { }); it("merges multiple assistant text segments before deduping candidates", () => { - const first = assistantText(1, "Preview http://localhost:5173 and README.md."); - const latest = assistantText(2, "Again: http://localhost:5173 and ./README.md."); + const first = assistantText(1, "Generated report.pdf and README.md."); + const latest = assistantText(2, "Again: report.pdf and ./README.md."); expect(buildForRow(latest, [first, latest]).map((card) => card.id)).toEqual([ "markdown:/workspace/README.md", - "website:http://localhost:5173", + "file:pdf:/workspace/report.pdf", ]); }); }); @@ -535,12 +535,12 @@ describe("ConversationTurnGroup assistant preview cards", () => { } }); it("renders preview cards once below the latest assistant text row", () => { - const early = assistantText(1, "Preview http://localhost:5173."); + const early = assistantText(1, "Generated report.pdf."); const latest = assistantText(2, "Final answer."); const html = renderTurn(baseUnit([early, latest])); expect(html.match(/mock-assistant-preview-cards/g)).toHaveLength(1); - expect(html).toContain('data-card-ids="website:http://localhost:5173"'); + expect(html).toContain('data-card-ids="file:pdf:/workspace/report.pdf"'); expect(html.indexOf("Final answer.")).toBeLessThan( html.indexOf('data-testid="mock-assistant-preview-cards"'), ); @@ -550,7 +550,7 @@ describe("ConversationTurnGroup assistant preview cards", () => { const onOpenBrowserUrl = vi.fn(); const onOpenCodeViewer = vi.fn(); const onOpenFileLink = vi.fn(); - const row = assistantText(1, "Preview http://localhost:5173 and README.md."); + const row = assistantText(1, "Generated report.pdf and README.md."); const html = renderTurnWithContext(baseUnit([row]), { ...rowContext, onOpenBrowserUrl, From 1c84ddb8809d7841836dbffc47a5a16653f45742 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:12:22 -0600 Subject: [PATCH 7/9] docs(ui): record removal of website cards and work-history excerpts Update assistant-preview-cards spec, the conversation-experience design note and the preview-cards desktop E2E spec to the 1.6.1 behaviour. Co-Authored-By: Claude Opus 5.5 --- ...15-conversation-experience-optimization.md | 25 +- docs/ui/assistant-preview-cards.md | 120 +++------ ...on-session-assistant-preview-cards.test.ts | 246 +++++------------- 3 files changed, 112 insertions(+), 279 deletions(-) diff --git a/docs/design/2026-11-15-conversation-experience-optimization.md b/docs/design/2026-11-15-conversation-experience-optimization.md index 9d469d1e224..13c3902c20a 100644 --- a/docs/design/2026-11-15-conversation-experience-optimization.md +++ b/docs/design/2026-11-15-conversation-experience-optimization.md @@ -103,27 +103,22 @@ flowchart LR ## 5. 具体交互合同 -### 5.1 过程折叠与成果常显 +### 5.1 过程折叠与成果常显(1.6.1 已撤销) -本节在既有折叠/预览合同 `docs/ui/assistant-preview-cards.md` 的 -“Work-history deliverable excerpts (UX04)”落地。纯提取与来源引用属于受管 -`packages/ui/src/v4/conversation-presentation`,经公开 `index.ts` 消费; -T04 不新增媒体协议事实,T05 再接入类型化媒体。 +1.6.1 按用户决定(Q41=A)移除“成果摘录”:它把历史中的链接段落、text 代码块和类型化媒体 +复制为额外的“打开 / 查看原始上下文”行,并追加在运行中 turn 的已展开历史末尾,导致完整段落 +或代码块出现在仍在流式输出的正文下方(流式不再自上而下),且与正文内链接重复。 - 不删除、搬写或改写原 assistantText。最终答复仍只在其原有位置承载复制/重试/分叉等操作。 -- 把已收到的明确媒体、文件、链接引用及其所在说明段落提取为来源可追溯的成果片段,放在过程折叠外。最终正文已经展示同一引用时不重复加一份成果卡。 -- 只做确定性识别:Markdown 链接/图片、已类型化媒体/文件、独立 URL,以及内容仅为一个 URL 的 text 代码块。命令、普通代码示例、行内代码中的 URL 不自动提升。 -- 片段保留完整上下文段落,不能只留下一个失去用途说明的 URL。保留查看原始上下文入口;原历史仍可展开。 -- 流式期间只接纳已闭合的 Markdown、以换行确认完整的独立 URL、闭合且仅含一个 URL 的 text 代码块或完整的类型化事实;终止/失败轮已收到的有效成果也不能消失。虚拟列表只处理已加载行,不假称缺失历史已扫描完整。 -- 成果提取保持原文顺序并按完整目标去重;不因标题、标签截断而截断真实目标。授权参数原样用于打开,不写诊断日志。 -- 工具普通诊断图片仍归工具详情;引擎明确给出的可交付图片/媒体和现有指定常显截图才进入成果区,避免每次浏览器操作都刷图墙。 +- flow 只按原行序输出原历史与外置正文,不再投影额外摘录行;历史中的链接与媒体随原历史展开查看。 +- `conversation-presentation` 只保留纯引用提取(闭合 Markdown 链接/图片与以换行确认完整的独立 URL),供正文媒体内嵌使用。 ### 5.2 图文与媒体 - 复用 MarkdownImage、现有图片画廊、artifact 读取、音视频播放器、文件预览和 Side Pane。 - 直接媒体有可访问名称、缩略/播放控件及打开原件入口;音视频不自动播放。加载失败展示可重试状态与原链接,不留空白。 -- 普通网页使用标题/域名/用途文本的链接卡片,不嵌任意 iframe,不要求联网抓取标题才能展示。 -- 无扩展名 URL 只有在已有可信 MIME/结构化元数据时才内嵌;不能判断时保留网页卡片,不靠 URL 文案猜内容。 +- 普通网页(含 localhost)只保留正文内可点链接,1.6.1 起不再生成网站预览卡;不嵌任意 iframe。 +- 无扩展名 URL 只有在已有可信 MIME/结构化元数据时才内嵌;不能判断时保持普通链接,不靠 URL 文案猜内容。 - 不从一句“已生成二维码”凭空生成二维码。已有图片、原生媒体与授权链接分别显示;生成缺失属于上游事实问题。 - 本地/SSH 文件继续由正确 workspace Host 读取;保留路径校验、图片尺寸/字节限制、既有候选检查上限、缓存与 Markdown/HTML fileChanges 门禁。 - 外部引擎原生媒体必须先成为可持久化、可回放的媒体事实,再接入同一 Renderer;不能只在 live 回调里临时显示。 @@ -206,8 +201,8 @@ sequenceDiagram | UX01 | 鼠标/键盘进入重命名稳定获焦,Enter 保存一次,Esc/IME/切换供应商符合合同。 | | UX02 | 支持 effort 的目录显示原生档位;目录更新、切模、恢复、ACK 乱序不丢能力或串会话。 | | UX03 | reply-only 子任务在详情、父摘要和冷恢复都有结果;流式正文加 reply 不重复。 | -| UX04 | 非最终正文里的授权链接、二维码图、成果与说明在折叠外可见,原上下文可回看。 | -| UX05 | 本地/SSH/直链媒体加载、失败、重试、类型化 ACP 媒体冷恢复,以及普通网页卡行为正确。 | +| UX04 | 1.6.1 撤销:不再生成折叠外成果摘录,运行中 turn 的流式正文保持自上而下。 | +| UX05 | 本地/SSH/直链媒体加载、失败、重试、类型化 ACP 媒体冷恢复正确;不生成网站卡。 | | UX06 | MCP 连续分组不跨正文/服务,真实父子关系与专用 renderer 保留,手动态不被自动折叠覆盖。 | | UX07 | 单选不自动提交,多题可返回,关闭再开保留草稿,跳过/多端竞争/超时语义正确。 | | UX08 | 子任务成功有摘要,全结束后汇总消失,正在查看的详情和文件 tab 不受影响。 | diff --git a/docs/ui/assistant-preview-cards.md b/docs/ui/assistant-preview-cards.md index 7e0c7a7c33b..e6c4411987e 100644 --- a/docs/ui/assistant-preview-cards.md +++ b/docs/ui/assistant-preview-cards.md @@ -17,10 +17,13 @@ directives such as `::code-comment{...}` remain strict. ## Scope -- Typed assistant media also remains visible outside collapsed work history when a later text summary arrives. Each received media item has one derived view with its original row/id source; media-only rows are valid. A final ordinary website link cannot hide MIME-qualified media. Only already embedded matching media covers that item; partial final coverage keeps the other items visible. The projection preserves original rows, scoped attachment authorization, and final-row actions. Anonymous shares show HTTP source links or attachment labels without automatic media requests or local artifact links. +- Since 1.6.1 no website cards are generated from assistant body URLs (localhost, + public links, closed Markdown links, single-URL `text` fences or bare URL lines), + and no work-history excerpt rows are projected. Body links stay clickable inline; + local HTML file cards, Markdown, Office, PDF and audio/video cards are unchanged. - Preview card file types: Markdown, HTML, DOCX, XLSX, PPTX, PDF, MP4, MOV, WebM, M4V, MP3, WAV, M4A, OGG, Opus, FLAC, and WEBA. -- Every preview card uses a 24 x 24 px leading icon for website, recognized-file, +- Every preview card uses a 24 x 24 px leading icon for recognized-file and fallback-file presentation, inside the existing card icon container. - The file type registry owns extension, subtitle, and opening behavior so another previewable file type can be added without changing the extraction pipeline. @@ -100,18 +103,15 @@ directives such as `::code-comment{...}` remain strict. ## Projection and state boundary -### Work-history deliverable excerpts (UX04) +### Work-history deliverable excerpts (UX04, removed in 1.6.1) -`conversation-presentation` owns the pure extraction contract at -`packages/ui/src/v4/conversation-presentation/index.ts`. It projects already -loaded assistant text, without protocol, media, Host, queue, or persistence facts. -The original row and its copy/fork/retry anchor remain unchanged. A collapsed -work history additionally exposes source excerpts and a button to expand the -original context. Excerpts have no message actions or preview-card auto-open. -Single-URL text fences retain their code block and explanation and additionally -offer an explicit native button through the existing URL-opening callbacks and -browser-routing policy. The complete validated target is passed directly, never -reconstructed as Markdown; keyboard activation has the same behavior as clicking. +Removed by user decision (Q41=A). The excerpt projection copied history paragraphs, +single-URL `text` fences and typed media into extra rows with "Open / View original +context" actions, appended at the end of a running turn's open history. Complete +paragraphs and code blocks therefore appeared below the still-streaming block, and +the excerpts duplicated links already clickable in the body. The flow now renders +only the original rows in order. `conversation-presentation` keeps only the pure +reference extraction used for inline media. Within one MessageResponse scope, streaming body updates keep the Markdown renderer component types stable. An existing Mermaid diagram retains its mounted @@ -119,68 +119,24 @@ instance and last successful SVG while later chunks arrive, including incomplete or invalid Mermaid text. Markdown image, audio, and video leaves retain their DOM identity, playback position, and already loaded resource/Blob URL when unrelated body text or a new text fence arrives; those updates do not reread the same -resource. A newly closed single-URL `text` fence immediately exposes its open -action with the current complete target, including when an earlier fence target -was already present. The renderer reads the current fence target set for each -render, rather than capturing a set from an earlier chunk. +resource. A single-URL `text` fence renders only as a code block; since 1.6.1 no +extra link line is added below it. The existing MessageResponse scope and media reader remain the resource owners: changing the reader, session, workspace path/identity, or remote session releases old temporary URLs, ignores stale reads, and loads through the new scope. Unmount -also releases temporary URLs. The text-fence projection owns only derived targets; -it does not cache media bytes or accept a second write path. +also releases temporary URLs. ```text -assistant body chunk -> MessageResponse props -> current reference/fence projection +assistant body chunk -> MessageResponse props -> current media reference projection -> stable Markdown renderer types -> mounted Mermaid/media leaves -closed fence arrives -> current target lookup -> native open action (complete URL) scope/reader changes or unmount -> leaf cleanup -> revoke old Blob / ignore stale read ``` -Only closed Markdown links/images, standalone HTTP(S) URLs, and closed `text` -fences containing exactly one HTTP(S) URL qualify. Inline code, indented code, -other fences and commands do not qualify. Streaming standalone URLs require a -line ending; incomplete Markdown/fences never qualify. Valid received references -survive failed/interrupted turns. This does not change terminal preview-card -gates, file validation, limits, or the Markdown/HTML fileChanges gate. - -Each reference retains its source row, exact half-open source range, and complete -surrounding paragraph; a standalone URL also retains the immediately preceding -explanation paragraph. Extraction retains every valid source reference; complete -source-context target groups are formed before cross-source deduplication. Targets -already present in the visible final body produce no extra standalone excerpt. A -paragraph containing several references is rendered once. If only some targets -are in the final body, the complete source paragraph remains intact for the new -targets, even when it also contains those previously visible references; when -all targets are covered, the paragraph is omitted. Extraction is memoized by source -row/text/state so work-clock ticks do not parse unchanged history again. - -Overlapping context ranges from the same source row are merged into one exact -source slice, anchored to the first original reference key. Ranges from different -rows never merge. Coverage is evaluated over all merged targets; every uncovered -text-fence target retains a separate native open action keyed by its complete -target. An already covered target gets no additional standalone open action. - -The source/range key describes the actual selected reference. Prepending an older -duplicate may select that source and truthfully change its source key/range. -React identity is separate: it uses the sorted, complete original target group, -fixed before cross-source deduplication or final-body coverage. A duplicate-A -prepend therefore preserves both single-A identity and an existing A/B excerpt's -identity; it cannot silently re-anchor the A/B group to B. Fully covered source -groups are omitted in source order, while partial coverage preserves their full -original text and target-group identity. Neither a mutable representative cache -nor persisted presentation state is introduced. Mounted excerpts additionally use -`workspaceIdentity?.trim() || workspacePath`, remote session, session, log epoch, -and turn scope; file opening reuses the same row context and Host accessor. -The public module entrypoint remains pure so shared readonly timelines cannot -pull runtime services into the public share dependency closure. - -```text -delivered assistant rows -> pure source/range extraction -> collapsed-history excerpt - -> unchanged original work history -> expand original context -existing row context -> selected workspace Host -> existing file/link opening -``` +Media extraction accepts only closed Markdown links/images and standalone HTTP(S) +URLs; inline code, indented code, fences and commands do not qualify. Streaming +standalone URLs require a line ending; incomplete Markdown never qualifies. Preview cards remain a UI-only projection from already delivered V4 rows. The separate UX05 native-media contract adds optional `assistantText.media` references; @@ -190,20 +146,18 @@ The public share timeline explicitly disables automatic media rendering: links p by its existing image sanitization must not become fetched image/audio/video previews. Authenticated readonly conversation views retain their existing scoped media access. -### Delivered media and websites (UX05) +### Delivered media (UX05) -Ordinary HTTP(S) websites use received link titles and the URL domain only. No -page metadata fetch, arbitrary iframe, auto-open or autoplay is permitted. Existing -local HTML/file gates and Host-scoped opening remain unchanged; mobile suppresses -only unsupported localhost/file previews, not ordinary public website links. +Ordinary HTTP(S) and localhost URLs stay inline body links; since 1.6.1 they do +not produce website cards. No page metadata fetch, arbitrary iframe, auto-open or +autoplay is permitted. Existing local HTML file gates and Host-scoped opening remain +unchanged; mobile suppresses HTML file cards. Direct image/audio/video references render with existing image/media controls. Typed MIME metadata permits extensionless media; a URL without known MIME or a -recognized media extension stays a website. Missing/failed media retains its +recognized media extension stays an ordinary link. Missing/failed media retains its original reference, an unavailable state and an explicit retry action. Retrying -only rereads that resource, never reruns the assistant turn. Single-URL closed -`text` fences in final and historical bodies keep the original code and expose -the same safe native open action, so final-body deduplication cannot hide access. -The website-card open button and unavailable-resource retry button remain +only rereads that resource, never reruns the assistant turn. +The card open button and unavailable-resource retry button remain reachable by native Tab navigation and activate with Enter. Their desktop acceptance uses real keyboard input and verifies the resulting browser target or decoded resource, without programmatically focusing the target. @@ -233,7 +187,6 @@ assistantText rows (desktop continuous / mobile replayable hydration) | +-- join assistant text in body order once +-- extract file references once; reuse them for gate + card build - +-- extract localhost candidates +-- fetch this turn's fileChanges with the turnHeader target when md/html is present | +-- running: revision key + in-flight only | +-- terminal: target + active|reverted key + settled success, shared LRU <= 20 entries @@ -325,12 +278,8 @@ instead of path existence booleans. redirects, so business templates cannot replace the preview with `file:///login`. Preview supports source mode. Desktop local files additionally offer an explicit run action in the built-in browser; remote paths are never sent to the local browser. -- Web `/remote` does not project localhost/127.0.0.1 URL cards or HTML - output cards. Without port forwarding or a URL proxy those URLs cannot reach - the Desktop host. Markdown, DOCX, XLSX, PPTX, PDF, and video/audio cards remain available. -- Desktop localhost HTTP cards keep the Browser side-pane behavior. When a URL - maps to a generated HTML file, the backing file must also pass the existence - check. +- Web `/remote` does not project HTML output cards. Without port forwarding or a + URL proxy those files cannot be run against the Desktop host. Markdown, DOCX, XLSX, PPTX, PDF, and video/audio cards remain available. - Desktop local and Desktop remote workspaces support the automatic PPTX open because they expose a right-side Preview Pane. Web `/remote` keeps the cards visible, but does not auto-open when the current surface has no usable right- @@ -340,8 +289,8 @@ instead of path existence booleans. - Desktop stays on the existing `desktop-continuous` message path. - Web remote stays on `web-remote-replayable`; card projection runs only after - row hydration and does not enter gap/snapshot recovery. Unsupported local URL - and HTML candidates are filtered in renderer projection before the 15-card + row hydration and does not enter gap/snapshot recovery. Unsupported HTML + candidates are filtered in renderer projection before the 15-card existence-check window, without adding protocol or Host state. - The `fileChanges` cache is renderer-local query state. It does not add relay, Host, snapshot, or replayable state and does not alter delivery semantics. @@ -364,8 +313,7 @@ new actions; both entry points reuse the same opening handlers. File context menus offer Preview, Open (the system default application), an Open with submenu, then copying relative and absolute paths. The context menu omits Open containing folder and its separator. Chinese labels are 预览 and 打开. -Website cards use the same Preview and Open labels for side-pane and browser -actions, followed by copying the URL; file-backed local HTML additionally offers path actions. +File-backed local HTML cards use the same Preview and Open labels and path actions. The card primary button continues to read Open for all card types. Native file actions require the platform's explicit `canOpenLocalFiles` capability. @@ -390,5 +338,5 @@ primitives, keyboard navigation, light/dark tokens and localized labels. APC14 acceptance: right-click a real Office card, verify its dropdown remains unchanged, assert the compact labels and absence of the directory entry, preview the file, and verify the default-app shell call with a mock. Focused -component tests cover website links, HTML paths, unavailable preview, Web and +component tests cover HTML paths, unavailable preview, Web and remote-native capability exclusion. diff --git a/packages/desktop/test/e2e/conversation-session/conversation-session-assistant-preview-cards.test.ts b/packages/desktop/test/e2e/conversation-session/conversation-session-assistant-preview-cards.test.ts index 3dfefd67b07..7e7a82275fb 100644 --- a/packages/desktop/test/e2e/conversation-session/conversation-session-assistant-preview-cards.test.ts +++ b/packages/desktop/test/e2e/conversation-session/conversation-session-assistant-preview-cards.test.ts @@ -106,7 +106,7 @@ let retryMediaRequestCount = 0; let fixtureVideo: Buffer; let fixtureImage: Buffer; -async function setExcerptPresentation(locale: "zh-CN" | "en-US", theme: "zai-light" | "zai-dark") { +async function setLocaleAndTheme(locale: "zh-CN" | "en-US", theme: "zai-light" | "zai-dark") { const result = await browser.executeAsync( (next, done: (result: string) => void) => { const actions = (window as typeof window & { __testActions?: Record }) @@ -151,37 +151,18 @@ describe("Assistant Preview Cards E2E", () => { await clearAppData(); }); - it("UX05 展示:网页卡、直接及本地媒体、失效重试、最终正文入口", async () => { + it("UX05 展示:直接及本地媒体、失效重试;1.6.1 起无网页卡与 text fence 链接行", async () => { await prepareCase(); await materializeMediaFixtures(); retryMediaAvailable = false; retryMediaRequestCount = 0; - await setExcerptPresentation("zh-CN", "zai-light"); + await setLocaleAndTheme("zh-CN", "zai-light"); const marker = `${CASE_MARKER}_UX05_DISPLAY`; await sendV4Prompt(`${marker} E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`); await waitForCompleted(`${marker}_DONE`); await assertLoadedAssistantMedia(3); - await browser.waitUntil( - async () => - (await readPreviewCards(["UX05 公共网站"])).some((card) => card.title === "UX05 公共网站"), - { timeout: 30_000 }, - ); - const websiteOrigin = await establishKeyboardOrigin(); - const keyboardSteps = { - website: await activateByTabAndEnter( - await browser.$('[data-preview-card-title="UX05 公共网站"] button'), - 64, - true, - websiteOrigin.readCountAfter, - ), - }; - await browser.waitUntil( - async () => - (await browser.$(`[data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`).getValue()) === - "https://example.com/ux05", - { timeout: 10_000 }, - ); - await closeSidePanes(); + // 1.6.1:普通网页链接只保留正文内链接,不再生成网站卡。 + await expectPreviewCardMissing("UX05 公共网站"); const failed = await browser.$( `[data-assistant-media]:has(button[title="${fixtureRootUrl}-retry.wav"])`, ); @@ -206,11 +187,8 @@ describe("Assistant Preview Cards E2E", () => { async () => browser.execute((el) => (el as HTMLImageElement).naturalWidth > 0, image), { timeout: 10_000 }, ); - const fence = await browser.$("[data-assistant-text-fence-link]"); - await fence.scrollIntoView(); - await fence.click(); - await waitForBrowserSurface(`${fixtureRootUrl}-final?next=(step)&x=1`, "APC01_LOCAL_URL_PAGE"); - await closeSidePanes(); + // 1.6.1:单 URL text fence 只渲染代码块,下方不再追加链接行。 + expect(await browser.$("[data-assistant-text-fence-link]").isExisting()).toBe(false); const screenshots = process.env.ZCODE_E2E_RUNTIME_LOG_DIR; if (screenshots) { await browser.saveScreenshot(join(screenshots, "ux05-display-light-zh.png")); @@ -218,9 +196,7 @@ describe("Assistant Preview Cards E2E", () => { join(screenshots, "ux05-display-keyboard.json"), JSON.stringify( { - ...keyboardSteps, retry: retryKeyboard, - websiteOrigin, retryOrigin, retryReadCountAfterEnter, }, @@ -276,28 +252,18 @@ describe("Assistant Preview Cards E2E", () => { await sendV4PromptInPane(paneId, "UX05 验证原生输出媒体"); await waitForCompleted(marker); const sessionId = await waitForBoundSession(marker); - await assertNativeMediaOutsideHistory(); + await assertNativeMediaInHistory(); await assertLoadedAssistantMedia(3); - const sourceButton = await browser.$( - "[data-conversation-deliverable] [data-deliverable-show-source]", - ); - await sourceButton.click(); - expect( - await browser - .$('[data-testid^="chat-assistant-history-trigger-"]') - .getAttribute("data-history-open"), - ).toBe("true"); expect(await browser.$("body").getText()).toContain("UX05 未知资源说明"); - await browser.$('[data-testid^="chat-assistant-history-trigger-"]').click(); await startNewV4Draft(); await selectV4TaskById(sessionId); await waitForCompleted(marker); - await assertNativeMediaOutsideHistory(); + await assertNativeMediaInHistory(); await assertLoadedAssistantMedia(3); await browser.refresh(); await selectV4TaskById(sessionId, 60_000); await waitForCompleted(marker); - await assertNativeMediaOutsideHistory(); + await assertNativeMediaInHistory(); await assertLoadedAssistantMedia(3); const nativeWorkspace = await browser.execute( () => @@ -312,14 +278,14 @@ describe("Assistant Preview Cards E2E", () => { await restartCurrentWorkspacePreservingProfile(nativeWorkspace); await selectV4TaskById(sessionId, 60_000); await waitForCompleted(marker); - await assertNativeMediaOutsideHistory(); + await assertNativeMediaInHistory(); await assertLoadedAssistantMedia(3); const screenshots = process.env.ZCODE_E2E_RUNTIME_LOG_DIR; if (screenshots) await browser.saveScreenshot(join(screenshots, "ux05-native-cold.png")); await assertNativeMediaVirtualized(marker); }).timeout(360_000); - it("UX04: 非最终正文关键入口在已工作折叠外可见,并保留原始上下文", async () => { + it("UX04 撤销(1.6.1):非最终正文入口只在原历史中,不再在已工作折叠外追加摘录", async () => { await browser.waitUntil( async () => (await browser.$('[data-testid="onboarding-page"]').isExisting()) || @@ -328,121 +294,32 @@ describe("Assistant Preview Cards E2E", () => { ); await browser.keys("Escape"); await prepareCase({ yolo: true }); - await setExcerptPresentation("zh-CN", "zai-light"); const marker = `${CASE_MARKER}_WORK_EXCERPT`; await sendV4Prompt( `${marker}: publish the entry before working. E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`, ); await waitForCompleted(`${marker}_DONE`); - const sessionId = await waitForBoundSession(marker); - const excerpt = await browser.$( - `[data-conversation-deliverable]:has(button[title="${fixtureRootUrl}"])`, - ); - await excerpt.waitForDisplayed(); - expect(await excerpt.getText()).toContain("请打开此入口继续操作"); - expect(await excerpt.$(`button[title="${fixtureRootUrl}"]`).isDisplayed()).toBe(true); - expect(await excerpt.$$('[data-testid^="v4-fork"], [data-testid^="v4-retry"]').length).toBe(0); - const sourceKey = await excerpt.getAttribute("data-conversation-deliverable"); + expect(await browser.$("[data-conversation-deliverable]").isExisting()).toBe(false); + expect(await browser.$("[data-deliverable-show-source]").isExisting()).toBe(false); + expect(await browser.$("[data-deliverable-open-link]").isExisting()).toBe(false); const history = await browser.$('[data-testid^="chat-assistant-history-content"]'); expect(await history.isDisplayed()).toBe(false); - const screenshotDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR; - if (screenshotDir) await browser.saveScreenshot(join(screenshotDir, "ux04-collapsed.png")); - await excerpt.$("[data-deliverable-show-source]").click(); + await browser.$('[data-testid^="chat-assistant-history-trigger"]').click(); await history.waitForDisplayed(); expect(await history.getText()).toContain("请打开此入口继续操作"); - expect(await excerpt.getAttribute("data-conversation-deliverable")).toBe(sourceKey); - const trigger = await browser.$('[data-testid^="chat-assistant-history-trigger"]'); - await trigger.click(); - await history.waitForDisplayed({ reverse: true }); - await excerpt.$(`button[title="${fixtureRootUrl}"]`).click(); - await waitForBrowserSurface(fixtureRootUrl, "APC01_LOCAL_URL_PAGE"); - await closeSidePanes(); - const textEntryUrl = `${fixtureRootUrl}-text-entry?next=(step)&label=%E4%B8%AD%E6%96%87%20path&angle=%3Cdone%3E`; - const textEntry = await browser.$("button[data-deliverable-open-link]"); - expect(await textEntry.getAttribute("title")).toBe(textEntryUrl); - await textEntry.scrollIntoView(); - // 真实 Tab 聚焦与 Enter 激活,验证原生按钮可用且完整 URL 没有经过 Markdown 重建。 - await excerpt.$("[data-deliverable-show-source]").click(); - await trigger.click(); - await activateByTabAndEnter(textEntry, 16); - await waitForBrowserSurface(textEntryUrl, "APC01_LOCAL_URL_PAGE"); - await closeSidePanes(); - await startNewV4Draft(); - expect(await browser.$("[data-conversation-deliverable]").isExisting()).toBe(false); - await selectV4TaskById(sessionId); - const restored = await browser.$( - `[data-conversation-deliverable]:has(button[title="${fixtureRootUrl}"])`, - ); - await restored.waitForDisplayed(); - expect(await restored.getAttribute("data-conversation-deliverable")).toBe(sourceKey); - if (screenshotDir) await browser.saveScreenshot(join(screenshotDir, "ux04-restored.png")); - const originalWindow = await setCurrentElectronRendererContentSize(1280, 900); - const minimum = await browser.electron.execute((electron, id) => { - const window = electron.BrowserWindow.fromId(id)!; - const previous = window.getMinimumSize(); - // 仅测试窄屏:Windows 原生最小宽为 481px,暂时下调后验证真实 430px viewport。 - window.setMinimumSize(320, 400); - return previous; - }, originalWindow.windowId); - try { - await setCurrentElectronRendererContentSize(430, 900); - await setExcerptPresentation("en-US", "zai-dark"); - const drawer = await browser.$('[data-testid="workspace-sidebar-drawer-backdrop"]'); - if (await drawer.isDisplayed()) { - // 窄屏标题栏被 drawer 自身拖拽区覆盖,真实点击右侧露出的 backdrop 收起。 - await browser.action("pointer").move({ x: 420, y: 450 }).down().up().perform(); - await drawer.waitForDisplayed({ reverse: true }); - } - await restored.scrollIntoView(); - expect(await restored.$("[data-deliverable-show-source]").getText()).toBe( - "View original context", - ); - const layout = await browser.execute(() => ({ - width: window.innerWidth, - excerpts: Array.from(document.querySelectorAll("[data-conversation-deliverable]")).map( - (node) => { - const rect = node.getBoundingClientRect(); - return { left: rect.left, right: rect.right, width: rect.width }; - }, - ), - })); - if (screenshotDir) { - await browser.saveScreenshot(join(screenshotDir, "ux04-narrow-dark-en.png")); - await writeFile(join(screenshotDir, "ux04-layout.json"), JSON.stringify(layout, null, 2)); - } - // 与精确窗口 helper 相同:Windows 物理像素换算允许 1px 原生舍入,布局仍用实际宽度校验。 - expect(Math.abs(layout.width - 430)).toBeLessThanOrEqual(1); - expect(layout.excerpts).toHaveLength(1); - for (const rect of layout.excerpts) { - expect(rect.width).toBeGreaterThan(0); - expect(rect.left).toBeGreaterThanOrEqual(0); - expect(rect.right).toBeLessThanOrEqual(layout.width + 1); - } - } finally { - await browser.electron.execute( - (electron, id, min) => electron.BrowserWindow.fromId(id)?.setMinimumSize(min[0]!, min[1]!), - originalWindow.windowId, - minimum, - ); - await restoreElectronRendererContentSize(originalWindow); - await setExcerptPresentation("zh-CN", "zai-light"); - } - }).timeout(240_000); + }).timeout(180_000); - it("APC01/APC04: completed localhost URL 去重并打开真实 Browser 页面", async () => { + it("APC01(1.6.1): completed localhost URL 不再生成网站卡", async () => { await prepareCase(); const marker = `${CASE_MARKER}_LOCAL_URL`; await sendV4Prompt( `${marker}: reply with the same local preview URL more than once. E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`, ); await waitForCompleted(`${marker}_DONE`); - - await waitForPreviewCards(["APC Local Preview"]); - await clickPreviewCard("APC Local Preview"); - await waitForBrowserSurface(fixtureRootUrl, "APC01_LOCAL_URL_PAGE"); + expect(await readPreviewCards()).toEqual([]); }).timeout(180_000); - it("APC02: interrupted turn 在 URL 已到达后 Stop,卡片只在终态出现", async () => { + it("APC02(1.6.1): interrupted turn 在 URL 已到达后 Stop,终态也不生成网站卡", async () => { await prepareCase(); const marker = `${CASE_MARKER}_INTERRUPTED`; await sendV4Prompt(`${marker}: keep streaming after publishing ${STREAM_URL}.`); @@ -455,10 +332,10 @@ describe("Assistant Preview Cards E2E", () => { "APC02 Stop 后 turn 没有进入 interrupted 终态", 60_000, ); - await waitForPreviewCards(["assistant-preview-stream"]); + expect(await readPreviewCards()).toEqual([]); }).timeout(180_000); - it("APC03: streaming 期间不显示卡片,complete 后显示", async () => { + it("APC03(1.6.1): streaming 与 complete 后均不为 URL 生成网站卡", async () => { await prepareCase(); const marker = `${CASE_MARKER}_STREAMING`; await sendV4Prompt(`${marker}: stream ${STREAM_URL} before the final marker.`); @@ -466,10 +343,10 @@ describe("Assistant Preview Cards E2E", () => { expect(await readPreviewCards()).toEqual([]); await waitForCompleted(`${marker}_DONE`); - await waitForPreviewCards(["assistant-preview-stream"]); + expect(await readPreviewCards()).toEqual([]); }).timeout(180_000); - it("APC15 FR-I1: 同一流式正文保持 Mermaid/媒体叶子并及时显示完整 text fence 目标", async () => { + it("APC15 FR-I1: 同一流式正文保持 Mermaid/媒体叶子,text fence 闭合后不追加链接行", async () => { await prepareCase(); const marker = `${CASE_MARKER}_RENDERER`; const fixtureId = "assistant-preview-cards-renderer-stream"; @@ -560,27 +437,34 @@ describe("Assistant Preview Cards E2E", () => { ); await releaseControlledReplay(fixtureId); - const action = await browser.$(`[data-assistant-text-fence-link][title="${target}"]`); - await action.waitForDisplayed({ timeout: 30_000 }); + await browser.waitUntil( + async () => + browser.execute( + (expected) => + Array.from(document.querySelectorAll('[data-language="text"]')).some((node) => + (node.textContent ?? "").includes(expected), + ), + target, + ), + { timeout: 30_000, timeoutMsg: "APC15 闭合 text fence 未渲染为代码块" }, + ); + expect(await browser.$("[data-assistant-text-fence-link]").isExisting()).toBe(false); const afterClosed = await readRendererStreamProbe(); expect(afterClosed).toEqual( expect.objectContaining({ diagram: true, image: true, audio: true, video: true, svg: true }), ); - await action.click(); - await waitForBrowserSurface(target, "APC01_LOCAL_URL_PAGE"); - const afterClick = await readRendererStreamProbe(); const evidenceDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR; if (evidenceDir) { await browser.saveScreenshot(join(evidenceDir, "apc15-renderer-stream.png")); await writeFile( join(evidenceDir, "apc15-renderer-stream.json"), - JSON.stringify({ initial, afterPartial, afterClosed, afterClick }, null, 2), + JSON.stringify({ initial, afterPartial, afterClosed }, null, 2), ); } await waitForCompleted(`${marker}_DONE`); }).timeout(180_000); - it("APC04: localhost 与本轮 HTML 同时出现时按现有业务规则抑制 HTML", async () => { + it("APC04(1.6.1): localhost 与本轮 HTML 同时出现时只显示 HTML 文件卡", async () => { await prepareCase({ yolo: true }); const marker = `${CASE_MARKER}_LOCAL_SUPPRESSES_HTML`; await sendV4Prompt( @@ -588,8 +472,8 @@ describe("Assistant Preview Cards E2E", () => { ); await waitForCompleted(`${marker}_DONE`); - await waitForPreviewCards(["APC Local Only"]); - await expectPreviewCardMissing(basename(SOURCE_HTML_RELATIVE_PATH)); + await waitForPreviewCards([basename(SOURCE_HTML_RELATIVE_PATH)]); + await expectPreviewCardMissing("APC Local Only"); }).timeout(180_000); it("APC06/APC07: source gate、Office 自动打开 PPTX", async () => { @@ -806,8 +690,6 @@ async function readRendererStreamProbe() { const image = document.querySelector('img[alt="FRI1 图片"]'); const audio = document.querySelector('[data-assistant-media="audio"] audio'); const video = document.querySelector('[data-assistant-media="video"] video'); - const action = document.querySelector("[data-assistant-text-fence-link]"); - const rect = action?.getBoundingClientRect(); return { diagram: diagram === probe.diagram, svg: diagram?.innerHTML === probe.svg, @@ -817,9 +699,6 @@ async function readRendererStreamProbe() { imageWidth: image?.naturalWidth ?? 0, audioReadyState: audio?.readyState ?? 0, videoReadyState: video?.readyState ?? 0, - actionRect: rect - ? { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom } - : null, viewportWidth: window.innerWidth, viewportHeight: window.innerHeight, }; @@ -957,13 +836,17 @@ async function assertLoadedAssistantMedia(count: number) { expect(controls).toBe(true); } -async function assertNativeMediaOutsideHistory() { +// 1.6.1 移除成果摘录后,历史中的类型化媒体随原历史展开查看,不再常显在折叠外。 +async function assertNativeMediaInHistory() { const trigger = await browser.$('[data-testid^="chat-assistant-history-trigger-"]'); - expect(await trigger.getAttribute("data-history-open")).toBe("false"); - expect(await browser.$$("[data-conversation-deliverable] [data-assistant-media]")).toHaveLength( - 3, + if ((await trigger.getAttribute("data-history-open")) === "false") await trigger.click(); + await browser.waitUntil( + async () => (await trigger.getAttribute("data-history-open")) === "true", + { timeout: 10_000 }, ); - const image = await browser.$("[data-conversation-deliverable] img[data-markdown-image]"); + expect(await browser.$$("[data-conversation-deliverable]")).toHaveLength(0); + expect(await browser.$$("[data-assistant-media]")).toHaveLength(3); + const image = await browser.$("img[data-markdown-image]"); await image.waitForExist(); await image.scrollIntoView(); await browser.waitUntil( @@ -978,9 +861,7 @@ async function assertNativeMediaVirtualized(marker: string) { if (!paneId) throw new Error("缺少虚拟滚动验证的当前 pane"); const turnId = await browser.execute(() => { const turn = document.querySelector('[data-v4-turn-unit="true"]'); - const image = turn?.querySelector( - "[data-conversation-deliverable] img[data-markdown-image]", - ); + const image = turn?.querySelector("img[data-markdown-image]"); const media = Array.from( turn?.querySelectorAll( "[data-assistant-media] audio, [data-assistant-media] video", @@ -1055,15 +936,26 @@ async function assertNativeMediaVirtualized(marker: string) { expect(unmounted.mountedRenderUnitCount).toBeLessThan(historyTurns); expect(unmounted.scrollHeight).toBeGreaterThan(unmounted.clientHeight * 2); await scrollV4TimelineToTop(paneId); + // 历史展开态是 turn 内局部状态,虚拟滚动重挂后回到折叠,需重新展开才挂载媒体叶子。 + await browser.waitUntil( + async () => + browser.execute((id) => { + const trigger = Array.from(document.querySelectorAll('[data-v4-turn-unit="true"]')) + .find((node) => node.getAttribute("data-turn-id") === id) + ?.querySelector('[data-testid^="chat-assistant-history-trigger-"]'); + if (!trigger) return false; + if (trigger.getAttribute("data-history-open") === "false") trigger.click(); + return trigger.getAttribute("data-history-open") === "true"; + }, turnId), + { timeout: 15_000, timeoutMsg: "首轮重挂后无法展开原历史" }, + ); await browser.waitUntil( async () => browser.execute((id) => { const turn = Array.from(document.querySelectorAll('[data-v4-turn-unit="true"]')).find( (node) => node.getAttribute("data-turn-id") === id, ); - const image = turn?.querySelector( - "[data-conversation-deliverable] img[data-markdown-image]", - ); + const image = turn?.querySelector("img[data-markdown-image]"); const media = Array.from( turn?.querySelectorAll( "[data-assistant-media] audio, [data-assistant-media] video", @@ -1083,9 +975,7 @@ async function assertNativeMediaVirtualized(marker: string) { const turn = Array.from(document.querySelectorAll('[data-v4-turn-unit="true"]')).find( (node) => node.getAttribute("data-turn-id") === id, )!; - const image = turn.querySelector( - "[data-conversation-deliverable] img[data-markdown-image]", - )!; + const image = turn.querySelector("img[data-markdown-image]")!; const media = Array.from( turn.querySelectorAll( "[data-assistant-media] audio, [data-assistant-media] video", @@ -1124,7 +1014,7 @@ async function assertNativeMediaVirtualized(marker: string) { (node) => node.ready > 0 && node.controls && !node.autoplay && node.paused, ), ).toBe(true); - expect(remounted.historyOpen).toBe("false"); + expect(remounted.historyOpen).toBe("true"); const screenshots = process.env.ZCODE_E2E_RUNTIME_LOG_DIR; if (screenshots) { await browser.saveScreenshot(join(screenshots, "ux05-native-virtual-remount.png")); @@ -1150,7 +1040,7 @@ async function assertNarrowMediaLayout() { }, previous.windowId); try { await setCurrentElectronRendererContentSize(430, 900); - await setExcerptPresentation("en-US", "zai-dark"); + await setLocaleAndTheme("en-US", "zai-dark"); const drawer = await browser.$('[data-testid="workspace-sidebar-drawer-backdrop"]'); if (await drawer.isDisplayed()) { await browser.action("pointer").move({ x: 420, y: 450 }).down().up().perform(); @@ -1180,7 +1070,7 @@ async function assertNarrowMediaLayout() { minimum, ); await restoreElectronRendererContentSize(previous); - await setExcerptPresentation("zh-CN", "zai-light"); + await setLocaleAndTheme("zh-CN", "zai-light"); } } From b446b0e85e8b23ad6fcbe31c100dc683b0256175 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:21:20 -0600 Subject: [PATCH 8/9] fix(ui): keep reasoning body indentation and skip formatting while collapsed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 审查发现:trim() 会去掉思考首行缩进;正文未挂载时每个流式 chunk 仍做整段格式化。 Co-Authored-By: Claude Opus 5.5 --- .../src/components/ai-elements/reasoning.tsx | 18 ++++++++++++------ packages/ui/test/reasoningLayout.test.ts | 4 ++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/ui/src/components/ai-elements/reasoning.tsx b/packages/ui/src/components/ai-elements/reasoning.tsx index 6ecf3f9517f..d009b09fa80 100644 --- a/packages/ui/src/components/ai-elements/reasoning.tsx +++ b/packages/ui/src/components/ai-elements/reasoning.tsx @@ -285,10 +285,14 @@ export function resolveReasoningStreamingSummary( * 把 3 个以上换行折叠成一个空行,不改存储数据。 */ export function formatReasoningBody(text: string): string { - return text - .replace(/\r\n?/gu, "\n") - .trim() - .replace(/\n[ \t]*(?:\n[ \t]*){2,}/gu, "\n\n"); + return ( + text + .replace(/\r\n?/gu, "\n") + // 只去首尾空白行和末尾空白,保留首行缩进(思考可能以缩进代码或列表开头)。 + .replace(/^(?:[ \t]*\n)+/u, "") + .trimEnd() + .replace(/\n[ \t]*(?:\n[ \t]*){2,}/gu, "\n\n") + ); } const REASONING_SUMMARY_MASK = @@ -447,8 +451,10 @@ export const ReasoningContent = memo( const shouldRenderChildren = isOpen || shouldRenderContent || Boolean(forceMount); // split 的捕获组落在奇数位:整行 **标题** 去星号后轻量加粗,其余保持纯文本。 const bodyParts = useMemo( - () => formatReasoningBody(children).split(REASONING_TITLE_LINES), - [children], + // 收起时正文不挂载,跳过每个流式 chunk 上的整段格式化。 + () => + shouldRenderChildren ? formatReasoningBody(children).split(REASONING_TITLE_LINES) : [], + [children, shouldRenderChildren], ); const scrollRef = useRef(null); const contentRef = useRef(null); diff --git a/packages/ui/test/reasoningLayout.test.ts b/packages/ui/test/reasoningLayout.test.ts index 44283950cd8..1d6c6a8ef9d 100644 --- a/packages/ui/test/reasoningLayout.test.ts +++ b/packages/ui/test/reasoningLayout.test.ts @@ -193,6 +193,10 @@ describe("Reasoning layout", () => { expect(completed.indexOf("定位根因")).toBeLessThan(completed.indexOf("持续了 5 秒")); }); + it("keeps first-line indentation while dropping leading blank lines", () => { + expect(formatReasoningBody("\n\n - 缩进列表\n")).toBe(" - 缩进列表"); + }); + it("trims and collapses blank lines in the expanded body", () => { expect(formatReasoningBody("\n\n**标题**\n\n\n\n正文\n \n\n下一段\n\n")).toBe( "**标题**\n\n正文\n\n下一段", From 648da97eb7cde402453fd5e9d450f517179f8760 Mon Sep 17 00:00:00 2001 From: OpenX <136779645+OpenX123@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:21:21 -0600 Subject: [PATCH 9/9] chore(release): 1.6.1 Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d0dc86ffb26..8f7578d97c3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "zcode", - "version": "1.6.0", + "version": "1.6.1", "private": true, "license": "Apache-2.0", "type": "module",