Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): 修复首次私聊后 Owner 状态不刷新 (#308)
qsoyq2e7ebc58ec35
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.tsnew file mode 100644index 0000000000..74b7f427f0--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts@@ -0,0 +1,247 @@+// @vitest-environment jsdom+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, string>) =>+ vars?.message ? `${key}:${vars.message}` : key,+ }),+}));++vi.mock('@/lib/toast', () => ({+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock('@/lib/logger', () => ({+ createLogger: () => ({+ error: vi.fn(),+ warn: vi.fn(),+ info: vi.fn(),+ debug: vi.fn(),+ }),+}));++type StatusListener = (payload: {+ status: FeishuBotStatus;+ error?: string;+ botAppId: string | null;+ ownerOpenId: string | null;+}) => void;++type RegistrationListener = (payload: {+ status: 'success';+ appId: string;+ ownerOpenId: string;+}) => void;++type FeishuState = {+ status: FeishuBotStatus;+ appId: string | null;+ appSecret: string | null;+ hasSecret: boolean;+ ownerOpenId: string | null;+ lifecycleAnnouncement: boolean;+};++function installFeishuApi() {+ const statusListeners = new Set<StatusListener>();+ const registrationListeners = new Set<RegistrationListener>();+ const api = {+ getState: vi.fn(async (): Promise<FeishuState> => ({+ status: 'connected' as const,+ appId: 'cli_test',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: null,+ lifecycleAnnouncement: true,+ })),+ save: vi.fn(),+ reconnect: vi.fn(),+ clear: vi.fn(),+ setLifecycleAnnouncement: vi.fn(),+ registrationBegin: vi.fn(),+ registrationCancel: vi.fn(),+ onStatusChange: vi.fn((listener: StatusListener) => {+ statusListeners.add(listener);+ return () => statusListeners.delete(listener);+ }),+ onConflict: vi.fn(() => () => {}),+ onRegistrationStatus: vi.fn((listener: RegistrationListener) => {+ registrationListeners.add(listener);+ return () => registrationListeners.delete(listener);+ }),+ };+ (window as unknown as { electronAPI: { feishuBot: typeof api } }).electronAPI = {+ feishuBot: api,+ };+ return { api, statusListeners, registrationListeners };+}++let useFeishuBot: typeof import('../useFeishuBot').useFeishuBot;++describe('useFeishuBot', () => {+ beforeEach(async () => {+ vi.resetModules();+ vi.clearAllMocks();+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;+ ({ useFeishuBot } = await import('../useFeishuBot'));+ });++ it('updates the live owner and module cache when main claims the first sender', async () => {+ const { api, statusListeners } = installFeishuApi();+ api.getState.mockResolvedValueOnce({+ status: 'connected',+ appId: 'cli_hydrated_owner_test',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: null,+ lifecycleAnnouncement: true,+ });+ const first = renderHook(() => useFeishuBot());++ await waitFor(() => expect(first.result.current.appId).toBe('cli_hydrated_owner_test'));+ expect(first.result.current.ownerOpenId).toBeNull();++ act(() => {+ for (const listener of statusListeners) {+ listener({+ status: 'connected',+ botAppId: 'cli_hydrated_owner_test',+ ownerOpenId: 'ou_new_owner',+ });+ }+ });++ expect(first.result.current.ownerOpenId).toBe('ou_new_owner');+ first.unmount();++ api.getState.mockImplementationOnce(() => new Promise(() => {}));+ const second = renderHook(() => useFeishuBot());+ expect(second.result.current.ownerOpenId).toBe('ou_new_owner');+ });++ it('does not let an older getState response overwrite a newer owner push', async () => {+ let resolveState!: (state: {+ status: 'connected';+ appId: string;+ appSecret: null;+ hasSecret: true;+ ownerOpenId: null;+ lifecycleAnnouncement: true;+ }) => void;+ const staleState = new Promise<Parameters<typeof resolveState>[0]>((resolve) => {+ resolveState = resolve;+ });+ const { api, statusListeners } = installFeishuApi();+ api.getState.mockReturnValueOnce(staleState);++ const hook = renderHook(() => useFeishuBot());+ await waitFor(() => expect(statusListeners.size).toBe(1));++ act(() => {+ for (const listener of statusListeners) {+ listener({+ status: 'connected',+ botAppId: 'cli_test',+ ownerOpenId: 'ou_race_owner',+ });+ }+ });++ resolveState({+ status: 'connected',+ appId: 'cli_test',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: null,+ lifecycleAnnouncement: true,+ });++ expect(api.getState).toHaveBeenCalledOnce();+ await waitFor(() => expect(hook.result.current.ownerOpenId).toBe('ou_race_owner'));+ });++ it('subscribes before the initial state read so a synchronous push is not lost', async () => {+ const { api, statusListeners } = installFeishuApi();+ api.getState.mockImplementationOnce(async () => {+ for (const listener of statusListeners) {+ listener({+ status: 'connected',+ botAppId: 'cli_test',+ ownerOpenId: 'ou_mount_race_owner',+ });+ }+ return {+ status: 'connected',+ appId: 'cli_test',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: null,+ lifecycleAnnouncement: true,+ };+ });++ const hook = renderHook(() => useFeishuBot());++ await waitFor(() =>+ expect(hook.result.current.ownerOpenId).toBe('ou_mount_race_owner'),+ );+ });++ it('does not let an older reload overwrite a newer registration reload', async () => {+ type State = Awaited<ReturnType<ReturnType<typeof installFeishuApi>['api']['getState']>>;+ let resolveOlder!: (state: State) => void;+ let resolveNewer!: (state: State) => void;+ const olderState = new Promise<State>((resolve) => {+ resolveOlder = resolve;+ });+ const newerState = new Promise<State>((resolve) => {+ resolveNewer = resolve;+ });+ const { api, registrationListeners } = installFeishuApi();+ api.getState.mockReturnValueOnce(olderState).mockReturnValueOnce(newerState);++ const hook = renderHook(() => useFeishuBot());+ await waitFor(() => expect(api.getState).toHaveBeenCalledOnce());++ act(() => {+ for (const listener of registrationListeners) {+ listener({+ status: 'success',+ appId: 'cli_registered',+ ownerOpenId: 'ou_registered_owner',+ });+ }+ });+ await waitFor(() => expect(api.getState).toHaveBeenCalledTimes(2));++ resolveNewer({+ status: 'connected',+ appId: 'cli_registered',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: 'ou_registered_owner',+ lifecycleAnnouncement: true,+ });+ await waitFor(() => expect(hook.result.current.ownerOpenId).toBe('ou_registered_owner'));++ resolveOlder({+ status: 'connected',+ appId: 'cli_stale',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: null,+ lifecycleAnnouncement: true,+ });+ await act(async () => {+ await olderState;+ });++ expect(hook.result.current.appId).toBe('cli_registered');+ expect(hook.result.current.ownerOpenId).toBe('ou_registered_owner');+ });+});diff --git a/apps/desktop/src/renderer/hooks/useFeishuBot.ts b/apps/desktop/src/renderer/hooks/useFeishuBot.tsindex 2c6693e800..5265406db2 100644--- a/apps/desktop/src/renderer/hooks/useFeishuBot.ts+++ b/apps/desktop/src/renderer/hooks/useFeishuBot.ts@@ -96,20 +96,37 @@ export function useFeishuBot(): UseFeishuBotReturn {const [isReconnecting, setIsReconnecting] = useState(false);const [saveSuccess, setSaveSuccess] = useState(false);const saveSuccessTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const reloadRequestVersionRef = useRef(0);+ const statusPushVersionRef = useRef(0);+ const latestStatusPushRef = useRef<{+ status: FeishuBotStatus;+ errorMessage: string | null;+ ownerOpenId: string | null;+ } | null>(null);// 重新从 main 拉一次凭证 + 状态。挂载时和扫码注册成功后都要走一次,// 否则 device-code 流程在 main 写完凭证后, renderer 这边 appId/secret// 仍然停留在初始空字符串, 导致 ConnectedCard 显示空 + 跳转链接拼成// /app//event 落到飞书 app 列表页。const reloadState = useCallback(async (): Promise<void> => {+ const reloadRequestVersion = ++reloadRequestVersionRef.current;+ const statusPushVersion = statusPushVersionRef.current;try {const state = await window.electronAPI.feishuBot.getState();+ if (reloadRequestVersion !== reloadRequestVersionRef.current) return;const nextAppId = state.appId ?? '';const nextAppSecret = state.appSecret ?? '';- setStatus(state.status);+ const newerStatusPush =+ statusPushVersionRef.current !== statusPushVersion ? latestStatusPushRef.current : null;+ const nextStatus = newerStatusPush?.status ?? state.status;+ const nextErrorMessage = newerStatusPush+ ? newerStatusPush.errorMessage+ : (state.error ?? null);+ const nextOwnerOpenId = newerStatusPush ? newerStatusPush.ownerOpenId : state.ownerOpenId;+ setStatus(nextStatus);setHasSavedCreds(state.hasSecret);- setOwnerOpenId(state.ownerOpenId);- setErrorMessage(state.error ?? null);+ setOwnerOpenId(nextOwnerOpenId);+ setErrorMessage(nextErrorMessage);setLifecycleAnnouncementState(state.lifecycleAnnouncement);if (state.appId) {setAppIdState(state.appId);@@ -120,10 +137,10 @@ export function useFeishuBot(): UseFeishuBotReturn {cachedState = {appId: nextAppId || cachedState?.appId || '',appSecret: nextAppSecret || cachedState?.appSecret || '',- status: state.status,- errorMessage: state.error ?? null,+ status: nextStatus,+ errorMessage: nextErrorMessage,hasSavedCreds: state.hasSecret,- ownerOpenId: state.ownerOpenId,+ ownerOpenId: nextOwnerOpenId,lifecycleAnnouncement: state.lifecycleAnnouncement,};} catch (err) {@@ -132,27 +149,37 @@ export function useFeishuBot(): UseFeishuBotReturn {}}, []);- // ── initial load ─────────────────────────────────────────────────────────- useEffect(() => {- void reloadState();- }, [reloadState]);-// ── status push subscription ─────────────────────────────────────────────useEffect(() => {const unsub = window.electronAPI.feishuBot.onStatusChange((update) => {+ const nextErrorMessage = update.error ?? null;+ statusPushVersionRef.current += 1;+ latestStatusPushRef.current = {+ status: update.status,+ errorMessage: nextErrorMessage,+ ownerOpenId: update.ownerOpenId,+ };setStatus(update.status);- setErrorMessage(update.error ?? null);+ setErrorMessage(nextErrorMessage);+ setOwnerOpenId(update.ownerOpenId);if (cachedState) {cachedState = {...cachedState,status: update.status,- errorMessage: update.error ?? null,+ errorMessage: nextErrorMessage,+ ownerOpenId: update.ownerOpenId,};}});return unsub;}, []);+ // Subscribe before starting the initial read so a push cannot fall between+ // getState's snapshot and listener registration.+ useEffect(() => {+ void reloadState();+ }, [reloadState]);+// ── registration success: hydrate from payload + refetch ────────────────// device-code 流程不走 save() 路径, payload 里直接有 appId/ownerOpenId,// 立刻 hydrate 防止 ConnectedCard 显示空 + 跳转链接拼成 /app//event。diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 06c2cef2c3..9eeb8b95b9 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1515,6 +1515,7 @@ interface ElectronAPI {status: FeishuBotStatus;error?: string;botAppId: string | null;+ ownerOpenId: string | null;}) => void,) => () => void;onConflict: (callback: (payload: { appId: string }) => void) => () => void;diff --git a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.tsindex 2cf98426f2..17adf7907e 100644--- a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts@@ -12,7 +12,9 @@ const mocks = vi.hoisted(() => ({() => null as { appId: string; appSecret: string } | null,),writeCredentials: vi.fn(() => true),- writeOwnerOpenId: vi.fn(),+ writeOwnerOpenId: vi.fn(() => true),+ clearAll: vi.fn(),+ clearOwner: vi.fn(),loadOwner: vi.fn(),requestRegistration: vi.fn(),pollRegistration: vi.fn(),@@ -33,13 +35,13 @@ vi.mock('../storage.js', () => ({writeLifecycleAnnouncement: vi.fn(),writeCredentials: mocks.writeCredentials,writeOwnerOpenId: mocks.writeOwnerOpenId,- clearAll: vi.fn(),+ clearAll: mocks.clearAll,}));vi.mock('../ownerGuard.js', () => ({loadFromDisk: mocks.loadOwner,firstAllowed: vi.fn(() => null),- clear: vi.fn(),+ clear: mocks.clearOwner,}));vi.mock('../appRegistration.js', () => ({@@ -50,6 +52,7 @@ vi.mock('../appRegistration.js', () => ({import { FeishuIM } from '../index.js';import {cancelAppRegistration,+ clearAndDisconnect,reconnectSavedCredentials,saveAndConnect,} from '../ipc.js';@@ -125,6 +128,7 @@ beforeEach(() => {mocks.stop.mockResolvedValue(undefined);mocks.start.mockResolvedValue('connected');mocks.writeCredentials.mockReturnValue(true);+ mocks.writeOwnerOpenId.mockReturnValue(true);});afterEach(() => {@@ -199,6 +203,17 @@ describe('Feishu IPC account scope', () => {describe('Feishu credential connection semantics', () => {const credentials = { appId: 'cli_test', appSecret: 'secret' };+ it('delegates owner clearing to stop before the idle status is broadcast', async () => {+ await clearAndDisconnect();++ expect(mocks.stop).toHaveBeenCalledWith({+ reason: 'credentials-cleared',+ clearOwnerBeforeIdle: true,+ });+ expect(mocks.clearOwner).not.toHaveBeenCalled();+ expect(mocks.clearAll).toHaveBeenCalledOnce();+ });+it('keeps an already-connected transport untouched when credentials are unchanged', async () => {mocks.readCredentials.mockReturnValue(credentials);mocks.getCurrentStatus.mockReturnValue('connected');@@ -212,6 +227,38 @@ describe('Feishu credential connection semantics', () => {expect(mocks.start).not.toHaveBeenCalled();});+ it('persists a registration owner before returning for unchanged credentials', async () => {+ mocks.readCredentials.mockReturnValue(credentials);+ mocks.getCurrentStatus.mockReturnValue('connected');++ await expect(+ saveAndConnect(credentials.appId, credentials.appSecret, {+ replacementOwnerOpenId: 'ou_registered_owner',+ }),+ ).resolves.toEqual({ verdict: 'connected' });++ expect(mocks.writeOwnerOpenId).toHaveBeenCalledWith('ou_registered_owner');+ expect(mocks.loadOwner).toHaveBeenCalledOnce();+ expect(mocks.stop).not.toHaveBeenCalled();+ expect(mocks.start).not.toHaveBeenCalled();+ });++ it('fails closed when an unchanged registration owner cannot be persisted', async () => {+ mocks.readCredentials.mockReturnValue(credentials);+ mocks.getCurrentStatus.mockReturnValue('connected');+ mocks.writeOwnerOpenId.mockReturnValue(false);++ await expect(+ saveAndConnect(credentials.appId, credentials.appSecret, {+ replacementOwnerOpenId: 'ou_registered_owner',+ }),+ ).rejects.toThrow('[OWNER_PERSIST_FAILED]');++ expect(mocks.loadOwner).not.toHaveBeenCalled();+ expect(mocks.stop).not.toHaveBeenCalled();+ expect(mocks.start).not.toHaveBeenCalled();+ });+it.each(['testing', 'reconnecting'] as const)('keeps an in-flight %s transport untouched when credentials are unchanged',async (status) => {@@ -262,6 +309,72 @@ describe('Feishu credential connection semantics', () => {});});+ it('clears the per-app owner before connecting a different app ID', async () => {+ mocks.readCredentials.mockReturnValue(credentials);++ await expect(saveAndConnect('cli_other', 'other-secret')).resolves.toEqual({+ verdict: 'connected',+ });++ expect(mocks.stop).toHaveBeenCalledWith({+ reason: 'credentials-replaced',+ clearOwnerBeforeIdle: true,+ });+ expect(mocks.start).toHaveBeenCalledWith(+ { appId: 'cli_other', appSecret: 'other-secret' },+ { reason: 'credentials-replaced' },+ );+ });++ it('installs a replacement app registration owner after clearing the previous owner', async () => {+ mocks.readCredentials.mockReturnValue(credentials);++ await expect(+ saveAndConnect('cli_registered', 'registered-secret', {+ replacementOwnerOpenId: 'ou_registered_owner',+ }),+ ).resolves.toEqual({ verdict: 'connected' });++ expect(mocks.stop).toHaveBeenCalledWith({+ reason: 'credentials-replaced',+ clearOwnerBeforeIdle: true,+ });+ expect(mocks.writeOwnerOpenId).toHaveBeenCalledWith('ou_registered_owner');+ expect(mocks.loadOwner).toHaveBeenCalledOnce();+ expect(mocks.stop.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.writeOwnerOpenId.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,+ );+ });++ it('does not connect when a replacement registration owner cannot be persisted', async () => {+ mocks.readCredentials.mockReturnValue(credentials);+ mocks.writeOwnerOpenId.mockReturnValue(false);++ await expect(+ saveAndConnect('cli_registered', 'registered-secret', {+ replacementOwnerOpenId: 'ou_registered_owner',+ }),+ ).rejects.toThrow('[OWNER_PERSIST_FAILED]');++ expect(mocks.loadOwner).not.toHaveBeenCalled();+ expect(mocks.start).not.toHaveBeenCalled();+ });++ it('preserves the owner when only the secret changes for the same app ID', async () => {+ mocks.readCredentials.mockReturnValue(credentials);++ await expect(saveAndConnect(credentials.appId, 'rotated-secret')).resolves.toEqual({+ verdict: 'connected',+ });++ expect(mocks.stop).toHaveBeenCalledWith({+ reason: 'credentials-replaced',+ clearOwnerBeforeIdle: false,+ });+ expect(mocks.writeOwnerOpenId).not.toHaveBeenCalled();+ expect(mocks.loadOwner).not.toHaveBeenCalled();+ });+it('does not tear down the current transport when saving new credentials fails', async () => {mocks.readCredentials.mockReturnValue(credentials);mocks.writeCredentials.mockReturnValue(false);diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.tsindex 7038a2cf47..5d2b05ae71 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts@@ -10,6 +10,7 @@ import {} from 'vitest';import { feishuEvents } from '../events.js';+import { messages as transportMessages } from '../messages.js';interface CapturingLogger {info: (...args: unknown[]) => void;@@ -22,6 +23,8 @@ interface MockSdkOptions {onError?: (error: Error) => void;}+type EventHandler = (data: unknown) => Promise<unknown> | unknown;+const mocks = {options: [] as MockSdkOptions[],start: vi.fn(async () => undefined),@@ -30,9 +33,12 @@ const mocks = {unbindClient: vi.fn(),getBoundClient: vi.fn(() => null),sendText: vi.fn(),- firstAllowed: vi.fn(() => null),+ firstAllowed: vi.fn<() => string | null>(() => null),+ readOwnerOpenId: vi.fn<() => string | null>(() => null),+ clearOwner: vi.fn(),checkOwner: vi.fn(() => true),tryClaimOwner: vi.fn(() => false),+ eventHandlers: {} as Record<string, EventHandler>,log: {trace: vi.fn(),debug: vi.fn(),@@ -53,7 +59,8 @@ vi.doMock('@larksuiteoapi/node-sdk', () => ({}},EventDispatcher: class {- register(): this {+ register(handlers: Record<string, EventHandler>): this {+ mocks.eventHandlers = handlers;return this;}},@@ -69,10 +76,15 @@ vi.doMock('../outbound.js', () => ({vi.doMock('../ownerGuard.js', () => ({firstAllowed: mocks.firstAllowed,+ clear: mocks.clearOwner,check: mocks.checkOwner,tryClaimOwner: mocks.tryClaimOwner,}));+vi.doMock('../storage.js', () => ({+ readOwnerOpenId: mocks.readOwnerOpenId,+}));+vi.doMock('../moduleScope.js', () => ({getLog: () => mocks.log,}));@@ -98,7 +110,10 @@ function latestClient() {beforeEach(async () => {await wsClient.stop({ announceOffline: false, reason: 'test-reset' });mocks.options.length = 0;+ mocks.eventHandlers = {};vi.clearAllMocks();+ mocks.firstAllowed.mockReturnValue(null);+ mocks.readOwnerOpenId.mockReturnValue(null);});afterEach(async () => {@@ -113,6 +128,7 @@ afterAll(() => {vi.doUnmock('@larksuiteoapi/node-sdk');vi.doUnmock('../outbound.js');vi.doUnmock('../ownerGuard.js');+ vi.doUnmock('../storage.js');vi.doUnmock('../moduleScope.js');});@@ -177,3 +193,140 @@ describe('Feishu WebSocket conflict handling', () => {expect(sdkClient.close).toHaveBeenCalledWith({ force: true });});});++describe('Feishu owner binding updates', () => {+ it('falls back to the persisted owner before the in-memory guard is loaded', async () => {+ mocks.firstAllowed.mockReturnValue(null);+ mocks.readOwnerOpenId.mockReturnValue('ou_persisted_owner');+ const onStatus = vi.fn();+ feishuEvents.on('status', onStatus);++ try {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ latestClient().options.onReady?.();+ await expect(connecting).resolves.toBe('connected');++ expect(onStatus).toHaveBeenLastCalledWith({+ status: 'connected',+ error: undefined,+ botAppId: credentials.appId,+ ownerOpenId: 'ou_persisted_owner',+ });+ } finally {+ feishuEvents.off('status', onStatus);+ }+ });++ it('emits the claimed owner after the first valid p2p message', async () => {+ mocks.tryClaimOwner.mockReturnValueOnce(true);+ mocks.firstAllowed.mockReturnValueOnce(null).mockReturnValue('ou_new_owner');+ mocks.sendText.mockResolvedValueOnce({ messageId: 'welcome-message' });+ const onStatus = vi.fn();++ try {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ latestClient().options.onReady?.();+ await expect(connecting).resolves.toBe('connected');+ feishuEvents.on('status', onStatus);++ const handleMessage = mocks.eventHandlers['im.message.receive_v1'];+ expect(handleMessage).toBeDefined();+ await handleMessage?.({+ sender: { sender_id: { open_id: 'ou_new_owner' } },+ message: {+ message_id: 'om_first',+ chat_id: 'oc_owner_chat',+ chat_type: 'p2p',+ message_type: 'text',+ content: JSON.stringify({ text: 'hello' }),+ },+ });++ expect(onStatus).toHaveBeenCalledOnce();+ expect(onStatus).toHaveBeenCalledWith({+ status: 'connected',+ error: undefined,+ botAppId: credentials.appId,+ ownerOpenId: 'ou_new_owner',+ });+ } finally {+ feishuEvents.off('status', onStatus);+ }+ });++ it('clears the owner before broadcasting the credentials-cleared idle state', async () => {+ mocks.firstAllowed.mockReturnValue('ou_previous_owner');+ mocks.clearOwner.mockImplementationOnce(() => {+ mocks.firstAllowed.mockReturnValue(null);+ });+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ latestClient().options.onReady?.();+ await expect(connecting).resolves.toBe('connected');+ const onStatus = vi.fn();+ feishuEvents.on('status', onStatus);++ try {+ await wsClient.stop({+ announceOffline: false,+ clearOwnerBeforeIdle: true,+ reason: 'credentials-cleared',+ });++ expect(mocks.clearOwner).toHaveBeenCalledOnce();+ expect(onStatus).toHaveBeenLastCalledWith({+ status: 'idle',+ error: undefined,+ botAppId: null,+ ownerOpenId: null,+ });+ } finally {+ feishuEvents.off('status', onStatus);+ }+ });++ it('does not carry an old binding offline notice into a replacement app', async () => {+ mocks.firstAllowed.mockReturnValue('ou_previous_owner');+ mocks.clearOwner.mockImplementationOnce(() => {+ mocks.firstAllowed.mockReturnValue(null);+ });+ mocks.sendText.mockResolvedValue({ messageId: 'om_lifecycle' });++ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ latestClient().options.onReady?.();+ await expect(connecting).resolves.toBe('connected');+ await wsClient.stop({+ clearOwnerBeforeIdle: true,+ reason: 'credentials-replaced',+ });++ mocks.tryClaimOwner.mockImplementationOnce(() => {+ mocks.firstAllowed.mockReturnValue('ou_replacement_owner');+ return true;+ });+ const replacementCredentials = {+ appId: 'cli_replacement',+ appSecret: 'replacement-secret',+ };+ const replacementConnecting = wsClient.start(replacementCredentials, {+ announceLifecycle: false,+ });+ latestClient().options.onReady?.();+ await expect(replacementConnecting).resolves.toBe('connected');++ await mocks.eventHandlers['im.message.receive_v1']?.({+ sender: { sender_id: { open_id: 'ou_replacement_owner' } },+ message: {+ message_id: 'om_first_replacement',+ chat_id: 'oc_replacement',+ chat_type: 'p2p',+ message_type: 'text',+ content: JSON.stringify({ text: 'hello' }),+ },+ });++ expect(mocks.sendText).not.toHaveBeenCalledWith(+ 'ou_replacement_owner',+ transportMessages.lifecycle.offlineNotice,+ );+ });+});diff --git a/packages/lizi-im/src/feishu/internal-types.ts b/packages/lizi-im/src/feishu/internal-types.tsindex 8cbbae10dd..908e473993 100644--- a/packages/lizi-im/src/feishu/internal-types.ts+++ b/packages/lizi-im/src/feishu/internal-types.ts@@ -18,6 +18,7 @@ export interface FeishuStatusUpdate {status: FeishuConnectionStatus;error?: string;botAppId: string | null;+ ownerOpenId: string | null;}export type ConnectVerdict =diff --git a/packages/lizi-im/src/feishu/ipc.ts b/packages/lizi-im/src/feishu/ipc.tsindex 0deb9c601b..038307acad 100644--- a/packages/lizi-im/src/feishu/ipc.ts+++ b/packages/lizi-im/src/feishu/ipc.ts@@ -168,12 +168,21 @@ export function getPublicState(): FeishuPublicState {};}+interface SaveAndConnectOptions {+ /** Owner returned by app registration for the replacement app. */+ replacementOwnerOpenId?: string | null;+}+export async function saveAndConnect(appId: string,appSecret: string,+ options: SaveAndConnectOptions = {},): Promise<{ verdict: 'connected' | 'conflict' | 'error' | 'pending' }> {const saved = storage.readCredentials();const credentialsUnchanged = saved?.appId === appId && saved.appSecret === appSecret;+ if (credentialsUnchanged && options.replacementOwnerOpenId) {+ persistReplacementOwner(options.replacementOwnerOpenId);+ }if (credentialsUnchanged) {const status = wsClient.getCurrentStatus();if (status === 'connected') {@@ -191,11 +200,25 @@ export async function saveAndConnect(const ok = storage.writeCredentials({ appId, appSecret });if (!ok) return { verdict: 'error' };- await wsClient.stop({ reason: 'credentials-replaced' });+ await wsClient.stop({+ reason: 'credentials-replaced',+ clearOwnerBeforeIdle: saved?.appId !== appId,+ });+ if (options.replacementOwnerOpenId) {+ persistReplacementOwner(options.replacementOwnerOpenId);+ }const verdict = await wsClient.start({ appId, appSecret }, { reason: 'credentials-replaced' });return { verdict };}+function persistReplacementOwner(ownerOpenId: string): void {+ const ownerWritten = storage.writeOwnerOpenId(ownerOpenId);+ if (!ownerWritten) {+ throw new Error('[OWNER_PERSIST_FAILED] Failed to persist Feishu owner');+ }+ ownerGuard.loadFromDisk();+}+/** Restart the saved WebSocket connection without changing credentials or owner binding. */export async function reconnectSavedCredentials(): Promise<{verdict: 'connected' | 'conflict' | 'error';@@ -284,11 +307,9 @@ async function pollRegistrationInBackground(let verdict: 'connected' | 'conflict' | 'error' | 'pending';try {({ verdict } = await runInAccountScope(accountScope, async () => {- if (success.ownerOpenId) {- storage.writeOwnerOpenId(success.ownerOpenId);- ownerGuard.loadFromDisk();- }- return saveAndConnect(success.clientId, success.clientSecret);+ return saveAndConnect(success.clientId, success.clientSecret, {+ replacementOwnerOpenId: success.ownerOpenId,+ });}));} catch (err) {if (!isAccountScopeCurrent(accountScope)) return;@@ -337,7 +358,9 @@ function delay(ms: number): Promise<void> {export async function clearAndDisconnect(): Promise<void> {cancelAppRegistration();- await wsClient.stop({ reason: 'credentials-cleared' });- ownerGuard.clear();+ await wsClient.stop({+ reason: 'credentials-cleared',+ clearOwnerBeforeIdle: true,+ });storage.clearAll();}diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.tsindex b7ad89c4f7..71044fb2af 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -34,6 +34,7 @@ import { ConflictDetector } from './conflictDetector.js';import { feishuEvents } from './events.js';import * as outbound from './outbound.js';import * as ownerGuard from './ownerGuard.js';+import * as storage from './storage.js';import { parseIncoming } from './incomingContent.js';import { downloadAttachments } from './attachmentDownloader.js';import { parseCardAction } from './cardActionParser.js';@@ -60,9 +61,18 @@ let pendingOfflineNotice = false;const DEFAULT_OFFLINE_ANNOUNCE_TIMEOUT_MS = 1500;export const QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS = 4500;+function emitRendererStatus(error?: string): void {+ feishuEvents.emit('status', {+ status: currentStatus,+ error,+ botAppId: currentBotAppId,+ ownerOpenId: ownerGuard.firstAllowed() ?? storage.readOwnerOpenId(),+ });+}+function setStatus(status: FeishuConnectionStatus, error?: string): void {currentStatus = status;- feishuEvents.emit('status', { status, error, botAppId: currentBotAppId });+ emitRendererStatus(error);// Also broadcast public IMStatus to host orchestrator subscribersfeishuEvents.emit('imStatus', toImStatus(status, error));}@@ -362,6 +372,8 @@ interface StopOptions {offlineTimeoutMs?: number;/** False for transport recovery; true/default for a logical shutdown. */announceOffline?: boolean;+ /** Clear the owner after any offline notice, before broadcasting idle. */+ clearOwnerBeforeIdle?: boolean;reason?: string;}@@ -422,6 +434,10 @@ export async function stop(opts: StopOptions = {}): Promise<void> {detector = null;}outbound.unbindClient();+ if (opts.clearOwnerBeforeIdle) {+ pendingOfflineNotice = false;+ ownerGuard.clear();+ }if (!opts.keepStatus) {currentBotAppId = null;setStatus('idle');@@ -515,6 +531,7 @@ async function handleIncomingMessage(// processing this very message (so the user's first ask isn't lost).if (ownerGuard.tryClaimOwner(senderOpenId)) {log.info(`[feishu/wsClient] TOFU: claimed owner ...${senderOpenId.slice(-8)}`);+ emitRendererStatus();try {await outbound.sendText(senderOpenId, transportMessages.ownerBinding.welcome);} catch (err) {