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

[Observability AI Assistant] Use up / down arrows to select up to 5 previously used prompts #179696

Merged
merged 19 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"licensing",
"ml"
],
"requiredBundles": [ "kibanaReact" ],
"requiredBundles": ["kibanaReact", "kibanaUtils"],
"optionalPlugins": ["cloud"],
"extraPublicDirs": []
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { FunctionListPopover } from '../chat/function_list_popover';
import { PromptEditorFunction } from './prompt_editor_function';
import { PromptEditorNaturalLanguage } from './prompt_editor_natural_language';
import { useLastUsedPrompts } from '../../hooks/use_last_used_prompts';

export interface PromptEditorProps {
disabled: boolean;
Expand Down Expand Up @@ -49,6 +50,8 @@ export function PromptEditor({

const [hasFocus, setHasFocus] = useState(false);

const { previousPrompts, addLastUsed: addPrompt } = useLastUsedPrompts();
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved

const initialInnerMessage = initialRole
? {
role: initialRole,
Expand Down Expand Up @@ -102,6 +105,10 @@ export function PromptEditor({
return;
}

if (innerMessage.content) {
addPrompt(innerMessage.content);
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved
}

const oldMessage = innerMessage;

try {
Expand All @@ -123,7 +130,7 @@ export function PromptEditor({
setInnerMessage(oldMessage);
setMode(oldMessage.function_call?.name ? 'function' : 'prompt');
}
}, [innerMessage, loading, onSendTelemetry, onSubmit]);
}, [addPrompt, innerMessage, loading, onSendTelemetry, onSubmit]);
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved

// Submit on Enter
useEffect(() => {
Expand Down Expand Up @@ -174,6 +181,7 @@ export function PromptEditor({
<PromptEditorNaturalLanguage
disabled={disabled}
prompt={innerMessage?.content}
previousPrompts={previousPrompts}
onChange={handleChangeMessageInner}
onChangeHeight={onChangeHeight}
onFocus={() => setHasFocus(true)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,51 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React, { useCallback, useEffect, useRef } from 'react';
import { EuiTextArea } from '@elastic/eui';
import React, { KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
import { css } from '@emotion/css';
import { EuiInputPopover, EuiSelectable, EuiTextArea } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { MessageRole } from '@kbn/observability-ai-assistant-plugin/public';
import type { Message } from '@kbn/observability-ai-assistant-plugin/common';

interface Props {
disabled: boolean;
prompt: string | undefined;
previousPrompts: string[];
onChange: (message: Message['message']) => void;
onChangeHeight: (height: number) => void;
onFocus: () => void;
onBlur: () => void;
}

const inputPopoverClassName = css`
max-inline-size: 100%;
`;

const textAreaClassName = css`
max-height: 200px;
width: 100%;
`;

const selectableClassName = css`
.euiSelectableListItem__icon {
display: none;
}
`;

export function PromptEditorNaturalLanguage({
disabled,
prompt,
previousPrompts,
onChange,
onChangeHeight,
onFocus,
onBlur,
}: Props) {
const textAreaRef = useRef<HTMLTextAreaElement>(null);

const [isSelectablePopoverOpen, setSelectablePopoverOpen] = useState(false);

const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
handleResizeTextArea();

Expand All @@ -50,6 +70,28 @@ export function PromptEditorNaturalLanguage({
}
}, [onChangeHeight]);

const handleKeydown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
// only trigger select when no prompt is available
if (!prompt && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
e.preventDefault();
setSelectablePopoverOpen(true);
}
};

const handleSelectOption = (_: any, __: any, selectedOption: { label: string }) => {
onChange({
role: MessageRole.User,
content: selectedOption.label,
});
setSelectablePopoverOpen(false);
onFocus();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't onFocus be called when the EuiInputPopover element moves focus back to the text area? I'm assuming it does do that, and if not, should we do that ourselves? Depending on what we do on focus in the consumer of this component, maybe that doesn't matter much.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handleClosePopover on line 89 also calls onFocus. I removed the onFocus here and the focus is correctly passed back to the text area.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should that also apply to setSelectablePopoverOpen?

};

const handleClosePopover = () => {
setSelectablePopoverOpen(false);
onFocus();
};

useEffect(() => {
const textarea = textAreaRef.current;

Expand All @@ -69,21 +111,51 @@ export function PromptEditorNaturalLanguage({
}, [handleResizeTextArea, prompt]);

return (
<EuiTextArea
data-test-subj="observabilityAiAssistantChatPromptEditorTextArea"
css={{ maxHeight: 200 }}
disabled={disabled}
fullWidth
inputRef={textAreaRef}
placeholder={i18n.translate('xpack.observabilityAiAssistant.prompt.placeholder', {
defaultMessage: 'Send a message to the Assistant',
})}
resize="vertical"
rows={1}
value={prompt || ''}
onChange={handleChange}
onFocus={onFocus}
onBlur={onBlur}
/>
<EuiInputPopover
display="flex"
isOpen={isSelectablePopoverOpen}
closePopover={handleClosePopover}
className={inputPopoverClassName}
input={
<EuiTextArea
className={textAreaClassName}
data-test-subj="observabilityAiAssistantChatPromptEditorTextArea"
disabled={disabled}
fullWidth
inputRef={textAreaRef}
placeholder={i18n.translate('xpack.observabilityAiAssistant.prompt.placeholder', {
defaultMessage: 'Send a message to the Assistant',
})}
resize="vertical"
rows={1}
value={prompt || ''}
onChange={handleChange}
onFocus={onFocus}
onKeyDown={handleKeydown}
onBlur={onBlur}
/>
}
panelMinWidth={300}
anchorPosition="downLeft"
>
<EuiSelectable
aria-label={i18n.translate(
'xpack.observabilityAiAssistant.promptEditorNaturalLanguage.euiSelectable.selectAnOptionLabel',
{ defaultMessage: 'Select an option' }
)}
className={selectableClassName}
options={previousPrompts.map((label) => ({ label }))}
searchable
singleSelection
onChange={handleSelectOption}
>
{(list, search) => (
<>
{search}
{list}
</>
)}
</EuiSelectable>
</EuiInputPopover>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { CoreStart } from '@kbn/core/public';
import { Storage } from '@kbn/kibana-utils-plugin/public';
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved
import type { ObservabilityAIAssistantAppPluginStartDependencies } from '../types';

export type StartServices<TAdditionalServices> = CoreStart & {
plugins: { start: ObservabilityAIAssistantAppPluginStartDependencies };
storage: Storage;
} & TAdditionalServices & {};

const useTypedKibana = <AdditionalServices extends object = {}>() =>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* 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 { uniq } from 'lodash';
import { useKibana } from './use_kibana';

const AI_ASSISTANT_LAST_USED_PROMPT_STORAGE = 'ai-assistant-last-used-prompts';

export function useLastUsedPrompts() {
const { storage } = useKibana().services;

const previousPrompts = (storage.get(AI_ASSISTANT_LAST_USED_PROMPT_STORAGE) as string[]) ?? [];
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved

return {
previousPrompts,
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved
addLastUsed: (prompt: string) => {
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved
storage.set(
AI_ASSISTANT_LAST_USED_PROMPT_STORAGE,
uniq([prompt, ...previousPrompts]).slice(0, 5)
);
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { EuiErrorBoundary } from '@elastic/eui';
import type { CoreStart, CoreTheme } from '@kbn/core/public';
import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public';
import { Storage } from '@kbn/kibana-utils-plugin/public';
import { KibanaThemeProvider } from '@kbn/react-kibana-context-theme';
import { RedirectAppLinks } from '@kbn/shared-ux-link-redirect-app';
import React, { useMemo } from 'react';
Expand All @@ -15,6 +16,8 @@ import { ObservabilityAIAssistantAppServiceProvider } from '../context/observabi
import type { ObservabilityAIAssistantAppService } from '../service/create_app_service';
import type { ObservabilityAIAssistantAppPluginStartDependencies } from '../types';

const storage = new Storage(localStorage);
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved

export function SharedProviders({
children,
coreStart,
Expand Down Expand Up @@ -42,6 +45,7 @@ export function SharedProviders({
plugins: {
start: pluginsStart,
},
storage,
CoenWarmer marked this conversation as resolved.
Show resolved Hide resolved
}}
>
<RedirectAppLinks coreStart={coreStart}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@
"@kbn/shared-ux-link-redirect-app",
"@kbn/shared-ux-utility",
"@kbn/data-plugin",
"@kbn/deeplinks-observability"
"@kbn/deeplinks-observability",
"@kbn/kibana-utils-plugin"
],
"exclude": ["target/**/*"]
}