Skip to content

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

61.7 KB
Raw Blame
/**
 * Shared messaging binding editor — ONE implementation behind both the session-row dialog
 * and the conversation's Messaging dock panel (the two hosts differ only in where they
 * place the Save action and the FAQ folds, so the state machine is a hook and the pieces
 * are body components; neither host forks the form).
 *
 * Channel model: a Session keeps at most one saved config PER channel — all of them may
 * sit saved side by side — and AT MOST ONE of them is enabled. The channel selector
 * switches freely between the channel forms (each independently savable, each showing its
 * own configured/enabled state); enabling one channel while another is enabled is gated
 * with a "turn that one off first" hint (the server refuses it too, 409).
 *
 * The form opens on the connection controls and the credential fields trail them: the
 * channels' field lists differ in length, so controls placed under the fields would sit at
 * a different height in each channel and move on every switch. That is also why QQ's
 * replies-only rule — the one piece of channel copy too load-bearing to leave in a
 * collapsed fold — sits below its fields rather than above them. The explanation lives in
 * collapsed FAQ folds below the save area (`MessagingBindingHelp`), and the channel's
 * leading credential field — where the value starts being pasted — carries at its label's
 * top-right corner a link to wherever that channel issues the credential (the models-page
 * "get API key" idiom, which puts the link on the field, not in a row of its own). Secrets
 * follow that page's interaction: the field always starts empty, a stored secret shows as a
 * masked line under it with a "clear stored …" checkbox (typing unchecks it; applied on
 * Save), blank keeps the stored value — and clearing requires the channel's connection to be
 * disabled first. The connection switch IS the bind/unbind control — enabling binds the
 * bot to this conversation, turning it off releases it, and the credentials stay saved
 * through both, so several conversations may keep one bot saved and take turns holding it
 * (the server refuses a second live one with 409 `account_enabled_elsewhere`, naming
 * nothing about who holds it). That is semantics, so it is disclosed rather than parked on
 * screen: the switch carries it as its tooltip and the "what binding does" fold states it
 * in full. Deleting a stored credential remains a separate act — the per-field clear.
 *
 * Two channels lead their section with scan-to-connect, after which the server holds the
 * credentials without them ever passing through this browser. On QQ (`qq-scan-connect.tsx`)
 * the typed fields stay below the QR as the fallback; on WeChat
 * (`wechat-scan-connect.tsx`) there are no fields at all, because the bot token has no other
 * source — so that channel's section is the QR, the stored-token row, and nothing else.
 *
 * The GET is re-polled while the host shows the editor (the hook's `poll` flag) so
 * connect/error flips show up live.
 */
import { useEffect, useId, useRef, useState } from "react";
import type { ReactNode } from "react";
import type {
  MessagingBindingInfo,
  MessagingBindingsResponse,
  MessagingChannel,
  MessagingRuntimeStatus,
  TelegramTestResponse,
} from "@adelie/server/api";
import {
  Button,
  Checkbox,
  FieldLabel,
  HelpFold,
  InfoPopover,
  Input,
  PasswordInput,
  Segmented,
  Switch,
  toastError,
  toastInfo,
  toastSuccess,
} from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatDateTime } from "../../lib/format";
import { toneInk, type Tone } from "../../lib/tone";
import { QQScanConnect } from "./qq-scan-connect";
import { WeChatScanConnect } from "./wechat-scan-connect";
import { messagingTestRefusal } from "./messaging-test-refusal";
import { messagingTestMessageRefusal } from "./messaging-test-message-refusal";
import { messagingSaveRefusal } from "./messaging-save-refusal";
import {
  bindingsToForm,
  emptyMessagingForm,
  formDirty,
  formTestable,
  formToPut,
  formToTest,
  type MessagingDeliveryFields,
  type MessagingFormErrors,
  type MessagingFormState,
} from "./messaging-binding-form";

/** How often the visible editor refreshes the runtime status (connects settle within a poll or two). */
const STATUS_POLL_MS = 3000;

/** How long the hint line holds its attention colour after a click on the gated switch. */
const HINT_EMPHASIS_MS = 1500;

/** What a focus hand-off may land on inside the scan block; the first match wins. */
const FOCUSABLE =
  "button:not([disabled]), input:not([disabled]), a[href], [tabindex]:not([tabindex='-1'])";

/**
 * Per-channel external links: the walkthrough (setup FAQ fold) and where the channel issues
 * the credential (field corner). The second is a developer console for some channels and a
 * chat with a bot for others, so its label belongs to the channel — only the ones that do
 * have a console reach for the shared `S.messaging.console` wording.
 *
 * A channel may have NEITHER, which is why the entry is nullable: WeChat's bot is authorized
 * by a scan and has no public console and no walkthrough to point at, and inventing a URL
 * would send a reader to a page that does not answer them.
 */
const CHANNEL_LINKS = {
  feishu: {
    // Feishu's own echo-bot walkthrough: creating a self-built app and its long connection.
    tutorial: "https://open.feishu.cn/document/develop-an-echo-bot/introduction",
    credentialSource: "https://open.feishu.cn/app",
  },
  telegram: {
    // The BotFather section of the bot-features page: "a detailed guide to using
    // @BotFather", opening on /newbot and the token it returns — which is this fold's
    // steps, one level deeper. NOT /bots/tutorial: that one is "From BotFather to 'Hello
    // World'", and past its token section it is about downloading an IDE and picking a
    // framework, i.e. about WRITING a bot. Nobody here is writing one — Adelie is
    // the bot. The fragment is a plain document anchor present in the served HTML, so it
    // lands where it says (unlike a hash route, which the server never sees).
    tutorial: "https://core.telegram.org/bots/features#botfather",
    // Where the credential is actually issued. Telegram has no web console: the token comes
    // from @BotFather inside the app, and this link is the one that leads there.
    credentialSource: "https://t.me/BotFather",
  },
  qq: {
    // The wiki ROOT is the onboarding guide itself — "介绍与接入指南": registering a
    // developer account, creating the bot, and the page its AppID and AppSecret are shown
    // on. That is what a reader of the setup fold is after; the API reference one level
    // down at /develop/api-v2/ answers a question they are not asking yet.
    tutorial: "https://bot.q.qq.com/wiki/",
    // The trailing slash is load-bearing and must not be tidied away: /qqbot/dashboard
    // answers 404, while /qqbot/ alone serves a 700-byte shell that only lands anywhere
    // because the retired hash-route app still redirects out of it.
    credentialSource: "https://q.qq.com/qqbot/dashboard/",
  },
  wechat: null,
} as const satisfies Record<
  MessagingChannel,
  { tutorial: string; credentialSource: string } | null
