Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
This commit is contained in:
commit
ce165ece69
13 files changed
+1142
-45
No files matched your search
@@ -27,7 +27,7 @@ VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
|
||||
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
|
||||
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
|
||||
VITE_AIPI_MOPECHAT_URL=https://ch1.b.uat.4.cn/likun_b1_mope
|
||||
VITE_AIPI_BACKENP_URL=http://localhost:8003
|
||||
VITE_AIPI_BACKENP_URL=http://47.88.25.99:8000
|
||||
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
|
||||
# 工作室/空间前端地址(用于 auth/callback 等跳转)
|
||||
# VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { getBackendBaseURL } from '@/core/config';
|
||||
import { apiFetch } from '@/core/api';
|
||||
|
||||
/** 课题研究模板:一组写作表单预设(需求 0616 #5)。 */
|
||||
export interface ResearchTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
/** 引用的文章类型 key(对应 ArticleType.key);null = 不设。 */
|
||||
article_type_key: string | null;
|
||||
outline: string | null;
|
||||
material_source: 'general' | 'notebook';
|
||||
word_count: number;
|
||||
audience: string | null;
|
||||
strict_mode: boolean;
|
||||
topic: string | null;
|
||||
sort_order: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreateResearchTemplateRequest {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
article_type_key?: string | null;
|
||||
outline?: string | null;
|
||||
material_source?: 'general' | 'notebook';
|
||||
word_count?: number;
|
||||
audience?: string | null;
|
||||
strict_mode?: boolean;
|
||||
topic?: string | null;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export type UpdateResearchTemplateRequest = Partial<CreateResearchTemplateRequest>;
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/ai-writing/research-templates`;
|
||||
|
||||
export async function listResearchTemplates(): Promise<ResearchTemplate[]> {
|
||||
const resp = await apiFetch(BASE());
|
||||
if (!resp.ok) throw new Error(`获取研究模板失败: ${resp.status}`);
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
export async function createResearchTemplate(
|
||||
data: CreateResearchTemplateRequest,
|
||||
): Promise<ResearchTemplate> {
|
||||
const resp = await apiFetch(BASE(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`创建研究模板失败: ${resp.status}`);
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
export async function updateResearchTemplate(
|
||||
id: string,
|
||||
data: UpdateResearchTemplateRequest,
|
||||
): Promise<ResearchTemplate> {
|
||||
const resp = await apiFetch(`${BASE()}/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (resp.status === 404) throw new Error(`研究模板不存在`);
|
||||
if (!resp.ok) throw new Error(`更新研究模板失败: ${resp.status}`);
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
export async function deleteResearchTemplate(id: string): Promise<void> {
|
||||
const resp = await apiFetch(`${BASE()}/${id}`, { method: 'DELETE' });
|
||||
if (resp.status === 404) throw new Error(`研究模板不存在`);
|
||||
if (!resp.ok) throw new Error(`删除研究模板失败: ${resp.status}`);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { BookOpen, FileText, LayoutGrid, Loader2, Plus } from "lucide-react";
|
||||
import { BookOpen, FileText, LayoutGrid, Loader2, Plus, Settings2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -16,15 +17,17 @@ import { createSearchSpace } from "@/core/studio/api";
|
||||
import { useStudioNotebooks } from "@/core/studio/hooks";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { useArticleTypes } from "../../hooks/useArticleTypes";
|
||||
import { useResearchTemplates } from "../../hooks/useResearchTemplates";
|
||||
import type { ResearchTemplate } from "../../api/ai-writing-research-templates";
|
||||
import { useWritingForm } from "../../contexts/WritingFormContext";
|
||||
import { useAIWriting } from "../../contexts/AIWritingContext";
|
||||
|
||||
/**
|
||||
* 课题研究左栏(需求 0616 #5)。
|
||||
* - 上半「研究模板」= 文章类型(``useArticleTypes``);点击预填表单(设置文章类型 +
|
||||
* 默认字数 + 展开写作配置),沿用现有 articleType 设置逻辑。
|
||||
* - 下半「笔记本」= 我的空间(``useStudioNotebooks``);点击设为当前课题研究的素材来源
|
||||
* (materialSource='notebook' + 选中该本)。
|
||||
* - 上半「研究模板」= 研究模板实体(``useResearchTemplates``);点击一键预填整张写作表单
|
||||
* (文章类型 / 大纲 / 搜索来源 / 字数 / 受众 / 严格模式 / 主题)并展开配置。顶部「配置」
|
||||
* 入口进入模板配置页维护这些模板。
|
||||
* - 下半「笔记本」= 我的空间(``useStudioNotebooks``);点击在右侧内嵌打开该笔记本页。
|
||||
*/
|
||||
export function ResearchSidebar({
|
||||
viewingNotebookId,
|
||||
@@ -38,14 +41,25 @@ export function ResearchSidebar({
|
||||
/** 点击「所有空间」→ 在右侧内嵌打开空间列表页。 */
|
||||
onOpenAllSpaces: () => void;
|
||||
}) {
|
||||
const { articleTypes, refresh } = useArticleTypes();
|
||||
const navigate = useNavigate();
|
||||
const { templates, refresh } = useResearchTemplates();
|
||||
const { startWriting } = useAIWriting();
|
||||
const {
|
||||
notebooks,
|
||||
isLoading: notebooksLoading,
|
||||
isError: notebooksError,
|
||||
} = useStudioNotebooks();
|
||||
const { articleType, setArticleType, setWordCountInput, setFormExpanded } =
|
||||
useWritingForm();
|
||||
const {
|
||||
setIntent,
|
||||
setArticleType,
|
||||
setOutlineText,
|
||||
setShowOutline,
|
||||
setMaterialSource,
|
||||
setWordCountInput,
|
||||
setAudience,
|
||||
setStrictMode,
|
||||
setFormExpanded,
|
||||
} = useWritingForm();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// 新建空间弹窗(与 workspace-nav-studio 同款)。
|
||||
@@ -78,50 +92,86 @@ export function ResearchSidebar({
|
||||
}
|
||||
};
|
||||
|
||||
const handleTemplateClick = (key: string, defaultWordCount: number) => {
|
||||
setArticleType(key);
|
||||
if (defaultWordCount > 0) setWordCountInput(String(defaultWordCount));
|
||||
// 点击研究模板 → ①回填整张写作表单(保持写作态左栏显示与运行配置一致)
|
||||
// ②直接以模板预设进入 AI 写作流程(startWriting)。
|
||||
const handleTemplateClick = (tpl: ResearchTemplate) => {
|
||||
const intent = tpl.topic?.trim() ?? "";
|
||||
const articleType = tpl.article_type_key || "analysis";
|
||||
const outline = tpl.outline?.trim() || "";
|
||||
const audience = tpl.audience?.trim() || "普通读者";
|
||||
const wordCount = tpl.word_count > 0 ? tpl.word_count : 800;
|
||||
const writingMode = tpl.strict_mode ? "strict" : "loose";
|
||||
|
||||
// 回填表单上下文(写作态左栏据此展示)。
|
||||
if (intent) setIntent(intent);
|
||||
if (tpl.article_type_key) setArticleType(tpl.article_type_key);
|
||||
if (outline) {
|
||||
setOutlineText(outline);
|
||||
setShowOutline(true);
|
||||
}
|
||||
setMaterialSource(tpl.material_source);
|
||||
setWordCountInput(String(wordCount));
|
||||
if (tpl.audience?.trim()) setAudience(audience);
|
||||
setStrictMode(tpl.strict_mode);
|
||||
setFormExpanded(true);
|
||||
|
||||
// 无主题/意图无法发起写作 → 仅回填表单,由用户补充后手动开始。
|
||||
if (!intent) return;
|
||||
void startWriting({
|
||||
userIntent: intent,
|
||||
userOutline: outline || undefined,
|
||||
articleType,
|
||||
targetAudience: audience,
|
||||
wordCountTarget: wordCount,
|
||||
keywordCount: 1,
|
||||
writingMode,
|
||||
materialSource: tpl.material_source,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-64 shrink-0 flex-col overflow-hidden border-r border-border/70 bg-card/60 backdrop-blur-sm">
|
||||
{/* 上半:研究模板(文章类型) */}
|
||||
{/* 上半:研究模板 */}
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 py-3">
|
||||
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
|
||||
研究模板
|
||||
</h2>
|
||||
{articleTypes.length === 0 ? (
|
||||
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无研究模板</p>
|
||||
<div className="px-2 mb-1.5 flex items-center justify-between">
|
||||
<h2 className="text-muted-foreground/70 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
|
||||
研究模板
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate("/page/canvas/research-templates")}
|
||||
title="配置研究模板"
|
||||
aria-label="配置研究模板"
|
||||
className="text-muted-foreground/70 hover:text-foreground rounded p-0.5 transition-colors"
|
||||
>
|
||||
<Settings2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{templates.length === 0 ? (
|
||||
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">
|
||||
暂无研究模板,点右上角配置
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{articleTypes.map((t) => {
|
||||
const active = articleType === t.key;
|
||||
return (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => handleTemplateClick(t.key, t.default_word_count)}
|
||||
title={t.description ?? t.label}
|
||||
className={cn(
|
||||
"flex items-start gap-2 rounded-lg px-2.5 py-1.5 text-left transition-colors",
|
||||
active
|
||||
? "bg-primary/10 text-primary"
|
||||
: "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
|
||||
{templates.map((tpl) => (
|
||||
<button
|
||||
key={tpl.id}
|
||||
type="button"
|
||||
onClick={() => handleTemplateClick(tpl)}
|
||||
title={tpl.description ?? tpl.name}
|
||||
className="flex items-start gap-2 rounded-lg px-2.5 py-1.5 text-left text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
|
||||
>
|
||||
<FileText className="mt-0.5 size-3.5 shrink-0 text-muted-foreground/70" />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-[13px] font-medium">{tpl.name}</span>
|
||||
{tpl.description && (
|
||||
<span className="text-muted-foreground/70 line-clamp-1 block text-[11px]">
|
||||
{tpl.description}
|
||||
</span>
|
||||
)}
|
||||
>
|
||||
<FileText className="mt-0.5 size-3.5 shrink-0 text-muted-foreground/70" />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-[13px] font-medium">{t.label}</span>
|
||||
{t.description && (
|
||||
<span className="text-muted-foreground/70 line-clamp-1 block text-[11px]">
|
||||
{t.description}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import {
|
||||
createResearchTemplate,
|
||||
deleteResearchTemplate,
|
||||
listResearchTemplates,
|
||||
updateResearchTemplate,
|
||||
} from '../api/ai-writing-research-templates';
|
||||
import type {
|
||||
CreateResearchTemplateRequest,
|
||||
ResearchTemplate,
|
||||
UpdateResearchTemplateRequest,
|
||||
} from '../api/ai-writing-research-templates';
|
||||
|
||||
export function useResearchTemplates() {
|
||||
const [templates, setTemplates] = useState<ResearchTemplate[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
setTemplates(await listResearchTemplates());
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const create = useCallback(
|
||||
async (data: CreateResearchTemplateRequest): Promise<ResearchTemplate> => {
|
||||
const created = await createResearchTemplate(data);
|
||||
setTemplates((prev) =>
|
||||
[...prev, created].sort((a, b) => a.sort_order - b.sort_order),
|
||||
);
|
||||
return created;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const update = useCallback(
|
||||
async (id: string, data: UpdateResearchTemplateRequest): Promise<ResearchTemplate> => {
|
||||
const updated = await updateResearchTemplate(id, data);
|
||||
setTemplates((prev) =>
|
||||
prev.map((t) => (t.id === id ? updated : t)).sort((a, b) => a.sort_order - b.sort_order),
|
||||
);
|
||||
return updated;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const remove = useCallback(async (id: string): Promise<void> => {
|
||||
await deleteResearchTemplate(id);
|
||||
setTemplates((prev) => prev.filter((t) => t.id !== id));
|
||||
}, []);
|
||||
|
||||
return { templates, loading, error, refresh, create, update, remove };
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ArrowLeft, FileText, Loader2, Pencil, Plus, Trash2 } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
import { useResearchTemplates } from '../hooks/useResearchTemplates';
|
||||
import { useArticleTypes } from '../hooks/useArticleTypes';
|
||||
import type {
|
||||
CreateResearchTemplateRequest,
|
||||
ResearchTemplate,
|
||||
} from '../api/ai-writing-research-templates';
|
||||
|
||||
const INPUT_CLASS =
|
||||
'flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm ' +
|
||||
'placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50';
|
||||
const TEXTAREA_CLASS =
|
||||
'flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm ' +
|
||||
'placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring resize-none';
|
||||
const LABEL_CLASS = 'mb-1 block text-xs font-medium text-muted-foreground';
|
||||
|
||||
interface FormState {
|
||||
name: string;
|
||||
description: string;
|
||||
article_type_key: string;
|
||||
outline: string;
|
||||
material_source: 'general' | 'notebook';
|
||||
word_count: string;
|
||||
audience: string;
|
||||
strict_mode: boolean;
|
||||
topic: string;
|
||||
sort_order: string;
|
||||
}
|
||||
|
||||
const EMPTY_FORM: FormState = {
|
||||
name: '',
|
||||
description: '',
|
||||
article_type_key: '',
|
||||
outline: '',
|
||||
material_source: 'general',
|
||||
word_count: '800',
|
||||
audience: '',
|
||||
strict_mode: false,
|
||||
topic: '',
|
||||
sort_order: '0',
|
||||
};
|
||||
|
||||
function toForm(t: ResearchTemplate): FormState {
|
||||
return {
|
||||
name: t.name,
|
||||
description: t.description ?? '',
|
||||
article_type_key: t.article_type_key ?? '',
|
||||
outline: t.outline ?? '',
|
||||
material_source: t.material_source,
|
||||
word_count: String(t.word_count),
|
||||
audience: t.audience ?? '',
|
||||
strict_mode: t.strict_mode,
|
||||
topic: t.topic ?? '',
|
||||
sort_order: String(t.sort_order),
|
||||
};
|
||||
}
|
||||
|
||||
function toPayload(form: FormState): CreateResearchTemplateRequest {
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
description: form.description.trim() || null,
|
||||
article_type_key: form.article_type_key || null,
|
||||
outline: form.outline.trim() || null,
|
||||
material_source: form.material_source,
|
||||
word_count: Math.max(100, parseInt(form.word_count, 10) || 800),
|
||||
audience: form.audience.trim() || null,
|
||||
strict_mode: form.strict_mode,
|
||||
topic: form.topic.trim() || null,
|
||||
sort_order: parseInt(form.sort_order, 10) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
export default function ResearchTemplatesConfigPage() {
|
||||
const navigate = useNavigate();
|
||||
const { templates, loading, error, refresh, create, update, remove } = useResearchTemplates();
|
||||
const { articleTypes, refresh: refreshTypes } = useArticleTypes();
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [form, setForm] = useState<FormState>(EMPTY_FORM);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
void refreshTypes();
|
||||
}, [refresh, refreshTypes]);
|
||||
|
||||
const set = <K extends keyof FormState>(key: K, value: FormState[K]) =>
|
||||
setForm((f) => ({ ...f, [key]: value }));
|
||||
|
||||
const openCreate = () => {
|
||||
setEditingId(null);
|
||||
setForm(EMPTY_FORM);
|
||||
setFormError(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (t: ResearchTemplate) => {
|
||||
setEditingId(t.id);
|
||||
setForm(toForm(t));
|
||||
setFormError(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.name.trim()) {
|
||||
setFormError('请填写模板名称');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setFormError(null);
|
||||
try {
|
||||
const payload = toPayload(form);
|
||||
if (editingId) await update(editingId, payload);
|
||||
else await create(payload);
|
||||
setDialogOpen(false);
|
||||
} catch (e) {
|
||||
setFormError(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTargetId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await remove(deleteTargetId);
|
||||
setDeleteTargetId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const articleTypeLabel = (key: string | null) =>
|
||||
key ? articleTypes.find((t) => t.key === key)?.label ?? key : '—';
|
||||
|
||||
return (
|
||||
<div className="mx-auto h-full w-full max-w-4xl overflow-y-auto p-6">
|
||||
<div className="mb-5 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="icon-sm" onClick={() => navigate(-1)}>
|
||||
<ArrowLeft className="size-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold">研究模板配置</h1>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
配置课题研究左栏的研究模板;点击模板时一键预填写作表单。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
<Plus className="size-4" />
|
||||
新建模板
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && <p className="mb-3 text-sm text-destructive">{error}</p>}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Loader2 className="size-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
<p className="py-16 text-center text-sm text-muted-foreground">
|
||||
暂无研究模板,点击右上角「新建模板」创建。
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{templates.map((t) => (
|
||||
<div
|
||||
key={t.id}
|
||||
className="flex items-start gap-3 rounded-xl border border-border bg-card p-4"
|
||||
>
|
||||
<div className="bg-primary/10 text-primary mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<FileText className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold">{t.name}</span>
|
||||
<span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">
|
||||
{articleTypeLabel(t.article_type_key)}
|
||||
</span>
|
||||
</div>
|
||||
{t.description && (
|
||||
<p className="mt-0.5 line-clamp-1 text-xs text-muted-foreground">{t.description}</p>
|
||||
)}
|
||||
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground/80">
|
||||
<span>来源:{t.material_source === 'notebook' ? '我的空间' : '通用检索'}</span>
|
||||
<span>字数:{t.word_count}</span>
|
||||
{t.audience && <span>受众:{t.audience}</span>}
|
||||
<span>{t.strict_mode ? '严格模式' : '宽松模式'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button variant="ghost" size="icon-sm" onClick={() => openEdit(t)} title="编辑">
|
||||
<Pencil className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setDeleteTargetId(t.id)}
|
||||
title="删除"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 新建 / 编辑 弹窗 */}
|
||||
<Dialog open={dialogOpen} onOpenChange={(v) => !saving && setDialogOpen(v)}>
|
||||
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-[640px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? '编辑研究模板' : '新建研究模板'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="grid grid-cols-2 gap-4 py-2">
|
||||
<div className="col-span-2">
|
||||
<label className={LABEL_CLASS}>模板名称 *</label>
|
||||
<input
|
||||
className={INPUT_CLASS}
|
||||
value={form.name}
|
||||
onChange={(e) => set('name', e.target.value)}
|
||||
placeholder="如:深度舆情分析"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className={LABEL_CLASS}>描述</label>
|
||||
<input
|
||||
className={INPUT_CLASS}
|
||||
value={form.description}
|
||||
onChange={(e) => set('description', e.target.value)}
|
||||
placeholder="模板用途简述"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={LABEL_CLASS}>文章类型</label>
|
||||
<select
|
||||
className={INPUT_CLASS}
|
||||
value={form.article_type_key}
|
||||
onChange={(e) => set('article_type_key', e.target.value)}
|
||||
>
|
||||
<option value="">不设</option>
|
||||
{articleTypes.map((t) => (
|
||||
<option key={t.key} value={t.key}>
|
||||
{t.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={LABEL_CLASS}>搜索来源</label>
|
||||
<select
|
||||
className={INPUT_CLASS}
|
||||
value={form.material_source}
|
||||
onChange={(e) => set('material_source', e.target.value as 'general' | 'notebook')}
|
||||
>
|
||||
<option value="general">通用检索</option>
|
||||
<option value="notebook">我的空间(笔记本)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={LABEL_CLASS}>目标字数</label>
|
||||
<input
|
||||
type="number"
|
||||
className={INPUT_CLASS}
|
||||
value={form.word_count}
|
||||
onChange={(e) => set('word_count', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={LABEL_CLASS}>目标受众</label>
|
||||
<input
|
||||
className={INPUT_CLASS}
|
||||
value={form.audience}
|
||||
onChange={(e) => set('audience', e.target.value)}
|
||||
placeholder="如:决策者"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className={LABEL_CLASS}>主题 / 意图</label>
|
||||
<textarea
|
||||
className={TEXTAREA_CLASS}
|
||||
rows={2}
|
||||
value={form.topic}
|
||||
onChange={(e) => set('topic', e.target.value)}
|
||||
placeholder="点击模板时预填到写作意图输入框"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className={LABEL_CLASS}>默认大纲</label>
|
||||
<textarea
|
||||
className={TEXTAREA_CLASS}
|
||||
rows={4}
|
||||
value={form.outline}
|
||||
onChange={(e) => set('outline', e.target.value)}
|
||||
placeholder={'一、…\n二、…\n三、…'}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="rt-strict"
|
||||
type="checkbox"
|
||||
checked={form.strict_mode}
|
||||
onChange={(e) => set('strict_mode', e.target.checked)}
|
||||
className="size-4"
|
||||
/>
|
||||
<label htmlFor="rt-strict" className="text-sm">
|
||||
严格写作模式
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label className={LABEL_CLASS}>排序(小在前)</label>
|
||||
<input
|
||||
type="number"
|
||||
className={INPUT_CLASS}
|
||||
value={form.sort_order}
|
||||
onChange={(e) => set('sort_order', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{formError && <p className="text-sm text-destructive">{formError}</p>}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDialogOpen(false)} disabled={saving}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={() => void handleSave()} disabled={saving}>
|
||||
{saving && <Loader2 className="size-4 animate-spin" />}
|
||||
保存
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 删除确认 */}
|
||||
<Dialog open={!!deleteTargetId} onOpenChange={(v) => !deleting && !v && setDeleteTargetId(null)}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>删除研究模板</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="py-2 text-sm text-muted-foreground">确定删除该研究模板吗?此操作不可恢复。</p>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleteTargetId(null)} disabled={deleting}>
|
||||
取消
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={() => void handleDelete()} disabled={deleting}>
|
||||
{deleting && <Loader2 className="size-4 animate-spin" />}
|
||||
删除
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import CanvasHomePage from "../pages/CanvasHomePage";
|
||||
import CanvasThreadPage from "../pages/CanvasThreadPage";
|
||||
import AIWritingPage from "../pages/AIWritingPage";
|
||||
import ArticleTypesConfigPage from "../pages/ArticleTypesConfigPage";
|
||||
import ResearchTemplatesConfigPage from "../pages/ResearchTemplatesConfigPage";
|
||||
|
||||
export default function OpenCanvasRoutes() {
|
||||
return (
|
||||
@@ -11,6 +12,7 @@ export default function OpenCanvasRoutes() {
|
||||
<Route index element={<CanvasHomePage />} />
|
||||
<Route path="ai-writing" element={<AIWritingPage hideAdvancedFields />} />
|
||||
<Route path="article-types" element={<ArticleTypesConfigPage />} />
|
||||
<Route path="research-templates" element={<ResearchTemplatesConfigPage />} />
|
||||
<Route path=":thread_id" element={<CanvasThreadPage />} />
|
||||
</Routes>
|
||||
);
|
||||
|
||||
@@ -168,6 +168,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
app.state.article_type_store = make_article_type_store(sf)
|
||||
|
||||
from deerflow.persistence.research_templates import make_research_template_store
|
||||
|
||||
app.state.research_template_store = make_research_template_store(sf)
|
||||
|
||||
from deerflow.persistence.memory_config import make_user_memory_config_store
|
||||
|
||||
app.state.memory_config_store = make_user_memory_config_store(sf)
|
||||
@@ -423,6 +427,11 @@ def get_article_type_store(request: Request):
|
||||
return getattr(request.app.state, "article_type_store", None)
|
||||
|
||||
|
||||
def get_research_template_store(request: Request):
|
||||
"""Return the research template store, or None when not configured."""
|
||||
return getattr(request.app.state, "research_template_store", None)
|
||||
|
||||
|
||||
def get_memory_config_store(request: Request):
|
||||
"""Return the per-user memory config store."""
|
||||
val = getattr(request.app.state, "memory_config_store", None)
|
||||
|
||||
@@ -90,6 +90,48 @@ class ArticleTypeResponse(BaseModel):
|
||||
updated_at: str
|
||||
|
||||
|
||||
class ResearchTemplateRequest(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
article_type_key: Optional[str] = None
|
||||
outline: Optional[str] = None
|
||||
material_source: str = "general"
|
||||
word_count: int = 800
|
||||
audience: Optional[str] = None
|
||||
strict_mode: bool = False
|
||||
topic: Optional[str] = None
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class UpdateResearchTemplateRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
article_type_key: Optional[str] = None
|
||||
outline: Optional[str] = None
|
||||
material_source: Optional[str] = None
|
||||
word_count: Optional[int] = None
|
||||
audience: Optional[str] = None
|
||||
strict_mode: Optional[bool] = None
|
||||
topic: Optional[str] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class ResearchTemplateResponse(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
article_type_key: Optional[str] = None
|
||||
outline: Optional[str] = None
|
||||
material_source: str
|
||||
word_count: int
|
||||
audience: Optional[str] = None
|
||||
strict_mode: bool
|
||||
topic: Optional[str] = None
|
||||
sort_order: int
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
id: str
|
||||
user_id: Optional[str] = None
|
||||
@@ -268,6 +310,94 @@ async def delete_article_type(article_type_id: str, request: Request):
|
||||
return {"success": True}
|
||||
|
||||
|
||||
# ── 研究模板(课题研究左栏一键预填表单,需求 0616 #5)────────────────────────────
|
||||
|
||||
|
||||
@router.get("/research-templates", response_model=list[ResearchTemplateResponse])
|
||||
async def list_research_templates(request: Request):
|
||||
"""列出所有研究模板,按 sort_order 升序。
|
||||
|
||||
新机器/空表时自动写入内置范例模板(网摘/周报/要讯),幂等仅在表为空时执行。
|
||||
"""
|
||||
from app.gateway.deps import get_research_template_store
|
||||
|
||||
store = get_research_template_store(request)
|
||||
if store is None:
|
||||
return []
|
||||
try:
|
||||
await store.seed_defaults()
|
||||
except Exception:
|
||||
logger.exception("ai_writing: failed to seed default research templates")
|
||||
return await store.list()
|
||||
|
||||
|
||||
@router.post("/research-templates", response_model=ResearchTemplateResponse, status_code=201)
|
||||
async def create_research_template(body: ResearchTemplateRequest, request: Request):
|
||||
"""新增研究模板。"""
|
||||
from app.gateway.deps import get_research_template_store
|
||||
|
||||
store = get_research_template_store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Research template store not available")
|
||||
return await store.create(
|
||||
name=body.name,
|
||||
description=body.description,
|
||||
article_type_key=body.article_type_key,
|
||||
outline=body.outline,
|
||||
material_source=body.material_source,
|
||||
word_count=body.word_count,
|
||||
audience=body.audience,
|
||||
strict_mode=body.strict_mode,
|
||||
topic=body.topic,
|
||||
sort_order=body.sort_order,
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/research-templates/{template_id}", response_model=ResearchTemplateResponse)
|
||||
async def update_research_template(template_id: str, body: UpdateResearchTemplateRequest, request: Request):
|
||||
"""更新研究模板字段(只传需要修改的字段)。"""
|
||||
from app.gateway.deps import get_research_template_store
|
||||
|
||||
store = get_research_template_store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Research template store not available")
|
||||
|
||||
kwargs = {}
|
||||
for field in (
|
||||
"name",
|
||||
"description",
|
||||
"article_type_key",
|
||||
"outline",
|
||||
"material_source",
|
||||
"word_count",
|
||||
"audience",
|
||||
"strict_mode",
|
||||
"topic",
|
||||
"sort_order",
|
||||
):
|
||||
val = getattr(body, field)
|
||||
if val is not None:
|
||||
kwargs[field] = val
|
||||
|
||||
updated = await store.update(template_id, **kwargs)
|
||||
if updated is None:
|
||||
raise HTTPException(status_code=404, detail="Research template not found")
|
||||
return updated
|
||||
|
||||
|
||||
@router.delete("/research-templates/{template_id}")
|
||||
async def delete_research_template(template_id: str, request: Request):
|
||||
"""删除研究模板。"""
|
||||
from app.gateway.deps import get_research_template_store
|
||||
|
||||
store = get_research_template_store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Research template store not available")
|
||||
deleted = await store.delete(template_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="Research template not found")
|
||||
return {"success": True}
|
||||
|
||||
|
||||
# ── 管理接口 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
+2
@@ -42,6 +42,7 @@ from deerflow.persistence.models.run_event import RunEventRow
|
||||
from deerflow.persistence.notifications.model import NotificationRow
|
||||
from deerflow.persistence.parallel_agent_tasks.model import ParallelAgentTaskRow
|
||||
from deerflow.persistence.recommended_questions.model import RecommendedQuestionRow
|
||||
from deerflow.persistence.research_templates.model import ResearchTemplateRow
|
||||
from deerflow.persistence.roundtable_chains.model import RoundtableChainRow
|
||||
from deerflow.persistence.roundtable_draft_shares.model import RoundtableDraftShareRow
|
||||
from deerflow.persistence.roundtable_drafts.model import (
|
||||
@@ -89,6 +90,7 @@ __all__ = [
|
||||
"NotificationRow",
|
||||
"ParallelAgentTaskRow",
|
||||
"RecommendedQuestionRow",
|
||||
"ResearchTemplateRow",
|
||||
"RoundtableChainRow",
|
||||
"RoundtableDraftRow",
|
||||
"RoundtableDraftShareRow",
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
from deerflow.persistence.research_templates.model import ResearchTemplateRow
|
||||
from deerflow.persistence.research_templates.sql import ResearchTemplateRepository
|
||||
|
||||
|
||||
def make_research_template_store(session_factory) -> ResearchTemplateRepository | None:
|
||||
if session_factory is None:
|
||||
return None
|
||||
return ResearchTemplateRepository(session_factory)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ResearchTemplateRow",
|
||||
"ResearchTemplateRepository",
|
||||
"make_research_template_store",
|
||||
]
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""ORM model for AI writing research templates (课题研究模板).
|
||||
|
||||
A research template bundles a set of writing-form presets — article type,
|
||||
outline, material source, word count, audience, strict mode and a topic/intent —
|
||||
so a user can one-click pre-fill the whole 课题研究 form. Maintained from the
|
||||
research-template config page (需求 0616 #5).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
|
||||
|
||||
class ResearchTemplateRow(Base):
|
||||
__tablename__ = "ai_writing_research_templates"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
# 预设字段(点击模板时回填表单)。
|
||||
article_type_key: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
outline: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
material_source: Mapped[str] = mapped_column(String(32), nullable=False, default="general")
|
||||
word_count: Mapped[int] = mapped_column(Integer, nullable=False, default=800)
|
||||
audience: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
strict_mode: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
topic: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
"""SQLAlchemy-backed research template storage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.research_templates.model import ResearchTemplateRow
|
||||
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
# 新机器内置范例模板(表为空时由 seed_defaults() 写入;作为给用户的范例,内容务求规范好用)。
|
||||
# article_type_key 取自默认文章类型(news/analysis/feature/report,见 20260517_02 迁移)。
|
||||
DEFAULT_RESEARCH_TEMPLATES: list[dict] = [
|
||||
{
|
||||
"name": "网摘",
|
||||
"description": "汇编近期网络热点信息,分条摘录核心要点并标注来源,快速掌握全貌",
|
||||
"article_type_key": "news",
|
||||
"material_source": "general",
|
||||
"word_count": 1000,
|
||||
"audience": "关注热点动态的一般读者",
|
||||
"strict_mode": False,
|
||||
"topic": (
|
||||
"围绕【主题】检索并汇编近一周网络上的重要信息与热点动态,"
|
||||
"逐条摘录核心事实、关键数据与原文出处,帮助读者快速掌握全貌。"
|
||||
),
|
||||
"outline": (
|
||||
"一、热点速览(用一句话清单列出本期要点)\n"
|
||||
"二、重点摘录\n"
|
||||
" 1.【事件/话题标题】——核心事实、关键数据、信息来源\n"
|
||||
" 2.【事件/话题标题】——……\n"
|
||||
" 3.(按重要性依次罗列)\n"
|
||||
"三、关联动态与背景补充(串联相关信息、补足来龙去脉)\n"
|
||||
"四、小结与观察(提炼趋势或值得关注的看点)"
|
||||
),
|
||||
"sort_order": 0,
|
||||
},
|
||||
{
|
||||
"name": "周报",
|
||||
"description": "按周梳理工作进展、数据指标与问题风险,输出结构化周度汇报",
|
||||
"article_type_key": "report",
|
||||
"material_source": "general",
|
||||
"word_count": 1200,
|
||||
"audience": "团队成员与上级主管",
|
||||
"strict_mode": True,
|
||||
"topic": (
|
||||
"汇总本周【项目/团队】的工作进展,撰写周报:"
|
||||
"覆盖关键成果、数据指标、问题风险与下周计划,简明、客观、可量化。"
|
||||
),
|
||||
"outline": (
|
||||
"一、本周概览(一句话总结 + 关键指标对比上周)\n"
|
||||
"二、重点进展\n"
|
||||
" 1. 已完成事项与成果(结论先行,附支撑数据)\n"
|
||||
" 2. 关键数据 / 里程碑达成情况\n"
|
||||
"三、问题与风险(逐条列出问题、影响面及应对措施)\n"
|
||||
"四、下周计划与资源需求(目标、负责人、所需支持)"
|
||||
),
|
||||
"sort_order": 1,
|
||||
},
|
||||
{
|
||||
"name": "要讯",
|
||||
"description": "提炼最重要的资讯,精炼成简报式要点,突出核心事实与潜在影响",
|
||||
"article_type_key": "analysis",
|
||||
"material_source": "general",
|
||||
"word_count": 600,
|
||||
"audience": "需快速掌握要点的决策者",
|
||||
"strict_mode": True,
|
||||
"topic": (
|
||||
"围绕【主题/领域】提炼近期最重要的资讯,编写要讯:"
|
||||
"每条聚焦核心事实、关键背景与潜在影响,文字精炼、判断审慎。"
|
||||
),
|
||||
"outline": (
|
||||
"一、头条要讯(1–3 条,每条用一句话点明核心)\n"
|
||||
"二、要点详述(逐条展开)\n"
|
||||
" · 事实:发生了什么、何时何地、涉及谁\n"
|
||||
" · 背景:为何重要、与既有态势的关系\n"
|
||||
" · 影响:可能带来的后果与连锁反应\n"
|
||||
"三、研判与建议(给出倾向性判断与可行动建议)"
|
||||
),
|
||||
"sort_order": 2,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class ResearchTemplateRepository:
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
@staticmethod
|
||||
def _row_to_dict(row: ResearchTemplateRow) -> dict:
|
||||
d = row.to_dict()
|
||||
for k in ("created_at", "updated_at"):
|
||||
if isinstance(d.get(k), datetime):
|
||||
d[k] = d[k].isoformat()
|
||||
return d
|
||||
|
||||
async def create(
|
||||
self,
|
||||
*,
|
||||
name: str,
|
||||
description: str | None = None,
|
||||
article_type_key: str | None = None,
|
||||
outline: str | None = None,
|
||||
material_source: str = "general",
|
||||
word_count: int = 800,
|
||||
audience: str | None = None,
|
||||
strict_mode: bool = False,
|
||||
topic: str | None = None,
|
||||
sort_order: int = 0,
|
||||
) -> dict:
|
||||
now = datetime.now(UTC)
|
||||
row = ResearchTemplateRow(
|
||||
id=str(uuid.uuid4()),
|
||||
name=name,
|
||||
description=description,
|
||||
article_type_key=article_type_key,
|
||||
outline=outline,
|
||||
material_source=material_source,
|
||||
word_count=word_count,
|
||||
audience=audience,
|
||||
strict_mode=strict_mode,
|
||||
topic=topic,
|
||||
sort_order=sort_order,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self._sf() as session:
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return self._row_to_dict(row)
|
||||
|
||||
async def update(
|
||||
self,
|
||||
template_id: str,
|
||||
*,
|
||||
name=_UNSET,
|
||||
description=_UNSET,
|
||||
article_type_key=_UNSET,
|
||||
outline=_UNSET,
|
||||
material_source=_UNSET,
|
||||
word_count=_UNSET,
|
||||
audience=_UNSET,
|
||||
strict_mode=_UNSET,
|
||||
topic=_UNSET,
|
||||
sort_order=_UNSET,
|
||||
) -> dict | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(ResearchTemplateRow, template_id)
|
||||
if row is None:
|
||||
return None
|
||||
if name is not _UNSET:
|
||||
row.name = name
|
||||
if description is not _UNSET:
|
||||
row.description = description
|
||||
if article_type_key is not _UNSET:
|
||||
row.article_type_key = article_type_key
|
||||
if outline is not _UNSET:
|
||||
row.outline = outline
|
||||
if material_source is not _UNSET:
|
||||
row.material_source = material_source
|
||||
if word_count is not _UNSET:
|
||||
row.word_count = word_count
|
||||
if audience is not _UNSET:
|
||||
row.audience = audience
|
||||
if strict_mode is not _UNSET:
|
||||
row.strict_mode = strict_mode
|
||||
if topic is not _UNSET:
|
||||
row.topic = topic
|
||||
if sort_order is not _UNSET:
|
||||
row.sort_order = sort_order
|
||||
row.updated_at = datetime.now(UTC)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return self._row_to_dict(row)
|
||||
|
||||
async def get(self, template_id: str) -> dict | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(ResearchTemplateRow, template_id)
|
||||
if row is None:
|
||||
return None
|
||||
return self._row_to_dict(row)
|
||||
|
||||
async def list(self) -> list[dict]:
|
||||
stmt = select(ResearchTemplateRow).order_by(
|
||||
ResearchTemplateRow.sort_order.asc(), ResearchTemplateRow.created_at.asc()
|
||||
)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_dict(r) for r in result.scalars()]
|
||||
|
||||
async def delete(self, template_id: str) -> bool:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(ResearchTemplateRow, template_id)
|
||||
if row is None:
|
||||
return False
|
||||
await session.delete(row)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
async def seed_defaults(self) -> int:
|
||||
"""新机器/空表时写入内置范例模板(网摘/周报/要讯)。
|
||||
|
||||
幂等:仅当表为空时插入;已有任何模板则跳过(避免覆盖用户配置或重复播种)。
|
||||
返回插入条数。
|
||||
"""
|
||||
async with self._sf() as session:
|
||||
existing = await session.execute(select(ResearchTemplateRow.id).limit(1))
|
||||
if existing.first() is not None:
|
||||
return 0
|
||||
now = datetime.now(UTC)
|
||||
for t in DEFAULT_RESEARCH_TEMPLATES:
|
||||
session.add(
|
||||
ResearchTemplateRow(id=str(uuid.uuid4()), created_at=now, updated_at=now, **t)
|
||||
)
|
||||
await session.commit()
|
||||
return len(DEFAULT_RESEARCH_TEMPLATES)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Tests for the research-template store (课题研究模板,需求 0616 #5).
|
||||
|
||||
A research template bundles writing-form presets (article type / outline /
|
||||
material source / word count / audience / strict mode / topic) for one-click
|
||||
pre-fill. Covers create (with defaults) / list ordering / get / partial update /
|
||||
delete.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.research_templates import ResearchTemplateRepository
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def store(tmp_path):
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'rt.db'}")
|
||||
async with engine.begin() as conn:
|
||||
import deerflow.persistence.research_templates.model # noqa: F401
|
||||
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
sf = async_sessionmaker(engine, expire_on_commit=False)
|
||||
return ResearchTemplateRepository(sf)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_applies_defaults(store: ResearchTemplateRepository):
|
||||
row = await store.create(name="深度分析模板")
|
||||
assert row["name"] == "深度分析模板"
|
||||
assert row["material_source"] == "general"
|
||||
assert row["word_count"] == 800
|
||||
assert row["strict_mode"] is False
|
||||
assert row["article_type_key"] is None
|
||||
assert row["id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_full_then_get_roundtrips(store: ResearchTemplateRepository):
|
||||
created = await store.create(
|
||||
name="舆情研究",
|
||||
description="围绕舆情的研究模板",
|
||||
article_type_key="analysis",
|
||||
outline="一、背景\n二、分析\n三、结论",
|
||||
material_source="notebook",
|
||||
word_count=1500,
|
||||
audience="决策者",
|
||||
strict_mode=True,
|
||||
topic="某品牌近期舆情",
|
||||
sort_order=2,
|
||||
)
|
||||
fetched = await store.get(created["id"])
|
||||
assert fetched is not None
|
||||
assert fetched["article_type_key"] == "analysis"
|
||||
assert fetched["outline"].startswith("一、背景")
|
||||
assert fetched["material_source"] == "notebook"
|
||||
assert fetched["word_count"] == 1500
|
||||
assert fetched["audience"] == "决策者"
|
||||
assert fetched["strict_mode"] is True
|
||||
assert fetched["topic"] == "某品牌近期舆情"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_orders_by_sort_order(store: ResearchTemplateRepository):
|
||||
await store.create(name="B", sort_order=2)
|
||||
await store.create(name="A", sort_order=1)
|
||||
rows = await store.list()
|
||||
assert [r["name"] for r in rows] == ["A", "B"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_partial_keeps_other_fields(store: ResearchTemplateRepository):
|
||||
created = await store.create(name="模板", word_count=800, strict_mode=False)
|
||||
updated = await store.update(created["id"], word_count=2000, strict_mode=True)
|
||||
assert updated is not None
|
||||
assert updated["word_count"] == 2000
|
||||
assert updated["strict_mode"] is True
|
||||
assert updated["name"] == "模板" # untouched
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_missing_returns_none(store: ResearchTemplateRepository):
|
||||
assert await store.update("nope", name="x") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete(store: ResearchTemplateRepository):
|
||||
created = await store.create(name="待删")
|
||||
assert await store.delete(created["id"]) is True
|
||||
assert await store.get(created["id"]) is None
|
||||
assert await store.delete(created["id"]) is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seed_defaults_inserts_builtins_when_empty(store: ResearchTemplateRepository):
|
||||
inserted = await store.seed_defaults()
|
||||
assert inserted == 3
|
||||
rows = await store.list()
|
||||
names = [r["name"] for r in rows]
|
||||
assert names == ["网摘", "周报", "要讯"] # sort_order 0/1/2
|
||||
# 内置模板内容完整(范例质量)。
|
||||
by_name = {r["name"]: r for r in rows}
|
||||
assert by_name["网摘"]["article_type_key"] == "news"
|
||||
assert by_name["周报"]["strict_mode"] is True
|
||||
assert by_name["要讯"]["outline"]
|
||||
assert all(r["topic"] for r in rows)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seed_defaults_is_idempotent(store: ResearchTemplateRepository):
|
||||
assert await store.seed_defaults() == 3
|
||||
# 已有模板 → 再次播种跳过,不重复、不覆盖。
|
||||
assert await store.seed_defaults() == 0
|
||||
assert len(await store.list()) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seed_defaults_skips_when_user_has_templates(store: ResearchTemplateRepository):
|
||||
await store.create(name="用户自建")
|
||||
assert await store.seed_defaults() == 0
|
||||
assert [r["name"] for r in await store.list()] == ["用户自建"]
|
||||
Reference in new issue
Block a user