mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
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 <willem.jiang@gmail.com>
This commit is contained in:
parent
8436b9b015
commit
c29e1b7004
@ -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
|
||||
|
||||
@ -101,7 +101,6 @@ class Article:
|
||||
|
||||
_BASE_TAG_RE = re.compile(r"<base", re.IGNORECASE)
|
||||
_DOCUMENT_WRAPPER_RE = re.compile(r"<(?:html|head|body)\b", re.IGNORECASE)
|
||||
_BODY_INNER_RE = re.compile(r"<body[^>]*>(.*)</body>", 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 <body> content so that <a> 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():
|
||||
|
||||
@ -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", ['<script>const example = "<body>Sample body";</script>', "<!-- <body>Sample body -->"])
|
||||
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('<a href="../next">Next</a>', 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"),
|
||||
[
|
||||
|
||||
@ -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.
|
||||
|
||||

|
||||
|
||||
Choose **Continue in my workspace** to create an independent conversation with
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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 ? (
|
||||
<img
|
||||
src={shareArtifactURL(token, artifact.path)}
|
||||
src={target}
|
||||
alt={alt ?? ""}
|
||||
referrerPolicy="no-referrer"
|
||||
className="max-w-full"
|
||||
|
||||
@ -6,7 +6,8 @@ export function resolveShareArtifact(
|
||||
artifacts: SharedArtifact[],
|
||||
basePath = "",
|
||||
) {
|
||||
let path = href.replace(/^sandbox:/, "");
|
||||
// Split URL syntax before decoding: %23 and %3F are filename characters.
|
||||
let path = href.split(/[?#]/, 1)[0]!.replace(/^sandbox:/, "");
|
||||
try {
|
||||
path = decodeURIComponent(path);
|
||||
} catch {
|
||||
@ -31,14 +32,40 @@ export function resolveShareArtifact(
|
||||
return artifacts.find((artifact) => 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 (
|
||||
|
||||
@ -20,11 +20,17 @@ const snapshot = {
|
||||
id: "answer",
|
||||
type: "ai",
|
||||
content:
|
||||
"Revenue rose. [Report](sandbox:/mnt/user-data/outputs/report.html)  [private](/workspace/chats/secret)",
|
||||
"Revenue rose. [Report](sandbox:/mnt/user-data/outputs/report.html?download=summary#summary)   [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",
|
||||
: "<h1>Frozen report</h1><script>parent.document.body.innerHTML='unsafe'</script>",
|
||||
}),
|
||||
);
|
||||
await page.route(`**/api/shares/${token}/artifacts/charts.svg*`, (route) =>
|
||||
route.fulfill({
|
||||
contentType: "image/svg+xml",
|
||||
body: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><view id="detail" viewBox="0 0 5 5"/><rect width="10" height="10"/></svg>',
|
||||
}),
|
||||
);
|
||||
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(
|
||||
|
||||
@ -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:
|
||||
"   ",
|
||||
}),
|
||||
);
|
||||
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", [
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user