Skip to content

Commit d9292fa

Browse files
committed
fix(preview): 精简 Office 预览并移除 PPT 放映
1 parent 6230edd commit d9292fa

40 files changed

Lines changed: 669 additions & 1024 deletions

‎.github/workflows/system-tests.yml‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,9 +467,14 @@ jobs:
467467
exit 1
468468
- name: Verify readiness API
469469
run: docker compose exec -T api uv run --no-sync --no-dev pytest --junitxml=test/ci-reports/system-07.xml --durations=20 test/integration/api/test_system_router_api.py::test_health_endpoint_is_public test/integration/api/test_system_router_api.py::test_readiness_endpoint_proves_core_runtime_dependencies test/integration/api/test_system_router_api.py::test_discovery_and_openapi_declare_full_knowledge_capabilities -q
470-
- name: Verify attachment HTTP and object contract
470+
- name: Verify attachment and Office preview HTTP contracts
471471
timeout-minutes: 3
472-
run: docker compose exec -T -e TEST_USERNAME="$E2E_USERNAME" -e TEST_PASSWORD="$E2E_PASSWORD" api uv run --no-sync --no-dev pytest --junitxml=test/ci-reports/system-08.xml --durations=20 test/integration/api/test_chat_router.py::test_thread_artifact_uses_image_signature_for_content_type test/integration/api/test_public_agent_files.py -q
472+
run: |
473+
docker compose exec -T -e TEST_USERNAME="$E2E_USERNAME" -e TEST_PASSWORD="$E2E_PASSWORD" api \
474+
uv run --no-sync --no-dev pytest --junitxml=test/ci-reports/system-08.xml --durations=20 \
475+
test/integration/api/test_chat_router.py::test_thread_artifact_uses_image_signature_for_content_type \
476+
test/integration/api/test_chat_router.py::test_office_artifact_keeps_public_pdf_and_product_source \
477+
test/integration/api/test_workspace_runtime_cache_api.py test/integration/api/test_public_agent_files.py -q
473478
- name: Verify MCP management connection contract
474479
run: docker compose exec -T -e TEST_USERNAME="$E2E_USERNAME" -e TEST_PASSWORD="$E2E_PASSWORD" api uv run --no-sync --no-dev pytest --junitxml=test/ci-reports/system-10.xml --durations=20 test/integration/api/test_mcp_router.py -q
475480
- name: Verify knowledge MCP authentication and persisted documents

‎.gitignore‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ __pycache__/
1111
### Vue gitignore
1212
dist
1313
node_modules
14-
# file-viewer 在开发态复制到 public 的 Worker 与清单,生产构建由 Vite 插件写入 dist。
15-
frontend/public/vendor/
16-
frontend/public/flyfish-viewer-assets.json
1714

1815
### common gitignore
1916
.DS_Store

‎backend/test/integration/api/test_chat_router.py‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import os
1212
import uuid
1313
from datetime import UTC, datetime, timedelta
14-
from pathlib import PurePosixPath
14+
from pathlib import Path, PurePosixPath
1515

