🤯 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(messenger): move Messenger and GitHub integration reads onto @lobechat/replica (#22787)
Arvin Xufdce3b2cbca1
diff --git a/src/features/Integrations/useGithubIntegration.replica.test.ts b/src/features/Integrations/useGithubIntegration.replica.test.tsnew file mode 100644index 00000000000..2b7580e0323--- /dev/null+++ b/src/features/Integrations/useGithubIntegration.replica.test.ts@@ -0,0 +1,140 @@+/**+ * @vitest-environment happy-dom+ *+ * The GitHub integration reads (config, identity, installations) are a local+ * replica: a reload paints the last connection before the network answers.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, 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 { AppIndexedDBStorage, cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { scmService } from '@/services/scm';++import { useGithubIntegration } from './useGithubIntegration';++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 deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+};++const CONFIG = { github: { appSlug: 'lobehub', enabled: true, installPath: '/install' } };+const IDENTITY = {+ avatarUrl: null,+ externalLogin: 'octocat',+ externalUserId: '1',+ provider: 'github',+};+const installation = (id: string, accountLogin: string) =>+ ({ accountLogin, id, installationId: id, repositories: [] }) as never;++// Same namespaces the integration replicas persist under (`replica:<name>:v<version>`).+const storages = {+ config: new AppIndexedDBStorage<unknown>({ namespace: 'replica:scmConfig:v1' }),+ identity: new AppIndexedDBStorage<unknown>({ namespace: 'replica:scmIdentity:v1' }),+ installations: new AppIndexedDBStorage<unknown>({ namespace: 'replica:scmInstallations:v1' }),+};++describe('useGithubIntegration local replica', () => {+ let scope = '';++ const persist = async (installations: unknown[]) => {+ const at = { queryKey: 'github', scope };+ await storages.config.set(at, { data: CONFIG, updatedAt: 1 });+ await storages.identity.set(at, { data: { identity: IDENTITY }, updatedAt: 1 });+ await storages.installations.set(at, { data: installations, updatedAt: 1 });+ };++ beforeEach(() => {+ // A fresh random scope per test: memory is dropped like on a cold boot.+ scope = `github-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ });++ afterEach(async () => {+ cleanup();+ for (const storage of Object.values(storages)) {+ await storage.remove({ queryKey: 'github', scope });+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ }+ vi.restoreAllMocks();+ });++ it('paints the persisted connection before the network answers, then refreshes it', async () => {+ await persist([installation('1', 'stored-org')]);+ const installations = deferred<never[]>();+ vi.spyOn(scmService, 'getConfig').mockResolvedValue(CONFIG as never);+ vi.spyOn(scmService, 'getIdentity').mockResolvedValue(IDENTITY as never);+ vi.spyOn(scmService, 'listInstallations').mockReturnValue(installations.promise as never);++ const { result } = renderHook(() => useGithubIntegration(), { wrapper });++ await waitFor(() => expect(result.current.isInitialLoading).toBe(false));+ expect(result.current.enabled).toBe(true);+ expect(result.current.identity?.externalLogin).toBe('octocat');+ expect(result.current.installations.map((item) => item.accountLogin)).toEqual(['stored-org']);++ await act(async () => installations.resolve([installation('2', 'fresh-org')]));+ await waitFor(() =>+ expect(result.current.installations.map((item) => item.accountLogin)).toEqual(['fresh-org']),+ );+ });++ it('keeps an empty restored copy loading until the server confirms it', async () => {+ await persist([]);+ const installations = deferred<never[]>();+ vi.spyOn(scmService, 'getConfig').mockResolvedValue(CONFIG as never);+ vi.spyOn(scmService, 'getIdentity').mockResolvedValue(IDENTITY as never);+ vi.spyOn(scmService, 'listInstallations').mockReturnValue(installations.promise as never);++ const { result } = renderHook(() => useGithubIntegration(), { wrapper });++ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(result.current.isInitialLoading).toBe(true);++ await act(async () => installations.resolve([]));+ await waitFor(() => expect(result.current.isInitialLoading).toBe(false));+ expect(result.current.enabled).toBe(false);+ });++ it('shares one request between the overview card and the detail page', async () => {+ vi.spyOn(scmService, 'getConfig').mockResolvedValue(CONFIG as never);+ vi.spyOn(scmService, 'getIdentity').mockResolvedValue(null as never);+ vi.spyOn(scmService, 'listInstallations').mockResolvedValue([] as never);++ const { result } = renderHook(() => [useGithubIntegration(), useGithubIntegration()], {+ wrapper,+ });++ await waitFor(() => expect(result.current[0].isInitialLoading).toBe(false));+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(scmService.getConfig).toHaveBeenCalledTimes(1);+ expect(scmService.getIdentity).toHaveBeenCalledTimes(1);+ expect(scmService.listInstallations).toHaveBeenCalledTimes(1);+ expect(result.current[1].identity).toBeNull();+ });+});diff --git a/src/features/Integrations/useGithubIntegration.ts b/src/features/Integrations/useGithubIntegration.tsindex ef4732bbb60..25eec4bacc4 100644--- a/src/features/Integrations/useGithubIntegration.ts+++ b/src/features/Integrations/useGithubIntegration.ts@@ -1,34 +1,27 @@-import useSWR from 'swr';--import { scmKeys } from '@/libs/swr/keys';-import { scmService } from '@/services/scm';+import { integrationActions, integrationSelectors, useIntegrationStore } from '@/store/integration';/**- * Everything the GitHub integration surfaces need, fetched once and shared- * by the overview card and the detail page. `enabled` is "at least one live+ * Everything the GitHub integration surfaces need, read once and shared by the+ * overview card and the detail page. A reload paints the last local copy and+ * revalidates in the background. `enabled` is "at least one live* installation", which is what the overview's Enabled section keys on.*/export const useGithubIntegration = () => {- const config = useSWR(scmKeys.config(), () => scmService.getConfig());- const identity = useSWR(scmKeys.identity('github'), () => scmService.getIdentity('github'));- const installations = useSWR(scmKeys.installations(null), () => scmService.listInstallations());-- const isInitialLoading =- config.data === undefined || installations.data === undefined || identity.data === undefined;- const error = config.error ?? installations.error ?? identity.error;- const mutate = () => {- void config.mutate();- void identity.mutate();- void installations.mutate();- };+ const { error } = integrationActions.useFetchGithub();+ const config = useIntegrationStore(integrationSelectors.scmConfig);+ const identity = useIntegrationStore(integrationSelectors.scmIdentity);+ const installations = useIntegrationStore(integrationSelectors.scmInstallations);+ const isSettled = useIntegrationStore(integrationSelectors.isGithubSettled);return {- config: config.data?.github,- enabled: (installations.data?.length ?? 0) > 0,+ config: config?.github,+ enabled: (installations?.length ?? 0) > 0,error,- identity: identity.data ?? null,- installations: installations.data ?? [],- isInitialLoading,- mutate,+ identity: identity?.identity ?? null,+ installations: installations ?? [],+ isInitialLoading: !isSettled,+ mutate: () => {+ void integrationActions.refreshGithub();+ },};};diff --git a/src/features/Messenger/AgentSelect.tsx b/src/features/Messenger/AgentSelect.tsxindex bb93a2d0026..f9f454aedfb 100644--- a/src/features/Messenger/AgentSelect.tsx+++ b/src/features/Messenger/AgentSelect.tsx@@ -4,11 +4,9 @@ import { agentDisplayName } from '@lobechat/types';import { Flexbox, Select, type SelectProps, Text } from '@lobehub/ui';import { memo, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import AgentAvatar from '@/components/AgentAvatar';-import { messengerKeys } from '@/libs/swr/keys';-import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';interface AgentSelectProps extends Omit<SelectProps<string>, 'options' | 'value' | 'onChange'> {/**@@ -27,16 +25,18 @@ const AgentSelect = memo<AgentSelectProps>(({ value, onChange, workspaceId, defaultToInbox, ...rest }) => {const { t: tCommon } = useTranslation('common');// Cascading fetch: agents are scoped to the selected `workspaceId` (or- // personal when null). The scope is part of the SWR key so switching scope- // refetches the right list.- const agentsSWR = useSWR(messengerKeys.agentsForBinding(workspaceId), () =>- messengerService.listAgentsForBinding(workspaceId),- );+ // personal when null), one replica entry per scope, so switching scope+ // reads the right list and a reload paints it from the local copy.+ const scopeId = workspaceId ?? null;+ const agentsSync = messengerActions.useFetchBindingAgents(scopeId);+ const agents = useMessengerStore(messengerSelectors.bindingAgents(scopeId));+ const isSettled = useMessengerStore(messengerSelectors.isBindingAgentsSettled(scopeId));+ const isConfirmed = useMessengerStore(messengerSelectors.isBindingAgentsConfirmed(scopeId));const defaultAgentTitle = tCommon('defaultSession');const options = useMemo(() =>- (agentsSWR.data ?? []).map((agent) => {+ (agents ?? []).map((agent) => {const title = agentDisplayName(agent, defaultAgentTitle);return {label: (@@ -56,13 +56,15 @@ const AgentSelect = memo<AgentSelectProps>(value: agent.id,};}),- [agentsSWR.data, defaultAgentTitle],+ [agents, defaultAgentTitle],);// Inbox (LobeAI) agent of the current scope, pinned to the top server-side.+ // Defaulting writes the pick to the server, so it waits for the server's+ // list rather than a restored copy that may be stale.const inboxAgentId = useMemo(- () => (agentsSWR.data ?? []).find((agent) => agent.isInbox)?.id,- [agentsSWR.data],+ () => (isConfirmed ? agents?.find((agent) => agent.isInbox)?.id : undefined),+ [agents, isConfirmed],);// When asked to default to the scope's inbox and nothing is selected, select@@ -78,7 +80,7 @@ const AgentSelect = memo<AgentSelectProps>(return (<Select- loading={agentsSWR.isLoading}+ loading={!isSettled && !agentsSync.error}options={options}value={value ?? null}onChange={(next) => onChange?.((next as string | null) ?? undefined)}diff --git a/src/features/Messenger/IntegrationDetail/Discord.tsx b/src/features/Messenger/IntegrationDetail/Discord.tsxindex bafd5caddc6..8699e3d4933 100644--- a/src/features/Messenger/IntegrationDetail/Discord.tsx+++ b/src/features/Messenger/IntegrationDetail/Discord.tsx@@ -41,15 +41,10 @@ const DiscordDetail = memo<DiscordDetailProps>(({ appId, botUsername, name, onBaconst data = useMessengerData('discord');const { handleSetActive, handleUnlink } = useLinkActions({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,name,platform: 'discord',});- const disconnectInstallation = useDisconnectInstallation({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,- });+ const disconnectInstallation = useDisconnectInstallation();const handleDisconnectInstallation = (id: string) =>canEdit &&diff --git a/src/features/Messenger/IntegrationDetail/Linq.tsx b/src/features/Messenger/IntegrationDetail/Linq.tsxindex 9fa780a8a0f..14ebc657c4d 100644--- a/src/features/Messenger/IntegrationDetail/Linq.tsx+++ b/src/features/Messenger/IntegrationDetail/Linq.tsx@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import { usePermission } from '@/hooks/usePermission';import { messengerService } from '@/services/messenger';+import { messengerActions } from '@/store/messenger';import { getMessengerErrorMessage } from '../i18n';import { MessengerPushSection } from './MessengerPush';@@ -282,8 +283,6 @@ const LinqDetail = memo<LinqDetailProps>(({ name, onBack }) => {const { allowed: canEdit } = usePermission('edit_own_content');const data = useMessengerData('linq');const { handleSetActive, handleUnlink } = useLinkActions({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,name,platform: 'linq',});@@ -296,7 +295,7 @@ const LinqDetail = memo<LinqDetailProps>(({ name, onBack }) => {const link = data.links[0];const handleLinked = async () => {- await data.linksMutate();+ await messengerActions.refreshAfterConnect();toast.success(t('messenger.linq.connected'));};diff --git a/src/features/Messenger/IntegrationDetail/MessengerPush.tsx b/src/features/Messenger/IntegrationDetail/MessengerPush.tsxindex d6a6f599a56..39a68e3772a 100644--- a/src/features/Messenger/IntegrationDetail/MessengerPush.tsx+++ b/src/features/Messenger/IntegrationDetail/MessengerPush.tsx@@ -4,17 +4,14 @@ import { Alert, Block, Button, Flexbox, Icon, Input, Select, Text, toast } fromimport { SendIcon } from 'lucide-react';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';-import { messengerKeys } from '@/libs/swr/keys';-import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import type { MessengerPlatform } from '../constants';import { getMessengerErrorMessage, getMessengerQueuedToast } from '../i18n';import { MessengerPushWindowState } from './MessengerPushWindowState';import { styles } from './shared';-const PUSH_WINDOW_REFRESH_INTERVAL = 5000;const PUSH_WINDOW_DEFAULT_MAX_SENDS = 10;export interface MessengerPushTarget {@@ -53,16 +50,9 @@ export const MessengerPushSection = memo<MessengerPushSectionProps>(}}, [targets, tenantId]);- const windowSWR = useSWR(- messengerKeys.pushWindow(platform, tenantId),- () => messengerService.getMessengerPushWindow(platform, tenantId),- {- refreshInterval: platform === 'wechat' ? PUSH_WINDOW_REFRESH_INTERVAL : 0,- refreshWhenHidden: false,- refreshWhenOffline: false,- },- );- const status = windowSWR.data;+ const windowSync = messengerActions.useFetchPushWindow({ platform, tenantId });+ // Live status, never restored from disk: undefined until the server answers.+ const status = useMessengerStore(messengerSelectors.pushWindow({ platform, tenantId }));const canPush = status?.deliverability === 'always' ? status.linked : !!status?.windowOpen;@@ -72,7 +62,7 @@ export const MessengerPushSection = memo<MessengerPushSectionProps>(setSending(true);try {- const result = await messengerService.sendMessengerPush({+ const result = await messengerActions.sendPush({content: text,platform,tenantId,@@ -103,7 +93,6 @@ export const MessengerPushSection = memo<MessengerPushSectionProps>(toast.warning(t('messenger.push.unavailableToast'));}}- await windowSWR.mutate();} catch (error) {toast.error(getMessengerErrorMessage(error, t, 'messenger.push.unavailableToast'));} finally {@@ -137,10 +126,12 @@ export const MessengerPushSection = memo<MessengerPushSectionProps>({t('messenger.push.title')}</Text><MessengerPushWindowState- error={windowSWR.error}+ error={windowSync.error}name={name}status={status}- onRetry={() => windowSWR.mutate()}+ onRetry={() => {+ void windowSync.revalidate();+ }}/></Flexbox></Flexbox>diff --git a/src/features/Messenger/IntegrationDetail/Slack.tsx b/src/features/Messenger/IntegrationDetail/Slack.tsxindex e91a7e04bc8..3862187c792 100644--- a/src/features/Messenger/IntegrationDetail/Slack.tsx+++ b/src/features/Messenger/IntegrationDetail/Slack.tsx@@ -35,15 +35,10 @@ const SlackDetail = memo<SlackDetailProps>(({ appId, botUsername, name, onBack }const data = useMessengerData('slack');const { handleSetActive, handleUnlink } = useLinkActions({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,name,platform: 'slack',});- const disconnectInstallation = useDisconnectInstallation({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,- });+ const disconnectInstallation = useDisconnectInstallation();// For Slack, disconnecting an install row freezes the workspace's bot —// dispatch is token-gated, so removing the install effectively kills thediff --git a/src/features/Messenger/IntegrationDetail/Telegram.tsx b/src/features/Messenger/IntegrationDetail/Telegram.tsxindex de067cd63e3..b06b445aa8e 100644--- a/src/features/Messenger/IntegrationDetail/Telegram.tsx+++ b/src/features/Messenger/IntegrationDetail/Telegram.tsx@@ -36,8 +36,6 @@ const TelegramDetail = memo<TelegramDetailProps>(({ appId, botUsername, name, onconst data = useMessengerData('telegram');const { handleSetActive, handleUnlink } = useLinkActions({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,name,platform: 'telegram',});diff --git a/src/features/Messenger/IntegrationDetail/Wechat.test.tsx b/src/features/Messenger/IntegrationDetail/Wechat.test.tsxindex 50fbed4d1b3..8a1f23504e1 100644--- a/src/features/Messenger/IntegrationDetail/Wechat.test.tsx+++ b/src/features/Messenger/IntegrationDetail/Wechat.test.tsx@@ -11,7 +11,7 @@ const messengerServiceMocks = vi.hoisted(() => ({pollWechatQrSession: vi.fn(),sendMessengerPush: vi.fn(),}));-const useSWRMock = vi.hoisted(() => vi.fn());+const pushWindowMock = vi.hoisted(() => vi.fn());vi.mock('@lobehub/ui', async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>();@@ -101,7 +101,14 @@ vi.mock('react-i18next', () => ({}),}));-vi.mock('swr', () => ({ default: useSWRMock }));+vi.mock('@/store/messenger', () => ({+ messengerActions: {+ sendPush: (params: unknown) => messengerServiceMocks.sendMessengerPush(params),+ useFetchPushWindow: () => ({ error: undefined, revalidate: vi.fn() }),+ },+ messengerSelectors: { pushWindow: () => () => pushWindowMock() },+ useMessengerStore: (selector: (state: object) => unknown) => selector({}),+}));vi.mock('@/components/AsyncError', () => ({ default: () => null }));vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({@@ -152,17 +159,14 @@ describe('MessengerPushSection', () => {beforeEach(() => {vi.clearAllMocks();messengerServiceMocks.sendMessengerPush.mockResolvedValue({ status: 'sent' });- useSWRMock.mockReturnValue({- data: {- deliverability: 'windowed',- expiresInSeconds: 3600,- linked: true,- maxSends: 10,- queued: 0,- remaining: 9,- windowOpen: true,- },- mutate: vi.fn(),+ pushWindowMock.mockReturnValue({+ deliverability: 'windowed',+ expiresInSeconds: 3600,+ linked: true,+ maxSends: 10,+ queued: 0,+ remaining: 9,+ windowOpen: true,});});@@ -177,17 +181,14 @@ describe('MessengerPushSection', () => {});it('renders the send-window description while the window is closed', () => {- useSWRMock.mockReturnValue({- data: {- deliverability: 'windowed',- expiresInSeconds: null,- linked: true,- maxSends: 10,- queued: 0,- remaining: 0,- windowOpen: false,- },- mutate: vi.fn(),+ pushWindowMock.mockReturnValue({+ deliverability: 'windowed',+ expiresInSeconds: null,+ linked: true,+ maxSends: 10,+ queued: 0,+ remaining: 0,+ windowOpen: false,});render(<MessengerPushSection name="WeChat" platform="wechat" />);@@ -197,17 +198,14 @@ describe('MessengerPushSection', () => {});it('renders an always-available state for non-windowed platforms', () => {- useSWRMock.mockReturnValue({- data: {- deliverability: 'always',- expiresInSeconds: null,- linked: true,- maxSends: 0,- queued: 0,- remaining: 0,- windowOpen: true,- },- mutate: vi.fn(),+ pushWindowMock.mockReturnValue({+ deliverability: 'always',+ expiresInSeconds: null,+ linked: true,+ maxSends: 0,+ queued: 0,+ remaining: 0,+ windowOpen: true,});render(<MessengerPushSection name="Telegram" platform="telegram" />);@@ -217,17 +215,14 @@ describe('MessengerPushSection', () => {});it('sends to the selected Slack workspace tenant', async () => {- useSWRMock.mockReturnValue({- data: {- deliverability: 'always',- expiresInSeconds: null,- linked: true,- maxSends: 0,- queued: 0,- remaining: 0,- windowOpen: true,- },- mutate: vi.fn(),+ pushWindowMock.mockReturnValue({+ deliverability: 'always',+ expiresInSeconds: null,+ linked: true,+ maxSends: 0,+ queued: 0,+ remaining: 0,+ windowOpen: true,});render(diff --git a/src/features/Messenger/IntegrationDetail/Wechat.tsx b/src/features/Messenger/IntegrationDetail/Wechat.tsxindex 091b9584e81..256fc259fbf 100644--- a/src/features/Messenger/IntegrationDetail/Wechat.tsx+++ b/src/features/Messenger/IntegrationDetail/Wechat.tsx@@ -20,6 +20,7 @@ import AsyncError from '@/components/AsyncError';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import { messengerService } from '@/services/messenger';+import { messengerActions } from '@/store/messenger';import { getMessengerErrorMessage } from '../i18n';import { MessengerPushSection } from './MessengerPush';@@ -254,8 +255,6 @@ const WechatDetail = memo<WechatDetailProps>(({ access, name, onBack }) => {const [rescanning, setRescanning] = useState(false);const data = useMessengerData('wechat');const { handleSetActive, handleUnlink } = useLinkActions({- installationsMutate: data.installationsMutate,- linksMutate: data.linksMutate,name,platform: 'wechat',});@@ -273,7 +272,7 @@ const WechatDetail = memo<WechatDetailProps>(({ access, name, onBack }) => {const sessionExpired = installation?.runtime?.errorCode === 'session_expired';const handleConfirmed = async () => {- await Promise.all([data.linksMutate(), data.installationsMutate()]);+ await messengerActions.refreshAfterConnect();setRescanning(false);toast.success(t('messenger.wechat.connected'));};diff --git a/src/features/Messenger/IntegrationDetail/shared.test.tsx b/src/features/Messenger/IntegrationDetail/shared.test.tsxindex 550891efee7..923456d2fe0 100644--- a/src/features/Messenger/IntegrationDetail/shared.test.tsx+++ b/src/features/Messenger/IntegrationDetail/shared.test.tsx@@ -1,8 +1,6 @@import { render, renderHook, screen, within } from '@testing-library/react';import type { ReactNode } from 'react';-import { describe, expect, it, vi } from 'vitest';--import { messengerKeys } from '@/libs/swr/keys';+import { afterEach, describe, expect, it, vi } from 'vitest';import { useLinkActions, UserAgentConnection } from './shared';@@ -26,11 +24,13 @@ vi.mock('@lobehub/ui', async (importOriginal) => {Select: ({classNames,options,+ value,}: {classNames?: { value?: string };options: { label: ReactNode; value: string }[];+ value?: string;}) => (- <div data-testid="scope-select" data-value-class={classNames?.value}>+ <div data-testid="scope-select" data-value={value} data-value-class={classNames?.value}>{options.map((option) => (<div data-testid={`scope-option-${option.value}`} key={option.value}>{option.label}@@ -96,20 +96,24 @@ vi.mock('react-i18next', () => ({}),}));-vi.mock('swr', () => ({- default: (key: unknown) => ({- data:- Array.isArray(key) && key[0] === messengerKeys.bindingScopes.root- ? [{ avatar: 'workspace-avatar', id: 'workspace-1', name: 'love' }]- : undefined,- isLoading: false,- }),-}));+const messengerState = {+ bindingScopes: [{ avatar: 'workspace-avatar', id: 'workspace-1', name: 'love' }],+ linksConfirmed: true,+};-vi.mock('@/services/messenger', () => ({- messengerService: {- listBindingScopes: vi.fn(),+vi.mock('@/store/messenger', () => ({+ messengerActions: {+ setActiveAgent: vi.fn(),+ uninstallInstallation: vi.fn(),+ unlink: vi.fn(),+ useFetchBindingScopes: vi.fn(),},+ messengerSelectors: {+ bindingScopes: (state: typeof messengerState) => state.bindingScopes,+ isLinksConfirmed: (state: typeof messengerState) => state.linksConfirmed,+ },+ useMessengerStore: (selector: (state: typeof messengerState) => unknown) =>+ selector(messengerState),}));vi.mock('@/store/serverConfig', () => ({@@ -192,12 +196,57 @@ describe('Messenger UserAgentConnection', () => {});});+describe('Messenger UserAgentConnection with a restored link', () => {+ const restoredLink = {+ activeAgentId: 'agt_workspace',+ platformUserId: 'platform-user',+ platformUsername: 'platform-name',+ workspaceId: 'workspace-1' as string | null,+ };++ afterEach(() => {+ messengerState.linksConfirmed = true;+ });++ it('moves the scope picker to the scope the server link is bound to', () => {+ const { rerender } = render(+ <UserAgentConnection link={restoredLink} onSetActive={vi.fn()} onUnlink={vi.fn()} />,+ );+ expect(screen.getByTestId('scope-select')).toHaveAttribute('data-value', 'workspace-1');++ // Revalidation: the binding moved to the personal scope since the copy was saved.+ rerender(+ <UserAgentConnection+ link={{ ...restoredLink, activeAgentId: 'agt_personal', workspaceId: null }}+ onSetActive={vi.fn()}+ onUnlink={vi.fn()}+ />,+ );++ expect(screen.getByTestId('scope-select')).toHaveAttribute('data-value', 'personal');+ // The picker shows the link's own agent, so nothing is auto-defaulted over it.+ expect(screen.getByTestId('agent-select')).toHaveAttribute('data-default-to-inbox', 'false');+ });++ it('does not default the binding to an inbox from a link the server has not confirmed', () => {+ messengerState.linksConfirmed = false;++ render(+ <UserAgentConnection+ link={{ ...restoredLink, activeAgentId: null, workspaceId: null }}+ onSetActive={vi.fn()}+ onUnlink={vi.fn()}+ />,+ );++ expect(screen.getByTestId('agent-select')).toHaveAttribute('data-default-to-inbox', 'false');+ });+});+describe('useLinkActions handleUnlink', () => {const renderActions = (platform: 'wechat' | 'telegram', name: string) =>renderHook(() =>useLinkActions({- installationsMutate: vi.fn(async () => undefined),- linksMutate: vi.fn(async () => undefined),name,platform,}),diff --git a/src/features/Messenger/IntegrationDetail/shared.tsx b/src/features/Messenger/IntegrationDetail/shared.tsxindex 200a0a6062a..957f4f035a9 100644--- a/src/features/Messenger/IntegrationDetail/shared.tsx+++ b/src/features/Messenger/IntegrationDetail/shared.tsx@@ -16,11 +16,9 @@ import { ArrowLeftIcon, CheckCircle2Icon, Trash2Icon, UserIcon } from 'lucide-reimport type { ReactNode } from 'react';import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import { usePermission } from '@/hooks/usePermission';-import { messengerKeys } from '@/libs/swr/keys';-import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -239,12 +237,20 @@ export const UserAgentConnection = memo<UserAgentConnectionProps>(// filters the agent list below. The active scope is persisted server-side// only when an agent is chosen (it derives the workspace from the agent).// `PERSONAL_SCOPE` is the sentinel for personal (null).- const scopesSWR = useSWR(enableWorkspaceScopes ? messengerKeys.bindingScopes() : null, () =>- messengerService.listBindingScopes(),- );- const [scope, setScope] = useState<string>(- enableWorkspaceScopes ? (link.workspaceId ?? PERSONAL_SCOPE) : PERSONAL_SCOPE,- );+ messengerActions.useFetchBindingScopes(enableWorkspaceScopes);+ const bindingScopes = useMessengerStore(messengerSelectors.bindingScopes);+ const linkScope = enableWorkspaceScopes ? (link.workspaceId ?? PERSONAL_SCOPE) : PERSONAL_SCOPE;+ const [scope, setScope] = useState<string>(linkScope);+ // A link painted from the local copy may name an older binding scope. When+ // the server's link moves to another scope, the picker follows it, so the+ // agent below is read (and defaulted) in the scope the link is bound to.+ const [syncedLinkScope, setSyncedLinkScope] = useState(linkScope);+ if (syncedLinkScope !== linkScope) {+ setSyncedLinkScope(linkScope);+ setScope(linkScope);+ }+ // Defaulting to the inbox writes the binding: never from a restored link.+ const isLinksConfirmed = useMessengerStore(messengerSelectors.isLinksConfirmed);const userAvatar = useUserStore(userProfileSelectors.userAvatar);const userDisplayName = useUserStore(userProfileSelectors.displayUserName);const userFullName = useUserStore(userProfileSelectors.fullName);@@ -261,9 +267,9 @@ export const UserAgentConnection = memo<UserAgentConnectionProps>(personalAvatar: userAvatar,personalLabel,personalTagLabel: t('messenger.scopePersonalTag', { defaultValue: 'personal' }),- workspaces: scopesSWR.data,+ workspaces: enableWorkspaceScopes ? bindingScopes : undefined,});- }, [scopesSWR.data, t, userAvatar, userDisplayName, userFullName]);+ }, [bindingScopes, enableWorkspaceScopes, t, userAvatar, userDisplayName, userFullName]);const scopeWorkspaceId = scope === PERSONAL_SCOPE ? null : scope;const linkIsActiveScope = scopeWorkspaceId === (link.workspaceId ?? null);@@ -274,7 +280,7 @@ export const UserAgentConnection = memo<UserAgentConnectionProps>(}, [enableWorkspaceScopes, scope]);// Optimistic selection for the currently-selected scope. Persisting the- // active agent does a server round-trip plus a `linksMutate()` refetch, so+ // active agent waits for the server to adopt the pick into the link, so// without this the dropdown only reflects the new pick once both finish.// `pending` mirrors the user's choice immediately and is cleared once the// link data catches up. Scoped by workspace so it only applies while the@@ -343,7 +349,7 @@ export const UserAgentConnection = memo<UserAgentConnectionProps>(<AgentSelect// Default to the scope's inbox agent whenever the selected scope has// no active Agent. This also repairs historical agent-less links.- defaultToInbox={canEdit && !pendingForScope && !activeAgentId}+ defaultToInbox={canEdit && isLinksConfirmed && !pendingForScope && !activeAgentId}disabled={!canEdit}placeholder={t('messenger.activeAgentPlaceholder')}value={activeAgentId ?? undefined}@@ -367,48 +373,42 @@ export const UserAgentConnection = memo<UserAgentConnectionProps>(UserAgentConnection.displayName = 'MessengerUserAgentConnection';export const useMessengerData = (platform: MessengerPlatform) => {- const linksSWR = useSWR(messengerKeys.listMyLinks(), () => messengerService.listMyLinks());- const installationsSWR = useSWR(messengerKeys.listMyInstallations(), () =>- messengerService.listMyInstallations(),- );-- const links = (linksSWR.data ?? []).filter((l) => l.platform === platform);- const installations = (installationsSWR.data ?? []).filter((i) => i.platform === platform);+ // A reload paints the last local copy of both lists, then revalidates.+ const linksSync = messengerActions.useFetchLinks();+ const installationsSync = messengerActions.useFetchInstallations();+ const links = useMessengerStore(messengerSelectors.linksByPlatform(platform)) ?? EMPTY;+ const installations =+ useMessengerStore(messengerSelectors.installationsByPlatform(platform)) ?? EMPTY;+ const isSettled = useMessengerStore(messengerSelectors.isPlatformDataSettled(platform));const tenantNameByTenantId = new Map(installations.map((i) => [i.tenantId, i.tenantName]));- const isInitialLoading = linksSWR.data === undefined || installationsSWR.data === undefined;- // A failed links / installations fetch leaves `data === undefined`, which the- // callers otherwise read as a permanent skeleton — surface the error so the- // detail renders a failure + Retry instead (ux Read §1.1).- const error = linksSWR.error ?? installationsSWR.error;+ // A failed links / installations fetch with nothing to paint would otherwise+ // read as a permanent skeleton — surface the error so the detail renders a+ // failure + Retry instead (ux Read §1.1). A retry in flight is loading again.+ const error =+ linksSync.isValidating || installationsSync.isValidating+ ? undefined+ : (linksSync.error ?? installationsSync.error);return {error,installations,- installationsMutate: installationsSWR.mutate,- isInitialLoading,+ isInitialLoading: !isSettled,links,- linksMutate: linksSWR.mutate,mutate: () => {- void linksSWR.mutate();- void installationsSWR.mutate();+ void messengerActions.refreshConnections();},tenantNameByTenantId,};};+const EMPTY: never[] = [];+interface UseLinkActionsArgs {- installationsMutate: () => Promise<unknown>;- linksMutate: () => Promise<unknown>;name: string;platform: MessengerPlatform;}-export const useLinkActions = ({- installationsMutate,- linksMutate,- name,- platform,-}: UseLinkActionsArgs) => {+export const useLinkActions = ({ name, platform }: UseLinkActionsArgs) => {const { t } = useTranslation('messenger');const { allowed: canEdit } = usePermission('edit_own_content');@@ -419,12 +419,11 @@ export const useLinkActions = ({if (!canEdit) return false;try {- await messengerService.setActiveAgent({+ await messengerActions.setActiveAgent({agentId,platform,tenantId: tenantId || undefined,});- await linksMutate();toast.success(t('messenger.setActiveSuccess'));return true;} catch (error) {@@ -448,8 +447,7 @@ export const useLinkActions = ({okButtonProps: { danger: true },onOk: async () => {try {- await messengerService.unlink({ platform, tenantId: tenantId || undefined });- await Promise.all([linksMutate(), installationsMutate()]);+ await messengerActions.unlink({ platform, tenantId: tenantId || undefined });toast.success(t('messenger.unlinkSuccess'));} catch (error) {toast.error(getMessengerErrorMessage(error, t, 'messenger.unlinkFailed'));@@ -473,11 +471,6 @@ export interface DisconnectInstallationCopy {title: string;}-interface UseDisconnectInstallationArgs {- installationsMutate: () => Promise<unknown>;- linksMutate: () => Promise<unknown>;-}-/*** Disconnect-installation handler shared by Slack and Discord. The copy* diverges sharply between platforms — for Slack the operation freezes the@@ -486,10 +479,7 @@ interface UseDisconnectInstallationArgs {* it. The platform passes already-localized strings + the `failedKey` so the* shared hook avoids embedding any platform-specific copy.*/-export const useDisconnectInstallation = ({- installationsMutate,- linksMutate,-}: UseDisconnectInstallationArgs) => {+export const useDisconnectInstallation = () => {const { t } = useTranslation('messenger');const { allowed: canEdit } = usePermission('edit_own_content');@@ -502,9 +492,7 @@ export const useDisconnectInstallation = ({okButtonProps: { danger: true },onOk: async () => {try {- await messengerService.uninstallInstallation({ installationId: id });- await installationsMutate();- await linksMutate();+ await messengerActions.uninstallInstallation(id);toast.success(copy.success);} catch (error) {toast.error(getMessengerErrorMessage(error, t, copy.failedKey));diff --git a/src/features/Messenger/IntegrationDetail/useMessengerData.replica.test.ts b/src/features/Messenger/IntegrationDetail/useMessengerData.replica.test.tsnew file mode 100644index 00000000000..9c63a03d8df--- /dev/null+++ b/src/features/Messenger/IntegrationDetail/useMessengerData.replica.test.ts@@ -0,0 +1,220 @@+/**+ * @vitest-environment happy-dom+ *+ * The messenger connection lists (links + installations) are a local replica:+ * a reload paints the last local copy before the network answers, then the+ * background revalidation replaces it.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, 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 { AppIndexedDBStorage, cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { messengerService } from '@/services/messenger';++import { useMessengerData } from './shared';++vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));++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 deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+};++const link = (id: string, platform = 'telegram') =>+ ({+ activeAgentId: null,+ id,+ platform,+ platformUserId: `user-${id}`,+ platformUsername: id,+ tenantId: '',+ workspaceId: null,+ }) as never;++const installation = (id: string, platform: string, runtime?: unknown) =>+ ({+ applicationId: 'app',+ enterpriseId: null,+ id,+ installedAt: new Date(0),+ isEnterpriseInstall: false,+ platform,+ runtime,+ scope: '',+ tenantId: `tenant-${id}`,+ tenantName: `Tenant ${id}`,+ }) as never;++// Same namespaces the messenger replicas persist under (`replica:<name>:v<version>`).+const linksStorage = new AppIndexedDBStorage<unknown>({ namespace: 'replica:messengerLinks:v1' });+const installationsStorage = new AppIndexedDBStorage<unknown>({+ namespace: 'replica:messengerInstallations:v1',+});++describe('useMessengerData local replica', () => {+ let scope = '';++ const persist = async (links: unknown[], installations: unknown[], at = scope) => {+ await linksStorage.set({ queryKey: 'all', scope: at }, { data: links, updatedAt: 1 });+ await installationsStorage.set(+ { queryKey: 'all', scope: at },+ { data: installations, updatedAt: 1 },+ );+ };++ // Every test runs in a fresh random scope, so memory from an earlier test is+ // dropped like on a cold boot; only storage carries over.+ beforeEach(() => {+ scope = `messenger-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(async () => {+ cleanup();+ for (const storage of [linksStorage, installationsStorage]) {+ await storage.remove({ queryKey: 'all', scope });+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ }+ vi.restoreAllMocks();+ });++ it('paints the persisted connection before the network answers, then refreshes it', async () => {+ await persist([link('stored')], []);+ const links = deferred<never[]>();+ vi.spyOn(messengerService, 'listMyLinks').mockReturnValue(links.promise as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([] as never);++ const { result } = renderHook(() => useMessengerData('telegram'), { wrapper });++ // The detail has the last connection on the first painted frame after reload.+ await waitFor(() => expect(result.current.isInitialLoading).toBe(false));+ expect(result.current.links.map((item: { id: string }) => item.id)).toEqual(['stored']);++ await act(async () => links.resolve([link('fresh')]));+ await waitFor(() =>+ expect(result.current.links.map((item: { id: string }) => item.id)).toEqual(['fresh']),+ );+ });++ it('treats a restored copy without this platform as loading until the server answers', async () => {+ await persist([], []);+ const links = deferred<never[]>();+ vi.spyOn(messengerService, 'listMyLinks').mockReturnValue(links.promise as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([] as never);++ const { result } = renderHook(() => useMessengerData('telegram'), { wrapper });++ // Storage answered with an empty list: still not "not connected".+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(result.current.isInitialLoading).toBe(true);++ await act(async () => links.resolve([]));+ await waitFor(() => expect(result.current.isInitialLoading).toBe(false));+ expect(result.current.links).toEqual([]);+ });++ it('keeps the last connection when the background refresh fails', async () => {+ await persist([link('stored')], []);+ vi.spyOn(messengerService, 'listMyLinks').mockRejectedValue(new Error('offline'));+ vi.spyOn(messengerService, 'listMyInstallations').mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => useMessengerData('telegram'), { wrapper });++ await waitFor(() => expect(messengerService.listMyLinks).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(result.current.isInitialLoading).toBe(false);+ expect(result.current.links.map((item: { id: string }) => item.id)).toEqual(['stored']);+ });++ it('never shows the previous identity connections after a scope switch', async () => {+ const other = `messenger-other-${randomUUID()}:personal`;+ await persist([link('mine')], []);+ await persist([link('theirs')], [], other);+ vi.spyOn(messengerService, 'listMyLinks').mockReturnValue(new Promise(() => {}) as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockReturnValue(+ new Promise(() => {}) as never,+ );++ const { result, rerender } = renderHook(() => useMessengerData('telegram'), { wrapper });+ await waitFor(() =>+ expect(result.current.links.map((item: { id: string }) => item.id)).toEqual(['mine']),+ );++ scope = other;+ rerender();+ await waitFor(() =>+ expect(result.current.links.map((item: { id: string }) => item.id)).toEqual(['theirs']),+ );++ for (const storage of [linksStorage, installationsStorage]) {+ await storage.remove({ queryKey: 'all', scope: other });+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope: other });+ }+ });++ it('issues one request for every detail section reading the lists', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([link('a')] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([] as never);++ const { result } = renderHook(+ () => [useMessengerData('telegram'), useMessengerData('slack'), useMessengerData('wechat')],+ { wrapper },+ );++ await waitFor(() => expect(result.current[0].isInitialLoading).toBe(false));+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(messengerService.listMyLinks).toHaveBeenCalledTimes(1);+ expect(messengerService.listMyInstallations).toHaveBeenCalledTimes(1);+ });++ it('does not persist the live WeChat runtime status', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([link('w', 'wechat')] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([+ installation('w', 'wechat', { errorCode: 'session_expired', status: 'failed' }),+ ] as never);++ const { result } = renderHook(() => useMessengerData('wechat'), { wrapper });++ // On screen the server's live status is shown…+ await waitFor(() =>+ expect(+ (result.current.installations[0] as { runtime?: { status: string } })?.runtime?.status,+ ).toBe('failed'),+ );+ // …but a reload cannot replay it: the stored row has no runtime.+ await waitFor(async () => {+ const stored = (await installationsStorage.get({ queryKey: 'all', scope }))?.data as+ { id: string; runtime?: unknown }[] | undefined;+ expect(stored?.map((item) => item.id)).toEqual(['w']);+ expect(stored?.[0]?.runtime).toBeUndefined();+ });+ });+});diff --git a/src/features/Messenger/PushResourceModal/PushResourceContent.tsx b/src/features/Messenger/PushResourceModal/PushResourceContent.tsxindex 5f1403b0a7a..d2e47683ef0 100644--- a/src/features/Messenger/PushResourceModal/PushResourceContent.tsx+++ b/src/features/Messenger/PushResourceModal/PushResourceContent.tsx@@ -18,11 +18,9 @@ import {} from '@lobehub/ui';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import FileIcon from '@/components/FileIcon';-import { messengerKeys } from '@/libs/swr/keys';-import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import { formatSize } from '@/utils/format';import type { MessengerPlatform } from '../constants';@@ -31,8 +29,6 @@ import { MessengerPushWindowState } from '../IntegrationDetail/MessengerPushWindimport { resolveAttachmentType } from './resolveAttachmentType';import { resolveOversizePlan } from './resolveOversizePlan';-const PUSH_WINDOW_REFRESH_INTERVAL = 5000;-export interface PushResourceFile {fileType?: string;id: string;@@ -74,16 +70,9 @@ export const PushResourceContent = memo<PushResourceModalProps>(const [oversizeImageStrategy, setOversizeImageStrategy] =useState<MessengerOversizeImageStrategy>(DEFAULT_OVERSIZE_IMAGE_STRATEGY);- const windowSWR = useSWR(- messengerKeys.pushWindow(platform, tenantId),- () => messengerService.getMessengerPushWindow(platform, tenantId),- {- refreshInterval: platform === 'wechat' ? PUSH_WINDOW_REFRESH_INTERVAL : 0,- refreshWhenHidden: false,- refreshWhenOffline: false,- },- );- const status = windowSWR.data;+ const windowSync = messengerActions.useFetchPushWindow({ platform, tenantId });+ // Live status, never restored from disk: undefined until the server answers.+ const status = useMessengerStore(messengerSelectors.pushWindow({ platform, tenantId }));const canPush = status?.deliverability === 'always' ? status.linked : !!status?.windowOpen;@@ -139,7 +128,7 @@ export const PushResourceContent = memo<PushResourceModalProps>(// and reads the name/MIME type off the owned row (a client-side// presigned URL can expire before the platform sender downloads it,// silently dropping the attachment).- const result = await messengerService.sendMessengerPush({+ const result = await messengerActions.sendPush({attachments: [{fileId: file.id,@@ -179,7 +168,6 @@ export const PushResourceContent = memo<PushResourceModalProps>(toast.warning(t('messenger.push.unavailableToast'));}}- await windowSWR.mutate();} catch (error) {toast.error(getMessengerErrorMessage(error, t, 'messenger.push.unavailableToast'));} finally {@@ -273,10 +261,12 @@ export const PushResourceContent = memo<PushResourceModalProps>()}<MessengerPushWindowState- error={windowSWR.error}+ error={windowSync.error}name={platformName}status={status}- onRetry={() => windowSWR.mutate()}+ onRetry={() => {+ void windowSync.revalidate();+ }}/>{!!status?.queued && (diff --git a/src/features/Messenger/PushResourceModal/useSendToMessengerMenuItem.tsx b/src/features/Messenger/PushResourceModal/useSendToMessengerMenuItem.tsxindex e09f135c56f..a53645951d1 100644--- a/src/features/Messenger/PushResourceModal/useSendToMessengerMenuItem.tsx+++ b/src/features/Messenger/PushResourceModal/useSendToMessengerMenuItem.tsx@@ -4,11 +4,9 @@ import type { ItemType } from '@lobehub/ui';import { cssVar, Flexbox, Icon } from '@lobehub/ui';import { SendIcon, Settings2Icon } from 'lucide-react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { messengerKeys } from '@/libs/swr/keys';-import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import {@@ -34,8 +32,9 @@ interface UseSendToMessengerMenuItemParams {* (one entry per platform × Slack workspace); an unlinked one deep-links to* that platform's messenger settings page for setup.*- * SWR dedupes the fetches across every row that renders this hook, so a long- * file list still issues a single request each.+ * The messenger store dedupes the reads across every row that renders this+ * hook, so a long file list still issues a single request each, and a reload+ * paints the submenu from the local copy.*/export const useSendToMessengerMenuItem = ({enabled,@@ -48,36 +47,33 @@ export const useSendToMessengerMenuItem = ({const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);const active = enabled && enableBusinessFeatures;- const platformsSWR = useSWR(- active ? messengerKeys.availablePlatforms() : null,- () => messengerService.availablePlatforms(),- { revalidateOnFocus: false },+ messengerActions.useFetchPlatforms({ enabled: active, revalidateOnFocus: false });+ messengerActions.useFetchLinks({ enabled: active, revalidateOnFocus: false });+ const platforms = useMessengerStore(messengerSelectors.platforms);+ const links = useMessengerStore(messengerSelectors.links);+ // An empty restored list may predate a new link: it is still loading, so the+ // submenu does not offer "Set Up" for a platform that is already linked.+ const isSettled = useMessengerStore(+ (s) => messengerSelectors.isPlatformsSettled(s) && messengerSelectors.isLinksSettled(s),);- const linksSWR = useSWR(- active ? messengerKeys.listMyLinks() : null,- () => messengerService.listMyLinks(),- { revalidateOnFocus: false },- );- const platforms = platformsSWR.data;- const links = linksSWR.data;// Slack links carry a workspace tenant; resolve its display name from the// caller's installations. Only fetched when a Slack link actually exists.const hasSlackLink = !!links?.some((link) => link.platform === 'slack');- const installationsSWR = useSWR(- hasSlackLink ? messengerKeys.listMyInstallations() : null,- () => messengerService.listMyInstallations(),- { revalidateOnFocus: false },- );+ messengerActions.useFetchInstallations({+ enabled: active && hasSlackLink,+ revalidateOnFocus: false,+ });+ const installations = useMessengerStore(messengerSelectors.installations);const tenantNameByTenantId = new Map(- (installationsSWR.data ?? []).map((i) => [i.tenantId, i.tenantName]),+ (installations ?? []).map((i) => [i.tenantId, i.tenantName]),);if (!active) return null;let children: ItemType[];- if (platforms === undefined || links === undefined) {+ if (!isSettled || platforms === undefined || links === undefined) {children = [{disabled: true,diff --git a/src/features/Messenger/Verify/Body/defaultAgent.test.ts b/src/features/Messenger/Verify/Body/defaultAgent.test.tsnew file mode 100644index 00000000000..74140bdccd9--- /dev/null+++ b/src/features/Messenger/Verify/Body/defaultAgent.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { resolveDefaultAgentId } from './defaultAgent';++describe('resolveDefaultAgentId', () => {+ const restored = [{ id: 'agt_removed' }, { id: 'agt_live' }];+ const confirmed = [{ id: 'agt_live' }, { id: 'agt_other' }];++ it('selects nothing from a restored list the server has not confirmed', () => {+ expect(resolveDefaultAgentId(restored, false, undefined)).toBeUndefined();+ });++ it('selects the first confirmed agent', () => {+ expect(resolveDefaultAgentId(confirmed, true, undefined)).toBe('agt_live');+ });++ it('replaces a pick the confirmed list no longer has', () => {+ expect(resolveDefaultAgentId(confirmed, true, 'agt_removed')).toBe('agt_live');+ });++ it('keeps a pick the confirmed list still has', () => {+ expect(resolveDefaultAgentId(confirmed, true, 'agt_other')).toBe('agt_other');+ });++ it('has no default for a confirmed empty scope', () => {+ expect(resolveDefaultAgentId([], true, 'agt_removed')).toBeUndefined();+ });+});diff --git a/src/features/Messenger/Verify/Body/defaultAgent.ts b/src/features/Messenger/Verify/Body/defaultAgent.tsnew file mode 100644index 00000000000..984abaafb51--- /dev/null+++ b/src/features/Messenger/Verify/Body/defaultAgent.ts@@ -0,0 +1,16 @@+/**+ * The agent the verify card should have selected. A list restored from the+ * local copy may still hold agents that were removed since, so nothing is+ * chosen from it: only a server-confirmed list picks the default (inbox is+ * pinned first) or drops a pick that is no longer in it.+ */+export const resolveDefaultAgentId = (+ agents: { id: string }[] | undefined,+ isConfirmed: boolean,+ selectedAgentId: string | undefined,+): string | undefined => {+ if (!isConfirmed || !agents) return selectedAgentId;+ if (selectedAgentId && agents.some((agent) => agent.id === selectedAgentId))+ return selectedAgentId;+ return agents[0]?.id;+};diff --git a/src/features/Messenger/Verify/Body/shared.tsx b/src/features/Messenger/Verify/Body/shared.tsxindex 3c6e1f3a470..d287776d3de 100644--- a/src/features/Messenger/Verify/Body/shared.tsx+++ b/src/features/Messenger/Verify/Body/shared.tsx@@ -4,11 +4,10 @@ import { Block, Button, createStaticStyles, Flexbox, Icon, Select, Text, toast }import { AlertTriangleIcon, CheckCircle2Icon, LinkIcon } from 'lucide-react';import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import { ProductLogo } from '@/components/Branding';-import { messengerKeys } from '@/libs/swr/keys';import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -22,6 +21,7 @@ import {PERSONAL_SCOPE,resolvePersonalScopeLabel,} from '../../scopeOptions';+import { resolveDefaultAgentId } from './defaultAgent';export const styles = createStaticStyles(({ css, cssVar }) => ({bubble: css`@@ -169,9 +169,8 @@ export const ConfirmCard = memo<ConfirmCardProps>(// First-level scope selector — personal plus every workspace the user// belongs to. Picking a scope just filters the agent list below; the// backend derives the binding's workspace from the chosen agent on confirm.- const scopesSWR = useSWR(enableWorkspaceScopes ? messengerKeys.bindingScopes() : null, () =>- messengerService.listBindingScopes(),- );+ messengerActions.useFetchBindingScopes(enableWorkspaceScopes);+ const bindingScopes = useMessengerStore(messengerSelectors.bindingScopes);const [scope, setScope] = useState<string>(PERSONAL_SCOPE);const [selectedAgentId, setSelectedAgentId] = useState<string | undefined>(undefined);const scopeWorkspaceId = scope === PERSONAL_SCOPE ? null : scope;@@ -184,21 +183,25 @@ export const ConfirmCard = memo<ConfirmCardProps>(setSelectedAgentId(undefined);}, [enableWorkspaceScopes, scope]);- // Scope-aware agent list. The SWR key matches AgentSelect's so the fetch is- // shared (single request per scope) and stays in sync as the scope changes.- const agentsSWR = useSWR(messengerKeys.agentsForBinding(scopeWorkspaceId), () =>- messengerService.listAgentsForBinding(scopeWorkspaceId),+ // Scope-aware agent list, the same replica entry AgentSelect reads, so the+ // fetch is shared (single request per scope) and follows the scope.+ messengerActions.useFetchBindingAgents(scopeWorkspaceId);+ const agents = useMessengerStore(messengerSelectors.bindingAgents(scopeWorkspaceId));+ // "No agents" only from the server: a restored empty copy may be stale.+ const isAgentsConfirmed = useMessengerStore(+ messengerSelectors.isBindingAgentsConfirmed(scopeWorkspaceId),);const [confirming, setConfirming] = useState(false);- // Default-select the first agent (inbox is pinned to the top) once a scope's- // list loads. Resetting selectedAgentId on scope change re-triggers this so- // it re-defaults to the new scope's inbox.+ // Default-select the first agent (inbox is pinned to the top) once the+ // server confirms a scope's list, and drop a pick that list no longer has.+ // Resetting selectedAgentId on scope change re-triggers this so it+ // re-defaults to the new scope's inbox.+ const resolvedAgentId = resolveDefaultAgentId(agents, isAgentsConfirmed, selectedAgentId);useEffect(() => {- if (selectedAgentId || !agentsSWR.data?.length) return;- setSelectedAgentId(agentsSWR.data[0].id);- }, [agentsSWR.data, selectedAgentId]);+ if (resolvedAgentId !== selectedAgentId) setSelectedAgentId(resolvedAgentId);+ }, [resolvedAgentId, selectedAgentId]);// Mirror the Messenger connection card's scope picker: avatar + name per row.// Personal uses the user's avatar; workspaces use their own.@@ -212,18 +215,18 @@ export const ConfirmCard = memo<ConfirmCardProps>(personalAvatar: userAvatar,personalLabel,personalTagLabel: t('messenger.scopePersonalTag', { defaultValue: 'personal' }),- workspaces: scopesSWR.data,+ workspaces: enableWorkspaceScopes ? bindingScopes : undefined,});- }, [scopesSWR.data, t, userAvatar, userDisplayName, userFullName]);+ }, [bindingScopes, enableWorkspaceScopes, t, userAvatar, userDisplayName, userFullName]);// Personal-only deployments (OSS) return no workspaces — hide the scope// selector entirely so the experience is unchanged there.- const hasWorkspaces = enableWorkspaceScopes && (scopesSWR.data?.length ?? 0) > 0;+ const hasWorkspaces = enableWorkspaceScopes && (bindingScopes?.length ?? 0) > 0;const isBlocked = !!blockingNotice;const handleConfirm = async () => {- if (!selectedAgentId) return;+ if (!selectedAgentId || !isAgentsConfirmed) return;setConfirming(true);try {await messengerService.confirmLink({ initialAgentId: selectedAgentId, randomId });@@ -290,7 +293,7 @@ export const ConfirmCard = memo<ConfirmCardProps>()}<Flexbox gap={8}><Text strong>{t('verify.confirm.defaultAgent')}</Text>- {agentsSWR.data?.length === 0 ? (+ {isAgentsConfirmed && agents?.length === 0 ? (<Text type="warning">{t('verify.confirm.noAgents')}</Text>) : (<AgentSelect@@ -309,7 +312,7 @@ export const ConfirmCard = memo<ConfirmCardProps>(<Buttonblock- disabled={isBlocked || !selectedAgentId}+ disabled={isBlocked || !selectedAgentId || !isAgentsConfirmed}loading={confirming}size="large"type="primary"diff --git a/src/features/Messenger/Verify/index.tsx b/src/features/Messenger/Verify/index.tsxindex c22a8dd2388..e328df09c32 100644--- a/src/features/Messenger/Verify/index.tsx+++ b/src/features/Messenger/Verify/index.tsx@@ -10,6 +10,7 @@ import Loading from '@/components/Loading/BrandTextLoading';import { useSession } from '@/libs/better-auth/auth-client';import { messengerKeys } from '@/libs/swr/keys';import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import { type MessengerPlatform } from '../constants';import { getMessengerErrorMessage } from '../i18n';@@ -31,9 +32,8 @@ const MessengerVerifyPage = memo(() => {const isSignedIn = !!session?.user;// Used in the success state to deep-link the user back to the bot.- const platformsSWR = useSWR(messengerKeys.availablePlatforms(), () =>- messengerService.availablePlatforms(),- );+ messengerActions.useFetchPlatforms();+ const platforms = useMessengerStore(messengerSelectors.platforms);const tokenSWR = useSWR(randomId && isSignedIn ? messengerKeys.peek(randomId) : null, async () =>messengerService.peekLinkToken(randomId),@@ -148,7 +148,7 @@ const MessengerVerifyPage = memo(() => {);}- const platformMeta = platformsSWR.data?.find(+ const platformMeta = platforms?.find((p) =>p.id ===(existingLinkSWR.data?.platform ??diff --git a/src/features/Messenger/index.tsx b/src/features/Messenger/index.tsxindex 528f24ed935..6123bd156b0 100644--- a/src/features/Messenger/index.tsx+++ b/src/features/Messenger/index.tsx@@ -4,7 +4,6 @@ import { Button, createStaticStyles, Flexbox, Text, toast } from '@lobehub/ui';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';-import useSWR from 'swr';import AsyncBoundary from '@/components/AsyncBoundary';import ImperativeModal from '@/components/ImperativeModal';@@ -13,8 +12,7 @@ import {MessengerPlatformDetailSkeleton,} from '@/components/Skeleton/Settings/MessengerDetail';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { messengerKeys } from '@/libs/swr/keys';-import { messengerService } from '@/services/messenger';+import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';import { type MessengerPlatform, PlatformAvatar } from './constants';import { getDiscordInstallErrorReason, getSlackInstallErrorReason } from './i18n';@@ -66,9 +64,11 @@ const MessengerSettings = memo(() => {// next-step guidance.const [blocked, setBlocked] = useState<BlockedInstall | null>(null);- const platformsSWR = useSWR(messengerKeys.availablePlatforms(), () =>- messengerService.availablePlatforms(),- );+ // A reload paints the last local copy, then revalidates in the background.+ const platformsSync = messengerActions.useFetchPlatforms();+ const platformList = useMessengerStore(messengerSelectors.platforms);+ const isPlatformsSettled = useMessengerStore(messengerSelectors.isPlatformsSettled);+ const isPlatformsConfirmed = useMessengerStore(messengerSelectors.isPlatformsConfirmed);// If the URL points at an unknown platform sub-segment, replace it with the// bare list URL — keeps deep-links graceful when bots get removed from the@@ -125,13 +125,16 @@ const MessengerSettings = memo(() => {window.history.replaceState({}, '', url.pathname + (url.search ? `?${url.searchParams}` : ''));}, [t, selected, ready]);- const platforms = platformsSWR.data ?? [];+ const platforms = platformList ?? [];const selectedMeta = platforms.find((p) => p.id === selected);+ // A restored copy may predate a newly enabled platform: until the server+ // answers, a miss is still loading, not a reason to fall back to the list.+ const isSelectedPending = !selectedMeta && !isPlatformsConfirmed && !platformsSync.error;return (<div className={styles.page}><Flexbox gap={20}>- {selected && !selectedMeta && platformsSWR.isLoading ? (+ {selected && isSelectedPending ? (<MessengerPlatformDetailSkeleton platform={selected} />) : selected && selectedMeta ? (<IntegrationDetail@@ -146,16 +149,20 @@ const MessengerSettings = memo(() => {<><Text type="secondary">{t('messenger.subtitle')}</Text><AsyncBoundary- data={platformsSWR.data}- error={platformsSWR.error}+ data={isPlatformsSettled || undefined}+ error={platformsSync.error}errorVariant={'block'}isEmpty={platforms.length === 0}- isLoading={platformsSWR.isLoading}loading={<MessengerListGridSkeleton />}empty={<div className={styles.emptyState}>{t('messenger.noPlatformsConfigured')}</div>}- onRetry={() => platformsSWR.mutate()}+ isLoading={+ !isPlatformsSettled && (!platformsSync.error || platformsSync.isValidating)+ }+ onRetry={() => {+ void platformsSync.revalidate();+ }}><IntegrationListplatforms={platforms}diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex 6a48181eb4a..dd744ed678f 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -87,14 +87,8 @@ const LEGACY_SWR_KEYS = ['localFileKeys.projectIndex','mcpAppKeys.resource','messageKeys.list',- 'messengerKeys.agentsForBinding',- 'messengerKeys.availablePlatforms',- 'messengerKeys.bindingScopes',- 'messengerKeys.listMyInstallations',- 'messengerKeys.listMyLinks','messengerKeys.myLink','messengerKeys.peek',- 'messengerKeys.pushWindow','ollamaKeys.downloadModel','onboardingKeys.agentBootstrap','onboardingKeys.agentHistoryTopics',@@ -111,9 +105,6 @@ const LEGACY_SWR_KEYS = ['recommendationsKeys.heteroDetections','resourceKeys.list','scmKeys.changeRequests',- 'scmKeys.config',- 'scmKeys.identity',- 'scmKeys.installations','scmKeys.repositories','scmKeys.wakeTarget','serverConfigKeys.get',diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 9b16772fa79..3c9817cd9b8 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -555,27 +555,12 @@ export const apiKeyKeys = {// ---- messenger / platform integration -----------------------------------export const messengerKeys = {- agentsForBinding: def('messenger:agentsForBinding', (workspaceId: string | null | undefined) => [- 'messenger:agentsForBinding',- workspaceId ?? null,- ]),- availablePlatforms: def('messenger:availablePlatforms', () => ['messenger:availablePlatforms']),- bindingScopes: def('messenger:bindingScopes', () => ['messenger:bindingScopes']),- listMyInstallations: def('messenger:listMyInstallations', () => [- 'messenger:listMyInstallations',- ]),- listMyLinks: def('messenger:listMyLinks', () => ['messenger:listMyLinks']),myLink: def('messenger:myLink', (platform: string, tokenScopeKey: string | undefined) => ['messenger:myLink',platform,tokenScopeKey,]),peek: def('messenger:peek', (randomId: string) => ['messenger:peek', randomId]),- pushWindow: def('messenger:pushWindow', (platform: string, tenantId?: string) => [- 'messenger:pushWindow',- platform,- tenantId ?? null,- ]),};// ---- scm (GitHub App integration) --------------------------------------@@ -584,12 +569,6 @@ export const scmKeys = {'scm:changeRequests',workspaceId ?? null,]),- config: def('scm:config', () => ['scm:config']),- identity: def('scm:identity', (provider: string) => ['scm:identity', provider]),- installations: def('scm:installations', (workspaceId: string | null | undefined) => [- 'scm:installations',- workspaceId ?? null,- ]),repositories: def('scm:repositories', (workspaceId: string | null | undefined) => ['scm:repositories',workspaceId ?? null,diff --git a/src/store/integration/action.ts b/src/store/integration/action.tsnew file mode 100644index 00000000000..1304786055b--- /dev/null+++ b/src/store/integration/action.ts@@ -0,0 +1,53 @@+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { initialIntegrationState, type IntegrationState } from './initialState';+import { IntegrationPrivateAction } from './privateAction';+import { INTEGRATION_PARAMS } from './projection';+import { useIntegrationStore } from './store';++const n = setNamespace('integration');++/** The overview card and the detail page mount the same reads. */+const DEDUPING_INTERVAL = 10_000;++type Setter = StoreSetter<IntegrationState>;++export class IntegrationActionImpl {+ readonly #private: IntegrationPrivateAction;+ readonly #set: Setter;++ constructor(set: Setter, _get: () => IntegrationState, privateAction: IntegrationPrivateAction) {+ this.#set = set;+ this.#private = privateAction;+ }++ reset = (): void => {+ this.#set(initialIntegrationState, false, n('reset'));+ };++ /** Config, identity and installations of the GitHub integration; flags of all three. */+ useFetchGithub = () => {+ const options = { dedupingInterval: DEDUPING_INTERVAL };+ const config = this.#private.scmConfig.useSync(INTEGRATION_PARAMS, options);+ const identity = this.#private.scmIdentity.useSync(INTEGRATION_PARAMS, options);+ const installations = this.#private.scmInstallations.useSync(INTEGRATION_PARAMS, options);+ return {+ error: config.error ?? installations.error ?? identity.error,+ isValidating: config.isValidating || identity.isValidating || installations.isValidating,+ };+ };++ refreshGithub = () =>+ Promise.all([+ this.#private.scmConfig.fetch(INTEGRATION_PARAMS, { fresh: true }),+ this.#private.scmIdentity.fetch(INTEGRATION_PARAMS, { fresh: true }),+ this.#private.scmInstallations.fetch(INTEGRATION_PARAMS, { fresh: true }),+ ]);+}++export const integrationActions = new IntegrationActionImpl(+ useIntegrationStore.setState,+ useIntegrationStore.getState,+ new IntegrationPrivateAction(useIntegrationStore.setState, useIntegrationStore.getState),+);diff --git a/src/store/integration/index.ts b/src/store/integration/index.tsnew file mode 100644index 00000000000..90f7886e894--- /dev/null+++ b/src/store/integration/index.ts@@ -0,0 +1,5 @@+export { integrationActions } from './action';+export { type IntegrationState } from './initialState';+export type { ScmConfig, ScmIdentity, ScmInstallationItem } from './projection';+export * from './selectors';+export { useIntegrationStore } from './store';diff --git a/src/store/integration/initialState.ts b/src/store/integration/initialState.tsnew file mode 100644index 00000000000..33273c6388a--- /dev/null+++ b/src/store/integration/initialState.ts@@ -0,0 +1,21 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type { ScmConfig, ScmIdentityEntry, ScmInstallationItem } from './projection';++export interface IntegrationState {+ scmConfigMap: Record<string, ScmConfig>;+ scmConfigReplica: ReplicaState<ScmConfig>;+ scmIdentityMap: Record<string, ScmIdentityEntry>;+ scmIdentityReplica: ReplicaState<ScmIdentityEntry>;+ scmInstallationsMap: Record<string, ScmInstallationItem[]>;+ scmInstallationsReplica: ReplicaState<ScmInstallationItem[]>;+}++export const initialIntegrationState: IntegrationState = {+ scmConfigMap: {},+ scmConfigReplica: createReplicaState(),+ scmIdentityMap: {},+ scmIdentityReplica: createReplicaState(),+ scmInstallationsMap: {},+ scmInstallationsReplica: createReplicaState(),+};diff --git a/src/store/integration/privateAction.ts b/src/store/integration/privateAction.tsnew file mode 100644index 00000000000..d7729120b27--- /dev/null+++ b/src/store/integration/privateAction.ts@@ -0,0 +1,48 @@+import { createReplicaSlice, recordLens } from '@/libs/replica';+import { scmService } from '@/services/scm';+import type { StoreSetter } from '@/store/types';++import type { IntegrationState } from './initialState';+import {+ type ScmConfig,+ scmConfigResource,+ type ScmIdentityEntry,+ scmIdentityResource,+ type ScmInstallationItem,+ scmInstallationsResource,+} from './projection';++type Setter = StoreSetter<IntegrationState>;++export class IntegrationPrivateAction {+ readonly scmConfig;+ readonly scmIdentity;+ readonly scmInstallations;++ constructor(set: Setter, get: () => IntegrationState) {+ this.scmConfig = createReplicaSlice(scmConfigResource, {+ actionPrefix: 'integration/scmConfig',+ fetcher: () => scmService.getConfig(),+ get,+ set,+ stateKey: 'scmConfigReplica',+ view: recordLens<IntegrationState, ScmConfig>('scmConfigMap'),+ });+ this.scmIdentity = createReplicaSlice(scmIdentityResource, {+ actionPrefix: 'integration/scmIdentity',+ fetcher: async () => ({ identity: await scmService.getIdentity('github') }),+ get,+ set,+ stateKey: 'scmIdentityReplica',+ view: recordLens<IntegrationState, ScmIdentityEntry>('scmIdentityMap'),+ });+ this.scmInstallations = createReplicaSlice(scmInstallationsResource, {+ actionPrefix: 'integration/scmInstallations',+ fetcher: () => scmService.listInstallations(),+ get,+ set,+ stateKey: 'scmInstallationsReplica',+ view: recordLens<IntegrationState, ScmInstallationItem[]>('scmInstallationsMap'),+ });+ }+}diff --git a/src/store/integration/projection.ts b/src/store/integration/projection.tsnew file mode 100644index 00000000000..4ef42e7159c--- /dev/null+++ b/src/store/integration/projection.ts@@ -0,0 +1,45 @@+import { defineReplica } from '@/libs/replica';+import type { scmService } from '@/services/scm';++type Resolved<T extends (...args: any[]) => Promise<unknown>> = Awaited<ReturnType<T>>;++export type ScmConfig = Resolved<typeof scmService.getConfig>;+export type ScmIdentity = NonNullable<Resolved<typeof scmService.getIdentity>>;+export type ScmInstallationItem = Resolved<typeof scmService.listInstallations>[number];++/**+ * The caller's GitHub identity, wrapped so "not connected" (`identity: null`)+ * is a value the local copy can replay, not an absence. Served without+ * credentials.+ */+export interface ScmIdentityEntry {+ identity: ScmIdentity | null;+}++/** Each integration read has one entry; the scope partitions it per user + workspace. */+export type IntegrationParams = Record<string, never>;+export const INTEGRATION_PARAMS: IntegrationParams = {};+export const INTEGRATION_KEY = 'github';++/** Whether this deployment runs the GitHub App, and where installs start. */+export const scmConfigResource = defineReplica<IntegrationParams, ScmConfig>({+ key: () => INTEGRATION_KEY,+ name: 'scmConfig',+ storage: 'indexedDB',+ version: 1,+});++export const scmIdentityResource = defineReplica<IntegrationParams, ScmIdentityEntry>({+ key: () => INTEGRATION_KEY,+ name: 'scmIdentity',+ storage: 'indexedDB',+ version: 1,+});++/** Live GitHub App installations bound to the active scope. */+export const scmInstallationsResource = defineReplica<IntegrationParams, ScmInstallationItem[]>({+ key: () => INTEGRATION_KEY,+ name: 'scmInstallations',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/integration/selectors.ts b/src/store/integration/selectors.tsnew file mode 100644index 00000000000..acd40eabbfb--- /dev/null+++ b/src/store/integration/selectors.ts@@ -0,0 +1,27 @@+import type { IntegrationState } from './initialState';+import { INTEGRATION_KEY } from './projection';++const scmConfig = (s: IntegrationState) => s.scmConfigMap[INTEGRATION_KEY];+const scmIdentity = (s: IntegrationState) => s.scmIdentityMap[INTEGRATION_KEY];+const scmInstallations = (s: IntegrationState) => s.scmInstallationsMap[INTEGRATION_KEY];++/**+ * The GitHub surfaces can render. A restored copy without installations may+ * predate a new connection, so it waits for the server before the page reads+ * as "not connected" (and the overview drops GitHub from its Enabled strip).+ */+const isGithubSettled = (s: IntegrationState) => {+ const installations = scmInstallations(s);+ if (!scmConfig(s) || !scmIdentity(s) || !installations) return false;+ return (+ installations.length > 0 ||+ s.scmInstallationsReplica.entries[INTEGRATION_KEY]?.source === 'server'+ );+};++export const integrationSelectors = {+ isGithubSettled,+ scmConfig,+ scmIdentity,+ scmInstallations,+};diff --git a/src/store/integration/store.ts b/src/store/integration/store.tsnew file mode 100644index 00000000000..544a6ee8f5c--- /dev/null+++ b/src/store/integration/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { initialIntegrationState, type IntegrationState } from './initialState';++const devtools = createDevtools('integration');++export const useIntegrationStore = createWithEqualityFn<IntegrationState>()(+ devtools(() => initialIntegrationState),+ shallow,+);++expose('integration', useIntegrationStore);diff --git a/src/store/messenger/action.test.ts b/src/store/messenger/action.test.tsnew file mode 100644index 00000000000..cda1ea7b950--- /dev/null+++ b/src/store/messenger/action.test.ts@@ -0,0 +1,287 @@+/**+ * @vitest-environment happy-dom+ *+ * Messenger writes land on the replica (view + persisted copy), so a reload+ * never brings back a removed connection, and a failed write rolls back.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, 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, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { messengerService } from '@/services/messenger';++import { messengerActions } from './action';+import {+ messengerInstallationsResource,+ messengerLinksResource,+ messengerPlatformsResource,+ messengerPushWindowResource,+} from './projection';+import { messengerSelectors } from './selectors';+import { useMessengerStore } from './store';++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 link = (id: string, platform: string, tenantId = '') =>+ ({+ activeAgentId: null,+ id,+ platform,+ platformUserId: id,+ platformUsername: id,+ tenantId,+ workspaceId: null,+ }) as never;++const installation = (id: string, platform: string, tenantId: string) =>+ ({ id, platform, tenantId, tenantName: tenantId }) as never;++const linksStorage = messengerLinksResource.storage!;+const installationsStorage = messengerInstallationsResource.storage!;+const ids = (items: { id: string }[] | undefined) => items?.map((item) => item.id);++describe('messengerActions writes', () => {+ let scope = '';++ const stored = async (storage: typeof linksStorage) =>+ (await storage.get({ queryKey: 'all', scope }))?.data as { id: string }[] | undefined;++ /** Mount the lists like the settings page and wait for the server's answer. */+ const mountConnections = async () => {+ renderHook(+ () => {+ messengerActions.useFetchLinks();+ messengerActions.useFetchInstallations();+ },+ { wrapper },+ );+ await waitFor(() => {+ expect(messengerSelectors.links(useMessengerStore.getState())).toBeDefined();+ expect(messengerSelectors.installations(useMessengerStore.getState())).toBeDefined();+ });+ await waitFor(async () => expect(await stored(linksStorage)).toBeDefined());+ };++ beforeEach(() => {+ scope = `messenger-write-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ act(() => messengerActions.reset());+ });++ afterEach(async () => {+ cleanup();+ for (const storage of [linksStorage, installationsStorage]) {+ await storage.remove({ queryKey: 'all', scope });+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ }+ vi.restoreAllMocks();+ });++ it('removes an unlinked WeChat connection from the view and from storage', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([+ link('tg', 'telegram'),+ link('wx', 'wechat', 'wx-tenant'),+ ] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([+ installation('wx', 'wechat', 'wx-tenant'),+ ] as never);+ await mountConnections();++ vi.spyOn(messengerService, 'unlink').mockResolvedValue({ success: true } as never);+ // The refresh after the write fails: the removal must not depend on it.+ vi.mocked(messengerService.listMyLinks).mockRejectedValue(new Error('offline'));+ vi.mocked(messengerService.listMyInstallations).mockRejectedValue(new Error('offline'));++ await act(() => messengerActions.unlink({ platform: 'wechat', tenantId: 'wx-tenant' }));++ const state = useMessengerStore.getState();+ expect(ids(messengerSelectors.links(state))).toEqual(['tg']);+ expect(messengerSelectors.installations(state)).toEqual([]);+ // A reload cannot restore it from the local copy.+ await waitFor(async () => expect(ids(await stored(linksStorage))).toEqual(['tg']));+ await waitFor(async () => expect(await stored(installationsStorage)).toEqual([]));+ });++ it('restores the link when unlinking fails', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([link('tg', 'telegram')] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([] as never);+ await mountConnections();+ vi.spyOn(messengerService, 'unlink').mockRejectedValue(new Error('denied'));++ await act(async () => {+ await expect(messengerActions.unlink({ platform: 'telegram' })).rejects.toThrow('denied');+ });++ expect(ids(messengerSelectors.links(useMessengerStore.getState()))).toEqual(['tg']);+ expect(ids(await stored(linksStorage))).toEqual(['tg']);+ });++ it('removes an uninstalled installation from the view and from storage', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([+ installation('a', 'slack', 'T1'),+ installation('b', 'slack', 'T2'),+ ] as never);+ await mountConnections();+ vi.spyOn(messengerService, 'uninstallInstallation').mockResolvedValue({} as never);+ vi.mocked(messengerService.listMyInstallations).mockRejectedValue(new Error('offline'));++ await act(() => messengerActions.uninstallInstallation('a'));++ expect(ids(messengerSelectors.installations(useMessengerStore.getState()))).toEqual(['b']);+ await waitFor(async () => expect(ids(await stored(installationsStorage))).toEqual(['b']));+ });++ it('shows a new active agent at once and adopts the server row', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([+ link('s1', 'slack', 'T1'),+ link('s2', 'slack', 'T2'),+ ] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([] as never);+ await mountConnections();++ let release!: () => void;+ vi.spyOn(messengerService, 'setActiveAgent').mockImplementation(+ () =>+ new Promise((resolve) => {+ release = () =>+ resolve({+ data: {+ ...(link('s1', 'slack', 'T1') as object),+ activeAgentId: 'agt_1',+ workspaceId: 'ws_1',+ },+ success: true,+ } as never);+ }),+ );++ let pending!: Promise<void>;+ act(() => {+ pending = messengerActions.setActiveAgent({+ agentId: 'agt_1',+ platform: 'slack',+ tenantId: 'T1',+ });+ });++ const optimistic = messengerSelectors.links(useMessengerStore.getState()) as {+ activeAgentId: string | null;+ }[];+ expect(optimistic.map((item) => item.activeAgentId)).toEqual(['agt_1', null]);++ await act(async () => {+ release();+ await pending;+ });+ const confirmed = messengerSelectors.links(useMessengerStore.getState()) as {+ workspaceId: string | null;+ }[];+ expect(confirmed.map((item) => item.workspaceId)).toEqual(['ws_1', null]);+ });++ it('rolls the active agent back when the server rejects it', async () => {+ vi.spyOn(messengerService, 'listMyLinks').mockResolvedValue([link('tg', 'telegram')] as never);+ vi.spyOn(messengerService, 'listMyInstallations').mockResolvedValue([] as never);+ await mountConnections();+ vi.spyOn(messengerService, 'setActiveAgent').mockRejectedValue(new Error('denied'));++ await act(async () => {+ await expect(+ messengerActions.setActiveAgent({ agentId: 'agt_1', platform: 'telegram' }),+ ).rejects.toThrow('denied');+ });++ const links = messengerSelectors.links(useMessengerStore.getState()) as {+ activeAgentId: string | null;+ }[];+ expect(links[0].activeAgentId).toBeNull();+ });+});++describe('messenger read replicas', () => {+ let scope = '';++ beforeEach(() => {+ scope = `messenger-read-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => messengerActions.reset());+ });++ afterEach(async () => {+ cleanup();+ await messengerPlatformsResource.storage!.remove({ queryKey: 'all', scope });+ await messengerPlatformsResource.storage!.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ vi.restoreAllMocks();+ });++ it('paints the persisted platform list before the network answers', async () => {+ await messengerPlatformsResource.storage!.set(+ { queryKey: 'all', scope },+ { data: [{ id: 'telegram', name: 'Telegram' }] as never, updatedAt: 1 },+ );+ vi.spyOn(messengerService, 'availablePlatforms').mockReturnValue(+ new Promise(() => {}) as never,+ );++ renderHook(() => messengerActions.useFetchPlatforms(), { wrapper });++ await waitFor(() =>+ expect(ids(messengerSelectors.platforms(useMessengerStore.getState()))).toEqual(['telegram']),+ );+ expect(messengerSelectors.isPlatformsSettled(useMessengerStore.getState())).toBe(true);+ // Restored, not confirmed: a missing platform is not yet "not configured".+ expect(messengerSelectors.isPlatformsConfirmed(useMessengerStore.getState())).toBe(false);+ });++ it('keeps the live push window in memory only and refreshes it after a send', async () => {+ const params = { platform: 'wechat' as const };+ vi.spyOn(messengerService, 'getMessengerPushWindow')+ .mockResolvedValueOnce({+ deliverability: 'windowed',+ remaining: 3,+ windowOpen: true,+ } as never)+ .mockResolvedValue({ deliverability: 'windowed', remaining: 2, windowOpen: true } as never);+ vi.spyOn(messengerService, 'sendMessengerPush').mockResolvedValue({+ remaining: 2,+ status: 'sent',+ } as never);++ renderHook(() => messengerActions.useFetchPushWindow(params), { wrapper });+ await waitFor(() =>+ expect(messengerSelectors.pushWindow(params)(useMessengerStore.getState())).toBeDefined(),+ );++ await act(() => messengerActions.sendPush({ content: 'hi', platform: 'wechat' }));++ expect(+ (messengerSelectors.pushWindow(params)(useMessengerStore.getState()) as { remaining: number })+ .remaining,+ ).toBe(2);+ expect(messengerPushWindowResource.persistKey('wechat:')).toBe(false);+ });+});diff --git a/src/store/messenger/action.ts b/src/store/messenger/action.tsnew file mode 100644index 00000000000..95e27cb9706--- /dev/null+++ b/src/store/messenger/action.ts@@ -0,0 +1,208 @@+import type { ReplicaSyncResult } from '@/libs/replica';+import { messengerService } from '@/services/messenger';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { initialMessengerState, type MessengerState } from './initialState';+import { MessengerPrivateAction } from './privateAction';+import {+ MESSENGER_LIST_KEY,+ MESSENGER_LIST_PARAMS,+ type MessengerInstallationItem,+ type MessengerLinkItem,+ type MessengerPushWindowParams,+} from './projection';+import { useMessengerStore } from './store';++const n = setNamespace('messenger');++/**+ * The settings page, the file row menus (one hook per row) and the verify flow+ * all read the same lists: collapse their mounts into one request.+ */+const LIST_DEDUPING_INTERVAL = 10_000;++const PUSH_WINDOW_REFRESH_INTERVAL = 5000;++type MessengerPlatform = MessengerPushWindowParams['platform'];++interface LinkTarget {+ platform: MessengerPlatform;+ tenantId?: string;+}++interface ListSyncOptions {+ enabled?: boolean;+ revalidateOnFocus?: boolean;+}++/** Without a tenant the server addresses the platform's only (global) link. */+const matchesTarget =+ ({ platform, tenantId }: LinkTarget) =>+ (row: { platform: string; tenantId: string }) =>+ row.platform === platform && (!tenantId || row.tenantId === tenantId);++type Setter = StoreSetter<MessengerState>;++export class MessengerActionImpl {+ readonly #private: MessengerPrivateAction;+ readonly #set: Setter;++ constructor(set: Setter, _get: () => MessengerState, privateAction: MessengerPrivateAction) {+ this.#set = set;+ this.#private = privateAction;+ }++ reset = (): void => {+ this.#set(initialMessengerState, false, n('reset'));+ };++ useFetchPlatforms = ({ enabled = true, revalidateOnFocus }: ListSyncOptions = {}) =>+ this.#private.platforms.useSync(MESSENGER_LIST_PARAMS, {+ dedupingInterval: LIST_DEDUPING_INTERVAL,+ enabled,+ revalidateOnFocus,+ });++ useFetchLinks = ({ enabled = true, revalidateOnFocus }: ListSyncOptions = {}) =>+ this.#private.links.useSync(MESSENGER_LIST_PARAMS, {+ dedupingInterval: LIST_DEDUPING_INTERVAL,+ enabled,+ revalidateOnFocus,+ });++ useFetchInstallations = ({ enabled = true, revalidateOnFocus }: ListSyncOptions = {}) =>+ this.#private.installations.useSync(MESSENGER_LIST_PARAMS, {+ dedupingInterval: LIST_DEDUPING_INTERVAL,+ enabled,+ revalidateOnFocus,+ });++ useFetchBindingScopes = (enabled: boolean): ReplicaSyncResult =>+ this.#private.bindingScopes.useSync(MESSENGER_LIST_PARAMS, {+ dedupingInterval: LIST_DEDUPING_INTERVAL,+ enabled,+ });++ useFetchBindingAgents = (workspaceId: string | null | undefined): ReplicaSyncResult =>+ this.#private.bindingAgents.useSync(+ { workspaceId: workspaceId ?? null },+ { dedupingInterval: LIST_DEDUPING_INTERVAL },+ );++ /** WeChat's window moves with every inbound message, so it polls while shown. */+ useFetchPushWindow = (params: MessengerPushWindowParams): ReplicaSyncResult =>+ this.#private.pushWindow.useSync(params, {+ refreshInterval: params.platform === 'wechat' ? PUSH_WINDOW_REFRESH_INTERVAL : 0,+ refreshWhenHidden: false,+ refreshWhenOffline: false,+ });++ refreshPlatforms = () => this.#private.platforms.fetch(MESSENGER_LIST_PARAMS, { fresh: true });++ refreshLinks = () => this.#private.links.fetch(MESSENGER_LIST_PARAMS, { fresh: true });++ refreshInstallations = () =>+ this.#private.installations.fetch(MESSENGER_LIST_PARAMS, { fresh: true });++ refreshConnections = () => Promise.all([this.refreshLinks(), this.refreshInstallations()]);++ refreshPushWindow = (params: MessengerPushWindowParams) =>+ this.#private.pushWindow.fetch(params, { fresh: true });++ /**+ * Refresh after a write that already committed. A failed refresh must not+ * read as a failed write (the caller would toast an error for a change that+ * went through); the next sync catches up.+ */+ #refreshAfterWrite = async (refresh: () => Promise<unknown>) => {+ try {+ await refresh();+ } catch (error) {+ console.error('Failed to refresh Messenger after a write', error);+ }+ };++ /**+ * Route the link's conversations to another agent. The link shows the pick+ * at once and adopts the server's row (which also carries the derived+ * workspace); a failure restores the previous agent.+ */+ setActiveAgent = async (target: LinkTarget & { agentId: string | null }) => {+ const matches = matchesTarget(target);+ await this.#private.links.optimistic(+ MESSENGER_LIST_KEY,+ (items) =>+ items?.map((link) => (matches(link) ? { ...link, activeAgentId: target.agentId } : link)),+ () =>+ messengerService.setActiveAgent({+ agentId: target.agentId,+ platform: target.platform,+ tenantId: target.tenantId,+ }),+ {+ confirm:+ ({ data }) =>+ (items) =>+ items?.map((link) => (link.id === data.id ? (data as MessengerLinkItem) : link)),+ },+ );+ };++ /**+ * Remove an account link. The row leaves the lists (and their persisted+ * copies) once the server confirms, so a reload cannot bring it back; a+ * WeChat connection is listed through its link, so its installation view goes+ * with it. A failure restores both.+ */+ unlink = async (target: LinkTarget) => {+ const matches = matchesTarget(target);+ await this.#private.links.optimistic(+ MESSENGER_LIST_KEY,+ (items) => items?.filter((link) => !matches(link)),+ () =>+ this.#private.installations.optimistic(+ MESSENGER_LIST_KEY,+ (items) =>+ target.platform === 'wechat'+ ? items?.filter((installation) => !matches(installation))+ : items,+ () => messengerService.unlink({ platform: target.platform, tenantId: target.tenantId }),+ ),+ );+ await this.#refreshAfterWrite(this.refreshConnections);+ };++ /** Disconnect a Slack / Discord installation; links served through it are re-read. */+ uninstallInstallation = async (installationId: string) => {+ await this.#private.installations.optimistic(+ MESSENGER_LIST_KEY,+ (items) =>+ items?.filter(+ (installation: MessengerInstallationItem) => installation.id !== installationId,+ ),+ () => messengerService.uninstallInstallation({ installationId }),+ );+ await this.#refreshAfterWrite(this.refreshConnections);+ };++ /** A connection completed out of band (QR scan, iMessage handshake). */+ refreshAfterConnect = () => this.#refreshAfterWrite(this.refreshConnections);++ sendPush = async (+ params: Parameters<typeof messengerService.sendMessengerPush>[0],+ ): ReturnType<typeof messengerService.sendMessengerPush> => {+ const result = await messengerService.sendMessengerPush(params);+ // Every send spends window quota (or queues), whatever the outcome.+ await this.#refreshAfterWrite(() =>+ this.refreshPushWindow({ platform: params.platform, tenantId: params.tenantId }),+ );+ return result;+ };+}++export const messengerActions = new MessengerActionImpl(+ useMessengerStore.setState,+ useMessengerStore.getState,+ new MessengerPrivateAction(useMessengerStore.setState, useMessengerStore.getState),+);diff --git a/src/store/messenger/index.ts b/src/store/messenger/index.tsnew file mode 100644index 00000000000..49638f6fdda--- /dev/null+++ b/src/store/messenger/index.ts@@ -0,0 +1,13 @@+export { messengerActions } from './action';+export { type MessengerState } from './initialState';+export type {+ MessengerBindingAgent,+ MessengerBindingScope,+ MessengerInstallationItem,+ MessengerLinkItem,+ MessengerPlatformItem,+ MessengerPushWindow,+ MessengerPushWindowParams,+} from './projection';+export * from './selectors';+export { useMessengerStore } from './store';diff --git a/src/store/messenger/initialState.ts b/src/store/messenger/initialState.tsnew file mode 100644index 00000000000..a8ad02bf3d4--- /dev/null+++ b/src/store/messenger/initialState.ts@@ -0,0 +1,42 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type {+ MessengerBindingAgent,+ MessengerBindingScope,+ MessengerInstallationItem,+ MessengerLinkItem,+ MessengerPlatformItem,+ MessengerPushWindow,+} from './projection';++export interface MessengerState {+ /** Bindable agents, by `messengerBindingAgentsKey`. */+ bindingAgentsMap: Record<string, MessengerBindingAgent[]>;+ bindingAgentsReplica: ReplicaState<MessengerBindingAgent[]>;+ bindingScopesMap: Record<string, MessengerBindingScope[]>;+ bindingScopesReplica: ReplicaState<MessengerBindingScope[]>;+ installationsMap: Record<string, MessengerInstallationItem[]>;+ installationsReplica: ReplicaState<MessengerInstallationItem[]>;+ linksMap: Record<string, MessengerLinkItem[]>;+ linksReplica: ReplicaState<MessengerLinkItem[]>;+ platformsMap: Record<string, MessengerPlatformItem[]>;+ platformsReplica: ReplicaState<MessengerPlatformItem[]>;+ /** Send-window status, by `messengerPushWindowKey`; memory only. */+ pushWindowMap: Record<string, MessengerPushWindow>;+ pushWindowReplica: ReplicaState<MessengerPushWindow>;+}++export const initialMessengerState: MessengerState = {+ bindingAgentsMap: {},+ bindingAgentsReplica: createReplicaState(),+ bindingScopesMap: {},+ bindingScopesReplica: createReplicaState(),+ installationsMap: {},+ installationsReplica: createReplicaState(),+ linksMap: {},+ linksReplica: createReplicaState(),+ platformsMap: {},+ platformsReplica: createReplicaState(),+ pushWindowMap: {},+ pushWindowReplica: createReplicaState(),+};diff --git a/src/store/messenger/privateAction.ts b/src/store/messenger/privateAction.tsnew file mode 100644index 00000000000..88aca473b76--- /dev/null+++ b/src/store/messenger/privateAction.ts@@ -0,0 +1,84 @@+import { createReplicaSlice, recordLens } from '@/libs/replica';+import { messengerService } from '@/services/messenger';+import type { StoreSetter } from '@/store/types';++import type { MessengerState } from './initialState';+import {+ type MessengerBindingAgent,+ messengerBindingAgentsResource,+ type MessengerBindingScope,+ messengerBindingScopesResource,+ type MessengerInstallationItem,+ messengerInstallationsResource,+ type MessengerLinkItem,+ messengerLinksResource,+ type MessengerPlatformItem,+ messengerPlatformsResource,+ type MessengerPushWindow,+ messengerPushWindowResource,+ toPersistedMessengerInstallations,+} from './projection';++type Setter = StoreSetter<MessengerState>;++export class MessengerPrivateAction {+ readonly bindingAgents;+ readonly bindingScopes;+ readonly installations;+ readonly links;+ readonly platforms;+ readonly pushWindow;++ constructor(set: Setter, get: () => MessengerState) {+ this.platforms = createReplicaSlice(messengerPlatformsResource, {+ actionPrefix: 'messenger/platforms',+ fetcher: () => messengerService.availablePlatforms(),+ get,+ set,+ stateKey: 'platformsReplica',+ view: recordLens<MessengerState, MessengerPlatformItem[]>('platformsMap'),+ });+ this.links = createReplicaSlice(messengerLinksResource, {+ actionPrefix: 'messenger/links',+ fetcher: () => messengerService.listMyLinks(),+ get,+ set,+ stateKey: 'linksReplica',+ view: recordLens<MessengerState, MessengerLinkItem[]>('linksMap'),+ });+ this.installations = createReplicaSlice(messengerInstallationsResource, {+ actionPrefix: 'messenger/installations',+ fetcher: () => messengerService.listMyInstallations(),+ get,+ set,+ stateKey: 'installationsReplica',+ toPersisted: toPersistedMessengerInstallations,+ view: recordLens<MessengerState, MessengerInstallationItem[]>('installationsMap'),+ });+ this.bindingScopes = createReplicaSlice(messengerBindingScopesResource, {+ actionPrefix: 'messenger/bindingScopes',+ fetcher: () => messengerService.listBindingScopes(),+ get,+ set,+ stateKey: 'bindingScopesReplica',+ view: recordLens<MessengerState, MessengerBindingScope[]>('bindingScopesMap'),+ });+ this.bindingAgents = createReplicaSlice(messengerBindingAgentsResource, {+ actionPrefix: 'messenger/bindingAgents',+ fetcher: ({ workspaceId }) => messengerService.listAgentsForBinding(workspaceId),+ get,+ set,+ stateKey: 'bindingAgentsReplica',+ view: recordLens<MessengerState, MessengerBindingAgent[]>('bindingAgentsMap'),+ });+ this.pushWindow = createReplicaSlice(messengerPushWindowResource, {+ actionPrefix: 'messenger/pushWindow',+ fetcher: ({ platform, tenantId }) =>+ messengerService.getMessengerPushWindow(platform, tenantId),+ get,+ set,+ stateKey: 'pushWindowReplica',+ view: recordLens<MessengerState, MessengerPushWindow>('pushWindowMap'),+ });+ }+}diff --git a/src/store/messenger/projection.ts b/src/store/messenger/projection.tsnew file mode 100644index 00000000000..1a126fe937e--- /dev/null+++ b/src/store/messenger/projection.ts@@ -0,0 +1,114 @@+import { defineReplica } from '@/libs/replica';+import type { messengerService } from '@/services/messenger';++type Resolved<T extends (...args: any[]) => Promise<unknown>> = Awaited<ReturnType<T>>;++export type MessengerPlatformItem = Resolved<typeof messengerService.availablePlatforms>[number];+export type MessengerLinkItem = Resolved<typeof messengerService.listMyLinks>[number];+export type MessengerInstallationItem = Resolved<+ typeof messengerService.listMyInstallations+>[number];+export type MessengerBindingScope = Resolved<typeof messengerService.listBindingScopes>[number];+export type MessengerBindingAgent = Resolved<typeof messengerService.listAgentsForBinding>[number];+export type MessengerPushWindow = Resolved<typeof messengerService.getMessengerPushWindow>;++/** The caller-wide lists have a single entry; the scope partitions them per user + workspace. */+export type MessengerListParams = Record<string, never>;+export const MESSENGER_LIST_PARAMS: MessengerListParams = {};+export const MESSENGER_LIST_KEY = 'all';++/** Platforms this deployment enables, with each one's plan-gated access meta. */+export const messengerPlatformsResource = defineReplica<+ MessengerListParams,+ MessengerPlatformItem[]+>({+ key: () => MESSENGER_LIST_KEY,+ name: 'messengerPlatforms',+ storage: 'indexedDB',+ version: 1,+});++/** The caller's account links across platforms and tenants (served without credentials). */+export const messengerLinksResource = defineReplica<MessengerListParams, MessengerLinkItem[]>({+ key: () => MESSENGER_LIST_KEY,+ name: 'messengerLinks',+ storage: 'indexedDB',+ version: 1,+});++/**+ * The caller's System Bot installations (served without credentials). WeChat+ * rows carry the bot's live `runtime` status, which is stripped before+ * persisting: a reload must not replay an old failure, so it stays unknown+ * until the server answers.+ */+export const messengerInstallationsResource = defineReplica<+ MessengerListParams,+ MessengerInstallationItem[]+>({+ key: () => MESSENGER_LIST_KEY,+ name: 'messengerInstallations',+ storage: 'indexedDB',+ version: 1,+});++export const toPersistedMessengerInstallations = (+ items: MessengerInstallationItem[],+): MessengerInstallationItem[] =>+ items.map((item) => (item.runtime === undefined ? item : { ...item, runtime: undefined }));++/** Workspaces the System Bot can route to; personal is implicit. */+export const messengerBindingScopesResource = defineReplica<+ MessengerListParams,+ MessengerBindingScope[]+>({+ key: () => MESSENGER_LIST_KEY,+ name: 'messengerBindingScopes',+ storage: 'indexedDB',+ version: 1,+});++export interface MessengerBindingAgentsParams {+ /** `null` is the personal scope. */+ workspaceId: string | null;+}++export const messengerBindingAgentsKey = ({ workspaceId }: MessengerBindingAgentsParams) =>+ workspaceId ?? '~personal';++/** Agents the System Bot can route to, per picked binding scope. */+export const messengerBindingAgentsResource = defineReplica<+ MessengerBindingAgentsParams,+ MessengerBindingAgent[]+>({+ key: messengerBindingAgentsKey,+ name: 'messengerBindingAgents',+ persist: { maxEntries: 10 },+ storage: 'indexedDB',+ version: 1,+});++export interface MessengerPushWindowParams {+ platform: Parameters<typeof messengerService.getMessengerPushWindow>[0];+ tenantId?: string;+}++export const messengerPushWindowKey = ({ platform, tenantId }: MessengerPushWindowParams) =>+ `${platform}:${tenantId ?? ''}`;++/**+ * Whether the bot can message the caller right now (WeChat's send window and+ * quota move with every inbound message and with time). Live status: shared+ * between the settings card and the push modal in memory, never persisted, so+ * a reload cannot enable Send from an expired window.+ */+export const messengerPushWindowResource = defineReplica<+ MessengerPushWindowParams,+ MessengerPushWindow+>({+ key: messengerPushWindowKey,+ name: 'messengerPushWindow',+ persistKey: () => false,+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/messenger/selectors.ts b/src/store/messenger/selectors.tsnew file mode 100644index 00000000000..38a20a6c647--- /dev/null+++ b/src/store/messenger/selectors.ts@@ -0,0 +1,92 @@+import type { ReplicaState } from '@/libs/replica';++import type { MessengerState } from './initialState';+import {+ MESSENGER_LIST_KEY,+ messengerBindingAgentsKey,+ messengerPushWindowKey,+ type MessengerPushWindowParams,+} from './projection';++/**+ * The server answered in this session. A value restored from the local copy is+ * not confirmed: it may be stale, so an empty restore must read as loading,+ * never as "nothing connected".+ */+const isConfirmed = <T>(replica: ReplicaState<T>, key: string) =>+ replica.entries[key]?.source === 'server';++/** Something to paint: a non-empty local copy, or whatever the server answered. */+const isSettled = (list: unknown[] | undefined, confirmed: boolean) =>+ list !== undefined && (list.length > 0 || confirmed);++const platforms = (s: MessengerState) => s.platformsMap[MESSENGER_LIST_KEY];+const links = (s: MessengerState) => s.linksMap[MESSENGER_LIST_KEY];+const installations = (s: MessengerState) => s.installationsMap[MESSENGER_LIST_KEY];+const bindingScopes = (s: MessengerState) => s.bindingScopesMap[MESSENGER_LIST_KEY];++const isPlatformsConfirmed = (s: MessengerState) =>+ isConfirmed(s.platformsReplica, MESSENGER_LIST_KEY);++const isPlatformsSettled = (s: MessengerState) =>+ isSettled(platforms(s), isConfirmed(s.platformsReplica, MESSENGER_LIST_KEY));++const isLinksConfirmed = (s: MessengerState) => isConfirmed(s.linksReplica, MESSENGER_LIST_KEY);++const isLinksSettled = (s: MessengerState) =>+ isSettled(links(s), isConfirmed(s.linksReplica, MESSENGER_LIST_KEY));++const linksByPlatform = (platform: string) => (s: MessengerState) =>+ links(s)?.filter((link) => link.platform === platform);++const installationsByPlatform = (platform: string) => (s: MessengerState) =>+ installations(s)?.filter((installation) => installation.platform === platform);++/**+ * One platform's detail can render: both lists are known, and either the local+ * copy already shows a connection for this platform or the server confirmed+ * both lists — a restored copy without one may predate a new connection.+ */+const isPlatformDataSettled = (platform: string) => (s: MessengerState) => {+ const platformLinks = linksByPlatform(platform)(s);+ const platformInstallations = installationsByPlatform(platform)(s);+ if (!platformLinks || !platformInstallations) return false;+ if (platformLinks.length > 0 || platformInstallations.length > 0) return true;+ return (+ isConfirmed(s.linksReplica, MESSENGER_LIST_KEY) &&+ isConfirmed(s.installationsReplica, MESSENGER_LIST_KEY)+ );+};++const bindingAgents = (workspaceId: string | null) => (s: MessengerState) =>+ s.bindingAgentsMap[messengerBindingAgentsKey({ workspaceId })];++const isBindingAgentsSettled = (workspaceId: string | null) => (s: MessengerState) =>+ isSettled(+ bindingAgents(workspaceId)(s),+ isConfirmed(s.bindingAgentsReplica, messengerBindingAgentsKey({ workspaceId })),+ );++const isBindingAgentsConfirmed = (workspaceId: string | null) => (s: MessengerState) =>+ isConfirmed(s.bindingAgentsReplica, messengerBindingAgentsKey({ workspaceId }));++const pushWindow = (params: MessengerPushWindowParams) => (s: MessengerState) =>+ s.pushWindowMap[messengerPushWindowKey(params)];++export const messengerSelectors = {+ bindingAgents,+ bindingScopes,+ installations,+ installationsByPlatform,+ isBindingAgentsConfirmed,+ isBindingAgentsSettled,+ isLinksConfirmed,+ isLinksSettled,+ isPlatformDataSettled,+ isPlatformsConfirmed,+ isPlatformsSettled,+ links,+ linksByPlatform,+ platforms,+ pushWindow,+};diff --git a/src/store/messenger/store.ts b/src/store/messenger/store.tsnew file mode 100644index 00000000000..462935013db--- /dev/null+++ b/src/store/messenger/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { initialMessengerState, type MessengerState } from './initialState';++const devtools = createDevtools('messenger');++export const useMessengerStore = createWithEqualityFn<MessengerState>()(+ devtools(() => initialMessengerState),+ shallow,+);++expose('messenger', useMessengerStore);diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.tsindex d6a3a8021a4..a3bdb0a9819 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -14,8 +14,10 @@ import { expertiseActions } from '@/store/expertise';import { useFileStore } from '@/store/file';import { useHomeStore } from '@/store/home';import { useImageStore } from '@/store/image';+import { integrationActions } from '@/store/integration';import { useKnowledgeBaseStore } from '@/store/library';import { useMentionStore } from '@/store/mention';+import { messengerActions } from '@/store/messenger';import { useNotebookStore } from '@/store/notebook';import { pageActions } from '@/store/page';import { projectFileActions } from '@/store/projectFile';@@ -61,6 +63,8 @@ const resetableActions: ResetableStore[] = [channelActions,agentDocumentActions,expertiseActions,+ integrationActions,+ messengerActions,pageActions,projectFileActions,resourcePermissionActions,