Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OpenAI Preconfigured Connector Dashboard Link #169148

Merged
merged 8 commits into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React, { useCallback } from 'react';
import { EuiLink } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { useGetDashboard } from './use_get_dashboard';
import { useKibana } from '../../../../..';

interface Props {
connectorId: string;
connectorName: string;
}

export const DashboardLink: React.FC<Props> = ({ connectorId, connectorName }) => {
const { dashboardUrl } = useGetDashboard({ connectorId });
const {
services: {
application: { navigateToUrl },
},
} = useKibana();
const onClick = useCallback(
(e) => {
e.preventDefault();
if (dashboardUrl) {
navigateToUrl(dashboardUrl);
}
},
[dashboardUrl, navigateToUrl]
);
return dashboardUrl != null ? (
<EuiLink data-test-subj="link-gen-ai-token-dashboard" onClick={onClick}>
<FormattedMessage
id="xpack.triggersActionsUI.sections.editConnectorForm.genAi.dashboardLink"
values={{ connectorName }}
defaultMessage={'View Usage Dashboard for "{ connectorName }" Connector'}
/>
</EuiLink>
) : null;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { ActionTypeExecutorResult, RewriteResponseCase } from '@kbn/actions-plugin/common';
import { HttpSetup } from '@kbn/core-http-browser';
import { BASE_ACTION_API_PATH } from '@kbn/actions-plugin/common';

export type ConnectorExecutorResult<T> = ReturnType<
RewriteResponseCase<ActionTypeExecutorResult<T>>
>;

const rewriteResponseToCamelCase = <T>({
connector_id: actionId,
service_message: serviceMessage,
...data
}: ConnectorExecutorResult<T>): ActionTypeExecutorResult<T> => ({
...data,
actionId,
...(serviceMessage && { serviceMessage }),
});

export const getDashboardId = (spaceId: string): string => `generative-ai-token-usage-${spaceId}`;

export async function getDashboard({
http,
signal,
dashboardId,
connectorId,
}: {
http: HttpSetup;
signal: AbortSignal;
connectorId: string;
dashboardId: string;
}): Promise<ActionTypeExecutorResult<{ available: boolean }>> {
const res = await http.post<ConnectorExecutorResult<{ available: boolean }>>(
`${BASE_ACTION_API_PATH}/connector/${encodeURIComponent(connectorId)}/_execute`,
{
body: JSON.stringify({
params: { subAction: 'getDashboard', subActionParams: { dashboardId } },
}),
signal,
}
);
return rewriteResponseToCamelCase(res);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useState, useEffect, useRef, useCallback } from 'react';

import { i18n } from '@kbn/i18n';
import { useKibana } from '../../../../..';
import { getDashboard, getDashboardId } from './helpers';

interface Props {
connectorId: string;
}

export interface UseGetDashboard {
dashboardUrl: string | null;
isLoading: boolean;
}

export const useGetDashboard = ({ connectorId }: Props): UseGetDashboard => {
stephmilovic marked this conversation as resolved.
Show resolved Hide resolved
const {
dashboard,
http,
notifications: { toasts },
spaces,
} = useKibana().services;

const [spaceId, setSpaceId] = useState<string | null>(null);

useEffect(() => {
let didCancel = false;
if (spaces) {
spaces.getActiveSpace().then((space) => {
if (!didCancel) setSpaceId(space.id);
});
}

return () => {
didCancel = true;
};
}, [spaces]);

const [isLoading, setIsLoading] = useState(false);
const [dashboardUrl, setDashboardUrl] = useState<string | null>(null);
const [dashboardCheckComplete, setDashboardCheckComplete] = useState<boolean>(false);
const abortCtrl = useRef(new AbortController());

const setUrl = useCallback(
(dashboardId: string) => {
const url = dashboard?.locator?.getRedirectUrl({
query: {
language: 'kuery',
query: `kibana.saved_objects: { id : ${connectorId} }`,
},
dashboardId,
});
setDashboardUrl(url ?? null);
},
[connectorId, dashboard?.locator]
);

useEffect(() => {
let didCancel = false;
const fetchData = async (dashboardId: string) => {
abortCtrl.current = new AbortController();
if (!didCancel) setIsLoading(true);
try {
const res = await getDashboard({
http,
signal: abortCtrl.current.signal,
connectorId,
dashboardId,
});

if (!didCancel) {
setDashboardCheckComplete(true);
setIsLoading(false);
if (res.data?.available) {
setUrl(dashboardId);
}

if (res.status && res.status === 'error') {
toasts.addDanger({
title: i18n.translate('xpack.triggersActionsUI.genAi.dashbaord.error', {
defaultMessage: 'Error finding Generative AI Token Usage Dashboard.',
}),
text: `${res.serviceMessage ?? res.message}`,
});
}
}
} catch (error) {
if (!didCancel) {
setDashboardCheckComplete(true);
setIsLoading(false);
toasts.addDanger({
title: 'Error finding Generative AI Token Usage Dashboard.',
text: error.message,
});
}
}
};

if (spaceId != null && connectorId.length > 0 && !dashboardCheckComplete) {
abortCtrl.current.abort();
fetchData(getDashboardId(spaceId));
}

return () => {
didCancel = true;
setIsLoading(false);
abortCtrl.current.abort();
};
}, [connectorId, dashboardCheckComplete, dashboardUrl, http, setUrl, spaceId, toasts]);

return {
isLoading,
dashboardUrl,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,12 @@
*/

import React, { memo, ReactNode, useCallback, useEffect, useRef, useState } from 'react';
import {
EuiFlyout,
EuiText,
EuiFlyoutBody,
EuiLink,
EuiButton,
EuiConfirmModal,
} from '@elastic/eui';
import { EuiFlyout, EuiFlyoutBody, EuiButton, EuiConfirmModal } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { i18n } from '@kbn/i18n';
import { ActionTypeExecutorResult, isActionTypeExecutorResult } from '@kbn/actions-plugin/common';
import { Option, none, some } from 'fp-ts/lib/Option';
import { ReadOnlyConnectorMessage } from './read_only';
import {
ActionConnector,
ActionTypeModel,
Expand Down Expand Up @@ -51,24 +45,6 @@ const getConnectorWithoutSecrets = (
secrets: {},
});

const ReadOnlyConnectorMessage: React.FC<{ href: string }> = ({ href }) => {
return (
<>
<EuiText>
{i18n.translate('xpack.triggersActionsUI.sections.editConnectorForm.descriptionText', {
defaultMessage: 'This connector is readonly.',
})}
</EuiText>
<EuiLink href={href} target="_blank">
<FormattedMessage
id="xpack.triggersActionsUI.sections.editConnectorForm.preconfiguredHelpLabel"
defaultMessage="Learn more about preconfigured connectors."
/>
</EuiLink>
</>
);
};

const EditConnectorFlyoutComponent: React.FC<EditConnectorFlyoutProps> = ({
actionTypeRegistry,
connector,
Expand Down Expand Up @@ -240,7 +216,7 @@ const EditConnectorFlyoutComponent: React.FC<EditConnectorFlyoutProps> = ({
isMounted.current = false;
};
}, []);

console.log('connector', connector);
return (
<>
<EuiFlyout
Expand Down Expand Up @@ -299,7 +275,12 @@ const EditConnectorFlyoutComponent: React.FC<EditConnectorFlyoutProps> = ({
)}
</>
) : (
<ReadOnlyConnectorMessage href={docLinks.links.alerting.preconfiguredConnectors} />
<ReadOnlyConnectorMessage
href={docLinks.links.alerting.preconfiguredConnectors}
actionTypeId={connector.actionTypeId}
connectorId={connector.id}
connectorName={connector.name}
/>
)
) : (
<TestConnectorForm
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { EuiLink, EuiSpacer, EuiText } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import { DashboardLink } from './gen_ai/dashboard_link';

export const ReadOnlyConnectorMessage: React.FC<{
actionTypeId: string;
connectorId: string;
connectorName: string;
href: string;
}> = ({ actionTypeId, connectorId, connectorName, href }) => {
return (
<>
<EuiText>
{i18n.translate('xpack.triggersActionsUI.sections.editConnectorForm.descriptionText', {
defaultMessage: 'This connector is readonly.',
})}
</EuiText>
<EuiLink href={href} target="_blank">
<FormattedMessage
id="xpack.triggersActionsUI.sections.editConnectorForm.preconfiguredHelpLabel"
defaultMessage="Learn more about preconfigured connectors."
/>
</EuiLink>
{actionTypeId === '.gen-ai' && (
<>
<EuiSpacer size="m" />
<DashboardLink connectorId={connectorId} connectorName={connectorName} />
</>
)}
</>
);
};