import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { ChevronsDown, CloudUpload, PanelRightClose, Pause, Play, Plus, RotateCcw, Settings2, Trash2 } from 'lucide-react'; import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; import { cn } from '@/lib/utils'; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import { useArticleTypes } from '../../hooks/useArticleTypes'; import { useAIWriting } from '../../contexts/AIWritingContext'; import { useAIWritingHistory } from '../../contexts/AIWritingHistoryContext'; import { useWritingFormOptional } from '../../contexts/WritingFormContext'; import { useAIWritingSessions } from '../../hooks/useAIWritingSessions'; import { adminCleanupAIWritingSessions, getAIWritingSession, suspendAIWritingToBackground, } from '../../api/ai-writing-sessions'; /** * 暂停 / 继续功能开关(现已开启)。 * * 真·暂停:``pauseWriting`` → ``stream.stop()`` 取消当前 run(LangGraph 已完成的阶段 * 已落 checkpoint,不丢)。真·继续:``resumeWriting`` → 带空 ``command:{}`` 重新 submit, * 后端 worker 据此让 Pregel 从最近 checkpoint 续跑挂起的当前阶段节点(重跑当前未完成阶段, * 已完成阶段不重来;见 runtime/runs/worker.py)。刷新页面 = 重置(不自动重连)。 */ const ENABLE_PAUSE_RESUME_UI = true; const RESUMABLE_HISTORY_STATUSES = new Set(['in_progress', 'draft_ready', 'review_ready']); import { countArticleWords } from '../../utils/wordCount'; import { AIWritingForm } from './AIWritingForm'; import { AIWritingTimeline } from './AIWritingTimeline'; import { InterventionCard } from './InterventionCard'; import { SkillStepsCard } from './SkillStepsCard'; import { SkillSelectStreamingView } from './SkillSelectStreamingView'; import { KeywordStreamingView } from './KeywordStreamingView'; import { WritingSkeletonCard } from './WritingSkeletonCard'; import { DraftGeneratingView } from './DraftGeneratingView'; import { DraftSync } from './DraftSync'; import { IntentResultCard } from './IntentResultCard'; import { IntentStreamingView } from './IntentStreamingView'; import { SampleAnalysisStreamingView } from './SampleAnalysisStreamingView'; import { SampleStyleProfileCard } from './SampleStyleProfileCard'; import { OutlineStreamingView } from './OutlineStreamingView'; import { ReviewStreamingView } from './ReviewStreamingView'; import { RevisionSummaryCard } from './RevisionSummaryCard'; import { AIWritingHistoryDropdown } from './AIWritingHistoryDropdown'; import { AIWritingHistoryView } from './AIWritingHistoryView'; import { AIWritingFlowDialog } from './AIWritingFlowDialog'; import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions'; const STATUS_LABEL: Record = { idle: '就绪', analyzing_sample: '样文分析师分析文风中…', researching: '素材收集专家搜集素材中…', awaiting_material_confirm: '等待确认素材', writing_outline: '作家规划大纲中…', awaiting_outline_confirm: '等待确认大纲', writing_draft: '作家写作中…', awaiting_section_help: '等待处理素材不足的章节', awaiting_draft_confirm: '等待确认草稿', reviewing: '编辑审核中…', awaiting_review_confirm: '等待处理编辑意见', revising: '按意见修改中…', done: '写作完成 ✓', error: '出错了', }; export function AIWritingPanel({ hideAdvancedFields = false, initialNotebookId, initialDocumentIds, studioToken, headerActionsBeforeCollapse, }: { hideAdvancedFields?: boolean; initialNotebookId?: number; initialDocumentIds?: number[]; studioToken?: string; headerActionsBeforeCollapse?: ReactNode; } = {}) { const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const { state, startWriting, submitIntervention, pauseWriting, resumeWriting, continueWriting, reset } = useAIWriting(); const { historySession, isHistoryMode, openHistory, closeHistory } = useAIWritingHistory(); const writingForm = useWritingFormOptional(); const { sessions, loading: sessionsLoading, refresh, rename, remove, markBackground, clearBackground } = useAIWritingSessions(); const { articleTypes, refresh: refreshArticleTypes } = useArticleTypes(); useEffect(() => { refreshArticleTypes(); }, [refreshArticleTypes]); const [reqDialogOpen, setReqDialogOpen] = useState(false); // 「查看进度」流程图弹窗当前展示的会话(点击历史里的「挂起中」记录时打开)。 const [progressSession, setProgressSession] = useState(null); const isIdle = state.status === 'idle'; const isDone = state.status === 'done'; const isError = state.status === 'error'; const isRunning = !isIdle && !isDone && !isError; const shouldAutoFollow = !isIdle && !isHistoryMode; const showSkeleton = isRunning && !state.currentPause && !state.isPaused; const intentSlot = (state.intentStreamingText || state.intentThinkingText) ? ( ) : state.parsedIntent ? ( ) : null; const sampleAnalysisSlot = (state.sampleAnalysisStreamingText || state.sampleAnalysisThinkingText) ? ( ) : null; const sampleProfileSlot = state.sampleStyleProfile ? ( ) : null; // ── 自动滚底逻辑 ──────────────────────────────────────────────────────────── const scrollRef = useRef(null); const bottomRef = useRef(null); // 程序触发滚动时置 true,阻止 scroll 事件误判为用户上划 const isAutoScrollingRef = useRef(false); // 同步 ref:让 scroll/wheel 回调可以立即读取最新值,不依赖 state 异步更新 const autoScrollRef = useRef(true); const shouldAutoFollowRef = useRef(shouldAutoFollow); shouldAutoFollowRef.current = shouldAutoFollow; const scrollbarDragRef = useRef(false); const touchYRef = useRef(null); const [autoScroll, setAutoScroll] = useState(true); const enableAutoScroll = useCallback(() => { autoScrollRef.current = true; setAutoScroll(true); }, []); const disableAutoScroll = useCallback(() => { autoScrollRef.current = false; setAutoScroll(false); }, []); const scrollToBottomNow = useCallback(() => { const el = scrollRef.current; if (!el) return; isAutoScrollingRef.current = true; const jump = () => { if (bottomRef.current) { bottomRef.current.scrollIntoView({ block: 'end' }); } else { el.scrollTop = el.scrollHeight; } }; jump(); requestAnimationFrame(() => { jump(); requestAnimationFrame(() => { isAutoScrollingRef.current = false; }); }); }, []); const maybeAutoScrollToBottom = useCallback(() => { if (!autoScrollRef.current || !shouldAutoFollowRef.current) return; scrollToBottomNow(); }, [scrollToBottomNow]); // 新会话 / 重置后恢复自动滚底 useEffect(() => { if (isIdle) { enableAutoScroll(); } }, [enableAutoScroll, isIdle]); // 开始写作 / 点击继续后恢复自动滚底 useEffect(() => { if (shouldAutoFollow && !state.isPaused) { enableAutoScroll(); requestAnimationFrame(scrollToBottomNow); } }, [enableAutoScroll, scrollToBottomNow, shouldAutoFollow, state.isPaused]); // 监听用户手动滚动(挂载一次) useEffect(() => { const el = scrollRef.current; if (!el) return; const nearBottom = () => el.scrollHeight - el.scrollTop - el.clientHeight < 24; // wheel 事件:鼠标滚轮 / 触控板,只由用户触发 const onWheel = (e: WheelEvent) => { if (e.deltaY < 0) disableAutoScroll(); // 向上滚 }; const onTouchStart = (e: TouchEvent) => { touchYRef.current = e.touches[0]?.clientY ?? null; }; const onTouchMove = (e: TouchEvent) => { const prevY = touchYRef.current; const nextY = e.touches[0]?.clientY ?? null; if (prevY !== null && nextY !== null && nextY > prevY + 4) { disableAutoScroll(); } touchYRef.current = nextY; }; const onPointerDown = (e: PointerEvent) => { if (e.target === el) { scrollbarDragRef.current = true; } }; const onPointerDone = () => { scrollbarDragRef.current = false; }; // scroll 事件只处理「用户拖动滚动条」和「手动回到底部」。 // 普通布局变化也会触发 scroll,不能再把所有 scrollTop 下降都当成用户上划。 let lastTop = el.scrollTop; const onScroll = () => { const cur = el.scrollTop; if (isAutoScrollingRef.current) { lastTop = cur; return; } if (nearBottom()) { enableAutoScroll(); } else if (scrollbarDragRef.current && cur < lastTop - 2) { disableAutoScroll(); } lastTop = cur; }; el.addEventListener('wheel', onWheel, { passive: true }); el.addEventListener('touchstart', onTouchStart, { passive: true }); el.addEventListener('touchmove', onTouchMove, { passive: true }); el.addEventListener('pointerdown', onPointerDown); window.addEventListener('pointerup', onPointerDone); window.addEventListener('pointercancel', onPointerDone); el.addEventListener('scroll', onScroll, { passive: true }); return () => { el.removeEventListener('wheel', onWheel); el.removeEventListener('touchstart', onTouchStart); el.removeEventListener('touchmove', onTouchMove); el.removeEventListener('pointerdown', onPointerDown); window.removeEventListener('pointerup', onPointerDone); window.removeEventListener('pointercancel', onPointerDone); el.removeEventListener('scroll', onScroll); }; }, [disableAutoScroll, enableAutoScroll]); // 内容高度变化兜底:同一 timeline 节点内卡片展开、文风画像替换、流式文本变长, // 都可能不改变 progressEvents.length。监听 DOM 变化可以把这些情况统一托底。 useEffect(() => { const el = scrollRef.current; if (!el || typeof MutationObserver === 'undefined') return; const observer = new MutationObserver(() => { maybeAutoScrollToBottom(); }); observer.observe(el, { childList: true, subtree: true, characterData: true }); return () => observer.disconnect(); }, [maybeAutoScrollToBottom]); // 内容变化时若自动滚底开启则滚到底部 useLayoutEffect(() => { maybeAutoScrollToBottom(); }, [ maybeAutoScrollToBottom, autoScroll, // 点击按钮后重新触发一次 isRunning, state.status, state.progressEvents.length, state.sampleAnalysisStreamingText, state.sampleAnalysisThinkingText, state.sampleStyleProfile, state.intentStreamingText, state.intentThinkingText, state.parsedIntent, state.keywordStreamingText, state.keywordThinkingText, state.skillSearchSteps.length, state.skillSelectStreamingText, state.skillSelectThinkingText, state.streamingDraftSections.length, state.streamingReviewItems.length, state.outlineStreamingText, state.outlineThinkingText, state.revisionSummary, state.currentPause, ]); const scrollToBottom = useCallback(() => { enableAutoScroll(); scrollToBottomNow(); }, [enableAutoScroll, scrollToBottomNow]); const handleSelectHistory = useCallback((session: AIWritingSessionSummary) => { void openHistory(session); }, [openHistory]); // 点击历史里的「挂起中」记录 → 打开流程图弹窗看实际进度(而非直接打开会话)。 const handleShowProgress = useCallback((session: AIWritingSessionSummary) => { setProgressSession(session); }, []); const handleNewSession = useCallback(() => { closeHistory(); reset(); }, [closeHistory, reset]); const canRestoreHistory = isHistoryMode && !!historySession && RESUMABLE_HISTORY_STATUSES.has(historySession.status); const handleRestoreHistory = useCallback(() => { if (!historySession || !RESUMABLE_HISTORY_STATUSES.has(historySession.status)) return; closeHistory(); continueWriting(historySession.id); }, [historySession, closeHistory, continueWriting]); // ── 后台挂起:把当前写作转后台,后端自动驱动到定稿(离页/刷新/切号不打断) ── // 与「多智能体会商」一致:点击后**立刻**回到初始页面,挂起请求 fire-and-forget; // 历史下拉靠乐观标记马上显示「挂起中」,不等后端确认。 const handleBackgroundSuspend = useCallback(() => { const sid = state.sessionId; if (!sid) { toast.error('当前没有可挂起的写作会话'); return; } // 1) 立刻:乐观标记 + 重置 UI 回到 idle(reset() 会 stop 客户端 SSE 订阅, // 后端驱动器接管续跑,不冲突)。 markBackground(sid); reset(); toast.success('已转入后台自动完成,稍后可在「历史记录」查看进度与结果'); // 2) 后台:fire-and-forget 通知后端拉起驱动;完成后刷新真实状态并清除乐观标记。 void (async () => { try { await suspendAIWritingToBackground(sid); } catch (e) { toast.error(e instanceof Error ? e.message : '后台挂起失败'); } finally { await refresh(); clearBackground(sid); } })(); }, [state.sessionId, reset, refresh, markBackground, clearBackground]); // 离页 / 刷新 = 重置(不自动重连、不自动转后台):刷新会断开 SSE,后端默认 // on_disconnect=cancel 取消该 run,页面重新挂载回到 idle。需要"后台自动跑完" // (自动确认素材/大纲/审核到定稿、离页不中断)可手动点「后台挂起」。 // 页内的「暂停/继续」从 checkpoint 续跑当前阶段,不受刷新重置影响(刷新即新开)。 // ── 侧边栏"最近写作"通信:两种路径 ──────────────────────────────────────── // 用 ref 包住 handler,保证事件监听器始终能拿到最新版本 const handleSelectHistoryRef = useRef(handleSelectHistory); useEffect(() => { handleSelectHistoryRef.current = handleSelectHistory; }, [handleSelectHistory]); // 路径1:导航进入本页面时,从 sessionStorage 恢复待打开的 session useEffect(() => { const raw = sessionStorage.getItem('ai-writing:pending-session'); if (!raw) return; sessionStorage.removeItem('ai-writing:pending-session'); try { const session = JSON.parse(raw) as AIWritingSessionSummary; handleSelectHistoryRef.current(session); } catch { /* ignore */ } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // 仅挂载时执行一次 // 路径2:已在本页面时,监听侧边栏触发的自定义事件 useEffect(() => { function onOpenSession(e: Event) { const session = (e as CustomEvent).detail; if (session) handleSelectHistoryRef.current(session); } window.addEventListener('ai-writing:open-session', onOpenSession); return () => window.removeEventListener('ai-writing:open-session', onOpenSession); }, []); // 路径4:左侧研究栏「历史记录」点「挂起中」记录 → 打开进度流程图弹窗(与下拉历史一致)。 useEffect(() => { function onShowProgress(e: Event) { const session = (e as CustomEvent).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'); if (!sessionId) return; // 消费参数,避免刷新重复触发 setSearchParams((prev) => { prev.delete('session'); return prev; }, { replace: true }); getAIWritingSession(sessionId) .then((session) => handleSelectHistoryRef.current(session)) .catch(() => { /* session 不存在时静默忽略 */ }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // 仅挂载时执行一次 // ── ⚠️ 临时调试:admin 一键清理所有过期会话 ──────────────────────────────── // ai-writing-优化.md §阶段 7 删冗余代码时,本按钮 + 对应 api 一并删除。 // 仅 admin 能成功调用(后端 _require_admin),普通用户调会拿到 403。 const handleAdminCleanup = useCallback(async () => { if (!window.confirm('确认清理:retention_days=0 会清掉所有 done/error 的历史会话,正在跑的会跳过。继续?')) { return; } try { const result = await adminCleanupAIWritingSessions({ retention_days: 0, only_finished: true }); toast.success(`已清理:DB ${result.deleted_db} 行,checkpoint ${result.deleted_checkpoints} 条,跳过活跃 ${result.skipped_active}`); // 刷新历史列表 refresh(); } catch (e) { toast.error(e instanceof Error ? e.message : String(e)); } }, [refresh]); const showNewButton = isHistoryMode || state.status !== 'idle'; return (
{!isHistoryMode && ( )} {/* 头部 */}
{canRestoreHistory && ( )} { if (!isIdle && !isHistoryMode && state.request) setReqDialogOpen(true); }} title={isHistoryMode ? (historySession?.draft_title ?? historySession?.title) : undefined} > {isHistoryMode ? (historySession?.draft_title ?? historySession?.title ?? '写作历史') : 'AI 智能写作'}
{/* ⚠️ 临时调试:admin 一键清理 —— 阶段 7 删冗余时移除 */} {showNewButton && ( )} {/* 后台挂起:写作进行中(含等待干预)时出现,点击后由后端自动跑完剩余流程 */} {isRunning && !isHistoryMode && state.sessionId && ( )} {/* ⏸️/▶️ "暂停 / 继续":暂停=stream.stop() 取消当前 run(已完成阶段已落 checkpoint); 继续=从 checkpoint 重新驱动 graph 续跑(重跑当前阶段,已完成阶段不丢)。 */} {ENABLE_PAUSE_RESUME_UI && isRunning && !state.isPaused && ( )} {ENABLE_PAUSE_RESUME_UI && state.isPaused && ( <> )} {(isDone || isError) && ( )} {headerActionsBeforeCollapse} {/* 收起写作配置:仅在 idle 配置阶段、表单展开时出现(与 AIWritingPage 的整块收起联动) */} {writingForm && isIdle && !isHistoryMode && writingForm.formExpanded && ( )}
{/* 主体:relative 父容器 + absolute 滚动容器,确保滚动容器尺寸始终正确 */}
{/* 历史回看:左侧时间线(与实时写作同一套 AIWritingTimeline) */} {isHistoryMode && historySession && ( )} {/* 未开始时显示表单 */} {isIdle && !isHistoryMode && ( )} {/* 运行中或完成后显示时间线 */} {!isIdle && !isHistoryMode && ( 0} onSubmit={submitIntervention} disabled={false} /> ) : undefined } /> )} {/* 大纲流式思考框(用户自带大纲时文案显示「整理」) */} {state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText) && ( )} {/* 编辑审核流式结果 */} {state.status === 'reviewing' && state.streamingReviewItems.length > 0 && ( )} {/* 修改完成摘要 */} {state.revisionSummary && (
)} {/* 草稿生成中:左侧只展示思考过程(若有)+「内容生成中」骨架屏;正文实时显示在右侧画布 */} {state.status === 'writing_draft' && ( )} {/* 检索词生成过程:先展示模型如何从写作意图提炼搜索方向,再进入技能匹配 / 检索。 */} {state.status === 'researching' && ( state.keywordStreamingText || state.keywordThinkingText ) && ( )} {/* 技能选择 LLM 流式打字(含 思考分离),select_skills 完成后自动清空。 挂载条件包含"过渡态":已经走到 match_skills 但还没出 select_skills 时也保持挂载, 让首个空 chunk 一到就能立刻显示等待提示 + 闪烁光标,避免模型 buffer 期间静默。 */} {state.status === 'researching' && ( state.skillSelectStreamingText || state.skillSelectThinkingText || (state.skillSearchSteps.some((s) => s.type === 'match_skills') && !state.skillSearchSteps.some((s) => s.type === 'select_skills')) ) && ( )} {/* 技能检索过程实时展示: ① skillSearchPending —— PAUSE-1 用户点"重新搜索/按输入追加"瞬间到 awaiting 之间的占位(steps 为空时 SkillStepsCard 内部渲染骨架行,不让用户干等空白); ② 首次素材收集(researching 且已有 skill_search_step)—— 让"调用了哪个技能 / 检索到多少条 / 检索完成"像智能体问答一样边搜边显示,而不是搜完才在素材确认 卡里一次性看到。素材确认(awaiting_material_confirm)时由 InterventionCard 接管展示同一份 steps,这里 researching 条件自动失效,不会重复。 */} {(state.skillSearchPending || (state.status === 'researching' && state.skillSearchSteps.length > 0)) && (
)} {showSkeleton && state.status !== 'writing_draft' && !(state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText)) && !(state.status === 'reviewing' && state.streamingReviewItems.length > 0) && /* 检索词生成卡 / 技能检索占位卡 / 选择打字机 / 已流式的技能步骤 已经在展示,不再叠加 skeleton。 (研究阶段一旦有 skill_search_step,就改由上面的 SkillStepsCard 实时呈现进度, 关键词 chunk 还没到之前仍走 skeleton 透传 researchProgress 文案。) */ !state.skillSearchPending && !(state.status === 'researching' && state.skillSearchSteps.length > 0) && !(state.status === 'researching' && (state.keywordStreamingText || state.keywordThinkingText)) && !(state.status === 'researching' && (state.skillSelectStreamingText || state.skillSelectThinkingText)) && /* 样文分析已有流式过程卡时,不再叠加 skeleton */ !state.sampleAnalysisStreamingText && !state.sampleAnalysisThinkingText && /* 意图解析流式过程中(LLM 还在吐 JSON)不要显示 skeleton */ !state.intentStreamingText && !state.intentThinkingText && (
)} {isError && state.error && (
{state.error}
)} {/* 滚动内容区结束 */} {/* 回到底部悬浮按钮:生成中且用户已上划时出现 */} {isRunning && !autoScroll && (
)}
{/* 相对定位容器结束 */} {/* 状态栏 */} {!isIdle && !isHistoryMode && (
{ENABLE_PAUSE_RESUME_UI && state.isPaused ? ( <> 已暂停 ) : ( <> {isRunning && ( )} {state.status === 'researching' && state.researchProgress ? state.researchProgress : state.status === 'writing_outline' && state.request?.userOutline ? '作家整理你的大纲中…' : STATUS_LABEL[state.status] ?? state.status} )}
)} {/* 查看进度流程图弹窗:点击历史里的「挂起中」记录时打开 */} { if (!o) setProgressSession(null); }} /> {/* 写作参数查看弹窗 */} {state.request && ( 本次写作参数

{state.request.userIntent}

{articleTypes.find((t) => t.key === state.request!.articleType)?.label ?? state.request.articleType} {!hideAdvancedFields && ( {state.request.targetAudience} )} {state.request.wordCountTarget} 字 {!hideAdvancedFields && ( <> {state.request.keywordCount} 个 {state.request.writingMode === 'strict' ? '严格依据素材' : '宽松(可结合通用知识)'} )} {state.request.modelName && ( {state.request.modelName} )}
)}
); } function ReqRow({ label, children }: { label: string; children: React.ReactNode }) { return (

{label}

{children}
); }