Merge branch 'dhk-1' into 'master'

fix(ai写作): 恢复内网直连检索(知识库检索)空地址回退默认端点

See merge request knowledge-base-bj/deerflow-server!154
This commit is contained in:
董宏凯 committed 2026-06-26 16:02:52 +00:00
commit 45315f18d2
10 files changed
+415 -123

No files matched your search

@@ -6,7 +6,8 @@ import { cn } from '@/lib/utils';
import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
export const STATUS_LABELS: Record<string, { label: string; color: string }> = {
in_progress: { label: '进行中', color: 'text-blue-500' },
// 刷新=重置后 in_progress 会话已无活进程,显示中性「未完成」而非「进行中」,避免歧义。
in_progress: { label: '未完成', color: 'text-slate-400' },
// 后台挂起中:后端正自动驱动到定稿(离页/刷新/切号不打断)。
background: { label: '挂起中', color: 'text-sky-500' },
draft_ready: { label: '草稿', color: 'text-amber-500' },
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ChevronsDown, CloudUpload, PanelRightClose, Play, Plus, RotateCcw, Settings2, Square, Trash2 } from 'lucide-react';
import { ChevronsDown, CloudUpload, PanelRightClose, Pause, Play, Plus, RotateCcw, Settings2, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
@@ -21,26 +21,17 @@ import {
adminCleanupAIWritingSessions,
getAIWritingSession,
suspendAIWritingToBackground,
suspendAIWritingToBackgroundKeepalive,
} from '../../api/ai-writing-sessions';
/**
* 暂停 / 继续功能开关(默认 false = 关)。
* 暂停 / 继续功能开关(现已开启)。
*
* 历史背景:legacy 路径下,为了让用户点"停止"后还能"继续",引入了 per-worker
* 内存 dict(``_event_queues`` / ``_session_pending_pause``)。多 worker 部署下
* 这些 dict 互相看不见 → SSE 重连失败 / "会话丢失" → 触发了整个 ai-writing-优化.md
* 的迁移计划。
*
* 当前 LangGraph Server 路径下架构已无 per-worker 状态,但 ``stream.stop()`` 仅
* 取消客户端 SSE 订阅,**不会真正暂停后端 run**(LLM 继续烧 token);``resume``
* 也无法重新订阅同一个 run。这是个产品语义没想清楚的功能,先关掉。
*
* 后期想清楚怎么做"真·暂停"(``client.runs.cancel(run_id, action='interrupt')``
* 保留 checkpoint)+ "真·继续"(``client.runs.joinStream`` 续上原 run)时,
* 把这个 flag 翻成 true 即可,UI / hook 全套代码都已就位。
* 真·暂停:``pauseWriting`` → ``stream.stop()`` 取消当前 run(LangGraph 已完成的阶段
* 已落 checkpoint,不丢)。真·继续:``resumeWriting`` → 带空 ``command:{}`` 重新 submit,
* 后端 worker 据此让 Pregel 从最近 checkpoint 续跑挂起的当前阶段节点(重跑当前未完成阶段,
* 已完成阶段不重来;见 runtime/runs/worker.py)。刷新页面 = 重置(不自动重连)。
*/
const ENABLE_PAUSE_RESUME_UI = false;
const ENABLE_PAUSE_RESUME_UI = true;
import { countArticleWords } from '../../utils/wordCount';
import { AIWritingForm } from './AIWritingForm';
import { AIWritingTimeline } from './AIWritingTimeline';
@@ -234,26 +225,10 @@ export function AIWritingPanel({
})();
}, [state.sessionId, reset, refresh, markBackground, clearBackground]);
// 离页 / 刷新 / 关标签页时,若写作仍在进行中则自动转后台(与圆桌「自动挂起」一致)。
// 用 ref 持有最新的「是否在跑 + 会话 id」,让卸载/卸载前回调读到即时值。
const suspendRef = useRef<{ running: boolean; sid: string | null }>({ running: false, sid: null });
useEffect(() => {
suspendRef.current = { running: isRunning, sid: state.sessionId ?? null };
}, [isRunning, state.sessionId]);
useEffect(() => {
const onBeforeUnload = () => {
const { running, sid } = suspendRef.current;
if (running && sid) suspendAIWritingToBackgroundKeepalive(sid);
};
window.addEventListener('beforeunload', onBeforeUnload);
return () => {
window.removeEventListener('beforeunload', onBeforeUnload);
// 组件卸载(路由离开本页 / 切换工作区标签):写作未完成则自动转后台。
const { running, sid } = suspendRef.current;
if (running && sid) suspendAIWritingToBackgroundKeepalive(sid);
};
}, []);
// 离页 / 刷新 = 重置(不自动重连、不自动转后台):刷新会断开 SSE,后端默认
// on_disconnect=cancel 取消该 run,页面重新挂载回到 idle。需要"后台自动跑完"
// (自动确认素材/大纲/审核到定稿、离页不中断)可手动点「后台挂起」。
// 页内的「暂停/继续」从 checkpoint 续跑当前阶段,不受刷新重置影响(刷新即新开)。
// ── 侧边栏"最近写作"通信:两种路径 ────────────────────────────────────────
// 用 ref 包住 handler,保证事件监听器始终能拿到最新版本
@@ -284,6 +259,16 @@ export function AIWritingPanel({
return () => window.removeEventListener('ai-writing:open-session', onOpenSession);
}, []);
// 路径4:左侧研究栏「历史记录」点「挂起中」记录 → 打开进度流程图弹窗(与下拉历史一致)。
useEffect(() => {
function onShowProgress(e: Event) {
const session = (e as CustomEvent<AIWritingSessionSummary>).detail;
if (session) setProgressSession(session);
}
window.addEventListener('ai-writing:show-progress', onShowProgress);
return () => window.removeEventListener('ai-writing:show-progress', onShowProgress);
}, []);
// 路径3:URL ?session=xxx 直接定位到指定会话
useEffect(() => {
const sessionId = searchParams.get('session');
@@ -374,8 +359,8 @@ export function AIWritingPanel({
后台挂起
</Button>
)}
{/* ⏸️/▶️ "停止 / 继续" 由 ENABLE_PAUSE_RESUME_UI 控制(默认 false 隐藏)。
后期把 flag 翻成 true 即可恢复,UI / hook 全套代码都已就位。 */}
{/* ⏸️/▶️ "暂停 / 继续":暂停=stream.stop() 取消当前 run(已完成阶段已落 checkpoint);
继续=从 checkpoint 重新驱动 graph 续跑(重跑当前阶段,已完成阶段不丢)。 */}
{ENABLE_PAUSE_RESUME_UI && isRunning && !state.isPaused && (
<Button
variant="ghost"
@@ -383,8 +368,8 @@ export function AIWritingPanel({
className="h-7 px-2 text-xs gap-1 animate-breathe-stop text-red-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30"
onClick={pauseWriting}
>
<Square className="size-3 fill-current" />
停止
<Pause className="size-3 fill-current" />
暂停
</Button>
)}
{ENABLE_PAUSE_RESUME_UI && state.isPaused && (
@@ -3,20 +3,26 @@
import {
BarChart3,
BookOpen,
Eye,
FileText,
Globe2,
History,
LayoutGrid,
Loader2,
Newspaper,
PanelLeftClose,
Pencil,
Plus,
RefreshCw,
Search,
Settings2,
SlidersHorizontal,
Sparkles,
Trash2,
TrendingUp,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
@@ -33,9 +39,13 @@ import { useStudioNotebooks } from "@/core/studio/hooks";
import { cn } from "@/lib/utils";
import { useResearchTemplates } from "../../hooks/useResearchTemplates";
import { useAIWritingSessions } from "../../hooks/useAIWritingSessions";
import type { ResearchTemplate } from "../../api/ai-writing-research-templates";
import type { AIWritingSessionSummary } from "../../api/ai-writing-sessions";
import { useWritingForm } from "../../contexts/WritingFormContext";
import { useAIWriting } from "../../contexts/AIWritingContext";
import { useAIWritingHistory } from "../../contexts/AIWritingHistoryContext";
import { formatRelative } from "./AIWritingHistoryDropdown";
type TemplateVisual = {
Icon: LucideIcon;
@@ -86,14 +96,145 @@ function getTemplateVisual(tpl: ResearchTemplate, index: number): TemplateVisual
return TEMPLATE_VISUALS[index % TEMPLATE_VISUALS.length];
}
// 历史记录状态药丸样式(对齐多智能体会商的历史记录观感)。
// 注:`in_progress` 不再转圈显示「进行中」——刷新=重置后这些会话已无任何活进程,
// 转圈会误导用户以为还在跑;统一显示为中性、不动的「未完成」。真正还在跑的是 `background`
// (后台挂起,有 AIWritingJobExecutor 驱动),保留「挂起中」转圈。
const WRITING_STATUS_PILL: Record<string, { label: string; className: string; spin?: boolean; dot?: boolean }> = {
in_progress: { label: "未完成", className: "text-slate-400" },
background: { label: "挂起中", className: "text-sky-500", spin: true },
draft_ready: { label: "草稿", className: "text-amber-500" },
review_ready: { label: "审核", className: "text-purple-500", dot: true },
done: { label: "完成", className: "text-emerald-500" },
error: { label: "出错", className: "text-rose-500" },
};
/** 单条历史记录项 —— 样式参考多智能体会商的 HistoryDropdown 列表项(圆角卡片 + 状态药丸 + 操作按钮)。 */
function WritingHistoryItem({
session,
isCurrent,
onSelect,
onShowProgress,
onDelete,
onRename,
}: {
session: AIWritingSessionSummary;
isCurrent: boolean;
onSelect: () => void;
onShowProgress?: () => void;
onDelete: () => void;
onRename: (title: string) => void;
}) {
const [renaming, setRenaming] = useState(false);
const [value, setValue] = useState(session.title);
const inputRef = useRef<HTMLInputElement>(null);
const isBackground = session.status === "background";
// 「挂起中」点击看进度(流程图弹窗),其余打开历史回看。
const open = isBackground && onShowProgress ? onShowProgress : onSelect;
const pill = WRITING_STATUS_PILL[session.status] ?? { label: session.status, className: "text-slate-400" };
useEffect(() => {
if (renaming) inputRef.current?.focus();
}, [renaming]);
const commit = () => {
const t = value.trim();
if (t && t !== session.title) onRename(t);
setRenaming(false);
};
return (
<li
className="px-3 py-2.5 transition-colors hover:bg-slate-50"
style={isCurrent ? { backgroundColor: "#ecfdf5" } : undefined}
>
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
{renaming ? (
<input
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
if (e.key === "Escape") {
setValue(session.title);
setRenaming(false);
}
}}
onBlur={commit}
className="w-full rounded border border-slate-300 px-2 py-1 text-[11.5px] font-semibold text-slate-800 outline-none focus:border-primary"
/>
) : (
<button
type="button"
onClick={open}
className="block w-full text-left"
title={isBackground ? "查看进度" : "打开历史"}
>
<span className="line-clamp-2 text-[11.5px] font-semibold leading-snug text-slate-800">
{session.title}
</span>
<span className="mt-0.5 flex items-center gap-1 font-mono text-[10px] text-slate-400">
<span className={cn("inline-flex items-center gap-1 font-semibold", pill.className)}>
{pill.spin && <Loader2 className="size-3 animate-spin" />}
{pill.dot && <span className="inline-block size-1.5 animate-pulse rounded-full bg-current" />}
{pill.label}
</span>
<span className="text-slate-300">·</span>
{formatRelative(session.updated_at)}
</span>
</button>
)}
</div>
{!renaming && (
<div className="flex shrink-0 items-center gap-0.5">
<button
type="button"
onClick={open}
title={isBackground ? "查看进度" : "打开"}
className="rounded p-1 text-slate-500 transition hover:bg-slate-100 hover:text-primary"
>
<Eye className="size-3.5" />
</button>
<button
type="button"
onClick={() => {
setValue(session.title);
setRenaming(true);
}}
title="重命名"
className="rounded p-1 text-slate-500 transition hover:bg-slate-100 hover:text-primary"
>
<Pencil className="size-3.5" />
</button>
<button
type="button"
onClick={onDelete}
title="删除"
className="rounded p-1 text-slate-500 transition hover:bg-rose-50 hover:text-rose-600"
>
<Trash2 className="size-3.5" />
</button>
</div>
)}
</div>
</li>
);
}
export function ResearchSidebar({
viewingNotebookId,
onOpenNotebook,
onOpenAllSpaces,
onCollapse,
}: {
viewingNotebookId?: number | null;
onOpenNotebook: (notebookId: number) => void;
onOpenAllSpaces: () => void;
/** 收起侧栏(由页面承载收起态)。 */
onCollapse?: () => void;
}) {
const navigate = useNavigate();
const { templates, refresh } = useResearchTemplates();
@@ -116,6 +257,31 @@ export function ResearchSidebar({
} = useWritingForm();
const queryClient = useQueryClient();
// 「历史记录」列表(左下角,样式参考多智能体会商的历史记录):自带一份会话列表,
// 点击打开「历史回看」(openHistory,全局共享上下文,打开后本侧栏随写作进入历史态而隐藏)。
const {
sessions,
loading: sessionsLoading,
refresh: refreshSessions,
rename: renameSession,
remove: removeSession,
} = useAIWritingSessions();
const { openHistory, historySession } = useAIWritingHistory();
// 进入/返回写作配置页时刷新一次历史(本侧栏仅在 idle 态挂载,故等同每次回到表单刷新)。
useEffect(() => {
void refreshSessions();
}, [refreshSessions]);
const handleSelectHistory = (session: AIWritingSessionSummary) => {
void openHistory(session);
};
// 「挂起中」记录:交给右侧面板打开进度流程图弹窗(沿用面板已有的 window 事件解耦模式,
// 与 ai-writing:open-session 一致),本侧栏不直接持有弹窗状态。
const handleShowProgress = (session: AIWritingSessionSummary) => {
window.dispatchEvent(new CustomEvent("ai-writing:show-progress", { detail: session }));
};
const [templateSearch, setTemplateSearch] = useState("");
const [createOpen, setCreateOpen] = useState(false);
const [name, setName] = useState("");
@@ -191,6 +357,20 @@ export function ResearchSidebar({
return (
<aside className="ai-research-sidebar flex h-full w-[320px] shrink-0 flex-col overflow-hidden border-r border-slate-100 bg-white text-slate-700 shadow-[1px_0_18px_rgba(15,23,42,0.03)]">
{onCollapse && (
<div className="flex shrink-0 items-center justify-between border-b border-slate-100 px-3 py-1.5">
<span className="text-[11px] font-semibold tracking-wide text-slate-400">课题研究</span>
<button
type="button"
onClick={onCollapse}
title="收起侧栏"
aria-label="收起侧栏"
className="rounded-md p-1 text-slate-400 transition-colors hover:bg-slate-50 hover:text-slate-700"
>
<PanelLeftClose className="size-4" />
</button>
</div>
)}
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden px-3 py-4">
<section className="mb-5">
<div className="mb-3 flex items-center justify-between gap-3 px-1">
@@ -276,7 +456,7 @@ export function ResearchSidebar({
)}
</section>
<section className="flex min-h-0 flex-1 flex-col border-t border-slate-100 pt-5">
<section className="flex flex-col border-t border-slate-100 pt-5">
<div className="mb-3 flex items-center justify-between px-2">
<h2 className="text-[15px] font-bold tracking-wide text-slate-400">
笔记本
@@ -373,6 +553,52 @@ export function ResearchSidebar({
</button>
</div>
</section>
{/* 「历史记录」列表(样式参考多智能体会商):跟随侧栏自然向下滚动、不固定在底部。
点击打开历史回看(显示到右侧区域),✏️/双击改名,🗑删除,「挂起中」点击看进度。 */}
<section className="border-t border-slate-100 pt-5">
<div className="mb-3 flex items-center justify-between px-2">
<h2 className="flex items-center gap-1.5 text-[15px] font-bold tracking-wide text-slate-400">
<History className="size-3.5 text-slate-400" />
历史记录
<span className="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] text-slate-400">
{sessions.length}
</span>
</h2>
<button
type="button"
onClick={() => void refreshSessions()}
title="刷新历史记录"
aria-label="刷新历史记录"
className={cn(
"rounded-md p-1 text-slate-400 transition-colors hover:bg-slate-50 hover:text-slate-600",
sessionsLoading && "animate-spin",
)}
>
<RefreshCw className="size-3.5" />
</button>
</div>
{sessions.length === 0 ? (
<p className="rounded-xl border border-dashed border-slate-200 px-3 py-5 text-center text-xs text-slate-400">
{sessionsLoading ? "加载中…" : "暂无历史记录,开始写作后自动保存到这里"}
</p>
) : (
<ul className="divide-y divide-slate-100 overflow-hidden rounded-xl border border-slate-200 bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)]">
{sessions.map((s) => (
<WritingHistoryItem
key={s.id}
session={s}
isCurrent={s.id === (historySession?.id ?? null)}
onSelect={() => handleSelectHistory(s)}
onShowProgress={() => handleShowProgress(s)}
onDelete={() => removeSession(s.id)}
onRename={(title) => renameSession(s.id, title)}
/>
))}
</ul>
)}
</section>
</div>
<Dialog open={createOpen} onOpenChange={(v) => !creating && setCreateOpen(v)}>
@@ -33,6 +33,8 @@ import {
type Action,
type AIWritingValues,
} from '../hooks/useAIWritingStream';
const WRITING_STREAM_MODE = ['values', 'updates', 'custom', 'messages-tuple'] as const;
import type {
AIWritingRequest,
AIWritingState,
@@ -155,7 +157,8 @@ const AIWritingStreamHost = memo(function AIWritingStreamHost({
client: getAPIClient(),
assistantId: 'ai_writing',
threadId,
reconnectOnMount: true,
// 刷新页面 = 重置:不在挂载时自动重连已有 run(避免刷新后接回旧会话)。
reconnectOnMount: false,
onCreated(meta) {
dispatchRef.current?.({ type: 'set_session', sessionId: meta.thread_id });
},
@@ -250,6 +253,8 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
const streamRef = useRef<AIWritingStreamApi | null>(null);
const seenInterruptRef = useRef<string | null>(null);
// 刷新页面 = 重置:不持久化、不自动重连。provider 重新挂载即回到 idle 初始态
// (刷新会断开 SSE,后端默认 on_disconnect=cancel 取消该 run,不留孤儿)。
const threadId = state.sessionId ?? undefined;
useEffect(() => {
@@ -306,7 +311,7 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
} as Partial<AIWritingValues>,
{
config: { configurable: { model_name: request.modelName ?? '' } } as Record<string, unknown>,
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
streamMode: [...WRITING_STREAM_MODE],
},
);
} catch (err) {
@@ -410,7 +415,7 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
const resumeModelName = state.request?.modelName;
await stream.submit(undefined, {
command: { resume: resumePayload },
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
streamMode: [...WRITING_STREAM_MODE],
...(resumeModelName ? { config: { configurable: { model_name: resumeModelName } } } : {}),
});
} catch (err) {
@@ -426,13 +431,44 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
state.status]);
const pauseWriting = useCallback(() => {
// 真停:取消当前 run(graph 已完成的阶段已落 checkpoint)。继续时从该 checkpoint 续跑。
void streamRef.current?.stop();
dispatch({ type: 'pause' });
}, []);
// 「继续」:清掉当前阶段流式缓冲后,从最近的 checkpoint 恢复 graph 续跑
// (会重跑当前未完成的阶段,已完成阶段不丢)。同时用于断网后 run 已死的兜底恢复。
//
// **关键**:必须带一个 `command`(哪怕是空对象),后端 worker 才会把它翻成
// `langgraph.types.Command` 让 Pregel **从最近 checkpoint 恢复**(与 4 个干预卡续跑同机制);
// 不带 command 时 worker 按 graph_input **起新一轮**=从图入口 intent 重跑(就是之前
// "暂停后继续又从识别意图开始" 的根因,见 runtime/runs/worker.py 注释)。空 Command
// 没有 interrupt 可消费 → Pregel 直接续跑 checkpoint 里挂起的当前阶段节点。
const resumeWriting = useCallback(() => {
dispatch({ type: 'resume_ui' });
}, []);
const stream = streamRef.current;
if (!stream) {
dispatch({ type: 'resume_ui' });
return;
}
dispatch({ type: 'clear_streaming' });
const resumeModelName = state.request?.modelName;
void (async () => {
try {
await stream.submit(undefined, {
command: {},
streamMode: [...WRITING_STREAM_MODE],
...(resumeModelName ? { config: { configurable: { model_name: resumeModelName } } } : {}),
});
} catch (err) {
const message = getStreamErrorMessage(err);
if (isThreadNotAccessibleError(message)) {
notifyThreadAccessChangedAndReload();
return;
}
dispatch({ type: 'set_error', message });
}
})();
}, [state.request]);
const reset = useCallback(() => {
void streamRef.current?.stop();
@@ -85,6 +85,8 @@ export type Action =
| { type: 'intervention_submitted'; record: CompletedIntervention; nextStatus: WritingStatus; pendingRevisionContext: AIWritingState['pendingRevisionContext'] }
| { type: 'pause' }
| { type: 'resume_ui' }
// 手动「继续」从检查点重跑当前阶段前,清空该阶段的流式缓冲(避免与重跑的新输出粘连)。
| { type: 'clear_streaming' }
| { type: 'reset' }
| { type: 'set_error'; message: string };
@@ -132,6 +134,18 @@ export function reducer(prev: AIWritingState, action: Action): AIWritingState {
case 'resume_ui':
return { ...prev, isPaused: false };
case 'clear_streaming':
// 「继续」重跑当前阶段:清掉各阶段流式缓冲,重跑的输出从干净状态累积。
return {
...prev,
isPaused: false,
intentStreamingText: '', intentThinkingText: '',
outlineStreamingText: '', outlineThinkingText: '',
streamingDraftSections: [], streamingDraftTitle: '',
streamingReviewItems: [],
skillSelectStreamingText: '', skillSelectThinkingText: '',
};
case 'reset':
return INITIAL_STATE;
@@ -82,7 +82,7 @@
* ──────────────────────────────────────────────────────────────────────────
*/
import { useRef, useState } from 'react';
import { ArrowLeft, PanelRightOpen } from 'lucide-react';
import { ArrowLeft, History, PanelLeftOpen, PanelRightOpen } from 'lucide-react';
import { TooltipProvider } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import type { GroupImperativeHandle } from 'react-resizable-panels';
@@ -237,19 +237,39 @@ function AIWritingBody({ hideAdvancedFields, initialNotebookId, initialDocumentI
const overlayActive = rightView != null;
const viewingNotebookId = rightView?.kind === 'notebook' ? rightView.id : null;
// 进入写作(开始生成 / 查看历史)后收起研究模板侧栏;嵌入态(studioToken)始终不展示。
const showSidebar = !studioToken && state.status === 'idle' && !isHistoryMode;
// 侧栏「收起」态:由页面承载,ResearchSidebar 顶部的收起按钮触发,收起后显示一条细窄展开条。
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
// 研究模板侧栏在「写作配置(idle)」与「历史回看」两态都展示(点历史记录后保留侧栏、
// 历史内容显示到右侧区域);写作进行中收起;嵌入态(studioToken)始终不展示。
const showSidebar = !studioToken && (state.status === 'idle' || isHistoryMode);
return (
<div className="flex-1 min-h-0 overflow-hidden flex">
{/* 需求 0616 #5:课题研究左栏(研究模板 + 笔记本)。进入写作后收起。 */}
{showSidebar && (
<ResearchSidebar
viewingNotebookId={viewingNotebookId}
onOpenNotebook={(id) => setRightView({ kind: 'notebook', id })}
onOpenAllSpaces={() => setRightView({ kind: 'allSpaces' })}
/>
)}
{/* 课题研究左栏(研究模板 + 笔记本 + 历史记录)。支持收起为细窄展开条。
写作配置(idle) 与 历史回看 两态都显示;写作进行中整体收起。 */}
{showSidebar &&
(sidebarCollapsed ? (
<div className="flex h-full w-11 shrink-0 flex-col items-center gap-2 border-r border-slate-100 bg-white py-3">
<button
type="button"
onClick={() => setSidebarCollapsed(false)}
title="展开侧栏"
aria-label="展开侧栏"
className="rounded-md p-1.5 text-slate-400 transition-colors hover:bg-slate-50 hover:text-slate-700"
>
<PanelLeftOpen className="size-4" />
</button>
<History className="size-4 text-slate-300" />
</div>
) : (
<ResearchSidebar
viewingNotebookId={viewingNotebookId}
onOpenNotebook={(id) => setRightView({ kind: 'notebook', id })}
onOpenAllSpaces={() => setRightView({ kind: 'allSpaces' })}
onCollapse={() => setSidebarCollapsed(true)}
/>
))}
{/* 右侧:写作布局常驻(仅 display:none 隐藏,避免 WritingSetupChat 重挂丢线程),
查看笔记本 / 所有空间时在其上叠加内嵌页。 */}
<div className="relative flex-1 min-h-0 overflow-hidden">
+1 -1
View File
@@ -273,7 +273,7 @@ The AI-writing graph (`packages/harness/deerflow/agents/ai_writing/`) has four s
Seeding mirrors the roundtable pattern: verified `config.yaml` + `SOUL.md` ship in `app/gateway/routers/_ai_writing_seed_assets/<id>/`; `_ai_writing_seed.py::ensure_ai_writing_functional_agents()` copies them to `.deer-flow/agents/` when missing (never overwrites local edits), called from the startup lifespan (before `_sync_legacy_agents`, so the agents appear in `/api/agents` on first boot) and self-heals from `GET /api/ai-writing/sessions` + `GET /api/ai-writing/article-types`. Tests: `tests/test_ai_writing_seed.py`, `tests/test_ai_writing_agent_runner.py`.
**Skill-driven retrieval (检索类型).** `material_source` has three values: `general` (通用检索, default), `knowledge_base` (知识库检索), and `notebook` (我的空间); legacy `skill` is normalized to `general` by the researcher node. **`knowledge_base` 直连内网 ES 接口** — it bypasses skill orchestration entirely and calls `IntranetSearchProvider` over `ai_writing.intranet_search_url` (concurrent over the generated keywords; `intranet_knowledge_base`/`intranet_search_timeout` apply); an unconfigured url → no materials + a `skill_error` notice. This is the "弱模型识别不了技能" escape hatch — the old no-skill retrieval path restored as an explicit option (weak models like deepseek-chat often fail to invoke configured skills). Tests: `tests/test_ai_writing_knowledge_base.py`. General retrieval is orchestrated from the **skills configured on the `ai-writing-researcher` agent** (`config.yaml → skills`, editable from the agent management page): the built-in `knowledge-base-search` skill (知识库检索) runs the native keyword fan-out web/intranet search (the old default path), while any other configured skill searches with a `description`-targeted query; skills run in configured order with early-stop at `max_materials`, and an empty/unresolvable skills config falls back to the built-in knowledge search so retrieval always works. The skill itself is seeded from `_ai_writing_seed_assets/skills/knowledge-base-search/SKILL.md` into `skills/public/` (never overwrites), and a pre-existing researcher `config.yaml` lacking the `skills` key is patched in place with the default (explicit `skills: []` is respected). **PAUSE-1 input append flow**: when the user types natural language into the material-confirm input (`re_search`/legacy `enable_skill_search` + `user_query`), the node matches the most relevant configured skill via `SkillPicker(candidates=…)` (skipped when only one skill is configured), searches with the user's words, and **appends** the new materials to the existing package (URL-dedup, original order preserved, no LLM re-rank/truncation, 100-item hard cap). **Skill-failure fault tolerance**: a configured skill that times out / raises / has all its keyword searches fail (vs. legitimately returning 0 results) no longer just silently moves on — the researcher node emits a `skill_search_step` of type `skill_error` (carrying the error `reason`), and if the configured skills collected **no** new materials at all it runs a `fallback` pass over other available skills (`_fallback_candidate_skills`: the built-in `knowledge-base-search` native path first, then other enabled catalog skills not yet tried) instead of erroring out. The frontend `SkillStepsCard` renders `skill_error` (rose) and `fallback` (amber) so the timeline shows "技能报错 → 改用其他技能搜集". Tests: `tests/test_ai_writing_material_source.py`.
**Skill-driven retrieval (检索类型).** `material_source` has three values: `general` (通用检索, default), `knowledge_base` (知识库检索), and `notebook` (我的空间); legacy `skill` is normalized to `general` by the researcher node. **`knowledge_base` 直连内网 ES 接口(= 旧版「内网直连检索」)** — it bypasses skill orchestration entirely and calls `IntranetSearchProvider` over `ai_writing.intranet_search_url` (concurrent over the generated keywords; `intranet_knowledge_base`/`intranet_search_timeout` apply). **An empty/unconfigured `intranet_search_url` does NOT disable it** — the empty string is passed straight to `IntranetSearchProvider`, which falls back to its built-in default endpoint (`intranet_stub._DEFAULT_ENDPOINT`), exactly like the legacy `get_search_provider(search_provider=intranet)` path. So 内网直连检索 works out of the box without configuring an address (configure `intranet_search_url` only to point at a different endpoint). This is the "弱模型识别不了技能" escape hatch — the old no-skill retrieval path restored as an explicit option (weak models like deepseek-chat often fail to invoke configured skills). Tests: `tests/test_ai_writing_knowledge_base.py`. General retrieval is orchestrated from the **skills configured on the `ai-writing-researcher` agent** (`config.yaml → skills`, editable from the agent management page): the built-in `knowledge-base-search` skill (知识库检索) runs the native keyword fan-out web/intranet search (the old default path), while any other configured skill searches with a `description`-targeted query; skills run in configured order with early-stop at `max_materials`, and an empty/unresolvable skills config falls back to the built-in knowledge search so retrieval always works. The skill itself is seeded from `_ai_writing_seed_assets/skills/knowledge-base-search/SKILL.md` into `skills/public/` (never overwrites), and a pre-existing researcher `config.yaml` lacking the `skills` key is patched in place with the default (explicit `skills: []` is respected). **PAUSE-1 input append flow**: when the user types natural language into the material-confirm input (`re_search`/legacy `enable_skill_search` + `user_query`), the node matches the most relevant configured skill via `SkillPicker(candidates=…)` (skipped when only one skill is configured), searches with the user's words, and **appends** the new materials to the existing package (URL-dedup, original order preserved, no LLM re-rank/truncation, 100-item hard cap). **Skill-failure fault tolerance**: a configured skill that times out / raises / has all its keyword searches fail (vs. legitimately returning 0 results) no longer just silently moves on — the researcher node emits a `skill_search_step` of type `skill_error` (carrying the error `reason`), and if the configured skills collected **no** new materials at all it runs a `fallback` pass over other available skills (`_fallback_candidate_skills`: the built-in `knowledge-base-search` native path first, then other enabled catalog skills not yet tried) instead of erroring out. The frontend `SkillStepsCard` renders `skill_error` (rose) and `fallback` (amber) so the timeline shows "技能报错 → 改用其他技能搜集". Tests: `tests/test_ai_writing_material_source.py`.
**Skill-call timeout** is hardcoded **300s (5 min)** — `researcher.py` `_SKILL_SEARCH_TIMEOUT_SECONDS` (per-skill wrapper) and `_skill_agent.py` `_REAL_AGENT_TIMEOUT_SECONDS` (whole real-agent skill run). The intranet ES fallback (`IntranetSearchProvider`) gets a longer **600s (10 min)** default (`intranet_stub.py`; overridable via `ai_writing.intranet_search_timeout`) — that interface is the slow one, so our own fallback timeout is generous to avoid being blamed for "检不出".
@@ -5,9 +5,10 @@
config.yaml 配置的技能顺序编排检索。内置「知识库检索」技能
(knowledge-base-search)走原生 web/intranet 关键词并发检索;其它技能用
其 description 生成定向 query 后调真实 provider 检索。
- ``knowledge_base``(知识库检索):**直连内网知识库 ES 接口**
(``ai_writing.intranet_search_url`` 配的 ``IntranetSearchProvider``),
不编排任何技能、也不跑通用 provider。未配置接口地址时本次无素材并给出告警。
- ``knowledge_base``(知识库检索 / 内网直连检索):**直连内网知识库 ES 接口**
(``IntranetSearchProvider``),不编排任何技能、也不跑通用 provider。接口地址取
``ai_writing.intranet_search_url``,**留空时回退 provider 内置默认内网端点**——与旧版
``get_search_provider(search_provider=intranet)`` 一致,即便没配地址内网直连仍可用。
- ``notebook``(我的空间):仅用笔记 API 素材。
旧值 ``skill`` 仍按 ``general`` 兼容处理。
@@ -568,57 +569,50 @@ async def researcher_node(state: AIWritingState, config: RunnableConfig) -> dict
# 仅使用 Step 1.5 已拉取的 notebook_materials。
_emit(f"仅使用笔记素材,跳过技能检索({len(notebook_materials)} 条)")
elif material_source == "knowledge_base":
# ── 知识库检索:直连内网 ES 接口 ──
# 用户在表单选了「知识库检索」→ 跳过技能编排、跳过通用 provider,
# 直接调 config.yaml 配的 ai_writing.intranet_search_url 内网知识库 ES 接口
# (IntranetSearchProvider)对检索词并发检索。未配置地址 → 无素材 + 告警。
intranet_url = (ai_writing_config.get("intranet_search_url") or "").strip()
if not intranet_url:
_emit("未配置内网知识库检索接口(ai_writing.intranet_search_url),本次未检索到素材")
search_errors.append("未配置 ai_writing.intranet_search_url,知识库检索不可用")
_emit_skill_step({
"type": "skill_error",
"message": "「知识库检索」未配置内网接口地址(ai_writing.intranet_search_url),无法检索",
"skill_name": KNOWLEDGE_SEARCH_SKILL_NAME,
"reason": "intranet_search_url 为空",
})
else:
from ..search.intranet_stub import IntranetSearchProvider
# ── 知识库检索:直连内网 ES 接口(恢复旧版「内网直连检索」可用逻辑)──
# 用户在表单选了「知识库检索」→ 跳过技能编排、跳过通用 provider,直接调内网知识库
# ES 接口(IntranetSearchProvider)对检索词并发检索。接口地址优先取 config.yaml 的
# ai_writing.intranet_search_url;**留空时回退到 IntranetSearchProvider 内置默认端点**
# (历史上一直可用的内网 ES 地址),与旧版 get_search_provider(search_provider=intranet)
# 完全一致——所以即便没配地址,内网直连依然可用,不再短路成「未配置 → 无素材」。
from ..search.intranet_stub import IntranetSearchProvider
provider = IntranetSearchProvider(
base_url=intranet_url,
knowledge_base_name=ai_writing_config.get("intranet_knowledge_base", "samples"),
# 内网慢检索超时可在 config.yaml 的 ai_writing.intranet_search_timeout 调大,默认 600s。
timeout=ai_writing_config.get("intranet_search_timeout", 600),
)
# 用户输入框追加(is_user_query_search)时 keywords 已是 [用户原话],全部检索;
# 首次检索按 keyword_count 截断检索词。
search_keywords = keywords if is_user_query_search else keywords[:keyword_count]
total = len(search_keywords)
per_keyword = _per_keyword_limit(max_materials, total)
_emit(f"知识库检索:直连内网接口检索 {total} 个方向…")
_emit_skill_step({
"type": "invoke_skill",
"message": f"使用「{_KNOWLEDGE_SKILL_DISPLAY}」直连内网接口检索 {total} 个方向:{('、'.join(search_keywords[:3]))[:60]}",
"skill_name": KNOWLEDGE_SEARCH_SKILL_NAME,
})
gathered = await asyncio.gather(
*[provider.search(kw, max_results=per_keyword) for kw in search_keywords],
return_exceptions=True,
)
for results in gathered:
if isinstance(results, Exception):
logger.warning("[knowledge-base] search failed: %s", results)
search_errors.append(f"{type(results).__name__}: {results}")
continue
new_results.extend(results or [])
search_errors.extend(getattr(provider, "errors", []))
_emit_skill_step({
"type": "skill_result",
"message": f"「{_KNOWLEDGE_SKILL_DISPLAY}」(内网接口)检索到 {len(new_results)} 条素材",
"skill_name": KNOWLEDGE_SEARCH_SKILL_NAME,
"matched_count": len(new_results),
})
intranet_url = (ai_writing_config.get("intranet_search_url") or "").strip()
provider = IntranetSearchProvider(
base_url=intranet_url, # 空串 → provider 内部回退默认内网端点(旧逻辑)
knowledge_base_name=ai_writing_config.get("intranet_knowledge_base", "samples"),
# 内网慢检索超时可在 config.yaml 的 ai_writing.intranet_search_timeout 调大,默认 600s。
timeout=ai_writing_config.get("intranet_search_timeout", 600),
)
endpoint_label = intranet_url or getattr(provider, "endpoint", "内置默认内网端点")
# 用户输入框追加(is_user_query_search)时 keywords 已是 [用户原话],全部检索;
# 首次检索按 keyword_count 截断检索词。
search_keywords = keywords if is_user_query_search else keywords[:keyword_count]
total = len(search_keywords)
per_keyword = _per_keyword_limit(max_materials, total)
_emit(f"知识库检索:直连内网接口检索 {total} 个方向…")
_emit_skill_step({
"type": "invoke_skill",
"message": f"使用「{_KNOWLEDGE_SKILL_DISPLAY}」直连内网接口({endpoint_label})检索 {total} 个方向:{('、'.join(search_keywords[:3]))[:60]}",
"skill_name": KNOWLEDGE_SEARCH_SKILL_NAME,
})
gathered = await asyncio.gather(
*[provider.search(kw, max_results=per_keyword) for kw in search_keywords],
return_exceptions=True,
)
for results in gathered:
if isinstance(results, Exception):
logger.warning("[knowledge-base] search failed: %s", results)
search_errors.append(f"{type(results).__name__}: {results}")
continue
new_results.extend(results or [])
search_errors.extend(getattr(provider, "errors", []))
_emit_skill_step({
"type": "skill_result",
"message": f"「{_KNOWLEDGE_SKILL_DISPLAY}」(内网接口)检索到 {len(new_results)} 条素材",
"skill_name": KNOWLEDGE_SEARCH_SKILL_NAME,
"matched_count": len(new_results),
})
elif is_append_only:
# ── 兼容旧版追加关键词模式 ──
# 直接对用户给的关键词做原生并发检索(不走技能编排),结果追加到旧素材。
@@ -282,13 +282,25 @@ async def run_agent(
# 起新一轮。Pregel 检查到 Command 会从最近 checkpoint 处恢复,而不是重头跑。
stream_input: Any = graph_input
if command is not None:
from langgraph.types import Command as _LGCommand
# 有 resume/update/goto(如 AI 写作 4 个干预卡的 Command(resume=user_input))→
# 构造 langgraph.types.Command,Pregel 从 interrupt 处恢复。
# **空 command(无任何指令)= "从最近 checkpoint 继续执行挂起的任务"**:AI 写作
# "暂停后继续" —— 暂停时硬取消了活跃节点(非 interrupt),continue 要让该阶段节点
# 从 checkpoint 续跑。此时必须用 **None 输入**让 Pregel resume pending tasks;
# 既不能用 graph_input={}(空 dict 被当新一轮输入 → 从图入口 intent 重跑),也不能
# 构造 Command()(没有挂起的 interrupt 可消费,LangGraph 内部会抛
# "cannot access local variable 'resume_is_map'")。
has_directive = any(command.get(k) is not None for k in ("resume", "update", "goto"))
if has_directive:
from langgraph.types import Command as _LGCommand
stream_input = _LGCommand(
resume=command.get("resume"),
update=command.get("update"),
goto=command.get("goto"),
)
stream_input = _LGCommand(
resume=command.get("resume"),
update=command.get("update"),
goto=command.get("goto"),
)
else:
stream_input = None
if len(lg_modes) == 1 and not stream_subgraphs:
# Single mode, no subgraphs: astream yields raw chunks
@@ -88,12 +88,16 @@ async def test_knowledge_base_hits_intranet_directly(monkeypatch):
@pytest.mark.asyncio
async def test_knowledge_base_no_url_empty(monkeypatch):
"""未配置内网接口地址:无素材,且不实例化 provider。"""
async def test_knowledge_base_no_url_falls_back_to_default_endpoint(monkeypatch):
"""未配置接口地址:仍实例化 IntranetSearchProvider(base_url 传空串,由 provider 内部
回退默认内网端点),内网直连依然可用——恢复旧版 search_provider=intranet 的行为。"""
_patch(monkeypatch, intranet_url="")
out = await R.researcher_node(_state(), {"configurable": {}})
assert out["material_package"]["materials"] == []
assert _FakeIntranet.instances == [], "无地址时不应实例化内网 provider"
mats = out["material_package"]["materials"]
assert mats, "无地址时应回退默认内网端点,仍返回素材"
assert all(m["source_type"] == "intranet" for m in mats)
assert _FakeIntranet.instances, "应实例化 IntranetSearchProvider 直连内网接口"
assert _FakeIntranet.instances[0].kw.get("base_url") == "", "空地址应原样下传,由 provider 回退默认端点"
@pytest.mark.asyncio