/** * 深度研究「工作流配置 / 报告结构」API 客户端 + React Query hooks。 * * 后端:`/api/report-structures`(见 app/gateway/routers/report_structures.py)。 * 全局共享、无用户隔离;新增永远默认启用(服务端强制,不收 enabled 字段)。 * snake_case ⇄ camelCase 在此边界收敛。 */ import { keepPreviousData, useMutation, useQuery, useQueryClient, } from "@tanstack/react-query"; import { apiFetch } from "@/core/api/fetch-client"; import { getBackendBaseURL } from "@/core/config"; export type ReportStructureMode = "fixed" | "adaptive"; export const DEFAULT_REPORT_STRUCTURE_MODE: ReportStructureMode = "adaptive"; export const REPORT_STRUCTURE_MODE_OPTIONS: { value: ReportStructureMode; label: string; description: string; }[] = [ { value: "fixed", label: "固定大纲", description: "按结构内容的章节标题与层级逐一成文,不得改写、合并或省略。", }, { value: "adaptive", label: "弹性大纲", description: "保留现有成文策略,可按材料对无依据小节做合并或省略。", }, ]; export function normalizeReportStructureMode(value: unknown): ReportStructureMode { return value === "fixed" ? "fixed" : "adaptive"; } export function reportStructureModeLabel(mode: ReportStructureMode): string { return mode === "fixed" ? "固定大纲" : "弹性大纲"; } export const MAX_RETRIEVAL_DIRECTIONS = 12; export const MAX_RETRIEVAL_DIRECTION_CHARS = 200; export const MAX_RETRIEVAL_SKILLS = 8; export const MAX_RETRIEVAL_SKILL_CHARS = 64; const EMPTY_LIST_TOKENS = new Set(["", "[]", "{}", "null", "none", "undefined"]); function coerceListish(value: unknown): unknown[] { if (value == null || typeof value === "boolean") return []; if (Array.isArray(value)) return value; if (typeof value === "string") { const text = value.trim(); if (!text || EMPTY_LIST_TOKENS.has(text.toLowerCase())) return []; if (text.startsWith("[") || text.startsWith("{")) { try { const parsed = JSON.parse(text) as unknown; if (parsed == null) return []; if (Array.isArray(parsed)) return parsed; return []; } catch { return [value]; } } return [value]; } return []; } export function normalizeRetrievalDirections(value: unknown): string[] { const parts = coerceListish(value); const seen = new Set(); const out: string[] = []; for (const item of parts) { const text = String(item ?? "") .replace(/\s+/g, " ") .trim() .slice(0, MAX_RETRIEVAL_DIRECTION_CHARS); if (!text || EMPTY_LIST_TOKENS.has(text.toLowerCase())) continue; const key = text.toLowerCase(); if (seen.has(key)) continue; seen.add(key); out.push(text); if (out.length >= MAX_RETRIEVAL_DIRECTIONS) break; } return out; } export function normalizeRetrievalSkills(value: unknown): string[] { const parts = coerceListish(value); const seen = new Set(); const out: string[] = []; for (const item of parts) { const text = String(item ?? "") .replace(/[\x00\r\n]/g, "") .trim() .slice(0, MAX_RETRIEVAL_SKILL_CHARS); if (!text || EMPTY_LIST_TOKENS.has(text.toLowerCase()) || /\s/.test(text)) continue; const key = text.toLowerCase(); if (seen.has(key)) continue; seen.add(key); out.push(text); if (out.length >= MAX_RETRIEVAL_SKILLS) break; } return out; } const COLLECTOR_DIRECTION_INTRO = "请按以下检索方向拆分检索词(这是拆词约束,不是检索词本身):每个方向拆成若干具体、可检索的检索词(含课题中的专名、时间、地点、同义/中英对照等),不要直接把方向名称拿去搜索——方向标签往往搜不到结果。覆盖列出的每一个方向;未列出的方面不必主动扩展。某个检索词没有结果时,换更具体或更短的词再试,仍不要改用未列出的方向。"; const COLLECTOR_SKILL_INTRO = "请严格按照以下技能收集素材:先用 read_file 读取每个技能的 SKILL.md,再按其说明调用工具检索。不要改用未列出的技能,也不要自行改成纯 web_search(除非技能说明要求联网)。每个技能至少使用一轮。"; /** First collector turn: append direction / skill blocks only when they exist. */ export function composeCollectorQueryWithDirections( query: string, directions: unknown, skills?: unknown, ): string { let topic = query.trim(); if (!topic) return topic; const cleanedDirections = normalizeRetrievalDirections(directions); if (cleanedDirections.length > 0 && !topic.includes("")) { const lines = cleanedDirections.map((item, index) => `${index + 1}. ${item}`).join("\n"); topic = `${topic}\n\n\n${COLLECTOR_DIRECTION_INTRO}\n${lines}\n`; } const cleanedSkills = normalizeRetrievalSkills(skills); if (cleanedSkills.length > 0 && !topic.includes("")) { const lines = cleanedSkills.map((item, index) => `${index + 1}. ${item}`).join("\n"); topic = `${topic}\n\n\n${COLLECTOR_SKILL_INTRO}\n${lines}\n`; } return topic; } export interface ReportStructure { id: string; /** 标题:卡片主标签,也是列表「标题筛选」的目标。 */ title: string; /** 描述:一句话说明这套结构的适用场景(存储列沿用 name)。 */ name: string; /** 接口内容:选中卡片后应用到报告结构(custom_outline)的 Markdown 文本。 */ content: string; /** 结构约束:固定大纲逐章对照;弹性大纲沿用现有材料驱动写法。 */ structureMode: ReportStructureMode; /** 检索方向:选中后收集员按这些方向拆分具体检索词;空则沿用收集员自行拆词。 */ retrievalDirections: string[]; /** 检索来源:选中后收集素材调用这些技能;空则沿用收集员默认工具。 */ retrievalSkills: string[]; enabled: boolean; /** 创建用户名(本部署为邮箱;系统内置种子为“系统内置”)。 */ createdBy: string | null; createdAt: string | null; /** 最后修改时间(编辑、启停都会刷新)。 */ updatedAt: string | null; } export type ReportStructureInput = { title: string; name: string; content: string; structureMode: ReportStructureMode; retrievalDirections: string[]; retrievalSkills: string[]; }; export type ReportStructurePatch = Partial; export type ReportStructureStatusFilter = "all" | "enabled" | "disabled"; const BASE = () => `${getBackendBaseURL()}/api/report-structures`; interface ServerStructure { id: string; title: string; name: string; content: string; structure_mode?: string | null; retrieval_directions?: string[] | null; retrieval_skills?: string[] | null; enabled: boolean; created_by: string | null; created_at: string | null; updated_at: string | null; } function toStructure(s: ServerStructure): ReportStructure { return { id: s.id, title: s.title, name: s.name ?? "", content: s.content, structureMode: normalizeReportStructureMode(s.structure_mode), retrievalDirections: normalizeRetrievalDirections(s.retrieval_directions), retrievalSkills: normalizeRetrievalSkills(s.retrieval_skills), enabled: s.enabled ?? true, createdBy: s.created_by ?? null, createdAt: s.created_at ?? null, updatedAt: s.updated_at ?? null, }; } async function readJson(res: Response, ctx: string): Promise { if (!res.ok) { const data = await res.json().catch(() => null as unknown); const detail = data && typeof data === "object" && "detail" in data ? String((data as { detail: unknown }).detail) : `${ctx} failed (${res.status})`; throw new Error(detail); } return (await res.json()) as T; } export async function listReportStructures(params: { status?: ReportStructureStatusFilter; title?: string; } = {}): Promise { const qs = new URLSearchParams(); if (params.status === "enabled") qs.set("enabled", "true"); if (params.status === "disabled") qs.set("enabled", "false"); const title = params.title?.trim(); if (title) qs.set("title", title); const query = qs.toString(); const res = await apiFetch(`${BASE()}${query ? `?${query}` : ""}`, { method: "GET" }); const data = await readJson<{ structures: ServerStructure[] }>(res, "list report structures"); return (data.structures ?? []).map(toStructure); } export async function createReportStructure(input: ReportStructureInput): Promise { const res = await apiFetch(BASE(), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: input.title, name: input.name, content: input.content, structure_mode: normalizeReportStructureMode(input.structureMode), retrieval_directions: normalizeRetrievalDirections(input.retrievalDirections), retrieval_skills: normalizeRetrievalSkills(input.retrievalSkills), }), }); return toStructure(await readJson(res, "create report structure")); } export async function updateReportStructure( id: string, patch: ReportStructurePatch, ): Promise { const body: Record = {}; if (patch.title !== undefined) body.title = patch.title; if (patch.name !== undefined) body.name = patch.name; if (patch.content !== undefined) body.content = patch.content; if (patch.structureMode !== undefined) body.structure_mode = normalizeReportStructureMode(patch.structureMode); if (patch.retrievalDirections !== undefined) { body.retrieval_directions = normalizeRetrievalDirections(patch.retrievalDirections); } if (patch.retrievalSkills !== undefined) { body.retrieval_skills = normalizeRetrievalSkills(patch.retrievalSkills); } const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); return toStructure(await readJson(res, "update report structure")); } export async function setReportStructureEnabled(id: string, enabled: boolean): Promise { const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}/enabled`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled }), }); return toStructure(await readJson(res, "toggle report structure")); } export async function deleteReportStructure(id: string): Promise { const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "DELETE" }); // 204 无响应体,不能再走 readJson 的 res.json()。 if (!res.ok) { const data = (await res.json().catch(() => null)) as { detail?: unknown } | null; throw new Error( data && typeof data.detail === "string" ? data.detail : `delete report structure failed (${res.status})`, ); } } // ── React Query hooks(工作流配置弹窗内各视图共用缓存) ────────────────────── const REPORT_STRUCTURES_KEY = "report-structures"; export function useReportStructures(params: { status?: ReportStructureStatusFilter; title?: string } = {}) { return useQuery({ queryKey: [REPORT_STRUCTURES_KEY, "list", params.status ?? "all", params.title ?? ""], queryFn: () => listReportStructures(params), placeholderData: keepPreviousData, refetchOnWindowFocus: false, }); } export function useReportStructureMutations() { const queryClient = useQueryClient(); const invalidate = () => queryClient.invalidateQueries({ queryKey: [REPORT_STRUCTURES_KEY] }); const create = useMutation({ mutationFn: (input: ReportStructureInput) => createReportStructure(input), onSuccess: invalidate, }); const update = useMutation({ mutationFn: ({ id, patch }: { id: string; patch: ReportStructurePatch }) => updateReportStructure(id, patch), onSuccess: invalidate, }); const toggleEnabled = useMutation({ mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) => setReportStructureEnabled(id, enabled), onSuccess: invalidate, }); const remove = useMutation({ mutationFn: (id: string) => deleteReportStructure(id), onSuccess: invalidate, }); return { create, update, toggleEnabled, remove }; }