Skip to content

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

fix(web): 凭据探测没通过时,原因留在「测试连接」按钮下面,不再只活六秒

lmliheng9647c368cb50
diff --git a/changelog/unreleased/2026-11-05-messaging-test-refusal.md b/changelog/unreleased/2026-11-05-messaging-test-refusal.md
new file mode 100644
index 00000000..ff58abc4
--- /dev/null
+++ b/changelog/unreleased/2026-11-05-messaging-test-refusal.md
@@ -0,0 +1,53 @@
+# A messaging credential probe that did not get through says why under its button, not in a six-second toast
+
+- **Date:** 2026-11-05
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-05-messaging-test-refusal.zh.md)
+
+The messaging card's "test connection" button runs the selected channel's current — still unsaved —
+values through the server's credential probe, which saves nothing. When the probe was refused
+(Telegram rejecting the token, a Feishu base domain that does not dial, WeChat's stored bot token
+gone stale), the card looked exactly as it did before the press while the reason arrived as one
+notification that dismissed itself after six seconds — and the App ID, the secret and the base
+domain that sentence is about are the fields right below it.
+
+That sentence now sits under the probe buttons (`role="alert"`, danger colour, two lines with the
+whole text on hover) and stays until the form is edited, the channel is switched or the next probe
+starts — the same button is the retry. A probe that *connects* keeps its toast (the latency,
+Telegram's bot name and its Group Privacy caveat): that outcome leaves nothing behind to explain.
+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.
+
+## Details
+
+- `packages/web/src/features/messaging/messaging-test-refusal.ts` (new): `messagingTestRefusal(...)`
+ — the pure decision, so which sentence appears is in one place and testable without the card.
+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`: the hook gains a `testRefusal`
+ state, written by the probe's failed branch (which used to `toastError`) and cleared by a form
+ edit, a channel switch, a session swap and the start of the next probe; the card renders it below
+ the two probe buttons, above the gating hint. The four per-channel probe calls collapse into one
+ answer shape, and only the connecting branch differs (Telegram's notices stay as they were).
+
+## Tests
+
+- `packages/web/test/messaging-test-refusal.test.ts` (new, 6 cases): a connecting answer leaves
+ nothing; the platform's detail is carried verbatim; no detail falls back to the generic sentence;
+ a failed request reads through `refusalText` (not the wire message); a client-raised error keeps
+ its message; the active language is the one used.
+- `packages/web/test/messaging-binding-editor.test.ts`: one case for the rendered card — the line
+ appears once, between the probe button and the credential fields, bounded and with the whole
+ sentence on hover, and nothing when no probe was refused.
+- `packages/web/e2e/messaging-test-refusal.spec.mjs` (new, real server, real browser): bind Feishu
+ to a conversation, stub the probe route. A refused answer draws the line and no notification, and
+ it is still there **seven seconds later**; editing a field drops it and the retried probe (now
+ connecting) carries the edited value and toasts its numbers; a 500 on the route draws the code's
+ own sentence.
+
+## Compatibility
+
+No interface change, no new dependency, no Project config change. The other button beside the probe
+("send test message") keeps its toast: what its failure asks the reader to change lives in the chat
+platform, not in a field on this card.
diff --git a/changelog/unreleased/2026-11-05-messaging-test-refusal.zh.md b/changelog/unreleased/2026-11-05-messaging-test-refusal.zh.md
new file mode 100644
index 00000000..ab0ce96c
--- /dev/null
+++ b/changelog/unreleased/2026-11-05-messaging-test-refusal.zh.md
@@ -0,0 +1,43 @@
+# 消息绑定卡片的凭据探测没通过时,原因留在按钮下面,不再只活六秒
+
+- **日期:** 2026-11-05
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 否
+
+[English](2026-11-05-messaging-test-refusal.md)
+
+消息绑定卡片里那颗「测试连接」跑的是所选通道**尚未保存**的值,服务端只探测、不写任何东西。探测没通过时
+(Telegram 拒了 token、飞书的 base domain 根本连不上、微信存的机器人 token 已失效),卡片与按键前一模
+一样,而原因只落进一条六秒后自己消失的通知 —— 那句话点名的 App ID、密钥与 base domain,正是它下面那几格
+字段。
+
+那句话现在画在两颗探测按钮下面(`role="alert"`、危险色、限两行、整句挂悬停),一直留到表单被编辑、切换
+通道或下一次探测开始 —— 同一颗按钮就是重试。**连通的那一次仍是通知**(耗时、Telegram 的机器人名与
+群组隐私提示):那个结果没有留在卡片上的东西要解释。请求本身没到服务端时,现在念错误码自己的本地化句子,
+而不是它的线上英文原文 —— 全应用拒绝位早就按这条规则走。
+
+## 明细
+
+- `packages/web/src/features/messaging/messaging-test-refusal.ts`(新):`messagingTestRefusal(...)` ——
+ 纯判断,念哪句话只在这一处,不依赖卡片就能测。
+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`:hook 多一个 `testRefusal` 状态 ——
+ 探测的失败分支写上(原来走 `toastError`),表单编辑、切换通道、切换会话、下一次探测开始各自清掉;卡片
+ 把它画在两颗探测按钮下面、前提提示上面。四条通道各自的探测调用收成一个答复形状,只有连通那条分支还分开
+ (Telegram 的通知照旧)。
+
+## 测试
+
+- `packages/web/test/messaging-test-refusal.test.ts`(新,6 条):连通的答复什么都不留;平台的细节原样
+ 带上;无细节退回通用句;没到服务端的请求按 `refusalText` 读(不念线上原文);客户端自己抛的错误保留原话;
+ 用的是当前语言。
+- `packages/web/test/messaging-binding-editor.test.ts`:加一条渲染用例 —— 那句话只出现一次、在探测按钮与
+ 凭据字段之间、限两行且整句挂悬停,没有失败时一条都不画。
+- `packages/web/e2e/messaging-test-refusal.spec.mjs`(新,真服务端 + 真浏览器):给一个会话绑定飞书,把
+ 探测路由桩成三种答复。被拒时那句话出现、通知区里没有它,**7 秒后**仍在;改一格字段后它消失,重试的探测
+ (这次连通)带的是改过的值、并以通知报出耗时;路由 500 时画的是错误码自己那句。
+
+## 兼容性
+
+不碰接口、不引入新依赖、不改 Project 配置。旁边那颗「发送测试消息」仍走通知:它失败之后要改的东西在聊天
+平台那一边,不在这张卡片的字段里。
diff --git a/packages/web/e2e/messaging-test-refusal.spec.mjs b/packages/web/e2e/messaging-test-refusal.spec.mjs
new file mode 100644
index 00000000..953d6e76
--- /dev/null
+++ b/packages/web/e2e/messaging-test-refusal.spec.mjs
@@ -0,0 +1,252 @@
+/**
+ * Regression: the messaging card's "test connection" button says why a probe did not get through —
+ * in the card, under that button — instead of leaving the form exactly as it was with the reason in
+ * a notification that dismissed itself after six seconds.
+ *
+ * The button runs the selected channel's current (unsaved) values through the server's credential
+ * probe, which saves nothing. A refused probe therefore leaves a card that looks untouched, while
+ * the App ID, the secret and the base domain the sentence is about are the fields right below it.
+ * Six seconds later that sentence used to be gone, and nothing on the card said the button had been
+ * pressed at all.
+ *
+ * Both channels' probes are stubbed rather than travelled: what this spec is about is what the page
+ * does with the answer, and a real probe would dial the platform. The binding itself is real (a
+ * stored credential is what makes the button clickable), and it points at a closed local port, 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";
+
+/** Where this channel's connector dials: nothing listens on port 9, so nothing leaves the machine. */
+const DEAD_ORIGIN = "http://127.0.0.1:9";
+/** The row menu action that opens the dialog (`S.messaging.bindAction`). */
+const OPEN = "远程控制";
+/** The probe button (`S.messaging.test`). */
+const TEST = "测试连接";
+/** The platform's own words for a rejected credential, as a probe route reports them. */
+const PLATFORM_DETAIL = "Unauthorized";
+/** The line the card draws: the sentence's lead-in plus those words. */
+const REFUSED_LINE = `连接失败:${PLATFORM_DETAIL}`;
+/** The app's own sentence for a failed request (`internal`), not the server's wire message. */
+const FAILED_REQUEST_LINE = "连接失败:服务器内部错误,请稍后重试。";
+/** The success toast every channel's connecting probe uses (`S.messaging.testOk`). */
+const CONNECTED_TOAST = "连接成功(12ms)";
+
+/**
+ * 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 chat.spec.mjs uses for the same menu.
+ */
+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 bind Feishu to it; returns its id.
+ *
+ * `appId` is unique per test: one account may hold only one enabled connection, and these tests
+ * share a data root, so a fixed id would let an earlier run's leftover row answer the later one
+ * with a 409 that has nothing to do with what is being measured.
+ */
+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 the probe button clickable at all: without one it is gated
+ // (it dims and explains), and every test here is about what the route's answer does.
+ const bound = await page.request.put(`${BASE}/api/sessions/${sessionId}/messaging/feishu`, {
+ data: { appId, appSecret: "probe-app-secret", baseDomain: DEAD_ORIGIN },
+ });
+ expect(bound.ok(), "bind feishu").toBeTruthy();
+ return sessionId;
+}
+
+/**
+ * Take over the Feishu probe route. `state.answer` picks what it does: `"refuse"` (the platform's
+ * rejection, the route's ordinary `ok:false` shape), `"error"` (the request itself failing) or
+ * `"connect"`; every call records the body, so a test can check it carried the form's values.
+ */
+async function stubProbe(page, state) {
+ await page.route("**/api/sessions/*/messaging/feishu/test", async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ state.seen.push(route.request().postDataJSON());
+ if (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:
+ state.answer === "refuse"
+ ? JSON.stringify({ ok: false, error: PLATFORM_DETAIL })
+ : JSON.stringify({ ok: true, latencyMs: 12 }),
+ });
+ });
+}
+
+/**
+ * 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 a 500 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" && url.includes("/messaging/")) return false;
+ return true;
+ }),
+ };
+}
+
+/** Open the binding dialog from the seeded row (it opens on Feishu, 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 refused probe keeps the reason under the button, and only there", async ({ page }) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "probetest", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e refused probe ${Date.now()}`;
+ await seed(page, projectId, title, `probe-refused-${Date.now()}`);
+
+ const state = { seen: [], answer: "refuse" };
+ await stubProbe(page, state);
+ const dialog = await openDialog(page, title);
+
+ await dialog.getByRole("button", { name: TEST, exact: true }).click();
+
+ // The sentence sits in the card, under the button that asked, exactly once.
+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);
+ await expect(dialog.getByRole("alert")).toHaveCount(1);
+ // Not a toast: the notification region holds nothing to dismiss.
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ // The probe travelled, carrying the form's own (empty) draft — the stored secret is the fallback.
+ 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(REFUSED_LINE);
+ expect(console_.unexpected()).toEqual([]);
+});
+
+test("an edit drops the sentence, and the same button is the retry", async ({ page }) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "proberetry", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e retried probe ${Date.now()}`;
+ await seed(page, projectId, title, `probe-retried-${Date.now()}`);
+
+ const state = { seen: [], answer: "refuse" };
+ await stubProbe(page, state);
+ const dialog = await openDialog(page, title);
+ await dialog.getByRole("button", { name: TEST, exact: true }).click();
+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);
+
+ // The probe sent the values that were on screen, so changing one of them makes the sentence
+ // describe a connection nothing asked about any more.
+ const appId = dialog.getByLabel("App ID", { exact: true });
+ await appId.fill("cli_probe_edited");
+ await expect(dialog.getByRole("alert")).toHaveCount(0);
+
+ // Same button, second press: this time the probe connects, so the sentence stays away and the
+ // numbers arrive as the toast every connecting probe uses.
+ state.answer = "connect";
+ await dialog.getByRole("button", { name: TEST, exact: true }).click();
+ await expect(notifications(page).getByText(CONNECTED_TOAST)).toBeVisible();
+ await expect(dialog.getByRole("alert")).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ // The second probe travelled to the edited value, not the one the first sentence was about.
+ expect(state.seen[1].appId).toBe("cli_probe_edited");
+ expect(console_.unexpected()).toEqual([]);
+});
+
+test("a probe whose request never reached the route reads its code, not the wire message", async ({
+ page,
+}) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, "probeerror", P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e failed probe ${Date.now()}`;
+ await seed(page, projectId, title, `probe-error-${Date.now()}`);
+
+ const state = { seen: [], answer: "error" };
+ await stubProbe(page, state);
+ const dialog = await openDialog(page, title);
+ await dialog.getByRole("button", { name: TEST, exact: true }).click();
+
+ // `refusalText`'s rule: a request that never reached the platform is answered with its code's
+ // own sentence, not the server's English — the same rule the app's other refusal slots follow.
+ await expect(dialog.getByRole("alert")).toHaveText(FAILED_REQUEST_LINE);
+ await expect(dialog.getByRole("alert")).not.toContainText("RAW ENGLISH MESSAGE");
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(console_.unexpected()).toEqual([]);
+});
diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsx
index 5100532b..5a395765 100644
--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx
+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx
@@ -69,6 +69,7 @@ import { formatDateTime } from "../../lib/format";
import { toneInk, type Tone } from "../../lib/tone";
import { QQScanConnect } from "./qq-scan-connect";
import { WeChatScanConnect } from "./wechat-scan-connect";
+import { messagingTestRefusal } from "./messaging-test-refusal";
import {
bindingsToForm,
emptyMessagingForm,
@@ -238,6 +239,12 @@ export interface MessagingBindingEditorState {
* until the next flip or a channel switch, which is what makes it readable after the attempt.
*/
toggleRefusal: string | null;
+ /**
+ * Why the last credential probe did not get through (null when it connected or none ran). It
+ * stays under the button that asked until the form is edited, the channel is switched or the
+ * next probe starts — see `messaging-test-refusal.ts`.
+ */
+ testRefusal: string | null;
/** The id hosts give their Save action, so a switch gated on unsaved edits can focus it. */
saveButtonId: string;
/**
@@ -368,6 +375,8 @@ export function useMessagingBinding(
const [toggleRefusal, setToggleRefusal] = useState<string | null>(null);
const [testing, setTesting] = useState(false);
const [sendingTest, setSendingTest] = useState(false);
+ /** The last refused credential probe, under the button that asked (see `messaging-test-refusal.ts`). */
+ const [testRefusal, setTestRefusal] = useState<string | null>(null);
const saveButtonId = useId();
/** Which session the form was loaded for (the initial load runs once per session, not per poll flip). */
@@ -405,6 +414,8 @@ export function useMessagingBinding(
// A swapped session must never show the previous one's fields while its load runs.
setForm(null);
setBaseline(null);
+ // Nor the previous session's probe answer: its fields are about to leave the screen.
+ setTestRefusal(null);
void refresh(true);
}
const timer = poll ? setInterval(() => void refresh(false), STATUS_POLL_MS) : null;
@@ -423,12 +434,17 @@ export function useMessagingBinding(
const patchForm = (patch: Partial<MessagingFormState>) => {
setForm((prev) => (prev ? { ...prev, ...patch } : prev));
setFieldErrors({});
+ // The probe sent exactly the values on the form, so any edit makes its sentence describe a
+ // connection nothing asked about any more.
+ setTestRefusal(null);
};
const selectChannel = (channel: MessagingChannel) => {
// The refusal belongs to the switch of the channel it was refused on: another channel's
// switch is a different control, and carrying the sentence across would accuse it.
setToggleRefusal(null);
+ // Same rule for the probe: another channel's credentials are not what that button tested.
+ setTestRefusal(null);
patchForm({ channel });
};
@@ -467,34 +483,47 @@ export function useMessagingBinding(
}
};
+ /**
+ * Probes the selected channel with the form's current (unsaved) values and saves nothing.
+ *
+ * A connection that gets through pops its numbers as a toast; one that does not leaves its
+ * sentence under the button that asked, and NOT in a toast (see `messaging-test-refusal.ts`):
+ * the card is otherwise unchanged, so six seconds later nothing on screen would say the button
+ * had been pressed — while the credential fields that sentence points at sit right below it.
+ */
const testConnection = async () => {
if (!form) return;
+ // This probe's answer replaces the last one's.
+ setTestRefusal(null);
setTesting(true);
try {
const draft = formToTest(form);
+ const res =
+ draft.channel === "telegram"
+ ? await api.testTelegramBinding(sessionId, draft.body)
+ : draft.channel === "qq"
+ ? await api.testQQBinding(sessionId, draft.body)
+ : // No body on WeChat: this channel's probe reads the stored binding, there being no draft.
+ draft.channel === "wechat"
+ ? await api.testWeChatBinding(sessionId)
+ : await api.testFeishuBinding(sessionId, draft.body);
+ const refusal = messagingTestRefusal({ result: res });
+ if (refusal !== null) {
+ setTestRefusal(refusal);
+ return;
+ }
+ // Connected: what is left of Telegram's notices is the success line and the Group Privacy
+ // caveat — the failure branch was answered above.
if (draft.channel === "telegram") {
- const res = await api.testTelegramBinding(sessionId, draft.body);
for (const notice of telegramTestNotices(res)) {
- if (notice.tone === "error") toastError(notice.text);
- else if (notice.tone === "info") toastInfo(notice.text);
+ if (notice.tone === "info") toastInfo(notice.text);
else toastSuccess(notice.text);
}
- } else if (draft.channel === "qq") {
- const res = await api.testQQBinding(sessionId, draft.body);
- if (res.ok) toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));
- else toastError(S.messaging.testFail(res.error ?? S.common.unknownError));
- } else if (draft.channel === "wechat") {
- // No body: this channel's probe reads the stored binding, there being no draft.
- const res = await api.testWeChatBinding(sessionId);
- if (res.ok) toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));
- else toastError(S.messaging.testFail(res.error ?? S.common.unknownError));
} else {
- const res = await api.testFeishuBinding(sessionId, draft.body);
- if (res.ok) toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));
- else toastError(S.messaging.testFail(res.error ?? S.common.unknownError));
+ toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));
}
} catch (e) {
- toastError(S.messaging.testFail(apiErrorText(e)));
+ setTestRefusal(messagingTestRefusal({ result: null, error: e }));
} finally {
setTesting(false);
}
@@ -584,6 +613,7 @@ export function useMessagingBinding(
toggleBusy: toggling || busy,
enableGate,
toggleRefusal,
+ testRefusal,
saveButtonId,
adoptBinding: (binding) =>
applyChannel(binding.channel, binding, channels[binding.channel].status),
@@ -941,7 +971,8 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
</p>
)}
</div>
- {/* Entry-level probes — the MCP dialog idiom: standalone buttons, results as toasts. */}
+ {/* Entry-level probes — the MCP dialog idiom: standalone buttons, a connecting answer as a
+ toast, a refused one drawn below them (see `messaging-test-refusal.ts`). */}
<div className="flex flex-wrap items-center gap-2">
<Button
size="sm"
@@ -972,6 +1003,19 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
{b.sendingTest ? S.messaging.sendingTestMessage : S.messaging.sendTestMessage}
</Button>
</div>
+ {/* Under the button that asked, not over the card: `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. */}
+ {b.testRefusal !== null && (
+ <p
+ role="alert"
+ data-tooltip={b.testRefusal}
+ data-tooltip-content="text"
+ className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}
+ >
+ {b.testRefusal}
+ </p>
+ )}
{/* The gating reason closes the control block rather than sitting under the switch:
it comes and goes with the switch's own state, so anything below it shifts by a
line — trailing the probes leaves both of them at a fixed offset. */}
diff --git a/packages/web/src/features/messaging/messaging-test-refusal.ts b/packages/web/src/features/messaging/messaging-test-refusal.ts
new file mode 100644
index 00000000..e73d41a3
--- /dev/null
+++ b/packages/web/src/features/messaging/messaging-test-refusal.ts
@@ -0,0 +1,48 @@
+/**
+ * The messaging card's "test connection" button: the sentence a credential probe that did not get
+ * through leaves under it, and why that sentence is a line in the card rather than a toast.
+ *
+ * The button runs the selected channel's current — still unsaved — values through the server's
+ * credential probe, which writes nothing. Every failed probe is therefore a form that looks exactly
+ * as it did before the press, with the one sentence that explains the failure in a notification
+ * that dismisses itself after six seconds — while the App ID, the secret and the base URL that
+ * sentence points at are the fields right below. So the refusal is drawn inside the card, under the
+ * button that asked, and it stays until the form is edited, the channel is switched or the next
+ * probe starts: the button is the retry.
+ *
+ * A probe that *connects* keeps its toast (the latency, Telegram's bot name and its Group Privacy
+ * caveat, the MCP dialog idiom): that outcome leaves nothing behind to explain, so only one of the
+ * two answers has a place on the card.
+ */
+import { S } from "../../lib/strings";
+import { refusalText } from "../../lib/api-error";
+
+/** What all four channels' probe routes answer with, as far as a refusal is concerned. */
+export interface MessagingProbeResult {
+ readonly ok: boolean;
+ /** The platform's own words; absent when the route had none to give. */
+ readonly error?: string;
+}
+
+/** What one press of the button came back with. */
+export interface MessagingTestAnswer {
+ /** The route's own answer, or `null` when the request itself failed (login gone, server down). */
+ readonly result: MessagingProbeResult | null;
+ /** Why the request failed; read only when `result` is `null`. */
+ readonly error?: unknown;
+}
+
+/**
+ * The line the card draws under the test button, or `null` when the probe connected.
+ *
+ * Three shapes reach it, and each keeps the rule the rest of the app's refusal slots follow
+ * (`refusalText`): the route's answer carries the platform's detail (an unauthorized token, an
+ * unreachable base domain), a failed request carries its code's sentence rather than the server's
+ * English, and an answer with no detail at all falls back to the generic text — an empty line under
+ * the button would say less than the toast it replaced.
+ */
+export function messagingTestRefusal(answer: MessagingTestAnswer): string | null {
+ if (answer.result === null) return S.messaging.testFail(refusalText(answer.error));
+ if (answer.result.ok) return null;
+ return S.messaging.testFail(answer.result.error ?? S.common.unknownError);
+}
diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.ts
index 64105c58..c0934e6b 100644
--- a/packages/web/test/messaging-binding-editor.test.ts
+++ b/packages/web/test/messaging-binding-editor.test.ts
@@ -85,6 +85,7 @@ function stateOf(
toggleBusy: false,
enableGate: null,
toggleRefusal: null,
+ testRefusal: null,
saveButtonId: "save-under-test",
adoptBinding: () => {},
save: noop,
@@ -227,6 +228,29 @@ describe("MessagingBindingBody", () => {
expect(render(stateOf("telegram"))).not.toContain(`role="alert"`);
});
+ it("keeps a refused credential probe under the button that asked", () => {
+ // The probe runs the form's unsaved values and writes nothing, so a refusal leaves the card
+ // exactly as it was — the sentence is the only account of the press, and the fields it points
+ // at are the ones right below it.
+ const line = S.messaging.testFail("Unauthorized");
+ const html = render(stateOf("telegram", {}, { testRefusal: line }));
+ expect(html).toContain(`>${line}</p>`);
+ expect(html).toContain('role="alert"');
+ // Between the probe buttons and the credential fields: under the button, not at the form's foot.
+ const buttonAt = html.indexOf(S.messaging.test);
+ const fieldsAt = html.indexOf(S.telegram.botToken);
+ const lineAt = html.indexOf(line);
+ expect(buttonAt).toBeGreaterThanOrEqual(0);
+ expect(fieldsAt).toBeGreaterThan(buttonAt);
+ expect(lineAt).toBeGreaterThan(buttonAt);
+ expect(lineAt).toBeLessThan(fieldsAt);
+ // Bounded, with the whole platform sentence on hover.
+ expect(html).toContain(`data-tooltip="${line}"`);
+ expect(html).toContain("line-clamp-2");
+ // And it is that probe's own line: with nothing refused, the card draws none.
+ expect(render(stateOf("telegram"))).not.toContain('role="alert"');
+ });
+
it('closes the form with the delivery options, each explanation behind its label\'s "?"', () => {
for (const channel of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
const html = render(stateOf(channel));
diff --git a/packages/web/test/messaging-test-refusal.test.ts b/packages/web/test/messaging-test-refusal.test.ts
new file mode 100644
index 00000000..6d4c8785
--- /dev/null
+++ b/packages/web/test/messaging-test-refusal.test.ts
@@ -0,0 +1,76 @@
+/**
+ * The messaging card's "test connection" line (src/features/messaging/messaging-test-refusal.ts):
+ * which answers leave a sentence under the button, and whose words that sentence uses.
+ *
+ * A refused probe changes nothing else on the card — the form keeps every value it was asked with
+ * — 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 the answer comes in plus the two languages, and the rule
+ * that matters most: a probe that connected leaves nothing behind.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import type { FeishuTestResponse, TelegramTestResponse } from "@adelie/server/api";
+import { en as EN } from "../src/lib/strings-en";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { messagingTestRefusal } from "../src/features/messaging/messaging-test-refusal";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+describe("messagingTestRefusal", () => {
+ it("leaves no line when the probe connected", () => {
+ // Typed as the route's own answer, so the extra success fields (the toast's latency, the bot
+ // name, the Group Privacy caveat) are the shapes the line is deliberately blind to.
+ const connected: FeishuTestResponse = { ok: true, latencyMs: 12 };
+ expect(messagingTestRefusal({ result: connected })).toBeNull();
+ const telegram: TelegramTestResponse = {
+ ok: true,
+ latencyMs: 8,
+ botUsername: "@probe_bot",
+ groupPrivacy: true,
+ };
+ expect(messagingTestRefusal({ result: telegram })).toBeNull();
+ });
+
+ it("carries the platform's own detail verbatim, behind the sentence's lead-in", () => {
+ // What the routes send when Telegram rejects the token, or a base domain refuses the dial.
+ expect(messagingTestRefusal({ result: { ok: false, error: "Unauthorized" } })).toBe(
+ S.messaging.testFail("Unauthorized"),
+ );
+ });
+
+ it("still says something when the route refused without a detail", () => {
+ // An empty line under the button would say less than the toast it replaced.
+ expect(messagingTestRefusal({ result: { ok: false } })).toBe(
+ S.messaging.testFail(S.common.unknownError),
+ );
+ });
+
+ it("reads a failed request through its code, so the line is the localized one", () => {
+ const refused = messagingTestRefusal({
+ result: null,
+ error: new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"),
+ });
+ expect(refused).toBe(S.messaging.testFail(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 (a dropped connection, say), not as "unknown".
+ expect(messagingTestRefusal({ result: null, error: new Error("network down") })).toBe(
+ S.messaging.testFail("network down"),
+ );
+ expect(messagingTestRefusal({ result: null, error: undefined })).toBe(
+ S.messaging.testFail(S.common.unknownError),
+ );
+ });
+
+ it("follows the interface language", () => {
+ setActiveStrings(EN);
+ expect(messagingTestRefusal({ result: { ok: false, error: "Unauthorized" } })).toBe(
+ "Connection failed: Unauthorized",
+ );
+ });
+});