Skip to content

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

♻️ refactor(lobehubSkill): move the LobeHub Skill connections onto @lobechat/replica (#20583)

Arvin Xu10dd7a8ec52f
diff --git a/src/features/SkillStore/SkillDetail/LobehubDetailProvider.tsx b/src/features/SkillStore/SkillDetail/LobehubDetailProvider.tsx
index e4746d9f5a2..ce63dafce8b 100644
--- a/src/features/SkillStore/SkillDetail/LobehubDetailProvider.tsx
+++ b/src/features/SkillStore/SkillDetail/LobehubDetailProvider.tsx
@@ -35,7 +35,14 @@ export const LobehubDetailProvider = ({ children, identifier }: LobehubDetailPro
);
const useFetchProviderTools = useToolStore((s) => s.useFetchProviderTools);
- const { data: tools = [], isLoading: toolsLoading } = useFetchProviderTools(identifier);
+ const providerTools = useToolStore((s) => s.lobehubSkillToolsMap[identifier]);
+ const { isHydrated, isValidating } = useFetchProviderTools(identifier);
+
+ // The tool catalog is read from the store (the replica view); the hook only
+ // orchestrates the fetch. `isLoading` means "nothing to show yet" — a
+ // revalidation with the tools already on screen must not blank them.
+ const tools = providerTools ?? [];
+ const toolsLoading = !providerTools && (isValidating || !isHydrated);
if (!config) return null;
diff --git a/src/features/SkillStore/SkillList/LobeHub/useSkillConnect.ts b/src/features/SkillStore/SkillList/LobeHub/useSkillConnect.ts
index aaf701f94b8..9f946005493 100644
--- a/src/features/SkillStore/SkillList/LobeHub/useSkillConnect.ts
+++ b/src/features/SkillStore/SkillList/LobeHub/useSkillConnect.ts
@@ -234,9 +234,11 @@ export const useSkillConnect = ({ identifier, serverName, type }: UseSkillConnec
const provider = lobehubServer.identifier;
await revokeLobehubConnect(provider);
- const latestServer = useToolStore
- .getState()
- .lobehubSkillServers.find((server) => server.identifier === provider);
+ // The list is a replica view: `undefined` means "not loaded yet", which
+ // reads the same as an empty list here (no row ⇒ not connected).
+ const latestServer = (useToolStore.getState().lobehubSkillServers ?? []).find(
+ (server) => server.identifier === provider,
+ );
return latestServer?.status !== LobehubSkillStatus.CONNECTED;
} else if (type === 'composio' && composioServer) {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 9d9bffa1a73..2a3aafa8e2b 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -879,13 +879,6 @@ export const toolKeys = {
]),
composioConnections: def('tool:composioConnections', () => ['tool:composioConnections']),
installedPlugins: def('tool:installedPlugins', () => ['tool:installedPlugins']),
- lobehubSkillConnections: def('tool:lobehubSkillConnections', () => [
- 'tool:lobehubSkillConnections',
- ]),
- lobehubSkillTools: def('tool:lobehubSkillTools', (provider: string) => [
- 'tool:lobehubSkillTools',
- provider,
- ]),
uninstalledBuiltins: def('tool:uninstalledBuiltins', (workspaceId: string | null | undefined) => [
'tool:uninstalledBuiltins',
workspaceId,
diff --git a/src/store/tool/slices/lobehubSkillStore/action.test.ts b/src/store/tool/slices/lobehubSkillStore/action.test.ts
index 1d0529f7cd5..9b347b96a40 100644
--- a/src/store/tool/slices/lobehubSkillStore/action.test.ts
+++ b/src/store/tool/slices/lobehubSkillStore/action.test.ts
@@ -1,18 +1,30 @@
+import { randomUUID } from 'node:crypto';
+
import type * as LobechatConstModule from '@lobechat/const';
import { act, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { cacheScope, createReplicaState } from '@/libs/replica';
import { toolsClient } from '@/libs/trpc/client';
import { useUserStore } from '@/store/user';
import { useToolStore } from '../../store';
+import { initialLobehubSkillStoreState } from './initialState';
import { LobehubSkillStatus } from './types';
+// Each test owns a fresh replica scope, so the store's replica entries and the
+// connections list's local intent never leak from one case to the next.
+let scope = '';
+vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+
beforeEach(() => {
vi.clearAllMocks();
+ scope = `lobehub-skill-action-${randomUUID()}:personal`;
useUserStore.setState({ isSignedIn: false });
+ act(() => useToolStore.setState(initialLobehubSkillStoreState));
});
vi.mock('@lobechat/const', async (importOriginal) => {
@@ -460,8 +472,10 @@ describe('lobehubSkillStore actions', () => {
});
expect(result.current.lobehubSkillServers).toHaveLength(1);
- expect(result.current.lobehubSkillServers[0].isConnected).toBe(true);
- expect(result.current.lobehubSkillServers[0].status).toBe(LobehubSkillStatus.CONNECTED);
+ expect((result.current.lobehubSkillServers ?? [])[0].isConnected).toBe(true);
+ expect((result.current.lobehubSkillServers ?? [])[0].status).toBe(
+ LobehubSkillStatus.CONNECTED,
+ );
});
it('should track loading state during status check', async () => {
@@ -606,7 +620,7 @@ describe('lobehubSkillStore actions', () => {
});
});
- expect(result.current.lobehubSkillServers[0]).toMatchObject({
+ expect((result.current.lobehubSkillServers ?? [])[0]).toMatchObject({
identifier: 'linear',
status: LobehubSkillStatus.ERROR,
errorMessage: 'Token expired',
@@ -668,8 +682,12 @@ describe('lobehubSkillStore actions', () => {
});
expect(refreshed).toBe(true);
- expect(result.current.lobehubSkillServers[0].tokenExpiresAt).toBe('2024-12-31T00:00:00Z');
- expect(result.current.lobehubSkillServers[0].status).toBe(LobehubSkillStatus.CONNECTED);
+ expect((result.current.lobehubSkillServers ?? [])[0].tokenExpiresAt).toBe(
+ '2024-12-31T00:00:00Z',
+ );
+ expect((result.current.lobehubSkillServers ?? [])[0].status).toBe(
+ LobehubSkillStatus.CONNECTED,
+ );
});
it('should return false when refresh fails', async () => {
@@ -758,9 +776,9 @@ describe('lobehubSkillStore actions', () => {
await result.current.refreshLobehubSkillTools('linear');
});
- expect(result.current.lobehubSkillServers[0].tools).toHaveLength(2);
- expect(result.current.lobehubSkillServers[0].tools![0].name).toBe('createIssue');
- expect(result.current.lobehubSkillServers[0].tools![1].name).toBe('listIssues');
+ expect((result.current.lobehubSkillServers ?? [])[0].tools).toHaveLength(2);
+ expect((result.current.lobehubSkillServers ?? [])[0].tools![0].name).toBe('createIssue');
+ expect((result.current.lobehubSkillServers ?? [])[0].tools![1].name).toBe('listIssues');
});
it('should do nothing when server not found', async () => {
@@ -811,7 +829,7 @@ describe('lobehubSkillStore actions', () => {
});
// Should not crash and server should remain unchanged
- expect(result.current.lobehubSkillServers[0].tools).toBeUndefined();
+ expect((result.current.lobehubSkillServers ?? [])[0].tools).toBeUndefined();
});
});
@@ -847,7 +865,7 @@ describe('lobehubSkillStore actions', () => {
});
expect(result.current.lobehubSkillServers).toHaveLength(1);
- expect(result.current.lobehubSkillServers[0].identifier).toBe('github');
+ expect((result.current.lobehubSkillServers ?? [])[0].identifier).toBe('github');
expect(toolsClient.market.connectRevoke.mutate).toHaveBeenCalledWith({
provider: 'linear',
});
@@ -927,7 +945,7 @@ describe('lobehubSkillStore actions', () => {
});
describe('useFetchLobehubSkillConnections', () => {
- it('should not fetch when disabled', () => {
+ it('should not fetch when disabled', async () => {
act(() => {
useToolStore.setState({
lobehubSkillServers: [],
@@ -938,12 +956,16 @@ describe('lobehubSkillStore actions', () => {
vi.mocked(toolsClient.market.connectListConnections.query).mockClear();
- renderHook(() => useToolStore.getState().useFetchLobehubSkillConnections(false));
+ renderHook(() => useToolStore.getState().useFetchLobehubSkillConnections(false), {
+ wrapper: createSWRWrapper(),
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
expect(toolsClient.market.connectListConnections.query).not.toHaveBeenCalled();
});
- it('should not fetch when user is not signed in', () => {
+ it('should not fetch when user is not signed in', async () => {
act(() => {
useToolStore.setState({
lobehubSkillServers: [],
@@ -955,12 +977,16 @@ describe('lobehubSkillStore actions', () => {
vi.mocked(toolsClient.market.connectListConnections.query).mockClear();
- renderHook(() => useToolStore.getState().useFetchLobehubSkillConnections(true));
+ renderHook(() => useToolStore.getState().useFetchLobehubSkillConnections(true), {
+ wrapper: createSWRWrapper(),
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
expect(toolsClient.market.connectListConnections.query).not.toHaveBeenCalled();
});
- it('should fetch connections when enabled', async () => {
+ it('should sync the connections into the replica view when enabled', async () => {
act(() => {
useToolStore.setState({
lobehubSkillServers: [],
@@ -989,16 +1015,34 @@ describe('lobehubSkillStore actions', () => {
tools: [],
});
- renderHook(() => useToolStore.getState().useFetchLobehubSkillConnections(true));
+ renderHook(() => useToolStore.getState().useFetchLobehubSkillConnections(true), {
+ wrapper: createSWRWrapper(),
+ });
await waitFor(() => {
expect(toolsClient.market.connectListConnections.query).toHaveBeenCalled();
});
+
+ await waitFor(() => {
+ expect(useToolStore.getState().lobehubSkillServers).toHaveLength(1);
+ });
+ expect(useToolStore.getState().lobehubSkillServers?.[0].identifier).toBe('linear');
+ expect(useToolStore.getState().lobehubSkillServers?.[0].name).toBe('Linear');
+ expect(useToolStore.getState().lobehubSkillServers?.[0].status).toBe(
+ LobehubSkillStatus.CONNECTED,
+ );
});
});
describe('useFetchProviderTools', () => {
- it('should fetch and normalize provider tools', async () => {
+ it('should fetch, normalize and expose provider tools through the replica view', async () => {
+ act(() => {
+ useToolStore.setState({
+ lobehubSkillToolsMap: {},
+ lobehubSkillToolsReplica: createReplicaState(),
+ });
+ });
+
vi.mocked(toolsClient.market.connectListTools.query).mockResolvedValue({
provider: 'posthog',
tools: [
@@ -1016,86 +1060,46 @@ describe('lobehubSkillStore actions', () => {
);
await waitFor(() => {
- expect(toolsClient.market.connectListTools.query).toHaveBeenCalledWith({
- provider: 'posthog',
- });
+ expect(useToolStore.getState().lobehubSkillToolsMap.posthog).toEqual([
+ {
+ description: 'Run a PostHog query',
+ inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },
+ name: 'query',
+ },
+ ]);
});
- const normalized = await result.current.mutate();
-
- expect(normalized).toEqual([
- {
- description: 'Run a PostHog query',
- inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },
- name: 'query',
- },
- ]);
+ expect(toolsClient.market.connectListTools.query).toHaveBeenCalledWith({
+ provider: 'posthog',
+ });
+ expect(typeof result.current.revalidate).toBe('function');
});
- it('should not fetch tools when provider is undefined', () => {
+ it('should not fetch tools when provider is undefined', async () => {
vi.mocked(toolsClient.market.connectListTools.query).mockClear();
- const { result } = renderHook(
- () => useToolStore.getState().useFetchProviderTools(undefined),
- {
- wrapper: createSWRWrapper(),
- },
- );
-
- expect(result.current.data).toEqual([]);
- expect(toolsClient.market.connectListTools.query).not.toHaveBeenCalled();
- });
- });
-
- describe('server deduplication logic', () => {
- it('should deduplicate servers by identifier when adding new servers', () => {
act(() => {
useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
+ lobehubSkillToolsMap: {},
+ lobehubSkillToolsReplica: createReplicaState(),
});
});
- const incomingServers = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- {
- identifier: 'github',
- name: 'GitHub',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
-
- act(() => {
- const existingServers = useToolStore.getState().lobehubSkillServers;
- const existingIdentifiers = new Set(existingServers.map((s) => s.identifier));
- const newServers = incomingServers.filter((s) => !existingIdentifiers.has(s.identifier));
-
- useToolStore.setState({
- lobehubSkillServers: [...existingServers, ...newServers],
- });
+ renderHook(() => useToolStore.getState().useFetchProviderTools(undefined), {
+ wrapper: createSWRWrapper(),
});
- const finalServers = useToolStore.getState().lobehubSkillServers;
- expect(finalServers).toHaveLength(2);
- expect(finalServers.find((s) => s.identifier === 'linear')).toBeDefined();
- expect(finalServers.find((s) => s.identifier === 'github')).toBeDefined();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(toolsClient.market.connectListTools.query).not.toHaveBeenCalled();
+ expect(useToolStore.getState().lobehubSkillToolsMap).toEqual({});
});
+ });
+
+ describe('connection list identity', () => {
+ it('keeps one row when the same provider connects twice', async () => {
+ const { result } = renderHook(() => useToolStore());
- it('should add all servers when none exist', () => {
act(() => {
useToolStore.setState({
lobehubSkillServers: [],
@@ -1104,26 +1108,24 @@ describe('lobehubSkillStore actions', () => {
});
});
- const incomingServers = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
-
- act(() => {
- const existingServers = useToolStore.getState().lobehubSkillServers;
- const existingIdentifiers = new Set(existingServers.map((s) => s.identifier));
- const newServers = incomingServers.filter((s) => !existingIdentifiers.has(s.identifier));
+ vi.mocked(toolsClient.market.connectGetStatus.query).mockResolvedValue({
+ connected: true,
+ icon: 'linear-icon',
+ } as any);
+ vi.mocked(toolsClient.market.connectListTools.query).mockResolvedValue({
+ provider: 'linear',
+ tools: [],
+ });
- useToolStore.setState({
- lobehubSkillServers: [...existingServers, ...newServers],
- });
+ await act(async () => {
+ await result.current.checkLobehubSkillStatus('linear');
+ });
+ await act(async () => {
+ await result.current.checkLobehubSkillStatus('linear');
});
- expect(useToolStore.getState().lobehubSkillServers).toHaveLength(1);
+ expect(result.current.lobehubSkillServers).toHaveLength(1);
+ expect(result.current.lobehubSkillServers?.[0].identifier).toBe('linear');
});
});
});
diff --git a/src/store/tool/slices/lobehubSkillStore/action.ts b/src/store/tool/slices/lobehubSkillStore/action.ts
index 8cf3c2202df..66dd2baa5c9 100644
--- a/src/store/tool/slices/lobehubSkillStore/action.ts
+++ b/src/store/tool/slices/lobehubSkillStore/action.ts
@@ -1,9 +1,14 @@
import { getLobehubSkillProviderById } from '@lobechat/const';
import { produce } from 'immer';
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
-import { toolKeys } from '@/libs/swr/keys';
+import {
+ cacheScope,
+ createReplicaSlice,
+ linkReplicaEntity,
+ recordLens,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
import { toolsClient } from '@/libs/trpc/client';
import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
@@ -12,6 +17,16 @@ import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
import { type LobehubSkillStoreState } from './initialState';
+import {
+ createLobehubSkillLocalIntent,
+ LOBEHUB_SKILL_SERVERS_KEY,
+ type LobehubSkillLocalIntent,
+ lobehubSkillProviderToolsResource,
+ lobehubSkillServersEntity,
+ lobehubSkillServersResource,
+ mapProviderTools,
+ mergeLobehubSkillServers,
+} from './projection';
import {
type CallLobehubSkillToolParams,
type CallLobehubSkillToolResult,
@@ -26,18 +41,90 @@ const n = setNamespace('lobehubSkillStore');
* LobeHub Skill Store Actions
*/
+/** The connections list is one entry, so every sync shares these params. */
+const SERVERS_PARAMS = {} as Record<string, never>;
+
+/**
+ * The connections list keeps its long-standing flat `lobehubSkillServers` field
+ * as the replica view, so every selector reads what it did. `undefined` means
+ * "not loaded yet": the engine only hydrates an empty slot, so an empty-array
+ * default would read as a real value and block the persisted row.
+ */
+const serversLens: ReplicaLens<ToolStore, LobehubSkillServer[]> = {
+ clear: () => ({ lobehubSkillServers: undefined }),
+ get: (state) => state.lobehubSkillServers,
+ keys: (state) => (state.lobehubSkillServers ? [LOBEHUB_SKILL_SERVERS_KEY] : []),
+ set: (_state, _key, data) => ({ lobehubSkillServers: data }),
+};
+
+/** The connections sync, plus the `mutate` alias the skills surfaces call. */
+export interface LobehubSkillConnectionsSyncResult extends ReplicaSyncResult {
+ /**
+ * Nothing has been painted yet (no persisted row, no response) and a sync is
+ * in flight. This is the `isLoading` the callers gated on before the replica
+ * — it must stay on the public surface: a caller that reads "un-loaded" as
+ * "empty" would flash a false state on a cold start (see `ToolAuthAlert`).
+ */
+ isLoading: boolean;
+ /** Alias of `revalidate`, kept for the existing "reload skills" control. */
+ mutate: () => Promise<unknown>;
+}
+
type Setter = StoreSetter<ToolStore>;
export const createLobehubSkillStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
new LobehubSkillStoreActionImpl(set, get, _api);
export class LobehubSkillStoreActionImpl {
readonly #get: () => ToolStore;
+ #intent = createLobehubSkillLocalIntent();
+ #intentScope?: string;
+ /**
+ * One provider's tool catalog, keyed by provider id — the replica view the
+ * skill detail surfaces render from.
+ */
+ readonly #providerTools;
+ /**
+ * The user's connected providers — a `@lobechat/replica` list, so the
+ * persisted row paints before the network answers and a connect / revoke shows
+ * on the row at once.
+ */
+ readonly #servers;
+ /** Entity handle so per-provider changes reach every place holding the row. */
+ readonly #server;
readonly #set: Setter;
constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#servers = createReplicaSlice(lobehubSkillServersResource, {
+ actionPrefix: 'lobehubSkillServers',
+ entity: lobehubSkillServersEntity,
+ fetcher: () => this.#fetchServers(),
+ get,
+ // A list response replaces the whole value; merge local intent the
+ // response predates so an in-flight sync cannot drop a just-connected
+ // provider or resurrect a just-revoked one. The confirmed value is passed
+ // in too, so a response without a tool catalog keeps the tools the row
+ // already holds (see `mergeLobehubSkillServers`).
+ merge: (incoming, confirmed) =>
+ mergeLobehubSkillServers(incoming, this.#localIntent(), confirmed),
+ set,
+ stateKey: 'lobehubSkillServersReplica',
+ view: serversLens,
+ });
+ this.#server = linkReplicaEntity<LobehubSkillServer>([this.#servers]);
+ this.#providerTools = createReplicaSlice(lobehubSkillProviderToolsResource, {
+ actionPrefix: 'lobehubSkillProviderTools',
+ fetcher: async (provider) => {
+ const response = await toolsClient.market.connectListTools.query({ provider });
+ return mapProviderTools(response.tools);
+ },
+ get,
+ set,
+ stateKey: 'lobehubSkillToolsReplica',
+ view: recordLens<ToolStore, LobehubSkillTool[]>('lobehubSkillToolsMap'),
+ });
}
callLobehubSkillTool = async (
@@ -146,16 +233,10 @@ export class LobehubSkillStoreActionImpl {
tokenExpiresAt: response.connection?.tokenExpiresAt,
};
+ this.#upsertServer(server);
+
this.#set(
produce((draft: LobehubSkillStoreState) => {
- const existingIndex = draft.lobehubSkillServers.findIndex(
- (s) => s.identifier === provider,
- );
- if (existingIndex >= 0) {
- draft.lobehubSkillServers[existingIndex] = server;
- } else {
- draft.lobehubSkillServers.push(server);
- }
draft.lobehubSkillLoadingIds.delete(provider);
}),
false,
@@ -203,19 +284,7 @@ export class LobehubSkillStoreActionImpl {
provider: string,
update: Partial<LobehubSkillServer>,
): void => {
- this.#set(
- produce((draft: LobehubSkillStoreState) => {
- const serverIndex = draft.lobehubSkillServers.findIndex((s) => s.identifier === provider);
- if (serverIndex >= 0) {
- draft.lobehubSkillServers[serverIndex] = {
- ...draft.lobehubSkillServers[serverIndex],
- ...update,
- };
- }
- }),
- false,
- n('internal_updateLobehubSkillServer'),
- );
+ this.#server.update(provider, (server) => ({ ...server, ...update }));
};
refreshLobehubSkillToken = async (provider: string): Promise<boolean> => {
@@ -240,16 +309,10 @@ export class LobehubSkillStoreActionImpl {
try {
const response = await toolsClient.market.connectListTools.query({ provider });
- this.#set(
- produce((draft: LobehubSkillStoreState) => {
- const serverIndex = draft.lobehubSkillServers.findIndex((s) => s.identifier === provider);
- if (serverIndex >= 0) {
- draft.lobehubSkillServers[serverIndex].tools = response.tools as LobehubSkillTool[];
- }
- }),
- false,
- n('refreshLobehubSkillTools/success'),
- );
+ this.#server.update(provider, (server) => ({
+ ...server,
+ tools: response.tools as LobehubSkillTool[],
+ }));
} catch (error) {
console.error('[LobehubSkill] Failed to refresh tools:', error);
}
@@ -267,11 +330,15 @@ export class LobehubSkillStoreActionImpl {
try {
await toolsClient.market.connectRevoke.mutate({ provider });
+ // Drop the row locally, and keep a list response that was already in
+ // flight from bringing the revoked provider back.
+ const intent = this.#localIntent();
+ intent.added.delete(provider);
+ intent.removed.add(provider);
+ this.#server.remove(provider);
+
this.#set(
produce((draft: LobehubSkillStoreState) => {
- draft.lobehubSkillServers = draft.lobehubSkillServers.filter(
- (s) => s.identifier !== provider,
- );
draft.lobehubSkillLoadingIds.delete(provider);
}),
false,
@@ -290,75 +357,96 @@ export class LobehubSkillStoreActionImpl {
}
};
- useFetchLobehubSkillConnections = (enabled: boolean): SWRResponse<LobehubSkillServer[]> => {
+ /**
+ * Fetch orchestration only; read the tools through `lobehubSkillToolsMap`.
+ * One replica entry per provider, so switching providers paints the cached
+ * tools and the network only confirms.
+ */
+ useFetchProviderTools = (provider: string | undefined): ReplicaSyncResult =>
+ this.#providerTools.useSync(provider ?? null, { revalidateOnFocus: false });
+
+ /**
+ * Fetch orchestration only; read the list through `lobehubSkillSelectors`.
+ * The persisted row paints the first frame, and a connect / revoke is folded
+ * into the same replica entry the surfaces already read.
+ */
+ useFetchLobehubSkillConnections = (enabled: boolean): LobehubSkillConnectionsSyncResult => {
const isSignedIn = useUserStore(authSelectors.isLogin);
- return useSWR<LobehubSkillServer[]>(
- enabled && isSignedIn ? toolKeys.lobehubSkillConnections() : null,
- async () => {
- const response = await toolsClient.market.connectListConnections.query();
-
- // Debug logging
-
- return response.connections.map((conn: any) => {
- // Debug logging for each connection
-
- // Get provider config from local definition for correct display name
- const providerConfig = getLobehubSkillProviderById(conn.providerId);
- return {
- cachedAt: Date.now(),
- icon: conn.icon,
- identifier: conn.providerId,
- isConnected: true,
- // Use local config label (e.g., "Linear") instead of API's providerName (which is user's name on that service)
- name: providerConfig?.label || conn.providerId,
- providerUsername: conn.providerUsername,
- scopes: conn.scopes,
- status: LobehubSkillStatus.CONNECTED,
- tokenExpiresAt: conn.tokenExpiresAt,
- };
- });
- },
- {
- onSuccess: (data) => {
- if (data.length > 0) {
- this.#set(
- produce((draft: LobehubSkillStoreState) => {
- const existingIds = new Set(draft.lobehubSkillServers.map((s) => s.identifier));
- const newServers = data.filter((s) => !existingIds.has(s.identifier));
- draft.lobehubSkillServers = [...draft.lobehubSkillServers, ...newServers];
- }),
- false,
- n('useFetchLobehubSkillConnections'),
- );
-
- for (const server of data) {
- this.#get().refreshLobehubSkillTools(server.identifier);
- }
- }
- },
- revalidateOnFocus: false,
- shouldRetryOnError: false,
+ const sync = this.#servers.useSync(SERVERS_PARAMS, {
+ enabled: enabled && isSignedIn,
+ onSuccess: (servers) => {
+ // The connections response carries no tools; fill each connected
+ // provider's catalog so the agent tool list can resolve them.
+ for (const server of servers) {
+ this.#get().refreshLobehubSkillTools(server.identifier);
+ }
},
- );
+ revalidateOnFocus: false,
+ });
+
+ // `isLoading` in the pre-replica sense: the list has not been painted yet
+ // (neither the persisted row nor a response) and a sync is in flight. It is
+ // read through the view instead of `isHydrated`, because hydration resolves
+ // just after mount even when there is nothing stored — gating on it would
+ // re-open the cold-start false state this flag exists to prevent.
+ const isLoading = this.#get().lobehubSkillServers === undefined && sync.isValidating;
+
+ return { ...sync, isLoading, mutate: sync.revalidate };
};
- useFetchProviderTools = (provider: string | undefined): SWRResponse<LobehubSkillTool[]> => {
- return useSWR<LobehubSkillTool[]>(
- provider ? toolKeys.lobehubSkillTools(provider) : null,
- async () => {
- const response = await toolsClient.market.connectListTools.query({ provider: provider! });
- return (response.tools || []).map((tool: any) => ({
- description: tool.description,
- inputSchema: tool.inputSchema,
- name: tool.name,
- }));
- },
- {
- fallbackData: [],
- revalidateOnFocus: false,
- },
- );
+ /**
+ * Local intent of the active identity. Kept per scope: the intent is about
+ * this user's unsynced writes, so a workspace / user switch starts clean
+ * rather than carrying the previous identity's pending rows over.
+ */
+ #localIntent = (): LobehubSkillLocalIntent => {
+ const scope = cacheScope.get();
+ if (scope !== this.#intentScope) {
+ this.#intentScope = scope;
+ this.#intent = createLobehubSkillLocalIntent();
+ }
+ return this.#intent;
+ };
+
+ /** Replace the row in place (by identifier) or append the new one. */
+ #upsertServer = (server: LobehubSkillServer): void => {
+ // The two intents are mutually exclusive per provider: a fresh write
+ // supersedes a pending revoke, so a re-connect inside the race window is
+ // never hidden by the previous revoke.
+ const intent = this.#localIntent();
+ intent.removed.delete(server.identifier);
+ // The row survives a list response that was already in flight when it was
+ // written (see `mergeLobehubSkillServers`).
+ intent.added.set(server.identifier, server);
+ this.#servers.update(LOBEHUB_SKILL_SERVERS_KEY, (servers) => {
+ const list = servers ?? [];
+ const index = list.findIndex((s) => s.identifier === server.identifier);
+ if (index < 0) return [...list, server];
+ return list.map((s, i) => (i === index ? { ...s, ...server } : s));
+ });
+ };
+
+ /** The user's connected providers (`connectListConnections`). */
+ #fetchServers = async (): Promise<LobehubSkillServer[]> => {
+ const response = await toolsClient.market.connectListConnections.query();
+
+ return response.connections.map((conn: any) => {
+ // Get provider config from local definition for correct display name
+ const providerConfig = getLobehubSkillProviderById(conn.providerId);
+ return {
+ cachedAt: Date.now(),
+ icon: conn.icon,
+ identifier: conn.providerId,
+ isConnected: true,
+ // Use local config label (e.g., "Linear") instead of API's providerName (which is user's name on that service)
+ name: providerConfig?.label || conn.providerId,
+ providerUsername: conn.providerUsername,
+ scopes: conn.scopes,
+ status: LobehubSkillStatus.CONNECTED,
+ tokenExpiresAt: conn.tokenExpiresAt,
+ };
+ });
};
}
diff --git a/src/store/tool/slices/lobehubSkillStore/index.ts b/src/store/tool/slices/lobehubSkillStore/index.ts
index 7ebb1ea9dd2..0b3e7450321 100644
--- a/src/store/tool/slices/lobehubSkillStore/index.ts
+++ b/src/store/tool/slices/lobehubSkillStore/index.ts
@@ -1,4 +1,5 @@
export * from './action';
export * from './initialState';
+export * from './projection';
export * from './selectors';
export * from './types';
diff --git a/src/store/tool/slices/lobehubSkillStore/initialState.ts b/src/store/tool/slices/lobehubSkillStore/initialState.ts
index 035775f7c66..8019773c9a8 100644
--- a/src/store/tool/slices/lobehubSkillStore/initialState.ts
+++ b/src/store/tool/slices/lobehubSkillStore/initialState.ts
@@ -1,17 +1,31 @@
-import { type LobehubSkillServer } from './types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import { type LobehubSkillServer, type LobehubSkillTool } from './types';
/**
* LobeHub Skill Store state interface
*
- * NOTE: All connection states and tool data are fetched in real-time from Market API, not stored in local database
+ * NOTE: connection states and tool data are a local-first copy of the Market
+ * API — the replica persists them and the network only confirms.
*/
export interface LobehubSkillStoreState {
/** Set of executing tool call IDs */
lobehubSkillExecutingToolIds: Set<string>;
/** Set of loading Provider IDs */
lobehubSkillLoadingIds: Set<string>;
- /** List of connected LobeHub Skill Servers */
- lobehubSkillServers: LobehubSkillServer[];
+ /**
+ * The connected providers of the active scope — the view of the
+ * `lobehubSkillServers` replica. `undefined` until the persisted row hydrates
+ * or the first network response lands, so an un-loaded list never reads as an
+ * empty one (and the empty default never blocks hydration).
+ */
+ lobehubSkillServers?: LobehubSkillServer[];
+ /** Replica bookkeeping of `lobehubSkillServers`. */
+ lobehubSkillServersReplica: ReplicaState<LobehubSkillServer[]>;
+ /** Replica view of the provider tool catalogs, one entry per provider id. */
+ lobehubSkillToolsMap: Record<string, LobehubSkillTool[]>;
+ /** Replica bookkeeping of `lobehubSkillToolsMap`. */
+ lobehubSkillToolsReplica: ReplicaState<LobehubSkillTool[]>;
}
/**
@@ -20,5 +34,9 @@ export interface LobehubSkillStoreState {
export const initialLobehubSkillStoreState: LobehubSkillStoreState = {
lobehubSkillExecutingToolIds: new Set(),
lobehubSkillLoadingIds: new Set(),
- lobehubSkillServers: [],
+ // Absent until the persisted row hydrates or the first network response lands.
+ lobehubSkillServers: undefined,
+ lobehubSkillServersReplica: createReplicaState(),
+ lobehubSkillToolsMap: {},
+ lobehubSkillToolsReplica: createReplicaState(),
};
diff --git a/src/store/tool/slices/lobehubSkillStore/projection.test.ts b/src/store/tool/slices/lobehubSkillStore/projection.test.ts
new file mode 100644
index 00000000000..e6375859994
--- /dev/null
+++ b/src/store/tool/slices/lobehubSkillStore/projection.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createLobehubSkillLocalIntent,
+ type LobehubSkillLocalIntent,
+ mergeLobehubSkillServers,
+} from './projection';
+import { type LobehubSkillServer, LobehubSkillStatus } from './types';
+
+const tool = (name: string) => ({
+ description: `${name} tool`,
+ inputSchema: { type: 'object' },
+ name,
+});
+
+const server = (identifier: string, tools?: LobehubSkillServer['tools']): LobehubSkillServer => ({
+ identifier,
+ isConnected: true,
+ name: identifier,
+ status: LobehubSkillStatus.CONNECTED,
+ ...(tools ? { tools } : {}),
+});
+
+describe('mergeLobehubSkillServers', () => {
+ it('keeps a confirmed row’s tools when the response carries none', () => {
+ const confirmed = [server('linear', [tool('createIssue')])];
+
+ const merged = mergeLobehubSkillServers(
+ [server('linear')],
+ createLobehubSkillLocalIntent(),
+ confirmed,
+ );
+
+ expect(merged).toHaveLength(1);
+ expect(merged[0].tools).toEqual([tool('createIssue')]);
+ });
+
+ it('lets a fresh catalog replace the cached one', () => {
+ const confirmed = [server('linear', [tool('createIssue')])];
+
+ const merged = mergeLobehubSkillServers(
+ [server('linear', [tool('listIssues')])],
+ createLobehubSkillLocalIntent(),
+ confirmed,
+ );
+
+ expect(merged[0].tools).toEqual([tool('listIssues')]);
+ });
+
+ it('does not attach cached tools to a provider the response no longer lists', () => {
+ const confirmed = [server('linear', [tool('createIssue')])];
+
+ const merged = mergeLobehubSkillServers([], createLobehubSkillLocalIntent(), confirmed);
+
+ expect(merged).toEqual([]);
+ });
+
+ it('keeps the response reference when there is no cached catalog', () => {
+ const incoming = [server('linear')];
+
+ const merged = mergeLobehubSkillServers(incoming, createLobehubSkillLocalIntent(), []);
+
+ expect(merged).toBe(incoming);
+ });
+
+ it('carries cached tools onto a pending add and still settles the intent', () => {
+ const intent: LobehubSkillLocalIntent = createLobehubSkillLocalIntent();
+ intent.added.set('github', server('github'));
+
+ // The response does not list the just-connected provider yet, and it also
+ // drops the tools of the provider it does list.
+ const merged = mergeLobehubSkillServers([server('linear')], intent, [
+ server('linear', [tool('createIssue')]),
+ server('github', [tool('listIssues')]),
+ ]);
+
+ expect(merged.map((s) => s.identifier)).toEqual(['linear', 'github']);
+ expect(merged[0].tools).toEqual([tool('createIssue')]);
+ expect(merged[1].tools).toEqual([tool('listIssues')]);
+
+ // Once the response echoes `github`, the pending add settles.
+ const settled: LobehubSkillLocalIntent = createLobehubSkillLocalIntent();
+ settled.added.set('github', server('github'));
+ mergeLobehubSkillServers([server('linear'), server('github')], settled, []);
+
+ expect(settled.added.size).toBe(0);
+ });
+});
diff --git a/src/store/tool/slices/lobehubSkillStore/projection.ts b/src/store/tool/slices/lobehubSkillStore/projection.ts
new file mode 100644
index 00000000000..73720885b04
--- /dev/null
+++ b/src/store/tool/slices/lobehubSkillStore/projection.ts
@@ -0,0 +1,139 @@
+import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';
+
+import { type LobehubSkillServer, type LobehubSkillTool } from './types';
+
+/** The user's connected LobeHub Skill providers are one list entry per scope. */
+export const LOBEHUB_SKILL_SERVERS_KEY = 'all';
+
+/**
+ * The user's connected LobeHub Skill providers (`connectListConnections`): a
+ * local-first replica, so the settings / skill-store / chat-input surfaces paint
+ * the persisted list on the first frame and the network only confirms it.
+ *
+ * The list is not partitioned per container, so every sync shares one key.
+ */
+export const lobehubSkillServersResource = defineReplica<
+ Record<string, never>,
+ LobehubSkillServer[]
+>({
+ key: () => LOBEHUB_SKILL_SERVERS_KEY,
+ name: 'lobehubSkillServers',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** A provider is addressed by its `identifier` across the tool store. */
+export const lobehubSkillServersEntity: ReplicaEntityAdapter<
+ LobehubSkillServer[],
+ LobehubSkillServer
+> = arrayEntity<LobehubSkillServer>((server) => server.identifier);
+
+/**
+ * One provider's tool catalog (`connectListTools`), keyed by provider id.
+ * Read-only and shared by the skill detail surfaces, so a persisted copy paints
+ * the tools before the network answers.
+ */
+export const lobehubSkillProviderToolsResource = defineReplica<string, LobehubSkillTool[]>({
+ key: (provider) => provider,
+ name: 'lobehubSkillProviderTools',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * The value a tool catalog is normalized to before it enters the replica: the
+ * market response carries fields the UI never reads, so only the shape the
+ * detail surfaces render is kept.
+ */
+export const mapProviderTools = (tools: unknown): LobehubSkillTool[] =>
+ ((tools as any[]) || []).map((tool) => ({
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ name: tool.name,
+ }));
+
+/**
+ * Local intent of the connections replica that the server has not echoed yet:
+ * rows this client wrote, and rows it revoked. Kept only until a response
+ * reflects them.
+ */
+export interface LobehubSkillLocalIntent {
+ /** Written rows, by `identifier` — re-appended until the server echoes them. */
+ added: Map<string, LobehubSkillServer>;
+ /** Revoked `identifier`s — hidden until a response confirms they are gone. */
+ removed: Set<string>;
+}
+
+export const createLobehubSkillLocalIntent = (): LobehubSkillLocalIntent => ({
+ added: new Map(),
+ removed: new Set(),
+});
+
+/**
+ * Folds a connections response into the replica without discarding local intent
+ * the response predates.
+ *
+ * An OAuth completion writes a row (and a disconnect drops one), but a
+ * `connectListConnections` response that was already in flight when the write
+ * happened still arrives afterwards and `replace`s the whole value: the
+ * just-connected row would vanish, or the just-revoked one would come back.
+ * `replace` carries no request ordering, so the response is merged instead of
+ * trusted blindly: a pending add is re-appended until the server echoes it, a
+ * pending removal stays hidden until a response confirms it is gone. Each
+ * settles the moment a response reflects it, after which the server is
+ * authoritative again.
+ *
+ * The list response also carries no tool catalog, so a confirmed row's tools
+ * are carried over whenever the response omits them — the agent tool list keeps
+ * resolving a connected provider even if the follow-up `connectListTools` call
+ * fails.
+ */
+export const mergeLobehubSkillServers = (
+ incoming: LobehubSkillServer[],
+ intent: LobehubSkillLocalIntent,
+ confirmed?: LobehubSkillServer[],
+): LobehubSkillServer[] => {
+ const echoed = new Set(incoming.map((server) => server.identifier));
+
+ // A response confirms a pending add (echoed) or drop (gone): settle it.
+ for (const identifier of intent.added.keys()) {
+ if (echoed.has(identifier)) intent.added.delete(identifier);
+ }
+ for (const identifier of intent.removed) {
+ if (!echoed.has(identifier)) intent.removed.delete(identifier);
+ }
+
+ const kept = intent.removed.size
+ ? incoming.filter((server) => !intent.removed.has(server.identifier))
+ : incoming;
+ const carried = [...intent.added.values()];
+
+ // `connectListConnections` carries no tool catalog, so the response alone
+ // would drop the tools a confirmed row already holds. Keep them until a
+ // `connectListTools` success replaces them: a transient tool-fetch failure
+ // must not remove a connected provider from the agent tool list while a
+ // usable persisted catalog still exists.
+ const cachedTools = new Map<string, LobehubSkillTool[]>();
+ for (const server of confirmed ?? []) {
+ if (server.tools?.length) cachedTools.set(server.identifier, server.tools);
+ }
+ const keepTools = (server: LobehubSkillServer): LobehubSkillServer => {
+ if (server.tools?.length) return server;
+ const tools = cachedTools.get(server.identifier);
+ return tools ? { ...server, tools } : server;
+ };
+ const withCachedTools = (list: LobehubSkillServer[]): LobehubSkillServer[] => {
+ if (cachedTools.size === 0) return list;
+ const next = list.map(keepTools);
+ // Return the original list when nothing gained tools, so an unchanged
+ // response keeps its reference (no needless write).
+ return next.some((server, index) => server !== list[index]) ? next : list;
+ };
+
+ const keptWithTools = withCachedTools(kept);
+ const carriedWithTools = withCachedTools(carried);
+
+ if (carriedWithTools.length === 0 && keptWithTools === incoming) return incoming;
+
+ return [...keptWithTools, ...carriedWithTools];
+};
diff --git a/src/store/tool/slices/lobehubSkillStore/replica.test.ts b/src/store/tool/slices/lobehubSkillStore/replica.test.ts
new file mode 100644
index 00000000000..7e26fd12965
--- /dev/null
+++ b/src/store/tool/slices/lobehubSkillStore/replica.test.ts
@@ -0,0 +1,520 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The connected LobeHub Skill providers are a replica: the settings / skill
+ * store / chat-input surfaces paint the persisted list on the first frame, the
+ * network only confirms, and a connect / revoke shows on the row at once. One
+ * provider's tool catalog is a replica too.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type * as LobechatConstModule from '@lobechat/const';
+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 } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { useUserStore } from '@/store/user';
+
+import { useToolStore } from '../../store';
+import { initialLobehubSkillStoreState } from './initialState';
+import { lobehubSkillProviderToolsResource, lobehubSkillServersResource } from './projection';
+import { lobehubSkillStoreSelectors } from './selectors';
+import { LobehubSkillStatus } from './types';
+
+const mocks = vi.hoisted(() => ({
+ connectGetStatus: vi.fn(),
+ connectListConnections: vi.fn(),
+ connectListTools: vi.fn(),
+ connectRevoke: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ toolsClient: {
+ market: {
+ connectGetStatus: { query: mocks.connectGetStatus },
+ connectListConnections: { query: mocks.connectListConnections },
+ connectListTools: { query: mocks.connectListTools },
+ connectRevoke: { mutate: mocks.connectRevoke },
+ },
+ },
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<typeof LobechatConstModule>();
+ return {
+ ...actual,
+ getLobehubSkillProviderById: vi.fn((id: string) => ({
+ id,
+ label: id.charAt(0).toUpperCase() + id.slice(1),
+ icon: 'đź”—',
+ })),
+ };
+});
+
+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,
+ );
+
+/** A connection row, as the Market `connectListConnections` returns it. */
+const connection = (providerId: string) => ({
+ icon: `${providerId}-icon`,
+ providerId,
+ providerUsername: 'testuser',
+ scopes: ['read'],
+ tokenExpiresAt: '2024-12-31T00:00:00Z',
+});
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const SERVERS_STORAGE_KEY = lobehubSkillServersResource.storageKey({} as Record<string, never>);
+const PROVIDER_TOOLS_STORAGE_KEY = lobehubSkillProviderToolsResource.storageKey('linear');
+
+const serverIds = () =>
+ (useToolStore.getState().lobehubSkillServers ?? []).map((s) => s.identifier);
+
+describe('lobehubSkill connections replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`lobehub-skill-user-${randomUUID()}:personal`);
+ act(() => useToolStore.setState(initialLobehubSkillStoreState));
+ act(() => useUserStore.setState({ isSignedIn: true }));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all([
+ ...[...scopes].map((value) =>
+ lobehubSkillServersResource.storage!.remove({
+ queryKey: SERVERS_STORAGE_KEY,
+ scope: value,
+ }),
+ ),
+ ...[...scopes].map((value) =>
+ lobehubSkillProviderToolsResource.storage!.remove({
+ queryKey: PROVIDER_TOOLS_STORAGE_KEY,
+ scope: value,
+ }),
+ ),
+ ]);
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted list before the network answers', async () => {
+ const cached = {
+ identifier: 'linear',
+ isConnected: true,
+ name: 'Linear',
+ status: LobehubSkillStatus.CONNECTED,
+ };
+ await lobehubSkillServersResource.storage!.set(
+ { queryKey: SERVERS_STORAGE_KEY, scope },
+ { data: [cached], updatedAt: 1 },
+ );
+ mocks.connectListConnections.mockImplementation(pending);
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ });
+
+ it('keeps the pre-replica sync surface: isLoading is true until the list is painted', async () => {
+ // The caller gates on `isLoading` (ToolAuthAlert): reading an un-loaded list
+ // as an empty one flashes a false "needs authorization" card on a cold start.
+ mocks.connectListConnections.mockImplementation(pending);
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(sync.result.current.isLoading).toBe(true));
+ // Must be a real boolean: `isLoading` reading as `undefined` made
+ // `!isLoading` true, so the caller treated an un-loaded list as initialized
+ // and flashed a false "needs authorization" card on a cold start.
+ expect(typeof sync.result.current.isLoading).toBe('boolean');
+ expect(typeof sync.result.current.mutate).toBe('function');
+ expect(sync.result.current.error).toBeUndefined();
+
+ // The response lands: the list is painted and the flag clears.
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+ expect(sync.result.current.isLoading).toBe(false);
+ });
+
+ it('does not report loading once the persisted row has painted', async () => {
+ await lobehubSkillServersResource.storage!.set(
+ { queryKey: SERVERS_STORAGE_KEY, scope },
+ {
+ data: [
+ {
+ identifier: 'linear',
+ isConnected: true,
+ name: 'Linear',
+ status: LobehubSkillStatus.CONNECTED,
+ },
+ ],
+ updatedAt: 1,
+ },
+ );
+ mocks.connectListConnections.mockImplementation(pending);
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+ expect(sync.result.current.isLoading).toBe(false);
+ });
+
+ it('replaces the list with the server response and persists it', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+
+ renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), { wrapper });
+
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+ const [server] = useToolStore.getState().lobehubSkillServers!;
+ expect(server.name).toBe('Linear');
+ expect(server.status).toBe(LobehubSkillStatus.CONNECTED);
+ expect(server.providerUsername).toBe('testuser');
+
+ await waitFor(async () =>
+ expect(
+ (
+ await lobehubSkillServersResource.storage!.get({
+ queryKey: SERVERS_STORAGE_KEY,
+ scope,
+ })
+ )?.data.map((s) => s.identifier),
+ ).toEqual(['linear']),
+ );
+ });
+
+ it('drops the previous identity’s servers before the next one paints', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(serverIds()).toHaveLength(1));
+
+ mocks.connectListConnections.mockImplementation(pending);
+ useScope(`lobehub-skill-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(useToolStore.getState().lobehubSkillServers).toBeUndefined());
+ });
+
+ it('does not fetch while the sync is disabled', async () => {
+ renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(false), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(mocks.connectListConnections).not.toHaveBeenCalled();
+ expect(useToolStore.getState().lobehubSkillServers).toBeUndefined();
+ });
+
+ it('shows a newly connected provider at once', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+ mocks.connectGetStatus.mockResolvedValue({
+ connected: true,
+ connection: { providerUsername: 'testuser' },
+ icon: 'github-icon',
+ });
+
+ renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), { wrapper });
+ await waitFor(() => expect(useToolStore.getState().lobehubSkillServers).toEqual([]));
+
+ await act(async () => {
+ await useToolStore.getState().checkLobehubSkillStatus('github');
+ });
+
+ expect(serverIds()).toEqual(['github']);
+ expect(useToolStore.getState().lobehubSkillServers![0].status).toBe(
+ LobehubSkillStatus.CONNECTED,
+ );
+ });
+
+ it('keeps a just-connected provider when a list response that predates it lands', async () => {
+ // The list loads empty first, then a response racing the connect arrives.
+ mocks.connectListConnections.mockResolvedValue({ connections: [] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+ mocks.connectGetStatus.mockResolvedValue({ connected: true, icon: 'github-icon' });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(useToolStore.getState().lobehubSkillServers).toEqual([]));
+
+ await act(async () => {
+ await useToolStore.getState().checkLobehubSkillStatus('github');
+ });
+ expect(serverIds()).toEqual(['github']);
+
+ // The `connectListConnections` response the connect raced (no new row) lands.
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ expect(serverIds()).toEqual(['github']);
+ });
+
+ it('hands the list back to the server once it echoes the new provider', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+ mocks.connectGetStatus.mockResolvedValue({ connected: true, icon: 'github-icon' });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(useToolStore.getState().lobehubSkillServers).toEqual([]));
+
+ await act(async () => {
+ await useToolStore.getState().checkLobehubSkillStatus('github');
+ });
+
+ // The server now lists it: the local intent settles and the response rules.
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('github')] });
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ expect(serverIds()).toEqual(['github']);
+ expect(useToolStore.getState().lobehubSkillServers![0].providerUsername).toBe('testuser');
+
+ // A later response without the row drops it — the server is authoritative again.
+ mocks.connectListConnections.mockResolvedValue({ connections: [] });
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ expect(serverIds()).toEqual([]);
+ });
+
+ it('revokes a provider locally and keeps a stale list response from resurrecting it', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+ mocks.connectRevoke.mockResolvedValue({});
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+
+ await act(async () => {
+ await useToolStore.getState().revokeLobehubSkill('linear');
+ });
+
+ expect(serverIds()).toEqual([]);
+ expect(mocks.connectRevoke).toHaveBeenCalledWith({ provider: 'linear' });
+
+ // A list response that predates the revoke still lists the provider.
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ expect(serverIds()).toEqual([]);
+ });
+
+ it('keeps a revoked provider hidden until a response confirms it is gone', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+ mocks.connectRevoke.mockResolvedValue({});
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+
+ await act(async () => {
+ await useToolStore.getState().revokeLobehubSkill('linear');
+ });
+
+ // The server confirms it is gone …
+ mocks.connectListConnections.mockResolvedValue({ connections: [] });
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ // … so a later, legitimate re-connect is shown again.
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ expect(serverIds()).toEqual(['linear']);
+ });
+
+ it('shows a provider re-connected inside the revoke race window', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({ tools: [] });
+ mocks.connectRevoke.mockResolvedValue({});
+ mocks.connectGetStatus.mockResolvedValue({ connected: true, icon: 'linear-icon' });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(serverIds()).toEqual(['linear']));
+
+ await act(async () => {
+ await useToolStore.getState().revokeLobehubSkill('linear');
+ });
+ expect(serverIds()).toEqual([]);
+
+ // Re-connected before any response confirmed the revoke: the fresh write
+ // supersedes the pending revoke, so the row shows again …
+ await act(async () => {
+ await useToolStore.getState().checkLobehubSkillStatus('linear');
+ });
+ expect(serverIds()).toEqual(['linear']);
+
+ // … and a list response that still lists it keeps showing it.
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+ expect(serverIds()).toEqual(['linear']);
+ });
+
+ it('keeps the connect response tools on the provider row for the agent tool list', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({
+ tools: [
+ { description: 'Create an issue', inputSchema: { type: 'object' }, name: 'createIssue' },
+ ],
+ });
+
+ renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), { wrapper });
+
+ await waitFor(() =>
+ expect(useToolStore.getState().lobehubSkillServers?.[0].tools).toHaveLength(1),
+ );
+ expect(useToolStore.getState().lobehubSkillServers?.[0].tools![0].name).toBe('createIssue');
+ });
+
+ it('keeps a connected provider’s cached tools when a revalidation drops them and the tool fetch fails', async () => {
+ mocks.connectListConnections.mockResolvedValue({ connections: [connection('linear')] });
+ mocks.connectListTools.mockResolvedValue({
+ tools: [
+ { description: 'Create an issue', inputSchema: { type: 'object' }, name: 'createIssue' },
+ ],
+ });
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchLobehubSkillConnections)(true), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(useToolStore.getState().lobehubSkillServers?.[0].tools).toHaveLength(1),
+ );
+
+ // The revalidation's list response carries no tools, and this time the
+ // follow-up `connectListTools` call fails.
+ mocks.connectListTools.mockRejectedValue(new Error('network down'));
+ await act(async () => {
+ await sync.result.current.mutate();
+ });
+
+ // The persisted catalog survives on the row, so the provider still resolves
+ // for the agent tool list even though the refresh failed.
+ expect(mocks.connectListTools).toHaveBeenCalledWith({ provider: 'linear' });
+ expect(useToolStore.getState().lobehubSkillServers?.[0].tools).toHaveLength(1);
+ expect(
+ lobehubSkillStoreSelectors.lobehubSkillAsLobeTools(useToolStore.getState()),
+ ).toHaveLength(1);
+ });
+
+ it('paints a provider’s persisted tool catalog before the network answers', async () => {
+ const cachedTool = {
+ description: 'Cached tool',
+ inputSchema: { type: 'object' },
+ name: 'cached',
+ };
+ await lobehubSkillProviderToolsResource.storage!.set(
+ { queryKey: PROVIDER_TOOLS_STORAGE_KEY, scope },
+ { data: [cachedTool], updatedAt: 1 },
+ );
+ mocks.connectListTools.mockImplementation(pending);
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchProviderTools)('linear'), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(useToolStore.getState().lobehubSkillToolsMap.linear).toEqual([cachedTool]),
+ );
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ });
+
+ it('replaces a provider’s tool catalog with the network response and persists it', async () => {
+ mocks.connectListTools.mockResolvedValue({
+ tools: [
+ {
+ description: 'Create an issue',
+ inputSchema: { type: 'object' },
+ name: 'createIssue',
+ // Not rendered anywhere: the projection keeps only the three fields.
+ weirdMarketField: 'ignored',
+ },
+ ],
+ });
+
+ renderHook(() => useToolStore((s) => s.useFetchProviderTools)('linear'), { wrapper });
+
+ await waitFor(() =>
+ expect(useToolStore.getState().lobehubSkillToolsMap.linear).toEqual([
+ { description: 'Create an issue', inputSchema: { type: 'object' }, name: 'createIssue' },
+ ]),
+ );
+
+ await waitFor(async () =>
+ expect(
+ (
+ await lobehubSkillProviderToolsResource.storage!.get({
+ queryKey: PROVIDER_TOOLS_STORAGE_KEY,
+ scope,
+ })
+ )?.data,
+ ).toEqual([
+ { description: 'Create an issue', inputSchema: { type: 'object' }, name: 'createIssue' },
+ ]),
+ );
+ });
+});