feat: 公开定时任务页面、Word 导出、定时任务实时刷新与技能详情重构
- 新增 /public/scheduled-tasks/:taskId 公开只读访问页与对应的 /api/public/scheduled-tasks 后端路由(无需登录) - 新增对话整体 / 单条消息 / Markdown 工件 "另存为 Word (.docx)" 能力 - 定时任务列表与运行列表在任务执行中自动轮询刷新,并新增"正在执行"标记 - 定时任务运行消息接口在事件存储为空时回退到 LangGraph checkpoint, 让正在执行的任务也能立即看到提示词与流式输出 - 技能详情对话框由折叠面板改为 Tab 切换(Detail / SKILL.md), 并支持 Rendered / Raw 切换、一键复制 - config.yaml 增加 database (MySQL) 与 checkpointer (SQLite) 配置块 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7e75c5b9b9
commit
d339db4799
18 files changed
+1617
-125
No files matched your search
@@ -35,6 +35,7 @@ from app.gateway.routers import (
|
||||
memory,
|
||||
models,
|
||||
notifications,
|
||||
public_scheduled_tasks,
|
||||
recommended_questions,
|
||||
runs,
|
||||
scheduled_tasks,
|
||||
@@ -685,6 +686,11 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
# Scheduled task API is mounted at /api/scheduled-tasks
|
||||
app.include_router(scheduled_tasks.router)
|
||||
|
||||
# Public, unauthenticated read-only scheduled task API
|
||||
# (/api/public/scheduled-tasks/*). Lets external systems query tasks and
|
||||
# surface results without a DeerFlow login.
|
||||
app.include_router(public_scheduled_tasks.router)
|
||||
|
||||
# System settings API is mounted at /api/system-settings
|
||||
app.include_router(system_settings.router)
|
||||
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Public (unauthenticated) read-only API for scheduled tasks.
|
||||
|
||||
Mounted under the ``/api/public/`` prefix so the auth middleware lets these
|
||||
routes through without a session cookie. Intended for embedding scheduled
|
||||
task results into external dashboards / documentation / chat systems that
|
||||
shouldn't need a DeerFlow login.
|
||||
|
||||
Surface area:
|
||||
|
||||
- ``GET /api/public/scheduled-tasks/`` — list every task (no prompt body)
|
||||
- ``GET /api/public/scheduled-tasks/{task_id}`` — task metadata
|
||||
- ``GET /api/public/scheduled-tasks/{task_id}/runs`` — runs for a task (latest first)
|
||||
- ``GET /api/public/scheduled-tasks/runs/{run_id}`` — single run (result included)
|
||||
- ``GET /api/public/scheduled-tasks/runs/{run_id}/files/{i}``— inline file content / preview
|
||||
- ``GET /api/public/scheduled-tasks/runs/{run_id}/download`` — zip / md download of result
|
||||
|
||||
These are read-only. No write/mutation routes belong here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import mimetypes
|
||||
import re
|
||||
import zipfile
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
|
||||
from deerflow.runtime.scheduler import get_scheduled_task_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Whitelisted under ``auth_middleware._PUBLIC_PATH_PREFIXES`` (``/api/public/``).
|
||||
router = APIRouter(prefix="/api/public/scheduled-tasks", tags=["public-scheduled-tasks"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sanitisation helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
# Fields stripped from every task before it leaves the public boundary.
|
||||
# Keeps owner ids, raw cron, and the (often verbose) author prompt out of
|
||||
# anonymous responses.
|
||||
_TASK_PRIVATE_FIELDS: frozenset[str] = frozenset(
|
||||
{
|
||||
"user_id",
|
||||
"owner_user_id",
|
||||
"creator_user_id",
|
||||
"creator_email",
|
||||
"prompt",
|
||||
"execution_context",
|
||||
"_subscription",
|
||||
"role",
|
||||
"scheduler_thread_id",
|
||||
}
|
||||
)
|
||||
|
||||
# Fields stripped from every run before it leaves the public boundary.
|
||||
# We keep the result body (the user explicitly wants the MD content surfaced)
|
||||
# but redact any path that points at a server-side filesystem location.
|
||||
_RUN_PRIVATE_FIELDS: frozenset[str] = frozenset(
|
||||
{
|
||||
"user_id",
|
||||
"owner_user_id",
|
||||
"scheduler_thread_id",
|
||||
"agent_run_id",
|
||||
"can_edit",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _redact_task(task: dict[str, Any]) -> dict[str, Any]:
|
||||
return {k: v for k, v in task.items() if k not in _TASK_PRIVATE_FIELDS}
|
||||
|
||||
|
||||
def _redact_run(run: dict[str, Any]) -> dict[str, Any]:
|
||||
cleaned = {k: v for k, v in run.items() if k not in _RUN_PRIVATE_FIELDS}
|
||||
result = cleaned.get("result")
|
||||
if isinstance(result, dict):
|
||||
files = result.get("files")
|
||||
if isinstance(files, list):
|
||||
cleaned_files = []
|
||||
for idx, item in enumerate(files):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
# Strip absolute filesystem path; clients use the file index
|
||||
# to fetch content via the public file endpoint.
|
||||
public_file = {k: v for k, v in item.items() if k != "path"}
|
||||
public_file["index"] = idx
|
||||
cleaned_files.append(public_file)
|
||||
result = {**result, "files": cleaned_files}
|
||||
cleaned["result"] = result
|
||||
return cleaned
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _safe_filename(value: str, default: str = "scheduled-task-result") -> str:
|
||||
name = re.sub(r'[\\/:*?"<>|\r\n]+', "-", value).strip(" .")
|
||||
return name or default
|
||||
|
||||
|
||||
def _result_markdown(result: dict[str, Any]) -> str:
|
||||
title = str(result.get("title") or "Scheduled Task Result")
|
||||
content = str(result.get("content") or "")
|
||||
return f"# {title}\n\n{content}".strip() + "\n"
|
||||
|
||||
|
||||
def _utf8_sig_bytes(content: str) -> bytes:
|
||||
return content.encode("utf-8-sig")
|
||||
|
||||
|
||||
def _content_disposition(filename: str) -> str:
|
||||
quoted = quote(filename)
|
||||
return f"attachment; filename*=UTF-8''{quoted}"
|
||||
|
||||
|
||||
def _run_file_path(run: dict[str, Any], file_index: int) -> tuple[dict[str, Any], Path]:
|
||||
result = run.get("result") or {}
|
||||
files = result.get("files") if isinstance(result, dict) and isinstance(result.get("files"), list) else []
|
||||
if file_index < 0 or file_index >= len(files):
|
||||
raise HTTPException(status_code=404, detail="Result file not found")
|
||||
item = files[file_index]
|
||||
if not isinstance(item, dict) or not isinstance(item.get("path"), str):
|
||||
raise HTTPException(status_code=404, detail="Result file not found")
|
||||
path = Path(item["path"])
|
||||
if not path.exists() or not path.is_file():
|
||||
raise HTTPException(status_code=404, detail="Result file is no longer available")
|
||||
return item, path
|
||||
|
||||
|
||||
def _is_text_previewable(path: Path, mime_type: str | None) -> bool:
|
||||
if mime_type and (mime_type.startswith("text/") or mime_type in {"application/json", "application/xml"}):
|
||||
return True
|
||||
return path.suffix.lower() in {".md", ".markdown", ".txt", ".json", ".csv", ".xml", ".yaml", ".yml", ".log"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Routes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def public_list_tasks(
|
||||
search: str | None = Query(default=None, description="Case-insensitive fuzzy match on task name"),
|
||||
limit: int = Query(default=200, ge=1, le=500),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
) -> dict[str, Any]:
|
||||
"""Return every scheduled task across all users.
|
||||
|
||||
Sensitive fields (user_id, raw prompt, scheduler thread id, …) are stripped
|
||||
before serialisation. The response shape is intentionally stable so external
|
||||
integrations can pin to it without surprises.
|
||||
"""
|
||||
service = get_scheduled_task_service()
|
||||
tasks = await service.admin_list_tasks()
|
||||
|
||||
if search:
|
||||
needle = search.strip().lower()
|
||||
tasks = [t for t in tasks if needle in str(t.get("name", "")).lower()]
|
||||
|
||||
total = len(tasks)
|
||||
sliced = tasks[offset : offset + limit]
|
||||
return {
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"tasks": [_redact_task(task) for task in sliced],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{task_id}")
|
||||
async def public_get_task(task_id: str) -> dict[str, Any]:
|
||||
"""Return metadata for a single task (without prompt body)."""
|
||||
service = get_scheduled_task_service()
|
||||
task = await service.store.get_task_any(task_id)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
|
||||
return _redact_task(task)
|
||||
|
||||
|
||||
@router.get("/{task_id}/runs")
|
||||
async def public_list_task_runs(
|
||||
task_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=200),
|
||||
) -> dict[str, Any]:
|
||||
"""Return runs for a task, latest first."""
|
||||
service = get_scheduled_task_service()
|
||||
task = await service.store.get_task_any(task_id)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
|
||||
runs = await service.admin_list_runs(task_id, limit=limit)
|
||||
return {
|
||||
"task": _redact_task(task),
|
||||
"total": len(runs),
|
||||
"runs": [_redact_run(run) for run in runs],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/runs/{run_id}")
|
||||
async def public_get_run(run_id: str) -> dict[str, Any]:
|
||||
"""Return a single run with its full result body (Markdown included)."""
|
||||
service = get_scheduled_task_service()
|
||||
run = await service.admin_get_run(run_id)
|
||||
if run is None:
|
||||
raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
|
||||
return _redact_run(run)
|
||||
|
||||
|
||||
@router.get("/runs/{run_id}/files/{file_index}")
|
||||
async def public_get_run_file(run_id: str, file_index: int) -> dict[str, Any]:
|
||||
"""Return a single result-file entry with its inline text content where
|
||||
previewable. Binary files come back with ``previewable: false`` and the
|
||||
consumer should fetch the download endpoint instead."""
|
||||
service = get_scheduled_task_service()
|
||||
run = await service.admin_get_run(run_id)
|
||||
if run is None:
|
||||
raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
|
||||
item, path = _run_file_path(run, file_index)
|
||||
mime_type = item.get("mime_type") or mimetypes.guess_type(path.name)[0]
|
||||
previewable = _is_text_previewable(path, mime_type)
|
||||
content: str | None = None
|
||||
if previewable:
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8")
|
||||
except UnicodeDecodeError:
|
||||
content = path.read_text(encoding="utf-8", errors="replace")
|
||||
return {
|
||||
"index": file_index,
|
||||
"name": item.get("name") or path.name,
|
||||
"mime_type": mime_type,
|
||||
"kind": item.get("kind"),
|
||||
"size": path.stat().st_size,
|
||||
"previewable": previewable,
|
||||
"content": content,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/runs/{run_id}/files/{file_index}/download")
|
||||
async def public_download_run_file(run_id: str, file_index: int):
|
||||
"""Stream a single result file as a download."""
|
||||
service = get_scheduled_task_service()
|
||||
run = await service.admin_get_run(run_id)
|
||||
if run is None:
|
||||
raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
|
||||
item, path = _run_file_path(run, file_index)
|
||||
filename = _safe_filename(str(item.get("name") or path.name), path.name)
|
||||
media = item.get("mime_type") or mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
||||
return FileResponse(path, filename=filename, media_type=media)
|
||||
|
||||
|
||||
@router.get("/runs/{run_id}/download")
|
||||
async def public_download_run(run_id: str):
|
||||
"""Download the full result: a zipped bundle of result.md + every file,
|
||||
or a single ``.md`` when no auxiliary files were produced."""
|
||||
service = get_scheduled_task_service()
|
||||
run = await service.admin_get_run(run_id)
|
||||
if run is None:
|
||||
raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
|
||||
|
||||
result = run.get("result") or {}
|
||||
if not isinstance(result, dict):
|
||||
result = {}
|
||||
files = result.get("files") if isinstance(result.get("files"), list) else []
|
||||
accessible_files: list[tuple[str, Path]] = []
|
||||
for item in files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
path_value = item.get("path")
|
||||
if not isinstance(path_value, str) or not path_value:
|
||||
continue
|
||||
path = Path(path_value)
|
||||
if path.exists() and path.is_file():
|
||||
accessible_files.append((str(item.get("name") or path.name), path))
|
||||
|
||||
base_name = _safe_filename(str(result.get("title") or "scheduled-task-result"))
|
||||
if not accessible_files:
|
||||
return Response(
|
||||
content=_utf8_sig_bytes(_result_markdown(result)),
|
||||
media_type="text/markdown; charset=utf-8",
|
||||
headers={"Content-Disposition": _content_disposition(f"{base_name}.md")},
|
||||
)
|
||||
|
||||
archive = BytesIO()
|
||||
with zipfile.ZipFile(archive, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("result.md", _utf8_sig_bytes(_result_markdown(result)))
|
||||
for name, path in accessible_files:
|
||||
arcname = _safe_filename(name, path.name)
|
||||
zf.write(path, arcname=arcname)
|
||||
archive.seek(0)
|
||||
return StreamingResponse(
|
||||
archive,
|
||||
media_type="application/zip",
|
||||
headers={"Content-Disposition": _content_disposition(f"{base_name}.zip")},
|
||||
)
|
||||
@@ -14,7 +14,16 @@ from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.deps import get_current_user, get_local_provider, get_optional_user_from_request, get_run_event_store, get_run_store, get_tag_store
|
||||
from app.gateway.deps import (
|
||||
get_checkpointer,
|
||||
get_current_user,
|
||||
get_local_provider,
|
||||
get_optional_user_from_request,
|
||||
get_run_event_store,
|
||||
get_run_store,
|
||||
get_tag_store,
|
||||
)
|
||||
from deerflow.runtime import serialize_channel_values
|
||||
from deerflow.runtime.scheduler import DuplicateTaskNameError, get_scheduled_task_service
|
||||
|
||||
router = APIRouter(prefix="/api/scheduled-tasks", tags=["scheduled-tasks"])
|
||||
@@ -235,31 +244,129 @@ async def get_scheduled_task_run(run_id: str, request: Request) -> dict:
|
||||
return run
|
||||
|
||||
|
||||
def _event_type_for_checkpoint_message(message: dict) -> str:
|
||||
"""Map a serialized LangChain message to the same ``event_type`` strings
|
||||
the run-event store uses, so the frontend's existing role labels keep
|
||||
working for checkpoint-derived synthetic rows."""
|
||||
raw_type = message.get("type") or message.get("role") or ""
|
||||
if raw_type in {"human", "user"}:
|
||||
return "llm.human.input"
|
||||
if raw_type in {"ai", "assistant"}:
|
||||
return "llm.ai.response"
|
||||
if raw_type == "tool":
|
||||
return "llm.tool.result"
|
||||
if raw_type == "system":
|
||||
return "llm.system"
|
||||
return f"llm.{raw_type or 'message'}"
|
||||
|
||||
|
||||
async def _checkpoint_messages_for_run(
|
||||
request: Request, agent_run: dict, *, limit: int
|
||||
) -> list[dict]:
|
||||
"""Return a synthetic list of message rows pulled from the LangGraph
|
||||
checkpoint for an in-flight run.
|
||||
|
||||
The event store is updated by the streaming pipeline and may stay empty
|
||||
until the first message tuple is flushed — meanwhile the checkpoint
|
||||
already carries the current state (input + accumulating AI deltas). We
|
||||
project that into the same row shape the frontend uses for the event
|
||||
store, so the run-detail page can show progress immediately."""
|
||||
try:
|
||||
checkpointer = get_checkpointer(request)
|
||||
except Exception:
|
||||
return []
|
||||
thread_id = agent_run.get("thread_id")
|
||||
if not thread_id:
|
||||
return []
|
||||
config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
||||
try:
|
||||
tup = await checkpointer.aget_tuple(config)
|
||||
except Exception:
|
||||
return []
|
||||
if tup is None:
|
||||
return []
|
||||
checkpoint = getattr(tup, "checkpoint", {}) or {}
|
||||
channel_values = checkpoint.get("channel_values") or {}
|
||||
try:
|
||||
values = serialize_channel_values(channel_values)
|
||||
except Exception:
|
||||
return []
|
||||
messages = values.get("messages") or []
|
||||
|
||||
rows: list[dict] = []
|
||||
for index, message in enumerate(messages[-limit:]):
|
||||
if not isinstance(message, dict):
|
||||
continue
|
||||
rows.append(
|
||||
{
|
||||
"seq": index + 1,
|
||||
"event_type": _event_type_for_checkpoint_message(message),
|
||||
"category": "message",
|
||||
"content": message,
|
||||
"metadata": {"source": "checkpoint"},
|
||||
"created_at": None,
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
@router.get("/runs/{run_id}/messages")
|
||||
async def get_scheduled_task_run_messages(run_id: str, request: Request, limit: int = 500) -> dict:
|
||||
"""Agent messages produced by a scheduled run's underlying agent run.
|
||||
|
||||
Lets the run-detail page show what the agent is doing — useful when a run
|
||||
is stuck in ``running``. Authorization reuses :func:`_load_run` (owner /
|
||||
subscriber / admin); the event-store query then passes ``user_id=None``
|
||||
because access has already been checked.
|
||||
Resolution order (most authoritative first):
|
||||
|
||||
1. Event-store rows for the underlying agent run — these are the per-tuple
|
||||
streaming events the worker writes as the agent runs.
|
||||
2. LangGraph checkpoint snapshot — the canonical conversation state. Used
|
||||
as a fallback when the event store is still empty (early in a run) or
|
||||
when only partial events have been flushed; we project the snapshot
|
||||
into the same row shape the frontend already renders so the user can
|
||||
see the prompt + current AI output while the task is mid-flight.
|
||||
3. Synthetic human-input row built from ``task.prompt`` — shown even
|
||||
before the agent run is registered, so a `pending` task at minimum
|
||||
displays what was queued.
|
||||
"""
|
||||
service = get_scheduled_task_service()
|
||||
user_id = await _user_id(request)
|
||||
run = await _load_run(service, request, run_id, user_id)
|
||||
if run is None:
|
||||
raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
|
||||
capped = max(1, min(limit, 1000))
|
||||
|
||||
# Always available: task prompt as the seeded human input. Lets the
|
||||
# ``execution process`` tab show *something* even before the agent run is
|
||||
# registered, which is the user-visible bug we're fixing.
|
||||
fallback_rows: list[dict] = []
|
||||
task_id = run.get("task_id")
|
||||
if task_id:
|
||||
task = await service.store.get_task_any(task_id)
|
||||
prompt = (task or {}).get("prompt")
|
||||
if prompt:
|
||||
fallback_rows.append(
|
||||
{
|
||||
"seq": 0,
|
||||
"event_type": "llm.human.input",
|
||||
"category": "message",
|
||||
# Frontend treats human-input content as a plain string.
|
||||
"content": str(prompt),
|
||||
"metadata": {"source": "task_prompt"},
|
||||
"created_at": run.get("created_at") or run.get("scheduled_for"),
|
||||
}
|
||||
)
|
||||
|
||||
agent_run_id = run.get("agent_run_id")
|
||||
if not agent_run_id:
|
||||
return {"messages": [], "has_more": False}
|
||||
return {"messages": fallback_rows, "has_more": False}
|
||||
|
||||
# Each scheduled run executes on its own throwaway runtime thread — NOT the
|
||||
# run row's ``scheduler_thread_id`` — so resolve the real thread from the
|
||||
# run store before querying its message events.
|
||||
run_store = get_run_store(request)
|
||||
agent_run = await run_store.get(agent_run_id, user_id=None)
|
||||
if agent_run is None:
|
||||
return {"messages": [], "has_more": False}
|
||||
capped = max(1, min(limit, 1000))
|
||||
return {"messages": fallback_rows, "has_more": False}
|
||||
|
||||
event_store = get_run_event_store(request)
|
||||
rows = await event_store.list_messages_by_run(
|
||||
agent_run["thread_id"],
|
||||
@@ -267,6 +374,16 @@ async def get_scheduled_task_run_messages(run_id: str, request: Request, limit:
|
||||
limit=capped + 1,
|
||||
user_id=None,
|
||||
)
|
||||
|
||||
# Event store has no rows yet (run just started, or events still buffering).
|
||||
# Fall back to the live checkpoint so the user immediately sees the prompt
|
||||
# + whatever AI output has been streamed so far.
|
||||
if not rows:
|
||||
checkpoint_rows = await _checkpoint_messages_for_run(request, agent_run, limit=capped)
|
||||
if checkpoint_rows:
|
||||
return {"messages": checkpoint_rows[:capped], "has_more": False}
|
||||
return {"messages": fallback_rows, "has_more": False}
|
||||
|
||||
has_more = len(rows) > capped
|
||||
return {"messages": rows[:capped] if has_more else rows, "has_more": has_more}
|
||||
|
||||
|
||||
@@ -109,6 +109,16 @@ skills:
|
||||
agents_api:
|
||||
enabled: true
|
||||
|
||||
database:
|
||||
backend: mysql
|
||||
mysql_url: $MYSQL_DATABASE_URL
|
||||
pool_size: 10
|
||||
echo_sql: false
|
||||
|
||||
checkpointer:
|
||||
type: sqlite
|
||||
connection_string: D:\cursor-work\offline-backend-20260512\backend\.deer-flow\data\deerflow.db
|
||||
|
||||
# 记忆子系统:跨会话持久化用户画像与 agent 私有记忆。
|
||||
# 三层覆盖优先级(高->低):
|
||||
# users/{user_id}/memory_config.json > .deer-flow/memory_user_overrides.json > 此处
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# 公开定时任务 API
|
||||
|
||||
本文档描述用于对接外部系统的**公开只读**定时任务接口,以及配套的公开网页入口。所有 `/api/public/*` 接口都**无需登录**,可以直接调用。
|
||||
|
||||
> ⚠️ 任何接入这套接口的系统需要确认:暴露 task / run 列表与正文是符合贵方业务安全要求的。如果不希望全员可见,请走带鉴权的 `/api/scheduled-tasks/*`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 基础信息
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 网关基址(开发) | `http://localhost:8001` |
|
||||
| 网关基址(生产) | 部署到 Nginx 后通常是 `https://<你的域名>` |
|
||||
| 公开 API 前缀 | `/api/public/scheduled-tasks` |
|
||||
| 鉴权 | **无需**鉴权(白名单在 `auth_middleware._PUBLIC_PATH_PREFIXES`) |
|
||||
| 编码 | 请求 / 响应均为 UTF-8,响应类型 `application/json`(下载除外) |
|
||||
| 错误响应 | 标准 FastAPI 错误体 `{"detail": "..."}`;HTTP 状态码 `404 / 400 / 500` 等 |
|
||||
|
||||
公开网页页面:
|
||||
|
||||
```
|
||||
#/public/scheduled-tasks/<task_id>
|
||||
```
|
||||
|
||||
例如 `https://<你的域名>/#/public/scheduled-tasks/8f1d8b9c-...`。
|
||||
左侧列出该任务所有执行记录,默认打开第一条;右侧默认渲染 Markdown 正文,点击 Tab 可以查看“结果文件”或“元数据”,点击左侧任意记录右侧内容会跟随切换。
|
||||
|
||||
---
|
||||
|
||||
## 2. 接口列表
|
||||
|
||||
### 2.1 列出全部定时任务
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks
|
||||
```
|
||||
|
||||
**Query 参数**
|
||||
|
||||
| 名称 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `search` | string | 否 | — | 任务名模糊匹配(不区分大小写) |
|
||||
| `limit` | int | 否 | 200 | 单页数量,1–500 |
|
||||
| `offset` | int | 否 | 0 | 偏移量,配合 `limit` 分页 |
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"total": 12,
|
||||
"limit": 200,
|
||||
"offset": 0,
|
||||
"tasks": [
|
||||
{
|
||||
"task_id": "8f1d8b9c-...",
|
||||
"name": "每日舆情简报",
|
||||
"schedule_text": "每天 09:00",
|
||||
"cron_expr": "0 9 * * *",
|
||||
"timezone": "Asia/Shanghai",
|
||||
"enabled": true,
|
||||
"next_run_at": "2026-05-21T01:00:00+00:00",
|
||||
"last_run_at": "2026-05-20T01:00:12+00:00",
|
||||
"last_status": "succeeded",
|
||||
"published": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> 已脱敏:`user_id`、`creator_email`、`prompt`、`scheduler_thread_id`、`execution_context` 等私有字段不会出现在公开响应里。
|
||||
|
||||
### 2.2 获取单个任务元数据
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks/{task_id}
|
||||
```
|
||||
|
||||
**响应**:与上面 `tasks[]` 的元素结构一致;任务不存在返回 `404`。
|
||||
|
||||
### 2.3 列出某任务的所有执行记录
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks/{task_id}/runs
|
||||
```
|
||||
|
||||
**Query 参数**
|
||||
|
||||
| 名称 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `limit` | int | 否 | 50 | 最近执行数量,1–200 |
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"task": { "task_id": "...", "name": "...", "schedule_text": "...", "timezone": "...", "enabled": true },
|
||||
"total": 7,
|
||||
"runs": [
|
||||
{
|
||||
"id": "run-uuid-...",
|
||||
"task_id": "8f1d8b9c-...",
|
||||
"scheduled_for": "2026-05-20T01:00:00+00:00",
|
||||
"started_at": "2026-05-20T01:00:01+00:00",
|
||||
"finished_at": "2026-05-20T01:00:12+00:00",
|
||||
"status": "succeeded",
|
||||
"error": null,
|
||||
"retry_count": 0,
|
||||
"result": {
|
||||
"title": "2026-05-20 舆情简报",
|
||||
"content": "# 简报\n\n...",
|
||||
"format": "markdown",
|
||||
"files": [
|
||||
{ "index": 0, "name": "report.md", "mime_type": "text/markdown", "kind": "markdown", "size": 4321 }
|
||||
],
|
||||
"created_at": "2026-05-20T01:00:12+00:00"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> 已脱敏:返回的 `files[]` 不包含服务器绝对路径;客户端通过下标 `index` 调用文件接口。
|
||||
|
||||
### 2.4 获取单条执行记录
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks/runs/{run_id}
|
||||
```
|
||||
|
||||
返回单条 run 数据(结构同 2.3 中的 `runs[]` 元素)。
|
||||
|
||||
### 2.5 获取单个结果文件的内容(可预览文本直接内联)
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks/runs/{run_id}/files/{file_index}
|
||||
```
|
||||
|
||||
`file_index` 来自 `run.result.files[].index`。
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"index": 0,
|
||||
"name": "report.md",
|
||||
"mime_type": "text/markdown",
|
||||
"kind": "markdown",
|
||||
"size": 4321,
|
||||
"previewable": true,
|
||||
"content": "# 简报\n\n..."
|
||||
}
|
||||
```
|
||||
|
||||
二进制文件 `previewable=false`、`content=null`,请走 2.6 下载。
|
||||
|
||||
### 2.6 下载单个结果文件
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks/runs/{run_id}/files/{file_index}/download
|
||||
```
|
||||
|
||||
返回原始文件二进制流,附带 `Content-Disposition: attachment` 头部。
|
||||
|
||||
### 2.7 打包下载整个执行结果
|
||||
|
||||
```
|
||||
GET /api/public/scheduled-tasks/runs/{run_id}/download
|
||||
```
|
||||
|
||||
- 如果该 run **没有附加文件**:直接返回 `result.md`(UTF-8 BOM)。
|
||||
- 如果有 ≥ 1 个附加文件:返回 ZIP,里面包含:
|
||||
- `result.md` — 标题 + 正文 Markdown
|
||||
- 每个生成文件原样
|
||||
|
||||
---
|
||||
|
||||
## 3. 调用示例
|
||||
|
||||
### curl
|
||||
|
||||
```bash
|
||||
# 列出全部任务
|
||||
curl -s "https://<domain>/api/public/scheduled-tasks?limit=50"
|
||||
|
||||
# 查看任务的执行记录
|
||||
curl -s "https://<domain>/api/public/scheduled-tasks/<task_id>/runs"
|
||||
|
||||
# 下载某次执行
|
||||
curl -L -o report.zip \
|
||||
"https://<domain>/api/public/scheduled-tasks/runs/<run_id>/download"
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
base = "https://<domain>/api/public/scheduled-tasks"
|
||||
|
||||
tasks = requests.get(f"{base}", params={"limit": 100, "search": "舆情"}).json()
|
||||
for task in tasks["tasks"]:
|
||||
runs = requests.get(f"{base}/{task['task_id']}/runs", params={"limit": 5}).json()
|
||||
for run in runs["runs"]:
|
||||
if run.get("result"):
|
||||
print(task["name"], run["id"], run["result"]["title"])
|
||||
print(run["result"]["content"][:200])
|
||||
```
|
||||
|
||||
### 直接嵌入 iframe
|
||||
|
||||
```html
|
||||
<iframe src="https://<domain>/#/public/scheduled-tasks/<task_id>"
|
||||
style="width:100%;height:800px;border:0"></iframe>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 状态码
|
||||
|
||||
| 状态码 | 含义 |
|
||||
|---|---|
|
||||
| 200 | 成功 |
|
||||
| 400 | 参数错误(如 `limit` 超出范围) |
|
||||
| 404 | 任务 / 执行 / 文件 不存在 |
|
||||
| 5xx | 网关 / 后台错误 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 字段映射快查
|
||||
|
||||
### `task` 字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `task_id` | string | 任务 ID |
|
||||
| `name` | string | 任务名 |
|
||||
| `schedule_text` | string | 人类可读的执行计划 |
|
||||
| `cron_expr` | string | 规范化的 cron 表达式 |
|
||||
| `timezone` | string | 时区 |
|
||||
| `enabled` | bool | 是否启用 |
|
||||
| `next_run_at` | string | null | 下次执行时间(ISO 8601) |
|
||||
| `last_run_at` | string | null | 上次执行时间 |
|
||||
| `last_status` | string | null | 上次执行状态(`succeeded` / `failed` / `running` / `pending` / `…`) |
|
||||
| `published` | bool | 是否被发布到广场 |
|
||||
|
||||
### `run` 字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | string | 执行 ID |
|
||||
| `task_id` | string | 所属任务 ID |
|
||||
| `scheduled_for` | string | 原定执行时间 |
|
||||
| `started_at` | string | null | 实际开始时间 |
|
||||
| `finished_at` | string | null | 完成 / 失败时间 |
|
||||
| `status` | string | `pending` / `running` / `succeeded` / `failed` |
|
||||
| `error` | string | null | 失败描述 |
|
||||
| `retry_count` | int | null | 重试次数 |
|
||||
| `result` | object | null | 执行结果(见下) |
|
||||
|
||||
### `result` 字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `title` | string | 结果标题 |
|
||||
| `content` | string | 主体 Markdown / 文本 |
|
||||
| `format` | string | `markdown` / `text` / `json` / `mixed` |
|
||||
| `files[]` | array | 附加文件元数据,含 `index / name / mime_type / kind / size` |
|
||||
| `created_at` | string | 结果生成时间 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 实现位置
|
||||
|
||||
- 路由实现:[`app/gateway/routers/public_scheduled_tasks.py`](../app/gateway/routers/public_scheduled_tasks.py)
|
||||
- 公开 URL 白名单:[`app/gateway/auth_middleware.py`](../app/gateway/auth_middleware.py) 中的 `_PUBLIC_PATH_PREFIXES`
|
||||
- 前端公开页面:[`frontend-web/src/pages/PublicScheduledTaskPage.tsx`](../../../frontend-web/src/pages/PublicScheduledTaskPage.tsx)
|
||||
- 路由注册:[`frontend-web/src/App.tsx`](../../../frontend-web/src/App.tsx) `/#/public/scheduled-tasks/:taskId`
|
||||
Reference in new issue
Block a user