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.

33.8 KB
Raw Blame
import { isDesktop } from '@lobechat/const';
import type { LobeToolCustomPlugin } from '@lobechat/types';
import {
  connectorDeviceBinding,
  connectorMcpEndpoint,
  isDeviceOnlyMcpEndpoint,
} from '@lobechat/utils/mcpEndpoint';
import type { SWRResponse } from 'swr';

import type { ConnectorToolPermission } from '@/database/schemas';
import { runsOnAnotherDevice } from '@/helpers/mcpDeviceBinding';
import { buildCloudMcpManifest, cloudManifestTools } from '@/libs/mcp/cloudManifest';
import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';
import {
  cacheScope,
  createReplicaSlice,
  linkReplicaEntity,
  type ReplicaLens,
  type ReplicaSyncResult,
} from '@/libs/replica';
import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
import { useClientDataSWR } from '@/libs/swr';
import { lambdaClient } from '@/libs/trpc/client';
import { discoverService } from '@/services/discover';
import { type LocalMcpTool, mcpService } from '@/services/mcp';
import type { StoreSetter } from '@/store/types';
import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';

import type { ToolStore } from '../../store';
import { executeLegacyMigrationSave } from './legacyPluginMigration';
import {
  agentBoundConnectorsEntity,
  agentBoundConnectorsResource,
  agentConnectorsResource,
  CONNECTOR_LIST_KEY,
  connectorsEntity,
  connectorsResource,
  withoutConnectorSecrets,
} from './projection';
import { connectorSelectors } from './selectors';
import type {
  AgentBoundConnector,
  ConnectorAccountFlowOptions,
  ConnectorAccountFlowResult,
  ConnectorWithTools,
} from './types';

type Setter = StoreSetter<ToolStore>;

const CONNECTOR_LIST_SWR_KEY = 'connectorList';

/** The connector lists are one entry per scope, so every sync shares these params. */
const LIST_PARAMS = {} as Record<string, never>;

/**
 * The base connector list keeps its long-standing flat `connectors` field as
 * the replica view, so every selector keeps reading what it did. The init flag
 * gates `get`: before the first hydrate/replace the view must read `undefined`,
 * otherwise the empty default would block hydration from storage.
 */
const connectorsLens: ReplicaLens<ToolStore, ConnectorWithTools[]> = {
  clear: () => ({ connectors: [], isConnectorsInit: false }),
  get: (state) => (state.isConnectorsInit ? state.connectors : undefined),
  keys: (state) => (state.isConnectorsInit ? [CONNECTOR_LIST_KEY] : []),
  set: (_state, _key, data) =>
    data === undefined
      ? { connectors: [], isConnectorsInit: false }
      : { connectors: data, isConnectorsInit: true },
};

/** The agent-bound aggregate is one entry, gated by `isAgentBoundInit`. */
const agentBoundConnectorsLens: ReplicaLens<ToolStore, AgentBoundConnector[]> = {
  clear: () => ({ agentBoundConnectors: [], isAgentBoundInit: false }),
  get: (state) => (state.isAgentBoundInit ? state.agentBoundConnectors : undefined),
  keys: (state) => (state.isAgentBoundInit ? [CONNECTOR_LIST_KEY] : []),
  set: (_state, _key, data) =>
    data === undefined
      ? { agentBoundConnectors: [], isAgentBoundInit: false }
      : { agentBoundConnectors: data, isAgentBoundInit: true },
};

/**
 * Per-agent lists live in `agentConnectors[agentId]`; the per-agent bucket of
 * `agentConnectorsInit` carries the same gate the flat lists use.
 */
const agentConnectorsLens: ReplicaLens<ToolStore, ConnectorWithTools[]> = {
  clear: () => ({ agentConnectors: {}, agentConnectorsInit: {} }),
  get: (state, key) => (state.agentConnectorsInit[key] ? state.agentConnectors[key] : undefined),
  keys: (state) => Object.keys(state.agentConnectors ?? {}),
  set: (state, key, data) => {
    const agentConnectors = { ...state.agentConnectors };
    const agentConnectorsInit = { ...state.agentConnectorsInit };
    if (data === undefined) {
      delete agentConnectors[key];
      delete agentConnectorsInit[key];
    } else {
      agentConnectors[key] = data;
      agentConnectorsInit[key] = true;
    }
    return { agentConnectors, agentConnectorsInit };
  },
};

