P1-6 useStyleLearn/useKimiOauth 修 stale-closure 依赖。 P1-7 CommandPalette/Drawer 加 focus trap(新 lib/a11y/focusTrap)。 P1-8 SSE 解析与 server.ts 去 as 强转改类型守卫/运行时校验。 P2 删冗余强转、开 noUncheckedIndexedAccess、Toast 清理+稳定 key、列表 key 稳定化、 rel=noopener、useMemo 大文本、ConflictCard role=group、useInjection 加锁、 client.test 真断言。 codegen 重生成 schema.d.ts + 消费 DimensionEntry/ReviewConflictView 强类型。
90 lines
2.6 KiB
TypeScript
90 lines
2.6 KiB
TypeScript
"use client";
|
||
|
||
import { useCallback, useState } from "react";
|
||
|
||
import { api } from "@/lib/api/client";
|
||
import { useToast } from "@/components/Toast";
|
||
import { buildRefineRequest } from "./style";
|
||
|
||
export type RefineStatus = "idle" | "refining" | "done" | "error";
|
||
|
||
export interface RefineResult {
|
||
original: string;
|
||
refined: string;
|
||
}
|
||
|
||
export interface UseRefine {
|
||
status: RefineStatus;
|
||
result: RefineResult | null;
|
||
// 回炉重写某段(可选改写指令)→ 返回 {original, refined} 或 null(失败)。
|
||
refine: (
|
||
projectId: string,
|
||
chapterNo: number,
|
||
segment: string,
|
||
instruction?: string,
|
||
) => Promise<RefineResult | null>;
|
||
reset: () => void;
|
||
}
|
||
|
||
function errorCode(error: unknown): string | undefined {
|
||
if (typeof error !== "object" || error === null) return undefined;
|
||
const env = error as { error?: { code?: unknown } };
|
||
return typeof env.error?.code === "string" ? env.error.code : undefined;
|
||
}
|
||
|
||
// 回炉(POST .../refine):同步返回新旧 diff,不写库(不变量#3)。
|
||
// 503 LLM_UNAVAILABLE(无凭据)优雅提示去设置;其余失败 toast。
|
||
export function useRefine(): UseRefine {
|
||
const [status, setStatus] = useState<RefineStatus>("idle");
|
||
const [result, setResult] = useState<RefineResult | null>(null);
|
||
const toast = useToast();
|
||
|
||
const refine = useCallback<UseRefine["refine"]>(
|
||
async (projectId, chapterNo, segment, instruction) => {
|
||
setStatus("refining");
|
||
setResult(null);
|
||
try {
|
||
const { data, error } = await api.POST(
|
||
"/projects/{project_id}/chapters/{chapter_no}/refine",
|
||
{
|
||
params: {
|
||
path: { project_id: projectId, chapter_no: chapterNo },
|
||
},
|
||
body: buildRefineRequest(segment, instruction),
|
||
},
|
||
);
|
||
if (error || !data) {
|
||
setStatus("error");
|
||
const code = errorCode(error);
|
||
toast(
|
||
code === "LLM_UNAVAILABLE"
|
||
? "未配置提供商,请先去设置页连一家。"
|
||
: "回炉失败,请稍后重试。",
|
||
"error",
|
||
);
|
||
return null;
|
||
}
|
||
const outcome: RefineResult = {
|
||
original: data.original,
|
||
refined: data.refined,
|
||
};
|
||
setResult(outcome);
|
||
setStatus("done");
|
||
return outcome;
|
||
} catch {
|
||
setStatus("error");
|
||
toast("回炉请求异常,请检查网络。", "error");
|
||
return null;
|
||
}
|
||
},
|
||
[toast],
|
||
);
|
||
|
||
const reset = useCallback((): void => {
|
||
setStatus("idle");
|
||
setResult(null);
|
||
}, []);
|
||
|
||
return { status, result, refine, reset };
|
||
}
|