feat(ai写作): 左栏智能体 Tab 内嵌问答并优化模块侧栏

AI 写作页默认展示智能体 Tab,在页内复用 ai-writing 模块配置与 AgentChatPage;确认类型后侧栏扁平展示类型名并支持整块收起动画。同步历史回看、流式续跑、改写菜单与 researcher 检索相关改动。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-06-27 15:53:51 +08:00
1 parent c11307aa67
commit 5de74e90dc
21 files changed
+1379 -386

No files matched your search

@@ -1,88 +1,370 @@
import { useMemo } from 'react';
import { CheckCircle2, ChevronRight, FileText, Search, PenLine, ClipboardEdit, Star } from 'lucide-react';
import type { AIWritingSessionSummary, CompletedInterventionRecord } from '../../api/ai-writing-sessions';
import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
import {
normalizeProgressDict,
normalizeMaterial,
normalizeOutline,
normalizeReviewResult,
} from '../../hooks/useAIWritingStream';
import type { CompletedIntervention } from '../../types/ai-writing';
import type { CompletedIntervention, ProgressEvent, ReviewResult } from '../../types/ai-writing';
import { countArticleWords } from '../../utils/wordCount';
import { AIWritingTimeline } from './AIWritingTimeline';
/**
* 归一化一条 completedIntervention(后台挂起重建的干预记录里素材/大纲/审核数据是
* snake_case,前端干预卡期望 camelCase)。对前端实时存的 camelCase 记录幂等。
*/
function normalizeCompletedIntervention(rec: Record<string, unknown>): CompletedIntervention {
const out: Record<string, unknown> = { ...rec };
out.pausePoint = rec.pausePoint ?? rec.pause_point;
const PAUSE_POINTS = new Set<CompletedIntervention['pausePoint']>([
'material_confirm',
'outline_confirm',
'draft_confirm',
'review_confirm',
'section_help',
]);
const PAUSE_MESSAGES: Record<CompletedIntervention['pausePoint'], string> = {
material_confirm: '素材收集专家已完成素材搜集,请确认素材后继续。',
outline_confirm: '作家已完成大纲规划,请确认或编辑大纲后继续。',
draft_confirm: '草稿已完成,请确认或给出修改意见。',
review_confirm: '编辑认为文章需要修改,请决定下一步操作。',
section_help: '部分章节缺少足够素材支撑写作,请决定如何处理。',
};
interface TimelineSnapshot {
materials?: CompletedIntervention['materials'];
outline?: CompletedIntervention['outline'];
draftTitle?: string;
draftWordCount?: number;
reviewResult?: ReviewResult | null;
}
function asPausePoint(value: unknown): CompletedIntervention['pausePoint'] | null {
const pausePoint = String(value ?? '');
return PAUSE_POINTS.has(pausePoint as CompletedIntervention['pausePoint'])
? (pausePoint as CompletedIntervention['pausePoint'])
: null;
}
function normalizeCompletedIntervention(rec: Record<string, unknown>): CompletedIntervention | null {
const pausePoint = asPausePoint(rec.pausePoint ?? rec.pause_point);
if (!pausePoint) return null;
const out: CompletedIntervention = {
pausePoint,
action: String(rec.action ?? defaultActionForPause(pausePoint)),
};
if (Array.isArray(rec.materials)) {
out.materials = (rec.materials as Record<string, unknown>[]).map(normalizeMaterial);
}
if (rec.outline) out.outline = normalizeOutline(rec.outline);
const rr = rec.reviewResult ?? rec.review_result;
if (rr) out.reviewResult = normalizeReviewResult(rr);
if (out.draftTitle == null && rec.draft_title != null) out.draftTitle = rec.draft_title;
if (out.draftWordCount == null && rec.draft_word_count != null) out.draftWordCount = rec.draft_word_count;
if (out.userInput == null && rec.user_input != null) out.userInput = rec.user_input;
return out as unknown as CompletedIntervention;
const outline = normalizeOutline(rec.outline);
if (outline) out.outline = outline;
const reviewResult = normalizeReviewResult(rec.reviewResult ?? rec.review_result);
if (reviewResult) out.reviewResult = reviewResult;
const draftTitle = rec.draftTitle ?? rec.draft_title;
if (typeof draftTitle === 'string' && draftTitle.trim()) out.draftTitle = draftTitle;
const draftWordCount = Number(rec.draftWordCount ?? rec.draft_word_count);
if (Number.isFinite(draftWordCount) && draftWordCount > 0) {
out.draftWordCount = draftWordCount;
}
const userInput =
rec.userInput ??
rec.user_input ??
rec.userQuery ??
rec.user_query ??
rec.outlineFeedback ??
rec.outline_feedback ??
rec.userRevisionNotes ??
rec.user_revision_notes;
if (typeof userInput === 'string' && userInput.trim()) out.userInput = userInput;
return out;
}
const PAUSE_LABELS: Record<string, string> = {
material_confirm: '素材确认',
outline_confirm: '大纲确认',
draft_confirm: '草稿确认',
review_confirm: '编辑意见处理',
};
function normalizeInterventionList(records: unknown): CompletedIntervention[] {
if (!Array.isArray(records)) return [];
return records
.map((rec) => (
rec && typeof rec === 'object'
? normalizeCompletedIntervention(rec as Record<string, unknown>)
: null
))
.filter((rec): rec is CompletedIntervention => rec != null);
}
const ACTION_LABELS: Record<string, string> = {
approve: '已批准',
re_search: '重新搜索',
re_outline: '重新规划',
finalize: '直接定稿',
to_editor: '提交审核',
user_revise: '手动修改',
accept_review: '接受意见',
force_finalize: '强制定稿',
};
function defaultActionForPause(pausePoint: CompletedIntervention['pausePoint']): string {
switch (pausePoint) {
case 'draft_confirm':
return 'to_editor';
case 'review_confirm':
return 'accept_review';
case 'section_help':
return 'section_help';
default:
return 'confirm';
}
}
const PAUSE_ICONS: Record<string, React.ElementType> = {
material_confirm: Search,
outline_confirm: PenLine,
draft_confirm: FileText,
review_confirm: ClipboardEdit,
};
function classifyResumeEvent(message: string): Pick<CompletedIntervention, 'pausePoint' | 'action'> | null {
const m = message || '';
if (m.includes('确认素材')) return { pausePoint: 'material_confirm', action: 'confirm' };
if (m.includes('匹配技能检索') || m.includes('重新检索') || m.includes('重新搜索')) {
return { pausePoint: 'material_confirm', action: 're_search' };
}
if (m.includes('确认大纲')) return { pausePoint: 'outline_confirm', action: 'confirm' };
if (m.includes('重新规划大纲')) return { pausePoint: 'outline_confirm', action: 're_outline' };
if (m.includes('提交编辑审核')) return { pausePoint: 'draft_confirm', action: 'to_editor' };
if (m.includes('强制定稿')) return { pausePoint: 'review_confirm', action: 'force_finalize' };
if (m.includes('确认定稿')) return { pausePoint: 'draft_confirm', action: 'finalize' };
if (m.includes('按用户意见重写')) return { pausePoint: 'draft_confirm', action: 'user_revise' };
if (m.includes('按编辑意见重写')) return { pausePoint: 'review_confirm', action: 'accept_review' };
if (m.includes('补充检索素材')) return { pausePoint: 'section_help', action: 'supplement' };
if (m.includes('继续写作')) return { pausePoint: 'section_help', action: 'loose' };
return null;
}
function InterventionTimelineItem({ record, isLast }: { record: CompletedInterventionRecord; isLast: boolean }) {
const Icon = PAUSE_ICONS[record.pausePoint] ?? CheckCircle2;
const ts = record.timestamp
? new Date(record.timestamp).toLocaleString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
: '';
function actionFromNextResume(
pausePoint: CompletedIntervention['pausePoint'],
events: ProgressEvent[],
startIndex: number,
): string {
for (let i = startIndex; i < events.length; i += 1) {
const event = events[i];
if (event.type === 'await_user') break;
if (event.type !== 'resumed') continue;
const classified = classifyResumeEvent(event.message);
if (classified?.pausePoint === pausePoint) return classified.action;
break;
}
return defaultActionForPause(pausePoint);
}
return (
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
<Icon className="w-3 h-3 text-primary" />
</div>
{!isLast && <div className="w-px flex-1 bg-border/60 mt-1" />}
</div>
<div className="pb-4 min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-xs font-medium">
{PAUSE_LABELS[record.pausePoint] ?? record.pausePoint}
</span>
<ChevronRight className="w-3 h-3 text-muted-foreground" />
<span className="text-xs text-primary font-medium">
{ACTION_LABELS[record.action] ?? record.action}
</span>
</div>
{ts && <p className="text-[10px] text-muted-foreground mt-0.5">{ts}</p>}
</div>
</div>
);
function materialsFromEvent(event: ProgressEvent | undefined): CompletedIntervention['materials'] | undefined {
if (!event) return undefined;
if (event.materials?.length) return event.materials;
const raw = event.pauseContext?.materials;
return Array.isArray(raw)
? raw.map((item) => normalizeMaterial(item as Record<string, unknown>))
: undefined;
}
function outlineFromEvent(event: ProgressEvent | undefined): CompletedIntervention['outline'] | undefined {
if (!event) return undefined;
if (event.outline) return event.outline;
const outline = normalizeOutline(event.pauseContext?.outline);
return outline ?? undefined;
}
function reviewFromEvent(event: ProgressEvent | undefined): ReviewResult | null | undefined {
if (!event) return undefined;
if (event.reviewResult) return event.reviewResult;
return normalizeReviewResult(event.pauseContext?.reviewResult ?? event.pauseContext?.review_result) ?? undefined;
}
function updateSnapshot(snapshot: TimelineSnapshot, event: ProgressEvent): void {
if (event.type === 'materials_ready' && event.materials) {
snapshot.materials = event.materials;
}
if (event.type === 'outline_ready' && event.outline) {
snapshot.outline = event.outline;
}
if (event.type === 'draft_ready') {
if (event.draftTitle) snapshot.draftTitle = event.draftTitle;
if (event.draftMarkdown) snapshot.draftWordCount = countArticleWords(event.draftMarkdown);
}
if (event.type === 'review_ready' && event.reviewResult) {
snapshot.reviewResult = event.reviewResult;
}
}
function enrichIntervention(
record: CompletedIntervention,
sourceEvent: ProgressEvent | undefined,
snapshot: TimelineSnapshot,
sessionDraftTitle: string | null,
sessionDraftMarkdown: string | null,
sessionReviewResult: ReviewResult | null,
): CompletedIntervention {
const enriched: CompletedIntervention = { ...record };
if (record.pausePoint === 'material_confirm') {
enriched.materials = record.materials?.length
? record.materials
: (materialsFromEvent(sourceEvent) ?? snapshot.materials ?? []);
}
if (record.pausePoint === 'outline_confirm') {
enriched.outline = record.outline ?? outlineFromEvent(sourceEvent) ?? snapshot.outline;
}
if (record.pausePoint === 'draft_confirm') {
enriched.draftTitle =
record.draftTitle ??
sourceEvent?.draftTitle ??
snapshot.draftTitle ??
sessionDraftTitle ??
undefined;
enriched.draftWordCount =
record.draftWordCount ??
snapshot.draftWordCount ??
(sessionDraftMarkdown ? countArticleWords(sessionDraftMarkdown) : undefined);
enriched.reviewResult =
record.reviewResult ??
reviewFromEvent(sourceEvent) ??
snapshot.reviewResult ??
sessionReviewResult ??
undefined;
}
if (record.pausePoint === 'review_confirm') {
enriched.reviewResult =
record.reviewResult ??
reviewFromEvent(sourceEvent) ??
snapshot.reviewResult ??
sessionReviewResult ??
undefined;
}
return enriched;
}
function synthesizeInterventions(
events: ProgressEvent[],
sessionDraftTitle: string | null,
sessionDraftMarkdown: string | null,
sessionReviewResult: ReviewResult | null,
): CompletedIntervention[] {
const records: CompletedIntervention[] = [];
const snapshot: TimelineSnapshot = {
draftTitle: sessionDraftTitle ?? undefined,
draftWordCount: sessionDraftMarkdown ? countArticleWords(sessionDraftMarkdown) : undefined,
reviewResult: sessionReviewResult,
};
const hasAwaitUser = events.some((event) => event.type === 'await_user');
for (let i = 0; i < events.length; i += 1) {
const event = events[i];
if (event.type === 'await_user') {
const pausePoint = asPausePoint(event.pausePoint);
if (pausePoint) {
const record: CompletedIntervention = {
pausePoint,
action: actionFromNextResume(pausePoint, events, i + 1),
};
records.push(
enrichIntervention(
record,
event,
snapshot,
sessionDraftTitle,
sessionDraftMarkdown,
sessionReviewResult,
),
);
}
} else if (!hasAwaitUser && event.type === 'resumed') {
const classified = classifyResumeEvent(event.message);
if (classified) {
records.push(
enrichIntervention(
classified,
event,
snapshot,
sessionDraftTitle,
sessionDraftMarkdown,
sessionReviewResult,
),
);
}
}
updateSnapshot(snapshot, event);
}
return records;
}
function mergeIntervention(primary: CompletedIntervention, fallback: CompletedIntervention): CompletedIntervention {
const defaultAction = defaultActionForPause(primary.pausePoint);
const action = primary.action === defaultAction && fallback.action
? fallback.action
: (primary.action || fallback.action);
return {
pausePoint: primary.pausePoint,
action,
userInput: primary.userInput ?? fallback.userInput,
materials: primary.materials?.length ? primary.materials : fallback.materials,
outline: primary.outline ?? fallback.outline,
draftTitle: primary.draftTitle ?? fallback.draftTitle,
draftWordCount: primary.draftWordCount ?? fallback.draftWordCount,
reviewResult: primary.reviewResult ?? fallback.reviewResult,
};
}
function mergeInterventionLists(
synthesized: CompletedIntervention[],
transcriptRecords: CompletedIntervention[],
sessionRecords: CompletedIntervention[],
): CompletedIntervention[] {
const max = Math.max(synthesized.length, transcriptRecords.length, sessionRecords.length);
const merged: CompletedIntervention[] = [];
for (let i = 0; i < max; i += 1) {
const anchor = synthesized[i] ?? transcriptRecords[i] ?? sessionRecords[i];
if (!anchor) continue;
let record = anchor;
const candidates = [transcriptRecords[i], sessionRecords[i]];
for (const candidate of candidates) {
if (!candidate || candidate.pausePoint !== record.pausePoint) continue;
record = mergeIntervention(record, candidate);
}
merged.push(record);
}
return merged;
}
function eventFromIntervention(record: CompletedIntervention, sessionId: string): ProgressEvent {
return {
type: 'await_user',
sessionId,
message: PAUSE_MESSAGES[record.pausePoint],
pausePoint: record.pausePoint,
materials: record.materials,
outline: record.outline,
reviewResult: record.reviewResult,
draftTitle: record.draftTitle,
};
}
function ensureInterventionAnchors(
events: ProgressEvent[],
records: CompletedIntervention[],
sessionId: string,
): ProgressEvent[] {
if (events.some((event) => event.type === 'await_user')) return events;
if (records.length === 0) return events;
if (events.length === 0) return records.map((record) => eventFromIntervention(record, sessionId));
const nextEvents: ProgressEvent[] = [];
let recordIndex = 0;
for (const event of events) {
if (event.type === 'resumed' && recordIndex < records.length) {
nextEvents.push(eventFromIntervention(records[recordIndex], sessionId));
recordIndex += 1;
}
nextEvents.push(event);
}
while (recordIndex < records.length) {
nextEvents.push(eventFromIntervention(records[recordIndex], sessionId));
recordIndex += 1;
}
return nextEvents;
}
interface AIWritingHistoryViewProps {
@@ -90,26 +372,42 @@ interface AIWritingHistoryViewProps {
}
export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
const interventions = session.completed_interventions ?? [];
const transcript = session.transcript;
// 有完整时间线快照时,复用实时对话的 AIWritingTimeline 渲染,保证回显与实时一致
const hasTranscript = !!transcript && (transcript.progressEvents?.length ?? 0) > 0;
// 归一化 transcript 事件:后台挂起跑出的事件是 raw(snake_case),前端实时存的是
// camelCase——统一过一遍 normalizeProgressDict(幂等),两种来源回显都正确一致。
const sessionReviewResult = useMemo(
() => normalizeReviewResult(session.review_result),
[session.review_result],
);
const normalizedEvents = useMemo(
() => (transcript?.progressEvents ?? []).map(
(e) => normalizeProgressDict(e as unknown as Record<string, unknown>, session.id),
(event) => normalizeProgressDict(event as unknown as Record<string, unknown>, session.id),
),
[transcript, session.id],
);
// 干预记录同样归一化(后台重建的素材/大纲/审核数据为 snake_case;前端实时记录已是
// camelCase,归一化幂等),保证素材列表/大纲/编辑审核卡片正确渲染。
const normalizedInterventions = useMemo(
() => (transcript?.completedInterventions ?? []).map(
(rec) => normalizeCompletedIntervention(rec as unknown as Record<string, unknown>),
),
const transcriptInterventions = useMemo(
() => normalizeInterventionList(transcript?.completedInterventions),
[transcript],
);
const sessionInterventions = useMemo(
() => normalizeInterventionList(session.completed_interventions),
[session.completed_interventions],
);
const synthesizedInterventions = useMemo(
() => synthesizeInterventions(
normalizedEvents,
session.draft_title,
session.draft_markdown,
sessionReviewResult,
),
[normalizedEvents, session.draft_title, session.draft_markdown, sessionReviewResult],
);
const completedInterventions = useMemo(
() => mergeInterventionLists(synthesizedInterventions, transcriptInterventions, sessionInterventions),
[synthesizedInterventions, transcriptInterventions, sessionInterventions],
);
const timelineEvents = useMemo(
() => ensureInterventionAnchors(normalizedEvents, completedInterventions, session.id),
[normalizedEvents, completedInterventions, session.id],
);
const createdAt = session.created_at
? new Date(session.created_at).toLocaleString('zh-CN', {
year: 'numeric', month: 'short', day: 'numeric',
@@ -119,7 +417,6 @@ export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
return (
<div className="flex-1 overflow-y-auto">
{/* 元信息 */}
<div className="px-4 pt-3">
<div className="rounded-lg border bg-muted/30 px-3 py-2.5 space-y-1">
<p className="text-xs font-semibold truncate">{session.draft_title ?? session.title}</p>
@@ -134,39 +431,15 @@ export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
</div>
</div>
{hasTranscript ? (
/* 完整对话时间线回显 */
{timelineEvents.length > 0 ? (
<AIWritingTimeline
events={normalizedEvents}
completedInterventions={normalizedInterventions}
events={timelineEvents}
completedInterventions={completedInterventions}
currentPause={null}
/>
) : (
/* 旧会话无时间线快照时,回退到精简阶段列表 */
<div className="px-4 py-3 space-y-4">
{interventions.length > 0 ? (
<div>
<p className="text-[11px] font-medium text-muted-foreground mb-2">写作阶段</p>
<div>
{interventions.map((rec, i) => (
<InterventionTimelineItem
key={i}
record={rec}
isLast={i === interventions.length - 1}
/>
))}
</div>
</div>
) : (
<div className="text-center py-4 text-xs text-muted-foreground">无阶段记录</div>
)}
{session.status === 'done' && (
<div className="flex items-center gap-2 text-xs text-green-600 dark:text-green-400">
<Star className="w-3.5 h-3.5" />
<span>写作完成</span>
</div>
)}
<div className="px-4 py-6 text-center text-xs text-muted-foreground">
暂无阶段记录
</div>
)}
</div>
@@ -32,6 +32,7 @@ import {
* 已完成阶段不重来;见 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';
@@ -80,7 +81,7 @@ export function AIWritingPanel({
} = {}) {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const { state, startWriting, submitIntervention, pauseWriting, resumeWriting, reset } = useAIWriting();
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();
@@ -198,6 +199,15 @@ export function AIWritingPanel({
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;
// 历史下拉靠乐观标记马上显示「挂起中」,不等后端确认。
@@ -307,19 +317,33 @@ export function AIWritingPanel({
)}
{/* 头部 */}
<div className="flex items-center justify-between px-4 py-2.5 border-b shrink-0">
<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',
<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>
)}
onClick={() => { if (!isIdle && !isHistoryMode && state.request) setReqDialogOpen(true); }}
title={isHistoryMode ? (historySession?.draft_title ?? historySession?.title) : undefined}
>
{isHistoryMode
? (historySession?.draft_title ?? historySession?.title ?? '写作历史')
: 'AI 智能写作'}
</span>
<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
@@ -8,7 +8,6 @@ import { buildIntranetSourceUrl } from '@/core/config';
import type { AIMaterial, CompletedIntervention } from '../../types/ai-writing';
import { OutlineCard } from './OutlineCard';
import { ReviewCard } from './ReviewCard';
import { ScoreBar } from './ScoreBar';
import { CollapseTransition } from './CollapseTransition';
interface Props {
@@ -282,14 +281,8 @@ function ReviewCompleted({ record, expanded, onToggle }: { record: CompletedInte
</button>
<CollapseTransition open={expanded && !!record.reviewResult}>
<div className="px-2.5 pb-2.5 pt-1 space-y-1.5 border-t border-green-200/40 dark:border-green-900/20">
{record.reviewResult && (
<>
<ScoreBar label="事实准确性" score={record.reviewResult.factScore} />
<ScoreBar label="逻辑结构" score={record.reviewResult.logicScore} />
<ScoreBar label="语言文字" score={record.reviewResult.languageScore} />
</>
)}
<div className="px-2.5 pb-2.5 pt-1 border-t border-green-200/40 dark:border-green-900/20">
{record.reviewResult && <ReviewCard review={record.reviewResult} />}
</div>
</CollapseTransition>
</div>
@@ -12,7 +12,6 @@ import {
Newspaper,
PanelLeftClose,
Pencil,
Play,
Plus,
RefreshCw,
Search,
@@ -110,17 +109,12 @@ const WRITING_STATUS_PILL: Record<string, { label: string; className: string; sp
error: { label: "出错", className: "text-rose-500" },
};
/** 可「继续未完成」的状态:有可恢复的 checkpoint(mid-stage 或停在确认点)。done/error 终态、
* background 自有进度弹窗,都不算。 */
const RESUMABLE_STATUSES = new Set(["in_progress", "draft_ready", "review_ready"]);
/** 单条历史记录项 —— 样式参考多智能体会商的 HistoryDropdown 列表项(圆角卡片 + 状态药丸 + 操作按钮)。 */
function WritingHistoryItem({
session,
isCurrent,
onSelect,
onShowProgress,
onContinue,
onDelete,
onRename,
}: {
@@ -128,8 +122,6 @@ function WritingHistoryItem({
isCurrent: boolean;
onSelect: () => void;
onShowProgress?: () => void;
/** 继续这条未完成的会话(从 checkpoint 续跑当前阶段 / 显示确认卡)。 */
onContinue?: () => void;
onDelete: () => void;
onRename: (title: string) => void;
}) {
@@ -137,10 +129,9 @@ function WritingHistoryItem({
const [value, setValue] = useState(session.title);
const inputRef = useRef<HTMLInputElement>(null);
const isBackground = session.status === "background";
const canContinue = !!onContinue && RESUMABLE_STATUSES.has(session.status);
// 行/标题主点击:未完成→继续续跑;挂起中→看进度弹窗;其余(完成/出错)→只读历史回看。
const primary = isBackground && onShowProgress ? onShowProgress : (canContinue ? onContinue! : onSelect);
const primaryTitle = isBackground ? "查看进度" : canContinue ? "继续未完成" : "打开历史";
// Row/title click only opens the history view; restore starts from the detail header.
const primary = isBackground && onShowProgress ? onShowProgress : onSelect;
const primaryTitle = isBackground ? "查看进度" : "打开历史";
const pill = WRITING_STATUS_PILL[session.status] ?? { label: session.status, className: "text-slate-400" };
useEffect(() => {
@@ -200,16 +191,6 @@ function WritingHistoryItem({
{!renaming && (
<div className="flex shrink-0 items-center gap-0.5">
{canContinue && (
<button
type="button"
onClick={onContinue}
title="继续未完成"
className="rounded p-1 text-emerald-500 transition hover:bg-emerald-50 hover:text-emerald-600"
>
<Play className="size-3.5 fill-current" />
</button>
)}
<button
type="button"
onClick={isBackground && onShowProgress ? onShowProgress : onSelect}
@@ -258,7 +239,7 @@ export function ResearchSidebar({
}) {
const navigate = useNavigate();
const { templates, refresh } = useResearchTemplates();
const { startWriting, continueWriting } = useAIWriting();
const { startWriting } = useAIWriting();
const {
notebooks,
isLoading: notebooksLoading,
@@ -286,7 +267,7 @@ export function ResearchSidebar({
rename: renameSession,
remove: removeSession,
} = useAIWritingSessions();
const { openHistory, closeHistory, historySession } = useAIWritingHistory();
const { openHistory, historySession } = useAIWritingHistory();
// 进入/返回写作配置页时刷新一次历史(本侧栏仅在 idle 态挂载,故等同每次回到表单刷新)。
useEffect(() => {
@@ -296,11 +277,6 @@ export function ResearchSidebar({
const handleSelectHistory = (session: AIWritingSessionSummary) => {
void openHistory(session);
};
// 「继续未完成」:退出只读历史态(若在),把该会话设为活跃并从 checkpoint 续跑。
const handleContinue = (session: AIWritingSessionSummary) => {
closeHistory();
continueWriting(session.id);
};
// 「挂起中」记录:交给右侧面板打开进度流程图弹窗(沿用面板已有的 window 事件解耦模式,
// 与 ai-writing:open-session 一致),本侧栏不直接持有弹窗状态。
const handleShowProgress = (session: AIWritingSessionSummary) => {
@@ -617,7 +593,6 @@ export function ResearchSidebar({
isCurrent={s.id === (historySession?.id ?? null)}
onSelect={() => handleSelectHistory(s)}
onShowProgress={() => handleShowProgress(s)}
onContinue={() => handleContinue(s)}
onDelete={() => removeSession(s.id)}
onRename={(title) => renameSession(s.id, title)}
/>