/** The connector lists of the active scope (their entry params are constant). */
const fetchConnectorList = (): Promise<ConnectorWithTools[]> =>
  lambdaClient.connector.list.query() as unknown as Promise<ConnectorWithTools[]>;

const fetchAgentBoundConnectorList = (): Promise<AgentBoundConnector[]> =>
  lambdaClient.connector.listAgentBound.query() as unknown as Promise<AgentBoundConnector[]>;

const fetchAgentConnectorList = ({ agentId }: { agentId: string }): Promise<ConnectorWithTools[]> =>
  lambdaClient.connector.listByAgent.query({ agentId }) as unknown as Promise<ConnectorWithTools[]>;

/** The base connector list's entry among the server-confirmed lists */
const BASE_LIST_KEY = '#base';

export const createConnectorSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
  new ConnectorActionImpl(set, get, _api);

/**
 * The connector slice is a set of `local-replica` resources: the base
 * list, the agent-bound aggregate and the per-agent buckets. The store fields
 * keep their historical shape (`connectors`, `agentBoundConnectors`,
 * `agentConnectors`) as the replica views, so every selector and consumer is
 * unchanged; the slab below only orchestrates fetching and writes.
 */
export class ConnectorActionImpl {
  readonly #agentBoundConnectors;
  readonly #agentConnectors;
  /** One connector lives in the base list, the aggregate and per-agent buckets. */
  readonly #connectorRows;
  readonly #connectors;
  /** `${scope}|${list}` entries the server answered in this session (not painted from storage) */
  readonly #confirmed = new Set<string>();
  readonly #confirming = new Map<string, Promise<void>>();
  readonly #get: () => ToolStore;
  readonly #set: Setter;

  constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
    void _api;
    this.#set = set;
    this.#get = get;
    this.#connectors = createReplicaSlice(connectorsResource, {
      actionPrefix: 'connectors',
      entity: connectorsEntity,
      fetcher: fetchConnectorList,
      get,
      set,
      stateKey: 'connectorsReplica',
      toPersisted: withoutConnectorSecrets,
      view: connectorsLens,
    });
    this.#agentBoundConnectors = createReplicaSlice(agentBoundConnectorsResource, {
      actionPrefix: 'agentBoundConnectors',
      entity: agentBoundConnectorsEntity,
      fetcher: fetchAgentBoundConnectorList,
      get,
      set,
      stateKey: 'agentBoundConnectorsReplica',
      toPersisted: withoutConnectorSecrets,
      view: agentBoundConnectorsLens,
    });
    this.#agentConnectors = createReplicaSlice(agentConnectorsResource, {
      actionPrefix: 'agentConnectors',
      effects: {
        onApplied: (_rows, { agentId }, { scope }) => {
          this.#confirmed.add(`${scope}|${agentId}`);
        },
      },
      entity: connectorsEntity,
      fetcher: fetchAgentConnectorList,
      get,
      set,
      stateKey: 'agentConnectorsReplica',
      toPersisted: withoutConnectorSecrets,
      view: agentConnectorsLens,
    });
    this.#connectorRows = linkReplicaEntity<ConnectorWithTools>([
      this.#connectors,
      this.#agentBoundConnectors,
      this.#agentConnectors,
    ]);

    // Imperative consumers also read these views, even when no sync hook is mounted.
    // Clear every previous identity's rows and init flags as soon as the scope changes.
    subscribeCacheScope((scope) => this.#dropStaleScope(scope));
  }

  /**
   * Drop every connector view of the previous identity (rows *and* the init
   * flag that lets consumers skip their fetch). A no-op when the scope has not
   * moved on, which is the common case on the imperative refresh paths.
   */
  #dropStaleScope = (scope: string): void => {
    this.#connectors.ensureScope(scope);
    this.#agentBoundConnectors.ensureScope(scope);
    this.#agentConnectors.ensureScope(scope);
    // The lists were dropped with the scope, so were their confirmations:
    // coming back to a scope must load its lists from the server again
    for (const id of this.#confirmed) {
      if (!id.startsWith(`${scope}|`)) this.#confirmed.delete(id);
    }
  };

  /**
   * Refresh the base connector list. The persisted projection paints as soon
   * as it is read while the network confirms it in parallel, instead of
   * blanking to an empty array first.
   *
   * The identity scope is captured when the request is issued: `fetch`
   * captures it itself and `hydrate` gets it explicitly, because the replica
   * reads the *active* scope at call time — i.e. after the response has already
   * landed. A response that resolves after the scope moved on is then dropped
   * by the replica's settle pipeline instead of being written into the next
   * identity's partition. The refresh never joins a request already in flight
   * (`fresh`): it runs after mutations, and that one may hold the pre-mutation
   * list.
   *
   * The whole cache scope (user + workspace) is captured, not just the
   * workspace: two different signed-in users in personal context both have a
   * `null` workspace, so a workspace-only guard cannot tell them apart and
   * would store user A's connector inventory in user B's partition after an
   * account switch. Booting straight into a workspace URL is the other case
   * this covers — the tree mounts once in personal context before the URL→store
   * sync resolves the slug, so a personal `list` query is already in flight
   * when the workspace switch fires its own, and the personal one landing last
   * is what made a business workspace list the user's PERSONAL tools.
   *
   * Dropping the response is only half of it. A dropped response must not leave
   * the *previous* scope's hydration behind either: the persisted personal
   * projection can have painted (and set `isConnectorsInit`) during that same
   * personal window, and every consumer gates its fetch on that flag — so the
   * workspace would keep showing the personal inventory and never load its own.
   * `#dropStaleScope` clears the views the moment the scope moves (see the
   * `subscribeCacheScope` wiring in the constructor).
   *
   * No reset is needed here for the fetch itself: the engine folds the scope
   * reset into the same commit as the response, so a stale view can never be
   * replaced into — and doing it here would commit store state synchronously
   * before the caller's in-flight guard is up, which multiplies the requests a
   * single scope switch launches.
   */
  fetchConnectors = async (): Promise<void> => {
    const scope = cacheScope.get();
    const pending = this.#connectors.fetch(LIST_PARAMS, { fresh: true });
    // Awaited together, so a request that fails while storage paints is still handled
    const [, result] = await Promise.all([
      this.#get().isConnectorsInit ? undefined : this.#connectors.hydrate(LIST_PARAMS, scope),
      pending,
    ]);
    if (result.applied) this.#confirmed.add(`${scope}|${BASE_LIST_KEY}`);
  };

  /**
   * Load the base connector list for a view that reads it, e.g. the install
   * state of a marketplace MCP that only exists as a connector. Loads through
   * {@link fetchConnectors}, so the list is confirmed for this cache scope like
   * any other load; a view mounting after the first load reuses it. Keyed by
   * the cache scope: a caller that re-renders when a scope switch drops the
   * list (`isConnectorsInit`) loads the new identity's list.
   */
  useFetchConnectors = (enable: boolean): SWRResponse =>
    useClientDataSWR(
      enable ? [CONNECTOR_LIST_SWR_KEY, cacheScope.get()] : null,
      () => this.fetchConnectors(),
      { revalidateIfStale: false, revalidateOnFocus: false },
    );

  useFetchAgentConnectors = (agentId: string): ReplicaSyncResult =>
    this.#agentConnectors.useSync(agentId ? { agentId } : null);

  useFetchAgentBoundConnectors = (enabled: boolean): ReplicaSyncResult =>
    this.#agentBoundConnectors.useSync(LIST_PARAMS, { enabled });

  /**
   * Refresh the connector lists after a mutation. Always refreshes the base
   * list; also refreshes the agent-bound aggregate when it has been loaded (the
   * unified settings page), so a connector-detail action on an agent connector
   * (delete / sync / permission reset) updates that list too. On base-only
   * pages `isAgentBoundInit` is false, so this stays a single query.
   */
  /** Agents whose own connectors are loaded, so every write keeps them current. */
  #loadedAgentIds = (): string[] => {
    const init = this.#get().agentConnectorsInit;
    return Object.keys(init).filter((agentId) => init[agentId]);
  };

  #refreshConnectorLists = async (): Promise<void> => {
    const tasks = [this.fetchConnectors()];
    if (this.#get().isAgentBoundInit) tasks.push(this.fetchAgentBoundConnectors());
    // The per-agent lists decide what a view's tool call needs (approval,
    // availability), so they must not keep a connector's old state either
    for (const agentId of this.#loadedAgentIds()) tasks.push(this.fetchAgentConnectors(agentId));
    await Promise.all(tasks);
  };

  /**
   * Fetch every agent-owned connector across all agents (the flat aggregate for
   * the unified connector-settings page). Each row is enriched
   * server-side with the owning agent's title/avatar. Scope-correct: a workspace
   * context only returns that workspace's agent connectors. See
   * {@link ConnectorActionImpl.fetchConnectors} for the captured-scope rule.
   */
  fetchAgentBoundConnectors = async (): Promise<void> => {
    const scope = cacheScope.get();
    const pending = this.#agentBoundConnectors.fetch(LIST_PARAMS, { fresh: true });
    if (!this.#get().isAgentBoundInit) await this.#agentBoundConnectors.hydrate(LIST_PARAMS, scope);
    await pending;
  };

  /**
   * Fetch an agent's own tools (agent-owned + mounted) for the "Agent Tools"
   * tab. Stored keyed by agentId. See
   * {@link ConnectorActionImpl.fetchConnectors} for the captured-scope rule.
   */
  fetchAgentConnectors = async (agentId: string): Promise<void> => {
    const scope = cacheScope.get();
    const params = { agentId };
    const pending = this.#agentConnectors.fetch(params, { fresh: true });
    // Awaited together, so a request that fails while storage paints is still handled
    await Promise.all([
      this.#get().agentConnectorsInit[agentId]
        ? undefined
        : this.#agentConnectors.hydrate(params, scope),
      pending,
    ]);
  };

  /**
   * Whether the base connector list (and `agentId`'s own, if given) came from
   * the server in this cache scope. A list painted from storage is not: its
   * permissions may be stale, so nothing that authorizes a call may trust it.
   */
  isConnectorListConfirmed = (agentId?: string): boolean => {
    const scope = cacheScope.get();
    return (
      this.#confirmed.has(`${scope}|${BASE_LIST_KEY}`) &&
      (!agentId || this.#confirmed.has(`${scope}|${agentId}`))
    );
  };

  /**
   * Load the connector lists from the server unless this cache scope already
   * has, for callers that resolve an identifier the way an agent's runs do and
   * act on what they find (a view's tool-call policy, its resource read): the
   * base list, and `agentId`'s own tools if given. Joins a load in flight.
   *
   * `revalidate` loads them even when confirmed, for a caller that authorizes
   * by them: a permission may have changed since, in another tab or by another
   * workspace member.
   */
  ensureConfirmedConnectors = async (
    agentId?: string,
    { revalidate = false }: { revalidate?: boolean } = {},
  ): Promise<void> => {
    const confirm = (key: string, load: () => Promise<void>) => {
      const id = `${cacheScope.get()}|${key}`;
      if (!revalidate && this.#confirmed.has(id)) return;
      let loading = this.#confirming.get(id);
      if (!loading) {
        loading = load().finally(() => this.#confirming.delete(id));
        this.#confirming.set(id, loading);
      }
      return loading;
    };

    await Promise.all([
      confirm(BASE_LIST_KEY, this.fetchConnectors),
      agentId ? confirm(agentId, () => this.fetchAgentConnectors(agentId)) : undefined,
    ]);
  };

  /** Copy a user connector into an agent-owned, independently editable row. */
  copyConnectorToAgent = async (connectorId: string, agentId: string): Promise<string> => {
    const { id } = await lambdaClient.connector.copyToAgent.mutate({ agentId, connectorId });
    await this.fetchAgentConnectors(agentId);
    return id;
  };

  /** Mount (reference + lock) a user connector onto an agent. */
  mountConnectorToAgent = async (connectorId: string, agentId: string): Promise<void> => {
    await lambdaClient.connector.mountToAgent.mutate({ agentId, connectorId });
    await Promise.all([this.fetchAgentConnectors(agentId), this.fetchConnectors()]);
  };

  /** Unmount / detach a connector from an agent (unmounts or deletes the agent row). */
  detachConnectorFromAgent = async (
    connectorId: string,
    agentId: string,
    mode: 'unmount' | 'delete',
  ): Promise<void> => {
    if (mode === 'unmount') {
      await lambdaClient.connector.unmountFromAgent.mutate({ connectorId });
    } else {
      await lambdaClient.connector.delete.mutate({ id: connectorId });
    }
    await Promise.all([this.fetchAgentConnectors(agentId), this.fetchConnectors()]);
  };

  /**
   * Fetch the connector with its decrypted user-set credentials for the edit
   * form. Does NOT update the store — caller uses the result directly.
   * Machine-managed OAuth tokens are excluded server-side.
   */
  getConnectorForEdit = async (id: string) => {
    return lambdaClient.connector.getForEdit.query({ id });
  };

  /**
   * Create (or idempotently update) a connector. `isNew` is the server's
   * knowledge of whether the row was freshly created — callers that roll back
   * on a later sync failure must use it instead of a client-side cache check,
   * which is unreliable before `fetchConnectors` has completed.
   */
  createConnector = async (
    params: Parameters<typeof lambdaClient.connector.create.mutate>[0],
  ): Promise<{ id: string; isNew: boolean }> => {
    this.#set({ connectorCreating: true }, false, 'createConnector/start');
    try {
      const created = await lambdaClient.connector.create.mutate(params);
      // The row is written: a list refresh that fails now must not fail the
      // create, or the caller could not roll back the row it replaced
      await this.fetchConnectors().catch((error) => {
        console.error(
          '[connector] refreshing the list after creating %s failed:',
          created.id,
          error,
        );
      });
      return { id: created.id, isNew: created.isNew };
    } finally {
      this.#set({ connectorCreating: false }, false, 'createConnector/end');
    }
  };

  migrateLegacyPlugin = (legacy: LobeToolCustomPlugin, value: LobeToolCustomPlugin) =>
    executeLegacyMigrationSave(legacy, value, {
      createConnector: (payload) => lambdaClient.connector.create.mutate(payload),
      deleteConnector: this.#deleteConnectorRecord,
      refreshLists: async () => {
        await Promise.all([this.#refreshConnectorLists(), this.#get().refreshPlugins()]);
      },
      syncConnectorTools: (id, payload) => this.#writeConnectorTools(id, {}, payload),
      uninstallCustomPlugin: (identifier) => this.#get().removeInstalledPluginRecord(identifier),
    });

  /** Connect an additional account and refresh all connector lists after authorization. */
  connectConnectorAccount = (
    connectorId: string,
    options?: ConnectorAccountFlowOptions,
  ): Promise<ConnectorAccountFlowResult> =>
    this.#authorizeAccount(connectorId, { mode: 'add' }, options);

  /** Reauthorize the selected account and return the actual server-resolved outcome. */
  reauthorizeConnectorAccount = (
    connectorId: string,
    linkId: string,
    options?: ConnectorAccountFlowOptions,
  ): Promise<ConnectorAccountFlowResult> =>
    this.#authorizeAccount(connectorId, { mode: 'reauthorize', linkId }, options);

  #authorizeAccount = async (
    connectorId: string,
    link: { mode: 'add' } | { mode: 'reauthorize'; linkId: string },
    options: ConnectorAccountFlowOptions = {},
  ): Promise<ConnectorAccountFlowResult> => {
    const linksOf = () =>
      [
        ...(this.#get().connectors ?? []),
        ...(this.#get().agentBoundConnectors ?? []),
        ...Object.values(this.#get().agentConnectors ?? {}).flat(),
      ].find((c) => c.id === connectorId)?.links ?? [];
    const before = linksOf();
    let flowId: string | undefined;
    try {
      options.signal?.throwIfAborted();
      const started = await lambdaClient.connector.startOAuth.mutate(
        {
          id: connectorId,
          link,
        },
        { signal: options.signal },
      );
      flowId = started.flowId;
      const reported = await waitForConnectorOAuth(
        options.popup,
        connectorId,
        started.authorizationUrl,
        options.signal,
        link.mode === 'add',
      );
      await this.#refreshConnectorLists();
      // The callback's own report, else the server's record of the flow (the
      // native window reports success alone), else the lists' difference: the
      // record is a fallback whose absence never fails a stored authorization
      if (reported) return reported;
      const recorded = flowId
        ? await lambdaClient.connector.oauthResult.query({ flowId }).catch(() => undefined)
        : undefined;
      if (recorded) return recorded;
      const created = linksOf().find((item) => !before.some((old) => old.id === item.id));
      return created
        ? { outcome: 'created', linkId: created.id }
        : {
            outcome: link.mode === 'add' ? 'matchedExisting' : 'reauthorized',
            linkId: link.mode === 'reauthorize' ? link.linkId : undefined,
          };
    } catch (error) {
      if (options.signal?.aborted) throw new ConnectorOAuthError('dismissed');
      // Providers whose COOP policy severs `window.opener` lose the callback's
      // message: the window then reads as closed or never reporting back,
      // although the callback stored the account. The server recorded how the
      // flow ended, so ask it before calling the authorization lost.
      const recovered = await this.#recoverAccountAuthorization(error, flowId);
      if (recovered) return recovered;
      // Server rejections (a 403, an OAuth server that refuses registration)
      // carry the reason the caller shows; only the window flow is an OAuth error.
      throw error;
    } finally {
      options.popup?.close();
    }
  };

  #recoverAccountAuthorization = async (
    error: unknown,
    flowId: string | undefined,
  ): Promise<ConnectorAccountFlowResult | undefined> => {
    if (!flowId || !(error instanceof ConnectorOAuthError)) return;
    if (error.reason !== 'dismissed' && error.reason !== 'timeout') return;
    let result: ConnectorAccountFlowResult;
    try {
      result = await lambdaClient.connector.oauthResult.query({ flowId });
    } catch {
      return; // no completion recorded: the authorization did not finish
    }
    await this.#refreshConnectorLists();
    return result;
  };

  /** Rename an account and refresh every loaded connector list. */
  renameConnectorAccount = async (
    connectorId: string,
    linkId: string,
    name: string,
  ): Promise<void> => {
    await lambdaClient.connector.renameLink.mutate({ id: connectorId, linkId, name });
    await this.#refreshConnectorLists();
  };

  /** Remove an account and refresh its connector, including last-account disconnection. */
  removeConnectorAccount = async (connectorId: string, linkId: string): Promise<void> => {
    await lambdaClient.connector.deleteLink.mutate({ id: connectorId, linkId });
    await this.#refreshConnectorLists();
  };

  /**
   * Begin the OAuth authorization-code flow for a custom connector and return
   * the authorize URL for the caller to open in a popup. Resolves the client
   * on the server: pre-registration, a Client ID Metadata Document, or DCR.
   */
  startConnectorOAuth = async (id: string): Promise<string> => {
    const { authorizationUrl } = await lambdaClient.connector.startOAuth.mutate({ id });
    return authorizationUrl;
  };

  /**
   * Delete a connector. The row leaves every list that holds it (base,
   * agent-bound and per-agent buckets) in one fan-out — but only once the
   * server has confirmed the delete. The row must stay mounted while the
   * request is in flight: a detail pane bound to it would otherwise blank for
   * every deletion (and blink back if the delete is rejected), which is why the
   * removal is confirmed rather than optimistic.
   */
  deleteConnector = async (id: string): Promise<void> => {
    await this.#deleteConnectorRecord(id);
    await this.#refreshConnectorLists();
  };

  #deleteConnectorRecord = async (id: string): Promise<void> => {
    await lambdaClient.connector.delete.mutate({ id });
    this.#connectorRows.remove(id);
  };

  updateConnector = async (
    id: string,
    patch: {
      credentials?:
        | { token: string; type: 'bearer' }
        | { headers: Record<string, string>; type: 'header' }
        | null;
      isEnabled?: boolean;
      /** `null` clears the field, as on an endpoint-less row being put back. */
      mcpConnectionType?: 'cloud' | 'http' | 'stdio' | null;
      mcpServerUrl?: string | null;
      mcpStdioConfig?: { args?: string[]; command: string; env?: Record<string, string> } | null;
      metadata?: Record<string, unknown>;
      name?: string;
      /** A new client leaves the row disconnected until it is authorized; `null` drops it. */
      oidcConfig?: {
        clientId?: string;
        clientSecret?: string;
        scheme?: 'pre_registration' | 'dcr' | 'client_id_metadata_document';
      } | null;
      /** Puts back the source a failed install's `createConnector` moved the row off. */
      sourceType?: 'custom' | 'marketplace';
    },
  ): Promise<void> => {
    await lambdaClient.connector.update.mutate({ id, patch: patch as any });
    await this.#refreshConnectorLists();
  };

  /**
   * List the connector's tools and store them. `pruneMissingAutoTools` is for
   * an install: the `auto` tools the server no longer lists are dropped.
   */
  syncConnectorTools = async (
    id: string,
    options: { pruneMissingAutoTools?: boolean } = {},
  ): Promise<void> => {
    this.#set(
      (s) => ({ connectorSyncing: { ...s.connectorSyncing, [id]: true } }),
      false,
      'syncConnectorTools/start',
    );
    try {
      await this.#writeConnectorTools(
        id,
        options,
        connectorSelectors.connectorById(id)(this.#get()),
      );
      await this.#refreshConnectorLists();
    } finally {
      this.#set(
        (s) => ({ connectorSyncing: { ...s.connectorSyncing, [id]: false } }),
        false,
        'syncConnectorTools/end',
      );
    }
  };

  #writeConnectorTools = async (
    id: string,
    options: { pruneMissingAutoTools?: boolean },
    connector: Pick<ConnectorWithTools, 'identifier' | 'mcpConnectionType'> | undefined,
  ): Promise<void> => {
    if (connector?.mcpConnectionType === 'cloud') {
      await this.#syncCloudConnectorTools(id, options, connector.identifier);
    } else if (!(await this.#syncLocalConnectorTools(id, options))) {
      await lambdaClient.connector.syncTools.mutate({ id, ...options });
    }
  };

  /** A market-hosted connector lists its tools in the market manifest. */
  #syncCloudConnectorTools = async (
    id: string,
    options: { pruneMissingAutoTools?: boolean },
    identifier: string,
  ): Promise<void> => {
    const data = await discoverService.getMCPPluginManifest(identifier);
    await lambdaClient.connector.syncToolsFromClientById.mutate({
      id,
      ...options,
      tools: cloudManifestTools(buildCloudMcpManifest({ data, plugin: { identifier } })),
    });
  };

  /**
   * Desktop-only install/refresh path for connectors the cloud server cannot
   * reach itself: stdio MCP (must spawn on this machine), local/private
   * network HTTP endpoints, and HTTP set to connect through the device. The server-side `syncTools` would try to connect
   * FROM the cloud and fail with "Failed to start MCP service process" /
   * "fetch failed" (#16533), so the client lists the tools locally (via the
   * Electron main process, same path Test Connection uses) and reports them
   * through `syncToolsFromClientById`.
   *
   * Returns false when the connector is server-reachable (public HTTP) or when
   * not running in desktop — the caller falls back to the server-side sync.
   */
  #syncLocalConnectorTools = async (
    id: string,
    options: { pruneMissingAutoTools?: boolean },
  ): Promise<boolean> => {
    if (!isDesktop) return false;

    // `getForEdit` returns the decrypted user-set credentials (bearer/apikey/
    // header) needed to connect locally; an OAuth connector's access token is
    // fetched on its own (`resolveLocalConnectorHttpParams`).
    const detail = await lambdaClient.connector.getForEdit.query({ id });
    const isStdio = detail.mcpConnectionType === 'stdio';
    // A localhost / LAN address, or one the user set to connect through the device
    const isLocalHttp =
      !!detail.mcpServerUrl && isDeviceOnlyMcpEndpoint(connectorMcpEndpoint(detail));
    if (!isStdio && !isLocalHttp) return false;
    // Bound to another device: the server lists it there, where its calls run
    if (runsOnAnotherDevice(connectorDeviceBinding(detail)?.deviceId)) return false;

    // The full tool list, not a manifest: a manifest leaves out view-only
    // tools, yet a view's call must find its tool synced.
    let tools: LocalMcpTool[];
    if (isStdio) {
      if (!detail.mcpStdioConfig?.command) throw new Error('Connector is missing stdio config');
      tools = await mcpService.listLocalMcpTools({
        stdio: {
          args: detail.mcpStdioConfig.args ?? [],
          command: detail.mcpStdioConfig.command,
          env: detail.mcpStdioConfig.env ?? undefined,
          name: detail.identifier,
        },
      });
    } else {
      // The same credentials and headers its tool calls send
      const http = await resolveLocalConnectorHttpParams(detail, (connectorId) =>
        lambdaClient.connector.getLocalCallToken.mutate({ id: connectorId }),
      );
      tools = await mcpService.listLocalMcpTools({ http });
    }

    await lambdaClient.connector.syncToolsFromClientById.mutate({
      id,
      ...options,
      tools: tools.map((tool) => ({
        description: tool.description,
        inputSchema: tool.inputSchema,
        toolName: tool.name,
        visibility: tool.visibility,
        ...(tool.mcpAppMeta && { mcpAppMeta: tool.mcpAppMeta }),
      })),
    });
    return true;
  };

  disconnectConnector = async (id: string): Promise<void> => {
    await lambdaClient.connector.update.mutate({
      id,
      patch: { isEnabled: false },
    });
    await this.#refreshConnectorLists();
  };

  /**
   * Reset all tool permissions for a connector back to 'auto' (fully open).
   */
  resetConnectorPermissions = async (id: string): Promise<void> => {
    await lambdaClient.connector.resetPermissions.mutate({ id });
    await this.#refreshConnectorLists();
  };

  /**
   * Sync tools from a client-provided list (for Lobehub OAuth skills / Composio
   * that already have their tool list available on the client side).
   * Idempotent — safe to call whenever the detail panel opens.
   * Returns the connectorId, or `null` when no row was produced.
   */
  syncToolsFromClient = async (params: {
    identifier: string;
    name: string;
    sourceType: 'builtin' | 'custom' | 'marketplace';
    tools: Array<{ description?: string; inputSchema?: Record<string, unknown>; toolName: string }>;
  }): Promise<string | null> => {
    const result = await lambdaClient.connector.syncToolsFromClient.mutate(params);
    await this.fetchConnectors();
    return result.connectorId;
  };

  /**
   * Bootstrap connector entry for a builtin tool (reads manifest server-side).
   * Idempotent — safe to call whenever the detail panel opens.
   * Returns the connectorId, or `null` when no row was produced.
   */
  syncBuiltinTool = async (identifier: string): Promise<string | null> => {
    const result = await lambdaClient.connector.syncBuiltinTool.mutate({ identifier });
    await this.fetchConnectors();
    return result.connectorId;
  };

  /**
   * Bootstrap connector entry for an installed marketplace plugin.
   * Idempotent — safe to call whenever the detail panel opens.
   * Returns the connectorId, or `null` for legacy customPlugin rows that own
   * an MCP endpoint (those go through the frontend migration flow instead) and
   * for a plugin whose Composio account sits on a teammate's private connector.
   */
  syncPluginTools = async (identifier: string): Promise<string | null> => {
    const result = await lambdaClient.connector.syncPluginTools.mutate({ identifier });
    await this.fetchConnectors();
    return result.connectorId;
  };

  updateToolPermission = async (
    toolId: string,
    permission: ConnectorToolPermission,
  ): Promise<void> => {
    // Optimistic update — patch the tool in whichever list holds it. The base
    // list and the agent-bound aggregate are separate replicas, so each gets
    // its own overlay and both settle together.
    const patchTools = <
      T extends { tools: Array<{ id: string; permission: ConnectorToolPermission }> },
    >(
      list: T[],
    ): T[] =>
      list.map((c) => ({
        ...c,
        tools: c.tools.map((t) => (t.id === toolId ? { ...t, permission } : t)),
      }));

    const overlays = [
      this.#connectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools),
      this.#agentBoundConnectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools),
      // A loaded agent list may hold the same tool, and a view's tool call
      // reads its permission there
      ...this.#loadedAgentIds().map((agentId) =>
        this.#agentConnectors.beginOptimistic(agentId, patchTools),
      ),
    ];

    try {
      await lambdaClient.connector.updateToolPermission.mutate({ permission, toolId });
      for (const overlay of overlays) overlay.commit();
    } catch {
      // Roll back the overlays, then rebuild from the server.
      for (const overlay of overlays) overlay.rollback();
      await this.#refreshConnectorLists();
    }
  };
}

export type ConnectorAction = Pick<ConnectorActionImpl, keyof ConnectorActionImpl>;