智能选中文字

This commit is contained in:
董宏凯 committed 2026-05-16 22:00:34 +08:00
1 parent e8a31b5d37
commit da4a08dfe1
34 files changed
+3208 -541

No files matched your search

@@ -1,13 +1,13 @@
import { useCallback } from "react";
import { useCanvasGraphContext } from "../contexts/CanvasGraphContext";
import { useCanvasStreamContext } from "../contexts/CanvasStreamContext";
import type { QuickActionId } from "../types/quick-action";
import { getCurrentArtifactContent } from "../utils/artifact";
import { buildQuickActionMessage } from "../utils/quick-actions";
import { useCanvasStream } from "./useCanvasStream";
export function useCanvasQuickActions() {
const { sendMessage } = useCanvasStream();
const { sendMessage } = useCanvasStreamContext();
const { artifact } = useCanvasGraphContext();
const triggerQuickAction = useCallback(
@@ -15,7 +15,7 @@ export function useCanvasQuickActions() {
const content = getCurrentArtifactContent(artifact);
if (!content) return;
const message = buildQuickActionMessage(actionId);
const message = buildQuickActionMessage(actionId, content);
await sendMessage(message, { quick_action_id: actionId });
},
[sendMessage, artifact],
@@ -8,7 +8,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { getAPIClient } from "@/core/api";
import { getCanvasAPIClient } from "@/core/api/canvas-client";
import { useUpdateSubtask } from "@/core/tasks/context";
import { CANVAS_AGENT_ID, CANVAS_THREAD_METADATA } from "../constants";
@@ -61,7 +61,7 @@ export function useCanvasThreadStream() {
}, [threadId]);
const thread = useStream<CanvasThreadValues>({
client: getAPIClient(),
client: getCanvasAPIClient(),
assistantId: CANVAS_AGENT_ID,
threadId: onStreamThreadId,
fetchStateHistory: { limit: 1 },
@@ -70,7 +70,7 @@ export function useCanvasThreadStream() {
threadIdRef.current = meta.thread_id;
setThreadId(meta.thread_id);
navigate(`/page/canvas/${meta.thread_id}`, { replace: true });
void getAPIClient()
void getCanvasAPIClient()
.threads.update(meta.thread_id, { metadata: CANVAS_THREAD_METADATA })
.catch(() => {});
},
@@ -183,8 +183,10 @@ export function useCanvasThreadStream() {
},
]);
// Pass current artifact info so the backend can instruct the LLM to
// continue editing the same artifact instead of creating a new one.
// Inject current artifact content into the human message so the LLM can see
// what to edit. create_agent only passes state.messages to the LLM — state.artifact
// is NOT automatically visible. Skip injection when the caller already embedded
// the artifact (e.g. quick actions build the full message themselves).
const currentContent = artifact ? getCurrentArtifactContent(artifact) : null;
const artifactContext = currentContent
? {
@@ -193,11 +195,26 @@ export function useCanvasThreadStream() {
}
: {};
const messageText =
currentContent && !trimmed.includes("<artifact")
? (() => {
const body =
currentContent.type === "code"
? currentContent.code
: currentContent.fullMarkdown;
const tag =
currentContent.type === "code"
? `language="${currentContent.language}"`
: "";
return `${trimmed}\n\n<artifact ${tag}>\n${body}\n</artifact>`;
})()
: trimmed;
try {
await thread.submit(
{
messages: [
{ type: "human", content: [{ type: "text", text: trimmed }] },
{ type: "human", content: [{ type: "text", text: messageText }] },
],
},
{
@@ -0,0 +1,53 @@
import { useEffect, useRef } from "react";
import { useEditor } from "@tiptap/react";
import { buildExtensions } from "../editor/TiptapExtensions";
interface UseWritingEditorOptions {
markdown: string;
onChange?: (markdown: string) => void;
editable?: boolean;
placeholder?: string;
}
export function useWritingEditor({
markdown,
onChange,
editable = true,
placeholder,
}: UseWritingEditorOptions) {
const prevMarkdownRef = useRef<string>(markdown);
const editor = useEditor({
extensions: buildExtensions(placeholder),
editable,
content: markdown,
onUpdate({ editor }) {
if (!onChange) return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const md = (editor as any).storage?.markdown?.getMarkdown?.() ?? editor.getText();
onChange(md);
},
});
// Sync external markdown changes (e.g. after streaming completes)
useEffect(() => {
if (!editor) return;
if (markdown === prevMarkdownRef.current) return;
prevMarkdownRef.current = markdown;
const { from, to } = editor.state.selection;
editor.commands.setContent(markdown, { emitUpdate: false });
const docSize = editor.state.doc.content.size;
if (from <= docSize && to <= docSize) {
editor.commands.setTextSelection({ from, to });
}
}, [editor, markdown]);
// Sync editable flag
useEffect(() => {
if (!editor) return;
editor.setEditable(editable);
}, [editor, editable]);
return editor;
}
@@ -0,0 +1,206 @@
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 || !threadId || !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, threadId, modelName, editor, runStream],
);
const rewriteFollowUp = useCallback(
async (instruction: string, action: RewriteAction, tone?: RewriteTone) => {
if (!writingSelection || !threadId || !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, threadId, 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 };
}