fix(qq): clarify QR binding states and setup actions (#6340)

* fix(qq): clarify QR binding states and setup actions

* fix(qq): confirm rebinding instead of showing a persistent warning

* fix(qq): make rebind credential warning conditional

* docs(qq): align rebind guide with conditional warning
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 01:55:20 +08:00
1 parent 51a0fc83a2
commit 130f4edefe
27 files changed
+634 -168

No files matched your search

+3 -1
View File
@@ -24,7 +24,9 @@ For terminal or server setup, use the manual configuration section below. Reuse
## Enable the QQ channel ## 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> <details>
<summary>Manual configuration</summary> <summary>Manual configuration</summary>
+6 -16
View File
@@ -126,14 +126,7 @@ class QQConnectStore:
except Exception as exc: except Exception as exc:
raise ChannelConnectError(f"Unable to start QQ QR login: {exc}", status=502) from exc raise ChannelConnectError(f"Unable to start QQ QR login: {exc}", status=502) from exc
session = self._new_session(task_id, key) session = self._new_session(task_id, key)
return { return _pending(session, "Scan with mobile QQ to connect.")
"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.",
}
async def poll(self, session_id: str) -> dict[str, Any]: async def poll(self, session_id: str) -> dict[str, Any]:
self._cleanup() self._cleanup()
@@ -145,7 +138,7 @@ class QQConnectStore:
result = await poll_bind_task(session.task_id) result = await poll_bind_task(session.task_id)
except Exception: except Exception:
# A transient portal error is not proof the scan failed; keep waiting. # 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() self._cleanup()
if self._sessions.get(session_id) is not session: 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) commit.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
await asyncio.shield(commit) await asyncio.shield(commit)
session.credentials = (app_id, secret) session.credentials = (app_id, secret)
return { return _payload(session_id, "succeeded", "QQ is connected.")
"session_id": session_id,
"status": "succeeded",
"message": "QQ is connected.",
}
async def cancel(self, session_id: str) -> dict[str, Any]: async def cancel(self, session_id: str) -> dict[str, Any]:
self._sessions.pop(session_id, None) 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]: 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 { return {
"session_id": session.id, "session_id": session.id,
"status": "pending", "status": "pending",
@@ -245,6 +234,7 @@ def _pending(session: QQConnectSession, message: str) -> dict[str, Any]:
"interval_ms": POLL_INTERVAL_MS, "interval_ms": POLL_INTERVAL_MS,
"expires_at_ms": int((session.created_wall + SESSION_TTL_SECONDS) * 1000), "expires_at_ms": int((session.created_wall + SESSION_TTL_SECONDS) * 1000),
"message": message, "message": message,
"retrying": retrying,
} }
+28 -4
View File
@@ -47,16 +47,19 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
started = await store.start() started = await store.start()
assert started["status"] == "pending" assert started["status"] == "pending"
assert started["retrying"] is False
assert started["qr_url"].endswith("task_id=task-1&_wv=2") assert started["qr_url"].endswith("task_id=task-1&_wv=2")
assert store.has_pending_work assert store.has_pending_work
polled = await store.poll(started["session_id"]) polled = await store.poll(started["session_id"])
assert polled["status"] == "succeeded" assert polled["status"] == "succeeded"
assert not store.has_pending_work assert not store.has_pending_work
assert polled["retrying"] is False
assert await store.poll(started["session_id"]) == { assert await store.poll(started["session_id"]) == {
"session_id": started["session_id"], "session_id": started["session_id"],
"status": "expired", "status": "expired",
"message": "This QQ login has expired. Start again.", "message": "This QQ login has expired. Start again.",
"retrying": False,
} }
saved = json.loads(_isolated_config.read_text(encoding="utf-8")) 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 @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]: async def fake_create() -> tuple[str, str]:
return "task-2", base64.b64encode(b"k" * 32).decode() return "task-2", base64.b64encode(b"k" * 32).decode()
async def fake_poll(_task_id: str) -> dict[str, Any]: poll_count = 0
raise RuntimeError("portal hiccup")
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, "create_bind_task", fake_create)
monkeypatch.setattr(connect, "poll_bind_task", fake_poll) monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
store = QQConnectStore() store = QQConnectStore()
started = await store.start() 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.asyncio @pytest.mark.asyncio
+14 -3
View File
@@ -1,27 +1,38 @@
import { useTranslation } from "react-i18next";
import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types"; import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow"; import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
import { channelStatusLabel } from "@/components/settings/channels/ChannelIdentity";
import { QQConnectFlowView, useQQConnectLabels } from "./QQConnectFlowView"; import { QQConnectFlowView, useQQConnectLabels } from "./QQConnectFlowView";
export function QQConnectFlow({ export function QQConnectFlow({
token, token,
feature, feature,
idleLabel,
connectRequestId, connectRequestId,
onOpenAdvanced,
onFeaturesUpdate, onFeaturesUpdate,
}: ChannelPluginConnectFlowProps) { }: ChannelPluginConnectFlowProps) {
const { t } = useTranslation();
const labels = useQQConnectLabels(); 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 ( return (
<ChannelQrConnectFlow <ChannelQrConnectFlow
token={token} token={token}
channelName="qq" channelName="qq"
idleLabel={idleLabel}
connectRequestId={connectRequestId} connectRequestId={connectRequestId}
autoStart={!feature.configured} autoStart={!feature.configured}
forceOnRepeat forceOnRepeat
labels={labels} labels={labels}
onFeaturesUpdate={onFeaturesUpdate} 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} />}
/> />
); );
} }
+108 -19
View File
@@ -1,43 +1,132 @@
import { useRef, useState } from "react";
import { Check } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { channelTranslator } from "@/channel-plugins/i18n"; 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 { 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"> & { export type QQConnectFlowViewProps = Omit<ChannelQrConnectFlowViewProps, "labels"> & {
configured?: boolean; configured?: boolean;
appId?: string;
runtimeStatus?: ChannelRuntimeStatus;
runtimeLabel?: string;
onManualSetup?: () => void;
}; };
export function useQQConnectLabels(): ChannelQrConnectLabels { export function useQQConnectLabels(): ChannelQrConnectLabels {
const { t } = useTranslation(); const { t } = useTranslation();
const tx = channelTranslator(t, "qq"); const tx = channelTranslator(t, "qq");
return { 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"), scanTitle: tx("custom.scanTitle", "Scan with mobile QQ"),
scanDescription: "", scanDescription: "",
waiting: tx("custom.waiting", "Waiting for QQ scan..."), waiting: tx("custom.waiting", "Waiting for scan…"),
connected: tx("custom.connected", "QQ is connected."), connected: tx("custom.connected", "Binding complete"),
stopped: tx("custom.stopped", "QQ login stopped."), stopped: tx("custom.stopped", "Cancelled"),
connecting: tx("custom.connecting", "Connecting..."), connecting: tx("custom.connecting", "Preparing QR code…"),
scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }), scanAgain: tx("custom.rebind", "Rebind bot"),
connect: t("settings.channels.connect", { defaultValue: "Connect" }), 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 { t } = useTranslation();
const tx = channelTranslator(t, "qq"); const tx = channelTranslator(t, "qq");
const labels = useQQConnectLabels(); const labels = useQQConnectLabels();
const rescanWarning = configured ? tx("custom.scanAgainWarning", "") : ""; const [rebindOpen, setRebindOpen] = useState(false);
return <ChannelQrConnectFlowView {...props} labels={labels} const rebindTrigger = useRef<HTMLElement | null>(null);
renderActions={(connectButton) => ( const pending = props.connect?.status === "pending";
<div className="flex flex-wrap items-center justify-end gap-2"> const pollFailed = pending && props.errorAction === "poll" && Boolean(props.error);
{rescanWarning ? ( const retrying = props.connect?.retrying || pollFailed;
<p className="max-w-[22rem] text-[11.5px] leading-5 text-muted-foreground"> const needsRetry = props.connect?.status === "failed" || Boolean(props.error);
{rescanWarning} 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> </p>
) : null} {appId ? <p className="break-all text-caption text-muted-foreground">
{connectButton} {tx("setup.fields.appId.label", "App ID")}: <code>{appId}</code>
</p> : null}
</div>
{runtimeLabel ? <ChannelStatusBadge status={runtimeStatus}>{runtimeLabel}</ChannelStatusBadge> : null}
</div> </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>;
} }
+3 -3
View File
@@ -27,9 +27,9 @@ export default {
{ key: "channels.qq.msgFormat", section: "behavior" }, { key: "channels.qq.msgFormat", section: "behavior" },
{ key: "channels.qq.ackMessage", section: "behavior" }, { key: "channels.qq.ackMessage", section: "behavior" },
{ key: "channels.qq.showCompactionNotices", section: "behavior" }, { key: "channels.qq.showCompactionNotices", section: "behavior" },
{ key: "channels.qq.mediaDir", section: "behavior" }, { key: "channels.qq.mediaDir", section: "advanced" },
{ key: "channels.qq.downloadChunkSize", section: "behavior" }, { key: "channels.qq.downloadChunkSize", section: "advanced" },
{ key: "channels.qq.downloadMaxBytes", section: "behavior" }, { key: "channels.qq.downloadMaxBytes", section: "advanced" },
], ],
}, },
}, },
+20 -6
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "Open QQ setup", "docsLabel": "Open QQ setup",
"officialLabel": "Open QQ bot console", "officialLabel": "Open QQ bot console",
"sections": {
"credentials": "Manual credentials",
"advanced": "Advanced"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"qrAlt": "QQ login QR code", "qrAlt": "QQ binding QR code",
"scanTitle": "Scan with mobile QQ", "scanTitle": "Scan with mobile QQ",
"waiting": "Waiting for QQ scan…", "waiting": "Waiting for scan…",
"connected": "QQ is connected.", "connected": "Binding complete",
"stopped": "QQ login stopped.", "stopped": "Cancelled",
"connecting": "Connecting...", "connecting": "Preparing QR code…",
"scanAgainWarning": "Scanning again replaces the current App Secret. The previous App Secret stops working once the new scan completes." "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"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "Abrir guía de QQ", "docsLabel": "Abrir guía de QQ",
"officialLabel": "Abrir consola del bot de QQ", "officialLabel": "Abrir consola del bot de QQ",
"sections": {
"credentials": "Credenciales manuales",
"advanced": "Avanzado"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "Escanea con QQ móvil", "scanTitle": "Escanea con QQ en el móvil",
"waiting": "Esperando el escaneo de QQ…", "waiting": "Esperando escaneo…",
"connected": "QQ está conectado.", "connected": "Vinculación completada",
"stopped": "El inicio de sesión de QQ se detuvo.", "stopped": "Cancelado",
"connecting": "Conectando…", "connecting": "Preparando código QR…",
"qrAlt": "Código QR de inicio de sesión de QQ", "qrAlt": "Código QR para vincular QQ",
"scanAgainWarning": "Escanear de nuevo reemplaza el App Secret actual. El App Secret anterior deja de funcionar cuando termina el nuevo escaneo." "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"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "Ouvrir le guide QQ", "docsLabel": "Ouvrir le guide QQ",
"officialLabel": "Ouvrir la console du bot QQ", "officialLabel": "Ouvrir la console du bot QQ",
"sections": {
"credentials": "Identifiants (saisie manuelle)",
"advanced": "Avancé"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "Scannez avec QQ mobile", "scanTitle": "Scannez avec QQ sur mobile",
"waiting": "En attente du scan QQ…", "waiting": "En attente du scan…",
"connected": "QQ est connecté.", "connected": "Association terminée",
"stopped": "La connexion QQ s'est arrêtée.", "stopped": "Annulé",
"connecting": "Connexion…", "connecting": "Préparation du QR code…",
"qrAlt": "QR code de connexion QQ", "qrAlt": "QR code d'association QQ",
"scanAgainWarning": "Un nouveau scan remplace l'App Secret actuel. L'ancien App Secret cesse de fonctionner dès la fin du nouveau scan." "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"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "Buka panduan QQ", "docsLabel": "Buka panduan QQ",
"officialLabel": "Buka konsol bot QQ", "officialLabel": "Buka konsol bot QQ",
"sections": {
"credentials": "Kredensial manual",
"advanced": "Lanjutan"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "Pindai dengan QQ seluler", "scanTitle": "Pindai dengan QQ di ponsel",
"waiting": "Menunggu pindaian QQ…", "waiting": "Menunggu pemindaian…",
"connected": "QQ terhubung.", "connected": "Penautan selesai",
"stopped": "Login QQ dihentikan.", "stopped": "Dibatalkan",
"connecting": "Menghubungkan…", "connecting": "Menyiapkan kode QR…",
"qrAlt": "Kode QR login QQ", "qrAlt": "Kode QR penautan QQ",
"scanAgainWarning": "Memindai ulang menggantikan App Secret saat ini. App Secret lama tidak lagi berfungsi setelah pemindaian baru selesai." "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"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "QQ 設定ガイドを開く", "docsLabel": "QQ 設定ガイドを開く",
"officialLabel": "QQ ボットコンソールを開く", "officialLabel": "QQ ボットコンソールを開く",
"sections": {
"credentials": "手動入力の認証情報",
"advanced": "詳細設定"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "モバイル QQ でスキャン", "scanTitle": "スマートフォンの QQ でスキャン",
"waiting": "QQ のスキャンを待っています…", "waiting": "スキャン待ち…",
"connected": "QQ に接続しました。", "connected": "連携完了",
"stopped": "QQ ログインを停止しました。", "stopped": "キャンセル済み",
"connecting": "接続中…", "connecting": "QR コードを準備中…",
"qrAlt": "QQ ログイン QR コード", "qrAlt": "QQ 連携用 QR コード",
"scanAgainWarning": "再スキャンすると現在の App Secret が置き換わります。新しいスキャンが完了すると、以前の App Secret は無効になります。" "scanAgainWarning": "再連携すると、この QQ ボットを利用する他のアプリの接続が切れる可能性があります。App Secret がリセットされた場合、古いシークレットは無効になり、他のアプリでも新しいシークレットへの更新が必要です。",
"configured": "設定済み",
"bind": "QQ ボットと連携",
"rebind": "ボットと再連携",
"refresh": "QR コードを更新",
"retry": "再試行",
"expired": "QR コードの有効期限切れ",
"failed": "連携失敗",
"cancelFailed": "キャンセルできませんでした",
"retrying": "再試行中…",
"manualSetup": "認証情報を手動で入力"
} }
} }
+20 -6
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "QQ 설정 가이드 열기", "docsLabel": "QQ 설정 가이드 열기",
"officialLabel": "QQ 봇 콘솔 열기", "officialLabel": "QQ 봇 콘솔 열기",
"sections": {
"credentials": "수동 인증 정보",
"advanced": "고급"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -45,11 +49,21 @@
}, },
"custom": { "custom": {
"scanTitle": "모바일 QQ로 스캔", "scanTitle": "모바일 QQ로 스캔",
"waiting": "QQ 스캔을 기다리는 중…", "waiting": "스캔 대기 중…",
"connected": "QQ가 연결되었습니다.", "connected": "연동 완료",
"stopped": "QQ 로그인이 중지되었습니다.", "stopped": "취소됨",
"connecting": "연결 중…", "connecting": "QR 코드 준비 중…",
"qrAlt": "QQ 로그인 QR 코드", "qrAlt": "QQ 연동 QR 코드",
"scanAgainWarning": "다시 스캔하면 현재 App Secret이 교체됩니다. 새 스캔이 완료되면 이전 App Secret은 더 이상 작동하지 않습니다." "scanAgainWarning": "재연동하면 이 QQ 봇을 사용하는 다른 앱의 연결이 끊길 수 있습니다. App Secret이 재설정되면 기존 시크릿이 무효화되므로 다른 앱도 새 시크릿으로 업데이트해야 합니다.",
"configured": "구성됨",
"bind": "QQ 봇 연동",
"rebind": "봇 다시 연동",
"refresh": "QR 코드 새로고침",
"retry": "재시도",
"expired": "QR 코드 만료",
"failed": "연동 실패",
"cancelFailed": "취소하지 못함",
"retrying": "재시도 중…",
"manualSetup": "인증 정보 수동 입력"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "Abrir guia do QQ", "docsLabel": "Abrir guia do QQ",
"officialLabel": "Abrir console do bot QQ", "officialLabel": "Abrir console do bot QQ",
"sections": {
"credentials": "Credenciais manuais",
"advanced": "Avançado"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "Escaneie com o QQ móvel", "scanTitle": "Escaneie com o QQ no celular",
"waiting": "Aguardando leitura do QQ…", "waiting": "Aguardando leitura…",
"connected": "QQ está conectado.", "connected": "Vinculação concluída",
"stopped": "O login do QQ foi interrompido.", "stopped": "Cancelado",
"connecting": "Conectando…", "connecting": "Preparando QR code…",
"qrAlt": "QR code de login do QQ", "qrAlt": "QR code de vinculação do QQ",
"scanAgainWarning": "Escanear novamente substitui o App Secret atual. O App Secret anterior deixa de funcionar quando a nova leitura termina." "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"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "Mở hướng dẫn QQ", "docsLabel": "Mở hướng dẫn QQ",
"officialLabel": "Mở bảng điều khiển bot 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": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "Quét bằng QQ di động", "scanTitle": "Quét bằng QQ trên điện thoại",
"waiting": "Đang chờ quét QQ…", "waiting": "Đang chờ quét mã…",
"connected": "QQ đã được kết nối.", "connected": "Liên kết hoàn tất",
"stopped": "Đăng nhập QQ đã dừng.", "stopped": "Đã hủy",
"connecting": "Đang kết nối…", "connecting": "Đang chuẩn bị mã QR…",
"qrAlt": "Mã QR đăng nhập QQ", "qrAlt": "Mã QR liên kết 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." "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"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "打开 QQ 配置指南", "docsLabel": "打开 QQ 配置指南",
"officialLabel": "打开 QQ 机器人后台", "officialLabel": "打开 QQ 机器人后台",
"sections": {
"credentials": "手动凭据",
"advanced": "高级"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "用手机 QQ 扫码登录", "scanTitle": "用手机 QQ 扫码绑定",
"waiting": "等待 QQ 扫码…", "waiting": "等待扫码…",
"connected": "QQ 已连接。", "connected": "绑定成功",
"stopped": "QQ 登录已停止。", "stopped": "已取消",
"connecting": "连接中…", "connecting": "生成中…",
"qrAlt": "QQ 登录二维码", "qrAlt": "QQ 绑定二维码",
"scanAgainWarning": "重新扫码会替换当前的 App Secret,新扫码完成后旧 Secret 将失效。" "scanAgainWarning": "重新绑定可能中断其他软件与此 QQ 机器人的连接。若 App Secret 被重置,旧密钥将失效,使用旧密钥的软件也需更新密钥。",
"configured": "已配置",
"bind": "绑定机器人",
"rebind": "重新绑定",
"refresh": "刷新二维码",
"retry": "重试",
"expired": "二维码已过期",
"failed": "绑定失败",
"cancelFailed": "取消失败",
"retrying": "正在重试…",
"manualSetup": "手动配置"
} }
} }
+21 -7
View File
@@ -2,6 +2,10 @@
"setup": { "setup": {
"docsLabel": "開啟 QQ 設定指南", "docsLabel": "開啟 QQ 設定指南",
"officialLabel": "開啟 QQ 機器人後台", "officialLabel": "開啟 QQ 機器人後台",
"sections": {
"credentials": "手動憑證",
"advanced": "進階"
},
"fields": { "fields": {
"appId": { "appId": {
"label": "App ID", "label": "App ID",
@@ -44,12 +48,22 @@
} }
}, },
"custom": { "custom": {
"scanTitle": "用手機 QQ 掃碼登入", "scanTitle": "用手機 QQ 掃碼綁定",
"waiting": "等待 QQ 掃碼…", "waiting": "等待掃碼…",
"connected": "QQ 已連線。", "connected": "綁定成功",
"stopped": "QQ 登入已停止。", "stopped": "已取消",
"connecting": "連線中…", "connecting": "產生中…",
"qrAlt": "QQ 登入 QR code", "qrAlt": "QQ 綁定 QR code",
"scanAgainWarning": "重新掃碼會取代目前的 App Secret,新掃碼完成後舊 Secret 將失效。" "scanAgainWarning": "重新綁定可能中斷其他軟體與此 QQ 機器人的連線。若 App Secret 被重設,舊金鑰將失效,使用舊金鑰的軟體也需更新金鑰。",
"configured": "已設定",
"bind": "綁定機器人",
"rebind": "重新綁定",
"refresh": "更新 QR code",
"retry": "重試",
"expired": "QR code 已過期",
"failed": "綁定失敗",
"cancelFailed": "取消失敗",
"retrying": "正在重試…",
"manualSetup": "手動設定"
} }
} }
+1
View File
@@ -34,6 +34,7 @@ export type ChannelPluginConnectFlowProps = {
feature: NanobotFeatureInfo; feature: NanobotFeatureInfo;
idleLabel?: string; idleLabel?: string;
connectRequestId?: number; connectRequestId?: number;
onOpenAdvanced?: () => void;
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void; onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
}; };
@@ -79,7 +79,7 @@ export function ChannelFieldGroups({
if (!sectionFields?.length) return null; if (!sectionFields?.length) return null;
return ( return (
<fieldset key={section} className="min-w-0"> <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)} {channelFieldSectionLabel(section, tx, sectionLabels)}
</legend> </legend>
<div> <div>
@@ -66,7 +66,10 @@ export function ChannelQrConnectFlow({
const pageVisible = usePageVisibility(); const pageVisible = usePageVisibility();
const [connect, setConnect] = useState<ChannelConnectPayload | null>(null); const [connect, setConnect] = useState<ChannelConnectPayload | null>(null);
const [busy, setBusy] = useState(false); 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 handledRequestId = useRef(0);
const autoStarted = useRef(false); const autoStarted = useRef(false);
const pollInFlight = useRef(false); const pollInFlight = useRef(false);
@@ -103,11 +106,10 @@ export function ChannelQrConnectFlow({
if (payload.nanobot_features) { if (payload.nanobot_features) {
onFeaturesUpdate(payload.nanobot_features); onFeaturesUpdate(payload.nanobot_features);
} }
if (payload.status !== "pending") { setError((current) => payload.status !== "pending" || current?.action === "poll" ? null : current);
setError(null);
}
} catch (err) { } 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 { } finally {
pollInFlight.current = false; pollInFlight.current = false;
} }
@@ -146,7 +148,7 @@ export function ChannelQrConnectFlow({
onFeaturesUpdate(payload.nanobot_features); onFeaturesUpdate(payload.nanobot_features);
} }
} catch (err) { } catch (err) {
setError((err as Error).message); setError({ action: "start", message: (err as Error).message });
} finally { } finally {
setBusy(false); setBusy(false);
} }
@@ -173,8 +175,9 @@ export function ChannelQrConnectFlow({
connect.session_id, connect.session_id,
); );
setConnect(payload); setConnect(payload);
setError(null);
} catch (err) { } catch (err) {
setError((err as Error).message); setError({ action: "cancel", message: (err as Error).message });
} finally { } finally {
setBusy(false); setBusy(false);
} }
@@ -206,7 +209,7 @@ export function ChannelQrConnectFlow({
} }
return payload; return payload;
} catch (err) { } catch (err) {
setError((err as Error).message); setError({ action: "poll", message: (err as Error).message });
return null; return null;
} finally { } finally {
setBusy(false); setBusy(false);
@@ -216,7 +219,8 @@ export function ChannelQrConnectFlow({
const viewProps: ChannelQrConnectFlowViewProps = { const viewProps: ChannelQrConnectFlowViewProps = {
connect, connect,
busy, busy,
error, error: error?.message ?? null,
errorAction: error?.action,
onStart: () => void start(forceOnRepeat && !pending && (connected || connect?.status === "succeeded")), onStart: () => void start(forceOnRepeat && !pending && (connected || connect?.status === "succeeded")),
onCancel: () => void cancel(), onCancel: () => void cancel(),
onPoll: submitPoll, onPoll: submitPoll,
@@ -1,6 +1,6 @@
import { useEffect, useState, type ReactNode } from "react"; import { useEffect, useState, type ReactNode } from "react";
import QRCode from "qrcode"; 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 { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -31,6 +31,7 @@ export type ChannelQrConnectFlowViewProps = {
connect: ChannelConnectPayload | null; connect: ChannelConnectPayload | null;
busy: boolean; busy: boolean;
error: string | null; error: string | null;
errorAction?: "start" | "poll" | "cancel";
onStart: () => void; onStart: () => void;
onCancel: () => void; onCancel: () => void;
onPoll: ChannelQrConnectPendingContext["poll"]; onPoll: ChannelQrConnectPendingContext["poll"];
@@ -70,6 +71,7 @@ export function ChannelQrConnectFlowView({
const pending = connect?.status === "pending"; const pending = connect?.status === "pending";
const succeeded = !pending && (connected || connect?.status === "succeeded"); const succeeded = !pending && (connected || connect?.status === "succeeded");
const canStart = !pending && !busy; const canStart = !pending && !busy;
const TerminalIcon = connect?.status === "expired" ? Clock : connect?.status === "failed" ? CircleAlert : X;
const displayMessage = connect const displayMessage = connect
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined) ? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
: undefined; : undefined;
@@ -103,9 +105,9 @@ export function ChannelQrConnectFlowView({
return ( return (
<div className="mt-3 space-y-3"> <div className="mt-3 space-y-3">
{autoStart && busy && !connect ? ( {autoStart && busy && !connect ? (
<div role="status" className="grid min-h-[228px] place-items-center"> <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 text-muted-foreground" aria-hidden /> <Loader2 className="h-5 w-5 animate-spin motion-reduce:animate-none" aria-hidden />
<span className="sr-only">{labels.connecting}</span> <span className="text-caption">{labels.connecting}</span>
</div> </div>
) : null} ) : null}
{pending && minimalPending && showQrCode ? ( {pending && minimalPending && showQrCode ? (
@@ -124,7 +126,7 @@ export function ChannelQrConnectFlowView({
{renderPending?.({ connect, busy, poll: onPoll })} {renderPending?.({ connect, busy, poll: onPoll })}
</div> </div>
) : pending ? ( ) : 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"> {showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">
{qrDataUrl ? ( {qrDataUrl ? (
<img <img
@@ -137,15 +139,15 @@ export function ChannelQrConnectFlowView({
)} )}
</div> : null} </div> : null}
<div className="flex min-w-0 flex-col justify-center"> <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} {labels.scanTitle}
</div> </div>
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground"> {labels.scanDescription && (!showQrCode || qrDataUrl) ? (
{!showQrCode || qrDataUrl ? labels.scanDescription : null} <p className="mt-1 text-caption text-muted-foreground">{labels.scanDescription}</p>
</p> ) : null}
{renderPending?.({ connect, busy, poll: onPoll }) ?? ( {renderPending?.({ connect, busy, poll: onPoll }) ?? (
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground"> <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" aria-hidden /> <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />
{!showQrCode || qrDataUrl ? labels.waiting : labels.connecting} {!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}
</div> </div>
)} )}
@@ -154,7 +156,6 @@ export function ChannelQrConnectFlowView({
type="button" type="button"
size="sm" size="sm"
variant="outline" variant="outline"
className="h-8 rounded-full px-3 text-[12px] font-semibold"
onClick={() => onCancel()} onClick={() => onCancel()}
disabled={busy} disabled={busy}
> >
@@ -166,7 +167,7 @@ export function ChannelQrConnectFlowView({
) : null} ) : null}
{succeeded && !suppressSucceeded ? ( {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 /> <Check className="h-3.5 w-3.5" aria-hidden />
{displayMessage ?? labels.connected} {displayMessage ?? labels.connected}
</div> </div>
@@ -174,13 +175,15 @@ export function ChannelQrConnectFlowView({
{connect && ["expired", "failed", "cancelled"].includes(connect.status) {connect && ["expired", "failed", "cancelled"].includes(connect.status)
&& !(connected && connect.status === "cancelled") ? ( && !(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} {displayMessage || labels.stopped}
</div> </div>
) : null} ) : null}
{error ? ( {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} {error}
</div> </div>
) : null} ) : null}
@@ -190,7 +193,6 @@ export function ChannelQrConnectFlowView({
type="button" type="button"
size="sm" size="sm"
variant="outline" variant="outline"
className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold settings-hover"
onClick={() => onStart()} onClick={() => onStart()}
disabled={!canStart} disabled={!canStart}
> >
@@ -121,7 +121,7 @@ export function ChannelSetupPanel({
const header = ( const header = (
<div className="flex min-w-0 items-center gap-3"> <div className="flex min-w-0 items-center gap-3">
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} /> <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<h3 className="sr-only">{displayName}</h3> <h3 className="text-ui-heading">{displayName}</h3>
{missingSupport && feature.install_supported ? ( {missingSupport && feature.install_supported ? (
<Button <Button
type="button" type="button"
@@ -508,7 +508,8 @@ function ChannelSetupSurface({
connectFlow={mode === "connect" && ConnectFlow ? <Suspense fallback={<ChannelPluginLoading compact />}> connectFlow={mode === "connect" && ConnectFlow ? <Suspense fallback={<ChannelPluginLoading compact />}>
<ConnectFlow token={token} feature={feature} <ConnectFlow token={token} feature={feature}
idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")} idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
connectRequestId={connectRequestId} onFeaturesUpdate={onFeaturesUpdate} /> connectRequestId={connectRequestId} onOpenAdvanced={() => setAdvancedOpen(true)}
onFeaturesUpdate={onFeaturesUpdate} />
</Suspense> : undefined} </Suspense> : undefined}
/>; />;
} }
@@ -64,6 +64,19 @@ export function ChannelSetupSurfaceView({
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const mode = setup.mode ?? "credentials"; const mode = setup.mode ?? "credentials";
const hasAdvanced = advancedFields.length > 0 || savedSecretFields.length > 0 || availablePresets.length > 0; 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 const inlineActions = mode === "credentials" && primaryFields.length === 1
&& !advancedOpen && !setup.presets?.length && !setup.actions?.length; && !advancedOpen && !setup.presets?.length && !setup.actions?.length;
const credentialActions = mode === "credentials" ? ( const credentialActions = mode === "credentials" ? (
@@ -243,20 +256,11 @@ export function ChannelSetupSurfaceView({
</div> </div>
{advancedFields.length ? ( {advancedFields.length ? (
<div onBlur={() => void saveConnectionSettings()}> <div onBlur={() => void saveConnectionSettings()}>
<CredentialForm {mode === "connect" ? (
fields={advancedFields} <ChannelFieldGroups {...advancedFormProps} requirements={[]} sectionLabels={setup.sectionLabels} />
values={fieldValues} ) : (
configuredFields={configuredFields} <CredentialForm {...advancedFormProps} compact />
visibleSecrets={visibleSecrets} )}
onChange={setFieldValue}
onFieldBlur={saveSecretOnBlur}
onToggleSecret={toggleSecret}
errors={fieldErrors}
clearedSecrets={clearedSecrets}
onClearSecret={setSecretCleared}
compact
disabled={actionPending}
/>
</div> </div>
) : null} ) : null}
</div> </div>
+3 -2
View File
@@ -5,7 +5,7 @@ import type { ChannelConnectPayload } from "@/lib/types";
import { StatePicker, type ComponentExample } from "./example"; import { StatePicker, type ComponentExample } from "./example";
import { useGalleryTranslation } from "./i18n"; 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]; type ConnectState = typeof connectStates[number];
function QQConnectionPreview() { function QQConnectionPreview() {
@@ -13,7 +13,8 @@ function QQConnectionPreview() {
const [state, setState] = useState<ConnectState>("pending"); const [state, setState] = useState<ConnectState>("pending");
const connect: ChannelConnectPayload | null = state === "idle" || state === "starting" || state === "error" const connect: ChannelConnectPayload | null = state === "idle" || state === "starting" || state === "error"
? null ? 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 <> return <>
<StatePicker label={t("previews.channelConnect.state", { channel: "QQ" })} value={state} options={connectStates} onChange={setState} /> <StatePicker label={t("previews.channelConnect.state", { channel: "QQ" })} value={state} options={connectStates} onChange={setState} />
<QQConnectFlowView connect={connect} busy={state === "starting"} autoStart={state === "starting"} <QQConnectFlowView connect={connect} busy={state === "starting"} autoStart={state === "starting"}
+1
View File
@@ -1330,6 +1330,7 @@ export interface ChannelConnectPayload {
qr_url?: string; qr_url?: string;
interval_ms?: number; interval_ms?: number;
expires_at_ms?: number; expires_at_ms?: number;
retrying?: boolean;
nanobot_features?: NanobotFeaturesPayload; nanobot_features?: NanobotFeaturesPayload;
} }
+11 -7
View File
@@ -239,16 +239,20 @@ it("previews QQ QR states and retries without connecting to the portal", async (
render(<Gallery />); render(<Gallery />);
await screen.findByRole("heading", { name: "QQConnectFlowView · QQ QR connection" }); await screen.findByRole("heading", { name: "QQConnectFlowView · QQ QR connection" });
const preview = within(screen.getByRole("region", { name: "Component preview" })); 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" })); await userEvent.click(preview.getByRole("button", { name: "Cancel" }));
expect(preview.queryByRole("img", { name: "QQ login QR code" })).not.toBeInTheDocument(); expect(preview.queryByRole("img", { name: "QQ binding QR code" })).not.toBeInTheDocument();
await userEvent.click(preview.getByRole("button", { name: "Connect" })); await userEvent.click(preview.getByRole("button", { name: "Bind QQ bot" }));
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("combobox", { name: "QQ connection state" })); await userEvent.click(preview.getByRole("combobox", { name: "QQ connection state" }));
await userEvent.click(screen.getByRole("option", { name: "succeeded" })); await userEvent.click(screen.getByRole("option", { name: "succeeded" }));
expect(preview.getByText("QQ is connected.")).toBeVisible(); expect(preview.getByText("Configured")).toBeVisible();
expect(preview.getByText(/previous App Secret stops working/)).toBeVisible(); expect(preview.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();
expect(preview.getByRole("button", { name: "Scan again" })).toBeVisible(); 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).toHaveBeenCalledTimes(1);
expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components"); expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
}); });
+129
View File
@@ -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();
});
+66 -3
View File
@@ -2114,20 +2114,83 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" }); renderSettingsView({ initialSection: "channels" });
fireEvent.click(await screen.findByRole("button", { name: "View QQ settings" })); 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( expect(requestMutationMock).toHaveBeenCalledWith(
"settings.channel.connect.start", { channel: "qq" }, 150_000, "settings.channel.connect.start", { channel: "qq" }, 150_000,
); );
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith( await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.channel.connect.poll", { channel: "qq", session_id: "qq-1" }, 150_000, "settings.channel.connect.poll", { channel: "qq", session_id: "qq-1" }, 150_000,
)); ));
expect(await screen.findByText("QQ is connected.")).toBeInTheDocument(); expect(await screen.findByText("Configured")).toBeInTheDocument();
expect(screen.getByText(/previous App Secret stops working/)).toBeInTheDocument(); expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
expect(screen.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Advanced" })); fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
expect(screen.getByLabelText("App ID")).toHaveValue("1024"); expect(screen.getByLabelText("App ID")).toHaveValue("1024");
expect(screen.getByLabelText("Acknowledgement message")).toHaveValue("⏳ Processing..."); 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 () => { it("keeps the WebUI websocket channel enabled without opening a setup dialog", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input); const url = String(input);