Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(connector): move the connector lists onto @lobechat/replica (#20573)

Arvin Xu90edc34ebd32
diff --git a/src/features/Connectors/CustomConnectorModal/index.test.tsx b/src/features/Connectors/CustomConnectorModal/index.test.tsx
new file mode 100644
index 00000000000..00d4ef08980
--- /dev/null
+++ b/src/features/Connectors/CustomConnectorModal/index.test.tsx
@@ -0,0 +1,135 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import CustomConnectorModal from './index';
+
+const mocks = vi.hoisted(() => ({
+ state: {
+ connector: undefined as unknown,
+ createConnector: vi.fn(),
+ deleteConnector: vi.fn(),
+ getConnectorForEdit: vi.fn(),
+ startConnectorOAuth: vi.fn(),
+ syncConnectorTools: vi.fn(),
+ uninstallCustomPlugin: vi.fn(),
+ updateConnector: vi.fn(),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (_key: string, options?: { defaultValue?: string } | string) =>
+ typeof options === 'object' ? (options.defaultValue ?? _key) : (options ?? _key),
+ }),
+}));
+
+vi.mock('@/store/tool', () => ({
+ useToolStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),
+}));
+
+vi.mock('@/store/tool/slices/connector', () => ({
+ connectorSelectors: {
+ connectorById: () => (state: typeof mocks.state) => state.connector,
+ },
+}));
+
+// The form itself is a heavy antd form; what matters here is the value the
+// modal seeds it with.
+vi.mock('@/features/PluginDevModal', () => ({
+ default: ({ value }: { value?: unknown }) => (
+ <div data-testid="seed">{JSON.stringify(value ?? null)}</div>
+ ),
+}));
+
+vi.mock('@/utils/connectorOAuth', () => ({ waitForConnectorOAuth: vi.fn() }));
+
+/**
+ * The persisted list projection strips `mcpStdioConfig.env` and
+ * `metadata.customHeaders` (see `withoutConnectorSecrets`). A row hydrated from
+ * IndexedDB therefore has neither, and the edit form has to take them from the
+ * protected `getForEdit` read — otherwise it seeds empty secret fields and
+ * saving the apparently untouched form deletes them.
+ */
+describe('CustomConnectorModal edit pre-fill', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Exactly what a hydrated list row looks like: no stdio env, no headers.
+ mocks.state.connector = {
+ id: 'c1',
+ identifier: 'my-mcp',
+ mcpConnectionType: 'stdio',
+ mcpServerUrl: null,
+ metadata: { description: 'My MCP' },
+ name: 'My MCP',
+ sourceType: 'custom',
+ };
+ mocks.state.getConnectorForEdit.mockResolvedValue({
+ credentials: null,
+ mcpStdioConfig: { args: ['-y'], command: 'npx', env: { API_KEY: 'sk-live-secret' } },
+ metadata: { customHeaders: { Authorization: 'Bearer header-secret' }, description: 'My MCP' },
+ oidcConfig: null,
+ });
+ });
+
+ it('seeds the stdio env and custom headers from the protected edit read', async () => {
+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));
+
+ const seeded = JSON.parse(screen.getByTestId('seed').textContent!);
+ expect(seeded.customParams.mcp.env).toEqual({ API_KEY: 'sk-live-secret' });
+ expect(seeded.customParams.mcp.headers).toEqual({ Authorization: 'Bearer header-secret' });
+ expect(seeded.customParams.mcp.command).toBe('npx');
+ });
+
+ it('falls back to the list row only when the edit read omits the field', async () => {
+ mocks.state.connector = {
+ ...(mocks.state.connector as object),
+ mcpStdioConfig: { command: 'uvx', env: { LEGACY: 'from-row' } },
+ };
+ // `undefined` = an older read that does not ship the field at all.
+ mocks.state.getConnectorForEdit.mockResolvedValue({
+ credentials: null,
+ metadata: undefined,
+ oidcConfig: null,
+ });
+
+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));
+
+ const seeded = JSON.parse(screen.getByTestId('seed').textContent!);
+ expect(seeded.customParams.mcp.env).toEqual({ LEGACY: 'from-row' });
+ });
+
+ // `null` from the protected read is the server confirming there is nothing —
+ // not "field missing". A row cached by this browser can be older than the
+ // connector (re-created or cleared in another session), so it must not
+ // resurrect secrets that the read says are gone.
+ it('treats an explicit null from the edit read as authoritative', async () => {
+ mocks.state.connector = {
+ ...(mocks.state.connector as object),
+ metadata: { customHeaders: { Authorization: 'stale-header' }, description: 'Stale' },
+ mcpStdioConfig: { command: 'uvx', env: { STALE: 'from-row' } },
+ };
+ mocks.state.getConnectorForEdit.mockResolvedValue({
+ credentials: null,
+ mcpStdioConfig: null,
+ metadata: null,
+ oidcConfig: null,
+ });
+
+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));
+
+ const seeded = JSON.parse(screen.getByTestId('seed').textContent!);
+ expect(seeded.customParams.mcp.env).toBeUndefined();
+ expect(seeded.customParams.mcp.command).toBeUndefined();
+ expect(seeded.customParams.mcp.headers).toBeUndefined();
+ expect(seeded.customParams.description).toBeUndefined();
+ });
+});
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index b2193803ec6..db4940c287e 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -38,6 +38,17 @@ const cleanRecord = (record?: Record<string, string>): Record<string, string> |
return Object.keys(cleaned).length > 0 ? cleaned : undefined;
};
+/**
+ * The stdio launch config (including the `env` secrets an MCP stdio process is
+ * started with). Shipped at runtime by the list and edit reads, but not part of
+ * `ConnectorWithTools`.
+ */
+interface StdioConfig {
+ args?: string[];
+ command?: string;
+ env?: Record<string, string>;
+}
+
/**
* "Add / Edit custom connector" entry. Reuses the rich PluginDevModal MCP form,
* but persists everything onto the connector subsystem (the single backend for
@@ -73,8 +84,16 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
// Full connector data (with decrypted credentials) fetched for the edit form.
// null = not yet loaded; object = loaded (credentials may still be null if none set).
+ //
+ // `metadata` and `mcpStdioConfig` come from this protected read, NOT from the
+ // list row: the list projection strips both secrets before it is persisted
+ // (see `withoutConnectorSecrets`), so a row hydrated from IndexedDB would
+ // seed the form with empty values and saving the untouched form would wipe
+ // the live env / custom headers.
type EditFetchedData = {
credentials: Exclude<ConnectorCredentials, { type: 'oauth2' }> | null;
+ mcpStdioConfig: StdioConfig | null | undefined;
+ metadata: Record<string, unknown> | null | undefined;
oidcConfig: Omit<OIDCConfig, 'clientSecret'> | null | undefined;
};
const [editFetchedData, setEditFetchedData] = useState<EditFetchedData | null>(null);
@@ -95,6 +114,11 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
if (controller.signal.aborted) return;
setEditFetchedData({
credentials: (data?.credentials ?? null) as EditFetchedData['credentials'],
+ // Keep `undefined` (the read did not ship the field) distinct from
+ // `null` (the server confirmed there is none): only the former may
+ // fall back to the list row.
+ mcpStdioConfig: data?.mcpStdioConfig,
+ metadata: data?.metadata,
oidcConfig: (data?.oidcConfig ?? null) as EditFetchedData['oidcConfig'],
});
});
@@ -102,7 +126,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
return () => {
controller.abort();
};
- }, [open, connectorId]);
+ }, [open, connectorId, getConnectorForEdit]);
// Build the pre-fill value for edit mode once the credentials fetch completes.
// Returns undefined while loading so DevModal defers seeding the form.
@@ -114,9 +138,21 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
if (!isEditMode || !connector || editFetchedData === null) return undefined;
const c = connector as typeof connector & {
- mcpStdioConfig?: { args?: string[]; command?: string; env?: Record<string, string> };
+ mcpStdioConfig?: StdioConfig;
};
- const mcpStdioConfig = c.mcpStdioConfig;
+ // Both of these are stripped from the persisted list projection, so the
+ // protected edit read is authoritative. `undefined` means the read did not
+ // ship the field at all (older server), which is the only case where the
+ // list row may be used; `null` means the server confirmed there is none,
+ // and a row cached by this browser must not resurrect it — that is how a
+ // connector re-created or cleared in another session would come back with
+ // stale secrets written from the editor.
+ const mcpStdioConfig =
+ editFetchedData.mcpStdioConfig === undefined
+ ? c.mcpStdioConfig
+ : (editFetchedData.mcpStdioConfig ?? undefined);
+ const metadata =
+ editFetchedData.metadata === undefined ? connector.metadata : editFetchedData.metadata;
const { credentials, oidcConfig } = editFetchedData;
@@ -133,14 +169,14 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
// credential so existing connectors still pre-fill their headers — and do
// so regardless of the auth radio (headers can coexist with bearer auth).
const customHeaders =
- (connector.metadata?.customHeaders as Record<string, string> | undefined) ??
+ (metadata?.customHeaders as Record<string, string> | undefined) ??
(credentials?.type === 'header'
? (credentials as { headers: Record<string, string> }).headers
: undefined);
return {
customParams: {
- description: connector.metadata?.description as string | undefined,
+ description: metadata?.description as string | undefined,
mcp: {
args: mcpStdioConfig?.args,
auth: {
diff --git a/src/libs/replica/cacheScopeEvents.ts b/src/libs/replica/cacheScopeEvents.ts
new file mode 100644
index 00000000000..0f1ee07b488
--- /dev/null
+++ b/src/libs/replica/cacheScopeEvents.ts
@@ -0,0 +1,57 @@
+/**
+ * Cache-scope change signal for the local-first replicas.
+ *
+ * Every client persistence tier is partitioned by the cache scope
+ * (`${userId}:${workspace}`, see `@/libs/swr/useCacheScope`). A React consumer
+ * observes a switch through `useCacheScope()`; a replica that lives in a
+ * zustand store is not rendered by anything, so it sees nothing.
+ *
+ * `useSync`-driven replicas get this for free — the hook re-runs on a scope
+ * switch and calls `ensureScope(newScope)` before paint. Imperative replicas
+ * (the connector slice drives its fetches from legacy effects gated on an init
+ * flag) have no such hook, so the engine would only notice the switch on its
+ * *next dispatch*. Until then the previous identity's rows stay in the store's
+ * view **and** keep its init flag set, which makes every gated consumer skip
+ * the fetch for the new scope — the workspace then paints the previous user's
+ * (or the personal) connector inventory until something unrelated happens to
+ * dispatch.
+ *
+ * `useCacheScope` therefore broadcasts the new scope here, and imperative
+ * replica owners subscribe to `ensureScope(scope)` the state those views are
+ * derived from, so a switch drops the previous identity's memory immediately
+ * instead of waiting for a dispatch that may never come.
+ *
+ * This module is deliberately dependency-free: `@/libs/replica/index` imports
+ * `useCacheScope`, so `useCacheScope` must import this leaf file directly.
+ */
+type CacheScopeListener = (scope: string) => void;
+
+const listeners = new Set<CacheScopeListener>();
+let lastBroadcast: string | undefined;
+
+/** Subscribe to cache-scope changes. Returns the unsubscribe. */
+export const subscribeCacheScope = (listener: CacheScopeListener): (() => void) => {
+ listeners.add(listener);
+
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+/**
+ * Announce that `scope` is now the active one. Idempotent: every mounted
+ * `useCacheScope()` reports the same value, only the first is forwarded.
+ */
+export const broadcastCacheScope = (scope: string): void => {
+ if (lastBroadcast === scope) return;
+ lastBroadcast = scope;
+
+ // Iterating the Set directly: a listener that unsubscribes mid-flight is
+ // simply skipped, which is what the unsubscribe contract promises.
+ for (const listener of listeners) listener(scope);
+};
+
+/** Forget the last broadcast value (tests: keeps cases independent). */
+export const resetCacheScopeBroadcast = (): void => {
+ lastBroadcast = undefined;
+};
diff --git a/src/libs/swr/useCacheScope.test.ts b/src/libs/swr/useCacheScope.test.ts
index fec698b0bf4..a735f517e83 100644
--- a/src/libs/swr/useCacheScope.test.ts
+++ b/src/libs/swr/useCacheScope.test.ts
@@ -1,11 +1,15 @@
+import { cleanup, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { resetCacheScopeBroadcast, subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
+
import {
buildCacheScope,
clearActiveScopeKey,
getCacheScope,
isAnonymousScope,
isScopeTrusted,
+ useCacheScope,
} from './useCacheScope';
let mockUserId: string | null | undefined = undefined;
@@ -19,12 +23,14 @@ vi.mock('@lobechat/const', () => ({
return mockIsDesktop;
},
}));
+const mockUserState = () => ({
+ isLoaded: mockIsAuthLoaded,
+ isIdentityResolved: mockIsIdentityResolved,
+ user: { id: mockUserId },
+});
vi.mock('@/store/user', () => ({
- getUserStoreState: () => ({
- isLoaded: mockIsAuthLoaded,
- isIdentityResolved: mockIsIdentityResolved,
- user: { id: mockUserId },
- }),
+ getUserStoreState: () => mockUserState(),
+ useUserStore: (selector: (state: unknown) => unknown) => selector(mockUserState()),
}));
vi.mock('@/store/user/selectors', () => ({
authSelectors: { isLoaded: (s: any) => s.isLoaded },
@@ -153,3 +159,43 @@ describe('isScopeTrusted', () => {
expect(isScopeTrusted()).toBe(true);
});
});
+
+describe('useCacheScope broadcast', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ mockUserId = 'user_a';
+ mockIsAuthLoaded = true;
+ mockIsIdentityResolved = false;
+ mockWorkspaceId = null;
+ mockIsDesktop = false;
+ resetCacheScopeBroadcast();
+ });
+
+ afterEach(() => {
+ cleanup();
+ localStorage.clear();
+ });
+
+ // Imperative replicas (the connector slice) live in zustand stores that
+ // nothing re-renders on a scope switch; this broadcast is how they learn the
+ // scope moved and drop the previous identity's views.
+ it('broadcasts the active scope, once per change', () => {
+ const seen: string[] = [];
+ const unsubscribe = subscribeCacheScope((scope) => seen.push(scope));
+
+ const { rerender } = renderHook(() => useCacheScope());
+ expect(seen).toEqual(['user_a:personal']);
+
+ // The URL→workspace sync resolves the slug.
+ mockWorkspaceId = 'ws-1';
+ rerender();
+ expect(seen).toEqual(['user_a:personal', 'user_a:ws-1']);
+
+ // A re-render — or a second mounted observer — reporting the same scope
+ // must not re-broadcast it.
+ rerender();
+ expect(seen).toEqual(['user_a:personal', 'user_a:ws-1']);
+
+ unsubscribe();
+ });
+});
diff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.ts
index 7d92c5cc3fb..30d13a2838a 100644
--- a/src/libs/swr/useCacheScope.ts
+++ b/src/libs/swr/useCacheScope.ts
@@ -1,10 +1,13 @@
import { isDesktop } from '@lobechat/const';
-import { useEffect, useState } from 'react';
+import { useEffect, useLayoutEffect, useState } from 'react';
import {
getActiveWorkspaceId,
useActiveWorkspaceId,
} from '@/business/client/hooks/useActiveWorkspaceId';
+// Leaf import on purpose: `@/libs/replica` imports this module, so going
+// through its index would be a cycle.
+import { broadcastCacheScope } from '@/libs/replica/cacheScopeEvents';
import { getUserStoreState, type UserStore, useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
@@ -132,6 +135,13 @@ export const useCacheScope = (): string => {
const scope = resolveScope(userId, workspaceId, persisted, identityResolved);
+ // Before paint, so an imperative replica can drop the previous identity's
+ // views in the same frame the switch commits — a passive effect would leave
+ // one paintable frame of the old scope on screen.
+ useLayoutEffect(() => {
+ broadcastCacheScope(scope);
+ }, [scope]);
+
useEffect(() => {
if (userId && !isAnonymousScope(scope)) writeActiveScope(scope);
// The identity round-trip landed on "nobody": the persisted scope belongs to
diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.ts
index ced9de2619d..b514db4ed35 100644
--- a/src/services/mcp.test.ts
+++ b/src/services/mcp.test.ts
@@ -13,8 +13,11 @@ const mockElectronIpc = {
},
};
-// Mock dependencies
-vi.mock('@lobechat/const', () => ({
+// Mock dependencies. Spread the real module: the connector slice this service
+// pulls in lazily now reaches the user store chain, which reads `DEFAULT_AGENT`
+// from `@lobechat/const` — a partial factory would break on that missing export.
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
CURRENT_VERSION: '1.0.0',
isDesktop: false,
}));
diff --git a/src/spa/initialize/connectors.test.ts b/src/spa/initialize/connectors.test.ts
index ee5185c4eda..c912d444273 100644
--- a/src/spa/initialize/connectors.test.ts
+++ b/src/spa/initialize/connectors.test.ts
@@ -4,10 +4,15 @@ const mocks = vi.hoisted(() => ({
fetchConnectors: vi.fn(async () => {}),
isConnectorsInit: false,
isSignedIn: false,
+ scope: 'user_a:personal',
toolSubscribe: vi.fn(),
userSubscribe: vi.fn(),
}));
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => mocks.scope,
+}));
+
vi.mock('@/store/tool', () => ({
getToolStoreState: () => ({
fetchConnectors: mocks.fetchConnectors,
@@ -34,6 +39,7 @@ describe('startConnectorInitialization', () => {
mocks.fetchConnectors.mockResolvedValue(undefined);
mocks.isConnectorsInit = false;
mocks.isSignedIn = false;
+ mocks.scope = 'user_a:personal';
});
it('fetches connectors when a signed-in user is present', async () => {
@@ -57,4 +63,70 @@ describe('startConnectorInitialization', () => {
expect(mocks.fetchConnectors).toHaveBeenCalledTimes(1);
});
+
+ // A scope switch commits tool-store state synchronously (the connector slice
+ // clears its views through `ensureScope`) and the fetch runs inside that same
+ // commit. If the guard were only set once the fetch returned, the commit would
+ // re-enter this subscriber while it is still unset and launch a duplicate
+ // list request for one switch.
+ it('claims the in-flight slot before entering the fetch', async () => {
+ mocks.isSignedIn = true;
+
+ const { startConnectorInitialization } = await import('./connectors');
+ startConnectorInitialization();
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(1);
+
+ // Let the first fetch settle so its in-flight slot is released.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const toolListener = mocks.toolSubscribe.mock.calls[0]![0] as () => void;
+
+ // The switch re-arms the init gate, and the fetch re-enters the subscriber
+ // once — the guard must already be up.
+ mocks.isConnectorsInit = false;
+ let reentered = false;
+ mocks.fetchConnectors.mockImplementation(async () => {
+ if (reentered) return;
+ reentered = true;
+ toolListener();
+ });
+
+ toolListener();
+
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(2);
+ });
+
+ // The other half of the same guard: a scope switch while the request is in
+ // flight re-arms the gate, but the subscriber's re-entrant call is swallowed
+ // by the in-flight slot — and the response being awaited belongs to the old
+ // scope, so it will be discarded. The new scope must get its own request once
+ // the slot frees up, instead of waiting for an unrelated store update.
+ it('re-runs the fetch when the scope changed while one was in flight', async () => {
+ mocks.isSignedIn = true;
+
+ const { startConnectorInitialization } = await import('./connectors');
+
+ let resolveInFlight!: () => void;
+ mocks.fetchConnectors.mockImplementationOnce(
+ () => new Promise<void>((resolve) => (resolveInFlight = resolve)),
+ );
+
+ startConnectorInitialization();
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(1);
+
+ const toolListener = mocks.toolSubscribe.mock.calls[0]![0] as () => void;
+
+ // The workspace slug resolves while the personal request is still pending.
+ mocks.scope = 'user_a:ws-1';
+ mocks.isConnectorsInit = false;
+ toolListener();
+
+ // Swallowed by the in-flight slot — not a second request.
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(1);
+
+ resolveInFlight();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/src/spa/initialize/connectors.ts b/src/spa/initialize/connectors.ts
index d3a89c2dde9..2c058fc1957 100644
--- a/src/spa/initialize/connectors.ts
+++ b/src/spa/initialize/connectors.ts
@@ -1,21 +1,38 @@
+import { getCacheScope } from '@/libs/swr/useCacheScope';
import { getToolStoreState, useToolStore } from '@/store/tool';
import { getUserStoreState, useUserStore } from '@/store/user';
let connectorsStarted = false;
-let pendingFetch: Promise<void> | undefined;
+let connectorsFetching = false;
const ensureConnectors = () => {
const { isSignedIn } = getUserStoreState();
const { fetchConnectors, isConnectorsInit } = getToolStoreState();
- if (!isSignedIn || isConnectorsInit || pendingFetch) return;
+ if (!isSignedIn || isConnectorsInit || connectorsFetching) return;
- pendingFetch = fetchConnectors()
+ // Claim the slot BEFORE calling: `fetchConnectors()` is subscribed to the
+ // tool store, so any state it commits in its synchronous prefix would
+ // re-enter this very function while the guard is still unset and launch a
+ // duplicate list request.
+ connectorsFetching = true;
+ const scope = getCacheScope();
+ fetchConnectors()
.catch((error) => {
console.error('[SPA Initialize] fetchConnectors failed', error);
})
.finally(() => {
- pendingFetch = undefined;
+ connectorsFetching = false;
+ // A scope switch during the request re-arms the init gate (the slice
+ // drops the previous identity's views on the change), but its re-entrant
+ // call here was swallowed by the in-flight slot — and the response this
+ // request is waiting for belongs to the old scope, so it will be
+ // discarded. Re-check now that the slot is free, otherwise the new scope
+ // waits for an unrelated store update to get its own list.
+ //
+ // Keyed on the scope moving, not on the gate alone: a *failed* fetch also
+ // leaves the gate unset, and retrying that here would spin.
+ if (getCacheScope() !== scope) ensureConnectors();
});
};
diff --git a/src/store/tool/slices/connector/action.test.ts b/src/store/tool/slices/connector/action.test.ts
index 3eda920a4c2..89e590ad227 100644
--- a/src/store/tool/slices/connector/action.test.ts
+++ b/src/store/tool/slices/connector/action.test.ts
@@ -1,7 +1,7 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import * as workspaceHooks from '@/business/client/hooks/useActiveWorkspaceId';
+import { cacheScope } from '@/libs/replica';
import { lambdaClient } from '@/libs/trpc/client';
import { useToolStore } from '../../store';
@@ -27,9 +27,14 @@ const listByAgentQuery = lambdaClient.connector.listByAgent.query as unknown as
const connector = (identifier: string) => ({ id: identifier, identifier, tools: [] });
+let scopeSpy: ReturnType<typeof vi.spyOn>;
+
describe('createConnectorSlice — scope guard', () => {
beforeEach(() => {
useToolStore.setState({ ...initialConnectorState });
+ // The guard captures the full cache scope (user + workspace), not just the
+ // workspace id, so the tests drive the scope string directly.
+ scopeSpy = vi.spyOn(cacheScope, 'get').mockReturnValue('user-a:personal');
});
afterEach(() => {
@@ -37,17 +42,16 @@ describe('createConnectorSlice — scope guard', () => {
vi.clearAllMocks();
});
- // The connector list is workspace-scoped server-side but lands in one global
+ // The connector list is identity-scoped server-side but lands in one global
// store bucket, so a response that resolves after the active scope moved on
// must be dropped. Booting straight into a workspace URL is exactly that: the
// tree mounts once in personal context before the URL→store sync resolves the
// slug, so a personal query is already in flight when the workspace switch
// fires its own — and the personal one landing last is what made a business
// workspace list the user's PERSONAL tools.
- it('drops a fetchConnectors response that resolves after the scope changed', async () => {
- const wsSpy = vi.spyOn(workspaceHooks, 'getActiveWorkspaceId').mockReturnValue(null);
+ it('drops a fetchConnectors response that resolves after the workspace changed', async () => {
listQuery.mockImplementation(async () => {
- wsSpy.mockReturnValue('ws-1');
+ scopeSpy.mockReturnValue('user-a:ws-1');
return [connector('personal-tool')];
});
@@ -60,8 +64,25 @@ describe('createConnectorSlice — scope guard', () => {
expect(useToolStore.getState().isConnectorsInit).toBe(false);
});
+ // The gap a workspace-only guard leaves open: two signed-in users in personal
+ // context both have a `null` workspace, so the scope must include the user or
+ // user A's inventory lands in user B's partition after an account switch.
+ it('drops a fetchConnectors response that resolves after the signed-in user changed', async () => {
+ listQuery.mockImplementation(async () => {
+ scopeSpy.mockReturnValue('user-b:personal');
+ return [connector('user-a-tool')];
+ });
+
+ const { result } = renderHook(() => useToolStore());
+ await act(async () => {
+ await result.current.fetchConnectors();
+ });
+
+ expect(useToolStore.getState().connectors).toEqual([]);
+ expect(useToolStore.getState().isConnectorsInit).toBe(false);
+ });
+
it('writes a fetchConnectors response that resolves in the same scope', async () => {
- vi.spyOn(workspaceHooks, 'getActiveWorkspaceId').mockReturnValue('ws-1');
listQuery.mockResolvedValue([connector('workspace-tool')]);
const { result } = renderHook(() => useToolStore());
@@ -74,9 +95,8 @@ describe('createConnectorSlice — scope guard', () => {
});
it('drops a fetchAgentBoundConnectors response that resolves after the scope changed', async () => {
- const wsSpy = vi.spyOn(workspaceHooks, 'getActiveWorkspaceId').mockReturnValue('ws-1');
listAgentBoundQuery.mockImplementation(async () => {
- wsSpy.mockReturnValue(null);
+ scopeSpy.mockReturnValue('user-b:personal');
return [connector('agent-bound')];
});
@@ -90,9 +110,8 @@ describe('createConnectorSlice — scope guard', () => {
});
it('drops a fetchAgentConnectors response that resolves after the scope changed', async () => {
- const wsSpy = vi.spyOn(workspaceHooks, 'getActiveWorkspaceId').mockReturnValue('ws-1');
listByAgentQuery.mockImplementation(async () => {
- wsSpy.mockReturnValue('ws-2');
+ scopeSpy.mockReturnValue('user-a:ws-2');
return [connector('agent-owned')];
});
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index 49e00fe8a19..7d0fd6d7625 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -1,56 +1,215 @@
import { isDesktop } from '@lobechat/const';
import { isLocalOrPrivateUrl } from '@lobechat/utils';
-import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import type { ConnectorToolPermission } from '@/database/schemas';
+import {
+ cacheScope,
+ createReplicaSlice,
+ linkReplicaEntity,
+ type ReplicaLens,
+} from '@/libs/replica';
+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
import { lambdaClient } from '@/libs/trpc/client';
import { mcpService } from '@/services/mcp';
import type { StoreSetter } from '@/store/types';
import type { ToolStore } from '../../store';
+import {
+ agentBoundConnectorsEntity,
+ agentBoundConnectorsResource,
+ agentConnectorsResource,
+ CONNECTOR_LIST_KEY,
+ connectorsEntity,
+ connectorsResource,
+ withoutConnectorSecrets,
+} from './projection';
+import type { AgentBoundConnector, ConnectorWithTools } from './types';
type Setter = StoreSetter<ToolStore>;
+/** The connector lists are one entry per scope, so every sync shares these params. */
+const LIST_PARAMS = {} as Record<string, never>;
+
+/**
+ * The base connector list keeps its long-standing flat `connectors` field as
+ * the replica view, so every selector keeps reading what it did. The init flag
+ * gates `get`: before the first hydrate/replace the view must read `undefined`,
+ * otherwise the empty default would block hydration from storage.
+ */
+const connectorsLens: ReplicaLens<ToolStore, ConnectorWithTools[]> = {
+ clear: () => ({ connectors: [], isConnectorsInit: false }),
+ get: (state) => (state.isConnectorsInit ? state.connectors : undefined),
+ keys: (state) => (state.isConnectorsInit ? [CONNECTOR_LIST_KEY] : []),
+ set: (_state, _key, data) =>
+ data === undefined
+ ? { connectors: [], isConnectorsInit: false }
+ : { connectors: data, isConnectorsInit: true },
+};
+
+/** The agent-bound aggregate is one entry, gated by `isAgentBoundInit`. */
+const agentBoundConnectorsLens: ReplicaLens<ToolStore, AgentBoundConnector[]> = {
+ clear: () => ({ agentBoundConnectors: [], isAgentBoundInit: false }),
+ get: (state) => (state.isAgentBoundInit ? state.agentBoundConnectors : undefined),
+ keys: (state) => (state.isAgentBoundInit ? [CONNECTOR_LIST_KEY] : []),
+ set: (_state, _key, data) =>
+ data === undefined
+ ? { agentBoundConnectors: [], isAgentBoundInit: false }
+ : { agentBoundConnectors: data, isAgentBoundInit: true },
+};
+
+/**
+ * Per-agent lists live in `agentConnectors[agentId]`; the per-agent bucket of
+ * `agentConnectorsInit` carries the same gate the flat lists use.
+ */
+const agentConnectorsLens: ReplicaLens<ToolStore, ConnectorWithTools[]> = {
+ clear: () => ({ agentConnectors: {}, agentConnectorsInit: {} }),
+ get: (state, key) => (state.agentConnectorsInit[key] ? state.agentConnectors[key] : undefined),
+ keys: (state) => Object.keys(state.agentConnectors ?? {}),
+ set: (state, key, data) => {
+ const agentConnectors = { ...state.agentConnectors };
+ const agentConnectorsInit = { ...state.agentConnectorsInit };
+ if (data === undefined) {
+ delete agentConnectors[key];
+ delete agentConnectorsInit[key];
+ } else {
+ agentConnectors[key] = data;
+ agentConnectorsInit[key] = true;
+ }
+ return { agentConnectors, agentConnectorsInit };
+ },
+};
+
+/** The connector lists of the active scope (their entry params are constant). */
+const fetchConnectorList = (): Promise<ConnectorWithTools[]> =>
+ lambdaClient.connector.list.query() as unknown as Promise<ConnectorWithTools[]>;
+
+const fetchAgentBoundConnectorList = (): Promise<AgentBoundConnector[]> =>
+ lambdaClient.connector.listAgentBound.query() as unknown as Promise<AgentBoundConnector[]>;
+
+const fetchAgentConnectorList = ({ agentId }: { agentId: string }): Promise<ConnectorWithTools[]> =>
+ lambdaClient.connector.listByAgent.query({ agentId }) as unknown as Promise<ConnectorWithTools[]>;
+
export const createConnectorSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
new ConnectorActionImpl(set, get, _api);
+/**
+ * The connector slice is a set of `@lobechat/replica` resources: the base
+ * list, the agent-bound aggregate and the per-agent buckets. The store fields
+ * keep their historical shape (`connectors`, `agentBoundConnectors`,
+ * `agentConnectors`) as the replica views, so every selector and consumer is
+ * unchanged; the slab below only orchestrates fetching and writes.
+ */
export class ConnectorActionImpl {
- readonly #set: Setter;
+ readonly #agentBoundConnectors;
+ readonly #agentConnectors;
+ /** One connector lives in the base list, the aggregate and per-agent buckets. */
+ readonly #connectorRows;
+ readonly #connectors;
readonly #get: () => ToolStore;
+ readonly #set: Setter;
constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#connectors = createReplicaSlice(connectorsResource, {
+ actionPrefix: 'connectors',
+ entity: connectorsEntity,
+ fetcher: fetchConnectorList,
+ get,
+ set,
+ stateKey: 'connectorsReplica',
+ toPersisted: withoutConnectorSecrets,
+ view: connectorsLens,
+ });
+ this.#agentBoundConnectors = createReplicaSlice(agentBoundConnectorsResource, {
+ actionPrefix: 'agentBoundConnectors',
+ entity: agentBoundConnectorsEntity,
+ fetcher: fetchAgentBoundConnectorList,
+ get,
+ set,
+ stateKey: 'agentBoundConnectorsReplica',
+ toPersisted: withoutConnectorSecrets,
+ view: agentBoundConnectorsLens,
+ });
+ this.#agentConnectors = createReplicaSlice(agentConnectorsResource, {
+ actionPrefix: 'agentConnectors',
+ entity: connectorsEntity,
+ fetcher: fetchAgentConnectorList,
+ get,
+ set,
+ stateKey: 'agentConnectorsReplica',
+ toPersisted: withoutConnectorSecrets,
+ view: agentConnectorsLens,
+ });
+ this.#connectorRows = linkReplicaEntity<ConnectorWithTools>([
+ this.#connectors,
+ this.#agentBoundConnectors,
+ this.#agentConnectors,
+ ]);
+
+ // These three resources have no `useSync` mount, so nothing re-renders them
+ // on a cache-scope switch and the engine only resets on its *next* dispatch
+ // — which the gated consumers never make, because the init flag they check
+ // is still set. Drop the previous identity's views the moment the scope
+ // changes. The store is an app-lifetime singleton, so the subscription is
+ // never torn down.
+ subscribeCacheScope((scope) => this.#dropStaleScope(scope));
}
/**
- * Whether the scope captured when a request was issued is still the active
- * one. Connector lists are workspace-scoped server-side (the request carries
- * the active workspace as a header), but the store bucket is a single global
- * one — so a late response must not be written after the scope moved on.
+ * Drop every connector view of the previous identity (rows *and* the init
+ * flag that lets consumers skip their fetch). A no-op when the scope has not
+ * moved on, which is the common case on the imperative refresh paths.
+ */
+ #dropStaleScope = (scope: string): void => {
+ this.#connectors.ensureScope(scope);
+ this.#agentBoundConnectors.ensureScope(scope);
+ this.#agentConnectors.ensureScope(scope);
+ };
+
+ /**
+ * Refresh the base connector list. The persisted projection paints as soon
+ * as it is read while the network confirms it in parallel, instead of
+ * blanking to an empty array first.
*
- * Booting straight into a workspace URL is exactly that case: the tree mounts
- * once in personal context before the URL→store sync resolves the slug, so a
- * personal `list` query is already in flight when the workspace switch fires
- * its own. Whichever lands last wins, and when that is the personal one the
- * workspace's own tools vanish from the tool picker for the rest of the
- * session. In the open-source build there are no workspaces and
- * `getActiveWorkspaceId()` is always `null`, so this is a no-op.
+ * The identity scope is captured when the request is issued and handed to
+ * `hydrate` / `replace` explicitly, because the replica reads the *active*
+ * scope at call time — i.e. after the response has already landed. A response
+ * that resolves after the scope moved on is then dropped by the replica
+ * itself (`dispatch` discards actions whose scope is no longer active),
+ * instead of being written into the next identity's partition.
*
- * Dropping a response deliberately leaves the one-shot init flag alone
- * rather than marking the bucket loaded: a scope change remounts the
- * workspace context slot's subtree, so the consumers gated on that flag
- * re-issue their fetch under the new scope and the discarded result is not
- * one anybody still needs.
+ * The whole cache scope (user + workspace) is captured, not just the
+ * workspace: two different signed-in users in personal context both have a
+ * `null` workspace, so a workspace-only guard cannot tell them apart and
+ * would store user A's connector inventory in user B's partition after an
+ * account switch. Booting straight into a workspace URL is the other case
+ * this covers — the tree mounts once in personal context before the URL→store
+ * sync resolves the slug, so a personal `list` query is already in flight
+ * when the workspace switch fires its own, and the personal one landing last
+ * is what made a business workspace list the user's PERSONAL tools.
+ *
+ * Dropping the response is only half of it. A dropped response must not leave
+ * the *previous* scope's hydration behind either: the persisted personal
+ * projection can have painted (and set `isConnectorsInit`) during that same
+ * personal window, and every consumer gates its fetch on that flag — so the
+ * workspace would keep showing the personal inventory and never load its own.
+ * `#dropStaleScope` clears the views the moment the scope moves (see the
+ * `subscribeCacheScope` wiring in the constructor).
+ *
+ * No reset is needed here for the fetch itself: the engine folds the scope
+ * reset into the same commit as the response, so a stale view can never be
+ * replaced into — and doing it here would commit store state synchronously
+ * before the caller's in-flight guard is up, which multiplies the requests a
+ * single scope switch launches.
*/
- #isStillInScope = (scope: string | null): boolean => getActiveWorkspaceId() === scope;
-
fetchConnectors = async (): Promise<void> => {
- const scope = getActiveWorkspaceId();
- const data = await lambdaClient.connector.list.query();
- if (!this.#isStillInScope(scope)) return;
- this.#set({ connectors: data as any, isConnectorsInit: true }, false, 'fetchConnectors');
+ const scope = cacheScope.get();
+ const pending = this.#connectors.fetcher!(LIST_PARAMS);
+ if (!this.#get().isConnectorsInit) await this.#connectors.hydrate(LIST_PARAMS, scope);
+ const data = await pending;
+ this.#connectors.replace(LIST_PARAMS, data, scope);
};
/**
@@ -70,35 +229,30 @@ export class ConnectorActionImpl {
* Fetch every agent-owned connector across all agents (the flat aggregate for
* the unified connector-settings page). Each row is enriched
* server-side with the owning agent's title/avatar. Scope-correct: a workspace
- * context only returns that workspace's agent connectors.
+ * context only returns that workspace's agent connectors. See
+ * {@link ConnectorActionImpl.fetchConnectors} for the captured-scope rule.
*/
fetchAgentBoundConnectors = async (): Promise<void> => {
- const scope = getActiveWorkspaceId();
- const data = await lambdaClient.connector.listAgentBound.query();
- if (!this.#isStillInScope(scope)) return;
- this.#set(
- { agentBoundConnectors: data as any, isAgentBoundInit: true },
- false,
- 'fetchAgentBoundConnectors',
- );
+ const scope = cacheScope.get();
+ const pending = this.#agentBoundConnectors.fetcher!(LIST_PARAMS);
+ if (!this.#get().isAgentBoundInit) await this.#agentBoundConnectors.hydrate(LIST_PARAMS, scope);
+ const data = await pending;
+ this.#agentBoundConnectors.replace(LIST_PARAMS, data, scope);
};
/**
* Fetch an agent's own tools (agent-owned + mounted) for the "Agent Tools"
- * tab. Stored keyed by agentId.
+ * tab. Stored keyed by agentId. See
+ * {@link ConnectorActionImpl.fetchConnectors} for the captured-scope rule.
*/
fetchAgentConnectors = async (agentId: string): Promise<void> => {
- const scope = getActiveWorkspaceId();
- const data = await lambdaClient.connector.listByAgent.query({ agentId });
- if (!this.#isStillInScope(scope)) return;
- this.#set(
- (s) => ({
- agentConnectors: { ...s.agentConnectors, [agentId]: data as any },
- agentConnectorsInit: { ...s.agentConnectorsInit, [agentId]: true },
- }),
- false,
- 'fetchAgentConnectors',
- );
+ const scope = cacheScope.get();
+ const params = { agentId };
+ const pending = this.#agentConnectors.fetcher!(params);
+ if (!this.#get().agentConnectorsInit[agentId])
+ await this.#agentConnectors.hydrate(params, scope);
+ const data = await pending;
+ this.#agentConnectors.replace(params, data, scope);
};
/** Copy a user connector into an agent-owned, independently editable row. */
@@ -166,8 +320,17 @@ export class ConnectorActionImpl {
return authorizationUrl;
};
+ /**
+ * Delete a connector. The row leaves every list that holds it (base,
+ * agent-bound and per-agent buckets) in one fan-out — but only once the
+ * server has confirmed the delete. The row must stay mounted while the
+ * request is in flight: a detail pane bound to it would otherwise blank for
+ * every deletion (and blink back if the delete is rejected), which is why the
+ * removal is confirmed rather than optimistic.
+ */
deleteConnector = async (id: string): Promise<void> => {
await lambdaClient.connector.delete.mutate({ id });
+ this.#connectorRows.remove(id);
await this.#refreshConnectorLists();
};
@@ -340,8 +503,9 @@ export class ConnectorActionImpl {
toolId: string,
permission: ConnectorToolPermission,
): Promise<void> => {
- // Optimistic update — patch the tool in whichever list holds it (base
- // connectors and agent-bound connectors are separate arrays).
+ // Optimistic update — patch the tool in whichever list holds it. The base
+ // list and the agent-bound aggregate are separate replicas, so each gets
+ // its own overlay and both settle together.
const patchTools = <
T extends { tools: Array<{ id: string; permission: ConnectorToolPermission }> },
>(
@@ -351,19 +515,18 @@ export class ConnectorActionImpl {
...c,
tools: c.tools.map((t) => (t.id === toolId ? { ...t, permission } : t)),
}));
- this.#set(
- (s) => ({
- agentBoundConnectors: patchTools(s.agentBoundConnectors ?? []),
- connectors: patchTools(s.connectors),
- }),
- false,
- 'updateToolPermission/optimistic',
- );
+
+ const base = this.#connectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools);
+ const bound = this.#agentBoundConnectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools);
try {
await lambdaClient.connector.updateToolPermission.mutate({ permission, toolId });
+ base.commit();
+ bound.commit();
} catch {
- // Roll back on error
+ // Roll back the overlays, then rebuild from the server.
+ base.rollback();
+ bound.rollback();
await this.#refreshConnectorLists();
}
};
diff --git a/src/store/tool/slices/connector/initialState.ts b/src/store/tool/slices/connector/initialState.ts
index 20b943967c5..4591ebf7739 100644
--- a/src/store/tool/slices/connector/initialState.ts
+++ b/src/store/tool/slices/connector/initialState.ts
@@ -1,3 +1,5 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
import type { AgentBoundConnector, ConnectorWithTools } from './types';
export interface ConnectorState {
@@ -5,24 +7,52 @@ export interface ConnectorState {
* All agent-owned connectors across every agent in the current scope, for the
* unified connector-settings page. Distinct from `agentConnectors`
* (keyed per-agent, includes mounted rows) — this is the flat aggregate.
+ * Replica view of `agentBoundConnectorsReplica`.
*/
agentBoundConnectors: AgentBoundConnector[];
- /** Agent-scoped connectors (owned + mounted), keyed by agentId. */
+ /** Replica bookkeeping for `agentBoundConnectors`. */
+ agentBoundConnectorsReplica: ReplicaState<AgentBoundConnector[]>;
+ /** Agent-scoped connectors (owned + mounted), keyed by agentId. Replica view. */
agentConnectors: Record<string, ConnectorWithTools[]>;
+ /**
+ * Per-agent init gate of `agentConnectors`: a bucket only counts as loaded
+ * once it has been hydrated or filled, so an empty default never blocks the
+ * first hydrate.
+ */
agentConnectorsInit: Record<string, boolean>;
+ /** Replica bookkeeping for `agentConnectors`. */
+ agentConnectorsReplica: ReplicaState<ConnectorWithTools[]>;
connectorCreating: boolean;
+ /**
+ * Connectors of the active scope. Replica view of `connectorsReplica`, read
+ * by the tool picker, the settings pages and the agent profile.
+ */
connectors: ConnectorWithTools[];
+ /** Replica bookkeeping for `connectors`. */
+ connectorsReplica: ReplicaState<ConnectorWithTools[]>;
connectorSyncing: Record<string, boolean>;
+ /**
+ * Whether the agent-bound aggregate has been filled (from storage or the
+ * server). Gates the replica lens the same way `isConnectorsInit` does.
+ */
isAgentBoundInit: boolean;
+ /**
+ * Whether the connector list has been filled (from storage or the server).
+ * Gates the replica lens: an un-loaded list must read `undefined`, otherwise
+ * hydration would treat the empty default as a real value.
+ */
isConnectorsInit: boolean;
}
export const initialConnectorState: ConnectorState = {
agentBoundConnectors: [],
+ agentBoundConnectorsReplica: createReplicaState(),
agentConnectors: {},
agentConnectorsInit: {},
+ agentConnectorsReplica: createReplicaState(),
connectorCreating: false,
connectors: [],
+ connectorsReplica: createReplicaState(),
connectorSyncing: {},
isAgentBoundInit: false,
isConnectorsInit: false,
diff --git a/src/store/tool/slices/connector/projection.ts b/src/store/tool/slices/connector/projection.ts
new file mode 100644
index 00000000000..04c169ebcb7
--- /dev/null
+++ b/src/store/tool/slices/connector/projection.ts
@@ -0,0 +1,108 @@
+import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';
+
+import type { AgentBoundConnector, ConnectorWithTools } from './types';
+
+/**
+ * The connector lists are not paged, so each resource holds one entry per
+ * scope and every sync shares these params.
+ */
+export const CONNECTOR_LIST_KEY = 'all';
+
+/**
+ * Connectors of the active scope (`connectors`), read by the tool picker, the
+ * connector settings page and the agent profile. A local-first replica paints
+ * the persisted list on the first frame and lets the network confirm it.
+ */
+export const connectorsResource = defineReplica<
+ Record<string, never>,
+ ConnectorWithTools[],
+ ConnectorWithTools[]
+>({
+ key: () => CONNECTOR_LIST_KEY,
+ name: 'connectors',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Every agent-owned connector across agents (`agentBoundConnectors`), for the
+ * unified connector-settings page. Kept as its own resource because it is a
+ * heavier, server-enriched projection (`listAgentBound`) than the base list.
+ */
+export const agentBoundConnectorsResource = defineReplica<
+ Record<string, never>,
+ AgentBoundConnector[],
+ AgentBoundConnector[]
+>({
+ key: () => CONNECTOR_LIST_KEY,
+ name: 'agentBoundConnectors',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One agent's own connectors — owned plus mounted (`agentConnectors[agentId]`),
+ * for the Agent Tools tab and the profile editor.
+ */
+export const agentConnectorsResource = defineReplica<{ agentId: string }, ConnectorWithTools[]>({
+ key: ({ agentId }) => agentId,
+ name: 'agentConnectors',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Connectors are addressed by `id` across the tool store. */
+export const connectorsEntity: ReplicaEntityAdapter<ConnectorWithTools[], ConnectorWithTools> =
+ arrayEntity<ConnectorWithTools>((connector) => connector.id);
+
+export const agentBoundConnectorsEntity: ReplicaEntityAdapter<
+ AgentBoundConnector[],
+ AgentBoundConnector
+> = arrayEntity<AgentBoundConnector>((connector) => connector.id);
+
+/**
+ * `mcpStdioConfig` is a runtime-only field of the connector rows — the server
+ * ships it, but `ConnectorWithTools` doesn't declare it (consumers cast for it).
+ */
+interface ConnectorSecretFields {
+ mcpStdioConfig?: { args?: string[]; command?: string; env?: Record<string, string> };
+}
+
+/**
+ * Strip the connector secrets the list routes ship for the *edit form* before a
+ * projection is persisted.
+ *
+ * `list` / `listByAgent` / `listAgentBound` remove `credentials` and the OIDC
+ * client secret, but they spread the rest of the row through — so
+ * `mcpStdioConfig.env` (the API keys / tokens an MCP stdio process is launched
+ * with) and `metadata.customHeaders` (the headers an HTTP MCP endpoint is
+ * called with) reach the browser. That is deliberate: `CustomConnectorModal`
+ * pre-fills both from the list instead of calling `getForEdit`.
+ *
+ * Keeping them in memory is fine. Writing them to IndexedDB is not: persisted
+ * projection rows outlive the session, are partitioned per scope but never
+ * cleared on logout, and would turn an authenticated response into durable
+ * plaintext secret storage. So strip them on the way to storage only — the
+ * in-memory row keeps them, and the `ConnectorWithTools` type never promised
+ * them anyway.
+ */
+export const withoutConnectorSecrets = <T extends ConnectorWithTools>(connectors: T[]): T[] =>
+ connectors.map((connector) => {
+ const stdio = (connector as ConnectorWithTools & ConnectorSecretFields).mcpStdioConfig;
+ const metadata = connector.metadata;
+
+ const stripStdioEnv = !!stdio?.env && Object.keys(stdio.env).length > 0;
+ const stripCustomHeaders = !!metadata && 'customHeaders' in metadata;
+ if (!stripStdioEnv && !stripCustomHeaders) return connector;
+
+ const next = { ...connector };
+ if (stripStdioEnv) {
+ const { env: _env, ...stdioConfig } = stdio!;
+ (next as ConnectorWithTools & ConnectorSecretFields).mcpStdioConfig = stdioConfig;
+ }
+ if (stripCustomHeaders) {
+ const { customHeaders: _customHeaders, ...restMetadata } = metadata!;
+ next.metadata = restMetadata;
+ }
+ return next;
+ });
diff --git a/src/store/tool/slices/connector/replica.test.ts b/src/store/tool/slices/connector/replica.test.ts
new file mode 100644
index 00000000000..05fc4e318a6
--- /dev/null
+++ b/src/store/tool/slices/connector/replica.test.ts
@@ -0,0 +1,312 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The connector lists are `@lobechat/replica` resources: the persisted
+ * projection paints while the network confirms it, a permission write shows on
+ * the row immediately and rolls back when the server rejects it, and a
+ * confirmed delete drops the same connector from every list that holds it in
+ * one fan-out.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { cleanup } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';
+import { lambdaClient } from '@/libs/trpc/client';
+
+import { useToolStore } from '../../store';
+import { initialConnectorState } from './initialState';
+import {
+ agentBoundConnectorsResource,
+ agentConnectorsResource,
+ connectorsResource,
+} from './projection';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ connector: {
+ delete: { mutate: vi.fn() },
+ list: { query: vi.fn() },
+ listAgentBound: { query: vi.fn() },
+ listByAgent: { query: vi.fn() },
+ updateToolPermission: { mutate: vi.fn() },
+ },
+ },
+}));
+
+const listQuery = lambdaClient.connector.list.query as unknown as ReturnType<typeof vi.fn>;
+const listAgentBoundQuery = lambdaClient.connector.listAgentBound.query as unknown as ReturnType<
+ typeof vi.fn
+>;
+const listByAgentQuery = lambdaClient.connector.listByAgent.query as unknown as ReturnType<
+ typeof vi.fn
+>;
+const deleteMutation = lambdaClient.connector.delete.mutate as unknown as ReturnType<typeof vi.fn>;
+const updateToolPermissionMutation = lambdaClient.connector.updateToolPermission
+ .mutate as unknown as ReturnType<typeof vi.fn>;
+
+/** A connector with a single tool in it, enough to assert permissions on. */
+const connector = (id: string, permission = 'auto') => ({
+ id,
+ identifier: id,
+ tools: [{ id: `${id}-tool`, permission }],
+});
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const LIST_STORAGE_KEY = connectorsResource.storageKey({});
+const AGENT_BOUND_STORAGE_KEY = agentBoundConnectorsResource.storageKey({});
+const AGENT_STORAGE_KEY = agentConnectorsResource.storageKey({ agentId: 'a1' });
+
+const storageKeys = {
+ agents: AGENT_STORAGE_KEY,
+ bound: AGENT_BOUND_STORAGE_KEY,
+ list: LIST_STORAGE_KEY,
+};
+
+describe('connector slice replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`connector-user-${randomUUID()}:personal`);
+ resetCacheScopeBroadcast();
+ useToolStore.setState({ ...initialConnectorState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ Object.values(storageKeys).map((queryKey) =>
+ connectorsResource.storage!.remove({ queryKey, scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted list before the network answers', async () => {
+ await connectorsResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [connector('cached')], updatedAt: 1 },
+ );
+ listQuery.mockImplementation(pending);
+
+ void useToolStore.getState().fetchConnectors();
+
+ await vi.waitFor(() =>
+ expect(useToolStore.getState().connectors.map((c) => c.id)).toEqual(['cached']),
+ );
+ expect(useToolStore.getState().isConnectorsInit).toBe(true);
+ });
+
+ it('replaces the list with the server response and persists it', async () => {
+ listQuery.mockResolvedValue([connector('server-1')]);
+
+ await useToolStore.getState().fetchConnectors();
+
+ expect(useToolStore.getState().connectors.map((c) => c.id)).toEqual(['server-1']);
+ expect(useToolStore.getState().isConnectorsInit).toBe(true);
+ await vi.waitFor(async () =>
+ expect(
+ (await connectorsResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope }))?.data,
+ ).toEqual([connector('server-1')]),
+ );
+ });
+
+ it('never hydrates another identity’s persisted list', async () => {
+ await connectorsResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [connector('mine')], updatedAt: 1 },
+ );
+ useScope(`connector-user-${randomUUID()}:personal`);
+ listQuery.mockImplementation(pending);
+
+ void useToolStore.getState().fetchConnectors();
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(useToolStore.getState().connectors).toEqual([]);
+ expect(useToolStore.getState().isConnectorsInit).toBe(false);
+ });
+
+ // These resources have no `useSync` mount: nothing re-renders them on a scope
+ // switch, so the engine would keep the previous identity's views — and their
+ // init flags, which is what makes every gated consumer skip the fetch for the
+ // new scope.
+ it('drops every connector view when the cache scope changes', async () => {
+ listQuery.mockResolvedValue([connector('c1')]);
+ listAgentBoundQuery.mockResolvedValue([connector('c1')]);
+ listByAgentQuery.mockResolvedValue([connector('c1')]);
+
+ await useToolStore.getState().fetchConnectors();
+ await useToolStore.getState().fetchAgentBoundConnectors();
+ await useToolStore.getState().fetchAgentConnectors('a1');
+ expect(useToolStore.getState().connectors).toHaveLength(1);
+ expect(useToolStore.getState().agentBoundConnectors).toHaveLength(1);
+ expect(useToolStore.getState().agentConnectors.a1).toHaveLength(1);
+
+ const workspaceScope = `${scope.split(':')[0]}:ws-1`;
+ useScope(workspaceScope);
+ broadcastCacheScope(workspaceScope);
+
+ expect(useToolStore.getState().connectors).toEqual([]);
+ expect(useToolStore.getState().isConnectorsInit).toBe(false);
+ expect(useToolStore.getState().agentBoundConnectors).toEqual([]);
+ expect(useToolStore.getState().isAgentBoundInit).toBe(false);
+ expect(useToolStore.getState().agentConnectors).toEqual({});
+ expect(useToolStore.getState().agentConnectorsInit).toEqual({});
+ });
+
+ // The reset the broadcast performs is also folded into the engine's own
+ // commit, so a fetch that runs under a new scope without a broadcast (nothing
+ // mounted `useCacheScope`) still cannot replace into the old scope's view.
+ it('replaces a stale scope’s rows instead of merging into them', async () => {
+ listQuery.mockResolvedValue([connector('personal-row')]);
+ await useToolStore.getState().fetchConnectors();
+ expect(useToolStore.getState().connectors.map((c) => c.id)).toEqual(['personal-row']);
+
+ const workspaceScope = `${scope.split(':')[0]}:ws-1`;
+ useScope(workspaceScope);
+ listQuery.mockResolvedValue([connector('workspace-row')]);
+
+ await useToolStore.getState().fetchConnectors();
+
+ expect(useToolStore.getState().connectors.map((c) => c.id)).toEqual(['workspace-row']);
+ expect(useToolStore.getState().isConnectorsInit).toBe(true);
+ });
+
+ // The reported boot: a direct workspace URL hydrates the personal projection
+ // before the URL→store sync resolves the slug. The personal response that is
+ // still in flight gets dropped — but if the hydrated view (and the init flag
+ // it set) survived the switch, the workspace would keep painting the personal
+ // inventory and never load its own.
+ it('re-arms the workspace fetch after a personal-scope hydration', async () => {
+ await connectorsResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [connector('personal-stale')], updatedAt: 1 },
+ );
+ listQuery.mockImplementation(pending);
+
+ void useToolStore.getState().fetchConnectors();
+ await vi.waitFor(() =>
+ expect(useToolStore.getState().connectors.map((c) => c.id)).toEqual(['personal-stale']),
+ );
+
+ const workspaceScope = `${scope.split(':')[0]}:ws-1`;
+ useScope(workspaceScope);
+ broadcastCacheScope(workspaceScope);
+
+ // The gate is back to "not loaded", so the consumers gated on it fetch
+ // again, and nothing from the personal partition is left on screen.
+ expect(useToolStore.getState().isConnectorsInit).toBe(false);
+ expect(useToolStore.getState().connectors).toEqual([]);
+ });
+
+ it('never persists connector secrets, but keeps them in the in-memory row', async () => {
+ const withSecrets = {
+ ...connector('c1'),
+ mcpStdioConfig: { args: ['-y'], command: 'npx', env: { API_KEY: 'sk-live-secret' } },
+ metadata: { customHeaders: { Authorization: 'Bearer header-secret' }, description: 'kept' },
+ };
+ listQuery.mockResolvedValue([withSecrets]);
+
+ await useToolStore.getState().fetchConnectors();
+
+ // The edit form still pre-fills from the in-memory row.
+ const inMemory = useToolStore.getState().connectors[0] as typeof withSecrets;
+ expect(inMemory.mcpStdioConfig.env).toEqual({ API_KEY: 'sk-live-secret' });
+ expect(inMemory.metadata.customHeaders).toEqual({ Authorization: 'Bearer header-secret' });
+
+ const persisted = await vi.waitFor(async () => {
+ const row = await connectorsResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope });
+ expect(row?.data).toBeDefined();
+ return row!.data as unknown as Array<typeof withSecrets>;
+ });
+
+ expect('env' in persisted[0].mcpStdioConfig).toBe(false);
+ expect(persisted[0].metadata).toEqual({ description: 'kept' });
+ });
+
+ it('shows a permission change immediately and rolls it back when rejected', async () => {
+ listQuery.mockResolvedValue([connector('c1', 'auto')]);
+ await useToolStore.getState().fetchConnectors();
+
+ let rejectWrite!: (error: unknown) => void;
+ updateToolPermissionMutation.mockImplementation(
+ () => new Promise((_resolve, reject) => (rejectWrite = reject)),
+ );
+
+ const operation = useToolStore.getState().updateToolPermission('c1-tool', 'needs_approval');
+ // The overlay is visible before the server answers.
+ expect(useToolStore.getState().connectors[0].tools[0].permission).toBe('needs_approval');
+
+ rejectWrite(new Error('boom'));
+ await operation;
+ // The rejected write rebuilt the row from the server value.
+ expect(useToolStore.getState().connectors[0].tools[0].permission).toBe('auto');
+ });
+
+ it('keeps a deleted connector mounted until the server confirms, then drops it everywhere', async () => {
+ listQuery.mockResolvedValue([connector('c1')]);
+ listAgentBoundQuery.mockResolvedValue([connector('c1')]);
+ listByAgentQuery.mockResolvedValue([connector('c1')]);
+
+ await useToolStore.getState().fetchConnectors();
+ await useToolStore.getState().fetchAgentBoundConnectors();
+ await useToolStore.getState().fetchAgentConnectors('a1');
+ expect(useToolStore.getState().connectors).toHaveLength(1);
+ expect(useToolStore.getState().agentBoundConnectors).toHaveLength(1);
+ expect(useToolStore.getState().agentConnectors.a1).toHaveLength(1);
+
+ let resolveDelete!: (value: unknown) => void;
+ deleteMutation.mockImplementation(() => new Promise((resolve) => (resolveDelete = resolve)));
+ const operation = useToolStore.getState().deleteConnector('c1');
+ // Still mounted while the request is in flight: the detail pane reads this
+ // row, so an optimistic removal would blank it for the whole delete.
+ expect(useToolStore.getState().connectors).toHaveLength(1);
+ expect(useToolStore.getState().agentBoundConnectors).toHaveLength(1);
+ expect(useToolStore.getState().agentConnectors.a1).toHaveLength(1);
+
+ listQuery.mockResolvedValue([]);
+ listAgentBoundQuery.mockResolvedValue([]);
+ listByAgentQuery.mockResolvedValue([]);
+ resolveDelete(undefined);
+ await operation;
+ // Confirmed: one fan-out drops the row from all three views.
+ expect(useToolStore.getState().connectors).toHaveLength(0);
+ expect(useToolStore.getState().agentBoundConnectors).toHaveLength(0);
+ expect(useToolStore.getState().agentConnectors.a1).toHaveLength(0);
+ });
+
+ it('keeps a connector in every list when the delete is rejected', async () => {
+ listQuery.mockResolvedValue([connector('c1')]);
+ listAgentBoundQuery.mockResolvedValue([connector('c1')]);
+ listByAgentQuery.mockResolvedValue([connector('c1')]);
+
+ await useToolStore.getState().fetchConnectors();
+ await useToolStore.getState().fetchAgentBoundConnectors();
+ await useToolStore.getState().fetchAgentConnectors('a1');
+
+ deleteMutation.mockRejectedValue(new Error('boom'));
+
+ await expect(useToolStore.getState().deleteConnector('c1')).rejects.toThrow('boom');
+
+ expect(useToolStore.getState().connectors.map((c) => c.id)).toEqual(['c1']);
+ expect(useToolStore.getState().agentBoundConnectors.map((c) => c.id)).toEqual(['c1']);
+ expect(useToolStore.getState().agentConnectors.a1.map((c) => c.id)).toEqual(['c1']);
+ });
+});