Skip to content

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

fix(web): 远程控制的连接开关被拒时,原因留在开关下面

lmliheng238e635a1b04
diff --git a/changelog/unreleased/2026-10-31-messaging-toggle-refusal.md b/changelog/unreleased/2026-10-31-messaging-toggle-refusal.md
new file mode 100644
index 00000000..dd6854d9
--- /dev/null
+++ b/changelog/unreleased/2026-10-31-messaging-toggle-refusal.md
@@ -0,0 +1,44 @@
+# The connection switch keeps a refusal's reason under it, instead of only in a toast
+
+- **Date:** 2026-10-31
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-10-31-messaging-toggle-refusal.zh.md)
+
+The remote-control binding's enable switch writes nothing optimistically: it moves only after the
+state call lands, so a refused flip springs back to where the server still has it. That left the
+reason in a toast and nowhere else — six seconds after the click the screen held a switch that
+would not move and no sentence saying why, while the reasons here are exactly the ones a reader
+acts on (another conversation already polling this bot, no saved credential, a lost connection).
+
+The reason now stays under the switch, in the same place the connection's own error line sits, as
+`role="alert"` so it is announced when it arrives. It is cleared by the next flip and by switching
+channels — another channel's switch is a different control and must not inherit the accusation.
+Both hosts of the editor (the sidebar dialog and the conversation's remote-control panel) get it,
+since the body is shared.
+
+## Details
+
+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`: `useMessagingBinding` keeps
+ `toggleRefusal`, set from the failed state POST (via `apiErrorText`, so the words are the
+ server's) instead of `toastError`; `selectChannel` and the next flip clear it. The body renders
+ it first among the lines under the status row, in the danger ink, bounded to two lines with the
+ whole sentence on hover — the same shape as `lastError`. The sentence reuses the shared lead-in
+ `S.common.refused`, so it reads like every other refused write in the app; no new copy.
+
+## Tests
+
+- `packages/web/test/messaging-binding-editor.test.ts`: one case renders a refusal and asserts the
+ shared lead-in plus the reason, `role="alert"`, the line's position outside the status row, and
+ that nothing is announced when no flip was refused.
+- `packages/web/e2e/messaging-toggle-refusal.spec.mjs` (new, two browser cases against the real
+ server): a refused enable leaves the line beside the switch, writes nothing (the switch stays
+ off, the notification region holds no toast), and the line is still there after the six seconds
+ a toast lives; then, with the refusal lifted, the next flip lands and the line goes with it.
+
+## Compatibility
+
+- No API, on-disk or request-shape change. A successful flip behaves exactly as before; only the
+ failure path stopped using a toast.
diff --git a/changelog/unreleased/2026-10-31-messaging-toggle-refusal.zh.md b/changelog/unreleased/2026-10-31-messaging-toggle-refusal.zh.md
new file mode 100644
index 00000000..f6ca759d
--- /dev/null
+++ b/changelog/unreleased/2026-10-31-messaging-toggle-refusal.zh.md
@@ -0,0 +1,37 @@
+# 连接开关被拒时,原因留在开关下面,不再只在一条六秒的提示里
+
+- **日期:** 2026-10-31
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 无
+
+[English](2026-10-31-messaging-toggle-refusal.md)
+
+「远程控制」绑定的启用开关不做乐观写入:状态请求落地之后它才动,所以被拒的那一次会弹回服务端
+仍记着的位置。于是原因只剩一条 toast —— 点完六秒之后,屏幕上是一个不再动的开关、一句已经消失的
+解释;而这里的失败恰恰都是读者要据此动作的那几条(另一个对话已经占用这个机器人、凭证还没保存、
+连接断了)。
+
+现在原因留在开关下面,与连接自己的错误行同一个位置,并且是 `role="alert"`,出现时会被读屏念到。
+下一次翻转与切换渠道都会把它清掉 —— 另一个渠道的开关是另一个控件,不该继承这句指责。编辑器的两
+个宿主(侧栏弹窗与对话内的远程控制面板)共用这份正文,因此两处同时生效。
+
+## 细节
+
+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`:`useMessagingBinding` 多一个
+ `toggleRefusal`,由失败的状态请求经 `apiErrorText` 填上(所以是服务端的原话),不再走
+ `toastError`;`selectChannel` 与下一次翻转把它清空。正文把它排在状态行下面那几行的最前,用
+ danger 色、限两行、整句挂在悬停上 —— 与 `lastError` 同一种形状。句子复用共享的引子
+ `S.common.refused`,与全站其它被拒的写入读起来一致;没有新增文案。
+
+## 测试
+
+- `packages/web/test/messaging-binding-editor.test.ts`:新增一条,渲染出拒绝后断言「共享引子 +
+ 原因」、「`role="alert"`」、这一行在状态行之外的位置,以及没有任何翻转被拒时页面上不出现 alert。
+- `packages/web/e2e/messaging-toggle-refusal.spec.mjs`(新,真服务端两条):被拒的启用把原因留在
+ 开关旁边、什么都不写(开关仍是关的、通知区里没有可点的 toast),并且 toast 该消失的六秒之后这
+ 一行还在;随后放开拒绝,下一次翻转真的落地,那一行随之消失。
+
+## 兼容
+
+- 接口、磁盘格式、请求体都没变。成功的翻转与从前完全一致,只有失败那条路不再用 toast。
diff --git a/packages/web/e2e/messaging-toggle-refusal.spec.mjs b/packages/web/e2e/messaging-toggle-refusal.spec.mjs
new file mode 100644
index 00000000..7f2615a1
--- /dev/null
+++ b/packages/web/e2e/messaging-toggle-refusal.spec.mjs
@@ -0,0 +1,231 @@
+/**
+ * Regression: the connection switch says why a flip did not settle, in place, and the sentence
+ * outlives the six seconds a toast lives.
+ *
+ * The switch writes nothing optimistically — it moves only when the state call lands — so a
+ * refused flip springs back to where the server still has it. The reason used to arrive as a
+ * toast and nothing else: a reader who looked away from the notification region was left with a
+ * switch that would not move and one sentence they never got to read. The editor now keeps it
+ * under the switch (`role="alert"`), like the connection's own error line, until the next flip
+ * or a channel switch.
+ *
+ * Both tests run against the real server (real login, real Session, real binding PUT); only the
+ * state POST that must be refused is taken over. The channel is Feishu pointed at a closed local
+ * port, so an enable that DOES reach the server dials 127.0.0.1:9 and fails at once — the stored
+ * intent is what the switch reads, and 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 USER = "probetoggle";
+const P = "password123";
+
+/** Where this channel's connector dials: nothing listens on port 9, so a connect fails at once. */
+const DEAD_ORIGIN = "http://127.0.0.1:9";
+/** The refusal an enable earns when another Session already holds that account — the server's words. */
+const REFUSAL = {
+ code: "account_enabled_elsewhere",
+ message: "Another Session has this bot's connection enabled: turn it off there first.",
+};
+/** The line the editor draws: the shared lead-in plus the app's own sentence for that code. */
+const REFUSED_LINE = "操作被拒绝:该机器人的连接已在另一个会话中启用:先在那边停用,再在此启用。";
+
+/** The enable switch's accessible name; its label wraps it, so the text is the name. */
+const SWITCH = "启用连接";
+/** The row menu action that opens the dialog (`S.messaging.bindAction`). */
+const OPEN = "远程控制";
+
+/**
+ * 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, 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 refuse 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 saved credential is what the switch needs to be clickable at all: without one the click is
+ // gated (it explains and sends nothing), and both tests are about the server's answer.
+ 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;
+}
+
+/** Store "enabled" (or not) out of band, so a test can start with the switch already on. */
+async function setEnabled(page, sessionId, enabled) {
+ const res = await page.request.post(`${BASE}/api/sessions/${sessionId}/messaging/feishu/state`, {
+ data: { enabled },
+ });
+ expect(res.ok(), `state ${enabled}`).toBeTruthy();
+ return (await res.json()).binding.enabled;
+}
+
+/**
+ * Take over the state POST: `state.refuse` produces the refusal and records the attempt,
+ * anything else falls through to the real server (so the retried flip lands for real).
+ */
+async function stubState(page, state) {
+ await page.route("**/api/sessions/*/messaging/*/state", async (route) => {
+ state.posts.push(new URL(route.request().url()).pathname);
+ if (!state.refuse) return route.fallback();
+ return route.fulfill({
+ status: 409,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+}
+
+/**
+ * Collect the page's console errors, keyed by the resource that produced them. The dialog's own
+ * poll touches `/api/projects/…/machines`, which answers 403 to anyone but an administrator, and
+ * the specs themselves produce one 409 — the app's normal behaviour for this account and the
+ * refusal under test, so those two 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 === "409" && 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;
+}
+
+test("a refused enable leaves its reason under the switch, and it outlives a toast", async ({
+ page,
+}) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, USER, P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e refused toggle ${Date.now()}`;
+ await seed(page, projectId, title, `probe-refused-${Date.now()}`);
+
+ const state = { posts: [], refuse: true };
+ await stubState(page, state);
+ const dialog = await openDialog(page, title);
+
+ const toggle = dialog.getByRole("switch", { name: SWITCH });
+ await expect(toggle).toBeVisible();
+ await expect(toggle).not.toBeChecked();
+
+ await toggle.click();
+
+ // The reason is beside the switch that asked, announced as an alert, with the server's words.
+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);
+ expect(state.posts).toHaveLength(1);
+ // Not a toast: the notification region holds nothing to dismiss.
+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);
+ // And the switch is where the server still has it — nothing was written optimistically.
+ await expect(toggle).not.toBeChecked();
+ // The whole point of the change: a toast is gone by now, this line is not.
+ await page.waitForTimeout(6500);
+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);
+ // Nothing failed in the browser beyond the known admin-only read.
+ expect(console_.unexpected()).toEqual([]);
+});
+
+test("the next flip clears the line: a landed disable leaves no reason behind", async ({
+ page,
+}) => {
+ const console_ = watchConsole(page);
+ await provisionAndLogin(page.request, USER, P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const title = `e2e retried toggle ${Date.now()}`;
+ const sessionId = await seed(page, projectId, title, `probe-retried-${Date.now()}`);
+ // On before the dialog opens, so the flip these tests take over is the harmless direction
+ // (disabling dials nothing) and the switch starts where the server left it.
+ expect(await setEnabled(page, sessionId, true)).toBe(true);
+
+ const state = { posts: [], refuse: true };
+ await stubState(page, state);
+ const dialog = await openDialog(page, title);
+ const toggle = dialog.getByRole("switch", { name: SWITCH });
+ await expect(toggle).toBeChecked();
+
+ await toggle.click();
+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);
+ // Refused means unwritten: the switch is still on.
+ await expect(toggle).toBeChecked();
+
+ // Let the next flip through to the real server: it lands, and the reason goes with it.
+ state.refuse = false;
+ await toggle.click();
+ await expect(dialog.getByRole("alert")).toHaveCount(0);
+ await expect(toggle).not.toBeChecked();
+ expect(state.posts).toHaveLength(2);
+ 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 20119a21..5100532b 100644
--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx
+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx
@@ -233,6 +233,11 @@ export interface MessagingBindingEditorState {
* must). The switch only looks disabled while gated: a click explains instead of toggling.
*/
enableGate: EnablePrerequisite | null;
+ /**
+ * Why the last flip of the switch did not settle (null when nothing was refused). It stays
+ * until the next flip or a channel switch, which is what makes it readable after the attempt.
+ */
+ toggleRefusal: string | null;
/** The id hosts give their Save action, so a switch gated on unsaved edits can focus it. */
saveButtonId: string;
/**
@@ -359,6 +364,8 @@ export function useMessagingBinding(
const [fieldErrors, setFieldErrors] = useState<MessagingFormErrors>({});
const [busy, setBusy] = useState(false);
const [toggling, setToggling] = useState(false);
+ /** The server's refusal of the last flip of the switch, until the next flip or channel switch. */
+ const [toggleRefusal, setToggleRefusal] = useState<string | null>(null);
const [testing, setTesting] = useState(false);
const [sendingTest, setSendingTest] = useState(false);
const saveButtonId = useId();
@@ -419,6 +426,9 @@ export function useMessagingBinding(
};
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);
patchForm({ channel });
};
@@ -529,15 +539,26 @@ export function useMessagingBinding(
}
};
- /** The Switch: connect/disconnect the SELECTED channel with its stored credentials. */
+ /**
+ * The Switch: connect/disconnect the SELECTED channel with its stored credentials.
+ *
+ * A refused flip leaves its reason in `toggleRefusal`, under the switch, and NOT in a toast:
+ * the switch springs back to where the server still has it (nothing is written optimistically),
+ * so the toast was the only trace of why, and it is gone in six seconds — while the reader who
+ * looked away has a switch that refuses to move and one sentence they never got to read. The
+ * reasons here are the settled ones a reader acts on (`*_not_bound`, another conversation
+ * already polling this bot's token, a lost connection), and the switch is exactly where they
+ * were looking when it happened.
+ */
const toggleEnabled = async (next: boolean) => {
+ setToggleRefusal(null);
setToggling(true);
try {
const res = await api.setMessagingBindingState(sessionId, selected, next);
applyChannel(selected, res.binding, res.status);
onChanged?.(sessionId, next && res.binding?.enabled === true ? selected : null);
} catch (e) {
- toastError(apiErrorText(e));
+ setToggleRefusal(apiErrorText(e));
} finally {
setToggling(false);
}
@@ -562,6 +583,7 @@ export function useMessagingBinding(
testable: form !== null && formTestable(form, facts.secretConfigured),
toggleBusy: toggling || busy,
enableGate,
+ toggleRefusal,
saveButtonId,
adoptBinding: (binding) =>
applyChannel(binding.channel, binding, channels[binding.channel].status),
@@ -836,6 +858,19 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
{S.messaging.status[facts.status.state]}
</span>
</div>
+ {/* The refused flip: first of the lines under the status row, because it is about the
+ control above it rather than about the connection's own health. `role="alert"` so it
+ is announced when it arrives — a toast was announced once and then left. */}
+ {b.toggleRefusal !== null && (
+ <p
+ role="alert"
+ data-tooltip={S.common.refused(b.toggleRefusal)}
+ data-tooltip-content="text"
+ className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}
+ >
+ {S.common.refused(b.toggleRefusal)}
+ </p>
+ )}
{facts.status.state === "error" && facts.status.lastError !== undefined && (
<p
data-tooltip={facts.status.lastError}
diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.ts
index 858cc9ea..64105c58 100644
--- a/packages/web/test/messaging-binding-editor.test.ts
+++ b/packages/web/test/messaging-binding-editor.test.ts
@@ -84,6 +84,7 @@ function stateOf(
testable: false,
toggleBusy: false,
enableGate: null,
+ toggleRefusal: null,
saveButtonId: "save-under-test",
adoptBinding: () => {},
save: noop,
@@ -208,6 +209,24 @@ describe("MessagingBindingBody", () => {
expect(html).toContain(`data-tooltip="${lastError}"`);
});
+ it("keeps a refused flip's reason under the switch, not in a toast that leaves in six seconds", () => {
+ // The switch writes nothing optimistically, so a refusal springs it back to where the
+ // server still has it. A toast was the only trace of why, and a reader who looked away
+ // was left with a switch that would not move and no sentence saying why.
+ const reason = "telegram_not_bound";
+ const html = render(stateOf("telegram", {}, { toggleRefusal: reason }));
+ // The shared lead-in, so the line reads the way every other refused write in the app does.
+ expect(html).toContain(`>${S.common.refused(reason)}</p>`);
+ // Announced when it arrives: `alert`, not a silent paragraph.
+ expect(html).toContain(`role="alert"`);
+ // Under the status row — below the switch the reader just flipped, not at the form's foot.
+ const rowAt = html.indexOf("flex flex-wrap items-center gap-2 text-xs");
+ expect(rowAt).toBeGreaterThanOrEqual(0);
+ expect(html.slice(rowAt, html.indexOf(S.common.refused(reason), rowAt))).toContain("</div>");
+ // And it is the flip's own line: with nothing refused, no alert is on screen at all.
+ 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));