🤯 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(composio): move the Composio connections onto @lobechat/replica (#20572)
Arvin Xu335cfc0c21d1
diff --git a/src/features/SkillStore/SkillDetail/ComposioDetailProvider.tsx b/src/features/SkillStore/SkillDetail/ComposioDetailProvider.tsxindex 9adf666d2db..200602aa8e5 100644--- a/src/features/SkillStore/SkillDetail/ComposioDetailProvider.tsx+++ b/src/features/SkillStore/SkillDetail/ComposioDetailProvider.tsx@@ -40,7 +40,14 @@ export const ComposioDetailProvider = ({);const useFetchAppTools = useToolStore((s) => s.useFetchAppTools);- const { data: tools = [], isLoading: toolsLoading } = useFetchAppTools(serverName);+ const appTools = useToolStore((s) => s.composioAppToolsMap[serverName]);+ const { isHydrated, isValidating } = useFetchAppTools(serverName);++ // 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 list already on screen must not blank it.+ const tools = appTools ?? [];+ const toolsLoading = !appTools && (isValidating || !isHydrated);if (!config) return null;diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 3a33e8e7997..8b7ed2b37a8 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -799,6 +799,8 @@ export const userMemoryKeys = {// ---- tool (skills / plugins / builtin / mcp / composio stores) -------------export const toolKeys = {+ agentSkillDetail: def('tool:agentSkillDetail', (id: string) => ['tool:agentSkillDetail', id]),+ agentSkills: def('tool:agentSkills', () => ['tool:agentSkills']),composioAppTools: def('tool:composioAppTools', (appSlug: string) => ['tool:composioAppTools',appSlug,diff --git a/src/store/tool/slices/composioStore/action.ts b/src/store/tool/slices/composioStore/action.tsindex 9424aa17963..2e7b02babba 100644--- a/src/store/tool/slices/composioStore/action.ts+++ b/src/store/tool/slices/composioStore/action.ts@@ -1,15 +1,29 @@import { COMPOSIO_APP_TYPES } 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 { lambdaClient, toolsClient } from '@/libs/trpc/client';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';import { type ComposioStoreState } from './initialState';+import {+ COMPOSIO_SERVERS_KEY,+ composioAppToolsResource,+ type ComposioLocalIntent,+ composioServersEntity,+ composioServersResource,+ createComposioLocalIntent,+ mergeComposioServers,+} from './projection';import {type CallComposioToolParams,type CallComposioToolResult,@@ -23,18 +37,114 @@ const n = setNamespace('composioStore');const VALID_COMPOSIO_IDENTIFIERS = new Set(COMPOSIO_APP_TYPES.map((t) => t.identifier));+/** The connections list is one entry, so every sync shares these params. */+const CONNECTIONS_PARAMS = {} as Record<string, never>;++/**+ * The connections list keeps its long-standing flat `composioServers` field as+ * the replica view, so every selector reads what it did. `isComposioServersInit`+ * gates `get`: before the first hydrate/replace the view must read `undefined`,+ * otherwise the empty default would block hydration from storage.+ */+const composioServersLens: ReplicaLens<ToolStore, ComposioServer[]> = {+ clear: () => ({ composioServers: [], isComposioServersInit: false }),+ get: (state) => (state.isComposioServersInit ? state.composioServers : undefined),+ keys: (state) => (state.isComposioServersInit ? [COMPOSIO_SERVERS_KEY] : []),+ set: (_state, _key, data) =>+ data+ ? { composioServers: data, isComposioServersInit: true }+ : { composioServers: [], isComposioServersInit: false },+};++/** The connections sync, plus the `mutate` alias the skills reload control calls. */+export interface ComposioConnectionsSyncResult extends ReplicaSyncResult {+ /** Alias of `revalidate`, kept for the existing "reload skills" control. */+ mutate: () => Promise<unknown>;+}+type Setter = StoreSetter<ToolStore>;export const createComposioStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>new ComposioStoreActionImpl(set, get, _api);export class ComposioStoreActionImpl {+ readonly #appTools;+ readonly #connections;readonly #get: () => ToolStore;+ /**+ * Local intent of the connections replica, per replica scope — the rows this+ * client wrote that the server has not echoed yet. Keyed by scope, like the+ * write sequence and persistence holds: a deletion still awaiting the server+ * has to survive a switch away and back, or the next revalidation — whose+ * sequence stamp the same scope accepts — resurrects the not-yet-deleted row.+ */+ #intentsByScope = new Map<string, ComposioLocalIntent>();+ readonly #servers;readonly #set: Setter;+ /**+ * Confirmed local writes to the connections list, per replica scope. A+ * `getComposioPlugins` request stamps itself with its scope's value on start;+ * a response stamped before that scope's latest write is dropped (see+ * `mergeComposioServers`), so an in-flight sync can never roll a confirmed+ * connect / delete / status refresh back. Kept per scope, not process-wide: a+ * write one identity still owes must not drop another identity's responses,+ * which would leave the switched-to scope empty until some later revalidation.+ */+ #writeSeqByScope = new Map<string, number>();+ /**+ * Local writes whose server persistence is still in flight, per replica scope.+ * A `getComposioPlugins` the server answers while one is pending still reflects+ * the pre-write row (the refresh's `ACTIVE` row is only persisted by+ * `updateComposioPlugin` below), so every response is dropped until it settles+ * — the stamp alone cannot tell such a response from a fresh one, because its+ * request was issued *after* the local write. Scoped for the same reason as+ * `#writeSeqByScope`.+ */+ #unpersistedWritesByScope = new Map<string, number>();constructor(set: Setter, get: () => ToolStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#connections = createReplicaSlice(composioServersResource, {+ actionPrefix: 'composioServers',+ entity: composioServersEntity,+ // Stamp the request with the write sequence in flight when it starts, so+ // `merge` can drop a response the server produced before a later write.+ fetcher: async () => {+ const since = this.#writeSeq();+ const servers = await this.#fetchServers();+ return { servers, since };+ },+ get,+ // A list response replaces the whole value; a response issued before the+ // latest local write — or while one is still being persisted — is dropped,+ // and one that clears both is still merged with the local intent (a new+ // connection the server has not echoed, a deletion it has not confirmed)+ // so an in-flight sync can neither drop a new connection nor resurrect a+ // deleted one.+ merge: (response) =>+ mergeComposioServers(+ response,+ this.#localIntent(),+ this.#writeSeq(),+ this.#hasUnpersistedWrite(),+ ),+ set,+ stateKey: 'composioServersReplica',+ view: composioServersLens,+ });+ this.#servers = linkReplicaEntity<ComposioServer>([this.#connections]);+ this.#appTools = createReplicaSlice(composioAppToolsResource, {+ actionPrefix: 'composioAppTools',+ fetcher: async (appSlug) => {+ const response = await toolsClient.composio.getActions.query({ appSlug });+ return (response.tools || []) as ComposioTool[];+ },+ get,+ set,+ stateKey: 'composioAppToolsReplica',+ view: recordLens<ToolStore, ComposioTool[]>('composioAppToolsMap'),+ });}callComposioTool = async (params: CallComposioToolParams): Promise<CallComposioToolResult> => {@@ -92,6 +202,9 @@ export class ComposioStoreActionImpl {params: CreateComposioServerParams,): Promise<ComposioServer | undefined> => {const { appSlug, identifier, label, agentId } = params;+ // The completion is bound to the identity that started it: the server may+ // answer after the user switched scope (see the guard below).+ const scope = cacheScope.get();this.#set(produce((draft: ComposioStoreState) => {@@ -109,6 +222,21 @@ export class ComposioStoreActionImpl {label,});+ // The user may have switched identity while the server answered. Writing+ // the row now would persist this scope's connected-account id and OAuth+ // redirect url into the other scope's replica partition, and show them+ // there; drop the completion instead.+ if (cacheScope.get() !== scope) {+ this.#set(+ produce((draft: ComposioStoreState) => {+ draft.loadingComposioServerIds.delete(identifier);+ }),+ false,+ n('createComposioConnection/scopeChanged'),+ );+ return undefined;+ }+const server: ComposioServer = {agentId,appSlug,@@ -121,14 +249,23 @@ export class ComposioStoreActionImpl {status: ComposioServerStatus.PENDING_AUTH,};+ // Replace the record in place (by identifier) or append the new one, so a+ // re-authorization keeps showing the same row with a fresh `redirectUrl`.+ // The intent survives a list response that was already in flight when the+ // connection was created (see `mergeComposioServers`); a pending removal+ // of the same identifier is cleared, since the row is back.+ this.#localIntent().removed.delete(identifier);+ this.#localIntent().added.set(identifier, server);+ this.#connections.update(COMPOSIO_SERVERS_KEY, (servers) => {+ const list = servers ?? [];+ const index = list.findIndex((s) => s.identifier === identifier);+ if (index < 0) return [...list, server];+ return list.map((s, i) => (i === index ? server : s));+ });+ this.#markLocalWrite();+this.#set(produce((draft: ComposioStoreState) => {- const existingIndex = draft.composioServers.findIndex((s) => s.identifier === identifier);- if (existingIndex >= 0) {- draft.composioServers[existingIndex] = server;- } else {- draft.composioServers.push(server);- }draft.loadingComposioServerIds.delete(identifier);}),false,@@ -160,6 +297,19 @@ export class ComposioStoreActionImpl {return;}+ // This refresh is bound to the identity that started it: the server may+ // answer after the user switched scope, and this row is that scope's (see+ // the guards below).+ const scope = cacheScope.get();+ const clearLoading = (action: string) =>+ this.#set(+ produce((draft: ComposioStoreState) => {+ draft.loadingComposioServerIds.delete(identifier);+ }),+ false,+ n(action),+ );+this.#set(produce((draft: ComposioStoreState) => {draft.loadingComposioServerIds.add(identifier);@@ -173,25 +323,20 @@ export class ComposioStoreActionImpl {connectedAccountId: server.connectedAccountId,});+ // Identity switched while the server answered: nothing below may touch+ // the now-active list.+ if (cacheScope.get() !== scope) {+ clearLoading('refreshComposioConnectionStatus/scopeChanged');+ return;+ }+if (connectionStatus.error === 'AUTH_ERROR') {- this.#set(- produce((draft: ComposioStoreState) => {- draft.loadingComposioServerIds.delete(identifier);- }),- false,- n('refreshComposioConnectionStatus/pendingAuth'),- );+ clearLoading('refreshComposioConnectionStatus/pendingAuth');return;}if (connectionStatus.status !== 'ACTIVE') {- this.#set(- produce((draft: ComposioStoreState) => {- draft.loadingComposioServerIds.delete(identifier);- }),- false,- n('refreshComposioConnectionStatus/notActive'),- );+ clearLoading('refreshComposioConnectionStatus/notActive');return;}@@ -200,55 +345,64 @@ export class ComposioStoreActionImpl {appSlug: server.appSlug,});+ if (cacheScope.get() !== scope) {+ clearLoading('refreshComposioConnectionStatus/scopeChanged');+ return;+ }+const tools = toolsResponse.tools as ComposioTool[];- this.#set(- produce((draft: ComposioStoreState) => {- const serverIndex = draft.composioServers.findIndex((s) => s.identifier === identifier);- if (serverIndex >= 0) {- draft.composioServers[serverIndex].tools = tools;- draft.composioServers[serverIndex].status = ComposioServerStatus.ACTIVE;- draft.composioServers[serverIndex].gmailReadPermission =- connectionStatus.gmailReadPermission;- draft.composioServers[serverIndex].redirectUrl = undefined;- draft.composioServers[serverIndex].errorMessage = undefined;- }- draft.loadingComposioServerIds.delete(identifier);- }),- false,- n('refreshComposioConnectionStatus/success'),- );+ this.#servers.update(identifier, (s) => ({+ ...s,+ errorMessage: undefined,+ gmailReadPermission: connectionStatus.gmailReadPermission,+ redirectUrl: undefined,+ status: ComposioServerStatus.ACTIVE,+ tools,+ }));+ // The row is ACTIVE locally, but the server keeps serving the pre-refresh+ // row until `updateComposioPlugin` lands below. Hold this scope's list+ // responses until then: one the server answered in that window carries the+ // old row and would revert this write.+ this.#holdServerWrite(scope);+ this.#markLocalWrite(scope);++ clearLoading('refreshComposioConnectionStatus/success');- await lambdaClient.composio.updateComposioPlugin.mutate({- agentId: server.agentId,- appSlug: server.appSlug,- authConfigId: server.authConfigId,- connectedAccountId: server.connectedAccountId,- identifier,- label: server.label,- status: 'ACTIVE',- tools: tools.map((t) => ({- description: t.description,- inputSchema: t.inputSchema,- name: t.name,- })),- });+ try {+ await lambdaClient.composio.updateComposioPlugin.mutate({+ agentId: server.agentId,+ appSlug: server.appSlug,+ authConfigId: server.authConfigId,+ connectedAccountId: server.connectedAccountId,+ identifier,+ label: server.label,+ status: 'ACTIVE',+ tools: tools.map((t) => ({+ description: t.description,+ inputSchema: t.inputSchema,+ name: t.name,+ })),+ });+ } finally {+ this.#releaseServerWrite(scope);+ }+ // The server only now reflects the ACTIVE row: invalidate anything issued+ // while that write was in flight, so it cannot revert the status.+ this.#markLocalWrite(scope);} catch (error) {console.error('[Composio] Failed to refresh connection status:', error);- this.#set(- produce((draft: ComposioStoreState) => {- const serverIndex = draft.composioServers.findIndex((s) => s.identifier === identifier);- if (serverIndex >= 0) {- draft.composioServers[serverIndex].status = ComposioServerStatus.ERROR;- draft.composioServers[serverIndex].errorMessage =- error instanceof Error ? error.message : String(error);- }- draft.loadingComposioServerIds.delete(identifier);- }),- false,- n('refreshComposioConnectionStatus/error'),- );+ if (cacheScope.get() === scope) {+ this.#servers.update(identifier, (s) => ({+ ...s,+ errorMessage: error instanceof Error ? error.message : String(error),+ status: ComposioServerStatus.ERROR,+ }));+ this.#markLocalWrite(scope);+ }++ clearLoading('refreshComposioConnectionStatus/error');}};@@ -258,6 +412,10 @@ export class ComposioStoreActionImpl {const { composioServers } = this.#get();const existing = composioServers.find((s) => s.identifier === identifier);if (!existing) return undefined;+ // Bound to the identity that started it, like `createComposioConnection`,+ // whose own guard only captures the scope once it starts — after the cleanup+ // below has already awaited.+ const scope = cacheScope.get();// Clean up the stale connection on Composio's side (the prior link likely// expired). Best-effort — if it's already gone we still mint a fresh one.@@ -270,6 +428,10 @@ export class ComposioStoreActionImpl {console.error('[Composio] Failed to clean up stale connection:', error);}+ // Identity switched during the cleanup: minting now would create (and+ // persist) this scope's connection under the other identity.+ if (cacheScope.get() !== scope) return undefined;+// Mint a fresh link; createComposioConnection replaces the record in place// (by identifier), so the UI keeps showing the same row with a new redirectUrl.return this.#get().createComposioConnection({@@ -283,13 +445,16 @@ export class ComposioStoreActionImpl {const { composioServers } = this.#get();const server = composioServers.find((s) => s.identifier === identifier);- this.#set(- produce((draft: ComposioStoreState) => {- draft.composioServers = draft.composioServers.filter((s) => s.identifier !== identifier);- }),- false,- n('removeComposioConnection'),- );+ // Drop the row locally first — the server delete stays best-effort, so a+ // failure never resurrects the row the user just deleted. Recording the+ // removal also cancels a pending add of the same identifier: the row was+ // created but never echoed, so leaving it in `added` would re-append it the+ // moment a response clears `removed`, resurrecting the deleted row for the+ // rest of the session.+ this.#localIntent().added.delete(identifier);+ this.#localIntent().removed.add(identifier);+ this.#servers.remove(identifier);+ this.#markLocalWrite();if (server) {try {@@ -303,80 +468,120 @@ export class ComposioStoreActionImpl {}};- useFetchAppTools = (appSlug: string | undefined): SWRResponse<ComposioTool[]> => {- return useSWR<ComposioTool[]>(- appSlug ? toolKeys.composioAppTools(appSlug) : null,- async () => {- const response = await toolsClient.composio.getActions.query({ appSlug: appSlug! });- return (response.tools || []) as ComposioTool[];- },- { fallbackData: [], revalidateOnFocus: false },- );+ /**+ * Fetch orchestration only; read the tools through `composioAppToolsMap[appSlug]`.+ * Deliberately does not subscribe to the store here — the composio slice is+ * imported by `tool/selectors/tool.ts`, so a runtime `useToolStore` import+ * would close a store↔slice cycle and break store initialization.+ *+ * No focus revalidation, matching the SWR hooks this replaced: the hook is+ * mounted on broad surfaces (ChatInput, settings, onboarding, …), so a+ * refocus must not refetch a catalog that only the server can change.+ */+ useFetchAppTools = (appSlug: string | undefined): ReplicaSyncResult =>+ this.#appTools.useSync(appSlug ?? null, { revalidateOnFocus: false });++ /** Fetch orchestration only; read the servers through `composioStoreSelectors`'. */+ useFetchUserComposioConnections = (enabled: boolean): ComposioConnectionsSyncResult => {+ // `revalidateOnFocus: false` likewise: the connections hook is mounted on+ // broad surfaces, so the pre-migration no-focus schedule is preserved and a+ // refocus does not add recurring `getComposioPlugins` traffic.+ const sync = this.#connections.useSync(CONNECTIONS_PARAMS, {+ enabled,+ revalidateOnFocus: false,+ });++ return { ...sync, mutate: sync.revalidate };};- useFetchUserComposioConnections = (enabled: boolean): SWRResponse<ComposioServer[]> => {- return useSWR<ComposioServer[]>(- enabled ? toolKeys.composioConnections() : null,- async () => {- const composioPlugins = await lambdaClient.composio.getComposioPlugins.query();-- if (composioPlugins.length === 0) return [];-- const validPlugins = composioPlugins.filter((plugin) => plugin.customParams?.composio);-- // Only surface connections this client knows how to render. Identifiers- // outside the static catalog are hidden locally — never deleted: an- // outdated bundle (missing a newly-added app) would otherwise silently- // destroy a legitimate remote connection. Deprecating an app is a- // server-side concern, not a side effect of a client fetch.- return validPlugins- .filter((plugin) => VALID_COMPOSIO_IDENTIFIERS.has(plugin.identifier))- .map((plugin) => {- const params = plugin.customParams!.composio!;- const appType = COMPOSIO_APP_TYPES.find((t) => t.identifier === plugin.identifier);- const tools: ComposioTool[] = (plugin.manifest?.api || []).map((api) => ({- description: api.description,- inputSchema: api.parameters as ComposioTool['inputSchema'],- name: api.name,- }));-- const statusMap: Record<string, ComposioServerStatus> = {- ACTIVE: ComposioServerStatus.ACTIVE,- FAILED: ComposioServerStatus.ERROR,- PENDING: ComposioServerStatus.PENDING_AUTH,- };-- return {- appSlug: params.appSlug || '',- authConfigId: params.authConfigId || '',- connectedAccountId: params.connectedAccountId,- createdAt: 0,- identifier: plugin.identifier,- label: appType?.label || plugin.identifier,- redirectUrl: params.redirectUrl,- status: statusMap[params.status] || ComposioServerStatus.PENDING_AUTH,- tools,- };- });- },- {- onSuccess: (data) => {- this.#set(- produce((draft: ComposioStoreState) => {- if (data.length > 0) {- const existingIdentifiers = new Set(draft.composioServers.map((s) => s.identifier));- const newServers = data.filter((s) => !existingIdentifiers.has(s.identifier));- draft.composioServers = [...draft.composioServers, ...newServers];- }- draft.isComposioServersInit = true;- }),- false,- n('useFetchUserComposioConnections'),- );- },- revalidateOnFocus: false,- },- );+ /**+ * Local intent of a scope (defaults to the active identity): the rows this+ * client wrote that the server has not echoed yet. Kept per scope, so a switch+ * away does not discard a deletion that is still awaiting the server.+ */+ #localIntent = (scope = cacheScope.get()): ComposioLocalIntent => {+ let intent = this.#intentsByScope.get(scope);+ if (!intent) {+ intent = createComposioLocalIntent();+ this.#intentsByScope.set(scope, intent);+ }+ return intent;+ };++ /** Write sequence of `scope` (defaults to the active identity). */+ #writeSeq = (scope = cacheScope.get()): number => this.#writeSeqByScope.get(scope) ?? 0;++ /**+ * Record a confirmed local write to the connections list. Monotonic per scope:+ * every `getComposioPlugins` response issued before that scope's latest write+ * is dropped, so a stale sync can neither drop a new connection, resurrect a+ * deleted one, nor revert a refreshed status (see `mergeComposioServers`).+ */+ #markLocalWrite = (scope = cacheScope.get()): void => {+ this.#writeSeqByScope.set(scope, this.#writeSeq(scope) + 1);+ };++ /** Hold this scope's list responses while a local write is being persisted. */+ #holdServerWrite = (scope: string): void => {+ this.#unpersistedWritesByScope.set(scope, (this.#unpersistedWritesByScope.get(scope) ?? 0) + 1);+ };++ /**+ * Release a hold. Keyed by the *initiating* scope, not the active one: the+ * identity may have switched while the write was in flight, and the other+ * scope's holds are not this write's to release.+ */+ #releaseServerWrite = (scope: string): void => {+ const pending = (this.#unpersistedWritesByScope.get(scope) ?? 0) - 1;+ if (pending > 0) this.#unpersistedWritesByScope.set(scope, pending);+ else this.#unpersistedWritesByScope.delete(scope);+ };++ #hasUnpersistedWrite = (scope = cacheScope.get()): boolean =>+ (this.#unpersistedWritesByScope.get(scope) ?? 0) > 0;++ /**+ * The user's Composio connections (`getComposioPlugins`), mapped to the+ * renderable catalog. Identifiers outside the static catalog are hidden+ * locally — never deleted: an outdated bundle (missing a newly-added app)+ * would otherwise silently destroy a legitimate remote connection. Deprecating+ * an app is a server-side concern, not a side effect of a client fetch.+ */+ #fetchServers = async (): Promise<ComposioServer[]> => {+ const composioPlugins = await lambdaClient.composio.getComposioPlugins.query();++ if (composioPlugins.length === 0) return [];++ return composioPlugins+ .filter((plugin) => plugin.customParams?.composio)+ .filter((plugin) => VALID_COMPOSIO_IDENTIFIERS.has(plugin.identifier))+ .map((plugin) => {+ const params = plugin.customParams!.composio!;+ const appType = COMPOSIO_APP_TYPES.find((t) => t.identifier === plugin.identifier);+ const tools: ComposioTool[] = (plugin.manifest?.api || []).map((api) => ({+ description: api.description,+ inputSchema: api.parameters as ComposioTool['inputSchema'],+ name: api.name,+ }));++ const statusMap: Record<string, ComposioServerStatus> = {+ ACTIVE: ComposioServerStatus.ACTIVE,+ FAILED: ComposioServerStatus.ERROR,+ PENDING: ComposioServerStatus.PENDING_AUTH,+ };++ return {+ appSlug: params.appSlug || '',+ authConfigId: params.authConfigId || '',+ connectedAccountId: params.connectedAccountId,+ createdAt: 0,+ identifier: plugin.identifier,+ label: appType?.label || plugin.identifier,+ redirectUrl: params.redirectUrl,+ status: statusMap[params.status] || ComposioServerStatus.PENDING_AUTH,+ tools,+ };+ });};}diff --git a/src/store/tool/slices/composioStore/focusSchedule.test.ts b/src/store/tool/slices/composioStore/focusSchedule.test.tsnew file mode 100644index 00000000000..5d9044be32d--- /dev/null+++ b/src/store/tool/slices/composioStore/focusSchedule.test.ts@@ -0,0 +1,39 @@+/**+ * The Composio connection list and per-app tool catalog are replicas whose sync+ * hooks are mounted on broad surfaces (ChatInput, settings, onboarding,+ * recommendations). The SWR hooks this slice replaced explicitly set+ * `revalidateOnFocus: false`; the replica syncs must keep that schedule, or a+ * window refocus would add recurring `getComposioPlugins` / `getActions` traffic.+ */+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useToolStore } from '../../store';++// Capture the schedule the replica fetch driver hands to SWR. Only the driver+// binding is replaced; the slice under test is the real one.+vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++describe('composio replica sync schedule', () => {+ beforeEach(() => vi.clearAllMocks());++ it('does not refetch the connections or the app tools on window focus', async () => {+ const { useClientDataSWR } = await import('@/libs/swr');++ renderHook(() => {+ useToolStore.getState().useFetchUserComposioConnections(true);+ useToolStore.getState().useFetchAppTools('gmail');+ });++ const syncConfigs = vi+ .mocked(useClientDataSWR)+ .mock.calls.filter(([key]) => Array.isArray(key) && key[0] === 'replica:sync')+ .map(([, , config]) => config as { revalidateOnFocus?: boolean });++ expect(syncConfigs).toHaveLength(2);+ for (const config of syncConfigs) expect(config.revalidateOnFocus).toBe(false);+ });+});diff --git a/src/store/tool/slices/composioStore/index.ts b/src/store/tool/slices/composioStore/index.tsindex 7ebb1ea9dd2..0b3e7450321 100644--- a/src/store/tool/slices/composioStore/index.ts+++ b/src/store/tool/slices/composioStore/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/composioStore/initialState.ts b/src/store/tool/slices/composioStore/initialState.tsindex 32db09b1ec5..ab680d826a7 100644--- a/src/store/tool/slices/composioStore/initialState.ts+++ b/src/store/tool/slices/composioStore/initialState.ts@@ -1,15 +1,34 @@-import { type ComposioServer } from './types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import { type ComposioServer, type ComposioTool } from './types';export interface ComposioStoreState {+ /** Replica view of app tool catalogs, one entry per `appSlug`. */+ composioAppToolsMap: Record<string, ComposioTool[]>;+ /** Replica bookkeeping of `composioAppToolsMap`. */+ composioAppToolsReplica: ReplicaState<ComposioTool[]>;+ /** In-flight tool calls, keyed `identifier:toolSlug` (local UI state; never persisted). */composioExecutingToolIds: Set<string>;+ /** The user's Composio connections — the view of the `composioServers` replica. */composioServers: ComposioServer[];+ /** Replica bookkeeping of `composioServers`. */+ composioServersReplica: ReplicaState<ComposioServer[]>;+ /**+ * Whether the connections view has been filled (from storage or the server).+ * Gates the replica lens: an un-loaded list must read `undefined`, otherwise+ * hydration would treat the empty default as a real value.+ */isComposioServersInit: boolean;+ /** In-flight connection writes, by `identifier` (local UI state; never persisted). */loadingComposioServerIds: Set<string>;}export const initialComposioStoreState: ComposioStoreState = {composioExecutingToolIds: new Set(),+ composioAppToolsMap: {},+ composioAppToolsReplica: createReplicaState(),composioServers: [],+ composioServersReplica: createReplicaState(),isComposioServersInit: false,loadingComposioServerIds: new Set(),};diff --git a/src/store/tool/slices/composioStore/projection.ts b/src/store/tool/slices/composioStore/projection.tsnew file mode 100644index 00000000000..9da5e2a1fb9--- /dev/null+++ b/src/store/tool/slices/composioStore/projection.ts@@ -0,0 +1,124 @@+import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';++import { type ComposioServer, type ComposioTool } from './types';++/** The user's Composio connections are one list entry per scope. */+export const COMPOSIO_SERVERS_KEY = 'all';++/**+ * One `getComposioPlugins` response, stamped with the local-write sequence that+ * was current when the request was issued.+ *+ * A list response replaces the whole value and carries no ordering of its own,+ * so the stamp is what lets the slice tell a response the server produced+ * *before* a local write (which must not be applied) from one produced after it.+ */+export interface ComposioServersResponse {+ servers: ComposioServer[];+ /** `writeSeq` at the moment the request was issued. */+ since: number;+}++/**+ * The user's Composio connections (`getComposioPlugins`): a local-first replica+ * so the settings / skills surfaces paint the persisted list on the first frame+ * and let the network confirm it, and a connect / delete shows on the row at once.+ */+export const composioServersResource = defineReplica<+ Record<string, never>,+ ComposioServer[],+ ComposioServersResponse+>({+ key: () => COMPOSIO_SERVERS_KEY,+ name: 'composioServers',+ storage: 'indexedDB',+ version: 1,+});++/** A connection is addressed by its `identifier` across the tool store. */+export const composioServersEntity: ReplicaEntityAdapter<ComposioServer[], ComposioServer> =+ arrayEntity<ComposioServer>((server) => server.identifier);++/**+ * One Composio app's tool catalog (`getActions`), keyed by `appSlug`. Read-only+ * and shared across the skill detail surfaces, so a persisted copy paints the+ * tools before the network answers.+ */+export const composioAppToolsResource = defineReplica<string, ComposioTool[]>({+ key: (appSlug) => appSlug,+ name: 'composioAppTools',+ storage: 'indexedDB',+ version: 1,+});++/**+ * Local intent of the connections replica that the server has not echoed yet:+ * rows this client created, and rows it removed. Kept only until a response+ * reflects them.+ */+export interface ComposioLocalIntent {+ /** Created rows, by `identifier` — re-appended until the server echoes them. */+ added: Map<string, ComposioServer>;+ /** Removed `identifier`s — hidden until a response confirms they are gone. */+ removed: Set<string>;+}++export const createComposioLocalIntent = (): ComposioLocalIntent => ({+ added: new Map(),+ removed: new Set(),+});++/**+ * Folds a connections response into the replica.+ *+ * Returns `undefined` — the engine's "keep the current value" — when the+ * response cannot be trusted to reflect the local writes:+ *+ * - `hasUnpersistedWrite`: a local write is still being persisted on the server+ * (a refresh's `active` row, while `updateComposioPlugin` is in flight). The+ * server keeps answering the pre-write row, so a response it produced in that+ * window would revert the write even though the request was *issued* after it.+ * Wait for a request issued once persistence finishes.+ * - `response.since < latestLocalWrite`: the request was issued before the+ * latest confirmed local write, so its snapshot predates it. This is the+ * reported race: `getComposioPlugins` was already in flight when the+ * connect / delete / status refresh wrote the list, so applying it wholesale+ * would roll the row back — drop the just-created row (the OAuth polling then+ * early-returns on `Server not found`), resurrect a just-deleted row, or+ * revert a row just marked `active`.+ *+ * A response that clears both checks is still merged, not trusted blindly,+ * because the write is local-first and the server may not have adopted it yet:+ * a pending add (created, not yet echoed) is re-appended, and 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.+ */+export const mergeComposioServers = (+ response: ComposioServersResponse,+ intent: ComposioLocalIntent,+ latestLocalWrite: number,+ hasUnpersistedWrite = false,+): ComposioServer[] | undefined => {+ if (hasUnpersistedWrite) return undefined;+ if (response.since < latestLocalWrite) return undefined;++ const incoming = response.servers;+ 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()];++ if (carried.length === 0 && kept === incoming) return incoming;++ return [...kept, ...carried];+};diff --git a/src/store/tool/slices/composioStore/replica.test.ts b/src/store/tool/slices/composioStore/replica.test.tsnew file mode 100644index 00000000000..fb0f1853487--- /dev/null+++ b/src/store/tool/slices/composioStore/replica.test.ts@@ -0,0 +1,965 @@+/**+ * @vitest-environment happy-dom+ *+ * The Composio connections list is a replica: it paints the persisted copy on+ * the first frame, the network only confirms, and a connect / delete / refresh+ * shows on the row at once. The per-app tool catalog is a replica too.+ */+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 } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';++import { useToolStore } from '../../store';+import { initialComposioStoreState } from './initialState';+import {+ COMPOSIO_SERVERS_KEY,+ composioAppToolsResource,+ composioServersResource,+ createComposioLocalIntent,+ mergeComposioServers,+} from './projection';++const mocks = vi.hoisted(() => ({+ createConnection: vi.fn(),+ deleteConnection: vi.fn(),+ executeAction: vi.fn(),+ getActions: vi.fn(),+ getComposioPlugins: vi.fn(),+ getConnection: vi.fn(),+ listActions: vi.fn(),+ updateComposioPlugin: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ composio: {+ createConnection: { mutate: mocks.createConnection },+ deleteConnection: { mutate: mocks.deleteConnection },+ getComposioPlugins: { query: mocks.getComposioPlugins },+ getConnection: { query: mocks.getConnection },+ updateComposioPlugin: { mutate: mocks.updateComposioPlugin },+ },+ },+ toolsClient: {+ composio: {+ executeAction: { mutate: mocks.executeAction },+ getActions: { query: mocks.getActions },+ listActions: { query: mocks.listActions },+ },+ },+}));++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 `user_installed_plugins` row carrying a Composio connection, as the server returns it. */+const composioPlugin = (+ identifier: string,+ overrides: {+ api?: { description?: string; name: string; parameters?: unknown }[];+ appSlug?: string;+ redirectUrl?: string;+ status?: string;+ } = {},+) => ({+ customParams: {+ composio: {+ appSlug: overrides.appSlug ?? identifier.toUpperCase(),+ authConfigId: `ac_${identifier}`,+ connectedAccountId: `ca_${identifier}`,+ redirectUrl: overrides.redirectUrl,+ status: overrides.status ?? 'ACTIVE',+ },+ },+ identifier,+ manifest: {+ api: overrides.api ?? [+ {+ description: `${identifier} tool`,+ name: `${identifier}_TOOL`,+ parameters: { type: 'object' },+ },+ ],+ },+});++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const SERVERS_STORAGE_KEY = composioServersResource.storageKey({} as Record<string, never>);+const APP_TOOLS_STORAGE_KEY = composioAppToolsResource.storageKey('gmail');++/** Identifiers of the connections the store currently shows. */+const connectionIds = () => useToolStore.getState().composioServers.map((s) => s.identifier);++describe('composio 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(`composio-user-${randomUUID()}:personal`);+ act(() => useToolStore.setState(initialComposioStoreState));+ });++ afterEach(async () => {+ cleanup();+ await Promise.all([+ ...[...scopes].map((value) =>+ composioServersResource.storage!.remove({ queryKey: SERVERS_STORAGE_KEY, scope: value }),+ ),+ ...[...scopes].map((value) =>+ composioAppToolsResource.storage!.remove({ queryKey: APP_TOOLS_STORAGE_KEY, scope: value }),+ ),+ ]);+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted list before the network answers', async () => {+ const cached = {+ appSlug: 'GMAIL',+ authConfigId: 'ac_gmail',+ connectedAccountId: 'ca_gmail',+ createdAt: 0,+ identifier: 'gmail',+ label: 'Gmail',+ status: 'active' as const,+ };+ await composioServersResource.storage!.set(+ { queryKey: SERVERS_STORAGE_KEY, scope },+ { data: [cached], updatedAt: 1 },+ );+ mocks.getComposioPlugins.mockImplementation(pending);++ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });++ await waitFor(() =>+ expect(useToolStore.getState().composioServers.map((s) => s.identifier)).toEqual(['gmail']),+ );+ expect(useToolStore.getState().isComposioServersInit).toBe(true);+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the list with the server response and persists it', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);++ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });++ await waitFor(() =>+ expect(useToolStore.getState().composioServers.map((s) => s.identifier)).toEqual(['gmail']),+ );+ const [server] = useToolStore.getState().composioServers;+ expect(server.status).toBe('active');+ expect(server.connectedAccountId).toBe('ca_gmail');+ expect(server.tools).toHaveLength(1);++ await waitFor(async () =>+ expect(+ (+ await composioServersResource.storage!.get({ queryKey: SERVERS_STORAGE_KEY, scope })+ )?.data.map((s) => s.identifier),+ ).toEqual(['gmail']),+ );+ });++ it('drops the previous identity’s servers before the next one paints', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);++ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));++ mocks.getComposioPlugins.mockImplementation(pending);+ useScope(`composio-user-${randomUUID()}:personal`);+ sync.rerender();++ await waitFor(() => expect(useToolStore.getState().isComposioServersInit).toBe(false));+ expect(useToolStore.getState().composioServers).toEqual([]);+ });++ it('does not fetch while the sync is disabled', async () => {+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(false), { wrapper });++ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(mocks.getComposioPlugins).not.toHaveBeenCalled();+ expect(useToolStore.getState().isComposioServersInit).toBe(false);+ });++ it('appends a newly created connection to the list', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));++ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });++ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });++ const identifiers = useToolStore.getState().composioServers.map((s) => s.identifier);+ expect(identifiers).toEqual(['gmail', 'slack']);+ const slack = useToolStore.getState().composioServers.find((s) => s.identifier === 'slack');+ expect(slack?.status).toBe('pending_auth');+ expect(slack?.redirectUrl).toBe('https://composio.dev/redirect');+ });++ it('drops the row locally and best-effort deletes the connection', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));++ await act(async () => {+ await useToolStore.getState().removeComposioConnection('gmail');+ });++ expect(useToolStore.getState().composioServers).toEqual([]);+ expect(mocks.deleteConnection).toHaveBeenCalledWith({+ connectedAccountId: 'ca_gmail',+ identifier: 'gmail',+ });+ });++ it('surfaces the error when the status refresh fails', async () => {+ // The failed refresh logs the cause; keep the test output clean.+ vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail', { status: 'PENDING' })]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));++ mocks.getConnection.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await useToolStore.getState().refreshComposioConnectionStatus('gmail');+ });++ const [server] = useToolStore.getState().composioServers;+ expect(server.status).toBe('error');+ expect(server.errorMessage).toBe('network down');+ expect(useToolStore.getState().loadingComposioServerIds.has('gmail')).toBe(false);+ });++ it('marks the connection active with its tools after a successful refresh', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail', { status: 'PENDING' })]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));++ mocks.getConnection.mockResolvedValue({ gmailReadPermission: true, status: 'ACTIVE' });+ mocks.listActions.mockResolvedValue({+ tools: [+ { description: 'Send email', inputSchema: { type: 'object' }, name: 'GMAIL_SEND_EMAIL' },+ ],+ });+ mocks.updateComposioPlugin.mockResolvedValue({ success: true });++ await act(async () => {+ await useToolStore.getState().refreshComposioConnectionStatus('gmail');+ });++ const [server] = useToolStore.getState().composioServers;+ expect(server.status).toBe('active');+ expect(server.gmailReadPermission).toBe(true);+ expect(server.redirectUrl).toBeUndefined();+ expect(server.tools?.map((t) => t.name)).toEqual(['GMAIL_SEND_EMAIL']);+ expect(mocks.updateComposioPlugin).toHaveBeenCalled();+ });++ it('keeps a new connection when a list response that predates it lands', async () => {+ // The list loads empty first, then a response racing the connect arrives.+ mocks.getComposioPlugins.mockResolvedValue([]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(useToolStore.getState().isComposioServersInit).toBe(true));++ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });+ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });+ expect(connectionIds()).toEqual(['slack']);++ // The `getComposioPlugins` response the connect raced (no new row) lands.+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual(['slack']);+ });++ it('hands the list back to the server once it echoes the new connection', async () => {+ mocks.getComposioPlugins.mockResolvedValue([]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(useToolStore.getState().isComposioServersInit).toBe(true));++ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: undefined,+ });+ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });++ // The server now echoes it: the local intent is settled.+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('slack')]);+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual(['slack']);++ // A later response without it is authoritative again (e.g. removed elsewhere).+ mocks.getComposioPlugins.mockResolvedValue([]);+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual([]);+ });++ it('keeps a removed connection gone when a list response that still has it lands', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(connectionIds()).toEqual(['gmail']));++ mocks.deleteConnection.mockResolvedValue({ success: true });+ await act(async () => {+ await useToolStore.getState().removeComposioConnection('gmail');+ });+ expect(connectionIds()).toEqual([]);++ // A list response fetched before the delete still carries the row.+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual([]);++ // Once the server confirms it is gone, the server is authoritative again.+ mocks.getComposioPlugins.mockResolvedValue([]);+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual([]);+ });++ it('still refreshes a connection created while a list response was in flight', async () => {+ // Reproduces the reported dead-end: connect, let the racing list response+ // land, then complete the OAuth flow — the row must still be there.+ mocks.getComposioPlugins.mockResolvedValue([]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(useToolStore.getState().isComposioServersInit).toBe(true));++ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });+ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });+ await act(async () => {+ await sync.result.current.mutate();+ });++ mocks.getConnection.mockResolvedValue({ gmailReadPermission: false, status: 'ACTIVE' });+ mocks.listActions.mockResolvedValue({+ tools: [+ { description: 'Post a message', inputSchema: { type: 'object' }, name: 'SLACK_POST' },+ ],+ });+ mocks.updateComposioPlugin.mockResolvedValue({ success: true });++ await act(async () => {+ await useToolStore.getState().refreshComposioConnectionStatus('slack');+ });++ const server = useToolStore.getState().composioServers.find((s) => s.identifier === 'slack');+ expect(server?.status).toBe('active');+ expect(server?.tools?.map((t) => t.name)).toEqual(['SLACK_POST']);+ expect(mocks.updateComposioPlugin).toHaveBeenCalled();+ });++ it('drops a list response that was issued before the connect', async () => {+ // The initial `getComposioPlugins` request is still in flight (issued+ // before any local write) when the connect lands.+ let resolveInFlight!: (value: unknown) => void;+ const inFlight = new Promise((resolve) => {+ resolveInFlight = resolve;+ });+ mocks.getComposioPlugins.mockReturnValueOnce(inFlight);++ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(mocks.getComposioPlugins).toHaveBeenCalledTimes(1));++ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });+ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });+ expect(connectionIds()).toEqual(['slack']);++ // The response issued *before* the connect (no `slack`) now arrives: it must+ // not roll the confirmed row back.+ await act(async () => {+ resolveInFlight([]);+ await inFlight;+ });+ expect(connectionIds()).toEqual(['slack']);+ });++ it('drops a list response that was issued before the delete', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(connectionIds()).toEqual(['gmail']));++ // A revalidation is in flight (its snapshot still carries `gmail`) when the+ // user deletes the row.+ let resolveInFlight!: (value: unknown) => void;+ const inFlight = new Promise((resolve) => {+ resolveInFlight = resolve;+ });+ mocks.getComposioPlugins.mockReturnValueOnce(inFlight);+ await act(async () => {+ void sync.result.current.mutate();+ });+ await waitFor(() => expect(mocks.getComposioPlugins).toHaveBeenCalledTimes(2));++ mocks.deleteConnection.mockResolvedValue({ success: true });+ await act(async () => {+ await useToolStore.getState().removeComposioConnection('gmail');+ });+ expect(connectionIds()).toEqual([]);++ // The pre-delete response lands: the deleted row must not be resurrected.+ await act(async () => {+ resolveInFlight([composioPlugin('gmail')]);+ await inFlight;+ });+ expect(connectionIds()).toEqual([]);+ });++ it('keeps a connection created and then deleted before any response echoes it', async () => {+ mocks.getComposioPlugins.mockResolvedValue([]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(useToolStore.getState().isComposioServersInit).toBe(true));++ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });+ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });+ expect(connectionIds()).toEqual(['slack']);++ // Deleted before any list response echoed the create.+ mocks.deleteConnection.mockResolvedValue({ success: true });+ await act(async () => {+ await useToolStore.getState().removeComposioConnection('slack');+ });+ expect(connectionIds()).toEqual([]);++ // The server never echoes the row: every later empty response must keep it+ // gone instead of re-appending the stale pending add.+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual([]);+ await act(async () => {+ await sync.result.current.mutate();+ });+ expect(connectionIds()).toEqual([]);+ });++ it('does not let a list response issued before a refresh revert the active row', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('slack', { status: 'PENDING' })]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(connectionIds()).toEqual(['slack']));++ // A focus revalidation is in flight (snapshot still `PENDING`, no tools) …+ let resolveInFlight!: (value: unknown) => void;+ const inFlight = new Promise((resolve) => {+ resolveInFlight = resolve;+ });+ mocks.getComposioPlugins.mockReturnValueOnce(inFlight);+ await act(async () => {+ void sync.result.current.mutate();+ });+ await waitFor(() => expect(mocks.getComposioPlugins).toHaveBeenCalledTimes(2));++ // … and OAuth completes locally before it lands.+ mocks.getConnection.mockResolvedValue({ gmailReadPermission: false, status: 'ACTIVE' });+ mocks.listActions.mockResolvedValue({+ tools: [+ { description: 'Post a message', inputSchema: { type: 'object' }, name: 'SLACK_POST' },+ ],+ });+ mocks.updateComposioPlugin.mockResolvedValue({ success: true });+ await act(async () => {+ await useToolStore.getState().refreshComposioConnectionStatus('slack');+ });+ expect(useToolStore.getState().composioServers[0].status).toBe('active');++ // The stale pre-refresh response lands: the confirmed ACTIVE row must win.+ await act(async () => {+ resolveInFlight([composioPlugin('slack', { status: 'PENDING' })]);+ await inFlight;+ });+ const row = useToolStore.getState().composioServers.find((s) => s.identifier === 'slack');+ expect(row?.status).toBe('active');+ expect(row?.tools?.map((t) => t.name)).toEqual(['SLACK_POST']);+ });++ it('keeps a refreshed connection active while its server write is still in flight', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('slack', { status: 'PENDING' })]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(connectionIds()).toEqual(['slack']));++ mocks.getConnection.mockResolvedValue({ gmailReadPermission: false, status: 'ACTIVE' });+ mocks.listActions.mockResolvedValue({+ tools: [+ { description: 'Post a message', inputSchema: { type: 'object' }, name: 'SLACK_POST' },+ ],+ });+ // The server write of the ACTIVE row stays in flight …+ let resolveUpdate!: (value: unknown) => void;+ const updateInFlight = new Promise((resolve) => {+ resolveUpdate = resolve;+ });+ mocks.updateComposioPlugin.mockReturnValueOnce(updateInFlight);++ let refresh!: Promise<void>;+ await act(async () => {+ refresh = useToolStore.getState().refreshComposioConnectionStatus('slack');+ });+ await waitFor(() => expect(mocks.updateComposioPlugin).toHaveBeenCalledTimes(1));+ expect(useToolStore.getState().composioServers[0].status).toBe('active');++ // … and a focus revalidation the server answers in that window still+ // returns the pre-refresh `PENDING` row: it must not revert the write.+ await act(async () => {+ await sync.result.current.mutate();+ });+ const row = useToolStore.getState().composioServers.find((s) => s.identifier === 'slack');+ expect(row?.status).toBe('active');+ expect(row?.tools?.map((t) => t.name)).toEqual(['SLACK_POST']);++ await act(async () => {+ resolveUpdate({ success: true });+ await refresh;+ });+ expect(useToolStore.getState().composioServers[0].status).toBe('active');+ });++ it('discards a connection the server confirms after the identity switched scope', async () => {+ mocks.getComposioPlugins.mockResolvedValue([]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(useToolStore.getState().isComposioServersInit).toBe(true));++ let resolveCreate!: (value: unknown) => void;+ mocks.createConnection.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveCreate = resolve;+ }),+ );++ let created!: Promise<unknown>;+ await act(async () => {+ created = useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'SLACK', identifier: 'slack', label: 'Slack' });+ });+ await waitFor(() => expect(mocks.createConnection).toHaveBeenCalledTimes(1));++ // The user switches identity before the server answers.+ const nextScope = `composio-user-${randomUUID()}:personal`;+ useScope(nextScope);+ await act(async () => {});++ await act(async () => {+ resolveCreate({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });+ await created;+ });++ // The completion belongs to the scope that started it: it must not land in+ // the switched-to list, nor be persisted into that scope's partition.+ expect(connectionIds()).not.toContain('slack');+ const persisted = await composioServersResource.storage!.get({+ queryKey: SERVERS_STORAGE_KEY,+ scope: nextScope,+ });+ expect((persisted?.data ?? []).some((s) => s.connectedAccountId === 'ca_slack')).toBe(false);+ });++ it('does not mint a reauthorized connection into the scope switched to during cleanup', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('slack', { status: 'FAILED' })]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(connectionIds()).toEqual(['slack']));++ let resolveDelete!: (value: unknown) => void;+ mocks.deleteConnection.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveDelete = resolve;+ }),+ );+ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_slack',+ connectedAccountId: 'ca_slack_new',+ identifier: 'slack',+ redirectUrl: 'https://composio.dev/redirect',+ });++ let reauthorized!: Promise<unknown>;+ await act(async () => {+ reauthorized = useToolStore.getState().reauthorizeComposioConnection('slack');+ });+ await waitFor(() => expect(mocks.deleteConnection).toHaveBeenCalledTimes(1));++ // The user switches identity while the stale connection is being cleaned up.+ const nextScope = `composio-user-${randomUUID()}:personal`;+ mocks.getComposioPlugins.mockResolvedValue([]);+ useScope(nextScope);+ await act(async () => {});++ await act(async () => {+ resolveDelete({ success: true });+ await reauthorized;+ });++ // The reauthorization belongs to the scope that started it: no fresh link is+ // minted for — nor persisted into — the switched-to identity.+ expect(mocks.createConnection).not.toHaveBeenCalled();+ const persisted = await composioServersResource.storage!.get({+ queryKey: SERVERS_STORAGE_KEY,+ scope: nextScope,+ });+ expect((persisted?.data ?? []).some((s) => s.connectedAccountId === 'ca_slack_new')).toBe(+ false,+ );+ });++ it('does not let a pending write in one scope drop another scope’s list', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail', { status: 'PENDING' })]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(connectionIds()).toEqual(['gmail']));++ mocks.getConnection.mockResolvedValue({ gmailReadPermission: false, status: 'ACTIVE' });+ mocks.listActions.mockResolvedValue({+ tools: [{ description: 'Fetch', inputSchema: { type: 'object' }, name: 'GMAIL_FETCH' }],+ });+ let resolveUpdate!: (value: unknown) => void;+ mocks.updateComposioPlugin.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveUpdate = resolve;+ }),+ );++ // Scope A starts a refresh whose server write stays in flight.+ let refresh!: Promise<void>;+ await act(async () => {+ refresh = useToolStore.getState().refreshComposioConnectionStatus('gmail');+ });+ await waitFor(() => expect(mocks.updateComposioPlugin).toHaveBeenCalledTimes(1));++ // The user switches scope while A's write is still pending.+ const nextScope = `composio-user-${randomUUID()}:personal`;+ useScope(nextScope);++ // B's own list must still load: A's hold is not B's to apply.+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('slack', { status: 'PENDING' })]);+ const nextSync = renderHook(+ () => useToolStore((s) => s.useFetchUserComposioConnections)(true),+ {+ wrapper,+ },+ );+ await waitFor(() => expect(connectionIds()).toEqual(['slack']));++ await act(async () => {+ resolveUpdate({ success: true });+ await refresh;+ });+ await act(async () => {+ await nextSync.result.current.mutate();+ });+ expect(connectionIds()).toEqual(['slack']);+ });++ it('keeps a deletion intent across a scope round trip', async () => {+ const firstScope = cacheScope.get();+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail', { status: 'PENDING' })]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(connectionIds()).toEqual(['gmail']));++ // A deletion whose server call stays in flight.+ let resolveDelete!: (value: unknown) => void;+ mocks.deleteConnection.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveDelete = resolve;+ }),+ );+ let removal!: Promise<void>;+ await act(async () => {+ removal = useToolStore.getState().removeComposioConnection('gmail');+ });+ await waitFor(() => expect(mocks.deleteConnection).toHaveBeenCalledTimes(1));+ expect(connectionIds()).toEqual([]);++ // Away to another scope — its sync runs, so the previous intent is touched —+ // and back, all while the deletion is still awaiting the server.+ useScope(`composio-user-${randomUUID()}:personal`);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(connectionIds()).toEqual(['gmail']));++ useScope(firstScope);+ const backSync = renderHook(+ () => useToolStore((s) => s.useFetchUserComposioConnections)(true),+ { wrapper },+ );+ // The server has not finished deleting: the response must not resurrect it.+ await act(async () => {+ await backSync.result.current.mutate();+ });+ expect(connectionIds()).toEqual([]);++ await act(async () => {+ resolveDelete({ success: true });+ await removal;+ });+ expect(connectionIds()).toEqual([]);+ });++ it('revalidates through the connections sync mutate without clearing the list', async () => {+ mocks.getComposioPlugins.mockResolvedValue([composioPlugin('gmail')]);+ const sync = renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), {+ wrapper,+ });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));++ await act(async () => {+ await sync.result.current.mutate();+ });++ expect(useToolStore.getState().composioServers).toHaveLength(1);+ });+});++describe('composio app tools replica', () => {+ let scope = '';++ beforeEach(() => {+ scope = `composio-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useToolStore.setState(initialComposioStoreState));+ });++ afterEach(async () => {+ cleanup();+ await composioAppToolsResource.storage!.remove({+ queryKey: APP_TOOLS_STORAGE_KEY,+ scope,+ });+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted catalog before the network answers', async () => {+ const cached = [{ description: 'Send email', inputSchema: { type: 'object' }, name: 'SEND' }];+ await composioAppToolsResource.storage!.set(+ { queryKey: APP_TOOLS_STORAGE_KEY, scope },+ { data: cached, updatedAt: 1 },+ );+ mocks.getActions.mockImplementation(pending);++ const hook = renderHook(+ () => ({+ data: useToolStore((s) => s.composioAppToolsMap.gmail),+ sync: useToolStore((s) => s.useFetchAppTools)('gmail'),+ }),+ { wrapper },+ );++ await waitFor(() => expect(hook.result.current.data).toEqual(cached));+ expect(hook.result.current.sync.isValidating).toBe(true);+ });++ it('replaces the catalog with the server response and persists it', async () => {+ mocks.getActions.mockResolvedValue({+ tools: [{ description: 'List files', inputSchema: { type: 'object' }, name: 'LIST' }],+ });++ const hook = renderHook(+ () => ({+ data: useToolStore((s) => s.composioAppToolsMap.gmail),+ sync: useToolStore((s) => s.useFetchAppTools)('gmail'),+ }),+ { wrapper },+ );++ await waitFor(() => expect(hook.result.current.data?.[0]?.name).toBe('LIST'));+ await waitFor(async () =>+ expect(+ (+ await composioAppToolsResource.storage!.get({+ queryKey: APP_TOOLS_STORAGE_KEY,+ scope,+ })+ )?.data[0]?.name,+ ).toBe('LIST'),+ );+ });++ it('reads nothing for an unknown app without fetching', async () => {+ renderHook(() => useToolStore((s) => s.useFetchAppTools)(undefined), { wrapper });++ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(mocks.getActions).not.toHaveBeenCalled();+ expect(useToolStore.getState().composioAppToolsMap['gmail']).toBeUndefined();+ });++ it('exposes the connections key as a single scope entry', () => {+ expect(COMPOSIO_SERVERS_KEY).toBe('all');+ });+});++describe('mergeComposioServers', () => {+ const server = (identifier: string) => ({ identifier }) as never;+ /** A response issued when the write sequence was `since`. */+ const response = (since: number, ...identifiers: string[]) => ({+ servers: identifiers.map(server),+ since,+ });++ it('carries a pending add and hides a pending remove until the server reflects them', () => {+ const intent = createComposioLocalIntent();+ intent.added.set('slack', server('slack'));+ intent.removed.add('gmail');++ // A response issued after both writes: the new row is re-appended, the+ // deleted one stays hidden (the server has not adopted them yet).+ expect(mergeComposioServers(response(0, 'gmail'), intent, 0)!.map((s) => s.identifier)).toEqual(+ ['slack'],+ );++ // The server echoes the add and confirms the removal: intent settles.+ expect(mergeComposioServers(response(0, 'slack'), intent, 0)!.map((s) => s.identifier)).toEqual(+ ['slack'],+ );+ expect(intent.added.size).toBe(0);+ expect(intent.removed.size).toBe(0);++ // The server is authoritative again: a later response wins.+ expect(mergeComposioServers(response(0, 'gmail'), intent, 0)!.map((s) => s.identifier)).toEqual(+ ['gmail'],+ );+ });++ it('returns the incoming list unchanged when nothing is pending', () => {+ const incoming = response(0, 'gmail');+ expect(mergeComposioServers(incoming, createComposioLocalIntent(), 0)).toBe(incoming.servers);+ });++ it('drops a response issued before the latest local write', () => {+ const incoming = response(3, 'gmail');++ // Two local writes happened after the request was issued (this is the+ // reported race): the response predates them and must not be applied.+ expect(mergeComposioServers(incoming, createComposioLocalIntent(), 5)).toBeUndefined();++ // A request issued after the latest write is applied as usual.+ expect(mergeComposioServers(response(5, 'gmail'), createComposioLocalIntent(), 5)).toEqual([+ server('gmail'),+ ]);+ });++ it('drops every response while a local write is still being persisted', () => {+ const intent = createComposioLocalIntent();+ intent.added.set('slack', server('slack'));++ // The request was issued after the local write, but the server has not+ // persisted it yet: nothing it answers can be trusted.+ expect(mergeComposioServers(response(5, 'slack'), intent, 5, true)).toBeUndefined();++ // Persistence finished: a response issued after the write applies again.+ expect(mergeComposioServers(response(5, 'slack'), intent, 5)!.map((s) => s.identifier)).toEqual(+ ['slack'],+ );+ });+});