Skip to content

The open alternative to Salesforce, designed for AI.

5.8 KB
Raw Blame
import { styled } from '@linaria/react';

import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
import { AI_INSTRUCTIONS_EDITOR_PROFILE } from '@/ai/constants/AiInstructionsEditorProfile';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useQuery } from '@apollo/client/react';
import { SettingsPath } from 'twenty-shared/types';
import {
  getSettingsPath,
  getValidTimeZoneOrUndefined,
  isDefined,
} from 'twenty-shared/utils';
import { Section } from 'twenty-ui/components/layout';
import { themeCssVariables } from 'twenty-ui/theme';
import { GetAiSystemPromptPreviewDocument } from '~/generated-metadata/graphql';
import { formatNumber } from '@/localization/utils/formatNumber';
import { useLingui } from '@lingui/react/macro';

const StyledSectionHeader = styled(Section.Header)`
  margin-block-end: 0;
`;

const StyledFormContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${themeCssVariables.spacing[4]};
`;

const StyledTitleContainer = styled.div`
  align-items: center;
  display: flex;
  gap: ${themeCssVariables.spacing[4]};
  margin-top: ${themeCssVariables.spacing[2]};
`;

export const SettingsAiPrompts = () => {
  const { t } = useLingui();
  const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);

  const { data: previewData, loading: previewLoading } = useQuery(
    GetAiSystemPromptPreviewDocument,
  );

  const preview = previewData?.getAiSystemPromptPreview;
  const sections = preview?.sections ?? [];

  const buildUserContextPreview = (): string => {
    if (!isDefined(currentWorkspaceMember)) {
      return '';
    }

    const parts = [
      `**${t`User`}:** ${currentWorkspaceMember.name.firstName} ${currentWorkspaceMember.name.lastName}`.trim(),
      `**${t`Locale`}:** ${currentWorkspaceMember.locale ?? 'en'}`,
    ];

    const validTimeZone = getValidTimeZoneOrUndefined(
      currentWorkspaceMember.timeZone,
    );

    if (isDefined(validTimeZone)) {
      parts.push(`**${t`Timezone`}:** ${validTimeZone}`);
    }

    const currentDate = new Intl.DateTimeFormat('en-US', {
      timeZone: validTimeZone,
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    }).format(new Date());

    parts.push(`**${t`Current date`}:** ${currentDate}`);

    return parts.join('\n\n');
  };

  const userContextPreview = buildUserContextPreview();

  const promptSections = sections.filter(
    (section) =>
      section.title !== 'Workspace Instructions' &&
      section.title !== 'User Context',
  );

  const totalTokenCount = isDefined(preview)
    ? t`~ ${formatNumber(preview.estimatedTokenCount, {
        abbreviate: true,
        decimals: 1,
      })} tokens`
    : '';

  return (
    <SettingsPageLayout
      links={[
        {
          children: t`Workspace`,
          href: getSettingsPath(SettingsPath.General),
        },
        { children: t`AI`, href: getSettingsPath(SettingsPath.AI) },
        { children: t`System Prompt` },
      ]}
    >
      <SettingsPageContainer>
        <Section.Root>
          <StyledTitleContainer>
            <StyledSectionHeader
              title={t`System Prompt`}
              description={[t`Read-only`, totalTokenCount]
                .filter(Boolean)
                .join(' ')}
              level={3}
              size="lg"
              descriptionLineClamp={2}
            />
          </StyledTitleContainer>
        </Section.Root>
        {promptSections.map((section) => {
          const sectionTokenCount = t`~ ${formatNumber(
            section.estimatedTokenCount,
            {
              abbreviate: true,
              decimals: 1,
            },
          )} tokens`;

          return (
            <Section.Root key={section.title}>
              <Section.Header
                title={section.title}
                description={[t`Read-only`, sectionTokenCount]
                  .filter(Boolean)
                  .join(' ')}
              />
              <StyledFormContainer>
                <FormAdvancedTextFieldInput
                  key={
                    previewLoading ? `loading-${section.title}` : section.title
                  }
                  label={section.title}
                  readonly={true}
                  defaultValue={section.content}
                  profile={AI_INSTRUCTIONS_EDITOR_PROFILE}
                  onChange={() => {}}
                  enableFullScreen={true}
                  fullScreenBreadcrumbs={[
                    {
                      children: t`System Prompt`,
                      href: '#',
                    },
                    {
                      children: section.title,
                    },
                  ]}
                  minHeight={120}
                />
              </StyledFormContainer>
            </Section.Root>
          );
        })}

        <Section.Root>
          <Section.Header
            title={t`User Context`}
            description={t`Information about the current user (auto-generated and included in each request)`}
          />
          <StyledFormContainer>
            <FormAdvancedTextFieldInput
              label={t`User Information`}
              readonly={true}
              defaultValue={userContextPreview}
              profile={AI_INSTRUCTIONS_EDITOR_PROFILE}
              onChange={() => {}}
              enableFullScreen={false}
              minHeight={80}
            />
          </StyledFormContainer>
        </Section.Root>
      </SettingsPageContainer>
    </SettingsPageLayout>
  );
};