>;

const STATUS_TONE: Record<MessagingRuntimeStatus["state"], Tone> = {
  disconnected: "muted",
  connecting: "busy",
  connected: "success",
  error: "danger",
};

function errorText(code: MessagingFormErrors[keyof MessagingFormErrors]): string | undefined {
  if (code === undefined) return undefined;
  if (code === "required") return S.common.requiredField;
  if (code === "token_invalid") return S.telegram.invalidToken;
  return S.feishu.invalidDomain;
}

/** One channel's server-side facts, as the editor renders them (the form fields stay client-side). */
export interface MessagingChannelFacts {
  /** A secret is stored (a cleared config keeps its row but loses this). */
  secretConfigured: boolean;
  /** The stored secret's site-wide mask (display-only, never round-trips); null without one. */
  secretMasked: string | null;
  enabled: boolean;
  status: MessagingRuntimeStatus;
  lastChatKnown: boolean;
}

const EMPTY_FACTS: MessagingChannelFacts = {
  secretConfigured: false,
  secretMasked: null,
  enabled: false,
  status: { state: "disconnected" },
  lastChatKnown: false,
};

type ChannelFactsMap = Record<MessagingChannel, MessagingChannelFacts>;

function factsOf(
  binding: MessagingBindingInfo | null,
  status: MessagingRuntimeStatus,
): MessagingChannelFacts {
  if (binding === null) return { ...EMPTY_FACTS, status };
  // The two token channels name the field `botTokenMasked`; the two App-Secret ones name it
  // `appSecretMasked`. Both are the same fact — a credential is stored — under the name its
  // own channel gives it.
  const masked =
    binding.channel === "telegram" || binding.channel === "wechat"
      ? binding.botTokenMasked
      : binding.appSecretMasked;
  return {
    secretConfigured: masked !== undefined,
    secretMasked: masked ?? null,
    enabled: binding.enabled,
    status,
    lastChatKnown: binding.lastChatKnown,
  };
}

function factsFromList(res: MessagingBindingsResponse): ChannelFactsMap {
  const map: ChannelFactsMap = {
    feishu: EMPTY_FACTS,
    telegram: EMPTY_FACTS,
    qq: EMPTY_FACTS,
    wechat: EMPTY_FACTS,
  };
  for (const entry of res.bindings) {
    map[entry.binding.channel] = factsOf(entry.binding, entry.status);
  }
  return map;
}

/** Everything a host renders the editor from: state + handlers, one instance per session. */
export interface MessagingBindingEditorState {
  /** The Session being edited (flows that talk to the API from inside the body need it). */
  sessionId: string;
  /** null until the stored bindings have been loaded (hosts show nothing until then). */
  form: MessagingFormState | null;
  patchForm(patch: Partial<MessagingFormState>): void;
  /** The selector's write: switches which channel's form shows (both stay editable). */
  selectChannel(channel: MessagingChannel): void;
  /** Per-channel server-side facts (secret / enabled / status / chat-known). */
  channels: ChannelFactsMap;
  fieldErrors: MessagingFormErrors;
  /** Unsaved edits on the SELECTED channel (a typed secret and a checked clear box count). */
  dirty: boolean;
  busy: boolean;
  toggling: boolean;
  testing: boolean;
  sendingTest: boolean;
  /** The credential probe needs a testable credential: the selected channel's draft or stored secret. */
  testable: boolean;
  /** A save or a toggle is in flight: the switch is natively disabled until it settles. */
  toggleBusy: boolean;
  /**
   * What must happen before the switch may enable the selected channel (null when nothing
   * 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;
  /**
   * Why the last credential probe did not get through (null when it connected or none ran). It
   * stays under the button that asked until the form is edited, the channel is switched or the
   * next probe starts — see `messaging-test-refusal.ts`.
   */
  testRefusal: string | null;
  /**
   * 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,
   * which is what makes it readable after the attempt — see `messaging-save-refusal.ts`.
   */
  saveRefusal: string | null;
  /** The id hosts give their Save action, so a switch gated on unsaved edits can focus it. */
  saveButtonId: string;
  /**
   * A flow OUTSIDE the form saved this channel's binding — either scan-to-connect, whose
   * credentials never pass through the browser. Folds the result into that channel's facts
   * and the form baseline, exactly as a Save would.
   */
  adoptBinding(binding: MessagingBindingInfo): void;
  save(): Promise<void>;
  toggleEnabled(next: boolean): Promise<void>;
  testConnection(): Promise<void>;
  sendTestMessage(): Promise<void>;
}

/** One notice a credential test produces; the tone picks the toast that carries it. */
export interface MessagingTestNotice {
  tone: "success" | "info" | "error";
  text: string;
}

/**
 * The notices one Telegram credential-test response turns into, in the order they are shown
 * (the updateCheckOutcome idiom: the classification is a pure function, the host only picks
 * toasts for it).
 *
 * A success whose bot still has Group Privacy on produces TWO. The success line stands
 * unchanged — the credentials really are fine, and the bot really will answer a direct chat —
 * and the privacy notice rides beside it rather than lengthening it: it is about group chats
 * only, and it is the one thing a user cannot discover by testing, since a bot that cannot
 * hear a group produces silence and never an error.
 */
export function telegramTestNotices(res: TelegramTestResponse): MessagingTestNotice[] {
  if (!res.ok) {
    return [{ tone: "error", text: S.messaging.testFail(res.error ?? S.common.unknownError) }];
  }
  const ms = res.latencyMs ?? 0;
  const notices: MessagingTestNotice[] = [
    // The success line names the bot: the one detail a user can check against @BotFather.
    {
      tone: "success",
      text:
        res.botUsername !== undefined
          ? S.messaging.testOkAs(res.botUsername, ms)
          : S.messaging.testOk(ms),
    },
  ];
  // Only an answered `true`: an absent field is unknown, and unknown is not a problem.
  if (res.groupPrivacy === true) notices.push({ tone: "info", text: S.messaging.testPrivacyOn });
  return notices;
}

/** Where a click on the prerequisite-gated switch moves focus. */
export type EnableFocus = "scan" | "credential" | "save";

