Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): start Feishu IM after owner DB ready (#299) (#400)

qsoyq639575c73c3a
diff --git a/apps/desktop/src/main/__tests__/accountIntegrationStartup.test.ts b/apps/desktop/src/main/__tests__/accountIntegrationStartup.test.ts
new file mode 100644
index 0000000000..4d8b0be13d
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/accountIntegrationStartup.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ startAccountIntegrationsAfterOwnerDbReady,
+ type AccountIntegrationStartupDeps,
+} from '../accountIntegrationStartup';
+
+function createDeps(
+ overrides: Partial<AccountIntegrationStartupDeps> = {},
+): AccountIntegrationStartupDeps {
+ return {
+ isOwnerCurrent: vi.fn(() => true),
+ startHookControlAccount: vi.fn(),
+ startImConnection: vi.fn(),
+ log: { warn: vi.fn() },
+ ...overrides,
+ };
+}
+
+describe('startAccountIntegrationsAfterOwnerDbReady', () => {
+ it('starts Feishu IM from the authoritative owner DB-ready boundary', () => {
+ const deps = createDeps();
+
+ expect(startAccountIntegrationsAfterOwnerDbReady('owner-a', deps)).toBe(true);
+
+ expect(deps.startHookControlAccount).toHaveBeenCalledOnce();
+ expect(deps.startImConnection).toHaveBeenCalledOnce();
+ expect(deps.log.warn).not.toHaveBeenCalled();
+ });
+
+ it('still starts Feishu IM when Hook activation throws', () => {
+ const deps = createDeps({
+ startHookControlAccount: vi.fn(() => {
+ throw new Error('invalid hook endpoint');
+ }),
+ });
+
+ startAccountIntegrationsAfterOwnerDbReady('owner-a', deps);
+
+ expect(deps.startImConnection).toHaveBeenCalledOnce();
+ expect(deps.log.warn).toHaveBeenCalledWith(
+ 'hook-control activation after owner DB ready failed (non-fatal)',
+ { error: 'invalid hook endpoint' },
+ );
+ });
+
+ it('contains Feishu IM activation failures so DB readiness can complete', () => {
+ const deps = createDeps({
+ startImConnection: vi.fn(() => {
+ throw new Error('invalid bot credentials');
+ }),
+ });
+
+ expect(() => startAccountIntegrationsAfterOwnerDbReady('owner-a', deps)).not.toThrow();
+ expect(deps.log.warn).toHaveBeenCalledWith(
+ 'feishu-im activation after owner DB ready failed (non-fatal)',
+ { error: 'invalid bot credentials' },
+ );
+ });
+
+ it('does not restart integrations for a stale owner and permits the next owner', () => {
+ let activeOwner = 'owner-a';
+ const deps = createDeps({
+ isOwnerCurrent: vi.fn((ownerId) => ownerId === activeOwner),
+ });
+
+ // Model logout/account replacement completing while the old onReady
+ // callback is awaiting another account startup hook.
+ activeOwner = 'owner-b';
+
+ expect(startAccountIntegrationsAfterOwnerDbReady('owner-a', deps)).toBe(false);
+ expect(deps.startHookControlAccount).not.toHaveBeenCalled();
+ expect(deps.startImConnection).not.toHaveBeenCalled();
+
+ expect(startAccountIntegrationsAfterOwnerDbReady('owner-b', deps)).toBe(true);
+ expect(deps.startHookControlAccount).toHaveBeenCalledOnce();
+ expect(deps.startImConnection).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/accountIntegrationStartup.ts b/apps/desktop/src/main/accountIntegrationStartup.ts
new file mode 100644
index 0000000000..f22a8dac05
--- /dev/null
+++ b/apps/desktop/src/main/accountIntegrationStartup.ts
@@ -0,0 +1,42 @@
+import type { Logger } from './logger';
+
+export interface AccountIntegrationStartupDeps {
+ isOwnerCurrent(ownerId: string): boolean;
+ startHookControlAccount(): void;
+ startImConnection(): void;
+ log: Pick<Logger, 'warn'>;
+}
+
+/**
+ * Start every account-scoped ingress after the current owner's DbClient is
+ * ready. Each integration is optional and isolated: one damaged configuration
+ * must not prevent the other transport, or the rest of DB-ready startup, from
+ * becoming available.
+ */
+export function startAccountIntegrationsAfterOwnerDbReady(
+ ownerId: string,
+ deps: AccountIntegrationStartupDeps,
+): boolean {
+ // onReady performs other asynchronous account initialization before it
+ // reaches this point. Logout or account replacement can finish while one of
+ // those awaits is pending, so reject the stale callback immediately before
+ // it can bring an old owner's transports back online.
+ if (!deps.isOwnerCurrent(ownerId)) return false;
+
+ const integrations = [
+ ['hook-control', deps.startHookControlAccount],
+ ['feishu-im', deps.startImConnection],
+ ] as const;
+
+ for (const [name, start] of integrations) {
+ try {
+ start();
+ } catch (err) {
+ deps.log.warn(`${name} activation after owner DB ready failed (non-fatal)`, {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ return true;
+}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 4e92e9550c..adaf022a12 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -302,6 +302,7 @@ import {
resetHookControlOwnerBoundary,
disposeHookControl,
} from './hook-control';
+import { startAccountIntegrationsAfterOwnerDbReady } from './accountIntegrationStartup';
import { registerSkillhubIpc } from './skillhub/registerIpc';
import { SkillhubMarketService } from './skillhub/marketService';
import { skillhubAutoSyncService } from './skillhub/autoSyncService';
@@ -835,8 +836,9 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// the auth-change activation pass after the new boundary is committed.
await waitForGhostMutations();
suspendAllGhosts();
- // Personal IM channels have the same DB boundary. Relogin restarts them via
- // app:ready-for-bot after the new DbClient is ready.
+ // Personal IM channels have the same DB boundary. Relogin restarts them from
+ // the next owner DB-ready callback; app:ready-for-bot remains a compatibility
+ // retry after the new DbClient is ready.
try {
await stopImConnection(reason);
} catch (err) {
@@ -5390,22 +5392,23 @@ app.on('ready', async () => {
error: err instanceof Error ? err.message : String(err),
});
}
- // Hook ingress has the same hard dependency on the current owner's DB as
- // the personal IM channel. Activate it from this authoritative Main-side
- // readiness point instead of relying only on the renderer's later
- // fire-and-forget app:ready-for-bot signal. That signal can be lost during
- // cold-start auto-login or an owner remount, leaving an enabled Hook
- // permanently disconnected until the user toggles it.
- try {
- startHookControlAccount();
- } catch (err) {
- // Hook is an optional account integration. A damaged config or endpoint
- // must not roll back an otherwise healthy owner DB; the renderer's
- // compatibility signal below provides a later retry.
- dbClientLog.warn('hook-control activation after owner DB ready failed (non-fatal)', {
- error: err instanceof Error ? err.message : String(err),
- });
- }
+ // Hook and personal IM both require the current owner's DbClient. Start
+ // them from this authoritative Main-side readiness point instead of
+ // relying only on the renderer's later fire-and-forget
+ // app:ready-for-bot signal. That signal can be lost during cold-start
+ // auto-login or an owner remount, leaving a saved Feishu bot disconnected
+ // and unable to claim the owner from its first p2p message.
+ startAccountIntegrationsAfterOwnerDbReady(userId, {
+ isOwnerCurrent: (ownerId) =>
+ isLocalDbOwnerCurrent(
+ authManager.getAuthState(),
+ ownerId,
+ isAppSessionBoundaryPending(),
+ ),
+ startHookControlAccount,
+ startImConnection,
+ log: dbClientLog,
+ });
attemptStartScheduler();
attemptStartEmbeddingHost();
// 旧「资料本地覆写」方案退役(2026-07)的一次性清理:清当前账号名下的
@@ -5545,12 +5548,11 @@ app.on('ready', async () => {
im.registerIpc();
// 挂业务 orchestrator: 订阅 feishuIm.onMessage / .onCardAction。orchestrator
// 必须在 createWindow 前挂好,避免 renderer 起来后第一波 IPC / event 找不到
- // handler。FeishuBot 的 WS 长连接此处不启动 —— 由 renderer 在用户登录 +
- // localDb 就绪后通过 'app:ready-for-bot' IPC 触发(见下方 handler)。
+ // handler。FeishuBot 的 WS 长连接必须等当前用户 localDb ready 后再启动。
startImOrchestrators();
// Renderer → main 的 "应用真正就绪" 兼容信号。LocalDbGate 在
- // localDb.ensureReady 成功之后调一次。Hook 已在 localDb onReady 的 Main
- // 权威时点激活,这里保留幂等兜底;FeishuBot 仍由本信号启动。
+ // localDb.ensureReady 成功之后调一次。Hook 与 FeishuBot 已在 localDb onReady
+ // 的 Main 权威时点激活,这里为旧时序与瞬时失败保留幂等重试。
ipcMain.handle('app:ready-for-bot', (event) => {
assertTrustedAppRendererEvent(event);
startHookControlAccount();
diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts
index 190f9ba385..23ab1bbb8e 100644
--- a/apps/desktop/src/main/hook-control/dispatcher.ts
+++ b/apps/desktop/src/main/hook-control/dispatcher.ts
@@ -161,9 +161,9 @@ export interface HookDispatcherDeps {
*/
resolveInteraction?: (interactionId: string, buttonId: string) => boolean;
/**
- * Production keeps ingress closed until app:ready-for-bot has opened the
- * account DB. Tests and standalone consumers retain the historical eager
- * behavior unless they opt out explicitly.
+ * Production keeps ingress closed until the owner DB-ready callback opens
+ * the account boundary. Tests and standalone consumers retain the historical
+ * eager behavior unless they opt out explicitly.
*/
accountInitiallyActive?: boolean;
log: { info(msg: string): void; warn(msg: string): void };
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index beb0b71ba1..da39fce0a9 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -17,9 +17,11 @@
* ├─────────────────────────────────┼──────────────────────────────────────┤
* │ App boot │ im.registerIpc + startImOrch │
* │ │ (orchestrators only — NO connect) │
- * │ User login + localDb ready │ app:ready-for-bot IPC → │
- * │ (LocalDbGate, renderer) │ startImConnection() → im.init() │
+ * │ User login + localDb ready │ Main localDb onReady → │
+ * │ │ startImConnection() → im.init() │
* │ │ (auto-connect if creds) │
+ * │ Renderer ready compatibility │ app:ready-for-bot IPC → idempotent │
+ * │ signal (LocalDbGate) │ startImConnection() retry │
* │ Logout / account replacement │ stopImConnection() before DbClient │
* │ │ dispose; clear runtime caches │
* │ App quit (before-quit) │ stopImConnection('quit') │
@@ -157,8 +159,8 @@ export function startImOrchestrators(): void {
// bindingStore.preload() 故意不在这里跑 —— 它要 DbClient, 而 localDb 在
// 用户登录后才 ensureReady (worker spawn + db open + smoke 后才 setCurrentDbClient)。
// orchestrator 注册和 bot 上线是分阶段的: 这一步只挂 in-process listener
- // (无 DB 依赖), 真正读表搬到 startImConnection 里 —— 那时 'app:ready-for-bot'
- // IPC 已触发, DbClient 必然 ready。
+ // (无 DB 依赖), 真正读表搬到 startImConnection 里 —— 那时 Main 的 owner
+ // DB-ready 回调已经完成, DbClient 必然 ready。
// Broadcast binding 变更给所有 renderer window — desktop UI 用这个广播
// 实时渲染 mask + 收回按钮的 attach/detach 状态。payload 形态固定:
@@ -262,8 +264,8 @@ export function startImOrchestrators(): void {
});
// Bot connection is intentionally NOT kicked off here — it happens in
- // `startImConnection()` once the renderer signals the user is logged in
- // and localDb is ready. See module header table for full lifecycle.
+ // `startImConnection()` after Main confirms the current owner's localDb is
+ // ready. See module header table for full lifecycle.
}
async function initializeImConnection(): Promise<void> {
@@ -424,8 +426,8 @@ export function startImConnection(): void {
// 此时 forward map 必须已经填好, 否则会被当成"没接管"误路由到默认 session。
// 放这里(而不是 startImOrchestrators)是因为 DbClient 要求 localDb 已
// ensureReady (worker takeover 完成 + setCurrentDbClient 已写入 currentRef),
- // 而本函数的调用方 'app:ready-for-bot' IPC 由 renderer 在 localDb 就绪后
- // 才触发, 时序保证 OK。
+ // 而本函数只会在 Main 的 localDb onReady 权威时点,或 renderer 随后的
+ // 'app:ready-for-bot' 兼容信号中调用,时序保证 OK。
connectionLifecycle.start();
}