# Conflicts: # frontend-web/src/open-canvas/components/ai-writing/AIWritingForm.tsx # frontend-web/src/open-canvas/components/ai-writing/AIWritingPanel.tsx # offline-backend-20260512/backend/CLAUDE.md # offline-backend-20260512/backend/app/gateway/services.py # offline-backend-20260512/backend/tests/test_ai_writing_knowledge_base.py
829 lines
35 KiB
TypeScript
829 lines
35 KiB
TypeScript
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<string, string> = {
|
||
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<AIWritingSessionSummary | null>(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) ? (
|
||
<IntentStreamingView text={state.intentStreamingText} thinkingText={state.intentThinkingText} />
|
||
) : state.parsedIntent ? (
|
||
<IntentResultCard
|
||
intent={state.parsedIntent}
|
||
articleTypes={articleTypes}
|
||
hideTargetAudience={hideAdvancedFields}
|
||
embedded
|
||
/>
|
||
) : null;
|
||
const sampleAnalysisSlot = (state.sampleAnalysisStreamingText || state.sampleAnalysisThinkingText) ? (
|
||
<SampleAnalysisStreamingView
|
||
text={state.sampleAnalysisStreamingText}
|
||
thinkingText={state.sampleAnalysisThinkingText}
|
||
/>
|
||
) : null;
|
||
const sampleProfileSlot = state.sampleStyleProfile ? (
|
||
<SampleStyleProfileCard profile={state.sampleStyleProfile} />
|
||
) : null;
|
||
|
||
// ── 自动滚底逻辑 ────────────────────────────────────────────────────────────
|
||
const scrollRef = useRef<HTMLDivElement>(null);
|
||
const bottomRef = useRef<HTMLDivElement>(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<number | null>(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<AIWritingSessionSummary>).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<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');
|
||
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 (
|
||
<div className="flex flex-col h-full overflow-hidden bg-background dark:bg-transparent">
|
||
{!isHistoryMode && (
|
||
<DraftSync status={state.status} markdown={state.currentDraftMarkdown} title={state.currentDraftTitle} />
|
||
)}
|
||
{/* 头部 */}
|
||
<div className="flex items-center justify-between px-4 py-2.5 border-b shrink-0">
|
||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||
{canRestoreHistory && (
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
className="h-7 px-2 text-xs gap-1 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
|
||
onClick={handleRestoreHistory}
|
||
title="恢复写作:跳过已完成阶段,从未完成阶段重新开始"
|
||
>
|
||
<Play className="size-3 fill-current" />
|
||
恢复
|
||
</Button>
|
||
)}
|
||
<span
|
||
className={cn(
|
||
'text-sm font-semibold shrink-0 min-w-0 truncate',
|
||
isHistoryMode && 'flex-1 mr-2',
|
||
!isIdle && !isHistoryMode && 'cursor-pointer hover:text-primary transition-colors',
|
||
)}
|
||
onClick={() => { if (!isIdle && !isHistoryMode && state.request) setReqDialogOpen(true); }}
|
||
title={isHistoryMode ? (historySession?.draft_title ?? historySession?.title) : undefined}
|
||
>
|
||
{isHistoryMode
|
||
? (historySession?.draft_title ?? historySession?.title ?? '写作历史')
|
||
: 'AI 智能写作'}
|
||
</span>
|
||
</div>
|
||
<div className="flex items-center gap-1.5">
|
||
{/* ⚠️ 临时调试:admin 一键清理 —— 阶段 7 删冗余时移除 */}
|
||
<Button
|
||
variant="ghost"
|
||
size="icon"
|
||
className="h-7 w-7 text-red-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30"
|
||
onClick={handleAdminCleanup}
|
||
title="[admin 调试] 清理所有过期会话"
|
||
>
|
||
<Trash2 className="size-3.5" />
|
||
</Button>
|
||
<Button
|
||
variant="ghost"
|
||
size="icon"
|
||
className="h-7 w-7"
|
||
onClick={() => navigate('/page/canvas/article-types')}
|
||
title="文章类型配置"
|
||
>
|
||
<Settings2 className="size-3.5" />
|
||
</Button>
|
||
{showNewButton && (
|
||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs gap-1" onClick={handleNewSession}>
|
||
<Plus className="size-3" />
|
||
新建
|
||
</Button>
|
||
)}
|
||
{/* 后台挂起:写作进行中(含等待干预)时出现,点击后由后端自动跑完剩余流程 */}
|
||
{isRunning && !isHistoryMode && state.sessionId && (
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
className="h-7 px-2 text-xs gap-1 text-sky-500 hover:text-sky-600 hover:bg-sky-50 dark:hover:bg-sky-950/30"
|
||
onClick={handleBackgroundSuspend}
|
||
title="转入后台:自动确认素材/大纲、写作、编辑审核直至定稿,离开页面也不中断"
|
||
>
|
||
<CloudUpload className="size-3" />
|
||
后台挂起
|
||
</Button>
|
||
)}
|
||
{/* ⏸️/▶️ "暂停 / 继续":暂停=stream.stop() 取消当前 run(已完成阶段已落 checkpoint);
|
||
继续=从 checkpoint 重新驱动 graph 续跑(重跑当前阶段,已完成阶段不丢)。 */}
|
||
{ENABLE_PAUSE_RESUME_UI && isRunning && !state.isPaused && (
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
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}
|
||
>
|
||
<Pause className="size-3 fill-current" />
|
||
暂停
|
||
</Button>
|
||
)}
|
||
{ENABLE_PAUSE_RESUME_UI && state.isPaused && (
|
||
<>
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
className="h-7 px-2 text-xs gap-1 text-primary hover:text-primary hover:bg-primary/8"
|
||
onClick={resumeWriting}
|
||
>
|
||
<Play className="size-3 fill-current" />
|
||
继续
|
||
</Button>
|
||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs gap-1" onClick={reset}>
|
||
<RotateCcw className="size-3" />
|
||
重置
|
||
</Button>
|
||
</>
|
||
)}
|
||
{(isDone || isError) && (
|
||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs gap-1" onClick={reset}>
|
||
<RotateCcw className="size-3" />
|
||
重置
|
||
</Button>
|
||
)}
|
||
<AIWritingHistoryDropdown
|
||
sessions={sessions}
|
||
selectedId={historySession?.id ?? null}
|
||
loading={sessionsLoading}
|
||
onSelect={handleSelectHistory}
|
||
onShowProgress={handleShowProgress}
|
||
onDelete={remove}
|
||
onRename={rename}
|
||
onRefresh={refresh}
|
||
/>
|
||
{headerActionsBeforeCollapse}
|
||
{/* 收起写作配置:仅在 idle 配置阶段、表单展开时出现(与 AIWritingPage 的整块收起联动) */}
|
||
{writingForm && isIdle && !isHistoryMode && writingForm.formExpanded && (
|
||
<Button
|
||
variant="ghost"
|
||
size="icon"
|
||
className="h-7 w-7"
|
||
onClick={() => writingForm.setFormExpanded(false)}
|
||
title="收起写作配置"
|
||
>
|
||
<PanelRightClose className="size-3.5" />
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
|
||
{/* 主体:relative 父容器 + absolute 滚动容器,确保滚动容器尺寸始终正确 */}
|
||
<div className="flex-1 min-h-0 relative">
|
||
<div
|
||
ref={scrollRef}
|
||
className={cn(
|
||
'absolute inset-0 overflow-y-auto',
|
||
autoScroll && '[overflow-anchor:none]',
|
||
)}
|
||
>
|
||
{/* 历史回看:左侧时间线(与实时写作同一套 AIWritingTimeline) */}
|
||
{isHistoryMode && historySession && (
|
||
<AIWritingHistoryView session={historySession} />
|
||
)}
|
||
|
||
{/* 未开始时显示表单 */}
|
||
{isIdle && !isHistoryMode && (
|
||
<AIWritingForm
|
||
onSubmit={startWriting}
|
||
hideAdvancedFields={hideAdvancedFields}
|
||
initialNotebookId={initialNotebookId}
|
||
initialDocumentIds={initialDocumentIds}
|
||
studioToken={studioToken}
|
||
/>
|
||
)}
|
||
|
||
{/* 运行中或完成后显示时间线 */}
|
||
{!isIdle && !isHistoryMode && (
|
||
<AIWritingTimeline
|
||
events={state.progressEvents}
|
||
completedInterventions={state.completedInterventions}
|
||
currentPause={state.currentPause}
|
||
sampleAnalysisSlot={sampleAnalysisSlot}
|
||
sampleProfileSlot={sampleProfileSlot}
|
||
intentSlot={intentSlot}
|
||
intentSlotDone={!!state.parsedIntent && !state.intentStreamingText && !state.intentThinkingText}
|
||
currentInterventionSlot={
|
||
state.currentPause ? (
|
||
<InterventionCard
|
||
pauseEvent={state.currentPause}
|
||
materials={state.materials}
|
||
outline={state.outline}
|
||
reviewResult={state.reviewResult}
|
||
draftTitle={state.currentDraftTitle}
|
||
draftWordCount={countArticleWords(state.currentDraftMarkdown)}
|
||
wordCountTarget={state.request?.wordCountTarget}
|
||
revisionCount={state.revisionCount}
|
||
skillSearchSteps={state.skillSearchSteps}
|
||
materialSource={state.request?.materialSource ?? 'general'}
|
||
canUseNotebookSearch={state.request?.noteSearchSpaceId != null}
|
||
skillSearchInProgress={state.status === 'researching' && state.skillSearchSteps.length > 0}
|
||
onSubmit={submitIntervention}
|
||
disabled={false}
|
||
/>
|
||
) : undefined
|
||
}
|
||
/>
|
||
)}
|
||
|
||
{/* 大纲流式思考框(用户自带大纲时文案显示「整理」) */}
|
||
{state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText) && (
|
||
<OutlineStreamingView
|
||
text={state.outlineStreamingText}
|
||
thinkingText={state.outlineThinkingText}
|
||
organizing={!!state.request?.userOutline}
|
||
/>
|
||
)}
|
||
|
||
{/* 编辑审核流式结果 */}
|
||
{state.status === 'reviewing' && state.streamingReviewItems.length > 0 && (
|
||
<ReviewStreamingView items={state.streamingReviewItems} />
|
||
)}
|
||
|
||
{/* 修改完成摘要 */}
|
||
{state.revisionSummary && (
|
||
<div className="px-4 pb-2">
|
||
<RevisionSummaryCard summary={state.revisionSummary} />
|
||
</div>
|
||
)}
|
||
|
||
{/* 草稿生成中:左侧只展示思考过程(若有)+「内容生成中」骨架屏;正文实时显示在右侧画布 */}
|
||
{state.status === 'writing_draft' && (
|
||
<DraftGeneratingView sections={state.streamingDraftSections} />
|
||
)}
|
||
|
||
{/* 检索词生成过程:先展示模型如何从写作意图提炼搜索方向,再进入技能匹配 / 检索。 */}
|
||
{state.status === 'researching' && (
|
||
state.keywordStreamingText || state.keywordThinkingText
|
||
) && (
|
||
<KeywordStreamingView
|
||
text={state.keywordStreamingText}
|
||
thinkingText={state.keywordThinkingText}
|
||
/>
|
||
)}
|
||
|
||
{/* 技能选择 LLM 流式打字(含 <think> 思考分离),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'))
|
||
) && (
|
||
<SkillSelectStreamingView
|
||
text={state.skillSelectStreamingText}
|
||
thinkingText={state.skillSelectThinkingText}
|
||
/>
|
||
)}
|
||
|
||
{/* 技能检索过程实时展示:
|
||
① 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)) && (
|
||
<div className="px-4 pb-2">
|
||
<SkillStepsCard steps={state.skillSearchSteps} inProgress />
|
||
</div>
|
||
)}
|
||
|
||
{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 && (
|
||
<div className="px-4 pb-4">
|
||
<WritingSkeletonCard
|
||
status={state.status}
|
||
researchProgress={state.researchProgress}
|
||
organizing={!!state.request?.userOutline}
|
||
/>
|
||
</div>
|
||
)}
|
||
|
||
{isError && state.error && (
|
||
<div className="mx-4 mt-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">
|
||
{state.error}
|
||
</div>
|
||
)}
|
||
<div ref={bottomRef} className="h-px" aria-hidden="true" />
|
||
</div>{/* 滚动内容区结束 */}
|
||
|
||
{/* 回到底部悬浮按钮:生成中且用户已上划时出现 */}
|
||
{isRunning && !autoScroll && (
|
||
<div className="absolute inset-x-0 bottom-4 flex justify-center z-10 pointer-events-none">
|
||
<button
|
||
onClick={scrollToBottom}
|
||
className="pointer-events-auto flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full bg-background border shadow-md hover:bg-muted transition-colors whitespace-nowrap"
|
||
>
|
||
<ChevronsDown className="size-3.5" />
|
||
回到底部
|
||
</button>
|
||
</div>
|
||
)}
|
||
</div>{/* 相对定位容器结束 */}
|
||
|
||
{/* 状态栏 */}
|
||
{!isIdle && !isHistoryMode && (
|
||
<div
|
||
className={cn(
|
||
'shrink-0 px-4 py-2 border-t text-xs flex items-center gap-2',
|
||
isError ? 'text-destructive' : 'text-muted-foreground',
|
||
)}
|
||
>
|
||
{ENABLE_PAUSE_RESUME_UI && state.isPaused ? (
|
||
<>
|
||
<span className="inline-block size-1.5 rounded-full bg-amber-400" />
|
||
已暂停
|
||
</>
|
||
) : (
|
||
<>
|
||
{isRunning && (
|
||
<span className="inline-block size-1.5 rounded-full bg-blue-500 animate-pulse" />
|
||
)}
|
||
{state.status === 'researching' && state.researchProgress
|
||
? state.researchProgress
|
||
: state.status === 'writing_outline' && state.request?.userOutline
|
||
? '作家整理你的大纲中…'
|
||
: STATUS_LABEL[state.status] ?? state.status}
|
||
</>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{/* 查看进度流程图弹窗:点击历史里的「挂起中」记录时打开 */}
|
||
<AIWritingFlowDialog
|
||
session={progressSession}
|
||
open={progressSession !== null}
|
||
onOpenChange={(o) => { if (!o) setProgressSession(null); }}
|
||
/>
|
||
|
||
{/* 写作参数查看弹窗 */}
|
||
{state.request && (
|
||
<Dialog open={reqDialogOpen} onOpenChange={setReqDialogOpen}>
|
||
<DialogContent className="sm:max-w-md">
|
||
<DialogHeader>
|
||
<DialogTitle>本次写作参数</DialogTitle>
|
||
</DialogHeader>
|
||
<div className="space-y-3 py-1 text-sm">
|
||
<ReqRow label="写作意图">
|
||
<p className="text-muted-foreground whitespace-pre-wrap leading-relaxed">{state.request.userIntent}</p>
|
||
</ReqRow>
|
||
<ReqRow label="文章类型">
|
||
<span className="text-muted-foreground">
|
||
{articleTypes.find((t) => t.key === state.request!.articleType)?.label ?? state.request.articleType}
|
||
</span>
|
||
</ReqRow>
|
||
{!hideAdvancedFields && (
|
||
<ReqRow label="目标读者">
|
||
<span className="text-muted-foreground">{state.request.targetAudience}</span>
|
||
</ReqRow>
|
||
)}
|
||
<ReqRow label="目标字数">
|
||
<span className="text-muted-foreground">{state.request.wordCountTarget} 字</span>
|
||
</ReqRow>
|
||
{!hideAdvancedFields && (
|
||
<>
|
||
<ReqRow label="检索关键词数量">
|
||
<span className="text-muted-foreground">{state.request.keywordCount} 个</span>
|
||
</ReqRow>
|
||
<ReqRow label="写作模式">
|
||
<span className="text-muted-foreground">
|
||
{state.request.writingMode === 'strict' ? '严格依据素材' : '宽松(可结合通用知识)'}
|
||
</span>
|
||
</ReqRow>
|
||
</>
|
||
)}
|
||
{state.request.modelName && (
|
||
<ReqRow label="写作模型">
|
||
<span className="text-muted-foreground">{state.request.modelName}</span>
|
||
</ReqRow>
|
||
)}
|
||
</div>
|
||
</DialogContent>
|
||
</Dialog>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ReqRow({ label, children }: { label: string; children: React.ReactNode }) {
|
||
return (
|
||
<div className="space-y-0.5">
|
||
<p className="text-xs font-medium text-foreground/60">{label}</p>
|
||
{children}
|
||
</div>
|
||
);
|
||
}
|