BotsDialog.tsx 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. /* eslint-disable max-lines -- BotsDialog 现在保留数据加载、保存和轮询编排;右侧卡片已拆到 BotsDialog/* 子组件,后续再继续下沉状态 hook。 */
  2. import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from "react";
  3. import QRCode from "qrcode";
  4. import { Bot, LoaderCircle, Plus } from "lucide-react";
  5. import type {
  6. BotConfig,
  7. BotProvider,
  8. BotServiceStatus,
  9. BotState,
  10. BotWorkspaceRef,
  11. BotsConfigFile,
  12. } from "@zcode/shared";
  13. import {
  14. ALL_BOT_WORKSPACES,
  15. createUuid,
  16. DEFAULT_BOT_REPLY_GRANULARITY,
  17. isFeishuBotProvider,
  18. normalizeBotReplyGranularity,
  19. } from "@zcode/shared";
  20. import { Button } from "@/components/ui/button.js";
  21. import {
  22. Dialog,
  23. DialogContent,
  24. DialogDescription,
  25. DialogHeader,
  26. DialogTitle,
  27. } from "@/components/ui/dialog.js";
  28. import { toast } from "@/components/ui/toast.js";
  29. import { usePlatform } from "@/hooks/usePlatform.js";
  30. import { useConfirmDialog } from "@/hooks/useConfirmDialog.js";
  31. import { useServices } from "@/hooks/useServices.js";
  32. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  33. import { isImeComposingKeyEvent } from "@/lib/imeComposition.js";
  34. import { logger } from "@/logger.js";
  35. import {
  36. BOT_PROVIDERS,
  37. getBotProviderRegionTagLabelId,
  38. resolveBotProviderEntry,
  39. type BotProviderEntryId,
  40. } from "@/botsUi.js";
  41. import { cn } from "@/components/lib/utils.js";
  42. import {
  43. BotDangerCard,
  44. BotReplyGranularityCard,
  45. BotSummaryCard,
  46. } from "@/BotsDialog/BotSummaryCard.js";
  47. import { ProviderSettingsCard } from "@/BotsDialog/ProviderSettingsCard.js";
  48. import { BoundGroupsCard } from "@/BotsDialog/BoundGroupsCard.js";
  49. import { WorkspaceAccessCard } from "@/BotsDialog/WorkspaceAccessCard.js";
  50. import { SettingsGroupCard } from "@/settings/SettingsPageParts.js";
  51. import {
  52. BIND_CODE_TTL_MS,
  53. ProviderIcon,
  54. TELEGRAM_BOTFATHER_URL,
  55. createDefaultCommands,
  56. formatBotDisplayName,
  57. isAllWorkspacesAllowed,
  58. runtimeDot,
  59. type BindCodeState,
  60. type FeishuRegistrationState,
  61. type WeixinRegistrationState,
  62. } from "@/BotsDialog/shared.js";
  63. function createEmptyConfig(): BotsConfigFile {
  64. return { version: 3, bots: [] };
  65. }
  66. function createDraftBot(params: { provider: BotProvider }): BotConfig {
  67. // Bugfix: Bot id 只是配置实体身份,不应该带 provider 前缀;
  68. // 新建时如果看到 telegram-* 这类 id,容易误以为渠道被固定到了 Telegram。
  69. const id = `bot-${createUuid()}`;
  70. return {
  71. id,
  72. name: "",
  73. provider: params.provider,
  74. enabled: true,
  75. allowedWorkspaces: [ALL_BOT_WORKSPACES],
  76. allowedCommands: createDefaultCommands(),
  77. currentOptions: {},
  78. replyMode: normalizeBotReplyGranularity(params.provider, DEFAULT_BOT_REPLY_GRANULARITY),
  79. };
  80. }
  81. export function BotsDialog({
  82. open,
  83. onOpenChange,
  84. entryProvider,
  85. }: {
  86. open: boolean;
  87. onOpenChange: (open: boolean) => void;
  88. entryProvider?: BotProvider | null;
  89. }) {
  90. const { intl } = useZCodeIntl();
  91. const platform = usePlatform();
  92. const confirmDialog = useConfirmDialog();
  93. const { botsService } = useServices();
  94. const [config, setConfig] = useState<BotsConfigFile>(() => createEmptyConfig());
  95. const [workspaceRefs, setWorkspaceRefs] = useState<BotWorkspaceRef[]>([]);
  96. const [status, setStatus] = useState<BotServiceStatus | null>(null);
  97. const [botStates, setBotStates] = useState<BotState[]>([]);
  98. const [selectedBotId, setSelectedBotId] = useState<string | null>(null);
  99. const [creatingBot, setCreatingBot] = useState(false);
  100. const [configLoaded, setConfigLoaded] = useState(false);
  101. const [creatingProvider, setCreatingProvider] = useState<BotProvider | null>(null);
  102. const [bindCode, setBindCode] = useState<BindCodeState | null>(null);
  103. const [feishuRegistration, setFeishuRegistration] = useState<FeishuRegistrationState | null>(
  104. null,
  105. );
  106. const [feishuRegistrationLoading, setFeishuRegistrationLoading] = useState(false);
  107. const [weixinRegistration, setWeixinRegistration] = useState<WeixinRegistrationState | null>(
  108. null,
  109. );
  110. const [weixinRegistrationLoading, setWeixinRegistrationLoading] = useState(false);
  111. const [nowMs, setNowMs] = useState(() => Date.now());
  112. const [credentialValue, setCredentialValue] = useState("");
  113. const [secretSaving, setSecretSaving] = useState(false);
  114. const [workspaceAccessSaving, setWorkspaceAccessSaving] = useState(false);
  115. const [botNameDraft, setBotNameDraft] = useState<{
  116. botId: string;
  117. value: string;
  118. } | null>(null);
  119. const [renamingBotId, setRenamingBotId] = useState<string | null>(null);
  120. const botNameCompositionActiveRef = useRef(false);
  121. const autoQrStartedBotIdsRef = useRef(new Set<string>());
  122. const autoBindCreatingBotIdsRef = useRef(new Set<string>());
  123. const handledEntryProviderRef = useRef<BotProvider | null>(null);
  124. const selectedBot = config.bots.find((bot) => bot.id === selectedBotId) ?? null;
  125. const selectedBotState = botStates.find((state) => state.botId === selectedBotId) ?? null;
  126. const selectedBotName =
  127. selectedBot && botNameDraft?.botId === selectedBot.id
  128. ? botNameDraft.value
  129. : (selectedBot?.name ?? "");
  130. const fallbackBotName = intl.formatMessage({
  131. id: "bots.newBot.fallbackName",
  132. });
  133. const selectedBotDisplayName = formatBotDisplayName(selectedBotName, fallbackBotName);
  134. const bindRemainingMs = bindCode ? Math.max(0, bindCode.expiresAt - nowMs) : 0;
  135. const bindExpired = Boolean(bindCode && bindRemainingMs <= 0);
  136. const bindCountdownProgress = bindCode
  137. ? Math.max(0, Math.min(100, (bindRemainingMs / bindCode.ttlMs) * 100))
  138. : 0;
  139. useEffect(() => {
  140. if (!open || !bindCode) return undefined;
  141. setNowMs(Date.now());
  142. // Bugfix: 绑定码缩短到 30 秒后,1 秒刷新会让进度条明显跳格。
  143. // 这里用更细的节奏驱动动画,文字仍由 formatBindCountdown 按秒展示。
  144. const timer = window.setInterval(() => setNowMs(Date.now()), 250);
  145. return () => window.clearInterval(timer);
  146. }, [bindCode, open]);
  147. useEffect(() => {
  148. if (!open || !bindCode || bindExpired) return undefined;
  149. let cancelled = false;
  150. const pollBindResult = async () => {
  151. try {
  152. const nextConfig = await botsService.getConfig();
  153. if (cancelled) return;
  154. setConfig(nextConfig);
  155. const targetBot = nextConfig.bots.find((bot) => bot.id === bindCode.botId);
  156. if (targetBot?.providerUserId) {
  157. // Bugfix: /bind 是从第三方聊天回写配置,UI 没有直接事件。
  158. // 绑定码展开期间低频刷新配置,绑定成功后立即收起绑定区域。
  159. setBindCode(null);
  160. }
  161. } catch (error) {
  162. logger.warn(
  163. "[BotsDialog] 轮询 Bot 绑定结果失败",
  164. error instanceof Error ? error.message : String(error),
  165. );
  166. }
  167. };
  168. void pollBindResult();
  169. const timer = window.setInterval(() => {
  170. void pollBindResult();
  171. }, 2000);
  172. return () => {
  173. cancelled = true;
  174. window.clearInterval(timer);
  175. };
  176. }, [bindCode, bindExpired, botsService, open]);
  177. useEffect(() => {
  178. if (!bindCode || bindCode.botId !== selectedBot?.id || !selectedBot.providerUserId) {
  179. return;
  180. }
  181. // Bugfix: /bind 成功是服务层异步回写配置;即使轮询刚好被切换/刷新打断,
  182. // 只要当前 Bot 已经带 providerUserId,就应该立即收起旧绑定码。
  183. setBindCode(null);
  184. }, [bindCode, selectedBot?.id, selectedBot?.providerUserId]);
  185. useEffect(() => {
  186. setCredentialValue("");
  187. setSecretSaving(false);
  188. setWorkspaceAccessSaving(false);
  189. setFeishuRegistration(null);
  190. setWeixinRegistration(null);
  191. }, [selectedBotId, selectedBot?.provider]);
  192. useEffect(() => {
  193. if (!open) return undefined;
  194. let cancelled = false;
  195. let timer: ReturnType<typeof setTimeout> | undefined;
  196. const pollStatus = async () => {
  197. try {
  198. const nextStatus = await botsService.getStatus();
  199. if (!cancelled) setStatus(nextStatus);
  200. } catch (error) {
  201. logger.debug("[BotsDialog] 刷新 Bot 运行状态失败", error);
  202. } finally {
  203. // 投递在后台完成;只在弹窗可见时串行刷新,避免慢 RPC 堆积或关闭后回写。
  204. if (!cancelled) timer = setTimeout(() => void pollStatus(), 2000);
  205. }
  206. };
  207. void pollStatus();
  208. return () => {
  209. cancelled = true;
  210. clearTimeout(timer);
  211. };
  212. }, [botsService, open]);
  213. const refresh = useCallback(async () => {
  214. try {
  215. const [nextConfig, nextStatus, nextWorkspaces, nextBotStates] = await Promise.all([
  216. botsService.getConfig(),
  217. botsService.getStatus(),
  218. botsService.listWorkspaceRefs(),
  219. botsService.getBotStates(),
  220. ]);
  221. setConfig(nextConfig);
  222. setStatus(nextStatus);
  223. setWorkspaceRefs(nextWorkspaces);
  224. setBotStates(nextBotStates);
  225. setConfigLoaded(true);
  226. setSelectedBotId((current) =>
  227. creatingBot ? current : (current ?? nextConfig.bots[0]?.id ?? null),
  228. );
  229. } catch (error) {
  230. const message = error instanceof Error ? error.message : String(error);
  231. logger.error("[BotsDialog] 加载 Bots 配置失败", message);
  232. toast(intl.formatMessage({ id: "bots.loadFailed" }, { error: message }));
  233. }
  234. }, [botsService, creatingBot, intl]);
  235. useEffect(() => {
  236. if (
  237. !open ||
  238. selectedBot?.provider !== "weixin" ||
  239. !selectedBot.credentialRef ||
  240. selectedBotState?.weixinActivatedAt
  241. ) {
  242. return undefined;
  243. }
  244. let cancelled = false;
  245. const pollActivationState = async () => {
  246. try {
  247. const nextBotStates = await botsService.getBotStates();
  248. if (!cancelled) {
  249. setBotStates(nextBotStates);
  250. }
  251. } catch (error) {
  252. logger.warn(
  253. "[BotsDialog] 轮询微信 Bot 激活状态失败",
  254. error instanceof Error ? error.message : String(error),
  255. );
  256. }
  257. };
  258. const timer = window.setInterval(() => {
  259. void pollActivationState();
  260. }, 2000);
  261. void pollActivationState();
  262. return () => {
  263. cancelled = true;
  264. window.clearInterval(timer);
  265. };
  266. }, [
  267. botsService,
  268. open,
  269. selectedBot?.credentialRef,
  270. selectedBot?.id,
  271. selectedBot?.provider,
  272. selectedBotState?.weixinActivatedAt,
  273. ]);
  274. useEffect(() => {
  275. if (open) {
  276. setConfigLoaded(false);
  277. void refresh();
  278. }
  279. }, [open, refresh]);
  280. useEffect(() => {
  281. handledEntryProviderRef.current = null;
  282. }, [entryProvider, open]);
  283. const saveBot = useCallback(
  284. async (bot: BotConfig, secrets?: { credentialValue?: string }) => {
  285. const saved = await botsService.saveBot({
  286. bot,
  287. credentialValue: secrets?.credentialValue,
  288. });
  289. setConfig((previous) => ({
  290. ...previous,
  291. bots: [...previous.bots.filter((item) => item.id !== saved.id), saved],
  292. }));
  293. setSelectedBotId(saved.id);
  294. setCreatingBot(false);
  295. setCredentialValue("");
  296. void refresh();
  297. return saved;
  298. },
  299. [botsService, refresh],
  300. );
  301. const createBindCodeForBot = useCallback(
  302. async (bot: BotConfig) => {
  303. const createdAt = Date.now();
  304. const result = await botsService.createBindCode({
  305. botId: bot.id,
  306. ttlMs: BIND_CODE_TTL_MS,
  307. allowedWorkspaces: bot.allowedWorkspaces,
  308. });
  309. setNowMs(createdAt);
  310. setBindCode({
  311. botId: bot.id,
  312. code: result.code,
  313. createdAt,
  314. expiresAt: result.expiresAt,
  315. ttlMs: Math.max(1, result.expiresAt - createdAt),
  316. });
  317. },
  318. [botsService],
  319. );
  320. useEffect(() => {
  321. const registration = feishuRegistration;
  322. if (!open || !selectedBot || !isFeishuBotProvider(selectedBot.provider) || !registration) {
  323. return undefined;
  324. }
  325. if (registration.status !== "pending") {
  326. return undefined;
  327. }
  328. let cancelled = false;
  329. const pollIntervalMs = Math.max(1, registration.interval) * 1000;
  330. const pollRegistration = async () => {
  331. try {
  332. const result = await botsService.pollFeishuRegistration({
  333. deviceCode: registration.deviceCode,
  334. domain: registration.domain,
  335. pollDomain: registration.pollDomain,
  336. });
  337. if (cancelled) {
  338. return;
  339. }
  340. if (result.status === "pending") {
  341. setFeishuRegistration((current) => {
  342. if (current?.deviceCode !== registration.deviceCode) {
  343. return current;
  344. }
  345. if (
  346. current.interval === result.interval &&
  347. current.domain === result.domain &&
  348. current.pollDomain === result.pollDomain
  349. ) {
  350. return current;
  351. }
  352. // Bugfix: pending 轮询结果通常不变;如果每次都创建新对象,会触发 effect 依赖变化,
  353. // 进而立即重启轮询并造成毫秒级 RPC 风暴。
  354. return {
  355. ...current,
  356. interval: result.interval,
  357. domain: result.domain,
  358. pollDomain: result.pollDomain,
  359. };
  360. });
  361. return;
  362. }
  363. if (result.status === "success") {
  364. // Bugfix: 服务层一直支持飞书扫码注册,但 Bots 重构后的 UI 只保留了手填凭据。
  365. // 扫码成功后直接复用 saveBot 的 secret 写入路径,避免把 App Secret 留在明文配置文件里。
  366. const savedBot = await saveBot(
  367. {
  368. ...selectedBot,
  369. provider: selectedBot.provider,
  370. name: result.appName?.trim() || selectedBot.name,
  371. feishuAppId: result.appId,
  372. },
  373. { credentialValue: result.appSecret },
  374. );
  375. if (!cancelled) {
  376. // Bugfix: 飞书/Lark 扫码成功只完成应用凭据接入;绑定码由“有凭据但未绑定”的统一状态机生成。
  377. // 这里仅收起二维码,避免二维码和 /bind 面板在一次状态更新里互相抢展示优先级。
  378. setConfig((previous) => ({
  379. ...previous,
  380. bots: previous.bots.map((bot) => (bot.id === savedBot.id ? savedBot : bot)),
  381. }));
  382. setFeishuRegistration(null);
  383. toast(intl.formatMessage({ id: "bots.feishuRegistrationSuccess" }));
  384. }
  385. return;
  386. }
  387. setFeishuRegistration((current) =>
  388. current?.deviceCode === registration.deviceCode
  389. ? {
  390. ...current,
  391. status: result.status,
  392. message:
  393. result.message ??
  394. intl.formatMessage({
  395. id: `bots.feishuRegistration.${result.status}`,
  396. }),
  397. }
  398. : current,
  399. );
  400. } catch (error) {
  401. const message = error instanceof Error ? error.message : String(error);
  402. logger.error("[BotsDialog] 飞书扫码注册轮询失败", message);
  403. if (!cancelled) {
  404. setFeishuRegistration((current) =>
  405. current?.deviceCode === registration.deviceCode
  406. ? { ...current, status: "error", message }
  407. : current,
  408. );
  409. }
  410. }
  411. };
  412. const timer = window.setInterval(() => {
  413. void pollRegistration();
  414. }, pollIntervalMs);
  415. void pollRegistration();
  416. return () => {
  417. cancelled = true;
  418. window.clearInterval(timer);
  419. };
  420. }, [botsService, createBindCodeForBot, feishuRegistration, intl, open, saveBot, selectedBot]);
  421. useEffect(() => {
  422. const registration = weixinRegistration;
  423. if (!open || !selectedBot || selectedBot.provider !== "weixin" || !registration) {
  424. return undefined;
  425. }
  426. if (registration.status !== "pending" && registration.status !== "scanned") {
  427. return undefined;
  428. }
  429. let cancelled = false;
  430. let timer: number | undefined;
  431. const pollIntervalMs = Math.max(1, registration.interval) * 1000;
  432. const scheduleNextPoll = () => {
  433. if (cancelled) {
  434. return;
  435. }
  436. timer = window.setTimeout(() => {
  437. void runPoll();
  438. }, pollIntervalMs);
  439. };
  440. const pollRegistration = async () => {
  441. try {
  442. const result = await botsService.pollWeixinRegistration({
  443. qrCode: registration.qrCode,
  444. });
  445. if (cancelled) {
  446. return;
  447. }
  448. if (result.status === "pending" || result.status === "scanned") {
  449. setWeixinRegistration((current) => {
  450. if (current?.qrCode !== registration.qrCode) {
  451. return current;
  452. }
  453. if (current.interval === result.interval && current.status === result.status) {
  454. return current;
  455. }
  456. return {
  457. ...current,
  458. interval: result.interval,
  459. status: result.status,
  460. };
  461. });
  462. return;
  463. }
  464. if (result.status === "success") {
  465. await saveBot(
  466. {
  467. ...selectedBot,
  468. webhookUrl: undefined,
  469. providerUserId: result.botId ?? selectedBot.providerUserId,
  470. displayName: result.botId ?? selectedBot.displayName,
  471. name: selectedBot.name,
  472. },
  473. { credentialValue: result.botToken },
  474. );
  475. if (!cancelled) {
  476. // Bugfix: 微信扫码成功即完成连接,保留 QR registration 会让用户看到过期的扫码区域。
  477. // 清掉临时状态后,Bot token 行会切到已连通的 Unbind 操作。
  478. setWeixinRegistration(null);
  479. toast(intl.formatMessage({ id: "bots.weixinRegistrationSuccess" }));
  480. }
  481. cancelled = true;
  482. return;
  483. }
  484. setWeixinRegistration((current) =>
  485. current?.qrCode === registration.qrCode
  486. ? {
  487. ...current,
  488. status: result.status,
  489. message:
  490. ("message" in result ? result.message : undefined) ??
  491. intl.formatMessage({
  492. id: `bots.weixinRegistration.${result.status}`,
  493. }),
  494. }
  495. : current,
  496. );
  497. cancelled = true;
  498. } catch (error) {
  499. const message = error instanceof Error ? error.message : String(error);
  500. logger.error("[BotsDialog] 微信扫码登录轮询失败", message);
  501. }
  502. };
  503. const runPoll = async () => {
  504. await pollRegistration();
  505. scheduleNextPoll();
  506. };
  507. // Bugfix: 微信扫码状态接口会长等待,如果用 setInterval 会在上一次请求未返回时继续堆叠 RPC。
  508. // 串行轮询可以避免连续 timeout,也避免多个结果互相覆盖 UI 状态。
  509. void runPoll();
  510. return () => {
  511. cancelled = true;
  512. if (timer !== undefined) {
  513. window.clearTimeout(timer);
  514. }
  515. };
  516. }, [botsService, intl, open, saveBot, selectedBot, weixinRegistration]);
  517. const patchSelectedBot = useCallback(
  518. (patch: Partial<BotConfig>) => {
  519. if (!selectedBot) return;
  520. void saveBot({ ...selectedBot, ...patch });
  521. },
  522. [saveBot, selectedBot],
  523. );
  524. const startBotNameRename = useCallback(() => {
  525. if (!selectedBot) return;
  526. setRenamingBotId(selectedBot.id);
  527. setBotNameDraft({ botId: selectedBot.id, value: selectedBot.name });
  528. }, [selectedBot]);
  529. const commitBotNameDraft = useCallback(() => {
  530. if (!selectedBot) return;
  531. const nextName = selectedBotName.trim();
  532. setBotNameDraft(null);
  533. setRenamingBotId(null);
  534. if (nextName === selectedBot.name) return;
  535. // Bugfix: Bot 名称输入过程中如果立即保存,服务层 trim 后的回写会吃掉刚输入的尾部空格,
  536. // 导致用户无法继续输入包含空格的名称;改为提交时保存,保留输入过程中的本地草稿。
  537. // 同时空名称是合法的未命名状态,展示层统一用多语言 fallback 名称兜底。
  538. void saveBot({ ...selectedBot, name: nextName });
  539. }, [saveBot, selectedBot, selectedBotName]);
  540. const handleBotNameKeyDown = useCallback(
  541. (event: KeyboardEvent<HTMLInputElement>) => {
  542. if (event.key === "Enter") {
  543. if (
  544. isImeComposingKeyEvent({
  545. compositionActive: botNameCompositionActiveRef.current,
  546. nativeEvent: event.nativeEvent,
  547. })
  548. ) {
  549. // Bugfix: Bot 名称重命名时中文输入法 Enter 是候选词确认,不是提交重命名。
  550. // 这里避免触发 blur,否则 blur 会继续走 commitBotNameDraft。
  551. logger.debug("[BotsDialog] ignore bot name enter during IME", {
  552. botId: selectedBot?.id ?? null,
  553. });
  554. return;
  555. }
  556. event.currentTarget.blur();
  557. return;
  558. }
  559. if (event.key === "Escape") {
  560. // Bugfix: 重命名输入框里的 Escape 只应该取消编辑,不能继续冒泡触发 Dialog 的关闭快捷键。
  561. setBotNameDraft(null);
  562. setRenamingBotId(null);
  563. event.preventDefault();
  564. event.stopPropagation();
  565. }
  566. },
  567. [selectedBot?.id],
  568. );
  569. const handleDialogEscapeKeyDown = useCallback(
  570. (event: Event) => {
  571. if (renamingBotId === null) return;
  572. // Bugfix: Radix Dialog 会在输入框 React onKeyDown 冒泡前处理 Escape 关闭。
  573. // 正在重命名时需要在 Dialog 的关闭入口拦截,Esc 只取消编辑,不关闭弹窗。
  574. event.preventDefault();
  575. setBotNameDraft(null);
  576. setRenamingBotId(null);
  577. },
  578. [renamingBotId],
  579. );
  580. const patchAllowedWorkspaces = useCallback(
  581. async (allowedWorkspaces: string[]) => {
  582. if (!selectedBot) return;
  583. setWorkspaceAccessSaving(true);
  584. const normalizedAllowedWorkspaces =
  585. allowedWorkspaces.length > 0 ? allowedWorkspaces : [ALL_BOT_WORKSPACES];
  586. const previousBot = selectedBot;
  587. const optimisticBot = {
  588. ...selectedBot,
  589. allowedWorkspaces: normalizedAllowedWorkspaces,
  590. };
  591. setConfig((previous) => ({
  592. ...previous,
  593. bots: previous.bots.map((bot) => (bot.id === optimisticBot.id ? optimisticBot : bot)),
  594. }));
  595. try {
  596. await saveBot(optimisticBot);
  597. } catch (error) {
  598. const message = error instanceof Error ? error.message : String(error);
  599. logger.error("[BotsDialog] 保存工作区访问范围失败", message);
  600. setConfig((previous) => ({
  601. ...previous,
  602. bots: previous.bots.map((bot) => (bot.id === previousBot.id ? previousBot : bot)),
  603. }));
  604. toast(intl.formatMessage({ id: "bots.saveFailed" }, { error: message }));
  605. } finally {
  606. setWorkspaceAccessSaving(false);
  607. }
  608. },
  609. [intl, saveBot, selectedBot],
  610. );
  611. const toggleWorkspaceAccess = useCallback(
  612. async (workspaceId: string, checked: boolean) => {
  613. if (!selectedBot) return;
  614. const currentAllowed = isAllWorkspacesAllowed(selectedBot.allowedWorkspaces)
  615. ? workspaceRefs.map((workspace) => workspace.id)
  616. : selectedBot.allowedWorkspaces;
  617. const nextAllowed = checked
  618. ? [...new Set([...currentAllowed, workspaceId])]
  619. : currentAllowed.filter((id) => id !== workspaceId);
  620. await patchAllowedWorkspaces(nextAllowed);
  621. },
  622. [patchAllowedWorkspaces, selectedBot, workspaceRefs],
  623. );
  624. const handleBeginAddBot = () => {
  625. setCreatingBot(true);
  626. setCreatingProvider(null);
  627. setSelectedBotId(null);
  628. setCredentialValue("");
  629. setFeishuRegistration(null);
  630. setWeixinRegistration(null);
  631. };
  632. const handleAddBot = useCallback(
  633. async (provider: BotProvider) => {
  634. if (creatingProvider) return;
  635. setCreatingProvider(provider);
  636. const bot = createDraftBot({
  637. provider,
  638. });
  639. try {
  640. await saveBot({
  641. ...bot,
  642. name: "",
  643. ...(provider === "webhook" ? { webhookAuthHeaderName: "x-zcode-bot-secret" } : {}),
  644. });
  645. } catch (error) {
  646. const message = error instanceof Error ? error.message : String(error);
  647. logger.error("[BotsDialog] 创建 Bot 失败", message);
  648. toast(intl.formatMessage({ id: "bots.saveFailed" }, { error: message }));
  649. } finally {
  650. setCreatingProvider(null);
  651. }
  652. },
  653. [creatingProvider, intl, saveBot],
  654. );
  655. useEffect(() => {
  656. if (!open || !entryProvider || !configLoaded) {
  657. return;
  658. }
  659. if (handledEntryProviderRef.current === entryProvider) {
  660. return;
  661. }
  662. const entry = resolveBotProviderEntry(config.bots, entryProvider);
  663. handledEntryProviderRef.current = entryProvider;
  664. setCredentialValue("");
  665. setFeishuRegistration(null);
  666. setWeixinRegistration(null);
  667. if (entry.mode === "select") {
  668. setCreatingBot(false);
  669. setCreatingProvider(null);
  670. setSelectedBotId(entry.botId);
  671. return;
  672. }
  673. // Bugfix: 远程控制弹窗新增 Bot Channel 快捷入口后,进入 BotsDialog 不能停在空白选择页。
  674. // 这里在配置加载完成后再判断并创建,避免异步刷新尚未拿到已有 bot 时重复新建。
  675. setCreatingBot(true);
  676. setSelectedBotId(null);
  677. void handleAddBot(entry.provider);
  678. }, [config.bots, configLoaded, entryProvider, handleAddBot, open]);
  679. const handleCreateBindCode = async () => {
  680. if (!selectedBot) return;
  681. await createBindCodeForBot(selectedBot);
  682. };
  683. const handleSaveSecret = async () => {
  684. if (!selectedBot || secretSaving) return;
  685. setSecretSaving(true);
  686. try {
  687. await saveBot(selectedBot, { credentialValue });
  688. } catch (error) {
  689. const message = error instanceof Error ? error.message : String(error);
  690. logger.error("[BotsDialog] 保存 Bot secret 失败", message);
  691. toast(intl.formatMessage({ id: "bots.saveFailed" }, { error: message }));
  692. } finally {
  693. setSecretSaving(false);
  694. }
  695. };
  696. const handleStartFeishuRegistration = useCallback(async () => {
  697. if (!selectedBot || !isFeishuBotProvider(selectedBot.provider)) return;
  698. setFeishuRegistrationLoading(true);
  699. try {
  700. const result = await botsService.beginFeishuRegistration({
  701. domain: selectedBot.provider,
  702. });
  703. let qrDataUrl: string | null = null;
  704. try {
  705. qrDataUrl = await QRCode.toDataURL(result.qrUrl, {
  706. margin: 1,
  707. width: 220,
  708. });
  709. } catch (error) {
  710. logger.error(
  711. "[BotsDialog] 生成飞书注册二维码失败",
  712. error instanceof Error ? error.message : String(error),
  713. );
  714. }
  715. setFeishuRegistration({
  716. botId: selectedBot.id,
  717. deviceCode: result.deviceCode,
  718. qrUrl: result.qrUrl,
  719. qrDataUrl,
  720. userCode: result.userCode,
  721. interval: result.interval,
  722. expiresAt: result.expiresAt,
  723. domain: result.domain,
  724. pollDomain: result.pollDomain,
  725. status: "pending",
  726. });
  727. toast(intl.formatMessage({ id: "bots.feishuRegistrationStarted" }));
  728. } catch (error) {
  729. const message = error instanceof Error ? error.message : String(error);
  730. logger.error("[BotsDialog] 启动飞书扫码注册失败", message);
  731. toast(intl.formatMessage({ id: "bots.feishuRegistrationFailed" }, { error: message }));
  732. } finally {
  733. setFeishuRegistrationLoading(false);
  734. }
  735. }, [botsService, intl, selectedBot]);
  736. const handleStartWeixinRegistration = useCallback(async () => {
  737. if (!selectedBot || selectedBot.provider !== "weixin") return;
  738. setWeixinRegistrationLoading(true);
  739. try {
  740. const result = await botsService.beginWeixinRegistration();
  741. let qrDataUrl: string | null = null;
  742. try {
  743. qrDataUrl = await QRCode.toDataURL(result.qrUrl, {
  744. margin: 1,
  745. width: 220,
  746. });
  747. } catch (error) {
  748. logger.error(
  749. "[BotsDialog] 生成微信登录二维码失败",
  750. error instanceof Error ? error.message : String(error),
  751. );
  752. }
  753. setWeixinRegistration({
  754. botId: selectedBot.id,
  755. qrCode: result.qrCode,
  756. qrUrl: result.qrUrl,
  757. qrDataUrl,
  758. interval: result.interval,
  759. expiresAt: result.expiresAt,
  760. status: "pending",
  761. });
  762. toast(intl.formatMessage({ id: "bots.weixinRegistrationStarted" }));
  763. } catch (error) {
  764. const message = error instanceof Error ? error.message : String(error);
  765. logger.error("[BotsDialog] 启动微信扫码登录失败", message);
  766. toast(intl.formatMessage({ id: "bots.weixinRegistrationFailed" }, { error: message }));
  767. } finally {
  768. setWeixinRegistrationLoading(false);
  769. }
  770. }, [botsService, intl, selectedBot]);
  771. useEffect(() => {
  772. if (!open || creatingBot || !selectedBot) {
  773. return;
  774. }
  775. if (isFeishuBotProvider(selectedBot.provider)) {
  776. if (!selectedBot.credentialRef) {
  777. if (feishuRegistrationLoading) {
  778. return;
  779. }
  780. if (feishuRegistration?.botId === selectedBot.id) {
  781. return;
  782. }
  783. const autoKey = `${selectedBot.id}:feishu-registration`;
  784. if (autoQrStartedBotIdsRef.current.has(autoKey)) {
  785. return;
  786. }
  787. // Bugfix: 未配置 token 的飞书/Lark Bot 首次进入详情时只显示“扫码”按钮,
  788. // 用户会误以为还需要额外展开;自动启动一次二维码流程,让缺失凭据的默认状态直接可操作。
  789. autoQrStartedBotIdsRef.current.add(autoKey);
  790. void handleStartFeishuRegistration();
  791. return;
  792. }
  793. if (!selectedBot.providerUserId) {
  794. if (bindCode?.botId === selectedBot.id && !bindExpired) {
  795. return;
  796. }
  797. if (autoBindCreatingBotIdsRef.current.has(selectedBot.id)) {
  798. return;
  799. }
  800. // Bugfix: 飞书/Lark 的接入凭据和聊天绑定是两个阶段;已有凭据但未绑定时需要自动展示 /bind。
  801. // 绑定码现在只有 30 秒有效期,过期后如果还停在旧码会打断自动绑定流程;这里自动续一枚新码。
  802. autoBindCreatingBotIdsRef.current.add(selectedBot.id);
  803. void createBindCodeForBot(selectedBot).finally(() => {
  804. autoBindCreatingBotIdsRef.current.delete(selectedBot.id);
  805. });
  806. }
  807. return;
  808. }
  809. if (selectedBot.provider === "telegram") {
  810. if (!selectedBot.credentialRef || selectedBot.providerUserId) {
  811. return;
  812. }
  813. if (bindCode?.botId === selectedBot.id && !bindExpired) {
  814. return;
  815. }
  816. if (autoBindCreatingBotIdsRef.current.has(selectedBot.id)) {
  817. return;
  818. }
  819. // Bugfix: Telegram 和飞书/Lark 一样分成凭据接入与私聊绑定两步;
  820. // token 保存后自动展示 /bind;绑定码过期也自动续码,避免 30 秒有效期让用户卡在旧码上。
  821. autoBindCreatingBotIdsRef.current.add(selectedBot.id);
  822. void createBindCodeForBot(selectedBot).finally(() => {
  823. autoBindCreatingBotIdsRef.current.delete(selectedBot.id);
  824. });
  825. return;
  826. }
  827. if (selectedBot.provider !== "weixin") {
  828. return;
  829. }
  830. if (selectedBot.credentialRef || weixinRegistrationLoading) {
  831. return;
  832. }
  833. if (weixinRegistration?.botId === selectedBot.id) {
  834. return;
  835. }
  836. const autoKey = `${selectedBot.id}:weixin-registration`;
  837. if (autoQrStartedBotIdsRef.current.has(autoKey)) {
  838. return;
  839. }
  840. // Bugfix: 微信 Bot 没有 token/绑定状态时需要立即给出登录二维码,
  841. // 否则新建后右侧默认只露出按钮,和“扫码接入”的主流程不一致。
  842. autoQrStartedBotIdsRef.current.add(autoKey);
  843. void handleStartWeixinRegistration();
  844. }, [
  845. creatingBot,
  846. feishuRegistration,
  847. feishuRegistrationLoading,
  848. bindCode,
  849. bindExpired,
  850. createBindCodeForBot,
  851. handleStartFeishuRegistration,
  852. handleStartWeixinRegistration,
  853. open,
  854. selectedBot,
  855. weixinRegistration,
  856. weixinRegistrationLoading,
  857. ]);
  858. const handleOpenTelegramBotFather = () => {
  859. platform.openExternal(TELEGRAM_BOTFATHER_URL);
  860. };
  861. const copyBindCommand = async () => {
  862. if (!bindCode || bindExpired) return;
  863. const command = `/bind ${bindCode.code}`;
  864. await navigator.clipboard?.writeText(command).catch((error: unknown) => {
  865. logger.warn(
  866. "[BotsDialog] 复制绑定命令失败",
  867. error instanceof Error ? error.message : String(error),
  868. );
  869. });
  870. toast(intl.formatMessage({ id: "bots.bindCommandCopied" }));
  871. };
  872. const handleUnbind = async () => {
  873. if (!selectedBot) return;
  874. await saveBot({
  875. ...selectedBot,
  876. providerUserId: undefined,
  877. displayName: undefined,
  878. });
  879. await botsService.resetBotState(selectedBot.id);
  880. };
  881. const handleRemoveSecret = async () => {
  882. if (!selectedBot) return;
  883. try {
  884. const saved = await botsService.removeBotSecret(selectedBot.id);
  885. autoQrStartedBotIdsRef.current.delete(`${selectedBot.id}:feishu-registration`);
  886. autoQrStartedBotIdsRef.current.delete(`${selectedBot.id}:weixin-registration`);
  887. autoBindCreatingBotIdsRef.current.delete(selectedBot.id);
  888. setConfig((previous) => ({
  889. ...previous,
  890. bots: previous.bots.map((item) => (item.id === saved.id ? saved : item)),
  891. }));
  892. setCredentialValue("");
  893. setBindCode(null);
  894. void refresh();
  895. } catch (error) {
  896. const message = error instanceof Error ? error.message : String(error);
  897. logger.error("[BotsDialog] 移除 Bot secret 失败", message);
  898. toast(intl.formatMessage({ id: "bots.removeSecretFailed" }, { error: message }));
  899. }
  900. };
  901. const handleDelete = async () => {
  902. if (!selectedBot) return;
  903. // Bugfix: 删除机器人之前没有二次确认,误触会直接移除凭据和绑定入口。
  904. // 这里复用项目统一 ConfirmDialog,让破坏性操作和其它设置页保持一致。
  905. const confirmed = await confirmDialog({
  906. confirmVariant: "destructive",
  907. title: intl.formatMessage(
  908. { id: "bots.deleteConfirmTitle" },
  909. { name: formatBotDisplayName(selectedBot.name, fallbackBotName) },
  910. ),
  911. description: intl.formatMessage({ id: "bots.deleteConfirmDescription" }),
  912. confirmLabel: intl.formatMessage({ id: "bots.delete" }),
  913. });
  914. if (!confirmed) return;
  915. try {
  916. await botsService.deleteBot(selectedBot.id);
  917. setSelectedBotId(null);
  918. void refresh();
  919. } catch (error) {
  920. const message = error instanceof Error ? error.message : String(error);
  921. logger.error("[BotsDialog] 删除 Bot 失败", message);
  922. toast(intl.formatMessage({ id: "bots.deleteFailed" }, { error: message }));
  923. }
  924. };
  925. const selectedRuntime = selectedBot
  926. ? status?.botRuntime.find((item) => item.botId === selectedBot.id)
  927. : undefined;
  928. const formatChannelName = (provider: BotProviderEntryId) =>
  929. intl.formatMessage({ id: `bots.channel.${provider}` });
  930. const renderChannelName = (provider: BotProviderEntryId) => {
  931. const regionTagLabelId = getBotProviderRegionTagLabelId(provider);
  932. return (
  933. <span className="inline-flex min-w-0 items-center gap-1.5">
  934. <span className="min-w-0 truncate">{formatChannelName(provider)}</span>
  935. {regionTagLabelId ? (
  936. <span className="inline-flex h-5 shrink-0 items-center rounded-full border border-border px-2 text-ui-xs font-medium leading-none text-foreground-subtle">
  937. {intl.formatMessage({ id: regionTagLabelId })}
  938. </span>
  939. ) : null}
  940. </span>
  941. );
  942. };
  943. return (
  944. <Dialog open={open} onOpenChange={onOpenChange}>
  945. <DialogContent
  946. className="flex h-[calc(100vh-6rem)] max-h-168 max-w-4xl flex-col overflow-hidden rounded-2xl"
  947. onEscapeKeyDown={handleDialogEscapeKeyDown}
  948. >
  949. <DialogHeader>
  950. <div className="flex flex-wrap items-center gap-2">
  951. <Bot className="size-5 text-foreground" />
  952. <DialogTitle className="text-ui-lg font-medium text-foreground">
  953. {intl.formatMessage({ id: "bots.title" })}
  954. </DialogTitle>
  955. <DialogDescription className="ml-3">
  956. {intl.formatMessage({ id: "bots.description" })}
  957. </DialogDescription>
  958. </div>
  959. </DialogHeader>
  960. <div className="flex min-h-0 flex-1 flex-col gap-3 md:flex-row">
  961. <aside className="flex max-h-40 w-full shrink-0 flex-col md:max-h-none md:w-64">
  962. <div className="min-h-0 flex-1 overflow-y-auto">
  963. <Button
  964. type="button"
  965. variant="outline"
  966. size="lg"
  967. onClick={handleBeginAddBot}
  968. className="mb-3 w-full justify-start gap-2 rounded-xl"
  969. >
  970. <Plus className="size-4" />
  971. <span className="min-w-0 truncate">
  972. {intl.formatMessage({ id: "bots.addBot" })}
  973. </span>
  974. </Button>
  975. {config.bots.length === 0 ? (
  976. <div className="p-4 text-ui-base text-foreground-subtle">
  977. {creatingBot
  978. ? intl.formatMessage({
  979. id: "bots.newBot.selectProviderHint",
  980. })
  981. : intl.formatMessage({ id: "bots.empty" })}
  982. </div>
  983. ) : (
  984. config.bots.map((bot) => {
  985. const runtime = status?.botRuntime.find((item) => item.botId === bot.id);
  986. const selected = bot.id === selectedBotId;
  987. return (
  988. <button
  989. key={bot.id}
  990. type="button"
  991. onClick={() => {
  992. setCreatingBot(false);
  993. setSelectedBotId(bot.id);
  994. }}
  995. className={cn(
  996. "mb-1 w-full rounded-xl px-2.5 pr-4 py-3 text-left transition-colors",
  997. selected
  998. ? "bg-surface-hover text-foreground"
  999. : "text-foreground-subtle hover:bg-surface-hover hover:text-foreground",
  1000. )}
  1001. >
  1002. <div className="flex items-center gap-2">
  1003. <ProviderIcon
  1004. provider={bot.provider}
  1005. className="size-10 shrink-0 object-contain text-foreground-subtle"
  1006. />
  1007. <span className="min-w-0 flex-1">
  1008. <span className="block text-foreground truncate text-ui-base font-medium">
  1009. {formatBotDisplayName(bot.name, fallbackBotName)}
  1010. </span>
  1011. <span className="mt-0.5 flex min-w-0 text-ui-base text-foreground-subtle">
  1012. {renderChannelName(bot.provider)}
  1013. </span>
  1014. </span>
  1015. <span
  1016. className={cn(
  1017. "size-2 shrink-0 rounded-full",
  1018. runtimeDot(runtime, bot.enabled),
  1019. )}
  1020. />
  1021. </div>
  1022. </button>
  1023. );
  1024. })
  1025. )}
  1026. </div>
  1027. </aside>
  1028. <section className="min-w-0 flex-1 overflow-y-auto rounded-xl border border-border bg-background p-4">
  1029. {creatingBot ? (
  1030. <div className="mx-auto flex min-h-full max-w-3xl flex-col justify-start gap-6">
  1031. <div className="space-y-2">
  1032. <div className="text-ui-lg font-medium">
  1033. {intl.formatMessage({ id: "bots.newBot.title" })}
  1034. </div>
  1035. <p className="max-w-2xl text-ui-base leading-6 text-foreground-subtle">
  1036. {intl.formatMessage({ id: "bots.newBot.description" })}
  1037. </p>
  1038. </div>
  1039. <div className="grid gap-3 md:grid-cols-2">
  1040. {BOT_PROVIDERS.filter((provider) => provider.id !== "webhook").map((provider) => {
  1041. const implemented = provider.implemented;
  1042. const isCreatingThisProvider = creatingProvider === provider.id;
  1043. const isCreatingAnyProvider = creatingProvider !== null;
  1044. return (
  1045. <button
  1046. key={provider.id}
  1047. type="button"
  1048. disabled={!implemented || isCreatingAnyProvider}
  1049. aria-busy={isCreatingThisProvider}
  1050. onClick={() => (implemented ? void handleAddBot(provider.id) : undefined)}
  1051. className={cn(
  1052. "flex items-start gap-3 rounded-lg border border-card-border bg-card py-4 px-3 text-left transition-colors",
  1053. implemented && !isCreatingAnyProvider
  1054. ? "hover:border-input-border-focused hover:bg-surface-hover"
  1055. : "cursor-not-allowed opacity-60",
  1056. isCreatingThisProvider &&
  1057. "border-input-border-focused bg-surface-hover opacity-100",
  1058. )}
  1059. >
  1060. {isCreatingThisProvider ? (
  1061. <div className="flex size-10 items-center justify-center">
  1062. <LoaderCircle className="size-6 shrink-0 animate-spin text-foreground-subtle" />
  1063. </div>
  1064. ) : (
  1065. <ProviderIcon
  1066. provider={provider.id}
  1067. className="size-10 shrink-0 text-foreground"
  1068. />
  1069. )}
  1070. <span className="min-w-0 flex-1">
  1071. <span className="flex min-w-0 text-ui-lg font-medium">
  1072. {renderChannelName(provider.id)}
  1073. </span>
  1074. <span className="mt-1 block text-ui-base text-foreground-subtle">
  1075. {implemented
  1076. ? intl.formatMessage({
  1077. id: `bots.newBot.providerDescription.${provider.id}`,
  1078. })
  1079. : intl.formatMessage({
  1080. id: "bots.newBot.comingSoon",
  1081. })}
  1082. </span>
  1083. </span>
  1084. </button>
  1085. );
  1086. })}
  1087. </div>
  1088. </div>
  1089. ) : !selectedBot ? (
  1090. <div className="flex h-full flex-col items-center justify-center gap-3 text-ui-base text-foreground-subtle">
  1091. <Bot className="size-8" />
  1092. <div>{intl.formatMessage({ id: "bots.empty" })}</div>
  1093. <Button variant="outline" size="lg" onClick={handleBeginAddBot}>
  1094. <Plus className="size-4" />
  1095. {intl.formatMessage({ id: "bots.addBot" })}
  1096. </Button>
  1097. </div>
  1098. ) : (
  1099. <div className="space-y-4">
  1100. <BotSummaryCard
  1101. bot={selectedBot}
  1102. runtime={selectedRuntime}
  1103. selectedBotDisplayName={selectedBotDisplayName}
  1104. selectedBotName={selectedBotName}
  1105. fallbackBotName={fallbackBotName}
  1106. renaming={renamingBotId === selectedBot.id}
  1107. onStartRename={startBotNameRename}
  1108. onCommitNameDraft={commitBotNameDraft}
  1109. onNameDraftChange={(value) => setBotNameDraft({ botId: selectedBot.id, value })}
  1110. onNameCompositionEnd={() => {
  1111. botNameCompositionActiveRef.current = false;
  1112. }}
  1113. onNameCompositionStart={() => {
  1114. botNameCompositionActiveRef.current = true;
  1115. }}
  1116. onNameInputKeyDown={handleBotNameKeyDown}
  1117. onPatchBot={patchSelectedBot}
  1118. />
  1119. <ProviderSettingsCard
  1120. bot={selectedBot}
  1121. runtime={selectedRuntime}
  1122. credentialValue={credentialValue}
  1123. bindCode={bindCode}
  1124. bindExpired={bindExpired}
  1125. bindRemainingMs={bindRemainingMs}
  1126. bindCountdownProgress={bindCountdownProgress}
  1127. feishuRegistration={feishuRegistration}
  1128. feishuRegistrationLoading={feishuRegistrationLoading}
  1129. weixinRegistration={weixinRegistration}
  1130. weixinRegistrationLoading={weixinRegistrationLoading}
  1131. weixinActivated={Boolean(selectedBotState?.weixinActivatedAt)}
  1132. secretSaving={secretSaving}
  1133. onCredentialValueChange={setCredentialValue}
  1134. onSaveSecret={() => void handleSaveSecret()}
  1135. onRemoveSecret={() => void handleRemoveSecret()}
  1136. onOpenTelegramBotFather={handleOpenTelegramBotFather}
  1137. onStartWeixinRegistration={() => void handleStartWeixinRegistration()}
  1138. onStartFeishuRegistration={() => void handleStartFeishuRegistration()}
  1139. onCreateBindCode={() => void handleCreateBindCode()}
  1140. onUnbind={() => void handleUnbind()}
  1141. onCopyBindCommand={() => void copyBindCommand()}
  1142. />
  1143. <SettingsGroupCard>
  1144. <BotReplyGranularityCard bot={selectedBot} onPatchBot={patchSelectedBot} />
  1145. {/*
  1146. 暂不暴露命令权限编辑入口,避免用户在 bot 可用前把关键命令关掉。
  1147. 如果要恢复 UI,重新渲染 selectedBot.allowedCommands 的列表并用 patchSelectedBot 保存。
  1148. */}
  1149. <WorkspaceAccessCard
  1150. bot={selectedBot}
  1151. workspaceRefs={workspaceRefs}
  1152. loading={workspaceAccessSaving}
  1153. onPatchAllowedWorkspaces={patchAllowedWorkspaces}
  1154. onToggleWorkspaceAccess={toggleWorkspaceAccess}
  1155. />
  1156. </SettingsGroupCard>
  1157. {isFeishuBotProvider(selectedBot.provider) && (
  1158. <BoundGroupsCard
  1159. key={selectedBot.id + ":" + selectedBot.providerUserId}
  1160. bot={selectedBot}
  1161. />
  1162. )}
  1163. <BotDangerCard onDelete={() => void handleDelete()} />
  1164. </div>
  1165. )}
  1166. </section>
  1167. </div>
  1168. </DialogContent>
  1169. </Dialog>
  1170. );
  1171. }