/** The unmet prerequisite that keeps the selected channel from being enabled. */
export interface EnablePrerequisite {
  /** The sentence the hint line shows, and a click on the switch repeats as a toast. */
  hint: string;
  /**
   * Where that click sends focus: the QR block on the scan channels, the first empty
   * credential field on the typed ones, or the Save action. Null when the fix is turning
   * another channel off, which is not on this form.
   */
  focus: EnableFocus | null;
}

/**
 * Why the selected channel cannot be enabled yet, strongest reason first: another channel
 * holds the connection, no credential is stored, the form has unsaved edits. Null when it can,
 * and always while it is enabled: turning a live connection off is never gated.
 */
export function enablePrerequisite({
  channel,
  facts,
  enabledChannel,
  dirty,
}: {
  channel: MessagingChannel;
  facts: Pick<MessagingChannelFacts, "enabled" | "secretConfigured">;
  /** The channel enabled on this Session, if any. */
  enabledChannel: MessagingChannel | null;
  /** Unsaved edits on the selected channel's form. */
  dirty: boolean;
}): EnablePrerequisite | null {
  if (facts.enabled) return null;
  if (enabledChannel !== null && enabledChannel !== channel) {
    return {
      hint: S.messaging.otherEnabledHint(S.messaging.channelName[enabledChannel]),
      focus: null,
    };
  }
  if (!facts.secretConfigured) {
    return {
      hint: S.messaging.credentialMissingHint[channel],
      // QQ's typed fields are the fallback below its QR, so the scan is where it starts too.
      focus: channel === "qq" || channel === "wechat" ? "scan" : "credential",
    };
  }
  if (dirty) return { hint: S.messaging.saveBeforeEnable, focus: "save" };
  return null;
}

