Skip to content

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

fix(kimi): improve sign-in flow and state safety

harry07034204d0f39afa
diff --git a/app/models/llm_provider.py b/app/models/llm_provider.py
index 31e6ed18..2ade9e95 100644
--- a/app/models/llm_provider.py
+++ b/app/models/llm_provider.py
@@ -233,6 +233,42 @@ LLM_PROVIDER_REGISTRY = (
default_service_endpoint_id="china",
international_service_endpoint_id="global",
),
+ # 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(
"openai",
@@ -487,42 +523,6 @@ 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
index 50f0c01e..1b92b5fc 100644
--- a/app/services/kimi_code_oauth.py
+++ b/app/services/kimi_code_oauth.py
@@ -71,6 +71,15 @@ _EXPIRY_MARGIN_SECONDS = 60.0
# Kimi 会轮换 refresh token,同一个旧 token 只能成功续期一次。并发请求必须
# 串行续期,否则第二个线程会拿着已轮换的旧 token 得到 invalid_grant。
_refresh_lock = threading.Lock()
+# 网络请求不持有凭据锁;验证响应归属和写回必须在同一个临界区完成。
+_credentials_lock = threading.RLock()
+_authorization_generation = 0
+
+
+def authorization_generation() -> int:
+ """返回登录/断开版本,供在途授权响应检查是否仍属于当前账号状态。"""
+ with _credentials_lock:
+ return _authorization_generation
def _cfg(key, default=""):
@@ -239,78 +248,91 @@ def _refresh(region: str, refresh_token: str) -> dict:
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 store_token_bundle(
+ region: str,
+ payload: dict,
+ *,
+ expected_generation: int | None = None,
+ expected_refresh_token: str | None = None,
+) -> None:
+ """原子检查响应归属并保存凭据,避免旧响应恢复断开或覆盖新登录。"""
+ global _authorization_generation
+ access = payload["access_token"]
+ expires_at = time.time() + float(payload.get("expires_in") or 900)
+ with _credentials_lock:
+ if (
+ expected_generation is not None
+ and expected_generation != _authorization_generation
+ ) or (
+ expected_refresh_token is not None
+ and str(_cfg(_K_REFRESH, "")).strip() != expected_refresh_token
+ ):
+ raise ValueError(
+ "kimi_code: credentials changed while authorizing or refreshing; "
+ "please sign in again if needed."
+ )
+ _set(_K_REGION, region)
+ _set(_K_ACCESS, access)
+ if payload.get("refresh_token"):
+ _set(_K_REFRESH, payload["refresh_token"])
+ _set(_K_EXPIRES_AT, expires_at)
+ if expected_refresh_token is None:
+ _authorization_generation += 1
+ # 保存不等待视频任务的配置锁,队列中的凭据仍可立即读取。
+ 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()
+ global _authorization_generation
+ with _credentials_lock:
+ _authorization_generation += 1
+ 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())
+ with _credentials_lock:
+ return bool(
+ str(_cfg(_K_REFRESH, "")).strip() or str(_cfg(_K_ACCESS, "")).strip()
+ )
def authorized_region() -> str:
- return str(_cfg(_K_REGION, "") or "")
+ with _credentials_lock:
+ 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 续第二次。
+ """返回有效 token;串行续期,并拒绝在登录/断开之后返回的旧响应。"""
+ with _credentials_lock:
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")
+ with _refresh_lock:
+ # 排队期间可能已有请求续期,因此重新读取完整凭据状态。
+ with _credentials_lock:
+ 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")
+ generation = _authorization_generation
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)
+ store_token_bundle(
+ region,
+ payload,
+ expected_generation=generation,
+ expected_refresh_token=refresh,
+ )
return payload["access_token"]
diff --git a/test/services/test_kimi_login_review.py b/test/services/test_kimi_login_review.py
new file mode 100644
index 00000000..4f28cd5c
--- /dev/null
+++ b/test/services/test_kimi_login_review.py
@@ -0,0 +1,205 @@
+"""审查复现:旧的设备授权和刷新结果不得撤销另一个页面的断开操作。"""
+
+import threading
+import time
+from unittest.mock import patch
+
+import pytest
+from streamlit.testing.v1 import AppTest
+
+from app.config import config
+from app.services import kimi_code_oauth as oauth
+
+
+def isolated_credentials():
+ app_config = {
+ "kimi_code_region": "china",
+ "kimi_code_access_token": "review-expired",
+ "kimi_code_refresh_token": "review-refresh",
+ "kimi_code_token_expires_at": time.time() - 1,
+ }
+ with (
+ patch.object(config, "app", app_config),
+ patch.object(config, "try_save_config", return_value=True),
+ ):
+ yield app_config
+
+
+def _click_link(app, key):
+ link = next(item for item in app.get("link_button") if item.proto.id.endswith(key))
+ states = app._tree.get_widget_states()
+ states.widgets.add(id=link.proto.id, trigger_value=True)
+ return app._run(states)
+
+
[email protected]("replace", [False, True])
+def test_refresh_commit_respects_disconnect_or_new_login(isolated_credentials, replace):
+ """暂停真实写回入口,让另一线程断开/登录,再恢复旧刷新。"""
+ ready, release = threading.Event(), threading.Event()
+ original_store = oauth.store_token_bundle
+ errors = []
+
+ def delayed_store(region, payload, **kwargs):
+ ready.set()
+ assert release.wait(3)
+ return original_store(region, payload, **kwargs)
+
+ def worker():
+ try:
+ oauth.get_valid_access_token()
+ except Exception as error:
+ errors.append(error)
+
+ with (
+ patch.object(
+ oauth,
+ "_refresh",
+ return_value={
+ "access_token": "review-stale",
+ "refresh_token": "review-stale-refresh",
+ "expires_in": 900,
+ },
+ ),
+ patch.object(oauth, "store_token_bundle", side_effect=delayed_store),
+ ):
+ thread = threading.Thread(target=worker)
+ thread.start()
+ try:
+ assert ready.wait(3)
+ oauth.clear_credentials()
+ if replace:
+ original_store(
+ "global",
+ {
+ "access_token": "review-new-login",
+ "refresh_token": "review-new-refresh",
+ "expires_in": 900,
+ },
+ )
+ finally:
+ release.set()
+ thread.join(3)
+ assert not thread.is_alive()
+ assert isolated_credentials["kimi_code_access_token"] == (
+ "review-new-login" if replace else ""
+ )
+ assert len(errors) == 1 and isinstance(errors[0], ValueError)
+
+
[email protected]("replace", [False, True])
+def test_device_authorization_does_not_restore_or_replace_newer_login(
+ isolated_credentials, replace
+):
+ """真实 Streamlit 登录面板:轮询响应返回前另一个页面断开/重新登录。"""
+ from webui import kimi_login
+
+ new_payload = {
+ "access_token": "review-new-login",
+ "refresh_token": "review-new-refresh",
+ "expires_in": 900,
+ }
+
+ def response_after_account_change(region, code):
+ oauth.clear_credentials()
+ if replace:
+ oauth.store_token_bundle("china", new_payload)
+ return {
+ "access_token": "review-stale-device",
+ "refresh_token": "review-stale-device-refresh",
+ "expires_in": 900,
+ }
+
+ with (
+ patch.object(
+ oauth,
+ "request_device_code",
+ return_value={
+ "device_code": "review-device",
+ "user_code": "REVIEW-CODE",
+ "interval": 5,
+ "verification_uri_complete": "https://www.kimi.ai/code/authorize_device?user_code=REVIEW-CODE",
+ },
+ ),
+ patch.object(oauth, "poll_token", side_effect=response_after_account_change),
+ ):
+ app = AppTest.from_string(
+ "from webui.kimi_login import render_kimi_login\n"
+ 'render_kimi_login("global", lambda key: key)\n'
+ )
+ app.run()
+ _click_link(app, "kimi_code_reauth_button")
+ flow = dict(app.session_state[kimi_login.FLOW_KEY])
+ flow["next_poll_at"] = 0
+ app.session_state[kimi_login.FLOW_KEY] = flow
+ app.run()
+ assert not app.exception
+ assert isolated_credentials["kimi_code_access_token"] == (
+ "review-new-login" if replace else ""
+ )
+ assert kimi_login.FLOW_KEY not in app.session_state
+
+
+def test_idle_authorization_link_renews_before_expiry():
+ """控制时钟验证未点击链接会更新,但不会提前轮询 token。"""
+ from webui import kimi_login
+
+ now = time.time()
+
+ def issue(region):
+ n = issuer.call_count
+ return {
+ "device_code": f"device-{n}",
+ "user_code": f"TEST-{n}",
+ "verification_uri_complete": f"https://www.kimi.com/?user_code=TEST-{n}",
+ "interval": 2,
+ "expires_in": 8,
+ }
+
+ with (
+ patch.object(config, "app", {}),
+ patch.object(oauth, "request_device_code", side_effect=issue) as issuer,
+ patch.object(oauth, "poll_token") as poll,
+ patch.object(kimi_login.time, "time", return_value=now) as clock,
+ ):
+ app = AppTest.from_string(
+ 'from webui.kimi_login import render_kimi_login\nrender_kimi_login("china", lambda key: key)'
+ )
+ app.run()
+ assert issuer.call_count == 1
+ clock.return_value = now + 3
+ app.run()
+ assert issuer.call_count == 1
+ clock.return_value = now + 5
+ app.run()
+ assert issuer.call_count == 2
+ assert app.get("link_button")[0].proto.url.endswith("TEST-2")
+ assert not app.exception
+ poll.assert_not_called()
+
+
+def test_credentials_remain_nonblocking_with_video_config_lock(isolated_credentials):
+ """另一线程持有视频配置锁,登录/断开仍能完成并读到排队更新。"""
+ held, release = threading.Event(), threading.Event()
+
+ def hold_video_lock():
+ with config.runtime_config_lock():
+ held.set()
+ assert release.wait(5)
+
+ thread = threading.Thread(target=hold_video_lock)
+ thread.start()
+ try:
+ assert held.wait(3)
+ oauth.store_token_bundle(
+ "china",
+ {"access_token": "review-live", "refresh_token": "review-live-refresh"},
+ )
+ assert oauth.get_valid_access_token() == "review-live"
+ oauth.clear_credentials()
+ assert not oauth.is_authorized()
+ assert thread.is_alive()
+ finally:
+ release.set()
+ thread.join(3)
+ assert not thread.is_alive()
diff --git a/test/services/test_llm.py b/test/services/test_llm.py
index c0800a88..3a9e33b3 100644
--- a/test/services/test_llm.py
+++ b/test/services/test_llm.py
@@ -469,6 +469,7 @@ class TestLiteLLMProvider(unittest.TestCase):
[provider.provider_id for provider in LLM_PROVIDER_REGISTRY],
[
"moonshot",
+ "kimi_code",
"openai",
"anthropic",
"gemini",
@@ -497,7 +498,6 @@ class TestLiteLLMProvider(unittest.TestCase):
"opper",
"ollama",
"claude_code",
- "kimi_code",
"oneapi",
"litellm",
"groq",
diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.py
index 61a5a14a..c9525e9c 100644
--- a/test/services/test_webui_i18n.py
+++ b/test/services/test_webui_i18n.py
@@ -68,6 +68,7 @@ ENGLISH_FALLBACK_KEYS = frozenset(
"kimi_code.oauth.region_mismatch",
"kimi_code.oauth.network_error",
"kimi_code.oauth.poll_retry",
+ "kimi_code.oauth.changed",
"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 e6152ec3..0efa7de8 100644
--- a/test/services/test_webui_llm_settings.py
+++ b/test/services/test_webui_llm_settings.py
@@ -7,6 +7,7 @@ from streamlit.testing.v1 import AppTest
from app.config import config
from app.services import kimi_code_oauth
from app.services import llm
+from webui import kimi_login
ROOT_DIR = Path(__file__).parent.parent.parent
@@ -22,6 +23,22 @@ def _widget_by_key(elements, key):
)
+def _click_kimi_login_link(app, key="kimi_code_login_button"):
+ # AppTest 尚未提供 LinkButton.click;向真实 widget 发送与浏览器相同的
+ # trigger_value,不把生产 link_button 替换成普通按钮。
+ link = next(item for item in app.get("link_button") if item.proto.id.endswith(key))
+ states = app._tree.get_widget_states()
+ states.widgets.add(id=link.proto.id, trigger_value=True)
+ return app._run(states)
+
+
+def _make_kimi_poll_due(app):
+ flow = dict(app.session_state[kimi_login.FLOW_KEY])
+ flow["next_poll_at"] = 0
+ app.session_state[kimi_login.FLOW_KEY] = flow
+ return app.run()
+
+
def test_fluxionai_settings_defaults_and_connection_button():
"""真实运行 Streamlit 组件:检查默认值、配置覆盖及连接测试入口,不写用户配置。"""
app_config = dict(
@@ -35,7 +52,9 @@ def test_fluxionai_settings_defaults_and_connection_button():
patch.object(config, "app", app_config),
patch.object(config, "ui", dict(config.ui, language="zh")),
patch.object(config, "try_save_config", return_value=True),
- patch.object(llm, "test_connection", return_value=(True, "", 0.1)) as test_connection,
+ patch.object(
+ llm, "test_connection", return_value=(True, "", 0.1)
+ ) as test_connection,
):
app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
app.session_state["ui_language"] = "zh"
@@ -111,8 +130,14 @@ def test_kimi_platform_selection_keeps_endpoint_configuration_consistent():
assert global_base_url.disabled is True
assert app_config["moonshot_base_url"] == "https://api.moonshot.ai/v1"
global_tips = "\n".join(str(item.value) for item in app.info)
- assert "https://platform.kimi.ai?track_id=track-9e3b711aa2594e378f6fe5b8de718a76&aff=moneyprinterturbo" in global_tips
- assert "https://platform.kimi.ai/docs/models?track_id=track-9e3b711aa2594e378f6fe5b8de718a76&aff=moneyprinterturbo" in global_tips
+ assert (
+ "https://platform.kimi.ai?track_id=track-9e3b711aa2594e378f6fe5b8de718a76&aff=moneyprinterturbo"
+ in global_tips
+ )
+ assert (
+ "https://platform.kimi.ai/docs/models?track_id=track-9e3b711aa2594e378f6fe5b8de718a76&aff=moneyprinterturbo"
+ in global_tips
+ )
assert "offer ends December 31, 2026" in global_tips
endpoint_select.set_value("china").run()
@@ -125,8 +150,14 @@ def test_kimi_platform_selection_keeps_endpoint_configuration_consistent():
# 中国站是 Registry 的兼容默认值,不应重复写入用户配置。
assert app_config["moonshot_base_url"] == ""
china_tips = "\n".join(str(item.value) for item in app.info)
- assert "https://platform.kimi.com?track_id=track-6eec1e56a4494e52adcaebbcbbefce59&aff=moneyprinterturbo" in china_tips
- assert "https://platform.kimi.com/docs/models?track_id=track-6eec1e56a4494e52adcaebbcbbefce59&aff=moneyprinterturbo" in china_tips
+ assert (
+ "https://platform.kimi.com?track_id=track-6eec1e56a4494e52adcaebbcbbefce59&aff=moneyprinterturbo"
+ in china_tips
+ )
+ assert (
+ "https://platform.kimi.com/docs/models?track_id=track-6eec1e56a4494e52adcaebbcbbefce59&aff=moneyprinterturbo"
+ in china_tips
+ )
endpoint_select = _widget_by_key(
app.selectbox,
@@ -232,16 +263,17 @@ def test_ai_video_settings_prioritize_sponsors_and_own_shengsuan_key():
"loomloom_api_token_input",
)
assert settings_token.value == "initial-token"
- assert all(
- item.key != "loomloom_user_api_token" for item in app.text_input
- )
+ assert all(item.key != "loomloom_user_api_token" for item in app.text_input)
settings_token.set_value("settings-token").run()
assert app_config["loomloom_api_token"] == "settings-token"
- assert _widget_by_key(
- app.text_input,
- "loomloom_api_token_input",
- ).value == "settings-token"
+ assert (
+ _widget_by_key(
+ app.text_input,
+ "loomloom_api_token_input",
+ ).value
+ == "settings-token"
+ )
assert [str(item.value) for item in app.exception] == []
@@ -319,17 +351,22 @@ def test_kimi_code_poll_network_error_retries_then_offers_restart():
_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()
+ _click_kimi_login_link(app)
+ assert poll_mock.call_count == 0
+ for _ in range(5):
+ _make_kimi_poll_due(app)
- # AppTest 会跟随 st.rerun:整段自动重试在一次点击内完成。
- # 连续 5 次网络失败后流程结束,页面提示网络错误,登录按钮保留可重试。
+ # 每个计时 tick 只请求一次,连续失败后结束流程并显示新的登录链接。
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")
+ assert any(
+ item.proto.id.endswith("kimi_code_login_button")
+ for item in app.get("link_button")
+ )
def test_kimi_code_pending_then_success_completes_flow():
@@ -371,8 +408,146 @@ def test_kimi_code_pending_then_success_completes_flow():
_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()
+ _click_kimi_login_link(app)
+ _make_kimi_poll_due(app)
+ assert kimi_login.FLOW_KEY in app.session_state
+ store_mock.assert_not_called()
+ _make_kimi_poll_due(app)
assert not app.exception
- store_mock.assert_called_once_with("china", token_payload)
+ store_mock.assert_called_once_with(
+ "china",
+ token_payload,
+ expected_generation=kimi_code_oauth.authorization_generation(),
+ )
assert "kimi_code_oauth_flow" not in app.session_state
+
+
+def test_kimi_login_opens_selected_region_and_waits_until_clicked():
+ """按钮已携带正确站点链接;选择 Provider 不开始轮询或重复申请授权码。"""
+ app_config = {
+ key: value
+ for key, value in config.app.items()
+ if not key.startswith("kimi_code_")
+ }
+ app_config["llm_provider"] = "kimi_code"
+
+ def issue_code(region):
+ return {
+ "device_code": f"device-{region}",
+ "user_code": "TEST-CODE",
+ "verification_uri_complete": f"https://www.kimi.{'com' if region == 'china' else 'ai'}/code/authorize_device?user_code=TEST-CODE",
+ "interval": 5,
+ "expires_in": 600,
+ }
+
+ 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=issue_code
+ ) as issue,
+ patch.object(
+ kimi_code_oauth, "poll_token", return_value={"pending": True}
+ ) as poll,
+ ):
+ 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()
+ app.run()
+ assert issue.call_count == 1
+ poll.assert_not_called()
+ assert kimi_login.FLOW_KEY not in app.session_state
+ link = next(
+ item
+ for item in app.get("link_button")
+ if item.proto.id.endswith("kimi_code_login_button")
+ )
+ assert link.proto.type == "primary"
+ assert link.proto.ignore_rerun is False
+ assert link.proto.url.startswith("https://www.kimi.ai/")
+
+ _widget_by_key(app.selectbox, "kimi_code_service_endpoint_select").set_value(
+ "china"
+ ).run()
+ assert issue.call_count == 2
+ link = next(
+ item
+ for item in app.get("link_button")
+ if item.proto.id.endswith("kimi_code_login_button")
+ )
+ assert link.proto.url.startswith("https://www.kimi.com/")
+ _click_kimi_login_link(app)
+ poll.assert_not_called()
+ assert app.session_state[kimi_login.FLOW_KEY]["region"] == "china"
+
+
+def test_kimi_poll_slow_down_and_cancel_do_not_busy_loop():
+ """遵守服务端轮询间隔;取消后不会再用旧授权码请求 token。"""
+ app_config = {
+ key: value
+ for key, value in config.app.items()
+ if not key.startswith("kimi_code_")
+ }
+ app_config["llm_provider"] = "kimi_code"
+ payload = {
+ "device_code": "review-device",
+ "user_code": "TEST-CODE",
+ "verification_uri_complete": "https://www.kimi.com/code/authorize_device?user_code=TEST-CODE",
+ "interval": 5,
+ "expires_in": 600,
+ }
+ 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=payload),
+ patch.object(
+ kimi_code_oauth,
+ "poll_token",
+ return_value={"pending": True, "slow_down": True},
+ ) as poll,
+ ):
+ 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()
+ _click_kimi_login_link(app)
+ _make_kimi_poll_due(app)
+ assert poll.call_count == 1
+ assert app.session_state[kimi_login.FLOW_KEY]["interval"] == 10
+ app.run()
+ assert poll.call_count == 1
+ _widget_by_key(app.button, "kimi_code_cancel_login_button").click().run()
+ assert not app.exception
+ assert kimi_login.FLOW_KEY not in app.session_state
+ assert poll.call_count == 1
+
+
+def test_kimi_login_does_not_prepare_links_on_other_settings_tabs():
+ """打开素材设置时不申请无关的授权码。"""
+ app_config = {
+ key: value
+ for key, value in config.app.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("test"),
+ ) as issue,
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.session_state["settings_dialog_open"] = True
+ app.session_state["settings_dialog_target_tab"] = "material"
+ app.run()
+ assert not app.exception
+ issue.assert_not_called()
diff --git a/webui/Main.py b/webui/Main.py
index 05afef96..a563da0f 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -3587,151 +3587,15 @@ def _render_settings_dialog():
),
)
- if llm_provider == "kimi_code":
- # OAuth 设备授权:用户点一次按钮拿到授权链接和 code,在浏览器
- # 里确认后这里自动轮询换 token。授权状态保存在 config 中,
- # 后续脚本调用由服务层用 refresh token 自动续期。
+ if llm_provider == "kimi_code" and middle_config_panel.open:
from app.services import kimi_code_oauth
+ from webui.kimi_login import render_kimi_login
- 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
+ # 给嵌套 fragment 独立的容器,轮询重绘不占用后续控件的位置。
+ with llm_form_panel.container():
+ render_kimi_login(
+ kimi_code_oauth.resolve_region(st_llm_base_url), tr
)
- 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"),
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index 9c18385d..810e0d12 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -588,7 +588,7 @@
"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.pending": "Confirm sign-in on the Kimi authorization page. This panel will update automatically.",
"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.",
@@ -598,6 +598,7 @@
"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.changed": "Sign-in state changed in another page. This authorization has stopped; sign in again if needed.",
"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 ee8f8dcb..79a281e1 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -588,7 +588,7 @@
"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.pending": "请在 Kimi 授权页面确认登录,完成后这里会自动更新。",
"kimi_code.oauth.open_page": "打开 Kimi 授权页面",
"kimi_code.oauth.success": "Kimi 登录成功",
"kimi_code.oauth.authorized": "已使用 Kimi 登录(区域:{region}),调用将消耗你的 Kimi Code 订阅额度。",
@@ -598,6 +598,7 @@
"kimi_code.oauth.reauth": "按所选区域重新登录 Kimi",
"kimi_code.oauth.region_mismatch": "当前凭证属于「{authorized}」区域,但所选 API Platform 为「{selected}」。请求将按凭证区域「{authorized}」发出;如需切换区域,请重新登录。",
"kimi_code.oauth.network_error": "无法连接 Kimi 授权服务(网络错误)。请检查网络连接后重新发起登录。",
+ "kimi_code.oauth.changed": "登录状态已在其他页面变更,本次授权已停止。请按需重新登录。",
"kimi_code.oauth.poll_retry": "检查授权状态时网络异常,正在自动重试……"
}
-}
\ No newline at end of file
+}
diff --git a/webui/kimi_login.py b/webui/kimi_login.py
new file mode 100644
index 00000000..8b2cbd6d
--- /dev/null
+++ b/webui/kimi_login.py
@@ -0,0 +1,200 @@
+"""Kimi 登录界面:直接打开授权链接,并局部轮询授权状态。"""
+
+import time
+
+import requests
+import streamlit as st
+from loguru import logger
+
+from app.services import kimi_code_oauth
+
+FLOW_KEY = "kimi_code_oauth_flow"
+PREPARED_KEY = "kimi_code_oauth_prepared"
+MESSAGE_KEY = "kimi_code_oauth_message"
+
+
+def _prepare_link(region, tr):
+ prepared = st.session_state.get(PREPARED_KEY)
+ if prepared and prepared["region"] == region:
+ if prepared.get("error") or time.time() < prepared["refresh_at"]:
+ return prepared
+
+ # 链接在展示按钮前准备好,点击时由浏览器原生打开新标签页。
+ # 不用服务器的 webbrowser.open,也不依赖容易被拦截的异步弹窗。
+ try:
+ payload = kimi_code_oauth.request_device_code(region)
+ except requests.RequestException:
+ logger.warning("kimi_code: could not prepare the authorization link")
+ prepared = {"region": region, "error": tr("kimi_code.oauth.network_error")}
+ except ValueError as error:
+ prepared = {"region": region, "error": str(error)}
+ else:
+ now = time.time()
+ lifetime = float(payload.get("expires_in", 600))
+ prepared = {
+ "region": region,
+ "device_code": payload["device_code"],
+ "user_code": payload["user_code"],
+ "verification_uri_complete": payload["verification_uri_complete"],
+ "interval": max(int(payload.get("interval", 5)), 2),
+ "expires_at": now + lifetime,
+ "refresh_at": now + lifetime - min(10, lifetime / 2),
+ }
+ st.session_state[PREPARED_KEY] = prepared
+ return prepared
+
+
+def _begin_login(prepared):
+ st.session_state[FLOW_KEY] = dict(
+ prepared,
+ next_poll_at=time.time() + prepared["interval"],
+ generation=kimi_code_oauth.authorization_generation(),
+ )
+ st.session_state.pop(PREPARED_KEY, None)
+ st.session_state.pop(MESSAGE_KEY, None)
+
+
+def _finish_login(level, message):
+ st.session_state.pop(FLOW_KEY, None)
+ st.session_state.pop(PREPARED_KEY, None)
+ st.session_state[MESSAGE_KEY] = (level, message)
+
+
+def _poll_login(tr):
+ flow = st.session_state.get(FLOW_KEY)
+ if not flow:
+ return
+ if flow.get("generation") != kimi_code_oauth.authorization_generation():
+ _finish_login("warning", tr("kimi_code.oauth.changed"))
+ return
+ now = time.time()
+ if now >= flow["expires_at"]:
+ _finish_login("warning", tr("kimi_code.oauth.expired"))
+ return
+
+ if now >= flow["next_poll_at"]:
+ try:
+ payload = kimi_code_oauth.poll_token(flow["region"], flow["device_code"])
+ except requests.RequestException:
+ flow["network_errors"] = flow.get("network_errors", 0) + 1
+ logger.warning(
+ "kimi_code: authorization poll network error "
+ f"({flow['network_errors']}/5)"
+ )
+ if flow["network_errors"] >= 5:
+ _finish_login("error", tr("kimi_code.oauth.network_error"))
+ return
+ except ValueError as error:
+ _finish_login("error", str(error))
+ return
+ else:
+ flow["network_errors"] = 0
+ if payload.get("expired"):
+ _finish_login("warning", tr("kimi_code.oauth.expired"))
+ return
+ elif payload.get("denied"):
+ _finish_login("warning", tr("kimi_code.oauth.denied"))
+ return
+ elif payload.get("pending"):
+ if payload.get("slow_down"):
+ flow["interval"] += 5
+ else:
+ try:
+ kimi_code_oauth.store_token_bundle(
+ flow["region"], payload, expected_generation=flow["generation"]
+ )
+ except ValueError:
+ _finish_login("warning", tr("kimi_code.oauth.changed"))
+ else:
+ _finish_login("success", tr("kimi_code.oauth.success"))
+ return
+ # 以响应结束时间计算下一次请求,避免慢请求之后立即再轮询。
+ flow["next_poll_at"] = time.time() + flow["interval"]
+ st.session_state[FLOW_KEY] = flow
+
+
+def _cancel_login():
+ st.session_state.pop(FLOW_KEY, None)
+ st.session_state.pop(PREPARED_KEY, None)
+
+
+def _disconnect():
+ st.session_state.pop(FLOW_KEY, None)
+ st.session_state.pop(PREPARED_KEY, None)
+ st.session_state.pop(MESSAGE_KEY, None)
+ kimi_code_oauth.clear_credentials()
+
+
[email protected](run_every="1s")
+def render_kimi_login(region, tr):
+ """在设置弹窗中渲染登录;未点击登录前不请求 token。"""
+ flow = st.session_state.get(FLOW_KEY)
+ if flow and flow["region"] != region:
+ # 用户切换站点后停止旧站点的待授权流程,旧凭据仍按原区域使用。
+ st.session_state.pop(FLOW_KEY, None)
+ flow = None
+
+ if flow:
+ _poll_login(tr)
+ flow = st.session_state.get(FLOW_KEY)
+
+ message = st.session_state.get(MESSAGE_KEY)
+ if message:
+ level, text = message
+ getattr(st, level)(text)
+
+ authorized = kimi_code_oauth.is_authorized()
+ auth_region = kimi_code_oauth.authorized_region() or region
+ mismatch = authorized and auth_region != region
+ if authorized:
+ if mismatch:
+ st.warning(
+ tr("kimi_code.oauth.region_mismatch").format(
+ authorized=auth_region, selected=region
+ )
+ )
+ else:
+ st.success(tr("kimi_code.oauth.authorized").format(region=auth_region))
+ st.button(
+ tr("kimi_code.oauth.disconnect"),
+ key="kimi_code_disconnect_button",
+ on_click=_disconnect,
+ )
+
+ if flow:
+ if flow.get("network_errors"):
+ st.warning(tr("kimi_code.oauth.poll_retry"))
+ st.info(tr("kimi_code.oauth.pending"))
+ # 保留重新打开入口,与取消操作放在同一行。
+ with st.container(horizontal=True, gap="small"):
+ st.link_button(
+ tr("kimi_code.oauth.open_page"), flow["verification_uri_complete"]
+ )
+ st.button(
+ tr("Cancel"),
+ key="kimi_code_cancel_login_button",
+ on_click=_cancel_login,
+ )
+ elif not authorized or mismatch:
+ prepared = _prepare_link(region, tr)
+ label = tr("kimi_code.oauth.reauth" if mismatch else "kimi_code.oauth.login")
+ key = "kimi_code_reauth_button" if mismatch else "kimi_code_login_button"
+ if prepared.get("error"):
+ st.error(prepared["error"])
+ st.button(
+ label,
+ key=key,
+ type="primary",
+ icon=":material/login:",
+ on_click=lambda: st.session_state.pop(PREPARED_KEY, None),
+ )
+ else:
+ st.link_button(
+ label,
+ prepared["verification_uri_complete"],
+ key=key,
+ type="primary",
+ icon=":material/login:",
+ on_click=_begin_login,
+ args=(prepared,),
+ )