deer-flow/frontend/tests/e2e/artifact-viewer-window.spec.ts
Nan Gao 73e3699347
feat(frontend): render markdown artifacts in the "open in new window" view (#5056)
* feat(frontend): render markdown artifacts in the new window

The artifacts panel's "open in new window" action handed the browser the
raw Gateway response. For markdown that is a `text/markdown` body the
browser can only show as source, so the new window was a text dump rather
than a reader.

Route markdown artifacts to a new `/artifacts/view` page that renders them
with the same components the panel uses (SafeStreamdown + the artifact
rehype chain + citation links/panel), including the truncated-preview
banner and its "load full file" action. Everything else keeps the raw
Gateway URL — notably HTML/SVG, which the Gateway deliberately serves as a
download so active content never executes in the application origin.

- `core/artifacts/viewer.ts` centralizes which stored artifacts are
  markdown (`.skill` archives included, since they hold a SKILL.md), so
  the panel and the viewer route cannot drift.
- `ArtifactFilePreview` and its siblings move out of
  `artifact-file-detail.tsx` into `artifact-file-preview.tsx`; otherwise
  the standalone route would pull the CodeMirror editor into its bundle.
- The window title comes from the route's `generateMetadata`, not
  `document.title`, which the App Router overwrites after hydration.
- The viewer reads content through `useStandaloneArtifactContent`, which
  shares `useArtifactContent`'s query key but not its `useThread`
  dependency, since a detached window has no thread context.

Claude-Session: https://claude.ai/code/session_013AiCrC5SBc3HdFYNxsp1EC

* fix(frontend): keep the artifact target across re-authentication

Review found the standalone viewer unrecoverable from an expired session.
The window's target lives entirely in `?path=...&thread_id=...`, and both
auth paths dropped it:

- The layout guard redirected to `/login` with no `next` at all. A layout
  cannot read `searchParams`, so the guard moves into the page, which can
  — and rebuilds the full viewer address for `next`. The layout loses its
  AuthProvider along the way: nothing under this route reads `useAuth`,
  and the guard now makes a single `getServerSideUser` call per request.
- The shared fetch wrapper built `next` from `window.location.pathname`,
  which silently truncated the query string. It now carries `search` too,
  so any route holding state in the query survives a 401, not just this
  one. `validateAuthNextPath` already accepts a query string.

`buildArtifactViewerURL` is split out of `resolveArtifactOpenURL`: the
guard needs the route itself, never the Gateway fallback that the latter
takes for non-markdown targets.

Tests: the login round trip (unit — the rebuilt URL survives
`validateAuthNextPath` and parses back to the same target), the fetch
wrapper preserving the query on 401 (unit), and the expired-session
window reaching `/login` with the artifact intact (E2E). The E2E asserts
on the popup's navigation *requests*, since `(auth)/layout` answers
`/login` with a server redirect under DEER_FLOW_AUTH_DISABLED and no
navigation commits.

`tests/unit/core/models/api.test.ts` stubbed `window.location` without
`search`; a real Location always has it.

Claude-Session: https://claude.ai/code/session_013AiCrC5SBc3HdFYNxsp1EC

* fix(frontend): keep public showcase artifacts out of the auth gate

Review found that the viewer's access check regressed `/showcase`. Those
pages render with `isMock`, their artifacts are served by the
unauthenticated demo route, and the raw artifact URL this window replaced
stayed public — so gating the window unconditionally bounced every
logged-out showcase visitor to /login for a document that is already
public.

`requiresAuthenticatedViewer` exempts a mock target only when
`resolveStaticDemoArtifact` would actually serve it. The allowlist is the
authority rather than the flag: `mock=true` is caller-supplied, so a
target the demo route answers with 404 — a non-allowlisted path, or a
thread that is not a demo thread — still needs a session.

Covered in `tests/e2e-auth/`, since the default E2E config disables auth
and cannot see this: a public showcase artifact renders without a
session, while a non-allowlisted path and a missing mock flag both land
on /login. Verified the positive case goes red without the exemption.

Claude-Session: https://claude.ai/code/session_013AiCrC5SBc3HdFYNxsp1EC
2026-08-29 11:07:16 +08:00

258 lines
8.8 KiB
TypeScript

import { expect, test, type Page } from "@playwright/test";
import { mockLangGraphAPI } from "./utils/mock-api";
/**
* Thread endpoints the workspace shell polls that `mockLangGraphAPI` does not
* cover. Left unmocked they reach a real Gateway when one happens to be
* running locally, and its 401 bounces the page to /login before the artifact
* panel ever opens. Answer with the same 5xx a missing backend produces, which
* these panels already tolerate.
*/
async function stubUnmockedThreadEndpoints(page: Page, threadId: string) {
for (const suffix of ["token-usage", "mcp-tasks**"]) {
await page.route(`**/api/threads/${threadId}/${suffix}`, (route) =>
route.fulfill({
status: 500,
contentType: "application/json",
body: "{}",
}),
);
}
}
const MARKDOWN_ARTIFACT_PATH = "/mnt/user-data/outputs/presented-report.md";
const HTML_ARTIFACT_PATH = "/mnt/user-data/outputs/presented-report.html";
const MARKDOWN_THREAD_ID = "00000000-0000-0000-0000-000000003130";
const HTML_THREAD_ID = "00000000-0000-0000-0000-000000003131";
const EXPIRED_THREAD_ID = "00000000-0000-0000-0000-000000003132";
const ARTIFACT_VIEWER_PATH = "/artifacts/view";
function presentFilesMessages(path: string) {
return [
{
type: "human",
id: "msg-human-present-file",
content: [{ type: "text", text: "Create a report" }],
},
{
type: "ai",
id: "msg-ai-present-file",
content: "The report has been written. Now let me present the file.",
tool_calls: [
{
id: "present-file-artifact",
name: "present_files",
args: { filepaths: [path] },
},
],
},
];
}
test.describe("Artifact viewer window", () => {
test("renders a markdown artifact instead of its source in the new window", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: MARKDOWN_THREAD_ID,
title: "Markdown artifact viewer window",
messages: presentFilesMessages(MARKDOWN_ARTIFACT_PATH),
artifacts: [MARKDOWN_ARTIFACT_PATH],
},
],
});
await stubUnmockedThreadEndpoints(page, MARKDOWN_THREAD_ID);
// Registered on the context, not the page: the detached viewer window
// fetches the same artifact and page routes do not reach it.
await page
.context()
.route(
`**/api/threads/${MARKDOWN_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.md`,
(route) =>
route.fulfill({
status: 200,
contentType: "text/markdown",
body: "# Quarterly Report\n\n测试内容 1\n",
}),
);
await page.goto(`/workspace/chats/${MARKDOWN_THREAD_ID}`);
await expect(page.getByText("presented-report.md")).toBeVisible({
timeout: 15_000,
});
await page.getByText("presented-report.md").first().click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("Quarterly Report")).toBeVisible();
const viewerPromise = page.context().waitForEvent("page");
await artifactsPanel
.getByRole("button", { name: "Open in new window" })
.click();
const viewer = await viewerPromise;
await viewer.waitForLoadState("domcontentloaded");
await expect
.poll(() => new URL(viewer.url()).pathname)
.toBe("/artifacts/view");
const params = new URL(viewer.url()).searchParams;
expect(params.get("path")).toBe(MARKDOWN_ARTIFACT_PATH);
expect(params.get("thread_id")).toBe(MARKDOWN_THREAD_ID);
await expect(
viewer.getByRole("heading", { name: "Quarterly Report" }),
).toBeVisible({ timeout: 15_000 });
await expect(viewer.getByText("测试内容 1")).toBeVisible();
// The raw markdown source must not be what the window shows.
await expect(viewer.getByText("# Quarterly Report")).toHaveCount(0);
await expect(viewer).toHaveTitle(/presented-report\.md/);
await viewer.close();
});
test("keeps html artifacts on the gateway URL so they stay downloads", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: HTML_THREAD_ID,
title: "Html artifact viewer window",
messages: presentFilesMessages(HTML_ARTIFACT_PATH),
artifacts: [HTML_ARTIFACT_PATH],
},
],
});
await stubUnmockedThreadEndpoints(page, HTML_THREAD_ID);
await page
.context()
.route(
`**/api/threads/${HTML_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.html`,
(route) =>
route.fulfill({
status: 200,
contentType: "text/html",
body: "<!doctype html><html><body><h1>Report draft</h1></body></html>",
}),
);
await page.goto(`/workspace/chats/${HTML_THREAD_ID}`);
await expect(page.getByText("presented-report.html")).toBeVisible({
timeout: 15_000,
});
await page.getByText("presented-report.html").first().click();
const artifactsPanel = page.locator("#artifacts");
await expect(
artifactsPanel.locator('iframe[title="Artifact preview"]'),
).toBeVisible();
const openedPromise = page.context().waitForEvent("page");
await artifactsPanel
.getByRole("button", { name: "Open in new window" })
.click();
const opened = await openedPromise;
await expect
.poll(() => new URL(opened.url()).pathname)
.toBe(
`/api/threads/${HTML_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.html`,
);
await opened.close();
});
test("returns to the same artifact after an expired session", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: EXPIRED_THREAD_ID,
title: "Expired session viewer window",
messages: presentFilesMessages(MARKDOWN_ARTIFACT_PATH),
artifacts: [MARKDOWN_ARTIFACT_PATH],
},
],
});
await stubUnmockedThreadEndpoints(page, EXPIRED_THREAD_ID);
// The session is valid for the panel and lapsed for the detached window,
// keyed off the requesting frame so the panel's own refetches cannot race
// for the 401.
await page
.context()
.route(
`**/api/threads/${EXPIRED_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.md`,
(route) =>
route.request().frame().url().includes(ARTIFACT_VIEWER_PATH)
? route.fulfill({
status: 401,
contentType: "application/json",
body: JSON.stringify({ detail: "Not authenticated" }),
})
: route.fulfill({
status: 200,
contentType: "text/markdown; charset=utf-8",
body: "# Quarterly Report\n",
}),
);
// Record the popup's navigation *requests*, not its committed URLs. This
// harness runs with DEER_FLOW_AUTH_DISABLED, so `(auth)/layout` treats the
// window as signed in and answers /login with a server redirect that never
// commits — the request is the only place the redirect target is visible.
const navigated: string[] = [];
page.context().on("page", (opened) => {
opened.on("request", (request) => {
if (request.isNavigationRequest()) {
navigated.push(request.url());
}
});
});
await page.goto(`/workspace/chats/${EXPIRED_THREAD_ID}`);
await expect(page.getByText("presented-report.md")).toBeVisible({
timeout: 15_000,
});
await page.getByText("presented-report.md").first().click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("Quarterly Report")).toBeVisible();
const viewerPromise = page.context().waitForEvent("page");
await artifactsPanel
.getByRole("button", { name: "Open in new window" })
.click();
const viewer = await viewerPromise;
// `about:blank` can appear here and `new URL` throws on an empty string,
// so parse defensively — otherwise the poll predicate errors out instead
// of retrying.
const findLogin = () =>
navigated.find((url) => {
try {
return new URL(url).pathname === "/login";
} catch {
return false;
}
});
await expect.poll(findLogin, { timeout: 15_000 }).toBeDefined();
const loginUrl = new URL(findLogin()!);
const next = loginUrl.searchParams.get("next");
expect(next).not.toBe(null);
// The whole viewer address travels through login — query string included —
// so the user comes back to this artifact, not the default workspace.
const returned = new URL(next!, loginUrl.origin);
expect(returned.pathname).toBe(ARTIFACT_VIEWER_PATH);
expect(returned.searchParams.get("path")).toBe(MARKDOWN_ARTIFACT_PATH);
expect(returned.searchParams.get("thread_id")).toBe(EXPIRED_THREAD_ID);
await viewer.close();
});
});