export function useMessagingBinding(
  sessionId: string,
  opts: {
    /** Keep the status poll running (hosts pass their visibility, e.g. the dock tab's `active`). */
    poll: boolean;
    /** Fired when the ENABLED channel changed (null = none); callers refresh their row/list indicator. */
    onChanged?: (sessionId: string, channel: MessagingChannel | null) => void;
    /** Fired when the initial load fails (the dialog closes itself; the panel shows its own retry). */
    onLoadFailed?: () => void;
  },
): MessagingBindingEditorState {
  const { poll, onChanged, onLoadFailed } = opts;
  const [form, setForm] = useState<MessagingFormState | null>(null);
  /** What the form last loaded/saved — the dirty check compares against it. */
  const [baseline, setBaseline] = useState<MessagingFormState | null>(null);
  const [channels, setChannels] = useState<ChannelFactsMap>({
    feishu: EMPTY_FACTS,
    telegram: EMPTY_FACTS,
    qq: EMPTY_FACTS,
    wechat: EMPTY_FACTS,
  });
  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);
  /** 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
   * probe: the two are answered by different buttons and one never stands for the other.
   */
  const [saveRefusal, setSaveRefusal] = useState<string | null>(null);
  const saveButtonId = useId();

  /** Which session the form was loaded for (the initial load runs once per session, not per poll flip). */
  const loadedFor = useRef<string | null>(null);

  // Initial load fills the form; the poll afterwards refreshes ONLY the per-channel
  // facts (stored / secret / enabled / status / chat-known), never the fields being
  // edited. A re-shown editor (the dock keeps hidden tabs mounted, `poll` flips back on)
  // only resumes that refresh: the form survives hide/show untouched.
  useEffect(() => {
    let cancelled = false;
    let initialDone = loadedFor.current === sessionId;
    const refresh = async (initial: boolean) => {
      try {
        const res = await api.getMessagingBinding(sessionId);
        if (cancelled) return;
        setChannels(factsFromList(res));
        if (initial) {
          const initialForm = bindingsToForm(res.bindings.map((b) => b.binding));
          setForm(initialForm);
          setBaseline(initialForm);
          initialDone = true;
        }
      } catch (e) {
        if (cancelled) return;
        if (initial) {
          initialDone = true; // reported; a retry is the host's call, not a silent loop
          toastError(apiErrorText(e));
          onLoadFailed?.();
        }
      }
    };
    if (loadedFor.current !== sessionId) {
      loadedFor.current = sessionId;
      // A swapped session must never show the previous one's fields while its load runs.
      setForm(null);
      setBaseline(null);
      // Nor the previous session's probe answer: its fields are about to leave the screen.
      setTestRefusal(null);
      // 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);
    }
    const timer = poll ? setInterval(() => void refresh(false), STATUS_POLL_MS) : null;
    return () => {
      cancelled = true;
      if (timer !== null) clearInterval(timer);
      // An initial load cancelled mid-flight (poll flipped, host unmounted) must retry on
      // the next run instead of leaving the form permanently unloaded.
      if (!initialDone && loadedFor.current === sessionId) loadedFor.current = null;
    };
    // Only sessionId/poll may restart the effect: onLoadFailed's identity would
    // otherwise re-run it every render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId, poll]);

  const patchForm = (patch: Partial<MessagingFormState>) => {
    setForm((prev) => (prev ? { ...prev, ...patch } : prev));
    setFieldErrors({});
    // The probe sent exactly the values on the form, so any edit makes its sentence describe a
    // connection nothing asked about any more.
    setTestRefusal(null);
  };

  const selectChannel = (channel: MessagingChannel) => {
    // The refusal belongs to the switch of the channel it was refused on: another channel's
    // switch is a different control, and carrying the sentence across would accuse it.
    setToggleRefusal(null);
    // Same rule for the probe: another channel's credentials are not what that button tested.
    setTestRefusal(null);
    // 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 });
  };

  const selected: MessagingChannel = form?.channel ?? "feishu";
  const facts = channels[selected];
  const enabledChannel: MessagingChannel | null = channels.feishu.enabled
    ? "feishu"
    : channels.telegram.enabled
      ? "telegram"
      : channels.qq.enabled
        ? "qq"
        : channels.wechat.enabled
          ? "wechat"
          : null;
  const dirty = form !== null && baseline !== null && formDirty(form, baseline);

  /** One channel's PUT/state response lands only in that channel's facts + form baseline. */
  const applyChannel = (
    channel: MessagingChannel,
    binding: MessagingBindingInfo | null,
    status: MessagingRuntimeStatus,
  ): void => {
    setChannels((prev) => ({ ...prev, [channel]: factsOf(binding, status) }));
    if (binding !== null) {
      const fresh = bindingsToForm([binding]);
      const sub =
        channel === "feishu"
          ? { feishu: fresh.feishu }
          : channel === "qq"
            ? { qq: fresh.qq }
            : channel === "wechat"
              ? { wechat: fresh.wechat }
              : { telegram: fresh.telegram };
      setForm((prev) => (prev ? { ...prev, ...sub } : prev));
      setBaseline((prev) => (prev ? { ...prev, ...sub } : prev));
    }
  };

  /**
   * Probes the selected channel with the form's current (unsaved) values and saves nothing.
   *
   * A connection that gets through pops its numbers as a toast; one that does not leaves its
   * sentence under the button that asked, and NOT in a toast (see `messaging-test-refusal.ts`):
   * the card is otherwise unchanged, so six seconds later nothing on screen would say the button
   * had been pressed — while the credential fields that sentence points at sit right below it.
   */
  const testConnection = async () => {
    if (!form) return;
    // This probe's answer replaces the last one's.
    setTestRefusal(null);
    setTesting(true);
    try {
      const draft = formToTest(form);
      const res =
        draft.channel === "telegram"
          ? await api.testTelegramBinding(sessionId, draft.body)
          : draft.channel === "qq"
            ? await api.testQQBinding(sessionId, draft.body)
            : // No body on WeChat: this channel's probe reads the stored binding, there being no draft.
              draft.channel === "wechat"
              ? await api.testWeChatBinding(sessionId)
              : await api.testFeishuBinding(sessionId, draft.body);
      const refusal = messagingTestRefusal({ result: res });
      if (refusal !== null) {
        setTestRefusal(refusal);
        return;
      }
      // Connected: what is left of Telegram's notices is the success line and the Group Privacy
      // caveat — the failure branch was answered above.
      if (draft.channel === "telegram") {
        for (const notice of telegramTestNotices(res)) {
          if (notice.tone === "info") toastInfo(notice.text);
          else toastSuccess(notice.text);
        }
      } else {
        toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));
      }
    } catch (e) {
      setTestRefusal(messagingTestRefusal({ result: null, error: e }));
    } finally {
      setTesting(false);
    }
  };

  /**
   * 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) {
      setTestMessageRefusal(messagingTestMessageRefusal(e));
    } finally {
      setSendingTest(false);
    }
  };

  /**
   * Save = persist the selected channel's credentials (no connection side effect; the toggle owns that).
   *
   * A refused write leaves its reason at the end of the card and NOT in a toast: the fields keep
   * every value that was typed, the saved baseline does not move (so the form still reads as
   * unsaved), and the success toast never comes — six seconds later nothing on screen would say
   * the button had been pressed, while the credential the server rejected is a field on this very
   * form. Save is the retry, so the sentence stays until the next press.
   */
  const save = async () => {
    if (!form) return;
    const built = formToPut(form, channels[form.channel].secretConfigured);
    if (!built.ok) {
      setFieldErrors(built.errors);
      return;
    }
    setBusy(true);
    // This save's answer replaces the last one's.
    setSaveRefusal(null);
    try {
      const res =
        built.channel === "telegram"
          ? await api.putTelegramBinding(sessionId, built.body)
          : built.channel === "qq"
            ? await api.putQQBinding(sessionId, built.body)
            : built.channel === "wechat"
              ? await api.putWeChatBinding(sessionId, built.body)
              : await api.putFeishuBinding(sessionId, built.body);
      applyChannel(built.channel, res.binding, res.status);
      toastSuccess(S.common.saved);
    } catch (e) {
      setSaveRefusal(messagingSaveRefusal(e));
    } finally {
      setBusy(false);
    }
  };

  /**
   * 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) {
      setToggleRefusal(apiErrorText(e));
    } finally {
      setToggling(false);
    }
  };

  // Enabling needs a saved credential, no unsaved edits, and the other channels dark;
  // disabling is always allowed.
  const enableGate = enablePrerequisite({ channel: selected, facts, enabledChannel, dirty });

  return {
    sessionId,
    form,
    patchForm,
    selectChannel,
    channels,
    fieldErrors,
    dirty,
    busy,
    toggling,
    testing,
    sendingTest,
    testable: form !== null && formTestable(form, facts.secretConfigured),
    toggleBusy: toggling || busy,
    enableGate,
    toggleRefusal,
    testRefusal,
    testMessageRefusal,
    saveRefusal,
    saveButtonId,
    adoptBinding: (binding) =>
      applyChannel(binding.channel, binding, channels[binding.channel].status),
    save,
    toggleEnabled,
    testConnection,
    sendTestMessage,
  };
}

/** External link styled like the models dialog's "get API key" corner action. */
function ExternalLink({ href, label }: { href: string; label: string }) {
  return (
    <a
      href={href}
      target="_blank"
      rel="noreferrer noopener"
      className="shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"
    >
      {label} ↗
    </a>
  );
}

/**
 * A field with an action link at the label's top-right corner — the models dialog's
 * "get API key" idiom. The control inside carries `aria-label` itself: this wrapper's
 * label row is layout, not a <label> element.
 */
function CornerLinkedField({
  label,
  required,
  link,
  children,
}: {
  label: string;
  required?: boolean;
  link: ReactNode;
  children: ReactNode;
}) {
  return (
    <div className="block">
      <span className="mb-1 flex items-baseline justify-between gap-2">
        <FieldLabel block={false} {...(required ? { required: true } : {})}>
          {label}
        </FieldLabel>
        {link}
      </span>
      {children}
    </div>
  );
}

/**
 * The stored secret's status row, under the secret field — the models-page configured-key
 * idiom: the site-wide mask in mono, and a "clear stored …" checkbox applied on Save
 * (typing into the field unchecks it). Clearing requires the channel's connection to be
 * disabled first, so the checkbox is gated with that hint while enabled.
 */
function StoredSecretRow({
  masked,
  clearLabel,
  checked,
  enabled,
  onChange,
}: {
  masked: string;
  clearLabel: string;
  /** The clear checkbox's state (lives in the form, applied on Save). */
  checked: boolean;
  /** The channel's connection is enabled: clearing is gated until it is turned off. */
  enabled: boolean;
  onChange: (checked: boolean) => void;
}) {
  return (
    <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
      <span className="font-mono">{masked}</span>
      <Checkbox checked={checked} disabled={enabled} onChange={onChange} label={clearLabel} />
      {/* A disabled checkbox does not reliably fire hover, so the reason is on screen rather
          than in a title: a gated control that never says why is the bug this avoids. */}
      {enabled && (
        <span className="text-gray-400 dark:text-gray-500">
          {S.messaging.disableBeforeClearHint}
        </span>
      )}
    </div>
  );
}

