1437 lines · 41.0 KB · TypeScript
RawDownload
import { Atom, Result } from "@effect-atom/atom";import type * as Registry from "@effect-atom/atom/Registry";import { RegistryContext, RegistryProvider, useAtomValue } from "@effect-atom/atom-react";import { createControlPlaneClient } from "@executor/control-plane/client";import type {  CompleteSourceOAuthResult,  ConnectSourceBatchPayload,  ConnectSourceBatchResult,  ConnectSourcePayload,  ConnectSourceResult,  ControlPlaneClient,  CreateSecretPayload,  CreateSecretResult,  CreateSourcePayload,  CreateWorkspaceOauthClientPayload,  DeleteSecretResult,  DiscoverSourcePayload,  InstanceConfig,  LocalInstallation,  SecretListItem,  Source,  SourceDiscoveryResult,  SourceInspection,  SourceInspectionDiscoverResult,  SourceInspectionToolDetail,  StartSourceOAuthPayload,  StartSourceOAuthResult,  UpdateSecretPayload,  UpdateSecretResult,  UpdateSourcePayload,  WorkspaceOauthClient,} from "@executor/control-plane";import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Runtime from "effect/Runtime";import * as React from "react"; const DEFAULT_EXECUTOR_API_BASE_URL = "http://127.0.0.1:8788";const PLACEHOLDER_WORKSPACE_ID = "ws_placeholder" as Source["workspaceId"];const PLACEHOLDER_ACCOUNT_ID = "acc_placeholder";const PLACEHOLDER_SOURCE_ID = "src_placeholder" as Source["id"]; type SourceMutationState<T> = {  status: "idle" | "pending" | "success" | "error";  data: T | null;  error: Error | null;}; export type SourceRemoveResult = {  removed: boolean;}; type AtomKeyPart = string | number | boolean | null | undefined; type SourcesKeyParts = readonly [boolean, Source["workspaceId"], string];type SourceKeyParts = readonly [boolean, Source["workspaceId"], string, Source["id"]];type SourceToolDetailKeyParts = readonly [  boolean,  Source["workspaceId"],  string,  Source["id"],  string | null,];type SourceDiscoveryKeyParts = readonly [  boolean,  Source["workspaceId"],  string,  Source["id"],  string,  number | null,];type WorkspaceOauthClientsKeyParts = readonly [  boolean,  Source["workspaceId"],  string,  string,]; type InvalidationTarget = {  workspaceId?: Source["workspaceId"];  accountId?: string;  sourceId?: Source["id"];}; type ActiveQueryCollections = {  sourceLists: Set<string>;  sources: Set<string>;  workspaceOauthClients: Set<string>;  inspections: Set<string>;  toolDetails: Set<string>;  discoveries: Set<string>;}; type ExecutorQueryContextValue = {  registry: Registry.Registry;  activeQueries: ActiveQueryCollections;  invalidateQueries: (target?: InvalidationTarget) => void;}; type MutationExecutionContext = {  workspaceId: Source["workspaceId"];  accountId: string;  registry: Registry.Registry;  invalidateQueries: (target?: InvalidationTarget) => void;}; type OptimisticMutationResult<T> =  | void  | (() => void)  | {      rollback?: () => void;      value?: T;    }; type MutationOptions<TInput, TOutput, TOptimistic = never> = {  optimisticUpdate?: (    context: MutationExecutionContext,    payload: TInput,  ) => OptimisticMutationResult<TOptimistic>;  onSuccess?: (    context: MutationExecutionContext,    payload: TInput,    data: TOutput,    optimisticValue: TOptimistic | undefined,  ) => void;}; type InternalNode<A> = {  setValue: (value: A) => void;  valueOption?: () => { _tag: "Some"; value: A } | { _tag: string };}; let apiBaseUrl =  typeof window !== "undefined" && typeof window.location?.origin === "string"    ? window.location.origin    : DEFAULT_EXECUTOR_API_BASE_URL; const ExecutorQueryContext = React.createContext<ExecutorQueryContextValue | null>(null); const encodeAtomKey = (parts: ReadonlyArray<AtomKeyPart>): string => JSON.stringify(parts); const decodeAtomKey = <T extends ReadonlyArray<AtomKeyPart>>(key: string): T => JSON.parse(key) as T; const encodeSourcesKey = (  enabled: boolean,  workspaceId: Source["workspaceId"],  accountId: string,): string => encodeAtomKey([enabled, workspaceId, accountId] satisfies SourcesKeyParts); const encodeSourceKey = (  enabled: boolean,  workspaceId: Source["workspaceId"],  accountId: string,  sourceId: Source["id"],): string => encodeAtomKey([enabled, workspaceId, accountId, sourceId] satisfies SourceKeyParts); const encodeToolDetailKey = (  enabled: boolean,  workspaceId: Source["workspaceId"],  accountId: string,  sourceId: Source["id"],  toolPath: string | null,): string =>  encodeAtomKey([enabled, workspaceId, accountId, sourceId, toolPath] satisfies SourceToolDetailKeyParts); const encodeDiscoveryKey = (  enabled: boolean,  workspaceId: Source["workspaceId"],  accountId: string,  sourceId: Source["id"],  query: string,  limit: number | null,): string =>  encodeAtomKey([enabled, workspaceId, accountId, sourceId, query, limit] satisfies SourceDiscoveryKeyParts); const encodeWorkspaceOauthClientsKey = (  enabled: boolean,  workspaceId: Source["workspaceId"],  accountId: string,  providerKey: string,): string =>  encodeAtomKey(    [enabled, workspaceId, accountId, providerKey] satisfies WorkspaceOauthClientsKeyParts,  ); const causeMessage = (cause: Cause.Cause<unknown>): Error =>  new Error(Cause.pretty(cause)); const toError = (cause: unknown): Error =>  cause instanceof Error ? cause : new Error(String(cause)); const shouldLogExecutorDevErrors = (): boolean => {  if (typeof window === "undefined") {    return false;  }   const hostname = window.location.hostname;  return hostname === "localhost" || hostname === "127.0.0.1";}; const describeExecutorDevError = (cause: unknown): Record<string, unknown> => {  if (Runtime.isFiberFailure(cause)) {    const inner = cause[Runtime.FiberFailureCauseId];    return {      name: cause.name,      message: cause.message,      cause: Cause.pretty(inner),    };  }   if (cause instanceof Error) {    return {      name: cause.name,      message: cause.message,      stack: cause.stack,    };  }   return {    message: String(cause),  };}; const logExecutorDevError = (label: string, details: Record<string, unknown>): void => {  if (!shouldLogExecutorDevErrors()) {    return;  }   console.error(`[executor react] ${label}`, details);}; const runControlPlane = async <A>(input: {  baseUrl?: string;  accountId?: string;  execute: (client: ControlPlaneClient) => Effect.Effect<A, unknown, never>;}): Promise<A> => {  const baseUrl = input.baseUrl ?? apiBaseUrl;  const accountId = input.accountId;   const exit = await Effect.runPromiseExit(    createControlPlaneClient({      baseUrl,      ...(accountId !== undefined ? { accountId } : {}),    }).pipe(Effect.flatMap(input.execute)),  );   if (Exit.isSuccess(exit)) {    return exit.value;  }   const error = Cause.squash(exit.cause);  logExecutorDevError("control-plane request failed", {    baseUrl,    accountId,    error: describeExecutorDevError(error),    cause: Cause.pretty(exit.cause),  });  throw error;}; const controlPlaneRequest = <A>(input: {  baseUrl?: string;  accountId?: string;  execute: (client: ControlPlaneClient) => Effect.Effect<A, unknown, never>;}): Effect.Effect<A, Error> =>  Effect.tryPromise({    try: () => runControlPlane(input),    catch: toError,  }); const localInstallationAtom = Atom.family((baseUrl: string) =>  Atom.make(    controlPlaneRequest({      baseUrl,      execute: (client) => client.local.installation({}),    }),  ).pipe(Atom.keepAlive),); const instanceConfigAtom = Atom.family((baseUrl: string) =>  Atom.make(    controlPlaneRequest({      baseUrl,      execute: (client) => client.local.config({}),    }),  ).pipe(Atom.keepAlive),); const secretsAtom = Atom.family((baseUrl: string) =>  Atom.make(    controlPlaneRequest({      baseUrl,      execute: (client) => client.local.listSecrets({}),    }),  ).pipe(Atom.keepAlive),); const sourcesAtom = Atom.family((key: string) => {  const [enabled, workspaceId, accountId] = decodeAtomKey<SourcesKeyParts>(key);   return Atom.make(    enabled      ? controlPlaneRequest({            accountId,            execute: (client) => client.sources.list({              path: {                workspaceId,              },            }),          })      : Effect.never,  ).pipe(Atom.keepAlive);}); const sourceAtom = Atom.family((key: string) => {  const [enabled, workspaceId, accountId, sourceId] = decodeAtomKey<SourceKeyParts>(key);   return Atom.make(    enabled      ? controlPlaneRequest({            accountId,            execute: (client) => client.sources.get({              path: {                workspaceId,                sourceId,              },            }),          })      : Effect.never,  ).pipe(Atom.keepAlive);}); const sourceInspectionAtom = Atom.family((key: string) => {  const [enabled, workspaceId, accountId, sourceId] = decodeAtomKey<SourceKeyParts>(key);   return Atom.make(    enabled      ? controlPlaneRequest({            accountId,            execute: (client) => client.sources.inspection({              path: {                workspaceId,                sourceId,              },            }),          })      : Effect.never,  ).pipe(Atom.keepAlive);}); const sourceInspectionToolAtom = Atom.family((key: string) => {  const [enabled, workspaceId, accountId, sourceId, toolPath] = decodeAtomKey<SourceToolDetailKeyParts>(key);   return Atom.make(    enabled && toolPath      ? controlPlaneRequest({            accountId,            execute: (client) => client.sources.inspectionTool({              path: {                workspaceId,                sourceId,                toolPath,              },            }),          })      : Effect.succeed<SourceInspectionToolDetail | null>(null),  ).pipe(Atom.keepAlive);}); const sourceDiscoveryAtom = Atom.family((key: string) => {  const [enabled, workspaceId, accountId, sourceId, query, limit] = decodeAtomKey<SourceDiscoveryKeyParts>(key);   return Atom.make(    !enabled      ? Effect.never      : query.trim().length === 0        ? Effect.succeed<SourceInspectionDiscoverResult>({            query: "",            queryTokens: [],            bestPath: null,            total: 0,            results: [],          })        : controlPlaneRequest({              accountId,              execute: (client) => client.sources.inspectionDiscover({                path: {                  workspaceId,                  sourceId,                },                payload: {                  query,                  ...(limit !== null ? { limit } : {}),                },              }),            }),  ).pipe(Atom.keepAlive);}); const workspaceOauthClientsAtom = Atom.family((key: string) => {  const [enabled, workspaceId, accountId, providerKey] = decodeAtomKey<WorkspaceOauthClientsKeyParts>(key);   return Atom.make(    enabled      ? controlPlaneRequest({          accountId,          execute: (client) => client.sources.listWorkspaceOauthClients({            path: {              workspaceId,            },            urlParams: {              providerKey,            },          }),        })      : Effect.never,  ).pipe(Atom.keepAlive);}); export type Loadable<T> =  | { status: "loading" }  | { status: "error"; error: Error }  | { status: "ready"; data: T }; type WorkspaceContext = {  installation: LocalInstallation;  workspaceId: Source["workspaceId"];  accountId: string;}; const toLoadable = <T>(result: Result.Result<T, Error>): Loadable<T> => {  if (Result.isSuccess(result)) {    return {      status: "ready",      data: result.value,    };  }   if (Result.isFailure(result)) {    return {      status: "error",      error: causeMessage(result.cause),    };  }   return {    status: "loading",  };}; const pendingLoadable = <T>(workspace: Loadable<WorkspaceContext>): Loadable<T> => {  if (workspace.status === "loading") {    return { status: "loading" };  }   if (workspace.status === "error") {    return { status: "error", error: workspace.error };  }   throw new Error("Expected workspace loadable to be pending or errored");}; const useLoadableAtom = <T>(atom: Atom.Atom<Result.Result<T, Error>>): Loadable<T> => {  const result = useAtomValue(atom);  return React.useMemo(() => toLoadable(result), [result]);}; const useWorkspaceContext = (): Loadable<WorkspaceContext> => {  const installation = useLoadableAtom(localInstallationAtom(apiBaseUrl));   return React.useMemo(() => {    if (installation.status !== "ready") {      return installation;    }     return {      status: "ready",      data: {        installation: installation.data,        workspaceId: installation.data.workspaceId,        accountId: installation.data.accountId,      },    } satisfies Loadable<WorkspaceContext>;  }, [installation]);}; const useWorkspaceRequestContext = () => {  const workspace = useWorkspaceContext();  const enabled = workspace.status === "ready";   const workspaceId = enabled    ? workspace.data.workspaceId    : PLACEHOLDER_WORKSPACE_ID;  const accountId = enabled    ? workspace.data.accountId    : PLACEHOLDER_ACCOUNT_ID;   return React.useMemo(    () => ({

Lines 1–500 of 1437.