From c29e1b700433259b3d1d358d7383d5e45833074d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=B0=E5=B0=BC=E9=BE=9F?= <3098584968@qq.com> Date: Thu, 26 Nov 2026 13:54:46 +0800 Subject: [PATCH] fix(sharing): preserve artifact link queries and fragments (#8626) * fix(sharing): preserve artifact link queries and fragments * fix(readability): preserve links in fallback without source URL * fix(readability): distinguish document wrappers from SVG titles * fix(sharing): preserve copied inline image URL suffixes * fix(sharing): isolate link queries and parse fallback bodies --------- Co-authored-by: Willem Jiang --- README.md | 2 +- .../harness/deerflow/utils/readability.py | 12 ++-- .../tests/test_web_fetch_relative_links.py | 11 ++++ docs/guide/sharing.md | 6 ++ docs/guide/skills-and-tools.md | 4 +- .../src/components/shares/share-markdown.tsx | 12 ++-- frontend/src/core/shares/links.ts | 33 ++++++++++- frontend/tests/e2e/share-snapshot.spec.ts | 25 +++++++- frontend/tests/unit/core/shares.dom.test.ts | 58 +++++++++++++++++++ 9 files changed, 141 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 237d96f72d..7b08db89c7 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ DeerFlow is model-agnostic — it works with any LLM that implements the OpenAI- - [Install.md](Install.md) - Setup instructions written for coding agents - [Configuration Reference](backend/docs/CONFIGURATION.md) - Every `config.yaml` option - [Backend Architecture](backend/README.md) - Backend architecture and API reference -- [Conversation Sharing](docs/guide/sharing.md) - Expiring read-only snapshots, artifact previews and workspace copies +- [Conversation Sharing](docs/guide/sharing.md) - Expiring snapshots, file links and previews, and workspace copies - [Architecture Overview](docs/ARCHITECTURE.md) - How the services fit together - [Contributing Guide](CONTRIBUTING.md) - Development environment, workflow and tests - [Changelog](CHANGELOG.md) - Release notes diff --git a/backend/packages/harness/deerflow/utils/readability.py b/backend/packages/harness/deerflow/utils/readability.py index 6c134e6089..2debcbd1e5 100644 --- a/backend/packages/harness/deerflow/utils/readability.py +++ b/backend/packages/harness/deerflow/utils/readability.py @@ -101,7 +101,6 @@ class Article: _BASE_TAG_RE = re.compile(r"]*>(.*)", re.DOTALL | re.IGNORECASE) def _has_document_wrapper(content: str) -> bool: @@ -236,15 +235,12 @@ class ReadabilityExtractor: if not html_content or not str(html_content).strip(): html_content = "No content could be extracted from this page" - # Detect whole-document extraction results through explicit document - # wrappers; an extracted chart can legitimately contain an SVG title. - # When detected, use the resolved - # HTML's content so that destinations survive. Apply the - # same fallback without a source URL, preserving relative destinations. + # A whole-document result needs the source body to retain link markup. + # Parse it as HTML so body-like text in the head cannot select the start. if html and _has_document_wrapper(html_content): logger.info("Readability extraction returned the unextracted document; using HTML body") - body_match = _BODY_INNER_RE.search(html) - html_content = body_match.group(1) if body_match else html + body = BeautifulSoup(html, "html5lib").body + html_content = body.decode_contents() if body is not None else html title = article.get("title") if not title or not str(title).strip(): diff --git a/backend/tests/test_web_fetch_relative_links.py b/backend/tests/test_web_fetch_relative_links.py index d65da830e8..89c34f37c9 100644 --- a/backend/tests/test_web_fetch_relative_links.py +++ b/backend/tests/test_web_fetch_relative_links.py @@ -73,6 +73,17 @@ def test_extract_article_without_url_preserves_legacy_relative_links(monkeypatch assert "[Next](../next)" in article.to_markdown() +@pytest.mark.parametrize("url", [None, PAGE_URL]) +@pytest.mark.parametrize("head", ['', ""]) +def test_python_fallback_uses_document_body_and_ignores_head_examples(monkeypatch, url, head): + monkeypatch.setattr("deerflow.utils.readability._readability_js_available", lambda: False) + article = ReadabilityExtractor().extract_article(_article('Next', head=head), url=url) + markdown = article.to_markdown() + assert "Sample body" not in markdown + assert markdown.count("Guide") == 1 + assert f"[Next]({urljoin(url or '', '../next')})" in markdown + + @pytest.mark.parametrize( ("base", "expected"), [ diff --git a/docs/guide/sharing.md b/docs/guide/sharing.md index e34270f3ce..556ad9689a 100644 --- a/docs/guide/sharing.md +++ b/docs/guide/sharing.md @@ -24,6 +24,12 @@ for download. Text previews show at most 512 KiB. HTML scripts, forms and networ requests are blocked. The page rechecks availability on return and every 30 seconds while visible. +Links and inline images for copied output files retain queries and fragments +such as `report.pdf#page=3` or `charts.svg#detail`. The file must appear in the +snapshot's artifact manifest. DeerFlow drops the reserved `download` parameter +from copied links and images so they can open inline. Use the snapshot's +download action to save the file. External images remain blocked. + ![A public read-only conversation snapshot](assets/sharing/share-preview.png) Choose **Continue in my workspace** to create an independent conversation with diff --git a/docs/guide/skills-and-tools.md b/docs/guide/skills-and-tools.md index e22f1a996c..ddbe46889b 100644 --- a/docs/guide/skills-and-tools.md +++ b/docs/guide/skills-and-tools.md @@ -510,8 +510,8 @@ repeatedly starting a missing toolchain. A non-zero extraction exit falls back only for that document, because malformed or oversized input can fail while the toolchain remains healthy. The fallback keeps resolved article links in the returned Markdown. -When extraction returns a whole document, the fallback uses the source HTML -body consistently with or without a source URL. Calls without a source URL +When extraction returns a whole document, the fallback parses the source HTML +and uses its body with or without a source URL. Calls without a source URL retain relative link destinations and do not repeat the document title. Only explicit document-level wrappers trigger that fallback. An inline SVG chart's title or a document-tag example in a comment or script leaves the diff --git a/frontend/src/components/shares/share-markdown.tsx b/frontend/src/components/shares/share-markdown.tsx index 05f7e93e69..5eee342872 100644 --- a/frontend/src/components/shares/share-markdown.tsx +++ b/frontend/src/components/shares/share-markdown.tsx @@ -3,8 +3,8 @@ import { useMemo } from "react"; import { visit } from "unist-util-visit"; -import { shareArtifactURL, type SharedArtifact } from "@/core/shares/api"; -import { resolveShareArtifact, sharedLink } from "@/core/shares/links"; +import { type SharedArtifact } from "@/core/shares/api"; +import { sharedArtifactLink, sharedLink } from "@/core/shares/links"; import { SafeMessageResponse, streamdownPluginsWithoutRawHtml, @@ -62,14 +62,14 @@ export function ShareMarkdown({ ); }, img: ({ src, alt }) => { - const artifact = + const target = typeof src === "string" - ? resolveShareArtifact(src, artifacts, basePath) + ? sharedArtifactLink(src, token, artifacts, basePath) : undefined; // Do not load third-party tracking images or live private file endpoints. - return artifact ? ( + return target ? ( {alt artifact.path === normalized.join("/")); } -export function sharedLink( +/** Build an inline URL only for a file in the snapshot manifest. */ +export function sharedArtifactLink( href: string, token: string, artifacts: SharedArtifact[], basePath = "", ) { const artifact = resolveShareArtifact(href, artifacts, basePath); - if (artifact) return shareArtifactURL(token, artifact.path); + if (!artifact) return undefined; + + const [, query = "", fragment = ""] = + /^[^?#]*(\?[^#]*)?(#[\s\S]*)?$/.exec(href) ?? []; + // The Gateway reserves `download` for its explicit download action. Keep + // other query entries in their original encoding and leave fragments intact. + const inlineQuery = query + .slice(1) + .split("&") + .filter((part) => !new URLSearchParams(`?${part}`).has("download")) + .join("&"); + return ( + shareArtifactURL(token, artifact.path) + + (inlineQuery ? `?${inlineQuery}` : "") + + fragment + ); +} + +export function sharedLink( + href: string, + token: string, + artifacts: SharedArtifact[], + basePath = "", +) { + const copied = sharedArtifactLink(href, token, artifacts, basePath); + if (copied) return copied; try { const url = new URL(href); if ( diff --git a/frontend/tests/e2e/share-snapshot.spec.ts b/frontend/tests/e2e/share-snapshot.spec.ts index adc43103b6..fee6c01ba2 100644 --- a/frontend/tests/e2e/share-snapshot.spec.ts +++ b/frontend/tests/e2e/share-snapshot.spec.ts @@ -20,11 +20,17 @@ const snapshot = { id: "answer", type: "ai", content: - "Revenue rose. [Report](sandbox:/mnt/user-data/outputs/report.html) ![tracking](https://tracker.invalid/pixel) [private](/workspace/chats/secret)", + "Revenue rose. [Report](sandbox:/mnt/user-data/outputs/report.html?download=summary#summary) ![detail](sandbox:/mnt/user-data/outputs/charts.svg?v=2&download=1#detail) ![tracking](https://tracker.invalid/pixel) [private](/workspace/chats/secret)", }, { id: "tool", type: "tool", name: "python", content: "Revenue: 42" }, ], artifacts: [ + { + path: "charts.svg", + mime_type: "image/svg+xml", + size: 100, + sha256: "c".repeat(64), + }, { path: "report.html", mime_type: "text/html", @@ -72,6 +78,12 @@ test("anonymous snapshot previews files without entering the private workspace", : "

Frozen report

", }), ); + await page.route(`**/api/shares/${token}/artifacts/charts.svg*`, (route) => + route.fulfill({ + contentType: "image/svg+xml", + body: '', + }), + ); await page.goto(`/share/${token}`); await expect( page.getByRole("heading", { name: "Quarterly report" }), @@ -80,12 +92,21 @@ test("anonymous snapshot previews files without entering the private workspace", page.getByText("Read-only snapshot", { exact: true }), ).toBeVisible(); await expect(page.locator("textarea, [contenteditable=true]")).toHaveCount(0); + await expect( + page.getByRole("img", { name: "detail", exact: true }), + ).toHaveAttribute( + "src", + `/api/shares/${token}/artifacts/charts.svg?v=2#detail`, + ); await expect( page.getByRole("link", { name: "private", exact: true }), ).toHaveCount(0); await expect( page.getByRole("link", { name: "Report", exact: true }), - ).toHaveAttribute("href", `/api/shares/${token}/artifacts/report.html`); + ).toHaveAttribute( + "href", + `/api/shares/${token}/artifacts/report.html#summary`, + ); await page.getByRole("button", { name: "report.html", exact: true }).click(); await expect(page.locator("iframe")).toHaveAttribute("sandbox", ""); await expect( diff --git a/frontend/tests/unit/core/shares.dom.test.ts b/frontend/tests/unit/core/shares.dom.test.ts index 68b5db10ed..1ba927223d 100644 --- a/frontend/tests/unit/core/shares.dom.test.ts +++ b/frontend/tests/unit/core/shares.dom.test.ts @@ -1,5 +1,8 @@ import { afterEach, describe, expect, it, rs } from "@rstest/core"; +import { cleanup, render, screen } from "@testing-library/react"; +import { createElement } from "react"; +import { ShareMarkdown } from "@/components/shares/share-markdown"; import { forkShare, readShare, shareArtifactURL } from "@/core/shares/api"; import { resolveShareArtifact, sharedLink } from "@/core/shares/links"; @@ -11,10 +14,65 @@ const artifact = { }; const token = "x".repeat(43); afterEach(() => { + cleanup(); rs.restoreAllMocks(); }); describe("share boundaries", () => { + it("keeps image URL suffixes while refusing external and private images", async () => { + render( + createElement(ShareMarkdown, { + token, + artifacts: [artifact], + content: + "![detail](sandbox:/mnt/user-data/outputs/charts/a%20b.svg?v=2&download=summary#detail) ![tracking](https://tracker.example/pixel.svg) ![private](/api/threads/private/artifacts/a.svg) ![missing](missing.svg)", + }), + ); + expect((await screen.findByAltText("detail")).getAttribute("src")).toBe( + shareArtifactURL(token, artifact.path) + "?v=2#detail", + ); + expect(screen.queryAllByRole("img")).toHaveLength(1); + }); + + it.each([ + ["?download=summary#detail", "#detail"], + ["?download=1", ""], + [ + "?v=a%20b&%64ownload=1&download=false&v=%2f#detail?download=1", + "?v=a%20b&v=%2f#detail?download=1", + ], + ["?label=download%3D1#detail", "?label=download%3D1#detail"], + ])( + "keeps copied link queries separate from download controls (%s)", + (query, suffix) => { + expect(sharedLink(`charts/a%20b.svg${query}`, token, [artifact])).toBe( + shareArtifactURL(token, artifact.path) + suffix, + ); + }, + ); + + it("resolves URL suffixes separately from encoded filename punctuation", () => { + const punctuated = { ...artifact, path: "charts/a#b?.svg" }; + for (const suffix of ["#page=3", "?v=2", "?v=2#section"]) { + const href = `charts/a%20b.svg${suffix}`; + expect(resolveShareArtifact(href, [artifact])).toEqual(artifact); + expect(sharedLink(href, token, [artifact])).toBe( + shareArtifactURL(token, artifact.path) + suffix, + ); + } + expect( + resolveShareArtifact("charts/a%23b%3F.svg#section", [punctuated]), + ).toEqual(punctuated); + expect( + resolveShareArtifact("../../private.svg#section", [artifact]), + ).toBeUndefined(); + expect( + resolveShareArtifact("/api/threads/private/artifacts/a.svg#section", [ + artifact, + ]), + ).toBeUndefined(); + }); + it("only resolves copied outputs, including relative markdown references", () => { expect( resolveShareArtifact("sandbox:/mnt/user-data/outputs/charts/a%20b.svg", [