π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(bot): move agent channel providers and platform catalog onto @lobechat/replica (#20651)
Arvin Xu63f6ead0b8ef
diff --git a/apps/desktop/src/main/services/__tests__/imessageBridgeSrv.test.ts b/apps/desktop/src/main/services/__tests__/imessageBridgeSrv.test.tsindex bf5b4ebb398..ac49d380e80 100644--- a/apps/desktop/src/main/services/__tests__/imessageBridgeSrv.test.ts+++ b/apps/desktop/src/main/services/__tests__/imessageBridgeSrv.test.ts@@ -1,5 +1,6 @@import { request } from 'node:http';+import { BOT_CREDENTIAL_MASK } from '@lobechat/const/bot';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -153,6 +154,51 @@ describe('ImessageBridgeService', () => {await service.stop();});+ it('keeps the stored webhook secret when an update carries the replica mask', async () => {+ const { service, store } = createService();+ await service.upsertConfig(config);++ // A cache-first save hands back the masked replica copy, not the secret.+ await service.upsertConfig({+ applicationId: 'home-mac-mini',+ blueBubblesServerUrl: 'http://127.0.0.1:5678',+ enabled: true,+ webhookSecret: BOT_CREDENTIAL_MASK,+ });++ expect(store.get('imessageBridgeConfigs')).toEqual([+ {+ applicationId: 'home-mac-mini',+ blueBubblesPassword: 'local-password',+ blueBubblesServerUrl: 'http://127.0.0.1:5678',+ enabled: true,+ webhookSecret: 'shared-secret',+ },+ ]);+ // The registered loopback webhook keeps using the real shared secret, so+ // forwarding to the cloud stays authenticated.+ expect(MockBlueBubblesApiClient.instances.at(-1)?.registerWebhook).toHaveBeenCalledWith(+ 'http://127.0.0.1:43210/webhooks/bluebubbles/home-mac-mini?secret=shared-secret',+ ['new-message'],+ );++ await service.stop();+ });++ it('refuses to persist a mask when no real secret is stored yet', async () => {+ const { service } = createService();++ await expect(+ service.upsertConfig({+ applicationId: 'home-mac-mini',+ blueBubblesPassword: 'local-password',+ blueBubblesServerUrl: 'http://127.0.0.1:1234',+ enabled: true,+ webhookSecret: BOT_CREDENTIAL_MASK,+ }),+ ).rejects.toThrow('webhookSecret is required');+ });+it('executes outbound iMessage sends from device-gateway message API calls', async () => {const { service } = createService();await service.upsertConfig(config);diff --git a/apps/desktop/src/main/services/imessageBridgeSrv.ts b/apps/desktop/src/main/services/imessageBridgeSrv.tsindex 0daee5b2d2f..50ce0e0b213 100644--- a/apps/desktop/src/main/services/imessageBridgeSrv.ts+++ b/apps/desktop/src/main/services/imessageBridgeSrv.ts@@ -7,6 +7,7 @@ import {type BlueBubblesSendOptions,type BlueBubblesWebhookEvent,} from '@lobechat/chat-adapter-imessage';+import { isMaskedBotCredential } from '@lobechat/const/bot';import type {ImessageBridgeConfig,ImessageBridgePublicConfig,@@ -216,12 +217,22 @@ export default class ImessageBridgeService extends ServiceModule {config.blueBubblesPassword?.trim() || existing?.blueBubblesPassword?.trim();if (!blueBubblesPassword) throw new Error('blueBubblesPassword is required');+ // `webhookSecret` is shared with the cloud provider, so the bridge and the+ // cloud must hold the same value. The renderer reads the provider through+ // the replica, whose at-rest copy masks credentials β a cache-first save+ // therefore hands us the mask, not the secret. Keep the real secret this+ // bridge already holds instead of persisting the placeholder, which would+ // make local webhook forwarding fail against the cloud.+ const webhookSecret = isMaskedBotCredential(config.webhookSecret)+ ? existing?.webhookSecret+ : config.webhookSecret;+return {applicationId: assertString(config.applicationId, 'applicationId'),blueBubblesPassword,blueBubblesServerUrl: assertString(config.blueBubblesServerUrl, 'blueBubblesServerUrl'),enabled: config.enabled,- webhookSecret: assertString(config.webhookSecret, 'webhookSecret'),+ webhookSecret: assertString(webhookSecret, 'webhookSecret'),};}diff --git a/packages/const/package.json b/packages/const/package.jsonindex 768c87d5f20..ff682e7357a 100644--- a/packages/const/package.json+++ b/packages/const/package.json@@ -5,6 +5,7 @@"exports": {".": "./src/index.ts","./apiKeyScope": "./src/apiKeyScope.ts",+ "./bot": "./src/bot.ts","./currency": "./src/currency.ts","./desktopGlobalShortcuts": "./src/desktopGlobalShortcuts.ts","./goal": "./src/goal.ts",diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 6141890f78e..f32e8471549 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -443,7 +443,7 @@ export const serverConfigKeys = {// ---- discover (marketplace) ---------------------------------------------// NOTE: discover/eval/ragEval/knowledgeBase/device/userMemory/agentKnowledge/-// agentBot/file prefixes are deliberately kept OUT of `CACHE_TIERS`+// file prefixes are deliberately kept OUT of `CACHE_TIERS`// (see localStorageProvider.ts) so this key-convergence introduces no new// persistence β they stay memory-only exactly as before.export const discoverKeys = {@@ -850,12 +850,6 @@ export const agentKnowledgeKeys = {),};-// ---- agent bot -----------------------------------------------------------export const agentBotKeys = {- platformDefinitions: def('agentBot:platformDefinitions', () => ['agentBot:platformDefinitions']),- providers: def('agentBot:providers', (agentId: string) => ['agentBot:providers', agentId]),-};-// ---- file ---------------------------------------------------------------export const fileKeys = {ttsFile: def('file:ttsFile', (messageId: string) => ['file:ttsFile', messageId]),@@ -1366,7 +1360,6 @@ export const matchDomain =*/export const swrKeys = {agent: agentConfigKeys,- agentBot: agentBotKeys,agentBuilder: agentBuilderKeys,agentDocument: agentDocumentSWRKeys,agentHome: agentHomeKeys,diff --git a/src/routes/(main)/agent/channel/channelLoader.ts b/src/routes/(main)/agent/channel/channelLoader.tsnew file mode 100644index 00000000000..57bae8484e0--- /dev/null+++ b/src/routes/(main)/agent/channel/channelLoader.ts@@ -0,0 +1,20 @@+import type { LoaderFunctionArgs } from 'react-router';++import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { useAgentStore } from '@/store/agent';++/**+ * Route loader for the agent channel surface (`/agent/:aid/channel`).+ *+ * Route loaders run before React commits the route: the only point where the+ * persisted channel data (an async IndexedDB read) can land before the channel+ * page paints its loading skeleton. See `preHydrateBotChannels`.+ */+export const channelDataLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {+ await settleWithin(+ useAgentStore.getState().preHydrateBotChannels(params.aid),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/routes/(main)/agent/channel/detail/formState.test.ts b/src/routes/(main)/agent/channel/detail/formState.test.tsindex ff672a28ced..fdd338e6687 100644--- a/src/routes/(main)/agent/channel/detail/formState.test.ts+++ b/src/routes/(main)/agent/channel/detail/formState.test.ts@@ -5,7 +5,9 @@ import type { FieldSchema } from '@/server/services/bot/platforms/types';import {extractSettingsDefaults,getChannelFormValues,+ mergeCredentialsForSave,mergeSettingsWithDefaults,+ shouldAdoptIncomingConfig,} from './formState';const slackSchema: FieldSchema[] = [@@ -111,6 +113,59 @@ describe('extractSettingsDefaults', () => {});});+describe('mergeCredentialsForSave', () => {+ it('carries a credential key the form does not mention', () => {+ // The persisted copy keeps every key, but a form that never registered a+ // field for one of them would drop it β the server replaces the blob+ // wholesale, so the carried mask is what stops the key being deleted.+ expect(+ mergeCredentialsForSave(+ { botId: 'β’β’β’β’β’β’β’β’', botToken: 'β’β’β’β’β’β’β’β’' },+ { botToken: 'β’β’β’β’β’β’β’β’' },+ ),+ ).toEqual({ botId: 'β’β’β’β’β’β’β’β’', botToken: 'β’β’β’β’β’β’β’β’' });+ });++ it('lets a form edit win over the config value', () => {+ expect(mergeCredentialsForSave({ botToken: 'β’β’β’β’β’β’β’β’' }, { botToken: 'rotated' })).toEqual({+ botToken: 'rotated',+ });+ });++ it('keeps clearing a credential meaningful', () => {+ // An explicit empty overrides the carried value and is then dropped, so the+ // server deletes the key instead of silently resurrecting it.+ expect(mergeCredentialsForSave({ botToken: 'β’β’β’β’β’β’β’β’' }, { botToken: '' })).toEqual({});+ });++ it('drops undefined values and tolerates a missing config', () => {+ expect(mergeCredentialsForSave(undefined, { botToken: undefined } as never)).toEqual({});+ });+});++describe('shouldAdoptIncomingConfig', () => {+ const provider = { id: 'provider-1', platform: 'wechat' };++ it('ignores a same-provider replacement while the form is dirty', () => {+ // The replica-backed background revalidation must not wipe a mid-edit form.+ expect(shouldAdoptIncomingConfig(provider, provider, true)).toBe(false);+ });++ it('adopts a same-provider replacement once the form is clean', () => {+ expect(shouldAdoptIncomingConfig(provider, provider, false)).toBe(true);+ });++ it('adopts a different provider even while the previous form was dirty', () => {+ expect(+ shouldAdoptIncomingConfig(provider, { id: 'provider-2', platform: 'wechat' }, true),+ ).toBe(true);+ });++ it('adopts on the first paint, when there is no previous config', () => {+ expect(shouldAdoptIncomingConfig(undefined, provider, true)).toBe(true);+ });+});+describe('mergeSettingsWithDefaults', () => {it('fills in schema defaults for missing keys', () => {expect(mergeSettingsWithDefaults(slackSchema, {})).toEqual({diff --git a/src/routes/(main)/agent/channel/detail/formState.ts b/src/routes/(main)/agent/channel/detail/formState.tsindex 648436dfdf4..9108ba5400d 100644--- a/src/routes/(main)/agent/channel/detail/formState.ts+++ b/src/routes/(main)/agent/channel/detail/formState.ts@@ -58,6 +58,45 @@ export const getChannelFormValues = (config: ChannelConfigFormState) => ({settings: normalizeSettings(config.settings),});+/**+ * Build the credential blob a save submits.+ *+ * The form is seeded from the persisted provider, which keeps every credential+ * *key* but replaces the values with masks (see `withoutBotProviderSecrets`).+ * The server replaces the credential blob wholesale on update, so any key the+ * form does not carry would be deleted on the way back β carry every key the+ * form leaves unmentioned from the config the form was seeded with. An explicit+ * empty (a field the user cleared) still wins and drops the key, so clearing a+ * credential keeps its meaning.+ */+export const mergeCredentialsForSave = (+ configCredentials: Record<string, string> | null | undefined,+ formCredentials: Record<string, string> | null | undefined,+): Record<string, string> =>+ Object.fromEntries(+ Object.entries({ ...configCredentials, ...formCredentials }).filter(+ ([, value]) => value !== undefined && value !== '',+ ),+ );++/**+ * Whether the form should adopt an incoming (revalidated) provider config.+ *+ * The provider list is replica-backed, so a revisit paints the persisted config+ * first and the live fetch replaces it in the background. Adopting that+ * background copy while the user is mid-edit would silently discard their+ * input, so a replacement of the *same* provider is ignored until the form is+ * clean again β after a save / discard, or when a different provider arrives.+ */+export const shouldAdoptIncomingConfig = (+ previous: { id?: string; platform?: string } | undefined,+ next: { id?: string; platform?: string } | undefined,+ isDirty: boolean,+): boolean => {+ const isSameProvider = previous?.id === next?.id && previous?.platform === next?.platform;+ return !(isSameProvider && isDirty);+};+/*** Extract default values from a platform's settings schema, in the same flat* shape used by the form (top-level keys + flattened nested object children,diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsxindex 2cabb162ca0..e3e275477e0 100644--- a/src/routes/(main)/agent/channel/detail/index.tsx+++ b/src/routes/(main)/agent/channel/detail/index.tsx@@ -22,7 +22,12 @@ import {import { keepPendingConnectResult, toTestResult } from './actionResults';import Body from './Body';import Footer from './Footer';-import { getChannelFormValues, mergeSettingsWithDefaults } from './formState';+import {+ getChannelFormValues,+ mergeCredentialsForSave,+ mergeSettingsWithDefaults,+ shouldAdoptIncomingConfig,+} from './formState';import { type ChannelPostSave, ChannelPostSaveContext } from './postSaveContext';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -252,11 +257,22 @@ const PlatformDetail = memo<PlatformDetailProps>(stopConnectPolling();}, [platformDef.id, stopConnectPolling]);- // Sync form with saved config+ // Sync form with saved config. The provider list is replica-backed, so on a+ // revisit the form paints the persisted config first and the live fetch+ // replaces it in the background. Adopting that background copy while the+ // user is mid-edit would silently discard their input, so a replacement of+ // the *same* provider is ignored until the form is clean again (after a+ // save / discard, or when a different provider arrives).+ const previousConfigRef = useRef<CurrentConfig | undefined>(undefined);useEffect(() => {+ const previous = previousConfigRef.current;+ previousConfigRef.current = currentConfig;++ if (!shouldAdoptIncomingConfig(previous, currentConfig, isDirty)) return;+form.reset(getFormValues(platformDef.schema, currentConfig));setIsDirty(false);- }, [currentConfig, form, platformDef.schema]);+ }, [currentConfig, form, platformDef.schema, isDirty]);useEffect(() => {if (!currentConfig?.enabled) {@@ -297,10 +313,11 @@ const PlatformDetail = memo<PlatformDetailProps>(settings: rawSettings = {},} = values;- // Strip undefined values from credentials (optional fields left empty by antd form)- const credentials = Object.fromEntries(- Object.entries(rawCredentials).filter(([, v]) => v !== undefined && v !== ''),- );+ // The form may be seeded from the credential-trimmed persisted provider,+ // so carry any credential key it does not mention from the config the+ // form was seeded with; the server replaces the blob wholesale and would+ // otherwise delete those keys. An explicitly cleared field still wins.+ const credentials = mergeCredentialsForSave(currentConfig?.credentials, rawCredentials);const settings = mergeSettingsWithDefaults(platformDef.schema,omitUndefinedValues(rawSettings),@@ -367,7 +384,8 @@ const PlatformDetail = memo<PlatformDetailProps>(setTestResult(undefined);try {- const { applicationId, credentials } = params;+ const { applicationId, credentials: authCredentials } = params;+ const credentials = mergeCredentialsForSave(currentConfig?.credentials, authCredentials);const settings = mergeSettingsWithDefaults(platformDef.schema,omitUndefinedValues(form.getValue('settings') || {}),diff --git a/src/routes/(main)/agent/channel/index.tsx b/src/routes/(main)/agent/channel/index.tsxindex 0a477846676..d0b7e56809f 100644--- a/src/routes/(main)/agent/channel/index.tsx+++ b/src/routes/(main)/agent/channel/index.tsx@@ -40,17 +40,19 @@ const ChannelContent = memo(() => {const { allowed: canEdit } = usePermission('edit_own_content');const {- data: platforms,isLoading: platformsLoading,error: platformsError,mutate: mutatePlatforms,} = useAgentStore((s) => s.useFetchPlatformDefinitions());const {- data: providers,isLoading: providersLoading,error: providersError,mutate: mutateProviders,} = useAgentStore((s) => s.useFetchBotProviders(aid));+ // The data lives in the replica views; the hooks above only orchestrate the+ // fetch (hydrate the persisted copy, then revalidate in the background).+ const platforms = useAgentStore((s) => s.botPlatformDefinitions);+ const providers = useAgentStore((s) => (aid ? s.botProvidersMap[aid] : undefined));const triggerRefreshAllBotStatuses = useAgentStore((s) => s.triggerRefreshAllBotStatuses);const enableImessage = useUserStore(labPreferSelectors.enableImessage);@@ -65,15 +67,20 @@ const ChannelContent = memo(() => {const isLoading = platformsLoading || providersLoading;const error = platformsError ?? providersError;- // Both fetches carry `fallbackData: []`, so a *failed* fetch leaves- // `platforms = []` and `allPlatforms` collapses to just the frontend-only- // `COMING_SOON_PLATFORMS` β `length > 0` stays true and the surface would- // render a plausible coming-soon-only catalog (every real / connected channel- // silently dropped). So "has data" is *not* the merged length: it's whether the- // real fetch actually yielded platforms. Gate on the raw fetched `platforms`- // (never the static merge) and require the providers fetch to have not errored,- // so a failed load branches to an error state before we merge the static half.- const hasData = (platforms?.length ?? 0) > 0 && !providersError;+ // A *failed* or still-empty platform fetch leaves `platforms` undefined, so+ // `allPlatforms` collapses to just the frontend-only `COMING_SOON_PLATFORMS`+ // β and the surface would render a plausible coming-soon-only catalog (every+ // real / connected channel silently dropped). So "has data" is *not* the merged+ // length: it's whether the real fetch actually yielded platforms. Gate on the+ // raw synced `platforms` (never the static merge).+ //+ // The providers fetch, though, is a replica: a *background* revalidate that+ // fails must not blank a hydrated first frame. Once the providers have a+ // settled value (local copy or network), a providers error is not fatal β the+ // grid renders from that value and reconciles behind it. It only falls through+ // to the error state when there is nothing settled for this agent either.+ const providersSettled = providers !== undefined;+ const hasData = (platforms?.length ?? 0) > 0 && (!providersError || providersSettled);// Merge server-side platforms with frontend-only coming-soon entries.// Coming-soon entries shadow a server-registered platform of the same id, so adiff --git a/src/spa/router/channelDataLoader.ts b/src/spa/router/channelDataLoader.tsnew file mode 100644index 00000000000..913cecb445a--- /dev/null+++ b/src/spa/router/channelDataLoader.ts@@ -0,0 +1,14 @@+import type { LoaderFunctionArgs } from 'react-router';++/**+ * Route-table entry for the agent channel pre-paint hydrate.+ *+ * The real loader imports the agent store. The route tables sit in the entry+ * chunk's static graph, so importing it directly would pull the store into the+ * first screen; resolving it on first use keeps it in the channel route's lazy+ * chunks, which load in parallel with this one.+ */+export const channelDataLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/agent/channel/channelLoader').then((module) =>+ module.channelDataLoader(args),+ );diff --git a/src/spa/router/channelDataLoader.wiring.test.ts b/src/spa/router/channelDataLoader.wiring.test.tsnew file mode 100644index 00000000000..37cfad64e7a--- /dev/null+++ b/src/spa/router/channelDataLoader.wiring.test.ts@@ -0,0 +1,45 @@+// @vitest-environment happy-dom+import type { RouteObject } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { channelDataLoader } from './channelDataLoader';+import { desktopRoutes } from './desktopRouter.config';++const loaderModule = vi.hoisted(() => ({ evaluated: false }));++// Evaluating the real loader means the agent store reached the entry chunk's+// first-screen graph.+vi.mock('@/routes/(main)/agent/channel/channelLoader', () => {+ loaderModule.evaluated = true;+ return { channelDataLoader: vi.fn(async () => null) };+});++const flatten = (routes: RouteObject[]): RouteObject[] =>+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);++describe('channel data loader wiring', () => {+ it('does not load the store-backed loader while the route tables load', () => {+ expect(loaderModule.evaluated).toBe(false);+ });++ it('pre-hydrates the channel data on both channel routes', () => {+ const channelRoutes = flatten(desktopRoutes).filter(+ (route) => route.path === 'channel' || route.path === 'channel/:platform',+ );++ // Both `channel` and `channel/:platform` carry it, in every route table copy.+ expect(new Set(channelRoutes.map((route) => route.path))).toEqual(+ new Set(['channel', 'channel/:platform']),+ );+ expect(channelRoutes.every((route) => route.loader === channelDataLoader)).toBe(true);+ });++ it('delegates to the real loader with the route args on first use', async () => {+ const { channelDataLoader: realLoader } =+ await import('@/routes/(main)/agent/channel/channelLoader');+ const args = { params: { aid: 'agt_1' } };++ await expect(channelDataLoader(args as never)).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalledWith(args);+ });+});diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 90cd8997f28..03934d74a4b 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -75,6 +75,7 @@ import {import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';+import { channelDataLoader } from '@/spa/router/channelDataLoader';import { pageListLoader } from '@/spa/router/pageListLoader';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';import { SettingsTabs } from '@/store/global/initialState';@@ -215,6 +216,7 @@ export const sharedMainAreaChildren: RouteObject[] = ['Desktop > Chat > Channel',),handle: { meta: agentChannelRouteMeta },+ loader: channelDataLoader,path: 'channel',},{@@ -223,6 +225,7 @@ export const sharedMainAreaChildren: RouteObject[] = ['Desktop > Chat > Channel Platform',),handle: { meta: agentChannelRouteMeta },+ loader: channelDataLoader,path: 'channel/:platform',},{diff --git a/src/store/agent/initialState.ts b/src/store/agent/initialState.tsindex c638e30068b..70907603f4e 100644--- a/src/store/agent/initialState.ts+++ b/src/store/agent/initialState.ts@@ -1,13 +1,19 @@import { type AgentSliceState } from './slices/agent';import { initialAgentSliceState } from './slices/agent';import { type AgentArtworkSliceState, initialAgentArtworkSliceState } from './slices/artwork';+import { type BotSliceState } from './slices/bot';+import { initialBotSliceState } from './slices/bot';import { type BuiltinAgentSliceState } from './slices/builtin';import { initialBuiltinAgentSliceState } from './slices/builtin';-export type AgentStoreState = AgentArtworkSliceState & AgentSliceState & BuiltinAgentSliceState;+export type AgentStoreState = AgentArtworkSliceState &+ AgentSliceState &+ BotSliceState &+ BuiltinAgentSliceState;export const initialState: AgentStoreState = {...initialAgentArtworkSliceState,...initialAgentSliceState,+ ...initialBotSliceState,...initialBuiltinAgentSliceState,};diff --git a/src/store/agent/slices/bot/action.test.ts b/src/store/agent/slices/bot/action.test.tsnew file mode 100644index 00000000000..f39aee4b7c3--- /dev/null+++ b/src/store/agent/slices/bot/action.test.ts@@ -0,0 +1,298 @@+/**+ * @vitest-environment happy-dom+ *+ * One agent's channel (bot) providers and the account-wide channel platform+ * catalog are replicas: the first frame paints the persisted copy, the network+ * only confirms, a mutation revalidates the affected agent's providers, and a+ * scope switch drops the previous identity's rows before the next paints.+ */+import { randomUUID } from 'node:crypto';++import { BOT_CREDENTIAL_MASK } from '@lobechat/const';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentBotProviderService } from '@/services/agentBotProvider';++import { useAgentStore } from '../../store';+import { initialBotSliceState } from './initialState';+import {+ type BotProviderItem,+ botProvidersResource,+ platformDefinitionsResource,+} from './projection';++vi.mock('@/services/agentBotProvider', () => ({+ agentBotProviderService: {+ connectBot: vi.fn(),+ create: vi.fn(),+ delete: vi.fn(),+ exportByAgentId: vi.fn(),+ feishuFetchOwnerId: vi.fn(),+ getByAgentId: vi.fn(),+ lineFetchBotInfo: vi.fn(),+ listPlatforms: vi.fn(),+ refreshRuntimeStatus: vi.fn(),+ refreshRuntimeStatusesByAgent: vi.fn(),+ testConnection: vi.fn(),+ update: vi.fn(),+ },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const provider = (id: string, platform = 'discord'): BotProviderItem => ({+ applicationId: `${id}-app`,+ credentials: {},+ enabled: true,+ id,+ platform,+});++const platformDef = (id: string) => ({ id }) as never;++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const AGENT_ID = 'agent-1';+const PROVIDERS_STORAGE_KEY = botProvidersResource.storageKey({ agentId: AGENT_ID });+const CATALOG_STORAGE_KEY = platformDefinitionsResource.storageKey({});++describe('bot replicas', () => {+ 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(`bot-user-${randomUUID()}:personal`);+ act(() => useAgentStore.setState(initialBotSliceState));+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) => [+ botProvidersResource.storage!.remove({ queryKey: PROVIDERS_STORAGE_KEY, scope: value }),+ platformDefinitionsResource.storage!.remove({+ queryKey: CATALOG_STORAGE_KEY,+ scope: value,+ }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted providers before the network answers', async () => {+ await botProvidersResource.storage!.set(+ { queryKey: PROVIDERS_STORAGE_KEY, scope },+ { data: [provider('bot-1')], updatedAt: 1 },+ );+ vi.mocked(agentBotProviderService.getByAgentId).mockImplementation(pending);++ const sync = renderHook(() => useAgentStore((s) => s.useFetchBotProviders)(AGENT_ID), {+ wrapper,+ });++ await waitFor(() =>+ expect(useAgentStore.getState().botProvidersMap[AGENT_ID]?.[0]?.id).toBe('bot-1'),+ );+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('masks every cleartext credential in the persisted copy but keeps them in memory', async () => {+ // A platform may hand a credential back in the clear β iMessage's+ // `webhookSecret` is public *and* the bearer secret inbound webhooks are+ // checked against β so the persisted copy must never carry a cleartext value.+ const imessage: BotProviderItem = {+ ...provider('bot-2', 'imessage'),+ credentials: { desktopDeviceId: 'dev-1', webhookSecret: 'shared-secret' },+ };+ vi.mocked(agentBotProviderService.getByAgentId).mockResolvedValue([imessage]);++ renderHook(() => useAgentStore((s) => s.useFetchBotProviders)(AGENT_ID), { wrapper });++ // The in-memory view keeps the real values, so an edit form can seed from it.+ await waitFor(() =>+ expect(useAgentStore.getState().botProvidersMap[AGENT_ID]?.[0]?.credentials).toEqual({+ desktopDeviceId: 'dev-1',+ webhookSecret: 'shared-secret',+ }),+ );+ // The persisted row masks every value β no bearer secret, and no cleartext+ // identifier, reaches disk.+ await waitFor(async () =>+ expect(+ (await botProvidersResource.storage!.get({ queryKey: PROVIDERS_STORAGE_KEY, scope }))?.data,+ ).toEqual([+ {+ ...provider('bot-2', 'imessage'),+ credentials: {+ desktopDeviceId: BOT_CREDENTIAL_MASK,+ webhookSecret: BOT_CREDENTIAL_MASK,+ },+ },+ ]),+ );+ });++ it('keeps every credential key β masked β so a save cannot delete the omitted ones', async () => {+ // WeChat provisions `botId`/`userId` through a QR handshake and declares them+ // public, so the server hands them back in the clear. The update replaces the+ // credential blob wholesale, so a persisted row that dropped them (or a form+ // that never carried them) would delete them on the next save.+ const wechat: BotProviderItem = {+ ...provider('bot-4', 'wechat'),+ credentials: { botId: 'bot-1', botToken: 'real-token', userId: 'user-1' },+ };+ vi.mocked(agentBotProviderService.getByAgentId).mockResolvedValue([wechat]);++ renderHook(() => useAgentStore((s) => s.useFetchBotProviders)(AGENT_ID), { wrapper });++ await waitFor(async () =>+ expect(+ (await botProvidersResource.storage!.get({ queryKey: PROVIDERS_STORAGE_KEY, scope }))?.data,+ ).toEqual([+ {+ ...provider('bot-4', 'wechat'),+ credentials: {+ botId: BOT_CREDENTIAL_MASK,+ botToken: BOT_CREDENTIAL_MASK,+ userId: BOT_CREDENTIAL_MASK,+ },+ },+ ]),+ );+ });++ it('pre-hydrates the catalog and this agentβs providers before any network', async () => {+ await botProvidersResource.storage!.set(+ { queryKey: PROVIDERS_STORAGE_KEY, scope },+ { data: [provider('bot-1')], updatedAt: 1 },+ );+ await platformDefinitionsResource.storage!.set(+ { queryKey: CATALOG_STORAGE_KEY, scope },+ { data: [platformDef('discord')], updatedAt: 1 },+ );+ vi.mocked(agentBotProviderService.getByAgentId).mockImplementation(pending);+ vi.mocked(agentBotProviderService.listPlatforms).mockImplementation(pending);++ await act(() => useAgentStore.getState().preHydrateBotChannels(AGENT_ID));++ expect(useAgentStore.getState().botProvidersMap[AGENT_ID]?.[0]?.id).toBe('bot-1');+ expect(useAgentStore.getState().botPlatformDefinitions?.[0]?.id).toBe('discord');+ });++ it('paints the persisted platform catalog before the network answers', async () => {+ await platformDefinitionsResource.storage!.set(+ { queryKey: CATALOG_STORAGE_KEY, scope },+ { data: [platformDef('discord')], updatedAt: 1 },+ );+ vi.mocked(agentBotProviderService.listPlatforms).mockImplementation(pending);++ const sync = renderHook(() => useAgentStore((s) => s.useFetchPlatformDefinitions)(), {+ wrapper,+ });++ await waitFor(() =>+ expect(useAgentStore.getState().botPlatformDefinitions?.[0]?.id).toBe('discord'),+ );+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the platform catalog with the server response', async () => {+ vi.mocked(agentBotProviderService.listPlatforms).mockResolvedValue([+ platformDef('slack'),+ platformDef('feishu'),+ ]);++ renderHook(() => useAgentStore((s) => s.useFetchPlatformDefinitions)(), { wrapper });++ await waitFor(() =>+ expect(useAgentStore.getState().botPlatformDefinitions?.map((item) => item.id)).toEqual([+ 'slack',+ 'feishu',+ ]),+ );+ });++ it('drops the previous identityβs providers before the next paints', async () => {+ vi.mocked(agentBotProviderService.getByAgentId).mockResolvedValue([provider('bot-1')]);+ const sync = renderHook(() => useAgentStore((s) => s.useFetchBotProviders)(AGENT_ID), {+ wrapper,+ });+ await waitFor(() => expect(useAgentStore.getState().botProvidersMap[AGENT_ID]).toHaveLength(1));++ vi.mocked(agentBotProviderService.getByAgentId).mockImplementation(pending);+ useScope(`bot-user-${randomUUID()}:personal`);+ sync.rerender();++ await waitFor(() => expect(useAgentStore.getState().botProvidersMap[AGENT_ID]).toBeUndefined());+ });++ describe('mutations', () => {+ const seed = async () => {+ vi.mocked(agentBotProviderService.getByAgentId).mockResolvedValue([+ provider('bot-1'),+ provider('bot-2'),+ ]);+ renderHook(() => useAgentStore((s) => s.useFetchBotProviders)(AGENT_ID), { wrapper });+ await waitFor(() =>+ expect(useAgentStore.getState().botProvidersMap[AGENT_ID]).toHaveLength(2),+ );+ };++ it('revalidates the agentβs providers after a delete', async () => {+ await seed();+ vi.mocked(agentBotProviderService.delete).mockResolvedValue({ success: true } as never);+ vi.mocked(agentBotProviderService.getByAgentId).mockResolvedValue([provider('bot-2')]);++ await act(() => useAgentStore.getState().deleteBotProvider('bot-1', AGENT_ID));++ await waitFor(() =>+ expect(useAgentStore.getState().botProvidersMap[AGENT_ID].map((item) => item.id)).toEqual([+ 'bot-2',+ ]),+ );+ });++ it('refreshes the active agent when no agent id is given', async () => {+ await seed();+ act(() => useAgentStore.setState({ activeAgentId: AGENT_ID }));+ vi.mocked(agentBotProviderService.getByAgentId).mockResolvedValue([provider('bot-3')]);++ await act(() => useAgentStore.getState().internal_refreshBotProviders());++ await waitFor(() =>+ expect(useAgentStore.getState().botProvidersMap[AGENT_ID]?.map((item) => item.id)).toEqual([+ 'bot-3',+ ]),+ );+ });+ });+});diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.tsindex 085233cb9b0..51e310e8077 100644--- a/src/store/agent/slices/bot/action.ts+++ b/src/store/agent/slices/bot/action.ts@@ -1,23 +1,51 @@-import { type SWRResponse } from 'swr';--import { mutate, useClientDataSWR } from '@/libs/swr';-import { agentBotKeys } from '@/libs/swr/keys';+import {+ cacheScope,+ createReplicaSlice,+ recordLens,+ type ReplicaLens,+ type ReplicaSyncResult,+} from '@/libs/replica';import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';import { agentBotProviderService } from '@/services/agentBotProvider';import { type StoreSetter } from '@/store/types';import type { BotRuntimeStatusSnapshot } from '@/types/botRuntimeStatus';import { type AgentStore } from '../../store';--export interface BotProviderItem {- applicationId: string;- credentials: Record<string, string>;- enabled: boolean;- id: string;- platform: string;- settings?: Record<string, unknown> | null;+import {+ type BotProviderItem,+ botProvidersResource,+ PLATFORM_DEFINITIONS_KEY,+ platformDefinitionsResource,+ withoutBotProviderSecrets,+} from './projection';++export type { BotProviderItem };++/** `useFetchBotProviders` / `useFetchPlatformDefinitions` result: replica flags plus the SWR-era aliases. */+export interface BotSyncResult extends ReplicaSyncResult {+ /** A request is in flight and there is nothing cached to show for this entry yet. */+ isLoading: boolean;+ /** Alias of `revalidate`. */+ mutate: () => Promise<unknown>;}+/** `botProvidersMap` is the view; the replica is its only writer. */+const botProvidersLens = recordLens<AgentStore, BotProviderItem[]>('botProvidersMap');++/**+ * The catalog is one value, not a keyed map, so it keeps its own flat field+ * (`botPlatformDefinitions`) as the replica view.+ */+const platformDefinitionsLens: ReplicaLens<AgentStore, SerializedPlatformDefinition[]> = {+ clear: () => ({ botPlatformDefinitions: undefined }),+ get: (state) => state.botPlatformDefinitions,+ keys: () => [PLATFORM_DEFINITIONS_KEY],+ set: (_state, _key, data) => ({ botPlatformDefinitions: data }),+};++/** The catalog fetch has no params; a stable empty object keeps the entry key constant. */+const PLATFORM_DEFINITIONS_PARAMS = {} as Record<string, never>;+type Setter = StoreSetter<AgentStore>;export const createBotSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>@@ -25,11 +53,35 @@ export const createBotSlice = (set: Setter, get: () => AgentStore, _api?: unknowexport class BotSliceActionImpl {readonly #get: () => AgentStore;+ readonly #platformDefinitions;+ readonly #providers;constructor(set: Setter, get: () => AgentStore, _api?: unknown) {void _api;- void set;this.#get = get;++ this.#providers = createReplicaSlice(botProvidersResource, {+ actionPrefix: 'botProviders',+ fetcher: async ({ agentId }) => agentBotProviderService.getByAgentId(agentId),+ get,+ set,+ stateKey: 'botProvidersReplica',+ // Cleartext credentials never reach disk: the server can hand one back in+ // the clear (iMessage's `webhookSecret` is an identifier *and* a bearer+ // secret), so the persisted row keeps only the masks. See+ // {@link withoutBotProviderSecrets}.+ toPersisted: withoutBotProviderSecrets,+ view: botProvidersLens,+ });++ this.#platformDefinitions = createReplicaSlice(platformDefinitionsResource, {+ actionPrefix: 'botPlatformDefinitions',+ fetcher: () => agentBotProviderService.listPlatforms(),+ get,+ set,+ stateKey: 'botPlatformDefinitionsReplica',+ view: platformDefinitionsLens,+ });}createBotProvider = async (params: {@@ -103,7 +155,7 @@ export class BotSliceActionImpl {/*** Kick off a background refresh of every provider's live gateway status.* Fire-and-forget: the list can render from cached statuses immediately,- * and we revalidate SWR once the server finishes updating Redis.+ * and we revalidate the replica once the server finishes updating Redis.*/triggerRefreshAllBotStatuses = (agentId: string) => {agentBotProviderService@@ -117,7 +169,32 @@ export class BotSliceActionImpl {internal_refreshBotProviders = async (agentId?: string) => {const id = agentId || this.#get().activeAgentId;if (!id) return;- await mutate(agentBotKeys.providers(id));+ await this.#providers.revalidate(id);+ };++ /**+ * Seed the persisted channel data β the account-wide platform catalog and this+ * agent's providers β before React commits the route.+ *+ * A route loader is the only point where the async (IndexedDB) read can land+ * *before* the channel surface paints, so its first frame is the local copy+ * instead of a loading skeleton. The mount-time `useSync` hydrate is a no-op+ * once these slots are filled, so the two never race.+ */+ preHydrateBotChannels = async (agentId?: string): Promise<boolean> => {+ const id = agentId || this.#get().activeAgentId;+ const scope = cacheScope.get();++ // The slots may still hold the previous identity's rows; drop them first.+ this.#platformDefinitions.ensureScope(scope);+ this.#providers.ensureScope(scope);++ const [catalog, providers] = await Promise.all([+ this.#platformDefinitions.hydrate(PLATFORM_DEFINITIONS_PARAMS, scope),+ id ? this.#providers.hydrate({ agentId: id }, scope) : Promise.resolve(false),+ ]);++ return catalog || providers;};updateBotProvider = async (@@ -134,20 +211,29 @@ export class BotSliceActionImpl {await this.internal_refreshBotProviders(agentId);};- useFetchBotProviders = (agentId?: string): SWRResponse<BotProviderItem[]> => {- return useClientDataSWR<BotProviderItem[]>(- agentId ? agentBotKeys.providers(agentId) : null,- async ([, id]: [string, string]) => agentBotProviderService.getByAgentId(id),- { fallbackData: [], revalidateOnFocus: false },- );+ /** Fetch orchestration only; read the list through `botProvidersMap[agentId]`. */+ useFetchBotProviders = (agentId?: string): BotSyncResult => {+ const sync = this.#providers.useSync(agentId ? { agentId } : null, {+ revalidateOnFocus: false,+ });+ return {+ ...sync,+ isLoading: sync.isValidating && !(agentId && this.#get().botProvidersMap[agentId]),+ mutate: () => sync.revalidate(),+ };};- useFetchPlatformDefinitions = (): SWRResponse<SerializedPlatformDefinition[]> => {- return useClientDataSWR<SerializedPlatformDefinition[]>(- agentBotKeys.platformDefinitions(),- () => agentBotProviderService.listPlatforms(),- { dedupingInterval: 300_000, fallbackData: [], revalidateOnFocus: false },- );+ /** Fetch orchestration only; read the catalog through `botPlatformDefinitions`. */+ useFetchPlatformDefinitions = (): BotSyncResult => {+ const sync = this.#platformDefinitions.useSync(PLATFORM_DEFINITIONS_PARAMS, {+ dedupingInterval: 300_000,+ revalidateOnFocus: false,+ });+ return {+ ...sync,+ isLoading: sync.isValidating && !this.#get().botPlatformDefinitions,+ mutate: () => sync.revalidate(),+ };};}diff --git a/src/store/agent/slices/bot/index.ts b/src/store/agent/slices/bot/index.tsindex 58d7a4daef8..18955a1c255 100644--- a/src/store/agent/slices/bot/index.ts+++ b/src/store/agent/slices/bot/index.ts@@ -1 +1,8 @@-export { type BotProviderItem, type BotSliceAction, createBotSlice } from './action';+export {+ type BotProviderItem,+ type BotSliceAction,+ type BotSyncResult,+ createBotSlice,+} from './action';+export type { BotSliceState } from './initialState';+export { initialBotSliceState } from './initialState';diff --git a/src/store/agent/slices/bot/initialState.ts b/src/store/agent/slices/bot/initialState.tsnew file mode 100644index 00000000000..0646a2eb4b2--- /dev/null+++ b/src/store/agent/slices/bot/initialState.ts@@ -0,0 +1,22 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';++import type { BotProviderItem } from './projection';++export interface BotSliceState {+ /** Server channel platform catalog (single entry), read by the channel page. */+ botPlatformDefinitions?: SerializedPlatformDefinition[];+ /** Replica bookkeeping of `botPlatformDefinitions`. */+ botPlatformDefinitionsReplica: ReplicaState<SerializedPlatformDefinition[]>;+ /** Replica view of each agent's channel providers, keyed by agent id. */+ botProvidersMap: Record<string, BotProviderItem[]>;+ /** Replica bookkeeping of `botProvidersMap`. */+ botProvidersReplica: ReplicaState<BotProviderItem[]>;+}++export const initialBotSliceState: BotSliceState = {+ botPlatformDefinitions: undefined,+ botPlatformDefinitionsReplica: createReplicaState(),+ botProvidersMap: {},+ botProvidersReplica: createReplicaState(),+};diff --git a/src/store/agent/slices/bot/projection.ts b/src/store/agent/slices/bot/projection.tsnew file mode 100644index 00000000000..611b4540bd8--- /dev/null+++ b/src/store/agent/slices/bot/projection.ts@@ -0,0 +1,88 @@+import { BOT_CREDENTIAL_MASK, isMaskedBotCredential } from '@lobechat/const';++import { defineReplica } from '@/libs/replica';+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';++/**+ * One channel (bot) provider row of an agent β the shape the channel settings+ * surface reads, keyed by agent id in {@link botProvidersResource}.+ */+export interface BotProviderItem {+ applicationId: string;+ credentials: Record<string, string>;+ enabled: boolean;+ id: string;+ platform: string;+ settings?: Record<string, unknown> | null;+}++export interface BotProvidersParams {+ agentId: string;+}++/**+ * The persisted shape of a provider row: every credential value is replaced by+ * the mask, and the *key set is kept whole*.+ *+ * `getByAgentId` masks the credentials it classifies as secret, but a platform+ * may publish a credential as an *identifier* and still have it authenticate+ * something β iMessage declares `webhookSecret` public because the user's own+ * desktop bridge reads it back and has no way to ask for it again, yet that same+ * value is the bearer secret inbound webhook requests are checked against. So+ * "what the server is willing to render in a live UI" is not the same question+ * as "what may sit in IndexedDB after the tab closes", and the frontend cannot+ * answer the second one from the masked payload alone.+ *+ * No cleartext value survives the write β a mask is not a secret. But the keys+ * do have to survive: the server replaces the credential blob wholesale on+ * update, so a persisted row that dropped the values the server left in the+ * clear (WeChat's `botId`/`userId`, Discord's `publicKey`) would submit an+ * incomplete blob on the next save and delete them. Keeping every key β masked β+ * lets the first frame identify what is configured and lets an untouched save+ * round-trip through `resolveMaskedCredentials`, which turns each mask back into+ * the stored value. An empty value stays empty so "not configured" remains+ * readable.+ */+export const withoutBotProviderSecrets = (providers: BotProviderItem[]): BotProviderItem[] =>+ providers.map((provider) => ({+ ...provider,+ credentials: Object.fromEntries(+ Object.entries(provider.credentials ?? {}).map(([key, value]) => [+ key,+ !value || isMaskedBotCredential(value) ? value : BOT_CREDENTIAL_MASK,+ ]),+ ),+ }));++/**+ * One agent's channel providers, one entry per agent. Persisted so a revisit+ * to the channel page paints the last known providers on the first frame and+ * reconciles with the server in the background. The persisted copy carries no+ * cleartext credential β see {@link withoutBotProviderSecrets}.+ */+export const botProvidersResource = defineReplica<BotProvidersParams, BotProviderItem[]>({+ key: ({ agentId }) => agentId,+ name: 'botProviders',+ storage: 'indexedDB',+ version: 1,+});++/** Entry key of the single, account-wide channel platform catalog. */+export const PLATFORM_DEFINITIONS_KEY = 'all';++/** The platform catalog has no identity of its own β one entry per scope. */+export type PlatformDefinitionsParams = Record<string, never>;++/**+ * The server's channel platform catalog. One entry per scope: it is the same+ * for every agent, so it never needs a per-agent key.+ */+export const platformDefinitionsResource = defineReplica<+ PlatformDefinitionsParams,+ SerializedPlatformDefinition[]+>({+ key: () => PLATFORM_DEFINITIONS_KEY,+ name: 'botPlatformDefinitions',+ storage: 'indexedDB',+ version: 1,+});