deer-flow/frontend/tests/e2e/artifact-preview.spec.ts
Zeren Wang a58ab484a6
feat(projects): Projects MVP Phase 2 — instructions, document shelf, promotion, trash (#5443)
* feat(projects): Projects MVP Phase 2 — instructions, document shelf, promotion, trash

Implements docs/superpowers/specs/2026-09-12-projects-mvp-phase2-design.md
(issue #5160, tracker #5129) in the slice order of the spec's §16.

Slices:
- A: ProjectsConfig + write-time 422 UTF-8 byte cap; PROJECT_CONTEXT_KEY
  admission pinning (both server-owned sets + worker hoist); latest-only
  request-scoped <project> block via DynamicContextMiddleware
  wrap_model_call/awrap_model_call (idempotent reassembly, reserved ID
  prefix + marker + provenance, never persisted); journal audit
  fingerprints; Instructions tab.
- B: ProjectDocumentRow + migration 0023; ProjectDocumentRepository with
  locked check-and-set; hash-qualified immutable shelf storage with
  Paths helpers; upload/list/content/delete-to-trash routes; project
  delete trashes the shelf in-transaction; request-scoped bounded
  <documents> index with honest count/shown + actionable overflow note;
  list_project_documents/read_project_document tools registered only on
  pinned runs; PAT allowlist + drift guards; blocking-IO anchors.
- C: shared thread-upload ingestion service (uploads router refactored to
  parity); POST from-thread with provenance; attach-to-thread with
  lock-staged copy (archived source allowed); read-only thread-files
  view with per-group truncation reporting.
- D: restore (restored/merged/not_found/no_target/content_missing; no
  file moves), purge (continuous row lock across unlink/delete/commit,
  retryable on FS errors), retention sweep (lazy + startup, 24h orphan
  guard, row-side reconciliation never deletes).
- E: Documents tab (shelf + conversation-files browser, provenance,
  archived banner, content-missing rows), /workspace/trash route,
  sidebar entry, composer attach handoff, i18n (en-US/zh-CN), e2e mocks
  + specs.

Review hardening folded in (10 rounds, all with tests):
- force active shelf content (HTML/XML family) to download; nosniff on
  artifact + content responses; unified unsandboxed-iframe PDF preview
  (fixes the pre-existing Chromium sandbox blank in the artifact viewer)
- scope document trash to the URL project under the document lock
- atomic no-overwrite filename reservation for ALL ingestion (seeded
  claims + os.link commit with suffix retry; same-name re-upload now
  unique-names instead of replacing); hidden staging only, no visible
  placeholders; lease cleanup on setup failure
- serialize conversion under the document lock with post-lock active
  revalidation; drain locked filesystem work on cancellation; preserve
  bytes when an insert's commit state is uncertain (including trashed
  rows)
- original-integrity checks before serving text or cached conversions;
  content_missing surfaced in list responses (UI reads the flag, no
  409-probe); downloads always serve original bytes
- bounded streaming document reads with cached char counts; shelf limits
  declared in middleware release identity
- thread-root confinement for from-thread sources; config fallback
  rejects fractional/infinite values; composer counts staged
  attachments; pending attachments persist until submission or removal;
  in-flight instruction/rename edits survive save refetches; shelf and
  trash pagination; conversation-file and thread-files pages stay
  subscribed to refetches

Docs: README/README_zh, backend API.md/ARCHITECTURE.md, AGENTS.md
contracts, config.example.yaml projects block.

Review follow-ups (head b4807477 → this revision):
- The trash retention sweep is split so repeated lazy triggers stay
  bounded: the indexed expiry purge still runs on every trigger
  (GET /api/trash/documents, POST /api/trash/purge) while the
  O(all rows + all files) reconciliation is throttled to one run per
  user per 15 minutes (process-local, per-user window). The startup
  sweep now runs as a background task instead of blocking gateway
  readiness, and shutdown awaits it (bounded).
- The export scrub (stripInternalMarkers) is fence- and indentation-aware
  like the render path, so a pasted, fenced <project>/<documents> snippet
  survives markdown export while real injected blocks (never fenced) are
  still removed. Fence regexes moved to a dependency-free leaf module to
  avoid the messages↔streamdown import cycle.
- The artifact viewer's PDF iframe no longer carries an added title
  attribute (the upstream e2e contract locates it via :not([title])), and
  the upstream artifact-preview spec now pins the new contract: PDFs
  render unsandboxed, images keep sandbox="".

* fix(projects): round-2 review — cancel an overrun trash sweep, restore the PDF frame title

- Shutdown cancelled only the shield around the background startup sweep,
  so an all-users reconciliation that outlived the 5s budget kept walking
  rows and files while the document repo and DB engine were disposed
  underneath it. The wait now lives in `_shutdown_startup_trash_sweep`,
  which cancels the task and drains it before worker exit: the shield
  keeps the wait bounded, the cancel makes it final (CancelledError lands
  at the sweep's next await, and `_run_startup_trash_sweep` only catches
  `Exception`, so nothing swallows it).
- The browser-preview iframe lost `title={getFileName(filepath)}` in the
  previous fix round, leaving the PDF frame without an accessible name
  while its siblings keep theirs. Restore it (WCAG frame titles), assert
  it in the DOM test, and anchor the e2e on `iframe[title="report.pdf"]`
  instead of `iframe:not([title])`.

* fix(projects): round-3 review — report the sweep's late finish, not a phantom cancel

`Task.cancel()` returns False when the sweep already finished inside the
window between the deadline firing and the cancel, so the shutdown log
claimed a cancellation that never happened. Branch on that outcome: the
warning stays for a real cancel, a late finish is logged at info, and both
paths still reap the task before worker exit.

* fix(projects): round-4 review — make Empty trash delete what it confirms

`POST /api/trash/purge` only ran the retention sweep, and the sweep's
candidate selection is age-gated, so a freshly trashed document survived
"Empty trash" even though the confirmation promises that every listed
document is permanently deleted. With one trashed row the route answered
`{"purged": 0}` and left it in place; `GET /api/trash/documents` sweeps
expired rows before listing, so the visible rows were normally ineligible
for the action by construction.

Empty trash now drives `purge_all_trashed`: the caller's trashed rows
(`list_all_trashed`, no age filter) each go through the same guarded,
row-locked `purge` as the single-document delete — bytes first, then the
row, in one transaction — so a row restored mid-flight is skipped instead of
force-deleted, and an unlink failure rolls that row back and answers 500 with
a retryable message. Retention expiry stays where it was: the sweep's
`purge_candidates` is now the only age-gated selection, and the lazy
retention sweep still runs on the listing and at startup.

Tests: the router suite replaces the retention-gated expectation with the
reviewer's repro (fresh row purged, bytes unlinked, shelf and other users'
trash untouched, a failing unlink stays retryable and 500); a blocking-I/O
anchor drives the new entry point through the offload; the mocked e2e covers
the action end to end; a new real-backend spec performs it against the real
gateway and re-reads `GET /api/trash/documents`. README, API, ARCHITECTURE
and the phase-2 design docs (en+zh) state the age-independent contract.
2026-09-16 18:46:18 +08:00