1616
import asyncpg
1717
import pytest
@@ -482,6 +482,39 @@ async def test_thread_artifact_preview_http_preserves_raw_download(test_client,
482482
assert raw_response.headers["content-type"].startswith("text/markdown")
483483

484484

485+
async def test_office_artifact_keeps_public_pdf_and_product_source(test_client, standard_user, admin_headers):
486+
"""公开预览保留 PDF,产品预览面向所属用户返回 Office 字节。"""
487+
headers = standard_user["headers"]
488+
thread_id = await _create_thread_for_user(test_client, headers)
489+
fixture = Path(__file__).resolve().parents[2] / "data" / "测试文档.docx"
490+
content = fixture.read_bytes()
491+
try:
492+
artifact_path = await _upload_project_file(test_client, headers, thread_id, "preview.docx", content, artifact_path=True)
493+
public_url = f"/api/v1/agents/sessions/{thread_id}/artifacts/{artifact_path.lstrip('/')}"
494+
product_url = f"/api/agent/threads/{thread_id}/artifacts/preview"
495+
response = await test_client.get(public_url, params={"preview": True}, headers=headers)
496+
assert response.status_code == 200, response.text
497+
assert response.headers["content-type"] == "application/pdf"
498+
assert response.content.startswith(b"%PDF-")
499+
500+
params = {"path": artifact_path}
501+
source = await test_client.get(product_url, params=params, headers=headers)
502+
assert source.status_code == 200, source.text
503+
assert source.headers["x-yuxi-preview-type"] == "office"
504+
assert source.headers["x-yuxi-preview-filename"] == "preview.docx"
505+
assert source.content == content
506+
fallback = await test_client.get(product_url, params={**params, "office_render": "pdf"}, headers=headers)
507+
assert fallback.status_code == 200, fallback.text
508+
assert fallback.headers["content-type"] == "application/pdf"
509+
assert fallback.content.startswith(b"%PDF-")
510+
511+
denied = await test_client.get(product_url, params=params, headers=admin_headers)
512+
assert denied.status_code == 404
513+
finally:
514+
await archive_public_thread(test_client, headers, thread_id)
515+
await delete_created_threads(thread_id)
516+
517+
485518
async def _create_thread_for_user(test_client, headers: dict[str, str]) -> str:
486519
agents_resp = await test_client.get("/api/agent", headers=headers)
487520
assert agents_resp.status_code == 200, agents_resp.text

‎backend/test/integration/api/test_workspace_runtime_cache_api.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ async def test_office_preview_cache_is_written_only_to_api_runtime(test_client,
5454
assert second.status_code == 200, second.text
5555
assert first.headers["content-type"].startswith("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
5656
assert first.headers["x-yuxi-preview-type"] == "office"
57+
assert first.headers["content-disposition"].startswith("attachment;")
58+
assert first.headers["x-content-type-options"] == "nosniff"
5759
assert first.content == original
5860
assert second.content == original
5961
assert _file_snapshot([runtime_cache]) == runtime_before
@@ -75,3 +77,23 @@ async def test_office_preview_cache_is_written_only_to_api_runtime(test_client,
7577
await test_client.delete("/api/workspace/file", params={"path": workspace_path}, headers=admin_headers)
7678
for cache_path in set(_file_snapshot([runtime_cache])) - set(runtime_before):
7779
cache_path.unlink(missing_ok=True)
80+
81+
82+
async def test_office_source_uses_document_media_type(test_client, admin_headers):
83+
"""Office 响应的媒体类型不能被上传内容改成浏览器可内联的类型。"""
84+
filename = f"pytest-office-media-{uuid4().hex}.xlsx"
85+
params = {"path": f"/{filename}"}
86+
content = b'<svg xmlns="http://www.w3.org/2000/svg"/>'
87+
uploaded = await test_client.post(
88+
"/api/workspace/upload", data={"parent_path": "/"}, files={"files": (filename, content)}, headers=admin_headers
89+
)
90+
assert uploaded.status_code == 200, uploaded.text
91+
try:
92+
response = await test_client.get("/api/workspace/file", params=params, headers=admin_headers)
93+
assert response.status_code == 200, response.text
94+
assert response.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
95+
assert response.headers["content-disposition"].startswith("attachment;")
96+
assert response.headers["x-content-type-options"] == "nosniff"
97+
assert response.content == content
98+
finally:
99+
await test_client.delete("/api/workspace/file", params=params, headers=admin_headers)

‎backend/test/unit/config/test_docker_compose_service_boundaries.py‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -414,13 +414,6 @@ def test_nginx_maps_mjs_to_javascript_mime():
414414
assert _maps_mjs_to_javascript_mime(source)
415415

416416

417-
def test_nginx_maps_wasm_to_webassembly_mime():
418-
"""Office 预览 WASM 必须以 WebAssembly MIME 提供。"""
419-
source = (project_root() / "docker" / "nginx" / "nginx.conf").read_text()
420-
421-
assert re.search(r"application/wasm\s+wasm\s*;", source) is not None
422-
423-
424417
def test_mime_guard_detects_missing_mjs_mapping():
425418
"""删除 .mjs 映射后部署契约 guard 必须失败。"""
426419
assert _maps_mjs_to_javascript_mime("types { application/javascript js; }") is False

‎backend/test/unit/services/test_artifact_service.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,6 @@ async def convert_office_to_pdf(filename, raw_content):
251251
captured.update(filename=filename, raw_content=raw_content)
252252
return b"%PDF-1.4 preview"
253253

254-
monkeypatch.setattr(svc, "is_office_pdf_convertible", lambda _path: True)
255254
monkeypatch.setattr(svc, "convert_office_to_pdf", convert_office_to_pdf)
256255

257256
source = await svc.resolve_thread_artifact_view(
@@ -260,6 +259,7 @@ async def convert_office_to_pdf(filename, raw_content):
260259
db=object(),
261260
path=path,
262261
preview=True,
262+
office_render="source",
263263
)
264264
assert source.preview_type == "office"
265265
assert source.filename == "report.docx"
@@ -272,7 +272,6 @@ async def convert_office_to_pdf(filename, raw_content):
272272
db=object(),
273273
path=path,
274274
preview=True,
275-
office_render="pdf",
276275
)
277276
assert response.preview_type == "pdf"
278277
assert response.content == b"%PDF-1.4 preview"

‎backend/test/unit/utils/test_filepreview.py‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88
from yuxi.infrastructure.file_preview import (
99
MAX_TEXT_PREVIEW_CHARS,
1010
detect_preview_type,
11-
is_office_source_preview,
1211
prepare_file_preview,
13-
prepare_office_source_preview,
1412
)
1513

1614

@@ -65,14 +63,11 @@ def test_prepare_file_preview_returns_complete_binary_result_from_signature():
6563

6664

6765
@pytest.mark.parametrize(
68-
("filename", "supported"),
69-
[("demo.docx", True), ("Demo.XLSX", True), ("sheet.xls", True), ("slides.pptx", True), ("notes.csv", False), ("report.pdf", False)],
66+
"filename",
67+
["demo.docx", "Demo.XLSX", "sheet.xls", "slides.pptx"],
7068
)
71-
def test_office_source_preview_keeps_original_extension(filename: str, supported: bool) -> None:
72-
assert is_office_source_preview(filename) is supported
73-
if not supported:
74-
return
75-
result = prepare_office_source_preview(filename, b"PK\x03\x04office")
69+
def test_office_source_preview_keeps_original_extension(filename: str) -> None:
70+
result = prepare_file_preview(filename, b"PK\x03\x04office", office_source=True)
7671
assert result.preview_type == "office"
7772
assert result.supported is True
7873
assert result.filename == filename

‎backend/yuxi/api/responses/files.py‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
"""把中立 Workspace preview 结果装配为 HTTP 响应。"""
22

3-
import io
43
import os
54
from urllib.parse import quote
65

7-
from fastapi.responses import FileResponse, StreamingResponse
6+
from fastapi.responses import FileResponse, Response
87
from starlette.background import BackgroundTask
98

109
from yuxi.shared.files import PreparedFile, PreviewResult
1110

1211

13-
def render_file_result(result: PreparedFile | PreviewResult | dict) -> FileResponse | StreamingResponse | dict:
12+
def render_file_result(result: PreparedFile | PreviewResult | dict) -> Response | dict:
1413
"""把已准备好的业务文件结果装配为 HTTP 响应。"""
1514
if isinstance(result, PreparedFile):
1615
headers = None
@@ -33,16 +32,16 @@ def render_file_result(result: PreparedFile | PreviewResult | dict) -> FileRespo
3332
return result
3433

3534

36-
def _preview_response(result: PreviewResult) -> dict | StreamingResponse:
35+
def _preview_response(result: PreviewResult) -> dict | Response:
3736
if not isinstance(result.content, bytes):
3837
return result.payload()
39-
filename = result.filename or "preview"
40-
return StreamingResponse(
41-
io.BytesIO(result.content),
42-
media_type=result.media_type or "application/octet-stream",
43-
headers={
44-
"Content-Disposition": f"inline; filename*=UTF-8''{quote(filename)}",
45-
"X-Yuxi-Preview-Type": result.preview_type,
46-
"X-Yuxi-Preview-Filename": quote(filename),
47-
},
48-
)
38+
filename = quote(result.filename or "preview")
39+
disposition = "attachment" if result.preview_type == "office" else "inline"
40+
headers = {
41+
"Content-Disposition": f"{disposition}; filename*=UTF-8''{filename}",
42+
"X-Yuxi-Preview-Type": result.preview_type,
43+
"X-Yuxi-Preview-Filename": filename,
44+
}
45+
if result.preview_type == "office":
46+
headers["X-Content-Type-Options"] = "nosniff"
47+
return Response(result.content, media_type=result.media_type or "application/octet-stream", headers=headers)

‎backend/yuxi/api/routers/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
router.include_router(system_routes) # /api/system/* 系统状态与全局配置
4141
router.include_router(identity_provider_router)
4242
router.include_router(auth) # /api/auth/* 登录、用户信息与 CLI 浏览器登录授权
43-
router.include_router(agent_files_router) # /api/agent/files* 与 /api/agent/images 产品预处理
43+
router.include_router(agent_files_router) # /api/agent 产品文件预览与预处理
4444
router.include_router(agent_router) # /api/agent/* 智能体管理与运行态
4545
router.include_router(session_links_router)
4646
router.include_router(feedback_router) # /api/agent/threads/* Web 用户反馈

‎backend/yuxi/api/routers/agents/files.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
1-
"""产品内部的附件预解析与图片处理入口。"""
1+
"""产品内部的文件预览、附件预解析与图片处理入口。"""
22

3-
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
3+
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
44
from pydantic import BaseModel, ConfigDict
55
from sqlalchemy.ext.asyncio import AsyncSession
66

77
from yuxi.api.dependencies.auth import get_db, require_product_user
8+
from yuxi.api.responses.files import render_file_result
89
from yuxi.api.uploads import read_upload_with_limit
10+
from yuxi.infrastructure.file_preview import OfficeRender
911
from yuxi.infrastructure.images import process_uploaded_image
1012
from yuxi.modules.agents.scope import ActorScope
13+
from yuxi.modules.agents.services.artifacts import resolve_thread_artifact_view
1114
from yuxi.modules.agents.services.attachments import get_draft_file, parse_draft_file
15+
from yuxi.modules.agents.services.thread_access import require_thread
1216
from yuxi.modules.identity.models import User
1317

1418
router = APIRouter(prefix="/agent", tags=["agent"], dependencies=[Depends(require_product_user)])
@@ -21,6 +25,24 @@ class DraftParse(BaseModel):
2125
parse_method: str | None = None
2226

2327

28+
@router.get("/threads/{thread_id}/artifacts/preview")
29+
async def preview_thread_artifact(
30+
thread_id: str,
31+
path: str = Query(..., description="产物路径"),
32+
office_render: OfficeRender = Query("source", description="Office 原文件或 PDF 回退"),
33+
user: User = Depends(require_product_user),
34+
db: AsyncSession = Depends(get_db),
35+
):
36+
"""产品浏览器预览沿用 Thread 与产物的授权边界。"""
37+
scope = ActorScope(uid=str(user.uid), app_id=None)
38+
await require_thread(db=db, scope=scope, thread_id=thread_id)
39+
return render_file_result(
40+
await resolve_thread_artifact_view(
41+
thread_id=thread_id, current_uid=scope.uid, db=db, path=path, preview=True, office_render=office_render
42+
)
43+
)
44+
45+
2446
@router.get("/files/{file_id}")
2547
async def retrieve_draft(file_id: str, user: User = Depends(require_product_user), db: AsyncSession = Depends(get_db)):
2648
"""产品读取 draft 的文件信息和可用解析方式。"""

0 commit comments

Comments
 (0)