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): preserve canonical history access without model routes

zqchrise6d3804a3751
diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
index e0290395d4..1ba4b357e6 100644
--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
@@ -393,14 +393,19 @@ export function BotsHomeView() {
() => getEffectiveBotModelChain().length > 0,
);
const creatingBotRef = useRef<{ botId: string; token: symbol } | null>(null);
+ const [unavailableCanonicalId, setUnavailableCanonicalId] = useState<string | null>(null);
const [isCreatingSession, setIsCreatingSession] = useState(false);
const [createSessionError, setCreateSessionError] = useState<unknown>(null);
const selectedBot = useMemo(() => bots.find((bot) => bot.id === botId) ?? null, [botId, bots]);
// An empty profile projection can predate the newly connected source/runtime.
// Only followers may resume from live defaults; Main resolves the actual route
// when opening the canonical task without writing a per-Bot override.
- const needsModelSelection = selectedBot?.capabilities.modelChain.length === 0
+ const modelUnavailable = selectedBot?.capabilities.modelChain.length === 0
&& !(selectedBot.capabilities.modelChainOverride === null && hasDefaultModel);
+ const currentCanonicalId = selectedBot ? canonicalBotSessionId(selectedBot) : undefined;
+ const needsCanonicalCreation = !currentCanonicalId || unavailableCanonicalId === currentCanonicalId;
+ const needsModelSelection = needsCanonicalCreation && modelUnavailable;
+ const needsProviderConnection = needsCanonicalCreation && providerOnboarding.visible;
// `?add=1` 是阵容还在弹模态那阵子的入口。阵容页面化之后它只剩兼容职责:
// 老书签、老深链通过 /bots/roster 复用同一个创建弹窗。
const addRequested = searchParams.get('add') === '1';
@@ -506,7 +511,7 @@ export function BotsHomeView() {
useRegisterContentHeader(headerContent);
useEffect(() => {
- if (providerOnboarding.visible || needsModelSelection) return;
+ if (needsProviderConnection || needsModelSelection) return;
if (selectedBot?.invitation && selectedBot.invitation.stage !== 'ready') return;
if (!selectedBot || shouldDeferCanonicalBotSessionNavigation({ settingsOpen, addRequested }))
return;
@@ -517,12 +522,19 @@ export function BotsHomeView() {
const canonicalSessionId = canonicalBotSessionId(selectedBot);
let cancelled = false;
+ // Read existing history even without a route; only reconstruction needs one.
+ const deferReconstruction = () => {
+ if (!providerOnboarding.visible && !modelUnavailable) return false;
+ setUnavailableCanonicalId(canonicalSessionId ?? null);
+ return true;
+ };
if (canonicalSessionId) {
setIsCreatingSession(false);
void withBotCanonicalSessionReadTimeout(() => sessionService.get(canonicalSessionId))
.then(async (session) => {
if (cancelled) return;
if (session.status !== 'active') {
+ if (deferReconstruction()) return;
setIsCreatingSession(true);
const next = await createCanonicalSession(selectedBot);
if (!cancelled) {
@@ -532,6 +544,7 @@ export function BotsHomeView() {
return;
}
if (session.source !== 'bot') {
+ if (deferReconstruction()) return;
// A renderer-held canonicalSessionId is not authority to reclassify an
// arbitrary existing Session. Preserve the existing task and create a
// fresh Bot-owned Session instead.
@@ -553,7 +566,7 @@ export function BotsHomeView() {
}
})
.catch(async () => {
- if (cancelled) return;
+ if (cancelled || deferReconstruction()) return;
setIsCreatingSession(true);
// The profile pointer is still the CAS authority even when its Session
// row disappeared. Passing null can never repair that state because
@@ -598,9 +611,9 @@ export function BotsHomeView() {
creatingBotRef.current = null;
}
};
- }, [addRequested, createCanonicalSession, selectedBot, sessionId, settingsOpen, navigate, providerOnboarding.visible, needsModelSelection]);
+ }, [addRequested, createCanonicalSession, selectedBot, sessionId, settingsOpen, navigate, providerOnboarding.visible, needsModelSelection, needsProviderConnection, modelUnavailable]);
- if (providerOnboarding.visible && !settingsOpen) {
+ if (needsProviderConnection && !settingsOpen) {
return <main className="flex h-full items-center justify-center px-6" role="main"><ConnectProviderCard dismissible={false} /></main>;
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
index a96f486445..fac115d3ea 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
@@ -8,10 +8,10 @@ import { beginProvidersRefresh, commitProvidersSnapshot } from '@/lib/providersS
vi.mock('@/state/modelVisibilityPrefs', () => ({ migrateModelVisibilityDefaults: vi.fn() }));
vi.mock('@/hooks/useProviderOnboarding', () => ({
- useProviderOnboarding: () => ({ visible: false }),
+ useProviderOnboarding: () => ({ visible: mocks.onboarding }),
}));
vi.mock('@/components/onboarding/ConnectProviderCard', () => ({
- ConnectProviderCard: () => null,
+ ConnectProviderCard: () => <div data-testid="connect-provider-card" />,
}));
const translate = (key: string, opts?: Record<string, unknown>) =>
@@ -20,6 +20,8 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
+ onboarding: false,
+ readSession: vi.fn(),
initialSearch: '' as string,
profiles: [] as BotProfile[],
params: {} as { botId?: string },
@@ -39,6 +41,8 @@ const mocks = vi.hoisted(() => ({
openPath: vi.fn(async (): Promise<{ success: boolean; error?: string }> => ({ success: true })),
}));
+vi.mock('@/lib/sessionService', () => ({ get: mocks.readSession }));
+
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal<typeof import('react-router-dom')>();
const { useCallback, useState } = await import('react');
@@ -179,6 +183,8 @@ function renderSettings(overrides: Partial<BotProfile> = {}, initialSearch = 'se
beforeEach(() => {
mocks.navigate.mockReset();
+ mocks.onboarding = false;
+ mocks.readSession.mockReset();
mocks.updateBotProfile.mockReset();
mocks.updateBotProfile.mockImplementation(async (_id, patch) => ({
id: 'bot-1',
@@ -204,6 +210,36 @@ afterEach(() => {
});
describe('Bot settings profile consolidation', () => {
+ it.each([true, false])('opens existing history without a model when onboarding is %s', async (onboarding) => {
+ const existing = bot({ capabilities: capabilities({ modelChain: [], model: '' }) });
+ mocks.profiles = [existing];
+ mocks.params = { botId: existing.id };
+ mocks.onboarding = onboarding;
+ mocks.readSession.mockResolvedValue({ id: existing.canonicalSessionId, status: 'active', source: 'bot', title: 'History', updatedAt: new Date().toISOString() });
+ const createCanonicalSession = vi.fn();
+ Object.assign(window.electronAPI, { localDb: { bots: { createCanonicalSession } } });
+ render(<BotsHomeView />);
+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith('/bots/bot-1/session/bot-1-chat', { replace: true }));
+ expect(screen.queryByTestId('connect-provider-card')).toBeNull();
+ expect(screen.queryByTestId('model-selector')).toBeNull();
+ expect(createCanonicalSession).not.toHaveBeenCalled();
+ expect(mocks.updateBotProfile).not.toHaveBeenCalled();
+ });
+
+ it.each(['missing', 'archived', 'foreign'])('requires a model before rebuilding a %s canonical task', async (state) => {
+ const existing = bot({ capabilities: capabilities({ modelChain: [], model: '' }) });
+ mocks.profiles = [existing];
+ mocks.params = { botId: existing.id };
+ if (state === 'missing') mocks.readSession.mockRejectedValue(new Error('missing'));
+ else mocks.readSession.mockResolvedValue({ status: state === 'archived' ? 'archived' : 'active', source: state === 'foreign' ? 'user' : 'bot' });
+ const createCanonicalSession = vi.fn();
+ Object.assign(window.electronAPI, { localDb: { bots: { createCanonicalSession } } });
+ render(<BotsHomeView />);
+ await screen.findByTestId('model-selector');
+ expect(createCanonicalSession).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
it('opens a model picker for an existing empty-chain bot without retrying creation', async () => {
const emptyBot = bot({ capabilities: capabilities({ modelChain: [], model: '' }), sessions: [], canonicalSessionId: undefined });
mocks.profiles = [emptyBot];