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(wechat): invalidate companion settings cache across accounts

Chris803482261654
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
index 704132fafd..e1a1eab4c4 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
@@ -2,6 +2,7 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { __testing, useWechatBot } from '../useWechatBot';
vi.mock('react-i18next', () => ({
@@ -45,6 +46,7 @@ function installWechatApi(initial: WechatBotState = disconnectedState()) {
state: { ...channelState, workingDir: 'D:/project' },
})),
resetWorkingDirectory: vi.fn(async () => channelState),
+ setCompanion: vi.fn(async (botId: string | null) => ({ ...channelState, companionBotId: botId })),
onStateChange: vi.fn((callback: (state: WechatBotState) => void) => {
listeners.add(callback);
return () => listeners.delete(callback);
@@ -66,6 +68,7 @@ function installWechatApi(initial: WechatBotState = disconnectedState()) {
describe('useWechatBot', () => {
beforeEach(() => {
vi.clearAllMocks();
+ setDataOwnerGeneration('owner-a');
__testing.resetCache();
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
@@ -158,6 +161,44 @@ describe('useWechatBot', () => {
expect(result.current.channelSettings?.workingDir).toBeNull();
expect(api.resetWorkingDirectory).toHaveBeenCalledTimes(1);
});
+
+ // #6492 r4318178122, unit: cached A + delayed directory response + B opening
+ // before its GET resolves must not expose A's binding or let A's action clear B.
+ // Existing unmount coverage only fences initial GETs, not cached/mutation results.
+ it('isolates cached settings and late mutations across account switches', async () => {
+ const a = installWechatApi({ phase: 'connected', bound: true, queuedTasks: 0 });
+ const settingsA = { version: 1 as const, workingDir: null, workingDirAvailable: true, companionBotId: 'bot-a' };
+ a.api.getChannelSettings.mockResolvedValue(settingsA);
+ const first = renderHook(() => useWechatBot());
+ await waitFor(() => expect(first.result.current.channelSettings?.companionBotId).toBe('bot-a'));
+ const staleUnlink = first.result.current.setCompanion;
+ let finishDirectory!: (value: Awaited<ReturnType<typeof a.api.chooseWorkingDirectory>>) => void;
+ a.api.chooseWorkingDirectory.mockReturnValueOnce(new Promise((resolve) => { finishDirectory = resolve; }));
+ let pending!: Promise<void>;
+ act(() => { pending = first.result.current.chooseWorkingDirectory(); });
+ first.unmount();
+
+ setDataOwnerGeneration('owner-b');
+ const b = installWechatApi();
+ let finishSettings!: (value: WechatChannelSettingsState) => void;
+ b.api.getChannelSettings.mockReturnValueOnce(new Promise((resolve) => { finishSettings = resolve; }));
+ const second = renderHook(() => useWechatBot());
+ expect(second.result.current.channelSettings).toBeNull();
+ expect(second.result.current.state).toEqual(disconnectedState());
+ await act(async () => {
+ expect(await staleUnlink(null)).toBe(false);
+ expect(await second.result.current.setCompanion(null)).toBe(false);
+ finishDirectory({ canceled: false, state: { ...settingsA, workingDir: 'D:/old-owner' } });
+ await pending;
+ });
+ expect(b.api.setCompanion).not.toHaveBeenCalled();
+ expect(__testing.getCache().channelSettings).toBeNull();
+ await act(async () => { finishSettings({ ...settingsA, companionBotId: 'bot-b' }); });
+ expect(second.result.current.channelSettings?.companionBotId).toBe('bot-b');
+ await act(async () => { expect(await second.result.current.setCompanion(null)).toBe(true); });
+ expect(b.api.setCompanion).toHaveBeenCalledWith(null);
+ second.unmount();
+ });
});
function disconnectedState(): WechatBotState {
diff --git a/apps/desktop/src/renderer/hooks/useWechatBot.ts b/apps/desktop/src/renderer/hooks/useWechatBot.ts
index aabb9f832b..25aab0bd6f 100644
--- a/apps/desktop/src/renderer/hooks/useWechatBot.ts
+++ b/apps/desktop/src/renderer/hooks/useWechatBot.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, isDataOwnerIdCurrent } from '@/contexts/dataOwnerGeneration';
import { createLogger } from '@/lib/logger';
import { toast } from '@/lib/toast';
@@ -14,6 +15,7 @@ const EMPTY_STATE: WechatBotState = {
let cachedState: WechatBotState | null = null;
let cachedChannelSettings: WechatChannelSettingsState | null = null;
+let cacheOwnerId = getDataOwnerGeneration().dataOwnerId;
export interface UseWechatBotReturn {
state: WechatBotState;
@@ -32,6 +34,13 @@ export interface UseWechatBotReturn {
export function useWechatBot(): UseWechatBotReturn {
const { t } = useTranslation();
+ const [owner] = useState(getDataOwnerGeneration);
+ // ProtectedRoute remounts on owner changes; module caches survive that remount.
+ if (cacheOwnerId !== getDataOwnerGeneration().dataOwnerId) {
+ cacheOwnerId = getDataOwnerGeneration().dataOwnerId;
+ cachedState = null;
+ cachedChannelSettings = null;
+ }
const [state, setState] = useState<WechatBotState>(() => cachedState ?? EMPTY_STATE);
const [channelSettings, setChannelSettings] = useState<WechatChannelSettingsState | null>(
() => cachedChannelSettings,
@@ -47,25 +56,26 @@ export function useWechatBot(): UseWechatBotReturn {
useEffect(() => {
let cancelled = false;
const unsubscribe = window.electronAPI.wechatBot.onStateChange((next) => {
- if (cancelled) return;
+ if (cancelled || !isDataOwnerIdCurrent(owner)) return;
pushVersionRef.current += 1;
cachedState = next;
setState(next);
});
const unsubscribeSettings = window.electronAPI.wechatBot.onChannelSettingsChange?.((settings) => {
- if (cancelled) return;
+ if (cancelled || !isDataOwnerIdCurrent(owner)) return;
settingsVersionRef.current += 1;
cachedChannelSettings = settings;
setChannelSettings(settings);
});
const initialPushVersion = pushVersionRef.current;
const initialSettingsVersion = settingsVersionRef.current;
+ const requestOwner = getDataOwnerGeneration();
void Promise.all([
window.electronAPI.wechatBot.getState(),
window.electronAPI.wechatBot.getChannelSettings(),
])
.then(([nextState, nextChannelSettings]) => {
- if (cancelled) return;
+ if (cancelled || !isDataOwnerGenerationCurrent(requestOwner)) return;
if (pushVersionRef.current === initialPushVersion) {
cachedState = nextState;
setState(nextState);
@@ -84,7 +94,7 @@ export function useWechatBot(): UseWechatBotReturn {
unsubscribe();
unsubscribeSettings?.();
};
- }, []);
+ }, [owner]);
const authorize = useCallback(async (): Promise<boolean> => {
if (isAuthorizing) return false;
@@ -127,10 +137,12 @@ export function useWechatBot(): UseWechatBotReturn {
}, [isUnbinding, t]);
const chooseWorkingDirectory = useCallback(async (): Promise<void> => {
- if (isUpdatingWorkingDir) return;
+ if (isUpdatingWorkingDir || !isDataOwnerIdCurrent(owner)) return;
+ const requestOwner = getDataOwnerGeneration();
setIsUpdatingWorkingDir(true);
try {
const result = await window.electronAPI.wechatBot.chooseWorkingDirectory();
+ if (!isDataOwnerGenerationCurrent(requestOwner)) return;
cachedChannelSettings = result.state;
setChannelSettings(result.state);
if (!result.canceled) toast.success(t('settings.wechatBot.toasts.workingDirSaved'));
@@ -140,13 +152,15 @@ export function useWechatBot(): UseWechatBotReturn {
} finally {
setIsUpdatingWorkingDir(false);
}
- }, [isUpdatingWorkingDir, t]);
+ }, [isUpdatingWorkingDir, owner, t]);
const resetWorkingDirectory = useCallback(async (): Promise<void> => {
- if (isUpdatingWorkingDir) return;
+ if (isUpdatingWorkingDir || !isDataOwnerIdCurrent(owner)) return;
+ const requestOwner = getDataOwnerGeneration();
setIsUpdatingWorkingDir(true);
try {
const next = await window.electronAPI.wechatBot.resetWorkingDirectory();
+ if (!isDataOwnerGenerationCurrent(requestOwner)) return;
cachedChannelSettings = next;
setChannelSettings(next);
toast.success(t('settings.wechatBot.toasts.workingDirReset'));
@@ -156,14 +170,16 @@ export function useWechatBot(): UseWechatBotReturn {
} finally {
setIsUpdatingWorkingDir(false);
}
- }, [isUpdatingWorkingDir, t]);
+ }, [isUpdatingWorkingDir, owner, t]);
const setCompanion = useCallback(async (botId: string | null): Promise<boolean> => {
- if (companionBusyRef.current) return false;
+ if (companionBusyRef.current || !channelSettings || !isDataOwnerIdCurrent(owner)) return false;
+ const requestOwner = getDataOwnerGeneration();
companionBusyRef.current = true;
setIsUpdatingCompanion(true);
try {
const next = await window.electronAPI.wechatBot.setCompanion(botId);
+ if (!isDataOwnerGenerationCurrent(requestOwner)) return false;
settingsVersionRef.current += 1;
cachedChannelSettings = next;
setChannelSettings(next);
@@ -175,7 +191,7 @@ export function useWechatBot(): UseWechatBotReturn {
companionBusyRef.current = false;
setIsUpdatingCompanion(false);
}
- }, [t]);
+ }, [channelSettings, owner, t]);
return {
state,
@@ -197,6 +213,7 @@ export const __testing = {
resetCache(): void {
cachedState = null;
cachedChannelSettings = null;
+ cacheOwnerId = getDataOwnerGeneration().dataOwnerId;
},
getCache(): {
state: WechatBotState | null;