635 lines
26 KiB
TypeScript
635 lines
26 KiB
TypeScript
/**
|
||
* AI 写作前端 hook —— LangGraph Server 路径(阶段 3)。
|
||
*
|
||
* 对外 API 与老 hook ``useAIWriting`` 完全一致:返回
|
||
* ``{ state, startWriting, submitIntervention, pauseWriting, resumeWriting, reset }``,
|
||
* 所以 ``AIWritingPanel`` 只需要按 env 开关切 import,不用改任何组件。
|
||
*
|
||
* 底层差别(参见 ai-writing-优化.md §阶段 3):
|
||
* - 老 hook 走 ``POST /start`` + ``GET /{id}/stream`` + ``POST /{id}/resume`` 自写 SSE
|
||
* - 本 hook 用 ``@langchain/langgraph-sdk/react`` 的 ``useStream``,assistant=``ai_writing``,
|
||
* thread 和 SSE 协议都交给 LangGraph Server 管。``resume`` 改成 ``Command(resume=...)``。
|
||
*
|
||
* 事件翻译层:
|
||
* - LangGraph ``custom`` 通道(节点 ``get_stream_writer`` 推) →
|
||
* ``ProgressEvent`` { type=draft_chunk/outline_chunk/research_progress/review_chunk/review_item_done }
|
||
* - LangGraph ``updates`` 通道(节点 return 的 state delta) → 合成
|
||
* ``materials_ready`` / ``outline_ready`` / ``draft_ready`` / ``review_ready`` /
|
||
* ``notice`` / ``step_*`` (后端节点把这些塞进 ``progress_events`` 数组里 return)
|
||
* - ``stream.interrupt`` → ``await_user`` 事件
|
||
*
|
||
* 这样 reducer 逻辑(INITIAL_STATE + switch 各分支)与老 hook 共享同一份代码,
|
||
* 只换"事件源"。阶段 7 删冗余时把老 hook 整个删掉就行。
|
||
*/
|
||
import { countWords } from '../utils/wordCount';
|
||
import type {
|
||
AIWritingRequest,
|
||
AIWritingState,
|
||
AIMaterial,
|
||
AIOutline,
|
||
BlockedSection,
|
||
CompletedIntervention,
|
||
ParsedIntent,
|
||
ProgressEvent,
|
||
ProgressEventType,
|
||
ReviewIssue,
|
||
ReviewResult,
|
||
SkillSearchStep,
|
||
StreamingReviewItem,
|
||
UserInterventionPayload,
|
||
WritingStatus,
|
||
} from '../types/ai-writing';
|
||
|
||
const INITIAL_STATE: AIWritingState = {
|
||
sessionId: null,
|
||
status: 'idle',
|
||
request: null,
|
||
isPaused: false,
|
||
progressEvents: [],
|
||
materials: [],
|
||
outline: null,
|
||
currentDraftMarkdown: '',
|
||
currentDraftTitle: '',
|
||
reviewResult: null,
|
||
revisionCount: 0,
|
||
currentPause: null,
|
||
completedInterventions: [],
|
||
error: null,
|
||
streamingDraftTitle: '',
|
||
streamingDraftSections: [],
|
||
outlineStreamingText: '',
|
||
outlineThinkingText: '',
|
||
intentStreamingText: '',
|
||
intentThinkingText: '',
|
||
parsedIntent: null,
|
||
researchProgress: '',
|
||
skillSearchSteps: [],
|
||
skillSelectStreamingText: '',
|
||
skillSelectThinkingText: '',
|
||
skillSearchPending: false,
|
||
streamingReviewItems: [],
|
||
revisionSummary: null,
|
||
pendingRevisionContext: null,
|
||
};
|
||
|
||
export { INITIAL_STATE };
|
||
|
||
// reducer action:HANDLE 直接复用老 hook 的 handleEvent switch;剩下的 action 处理
|
||
// 启动 / 干预提交 / 暂停 / 恢复 / 重置 这些"指令式"状态变更。
|
||
export type Action =
|
||
| { type: 'handle'; event: ProgressEvent }
|
||
| { type: 'handle_batch'; events: ProgressEvent[] }
|
||
| { type: 'start'; request: AIWritingRequest }
|
||
| { type: 'set_session'; sessionId: string }
|
||
| { type: 'intervention_submitted'; record: CompletedIntervention; nextStatus: WritingStatus; pendingRevisionContext: AIWritingState['pendingRevisionContext'] }
|
||
| { type: 'pause' }
|
||
| { type: 'resume_ui' }
|
||
| { type: 'reset' }
|
||
| { type: 'set_error'; message: string };
|
||
|
||
export function reducer(prev: AIWritingState, action: Action): AIWritingState {
|
||
switch (action.type) {
|
||
case 'handle':
|
||
return handleEvent(prev, action.event);
|
||
|
||
case 'handle_batch':
|
||
return action.events.reduce(handleEvent, prev);
|
||
|
||
case 'start':
|
||
return { ...INITIAL_STATE, status: 'researching', request: action.request };
|
||
|
||
case 'set_session':
|
||
return { ...prev, sessionId: action.sessionId };
|
||
|
||
case 'intervention_submitted': {
|
||
const ns = action.nextStatus;
|
||
// 点击瞬间标记技能检索 pending(动机 = 用户的 action 类型),让 SkillStepsCard 占位卡立即挂载
|
||
const enablingSkillSearch = action.record.action === 'enable_skill_search';
|
||
return {
|
||
...prev,
|
||
currentPause: null,
|
||
status: ns,
|
||
skillSearchPending: enablingSkillSearch ? true : prev.skillSearchPending,
|
||
...(ns === 'researching' ? { researchProgress: '', skillSearchSteps: [], skillSelectStreamingText: '', skillSelectThinkingText: '' } : {}),
|
||
...(ns === 'writing_outline' ? { outlineStreamingText: '', outlineThinkingText: '' } : {}),
|
||
...(ns === 'writing_draft' ? { streamingDraftSections: [], streamingDraftTitle: '' } : {}),
|
||
...(ns === 'reviewing' ? { streamingReviewItems: [] } : {}),
|
||
...(ns === 'revising' ? { streamingDraftSections: [], streamingDraftTitle: '' } : {}),
|
||
completedInterventions: [...prev.completedInterventions, action.record],
|
||
...(action.pendingRevisionContext ? { pendingRevisionContext: action.pendingRevisionContext } : {}),
|
||
};
|
||
}
|
||
|
||
case 'pause':
|
||
return { ...prev, isPaused: true };
|
||
|
||
case 'resume_ui':
|
||
return { ...prev, isPaused: false };
|
||
|
||
case 'reset':
|
||
return INITIAL_STATE;
|
||
|
||
case 'set_error':
|
||
return { ...prev, status: 'error', error: action.message };
|
||
|
||
default:
|
||
return prev;
|
||
}
|
||
}
|
||
|
||
// 把"正在流式生成"的草稿章节拼成 Markdown,用于边写边推送到右侧画布。
|
||
// 拼接格式与后端 writer_draft.py 的 _assemble() 对齐(# 文章标题 / ## 章节标题),
|
||
// 但这里是流式预览版:最终的 draft_ready 仍会用后端规范化后的完整 markdown 覆盖。
|
||
export function assembleStreamingDraftMarkdown(
|
||
sections: AIWritingState['streamingDraftSections'],
|
||
title: string,
|
||
): string {
|
||
const ordered = [...sections].sort((a, b) => a.sectionIndex - b.sectionIndex);
|
||
const body = ordered
|
||
.map((s) => {
|
||
const heading = s.sectionTitle ? `## ${s.sectionTitle}` : '';
|
||
const text = s.text ?? '';
|
||
return heading ? `${heading}\n\n${text}` : text;
|
||
})
|
||
.filter((part) => part.trim().length > 0)
|
||
.join('\n\n');
|
||
const head = title ? `# ${title}\n\n` : '';
|
||
return `${head}${body}`;
|
||
}
|
||
|
||
// 与老 hook 行为对齐的事件 reducer —— 直接从 useAIWriting.ts 移植,删掉 setArtifact 副作用
|
||
// (副作用单独提到 hook 顶层 useEffect 里处理)。
|
||
function handleEvent(prev: AIWritingState, event: ProgressEvent): AIWritingState {
|
||
const base: AIWritingState = {
|
||
...prev,
|
||
progressEvents: [...prev.progressEvents, event],
|
||
};
|
||
|
||
switch (event.type) {
|
||
case 'step_start':
|
||
if (event.agentName === '编辑' && prev.status !== 'reviewing') {
|
||
return { ...base, status: 'reviewing' };
|
||
}
|
||
return base;
|
||
|
||
case 'step_done':
|
||
return base;
|
||
|
||
case 'intent_chunk': {
|
||
const text = (event as unknown as { text: string }).text ?? '';
|
||
const isThinking = (event as unknown as { is_thinking: boolean }).is_thinking ?? false;
|
||
return {
|
||
...prev,
|
||
intentStreamingText: isThinking ? prev.intentStreamingText : prev.intentStreamingText + text,
|
||
intentThinkingText: isThinking ? prev.intentThinkingText + text : prev.intentThinkingText,
|
||
};
|
||
}
|
||
|
||
case 'intent_ready': {
|
||
const ev = event as unknown as {
|
||
articleType?: string;
|
||
article_type?: string;
|
||
targetAudience?: string;
|
||
target_audience?: string;
|
||
wordCountTarget?: number;
|
||
word_count_target?: number;
|
||
refinedIntent?: string;
|
||
refined_intent?: string;
|
||
};
|
||
const parsed: ParsedIntent = {
|
||
articleType: ev.articleType ?? ev.article_type ?? '',
|
||
targetAudience: ev.targetAudience ?? ev.target_audience ?? '',
|
||
wordCountTarget: Number(ev.wordCountTarget ?? ev.word_count_target ?? 800),
|
||
refinedIntent: ev.refinedIntent ?? ev.refined_intent ?? '',
|
||
};
|
||
return {
|
||
...base,
|
||
parsedIntent: parsed,
|
||
intentStreamingText: '',
|
||
intentThinkingText: '',
|
||
};
|
||
}
|
||
|
||
case 'research_progress':
|
||
return { ...base, researchProgress: event.message ?? '' };
|
||
|
||
case 'resumed':
|
||
return { ...base, currentPause: null };
|
||
|
||
case 'skill_search_step': {
|
||
const step = event.skillStep;
|
||
if (!step) return base;
|
||
// select_skills 步骤到达 = LLM 选择完成,清空流式打字缓冲
|
||
const clearStreaming = step.type === 'select_skills'
|
||
? { skillSelectStreamingText: '', skillSelectThinkingText: '' }
|
||
: {};
|
||
return { ...base, skillSearchSteps: [...prev.skillSearchSteps, step], ...clearStreaming };
|
||
}
|
||
|
||
case 'skill_select_chunk': {
|
||
const text = (event as unknown as { text: string }).text ?? '';
|
||
const isThinking = (event as unknown as { is_thinking: boolean }).is_thinking ?? false;
|
||
return {
|
||
...prev,
|
||
skillSelectStreamingText: isThinking ? prev.skillSelectStreamingText : prev.skillSelectStreamingText + text,
|
||
skillSelectThinkingText: isThinking ? prev.skillSelectThinkingText + text : prev.skillSelectThinkingText,
|
||
};
|
||
}
|
||
|
||
case 'materials_ready': {
|
||
// 后端把 pkg.skill_search_steps 一并塞回来时,覆盖前端累积(保证刷新页面回放也对)
|
||
const incomingSteps = (event as unknown as { skillSearchSteps?: SkillSearchStep[] }).skillSearchSteps;
|
||
return {
|
||
...base,
|
||
materials: (event.materials ?? []) as AIMaterial[],
|
||
researchProgress: '',
|
||
...(incomingSteps ? { skillSearchSteps: incomingSteps } : {}),
|
||
};
|
||
}
|
||
|
||
case 'outline_chunk': {
|
||
const text = (event as unknown as { text: string }).text ?? '';
|
||
const isThinking = (event as unknown as { is_thinking: boolean }).is_thinking ?? false;
|
||
return {
|
||
...prev,
|
||
status: 'writing_outline',
|
||
outlineStreamingText: isThinking ? prev.outlineStreamingText : prev.outlineStreamingText + text,
|
||
outlineThinkingText: isThinking ? prev.outlineThinkingText + text : prev.outlineThinkingText,
|
||
};
|
||
}
|
||
|
||
case 'outline_ready':
|
||
return {
|
||
...base,
|
||
outline: (event.outline ?? null) as AIOutline | null,
|
||
outlineStreamingText: '',
|
||
outlineThinkingText: '',
|
||
};
|
||
|
||
case 'draft_chunk': {
|
||
const idx = (event as unknown as { sectionIndex: number }).sectionIndex ?? 0;
|
||
const title = (event as unknown as { sectionTitle: string }).sectionTitle ?? '';
|
||
const text = (event as unknown as { text: string }).text ?? '';
|
||
const isThinking = (event as unknown as { is_thinking: boolean }).is_thinking ?? false;
|
||
const done = (event as unknown as { isSectionDone: boolean }).isSectionDone ?? false;
|
||
const sections = prev.streamingDraftSections.map((s) => ({ ...s }));
|
||
const existing = sections.find((s) => s.sectionIndex === idx);
|
||
if (existing) {
|
||
if (isThinking) existing.thinkingText += text;
|
||
else existing.text += text;
|
||
existing.isDone = done;
|
||
} else {
|
||
sections.push({
|
||
sectionIndex: idx,
|
||
sectionTitle: title,
|
||
text: isThinking ? '' : text,
|
||
thinkingText: isThinking ? text : '',
|
||
isDone: done,
|
||
});
|
||
}
|
||
const streamingTitle = prev.streamingDraftTitle || prev.outline?.title || '';
|
||
// 流式阶段只累积章节片段;右侧 Markdown 由面板按需拼装,避免每 chunk 改 currentDraftMarkdown
|
||
// 触发 DraftSync / 全树重渲染导致更新风暴。
|
||
return {
|
||
...prev,
|
||
status: 'writing_draft',
|
||
streamingDraftSections: sections,
|
||
streamingDraftTitle: streamingTitle,
|
||
currentDraftTitle: streamingTitle || prev.currentDraftTitle,
|
||
};
|
||
}
|
||
|
||
case 'review_chunk': {
|
||
const category = (event as unknown as { category: StreamingReviewItem['category'] }).category;
|
||
const text = (event as unknown as { text: string }).text ?? '';
|
||
const isThinking = (event as unknown as { is_thinking: boolean }).is_thinking ?? false;
|
||
const isNewCycle = prev.status !== 'reviewing';
|
||
const items = (isNewCycle ? [] : prev.streamingReviewItems).map((it) => ({ ...it }));
|
||
let item = items.find((it) => it.category === category);
|
||
if (!item) {
|
||
item = { category, isDone: false, streamingText: '', thinkingText: '', score: 0, issues: [] };
|
||
items.push(item);
|
||
}
|
||
if (isThinking) item.thinkingText += text;
|
||
else item.streamingText += text;
|
||
return { ...prev, status: 'reviewing', streamingReviewItems: items };
|
||
}
|
||
|
||
case 'review_item_done': {
|
||
const category = event.reviewItemCategory ?? 'fact';
|
||
const items = prev.streamingReviewItems.map((it) => ({ ...it }));
|
||
const item = items.find((it) => it.category === category);
|
||
if (item) {
|
||
item.isDone = true;
|
||
item.score = event.reviewItemScore ?? 80;
|
||
item.issues = event.reviewItemIssues ?? [];
|
||
} else {
|
||
items.push({
|
||
category, isDone: true, streamingText: '', thinkingText: '',
|
||
score: event.reviewItemScore ?? 80,
|
||
issues: event.reviewItemIssues ?? [],
|
||
});
|
||
}
|
||
return { ...prev, status: 'reviewing', streamingReviewItems: items };
|
||
}
|
||
|
||
case 'draft_ready': {
|
||
const newMarkdown = event.draftMarkdown ?? '';
|
||
const newWordCount = countWords(newMarkdown);
|
||
const summary = prev.pendingRevisionContext
|
||
? {
|
||
revisedIssues: prev.pendingRevisionContext.submittedIssues,
|
||
skippedIssues: prev.pendingRevisionContext.skippedIssues,
|
||
oldWordCount: prev.pendingRevisionContext.oldWordCount,
|
||
newWordCount,
|
||
}
|
||
: null;
|
||
return {
|
||
...base,
|
||
currentDraftMarkdown: newMarkdown,
|
||
currentDraftTitle: event.draftTitle ?? '',
|
||
revisionCount: event.revisionCount ?? 0,
|
||
streamingDraftSections: [],
|
||
streamingDraftTitle: '',
|
||
revisionSummary: summary,
|
||
pendingRevisionContext: null,
|
||
};
|
||
}
|
||
|
||
case 'review_ready':
|
||
return { ...base, reviewResult: (event.reviewResult ?? null) as ReviewResult | null };
|
||
|
||
case 'await_user': {
|
||
const pp = event.pausePoint;
|
||
if (prev.currentPause?.pausePoint === pp) return prev;
|
||
const pauseStatus = pp ? (`awaiting_${pp}` as AIWritingState['status']) : prev.status;
|
||
const extra: Partial<AIWritingState> = {};
|
||
if (pp === 'material_confirm' && event.materials?.length) extra.materials = event.materials;
|
||
if (pp === 'outline_confirm' && event.outline) extra.outline = event.outline;
|
||
// 进入素材确认(material_confirm)= 技能检索(如果在进行)已经完成,清掉 pending 占位
|
||
const clearPending = pp === 'material_confirm' ? { skillSearchPending: false } : {};
|
||
return { ...base, ...extra, ...clearPending, status: pauseStatus, currentPause: event };
|
||
}
|
||
|
||
case 'done':
|
||
return { ...base, status: 'done', currentPause: null };
|
||
|
||
case 'error': {
|
||
const msg = event.detail
|
||
? `${event.title ?? '出错了'}:${event.detail}`
|
||
: (event.message ?? '未知错误');
|
||
return { ...base, status: 'error', error: msg };
|
||
}
|
||
|
||
case 'notice':
|
||
return base;
|
||
|
||
default:
|
||
return base;
|
||
}
|
||
}
|
||
|
||
// ── snake_case ↔ camelCase 归一化(custom 通道事件 + interrupt payload) ──────
|
||
|
||
function normalizeMaterial(m: Record<string, unknown>): AIMaterial {
|
||
const extra = (m.extra_metadata ?? m.extraMetadata) as Record<string, unknown> | undefined;
|
||
return {
|
||
id: String(m.id ?? ''),
|
||
title: String(m.title ?? ''),
|
||
content: String(m.content ?? ''),
|
||
source: String(m.source ?? ''),
|
||
publishedAt: String(m.published_at ?? m.publishedAt ?? ''),
|
||
relevanceScore: Number(m.relevance_score ?? m.relevanceScore ?? 0),
|
||
sourceType: (m.source_type ?? m.sourceType ?? 'internet') as AIMaterial['sourceType'],
|
||
url: m.url as string | undefined,
|
||
recUuid: (m.recUuid ?? m.rec_uuid) as string | undefined,
|
||
extraMetadata: extra,
|
||
};
|
||
}
|
||
|
||
function normalizeSkillStep(s: Record<string, unknown>): SkillSearchStep {
|
||
return {
|
||
type: (s.type as SkillSearchStep['type']) ?? 'invoke_skill',
|
||
message: String(s.message ?? ''),
|
||
skillNames: (s.skill_names ?? s.skillNames) as string[] | undefined,
|
||
skillName: (s.skill_name ?? s.skillName) as string | undefined,
|
||
reason: s.reason as string | undefined,
|
||
matchedCount: (s.matched_count ?? s.matchedCount) as number | undefined,
|
||
};
|
||
}
|
||
|
||
function normalizeOutlineSection(s: Record<string, unknown>) {
|
||
return {
|
||
sectionTitle: String(s.section_title ?? s.sectionTitle ?? ''),
|
||
keyPoints: (s.key_points ?? s.keyPoints ?? []) as string[],
|
||
materialIds: (s.material_ids ?? s.materialIds ?? []) as string[],
|
||
};
|
||
}
|
||
|
||
function normalizeOutline(o: unknown): AIOutline | null {
|
||
if (!o || typeof o !== 'object') return null;
|
||
const obj = o as Record<string, unknown>;
|
||
return {
|
||
title: String(obj.title ?? ''),
|
||
sections: Array.isArray(obj.sections) ? obj.sections.map((s) => normalizeOutlineSection(s as Record<string, unknown>)) : [],
|
||
};
|
||
}
|
||
|
||
function normalizeReviewIssue(i: Record<string, unknown>): ReviewIssue {
|
||
return {
|
||
category: (i.category as ReviewIssue['category']) ?? 'fact',
|
||
severity: (i.severity as ReviewIssue['severity']) ?? 'minor',
|
||
location: String(i.location ?? ''),
|
||
issue: String(i.issue ?? ''),
|
||
suggestion: String(i.suggestion ?? ''),
|
||
};
|
||
}
|
||
|
||
function normalizeReviewResult(r: unknown): ReviewResult | null {
|
||
if (!r || typeof r !== 'object') return null;
|
||
const o = r as Record<string, unknown>;
|
||
return {
|
||
verdict: (o.verdict as 'pass' | 'reject') ?? 'pass',
|
||
factScore: Number(o.fact_score ?? o.factScore ?? 0),
|
||
logicScore: Number(o.logic_score ?? o.logicScore ?? 0),
|
||
languageScore: Number(o.language_score ?? o.languageScore ?? 0),
|
||
overallScore: Number(o.overall_score ?? o.overallScore ?? 0),
|
||
passThreshold: Number(o.pass_threshold ?? o.passThreshold ?? 75),
|
||
revisionNotes: Array.isArray(o.revision_notes ?? o.revisionNotes)
|
||
? ((o.revision_notes ?? o.revisionNotes) as Array<Record<string, unknown>>).map(normalizeReviewIssue)
|
||
: [],
|
||
};
|
||
}
|
||
|
||
function normalizeBlockedSection(b: Record<string, unknown>): BlockedSection {
|
||
return {
|
||
sectionTitle: String(b.section_title ?? b.sectionTitle ?? ''),
|
||
reason: String(b.reason ?? ''),
|
||
};
|
||
}
|
||
|
||
/** 把后端节点 ``progress_events`` 数组里的一条 dict 翻译成前端 ProgressEvent。 */
|
||
function normalizeProgressDict(parsed: Record<string, unknown>, sessionId: string): ProgressEvent {
|
||
const out: Record<string, unknown> = { ...parsed, sessionId };
|
||
|
||
if ('agent_name' in out) out.agentName = out.agent_name;
|
||
if ('pause_point' in out) out.pausePoint = out.pause_point;
|
||
|
||
if (Array.isArray(out.materials)) out.materials = (out.materials as Record<string, unknown>[]).map(normalizeMaterial);
|
||
if (out.outline) out.outline = normalizeOutline(out.outline);
|
||
|
||
if (Array.isArray(out.blocked_sections)) {
|
||
out.blockedSections = (out.blocked_sections as Record<string, unknown>[]).map(normalizeBlockedSection);
|
||
}
|
||
|
||
// draft_ready: 节点 emit 的字段是 draft_markdown / draft_title
|
||
if ('draft_markdown' in out && !out.draftMarkdown) out.draftMarkdown = out.draft_markdown;
|
||
if ('draft_title' in out && !out.draftTitle) out.draftTitle = out.draft_title;
|
||
if ('markdown' in out && !out.draftMarkdown) out.draftMarkdown = out.markdown;
|
||
if ('title' in out && !out.draftTitle) out.draftTitle = out.title;
|
||
if ('revision_count' in out) out.revisionCount = out.revision_count;
|
||
|
||
if (out.review_result) out.reviewResult = normalizeReviewResult(out.review_result);
|
||
if (out.reviewResult && !out.review_result) out.reviewResult = normalizeReviewResult(out.reviewResult);
|
||
|
||
if ('category' in out) out.reviewItemCategory = out.category;
|
||
if ('score' in out) out.reviewItemScore = out.score;
|
||
if ('issues' in out && Array.isArray(out.issues)) {
|
||
out.reviewItemIssues = (out.issues as Record<string, unknown>[]).map(normalizeReviewIssue);
|
||
}
|
||
|
||
if (!out.message) out.message = '';
|
||
return out as unknown as ProgressEvent;
|
||
}
|
||
|
||
/** custom 通道事件 → ProgressEvent。事件 ``type`` 字段决定是哪类。 */
|
||
export function customToProgressEvent(raw: unknown, sessionId: string): ProgressEvent | null {
|
||
if (!raw || typeof raw !== 'object') return null;
|
||
const o = raw as Record<string, unknown>;
|
||
const type = String(o.type ?? '');
|
||
// 后端 _save_draft_to_repo 等 helper 不走 custom 通道,type 必为节点 emit 的 chunk 类型
|
||
if (!type) return null;
|
||
const allowed: ProgressEventType[] = [
|
||
'intent_chunk', 'intent_ready',
|
||
'research_progress', 'outline_chunk', 'draft_chunk',
|
||
'review_chunk', 'review_item_done',
|
||
'skill_search_step', 'skill_select_chunk',
|
||
];
|
||
if (!allowed.includes(type as ProgressEventType)) return null;
|
||
|
||
// 共通:原样保留所有字段(is_thinking / text / section_index / section_title / category / score / issues)
|
||
const merged: Record<string, unknown> = { ...o, sessionId, message: o.message ?? '' };
|
||
// draft_chunk / outline_chunk 用 camelCase 字段名(reducer 期望)
|
||
if ('section_index' in merged) merged.sectionIndex = merged.section_index;
|
||
if ('section_title' in merged) merged.sectionTitle = merged.section_title;
|
||
if ('is_section_done' in merged) merged.isSectionDone = merged.is_section_done;
|
||
if ('category' in merged) merged.reviewItemCategory = merged.category;
|
||
if ('score' in merged) merged.reviewItemScore = merged.score;
|
||
if (Array.isArray(merged.issues)) {
|
||
merged.reviewItemIssues = (merged.issues as Record<string, unknown>[]).map(normalizeReviewIssue);
|
||
}
|
||
// skill_search_step:把字段折成 skillStep 子对象,方便 reducer / UI 取用
|
||
if (type === 'skill_search_step') {
|
||
merged.skillStep = normalizeSkillStep(o);
|
||
}
|
||
return merged as unknown as ProgressEvent;
|
||
}
|
||
|
||
/** updates 通道里的节点输出 → 一组 ProgressEvent(progress_events + *_ready 合成)。 */
|
||
export function nodeUpdatesToEvents(nodeOutput: unknown, sessionId: string): ProgressEvent[] {
|
||
if (!nodeOutput || typeof nodeOutput !== 'object') return [];
|
||
const out = nodeOutput as Record<string, unknown>;
|
||
const events: ProgressEvent[] = [];
|
||
|
||
// 节点 return 的 progress_events 数组(step_start / step_done / notice / draft_ready / outline_ready / review_ready / resumed / error)
|
||
if (Array.isArray(out.progress_events)) {
|
||
for (const e of out.progress_events as Record<string, unknown>[]) {
|
||
events.push(normalizeProgressDict(e, sessionId));
|
||
}
|
||
}
|
||
|
||
// ``material_package`` 出现 → materials_ready(节点 progress_events 里不带)
|
||
if (out.material_package && typeof out.material_package === 'object') {
|
||
const pkg = out.material_package as Record<string, unknown>;
|
||
const skillSteps = Array.isArray(pkg.skill_search_steps ?? pkg.skillSearchSteps)
|
||
? ((pkg.skill_search_steps ?? pkg.skillSearchSteps) as Record<string, unknown>[]).map(normalizeSkillStep)
|
||
: undefined;
|
||
events.push({
|
||
type: 'materials_ready',
|
||
sessionId,
|
||
message: '',
|
||
materials: Array.isArray(pkg.materials) ? (pkg.materials as Record<string, unknown>[]).map(normalizeMaterial) : [],
|
||
keywords: (pkg.keywords ?? []) as string[],
|
||
materialSummary: (pkg.summary as string) ?? '',
|
||
...(skillSteps ? { skillSearchSteps: skillSteps } as unknown as Partial<ProgressEvent> : {}),
|
||
} as ProgressEvent);
|
||
}
|
||
|
||
// ``current_outline`` 出现且 progress_events 里没 outline_ready → 合成一条
|
||
if (out.current_outline && !events.some((e) => e.type === 'outline_ready')) {
|
||
const outline = normalizeOutline(out.current_outline);
|
||
if (outline) events.push({ type: 'outline_ready', sessionId, message: '', outline });
|
||
}
|
||
|
||
// ``review_result`` 出现且 progress_events 里没 review_ready → 合成一条(带 reviewResult 字段)
|
||
if (out.review_result) {
|
||
const reviewResult = normalizeReviewResult(out.review_result);
|
||
if (reviewResult) {
|
||
// 如果 progress_events 里已有 review_ready(节点 emit 的)但字段不全,补上 reviewResult
|
||
const existing = events.find((e) => e.type === 'review_ready');
|
||
if (existing) {
|
||
existing.reviewResult = reviewResult;
|
||
} else {
|
||
events.push({ type: 'review_ready', sessionId, message: '', reviewResult });
|
||
}
|
||
}
|
||
}
|
||
|
||
// ``current_draft`` 出现 → 补全 draft_ready 的 draftMarkdown / draftTitle / revisionCount
|
||
if (out.current_draft && typeof out.current_draft === 'object') {
|
||
const d = out.current_draft as Record<string, unknown>;
|
||
const draftReady = events.find((e) => e.type === 'draft_ready');
|
||
const ev: ProgressEvent = draftReady ?? { type: 'draft_ready', sessionId, message: '' };
|
||
if (!ev.draftMarkdown) ev.draftMarkdown = (d.full_markdown ?? d.fullMarkdown ?? '') as string;
|
||
if (!ev.draftTitle) ev.draftTitle = (d.title ?? '') as string;
|
||
if (ev.revisionCount == null) ev.revisionCount = (d.revision_count ?? d.revisionCount ?? 0) as number;
|
||
if (!draftReady) events.push(ev);
|
||
}
|
||
|
||
return events;
|
||
}
|
||
|
||
/** ``stream.interrupt.value`` → await_user ProgressEvent。 */
|
||
export function interruptToEvent(value: unknown, sessionId: string): ProgressEvent | null {
|
||
if (!value || typeof value !== 'object') return null;
|
||
const v = value as Record<string, unknown>;
|
||
return {
|
||
type: 'await_user',
|
||
sessionId,
|
||
message: String(v.message ?? ''),
|
||
pausePoint: v.pause_point as ProgressEvent['pausePoint'],
|
||
materials: Array.isArray(v.materials) ? (v.materials as Record<string, unknown>[]).map(normalizeMaterial) : undefined,
|
||
keywords: v.keywords as string[] | undefined,
|
||
materialSummary: v.summary as string | undefined,
|
||
outline: v.outline ? (normalizeOutline(v.outline) as AIOutline) : undefined,
|
||
reviewResult: v.review_result ? (normalizeReviewResult(v.review_result) as ReviewResult) : undefined,
|
||
draftTitle: v.draft_title as string | undefined,
|
||
revisionCount: v.revision_count as number | undefined,
|
||
blockedSections: Array.isArray(v.blocked_sections)
|
||
? (v.blocked_sections as Record<string, unknown>[]).map(normalizeBlockedSection)
|
||
: undefined,
|
||
};
|
||
}
|
||
|
||
export type AIWritingValues = {
|
||
user_intent?: string;
|
||
user_outline_raw?: string;
|
||
article_type?: string;
|
||
status?: string;
|
||
material_package?: unknown;
|
||
current_outline?: unknown;
|
||
current_draft?: unknown;
|
||
review_result?: unknown;
|
||
progress_events?: unknown[];
|
||
};
|