Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): handle Feishu conflict signals (#280)
yz1210989026685cf794
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.tsnew file mode 100644index 0000000000..7038a2cf47--- /dev/null+++ b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts@@ -0,0 +1,179 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from 'vitest';++import { feishuEvents } from '../events.js';++interface CapturingLogger {+ info: (...args: unknown[]) => void;+ error: (...args: unknown[]) => void;+}++interface MockSdkOptions {+ logger: CapturingLogger;+ onReady?: () => void;+ onError?: (error: Error) => void;+}++const mocks = {+ options: [] as MockSdkOptions[],+ start: vi.fn(async () => undefined),+ close: vi.fn(),+ bindClient: vi.fn(),+ unbindClient: vi.fn(),+ getBoundClient: vi.fn(() => null),+ sendText: vi.fn(),+ firstAllowed: vi.fn(() => null),+ checkOwner: vi.fn(() => true),+ tryClaimOwner: vi.fn(() => false),+ log: {+ trace: vi.fn(),+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ fatal: vi.fn(),+ },+};++vi.doMock('@larksuiteoapi/node-sdk', () => ({+ WSClient: class {+ readonly start = mocks.start;+ readonly close = mocks.close;++ constructor(options: MockSdkOptions) {+ mocks.options.push(options);+ }+ },+ EventDispatcher: class {+ register(): this {+ return this;+ }+ },+ LoggerLevel: { info: 'info' },+}));++vi.doMock('../outbound.js', () => ({+ bindClient: mocks.bindClient,+ unbindClient: mocks.unbindClient,+ getBoundClient: mocks.getBoundClient,+ sendText: mocks.sendText,+}));++vi.doMock('../ownerGuard.js', () => ({+ firstAllowed: mocks.firstAllowed,+ check: mocks.checkOwner,+ tryClaimOwner: mocks.tryClaimOwner,+}));++vi.doMock('../moduleScope.js', () => ({+ getLog: () => mocks.log,+}));++let wsClient: typeof import('../wsClient.js');++const credentials = {+ appId: 'cli_conflict_test',+ appSecret: 'secret',+};++function latestClient() {+ const options = mocks.options.at(-1);+ if (!options) throw new Error('expected WSClient to be constructed');+ return {+ options,+ logger: options.logger,+ start: mocks.start,+ close: mocks.close,+ };+}++beforeEach(async () => {+ await wsClient.stop({ announceOffline: false, reason: 'test-reset' });+ mocks.options.length = 0;+ vi.clearAllMocks();+});++afterEach(async () => {+ await wsClient.stop({ announceOffline: false, reason: 'test-cleanup' });+});++beforeAll(async () => {+ wsClient = await import('../wsClient.js');+});++afterAll(() => {+ vi.doUnmock('@larksuiteoapi/node-sdk');+ vi.doUnmock('../outbound.js');+ vi.doUnmock('../ownerGuard.js');+ vi.doUnmock('../moduleScope.js');+});++describe('Feishu WebSocket conflict handling', () => {+ it('maps exceed_conn_limit during initial connection to conflict and closes the socket', async () => {+ const onConflict = vi.fn();+ feishuEvents.on('conflict', onConflict);++ try {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ const sdkClient = latestClient();++ sdkClient.options.onError?.(+ new Error(+ 'pullConnectConfig failed: code=1000040350, msg=exceed_conn_limit',+ ),+ );+ sdkClient.options.onReady?.();+ expect(wsClient.getCurrentStatus()).not.toBe('connected');++ await expect(connecting).resolves.toBe('conflict');+ expect(wsClient.getCurrentStatus()).toBe('conflict');+ expect(sdkClient.close).toHaveBeenCalledWith({ force: true });+ expect(onConflict).toHaveBeenCalledOnce();+ expect(onConflict).toHaveBeenCalledWith({ appId: credentials.appId });+ } finally {+ feishuEvents.off('conflict', onConflict);+ }+ });++ it('revokes an already-ready connection when a late conflict signal arrives', async () => {+ const onConflict = vi.fn();+ feishuEvents.on('conflict', onConflict);++ try {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ const sdkClient = latestClient();+ sdkClient.options.onReady?.();++ await expect(connecting).resolves.toBe('connected');+ expect(wsClient.getCurrentStatus()).toBe('connected');++ sdkClient.options.onError?.(new Error('exceed_conn_limit'));++ await vi.waitFor(() => expect(wsClient.getCurrentStatus()).toBe('conflict'));+ expect(sdkClient.close).toHaveBeenCalledWith({ force: true });+ expect(onConflict).toHaveBeenCalledOnce();+ expect(onConflict).toHaveBeenCalledWith({ appId: credentials.appId });+ } finally {+ feishuEvents.off('conflict', onConflict);+ }+ });++ it('keeps SDK error-log parsing as a conflict fallback', async () => {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ const sdkClient = latestClient();++ sdkClient.logger.error('[ws]', 'code: 1000040350, exceed_conn_limit');++ await expect(connecting).resolves.toBe('conflict');+ expect(wsClient.getCurrentStatus()).toBe('conflict');+ expect(sdkClient.close).toHaveBeenCalledWith({ force: true });+ });+});diff --git a/packages/lizi-im/src/feishu/conflictDetector.ts b/packages/lizi-im/src/feishu/conflictDetector.tsindex 0f29b6f952..1b544e3460 100644--- a/packages/lizi-im/src/feishu/conflictDetector.ts+++ b/packages/lizi-im/src/feishu/conflictDetector.ts@@ -30,6 +30,7 @@ export class ConflictDetector {private readonly reconnectThreshold: number;private reconnectCount = 0;private resolved = false;+ private verdict: ConnectVerdict | null = null;private resolver: ((v: ConnectVerdict) => void) | null = null;private timer: NodeJS.Timeout | null = null;private readonly verdictPromise: Promise<ConnectVerdict>;@@ -56,37 +57,44 @@ export class ConflictDetector {}, this.readyTimeoutMs);}- markReady(): void {- if (this.resolved) return;- this.resolve({ kind: 'connected' });+ markReady(): boolean {+ return this.resolve({ kind: 'connected' });}- markReconnecting(): void {- if (this.resolved) return;+ markReconnecting(): boolean {+ if (this.resolved) return false;this.reconnectCount++;+ return true;}- markReconnected(): void {- if (this.resolved) return;- this.resolve({ kind: 'connected' });+ markReconnected(): boolean {+ return this.resolve({ kind: 'connected' });}- markError(err: Error): void {- if (this.resolved) return;- this.resolve({ kind: 'error', message: err.message ?? 'Unknown error' });+ markConflict(): boolean {+ return this.resolve({ kind: 'conflict' });+ }++ markError(err: Error): boolean {+ return this.resolve({ kind: 'error', message: err.message ?? 'Unknown error' });+ }++ getVerdict(): ConnectVerdict | null {+ return this.verdict;}waitForVerdict(): Promise<ConnectVerdict> {return this.verdictPromise;}- abandon(): void {- if (this.resolved) return;- this.resolve({ kind: 'error', message: 'Abandoned by caller.' });+ abandon(): boolean {+ return this.resolve({ kind: 'error', message: 'Abandoned by caller.' });}- private resolve(v: ConnectVerdict): void {+ private resolve(v: ConnectVerdict): boolean {+ if (this.resolved) return false;this.resolved = true;+ this.verdict = v;if (this.timer) {clearTimeout(this.timer);this.timer = null;@@ -95,5 +103,6 @@ export class ConflictDetector {this.resolver(v);this.resolver = null;}+ return true;}}diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.tsindex 10785804ff..b7ad89c4f7 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -3,9 +3,9 @@* ---------------------------------------------------------------------------* Lark.WSClient + Lark.EventDispatcher wrapper.*- * 关键设计:SDK 既不暴露 EventEmitter 也不接受连接生命周期 callback。- * 我们注入一个**自定义 Logger** 包装 SDK 内部日志,按消息内容关键字- * 触发 ConflictDetector:+ * 关键设计:连接生命周期优先使用 SDK 的 onReady / onError /+ * onReconnecting / onReconnected callback。自定义 Logger 仍保留同一套+ * 信号解析作为兼容兜底:** info '[ws] ws client ready' → detector.markReady()* info '[ws] reconnect success' → detector.markReconnected()@@ -52,6 +52,7 @@ let currentBotAppId: string | null = null;let currentStatus: FeishuConnectionStatus = 'idle';let acceptingInbound = false;let lifecycleGeneration = 0;+let conflictTransitionGeneration: number | null = null;let lifecycleAnnouncementEnabled = true;let pendingOfflineNotice = false;@@ -87,6 +88,106 @@ export function setLifecycleAnnouncement(enabled: boolean): void {getLog().info(`[feishu/wsClient] lifecycleAnnouncement set to ${enabled}`);}+const FEISHU_CONFLICT_ERROR = '该 App 已被另一台设备占用 (exceed_conn_limit)';++function isConflictSignal(message: string): boolean {+ const normalized = message.toLowerCase();+ return normalized.includes('1000040350') || normalized.includes('exceed_conn_limit');+}++function isActiveConnection(generation: number, appId: string): boolean {+ return (+ acceptingInbound &&+ lifecycleGeneration === generation &&+ currentBotAppId === appId+ );+}++async function transitionToConflict(+ generation: number,+ appId: string,+): Promise<void> {+ if (+ conflictTransitionGeneration === generation ||+ !isActiveConnection(generation, appId)+ ) {+ return;+ }++ conflictTransitionGeneration = generation;+ setStatus('conflict', FEISHU_CONFLICT_ERROR);+ await stop({+ keepStatus: true,+ announceOffline: false,+ reason: 'connection-conflict',+ });+ feishuEvents.emit('conflict', { appId });+}++function handleReadySignal(+ activeDetector: ConflictDetector,+ generation: number,+ appId: string,+): void {+ if (!isActiveConnection(generation, appId)) return;+ activeDetector.markReady();+ if (+ activeDetector.getVerdict()?.kind === 'connected' &&+ currentStatus !== 'connected'+ ) {+ setStatus('connected');+ }+}++function handleReconnectingSignal(+ activeDetector: ConflictDetector,+ generation: number,+ appId: string,+): void {+ if (!isActiveConnection(generation, appId)) return;+ activeDetector.markReconnecting();+ if (+ activeDetector.getVerdict()?.kind !== 'conflict' &&+ currentStatus === 'connected'+ ) {+ setStatus('reconnecting');+ }+}++function handleReconnectedSignal(+ activeDetector: ConflictDetector,+ generation: number,+ appId: string,+): void {+ if (!isActiveConnection(generation, appId)) return;+ activeDetector.markReconnected();+ if (+ activeDetector.getVerdict()?.kind === 'connected' &&+ currentStatus !== 'connected'+ ) {+ setStatus('connected');+ }+}++function handleErrorSignal(+ error: Error,+ activeDetector: ConflictDetector,+ generation: number,+ appId: string,+): void {+ if (!isActiveConnection(generation, appId)) return;+ if (isConflictSignal(error.message)) {+ if (+ !activeDetector.markConflict() &&+ activeDetector.getVerdict()?.kind !== 'conflict'+ ) {+ void transitionToConflict(generation, appId);+ }+ return;+ }+ activeDetector.markError(error);+}+// ── SDK logger interceptor ────────────────────────────────────────────────────interface SdkLogger {@@ -97,7 +198,11 @@ interface SdkLogger {error: (...msg: unknown[]) => void | Promise<void>;}-function makeCapturingLogger(activeDetector: ConflictDetector): SdkLogger {+function makeCapturingLogger(+ activeDetector: ConflictDetector,+ generation: number,+ appId: string,+): SdkLogger {const log = getLog();return {trace: () => {},@@ -107,15 +212,13 @@ function makeCapturingLogger(activeDetector: ConflictDetector): SdkLogger {.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');log.debug('[feishu/sdk-info]', msg);+ if (!isActiveConnection(generation, appId)) return;if (msg.includes('ws client ready')) {- activeDetector.markReady();- if (currentStatus !== 'connected') setStatus('connected');+ handleReadySignal(activeDetector, generation, appId);} else if (msg.includes('reconnect success')) {- activeDetector.markReconnected();- if (currentStatus !== 'connected') setStatus('connected');+ handleReconnectedSignal(activeDetector, generation, appId);} else if (msg.includes('reconnect') && !msg.includes('success')) {- activeDetector.markReconnecting();- if (currentStatus === 'connected') setStatus('reconnecting');+ handleReconnectingSignal(activeDetector, generation, appId);} else if (msg.includes('unable to connect to the server')) {activeDetector.markError(new Error('unable to connect after retries'));setStatus('error', '连接失败:飞书服务无法访问,请检查网络');@@ -132,15 +235,20 @@ function makeCapturingLogger(activeDetector: ConflictDetector): SdkLogger {.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');log.error('[feishu/sdk-error]', msg);+ if (!isActiveConnection(generation, appId)) return;+ if (isConflictSignal(msg)) {+ handleErrorSignal(+ new Error(FEISHU_CONFLICT_ERROR),+ activeDetector,+ generation,+ appId,+ );+ return;+ }if (msg.includes('code: 514')) {activeDetector.markError(new Error('App ID / App Secret 不正确(auth_failed)'));setStatus('error', 'App ID 或 App Secret 不正确');}- if (msg.includes('1000040350')) {- activeDetector.markError(- new Error('该 App 已被另一台设备占用 (exceed_conn_limit)'),- );- }},};}@@ -175,7 +283,19 @@ export async function start(appSecret: creds.appSecret,loggerLevel: Lark.LoggerLevel.info,autoReconnect: true,- logger: makeCapturingLogger(startDetector),+ logger: makeCapturingLogger(startDetector, startedGeneration, creds.appId),+ onReady: () => {+ handleReadySignal(startDetector, startedGeneration, creds.appId);+ },+ onError: (error) => {+ handleErrorSignal(error, startDetector, startedGeneration, creds.appId);+ },+ onReconnecting: () => {+ handleReconnectingSignal(startDetector, startedGeneration, creds.appId);+ },+ onReconnected: () => {+ handleReconnectedSignal(startDetector, startedGeneration, creds.appId);+ },});outbound.bindClient(creds);@@ -223,9 +343,7 @@ export async function start(}return 'connected';case 'conflict':- setStatus('conflict', '该 App ID 似乎已被另一台设备使用');- await stop({ keepStatus: true });- feishuEvents.emit('conflict', { appId: creds.appId });+ await transitionToConflict(startedGeneration, creds.appId);return 'conflict';case 'error':setStatus('error', verdict.message);