ai写作修改
This commit is contained in:
1 parent
fdfb888be9
commit
3b5525a0a5
8 files changed
+583
-356
No files matched your search
@@ -0,0 +1,405 @@
|
||||
import {
|
||||
createContext,
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
type Dispatch,
|
||||
type MutableRefObject,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from 'react';
|
||||
import { useStream } from '@langchain/langgraph-sdk/react';
|
||||
|
||||
import { getAPIClient } from '@/core/api';
|
||||
|
||||
import { useCanvasGraphContext } from '../contexts/CanvasGraphContext';
|
||||
import { saveAIWritingTranscript } from '../api/ai-writing-sessions';
|
||||
import { countWords } from '../utils/wordCount';
|
||||
import {
|
||||
INITIAL_STATE,
|
||||
customToProgressEvent,
|
||||
interruptToEvent,
|
||||
nodeUpdatesToEvents,
|
||||
reducer,
|
||||
type Action,
|
||||
type AIWritingValues,
|
||||
} from '../hooks/useAIWritingStream';
|
||||
import type {
|
||||
AIWritingRequest,
|
||||
AIWritingState,
|
||||
CompletedIntervention,
|
||||
ProgressEvent,
|
||||
UserInterventionPayload,
|
||||
WritingStatus,
|
||||
} from '../types/ai-writing';
|
||||
|
||||
/** 高频 chunk 类型:合并到同一帧再 dispatch,避免同步嵌套 setState 触发 Maximum update depth。 */
|
||||
const BATCHED_CHUNK_TYPES = new Set<ProgressEvent['type']>([
|
||||
'draft_chunk',
|
||||
'outline_chunk',
|
||||
'intent_chunk',
|
||||
'skill_select_chunk',
|
||||
'review_chunk',
|
||||
]);
|
||||
|
||||
function createProgressEventBatcher(dispatchRef: RefObject<Dispatch<Action>>) {
|
||||
const pending: ProgressEvent[] = [];
|
||||
let rafId = 0;
|
||||
|
||||
const flush = () => {
|
||||
rafId = 0;
|
||||
if (pending.length === 0) return;
|
||||
const events = pending.splice(0, pending.length);
|
||||
if (events.length === 1) {
|
||||
dispatchRef.current?.({ type: 'handle', event: events[0] });
|
||||
} else {
|
||||
dispatchRef.current?.({ type: 'handle_batch', events });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
push(event: ProgressEvent) {
|
||||
pending.push(event);
|
||||
if (!rafId) rafId = requestAnimationFrame(flush);
|
||||
},
|
||||
pushImmediate(event: ProgressEvent) {
|
||||
// 关键:先把缓冲里的 chunk 同步 flush,再派发立即事件,保证事件顺序。
|
||||
// 否则 *_ready / await_user / step_* 会插队到尚在 rAF 缓冲里的 *_chunk 之前——
|
||||
// ready 先清空流式文本 / 切状态,随后残留 chunk 又被回灌,导致:
|
||||
// 意图/大纲/审核的流式视图清不掉(残留 JSON 尾巴)、切不回结果卡、右侧 markdown 切不回编辑器。
|
||||
if (rafId) cancelAnimationFrame(rafId);
|
||||
flush();
|
||||
dispatchRef.current?.({ type: 'handle', event });
|
||||
},
|
||||
cancel() {
|
||||
if (rafId) cancelAnimationFrame(rafId);
|
||||
rafId = 0;
|
||||
pending.length = 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type AIWritingStreamApi = Pick<
|
||||
ReturnType<typeof useStream<AIWritingValues>>,
|
||||
'submit' | 'stop' | 'interrupt'
|
||||
>;
|
||||
|
||||
export type AIWritingApi = {
|
||||
state: AIWritingState;
|
||||
startWriting: (request: AIWritingRequest) => Promise<void>;
|
||||
submitIntervention: (payload: UserInterventionPayload) => Promise<void>;
|
||||
pauseWriting: () => void;
|
||||
resumeWriting: () => void;
|
||||
reset: () => void;
|
||||
};
|
||||
|
||||
const AIWritingContext = createContext<AIWritingApi | null>(null);
|
||||
|
||||
/** 可选读取:不在 Provider 内时返回 null(如 Canvas 布局右侧 artifact 面板)。 */
|
||||
export function useAIWritingOptional(): AIWritingApi | null {
|
||||
return useContext(AIWritingContext);
|
||||
}
|
||||
|
||||
/** 在 ``AIWritingProvider`` 内读取写作状态与操作 API。 */
|
||||
export function useAIWriting(): AIWritingApi {
|
||||
const ctx = useContext(AIWritingContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useAIWriting must be used within AIWritingProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 承载 ``useStream`` 的独立组件(render null)。
|
||||
*
|
||||
* 用 ``memo`` 且仅随 ``threadId`` 重渲染,这样 ``draft_chunk`` 等高频 custom 事件
|
||||
* 更新 reducer 时不会重跑 ``useStream``,避免 onCustomEvent → dispatch → 重渲染
|
||||
* → useStream 重入 的更新风暴(Maximum update depth exceeded)。
|
||||
*/
|
||||
const AIWritingStreamHost = memo(function AIWritingStreamHost({
|
||||
threadId,
|
||||
dispatchRef,
|
||||
sessionIdRef,
|
||||
streamRef,
|
||||
seenInterruptRef,
|
||||
}: {
|
||||
threadId: string | undefined;
|
||||
dispatchRef: RefObject<Dispatch<Action>>;
|
||||
sessionIdRef: RefObject<string | null>;
|
||||
streamRef: MutableRefObject<AIWritingStreamApi | null>;
|
||||
seenInterruptRef: MutableRefObject<string | null>;
|
||||
}) {
|
||||
const eventBatcherRef = useRef<ReturnType<typeof createProgressEventBatcher> | null>(null);
|
||||
if (!eventBatcherRef.current) {
|
||||
eventBatcherRef.current = createProgressEventBatcher(dispatchRef);
|
||||
}
|
||||
|
||||
const emitProgressEvent = useCallback((event: ProgressEvent) => {
|
||||
if (BATCHED_CHUNK_TYPES.has(event.type)) {
|
||||
eventBatcherRef.current!.push(event);
|
||||
} else {
|
||||
eventBatcherRef.current!.pushImmediate(event);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const stream = useStream<AIWritingValues>({
|
||||
client: getAPIClient(),
|
||||
assistantId: 'ai_writing',
|
||||
threadId,
|
||||
reconnectOnMount: true,
|
||||
onCreated(meta) {
|
||||
dispatchRef.current?.({ type: 'set_session', sessionId: meta.thread_id });
|
||||
},
|
||||
onCustomEvent(event: unknown) {
|
||||
if (typeof window !== 'undefined' && (window as { __AI_WRITING_DEBUG__?: boolean }).__AI_WRITING_DEBUG__) {
|
||||
const t = (event as { type?: string } | null)?.type;
|
||||
// eslint-disable-next-line no-console
|
||||
console.debug(`[ai-writing:custom] +${Math.round(performance.now())}ms type=${t ?? '?'}`, event);
|
||||
}
|
||||
const pe = customToProgressEvent(event, sessionIdRef.current ?? '');
|
||||
if (pe) emitProgressEvent(pe);
|
||||
},
|
||||
onUpdateEvent(data: Record<string, unknown> | undefined) {
|
||||
if (!data) return;
|
||||
if (typeof window !== 'undefined' && (window as { __AI_WRITING_DEBUG__?: boolean }).__AI_WRITING_DEBUG__) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.debug(`[ai-writing:updates] +${Math.round(performance.now())}ms nodes=${Object.keys(data).join(',')}`);
|
||||
}
|
||||
if (Array.isArray((data as Record<string, unknown>).__interrupt__)) {
|
||||
const interrupts = (data as { __interrupt__: unknown[] }).__interrupt__;
|
||||
for (const intr of interrupts) {
|
||||
const value = (intr && typeof intr === 'object' && 'value' in intr)
|
||||
? (intr as { value: unknown }).value : intr;
|
||||
const ev = interruptToEvent(value, sessionIdRef.current ?? '');
|
||||
if (ev) emitProgressEvent(ev);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const nodeOutput of Object.values(data)) {
|
||||
const events = nodeUpdatesToEvents(nodeOutput, sessionIdRef.current ?? '');
|
||||
for (const ev of events) emitProgressEvent(ev);
|
||||
}
|
||||
},
|
||||
onError(err: unknown) {
|
||||
eventBatcherRef.current?.cancel();
|
||||
dispatchRef.current?.({
|
||||
type: 'set_error',
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
},
|
||||
onFinish(finishState) {
|
||||
eventBatcherRef.current?.cancel();
|
||||
const finalStatus = (finishState.values as AIWritingValues | undefined)?.status;
|
||||
if (finalStatus === 'done' || finalStatus === 'error') {
|
||||
dispatchRef.current?.({
|
||||
type: 'handle',
|
||||
event: {
|
||||
type: finalStatus === 'error' ? 'error' : 'done',
|
||||
sessionId: finishState.values?.sessionId as string ?? '',
|
||||
message: finalStatus === 'error' ? '写作出错' : '写作完成',
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
streamRef.current = stream;
|
||||
|
||||
useEffect(() => {
|
||||
const intr = stream.interrupt;
|
||||
if (!intr) {
|
||||
seenInterruptRef.current = null;
|
||||
return;
|
||||
}
|
||||
const key = intr.id ?? JSON.stringify(intr.value);
|
||||
if (seenInterruptRef.current === key) return;
|
||||
seenInterruptRef.current = key;
|
||||
const ev = interruptToEvent(intr.value, sessionIdRef.current ?? '');
|
||||
if (ev) emitProgressEvent(ev);
|
||||
}, [stream.interrupt, emitProgressEvent, seenInterruptRef, sessionIdRef]);
|
||||
|
||||
useEffect(() => () => { eventBatcherRef.current?.cancel(); }, []);
|
||||
|
||||
return null;
|
||||
}, (prev, next) => prev.threadId === next.threadId);
|
||||
|
||||
export function AIWritingProvider({ children }: { children: ReactNode }) {
|
||||
const { setArtifact } = useCanvasGraphContext();
|
||||
const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
|
||||
const dispatchRef = useRef(dispatch);
|
||||
dispatchRef.current = dispatch;
|
||||
const sessionIdRef = useRef<string | null>(state.sessionId);
|
||||
sessionIdRef.current = state.sessionId;
|
||||
const streamRef = useRef<AIWritingStreamApi | null>(null);
|
||||
const seenInterruptRef = useRef<string | null>(null);
|
||||
|
||||
const threadId = state.sessionId ?? undefined;
|
||||
|
||||
useEffect(() => {
|
||||
const s = state.status;
|
||||
const savable = s === 'done' || s === 'error' || s.startsWith('awaiting_');
|
||||
if (!state.sessionId || !savable || state.progressEvents.length === 0) return;
|
||||
saveAIWritingTranscript(state.sessionId, {
|
||||
progressEvents: state.progressEvents,
|
||||
completedInterventions: state.completedInterventions,
|
||||
}).catch(() => {});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state.status, state.sessionId]);
|
||||
|
||||
const startWriting = useCallback(async (request: AIWritingRequest) => {
|
||||
if (state.status !== 'idle' && state.status !== 'done' && state.status !== 'error') return;
|
||||
dispatch({ type: 'start', request });
|
||||
const stream = streamRef.current;
|
||||
if (!stream) return;
|
||||
try {
|
||||
await stream.submit(
|
||||
{
|
||||
user_intent: request.userIntent,
|
||||
article_type: request.articleType,
|
||||
target_audience: request.targetAudience,
|
||||
word_count_target: request.wordCountTarget,
|
||||
keyword_count: Math.max(1, Math.min(10, request.keywordCount)),
|
||||
writing_mode: request.writingMode === 'strict' ? 'strict' : 'loose',
|
||||
material_source: request.materialSource === 'skill' ? 'skill' : 'knowledge_base',
|
||||
revision_count: 0,
|
||||
max_revisions: 3,
|
||||
status: 'researching',
|
||||
drafts: [],
|
||||
progress_events: [],
|
||||
material_package: null,
|
||||
current_outline: null,
|
||||
current_draft: null,
|
||||
review_result: null,
|
||||
last_user_intervention: null,
|
||||
} as Partial<AIWritingValues>,
|
||||
{
|
||||
config: { configurable: { model_name: request.modelName ?? '' } } as Record<string, unknown>,
|
||||
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
dispatch({ type: 'set_error', message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}, [state.status]);
|
||||
|
||||
const submitIntervention = useCallback(async (payload: UserInterventionPayload) => {
|
||||
if (!state.sessionId || !state.currentPause) return;
|
||||
|
||||
const stream = streamRef.current;
|
||||
if (!stream) return;
|
||||
|
||||
const pausePoint = state.currentPause.pausePoint;
|
||||
const record: CompletedIntervention = {
|
||||
pausePoint: pausePoint as CompletedIntervention['pausePoint'],
|
||||
action: payload.action,
|
||||
};
|
||||
if (pausePoint === 'material_confirm') record.materials = state.materials;
|
||||
else if (pausePoint === 'outline_confirm') record.outline = state.outline ?? undefined;
|
||||
else if (pausePoint === 'draft_confirm') {
|
||||
record.draftTitle = state.currentDraftTitle;
|
||||
record.draftWordCount = countWords(state.currentDraftMarkdown);
|
||||
record.reviewResult = state.reviewResult ?? undefined;
|
||||
} else if (pausePoint === 'review_confirm') {
|
||||
record.reviewResult = state.reviewResult ?? undefined;
|
||||
}
|
||||
|
||||
let pendingRevisionContext: AIWritingState['pendingRevisionContext'] = null;
|
||||
const isApplyingReview = payload.selectedIssueIndices !== undefined && state.reviewResult != null;
|
||||
if (isApplyingReview && state.reviewResult) {
|
||||
const allIssues = state.reviewResult.revisionNotes;
|
||||
const selectedSet = new Set(payload.selectedIssueIndices!);
|
||||
pendingRevisionContext = {
|
||||
submittedIssues: allIssues.filter((_, i) => selectedSet.has(i)),
|
||||
skippedIssues: allIssues.filter((_, i) => !selectedSet.has(i)),
|
||||
oldWordCount: countWords(state.currentDraftMarkdown),
|
||||
};
|
||||
}
|
||||
|
||||
let nextStatus: WritingStatus = state.status;
|
||||
if (pausePoint === 'material_confirm') {
|
||||
nextStatus = (payload.action === 're_search' || payload.action === 'enable_skill_search')
|
||||
? 'researching' : 'writing_outline';
|
||||
} else if (pausePoint === 'outline_confirm') {
|
||||
nextStatus = payload.action === 're_outline' ? 'writing_outline' : 'writing_draft';
|
||||
} else if (pausePoint === 'draft_confirm') {
|
||||
if (payload.action === 'finalize') nextStatus = 'done';
|
||||
else if (payload.action === 'to_editor') nextStatus = 'reviewing';
|
||||
else nextStatus = 'revising';
|
||||
} else if (pausePoint === 'review_confirm') {
|
||||
nextStatus = payload.action === 'force_finalize' ? 'done' : 'revising';
|
||||
} else if (pausePoint === 'section_help') {
|
||||
nextStatus = payload.sectionDecisions?.some((d) => d.decision === 'supplement')
|
||||
? 'researching' : 'writing_draft';
|
||||
}
|
||||
|
||||
const resumePayload: Record<string, unknown> = { action: payload.action };
|
||||
if (payload.approvedMaterialIds !== undefined) resumePayload.approvedMaterialIds = payload.approvedMaterialIds;
|
||||
if (payload.extraKeywords !== undefined) resumePayload.extraKeywords = payload.extraKeywords;
|
||||
if (payload.userQuery !== undefined) resumePayload.userQuery = payload.userQuery;
|
||||
if (payload.editedOutline !== undefined) resumePayload.editedOutline = payload.editedOutline;
|
||||
if (payload.outlineFeedback !== undefined) resumePayload.outlineFeedback = payload.outlineFeedback;
|
||||
if (payload.userRevisionNotes !== undefined) resumePayload.userRevisionNotes = payload.userRevisionNotes;
|
||||
if (payload.overrideVerdict !== undefined) resumePayload.overrideVerdict = payload.overrideVerdict;
|
||||
if (payload.sectionDecisions !== undefined) {
|
||||
resumePayload.sectionDecisions = payload.sectionDecisions.map((d) => ({
|
||||
sectionTitle: d.sectionTitle, decision: d.decision,
|
||||
}));
|
||||
}
|
||||
|
||||
const intr = stream.interrupt;
|
||||
if (intr) {
|
||||
seenInterruptRef.current = intr.id ?? JSON.stringify(intr.value);
|
||||
}
|
||||
|
||||
dispatch({ type: 'intervention_submitted', record, nextStatus, pendingRevisionContext });
|
||||
|
||||
try {
|
||||
await stream.submit(undefined, {
|
||||
command: { resume: resumePayload },
|
||||
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
|
||||
});
|
||||
} catch (err) {
|
||||
dispatch({ type: 'set_error', message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}, [state.sessionId, state.currentPause, state.materials, state.outline,
|
||||
state.currentDraftTitle, state.currentDraftMarkdown, state.reviewResult,
|
||||
state.status]);
|
||||
|
||||
const pauseWriting = useCallback(() => {
|
||||
void streamRef.current?.stop();
|
||||
dispatch({ type: 'pause' });
|
||||
}, []);
|
||||
|
||||
const resumeWriting = useCallback(() => {
|
||||
dispatch({ type: 'resume_ui' });
|
||||
}, []);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
void streamRef.current?.stop();
|
||||
setArtifact(null);
|
||||
seenInterruptRef.current = null;
|
||||
dispatch({ type: 'reset' });
|
||||
}, [setArtifact]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ state, startWriting, submitIntervention, pauseWriting, resumeWriting, reset }),
|
||||
[state, startWriting, submitIntervention, pauseWriting, resumeWriting, reset],
|
||||
);
|
||||
|
||||
return (
|
||||
<AIWritingContext.Provider value={value}>
|
||||
<AIWritingStreamHost
|
||||
threadId={threadId}
|
||||
dispatchRef={dispatchRef}
|
||||
sessionIdRef={sessionIdRef}
|
||||
streamRef={streamRef}
|
||||
seenInterruptRef={seenInterruptRef}
|
||||
/>
|
||||
{children}
|
||||
</AIWritingContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user