feishuChannelRuntime.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import {
  2. isFeishuBotProvider,
  3. type BotConfig,
  4. type BotProvider,
  5. type BotProviderCallbackResult,
  6. type BotsConfigFile,
  7. } from "@zcode/shared";
  8. import type { ICredentialService } from "../credential/credential.js";
  9. import { startFeishuBotWebSocket, type FeishuWebSocketClient } from "./providers/feishuProvider.js";
  10. import {
  11. acquireFeishuWebSocketLock,
  12. assertBotCallbackSucceeded,
  13. BOT_RUNTIME_LOCK_RETRY_MS,
  14. createBotConnectionFingerprint,
  15. createLatestRuntimeRefreshQueue,
  16. type BotRuntimeLogger,
  17. type BotRuntimeStatusSink,
  18. waitFor,
  19. waitForAbort,
  20. } from "./channelRuntime.js";
  21. interface FeishuChannelRuntimeDeps {
  22. runBackgroundTasks?: boolean;
  23. onConnectionInvalidated?(botId: string): void;
  24. credentialService: ICredentialService;
  25. logger: BotRuntimeLogger;
  26. statusSink: BotRuntimeStatusSink;
  27. ensureBotStorageMigrated(): Promise<void>;
  28. readConfig(): Promise<BotsConfigFile>;
  29. summarizeCallbackPayload(payload: unknown): string;
  30. processProviderCallback(
  31. provider: BotProvider,
  32. payload: unknown,
  33. ): Promise<BotProviderCallbackResult>;
  34. acquireWebSocketLock?: typeof acquireFeishuWebSocketLock;
  35. startWebSocket?: typeof startFeishuBotWebSocket;
  36. }
  37. export function createFeishuChannelRuntime(deps: FeishuChannelRuntimeDeps) {
  38. interface RuntimeEntry {
  39. controller: AbortController;
  40. fingerprint: string;
  41. done: Promise<void>;
  42. }
  43. const runtimes = new Map<string, RuntimeEntry>();
  44. const refreshQueue = createLatestRuntimeRefreshQueue();
  45. async function getConnectionFingerprint(bot: BotConfig): Promise<string> {
  46. const credential = bot.credentialRef
  47. ? await deps.credentialService.load(bot.credentialRef)
  48. : null;
  49. return createBotConnectionFingerprint([
  50. bot.provider,
  51. bot.feishuAppId ?? "",
  52. bot.credentialRef ?? "",
  53. credential ?? "",
  54. ]);
  55. }
  56. async function runBot(bot: BotConfig, signal: AbortSignal): Promise<void> {
  57. let client: FeishuWebSocketClient | null = null;
  58. while (!signal.aborted) {
  59. let lock: Awaited<ReturnType<typeof acquireFeishuWebSocketLock>>;
  60. try {
  61. lock = await (deps.acquireWebSocketLock ?? acquireFeishuWebSocketLock)(bot);
  62. } catch (error) {
  63. if (signal.aborted) {
  64. return;
  65. }
  66. // Bugfix: runtime 停止或锁目录异常时,锁文件创建可能在进入连接 try 块前失败。
  67. // 必须把 acquire 纳入可恢复循环,否则多窗口关闭会留下未处理 rejection。
  68. deps.logger.warn(
  69. undefined,
  70. `acquire Feishu WebSocket lock failed bot=${bot.id}: ${error instanceof Error ? `${error.message}${"code" in error && typeof error.code === "string" ? ` code=${error.code}` : ""}` : String(error)}`,
  71. );
  72. deps.statusSink.setRuntimeStatus({
  73. botId: bot.id,
  74. provider: bot.provider,
  75. status: "error",
  76. message: `Feishu WebSocket lock failed: ${error instanceof Error ? error.message : String(error)}`,
  77. });
  78. await waitFor(5_000, signal);
  79. continue;
  80. }
  81. if (!lock) {
  82. deps.statusSink.setRuntimeStatus({
  83. botId: bot.id,
  84. provider: bot.provider,
  85. status: "idle",
  86. message: "Feishu WebSocket is handled by another ZCode window.",
  87. });
  88. await waitFor(BOT_RUNTIME_LOCK_RETRY_MS, signal);
  89. continue;
  90. }
  91. let retryAfterError = false;
  92. try {
  93. deps.statusSink.setRuntimeStatus({
  94. botId: bot.id,
  95. provider: bot.provider,
  96. status: "connected",
  97. messageId: "bots.runtime.feishuWebSocketConnecting",
  98. message: "Feishu WebSocket is connecting.",
  99. });
  100. deps.onConnectionInvalidated?.(bot.id);
  101. client = await (deps.startWebSocket ?? startFeishuBotWebSocket)({
  102. bot,
  103. signal,
  104. onConnectionStateChange: (state) => {
  105. if (state === "reconnecting") deps.onConnectionInvalidated?.(bot.id);
  106. deps.statusSink.setRuntimeStatus({
  107. botId: bot.id,
  108. provider: bot.provider,
  109. status: "connected",
  110. message:
  111. state === "reconnecting"
  112. ? "Feishu WebSocket is reconnecting."
  113. : "Feishu WebSocket is running.",
  114. messageId:
  115. state === "reconnecting"
  116. ? "bots.runtime.feishuWebSocketConnecting"
  117. : "bots.runtime.feishuWebSocketRunning",
  118. });
  119. },
  120. deps: {
  121. loadCredential: (key) => deps.credentialService.load(key),
  122. },
  123. onPayload: async (payload) => {
  124. if (signal.aborted) {
  125. return;
  126. }
  127. deps.logger.debug(
  128. undefined,
  129. `feishu websocket payload bot=${bot.id} ${deps.summarizeCallbackPayload(payload)}`,
  130. );
  131. const callbackResult = await deps.processProviderCallback(bot.provider, payload);
  132. assertBotCallbackSucceeded(bot.provider === "lark" ? "Lark" : "Feishu", callbackResult);
  133. return callbackResult.replies[0];
  134. },
  135. });
  136. deps.statusSink.setRuntimeStatus({
  137. botId: bot.id,
  138. provider: bot.provider,
  139. status: "connected",
  140. // 修复:运行状态会直接展示到 UI。补充 messageId,让前端按当前语言渲染,message 仅作为旧版本兜底。
  141. message: "Feishu WebSocket is running.",
  142. messageId: "bots.runtime.feishuWebSocketRunning",
  143. });
  144. // Bugfix:首次 ready 不是长连接生命周期终点。SDK 重连耗尽必须进入 catch,
  145. // 才能更新错误状态、关闭 client、释放跨窗口锁并进入外层恢复循环。
  146. await Promise.race([
  147. waitForAbort(signal),
  148. client.terminated ?? new Promise<void>(() => undefined),
  149. ]);
  150. } catch (error) {
  151. if (signal.aborted) {
  152. return;
  153. }
  154. deps.statusSink.setRuntimeStatus({
  155. botId: bot.id,
  156. provider: bot.provider,
  157. status: "error",
  158. message: `Feishu WebSocket failed: ${error instanceof Error ? error.message : String(error)}`,
  159. });
  160. retryAfterError = true;
  161. } finally {
  162. if (client) {
  163. try {
  164. client.close();
  165. } catch (error) {
  166. deps.logger.debug(
  167. undefined,
  168. `close Feishu WebSocket failed bot=${bot.id}: ${error instanceof Error ? error.message : String(error)}`,
  169. );
  170. }
  171. client = null;
  172. }
  173. await lock.release().catch((error: unknown) => {
  174. deps.logger.warn(
  175. undefined,
  176. `release Feishu WebSocket lock failed bot=${bot.id}: ${error instanceof Error ? error.message : String(error)}`,
  177. );
  178. });
  179. }
  180. // 修复原因:重试退避不能占着旧 client 和跨窗口锁等待,必须先完整清理资源。
  181. if (retryAfterError) {
  182. await waitFor(5_000, signal);
  183. }
  184. }
  185. }
  186. async function stopWebSocket(botId: string): Promise<void> {
  187. const runtime = runtimes.get(botId);
  188. runtime?.controller.abort();
  189. if (runtime) {
  190. await runtime.done;
  191. if (runtimes.get(botId) === runtime) {
  192. runtimes.delete(botId);
  193. }
  194. }
  195. const previous = deps.statusSink.getRuntimeStatus(botId);
  196. if (previous) {
  197. deps.statusSink.setRuntimeStatus({
  198. ...previous,
  199. status: "idle",
  200. messageId: "bots.runtime.feishuWebSocketStopped",
  201. message: "Feishu WebSocket is stopped.",
  202. });
  203. }
  204. }
  205. function startWebSocket(bot: BotConfig, fingerprint: string): void {
  206. if (runtimes.has(bot.id)) {
  207. return;
  208. }
  209. const controller = new AbortController();
  210. deps.statusSink.setRuntimeStatus({
  211. botId: bot.id,
  212. provider: bot.provider,
  213. status: "connected",
  214. messageId: "bots.runtime.feishuWebSocketStarting",
  215. message: "Feishu WebSocket is starting.",
  216. });
  217. const runtime: RuntimeEntry = {
  218. controller,
  219. fingerprint,
  220. done: Promise.resolve(),
  221. };
  222. runtime.done = runBot(bot, controller.signal).finally(() => {
  223. if (runtimes.get(bot.id) === runtime) {
  224. runtimes.delete(bot.id);
  225. const previous = deps.statusSink.getRuntimeStatus(bot.id);
  226. if (previous?.status === "connected") {
  227. deps.statusSink.setRuntimeStatus({
  228. botId: bot.id,
  229. provider: bot.provider,
  230. status: "idle",
  231. messageId: "bots.runtime.feishuWebSocketStopped",
  232. message: "Feishu WebSocket is stopped.",
  233. });
  234. }
  235. }
  236. });
  237. runtimes.set(bot.id, runtime);
  238. }
  239. async function reconcile(
  240. config: BotsConfigFile | undefined,
  241. isLatest: () => boolean,
  242. ): Promise<void> {
  243. await deps.ensureBotStorageMigrated();
  244. const currentConfig = config ?? (await deps.readConfig());
  245. if (!isLatest()) {
  246. return;
  247. }
  248. const activeFeishuIds = new Set(
  249. currentConfig.bots
  250. .filter(
  251. (bot) =>
  252. isFeishuBotProvider(bot.provider) &&
  253. bot.enabled &&
  254. bot.credentialRef &&
  255. bot.feishuAppId,
  256. )
  257. .map((bot) => bot.id),
  258. );
  259. for (const botId of runtimes.keys()) {
  260. if (!activeFeishuIds.has(botId)) {
  261. await stopWebSocket(botId);
  262. if (!isLatest()) {
  263. return;
  264. }
  265. }
  266. }
  267. for (const bot of currentConfig.bots) {
  268. if (
  269. isFeishuBotProvider(bot.provider) &&
  270. bot.enabled &&
  271. bot.credentialRef &&
  272. bot.feishuAppId
  273. ) {
  274. const fingerprint = await getConnectionFingerprint(bot);
  275. if (!isLatest()) {
  276. return;
  277. }
  278. const runtime = runtimes.get(bot.id);
  279. if (runtime && runtime.fingerprint !== fingerprint) {
  280. // Bugfix: 飞书/Lark 的 provider、App ID 或凭据变化后,旧 WebSocket 仍持有旧配置。
  281. // 必须等待旧 client 和跨窗口锁释放后再启动新连接,保证同一 Bot 只有一个配置版本在线。
  282. await stopWebSocket(bot.id);
  283. if (!isLatest()) {
  284. return;
  285. }
  286. }
  287. startWebSocket(bot, fingerprint);
  288. } else if (isFeishuBotProvider(bot.provider) && !bot.enabled) {
  289. deps.statusSink.setRuntimeStatus({
  290. botId: bot.id,
  291. provider: bot.provider,
  292. status: "disabled",
  293. messageId: "bots.runtime.botDisabled",
  294. message: "Bot is disabled.",
  295. });
  296. }
  297. }
  298. }
  299. function refresh(config?: BotsConfigFile): Promise<void> {
  300. return refreshQueue.enqueue((isLatest) => reconcile(config, isLatest));
  301. }
  302. function scheduleRefresh(config?: BotsConfigFile): void {
  303. if (deps.runBackgroundTasks === false) {
  304. // 修复原因:remote workspace host / desktop-attached 远端只暴露控制面服务;
  305. // bot runtime 后台连接必须留在本地桌面 host,避免配置变更后重新抢跑。
  306. return;
  307. }
  308. void refresh(config).catch((error: unknown) => {
  309. deps.logger.warn(
  310. undefined,
  311. `refresh Feishu WebSocket failed: ${error instanceof Error ? error.message : String(error)}`,
  312. );
  313. });
  314. }
  315. async function dispose(): Promise<void> {
  316. refreshQueue.invalidate();
  317. const activeRuntimes = [...runtimes.values()];
  318. for (const runtime of activeRuntimes) {
  319. runtime.controller.abort();
  320. }
  321. // Bugfix:abort 只是发出取消信号;销毁终态必须等 WebSocket 关闭和 finally 释放跨进程锁。
  322. await Promise.allSettled(activeRuntimes.map((runtime) => runtime.done));
  323. for (const [botId, runtime] of runtimes) {
  324. if (activeRuntimes.includes(runtime)) {
  325. runtimes.delete(botId);
  326. }
  327. }
  328. }
  329. return {
  330. dispose,
  331. refresh,
  332. scheduleRefresh,
  333. stopWebSocket,
  334. };
  335. }