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:
1 parent
51a0fc83a2
commit
130f4edefe
27 files changed
+634
-168
No files matched your search
@@ -34,6 +34,7 @@ export type ChannelPluginConnectFlowProps = {
|
||||
feature: NanobotFeatureInfo;
|
||||
idleLabel?: string;
|
||||
connectRequestId?: number;
|
||||
onOpenAdvanced?: () => void;
|
||||
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
||||
};
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}
|
||||
>
|
||||
|
||||
@@ -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 ? (
|
||||
<Button
|
||||
type="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}
|
||||
/>;
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -1330,6 +1330,7 @@ export interface ChannelConnectPayload {
|
||||
qr_url?: string;
|
||||
interval_ms?: number;
|
||||
expires_at_ms?: number;
|
||||
retrying?: boolean;
|
||||
nanobot_features?: NanobotFeaturesPayload;
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user