/**
 * One saved delivery preference: a label, its semantics behind the label's "?", and the
 * switch. What the option does to a reply is meaning rather than formatting, which is what
 * puts the sentence in a popover instead of under the row — a standing line of explanation
 * is read once and stepped over on every later visit.
 */
function DeliveryOptionRow({
  label,
  help,
  checked,
  onChange,
}: {
  label: string;
  /**
   * The semantics behind the "?". A node rather than a string because one channel's answer
   * needs a second paragraph, and the popover's panel does not preserve newlines — a `\n\n`
   * inside a string would collapse to a space and read as one run-on sentence.
   */
  help: ReactNode;
  checked: boolean;
  onChange: (checked: boolean) => void;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="flex items-center gap-1.5">
        <FieldLabel block={false}>{label}</FieldLabel>
        <InfoPopover label={label}>{help}</InfoPopover>
      </span>
      <Switch aria-label={label} checked={checked} onChange={onChange} />
    </div>
  );
}

/**
 * The editor's body, top to bottom: the channel selector, the connection controls (enable
 * toggle + live status, then the two probes, then the hint naming what gates the switch),
 * then the selected channel's credential fields (credential-source link at the credential
 * field's corner, models-style stored-secret row), and last the saved fields that are not
 * credentials — the two delivery options, which Save persists like the rest. Only the
 * selector and the controls sit above the fields, and everything above the fields is
 * channel-independent in height, so the toggle and the probes hold one vertical position no
 * matter which channel is selected. Hosts place their own Save action after it and
 * `MessagingBindingHelp` below that.
 */
