Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): 扫码连接没成功时,原因留在那张卡片上,不再只活六秒

lmlihengc0e560cb0970
diff --git a/changelog/unreleased/2026-11-05-scan-refusal.md b/changelog/unreleased/2026-11-05-scan-refusal.md
new file mode 100644
index 00000000..89ae7298
--- /dev/null
+++ b/changelog/unreleased/2026-11-05-scan-refusal.md
@@ -0,0 +1,59 @@
+# A scan-to-connect attempt that fails says why on its card, not in a six-second toast
+
+- **Date:** 2026-11-05
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-05-scan-refusal.zh.md)
+
+Both scan-to-connect cards — QQ's and WeChat's — end the same way after a failure: the QR comes down
+(or, for WeChat's pairing code, stays up with its input), the button that asks again is still on
+screen, and the reason arrived as one notification that dismissed itself after six seconds. Six
+seconds later the card was exactly what it had been before the press, and nothing said the button
+had been pressed at all — while that button is precisely the retry.
+
+The reason now stays under the control that asked (`role="alert"`, danger colour, two lines with
+the whole text on hover): under the scan button when the flow could not start or the poll loop gave
+up, and under the pairing-code input when WeChat refused the digits. It is cleared by the next
+attempt — the same button, or a submit — so it always describes the last thing that happened. A
+request that never reached the route now reads its code's own localized sentence instead of the
+server's English wording, the rule the app's other refusal slots already follow.
+
+One answer deliberately keeps its toast: `already_bound`. Nothing failed there, there is nothing to
+retry, and a QR that came down because the bot was already connected is news rather than a fault to
+fix on the card.
+
+## Details
+
+- `packages/web/src/features/messaging/scan-refusal.tsx` (new): `scanStartRefusal(...)` — the
+ sentence for a scan that never started, read through `refusalText`; `scanStopRefusal(...)` — the
+ fault a stop step leaves on the card, or `null` for news; and `ScanRefusalLine`, which both cards
+ draw so the two placements cannot drift apart.
+- `packages/web/src/features/messaging/qq-scan-connect.tsx`: the card gains a `refusal` state,
+ written where the two failures used to `toastError` (a start that was refused, a poll loop that
+ gave up) and cleared by the next start and by cancel; the idle branch draws it under the button.
+ `qqScanStep`'s failed-poll notice goes through `refusalText`.
+- `packages/web/src/features/messaging/wechat-scan-connect.tsx`: the same state for the start and
+ poll failures, plus the pairing code — a refused submit draws the sentence under the input, and
+ the QR stays up because the code is still the thing being authorized. `wechatScanStep`'s
+ failed-poll notice goes through `refusalText`; the `info` tone keeps its toast.
+
+## Tests
+
+- `packages/web/test/scan-refusal.test.ts` (new, 5 cases): a failed request reads through its code
+ rather than the wire message; a client-raised error keeps its message; an empty value falls back
+ to the generic sentence; each channel's own lead-in is used, in the interface language; a fault
+ stays on the card while news returns `null`.
+- `packages/web/e2e/scan-refusal.spec.mjs` (new, real server, real browser, 4 cases): a start the
+ route refuses draws the line under the button, with no notification, and it is still there
+ **seven seconds later**; the second press drops it and shows the code that attempt minted; a poll
+ loop that fails three times takes the code down and leaves the reason (still there after seven
+ seconds); WeChat's refused pairing code draws the line beside its input and editing the digits
+ retires it.
+
+## Compatibility
+
+No interface change, no new dependency, no Project config change. The QQ and WeChat step
+classifiers keep their shapes; only which words a failed poll produces changed, and only for an
+error that is not the server's.
diff --git a/changelog/unreleased/2026-11-05-scan-refusal.zh.md b/changelog/unreleased/2026-11-05-scan-refusal.zh.md
new file mode 100644
index 00000000..1f17f160
--- /dev/null
+++ b/changelog/unreleased/2026-11-05-scan-refusal.zh.md
@@ -0,0 +1,46 @@
+# 扫码连接失败时,原因留在那张卡片上,不再只活六秒
+
+- **日期:** 2026-11-05
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 否
+
+[English](2026-11-05-scan-refusal.md)
+
+两张扫码卡片 —— QQ 的与微信的 —— 失败之后的样子是同一个:二维码撤下来(微信的配对码那一步则是留着、输入
+框还在),能再试一次的按钮仍在屏幕上,而原因只落进一条六秒后自己消失的通知。六秒之后卡片与按键前一样,
+什么都没说这颗按钮被按过 —— 而那颗按钮正是重试。
+
+那句话现在留在发问的那个控件下面(`role="alert"`、危险色、限两行、整句挂悬停):扫码根本起不来或轮询
+放弃时留在扫码按钮下面,微信拒了那组数字时留在配对码输入框下面。它由下一次尝试清掉 —— 同一颗按钮,或再一次
+提交 —— 因此它说的总是最近发生的那件事。请求本身没到服务端时,现在念错误码自己的本地化句子,而不是它的
+线上英文原文 —— 全应用拒绝位早就按这条规则走。
+
+**有一个答复有意仍走通知**:`already_bound`。那里什么都没失败、没有可重试的东西,二维码因为机器人本就绑着
+而撤下来,是消息而不是卡片上要修的毛病。
+
+## 明细
+
+- `packages/web/src/features/messaging/scan-refusal.tsx`(新):`scanStartRefusal(...)` —— 扫码没起来时
+ 那句话,按 `refusalText` 读;`scanStopRefusal(...)` —— 停止那一步该留在卡片上的故障,消息类返回
+ `null`;`ScanRefusalLine` —— 两张卡片共用的那一行,两处画法因此不会各走各的。
+- `packages/web/src/features/messaging/qq-scan-connect.tsx`:卡片多一个 `refusal` 状态,写在原来两处走
+ `toastError` 的失败上(起不来的扫码、放弃的轮询),由下一次开始与「取消」清掉;空闲分支把它画在按钮下面。
+ `qqScanStep` 里轮询失败的措辞改走 `refusalText`。
+- `packages/web/src/features/messaging/wechat-scan-connect.tsx`:开始与轮询的失败同样处理,另加配对码 ——
+ 提交被拒时那句话画在输入框下面,二维码仍留着,因为被授权的还是那个码。`wechatScanStep` 里轮询失败的
+ 措辞改走 `refusalText`;`info` 那一档仍走通知。
+
+## 测试
+
+- `packages/web/test/scan-refusal.test.ts`(新,5 条):没到服务端的请求按错误码读、不念线上原文;客户端
+ 自己抛的错误保留原话;空值退回通用句;每条通道用自己的开场白、用当前语言;故障留在卡片上而消息类返回
+ `null`。
+- `packages/web/e2e/scan-refusal.spec.mjs`(新,真服务端 + 真浏览器,4 条):路由拒掉的开始把句子画在按钮
+ 下面、通知区里没有它,**7 秒后**仍在;第二次按下去它消失、换成那一次生成的二维码;轮询连失败三次后码撤
+ 下来并把原因留下(7 秒后仍在);微信被拒的配对码把句子画在输入框旁边,改动数字后它消失。
+
+## 兼容性
+
+不碰接口、不引入新依赖、不改 Project 配置。QQ 与微信那两个分类函数形状未变,变的只是轮询失败时用谁的措辞,
+而且只对「不是服务端给的」错误生效。
diff --git a/packages/web/e2e/scan-refusal.spec.mjs b/packages/web/e2e/scan-refusal.spec.mjs
new file mode 100644
index 00000000..1f4b53a2
--- /dev/null
+++ b/packages/web/e2e/scan-refusal.spec.mjs
@@ -0,0 +1,294 @@
+/**
+ * Regression: a scan-to-connect attempt that fails says why — on the card, under the control that
+ * asked — instead of leaving the card exactly as it was with the reason in a notification that
+ * dismissed itself after six seconds.
+ *
+ * Both scan flows end the same way after a failure: the QR comes down (or, for WeChat's pairing
+ * code, stays up with its input), the button that asks again is still on screen, and six seconds
+ * later nothing on the card said the button had been pressed at all. The button is the retry, so
+ * the sentence now stays until the next attempt.
+ *
+ * The scan routes are stubbed rather than travelled: what this spec measures is what the page does
+ * with the answer, and a real scan would dial the platform and wait for a phone. The binding is
+ * real — a stored QQ credential is what makes the dialog open on that channel — and the QR URL the
+ * stub hands back points at a name that does not resolve, so nothing here reaches the internet.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+
+/** The row menu action that opens the dialog (`S.messaging.bindAction`). */
+const OPEN = "远程控制";
+/** The scan button, on both channels (`S.qq.scanStart` / `S.wechat.scanStart`). */
+const SCAN = "扫码连接";
+/** The app's own sentence for a failed request (`internal`), not the server's wire message. */
+const FAILED_REQUEST = "服务器内部错误,请稍后重试。";
+/** The line the QQ card draws: its lead-in plus that sentence. */
+const QQ_REFUSED = `扫码连接失败:${FAILED_REQUEST}`;
+/** Never resolved: the code is rendered locally, never fetched. */
+const QR_URL = "https://scan.invalid/authorize?task_id=stub";
+
+/**
+ * Run one action from a Session row's "更多" menu. The trigger is a hover-revealed icon sitting
+ * over the row's own clickable surface: when the click lands a frame before the row has re-laid
+ * itself out, it hits the row (which navigates) and the menu never opens. So the open is retried
+ * and verified — the same helper the two neighbouring messaging specs use.
+ */
+async function pickRowAction(page, row, name) {
+ for (let attempt = 0; attempt < 4; attempt += 1) {
+ await row.hover();
+ await row.getByRole("button", { name: "更多" }).click();
+ const item = page.getByRole("button", { name, exact: true });
+ if (await item.count()) {
+ await item.first().click();
+ return;
+ }
+ await page.keyboard.press("Escape");
+ }
+ throw new Error(`the row menu never offered "${name}"`);
+}
+
+/** Configure the mock model, create one titled conversation and store a QQ credential on it. */
+async function seed(page, projectId, title, appId) {
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ const created = await page.request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { provider: "custom", modelId: "claude-4-8" } },
+ );
+ expect(created.ok(), "create session").toBeTruthy();
+ const sessionId = (await created.json()).session.sessionId;
+
+ const renamed = await page.request.patch(`${BASE}/api/sessions/${sessionId}`, {
+ data: { title },
+ });
+ expect(renamed.ok(), "rename session").toBeTruthy();
+
+ // A stored credential is what makes this session's dialog open on QQ, which is where the scan
+ // block is; the flow under test never reads it.
+ const bound = await page.request.put(`${BASE}/api/sessions/${sessionId}/messaging/qq`, {
+ data: { appId, appSecret: "scan-app-secret" },
+ });
+ expect(bound.ok(), "bind qq").toBeTruthy();
+ return sessionId;
+}
+
+/**
+ * Answer one of the two channels' scan routes. `state.answer` picks the reply — `"fail"` (the
+ * server refusing the start), `"error"`, `"ok"`, `"pending"`, `"verify"` (WeChat's pairing step) or
+ * `"verified"` — and every call is recorded, so a test can count the attempts.
+ *
+ * The globs stop at `/scan`: Playwright's `*` does not cross a slash, so the poll and verify routes
+ * are separate patterns rather than one that would swallow all three.
+ */
+async function stubScan(page, channel, state) {
+ await page.route(`**/api/sessions/*/messaging/${channel}/scan`, async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ state.seen.push(route.request().url());
+ if (state.answer === "fail" || state.answer === "error") {
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: { code: "internal", message: "RAW ENGLISH MESSAGE" } }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ taskId: "stub-task", qrUrl: QR_URL, pollMs: 300 }),
+ });
+ });
+ await page.route(`**/api/sessions/*/messaging/${channel}/scan/poll`, async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ state.polls += 1;
+ if (state.answer === "pending" || state.answer === "verify") {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ status: state.answer === "verify" ? "need_verify_code" : "pending",
+ }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: { code: "internal", message: "RAW ENGLISH MESSAGE" } }),
+ });
+ });
+ await page.route(`**/api/sessions/*/messaging/${channel}/scan/verify`, async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ state.verifies.push(route.request().postDataJSON());
+ await route.fulfill({
+ status: 400,
+ contentType: "application/json",
+ body: JSON.stringify({ error: { code: "internal", message: "RAW ENGLISH MESSAGE" } }),
+ });
+ });
+}
+
+/**
+ * Collect the page's console errors. The dialog's own poll touches `/api/projects/…/machines`,
+ * which answers 403 to anyone but an administrator, and these tests stub 500s on purpose — the
+ * app's normal behaviour for this account and the answer under test — so those are recognised by
+ * status and path and everything else fails.
+ */
+function watchConsole(page) {
+ const errors = [];
+ page.on("console", (msg) => {
+ if (msg.type() !== "error") return;
+ errors.push({ text: msg.text(), url: msg.location()?.url ?? "" });
+ });
+ return {
+ unexpected: () =>
+ errors.filter(({ text, url }) => {
+ const status = /status of (\d{3})/.exec(text)?.[1];
+ if (status === "403" && url.includes("/machines")) return false;
+ if ((status === "500" || status === "400") && url.includes("/messaging/")) return false;
+ return true;
+ }),
+ };
+}
+
+/** Open the binding dialog from the seeded row (it opens on QQ, the only bound channel). */
+async function openDialog(page, title) {
+ await page.goto("/chat");
+ const sidebar = page.getByRole("complementary");
+ const row = sidebar.locator("li", { hasText: title }).first();
+ await expect(row).toBeVisible();
+ await pickRowAction(page, row, OPEN);
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ return dialog;
+}
+
+/** The notification region: a refusal must not be announced there (that is the old toast). */
+const notifications = (page) => page.getByRole("region", { name: "通知" });
+
+test("a scan that cannot start keeps the reason under its button", async ({ page }) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "scanstart", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e scan start ${Date.now()}`;
+ await seed(page, projectId, title, `scan-start-${Date.now()}`);
+
+ const state = { seen: [], polls: 0, verifies: [], answer: "fail" };
+ await stubScan(page, "qq", state);
+ const dialog = await openDialog(page, title);
+
+ await dialog.getByRole("button", { name: SCAN, exact: true }).click();
+
+ // The sentence sits under the button that asked, exactly once, and is not a toast.
+ await expect(dialog.getByRole("alert")).toHaveText(QQ_REFUSED);
+ await expect(dialog.getByRole("alert")).toHaveCount(1);
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+
+ // Six seconds is how long a toast lives; this line has to still be there after it.
+ await page.waitForTimeout(7_000);
+ await expect(dialog.getByRole("alert")).toHaveText(QQ_REFUSED);
+ expect(console_.unexpected()).toEqual([]);
+});
+
+test("the same button is the retry, and its code replaces the sentence", async ({ page }) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "scanretry", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e scan retried ${Date.now()}`;
+ await seed(page, projectId, title, `scan-retried-${Date.now()}`);
+
+ const state = { seen: [], polls: 0, verifies: [], answer: "fail" };
+ await stubScan(page, "qq", state);
+ const dialog = await openDialog(page, title);
+ await dialog.getByRole("button", { name: SCAN, exact: true }).click();
+ await expect(dialog.getByRole("alert")).toHaveText(QQ_REFUSED);
+
+ // Second press, this time the route mints a task: the line goes when the attempt begins, and the
+ // code that attempt produced is what stands there instead.
+ state.answer = "pending";
+ await dialog.getByRole("button", { name: SCAN, exact: true }).click();
+ await expect(dialog.getByRole("alert")).toHaveCount(0);
+ await expect(dialog.getByRole("img", { name: "QQ 机器人授权二维码" })).toBeVisible();
+ expect(state.seen).toHaveLength(2);
+ expect(console_.unexpected()).toEqual([]);
+});
+
+test("a poll loop that gives up says so on the card", async ({ page }) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "scanpoll", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e scan poll ${Date.now()}`;
+ await seed(page, projectId, title, `scan-poll-${Date.now()}`);
+
+ // The start succeeds; every poll fails, and the third one takes the code down.
+ const state = { seen: [], polls: 0, verifies: [], answer: "ok" };
+ await stubScan(page, "qq", state);
+ const dialog = await openDialog(page, title);
+ await dialog.getByRole("button", { name: SCAN, exact: true }).click();
+ await expect(dialog.getByRole("img", { name: "QQ 机器人授权二维码" })).toBeVisible();
+
+ await expect(dialog.getByRole("alert")).toHaveText(QQ_REFUSED, { timeout: 15_000 });
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ // The code was abandoned on the third consecutive failure, not on the first.
+ expect(state.polls).toBeGreaterThanOrEqual(3);
+ // And it stays: the reason outlives the six seconds a toast would have lived.
+ await page.waitForTimeout(7_000);
+ await expect(dialog.getByRole("alert")).toHaveText(QQ_REFUSED);
+ expect(console_.unexpected()).toEqual([]);
+});
+
+test("WeChat's refused pairing code stays beside its input", async ({ page }) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "scanverify", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e scan verify ${Date.now()}`;
+ await seed(page, projectId, title, `scan-verify-${Date.now()}`);
+
+ // WeChat asks for the digits on every poll until they are accepted, so the QR stays up — which is
+ // why this one fault belongs under the input rather than where the button used to be.
+ const state = { seen: [], polls: 0, verifies: [], answer: "verify" };
+ await stubScan(page, "wechat", state);
+ const dialog = await openDialog(page, title);
+ await dialog.getByRole("button", { name: "微信", exact: true }).click();
+ await dialog.getByRole("button", { name: SCAN, exact: true }).click();
+
+ const code = dialog.getByLabel("配对码");
+ await expect(code).toBeVisible();
+ await code.fill("123456");
+ await dialog.getByRole("button", { name: "确认", exact: true }).click();
+
+ await expect(dialog.getByRole("alert")).toHaveText("扫码连接失败:服务器内部错误,请稍后重试。");
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.verifies).toHaveLength(1);
+ // The QR is still up: the code is still the thing being authorized.
+ await expect(dialog.getByRole("img", { name: "微信机器人授权二维码" })).toBeVisible();
+
+ // Editing the digits retires the sentence — it described the ones that were refused.
+ await code.fill("654321");
+ await expect(dialog.getByRole("alert")).toHaveCount(0);
+ expect(console_.unexpected()).toEqual([]);
+});
diff --git a/packages/web/src/features/messaging/qq-scan-connect.tsx b/packages/web/src/features/messaging/qq-scan-connect.tsx
index fef81ab6..77f1d886 100644
--- a/packages/web/src/features/messaging/qq-scan-connect.tsx
+++ b/packages/web/src/features/messaging/qq-scan-connect.tsx
@@ -21,10 +21,11 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { encode } from "uqr";
import type { MessagingBindingInfo, QQBindingInfo, QQScanPollResponse } from "@adelie/server/api";
-import { Button, toastError, toastSuccess } from "@adelie/ui";
+import { Button, toastSuccess } from "@adelie/ui";
import * as api from "../../api/endpoints";
-import { apiErrorText } from "../../lib/api-error";
+import { refusalText } from "../../lib/api-error";
import { S } from "../../lib/strings";
+import { ScanRefusalLine, scanStartRefusal } from "./scan-refusal";
/** Modules of quiet zone around the code — four is what the QR spec asks for. */
const QUIET_ZONE = 4;
@@ -118,7 +119,7 @@ export function qqScanStep(attempt: QQScanAttempt, tally: QQScanTally): QQScanSt
? { kind: "wait" }
: {
kind: "stop",
- notice: S.qq.scanFailed(apiErrorText(attempt.error)),
+ notice: S.qq.scanFailed(refusalText(attempt.error)),
releaseTask: true,
};
}
@@ -150,6 +151,12 @@ export function QQScanConnect({
onBound: (binding: MessagingBindingInfo) => void;
}) {
const [phase, setPhase] = useState<ScanPhase>({ kind: "idle" });
+ /**
+ * Why the last attempt did not get through, until the next one begins. Drawn under the control
+ * that asks again rather than left to a toast: the button beside it is the retry, so the reason
+ * has to outlive the six seconds a notification lives (`scan-refusal.ts`).
+ */
+ const [refusal, setRefusal] = useState<string | null>(null);
/** The task the effects act on, read by the unmount cleanup without re-running it. */
const taskRef = useRef<string | null>(null);
/** Set once the component is going away, so an in-flight poll stops writing state. */
@@ -160,6 +167,8 @@ export function QQScanConnect({
const start = useCallback(
async (refreshed: boolean) => {
setPhase({ kind: "starting" });
+ // A new attempt owns the line: what the previous one said is about a code this one replaces.
+ setRefusal(null);
// A new task starts a fresh failure count; only a scan the USER asked for starts a
// fresh refresh count, or the cap on automatic replacement would never be reached.
tallyRef.current = { failures: 0, refreshes: refreshed ? tallyRef.current.refreshes : 0 };
@@ -183,7 +192,7 @@ export function QQScanConnect({
if (goneRef.current) return;
taskRef.current = null;
setPhase({ kind: "idle" });
- toastError(S.qq.scanFailed(apiErrorText(e)));
+ setRefusal(scanStartRefusal(S.qq.scanFailed, e));
}
},
[sessionId],
@@ -192,6 +201,8 @@ export function QQScanConnect({
const stop = useCallback(() => {
const taskId = taskRef.current;
taskRef.current = null;
+ // Cancelling abandons the attempt, so the reason it failed goes with it.
+ setRefusal(null);
setPhase({ kind: "idle" });
if (taskId !== null) void api.cancelQQScan(sessionId, taskId).catch(() => {});
}, [sessionId]);
@@ -236,7 +247,9 @@ export function QQScanConnect({
// live: it is released here the way cancel and unmount release one, rather than left
// holding its key until the sweep.
if (step.releaseTask) void api.cancelQQScan(sessionId, taskId).catch(() => {});
- toastError(step.notice);
+ // Every one of QQ's stops is a fault — the code came down with nothing to show for it —
+ // and the card now stands in front of its own button again, so the reason stays there.
+ setRefusal(step.notice);
})();
}, pollMs);
return () => {
@@ -265,7 +278,7 @@ export function QQScanConnect({
// once, then in the way forever — so it is disclosed in the setup fold rather than
// standing beside the button: a control is not a title for a sentence.
return (
- <div>
+ <div className="space-y-1.5">
<Button
size="sm"
disabled={phase.kind === "starting" || enabled}
@@ -274,6 +287,8 @@ export function QQScanConnect({
>
{phase.kind === "starting" ? S.qq.scanStarting : S.qq.scanStart}
</Button>
+ {/* Under the button that asked, because that button is the retry. */}
+ {refusal !== null && <ScanRefusalLine text={refusal} />}
</div>
);
}
diff --git a/packages/web/src/features/messaging/scan-refusal.tsx b/packages/web/src/features/messaging/scan-refusal.tsx
new file mode 100644
index 00000000..ce6f0dc0
--- /dev/null
+++ b/packages/web/src/features/messaging/scan-refusal.tsx
@@ -0,0 +1,66 @@
+/**
+ * The scan-to-connect block's one refusal line: which answers get drawn on the card instead of
+ * arriving as a toast, and what the sentence says when the request never got through.
+ *
+ * Both cards (`qq-scan-connect.tsx`, `wechat-scan-connect.tsx`) look the same after a failure —
+ * the QR comes down, or for WeChat's pairing code it stays up with the input still showing — and
+ * the control that asks again is still on screen. A toast is the only place the reason used to
+ * appear, and after six seconds the card was exactly what it had been before the press, with the
+ * same button and no word about what happened. So a fault stays under the control that caused it,
+ * until the next attempt: the button itself is the retry.
+ *
+ * Three answers are faults. A scan that could not even start (the request failed), a poll loop
+ * that gave up after repeated failures, and WeChat's pairing code being refused. `already_bound`
+ * is not one of them: nothing failed, there is nothing to retry, and a QR that came down because
+ * the bot was already connected is news — it keeps its toast, the way every connecting answer in
+ * this app does.
+ */
+import { refusalText } from "../../lib/api-error";
+import { toneInk } from "../../lib/tone";
+
+/**
+ * The line for a scan that never started, built from the request's own error.
+ *
+ * `refusalText` rather than `apiErrorText`: that is the rule every refusal slot in the app
+ * follows (7.19) — a request that never reached the server is answered with its code's own
+ * localized sentence, and a value this codebase raised itself is shown as it wrote it. The scan
+ * can stop before a request is sent (a channel already gated, a task minted elsewhere), so the
+ * sentence has to survive an error that is not the server's.
+ */
+export function scanStartRefusal(failed: (detail: string) => string, error: unknown): string {
+ return failed(refusalText(error));
+}
+
+/** What a stop step carries, as far as this decision is concerned — either card's shape fits. */
+export interface ScanStopNotice {
+ readonly notice: string;
+ /** Absent on QQ, whose every stop is a fault; only WeChat's `already_bound` is news. */
+ readonly tone?: "error" | "info";
+}
+
+/**
+ * The line to keep on the card for a stop step, or `null` when the step is news and the caller
+ * should still hand it to a toast. The tone is optional because QQ's stops have no other kind.
+ */
+export function scanStopRefusal(step: ScanStopNotice): string | null {
+ return (step.tone ?? "error") === "error" ? step.notice : null;
+}
+
+/**
+ * The line itself, under whichever control asked: `role="alert"` so it is announced when it
+ * arrives (a toast was announced once and then left), `line-clamp-2` so a long platform sentence
+ * cannot push the fields around, and the whole text on hover — the shape every other refusal slot
+ * in the app has. Both cards draw it, and sharing it keeps the two from drifting apart.
+ */
+export function ScanRefusalLine({ text }: { text: string }) {
+ return (
+ <p
+ role="alert"
+ data-tooltip={text}
+ data-tooltip-content="text"
+ className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}
+ >
+ {text}
+ </p>
+ );
+}
diff --git a/packages/web/src/features/messaging/wechat-scan-connect.tsx b/packages/web/src/features/messaging/wechat-scan-connect.tsx
index 08eed940..c65002a6 100644
--- a/packages/web/src/features/messaging/wechat-scan-connect.tsx
+++ b/packages/web/src/features/messaging/wechat-scan-connect.tsx
@@ -30,11 +30,12 @@ import type {
WeChatBindingInfo,
WeChatScanPollResponse,
} from "@adelie/server/api";
-import { Button, Input, toastError, toastInfo, toastSuccess } from "@adelie/ui";
+import { Button, Input, toastInfo, toastSuccess } from "@adelie/ui";
import * as api from "../../api/endpoints";
-import { apiErrorText } from "../../lib/api-error";
+import { refusalText } from "../../lib/api-error";
import { S } from "../../lib/strings";
import { QrCode } from "./qq-scan-connect";
+import { ScanRefusalLine, scanStartRefusal, scanStopRefusal } from "./scan-refusal";
/**
* Consecutive poll failures ridden out before the code comes down. The interval fires
@@ -94,7 +95,7 @@ export function wechatScanStep(attempt: WeChatScanAttempt, tally: WeChatScanTall
? { kind: "wait" }
: {
kind: "stop",
- notice: S.wechat.scanFailed(apiErrorText(attempt.error)),
+ notice: S.wechat.scanFailed(refusalText(attempt.error)),
tone: "error",
releaseTask: true,
};
@@ -155,6 +156,13 @@ export function WeChatScanConnect({
const [phase, setPhase] = useState<ScanPhase>({ kind: "idle" });
const [verifyCode, setVerifyCode] = useState("");
const [verifying, setVerifying] = useState(false);
+ /**
+ * Why the last attempt did not get through, until the next one begins. Drawn on this card —
+ * under the button when the code came down, under the pairing-code input when a number was
+ * refused — rather than left to a toast: the control beside it is the retry, so the reason has
+ * to outlive the six seconds a notification lives (`scan-refusal.ts`).
+ */
+ const [refusal, setRefusal] = useState<string | null>(null);
/** The task the effects act on, read by the unmount cleanup without re-running it. */
const taskRef = useRef<string | null>(null);
/** Set once the component is going away, so an in-flight poll stops writing state. */
@@ -166,6 +174,8 @@ export function WeChatScanConnect({
async (refreshed: boolean) => {
setPhase({ kind: "starting" });
setVerifyCode("");
+ // A new attempt owns the line: what the previous one said is about a code this one replaces.
+ setRefusal(null);
// A new code starts a fresh failure count; only a scan the USER asked for starts a
// fresh refresh count, or the cap on automatic replacement would never be reached.
tallyRef.current = { failures: 0, refreshes: refreshed ? tallyRef.current.refreshes : 0 };
@@ -190,7 +200,7 @@ export function WeChatScanConnect({
if (goneRef.current) return;
taskRef.current = null;
setPhase({ kind: "idle" });
- toastError(S.wechat.scanFailed(apiErrorText(e)));
+ setRefusal(scanStartRefusal(S.wechat.scanFailed, e));
}
},
[sessionId],
@@ -199,6 +209,8 @@ export function WeChatScanConnect({
const stop = useCallback(() => {
const taskId = taskRef.current;
taskRef.current = null;
+ // Cancelling abandons the attempt, so the reason it failed goes with it.
+ setRefusal(null);
setPhase({ kind: "idle" });
if (taskId !== null) void api.cancelWeChatScan(sessionId, taskId).catch(() => {});
}, [sessionId]);
@@ -249,8 +261,11 @@ export function WeChatScanConnect({
// A run of failed polls says nothing about the server, so the task may well still be
// live: it is released here the way cancel and unmount release one.
if (step.releaseTask) void api.cancelWeChatScan(sessionId, taskId).catch(() => {});
- if (step.tone === "info") toastInfo(step.notice);
- else toastError(step.notice);
+ // A fault stays on the card under the control that asks again; `already_bound` is news
+ // (nothing failed, nothing to retry) and keeps the toast every connecting answer uses.
+ const fault = scanStopRefusal(step);
+ if (fault !== null) setRefusal(fault);
+ else toastInfo(step.notice);
})();
}, pollMs);
return () => {
@@ -278,13 +293,17 @@ export function WeChatScanConnect({
const code = verifyCode.trim();
if (code === "") return;
setVerifying(true);
+ // A fresh submit owns the line; what the previous digits got wrong is history now.
+ setRefusal(null);
try {
await api.verifyWeChatScan(sessionId, taskId, code);
// Cleared on submit rather than on acceptance: the platform reports a wrong code by
// asking again, and leaving the rejected digits in the box would read as accepted.
setVerifyCode("");
} catch (e) {
- toastError(S.wechat.scanFailed(apiErrorText(e)));
+ // The QR stays up: the code is still the thing being authorized, so the reason for the
+ // refused digits belongs beside the input rather than in a toast that outlives nothing.
+ setRefusal(scanStartRefusal(S.wechat.scanFailed, e));
} finally {
setVerifying(false);
}
@@ -292,7 +311,7 @@ export function WeChatScanConnect({
if (phase.kind !== "waiting") {
return (
- <div>
+ <div className="space-y-1.5">
<Button
size="sm"
disabled={phase.kind === "starting" || enabled}
@@ -305,6 +324,10 @@ export function WeChatScanConnect({
? S.wechat.scanRescan
: S.wechat.scanStart}
</Button>
+ {/* Under the button that asked, because that button is the retry: `line-clamp-2` keeps a
+ long platform sentence from pushing the fields down, and the whole text is on hover,
+ the way every other refusal slot in the app carries its longer form. */}
+ {refusal !== null && <ScanRefusalLine text={refusal} />}
</div>
);
}
@@ -333,7 +356,11 @@ export function WeChatScanConnect({
size="sm"
aria-label={S.wechat.verifyLabel}
value={verifyCode}
- onChange={(e) => setVerifyCode(e.target.value)}
+ onChange={(e) => {
+ setVerifyCode(e.target.value);
+ // The sentence is about the digits that were refused; editing them retires it.
+ setRefusal(null);
+ }}
className="w-28 font-mono"
inputMode="numeric"
autoComplete="off"
@@ -346,6 +373,9 @@ export function WeChatScanConnect({
) : (
<p>{S.wechat.scanSteps}</p>
)}
+ {/* A refused pairing code is the one fault the card can show while the QR is still up:
+ the input above stays, so the reason sits under it. */}
+ {needsCode && refusal !== null && <ScanRefusalLine text={refusal} />}
{/* Only shown once a code has actually lapsed: a standing note that codes expire is
noise until one does. */}
{phase.refreshed && (
diff --git a/packages/web/test/scan-refusal.test.ts b/packages/web/test/scan-refusal.test.ts
new file mode 100644
index 00000000..5910728c
--- /dev/null
+++ b/packages/web/test/scan-refusal.test.ts
@@ -0,0 +1,74 @@
+/**
+ * The scan-to-connect card's refusal line (src/features/messaging/scan-refusal.tsx): which of the
+ * flow's answers go on the card, and whose words the sentence uses.
+ *
+ * A failed scan changes nothing else on the card — the code comes down (or WeChat's pairing-code
+ * input stays up) and the button that asks again is still there — so this line is the only thing
+ * that accounts for the failure once the six-second toast is gone. The cases below are the three
+ * shapes a failed request comes in, the two channels' own lead-ins, and the one answer that is
+ * news rather than a fault.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { en as EN } from "../src/lib/strings-en";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { scanStartRefusal, scanStopRefusal } from "../src/features/messaging/scan-refusal";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+describe("scanStartRefusal", () => {
+ it("reads a failed request through its code, so the line is the localized one", () => {
+ // The scan route answers a platform it cannot reach with its own code; the server's message is
+ // English whatever the interface language is.
+ const refused = scanStartRefusal(
+ S.qq.scanFailed,
+ new ApiError(502, "internal", "RAW ENGLISH SERVER MESSAGE"),
+ );
+ expect(refused).toBe(S.qq.scanFailed(S.errors.byCode["internal"] as string));
+ expect(refused).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ });
+
+ it("keeps the message of an error the client itself raised", () => {
+ // `refusalText`'s rule: only an ApiError goes through the code table; anything else with
+ // something to say is shown as it is, not as "unknown".
+ expect(scanStartRefusal(S.qq.scanFailed, new Error("network down"))).toBe(
+ S.qq.scanFailed("network down"),
+ );
+ expect(scanStartRefusal(S.qq.scanFailed, undefined)).toBe(
+ S.qq.scanFailed(S.common.unknownError),
+ );
+ });
+
+ it("speaks each channel's own lead-in, in the interface language", () => {
+ const error = new Error("network down");
+ // The two cards say the same thing in their own words, which is why the sentence comes in as
+ // the channel's builder rather than from a table here. (In Chinese the two lead-ins happen to
+ // read alike; in English they do not, so the difference is asserted where it exists.)
+ expect(scanStartRefusal(S.wechat.scanFailed, error)).toBe(S.wechat.scanFailed("network down"));
+ setActiveStrings(EN);
+ expect(scanStartRefusal(S.qq.scanFailed, error)).toBe("Scan-to-connect failed: network down");
+ expect(scanStartRefusal(S.wechat.scanFailed, error)).toBe(
+ "Connecting by scan failed: network down",
+ );
+ });
+});
+
+describe("scanStopRefusal", () => {
+ it("keeps a fault on the card", () => {
+ // QQ's stops carry no tone at all: every one of them is a code that came down for nothing.
+ expect(scanStopRefusal({ notice: S.qq.scanExpiredRepeatedly })).toBe(
+ S.qq.scanExpiredRepeatedly,
+ );
+ expect(scanStopRefusal({ notice: S.wechat.scanBlocked, tone: "error" })).toBe(
+ S.wechat.scanBlocked,
+ );
+ });
+
+ it("leaves news to the toast", () => {
+ // Nothing failed and there is nothing to retry: the bot was already connected, and a line
+ // under the button would read as a fault to fix.
+ expect(scanStopRefusal({ notice: S.wechat.scanAlreadyBound, tone: "info" })).toBeNull();
+ });
+});