Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

feat(llm): add Kimi Code provider with OAuth device authorization

Tony Yu8cc3836a5eb3
diff --git a/app/models/llm_provider.py b/app/models/llm_provider.py
index 3b13092c..31e6ed18 100644
--- a/app/models/llm_provider.py
+++ b/app/models/llm_provider.py
@@ -487,6 +487,42 @@ LLM_PROVIDER_REGISTRY = (
LLMProviderField("timeout", "Timeout (seconds)", default_value="300"),
),
),
+ # Kimi 订阅(Plus 及以上档位的 Kimi Code 权益)采用 OAuth 设备授权:
+ # 用户在浏览器里一键确认后,服务层直接携带 Bearer token 调用官方
+ # OpenAI 兼容端点,不需要申请按量 API Key。中国站和 Global 使用各自
+ # 独立的账号与授权体系,endpoint 同步授权页、API 地址与订阅链接。
+ LLMProviderSpec(
+ "kimi_code",
+ "Kimi Code (Kimi subscription)",
+ adapter="kimi_code",
+ requires_api_key=False,
+ show_api_key=False,
+ requires_base_url=False,
+ show_base_url=False,
+ requires_model_name=False,
+ default_model="kimi-for-coding",
+ extra_fields=(
+ LLMProviderField("timeout", "Timeout (seconds)", default_value="300"),
+ ),
+ service_endpoints=(
+ LLMProviderEndpoint(
+ endpoint_id="china",
+ default_label="China",
+ base_url="https://api.kimi.com/coding/v1",
+ api_key_url="https://www.kimi.com/code?aff=moneyprinterturbo",
+ model_docs_url="https://platform.kimi.com/docs/models?aff=moneyprinterturbo",
+ ),
+ LLMProviderEndpoint(
+ endpoint_id="global",
+ default_label="Global",
+ base_url="https://api.kimi.ai/coding/v1",
+ api_key_url="https://www.kimi.ai/code?aff=moneyprinterturbo",
+ model_docs_url="https://platform.kimi.ai/docs/models?aff=moneyprinterturbo",
+ ),
+ ),
+ default_service_endpoint_id="china",
+ international_service_endpoint_id="global",
+ ),
LLMProviderSpec(
"oneapi",
"OneAPI",
diff --git a/app/services/kimi_code_oauth.py b/app/services/kimi_code_oauth.py
new file mode 100644
index 00000000..50f0c01e
--- /dev/null
+++ b/app/services/kimi_code_oauth.py
@@ -0,0 +1,326 @@
+"""
+Kimi Code (Kimi subscription) OAuth device-flow support.
+
+Kimi Code plan subscribers do not pay per token: they authenticate once in the
+browser and third-party apps call the OpenAI-compatible coding endpoint with a
+Bearer token. This module implements the device authorization grant used by
+the Kimi Code CLI:
+
+ 1. POST {auth}/api/oauth/device_authorization -> device_code + user_code
+ 2. user opens {site}/code/authorize_device?user_code=... and approves
+ 3. POST {auth}/api/oauth/token -> access_token (+ refresh_token)
+ 4. call {api}/usages, {api}/messages with the access token
+
+Both regions are supported: China (auth.kimi.com / api.kimi.com) and Global
+(auth.kimi.ai / api.kimi.ai). Token bundles are persisted in the app config so
+a refresh survives restarts; access tokens expire after 15 minutes and are
+renewed transparently with the stored refresh token.
+
+Requests identify themselves genuinely as MoneyPrinterTurbo (X-Msh-* headers
+and User-Agent), following Kimi's third-party guideline to keep the tool's
+real client identity — the same shape CLIProxyAPI uses in production.
+"""
+
+import math
+import threading
+import time
+import uuid
+
+import requests
+from loguru import logger
+
+from app import __version__
+from app.config import config
+
+# Public OAuth client id shipped by the Kimi Code CLI. There is no third-party
+# client registration today, so every integration with the device flow uses
+# this id (CLIProxyAPI and many others do the same); what identifies the
+# application is the genuine identity headers below, not the client id. A
+# dedicated MoneyPrinterTurbo client id can be set later through the
+# `kimi_code_client_id` config field once issued.
+DEFAULT_CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098"
+
+DEFAULT_TIMEOUT_SECONDS = 300.0
+
+_REGIONS = {
+ "china": {
+ "auth_base": "https://auth.kimi.com",
+ "api_base": "https://api.kimi.com/coding/v1",
+ "site_base": "https://www.kimi.com",
+ },
+ "global": {
+ "auth_base": "https://auth.kimi.ai",
+ "api_base": "https://api.kimi.ai/coding/v1",
+ "site_base": "https://www.kimi.ai",
+ },
+}
+
+# config.app keys used to persist the OAuth state
+_K_REGION = "kimi_code_region"
+_K_CLIENT_ID = "kimi_code_client_id"
+_K_DEVICE_ID = "kimi_code_device_id"
+_K_ACCESS = "kimi_code_access_token"
+_K_REFRESH = "kimi_code_refresh_token"
+_K_EXPIRES_AT = "kimi_code_token_expires_at" # unix seconds (float)
+_K_USER_CODE = "kimi_code_last_user_code" # diagnostics only
+
+# Refresh 60 seconds before actual expiry so a slow request never starts with
+# a token that dies mid-flight.
+_EXPIRY_MARGIN_SECONDS = 60.0
+
+# Kimi 会轮换 refresh token,同一个旧 token 只能成功续期一次。并发请求必须
+# 串行续期,否则第二个线程会拿着已轮换的旧 token 得到 invalid_grant。
+_refresh_lock = threading.Lock()
+
+
+def _cfg(key, default=""):
+ # 读路径必须合并排队中的非阻塞更新:视频任务持有配置锁期间,_set 的写入
+ # 只进入队列,直接读 config.app 会看不到刚完成的登录或 refresh 结果,
+ # 导致已授权被误判为未授权、或用已轮换的旧 refresh token 重复续期。
+ snapshot = config.snapshot_config_with_pending(config.app)
+ value = snapshot.get(key, default)
+ return value if value is not None else default
+
+
+def _set(key, value):
+ # Queued non-blocking update; applied immediately when no video task holds
+ # the config lock, otherwise applied when the running task releases it.
+ config.update_config_nonblocking(config.app, key, value)
+
+
+def client_id() -> str:
+ return str(_cfg(_K_CLIENT_ID, "") or DEFAULT_CLIENT_ID)
+
+
+def device_id() -> str:
+ existing = str(_cfg(_K_DEVICE_ID, "")).strip()
+ if existing:
+ return existing
+ new_id = str(uuid.uuid4())
+ _set(_K_DEVICE_ID, new_id)
+ return new_id
+
+
+def region_ids() -> list[str]:
+ return list(_REGIONS.keys())
+
+
+def resolve_region(base_url: str | None = None) -> str:
+ """Map an API base URL (or empty value) back to a region id."""
+ url = (base_url or "").strip().lower()
+ if "kimi.ai" in url:
+ return "global"
+ return "china"
+
+
+def api_base_url(region: str) -> str:
+ return _REGIONS[region]["api_base"]
+
+
+def site_base_url(region: str) -> str:
+ return _REGIONS[region]["site_base"]
+
+
+def _identity_headers() -> dict:
+ # 真实身份(对齐 Kimi 第三方指引与 CLIProxyAPI 的生产实践):platform 与
+ # 版本都是 MoneyPrinterTurbo 自己的,不伪装成 kimi_code_cli。
+ return {
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Accept": "application/json",
+ "User-Agent": f"MoneyPrinterTurbo/{__version__}",
+ "X-Msh-Platform": "MoneyPrinterTurbo",
+ "X-Msh-Version": __version__,
+ "X-Msh-Device-Name": "MoneyPrinterTurbo",
+ "X-Msh-Device-Model": "MoneyPrinterTurbo",
+ "X-Msh-Os-Version": "any",
+ "X-Msh-Device-Id": device_id(),
+ }
+
+
+def api_headers() -> dict:
+ """Identity headers for calls against the coding endpoint itself."""
+ headers = _identity_headers()
+ headers.pop("Content-Type", None)
+ return headers
+
+
+def request_device_code(region: str) -> dict:
+ """Start a device authorization flow. Returns the raw provider payload."""
+ if region not in _REGIONS:
+ raise ValueError(f"kimi_code: unknown region '{region}'")
+ url = f"{_REGIONS[region]['auth_base']}/api/oauth/device_authorization"
+ response = requests.post(
+ url,
+ headers=_identity_headers(),
+ data={"client_id": client_id()},
+ timeout=30,
+ )
+ if response.status_code != 200:
+ raise ValueError(
+ f"kimi_code: device code request failed "
+ f"({response.status_code}): {response.text[:300]}"
+ )
+ data = _json_or_raise(response, "device authorization")
+ for field in ("device_code", "user_code", "verification_uri_complete"):
+ if not data.get(field):
+ raise ValueError(f"kimi_code: device authorization missing '{field}'")
+ _set(_K_USER_CODE, data["user_code"])
+ return data
+
+
+def _json_or_raise(response, what: str) -> dict:
+ try:
+ return response.json()
+ except ValueError:
+ raise ValueError(
+ f"kimi_code: {what} returned a non-JSON response "
+ f"(HTTP {response.status_code}): {response.text[:200]}"
+ ) from None
+
+
+def poll_token(region: str, device_code: str) -> dict:
+ """
+ One poll of the token endpoint. Returns:
+ - {"pending": True} — user has not approved yet
+ - {"pending": True, "slow_down": True} — server asks to poll slower
+ - {"expired": True} — device code expired; restart
+ - {"denied": True} — user declined the request
+ - the token payload — approved
+ """
+ url = f"{_REGIONS[region]['auth_base']}/api/oauth/token"
+ response = requests.post(
+ url,
+ headers=_identity_headers(),
+ data={
+ "client_id": client_id(),
+ "device_code": device_code,
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ },
+ timeout=30,
+ )
+ data = _json_or_raise(response, "token endpoint")
+ if data.get("access_token"):
+ return data
+ error = data.get("error", "")
+ if error == "authorization_pending":
+ return {"pending": True}
+ if error == "slow_down":
+ # RFC 8628 §3.5: keep polling, but increase the interval — this is a
+ # rate hint, not a failure.
+ return {"pending": True, "slow_down": True}
+ if error == "expired_token":
+ return {"expired": True}
+ if error == "access_denied":
+ return {"denied": True}
+ raise ValueError(
+ f"kimi_code: token request failed: "
+ f"{data.get('error_description') or data.get('error') or data}"
+ )
+
+
+def _refresh(region: str, refresh_token: str) -> dict:
+ url = f"{_REGIONS[region]['auth_base']}/api/oauth/token"
+ response = requests.post(
+ url,
+ headers=_identity_headers(),
+ data={
+ "client_id": client_id(),
+ "refresh_token": refresh_token,
+ "grant_type": "refresh_token",
+ },
+ timeout=30,
+ )
+ data = _json_or_raise(response, "token refresh")
+ if not data.get("access_token"):
+ raise ValueError(
+ f"kimi_code: token refresh failed: "
+ f"{data.get('error_description') or data.get('error') or data}"
+ )
+ return data
+
+
+def store_token_bundle(region: str, payload: dict) -> None:
+ """Persist a fresh token payload (from poll_token or refresh)."""
+ expires_in = payload.get("expires_in") or 900
+ _set(_K_REGION, region)
+ _set(_K_ACCESS, payload["access_token"])
+ if payload.get("refresh_token"):
+ # Kimi rotates refresh tokens; only overwrite when a new one is issued.
+ _set(_K_REFRESH, payload["refresh_token"])
+ _set(_K_EXPIRES_AT, time.time() + float(expires_in))
+ # 必须落盘:纯 API 调用路径没有后续 WebUI 保存,若 refresh token 已轮换而
+ # 配置文件里仍是旧值,重启后将无法续期。非阻塞保存;长任务持锁时由后台
+ # 线程在任务结束后写入。
+ config.try_save_config()
+
+
+def clear_credentials() -> None:
+ for key in (_K_ACCESS, _K_REFRESH, _K_EXPIRES_AT, _K_USER_CODE):
+ _set(key, "")
+ config.try_save_config()
+
+
+def is_authorized() -> bool:
+ return bool(str(_cfg(_K_REFRESH, "")).strip() or str(_cfg(_K_ACCESS, "")).strip())
+
+
+def authorized_region() -> str:
+ return str(_cfg(_K_REGION, "") or "")
+
+
+def get_valid_access_token() -> str:
+ """
+ Return an access token valid for at least the next minute, refreshing with
+ the stored refresh token when needed. Raises ValueError when the user has
+ not completed the device authorization.
+ """
+ access = str(_cfg(_K_ACCESS, "")).strip()
+ expires_at = float(_cfg(_K_EXPIRES_AT, 0) or 0)
+ if access and time.time() < expires_at - _EXPIRY_MARGIN_SECONDS:
+ return access
+ if not str(_cfg(_K_REFRESH, "")).strip():
+ raise ValueError(
+ "kimi_code: not authorized yet, please complete the Kimi sign-in "
+ "in Settings first."
+ )
+ with _refresh_lock:
+ # 拿到锁后重新检查:排队期间另一个线程可能已经完成续期并写回配置,
+ # 直接用它的结果,不要再用同一个旧 refresh token 续第二次。
+ access = str(_cfg(_K_ACCESS, "")).strip()
+ expires_at = float(_cfg(_K_EXPIRES_AT, 0) or 0)
+ if access and time.time() < expires_at - _EXPIRY_MARGIN_SECONDS:
+ return access
+ refresh = str(_cfg(_K_REFRESH, "")).strip()
+ if not refresh:
+ raise ValueError(
+ "kimi_code: not authorized yet, please complete the Kimi "
+ "sign-in in Settings first."
+ )
+ region = str(_cfg(_K_REGION, "") or "china")
+ logger.info("kimi_code: refreshing access token")
+ payload = _refresh(region, refresh)
+ if str(_cfg(_K_REFRESH, "")).strip() != refresh:
+ # 等待响应期间用户断开了连接或重新登录:凭证已失效,丢弃这次
+ # 在途 refresh 的结果,不能让它把授权状态“复活”。
+ logger.info(
+ "kimi_code: credentials changed while refreshing; "
+ "discarding the in-flight refresh result"
+ )
+ raise ValueError(
+ "kimi_code: credentials changed while refreshing; "
+ "please sign in again if needed."
+ )
+ store_token_bundle(region, payload)
+ return payload["access_token"]
+
+
+def coerce_timeout(value) -> float:
+ if value in (None, ""):
+ return DEFAULT_TIMEOUT_SECONDS
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError):
+ raise ValueError(f"timeout must be a number, got '{value}'") from None
+ if not math.isfinite(parsed) or parsed <= 0:
+ raise ValueError(f"timeout must be a positive finite number, got '{value}'")
+ return parsed
diff --git a/app/services/llm.py b/app/services/llm.py
index ac82b766..1e5851e3 100644
--- a/app/services/llm.py
+++ b/app/services/llm.py
@@ -594,6 +594,59 @@ def _generate_response(prompt: str, app_config=None) -> str:
return _normalize_text_response(payload.get("result"), llm_provider)
+ if adapter == "kimi_code":
+ # Kimi 订阅(Plus+ 的 Kimi Code 权益)不签发按量 API Key,鉴权由
+ # OAuth 设备授权完成:WebUI 引导用户在浏览器里一键确认,本地保存
+ # refresh token;access token 15 分钟过期,由 kimi_code_oauth 透明
+ # 续期。请求走官方 OpenAI 兼容端点,与按量 API 是两套独立额度。
+ from app.services import kimi_code_oauth
+
+ try:
+ timeout_seconds = kimi_code_oauth.coerce_timeout(
+ extra_values.get("timeout")
+ )
+ except ValueError as timeout_error:
+ raise ValueError(f"{llm_provider}: {timeout_error}") from None
+
+ access_token = kimi_code_oauth.get_valid_access_token()
+ # 授权区域以凭证为准:token 只对签发它的区域有效。用户在授权后切换
+ # API Platform 时,若按界面区域发请求会把中国签发的 token 打到
+ # Global 端点(必然 401),因此请求地址优先跟随 token 的签发区域。
+ authorized_region = kimi_code_oauth.authorized_region()
+ if authorized_region:
+ request_base_url = kimi_code_oauth.api_base_url(authorized_region)
+ if base_url and authorized_region != kimi_code_oauth.resolve_region(
+ base_url
+ ):
+ logger.warning(
+ f"kimi_code: API Platform selection differs from the "
+ f"authorized region; using '{authorized_region}' to match "
+ "the issued token"
+ )
+ else:
+ request_base_url = base_url or kimi_code_oauth.api_base_url(
+ kimi_code_oauth.resolve_region(base_url)
+ )
+ # 模型名留空时默认 kimi-for-coding:订阅权益内的专用编码模型,
+ # 避免硬编码的通用模型 id 随权益变化而失效。
+ request_model = model_name or "kimi-for-coding"
+ logger.info(f"requesting kimi code chat completion, model: {request_model}")
+ client = sdk_client = OpenAI(
+ api_key=access_token,
+ base_url=request_base_url,
+ timeout=timeout_seconds,
+ # 服务端反爬管线要求与 CLI 一致的设备身份头。
+ default_headers=kimi_code_oauth.api_headers(),
+ )
+ response = client.chat.completions.create(
+ model=request_model, messages=[{"role": "user", "content": prompt}]
+ )
+ if response and isinstance(response, ChatCompletion):
+ return _extract_chat_completion_text(response, llm_provider)
+ raise Exception(
+ f'[{llm_provider}] returned an invalid response: "{response}"'
+ )
+
if adapter == "modelscope":
content = ""
client = sdk_client = OpenAI(
diff --git a/config.example.toml b/config.example.toml
index b4fed091..8e078f1a 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -436,6 +436,16 @@ claude_code_model_name = ""
claude_code_cli_path = ""
claude_code_timeout = ""
+# Kimi Code (Kimi subscription). No API key: sign in once in the browser from
+# Settings -> LLM Settings (OAuth device authorization, China or Global
+# platform) and requests run on your Kimi Code plan usage limits. Credentials
+# are stored here automatically after sign-in (kimi_code_access_token /
+# kimi_code_refresh_token / kimi_code_token_expires_at / kimi_code_region) and
+# refreshed transparently. Leave model_name empty to use "kimi-for-coding".
+# Leave timeout empty to use the 300s default.
+kimi_code_model_name = ""
+kimi_code_timeout = ""
+
# OneAPI. Use the token, Base URL, and model ID from your OneAPI deployment.
# Project: https://github.com/songquanpeng/one-api
oneapi_api_key = ""
diff --git a/docs/skill/mpt_agent.py b/docs/skill/mpt_agent.py
index 8825dd87..d775646b 100644
--- a/docs/skill/mpt_agent.py
+++ b/docs/skill/mpt_agent.py
@@ -75,11 +75,13 @@ RECOMMENDED_LLM_PROVIDERS = {
}
# Providers that generate without an API key stored in config.toml: Ollama talks
# to a local server, LiteLLM resolves credentials through its own environment,
-# and ``claude_code`` consumes the Claude subscription through the locally
-# logged-in ``claude`` CLI. Keep this set aligned with the
-# ``requires_api_key=False`` entries of ``app/models/llm_provider.py``; asking
-# the user for a key that the provider never reads leaves the Skill stuck.
-KEYLESS_LLM_PROVIDERS = {"ollama", "litellm", "claude_code"}
+# ``claude_code`` consumes the Claude subscription through the locally
+# logged-in ``claude`` CLI, and ``kimi_code`` consumes the Kimi Code plan
+# through the OAuth credentials the WebUI sign-in stores in config.toml. Keep
+# this set aligned with the ``requires_api_key=False`` entries of
+# ``app/models/llm_provider.py``; asking the user for a key that the provider
+# never reads leaves the Skill stuck.
+KEYLESS_LLM_PROVIDERS = {"ollama", "litellm", "claude_code", "kimi_code"}
CUSTOM_OPENAI_PROVIDER = "oneapi"
# Hidden providers such as Qwen, Azure, and Grok remain usable when already
@@ -300,6 +302,13 @@ def apply_environment_config(config_path: Path) -> None:
def _provider_is_ready(text: str, provider: str) -> bool:
"""Return whether a provider has enough configuration to generate."""
+ if provider == "kimi_code":
+ # 不需要 API Key,但需要 WebUI「使用 Kimi 登录」后写入的 OAuth 凭证;
+ # 没有凭证时不能当作就绪,否则生成会在运行时才报未授权。
+ return any(
+ _has_configured_value(_plain_config_value(text, field))
+ for field in ("kimi_code_refresh_token", "kimi_code_access_token")
+ )
if provider in KEYLESS_LLM_PROVIDERS:
return True
if not _has_configured_value(
@@ -365,6 +374,9 @@ def missing_config(config_path: Path, cli_args: list[str]) -> tuple[str, list[st
_plain_config_value(text, f"{provider}_api_key")
):
missing.append(f"{provider}_api_key")
+ if provider == "kimi_code" and not _provider_is_ready(text, provider):
+ # 无 Key 可填,缺失的是 WebUI 登录动作而不是配置字段。
+ missing.append("kimi_code_sign_in")
if provider == CUSTOM_OPENAI_PROVIDER:
for suffix in ("base_url", "model_name"):
field = f"{provider}_{suffix}"
@@ -483,6 +495,11 @@ def report_missing_config(provider: str, missing: list[str]) -> int:
if "pexels_api_keys" in missing:
print(f"PEXELS_API_KEY_URL={PEXELS_API_KEY_URL}")
print(f"PEXELS_API_KEY_HELP_URL={PEXELS_API_KEY_HELP_URL}")
+ if "kimi_code_sign_in" in missing:
+ print(
+ "KIMI_CODE_SIGN_IN_REQUIRED="
+ "open Settings -> LLM Settings and sign in with Kimi"
+ )
if "volcengine_seedance_api_key" in missing:
print(f"VOLCENGINE_ARK_API_KEY_URL={VOLCENGINE_ARK_API_KEY_URL}")
print("VOLCENGINE_ARK_API_KEY_ENV=MPT_VOLCENGINE_ARK_API_KEY")
diff --git a/test/services/test_kimi_code_oauth.py b/test/services/test_kimi_code_oauth.py
new file mode 100644
index 00000000..c7bb7734
--- /dev/null
+++ b/test/services/test_kimi_code_oauth.py
@@ -0,0 +1,436 @@
+"""kimi_code OAuth 模块的单元测试。
+
+覆盖设备授权状态机:设备码请求、pending / slow_down / expired / denied 轮询、
+token 持久化与 refresh 轮换、过期余量下的透明续期、并发续期串行化、凭证落盘、
+以及凭证清除。网络层(requests.post)与时间(time.time)全部打桩,不访问真实
+端点;除专门的落盘测试外,配置保存统一打桩,避免触碰真实 config.toml。
+"""
+
+import threading
+import time
+import unittest
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from unittest.mock import patch
+
+import toml
+
+from app.config import config
+from app.services import kimi_code_oauth as oauth
+
+
+def _response(payload, status_code=200):
+ class _Resp:
+ def __init__(self, data, code):
+ self._data = data
+ self.status_code = code
+ self.text = str(data)
+
+ def json(self):
+ if isinstance(self._data, Exception):
+ raise self._data
+ return self._data
+
+ return _Resp(payload, status_code)
+
+
+class TestKimiCodeOAuth(unittest.TestCase):
+ def setUp(self):
+ self.original_app_config = dict(config.app)
+ config.app.clear()
+ # 默认打桩配置保存,避免测试写真实 config.toml;落盘测试会临时恢复真实实现。
+ self.real_try_save_config = config.try_save_config
+ save_patcher = patch.object(config, "try_save_config", return_value=True)
+ self.mock_try_save_config = save_patcher.start()
+ self.addCleanup(save_patcher.stop)
+
+ def tearDown(self):
+ config.app.clear()
+ config.app.update(self.original_app_config)
+
+ # ---- request_device_code ----
+
+ def test_request_device_code_uses_regional_endpoint(self):
+ payload = {
+ "device_code": "dc-1",
+ "user_code": "ABCD-EFGH",
+ "verification_uri": "https://www.kimi.com/code/authorize_device",
+ "verification_uri_complete": "https://www.kimi.com/code/authorize_device?user_code=ABCD-EFGH",
+ "expires_in": 1800,
+ "interval": 5,
+ }
+ with patch.object(
+ oauth.requests, "post", return_value=_response(payload)
+ ) as post:
+ result = oauth.request_device_code("china")
+ self.assertEqual(result["device_code"], "dc-1")
+ self.assertEqual(result["user_code"], "ABCD-EFGH")
+ url = post.call_args.args[0]
+ self.assertTrue(url.startswith("https://auth.kimi.com/"))
+ self.assertEqual(
+ post.call_args.kwargs["data"]["client_id"], oauth.DEFAULT_CLIENT_ID
+ )
+
+ def test_request_device_code_global_region(self):
+ payload = {
+ "device_code": "dc-2",
+ "user_code": "WXYZ-1234",
+ "verification_uri_complete": "https://www.kimi.ai/code/authorize_device?user_code=WXYZ-1234",
+ }
+ with patch.object(
+ oauth.requests, "post", return_value=_response(payload)
+ ) as post:
+ oauth.request_device_code("global")
+ self.assertTrue(post.call_args.args[0].startswith("https://auth.kimi.ai/"))
+
+ def test_request_device_code_requires_fields(self):
+ with patch.object(
+ oauth.requests, "post", return_value=_response({"device_code": "dc"})
+ ):
+ with self.assertRaises(ValueError):
+ oauth.request_device_code("china")
+
+ def test_request_device_code_non_json_raises_diagnosable(self):
+ with patch.object(
+ oauth.requests,
+ "post",
+ return_value=_response(ValueError("No JSON"), status_code=200),
+ ):
+ with self.assertRaisesRegex(ValueError, "non-JSON"):
+ oauth.request_device_code("china")
+
+ # ---- poll_token ----
+
+ def _poll(self, payload):
+ with patch.object(
+ oauth.requests, "post", return_value=_response(payload)
+ ):
+ return oauth.poll_token("china", "dc")
+
+ def test_poll_pending(self):
+ self.assertEqual(
+ self._poll({"error": "authorization_pending"}), {"pending": True}
+ )
+
+ def test_poll_slow_down_stays_pending(self):
+ self.assertEqual(
+ self._poll({"error": "slow_down"}),
+ {"pending": True, "slow_down": True},
+ )
+
+ def test_poll_expired(self):
+ self.assertEqual(self._poll({"error": "expired_token"}), {"expired": True})
+
+ def test_poll_denied(self):
+ self.assertEqual(self._poll({"error": "access_denied"}), {"denied": True})
+
+ def test_poll_success_returns_payload(self):
+ payload = {"access_token": "at-1", "refresh_token": "rt-1", "expires_in": 900}
+ self.assertEqual(self._poll(payload), payload)
+
+ def test_poll_unknown_error_raises(self):
+ with self.assertRaisesRegex(ValueError, "bad thing"):
+ self._poll({"error": "unknown", "error_description": "bad thing"})
+
+ def test_poll_non_json_raises_diagnosable(self):
+ with patch.object(
+ oauth.requests,
+ "post",
+ return_value=_response(ValueError("No JSON"), status_code=502),
+ ):
+ with self.assertRaisesRegex(ValueError, "non-JSON"):
+ oauth.poll_token("china", "dc")
+
+ # ---- store_token_bundle / rotation ----
+
+ def test_store_token_bundle_persists_fields(self):
+ oauth.store_token_bundle(
+ "china", {"access_token": "at-1", "refresh_token": "rt-1", "expires_in": 900}
+ )
+ self.assertEqual(config.app["kimi_code_access_token"], "at-1")
+ self.assertEqual(config.app["kimi_code_refresh_token"], "rt-1")
+ self.assertEqual(config.app["kimi_code_region"], "china")
+ self.assertGreater(config.app["kimi_code_token_expires_at"], 0)
+
+ def test_store_token_bundle_rotates_refresh_only_when_issued(self):
+ oauth.store_token_bundle(
+ "china", {"access_token": "at-1", "refresh_token": "rt-old", "expires_in": 900}
+ )
+ # 新一轮 payload 未携带 refresh token 时,保留已有的,避免覆盖为空。
+ oauth.store_token_bundle(
+ "china", {"access_token": "at-2", "expires_in": 900}
+ )
+ self.assertEqual(config.app["kimi_code_access_token"], "at-2")
+ self.assertEqual(config.app["kimi_code_refresh_token"], "rt-old")
+ oauth.store_token_bundle(
+ "china", {"access_token": "at-3", "refresh_token": "rt-new", "expires_in": 900}
+ )
+ self.assertEqual(config.app["kimi_code_refresh_token"], "rt-new")
+
+ def test_store_token_bundle_requests_config_save(self):
+ # 纯 API 调用路径没有后续 WebUI 保存,写凭证时必须主动请求落盘。
+ oauth.store_token_bundle(
+ "china", {"access_token": "at-1", "refresh_token": "rt-1", "expires_in": 900}
+ )
+ self.mock_try_save_config.assert_called()
+
+ def test_store_token_bundle_saved_to_disk_and_survives_reload(self):
+ """refresh token 轮换后必须可靠落盘:模拟重启后凭磁盘状态仍能续期。"""
+ with TemporaryDirectory() as temp_dir:
+ config_path = Path(temp_dir) / "config.toml"
+ original_cfg = dict(config._cfg)
+ try:
+ with (
+ # 临时文件与目标文件放在同一目录,保证 os.replace 同盘原子替换。
+ patch.object(config, "root_dir", temp_dir),
+ patch.object(config, "config_file", str(config_path)),
+ patch.object(
+ config, "try_save_config", self.real_try_save_config
+ ),
+ ):
+ oauth.store_token_bundle(
+ "china",
+ {
+ "access_token": "at-1",
+ "refresh_token": "rt-new",
+ "expires_in": 900,
+ },
+ )
+ on_disk = toml.load(str(config_path))
+ finally:
+ # save_config 会重写模块级 _cfg,恢复以免影响其它测试。
+ config._cfg.clear()
+ config._cfg.update(original_cfg)
+ self.assertEqual(on_disk["app"]["kimi_code_access_token"], "at-1")
+ self.assertEqual(on_disk["app"]["kimi_code_refresh_token"], "rt-new")
+ # 模拟重启:清空内存配置,只从磁盘内容恢复。
+ config.app.clear()
+ config.app.update(on_disk["app"])
+ self.assertTrue(oauth.is_authorized())
+ self.assertEqual(oauth.get_valid_access_token(), "at-1")
+
+ # ---- get_valid_access_token ----
+
+ def _prime_tokens(self, expires_in=900):
+ oauth.store_token_bundle(
+ "china", {"access_token": "at-1", "refresh_token": "rt-1", "expires_in": expires_in}
+ )
+
+ def test_get_valid_access_token_returns_cached(self):
+ self._prime_tokens()
+ self.assertEqual(oauth.get_valid_access_token(), "at-1")
+
+ def test_get_valid_access_token_refreshes_near_expiry(self):
+ self._prime_tokens(expires_in=10) # 小于 60s 余量,触发续期
+ refreshed = {"access_token": "at-2", "refresh_token": "rt-2", "expires_in": 900}
+ with patch.object(
+ oauth.requests, "post", return_value=_response(refreshed)
+ ) as post:
+ token = oauth.get_valid_access_token()
+ self.assertEqual(token, "at-2")
+ # 续期结果必须写回配置,下一次调用不再重复刷新。
+ self.assertEqual(config.app["kimi_code_access_token"], "at-2")
+ self.assertEqual(config.app["kimi_code_refresh_token"], "rt-2")
+ self.assertEqual(post.call_args.kwargs["data"]["grant_type"], "refresh_token")
+
+ def test_get_valid_access_token_expired_refresh(self):
+ self._prime_tokens(expires_in=-1)
+ refreshed = {"access_token": "at-2", "refresh_token": "rt-2", "expires_in": 900}
+ with patch.object(oauth.requests, "post", return_value=_response(refreshed)):
+ self.assertEqual(oauth.get_valid_access_token(), "at-2")
+
+ def test_get_valid_access_token_requires_authorization(self):
+ with self.assertRaisesRegex(ValueError, "not authorized"):
+ oauth.get_valid_access_token()
+
+ def test_get_valid_access_token_refresh_failure_raises(self):
+ self._prime_tokens(expires_in=-1)
+ with patch.object(
+ oauth.requests,
+ "post",
+ return_value=_response({"error": "invalid_grant"}),
+ ):
+ with self.assertRaisesRegex(ValueError, "refresh failed"):
+ oauth.get_valid_access_token()
+
+ def test_concurrent_refresh_is_serialized(self):
+ """并发续期必须串行:旧 refresh token 只能换一次,其余线程复用结果。"""
+ self._prime_tokens(expires_in=-1)
+ refresh_calls = []
+
+ def fake_refresh(region, refresh_token):
+ refresh_calls.append(refresh_token)
+ time.sleep(0.05) # 放大竞态窗口
+ return {"access_token": "at-new", "refresh_token": "rt-new", "expires_in": 900}
+
+ results = []
+ errors = []
+
+ def worker():
+ try:
+ results.append(oauth.get_valid_access_token())
+ except Exception as exc: # pragma: no cover - 失败时便于诊断
+ errors.append(exc)
+
+ with patch.object(oauth, "_refresh", side_effect=fake_refresh):
+ threads = [threading.Thread(target=worker) for _ in range(4)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ self.assertEqual(errors, [])
+ self.assertEqual(len(refresh_calls), 1)
+ self.assertEqual(sorted(results), ["at-new"] * 4)
+ self.assertEqual(config.app["kimi_code_refresh_token"], "rt-new")
+
+ # ---- 配置锁持锁期间的可见性(视频任务并发场景) ----
+
+ def test_credentials_visible_while_config_lock_held(self):
+ """视频任务持锁时 _set 只排队:刚完成的登录必须立即对读取可见。"""
+ with config.runtime_config_lock():
+ oauth.store_token_bundle(
+ "china",
+ {"access_token": "at-1", "refresh_token": "rt-1", "expires_in": 900},
+ )
+ # 排队中的凭证也必须算数:不能误判为未授权。
+ self.assertTrue(oauth.is_authorized())
+ self.assertEqual(oauth.get_valid_access_token(), "at-1")
+
+ def test_successive_calls_reuse_queued_refresh_while_lock_held(self):
+ """持锁期间 refresh 结果仍在队列:后续调用不能重放已轮换的旧 token。"""
+ redeemed = []
+
+ def rotating_refresh(region, refresh_token):
+ if refresh_token in redeemed:
+ # 模拟服务端轮换后拒绝旧 token 重放
+ raise ValueError("kimi_code: token refresh failed: invalid_grant")
+ redeemed.append(refresh_token)
+ return {
+ "access_token": f"at-{len(redeemed)}",
+ "refresh_token": f"rt-{len(redeemed)}",
+ "expires_in": 900,
+ }
+
+ with config.runtime_config_lock(), patch.object(
+ oauth, "_refresh", side_effect=rotating_refresh
+ ):
+ self._prime_tokens(expires_in=-1) # at-1 已过期,rt-1 可兑换一次
+ first = oauth.get_valid_access_token()
+ second = oauth.get_valid_access_token()
+
+ self.assertEqual(first, second)
+ self.assertEqual(redeemed, ["rt-1"])
+
+ # ---- 在途 refresh 与凭证清除/更换的竞态 ----
+
+ def test_in_flight_refresh_discarded_after_disconnect(self):
+ """refresh 响应在途时用户断开连接:结果必须丢弃,授权状态不能复活。"""
+ self._prime_tokens(expires_in=-1)
+
+ def refresh_then_disconnect(region, refresh_token):
+ # 模拟响应返回前用户在另一个会话点了 Disconnect
+ oauth.clear_credentials()
+ return {"access_token": "at-zombie", "refresh_token": "rt-zombie", "expires_in": 900}
+
+ with patch.object(oauth, "_refresh", side_effect=refresh_then_disconnect):
+ with self.assertRaisesRegex(ValueError, "credentials changed"):
+ oauth.get_valid_access_token()
+ self.assertFalse(oauth.is_authorized())
+ self.assertEqual(config.app["kimi_code_access_token"], "")
+
+ def test_in_flight_refresh_discarded_after_credential_replacement(self):
+ """在途 refresh 期间凭证被新登录替换:旧结果不能覆盖新凭证。"""
+ self._prime_tokens(expires_in=-1)
+
+ def refresh_then_replace(region, refresh_token):
+ # 模拟响应返回前用户完成了一次新的登录
+ oauth.store_token_bundle(
+ "china",
+ {"access_token": "at-new-login", "refresh_token": "rt-new-login", "expires_in": 900},
+ )
+ return {"access_token": "at-stale", "refresh_token": "rt-stale", "expires_in": 900}
+
+ with patch.object(oauth, "_refresh", side_effect=refresh_then_replace):
+ with self.assertRaisesRegex(ValueError, "credentials changed"):
+ oauth.get_valid_access_token()
+ self.assertEqual(config.app["kimi_code_access_token"], "at-new-login")
+ self.assertEqual(config.app["kimi_code_refresh_token"], "rt-new-login")
+
+ # ---- 身份头(真实应用身份) ----
+
+ def test_identity_headers_use_genuine_application_identity(self):
+ """身份头必须是 MoneyPrinterTurbo 自己的,不伪装成 kimi_code_cli。"""
+ headers = oauth._identity_headers()
+ self.assertEqual(headers["X-Msh-Platform"], "MoneyPrinterTurbo")
+ self.assertEqual(headers["X-Msh-Version"], oauth.__version__)
+ self.assertTrue(headers["User-Agent"].startswith("MoneyPrinterTurbo/"))
+ self.assertNotIn("kimi_code_cli", headers.values())
+
+ payload = {
+ "device_code": "dc-1",
+ "user_code": "ABCD-EFGH",
+ "verification_uri_complete": "https://www.kimi.com/code/authorize_device?user_code=ABCD-EFGH",
+ }
+ with patch.object(
+ oauth.requests, "post", return_value=_response(payload)
+ ) as post:
+ oauth.request_device_code("china")
+ sent = post.call_args.kwargs["headers"]
+ self.assertEqual(sent["X-Msh-Platform"], "MoneyPrinterTurbo")
+ self.assertTrue(sent["User-Agent"].startswith("MoneyPrinterTurbo/"))
+
+ # ---- network error contract (WebUI 依赖) ----
+
+ def test_request_device_code_network_error_propagates(self):
+ """网络异常以 RequestException 原样抛出,WebUI 据此展示可重试错误。"""
+ with patch.object(
+ oauth.requests,
+ "post",
+ side_effect=oauth.requests.exceptions.ConnectTimeout("boom"),
+ ):
+ with self.assertRaises(oauth.requests.exceptions.RequestException):
+ oauth.request_device_code("china")
+
+ def test_poll_token_network_error_propagates(self):
+ with patch.object(
+ oauth.requests,
+ "post",
+ side_effect=oauth.requests.exceptions.ReadTimeout("boom"),
+ ):
+ with self.assertRaises(oauth.requests.exceptions.RequestException):
+ oauth.poll_token("china", "dc")
+
+ # ---- clear / helpers ----
+
+ def test_clear_credentials(self):
+ self._prime_tokens()
+ oauth.clear_credentials()
+ self.assertFalse(oauth.is_authorized())
+ self.assertEqual(config.app["kimi_code_access_token"], "")
+
+ def test_is_authorized_variants(self):
+ self.assertFalse(oauth.is_authorized())
+ self._prime_tokens()
+ self.assertTrue(oauth.is_authorized())
+
+ def test_resolve_region(self):
+ self.assertEqual(oauth.resolve_region("https://api.kimi.ai/coding/v1"), "global")
+ self.assertEqual(oauth.resolve_region("https://api.kimi.com/coding/v1"), "china")
+ self.assertEqual(oauth.resolve_region(""), "china")
+
+ def test_coerce_timeout(self):
+ self.assertEqual(oauth.coerce_timeout(None), oauth.DEFAULT_TIMEOUT_SECONDS)
+ self.assertEqual(oauth.coerce_timeout("120"), 120.0)
+ with self.assertRaises(ValueError):
+ oauth.coerce_timeout("abc")
+ with self.assertRaises(ValueError):
+ oauth.coerce_timeout("0")
+ with self.assertRaises(ValueError):
+ oauth.coerce_timeout("nan")
+ with self.assertRaises(ValueError):
+ oauth.coerce_timeout("inf")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/services/test_llm.py b/test/services/test_llm.py
index de981854..c0800a88 100644
--- a/test/services/test_llm.py
+++ b/test/services/test_llm.py
@@ -497,6 +497,7 @@ class TestLiteLLMProvider(unittest.TestCase):
"opper",
"ollama",
"claude_code",
+ "kimi_code",
"oneapi",
"litellm",
"groq",
diff --git a/test/services/test_mpt_agent_skill.py b/test/services/test_mpt_agent_skill.py
index 4a8e79eb..9cf85efa 100644
--- a/test/services/test_mpt_agent_skill.py
+++ b/test/services/test_mpt_agent_skill.py
@@ -687,6 +687,61 @@ class TestMptAgentSkill(unittest.TestCase):
config_path.read_text(encoding="utf-8"),
)
+ def test_kimi_code_signed_in_provider_needs_no_api_key(self):
+ """
+ Kimi Code 走 OAuth 订阅凭证,已登录时辅助脚本不能要求 API Key,
+ 也不能把订阅用户切到别的 Provider。
+ """
+ with tempfile.TemporaryDirectory() as temp_dir:
+ config_path = Path(temp_dir) / "config.toml"
+ config_path.write_text(
+ MINIMAL_CONFIG.replace(
+ 'llm_provider = "moonshot"', 'llm_provider = "kimi_code"'
+ ).replace(
+ 'deepseek_api_key = ""',
+ 'deepseek_api_key = "already-configured-key"',
+ ).replace(
+ "pexels_api_keys = []", 'pexels_api_keys = ["pexels-key"]'
+ )
+ + 'kimi_code_refresh_token = "rt-1"\n',
+ encoding="utf-8",
+ )
+ output = io.StringIO()
+
+ with redirect_stdout(output):
+ provider = mpt_agent.reuse_existing_llm_provider(config_path)
+ active_provider, missing = mpt_agent.missing_config(config_path, [])
+
+ self.assertEqual(provider, "kimi_code")
+ self.assertEqual(active_provider, "kimi_code")
+ self.assertEqual(missing, [])
+
+ def test_kimi_code_without_sign_in_reports_sign_in_not_api_key(self):
+ """未登录的 Kimi Code 缺的是登录动作;脚本应报告 sign-in 而非 API Key。"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ config_path = Path(temp_dir) / "config.toml"
+ config_path.write_text(
+ MINIMAL_CONFIG.replace(
+ 'llm_provider = "moonshot"', 'llm_provider = "kimi_code"'
+ ).replace(
+ 'deepseek_api_key = ""',
+ 'deepseek_api_key = "already-configured-key"',
+ ).replace(
+ "pexels_api_keys = []", 'pexels_api_keys = ["pexels-key"]'
+ ),
+ encoding="utf-8",
+ )
+
+ active_provider, missing = mpt_agent.missing_config(config_path, [])
+ output = io.StringIO()
+ with redirect_stdout(output):
+ mpt_agent.report_missing_config(active_provider, missing)
+
+ self.assertEqual(active_provider, "kimi_code")
+ self.assertEqual(missing, ["kimi_code_sign_in"])
+ self.assertNotIn("kimi_code_api_key", output.getvalue())
+ self.assertIn("KIMI_CODE_SIGN_IN_REQUIRED", output.getvalue())
+
def test_only_missing_pexels_key_does_not_ask_for_llm_again(self):
output = io.StringIO()
diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.py
index 19508028..61a5a14a 100644
--- a/test/services/test_webui_i18n.py
+++ b/test/services/test_webui_i18n.py
@@ -55,6 +55,19 @@ ENGLISH_FALLBACK_KEYS = frozenset(
"llm_provider_label.yapi",
"llm_provider_label.opper",
"llm_provider_label.shengsuanyun",
+ "llm_provider_label.kimi_code",
+ "kimi_code.oauth.login",
+ "kimi_code.oauth.pending",
+ "kimi_code.oauth.open_page",
+ "kimi_code.oauth.success",
+ "kimi_code.oauth.authorized",
+ "kimi_code.oauth.disconnect",
+ "kimi_code.oauth.expired",
+ "kimi_code.oauth.denied",
+ "kimi_code.oauth.reauth",
+ "kimi_code.oauth.region_mismatch",
+ "kimi_code.oauth.network_error",
+ "kimi_code.oauth.poll_retry",
"LoomLoom Poll Retry Pending",
"LoomLoom Poll Retry Warning",
"Resume LoomLoom Status Check",
diff --git a/test/services/test_webui_llm_settings.py b/test/services/test_webui_llm_settings.py
index 931bcdf9..e6152ec3 100644
--- a/test/services/test_webui_llm_settings.py
+++ b/test/services/test_webui_llm_settings.py
@@ -1,9 +1,11 @@
from pathlib import Path
from unittest.mock import patch
+import requests
from streamlit.testing.v1 import AppTest
from app.config import config
+from app.services import kimi_code_oauth
from app.services import llm
@@ -241,3 +243,136 @@ def test_ai_video_settings_prioritize_sponsors_and_own_shengsuan_key():
"loomloom_api_token_input",
).value == "settings-token"
assert [str(item.value) for item in app.exception] == []
+
+
+def test_kimi_code_device_authorization_network_error_is_recoverable():
+ """设备授权请求超时:页面不抛异常,提示网络错误,登录按钮保留可直接重试。"""
+ # 本地 config 可能存有真实 Kimi 凭证,必须剔除,否则面板直接显示已授权态。
+ app_config = {
+ key: value
+ for key, value in dict(config.app, llm_provider="kimi_code").items()
+ if not key.startswith("kimi_code_")
+ }
+ app_config["llm_provider"] = "kimi_code"
+
+ with (
+ patch.object(config, "app", app_config),
+ patch.object(config, "ui", dict(config.ui, language="en")),
+ patch.object(config, "try_save_config", return_value=True),
+ patch.object(
+ kimi_code_oauth,
+ "request_device_code",
+ side_effect=requests.exceptions.ConnectTimeout("boom"),
+ ),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.session_state["settings_dialog_open"] = True
+ app.run()
+ assert not app.exception
+
+ _widget_by_key(app.button, "kimi_code_login_button").click().run()
+
+ assert not app.exception
+ error_messages = [str(item.value) for item in app.error]
+ assert any("network error" in message.lower() for message in error_messages)
+ # 流程未建立,登录按钮仍在,用户可直接重试。
+ assert "kimi_code_oauth_flow" not in app.session_state
+ _widget_by_key(app.button, "kimi_code_login_button")
+
+
+def test_kimi_code_poll_network_error_retries_then_offers_restart():
+ """轮询阶段的网络错误不清除流程:自动重试,连续失败后回到可重新登录状态。"""
+ app_config = {
+ key: value
+ for key, value in dict(config.app, llm_provider="kimi_code").items()
+ if not key.startswith("kimi_code_")
+ }
+ app_config["llm_provider"] = "kimi_code"
+ device_payload = {
+ "device_code": "dc-1",
+ "user_code": "ABCD-EFGH",
+ "verification_uri_complete": "https://www.kimi.com/code/authorize_device?user_code=ABCD-EFGH",
+ "interval": 2,
+ }
+
+ with (
+ patch.object(config, "app", app_config),
+ patch.object(config, "ui", dict(config.ui, language="en")),
+ patch.object(config, "try_save_config", return_value=True),
+ patch.object(
+ kimi_code_oauth, "request_device_code", return_value=device_payload
+ ),
+ patch.object(
+ kimi_code_oauth,
+ "poll_token",
+ side_effect=requests.exceptions.ReadTimeout("boom"),
+ ) as poll_mock,
+ patch.object(kimi_code_oauth, "store_token_bundle") as store_mock,
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.session_state["settings_dialog_open"] = True
+ app.run()
+ assert not app.exception
+
+ _widget_by_key(app.selectbox, "kimi_code_service_endpoint_select").set_value(
+ "china"
+ ).run()
+ _widget_by_key(app.button, "kimi_code_login_button").click().run()
+
+ # AppTest 会跟随 st.rerun:整段自动重试在一次点击内完成。
+ # 连续 5 次网络失败后流程结束,页面提示网络错误,登录按钮保留可重试。
+ assert not app.exception
+ assert poll_mock.call_count == 5
+ store_mock.assert_not_called()
+ assert "kimi_code_oauth_flow" not in app.session_state
+ error_messages = [str(item.value) for item in app.error]
+ assert any("network error" in message.lower() for message in error_messages)
+ _widget_by_key(app.button, "kimi_code_login_button")
+
+
+def test_kimi_code_pending_then_success_completes_flow():
+ """轮询 pending 后继续等待,授权成功后写入凭证并结束流程。"""
+ app_config = {
+ key: value
+ for key, value in dict(config.app, llm_provider="kimi_code").items()
+ if not key.startswith("kimi_code_")
+ }
+ app_config["llm_provider"] = "kimi_code"
+ device_payload = {
+ "device_code": "dc-1",
+ "user_code": "ABCD-EFGH",
+ "verification_uri_complete": "https://www.kimi.com/code/authorize_device?user_code=ABCD-EFGH",
+ "interval": 2,
+ }
+ token_payload = {"access_token": "at-1", "refresh_token": "rt-1", "expires_in": 900}
+
+ with (
+ patch.object(config, "app", app_config),
+ patch.object(config, "ui", dict(config.ui, language="en")),
+ patch.object(config, "try_save_config", return_value=True),
+ patch.object(
+ kimi_code_oauth, "request_device_code", return_value=device_payload
+ ),
+ patch.object(
+ kimi_code_oauth,
+ "poll_token",
+ side_effect=[{"pending": True}, token_payload],
+ ),
+ patch.object(kimi_code_oauth, "store_token_bundle") as store_mock,
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.session_state["settings_dialog_open"] = True
+ app.run()
+ assert not app.exception
+
+ _widget_by_key(app.selectbox, "kimi_code_service_endpoint_select").set_value(
+ "china"
+ ).run()
+ _widget_by_key(app.button, "kimi_code_login_button").click().run()
+
+ assert not app.exception
+ store_mock.assert_called_once_with("china", token_payload)
+ assert "kimi_code_oauth_flow" not in app.session_state
diff --git a/webui/Main.py b/webui/Main.py
index 1fafa885..05afef96 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -3587,6 +3587,152 @@ def _render_settings_dialog():
),
)
+ if llm_provider == "kimi_code":
+ # OAuth 设备授权:用户点一次按钮拿到授权链接和 code,在浏览器
+ # 里确认后这里自动轮询换 token。授权状态保存在 config 中,
+ # 后续脚本调用由服务层用 refresh token 自动续期。
+ from app.services import kimi_code_oauth
+
+ oauth_region = kimi_code_oauth.resolve_region(st_llm_base_url)
+ oauth_state_key = "kimi_code_oauth_flow"
+
+ def _start_device_flow():
+ try:
+ device_payload = kimi_code_oauth.request_device_code(
+ oauth_region
+ )
+ except requests.RequestException as network_error:
+ # 网络超时/连接失败不炸页面:提示后登录按钮仍在,
+ # 用户可直接重试。
+ logger.warning(
+ "kimi_code: device authorization request failed: "
+ f"{network_error}"
+ )
+ llm_form_panel.error(tr("kimi_code.oauth.network_error"))
+ return False
+ except ValueError as request_error:
+ llm_form_panel.error(str(request_error))
+ return False
+ st.session_state[oauth_state_key] = {
+ "region": oauth_region,
+ "device_code": device_payload["device_code"],
+ "user_code": device_payload["user_code"],
+ "verification_uri_complete": device_payload[
+ "verification_uri_complete"
+ ],
+ "interval": device_payload.get("interval", 5),
+ }
+ return True
+
+ flow = st.session_state.get(oauth_state_key)
+ if flow:
+ try:
+ token_payload = kimi_code_oauth.poll_token(
+ flow["region"], flow["device_code"]
+ )
+ except requests.RequestException as network_error:
+ # 轮询遇到网络错误不清除流程:按当前间隔自动重试;
+ # 连续多次失败则结束流程,回到可重新登录的状态。
+ flow["network_errors"] = int(flow.get("network_errors", 0)) + 1
+ logger.warning(
+ "kimi_code: token poll failed "
+ f"({flow['network_errors']}): {network_error}"
+ )
+ if flow["network_errors"] >= 5:
+ llm_form_panel.error(tr("kimi_code.oauth.network_error"))
+ del st.session_state[oauth_state_key]
+ flow = None
+ else:
+ st.session_state[oauth_state_key] = flow
+ llm_form_panel.warning(tr("kimi_code.oauth.poll_retry"))
+ time.sleep(max(int(flow.get("interval", 5)), 2))
+ st.rerun()
+ except ValueError as flow_error:
+ llm_form_panel.error(str(flow_error))
+ del st.session_state[oauth_state_key]
+ flow = None
+ else:
+ flow["network_errors"] = 0
+ if token_payload.get("expired"):
+ # 授权码过期(用户长时间未确认):清掉流程,
+ # 回到可重新发起的状态。
+ llm_form_panel.warning(tr("kimi_code.oauth.expired"))
+ del st.session_state[oauth_state_key]
+ flow = None
+ elif token_payload.get("denied"):
+ llm_form_panel.warning(tr("kimi_code.oauth.denied"))
+ del st.session_state[oauth_state_key]
+ flow = None
+ elif token_payload.get("pending"):
+ if token_payload.get("slow_down"):
+ # RFC 8628 §3.5:服务端要求降低轮询频率时
+ # 加大间隔继续等,而不是中断流程。
+ flow["interval"] = int(flow.get("interval", 5)) + 5
+ st.session_state[oauth_state_key] = flow
+ with llm_form_panel:
+ st.info(
+ tr("kimi_code.oauth.pending").format(
+ user_code=flow["user_code"],
+ )
+ )
+ st.link_button(
+ tr("kimi_code.oauth.open_page"),
+ flow["verification_uri_complete"],
+ )
+ st.code(flow["user_code"], language=None)
+ time.sleep(max(int(flow.get("interval", 5)), 2))
+ st.rerun()
+ else:
+ kimi_code_oauth.store_token_bundle(
+ flow["region"], token_payload
+ )
+ del st.session_state[oauth_state_key]
+ llm_form_panel.success(tr("kimi_code.oauth.success"))
+ st.rerun()
+
+ if kimi_code_oauth.is_authorized():
+ auth_region = (
+ kimi_code_oauth.authorized_region() or oauth_region
+ )
+ region_mismatch = auth_region != oauth_region
+ if region_mismatch:
+ # 界面区域与凭证区域不一致:服务层按凭证签发区域发
+ # 请求,这里明确告知并提供按界面区域重新授权的入口。
+ llm_form_panel.warning(
+ tr("kimi_code.oauth.region_mismatch").format(
+ authorized=auth_region, selected=oauth_region
+ )
+ )
+ else:
+ llm_form_panel.success(
+ tr("kimi_code.oauth.authorized").format(
+ region=auth_region
+ )
+ )
+ if llm_form_panel.button(
+ tr("kimi_code.oauth.disconnect"),
+ key="kimi_code_disconnect_button",
+ ):
+ kimi_code_oauth.clear_credentials()
+ st.rerun()
+ if region_mismatch and llm_form_panel.button(
+ tr("kimi_code.oauth.reauth"),
+ key="kimi_code_reauth_button",
+ type="primary",
+ icon=":material/login:",
+ ):
+ if _start_device_flow():
+ st.rerun()
+ elif not flow:
+ if llm_form_panel.button(
+ tr("kimi_code.oauth.login"),
+ key="kimi_code_login_button",
+ type="primary",
+ icon=":material/login:",
+ ):
+ if _start_device_flow():
+ st.rerun()
+
if llm_form_panel.button(
tr("Test LLM Connection"),
key="test_llm_connection_button",
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index b9385d05..9c18385d 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -584,6 +584,20 @@
"MuAPI Billing Notice Without Script": "Each generated clip is billed by MuAPI. Enter or generate the video script to see an estimated task count.",
"Confirm MuAPI Charge": "I understand MuAPI video generation creates paid tasks",
"Confirm MuAPI Charge Help": "MuAPI clips are submitted one at a time and stop once they cover the voiceover duration. An ambiguous submission is not retried because it may already have created a billable remote task.",
- "Confirm MuAPI Charge Required": "Please confirm the MuAPI charge before generating the video."
+ "Confirm MuAPI Charge Required": "Please confirm the MuAPI charge before generating the video.",
+ "llm_provider_label.kimi_code": "Kimi Code (Kimi subscription)",
+ "llm_provider_tips.kimi_code": "##### Kimi Code Configuration\n- **API Key**: not required; click **Sign in with Kimi** and approve once in the browser — requests then run on your Kimi subscription (Kimi Code plan, Plus tier and above)\n- **Base Url**: selected by the API Platform option above (China: `api.kimi.com`; Global: `api.kimi.ai`)\n- **Model Name**: optional; defaults to `kimi-for-coding`\n- New here? Get a plan at the [Kimi Code site]({api_key_url}); see the [model list]({model_docs_url})\n- Requests use your Kimi Code plan usage limits, separate from pay-as-you-go API balance. Access tokens refresh automatically after sign-in",
+ "kimi_code.oauth.login": "Sign in with Kimi",
+ "kimi_code.oauth.pending": "Approve this device in your browser to finish sign-in. Code:",
+ "kimi_code.oauth.open_page": "Open the Kimi authorization page",
+ "kimi_code.oauth.success": "Kimi sign-in completed",
+ "kimi_code.oauth.authorized": "Signed in with Kimi (region: {region}). Requests will use your Kimi Code plan quota.",
+ "kimi_code.oauth.disconnect": "Disconnect Kimi",
+ "kimi_code.oauth.expired": "This sign-in code has expired. Start sign-in again to get a new one.",
+ "kimi_code.oauth.denied": "The authorization request was declined. Start sign-in again if that was a mistake.",
+ "kimi_code.oauth.reauth": "Sign in with Kimi for the selected region",
+ "kimi_code.oauth.region_mismatch": "Signed in for region \"{authorized}\", but the selected API Platform is \"{selected}\". Requests will use \"{authorized}\" to match your credential; sign in again to switch regions.",
+ "kimi_code.oauth.network_error": "Could not reach the Kimi authorization service (network error). Check your connection, then start sign-in again.",
+ "kimi_code.oauth.poll_retry": "Network error while checking the authorization status; retrying automatically…"
}
-}
+}
\ No newline at end of file
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index c7386cb0..ee8f8dcb 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -584,6 +584,20 @@
"MuAPI Billing Notice Without Script": "每段生成视频都会由 MuAPI 计费。填写或生成视频文案后可查看预计任务数量。",
"Confirm MuAPI Charge": "我已了解 MuAPI 视频生成会创建付费任务",
"Confirm MuAPI Charge Help": "MuAPI 素材按脚本片段逐段提交,凑够配音所需时长后立即停止。提交状态不明确时不会自动重试,因为远端任务可能已经创建并产生费用。",
- "Confirm MuAPI Charge Required": "请确认 MuAPI 生成费用后再生成视频。"
+ "Confirm MuAPI Charge Required": "请确认 MuAPI 生成费用后再生成视频。",
+ "llm_provider_label.kimi_code": "Kimi Code(Kimi 订阅)",
+ "llm_provider_tips.kimi_code": "##### Kimi Code 配置说明\n- **API Key**:不需要;点击「使用 Kimi 登录」,在浏览器中确认一次即可,后续调用使用你的 Kimi 订阅(Plus 及以上档位的 Kimi Code 权益)\n- **Base Url**:由上方 API Platform 选项决定(中国站 `api.kimi.com`;Global `api.kimi.ai`)\n- **Model Name**:可选;默认 `kimi-for-coding`\n- 还没有订阅?前往 [Kimi Code 站点]({api_key_url})了解套餐;模型列表见[模型文档]({model_docs_url})\n- 调用消耗 Kimi Code 订阅额度,与按量付费 API 余额相互独立。登录后访问令牌会自动续期",
+ "kimi_code.oauth.login": "使用 Kimi 登录",
+ "kimi_code.oauth.pending": "请在浏览器中打开授权页并确认本设备。授权码:",
+ "kimi_code.oauth.open_page": "打开 Kimi 授权页面",
+ "kimi_code.oauth.success": "Kimi 登录成功",
+ "kimi_code.oauth.authorized": "已使用 Kimi 登录(区域:{region}),调用将消耗你的 Kimi Code 订阅额度。",
+ "kimi_code.oauth.disconnect": "断开 Kimi 登录",
+ "kimi_code.oauth.expired": "授权码已过期,请重新发起登录以获取新的授权码。",
+ "kimi_code.oauth.denied": "授权请求已被拒绝。如果是误操作,请重新发起登录。",
+ "kimi_code.oauth.reauth": "按所选区域重新登录 Kimi",
+ "kimi_code.oauth.region_mismatch": "当前凭证属于「{authorized}」区域,但所选 API Platform 为「{selected}」。请求将按凭证区域「{authorized}」发出;如需切换区域,请重新登录。",
+ "kimi_code.oauth.network_error": "无法连接 Kimi 授权服务(网络错误)。请检查网络连接后重新发起登录。",
+ "kimi_code.oauth.poll_retry": "检查授权状态时网络异常,正在自动重试……"
}
-}
+}
\ No newline at end of file