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(bots): read window API objects when used, not as render identity

nanaf79f7e23692d
diff --git a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx
index e94773760c..4021afc0e7 100644
--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx
@@ -113,7 +113,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {
// This computer's messaging stack, or the teammate's computer's through the settings target.
const target = useBotSettingsTarget();
const { im, wechat, x: remoteX } = target.channels;
- const { payload, loading, apply } = useBotImConnections(im);
+ const { payload, loading, apply } = useBotImConnections(im, target);
const { confirm } = useConfirmDialog();
const [adding, setAdding] = useState(false);
const [wechatExpanded, setWechatExpanded] = useState(false);
@@ -272,11 +272,13 @@ function ConnectionGroups({ api, connectionId, botName }: { api: BotImConnection
const [error, setError] = useState<'load' | 'save' | null>(null);
const [reloadToken, setReloadToken] = useState(0);
const latest = useRef(0);
+ const apiRef = useRef(api);
+ apiRef.current = api;
useEffect(() => {
let cancelled = false;
setError(null);
- void listBotImConnectionGroups(api, connectionId)
+ void listBotImConnectionGroups(apiRef.current, connectionId)
.then((payload) => {
if (!cancelled) setGroups(payload.groups);
})
@@ -286,7 +288,7 @@ function ConnectionGroups({ api, connectionId, botName }: { api: BotImConnection
return () => {
cancelled = true;
};
- }, [api, connectionId, reloadToken]);
+ }, [connectionId, reloadToken]);
const setMode = useCallback(
(chatId: string, mode: BotImGroupActivationMode) => {
@@ -295,21 +297,21 @@ function ConnectionGroups({ api, connectionId, botName }: { api: BotImConnection
current ? current.map((g) => (g.chatId === chatId ? { ...g, activation: mode } : g)) : current,
);
setError(null);
- void setBotImConnectionGroupActivation(api, connectionId, chatId, mode)
+ void setBotImConnectionGroupActivation(apiRef.current, connectionId, chatId, mode)
.then((payload) => {
if (revision === latest.current) setGroups(payload.groups);
})
.catch(() => {
if (revision !== latest.current) return;
setError('save');
- void listBotImConnectionGroups(api, connectionId)
+ void listBotImConnectionGroups(apiRef.current, connectionId)
.then((payload) => {
if (revision === latest.current) setGroups(payload.groups);
})
.catch(() => undefined);
});
},
- [api, connectionId],
+ [connectionId],
);
if (groups === null && error !== 'load') return null;
@@ -381,11 +383,13 @@ function ConnectionLanes({ api, connectionId, botName }: { api: BotImConnectionA
const [reloadToken, setReloadToken] = useState(0);
const [now, setNow] = useState(() => Date.now());
const resettingRef = useRef(false);
+ const apiRef = useRef(api);
+ apiRef.current = api;
useEffect(() => {
let cancelled = false;
const load = () => {
- void listBotImConnectionLanes(api, connectionId)
+ void listBotImConnectionLanes(apiRef.current, connectionId)
.then((payload) => {
if (cancelled) return;
setLanes(payload.lanes);
@@ -404,7 +408,7 @@ function ConnectionLanes({ api, connectionId, botName }: { api: BotImConnectionA
cancelled = true;
clearInterval(timer);
};
- }, [api, connectionId, reloadToken]);
+ }, [connectionId, reloadToken]);
const laneName = (lane: BotImConnectionLane) =>
lane.kind === 'owner-dm' ? t('bots.channels.lanes.ownerName') : lane.name || lane.chatId || '';
@@ -428,7 +432,7 @@ function ConnectionLanes({ api, connectionId, botName }: { api: BotImConnectionA
setResettingId(lane.sessionId);
setNotice(null);
try {
- const payload = await resetBotImConnectionLane(api, connectionId, lane.sessionId);
+ const payload = await resetBotImConnectionLane(apiRef.current, connectionId, lane.sessionId);
setLanes(payload.lanes);
setNow(Date.now());
setNotice({ tone: 'done', text: t('bots.channels.lanes.resetDone', { lane: name }) });
@@ -618,11 +622,13 @@ function BotChannelAddDialog({
const credentialsHere = remoteName === undefined;
const useExisting = existing !== null && (source === 'existing' || !credentialsHere);
+ const apiRef = useRef(api);
+ apiRef.current = api;
const refreshAdoptable = useCallback(() => {
- void listAdoptablePersonalBots(api)
+ void listAdoptablePersonalBots(apiRef.current)
.then((next) => setAdoptable(next.bots))
.catch(() => setAdoptable([]));
- }, [api]);
+ }, []);
useEffect(refreshAdoptable, [refreshAdoptable]);
useEffect(() => {
@@ -694,7 +700,7 @@ function BotChannelAddDialog({
setBusy(true);
setError(null);
try {
- const next = input ? await addBotImConnection(api, input) : await adoptPersonalBot(api, { botId: bot.id, channel });
+ const next = input ? await addBotImConnection(apiRef.current, input) : await adoptPersonalBot(apiRef.current, { botId: bot.id, channel });
onApplied(next);
onOpenChange(false);
} catch (failure) {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx
index a669983cac..756fdecfbd 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx
@@ -360,6 +360,20 @@ describe('BotChannelsPage', () => {
});
});
+describe('BotChannelsPage with a window API that is not identity-stable', () => {
+ it('reads the connection list once, however often it renders', async () => {
+ const list = vi.fn(async () => ({ connections: [connection()] }));
+ Object.assign(window, { electronAPI: {
+ // A harness or proxying bridge hands out a fresh object per access.
+ get botImConnection() { return { list, onChanged: () => () => undefined }; },
+ } });
+ render(<BotChannelsPage bot={mia} />);
+ expect(await screen.findByText('bots.channels.platform.telegram')).toBeTruthy();
+ await new Promise((resolve) => setTimeout(resolve, 20)); // real-wait: let a would-be render loop show itself
+ expect(list).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('BotChannelsPage for a teammate on another computer', () => {
/** The page talks to the other computer's API only; this window's own API must stay untouched. */
function renderRemote(api: Record<string, unknown>, channels: Partial<BotSettingsTarget['channels']> = {}) {
diff --git a/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts b/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts
index 6bfdfe1ac5..d454cc18e8 100644
--- a/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts
+++ b/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts
@@ -4,7 +4,7 @@
* 同一份 `botImConnection.list()` 投影 + `botImConnection:changed` 广播: 添加、移除与
* 传输层状态变化都走广播刷新。线上类型与语义见 shared/botImConnection.ts。
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import type {
BotImAdoptablePersonalBotsPayload,
@@ -27,7 +27,11 @@ export function botImConnectionApi(): BotImConnectionApi | null {
return api && typeof api.list === 'function' ? api : null;
}
-export function useBotImConnections(api: BotImConnectionApi | null = botImConnectionApi()): {
+/**
+ * `scope` says which computer's connections these are (the settings target); the API object itself is read
+ * when the subscription starts, because a window API is not a render-stable identity.
+ */
+export function useBotImConnections(api: BotImConnectionApi | null = botImConnectionApi(), scope: unknown = null): {
payload: BotImConnectionListPayload | null;
/** 首次读取还在途; 读取失败或没有 IPC 时为 false, payload 保持 null。 */
loading: boolean;
@@ -35,8 +39,11 @@ export function useBotImConnections(api: BotImConnectionApi | null = botImConnec
} {
const [payload, setPayload] = useState<BotImConnectionListPayload | null>(null);
const [loading, setLoading] = useState(() => api !== null);
+ const apiRef = useRef(api);
+ apiRef.current = api;
useEffect(() => {
+ const api = apiRef.current;
if (!api) return;
setPayload(null);
let cancelled = false;
@@ -59,7 +66,7 @@ export function useBotImConnections(api: BotImConnectionApi | null = botImConnec
cancelled = true;
unsubscribe();
};
- }, [api]);
+ }, [scope]);
return { payload, loading, apply: setPayload };
}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
index ffc1a9ed2c..d9718cc390 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
@@ -226,6 +226,29 @@ describe('useWechatBot for another computer', () => {
});
});
+describe('useWechatBot with a window API that is not identity-stable', () => {
+ it('loads once instead of re-subscribing on every render', async () => {
+ setDataOwnerGeneration('owner-a');
+ __testing.resetCache();
+ const getState = vi.fn(async () => disconnectedState());
+ // UI harnesses (and any bridge that proxies the API) hand out a fresh object per access.
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ get wechatBot() {
+ return {
+ getState,
+ getChannelSettings: async () => ({ version: 1, workingDir: null, workingDirAvailable: true }),
+ onStateChange: () => () => undefined,
+ onChannelSettingsChange: () => () => undefined,
+ };
+ },
+ };
+ const { result } = renderHook(() => useWechatBot());
+ await waitFor(() => expect(result.current.channelSettings).not.toBeNull());
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); // real-wait: let a would-be render loop show itself
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
+});
+
function disconnectedState(): WechatBotState {
return {
phase: 'disconnected',
diff --git a/apps/desktop/src/renderer/hooks/useWechatBot.ts b/apps/desktop/src/renderer/hooks/useWechatBot.ts
index 23fcbe88c2..9e894fbf5e 100644
--- a/apps/desktop/src/renderer/hooks/useWechatBot.ts
+++ b/apps/desktop/src/renderer/hooks/useWechatBot.ts
@@ -40,7 +40,8 @@ type WechatBotApi = Window['electronAPI']['wechatBot'];
*/
export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
const { t } = useTranslation();
- const api = override ?? window.electronAPI.wechatBot;
+ // Resolved at use, as before: a window API object is not a render-stable identity.
+ const api = () => override ?? window.electronAPI.wechatBot;
const [owner] = useState(getDataOwnerGeneration);
// ProtectedRoute remounts on owner changes; module caches survive that remount.
if (cacheOwnerId !== getDataOwnerGeneration().dataOwnerId) {
@@ -62,13 +63,13 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
useEffect(() => {
let cancelled = false;
- const unsubscribe = api.onStateChange((next) => {
+ const unsubscribe = api().onStateChange((next) => {
if (cancelled || !isDataOwnerIdCurrent(owner)) return;
pushVersionRef.current += 1;
if (!override) cachedState = next;
setState(next);
});
- const unsubscribeSettings = api.onChannelSettingsChange?.((settings) => {
+ const unsubscribeSettings = api().onChannelSettingsChange?.((settings) => {
if (cancelled || !isDataOwnerIdCurrent(owner)) return;
settingsVersionRef.current += 1;
if (!override) cachedChannelSettings = settings;
@@ -78,8 +79,8 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
const initialSettingsVersion = settingsVersionRef.current;
const requestOwner = getDataOwnerGeneration();
void Promise.all([
- api.getState(),
- api.getChannelSettings(),
+ api().getState(),
+ api().getChannelSettings(),
])
.then(([nextState, nextChannelSettings]) => {
// Same-owner repair keeps this page mounted and these read-only settings valid.
@@ -102,13 +103,13 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
unsubscribe();
unsubscribeSettings?.();
};
- }, [owner, api, override]);
+ }, [owner, override]);
const authorize = useCallback(async (): Promise<boolean> => {
if (isAuthorizing) return false;
setIsAuthorizing(true);
try {
- await api.authorize();
+ await api().authorize();
return true;
} catch {
log.error('failed to start personal WeChat authorization');
@@ -117,22 +118,22 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
} finally {
setIsAuthorizing(false);
}
- }, [api, isAuthorizing, t]);
+ }, [isAuthorizing, t]);
const cancelAuthorization = useCallback(async (): Promise<void> => {
try {
- await api.cancelAuthorization();
+ await api().cancelAuthorization();
} catch {
log.error('failed to cancel personal WeChat authorization');
toast.error(t('settings.wechatBot.toasts.cancelFailed'));
}
- }, [api, t]);
+ }, [t]);
const unbind = useCallback(async (): Promise<boolean> => {
if (isUnbinding) return false;
setIsUnbinding(true);
try {
- await api.unbind();
+ await api().unbind();
toast.success(t('settings.wechatBot.toasts.unbound'));
return true;
} catch {
@@ -142,14 +143,14 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
} finally {
setIsUnbinding(false);
}
- }, [api, isUnbinding, t]);
+ }, [isUnbinding, t]);
const chooseWorkingDirectory = useCallback(async (): Promise<void> => {
if (isUpdatingWorkingDir || !isDataOwnerIdCurrent(owner)) return;
const requestOwner = getDataOwnerGeneration();
setIsUpdatingWorkingDir(true);
try {
- const result = await api.chooseWorkingDirectory();
+ const result = await api().chooseWorkingDirectory();
if (!isDataOwnerGenerationCurrent(requestOwner)) return;
if (!override) cachedChannelSettings = result.state;
setChannelSettings(result.state);
@@ -160,14 +161,14 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
} finally {
setIsUpdatingWorkingDir(false);
}
- }, [api, override, isUpdatingWorkingDir, owner, t]);
+ }, [override, isUpdatingWorkingDir, owner, t]);
const resetWorkingDirectory = useCallback(async (): Promise<void> => {
if (isUpdatingWorkingDir || !isDataOwnerIdCurrent(owner)) return;
const requestOwner = getDataOwnerGeneration();
setIsUpdatingWorkingDir(true);
try {
- const next = await api.resetWorkingDirectory();
+ const next = await api().resetWorkingDirectory();
if (!isDataOwnerGenerationCurrent(requestOwner)) return;
if (!override) cachedChannelSettings = next;
setChannelSettings(next);
@@ -178,7 +179,7 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
} finally {
setIsUpdatingWorkingDir(false);
}
- }, [api, override, isUpdatingWorkingDir, owner, t]);
+ }, [override, isUpdatingWorkingDir, owner, t]);
const setCompanion = useCallback(async (botId: string | null): Promise<boolean> => {
if (companionBusyRef.current || !channelSettings || !isDataOwnerIdCurrent(owner)) return false;
@@ -186,7 +187,7 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
companionBusyRef.current = true;
setIsUpdatingCompanion(true);
try {
- const next = await api.setCompanion(botId);
+ const next = await api().setCompanion(botId);
if (!isDataOwnerGenerationCurrent(requestOwner)) return false;
settingsVersionRef.current += 1;
if (!override) cachedChannelSettings = next;
@@ -199,7 +200,7 @@ export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {
companionBusyRef.current = false;
setIsUpdatingCompanion(false);
}
- }, [api, override, channelSettings, owner, t]);
+ }, [override, channelSettings, owner, t]);
return {
state,