A local-first multi-agent app development platform, built on PenguinHarness
/**
* The messaging binding editor, rendered to static markup
* (features/messaging/messaging-binding-editor.tsx).
*
* - The form opens on its fields, the explanation living in the collapsed help below; each
* channel's credential-source link rides the credential field's corner and is labelled with
* what it opens.
* - A stored secret is removed through the clear checkbox, gated on screen while the channel
* holds the connection; the connection switch carries the bind/unbind sentence as its
* tooltip, and its gating reason when another channel holds the connection.
* - A gated switch stays clickable; the gate names, per channel, what is missing and where a
* click sends focus to supply it.
* - A connection error gets its own line, whole, and stays on screen after the connection
* recovers; arrival is reported while connecting and erroring, naming the inbound stage when
* a message arrived but its task never started.
* - 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
* extra when privacy is off or unknown, and a failure as one error line.
*/
import { afterEach, describe, expect, it } from "vitest";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import type { MessagingChannel } from "@adelie/server/api";
import {
MessagingBindingBody,
MessagingBindingHelp,
enablePrerequisite,
telegramTestNotices,
type MessagingBindingEditorState,
type MessagingChannelFacts,
} from "../src/features/messaging/messaging-binding-editor";
import { emptyMessagingForm } from "../src/features/messaging/messaging-binding-form";
import { UiStringsProvider } from "@adelie/ui";
import { S, setActiveStrings, zh } from "../src/lib/strings";
import { uiStringsOf } from "../src/lib/ui-strings";
import { en } from "../src/lib/strings-en";
import { formatDateTime } from "../src/lib/format";
afterEach(() => setActiveStrings(zh));
const DARK: MessagingChannelFacts = {
secretConfigured: false,
secretMasked: null,
enabled: false,
status: { state: "disconnected" },
lastChatKnown: false,
};
/**
* Where a channel's credential section starts, for the assertions that the delivery rows
* trail it. WeChat has no credential FIELD — its token comes only from a scan — so its scan
* button is what stands at the head of that section.
*/
function credentialAnchor(channel: MessagingChannel): string {
if (channel === "telegram") return S.telegram.botToken;
if (channel === "qq") return S.qq.appId;
if (channel === "wechat") return S.wechat.scanStart;
return S.feishu.appId;
}
/** A state object shaped like the hook's, with the handlers stubbed (this renders, never acts). */
function stateOf(
channel: MessagingChannel,
facts: Partial<Record<MessagingChannel, MessagingChannelFacts>> = {},
extra: Partial<MessagingBindingEditorState> = {},
): MessagingBindingEditorState {
const noop = async () => {};
return {
sessionId: "session-under-test",
form: emptyMessagingForm(channel),
patchForm: () => {},
selectChannel: () => {},
channels: { feishu: DARK, telegram: DARK, qq: DARK, wechat: DARK, ...facts },
fieldErrors: {},
dirty: false,
busy: false,
toggling: false,
testing: false,
sendingTest: false,
testable: false,
toggleBusy: false,
enableGate: null,
toggleRefusal: null,
testRefusal: null,
testMessageRefusal: null,
saveRefusal: null,
saveButtonId: "save-under-test",
adoptBinding: () => {},
save: noop,
toggleEnabled: noop,
testConnection: noop,
sendTestMessage: noop,
...extra,
};
}
// The "?" labels read the package's UiStrings, which the app provides from the active dictionary.
const render = (state: MessagingBindingEditorState) =>
renderToStaticMarkup(
createElement(
UiStringsProvider,
{ strings: uiStringsOf(S) },
createElement(MessagingBindingBody, { b: state }),
),
);
describe("MessagingBindingBody", () => {
it("opens on the fields: no explanatory prose above the first input", () => {
const feishu = render(stateOf("feishu"));
expect(feishu).toContain(S.feishu.appId);
// The intro moved into the FAQ fold; leading the form with it is what this change undid.
expect(feishu).not.toContain(S.feishu.intro);
expect(render(stateOf("telegram"))).not.toContain(S.telegram.intro);
});
it("hangs each channel's credential source on its credential field's corner", () => {
// The models dialog's "get API key" idiom: the link sits where the value is pasted, so the
// reader never has to leave the field to find out where the value comes from.
expect(render(stateOf("feishu"))).toContain('href="https://open.feishu.cn/app"');
// Telegram's Bot Token is issued by @BotFather in the app, not by a web console — the
// corner link goes there rather than into the API reference it used to point at.
const telegram = render(stateOf("telegram"));
expect(telegram).toContain('href="https://t.me/BotFather"');
expect(telegram).not.toContain("core.telegram.org/bots/api");
// QQ's trailing slash is load-bearing — https://q.qq.com/qqbot/dashboard answers 404 —
// so it is pinned here rather than left to be tidied away by someone normalizing URLs.
const qq = render(stateOf("qq"));
expect(qq).toContain('href="https://q.qq.com/qqbot/dashboard/"');
expect(qq).not.toContain('href="https://q.qq.com/qqbot/dashboard"');
});
it("labels that corner link with what it opens, never with a console Telegram has not got", () => {
// The defect this pins: a link labelled "open developer console" that landed in the API
// manual. Both dictionaries, because the label is per-locale and `S` is zh until a test
// says otherwise — an assertion against the active dictionary alone would leave English
// free to carry the very wording this fixed.
for (const dict of [zh, en]) {
setActiveStrings(dict);
// Label and target in ONE assertion: pinned apart, they pass just as happily with the
// right href on the wrong anchor.
const telegram = render(stateOf("telegram"));
const corner = /<a href="https:\/\/t\.me\/BotFather"[^>]*>([^<]*)<\/a>/.exec(telegram);
expect(corner?.[1]).toBe(`${dict.telegram.openBotFather} ↗`);
expect(telegram).not.toContain(dict.messaging.console);
// ...and the channels that do have a console keep it.
expect(render(stateOf("feishu"))).toContain(dict.messaging.console);
expect(render(stateOf("qq"))).toContain(dict.messaging.console);
}
});
it("offers a stored secret's removal as the clear checkbox, gated on screen while enabled", () => {
const saved: MessagingChannelFacts = {
secretConfigured: true,
secretMasked: "abcd…7890",
enabled: false,
status: { state: "disconnected" },
lastChatKnown: false,
};
const dark = render(stateOf("feishu", { feishu: saved }));
expect(dark).toContain("abcd…7890");
expect(dark).toContain(S.feishu.clearSecret);
expect(dark).toMatch(/<input[^>]*type="checkbox"[^>]*\/>/);
expect(dark).not.toContain(S.messaging.disableBeforeClearHint);
// Enabled: clearing would leave a live connection running on a credential the store no
// longer has, so the box is disabled — and says why, since a disabled control does not
// reliably fire hover.
const live = render(
stateOf("feishu", { feishu: { ...saved, enabled: true, status: { state: "connected" } } }),
);
expect(live).toContain('type="checkbox" disabled=""');
expect(live).toContain(S.messaging.disableBeforeClearHint);
});
it("carries the bind/unbind sentence on the switch itself, as a tooltip rather than a line", () => {
// Enabling the connection is what binds the bot to this conversation, which a label
// reading "enable connection" does not say. It is semantics, so it is disclosed: on the
// control, where nothing below has to move to make room for it.
const html = render(stateOf("feishu"));
expect(html).toContain(`data-tooltip="${S.messaging.bindByEnableHint}"`);
expect(html).not.toContain(`>${S.messaging.bindByEnableHint}<`);
});
it("gives a connection error its own line, whole, instead of a share of the status row", () => {
// The connection failures worth reporting name the action in the sentence — a share of
// a row that already carries a switch, a label and a status word cut this one to
// "Conflict: ter", which tells the reader nothing they can act on.
const lastError =
"getUpdates failed: another program is already polling this bot — one bot token can serve only one Adelie server at a time (code 409)";
const html = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: { state: "error", lastError },
},
}),
);
// A paragraph of its own, carrying the message whole.
expect(html).toContain(`>${lastError}</p>`);
// Outside the toggle row: the row closes before the message begins.
const rowAt = html.indexOf("flex flex-wrap items-center gap-2 text-xs");
expect(rowAt).toBeGreaterThanOrEqual(0);
expect(html.slice(rowAt, html.indexOf(lastError, rowAt))).toContain("</div>");
// Bounded so an error still cannot push the probes far, with the whole text on hover.
expect(html).toContain("line-clamp-2");
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("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("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 closes
// the body because that is above Save in BOTH hosts (the dialog's footer, the panel's own
// row under the form), which is why the slot lives here rather than in either host.
const line = S.messaging.saveRefused(S.errors.byCode["internal"] as string);
const html = render(stateOf("telegram", {}, { saveRefusal: line }));
expect(html).toContain(`>${line}</p>`);
expect(html).toContain('role="alert"');
// At the foot: after the delivery options that close the form, not among the controls.
expect(html.indexOf(line)).toBeGreaterThan(html.indexOf(S.messaging.renderMarkdown));
expect(html.indexOf(line)).toBeGreaterThan(html.indexOf(S.telegram.botToken));
// Bounded, with the whole sentence on hover.
expect(html).toContain(`data-tooltip="${line}"`);
expect(html).toContain("line-clamp-2");
// And it is that save'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));
// Every channel carries both: they are delivery preferences, not credentials.
expect(html).toContain(S.messaging.linePerMessage);
expect(html).toContain(S.messaging.finalReplyOnly);
// Semantics disclose — each sentence is in a popover panel, which renders collapsed.
expect(html).toContain(S.common.moreInfoAbout(S.messaging.linePerMessage));
expect(html).toContain(S.common.moreInfoAbout(S.messaging.finalReplyOnly));
expect(html).not.toContain(S.messaging.linePerMessageHelp);
expect(html).not.toContain(S.messaging.finalReplyOnlyHelp);
// After the credential fields, not among them.
const fieldAt = html.indexOf(credentialAnchor(channel));
expect(fieldAt).toBeGreaterThanOrEqual(0);
expect(html.indexOf(S.messaging.finalReplyOnly)).toBeGreaterThan(fieldAt);
// In the order the two take effect: which messages are sent, then how each is split.
expect(html.indexOf(S.messaging.linePerMessage)).toBeGreaterThan(
html.indexOf(S.messaging.finalReplyOnly),
);
}
});
it("renders each delivery switch from its own form field", () => {
// One row per option, each fed from the SELECTED channel's sub-state: a row wired to the
// wrong field renders a switch that is on while the form says off, which no type checker
// and no snapshot of the default state would catch.
const form = emptyMessagingForm("telegram");
form.telegram.finalReplyOnly = true;
// Markdown rendering defaults ON, so the fresh form already has two of the three rows in
// opposite states — which is what makes each row's slice worth reading separately.
const html = render(stateOf("telegram", {}, { form }));
const finalAt = html.indexOf(S.messaging.finalReplyOnly);
const lineAt = html.indexOf(S.messaging.linePerMessage);
const markdownAt = html.indexOf(S.messaging.renderMarkdown);
expect(finalAt).toBeGreaterThanOrEqual(0);
expect(lineAt).toBeGreaterThan(finalAt);
expect(markdownAt).toBeGreaterThan(lineAt);
// Each switch reads its own field: flipped, unflipped, and on by default.
expect(html.slice(finalAt, lineAt)).toContain('aria-checked="true"');
expect(html.slice(lineAt, markdownAt)).toContain('aria-checked="false"');
expect(html.slice(markdownAt)).toContain('aria-checked="true"');
});
it('closes the form with the Markdown option too, its per-channel explanation behind the "?"', () => {
const help = {
feishu: S.messaging.renderMarkdownHelpFeishu,
telegram: S.messaging.renderMarkdownHelpTelegram,
qq: S.messaging.renderMarkdownHelpQQ,
wechat: S.messaging.renderMarkdownHelpWeChat,
} as const;
for (const channel of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
const html = render(stateOf(channel));
expect(html).toContain(S.messaging.renderMarkdown);
// Semantics disclose — the sentence is in the popover panel, which renders collapsed.
expect(html).toContain(S.common.moreInfoAbout(S.messaging.renderMarkdown));
expect(html).not.toContain(help[channel]);
// One sentence per channel: what a channel can show is the whole of what the reader
// needs here, and a shared line would have to say "depending on the channel".
for (const other of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
if (other !== channel) expect(html).not.toContain(help[other]);
}
// After the credential fields, like the other delivery preference.
const fieldAt = html.indexOf(credentialAnchor(channel));
expect(html.indexOf(S.messaging.renderMarkdown)).toBeGreaterThan(fieldAt);
}
});
it("states QQ's replies-only rule on screen, not in a collapsed fold", () => {
// The one piece of channel copy that cannot wait to be unfolded. QQ delivers only
// replies to messages sent from QQ, so a user who binds it and then works in the web app
// sees nothing arrive and concludes the binding is broken. Every other channel's
// explanation stays in the FAQ; this one is a line under the fields.
const html = render(stateOf("qq"));
expect(html).toContain(S.qq.repliesOnly);
// Under the credential fields, so the controls above hold one height across channels.
expect(html.indexOf(S.qq.repliesOnly)).toBeGreaterThan(html.indexOf(S.qq.appSecret));
// ...and it belongs to QQ alone.
expect(render(stateOf("feishu"))).not.toContain(S.qq.repliesOnly);
});
it("offers all four channels in the selector", () => {
const html = render(stateOf("qq"));
for (const name of [
S.messaging.channelName.feishu,
S.messaging.channelName.telegram,
S.messaging.channelName.qq,
S.messaging.channelName.wechat,
]) {
expect(html).toContain(`>${name}</button>`);
}
// The grid's column count is spelled out in the component rather than interpolated, so
// a fourth channel that did not widen it would silently wrap onto a second row.
expect(html).toContain("grid-cols-4");
});
it("says whether anything has arrived, and which end failed when something did", () => {
// A bot Telegram is withholding messages from is `connected` with no error, forever.
// Without this line the panel has nothing to distinguish it from a healthy binding
// nobody has written to.
const quiet = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: { state: "connected" },
},
}),
);
expect(quiet).toContain(S.messaging.inboundNone);
const seen = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: { state: "connected", lastInboundAt: "2026-08-26T09:30:00.000Z" },
},
}),
);
expect(seen).toContain(S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")));
expect(seen).not.toContain(S.messaging.inboundNone);
// The two post-arrival failures are the same silence in the chat and different actions
// for the reader, so the line names the stage rather than only the message.
const detail = "Bad Request: have no rights to send a message";
const at = "2026-08-26T09:31:00.000Z";
const failed = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: {
state: "connected",
lastInboundAt: "2026-08-26T09:30:00.000Z",
lastDeliveryError: { at, stage: "send", detail },
},
},
}),
);
expect(failed).toContain(S.messaging.deliveryFailedSend(formatDateTime(at), detail));
expect(failed).not.toContain(S.messaging.deliveryFailedInbound(formatDateTime(at), detail));
// The failure's own time is in the sentence, not parked in title=: nothing clears the
// record on a later success, so a rights problem fixed three days ago would otherwise
// read as live — and a hover-only title is unreachable on a touch screen.
expect(failed).toContain(`>${S.messaging.deliveryFailedSend(formatDateTime(at), detail)}</p>`);
expect(failed).toContain(`data-tooltip="${detail}"`);
// Arrival is still reported: a send failure is not a delivery failure.
expect(failed).toContain(S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")));
});
it("names the inbound stage when a message arrived and its task never started", () => {
// The stage is an instruction, not a wording: "it never started" sends the reader to the
// Session, "the reply never went out" sends them to the bot's rights in the chat. Only
// the send branch had ever been rendered here, so the other could break unseen.
// No apostrophe in the fixture: renderToStaticMarkup escapes one, and the assertion
// below matches the rendered text rather than the string the dictionary returned.
const detail = "The Workspace this Session runs in no longer exists";
const at = "2026-08-26T09:31:00.000Z";
const html = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: {
state: "connected",
lastInboundAt: "2026-08-26T09:30:00.000Z",
lastDeliveryError: { at, stage: "inbound", detail },
},
},
}),
);
expect(html).toContain(`>${S.messaging.deliveryFailedInbound(formatDateTime(at), detail)}</p>`);
expect(html).not.toContain(S.messaging.deliveryFailedSend(formatDateTime(at), detail));
});
it("reports arrival while connecting and while erroring: it is traffic, not the socket", () => {
const live: MessagingChannelFacts = { ...DARK, secretConfigured: true, enabled: true };
// Telegram's connect runs getMe, getWebhookInfo, a backlog drain and a first getUpdates
// before it reads as connected, and a token two programs are fighting over sits in
// `error` half the time. Gating this line on `connected` hid it in both — the flapping
// case being the one the panel was written for.
const connecting = render(
stateOf("telegram", { telegram: { ...live, status: { state: "connecting" } } }),
);
expect(connecting).toContain(S.messaging.inboundNone);
const erroring = render(
stateOf("telegram", {
telegram: {
...live,
status: {
state: "error",
lastError: "another program is already polling this bot",
lastInboundAt: "2026-08-26T09:30:00.000Z",
},
},
}),
);
// In `error`, a bot that has been receiving fine and one that never has are different
// problems, and lastConnectionError is hidden there — this line is all that separates them.
expect(erroring).toContain(
S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")),
);
// A binding with no connection has no such record and must not claim one.
const dark = render(stateOf("telegram", { telegram: { ...DARK, secretConfigured: true } }));
expect(dark).not.toContain(S.messaging.inboundNone);
});
it("leaves the last connection failure on screen after the connection recovers", () => {
const detail = "another program is already polling this bot";
const html = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: {
state: "connected",
lastConnectionError: { at: "2026-08-26T09:00:00.000Z", detail },
},
},
}),
);
// A flapping connector is `connected` in every snapshot between its failures, so without
// this the reader sees a healthy binding and no trace of the cause.
expect(html).toContain(
S.messaging.lastConnectionError(formatDateTime("2026-08-26T09:00:00.000Z"), detail),
);
// While the connection is actually down, `lastError` is the live one and this must not
// double up beside it.
const down = render(
stateOf("telegram", {
telegram: {
...DARK,
secretConfigured: true,
enabled: true,
status: {
state: "error",
lastError: detail,
lastConnectionError: { at: "2026-08-26T09:00:00.000Z", detail },
},
},
}),
);
expect(down).toContain(`>${detail}</p>`);
expect(down).not.toContain(
S.messaging.lastConnectionError(formatDateTime("2026-08-26T09:00:00.000Z"), detail),
);
});
it("shows the switch's gating reason, and leaves a gated switch clickable", () => {
const hint = S.messaging.otherEnabledHint(S.messaging.channelName.feishu);
const html = render(
stateOf(
"telegram",
{ feishu: { ...DARK, secretConfigured: true, enabled: true } },
{ enableGate: { hint, focus: null } },
),
);
expect(html).toContain(hint);
// Dimmed and announced as unavailable, but not natively disabled: a click has to reach
// the handler that explains what to do first.
const toggle = /<button[^>]*role="switch"[^>]*>/.exec(html)?.[0] ?? "";
expect(toggle).toContain('aria-disabled="true"');
expect(toggle).not.toContain('disabled=""');
});
});
describe("enablePrerequisite", () => {
const stored = { enabled: false, secretConfigured: true };
const blank = { enabled: false, secretConfigured: false };
it("names what each channel is missing and where focus goes to supply it", () => {
const expected = {
feishu: "credential",
telegram: "credential",
qq: "scan",
wechat: "scan",
} as const;
for (const channel of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
// No stored credential: the per-channel sentence, focus on the scan or the typed field.
expect(
enablePrerequisite({ channel, facts: blank, enabledChannel: null, dirty: false }),
).toEqual({ hint: S.messaging.credentialMissingHint[channel], focus: expected[channel] });
// Stored but edited since: save first.
expect(
enablePrerequisite({ channel, facts: stored, enabledChannel: null, dirty: true }),
).toEqual({ hint: S.messaging.saveBeforeEnable, focus: "save" });
// Another channel holds the connection: that outranks the rest, and its fix is not on
// this form, so focus stays put.
const other: MessagingChannel = channel === "feishu" ? "telegram" : "feishu";
expect(
enablePrerequisite({ channel, facts: blank, enabledChannel: other, dirty: true }),
).toEqual({
hint: S.messaging.otherEnabledHint(S.messaging.channelName[other]),
focus: null,
});
// Nothing missing; and turning a live connection off is never gated.
expect(
enablePrerequisite({ channel, facts: stored, enabledChannel: null, dirty: false }),
).toBeNull();
expect(
enablePrerequisite({
channel,
facts: { enabled: true, secretConfigured: true },
enabledChannel: channel,
dirty: true,
}),
).toBeNull();
}
});
});
describe("MessagingBindingHelp", () => {
it("stacks three self-titled folds, all collapsed, carrying the relocated explanation", () => {
const html = renderToStaticMarkup(
createElement(MessagingBindingHelp, { channel: "feishu" as MessagingChannel }),
);
for (const title of [
S.messaging.faqSetupTitle,
S.messaging.faqWhatTitle,
S.messaging.faqTroubleTitle,
]) {
expect(html).toContain(title);
}
expect(html.match(/aria-expanded="false"/g)).toHaveLength(3);
expect(html.match(/<div id="[^"]+" hidden/g)).toHaveLength(3);
// The panels stay in the DOM while folded (aria-controls has to resolve), so the text is
// present — hidden, not absent.
expect(html).toContain(S.feishu.intro);
// The channel-neutral half of that fold: how one bot moves between conversations, which
// is the question the enable-time 409 sends a reader here with.
expect(html).toContain(S.messaging.faqWhatBinding);
expect(html).toContain(S.messaging.troubleNoChat);
expect(html).toContain(S.feishu.setupSteps[0]);
});
it("carries the Telegram-only troubleshooting entries, and neither of them on Feishu", () => {
const telegram = renderToStaticMarkup(
createElement(MessagingBindingHelp, { channel: "telegram" as MessagingChannel }),
);
// Group Privacy is on by default and produces silence, not an error, so the fold is the
// only place a user who has not run a credential test can find out about it.
expect(telegram).toContain(S.messaging.troubleGroupPrivacy);
expect(telegram).toContain(S.messaging.troubleOnePoller);
const feishu = renderToStaticMarkup(
createElement(MessagingBindingHelp, { channel: "feishu" as MessagingChannel }),
);
expect(feishu).not.toContain(S.messaging.troubleGroupPrivacy);
expect(feishu).not.toContain(S.messaging.troubleOnePoller);
});
it("puts each channel's tutorial link in its setup fold", () => {
const feishu = renderToStaticMarkup(
createElement(MessagingBindingHelp, { channel: "feishu" as MessagingChannel }),
);
expect(feishu).toContain(
'href="https://open.feishu.cn/document/develop-an-echo-bot/introduction"',
);
const telegram = renderToStaticMarkup(
createElement(MessagingBindingHelp, { channel: "telegram" as MessagingChannel }),
);
// The BotFather guide, not "From BotFather to 'Hello World'": the reader of this fold is
// creating a bot to paste a token from, not writing one.
expect(telegram).toContain('href="https://core.telegram.org/bots/features#botfather"');
expect(telegram).toContain(S.telegram.setupSteps[0]);
const qq = renderToStaticMarkup(
createElement(MessagingBindingHelp, { channel: "qq" as MessagingChannel }),
);
// The onboarding guide, not the API reference: this fold is read by someone creating a
// bot and looking for its credentials.
expect(qq).toContain('href="https://bot.q.qq.com/wiki/"');
expect(qq).toContain(S.qq.setupSteps[0]);
// What the QR button spares the reader belongs beside those steps, not beside the
// button: it is semantics, and a control is not a title for a standing sentence.
expect(qq).toContain(S.qq.scanHint);
// The reply budget is how this channel delivers a long answer, not a fault: it rides the
// "what binding does" fold, while the passive-reply failure rides troubleshooting.
expect(qq).toContain(S.qq.replyBudget);
expect(qq).toContain(S.messaging.troubleQQPassive);
expect(telegram).not.toContain(S.messaging.troubleQQPassive);
});
});
describe("telegramTestNotices", () => {
it("adds the privacy notice as a second line, leaving the success line untouched", () => {
// Two lines, not one longer one: the credentials passed and a direct chat will answer,
// so the success line is the truth and the privacy line is a separate caveat.
expect(
telegramTestNotices({
ok: true,
latencyMs: 12,
botUsername: "@penguin_bot",
groupPrivacy: true,
}),
).toEqual([
{ tone: "success", text: S.messaging.testOkAs("@penguin_bot", 12) },
{ tone: "info", text: S.messaging.testPrivacyOn },
]);
});
it("says nothing extra when privacy is off, or when getMe never reported it", () => {
expect(telegramTestNotices({ ok: true, latencyMs: 12, groupPrivacy: false })).toEqual([
{ tone: "success", text: S.messaging.testOk(12) },
]);
// Absent is unknown, and unknown is not a problem: a notice on a field the API never
// sent would send a user to @BotFather for nothing.
expect(telegramTestNotices({ ok: true, latencyMs: 12 })).toEqual([
{ tone: "success", text: S.messaging.testOk(12) },
]);
});
it("reports a failed test as one error line and nothing else", () => {
expect(telegramTestNotices({ ok: false, error: "Unauthorized", groupPrivacy: true })).toEqual([
{ tone: "error", text: S.messaging.testFail("Unauthorized") },
]);
});
});