BotsDialog.tsx 46 KB

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