476 lines
15 KiB
TypeScript

import { expect, test } from "@playwright/test";
import { mockLangGraphAPI } from "./utils/mock-api";
const ARTIFACT_PATH = "/artifact-fixtures/report.html";
const MARKDOWN_ARTIFACT_PATH = "/artifact-fixtures/report.md";
const JSON_ARTIFACT_PATH = "/artifact-fixtures/report.json";
const PRESENTED_ARTIFACT_PATH = "/mnt/user-data/outputs/presented-report.md";
const PDF_ARTIFACT_PATH = "/artifact-fixtures/report.pdf";
const LARGE_JSON_ARTIFACT_PATH = "/mnt/user-data/outputs/large-report.json";
const IN_PROGRESS_THREAD_ID = "00000000-0000-0000-0000-000000003119";
const COMPLETE_THREAD_ID = "00000000-0000-0000-0000-000000003120";
const MARKDOWN_THREAD_ID = "00000000-0000-0000-0000-000000003121";
const MARKDOWN_ANCHOR_THREAD_ID = "00000000-0000-0000-0000-000000003123";
const JSON_THREAD_ID = "00000000-0000-0000-0000-000000003122";
const PRESENTED_THREAD_ID = "00000000-0000-0000-0000-000000003123";
const PERSISTED_PANEL_THREAD_ID = "00000000-0000-0000-0000-000000003125";
const PDF_THREAD_ID = "00000000-0000-0000-0000-000000003124";
const LARGE_JSON_THREAD_ID = "00000000-0000-0000-0000-000000003126";
function writeFileMessages({
path = ARTIFACT_PATH,
content = "<!doctype html><html><body><h1>Report draft</h1><p>测试内容</p></body></html>",
toolResult,
}: {
path?: string;
content?: string;
toolResult?: string;
} = {}) {
const messages: unknown[] = [
{
type: "human",
id: "msg-human-artifact",
content: [{ type: "text", text: "Create a report artifact" }],
},
{
type: "ai",
id: "msg-ai-write-artifact",
content: "",
tool_calls: [
{
id: "write-file-artifact",
name: "write_file",
args: {
description: "Writing report artifact",
path,
content,
},
},
],
},
];
if (toolResult !== undefined) {
messages.push({
type: "tool",
id: "msg-tool-write-artifact",
name: "write_file",
tool_call_id: "write-file-artifact",
content: toolResult,
});
}
return messages;
}
function presentFilesMessages(path = PRESENTED_ARTIFACT_PATH) {
return [
{
type: "human",
id: "msg-human-present-file",
content: [{ type: "text", text: "Create a markdown 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 preview stability", () => {
test("renders preview iframe for an in-progress write artifact", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: IN_PROGRESS_THREAD_ID,
title: "Artifact preview in progress",
messages: writeFileMessages(),
},
],
});
await page.goto(`/workspace/chats/${IN_PROGRESS_THREAD_ID}`);
await expect(page.getByText(ARTIFACT_PATH)).toBeVisible({
timeout: 15_000,
});
await page.getByText(ARTIFACT_PATH).click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("report.html")).toBeVisible();
await expect(
artifactsPanel.locator('iframe[title="Artifact preview"]'),
).toBeVisible();
await expect(
artifactsPanel.locator('iframe[title="Artifact preview"]'),
).toHaveAttribute("sandbox", "allow-scripts allow-forms");
});
test("renders preview iframe after the write artifact succeeds", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: COMPLETE_THREAD_ID,
title: "Artifact preview complete",
messages: writeFileMessages({ toolResult: "OK" }),
},
],
});
await page.goto(`/workspace/chats/${COMPLETE_THREAD_ID}`);
await expect(page.getByText(ARTIFACT_PATH)).toBeVisible({
timeout: 15_000,
});
await page.getByText(ARTIFACT_PATH).click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("report.html")).toBeVisible();
await expect(
artifactsPanel.locator('iframe[title="Artifact preview"]'),
).toBeVisible();
});
test("renders markdown preview for an in-progress write artifact", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: MARKDOWN_THREAD_ID,
title: "Markdown artifact preview in progress",
messages: writeFileMessages({
path: MARKDOWN_ARTIFACT_PATH,
content: "# Markdown draft\n\n- 测试内容 1\n- English term",
}),
},
],
});
await page.goto(`/workspace/chats/${MARKDOWN_THREAD_ID}`);
await expect(page.getByText(MARKDOWN_ARTIFACT_PATH)).toBeVisible({
timeout: 15_000,
});
await page.getByText(MARKDOWN_ARTIFACT_PATH).click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("report.md")).toBeVisible();
await expect(artifactsPanel.getByText("Markdown draft")).toBeVisible();
await expect(artifactsPanel.getByText("测试内容 1")).toBeVisible();
});
test("scrolls markdown artifact preview to heading anchors", async ({
page,
}) => {
const filler = Array.from(
{ length: 40 },
(_, index) => `填充段落 ${index + 1}`,
).join("\n\n");
mockLangGraphAPI(page, {
threads: [
{
thread_id: MARKDOWN_ANCHOR_THREAD_ID,
title: "Markdown artifact anchor navigation",
messages: writeFileMessages({
path: MARKDOWN_ARTIFACT_PATH,
content: [
"# Report",
"",
"- [概述](#概述)",
"",
filler,
"",
"## 概述",
"",
"目标章节内容",
].join("\n"),
}),
},
],
});
await page.goto(`/workspace/chats/${MARKDOWN_ANCHOR_THREAD_ID}`);
await expect(page.getByText(MARKDOWN_ARTIFACT_PATH)).toBeVisible({
timeout: 15_000,
});
await page.getByText(MARKDOWN_ARTIFACT_PATH).click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("report.md")).toBeVisible();
// Anchors keep rehype-sanitize's user-content- clobber prefix (see
// rehypeScopedSlug), so the heading id — and the translated fragment
// link that scrolls to it — are both prefixed.
const targetHeading = artifactsPanel.locator("h2#user-content-概述");
await expect(targetHeading).toHaveCount(1);
await artifactsPanel.getByRole("link", { name: "概述" }).click();
await expect
.poll(async () =>
targetHeading.evaluate((element) => {
const panel = document.querySelector("#artifacts");
if (!panel) {
return false;
}
const panelRect = panel.getBoundingClientRect();
const headingRect = element.getBoundingClientRect();
return (
headingRect.top >= panelRect.top &&
headingRect.top <= panelRect.bottom
);
}),
)
.toBe(true);
});
test("renders code view for an in-progress non-preview write artifact", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: JSON_THREAD_ID,
title: "JSON artifact code view in progress",
messages: writeFileMessages({
path: JSON_ARTIFACT_PATH,
content:
'{\n "status": "draft",\n "中文字段": "测试内容",\n "count": 3\n}',
}),
},
],
});
await page.goto(`/workspace/chats/${JSON_THREAD_ID}`);
await expect(page.getByText(JSON_ARTIFACT_PATH)).toBeVisible({
timeout: 15_000,
});
await page.getByText(JSON_ARTIFACT_PATH).click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("report.json")).toBeVisible();
await expect(artifactsPanel.getByText('"status": "draft"')).toBeVisible();
await expect(
artifactsPanel.getByText('"中文字段": "测试内容"'),
).toBeVisible();
});
test("loads a large code artifact only after explicit confirmation", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: LARGE_JSON_THREAD_ID,
title: "Large artifact preview",
messages: presentFilesMessages(LARGE_JSON_ARTIFACT_PATH),
artifacts: [LARGE_JSON_ARTIFACT_PATH],
},
],
});
const ranges: Array<string | undefined> = [];
await page.route(
`**/api/threads/${LARGE_JSON_THREAD_ID}/artifacts/mnt/user-data/outputs/large-report.json`,
(route) => {
const range = route.request().headers().range;
ranges.push(range);
if (range) {
const body = '{"preview":"PARTIAL_FILE_MARKER"}';
return route.fulfill({
status: 206,
contentType: "application/json",
headers: {
"Content-Range": `bytes 0-${Buffer.byteLength(body) - 1}/2000000`,
},
body,
});
}
return route.fulfill({
status: 200,
contentType: "application/json",
body: '{"complete":"FULL_FILE_MARKER"}',
});
},
);
await page.goto(`/workspace/chats/${LARGE_JSON_THREAD_ID}`);
await expect(page.getByText("large-report.json").first()).toBeVisible({
timeout: 15_000,
});
await page.getByText("large-report.json").first().click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText(/PARTIAL_FILE_MARKER/)).toBeVisible();
await expect(artifactsPanel.locator(".cm-editor")).toHaveCount(0);
await artifactsPanel
.getByRole("button", { name: "Load full file" })
.click();
await expect(artifactsPanel.getByText(/FULL_FILE_MARKER/)).toBeVisible();
expect(ranges).toEqual(["bytes=0-1048575", undefined]);
});
test("keeps an opened presented artifact in the header dropdown", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: PRESENTED_THREAD_ID,
title: "Presented artifact dropdown history",
messages: presentFilesMessages(),
artifacts: [MARKDOWN_ARTIFACT_PATH],
},
],
});
await page.route(
`**/api/threads/${PRESENTED_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.md`,
(route) =>
route.fulfill({
status: 200,
contentType: "text/markdown",
body: "# Presented Report\n\nGenerated content",
}),
);
await page.route(
`**/api/threads/${PRESENTED_THREAD_ID}/artifacts/artifact-fixtures/report.md`,
(route) =>
route.fulfill({
status: 200,
contentType: "text/markdown",
body: "# Thread Report\n\nTracked artifact content",
}),
);
await page.goto(`/workspace/chats/${PRESENTED_THREAD_ID}`);
// The file card in the message list shows the basename only.
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("presented-report.md")).toBeVisible();
await expect(artifactsPanel.getByText("Presented Report")).toBeVisible();
const artifactSelect = artifactsPanel.getByRole("combobox");
await artifactSelect.click();
await page.getByRole("option", { name: "report.md", exact: true }).click();
await expect(artifactsPanel.getByText("Thread Report")).toBeVisible();
await artifactSelect.click();
const presentedOption = page.getByRole("option", {
name: "presented-report.md",
});
await expect(presentedOption).toBeVisible();
await presentedOption.click();
await expect(artifactsPanel.getByText("Presented Report")).toBeVisible();
});
test("restores the artifact panel and selected file after a page refresh", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: PERSISTED_PANEL_THREAD_ID,
title: "Persisted artifact panel",
messages: presentFilesMessages(),
artifacts: [MARKDOWN_ARTIFACT_PATH],
},
],
});
await page.route(
`**/api/threads/${PERSISTED_PANEL_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.md`,
(route) =>
route.fulfill({
status: 200,
contentType: "text/markdown",
body: "# Presented Report\n\nGenerated content",
}),
);
await page.goto(`/workspace/chats/${PERSISTED_PANEL_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("Presented Report")).toBeVisible();
await page.reload();
await expect(page.getByTestId("artifact-trigger")).toBeVisible();
await expect(
page.locator("#artifacts").getByText("Presented Report"),
).toBeVisible();
});
test("renders a PDF in an unsandboxed iframe so Chromium's viewer can display it (urlOfArtifact path)", async ({
page,
}) => {
mockLangGraphAPI(page, {
threads: [
{
thread_id: PDF_THREAD_ID,
title: "PDF artifact preview",
messages: writeFileMessages({
path: PDF_ARTIFACT_PATH,
content: "%PDF-fake-content",
}),
},
],
});
await page.route(
`**/api/threads/${PDF_THREAD_ID}/artifacts${PDF_ARTIFACT_PATH}`,
(route) =>
route.fulfill({
status: 200,
contentType: "application/pdf",
body: "%PDF-1.4 fake pdf",
}),
);
await page.goto(`/workspace/chats/${PDF_THREAD_ID}`);
await expect(page.getByText(PDF_ARTIFACT_PATH)).toBeVisible({
timeout: 15_000,
});
await page.getByText(PDF_ARTIFACT_PATH).click();
const artifactsPanel = page.locator("#artifacts");
await expect(artifactsPanel.getByText("report.pdf")).toBeVisible();
// Chromium blocks its built-in PDF viewer inside a sandbox="" iframe, so
// PDFs render unsandboxed; the endpoint declares application/pdf and the
// Gateway adds X-Content-Type-Options: nosniff, so the response cannot be
// reinterpreted as active markup. Non-PDF previewable binaries (images,
// audio, video) keep the sandbox.
const urlOfArtifactIframe = artifactsPanel.locator(
'iframe[title="report.pdf"]',
);
await expect(urlOfArtifactIframe).toBeVisible();
await expect(urlOfArtifactIframe).not.toHaveAttribute("sandbox", "");
});
});