export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState }) {
  // Per-instance ids for the gated switch's focus hand-off: a dialog and a dock panel may be
  // open on the same Session at once, and a fixed id would send one's focus into the other.
  const idBase = useId();
  const [hintEmphasized, setHintEmphasized] = useState(false);
  const emphasisTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    return () => {
      if (emphasisTimer.current !== null) clearTimeout(emphasisTimer.current);
    };
  }, []);
  const { form } = b;
  if (!form) return null;
  const channel = form.channel;
  const facts = b.channels[channel];
  const gate = b.enableGate;
  const hintInk = hintEmphasized ? toneInk.attention : "text-gray-400 dark:text-gray-500";
  const ids = {
    hint: `${idBase}-enable-hint`,
    scan: `${idBase}-scan`,
    appId: `${idBase}-app-id`,
    appSecret: `${idBase}-app-secret`,
    botToken: `${idBase}-bot-token`,
  };
  /**
   * A click on the switch while a prerequisite is unmet sends nothing. It repeats the hint as
   * a toast, turns the hint line to the attention colour for a moment, and moves focus to
   * where the missing step is done. A click while the line is still lit skips the toast, so a
   * few quick presses do not stack copies of one sentence.
   */
  const explainGate = (prerequisite: EnablePrerequisite) => {
    if (emphasisTimer.current === null) toastInfo(prerequisite.hint);
    else clearTimeout(emphasisTimer.current);
    setHintEmphasized(true);
    emphasisTimer.current = setTimeout(() => {
      emphasisTimer.current = null;
      setHintEmphasized(false);
    }, HINT_EMPHASIS_MS);
    if (prerequisite.focus === "scan") {
      const block = document.getElementById(ids.scan);
      block?.scrollIntoView({ block: "nearest" });
      block?.querySelector<HTMLElement>(FOCUSABLE)?.focus({ preventScroll: true });
    } else if (prerequisite.focus === "credential") {
      // The first credential field still empty; with all of them typed, Save is what is left.
      const fields: [id: string, value: string][] =
        channel === "telegram"
          ? [[ids.botToken, form.telegram.botToken]]
          : [
              [ids.appId, form.feishu.appId],
              [ids.appSecret, form.feishu.appSecret],
            ];
      const empty = fields.find(([, value]) => value.trim() === "");
      document.getElementById(empty?.[0] ?? b.saveButtonId)?.focus();
    } else if (prerequisite.focus === "save") {
      document.getElementById(b.saveButtonId)?.focus();
    }
  };
  // The delivery preferences of the selected channel, and the patch that writes one back.
  // Every sub-state carries the same three, so resolving the channel once here keeps the
  // rows at the bottom free of a selector they have nothing to say about.
  const delivery =
    channel === "telegram"
      ? form.telegram
      : channel === "qq"
        ? form.qq
        : channel === "wechat"
          ? form.wechat
          : form.feishu;
  const patchDelivery = (patch: Partial<MessagingDeliveryFields>) =>
    b.patchForm(
      channel === "telegram"
        ? { telegram: { ...form.telegram, ...patch } }
        : channel === "qq"
          ? { qq: { ...form.qq, ...patch } }
          : channel === "wechat"
            ? { wechat: { ...form.wechat, ...patch } }
            : { feishu: { ...form.feishu, ...patch } },
    );
  return (
    <div className="space-y-3">
      {/* Channel first — each channel's config is saved independently, so the selector
          switches forms rather than locking (the mcp transport idiom). */}
      <div role="group" aria-label={S.messaging.channelLabel}>
        <Segmented
          cols={4}
          options={[
            { value: "feishu" as MessagingChannel, label: S.messaging.channelName.feishu },
            { value: "telegram" as MessagingChannel, label: S.messaging.channelName.telegram },
            { value: "qq" as MessagingChannel, label: S.messaging.channelName.qq },
            { value: "wechat" as MessagingChannel, label: S.messaging.channelName.wechat },
          ]}
          value={channel}
          onChange={(v) => b.selectChannel(v)}
        />
      </div>
      {/* The connection toggle + live status on one line: the Switch is the intent, the
          tone-colored text is what the connection actually is right now. The switch's
          title says the thing its label cannot — flipping it on is the bind, flipping it
          off the unbind — as a tooltip rather than a line, because a permanent sentence
          here would push everything below it down for a fact read once. At most one
          channel is enabled per Session, and at most one conversation may hold a given
          bot; the hint under the probes names what gates the switch, and only the
          per-Session rule is knowable client-side — the cross-conversation one arrives as
          the server's 409. The error state's `lastError` gets its own line below rather than a track
          on this one: the connection failures worth reporting name what to do about them
          ("another program is already polling this bot …"), and a share of a row that
          already carries a switch, a label and a status word truncates that to a couple of
          words. Clamped to two lines so an error still cannot push the probes far, with
          the whole message on hover. */}
      <div className="space-y-1">
        <div className="flex flex-wrap items-center gap-2 text-xs">
          <label
            className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300"
            data-tooltip={S.messaging.bindByEnableHint}
            data-tooltip-extra
          >
            {/* Natively disabled only while a request is in flight. A missing prerequisite
                dims it the same way but leaves it clickable (aria-disabled), because a
                control that ignores a click never says what it is waiting for. */}
            <Switch
              checked={facts.enabled}
              disabled={b.toggleBusy}
              {...(gate !== null
                ? {
                    "aria-disabled": true,
                    "aria-describedby": ids.hint,
                    className: "cursor-not-allowed opacity-60",
                  }
                : {})}
              onChange={(v) => {
                if (gate !== null) explainGate(gate);
                else void b.toggleEnabled(v);
              }}
            />
            {S.messaging.enabled}
          </label>
          <span className="ml-2 text-gray-500 dark:text-gray-400">{S.messaging.statusLabel}</span>
          <span className={`font-medium ${toneInk[STATUS_TONE[facts.status.state]]}`}>
            {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}
            data-tooltip-content="text"
            className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400"
          >
            {facts.status.lastError}
          </p>
        )}
        {/* A failure the connection has already recovered from. `lastError` belongs to the
            error state and is wiped the moment the state leaves it, so a connector that flaps
            — which is what a second program polling the same bot token produces — shows a
            clean `connected` in every snapshot taken between its failures, and the reader is
            left with the symptom and no trace of the cause. */}
        {facts.status.state !== "error" && facts.status.lastConnectionError !== undefined && (
          <p
            data-tooltip={facts.status.lastConnectionError.detail}
            data-tooltip-content="text"
            className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400"
          >
            {S.messaging.lastConnectionError(
              formatDateTime(facts.status.lastConnectionError.at),
              facts.status.lastConnectionError.detail,
            )}
          </p>
        )}
        {/* What this connection has actually seen. "Connected" answers whether the socket is
            up, and nothing else on this panel could tell a user whether the platform is
            delivering anything — a Telegram bot muted by group privacy, or one that was never
            really added to the group, is `connected` with no error, forever. It resets with
            every (re)connect, a re-enable or a credential save included (it is the live
            connection's own observation), which is why the empty case says "since this
            connection opened" rather than reading as "never".

            Shown outside `connected` too, and gated only on there being a connection at all:
            it is a fact about traffic rather than about the socket, and `connecting` (a
            Telegram bot is mid-handshake and backlog drain) and `error` (a flapping token) are
            exactly where a reader needs to know whether this bot has been receiving at all. */}
        {facts.status.state !== "disconnected" &&
          (facts.status.lastInboundAt !== undefined ? (
            <p className="text-xs text-gray-500 dark:text-gray-400">
              {S.messaging.inboundLastAt(formatDateTime(facts.status.lastInboundAt))}
            </p>
          ) : (
            <p className="text-xs text-gray-500 dark:text-gray-400">{S.messaging.inboundNone}</p>
          ))}
        {/* A failure AFTER a message arrived. Both stages reach the chat as silence, so the
            line has to say which one it was: "it never started" sends the user to the Session,
            "the reply never went out" sends them to the bot's permissions in the chat. Nothing
            clears it on a later success, so the time goes in the sentence like the connection
            error's: a revoked send right restored a minute later otherwise reads for days as a
            live fault, and a title= is hover-only and unreachable on touch. */}
        {facts.status.lastDeliveryError !== undefined && (
          <p
            data-tooltip={facts.status.lastDeliveryError.detail}
            data-tooltip-content="text"
            className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400"
          >
            {facts.status.lastDeliveryError.stage === "inbound"
              ? S.messaging.deliveryFailedInbound(
                  formatDateTime(facts.status.lastDeliveryError.at),
                  facts.status.lastDeliveryError.detail,
                )
              : S.messaging.deliveryFailedSend(
                  formatDateTime(facts.status.lastDeliveryError.at),
                  facts.status.lastDeliveryError.detail,
                )}
          </p>
        )}
      </div>
      {/* Entry-level probes — the MCP dialog idiom: standalone buttons, a connecting answer as a
          toast, a refused one drawn below them (see `messaging-test-refusal.ts`). */}
      <div className="flex flex-wrap items-center gap-2">
        <Button
          size="sm"
          disabled={b.testing || b.busy || !b.testable}
          onClick={() => void b.testConnection()}
        >
          {b.testing ? S.messaging.testing : S.messaging.test}
        </Button>
        <Button
          size="sm"
          disabled={
            b.sendingTest || b.busy || facts.status.state !== "connected" || !facts.lastChatKnown
          }
          {...(!facts.lastChatKnown
            ? {
                title:
                  channel === "telegram"
                    ? S.telegram.testMessageNoChat
                    : channel === "qq"
                      ? S.qq.testMessageNoChat
                      : channel === "wechat"
                        ? S.wechat.testMessageNoChat
                        : S.feishu.testMessageNoChat,
              }
            : {})}
          onClick={() => void b.sendTestMessage()}
        >
          {b.sendingTest ? S.messaging.sendingTestMessage : S.messaging.sendTestMessage}
        </Button>
      </div>
      {/* Under the button that asked, not over the card: `line-clamp-2` keeps a long platform
          sentence from pushing the fields down, and the whole text is on hover, the way every
          other refusal slot in the app carries its longer form. */}
      {b.testRefusal !== null && (
        <p
          role="alert"
          data-tooltip={b.testRefusal}
          data-tooltip-content="text"
          className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}
        >
          {b.testRefusal}
        </p>
      )}
      {/* The 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 a
          line — trailing the probes leaves both of them at a fixed offset. */}
      {gate !== null && (
        <p id={ids.hint} className={`text-xs transition-colors ${hintInk}`}>
          {gate.hint}
        </p>
      )}
      {/* The credential fields trail the controls above; explanations live in the FAQ folds
          below the save area. */}
      {channel === "telegram" ? (
        <>
          <CornerLinkedField
            label={S.telegram.botToken}
            required={!facts.secretConfigured}
            // Not the shared "developer console" label: this one opens @BotFather in the
            // Telegram app, and a corner link promising a console that does not exist sends
            // the reader looking for a web page Telegram has never had. The label names the
            // thing the click actually reaches — Telegram's own page for it is titled
            // "Launch @BotFather".
            link={
              <ExternalLink
                href={CHANNEL_LINKS.telegram.credentialSource}
                label={S.telegram.openBotFather}
              />
            }
          >
            <PasswordInput
              size="sm"
              id={ids.botToken}
              aria-label={S.telegram.botToken}
              {...(facts.secretConfigured ? { placeholder: S.telegram.botTokenKeepHint } : {})}
              error={errorText(b.fieldErrors.botToken)}
              value={form.telegram.botToken}
              onChange={(e) =>
                b.patchForm({
                  telegram: { ...form.telegram, botToken: e.target.value, clearToken: false },
                })
              }
              autoComplete="off"
            />
          </CornerLinkedField>
          {facts.secretMasked !== null && form.telegram.botToken === "" && (
            <StoredSecretRow
              masked={facts.secretMasked}
              clearLabel={S.telegram.clearToken}
              checked={form.telegram.clearToken}
              enabled={facts.enabled}
              onChange={(checked) =>
                b.patchForm({ telegram: { ...form.telegram, clearToken: checked } })
              }
            />
          )}
        </>
      ) : channel === "qq" ? (
        <>
          {/* The easy path leads: scanning is what most people will do, and the fields below
              are the fallback for a bot the scan cannot reach. Both are inside this channel's
              branch, so nothing above the fields moves when the QR opens. */}
          <div id={ids.scan}>
            <QQScanConnect
              sessionId={b.sessionId}
              enabled={facts.enabled}
              onBound={(binding) => b.adoptBinding(binding)}
            />
          </div>
          <p className="text-xs text-gray-400 dark:text-gray-500">{S.qq.scanOrManual}</p>
          <CornerLinkedField
            label={S.qq.appId}
            required
            link={
              <ExternalLink href={CHANNEL_LINKS.qq.credentialSource} label={S.messaging.console} />
            }
          >
            <Input
              size="sm"
              aria-label={S.qq.appId}
              error={errorText(b.fieldErrors.appId)}
              value={form.qq.appId}
              onChange={(e) => b.patchForm({ qq: { ...form.qq, appId: e.target.value } })}
              className="font-mono"
              placeholder="102000000"
              autoComplete="off"
            />
          </CornerLinkedField>
          <PasswordInput
            size="sm"
            label={S.qq.appSecret}
            {...(facts.secretConfigured
              ? { placeholder: S.qq.appSecretKeepHint }
              : { required: true })}
            error={errorText(b.fieldErrors.appSecret)}
            value={form.qq.appSecret}
            onChange={(e) =>
              b.patchForm({ qq: { ...form.qq, appSecret: e.target.value, clearSecret: false } })
            }
            autoComplete="off"
          />
          {facts.secretMasked !== null && form.qq.appSecret === "" && (
            <StoredSecretRow
              masked={facts.secretMasked}
              clearLabel={S.qq.clearSecret}
              checked={form.qq.clearSecret}
              enabled={facts.enabled}
              onChange={(checked) => b.patchForm({ qq: { ...form.qq, clearSecret: checked } })}
            />
          )}
          {/* The one channel whose rule cannot wait for a collapsed fold: QQ delivers only
              replies to messages sent from QQ, so a user who binds it and then types in the
              web app sees nothing arrive and concludes the binding is broken. It sits under
              this channel's fields rather than above them, which keeps the controls at the
              same height across channels. */}
          <p className="text-xs text-gray-500 dark:text-gray-400">{S.qq.repliesOnly}</p>
        </>
      ) : channel === "wechat" ? (
        <>
          {/* The whole credential form: there is nothing to type on this channel, so the QR
              is not the easy path but the only one. */}
          <div id={ids.scan}>
            <WeChatScanConnect
              sessionId={b.sessionId}
              enabled={facts.enabled}
              bound={facts.secretConfigured}
              onBound={(binding) => b.adoptBinding(binding)}
            />
          </div>
          {facts.secretMasked !== null && (
            <StoredSecretRow
              masked={facts.secretMasked}
              clearLabel={S.wechat.clearToken}
              checked={form.wechat.clearToken}
              enabled={facts.enabled}
              onChange={(checked) =>
                b.patchForm({ wechat: { ...form.wechat, clearToken: checked } })
              }
            />
          )}
          {/* This channel's rule that cannot wait for a collapsed fold: it carries direct
              chats only, so a user who binds it and then writes in a group sees nothing
              arrive and concludes the binding is broken. */}
          <p className="text-xs text-gray-500 dark:text-gray-400">{S.wechat.directOnly}</p>
        </>
      ) : (
        <>
          <CornerLinkedField
            label={S.feishu.appId}
            required
            link={
              <ExternalLink
                href={CHANNEL_LINKS.feishu.credentialSource}
                label={S.messaging.console}
              />
            }
          >
            <Input
              size="sm"
              id={ids.appId}
              aria-label={S.feishu.appId}
              error={errorText(b.fieldErrors.appId)}
              value={form.feishu.appId}
              onChange={(e) => b.patchForm({ feishu: { ...form.feishu, appId: e.target.value } })}
              className="font-mono"
              placeholder="cli_xxxxxxxxxxxxxxxx"
              autoComplete="off"
            />
          </CornerLinkedField>
          <PasswordInput
            size="sm"
            id={ids.appSecret}
            label={S.feishu.appSecret}
            {...(facts.secretConfigured
              ? { placeholder: S.feishu.appSecretKeepHint }
              : { required: true })}
            error={errorText(b.fieldErrors.appSecret)}
            value={form.feishu.appSecret}
            onChange={(e) =>
              b.patchForm({
                feishu: { ...form.feishu, appSecret: e.target.value, clearSecret: false },
              })
            }
            autoComplete="off"
          />
          {facts.secretMasked !== null && form.feishu.appSecret === "" && (
            <StoredSecretRow
              masked={facts.secretMasked}
              clearLabel={S.feishu.clearSecret}
              checked={form.feishu.clearSecret}
              enabled={facts.enabled}
              onChange={(checked) =>
                b.patchForm({ feishu: { ...form.feishu, clearSecret: checked } })
              }
            />
          )}
          <Input
            size="sm"
            label={S.feishu.baseDomain}
            hint={S.feishu.baseDomainHint}
            error={errorText(b.fieldErrors.baseDomain)}
            value={form.feishu.baseDomain}
            onChange={(e) =>
              b.patchForm({ feishu: { ...form.feishu, baseDomain: e.target.value } })
            }
            className="font-mono"
            placeholder="https://open.feishu.cn"
            autoComplete="off"
          />
        </>
      )}
      {/* The saved fields that are not credentials, so they close the form rather than
          sitting among them. Every row is offered on every channel, and their explanations
          sit behind the label's "?" — see DeliveryOptionRow. Order is the order they take
          effect in: which messages are sent, then how each one is split, then how each of
          those is rendered. The Markdown row's sentence is the one that differs per channel,
          because what a channel can show is the whole of what the reader needs to decide.

          The one place a channel changes the answer rather than shading it: on QQ every send
          is a passive reply anchored to an inbound message, and that anchor expires, so
          holding the reply to the run's end loses a long run's output entirely instead of
          merely delaying it. That is a different outcome, not a nuance of the same one, so it
          is appended to this option's explanation — and only there. A standing strip under the
          row would be the third thing on this form permanently explaining a channel to someone
          who has already read it once; what belongs on screen is the switch, and what belongs
          behind the "?" is why you might not want it. `linePerMessage` needs nothing similar:
          QQ clamps the split to its own budget and the reply still arrives. */}
      <DeliveryOptionRow
        label={S.messaging.finalReplyOnly}
        help={
          channel === "qq" ? (
            <>
              <p>{S.messaging.finalReplyOnlyHelp}</p>
              <p className="mt-2">{S.messaging.finalReplyOnlyQQWarning}</p>
            </>
          ) : (
            S.messaging.finalReplyOnlyHelp
          )
        }
        checked={delivery.finalReplyOnly}
        onChange={(v) => patchDelivery({ finalReplyOnly: v })}
      />
      <DeliveryOptionRow
        label={S.messaging.linePerMessage}
        help={S.messaging.linePerMessageHelp}
        checked={delivery.linePerMessage}
        onChange={(v) => patchDelivery({ linePerMessage: v })}
      />
      <DeliveryOptionRow
        label={S.messaging.renderMarkdown}
        help={
          channel === "telegram"
            ? S.messaging.renderMarkdownHelpTelegram
            : channel === "qq"
              ? S.messaging.renderMarkdownHelpQQ
              : channel === "wechat"
                ? S.messaging.renderMarkdownHelpWeChat
                : S.messaging.renderMarkdownHelpFeishu
        }
        checked={delivery.renderMarkdown}
        onChange={(v) => patchDelivery({ renderMarkdown: v })}
      />
      {/* The refused save closes the card, which is where Save sits in both hosts: the dock panel
          puts its own Save row right below this body, and the dialog's footer follows the body and
          the FAQ folds — so one slot here is above that button in either host, and the two hosts
          stay free to place their action where they already do. `role="alert"` so the sentence is
          announced when it arrives (a toast was announced once and then left), `line-clamp-2` so a
          long server sentence cannot push the form around, and the whole text on hover the way
          every other refusal slot carries its longer form. */}
      {b.saveRefusal !== null && (
        <p
          role="alert"
          data-tooltip={b.saveRefusal}
          data-tooltip-content="text"
          className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}
        >
          {b.saveRefusal}
        </p>
      )}
    </div>
  );
}

