Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(qq): clarify QR binding states and setup actions (#6340)
chengyongru130f4edefebd
diff --git a/docs/guides/qq-ai-agent.md b/docs/guides/qq-ai-agent.mdindex b2cb1c3a4..f08ee136a 100644--- a/docs/guides/qq-ai-agent.md+++ b/docs/guides/qq-ai-agent.md@@ -24,7 +24,9 @@ For terminal or server setup, use the manual configuration section below. Reuse## Enable the QQ channel-In **Channels → QQ**, scan the QR code with mobile QQ. nanobot saves the AppID and Secret automatically, enables the channel, and follows any installation or restart prompt. To use credentials you already copied, open **Advanced** and enter them manually. Scanning again replaces the current App Secret, and the previous secret stops working once the new scan completes.+In **Channels → QQ**, scan the QR code with mobile QQ. nanobot saves the AppID and Secret automatically, enables the channel, and follows any installation or restart prompt.++Choose **Enter credentials manually** to use existing credentials. **Rebind bot** may interrupt other apps using this QQ bot. If the App Secret is reset, the old secret becomes invalid and those apps need the new secret.<details><summary>Manual configuration</summary>diff --git a/nanobot/channels/qq/connect.py b/nanobot/channels/qq/connect.pyindex b9bd81c76..9daf42bf1 100644--- a/nanobot/channels/qq/connect.py+++ b/nanobot/channels/qq/connect.py@@ -126,14 +126,7 @@ class QQConnectStore:except Exception as exc:raise ChannelConnectError(f"Unable to start QQ QR login: {exc}", status=502) from excsession = self._new_session(task_id, key)- return {- "session_id": session.id,- "status": "pending",- "qr_url": CONNECT_URL.format(task_id=quote(task_id)),- "interval_ms": POLL_INTERVAL_MS,- "expires_at_ms": int((session.created_wall + SESSION_TTL_SECONDS) * 1000),- "message": "Scan with mobile QQ to connect.",- }+ return _pending(session, "Scan with mobile QQ to connect.")async def poll(self, session_id: str) -> dict[str, Any]:self._cleanup()@@ -145,7 +138,7 @@ class QQConnectStore:result = await poll_bind_task(session.task_id)except Exception:# A transient portal error is not proof the scan failed; keep waiting.- return _pending(session, "Waiting for QQ scan...")+ return _pending(session, "Waiting for QQ scan...", retrying=True)self._cleanup()if self._sessions.get(session_id) is not session:@@ -176,11 +169,7 @@ class QQConnectStore:commit.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)await asyncio.shield(commit)session.credentials = (app_id, secret)- return {- "session_id": session_id,- "status": "succeeded",- "message": "QQ is connected.",- }+ return _payload(session_id, "succeeded", "QQ is connected.")async def cancel(self, session_id: str) -> dict[str, Any]:self._sessions.pop(session_id, None)@@ -234,10 +223,10 @@ def _print_qr(url: str) -> None:def _payload(session_id: str, status: str, message: str) -> dict[str, Any]:- return {"session_id": session_id, "status": status, "message": message}+ return {"session_id": session_id, "status": status, "message": message, "retrying": False}-def _pending(session: QQConnectSession, message: str) -> dict[str, Any]:+def _pending(session: QQConnectSession, message: str, *, retrying: bool = False) -> dict[str, Any]:return {"session_id": session.id,"status": "pending",@@ -245,6 +234,7 @@ def _pending(session: QQConnectSession, message: str) -> dict[str, Any]:"interval_ms": POLL_INTERVAL_MS,"expires_at_ms": int((session.created_wall + SESSION_TTL_SECONDS) * 1000),"message": message,+ "retrying": retrying,}diff --git a/nanobot/channels/qq/tests/test_connect.py b/nanobot/channels/qq/tests/test_connect.pyindex 8e2133a17..21e1ae226 100644--- a/nanobot/channels/qq/tests/test_connect.py+++ b/nanobot/channels/qq/tests/test_connect.py@@ -47,16 +47,19 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pytestarted = await store.start()assert started["status"] == "pending"+ assert started["retrying"] is Falseassert started["qr_url"].endswith("task_id=task-1&_wv=2")assert store.has_pending_workpolled = await store.poll(started["session_id"])assert polled["status"] == "succeeded"assert not store.has_pending_work+ assert polled["retrying"] is Falseassert await store.poll(started["session_id"]) == {"session_id": started["session_id"],"status": "expired","message": "This QQ login has expired. Start again.",+ "retrying": False,}saved = json.loads(_isolated_config.read_text(encoding="utf-8"))@@ -178,19 +181,40 @@ async def test_qq_close_during_start_does_not_leave_a_new_session(monkeypatch: p@pytest.mark.asyncio-async def test_qq_connect_keeps_waiting_on_transient_portal_errors(monkeypatch: pytest.MonkeyPatch):+async def test_qq_connect_clears_retrying_after_portal_recovers(monkeypatch: pytest.MonkeyPatch):async def fake_create() -> tuple[str, str]:return "task-2", base64.b64encode(b"k" * 32).decode()- async def fake_poll(_task_id: str) -> dict[str, Any]:- raise RuntimeError("portal hiccup")+ poll_count = 0++ async def fake_poll(task_id: str) -> dict[str, Any]:+ nonlocal poll_count+ assert task_id == "task-2"+ poll_count += 1+ if poll_count == 1:+ raise RuntimeError("portal hiccup")+ return {"status": 0}monkeypatch.setattr(connect, "create_bind_task", fake_create)monkeypatch.setattr(connect, "poll_bind_task", fake_poll)store = QQConnectStore()started = await store.start()- assert (await store.poll(started["session_id"]))["status"] == "pending"+ assert started["retrying"] is False++ retrying = await store.poll(started["session_id"])+ assert retrying["status"] == "pending"+ assert retrying["retrying"] is True+ assert retrying["qr_url"] == started["qr_url"]++ waiting = await store.poll(started["session_id"])+ assert waiting["status"] == "pending"+ assert waiting["retrying"] is False+ assert waiting["qr_url"] == started["qr_url"]++ cancelled = await store.cancel(started["session_id"])+ assert cancelled["status"] == "cancelled"+ assert cancelled["retrying"] is False@pytest.mark.asynciodiff --git a/nanobot/channels/qq/webui/QQConnectFlow.tsx b/nanobot/channels/qq/webui/QQConnectFlow.tsxindex 65eef910e..f00d37999 100644--- a/nanobot/channels/qq/webui/QQConnectFlow.tsx+++ b/nanobot/channels/qq/webui/QQConnectFlow.tsx@@ -1,27 +1,38 @@+import { useTranslation } from "react-i18next";+import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";+import { channelStatusLabel } from "@/components/settings/channels/ChannelIdentity";import { QQConnectFlowView, useQQConnectLabels } from "./QQConnectFlowView";export function QQConnectFlow({token,feature,- idleLabel,connectRequestId,+ onOpenAdvanced,onFeaturesUpdate,}: ChannelPluginConnectFlowProps) {+ const { t } = useTranslation();const labels = useQQConnectLabels();+ const runtimeLabel = feature.runtime_status === "stopped"+ ? t("settings.channels.runtimeStopped", { defaultValue: "Not running" })+ : channelStatusLabel(feature, (key, fallback) => t(key, { defaultValue: fallback }));return (<ChannelQrConnectFlowtoken={token}channelName="qq"- idleLabel={idleLabel}connectRequestId={connectRequestId}autoStart={!feature.configured}forceOnRepeatlabels={labels}onFeaturesUpdate={onFeaturesUpdate}- renderView={(props) => <QQConnectFlowView {...props} configured={feature.configured} />}+ renderView={(props) => <QQConnectFlowView {...props}+ configured={feature.configured}+ appId={feature.config_values?.["channels.qq.appId"]}+ runtimeStatus={feature.runtime_status}+ runtimeLabel={feature.runtime_status ? runtimeLabel : undefined}+ onManualSetup={onOpenAdvanced} />}/>);}diff --git a/nanobot/channels/qq/webui/QQConnectFlowView.tsx b/nanobot/channels/qq/webui/QQConnectFlowView.tsxindex 9277b260d..3d2da32b9 100644--- a/nanobot/channels/qq/webui/QQConnectFlowView.tsx+++ b/nanobot/channels/qq/webui/QQConnectFlowView.tsx@@ -1,43 +1,132 @@+import { useRef, useState } from "react";+import { Check } from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";+import { ChannelStatusBadge } from "@/components/settings/channels/ChannelIdentity";import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import type { ChannelRuntimeStatus } from "@/lib/types";export type QQConnectFlowViewProps = Omit<ChannelQrConnectFlowViewProps, "labels"> & {configured?: boolean;+ appId?: string;+ runtimeStatus?: ChannelRuntimeStatus;+ runtimeLabel?: string;+ onManualSetup?: () => void;};export function useQQConnectLabels(): ChannelQrConnectLabels {const { t } = useTranslation();const tx = channelTranslator(t, "qq");return {- qrAlt: tx("custom.qrAlt", "QQ login QR code"),+ qrAlt: tx("custom.qrAlt", "QQ binding QR code"),scanTitle: tx("custom.scanTitle", "Scan with mobile QQ"),scanDescription: "",- waiting: tx("custom.waiting", "Waiting for QQ scan..."),- connected: tx("custom.connected", "QQ is connected."),- stopped: tx("custom.stopped", "QQ login stopped."),- connecting: tx("custom.connecting", "Connecting..."),- scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),- connect: t("settings.channels.connect", { defaultValue: "Connect" }),+ waiting: tx("custom.waiting", "Waiting for scan…"),+ connected: tx("custom.connected", "Binding complete"),+ stopped: tx("custom.stopped", "Cancelled"),+ connecting: tx("custom.connecting", "Preparing QR code…"),+ scanAgain: tx("custom.rebind", "Rebind bot"),+ connect: tx("custom.bind", "Bind QQ bot"),};}-export function QQConnectFlowView({ configured, ...props }: QQConnectFlowViewProps) {+export function QQConnectFlowView({+ configured, appId, runtimeStatus, runtimeLabel, onManualSetup, ...props+}: QQConnectFlowViewProps) {const { t } = useTranslation();const tx = channelTranslator(t, "qq");const labels = useQQConnectLabels();- const rescanWarning = configured ? tx("custom.scanAgainWarning", "") : "";- return <ChannelQrConnectFlowView {...props} labels={labels}- renderActions={(connectButton) => (- <div className="flex flex-wrap items-center justify-end gap-2">- {rescanWarning ? (- <p className="max-w-[22rem] text-[11.5px] leading-5 text-muted-foreground">- {rescanWarning}+ const [rebindOpen, setRebindOpen] = useState(false);+ const rebindTrigger = useRef<HTMLElement | null>(null);+ const pending = props.connect?.status === "pending";+ const pollFailed = pending && props.errorAction === "poll" && Boolean(props.error);+ const retrying = props.connect?.retrying || pollFailed;+ const needsRetry = props.connect?.status === "failed" || Boolean(props.error);+ const idleLabel = needsRetry ? tx("custom.retry", "Retry")+ : props.connect?.status === "expired" ? tx("custom.refresh", "Refresh QR code")+ : configured ? labels.scanAgain : labels.connect;+ const manualSetup = onManualSetup ? (+ <Button type="button" size="sm" variant="link" className="px-0"+ disabled={props.busy} onClick={onManualSetup}>+ {tx("custom.manualSetup", "Enter credentials manually")}+ </Button>+ ) : null;++ return <div className="space-y-3">+ {configured ? (+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0 space-y-1">+ <p className="flex items-center gap-2 text-ui-heading">+ <Check className="h-4 w-4 text-emerald-700 dark:text-emerald-200" aria-hidden />+ {tx("custom.configured", "Configured")}</p>- ) : null}- {connectButton}+ {appId ? <p className="break-all text-caption text-muted-foreground">+ {tx("setup.fields.appId.label", "App ID")}: <code>{appId}</code>+ </p> : null}+ </div>+ {runtimeLabel ? <ChannelStatusBadge status={runtimeStatus}>{runtimeLabel}</ChannelStatusBadge> : null}</div>- )}- />;+ ) : null}+ <ChannelQrConnectFlowView {...props}+ onStart={() => {+ if (configured) {+ rebindTrigger.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ setRebindOpen(true);+ } else {+ props.onStart();+ }+ }}+ labels={{ ...labels, waiting: retrying+ ? tx("custom.retrying", "Retrying…") : labels.waiting }}+ idleLabel={idleLabel}+ error={pollFailed || !props.error ? null : props.errorAction === "cancel"+ ? tx("custom.cancelFailed", "Could not cancel") : tx("custom.failed", "Binding failed")}+ suppressSucceeded={configured}+ resolveMessage={(payload) => {+ switch (payload.status) {+ case "succeeded": return labels.connected;+ case "cancelled": return labels.stopped;+ case "expired": return tx("custom.expired", "QR code expired");+ case "failed": return tx("custom.failed", "Binding failed");+ default: return labels.waiting;+ }+ }}+ renderActions={(connectButton) => (+ <div className="flex flex-wrap items-center justify-between gap-2">+ {manualSetup}+ <div className="ms-auto">{connectButton}</div>+ </div>+ )}+ />+ {pending || (props.autoStart && props.busy && !props.connect) ? manualSetup : null}+ <AlertDialog open={rebindOpen} onOpenChange={setRebindOpen}>+ <AlertDialogContent onCloseAutoFocus={(event) => {+ event.preventDefault();+ rebindTrigger.current?.focus();+ }}>+ <AlertDialogHeader>+ <AlertDialogTitle>{labels.scanAgain}</AlertDialogTitle>+ <AlertDialogDescription>+ {tx("custom.scanAgainWarning", "Rebinding may interrupt other apps using this QQ bot. If the App Secret is reset, the old secret becomes invalid and those apps need the new secret.")}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("settings.actions.cancel", { defaultValue: "Cancel" })}</AlertDialogCancel>+ <AlertDialogAction onClick={props.onStart}>{labels.scanAgain}</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>;}diff --git a/nanobot/channels/qq/webui/index.tsx b/nanobot/channels/qq/webui/index.tsxindex 41ccc1f83..8e221a16e 100644--- a/nanobot/channels/qq/webui/index.tsx+++ b/nanobot/channels/qq/webui/index.tsx@@ -27,9 +27,9 @@ export default {{ key: "channels.qq.msgFormat", section: "behavior" },{ key: "channels.qq.ackMessage", section: "behavior" },{ key: "channels.qq.showCompactionNotices", section: "behavior" },- { key: "channels.qq.mediaDir", section: "behavior" },- { key: "channels.qq.downloadChunkSize", section: "behavior" },- { key: "channels.qq.downloadMaxBytes", section: "behavior" },+ { key: "channels.qq.mediaDir", section: "advanced" },+ { key: "channels.qq.downloadChunkSize", section: "advanced" },+ { key: "channels.qq.downloadMaxBytes", section: "advanced" },],},},diff --git a/nanobot/channels/qq/webui/locales/en.json b/nanobot/channels/qq/webui/locales/en.jsonindex f41d570ce..0eecf831a 100644--- a/nanobot/channels/qq/webui/locales/en.json+++ b/nanobot/channels/qq/webui/locales/en.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "Open QQ setup","officialLabel": "Open QQ bot console",+ "sections": {+ "credentials": "Manual credentials",+ "advanced": "Advanced"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "qrAlt": "QQ login QR code",+ "qrAlt": "QQ binding QR code","scanTitle": "Scan with mobile QQ",- "waiting": "Waiting for QQ scan…",- "connected": "QQ is connected.",- "stopped": "QQ login stopped.",- "connecting": "Connecting...",- "scanAgainWarning": "Scanning again replaces the current App Secret. The previous App Secret stops working once the new scan completes."+ "waiting": "Waiting for scan…",+ "connected": "Binding complete",+ "stopped": "Cancelled",+ "connecting": "Preparing QR code…",+ "scanAgainWarning": "Rebinding may interrupt other apps using this QQ bot. If the App Secret is reset, the old secret becomes invalid and those apps need the new secret.",+ "configured": "Configured",+ "bind": "Bind QQ bot",+ "rebind": "Rebind bot",+ "refresh": "Refresh QR code",+ "retry": "Retry",+ "expired": "QR code expired",+ "failed": "Binding failed",+ "cancelFailed": "Could not cancel",+ "retrying": "Retrying…",+ "manualSetup": "Enter credentials manually"}}diff --git a/nanobot/channels/qq/webui/locales/es.json b/nanobot/channels/qq/webui/locales/es.jsonindex 61e076dcd..84bbb3b9c 100644--- a/nanobot/channels/qq/webui/locales/es.json+++ b/nanobot/channels/qq/webui/locales/es.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "Abrir guía de QQ","officialLabel": "Abrir consola del bot de QQ",+ "sections": {+ "credentials": "Credenciales manuales",+ "advanced": "Avanzado"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "Escanea con QQ móvil",- "waiting": "Esperando el escaneo de QQ…",- "connected": "QQ está conectado.",- "stopped": "El inicio de sesión de QQ se detuvo.",- "connecting": "Conectando…",- "qrAlt": "Código QR de inicio de sesión de QQ",- "scanAgainWarning": "Escanear de nuevo reemplaza el App Secret actual. El App Secret anterior deja de funcionar cuando termina el nuevo escaneo."+ "scanTitle": "Escanea con QQ en el móvil",+ "waiting": "Esperando escaneo…",+ "connected": "Vinculación completada",+ "stopped": "Cancelado",+ "connecting": "Preparando código QR…",+ "qrAlt": "Código QR para vincular QQ",+ "scanAgainWarning": "Volver a vincular este bot de QQ puede interrumpir otras aplicaciones que lo usan. Si se restablece su App Secret, el secreto anterior deja de ser válido y esas aplicaciones necesitan el nuevo.",+ "configured": "Configurado",+ "bind": "Vincular bot de QQ",+ "rebind": "Volver a vincular el bot",+ "refresh": "Actualizar código QR",+ "retry": "Reintentar",+ "expired": "Código QR caducado",+ "failed": "Vinculación fallida",+ "cancelFailed": "No se pudo cancelar",+ "retrying": "Reintentando…",+ "manualSetup": "Introducir credenciales manualmente"}}diff --git a/nanobot/channels/qq/webui/locales/fr.json b/nanobot/channels/qq/webui/locales/fr.jsonindex 0e68ece8c..9ee51da2b 100644--- a/nanobot/channels/qq/webui/locales/fr.json+++ b/nanobot/channels/qq/webui/locales/fr.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "Ouvrir le guide QQ","officialLabel": "Ouvrir la console du bot QQ",+ "sections": {+ "credentials": "Identifiants (saisie manuelle)",+ "advanced": "Avancé"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "Scannez avec QQ mobile",- "waiting": "En attente du scan QQ…",- "connected": "QQ est connecté.",- "stopped": "La connexion QQ s'est arrêtée.",- "connecting": "Connexion…",- "qrAlt": "QR code de connexion QQ",- "scanAgainWarning": "Un nouveau scan remplace l'App Secret actuel. L'ancien App Secret cesse de fonctionner dès la fin du nouveau scan."+ "scanTitle": "Scannez avec QQ sur mobile",+ "waiting": "En attente du scan…",+ "connected": "Association terminée",+ "stopped": "Annulé",+ "connecting": "Préparation du QR code…",+ "qrAlt": "QR code d'association QQ",+ "scanAgainWarning": "Une nouvelle association peut interrompre les autres applications utilisant ce bot QQ. Si son App Secret est réinitialisé, l’ancien secret devient invalide et ces applications doivent utiliser le nouveau.",+ "configured": "Configuré",+ "bind": "Associer le bot QQ",+ "rebind": "Réassocier le bot",+ "refresh": "Actualiser le QR code",+ "retry": "Réessayer",+ "expired": "QR code expiré",+ "failed": "Échec de l'association",+ "cancelFailed": "Annulation impossible",+ "retrying": "Nouvelle tentative…",+ "manualSetup": "Saisir les identifiants manuellement"}}diff --git a/nanobot/channels/qq/webui/locales/id.json b/nanobot/channels/qq/webui/locales/id.jsonindex 359a84db1..f1d988686 100644--- a/nanobot/channels/qq/webui/locales/id.json+++ b/nanobot/channels/qq/webui/locales/id.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "Buka panduan QQ","officialLabel": "Buka konsol bot QQ",+ "sections": {+ "credentials": "Kredensial manual",+ "advanced": "Lanjutan"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "Pindai dengan QQ seluler",- "waiting": "Menunggu pindaian QQ…",- "connected": "QQ terhubung.",- "stopped": "Login QQ dihentikan.",- "connecting": "Menghubungkan…",- "qrAlt": "Kode QR login QQ",- "scanAgainWarning": "Memindai ulang menggantikan App Secret saat ini. App Secret lama tidak lagi berfungsi setelah pemindaian baru selesai."+ "scanTitle": "Pindai dengan QQ di ponsel",+ "waiting": "Menunggu pemindaian…",+ "connected": "Penautan selesai",+ "stopped": "Dibatalkan",+ "connecting": "Menyiapkan kode QR…",+ "qrAlt": "Kode QR penautan QQ",+ "scanAgainWarning": "Menautkan ulang dapat mengganggu aplikasi lain yang menggunakan bot QQ ini. Jika App Secret direset, kunci lama menjadi tidak berlaku dan aplikasi tersebut perlu menggunakan kunci baru.",+ "configured": "Terkonfigurasi",+ "bind": "Tautkan bot QQ",+ "rebind": "Tautkan ulang bot",+ "refresh": "Perbarui kode QR",+ "retry": "Coba lagi",+ "expired": "Kode QR kedaluwarsa",+ "failed": "Penautan gagal",+ "cancelFailed": "Pembatalan gagal",+ "retrying": "Mencoba lagi…",+ "manualSetup": "Masukkan kredensial secara manual"}}diff --git a/nanobot/channels/qq/webui/locales/ja.json b/nanobot/channels/qq/webui/locales/ja.jsonindex 675b0ba95..225856ac3 100644--- a/nanobot/channels/qq/webui/locales/ja.json+++ b/nanobot/channels/qq/webui/locales/ja.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "QQ 設定ガイドを開く","officialLabel": "QQ ボットコンソールを開く",+ "sections": {+ "credentials": "手動入力の認証情報",+ "advanced": "詳細設定"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "モバイル QQ でスキャン",- "waiting": "QQ のスキャンを待っています…",- "connected": "QQ に接続しました。",- "stopped": "QQ ログインを停止しました。",- "connecting": "接続中…",- "qrAlt": "QQ ログイン QR コード",- "scanAgainWarning": "再スキャンすると現在の App Secret が置き換わります。新しいスキャンが完了すると、以前の App Secret は無効になります。"+ "scanTitle": "スマートフォンの QQ でスキャン",+ "waiting": "スキャン待ち…",+ "connected": "連携完了",+ "stopped": "キャンセル済み",+ "connecting": "QR コードを準備中…",+ "qrAlt": "QQ 連携用 QR コード",+ "scanAgainWarning": "再連携すると、この QQ ボットを利用する他のアプリの接続が切れる可能性があります。App Secret がリセットされた場合、古いシークレットは無効になり、他のアプリでも新しいシークレットへの更新が必要です。",+ "configured": "設定済み",+ "bind": "QQ ボットと連携",+ "rebind": "ボットと再連携",+ "refresh": "QR コードを更新",+ "retry": "再試行",+ "expired": "QR コードの有効期限切れ",+ "failed": "連携失敗",+ "cancelFailed": "キャンセルできませんでした",+ "retrying": "再試行中…",+ "manualSetup": "認証情報を手動で入力"}}diff --git a/nanobot/channels/qq/webui/locales/ko.json b/nanobot/channels/qq/webui/locales/ko.jsonindex fa5585761..38d8304fb 100644--- a/nanobot/channels/qq/webui/locales/ko.json+++ b/nanobot/channels/qq/webui/locales/ko.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "QQ 설정 가이드 열기","officialLabel": "QQ 봇 콘솔 열기",+ "sections": {+ "credentials": "수동 인증 정보",+ "advanced": "고급"+ },"fields": {"appId": {"label": "App ID",@@ -45,11 +49,21 @@},"custom": {"scanTitle": "모바일 QQ로 스캔",- "waiting": "QQ 스캔을 기다리는 중…",- "connected": "QQ가 연결되었습니다.",- "stopped": "QQ 로그인이 중지되었습니다.",- "connecting": "연결 중…",- "qrAlt": "QQ 로그인 QR 코드",- "scanAgainWarning": "다시 스캔하면 현재 App Secret이 교체됩니다. 새 스캔이 완료되면 이전 App Secret은 더 이상 작동하지 않습니다."+ "waiting": "스캔 대기 중…",+ "connected": "연동 완료",+ "stopped": "취소됨",+ "connecting": "QR 코드 준비 중…",+ "qrAlt": "QQ 연동 QR 코드",+ "scanAgainWarning": "재연동하면 이 QQ 봇을 사용하는 다른 앱의 연결이 끊길 수 있습니다. App Secret이 재설정되면 기존 시크릿이 무효화되므로 다른 앱도 새 시크릿으로 업데이트해야 합니다.",+ "configured": "구성됨",+ "bind": "QQ 봇 연동",+ "rebind": "봇 다시 연동",+ "refresh": "QR 코드 새로고침",+ "retry": "재시도",+ "expired": "QR 코드 만료",+ "failed": "연동 실패",+ "cancelFailed": "취소하지 못함",+ "retrying": "재시도 중…",+ "manualSetup": "인증 정보 수동 입력"}}diff --git a/nanobot/channels/qq/webui/locales/pt-BR.json b/nanobot/channels/qq/webui/locales/pt-BR.jsonindex a10ffaf4a..f66ce1334 100644--- a/nanobot/channels/qq/webui/locales/pt-BR.json+++ b/nanobot/channels/qq/webui/locales/pt-BR.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "Abrir guia do QQ","officialLabel": "Abrir console do bot QQ",+ "sections": {+ "credentials": "Credenciais manuais",+ "advanced": "Avançado"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "Escaneie com o QQ móvel",- "waiting": "Aguardando leitura do QQ…",- "connected": "QQ está conectado.",- "stopped": "O login do QQ foi interrompido.",- "connecting": "Conectando…",- "qrAlt": "QR code de login do QQ",- "scanAgainWarning": "Escanear novamente substitui o App Secret atual. O App Secret anterior deixa de funcionar quando a nova leitura termina."+ "scanTitle": "Escaneie com o QQ no celular",+ "waiting": "Aguardando leitura…",+ "connected": "Vinculação concluída",+ "stopped": "Cancelado",+ "connecting": "Preparando QR code…",+ "qrAlt": "QR code de vinculação do QQ",+ "scanAgainWarning": "Vincular este bot do QQ novamente pode interromper outros aplicativos que o utilizam. Se o App Secret for redefinido, o segredo antigo será invalidado e esses aplicativos precisarão do novo.",+ "configured": "Configurado",+ "bind": "Vincular bot QQ",+ "rebind": "Vincular bot novamente",+ "refresh": "Atualizar QR code",+ "retry": "Tentar novamente",+ "expired": "QR code expirado",+ "failed": "Falha na vinculação",+ "cancelFailed": "Não foi possível cancelar",+ "retrying": "Tentando novamente…",+ "manualSetup": "Inserir credenciais manualmente"}}diff --git a/nanobot/channels/qq/webui/locales/vi.json b/nanobot/channels/qq/webui/locales/vi.jsonindex ddd964583..88299ebd3 100644--- a/nanobot/channels/qq/webui/locales/vi.json+++ b/nanobot/channels/qq/webui/locales/vi.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "Mở hướng dẫn QQ","officialLabel": "Mở bảng điều khiển bot QQ",+ "sections": {+ "credentials": "Thông tin xác thực nhập thủ công",+ "advanced": "Nâng cao"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "Quét bằng QQ di động",- "waiting": "Đang chờ quét QQ…",- "connected": "QQ đã được kết nối.",- "stopped": "Đăng nhập QQ đã dừng.",- "connecting": "Đang kết nối…",- "qrAlt": "Mã QR đăng nhập QQ",- "scanAgainWarning": "Quét lại sẽ thay thế App Secret hiện tại. App Secret cũ sẽ ngừng hoạt động khi lần quét mới hoàn tất."+ "scanTitle": "Quét bằng QQ trên điện thoại",+ "waiting": "Đang chờ quét mã…",+ "connected": "Liên kết hoàn tất",+ "stopped": "Đã hủy",+ "connecting": "Đang chuẩn bị mã QR…",+ "qrAlt": "Mã QR liên kết QQ",+ "scanAgainWarning": "Liên kết lại có thể làm gián đoạn các ứng dụng khác đang dùng bot QQ này. Nếu App Secret được đặt lại, khóa cũ sẽ mất hiệu lực và các ứng dụng đó cần cập nhật khóa mới.",+ "configured": "Đã cấu hình",+ "bind": "Liên kết bot QQ",+ "rebind": "Liên kết lại bot",+ "refresh": "Làm mới mã QR",+ "retry": "Thử lại",+ "expired": "Mã QR đã hết hạn",+ "failed": "Liên kết thất bại",+ "cancelFailed": "Không thể hủy",+ "retrying": "Đang thử lại…",+ "manualSetup": "Nhập thông tin xác thực thủ công"}}diff --git a/nanobot/channels/qq/webui/locales/zh-CN.json b/nanobot/channels/qq/webui/locales/zh-CN.jsonindex 632ef5ca1..99913cfb5 100644--- a/nanobot/channels/qq/webui/locales/zh-CN.json+++ b/nanobot/channels/qq/webui/locales/zh-CN.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "打开 QQ 配置指南","officialLabel": "打开 QQ 机器人后台",+ "sections": {+ "credentials": "手动凭据",+ "advanced": "高级"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "用手机 QQ 扫码登录",- "waiting": "等待 QQ 扫码…",- "connected": "QQ 已连接。",- "stopped": "QQ 登录已停止。",- "connecting": "连接中…",- "qrAlt": "QQ 登录二维码",- "scanAgainWarning": "重新扫码会替换当前的 App Secret,新扫码完成后旧 Secret 将失效。"+ "scanTitle": "用手机 QQ 扫码绑定",+ "waiting": "等待扫码…",+ "connected": "绑定成功",+ "stopped": "已取消",+ "connecting": "生成中…",+ "qrAlt": "QQ 绑定二维码",+ "scanAgainWarning": "重新绑定可能中断其他软件与此 QQ 机器人的连接。若 App Secret 被重置,旧密钥将失效,使用旧密钥的软件也需更新密钥。",+ "configured": "已配置",+ "bind": "绑定机器人",+ "rebind": "重新绑定",+ "refresh": "刷新二维码",+ "retry": "重试",+ "expired": "二维码已过期",+ "failed": "绑定失败",+ "cancelFailed": "取消失败",+ "retrying": "正在重试…",+ "manualSetup": "手动配置"}}diff --git a/nanobot/channels/qq/webui/locales/zh-TW.json b/nanobot/channels/qq/webui/locales/zh-TW.jsonindex 0ba912520..24c792789 100644--- a/nanobot/channels/qq/webui/locales/zh-TW.json+++ b/nanobot/channels/qq/webui/locales/zh-TW.json@@ -2,6 +2,10 @@"setup": {"docsLabel": "開啟 QQ 設定指南","officialLabel": "開啟 QQ 機器人後台",+ "sections": {+ "credentials": "手動憑證",+ "advanced": "進階"+ },"fields": {"appId": {"label": "App ID",@@ -44,12 +48,22 @@}},"custom": {- "scanTitle": "用手機 QQ 掃碼登入",- "waiting": "等待 QQ 掃碼…",- "connected": "QQ 已連線。",- "stopped": "QQ 登入已停止。",- "connecting": "連線中…",- "qrAlt": "QQ 登入 QR code",- "scanAgainWarning": "重新掃碼會取代目前的 App Secret,新掃碼完成後舊 Secret 將失效。"+ "scanTitle": "用手機 QQ 掃碼綁定",+ "waiting": "等待掃碼…",+ "connected": "綁定成功",+ "stopped": "已取消",+ "connecting": "產生中…",+ "qrAlt": "QQ 綁定 QR code",+ "scanAgainWarning": "重新綁定可能中斷其他軟體與此 QQ 機器人的連線。若 App Secret 被重設,舊金鑰將失效,使用舊金鑰的軟體也需更新金鑰。",+ "configured": "已設定",+ "bind": "綁定機器人",+ "rebind": "重新綁定",+ "refresh": "更新 QR code",+ "retry": "重試",+ "expired": "QR code 已過期",+ "failed": "綁定失敗",+ "cancelFailed": "取消失敗",+ "retrying": "正在重試…",+ "manualSetup": "手動設定"}}diff --git a/webui/src/channel-plugins/types.ts b/webui/src/channel-plugins/types.tsindex e8462b296..8bbf0a8e8 100644--- a/webui/src/channel-plugins/types.ts+++ b/webui/src/channel-plugins/types.ts@@ -34,6 +34,7 @@ export type ChannelPluginConnectFlowProps = {feature: NanobotFeatureInfo;idleLabel?: string;connectRequestId?: number;+ onOpenAdvanced?: () => void;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;};diff --git a/webui/src/components/settings/channels/ChannelCredentialFields.tsx b/webui/src/components/settings/channels/ChannelCredentialFields.tsxindex 7c540e4b3..af4d8429e 100644--- a/webui/src/components/settings/channels/ChannelCredentialFields.tsx+++ b/webui/src/components/settings/channels/ChannelCredentialFields.tsx@@ -79,7 +79,7 @@ export function ChannelFieldGroups({if (!sectionFields?.length) return null;return (<fieldset key={section} className="min-w-0">- <legend className={groups.size === 1 ? "sr-only" : "mb-2 text-[12px] font-medium text-muted-foreground"}>+ <legend className={groups.size === 1 ? "sr-only" : "mb-2 text-ui-label text-muted-foreground"}>{channelFieldSectionLabel(section, tx, sectionLabels)}</legend><div>diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsxindex eda9c6991..c01909df0 100644--- a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx+++ b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx@@ -66,7 +66,10 @@ export function ChannelQrConnectFlow({const pageVisible = usePageVisibility();const [connect, setConnect] = useState<ChannelConnectPayload | null>(null);const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);+ const [error, setError] = useState<{+ action: NonNullable<ChannelQrConnectFlowViewProps["errorAction"]>;+ message: string;+ } | null>(null);const handledRequestId = useRef(0);const autoStarted = useRef(false);const pollInFlight = useRef(false);@@ -103,11 +106,10 @@ export function ChannelQrConnectFlow({if (payload.nanobot_features) {onFeaturesUpdate(payload.nanobot_features);}- if (payload.status !== "pending") {- setError(null);- }+ setError((current) => payload.status !== "pending" || current?.action === "poll" ? null : current);} catch (err) {- if (!cancelled) setError((err as Error).message);+ if (!cancelled) setError((current) => current?.action === "cancel"+ ? current : { action: "poll", message: (err as Error).message });} finally {pollInFlight.current = false;}@@ -146,7 +148,7 @@ export function ChannelQrConnectFlow({onFeaturesUpdate(payload.nanobot_features);}} catch (err) {- setError((err as Error).message);+ setError({ action: "start", message: (err as Error).message });} finally {setBusy(false);}@@ -173,8 +175,9 @@ export function ChannelQrConnectFlow({connect.session_id,);setConnect(payload);+ setError(null);} catch (err) {- setError((err as Error).message);+ setError({ action: "cancel", message: (err as Error).message });} finally {setBusy(false);}@@ -206,7 +209,7 @@ export function ChannelQrConnectFlow({}return payload;} catch (err) {- setError((err as Error).message);+ setError({ action: "poll", message: (err as Error).message });return null;} finally {setBusy(false);@@ -216,7 +219,8 @@ export function ChannelQrConnectFlow({const viewProps: ChannelQrConnectFlowViewProps = {connect,busy,- error,+ error: error?.message ?? null,+ errorAction: error?.action,onStart: () => void start(forceOnRepeat && !pending && (connected || connect?.status === "succeeded")),onCancel: () => void cancel(),onPoll: submitPoll,diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsxindex c863fb386..a984bd9b9 100644--- a/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx+++ b/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx@@ -1,6 +1,6 @@import { useEffect, useState, type ReactNode } from "react";import QRCode from "qrcode";-import { Check, Loader2, RotateCcw } from "lucide-react";+import { Check, CircleAlert, Clock, Loader2, RotateCcw, X } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";@@ -31,6 +31,7 @@ export type ChannelQrConnectFlowViewProps = {connect: ChannelConnectPayload | null;busy: boolean;error: string | null;+ errorAction?: "start" | "poll" | "cancel";onStart: () => void;onCancel: () => void;onPoll: ChannelQrConnectPendingContext["poll"];@@ -70,6 +71,7 @@ export function ChannelQrConnectFlowView({const pending = connect?.status === "pending";const succeeded = !pending && (connected || connect?.status === "succeeded");const canStart = !pending && !busy;+ const TerminalIcon = connect?.status === "expired" ? Clock : connect?.status === "failed" ? CircleAlert : X;const displayMessage = connect? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined): undefined;@@ -103,9 +105,9 @@ export function ChannelQrConnectFlowView({return (<div className="mt-3 space-y-3">{autoStart && busy && !connect ? (- <div role="status" className="grid min-h-[228px] place-items-center">- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />- <span className="sr-only">{labels.connecting}</span>+ <div role="status" className="flex min-h-[228px] flex-col items-center justify-center gap-3 text-muted-foreground">+ <Loader2 className="h-5 w-5 animate-spin motion-reduce:animate-none" aria-hidden />+ <span className="text-caption">{labels.connecting}</span></div>) : null}{pending && minimalPending && showQrCode ? (@@ -124,7 +126,7 @@ export function ChannelQrConnectFlowView({{renderPending?.({ connect, busy, poll: onPoll })}</div>) : pending ? (- <div className={`grid gap-4 rounded-control border border-border/70 p-4 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>+ <div className={`grid items-center gap-4 py-2 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>{showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">{qrDataUrl ? (<img@@ -137,15 +139,15 @@ export function ChannelQrConnectFlowView({)}</div> : null}<div className="flex min-w-0 flex-col justify-center">- <div className="text-[13px] font-semibold text-foreground">+ <div className="text-ui-heading text-foreground">{labels.scanTitle}</div>- <p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">- {!showQrCode || qrDataUrl ? labels.scanDescription : null}- </p>+ {labels.scanDescription && (!showQrCode || qrDataUrl) ? (+ <p className="mt-1 text-caption text-muted-foreground">{labels.scanDescription}</p>+ ) : null}{renderPending?.({ connect, busy, poll: onPoll }) ?? (- <div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ <div role="status" className="mt-3 flex items-center gap-2 text-caption text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />{!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}</div>)}@@ -154,7 +156,6 @@ export function ChannelQrConnectFlowView({type="button"size="sm"variant="outline"- className="h-8 rounded-full px-3 text-[12px] font-semibold"onClick={() => onCancel()}disabled={busy}>@@ -166,7 +167,7 @@ export function ChannelQrConnectFlowView({) : null}{succeeded && !suppressSucceeded ? (- <div className="flex items-center gap-2 rounded-control border border-emerald-500/20 px-3 py-2 text-[12px] font-medium text-emerald-700 dark:text-emerald-200">+ <div role="status" className="flex items-center gap-2 text-caption text-emerald-700 dark:text-emerald-200"><Check className="h-3.5 w-3.5" aria-hidden />{displayMessage ?? labels.connected}</div>@@ -174,13 +175,15 @@ export function ChannelQrConnectFlowView({{connect && ["expired", "failed", "cancelled"].includes(connect.status)&& !(connected && connect.status === "cancelled") ? (- <div className="rounded-control border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">+ <div role="status" className="flex items-center gap-2 text-caption text-muted-foreground">+ <TerminalIcon className="h-3.5 w-3.5 shrink-0" aria-hidden />{displayMessage || labels.stopped}</div>) : null}{error ? (- <div className="rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">+ <div role="alert" className="flex items-center gap-2 text-caption text-destructive">+ <CircleAlert className="h-3.5 w-3.5 shrink-0" aria-hidden />{error}</div>) : null}@@ -190,7 +193,6 @@ export function ChannelQrConnectFlowView({type="button"size="sm"variant="outline"- className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold settings-hover"onClick={() => onStart()}disabled={!canStart}>diff --git a/webui/src/components/settings/channels/ChannelSetupPanel.tsx b/webui/src/components/settings/channels/ChannelSetupPanel.tsxindex 23feefe3b..c4ac079c9 100644--- a/webui/src/components/settings/channels/ChannelSetupPanel.tsx+++ b/webui/src/components/settings/channels/ChannelSetupPanel.tsx@@ -121,7 +121,7 @@ export function ChannelSetupPanel({const header = (<div className="flex min-w-0 items-center gap-3"><ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />- <h3 className="sr-only">{displayName}</h3>+ <h3 className="text-ui-heading">{displayName}</h3>{missingSupport && feature.install_supported ? (<Buttontype="button"@@ -508,7 +508,8 @@ function ChannelSetupSurface({connectFlow={mode === "connect" && ConnectFlow ? <Suspense fallback={<ChannelPluginLoading compact />}><ConnectFlow token={token} feature={feature}idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}- connectRequestId={connectRequestId} onFeaturesUpdate={onFeaturesUpdate} />+ connectRequestId={connectRequestId} onOpenAdvanced={() => setAdvancedOpen(true)}+ onFeaturesUpdate={onFeaturesUpdate} /></Suspense> : undefined}/>;}diff --git a/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx b/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsxindex 51f55a4f1..98d19eb02 100644--- a/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx+++ b/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx@@ -64,6 +64,19 @@ export function ChannelSetupSurfaceView({const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const mode = setup.mode ?? "credentials";const hasAdvanced = advancedFields.length > 0 || savedSecretFields.length > 0 || availablePresets.length > 0;+ const advancedFormProps = {+ fields: advancedFields,+ values: fieldValues,+ configuredFields,+ visibleSecrets,+ onChange: setFieldValue,+ onFieldBlur: saveSecretOnBlur,+ onToggleSecret: toggleSecret,+ errors: fieldErrors,+ clearedSecrets,+ onClearSecret: setSecretCleared,+ disabled: actionPending,+ };const inlineActions = mode === "credentials" && primaryFields.length === 1&& !advancedOpen && !setup.presets?.length && !setup.actions?.length;const credentialActions = mode === "credentials" ? (@@ -243,20 +256,11 @@ export function ChannelSetupSurfaceView({</div>{advancedFields.length ? (<div onBlur={() => void saveConnectionSettings()}>- <CredentialForm- fields={advancedFields}- values={fieldValues}- configuredFields={configuredFields}- visibleSecrets={visibleSecrets}- onChange={setFieldValue}- onFieldBlur={saveSecretOnBlur}- onToggleSecret={toggleSecret}- errors={fieldErrors}- clearedSecrets={clearedSecrets}- onClearSecret={setSecretCleared}- compact- disabled={actionPending}- />+ {mode === "connect" ? (+ <ChannelFieldGroups {...advancedFormProps} requirements={[]} sectionLabels={setup.sectionLabels} />+ ) : (+ <CredentialForm {...advancedFormProps} compact />+ )}</div>) : null}</div>diff --git a/webui/src/dev/gallery/channels-qq.tsx b/webui/src/dev/gallery/channels-qq.tsxindex 3359fd2dc..7f4923341 100644--- a/webui/src/dev/gallery/channels-qq.tsx+++ b/webui/src/dev/gallery/channels-qq.tsx@@ -5,7 +5,7 @@ import type { ChannelConnectPayload } from "@/lib/types";import { StatePicker, type ComponentExample } from "./example";import { useGalleryTranslation } from "./i18n";-const connectStates = ["idle", "starting", "pending", "succeeded", "expired", "failed", "cancelled", "error"] as const;+const connectStates = ["idle", "starting", "pending", "retrying", "succeeded", "expired", "failed", "cancelled", "error"] as const;type ConnectState = typeof connectStates[number];function QQConnectionPreview() {@@ -13,7 +13,8 @@ function QQConnectionPreview() {const [state, setState] = useState<ConnectState>("pending");const connect: ChannelConnectPayload | null = state === "idle" || state === "starting" || state === "error"? null- : { session_id: "gallery-qq", status: state, qr_url: "https://example.invalid/qq-authorization" };+ : { session_id: "gallery-qq", status: state === "retrying" ? "pending" : state,+ retrying: state === "retrying", qr_url: "https://example.invalid/qq-authorization" };return <><StatePicker label={t("previews.channelConnect.state", { channel: "QQ" })} value={state} options={connectStates} onChange={setState} /><QQConnectFlowView connect={connect} busy={state === "starting"} autoStart={state === "starting"}diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 2be186534..43752e9e7 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -1330,6 +1330,7 @@ export interface ChannelConnectPayload {qr_url?: string;interval_ms?: number;expires_at_ms?: number;+ retrying?: boolean;nanobot_features?: NanobotFeaturesPayload;}diff --git a/webui/src/tests/component-gallery.test.tsx b/webui/src/tests/component-gallery.test.tsxindex 4346d3580..7aa52985e 100644--- a/webui/src/tests/component-gallery.test.tsx+++ b/webui/src/tests/component-gallery.test.tsx@@ -239,16 +239,20 @@ it("previews QQ QR states and retries without connecting to the portal", async (render(<Gallery />);await screen.findByRole("heading", { name: "QQConnectFlowView · QQ QR connection" });const preview = within(screen.getByRole("region", { name: "Component preview" }));- expect(await preview.findByRole("img", { name: "QQ login QR code" })).toBeVisible();+ expect(await preview.findByRole("img", { name: "QQ binding QR code" })).toBeVisible();await userEvent.click(preview.getByRole("button", { name: "Cancel" }));- expect(preview.queryByRole("img", { name: "QQ login QR code" })).not.toBeInTheDocument();- await userEvent.click(preview.getByRole("button", { name: "Connect" }));- expect(await preview.findByRole("img", { name: "QQ login QR code" })).toBeVisible();+ expect(preview.queryByRole("img", { name: "QQ binding QR code" })).not.toBeInTheDocument();+ await userEvent.click(preview.getByRole("button", { name: "Bind QQ bot" }));+ expect(await preview.findByRole("img", { name: "QQ binding QR code" })).toBeVisible();await userEvent.click(preview.getByRole("combobox", { name: "QQ connection state" }));await userEvent.click(screen.getByRole("option", { name: "succeeded" }));- expect(preview.getByText("QQ is connected.")).toBeVisible();- expect(preview.getByText(/previous App Secret stops working/)).toBeVisible();- expect(preview.getByRole("button", { name: "Scan again" })).toBeVisible();+ expect(preview.getByText("Configured")).toBeVisible();+ expect(preview.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();+ await userEvent.click(preview.getByRole("button", { name: "Rebind bot" }));+ const confirmation = screen.getByRole("alertdialog", { name: "Rebind bot" });+ expect(confirmation).toHaveTextContent("Rebinding may interrupt other apps using this QQ bot. If the App Secret is reset, the old secret becomes invalid and those apps need the new secret.");+ await userEvent.click(within(confirmation).getByRole("button", { name: "Cancel" }));+ expect(preview.getByText("Configured")).toBeVisible();expect(fetch).toHaveBeenCalledTimes(1);expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");});diff --git a/webui/src/tests/qq-connect-flow.test.tsx b/webui/src/tests/qq-connect-flow.test.tsxnew file mode 100644index 000000000..ac083771d--- /dev/null+++ b/webui/src/tests/qq-connect-flow.test.tsx@@ -0,0 +1,129 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import QRCode from "qrcode";++import i18n from "@/i18n";+import type { ChannelConnectPayload, NanobotFeatureInfo } from "@/lib/types";++import { QQConnectFlow } from "../../../nanobot/channels/qq/webui/QQConnectFlow";+import { QQConnectFlowView } from "../../../nanobot/channels/qq/webui/QQConnectFlowView";++const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));+vi.mock("@/providers/ClientProvider", () => {+ const client = { requestMutation };+ return { useClient: () => ({ client }) };+});++const pending: ChannelConnectPayload = {+ session_id: "qq-test",+ status: "pending",+ qr_url: "https://example.invalid/qq-bind",+ retrying: false,+};+const actions = () => ({+ busy: false,+ error: null,+ onStart: vi.fn(),+ onCancel: vi.fn(),+ onPoll: vi.fn(async () => null),+ onManualSetup: vi.fn(),+});++beforeEach(() => requestMutation.mockReset());+afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });++it("keeps the QR and manual setup available while retrying, then returns to waiting", async () => {+ const props = actions();+ const { rerender } = render(<QQConnectFlowView {...props} connect={pending} />);+ const qr = await screen.findByRole("img", { name: "QQ binding QR code" });+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for scan…");+ rerender(<QQConnectFlowView {...props} connect={{ ...pending, retrying: true }} />);+ expect(screen.getByRole("status")).toHaveTextContent("Retrying…");+ expect(qr).toBeInTheDocument();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Enter credentials manually" }));+ expect(props.onManualSetup).toHaveBeenCalledOnce();+ rerender(<QQConnectFlowView {...props} connect={pending} />);+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for scan…");+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(props.onCancel).toHaveBeenCalledOnce();+});++it.each([+ ["expired", "二维码已过期", "刷新二维码"],+ ["failed", "绑定失败", "重试"],+ ["cancelled", "已取消", "绑定机器人"],+] as const)("shows a localized %s state and a working recovery action", async (status, label, action) => {+ await i18n.changeLanguage("zh-CN");+ const props = actions();+ render(<QQConnectFlowView {...props} connect={{ ...pending, status, message: "Raw portal response" }} />);+ expect(screen.getByRole("status")).toHaveTextContent(label);+ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ expect(screen.queryByText("Raw portal response")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: action }));+ expect(props.onStart).toHaveBeenCalledOnce();+});++it("offers retry after QR preparation fails without showing a successful binding", () => {+ const props = { ...actions(), error: "Unable to start QQ QR login: portal error" };+ render(<QQConnectFlowView {...props} connect={null} autoStart />);+ expect(screen.getByRole("alert")).toHaveTextContent("Binding failed");+ expect(screen.queryByText("Configured")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(props.onStart).toHaveBeenCalledOnce();+});++it("clears a transport retry indication when polling recovers before the scan finishes", async () => {+ const feature: NanobotFeatureInfo = {+ name: "qq", display_name: "QQ", type: "channel", enabled: false,+ configured: false, installed: true, ready: false, status: "not_enabled",+ install_supported: true, requires_restart: false,+ };+ requestMutation.mockResolvedValueOnce({ ...pending, interval_ms: 2500 })+ .mockRejectedValueOnce(new Error("connection interrupted"))+ .mockResolvedValueOnce(pending);+ vi.spyOn(QRCode, "toDataURL").mockImplementation(async () => "data:image/png;base64,preview");+ vi.useFakeTimers();+ await act(async () => {+ render(<QQConnectFlow token="test" feature={feature} onFeaturesUpdate={vi.fn()} />);+ });+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for scan…");+ await act(async () => { await vi.advanceTimersByTimeAsync(900); });+ expect(screen.getByRole("status")).toHaveTextContent("Retrying…");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for scan…");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(requestMutation).toHaveBeenCalledTimes(3);+});++it("keeps cancellation errors distinct from poll recovery and clears them after cancelling", async () => {+ const feature: NanobotFeatureInfo = {+ name: "qq", display_name: "QQ", type: "channel", enabled: false,+ configured: false, installed: true, ready: false, status: "not_enabled",+ install_supported: true, requires_restart: false,+ };+ requestMutation.mockResolvedValueOnce({ ...pending, interval_ms: 2500 })+ .mockRejectedValueOnce(new Error("connection interrupted"))+ .mockRejectedValueOnce(new Error("cancel request failed"))+ .mockRejectedValueOnce(new Error("connection still interrupted"))+ .mockResolvedValueOnce(pending)+ .mockResolvedValueOnce({ session_id: pending.session_id, status: "cancelled", retrying: false });+ vi.spyOn(QRCode, "toDataURL").mockImplementation(async () => "data:image/png;base64,preview");+ vi.useFakeTimers();+ await act(async () => {+ render(<QQConnectFlow token="test" feature={feature} onFeaturesUpdate={vi.fn()} />);+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(900); });+ expect(screen.getByRole("status")).toHaveTextContent("Retrying…");+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Cancel" })); });+ expect(screen.getByRole("alert")).toHaveTextContent("Could not cancel");+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(screen.getByRole("alert")).toHaveTextContent("Could not cancel");+ await act(async () => { await vi.advanceTimersByTimeAsync(2500); });+ expect(screen.getByRole("alert")).toHaveTextContent("Could not cancel");+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Cancel" })); });+ expect(screen.getByRole("status")).toHaveTextContent("Cancelled");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Bind QQ bot" })).toBeEnabled();+});diff --git a/webui/src/tests/settings-channels.test.tsx b/webui/src/tests/settings-channels.test.tsxindex 0a0e3358b..16eded14b 100644--- a/webui/src/tests/settings-channels.test.tsx+++ b/webui/src/tests/settings-channels.test.tsx@@ -2114,20 +2114,83 @@ describe("Settings channels", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View QQ settings" }));- expect(await screen.findByRole("img", { name: "QQ login QR code" })).toBeInTheDocument();+ expect(await screen.findByRole("img", { name: "QQ binding QR code" })).toBeInTheDocument();expect(requestMutationMock).toHaveBeenCalledWith("settings.channel.connect.start", { channel: "qq" }, 150_000,);await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.channel.connect.poll", { channel: "qq", session_id: "qq-1" }, 150_000,));- expect(await screen.findByText("QQ is connected.")).toBeInTheDocument();- expect(screen.getByText(/previous App Secret stops working/)).toBeInTheDocument();+ expect(await screen.findByText("Configured")).toBeInTheDocument();+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();+ expect(screen.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Advanced" }));expect(screen.getByLabelText("App ID")).toHaveValue("1024");expect(screen.getByLabelText("Acknowledgement message")).toHaveValue("⏳ Processing...");});+ it("keeps saved QQ setup distinct from a running connection when reopening settings", async () => {+ const qqFeature: NanobotFeatureInfo = {+ ...catalogFeature("qq", false),+ display_name: "QQ",+ webui: "webui/index.tsx",+ configured: true,+ runtime_status: "stopped",+ config_values: { "channels.qq.appId": "1024" },+ configured_fields: ["channels.qq.appId", "channels.qq.secret"],+ setup: channelSetupContract("qq"),+ };+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/nanobot-features") {+ return jsonResponse({ features: [qqFeature], enabled_count: 0 });+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }));++ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View QQ settings" }));+ expect(await screen.findByText("Configured")).toBeInTheDocument();+ expect(within(screen.getByRole("dialog")).getByText("Not running")).toBeInTheDocument();+ expect(within(screen.getByRole("dialog")).queryByText("Running")).not.toBeInTheDocument();+ expect(screen.getByText("1024")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Rebind bot" })).toBeInTheDocument();+ expect(screen.queryByRole("img", { name: "QQ binding QR code" })).not.toBeInTheDocument();+ expect(requestMutationMock).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("button", { name: "Enter credentials manually" }));+ expect(screen.getByRole("group", { name: "Manual credentials" })).toBeInTheDocument();+ expect(screen.getByRole("group", { name: "Access" })).toBeInTheDocument();+ expect(screen.getByRole("group", { name: "Behavior" })).toBeInTheDocument();+ expect(screen.getByRole("group", { name: "Advanced" })).toBeInTheDocument();+ expect(screen.getByLabelText("App ID")).toHaveValue("1024");+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ fireEvent.click(screen.getByRole("button", { name: "View QQ settings" }));+ const rebind = await screen.findByRole("button", { name: "Rebind bot" });+ expect(screen.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();+ expect(requestMutationMock).not.toHaveBeenCalled();+ rebind.focus();+ fireEvent.click(rebind);+ const confirmation = await screen.findByRole("alertdialog", { name: "Rebind bot" });+ expect(confirmation).toHaveTextContent("Rebinding may interrupt other apps using this QQ bot. If the App Secret is reset, the old secret becomes invalid and those apps need the new secret.");+ expect(requestMutationMock).not.toHaveBeenCalled();+ fireEvent.click(within(confirmation).getByRole("button", { name: "Cancel" }));+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ expect(screen.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();+ expect(rebind).toHaveFocus();+ expect(requestMutationMock).not.toHaveBeenCalled();++ requestMutationMock.mockResolvedValue({ status: "pending", session_id: "qq-rebind", qr_url: "https://example.com/qq-rebind" });+ fireEvent.click(rebind);+ fireEvent.click(within(await screen.findByRole("alertdialog", { name: "Rebind bot" }))+ .getByRole("button", { name: "Rebind bot" }));+ expect(await screen.findByRole("img", { name: "QQ binding QR code" })).toBeInTheDocument();+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ expect(requestMutationMock).toHaveBeenCalledWith("settings.channel.connect.start", { channel: "qq" }, 150_000);+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();+ });+it("keeps the WebUI websocket channel enabled without opening a setup dialog", async () => {const fetchMock = vi.fn(async (input: RequestInfo | URL) => {const url = String(input);