Files
2026-05-17 20:18:11 +08:00

207 lines
6.8 KiB
TypeScript

import { useCallback, useRef, useState } from "react";
import type { Editor } from "@tiptap/react";
import {
streamRewrite,
type RewriteAction,
type RewriteRequest,
type RewriteTone,
} from "../api/rewrite";
import { useCanvasUIContext } from "../contexts/CanvasUIContext";
import { useCanvasThreadContext } from "../contexts/CanvasThreadContext";
export type RewriteStatus = "idle" | "loading" | "success" | "error";
// ── <think>…</think> tag stripper ────────────────────────────────────────────
// Handles tags split across multiple streaming chunks.
class ThinkTagParser {
private buf = "";
private inside = false;
push(chunk: string): { thinking: string; text: string } {
this.buf += chunk;
let thinking = "";
let text = "";
// eslint-disable-next-line no-constant-condition
while (true) {
if (!this.inside) {
const idx = this.buf.indexOf("<think>");
if (idx !== -1) {
text += this.buf.slice(0, idx);
this.buf = this.buf.slice(idx + 7);
this.inside = true;
} else {
// hold last 6 chars to guard against a partial opening tag
const safe = Math.max(0, this.buf.length - 6);
text += this.buf.slice(0, safe);
this.buf = this.buf.slice(safe);
break;
}
} else {
const idx = this.buf.indexOf("</think>");
if (idx !== -1) {
thinking += this.buf.slice(0, idx);
this.buf = this.buf.slice(idx + 8);
this.inside = false;
} else {
// hold last 7 chars to guard against a partial closing tag
const safe = Math.max(0, this.buf.length - 7);
thinking += this.buf.slice(0, safe);
this.buf = this.buf.slice(safe);
break;
}
}
}
return { thinking, text };
}
flush(): { thinking: string; text: string } {
const out = {
thinking: this.inside ? this.buf : "",
text: this.inside ? "" : this.buf,
};
this.buf = "";
return out;
}
}
// ─────────────────────────────────────────────────────────────────────────────
export function useWritingRewrite(editor: Editor | null) {
const { writingSelection } = useCanvasUIContext();
const { threadId, modelName } = useCanvasThreadContext();
const [status, setStatus] = useState<RewriteStatus>("idle");
const [result, setResult] = useState<string | null>(null);
const [thinking, setThinking] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const abortRef = useRef<AbortController | null>(null);
// Shared streaming runner — state setters from useState are stable references
const runStream = useCallback(
async (req: RewriteRequest, abort: AbortController) => {
const parser = new ThinkTagParser();
const applyParsed = (parsed: { thinking: string; text: string }) => {
if (parsed.thinking) setThinking((p) => (p ?? "") + parsed.thinking);
if (parsed.text) setResult((p) => (p ?? "") + parsed.text);
};
try {
let terminated = false;
for await (const event of streamRewrite(req, abort.signal)) {
if (abort.signal.aborted) break;
if (event.type === "thinking") {
setThinking((p) => (p ?? "") + event.chunk);
} else if (event.type === "text") {
applyParsed(parser.push(event.chunk));
} else if (event.type === "done") {
applyParsed(parser.flush());
setStatus("success");
terminated = true;
break;
} else if (event.type === "error") {
setError(event.message ?? "改写失败,请重试");
setStatus("error");
terminated = true;
break;
}
}
if (!terminated && !abort.signal.aborted) {
applyParsed(parser.flush());
setStatus("success");
}
} catch (e) {
if (abort.signal.aborted) return;
setError(e instanceof Error ? e.message : "改写失败,请重试");
setStatus("error");
}
},
[], // eslint-disable-line react-hooks/exhaustive-deps
);
const rewrite = useCallback(
async (action: RewriteAction, tone?: RewriteTone, customInstruction?: string) => {
if (!writingSelection || !editor) return;
abortRef.current?.abort();
const abort = new AbortController();
abortRef.current = abort;
const { from, to, text } = writingSelection;
const docText = editor.state.doc.textContent;
const docSize = editor.state.doc.content.size;
const req: RewriteRequest = {
threadId,
selection: { from, to, text },
action,
tone,
modelName: modelName ?? undefined,
surroundingContext: {
before: docText.substring(Math.max(0, from - 400), from),
after: docText.substring(to, Math.min(docSize, to + 400)),
},
customInstruction: customInstruction || undefined,
};
setStatus("loading");
setResult(null);
setThinking(null);
setError(null);
await runStream(req, abort);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[writingSelection, modelName, editor, runStream],
);
const rewriteFollowUp = useCallback(
async (instruction: string, action: RewriteAction, tone?: RewriteTone) => {
if (!writingSelection || !editor) return;
const prevResult = result;
if (!prevResult) return;
abortRef.current?.abort();
const abort = new AbortController();
abortRef.current = abort;
const { from, to, text } = writingSelection;
const docText = editor.state.doc.textContent;
const docSize = editor.state.doc.content.size;
const req: RewriteRequest = {
threadId,
selection: { from, to, text },
action,
tone,
modelName: modelName ?? undefined,
surroundingContext: {
before: docText.substring(Math.max(0, from - 400), from),
after: docText.substring(to, Math.min(docSize, to + 400)),
},
followUpInstruction: instruction,
previousResult: prevResult,
};
setStatus("loading");
setResult(null);
setThinking(null);
setError(null);
await runStream(req, abort);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[writingSelection, modelName, editor, result, runStream],
);
const reset = useCallback(() => {
abortRef.current?.abort();
abortRef.current = null;
setStatus("idle");
setResult(null);
setThinking(null);
setError(null);
}, []);
return { status, result, thinking, error, rewrite, rewriteFollowUp, reset };
}