feat: M4 文风 + M5 生成/多provider/Skill + Kimi Code 订阅接入 + 本地联调修复
M4(文风): style-auditor 双轨(提取指纹/漂移第四审)+ jobs 长任务框架(zombie reaper) + 回炉 refine + GET /style read-back。 M5(生成+扩展): worldbuilder/character-gen(入库 continuity 409 gate + partition_writes 白名单 + schema→JSONB 形变); 网关多 provider 回退链/熔断/能力降级(Anthropic/Gemini 适配器);Skill registry + 表权限沙箱 + 规则; 前端 角色生成器/世界观/Codex/规则页/技能库/⌘K 命令面板。 K1(Kimi Code 订阅接入): OAuth device-flow(kimi-code)+ 静态 Console key(kimi-code-key)两路径; coding 端点 KimiCLI 伪造头(实测 UA allow-list 门禁,缺则 403)+ JSON 模式结构化(thinking ⊥ tool_choice)。 本地联调修复: CORS 中间件;assemble 注入 premise+「写第N章」指令(修空 prompt 400); GET /outline·/draft read-back + 大纲/工作台/审稿页重载;写页 client/server 常量边界 + notFound 健壮化; 字数 toLocaleString locale 水合;审稿页终稿从已存草稿 seed(修 accept 422)。 门禁: backend ruff/mypy(157)/alembic 无漂移/pytest 451 · frontend lint/tsc/vitest/build。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
191
apps/web/lib/settings/kimiOauth.test.ts
Normal file
191
apps/web/lib/settings/kimiOauth.test.ts
Normal file
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { JobView, PollState } from "@/lib/jobs/job";
|
||||
import {
|
||||
authOpenUrl,
|
||||
connectPhase,
|
||||
formatExpiresAt,
|
||||
jobConnected,
|
||||
KIMI_CODE_MODEL,
|
||||
KIMI_CODE_PROVIDER,
|
||||
toConnectionStatus,
|
||||
toDeviceDisplay,
|
||||
} from "./kimiOauth";
|
||||
|
||||
const poll = (over: Partial<PollState>): PollState => ({
|
||||
status: "polling",
|
||||
progress: 0,
|
||||
job: null,
|
||||
error: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
const job = (over: Partial<JobView>): JobView => ({
|
||||
id: "j1",
|
||||
kind: "kimi_oauth",
|
||||
status: "done",
|
||||
progress: 100,
|
||||
result: null,
|
||||
error: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("KIMI_CODE constants", () => {
|
||||
it("uses the OAuth provider + coding model names", () => {
|
||||
expect(KIMI_CODE_PROVIDER).toBe("kimi-code");
|
||||
expect(KIMI_CODE_MODEL).toBe("kimi-for-coding");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toDeviceDisplay", () => {
|
||||
it("maps start response fields", () => {
|
||||
const d = toDeviceDisplay({
|
||||
job_id: "abc",
|
||||
user_code: "WXYZ-1234",
|
||||
verification_uri: "https://auth.kimi.com/device",
|
||||
verification_uri_complete: "https://auth.kimi.com/device?code=WXYZ-1234",
|
||||
expires_in: 600,
|
||||
interval: 5,
|
||||
});
|
||||
expect(d).toEqual({
|
||||
userCode: "WXYZ-1234",
|
||||
verificationUri: "https://auth.kimi.com/device",
|
||||
verificationUriComplete: "https://auth.kimi.com/device?code=WXYZ-1234",
|
||||
expiresIn: 600,
|
||||
interval: 5,
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults missing complete uri to null", () => {
|
||||
const d = toDeviceDisplay({
|
||||
job_id: "abc",
|
||||
user_code: "CODE",
|
||||
verification_uri: "https://auth.kimi.com/device",
|
||||
verification_uri_complete: null,
|
||||
expires_in: 600,
|
||||
interval: 5,
|
||||
});
|
||||
expect(d.verificationUriComplete).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("authOpenUrl", () => {
|
||||
it("prefers the complete uri when present", () => {
|
||||
expect(
|
||||
authOpenUrl({
|
||||
userCode: "C",
|
||||
verificationUri: "https://auth.kimi.com/device",
|
||||
verificationUriComplete: "https://auth.kimi.com/device?code=C",
|
||||
expiresIn: 600,
|
||||
interval: 5,
|
||||
}),
|
||||
).toBe("https://auth.kimi.com/device?code=C");
|
||||
});
|
||||
|
||||
it("falls back to the plain uri", () => {
|
||||
expect(
|
||||
authOpenUrl({
|
||||
userCode: "C",
|
||||
verificationUri: "https://auth.kimi.com/device",
|
||||
verificationUriComplete: null,
|
||||
expiresIn: 600,
|
||||
interval: 5,
|
||||
}),
|
||||
).toBe("https://auth.kimi.com/device");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toConnectionStatus", () => {
|
||||
it("narrows connected + expires_at", () => {
|
||||
expect(
|
||||
toConnectionStatus({ connected: true, expires_at: "2026-07-01T00:00:00Z" }),
|
||||
).toEqual({ connected: true, expiresAt: "2026-07-01T00:00:00Z" });
|
||||
});
|
||||
|
||||
it("defaults non-string expires_at to null", () => {
|
||||
expect(toConnectionStatus({ connected: false })).toEqual({
|
||||
connected: false,
|
||||
expiresAt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("jobConnected", () => {
|
||||
it("true only when result.connected === true (no token expected)", () => {
|
||||
expect(jobConnected(job({ result: { connected: true, provider: "kimi-code" } }))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(jobConnected(job({ result: { connected: false } }))).toBe(false);
|
||||
expect(jobConnected(job({ result: null }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("connectPhase", () => {
|
||||
it("not started + not connected → idle", () => {
|
||||
expect(
|
||||
connectPhase({ started: false, connected: false, poll: poll({}) }),
|
||||
).toBe("idle");
|
||||
});
|
||||
|
||||
it("not started + connected (status query) → connected", () => {
|
||||
expect(
|
||||
connectPhase({ started: false, connected: true, poll: poll({}) }),
|
||||
).toBe("connected");
|
||||
});
|
||||
|
||||
it("started + polling → awaiting", () => {
|
||||
expect(
|
||||
connectPhase({
|
||||
started: true,
|
||||
connected: false,
|
||||
poll: poll({ status: "polling" }),
|
||||
}),
|
||||
).toBe("awaiting");
|
||||
});
|
||||
|
||||
it("started + done + job.connected → connected", () => {
|
||||
expect(
|
||||
connectPhase({
|
||||
started: true,
|
||||
connected: false,
|
||||
poll: poll({
|
||||
status: "done",
|
||||
job: job({ result: { connected: true, provider: "kimi-code" } }),
|
||||
}),
|
||||
}),
|
||||
).toBe("connected");
|
||||
});
|
||||
|
||||
it("started + done but job not connected → error", () => {
|
||||
expect(
|
||||
connectPhase({
|
||||
started: true,
|
||||
connected: false,
|
||||
poll: poll({ status: "done", job: job({ result: { connected: false } }) }),
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
|
||||
it("started + poll error (expired/denied/network) → error", () => {
|
||||
expect(
|
||||
connectPhase({
|
||||
started: true,
|
||||
connected: false,
|
||||
poll: poll({ status: "error", error: "授权已过期" }),
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatExpiresAt", () => {
|
||||
it("returns null for null/invalid input", () => {
|
||||
expect(formatExpiresAt(null)).toBeNull();
|
||||
expect(formatExpiresAt("not-a-date")).toBeNull();
|
||||
});
|
||||
|
||||
it("formats a valid ISO timestamp to a non-empty string", () => {
|
||||
const out = formatExpiresAt("2026-07-01T08:30:00Z");
|
||||
expect(typeof out).toBe("string");
|
||||
expect(out).not.toBe("");
|
||||
});
|
||||
});
|
||||
101
apps/web/lib/settings/kimiOauth.ts
Normal file
101
apps/web/lib/settings/kimiOauth.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
// Kimi Code OAuth device-flow 连接态纯逻辑(C3 扩 K1.3,K1.4 前端)。
|
||||
// 把「连接状态查询」「device 启动响应」「job 轮询结果」收窄/归一成一个
|
||||
// 可渲染的连接阶段(connect phase),组件只读结果、不含分支逻辑。
|
||||
// 纯函数 + node-env 单测;token 永不出现(job 结果只 {connected, provider})。
|
||||
|
||||
import type { JobView, PollState } from "@/lib/jobs/job";
|
||||
import type {
|
||||
OAuthStartResponse,
|
||||
OAuthStatusResponse,
|
||||
} from "@/lib/api/types";
|
||||
|
||||
// Kimi Code 是 OAuth 订阅 plan 提供商(与 API-key provider `kimi` 分离)。
|
||||
export const KIMI_CODE_PROVIDER = "kimi-code";
|
||||
export const KIMI_CODE_MODEL = "kimi-for-coding";
|
||||
|
||||
// 连接流阶段:
|
||||
// - idle:未发起且未连接(展示「连接」按钮)。
|
||||
// - connected:状态查询/job 完成显示已连接(展示「断开」)。
|
||||
// - awaiting:已拿 device code,正在等待用户在浏览器授权 + 轮询 job。
|
||||
// - error:device 启动失败 / 轮询失败 / 过期 / 拒绝(展示错误 + 允许重试)。
|
||||
export type ConnectPhase = "idle" | "awaiting" | "connected" | "error";
|
||||
|
||||
// device 启动后用户面要展示的信息(无 token)。
|
||||
export interface DeviceDisplay {
|
||||
userCode: string;
|
||||
verificationUri: string;
|
||||
verificationUriComplete: string | null;
|
||||
expiresIn: number;
|
||||
interval: number;
|
||||
}
|
||||
|
||||
// 把 OAuthStartResponse 收窄成展示用 DeviceDisplay(缺字段给安全默认)。
|
||||
export function toDeviceDisplay(res: OAuthStartResponse): DeviceDisplay {
|
||||
return {
|
||||
userCode: res.user_code,
|
||||
verificationUri: res.verification_uri,
|
||||
verificationUriComplete: res.verification_uri_complete ?? null,
|
||||
expiresIn: typeof res.expires_in === "number" ? res.expires_in : 0,
|
||||
interval: typeof res.interval === "number" ? res.interval : 5,
|
||||
};
|
||||
}
|
||||
|
||||
// 优先打开的授权 URL:有 complete(带 user_code 预填)就用它,否则裸 verification_uri。
|
||||
export function authOpenUrl(device: DeviceDisplay): string {
|
||||
return device.verificationUriComplete ?? device.verificationUri;
|
||||
}
|
||||
|
||||
// 连接状态(GET .../oauth/status)收窄。
|
||||
export interface ConnectionStatus {
|
||||
connected: boolean;
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
export function toConnectionStatus(
|
||||
res: OAuthStatusResponse,
|
||||
): ConnectionStatus {
|
||||
return {
|
||||
connected: res.connected === true,
|
||||
expiresAt: typeof res.expires_at === "string" ? res.expires_at : null,
|
||||
};
|
||||
}
|
||||
|
||||
// kimi_oauth job 完成态的 result:{connected, provider}(**绝无 token**)。
|
||||
export function jobConnected(job: JobView): boolean {
|
||||
return job.result?.["connected"] === true;
|
||||
}
|
||||
|
||||
// 把「是否已发起连接 + 轮询状态」映射成连接阶段。
|
||||
// - 未发起(started=false):connected ? connected : idle。
|
||||
// - 已发起:done 且 job.connected → connected;error → error;否则 awaiting。
|
||||
export function connectPhase(args: {
|
||||
started: boolean;
|
||||
connected: boolean;
|
||||
poll: PollState;
|
||||
}): ConnectPhase {
|
||||
const { started, connected, poll } = args;
|
||||
if (!started) {
|
||||
return connected ? "connected" : "idle";
|
||||
}
|
||||
if (poll.status === "done") {
|
||||
return poll.job !== null && jobConnected(poll.job) ? "connected" : "error";
|
||||
}
|
||||
if (poll.status === "error") {
|
||||
return "error";
|
||||
}
|
||||
return "awaiting";
|
||||
}
|
||||
|
||||
// 把 ISO8601 过期时刻格式化成可读文案(无效/缺省→null)。
|
||||
export function formatExpiresAt(iso: string | null): string | null {
|
||||
if (!iso) return null;
|
||||
const ms = Date.parse(iso);
|
||||
if (Number.isNaN(ms)) return null;
|
||||
return new Date(ms).toLocaleString("zh-CN", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
107
apps/web/lib/settings/providers.test.ts
Normal file
107
apps/web/lib/settings/providers.test.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
API_KEY_PROVIDERS,
|
||||
KNOWN_PROVIDERS,
|
||||
applyProviderChange,
|
||||
defaultModelFor,
|
||||
draftsToRoutingInput,
|
||||
toRoutingDrafts,
|
||||
type RoutingDraft,
|
||||
} from "./providers";
|
||||
|
||||
describe("KNOWN_PROVIDERS", () => {
|
||||
it("includes kimi-code as an OAuth provider with a fixed model", () => {
|
||||
const kc = KNOWN_PROVIDERS.find((p) => p.id === "kimi-code");
|
||||
expect(kc).toBeDefined();
|
||||
expect(kc?.auth).toBe("oauth");
|
||||
expect(kc?.defaultModel).toBe("kimi-for-coding");
|
||||
});
|
||||
|
||||
it("API_KEY_PROVIDERS excludes the OAuth provider", () => {
|
||||
expect(API_KEY_PROVIDERS.some((p) => p.id === "kimi-code")).toBe(false);
|
||||
expect(API_KEY_PROVIDERS.some((p) => p.id === "deepseek")).toBe(true);
|
||||
});
|
||||
|
||||
it("includes kimi-code-key as an api_key provider with a fixed model", () => {
|
||||
const kck = KNOWN_PROVIDERS.find((p) => p.id === "kimi-code-key");
|
||||
expect(kck).toBeDefined();
|
||||
expect(kck?.auth).toBe("api_key");
|
||||
expect(kck?.defaultModel).toBe("kimi-for-coding");
|
||||
});
|
||||
|
||||
it("API_KEY_PROVIDERS includes the static-key Kimi Code provider", () => {
|
||||
expect(API_KEY_PROVIDERS.some((p) => p.id === "kimi-code-key")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("defaultModelFor", () => {
|
||||
it("returns the OAuth provider's fixed model", () => {
|
||||
expect(defaultModelFor("kimi-code")).toBe("kimi-for-coding");
|
||||
});
|
||||
|
||||
it("returns the static-key Kimi Code provider's fixed model", () => {
|
||||
expect(defaultModelFor("kimi-code-key")).toBe("kimi-for-coding");
|
||||
});
|
||||
|
||||
it("returns empty string for api_key providers / unknown", () => {
|
||||
expect(defaultModelFor("deepseek")).toBe("");
|
||||
expect(defaultModelFor("nope")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toRoutingDrafts", () => {
|
||||
it("expands to all tiers, filling missing ones empty", () => {
|
||||
const drafts = toRoutingDrafts([
|
||||
{ tier: "writer", provider: "deepseek", model: "deepseek-chat" },
|
||||
]);
|
||||
expect(drafts.map((d) => d.tier)).toEqual(["writer", "analyst", "light"]);
|
||||
expect(drafts[0]).toEqual({
|
||||
tier: "writer",
|
||||
provider: "deepseek",
|
||||
model: "deepseek-chat",
|
||||
});
|
||||
expect(drafts[1]).toEqual({ tier: "analyst", provider: "", model: "" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyProviderChange", () => {
|
||||
it("auto-fills the OAuth provider's fixed model", () => {
|
||||
const next = applyProviderChange(
|
||||
{ tier: "writer", provider: "", model: "" },
|
||||
"kimi-code",
|
||||
);
|
||||
expect(next).toEqual({
|
||||
tier: "writer",
|
||||
provider: "kimi-code",
|
||||
model: "kimi-for-coding",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears the model when switching to an api_key provider", () => {
|
||||
const next = applyProviderChange(
|
||||
{ tier: "writer", provider: "kimi-code", model: "kimi-for-coding" },
|
||||
"deepseek",
|
||||
);
|
||||
expect(next).toEqual({ tier: "writer", provider: "deepseek", model: "" });
|
||||
});
|
||||
|
||||
it("does not mutate the input draft", () => {
|
||||
const draft: RoutingDraft = { tier: "writer", provider: "", model: "" };
|
||||
applyProviderChange(draft, "kimi-code");
|
||||
expect(draft).toEqual({ tier: "writer", provider: "", model: "" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("draftsToRoutingInput", () => {
|
||||
it("keeps only rows with both provider and model", () => {
|
||||
const input = draftsToRoutingInput([
|
||||
{ tier: "writer", provider: "kimi-code", model: "kimi-for-coding" },
|
||||
{ tier: "analyst", provider: "", model: "" },
|
||||
{ tier: "light", provider: "deepseek", model: "" },
|
||||
]);
|
||||
expect(input).toEqual([
|
||||
{ tier: "writer", provider: "kimi-code", model: "kimi-for-coding" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,103 @@
|
||||
// 提供商鉴权方式:api_key(凭据行)或 oauth(device-flow 连接按钮,如 Kimi Code)。
|
||||
export type ProviderAuthKind = "api_key" | "oauth";
|
||||
|
||||
export interface KnownProvider {
|
||||
id: string;
|
||||
label: string;
|
||||
auth: ProviderAuthKind;
|
||||
// OAuth 提供商在档位路由里用的默认 model(API-key 提供商由用户填写/后端默认)。
|
||||
defaultModel?: string;
|
||||
}
|
||||
|
||||
// 已知提供商(UX §6.10)。后端按 provider 字符串识别;这里只是 UI 候选列表。
|
||||
export const KNOWN_PROVIDERS: { id: string; label: string }[] = [
|
||||
{ id: "anthropic", label: "Anthropic" },
|
||||
{ id: "deepseek", label: "DeepSeek" },
|
||||
{ id: "kimi", label: "Kimi" },
|
||||
{ id: "openai", label: "OpenAI" },
|
||||
{ id: "qwen", label: "通义千问" },
|
||||
{ id: "glm", label: "智谱 GLM" },
|
||||
{ id: "gemini", label: "Gemini" },
|
||||
// `kimi-code` 是 OAuth 订阅 plan 提供商(device flow,伪造客户端头,有封号风险),与 API-key
|
||||
// 的 `kimi` 分离(K1.4)。`kimi-code-key` 是同一订阅 plan 的**静态 Console Key** 路径(ToS 合规、
|
||||
// 无伪造头)——普通 api_key 提供商,固定 model `kimi-for-coding`。
|
||||
export const KNOWN_PROVIDERS: KnownProvider[] = [
|
||||
{ id: "anthropic", label: "Anthropic", auth: "api_key" },
|
||||
{ id: "deepseek", label: "DeepSeek", auth: "api_key" },
|
||||
{ id: "kimi", label: "Kimi", auth: "api_key" },
|
||||
{ id: "openai", label: "OpenAI", auth: "api_key" },
|
||||
{ id: "qwen", label: "通义千问", auth: "api_key" },
|
||||
{ id: "glm", label: "智谱 GLM", auth: "api_key" },
|
||||
{ id: "gemini", label: "Gemini", auth: "api_key" },
|
||||
{
|
||||
id: "kimi-code-key",
|
||||
label: "Kimi Code(订阅 Key)",
|
||||
auth: "api_key",
|
||||
defaultModel: "kimi-for-coding",
|
||||
},
|
||||
{
|
||||
id: "kimi-code",
|
||||
label: "Kimi Code(OAuth)",
|
||||
auth: "oauth",
|
||||
defaultModel: "kimi-for-coding",
|
||||
},
|
||||
];
|
||||
|
||||
// API-key 凭据行只展示 api_key 提供商;OAuth 提供商有独立连接区。
|
||||
export const API_KEY_PROVIDERS: KnownProvider[] = KNOWN_PROVIDERS.filter(
|
||||
(p) => p.auth === "api_key",
|
||||
);
|
||||
|
||||
export const TIER_LABELS: Record<string, string> = {
|
||||
writer: "写手档",
|
||||
analyst: "分析档",
|
||||
light: "轻量档",
|
||||
};
|
||||
|
||||
// 档位顺序(路由编辑器列出全部档位,缺省的也能配)。
|
||||
export const TIERS = ["writer", "analyst", "light"] as const;
|
||||
export type Tier = (typeof TIERS)[number];
|
||||
|
||||
// 某 provider 在路由里使用的默认 model:OAuth 提供商有固定 model,其余给空串占位。
|
||||
export function defaultModelFor(providerId: string): string {
|
||||
return (
|
||||
KNOWN_PROVIDERS.find((p) => p.id === providerId)?.defaultModel ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
// 单条档位路由的可编辑草稿(纯数据)。
|
||||
export interface RoutingDraft {
|
||||
tier: string;
|
||||
provider: string;
|
||||
model: string;
|
||||
}
|
||||
|
||||
export interface TierRouting {
|
||||
tier: string;
|
||||
provider: string;
|
||||
model: string;
|
||||
fallback?: string[] | null;
|
||||
}
|
||||
|
||||
// 把已存路由(可能缺档位)展开成「全部档位」的可编辑草稿(缺的给空)。
|
||||
export function toRoutingDrafts(existing: TierRouting[]): RoutingDraft[] {
|
||||
const byTier = new Map(existing.map((r) => [r.tier, r]));
|
||||
return TIERS.map((tier) => {
|
||||
const row = byTier.get(tier);
|
||||
return {
|
||||
tier,
|
||||
provider: row?.provider ?? "",
|
||||
model: row?.model ?? "",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// 选择 provider 时自动套用该 provider 的默认 model(OAuth 固定 model;否则保留已填值或清空)。
|
||||
export function applyProviderChange(
|
||||
draft: RoutingDraft,
|
||||
providerId: string,
|
||||
): RoutingDraft {
|
||||
const def = defaultModelFor(providerId);
|
||||
return { ...draft, provider: providerId, model: def !== "" ? def : "" };
|
||||
}
|
||||
|
||||
// 草稿 → PUT body 的 tier_routing:只取选了 provider+model 的行(不可变)。
|
||||
export function draftsToRoutingInput(
|
||||
drafts: RoutingDraft[],
|
||||
): { tier: string; provider: string; model: string }[] {
|
||||
return drafts
|
||||
.filter((d) => d.provider.trim() !== "" && d.model.trim() !== "")
|
||||
.map((d) => ({ tier: d.tier, provider: d.provider, model: d.model }));
|
||||
}
|
||||
|
||||
139
apps/web/lib/settings/useKimiOauth.ts
Normal file
139
apps/web/lib/settings/useKimiOauth.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api/client";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import { useJobPoll } from "@/lib/jobs/useJobPoll";
|
||||
import {
|
||||
authOpenUrl,
|
||||
connectPhase,
|
||||
toConnectionStatus,
|
||||
toDeviceDisplay,
|
||||
type ConnectPhase,
|
||||
type DeviceDisplay,
|
||||
} from "./kimiOauth";
|
||||
|
||||
const START = "/settings/providers/kimi-code/oauth/start";
|
||||
const DISCONNECT = "/settings/providers/kimi-code/oauth/disconnect";
|
||||
|
||||
export interface UseKimiOauth {
|
||||
// 派生连接阶段(idle/awaiting/connected/error),驱动 UI。
|
||||
phase: ConnectPhase;
|
||||
// device 启动后展示给用户的信息(user_code + 验证 URL);未启动→null。
|
||||
device: DeviceDisplay | null;
|
||||
// 已连接时的 access token 过期时刻(ISO8601;可能为 null)。
|
||||
expiresAt: string | null;
|
||||
// 任一在途请求(start/disconnect)或正在轮询。
|
||||
busy: boolean;
|
||||
// 错误文案(device 启动失败 / 轮询失败 / 过期 / 拒绝)。
|
||||
error: string | null;
|
||||
// 发起连接:POST start → 拿 user_code + job_id → 开浏览器 + 轮询 job。
|
||||
connect: () => Promise<void>;
|
||||
// 断开:POST disconnect → 复位为未连接。
|
||||
disconnect: () => Promise<void>;
|
||||
}
|
||||
|
||||
// 在浏览器打开授权页(device complete URL 优先)。SSR/无 window 时静默跳过。
|
||||
function openVerification(device: DeviceDisplay): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.open(authOpenUrl(device), "_blank", "noopener,noreferrer");
|
||||
}
|
||||
|
||||
// Kimi Code OAuth device-flow 连接编排(K1.4)。
|
||||
// connect:POST .../oauth/start(202)→ 展示 user_code + 开浏览器 → 轮询 job 到 done/failed。
|
||||
// status 进页传入 initialConnected/initialExpiresAt(Server Component 取)。
|
||||
export function useKimiOauth(args: {
|
||||
initialConnected: boolean;
|
||||
initialExpiresAt: string | null;
|
||||
}): UseKimiOauth {
|
||||
const [connected, setConnected] = useState(args.initialConnected);
|
||||
const [expiresAt, setExpiresAt] = useState<string | null>(
|
||||
args.initialExpiresAt,
|
||||
);
|
||||
const [device, setDevice] = useState<DeviceDisplay | null>(null);
|
||||
const [started, setStarted] = useState(false);
|
||||
const [inFlight, setInFlight] = useState(false);
|
||||
const poll = useJobPoll();
|
||||
const toast = useToast();
|
||||
const startedRef = useRef(false);
|
||||
|
||||
const phase = connectPhase({ started, connected, poll });
|
||||
|
||||
// 轮询终态:done 且 job.connected → 已连接(刷新状态);error → 提示。
|
||||
useEffect(() => {
|
||||
if (!startedRef.current) return;
|
||||
if (poll.status === "done") {
|
||||
void refreshStatus().then((ok) => {
|
||||
if (ok) {
|
||||
setConnected(true);
|
||||
toast("已连接 Kimi Code。", "success");
|
||||
}
|
||||
});
|
||||
}
|
||||
if (poll.status === "error") {
|
||||
toast(`连接失败:${poll.error ?? "授权未完成或已过期"}`, "error");
|
||||
}
|
||||
// 仅在 poll.status 变化时反应。
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [poll.status]);
|
||||
|
||||
const refreshStatus = useCallback(async (): Promise<boolean> => {
|
||||
const { data, error } = await api.GET(
|
||||
"/settings/providers/kimi-code/oauth/status",
|
||||
);
|
||||
if (error || !data) return false;
|
||||
const status = toConnectionStatus(data);
|
||||
setExpiresAt(status.expiresAt);
|
||||
return status.connected;
|
||||
}, []);
|
||||
|
||||
const connect = useCallback<UseKimiOauth["connect"]>(async () => {
|
||||
setInFlight(true);
|
||||
try {
|
||||
const { data, error } = await api.POST(START, {});
|
||||
if (error || !data) {
|
||||
toast("发起 Kimi Code 连接失败,请稍后重试。", "error");
|
||||
return;
|
||||
}
|
||||
const dev = toDeviceDisplay(data);
|
||||
setDevice(dev);
|
||||
setStarted(true);
|
||||
startedRef.current = true;
|
||||
openVerification(dev);
|
||||
poll.poll(data.job_id);
|
||||
} finally {
|
||||
setInFlight(false);
|
||||
}
|
||||
}, [poll, toast]);
|
||||
|
||||
const disconnect = useCallback<UseKimiOauth["disconnect"]>(async () => {
|
||||
setInFlight(true);
|
||||
try {
|
||||
const { data, error } = await api.POST(DISCONNECT, {});
|
||||
if (error || !data) {
|
||||
toast("断开 Kimi Code 失败,请稍后重试。", "error");
|
||||
return;
|
||||
}
|
||||
poll.reset();
|
||||
startedRef.current = false;
|
||||
setStarted(false);
|
||||
setDevice(null);
|
||||
setConnected(false);
|
||||
setExpiresAt(null);
|
||||
toast("已断开 Kimi Code。", "success");
|
||||
} finally {
|
||||
setInFlight(false);
|
||||
}
|
||||
}, [poll, toast]);
|
||||
|
||||
return {
|
||||
phase,
|
||||
device,
|
||||
expiresAt,
|
||||
busy: inFlight || (startedRef.current && poll.status === "polling"),
|
||||
error: poll.status === "error" ? poll.error : null,
|
||||
connect,
|
||||
disconnect,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user