/**
 * The collapsed-by-default FAQ under the save area — three titled `HelpFold`s: the
 * selected channel's setup steps (ending in its tutorial link), what binding does, and
 * troubleshooting. Hosts place it below their Save controls, which is what keeps the
 * form itself opening on the channel selector and the connection controls.
 */
export function MessagingBindingHelp({ channel }: { channel: MessagingChannel }) {
  const per =
    channel === "telegram"
      ? S.telegram
      : channel === "qq"
        ? S.qq
        : channel === "wechat"
          ? S.wechat
          : S.feishu;
  const links = CHANNEL_LINKS[channel];
  return (
    <div className="space-y-2 border-t border-gray-200 pt-3 dark:border-gray-800">
      <HelpFold title={S.messaging.faqSetupTitle}>
        <ol className="list-decimal space-y-1 pl-4">
          {per.setupSteps.map((step) => (
            <li key={step}>{step}</li>
          ))}
        </ol>
        {/* What the QR button spares the reader: the last two steps of the list above.
            Disclosed here rather than parked beside the button, which is a control and so
            cannot be the title a standing sentence would need. */}
        {channel === "qq" && <p className="mt-1.5">{S.qq.scanHint}</p>}
        {/* Why this channel's form has no fields, said where a reader looking for them
            arrives. */}
        {channel === "wechat" && <p className="mt-1.5">{S.wechat.scanOnly}</p>}
        {/* Absent for a channel with nowhere public to send the reader (see CHANNEL_LINKS). */}
        {links !== null && (
          <p className="mt-1.5">
            <ExternalLink href={links.tutorial} label={S.messaging.tutorial} />
          </p>
        )}
      </HelpFold>
      <HelpFold title={S.messaging.faqWhatTitle}>
        <p>{per.intro}</p>
        {/* The channel's own flavor first, then the channel-neutral rule that owns the
            question a reader actually arrives with: how the bot moves conversations. */}
        {/* QQ's reply budget belongs to "what binding does" rather than troubleshooting:
            it is not a fault, it is how the channel delivers a long answer. */}
        {channel === "qq" && <p className="mt-1.5">{S.qq.replyBudget}</p>}
        {/* What actually travels on this channel, which is more than on any other here and
            is the question its users ask first. */}
        {channel === "wechat" && <p className="mt-1.5">{S.wechat.media}</p>}
        <p className="mt-1.5">{S.messaging.faqWhatBinding}</p>
      </HelpFold>
      <HelpFold title={S.messaging.faqTroubleTitle}>
        <ul className="list-disc space-y-1 pl-4">
          <li>{S.messaging.troubleNoChat}</li>
          <li>{S.messaging.troubleConnError}</li>
          {channel === "telegram" && <li>{S.messaging.troubleOnePoller}</li>}
          {channel === "telegram" && <li>{S.messaging.troubleGroupPrivacy}</li>}
          {channel === "qq" && <li>{S.messaging.troubleQQPassive}</li>}
          {channel === "wechat" && <li>{S.messaging.troubleWeChatDirect}</li>}
          {channel === "telegram" && <li>{S.messaging.troubleNoGroupInbound}</li>}
        </ul>
      </HelpFold>
    </div>
  );
}