fix(feishu): restore assistant creation and pairing recovery

Refs NAN-239
This commit is contained in:
Xubin Ren committed 2026-10-12 17:38:43 +08:00
1 parent cfb0f51e78
commit 2aa98677c6
36 files changed
+369 -47

No files matched your search

+65 -36
View File
@@ -626,9 +626,14 @@ function PairingCodePopup({
() => requests.find((request) => request.code === normalizedCode) ?? null,
[normalizedCode, requests],
);
const firstRequest = requests[0] ?? null;
// Keep delivered and legacy requests usable even when another bot cannot reply.
const firstRequest = requests.find((request) => (
!request.delivery_status || request.delivery_status === "sent"
)) ?? requests[0] ?? null;
const displayRequest = matchedRequest ?? firstRequest;
const expires = formatPairingExpiry(firstRequest?.expires_in_seconds);
const deliveryBlocked = displayRequest?.delivery_status === "failed"
|| displayRequest?.delivery_status === "sending";
const expires = formatPairingExpiry(displayRequest?.expires_in_seconds);
const isCompleteCode = normalizedCode.length === 9;
const showNoMatch = isCompleteCode && !matchedRequest && !busyCode;
@@ -643,6 +648,17 @@ function PairingCodePopup({
if (!firstRequest) return null;
const codeInput = (
<PairingCodeSlots
value={value}
disabled={Boolean(busyCode)}
matched={Boolean(matchedRequest)}
invalid={showNoMatch}
ariaLabel={t("app.pairing.code", { defaultValue: "Pairing code" })}
onChange={(next) => setValue(formatPairingCodeInput(next))}
/>
);
return (
<div
role="dialog"
@@ -664,8 +680,15 @@ function PairingCodePopup({
<p className="text-[15px] font-semibold tracking-[-0.01em]">
{t("app.pairing.title", { defaultValue: "Pair a chat user" })}
</p>
<p className="mt-1 text-[13px] leading-5 text-muted-foreground">
{t("app.pairing.description", {
<p
className="mt-1 text-pretty text-[13px] leading-5 text-muted-foreground"
role={displayRequest.delivery_status === "failed" ? "alert" : undefined}
>
{displayRequest.delivery_status === "failed" ? t("app.pairing.deliveryFailed", {
defaultValue: "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.",
}) : displayRequest.delivery_status === "sending" ? t("app.pairing.deliverySending", {
defaultValue: "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.",
}) : t("app.pairing.description", {
defaultValue: "Enter the pairing code shown in the chat.",
})}
</p>
@@ -673,46 +696,52 @@ function PairingCodePopup({
<button
type="button"
aria-label={t("common.close", { defaultValue: "Close" })}
onClick={() => onDismiss(firstRequest.code)}
onClick={() => onDismiss(displayRequest.code)}
className="rounded-full p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
>
<X className="h-4 w-4" aria-hidden />
</button>
</div>
<label className="mt-4 block text-[12.5px] font-medium text-foreground">
{t("app.pairing.code", { defaultValue: "Pairing code" })}
</label>
<PairingCodeSlots
value={value}
disabled={Boolean(busyCode)}
matched={Boolean(matchedRequest)}
invalid={showNoMatch}
ariaLabel={t("app.pairing.code", { defaultValue: "Pairing code" })}
onChange={(next) => setValue(formatPairingCodeInput(next))}
/>
{deliveryBlocked ? (
<details className="mt-3 text-[12.5px] text-muted-foreground">
<summary className="cursor-pointer">
{t("app.pairing.haveCode", { defaultValue: "Already received a code?" })}
</summary>
{codeInput}
</details>
) : (
<>
<label className="mt-4 block text-[12.5px] font-medium text-foreground">
{t("app.pairing.code", { defaultValue: "Pairing code" })}
</label>
{codeInput}
</>
)}
<div className="mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground">
<span>
{matchedRequest
? t("app.pairing.matched", {
defaultValue: "Matched {{channel}}. Connecting...",
channel: channelLabel(matchedRequest.channel),
})
: t("app.pairing.expiresInline", {
defaultValue: "Code expires {{expires}}.",
expires,
})}
</span>
{total > 1 ? (
<span className="shrink-0">
{t("app.pairing.queueCount", {
defaultValue: "{{count}} pending",
count: total,
})}
{!deliveryBlocked || total > 1 ? (
<div className="mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground">
<span>
{matchedRequest
? t("app.pairing.matched", {
defaultValue: "Matched {{channel}}. Connecting...",
channel: channelLabel(matchedRequest.channel),
})
: deliveryBlocked ? null : t("app.pairing.expiresInline", {
defaultValue: "Code expires {{expires}}.",
expires,
})}
</span>
) : null}
</div>
{total > 1 ? (
<span className="shrink-0">
{t("app.pairing.queueCount", {
defaultValue: "{{count}} pending",
count: total,
})}
</span>
) : null}
</div>
) : null}
{showNoMatch ? (
<p className="mt-2 text-[12px] leading-5 text-destructive">
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot web UI — chat with your nanobot workspace."
},
"pairing": {
"haveCode": "Already received a code?",
"deliveryFailed": "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.",
"deliverySending": "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.",
"title": "Pair account",
"description": "Enter the pairing code received in chat.",
"code": "Pairing code",
+3
View File
@@ -339,6 +339,9 @@
"description": "Interfaz web de nanobot: conversa con tu espacio de trabajo de nanobot."
},
"pairing": {
"haveCode": "¿Ya recibiste un código?",
"deliveryFailed": "No se pudo enviar el código. Revisa los permisos de envío del bot y los registros de la pasarela. Después, envíale otro mensaje privado para reintentar.",
"deliverySending": "Enviando el código al chat. Si no llega, envía otro mensaje privado al bot para reintentar.",
"title": "Vincular cuenta",
"description": "Introduce el código de vinculación recibido en el chat.",
"code": "Código de vinculación",
+3
View File
@@ -339,6 +339,9 @@
"description": "Interface web nanobot — discutez avec votre espace de travail nanobot."
},
"pairing": {
"haveCode": "Vous avez déjà reçu un code ?",
"deliveryFailed": "Impossible d’envoyer le code. Vérifiez les autorisations d’envoi du bot et les journaux de la passerelle, puis envoyez-lui un autre message privé pour réessayer.",
"deliverySending": "Envoi du code dans votre conversation. Si vous ne le recevez pas, envoyez un autre message privé au bot pour réessayer.",
"title": "Associer un compte",
"description": "Saisissez le code d’association reçu dans la discussion.",
"code": "Code d’association",
+3
View File
@@ -339,6 +339,9 @@
"description": "UI web nanobot — ngobrol dengan ruang kerja nanobot Anda."
},
"pairing": {
"haveCode": "Sudah menerima kode?",
"deliveryFailed": "Kode tidak dapat dikirim. Periksa izin pengiriman pesan bot dan log gateway, lalu kirim pesan pribadi lagi untuk mencoba ulang.",
"deliverySending": "Mengirim kode ke obrolan Anda. Jika belum diterima, kirim pesan pribadi lagi ke bot untuk mencoba ulang.",
"title": "Pasangkan akun",
"description": "Masukkan kode pemasangan yang diterima di chat.",
"code": "Kode pairing",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot Web UI — nanobot ワークスペースと会話します。"
},
"pairing": {
"haveCode": "コードを受け取りましたか?",
"deliveryFailed": "ペアリングコードを送信できませんでした。ボットのメッセージ送信権限とゲートウェイのログを確認し、もう一度ボットにダイレクトメッセージを送ってください。",
"deliverySending": "チャットにペアリングコードを送信しています。届かない場合は、もう一度ボットにダイレクトメッセージを送ってください。",
"title": "アカウント連携",
"description": "チャットで受け取った連携コードを入力します。",
"code": "ペアリングコード",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot 웹 UI — nanobot 작업공간과 대화하세요."
},
"pairing": {
"haveCode": "이미 코드를 받으셨나요?",
"deliveryFailed": "페어링 코드를 보내지 못했습니다. 봇의 메시지 전송 권한과 게이트웨이 로그를 확인한 후, 봇에게 개인 메시지를 다시 보내세요.",
"deliverySending": "채팅으로 페어링 코드를 보내고 있습니다. 코드가 도착하지 않으면 봇에게 개인 메시지를 다시 보내세요.",
"title": "계정 연결",
"description": "채팅에서 받은 연결 코드를 입력하세요.",
"code": "연결 코드",
+3
View File
@@ -339,6 +339,9 @@
"description": "Interface web do nanobot — converse com o seu espaço de trabalho do nanobot."
},
"pairing": {
"haveCode": "Já recebeu um código?",
"deliveryFailed": "Não foi possível enviar o código. Verifique as permissões de envio do bot e os logs do gateway. Depois, envie outra mensagem privada para tentar novamente.",
"deliverySending": "Enviando o código ao chat. Se ele não chegar, envie outra mensagem privada ao bot para tentar novamente.",
"title": "Parear conta",
"description": "Digite o código de pareamento recebido na conversa.",
"code": "Código de vinculação",
+3
View File
@@ -339,6 +339,9 @@
"description": "Giao diện web nanobot — trò chuyện với không gian làm việc nanobot của bạn."
},
"pairing": {
"haveCode": "Bạn đã nhận được mã?",
"deliveryFailed": "Không thể gửi mã ghép nối. Hãy kiểm tra quyền gửi tin nhắn của bot và nhật ký gateway, rồi gửi thêm một tin nhắn riêng để thử lại.",
"deliverySending": "Đang gửi mã ghép nối đến cuộc trò chuyện. Nếu chưa nhận được, hãy gửi thêm một tin nhắn riêng cho bot để thử lại.",
"title": "Ghép tài khoản",
"description": "Nhập mã ghép nhận được trong cuộc trò chuyện.",
"code": "Mã liên kết",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot Web UI —— 与你的 nanobot 工作区对话。"
},
"pairing": {
"haveCode": "已收到配对码?",
"deliveryFailed": "配对码发送失败。请检查此机器人的消息发送权限和网关日志,再给它发一条私聊消息重试。",
"deliverySending": "正在向聊天发送配对码。如果没有收到,请再给机器人发一条私聊消息重试。",
"title": "账号配对",
"description": "输入聊天平台收到的配对码",
"code": "配对码",
+3
View File
@@ -339,6 +339,9 @@
"description": "nanobot Web UI —— 與你的 nanobot 工作區對話。"
},
"pairing": {
"haveCode": "已收到配對碼?",
"deliveryFailed": "配對碼傳送失敗。請檢查此機器人的訊息傳送權限和閘道日誌,再傳一則私訊給它以重試。",
"deliverySending": "正在向聊天傳送配對碼。如果沒有收到,請再傳一則私訊給機器人以重試。",
"title": "賬號配對",
"description": "輸入聊天平臺收到的配對碼",
"code": "配對碼",
+1
View File
@@ -1197,6 +1197,7 @@ export interface PairingRequestInfo {
created_at_ms?: number | null;
expires_at_ms?: number | null;
expires_in_seconds?: number | null;
delivery_status?: "sending" | "sent" | "failed";
}
export interface PairingPayload {
+26
View File
@@ -4063,6 +4063,32 @@ describe("App layout", () => {
unmount();
});
it.each(["sending", "failed"])("explains an undelivered pairing reply (%s) without empty code slots", async (delivery_status) => {
mockFetchRoutes({ "/api/settings/pairing": { requests: [{
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status,
}] } });
render(<App />);
const popup = await screen.findByRole("dialog", { name: "Pair account" });
expect(within(popup).getByText("Already received a code?").closest("details")).not.toHaveAttribute("open");
expect(within(popup).getByText(/another private message to retry/)).toBeVisible();
if (delivery_status === "failed") expect(within(popup).getByRole("alert")).toBeVisible();
fireEvent.click(within(popup).getByText("Already received a code?"));
expect(within(popup).getByRole("textbox", { name: "Pairing code" })).toBeEnabled();
expect(requestMutationSpy).not.toHaveBeenCalledWith("settings.pairing.approve", expect.anything(), expect.anything());
});
it.each([undefined, "sent"])("keeps legacy/delivered pairing usable behind a failed request (%s)", async (delivery_status) => {
mockFetchRoutes({ "/api/settings/pairing": { requests: [
{ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "failed" },
{ code: "IJKL-MNOP", channel: "feishu.second", sender_id: "bob", delivery_status },
] } });
render(<App />);
const popup = await screen.findByRole("dialog", { name: "Pair account" });
expect(within(popup).getByRole("textbox", { name: "Pairing code" })).toBeEnabled();
expect(within(popup).queryByRole("alert")).not.toBeInTheDocument();
expect(within(popup).getByText("2 pending")).toBeVisible();
});
it("reuses an in-flight pairing poll when the page becomes visible again", async () => {
let resolvePairing!: (response: Response) => void;
const pendingPairing = new Promise<Response>((resolve) => {
@@ -4,6 +4,8 @@ import QRCode from "qrcode";
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
import { FeishuConnectFlow } from "../../../nanobot/channels/feishu/webui/FeishuConnectFlow";
import { FeishuAssistantsPanel } from "../../../nanobot/channels/feishu/webui/FeishuAssistantsPanel";
import type { NanobotFeatureInfo } from "@/lib/types";
const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));
@@ -34,6 +36,53 @@ beforeEach(() => {
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
describe("channel QR connect parameters", () => {
it("adds an assistant without replacing existing ones, and supports cancellation and retry", async () => {
const feature: NanobotFeatureInfo = {
name: "feishu", display_name: "Feishu", type: "channel", webui: "webui/index.tsx",
enabled: true, configured: true, installed: true, ready: true, status: "enabled",
install_supported: true, requires_restart: false,
instances: [{
id: "default", name: "First assistant", enabled: true, configured: true,
runtime_status: "running", config_values: {}, configured_fields: [],
}],
};
const onFeaturesUpdate = vi.fn();
const props = { token: "tok", feature, showBrandLogos: false, onFeaturesUpdate };
const view = render(<FeishuAssistantsPanel {...props} />);
requestMutation.mockResolvedValueOnce({
session_id: "add-1", status: "pending", qr_url: "https://example.com/authorize",
});
fireEvent.click(screen.getByRole("button", { name: "Add another assistant" }));
expect(await screen.findByText("Scan with Feishu")).toBeVisible();
expect(requestMutation).toHaveBeenCalledWith("settings.channel.connect.start", {
channel: "feishu", domain: "feishu", instance_id: "default", mode: "create",
}, 150_000);
expect(screen.getByText("First assistant")).toBeVisible();
requestMutation.mockResolvedValueOnce({ session_id: "add-1", status: "cancelled" });
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
await screen.findByRole("button", { name: "Add another assistant" });
expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.cancel", {
channel: "feishu", session_id: "add-1",
}, 20_000);
expect(onFeaturesUpdate).not.toHaveBeenCalled();
requestMutation.mockRejectedValueOnce(new Error("Authorization unavailable"));
fireEvent.click(screen.getByRole("button", { name: "Add another assistant" }));
expect(await screen.findByText("Authorization unavailable")).toBeVisible();
const updated = { ...feature, instances: [...feature.instances!, {
...feature.instances![0], id: "assistant-new", name: "Second assistant",
}] };
const payload = { features: [updated], enabled_count: 1 };
requestMutation.mockResolvedValueOnce({ status: "succeeded", nanobot_features: payload });
fireEvent.click(screen.getByRole("button", { name: "Add another assistant" }));
await waitFor(() => expect(onFeaturesUpdate).toHaveBeenCalledWith(payload));
view.rerender(<FeishuAssistantsPanel {...props} feature={updated} />);
expect(screen.getByText("First assistant")).toBeVisible();
expect(screen.getByText("Second assistant")).toBeVisible();
expect(screen.getByRole("button", { name: "Add another assistant" })).toBeEnabled();
expect(screen.queryByText("Authorization unavailable")).not.toBeInTheDocument();
});
it.each([false, true])("keeps QR generation enabled by default (minimal=%s)", async (minimalPending) => {
const generateQr = vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,preview");
requestMutation.mockResolvedValueOnce({