A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 发送测试消息被拒时,原因留在按钮下面,不再只活六秒
lmlihengaa4c0b13ba06
diff --git a/changelog/unreleased/2026-11-08-messaging-test-message-refusal.md b/changelog/unreleased/2026-11-08-messaging-test-message-refusal.mdnew file mode 100644index 00000000..994b8777--- /dev/null+++ b/changelog/unreleased/2026-11-08-messaging-test-message-refusal.md@@ -0,0 +1,70 @@+# A refused test message in the messaging card says why, in the card, not in a six-second toast++- **Date:** 2026-11-08+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-08-messaging-test-message-refusal.zh.md)++The messaging card's "send test message" button puts one fixed line into the chat the connection+already knows, and writes nothing: the card looks exactly as it did before the press whatever the+outcome. A refused message therefore used to leave the one sentence that explained it in a+notification that dismissed itself after six seconds, while everything a reader would act on — the+connection's state, the bot's membership in the chat, the platform's reply window, the last+delivery failure — is on the rows right above it.++That sentence now renders under the row of two probe buttons with `role="alert"`, the danger colour,+two lines and the whole sentence on hover, and it stays until the next press or a channel switch:+the button is the retry. It is a slot of its own rather than the probe's: "the credentials do not+connect" and "the chat did not take the message" are different facts, answered by different buttons.++The line also distinguishes what it can and cannot know. When the route answered — the platform+refused the send, no chat is known any more, or the request was rejected — the message did not go+out, and the platform's own words are kept for a refused send (its detail is the actionable half;+the code's sentence merely repeats the button). When the request never came back with an answer, the+server may well have delivered it and only the reply was lost: that shape says the delivery is+unconfirmed, because claiming otherwise would send a second copy into a chat that already holds the+first.++## Details++- `packages/web/src/features/messaging/messaging-test-message-refusal.ts` (new):+ `messagingTestMessageRefusal(error)` — a `<channel>_send_failed` answer keeps the platform's+ detail, everything else goes through `refusalText` (7.19's rule: an answer the server gave is read+ through its code's own localized sentence rather than the English wire message), and a request+ that never answered gets `S.messaging.testMessageUnconfirmed` instead of+ `S.messaging.testMessageRefused`.+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`: the hook gains+ `testMessageRefusal` (cleared when the next press starts, when the channel is switched, and when+ the editor is pointed at another Session — editing the fields does not clear it, because the+ message goes through the stored binding rather than through the draft); the send's failure branch+ no longer goes to a notification but writes it; `MessagingBindingBody` draws it after the probe's+ line, in the same block under the button row.+- `packages/web/src/lib/strings{,-en}.ts`: two new sentences, `messaging.testMessageRefused(reason)`+ and `messaging.testMessageUnconfirmed(reason)`.++## Tests++- `packages/web/test/messaging-test-message-refusal.test.ts` (new, 7 cases): the platform's own words+ survive a refused send (and the code's generic sentence is not used instead); a send failure with+ no detail falls back to that sentence; a `no_chat` and a rejected request read their code's+ localized sentence rather than the English wire message; a request that never answered says the+ delivery is unconfirmed instead of "not sent"; nothing to say falls back to the generic text; both+ languages.+- `packages/web/test/messaging-binding-editor.test.ts` (+1 render case): the line is drawn under the+ button row, after the probe's own line and before the credential fields, with the whole sentence+ on hover — and with nothing refused the card draws no alert.+- `packages/web/e2e/messaging-test-message-refusal.spec.mjs` (new, real server + real browser): the+ send route is stubbed (the row dialog's two buttons need a connected binding with a known chat, so+ the `GET …/messaging` read is supplied too; no request leaves the machine). A refused send puts the+ sentence in the card, verbatim, once, in the platform's words, leaves the notification region out+ of it, and **seven seconds later** it is still there with the button pressable again. The second+ case: the same button once the send is allowed clears the sentence and pops the ordinary "test+ message sent" toast, with both requests recorded. The third: a request that never answers reads+ the unconfirmed sentence and never claims the message did not go out.++## Compatibility++No interface change, no new dependency, no Project config change. The success path, the probe's own+refusal, the save's refusal and the enable switch's refusal are untouched.diff --git a/changelog/unreleased/2026-11-08-messaging-test-message-refusal.zh.md b/changelog/unreleased/2026-11-08-messaging-test-message-refusal.zh.mdnew file mode 100644index 00000000..e3e5ea32--- /dev/null+++ b/changelog/unreleased/2026-11-08-messaging-test-message-refusal.zh.md@@ -0,0 +1,57 @@+# 远程控制卡片里发送测试消息被拒时,原因写在卡片里,不再只活六秒++- **日期:** 2026-11-08+- **类型:** 修复+- **范围:** `web`+- **破坏性变更:** 无++[English](2026-11-08-messaging-test-message-refusal.md)++远程控制卡片的「发送测试消息」把一句固定的话投进连接已知的那个聊天,除此之外什么也不写:无论+成不成,卡片都与按下之前一模一样。于是一条没发出去的消息,唯一的解释在那条六秒后自己消失的通知+里,而读者真正要看的东西 —— 连接状态、机器人还在不在那个聊天里、平台的回复时限、上一次投递失败+的原因 —— 就在上面那几行。++那句话现在画在两个探测按钮下面那一行:`role="alert"`、危险色、限两行、整句挂悬停,并且一直留到+下一次按下或切换渠道为止 —— 按钮自己就是重试。它单占一个槽位、不与凭证探测共用:「凭证连不上」+和「聊天不收这条消息」是两件事,也是两个按钮各自答复的。++这一行还分得清它知道什么、不知道什么。服务端答复了的时候 —— 平台拒收、已经没有已知聊天、请求+本身被拒 —— 消息确实没发出去,其中「平台拒收」保留平台自己的原话(细节才是能动手的那一半,+错误码的句子只是把按钮又念了一遍)。请求根本没回来的时候,服务端很可能已经把消息投出去了,只是+回程丢了:这一种写「没能确认是否已送达」,因为硬说「没发出去」会让人再发一条,而那一条大概率是+重复的。++## 细节++- 新增 `packages/web/src/features/messaging/messaging-test-message-refusal.ts`:+ `messagingTestMessageRefusal(error)` —— `<channel>_send_failed` 保留平台细节,其余走+ `refusalText`(7.19 的规则:服务端答复的按错误码念界面自己的本地化句子、不念线上英文原文),+ 而「请求根本没回来」那一种用 `S.messaging.testMessageUnconfirmed`,不是+ `S.messaging.testMessageRefused`。+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`:hook 多一个+ `testMessageRefusal`(下一次按下开始时、切换渠道时、编辑器改指另一个会话时清掉;改字段不清,+ 因为这条消息走的是已存下的绑定,不是草稿);发送的失败分支不再走通知,而是写上它;+ `MessagingBindingBody` 把它画在探测那一行之后、同一个块里、按钮行下面。+- `packages/web/src/lib/strings{,-en}.ts`:两条新文案,`messaging.testMessageRefused(reason)` 与+ `messaging.testMessageUnconfirmed(reason)`。++## 测试++- 新增 `packages/web/test/messaging-test-message-refusal.test.ts`(7 条):平台拒收时保留平台原话+ (不用错误码那句笼统的话顶替);平台拒收但没带细节时落到错误码那句;`no_chat` 与被拒的请求都+ 按错误码念界面自己的句子、不念线上英文原文;请求没回来时写「没能确认是否已送达」而不是「没发+ 出去」;什么都没有时落到通用文案;中英两种界面语言。+- `packages/web/test/messaging-binding-editor.test.ts`(+1 条渲染断言):句子画在按钮行下面、探测+ 那一句之后、凭证字段之前,整句挂悬停 —— 没有任何拒绝时卡片上一条 alert 都没有。+- 新增 `packages/web/e2e/messaging-test-message-refusal.spec.mjs`(真服务端 + 真浏览器):把发送+ 路由桩掉(行对话框里那两个按钮要有「已连接且有已知聊天」才可按,所以 `GET …/messaging` 的读+ 也一起供给;没有一个请求离开这台机器)。发送被拒时句子在卡片里、逐字、只有一条、念平台的原文,+ 通知区里没有它,**七秒后**仍在、按钮仍可再按。第二条:等发送放行后重按同一个按钮,句子消失、+ 弹出普通的「测试消息已发送」,两次请求都记下来了。第三条:请求一直不回答时念的是「没能确认」+ 那一句,绝不声称消息没发出去。++## 兼容性++不改接口、不引入新依赖、不改 Project 配置。成功路径、凭证探测的拒绝、保存的拒绝、启用开关的拒绝+都没动。diff --git a/packages/web/e2e/messaging-test-message-refusal.spec.mjs b/packages/web/e2e/messaging-test-message-refusal.spec.mjsnew file mode 100644index 00000000..97f877ff--- /dev/null+++ b/packages/web/e2e/messaging-test-message-refusal.spec.mjs@@ -0,0 +1,306 @@+/**+ * Regression: the messaging card's "send test message" button says why a message did not go out —+ * in the card, under that button — instead of leaving the card untouched with the reason in a+ * notification that dismissed itself after six seconds.+ *+ * The button puts one fixed line into the chat the connection already knows and writes nothing, so+ * a refused message leaves a card that looks exactly as it did before the press; six seconds later+ * the sentence used to be gone with nothing on the card saying the button had been pressed at all.+ * The connection it went through (the bot's state, its membership, the platform's reply window) is+ * the rows right above it.+ *+ * Both the send route and the `GET …/messaging` read are stubbed: the button is only pressable for+ * a channel that is `connected` with a known chat, and neither can be produced without a live+ * platform — while what this spec measures is what the page does with the answer. 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 the stub binding claims its 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 send button (`S.messaging.sendTestMessage`). */+const SEND = "发送测试消息";+/** The platform's own words for a message it would not take. */+const PLATFORM_DETAIL = "Bot is not a member of this chat.";+/** The line the card draws: the sentence's lead-in plus those words. */+const REFUSED_LINE = `测试消息没有发出去:${PLATFORM_DETAIL}`;+/** The success toast (`S.messaging.testMessageSent`). */+const SENT_TOAST = "测试消息已发送";+/**+ * The line for an exchange that never completed (`S.messaging.testMessageUnconfirmed` with the+ * client's own `network_error` sentence): it must not claim the message was not sent, because the+ * server may have delivered it with only its answer lost.+ */+const UNCONFIRMED_LEAD = "没能确认测试消息是否已送达:";++/**+ * 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();++ // The stored credential is what makes the card's credential section real; the read that follows+ // is stubbed, because "connected, with a known chat" cannot be produced without a live platform.+ 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;+}++/** A saved Feishu binding as the read reports it, with the two facts that enable the send button. */+function connectedFeishu(sessionId, appId) {+ return {+ bindings: [+ {+ binding: {+ sessionId,+ channel: "feishu",+ appId,+ appSecretMasked: "probe-app-secret",+ baseDomain: DEAD_ORIGIN,+ enabled: true,+ linePerMessage: false,+ finalReplyOnly: false,+ renderMarkdown: true,+ lastChatKnown: true,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ },+ status: { state: "connected", changedAt: new Date().toISOString() },+ },+ ],+ };+}++/**+ * Take over the binding read and the send route. `state.answer` picks what the send does:+ * `"refuse"` (the platform's rejection, the route's 502 shape), `"answer-missing"` (the exchange+ * never completes) or `"ok"`; every call records the request, so a test can count the presses.+ */+async function stubSend(page, sessionId, appId, state) {+ await page.route("**/api/sessions/*/messaging", async (route) => {+ if (route.request().method() !== "GET") return route.fallback();+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(connectedFeishu(sessionId, appId)),+ });+ });+ await page.route("**/api/sessions/*/messaging/feishu/test-message", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ state.seen.push(route.request().postData());+ if (state.answer === "answer-missing") {+ // What the browser raises when the exchange never completes; the client turns it into its+ // own status-0 `network_error`, and the message may well have been delivered by then.+ await route.abort("connectionreset");+ return;+ }+ if (state.answer === "refuse") {+ await route.fulfill({+ status: 502,+ contentType: "application/json",+ body: JSON.stringify({ error: { code: "feishu_send_failed", message: PLATFORM_DETAIL } }),+ });+ return;+ }+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ ok: true }),+ });+ });+}++/**+ * 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 answer 502 / abort 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 === "502" && url.includes("/messaging/")) return false;+ if (url.includes("/messaging/") && /ERR_CONNECTION_RESET|Failed to fetch/.test(text)) {+ 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 test message keeps its reason under the buttons, and only there", async ({+ page,+}) => {+ const console_ = watchConsole(page);+ await provisionAndLogin(page.request, "sendtest", P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const title = `e2e refused send ${Date.now()}`;+ const appId = `send-refused-${Date.now()}`;+ const sessionId = await seed(page, projectId, title, appId);++ const state = { seen: [], answer: "refuse" };+ await stubSend(page, sessionId, appId, state);+ const dialog = await openDialog(page, title);++ const send = dialog.getByRole("button", { name: SEND, exact: true });+ await expect(send).toBeEnabled();+ await send.click();++ // The sentence sits in the card, under the row, exactly once — in the platform's own words.+ 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 press went through the selected channel's own route, once.+ 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);+ // The button is the retry: still pressable with the sentence on screen.+ await expect(send).toBeEnabled();+ expect(console_.unexpected()).toEqual([]);+});++test("the same button is the retry, and a message that lands clears the sentence", async ({+ page,+}) => {+ const console_ = watchConsole(page);+ await provisionAndLogin(page.request, "sendretry", P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const title = `e2e retried send ${Date.now()}`;+ const appId = `send-retried-${Date.now()}`;+ const sessionId = await seed(page, projectId, title, appId);++ const state = { seen: [], answer: "refuse" };+ await stubSend(page, sessionId, appId, state);+ const dialog = await openDialog(page, title);+ await dialog.getByRole("button", { name: SEND, exact: true }).click();+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);++ // Editing the credentials does NOT clear this line: the message went through the stored binding,+ // not through the draft, so what it says is still true.+ await dialog.getByLabel("App ID", { exact: true }).fill("cli_send_edited");+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);++ // Same button, second press: this time the chat takes the message, so the sentence goes away+ // and the ordinary confirmation arrives.+ state.answer = "ok";+ await dialog.getByRole("button", { name: SEND, exact: true }).click();+ await expect(notifications(page).getByText(SENT_TOAST)).toBeVisible();+ await expect(dialog.getByRole("alert")).toHaveCount(0);+ expect(state.seen).toHaveLength(2);+ expect(console_.unexpected()).toEqual([]);+});++test("a send whose exchange never completed says so instead of claiming it did not go out", async ({+ page,+}) => {+ const console_ = watchConsole(page);+ await provisionAndLogin(page.request, "sendlost", P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const title = `e2e lost send ${Date.now()}`;+ const appId = `send-lost-${Date.now()}`;+ const sessionId = await seed(page, projectId, title, appId);++ const state = { seen: [], answer: "answer-missing" };+ await stubSend(page, sessionId, appId, state);+ const dialog = await openDialog(page, title);+ await dialog.getByRole("button", { name: SEND, exact: true }).click();++ // Nobody on this side saw an answer, so the line must not say the message was not sent.+ const alert = dialog.getByRole("alert");+ await expect(alert).toContainText(UNCONFIRMED_LEAD);+ await expect(alert).not.toContainText("测试消息没有发出去");+ // The same wording the app uses for a failed exchange, inside the sentence that says so.+ await expect(alert).toContainText("网络错误,请检查连接");+ await expect(notifications(page).getByRole("button")).toHaveCount(0);+ expect(state.seen).toHaveLength(1);+ 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.tsxindex 08c7071c..ef947895 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -70,6 +70,7 @@ 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 { messagingTestMessageRefusal } from "./messaging-test-message-refusal";import { messagingSaveRefusal } from "./messaging-save-refusal";import {bindingsToForm,@@ -246,6 +247,12 @@ export interface MessagingBindingEditorState {* next probe starts — see `messaging-test-refusal.ts`.*/testRefusal: string | null;+ /**+ * Why the last test message did not land (null when it was sent or none went out). It stays+ * under the two probe buttons until the next press or a channel switch — see+ * `messaging-test-message-refusal.ts`.+ */+ testMessageRefusal: string | null;/*** Why the last save did not land (null when nothing was refused). It stays at the end of the* card — above Save in both hosts — until the next save starts or the channel is switched,@@ -384,6 +391,13 @@ export function useMessagingBinding(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);+ /**+ * The last test message that did not land, under the same row (see+ * `messaging-test-message-refusal.ts`). Separate from `testRefusal`: that one is about a probe+ * that writes nothing, this one about a message the chat may or may not have received — and the+ * two are answered by different buttons, so one never stands for the other.+ */+ const [testMessageRefusal, setTestMessageRefusal] = useState<string | null>(null);/*** The last refused save, at the end of the card (see `messaging-save-refusal.ts`). Separate from* `testRefusal` because it is about a write that was supposed to change something, not about a@@ -429,6 +443,8 @@ export function useMessagingBinding(setBaseline(null);// Nor the previous session's probe answer: its fields are about to leave the screen.setTestRefusal(null);+ // Nor the test message that session's chat was sent: that chat is not this one's.+ setTestMessageRefusal(null);// Nor why that other conversation's save failed: this form is a different one.setSaveRefusal(null);void refresh(true);@@ -460,6 +476,8 @@ export function useMessagingBinding(setToggleRefusal(null);// Same rule for the probe: another channel's credentials are not what that button tested.setTestRefusal(null);+ // And for the test message: it went to the other channel's chat, if it went anywhere.+ setTestMessageRefusal(null);// And for the save: another channel's form is not the one that failed to write.setSaveRefusal(null);patchForm({ channel });@@ -546,13 +564,22 @@ export function useMessagingBinding(}};+ /**+ * Sends one fixed line into the chat the connection already knows (the outbound leg, end to+ * end). A message that landed pops its confirmation; one that did not leaves its sentence under+ * the buttons and NOT in a toast (see `messaging-test-message-refusal.ts`): the card is+ * otherwise identical, so six seconds later nothing on screen would say the button had been+ * pressed — while the connection the message went through sits on the rows right above.+ */const sendTestMessage = async () => {setSendingTest(true);+ // This press's answer replaces the last one's.+ setTestMessageRefusal(null);try {await api.sendMessagingTestMessage(sessionId, selected);toastSuccess(S.messaging.testMessageSent);} catch (e) {- toastError(apiErrorText(e));+ setTestMessageRefusal(messagingTestMessageRefusal(e));} finally {setSendingTest(false);}@@ -641,6 +668,7 @@ export function useMessagingBinding(enableGate,toggleRefusal,testRefusal,+ testMessageRefusal,saveRefusal,saveButtonId,adoptBinding: (binding) =>@@ -1044,6 +1072,19 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState }){b.testRefusal}</p>)}+ {/* The second button's own answer, in the same block and after the probe's line so the+ reading order matches the row (test, then send). A button of its own needs a slot of its+ own: a refused probe says nothing about whether a message reached the chat. */}+ {b.testMessageRefusal !== null && (+ <p+ role="alert"+ data-tooltip={b.testMessageRefusal}+ data-tooltip-content="text"+ className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}+ >+ {b.testMessageRefusal}+ </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 aline — trailing the probes leaves both of them at a fixed offset. */}diff --git a/packages/web/src/features/messaging/messaging-test-message-refusal.ts b/packages/web/src/features/messaging/messaging-test-message-refusal.tsnew file mode 100644index 00000000..fa9ff90c--- /dev/null+++ b/packages/web/src/features/messaging/messaging-test-message-refusal.ts@@ -0,0 +1,57 @@+/**+ * The messaging card's "send test message" button: the sentence a message that did not go out+ * leaves under it, and why that sentence is a line in the card rather than a toast.+ *+ * The button sends one fixed line into the chat the connection already knows, and writes nothing+ * — the card looks exactly as it did before the press either way. So a refusal used to leave the+ * one sentence that explained it in a notification that dismissed itself after six seconds, while+ * the connection it went through (and what to fix: the bot's membership, the platform's reply+ * window, a revoked scope) is on the rows right above.+ *+ * Two shapes reach here, and they are NOT the same claim:+ *+ * - An answer came back from the route — it tried to deliver and the platform refused (502+ * `<channel>_send_failed`), it refused to try at all (409 `<channel>_no_chat`: the known chat is+ * gone), or it rejected the request itself (403/404/500, read through `refusalText`, 7.19's+ * rule). Every one of those means the message did not go out.+ * - No answer came back — the client's own `network_error` (`ApiError` with status 0: the exchange+ * never completed), or a value that is not an `ApiError` at all (an answer that was not the JSON+ * the route promises). Whether the chat received the message is then unknown: the server may+ * have delivered it and only its answer was lost on the way back. Saying "not sent" there would+ * claim something this side cannot know, and the reader would send a second one into a chat that+ * may already hold the first; that shape gets its own sentence, which says so.+ */+import { ApiError } from "../../api/client";+import { S } from "../../lib/strings";+import { refusalText } from "../../lib/api-error";++/** `refusalText`'s answer, unless it is blank — an empty line says less than the toast it replaced. */+function reasonOf(error: unknown): string {+ const reason = refusalText(error);+ return reason.trim() === "" ? S.common.unknownError : reason;+}++/**+ * The line the card draws under the two probe buttons after a test message that did not land.+ *+ * The platform's own words are kept for a refused send: the code's sentence only says "sending+ * the message failed", which the button already said, while the detail is what the reader acts on+ * (a bot no longer in the chat, QQ's minute-long reply window, a revoked scope) — the same reason+ * the connection's own delivery-failure line prints it. Everything else goes through+ * `refusalText`, so a `no_chat` reads the channel's "message the bot once first" sentence and a+ * rejected request reads its code's localized one rather than the server's English.+ */+export function messagingTestMessageRefusal(error: unknown): string {+ // No answer at all: `network_error` is the client's own status-0 code, and anything that is not+ // an ApiError came from an answer this side could not read. Neither says the message is unsent.+ if (!(error instanceof ApiError) || error.status === 0) {+ return S.messaging.testMessageUnconfirmed(reasonOf(error));+ }+ // `<channel>_send_failed` with a detail: the platform's words are the actionable half. This is+ // also what an unmapped channel's code lands on (only Feishu and Telegram have a sentence of+ // their own in the table), which is right — the route forwards the connector's own message.+ if (error.code.endsWith("_send_failed") && error.message.trim() !== "") {+ return S.messaging.testMessageRefused(error.message);+ }+ return S.messaging.testMessageRefused(reasonOf(error));+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex dddba021..fb342a2a 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -4301,6 +4301,18 @@ export const en: Strings = {sendTestMessage: "Send test message",sendingTestMessage: "Sending…",testMessageSent: "Test message sent",+ /**+ * A test message the platform did not take, drawn under the button that sent it+ * (messaging-test-message-refusal.ts): nothing else on the card changes, so once the+ * six-second notification is gone this line is the only account of the press.+ */+ testMessageRefused: (reason: string): string => `The test message did not go out: ${reason}`,+ /**+ * The one case where "it did not go out" would be a claim the client cannot make: the request+ * never came back with an answer, so the server may have delivered it with only the reply lost.+ */+ testMessageUnconfirmed: (reason: string): string =>+ `Could not confirm whether the test message arrived: ${reason} (check the chat first — it may already be there)`,/*** A save the server refused, drawn at the end of the card, above Save (messaging-save-refusal.ts):* the form still holds what was typed and still reads as unsaved, so this line is the onlydiff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 2bfbdb72..686cbb2e 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4366,6 +4366,18 @@ export const zh = {sendTestMessage: "发送测试消息",sendingTestMessage: "发送中…",testMessageSent: "测试消息已发送",+ /**+ * A test message the platform did not take, drawn under the button that sent it+ * (messaging-test-message-refusal.ts): nothing else on the card changes, so once the+ * six-second notification is gone this line is the only account of the press.+ */+ testMessageRefused: (reason: string): string => `测试消息没有发出去:${reason}`,+ /**+ * The one case where "it did not go out" would be a claim the client cannot make: the request+ * never came back with an answer, so the server may have delivered it with only the reply lost.+ */+ testMessageUnconfirmed: (reason: string): string =>+ `没能确认测试消息是否已送达:${reason}(对方可能已经收到,先到聊天里看一眼)`,/*** A save the server refused, drawn at the end of the card, above Save (messaging-save-refusal.ts):* the form still holds what was typed and still reads as unsaved, so this line is the onlydiff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex f34682a6..de092432 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -16,6 +16,8 @@* - The delivery and Markdown options close the form, each switch rendered from its own field* with its explanation behind a "?"; QQ's replies-only rule is stated on screen; the selector* offers all four channels.+ * - A refused test message gets a line of its own under the same row — a refused probe says+ * nothing about whether the chat received the message, and the two buttons are not the same one.* - The help stacks three collapsed, self-titled folds with the relocated explanation, the* Telegram-only troubleshooting entries, and each channel's tutorial link.* - A Telegram test reports success with the Group Privacy caveat as a second line, nothing@@ -86,6 +88,7 @@ function stateOf(enableGate: null,toggleRefusal: null,testRefusal: null,+ testMessageRefusal: null,saveRefusal: null,saveButtonId: "save-under-test",adoptBinding: () => {},@@ -252,6 +255,34 @@ describe("MessagingBindingBody", () => {expect(render(stateOf("telegram"))).not.toContain('role="alert"');});+ it("keeps a refused test message under the same row, as that button's own line", () => {+ // The send button writes nothing either, so its refusal leaves a card that looks untouched —+ // and a refused probe says nothing about whether a message reached the chat, which is why the+ // two buttons get two slots rather than one.+ const line = S.messaging.testMessageRefused("Bot is not a member of this chat.");+ const probeLine = S.messaging.testFail("Unauthorized");+ const html = render(+ stateOf("telegram", {}, { testRefusal: probeLine, testMessageRefusal: line }),+ );+ expect(html).toContain(`>${line}</p>`);+ expect(html).toContain('role="alert"');+ // Under the row, in the control block before the credential fields; the probe's line first,+ // so the two read in the order of the buttons that answered them.+ const rowAt = html.indexOf(S.messaging.test);+ const fieldsAt = html.indexOf(S.telegram.botToken);+ const probeAt = html.indexOf(probeLine);+ const lineAt = html.indexOf(line);+ expect(rowAt).toBeGreaterThanOrEqual(0);+ expect(fieldsAt).toBeGreaterThan(rowAt);+ expect(probeAt).toBeGreaterThan(rowAt);+ expect(lineAt).toBeGreaterThan(probeAt);+ expect(lineAt).toBeLessThan(fieldsAt);+ // Bounded, with the whole sentence on hover.+ expect(html).toContain(`data-tooltip="${line}"`);+ // And it is that button's own line: with nothing refused, the card draws none.+ expect(render(stateOf("telegram"))).not.toContain('role="alert"');+ });+it("keeps a refused save at the form's foot, where both hosts put their Save action", () => {// Save writes nothing optimistically, so a refusal leaves the card exactly as it was — still// unsaved, no success toast — and the sentence is the only account of the press. It closesdiff --git a/packages/web/test/messaging-test-message-refusal.test.ts b/packages/web/test/messaging-test-message-refusal.test.tsnew file mode 100644index 00000000..f5834090--- /dev/null+++ b/packages/web/test/messaging-test-message-refusal.test.ts@@ -0,0 +1,115 @@+/**+ * The messaging card's test-message line (src/features/messaging/messaging-test-message-refusal.ts):+ * whose words the sentence uses, and which failures are allowed to say "it did not go out".+ *+ * The button sends one fixed line into the known chat and writes nothing, so a refusal leaves the+ * card exactly as it was — this line is the only account of the press once the six-second+ * notification is gone. The cases below are the shapes the failure comes in: the platform's+ * refusal (its own words are the actionable half), a route that refused to try, a request that was+ * itself rejected, and the one shape whose claim must be weaker — a request that never came back,+ * where nobody on this side can tell whether the chat received the message.+ */+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 { messagingTestMessageRefusal } from "../src/features/messaging/messaging-test-message-refusal";++afterEach(() => {+ setActiveStrings(ZH);+});++describe("messagingTestMessageRefusal", () => {+ it("keeps the platform's own words when the send was refused", () => {+ // 502 `<channel>_send_failed` carries the connector's detail: the bot is no longer in the+ // chat, QQ's reply window has passed, a scope was revoked. The code's sentence only says+ // "sending failed", which the button already said.+ const line = messagingTestMessageRefusal(+ new ApiError(502, "feishu_send_failed", "Bot is not a member of this chat."),+ );+ expect(line).toBe(S.messaging.testMessageRefused("Bot is not a member of this chat."));+ expect(line).not.toBe(+ S.messaging.testMessageRefused(S.errors.byCode["feishu_send_failed"] as string),+ );+ });++ it("still says something when the platform's refusal has no detail", () => {+ expect(messagingTestMessageRefusal(new ApiError(502, "telegram_send_failed", " "))).toBe(+ S.messaging.testMessageRefused(S.errors.byCode["telegram_send_failed"] as string),+ );+ // A channel whose code the table does not know (only Feishu and Telegram have one) and whose+ // detail is empty would otherwise resolve to an empty line.+ expect(messagingTestMessageRefusal(new ApiError(502, "qq_send_failed", ""))).toBe(+ S.messaging.testMessageRefused(S.common.unknownError),+ );+ });++ it("keeps the platform's detail for a channel whose code has no sentence of its own", () => {+ // QQ's 502 forwards the connector's own message (its minute-long reply window is what a+ // reader needs), and the error table has no `qq_send_failed` to read instead.+ expect(+ messagingTestMessageRefusal(new ApiError(502, "qq_send_failed", "reply window passed")),+ ).toBe(S.messaging.testMessageRefused("reply window passed"));+ });++ it("reads a route that refused to try through its code, not the wire message", () => {+ // 409 `<channel>_no_chat`: the chat the button relied on is gone. The interface has its own+ // sentence for it — "message the bot once first" — and the server's English is not it.+ const line = messagingTestMessageRefusal(+ new ApiError(409, "feishu_no_chat", "No Feishu chat is known yet: message the bot once."),+ );+ expect(line).toBe(S.messaging.testMessageRefused(S.errors.byCode["feishu_no_chat"] as string));+ expect(line).not.toContain("No Feishu chat is known yet");+ });++ it("reads a rejected request through its code as well", () => {+ const line = messagingTestMessageRefusal(+ new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"),+ );+ expect(line).toBe(S.messaging.testMessageRefused(S.errors.byCode["internal"] as string));+ expect(line).not.toContain("RAW ENGLISH SERVER MESSAGE");+ });++ it("does not claim the message was not sent when no answer came back", () => {+ // The client raises a status-0 `network_error` when the exchange never completed: the server+ // may have delivered the message and only its answer was lost. Saying "it did not go out"+ // would send a second copy into a chat that already holds the first.+ const network = new ApiError(0, "network_error", S.errors.networkError);+ expect(messagingTestMessageRefusal(network)).toBe(+ S.messaging.testMessageUnconfirmed(S.errors.networkError),+ );+ expect(messagingTestMessageRefusal(network)).not.toBe(+ S.messaging.testMessageRefused(S.errors.networkError),+ );+ // An answer this side could not read at all is the same kind of unknown.+ expect(messagingTestMessageRefusal(new SyntaxError("Unexpected end of JSON input"))).toBe(+ S.messaging.testMessageUnconfirmed("Unexpected end of JSON input"),+ );+ });++ it("still says something when an unanswered request carries nothing to say", () => {+ expect(messagingTestMessageRefusal(undefined)).toBe(+ S.messaging.testMessageUnconfirmed(S.common.unknownError),+ );+ expect(messagingTestMessageRefusal(new Error(" "))).toBe(+ S.messaging.testMessageUnconfirmed(S.common.unknownError),+ );+ expect(messagingTestMessageRefusal(new ApiError(0, "network_error", ""))).toBe(+ S.messaging.testMessageUnconfirmed(S.common.unknownError),+ );+ });++ it("follows the interface language", () => {+ setActiveStrings(EN);+ expect(+ messagingTestMessageRefusal(new ApiError(502, "telegram_send_failed", "Forbidden")),+ ).toBe("The test message did not go out: Forbidden");+ expect(messagingTestMessageRefusal(new Error("network down"))).toContain(+ "Could not confirm whether the test message arrived: network down",+ );+ setActiveStrings(ZH);+ expect(+ messagingTestMessageRefusal(new ApiError(502, "telegram_send_failed", "Forbidden")),+ ).toBe("测试消息没有发出去:Forbidden");+ });+});