Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

7.7 KB
Raw Blame
import { Button, ExternalLink, Spinner, Text } from '@invoke-ai/ui-library';
import { logger } from 'app/logging/logger';
import type { AppDispatch, AppGetState } from 'app/store/store';
import { getIsAdmin } from 'features/auth/hooks/useIsAdmin';
import { selectCurrentUser } from 'features/auth/store/authSlice';
import { getPrefixedId } from 'features/controlLayers/konva/util';
import { discordLink, githubIssuesLink } from 'features/system/store/constants';
import { toast, toastApi } from 'features/toast/toast';
import { navigationApi } from 'features/ui/layouts/navigation-api';
import { t } from 'i18next';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { api } from 'services/api';
import { authApi } from 'services/api/endpoints/auth';
import { modelsApi, useGetHFTokenStatusQuery } from 'services/api/endpoints/models';
import type { S } from 'services/api/types';
import { assert } from 'tsafe';

const log = logger('events');
const selectModelInstalls = modelsApi.endpoints.listModelInstalls.select();

const UNAUTHORIZED_TOAST_ID = getPrefixedId('unauthorized-toast');
const FORBIDDEN_TOAST_ID = getPrefixedId('forbidden-toast');

const getHFTokenStatusToastTitle = (token_status: S['HFTokenStatus']) => {
  switch (token_status) {
    case 'invalid':
      return t('modelManager.hfTokenInvalid');
    case 'unknown':
      return t('modelManager.hfTokenUnableToVerify');
    case 'valid':
      return 'HF Token is valid, but does not have access to model';
  }
};

const getHFTokenStatus = async (dispatch: AppDispatch): Promise<S['HFTokenStatus'] | null> => {
  const req = dispatch(modelsApi.endpoints.getHFTokenStatus.initiate(undefined, { subscribe: false }));
  try {
    return await req.unwrap();
  } catch {
    return null;
  }
};

const getIsAdminFromState = (getState: AppGetState): boolean => {
  const setupStatus = authApi.endpoints.getSetupStatus.select()(getState()).data;
  const user = selectCurrentUser(getState());
  return getIsAdmin(setupStatus, user);
};

/**
 * Handles model install error events by logging the error, displaying appropriate toast notifications.
 */
export const buildOnModelInstallError = (getState: AppGetState, dispatch: AppDispatch) => {
  return async (data: S['ModelInstallErrorEvent']) => {
    log.error({ data }, 'Model install error');

    const installs = selectModelInstalls(getState()).data;

    if (data.error === 'Unauthorized') {
      if (data.source.type === 'hf') {
        // Admin-only: model_install_error is broadcast to every connected client, but /hf_login is an
        // admin-only route and the toast concerns the server-wide HF token that only an admin can fix.
        // Without this guard every non-admin session fires a doomed request and logs a spurious 403.
        if (getIsAdminFromState(getState)) {
          const hfTokenStatus = await getHFTokenStatus(dispatch);
          if (hfTokenStatus === null) {
            // This means there was a problem getting the token status, should never happen...
            log.error('Error getting HF token status');
          } else {
            const title = getHFTokenStatusToastTitle(hfTokenStatus);
            toast({
              id: UNAUTHORIZED_TOAST_ID,
              title,
              description: <HFUnauthorizedToastDescription />,
              status: 'error',
              isClosable: true,
              duration: null,
            });
          }
        }
      } else if (data.source.type === 'url') {
        toast({
          id: UNAUTHORIZED_TOAST_ID,
          title: 'Model requires authorization',
          description: (
            <Text fontSize="md">
              {t('modelManager.urlUnauthorizedErrorMessage')}
              <ExternalLink
                label={t('modelManager.urlUnauthorizedErrorMessage2')}
                href="https://invoke.ai/configuration/invokeai-yaml/#model-marketplace-api-keys"
              />
            </Text>
          ),
          status: 'error',
          isClosable: true,
          duration: null,
        });
      } else {
        // data.source.type === 'path' - should never happen
        assert(false, 'Unexpected unauthorized error for path source');
      }
    } else if (data.error === 'Forbidden') {
      if (data.source.type === 'hf') {
        toast({
          id: FORBIDDEN_TOAST_ID,
          title: t('modelManager.hfForbidden'),
          description: (
            <Text fontSize="md">
              {t('modelManager.hfForbiddenErrorMessage')}
              <ExternalLink label={data.source.repo_id} href={`https://huggingface.co/${data.source.repo_id}`} />
            </Text>
          ),
          status: 'error',
          isClosable: true,
          duration: null,
        });
      } else if (data.source.type === 'url') {
        toast({
          id: FORBIDDEN_TOAST_ID,
          title: t('modelManager.urlForbidden'),
          description: t('modelManager.urlForbiddenErrorMessage'),
          status: 'error',
          isClosable: true,
          duration: null,
        });
      } else {
        // data.source.type === 'path' - should never happen
        assert(false, 'Unexpected forbidden error for path source');
      }
    } else {
      // Some other type of error, who knows!
      toast({
        title: 'Model install error',
        description: data.error,
        status: 'error',
        isClosable: true,
        duration: null,
      });
    }

    const install = installs?.find((install) => install.id === data.id);

    if (!install) {
      dispatch(api.util.invalidateTags([{ type: 'ModelInstalls' }]));
    } else {
      dispatch(
        modelsApi.util.updateQueryData('listModelInstalls', undefined, (draft) => {
          const modelImport = draft.find((m) => m.id === data.id);
          if (modelImport) {
            modelImport.status = 'error';
            modelImport.error_reason = data.error_type;
            modelImport.error = data.error;
          }
          return draft;
        })
      );
    }
  };
};

const HFUnauthorizedToastDescription = () => {
  const { data } = useGetHFTokenStatusQuery();

  const { t } = useTranslation();

  const onClick = useCallback(() => {
    navigationApi.switchToTab('models');
    toastApi.close(UNAUTHORIZED_TOAST_ID);
  }, []);

  if (!data) {
    return <Spinner />;
  }

  if (data === 'invalid') {
    return (
      <Text fontSize="md">
        {t('modelManager.hfTokenInvalidErrorMessage')} {t('modelManager.hfTokenRequired')}{' '}
        {t('modelManager.hfTokenInvalidErrorMessage2')}
        <Button onClick={onClick} variant="link" color="base.50" flexGrow={0}>
          {t('modelManager.modelManager')}.
        </Button>
      </Text>
    );
  }

  if (data === 'unknown') {
    return (
      <Text fontSize="md">
        {t('modelManager.hfTokenUnableToVerifyErrorMessage')}{' '}
        <Button onClick={onClick} variant="link" color="base.50" flexGrow={0}>
          {t('modelManager.modelManager')}.
        </Button>
      </Text>
    );
  }

  // data === 'valid' - user may have a token but not authorized for model?
  return (
    <Text fontSize="md">
      {t('modelManager.hfTokenForbiddenErrorMessage')}{' '}
      <Button onClick={onClick} variant="link" color="base.50" flexGrow={0}>
        {t('modelManager.modelManager')}.
      </Button>
    </Text>
  );
};

export const DiscordLink = () => {
  const { t: tFunc } = useTranslation();
  return (
    <ExternalLink
      fontWeight="semibold"
      href={discordLink}
      display="inline-flex"
      label={tFunc('supportVideos.discord')}
    />
  );
};
export const GitHubIssuesLink = () => {
  const { t: tFunc } = useTranslation();
  return (
    <ExternalLink
      fontWeight="semibold"
      href={githubIssuesLink}
      display="inline-flex"
      label={tFunc('supportVideos.github')}
    />
  );
};