Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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,125 @@
/*
* 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 { act, fireEvent, render, screen } from '@testing-library/react';
import { BehaviorSubject } from 'rxjs';

import { useKibana } from '@kbn/kibana-react-plugin/public';
import { AIChatExperience } from '@kbn/ai-assistant-common';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';

import { useUiPrivileges } from '../../application/hooks/use_ui_privileges';
import { OnechatNavControl } from './onechat_nav_control';

jest.mock('@kbn/kibana-react-plugin/public', () => ({
useKibana: jest.fn(),
}));

jest.mock('../../application/hooks/use_ui_privileges', () => ({
useUiPrivileges: jest.fn(),
}));

const mockUseKibana = useKibana as jest.MockedFunction<typeof useKibana>;
const mockUseUiPrivileges = useUiPrivileges as jest.MockedFunction<typeof useUiPrivileges>;

describe('OnechatNavControl', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('toggles the flyout when the nav button is clicked', () => {
const toggleConversationFlyout = jest.fn();
const openChat$ = new BehaviorSubject(AIChatExperience.Classic);

mockUseUiPrivileges.mockReturnValue({ show: true } as any);
mockUseKibana.mockReturnValue({
services: {
onechat: {
toggleConversationFlyout,
openConversationFlyout: jest.fn(),
},
aiAssistantManagementSelection: {
openChat$,
completeOpenChat: jest.fn(),
},
},
} as any);

render(
<IntlProvider locale="en">
<OnechatNavControl />
</IntlProvider>
);

fireEvent.click(screen.getByRole('button', { name: 'Open Agent Builder' }));
expect(toggleConversationFlyout).toHaveBeenCalledTimes(1);
});

it('toggles the flyout on Cmd/Ctrl+; keyboard shortcut', () => {
const toggleConversationFlyout = jest.fn();
const openChat$ = new BehaviorSubject(AIChatExperience.Classic);

mockUseUiPrivileges.mockReturnValue({ show: true } as any);
mockUseKibana.mockReturnValue({
services: {
onechat: {
toggleConversationFlyout,
openConversationFlyout: jest.fn(),
},
aiAssistantManagementSelection: {
openChat$,
completeOpenChat: jest.fn(),
},
},
} as any);

render(
<IntlProvider locale="en">
<OnechatNavControl />
</IntlProvider>
);

// Provide both ctrlKey and metaKey so the assertion is platform-independent
fireEvent.keyDown(window, { key: ';', code: 'Semicolon', ctrlKey: true, metaKey: true });
expect(toggleConversationFlyout).toHaveBeenCalledTimes(1);
});

it('opens the flyout when openChat$ emits Agent', () => {
const toggleConversationFlyout = jest.fn();
const openConversationFlyout = jest.fn();
const completeOpenChat = jest.fn();
const openChat$ = new BehaviorSubject(AIChatExperience.Classic);

mockUseUiPrivileges.mockReturnValue({ show: true } as any);
mockUseKibana.mockReturnValue({
services: {
onechat: {
toggleConversationFlyout,
openConversationFlyout,
},
aiAssistantManagementSelection: {
openChat$,
completeOpenChat,
},
},
} as any);

render(
<IntlProvider locale="en">
<OnechatNavControl />
</IntlProvider>
);

act(() => {
openChat$.next(AIChatExperience.Agent);
});

expect(openConversationFlyout).toHaveBeenCalledTimes(1);
expect(completeOpenChat).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React, { useEffect } from 'react';
import { EuiButton, EuiToolTip } from '@elastic/eui';
import React, { useCallback, useEffect } from 'react';
import { EuiButton, EuiToolTip, EuiWindowEvent } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { FormattedMessage } from '@kbn/i18n-react';
Expand All @@ -14,6 +14,9 @@ import type { OnechatPluginStart, OnechatStartDependencies } from '../../types';
import { RobotIcon } from '../../application/components/common/icons/robot';
import { useUiPrivileges } from '../../application/hooks/use_ui_privileges';

const isMac = navigator.platform.toLowerCase().indexOf('mac') >= 0;
const isSemicolon = (event: KeyboardEvent) => event.code === 'Semicolon' || event.key === ';';

interface OnechatNavControlServices {
onechat: OnechatPluginStart;
aiAssistantManagementSelection: OnechatStartDependencies['aiAssistantManagementSelection'];
Expand All @@ -26,6 +29,10 @@ export function OnechatNavControl() {

const { show: hasShowPrivilege } = useUiPrivileges();

const toggleFlyout = useCallback(() => {
onechat.toggleConversationFlyout();
}, [onechat]);

useEffect(() => {
if (!hasShowPrivilege) {
return;
Expand All @@ -43,30 +50,56 @@ export function OnechatNavControl() {
};
}, [hasShowPrivilege, onechat, aiAssistantManagementSelection]);

const onKeyDown = useCallback(
(event: KeyboardEvent) => {
if (isSemicolon(event) && (isMac ? event.metaKey : event.ctrlKey)) {
event.preventDefault();
toggleFlyout();
}
},
[toggleFlyout]
);

if (!hasShowPrivilege) {
return null;
}

const tooltipContent = (
<div style={{ textAlign: 'center' }}>
<span>{buttonLabel}</span>
<br />
<span>{shortcutLabel}</span>
</div>
);

return (
<EuiToolTip content={buttonLabel}>
<EuiButton
aria-label={buttonLabel}
data-test-subj="OnechatNavControlButton"
onClick={() => {
onechat.openConversationFlyout();
}}
color="primary"
size="s"
fullWidth={false}
minWidth={0}
>
<RobotIcon size="m" />
<FormattedMessage id="xpack.onechat.navControl.linkLabel" defaultMessage="AI Agent" />
</EuiButton>
</EuiToolTip>
<>
<EuiWindowEvent event="keydown" handler={onKeyDown} />
<EuiToolTip content={tooltipContent}>
<EuiButton
aria-label={buttonLabel}
data-test-subj="OnechatNavControlButton"
onClick={() => {
toggleFlyout();
}}
color="primary"
size="s"
fullWidth={false}
minWidth={0}
>
<RobotIcon size="m" />
<FormattedMessage id="xpack.onechat.navControl.linkLabel" defaultMessage="AI Agent" />
</EuiButton>
</EuiToolTip>
</>
);
}

const buttonLabel = i18n.translate('xpack.onechat.navControl.openTheOnechatFlyoutLabel', {
defaultMessage: 'Open Agent Builder',
});

const shortcutLabel = i18n.translate('xpack.onechat.navControl.keyboardShortcutTooltip', {
values: { keyboardShortcut: isMac ? '⌘ ;' : 'Ctrl ;' },
defaultMessage: '(Keyboard shortcut {keyboardShortcut})',
});
1 change: 1 addition & 0 deletions x-pack/platform/plugins/shared/onechat/public/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const createStartContractMock = (): jest.Mocked<OnechatPluginStart> => {
tools: {} as any,
setConversationFlyoutActiveConfig: jest.fn(),
clearConversationFlyoutActiveConfig: jest.fn(),
toggleConversationFlyout: jest.fn(),
openConversationFlyout: jest
.fn()
.mockImplementation((options: OpenConversationFlyoutOptions) => {
Expand Down
61 changes: 39 additions & 22 deletions x-pack/platform/plugins/shared/onechat/public/plugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,33 @@ export class OnechatPlugin

const hasAgentBuilder = core.application.capabilities.agentBuilder?.show === true;

const openFlyoutInternal = (options?: OpenConversationFlyoutOptions) => {
const config = options ?? this.conversationFlyoutActiveConfig;

// If a flyout is already open, update its props instead of creating a new one
if (this.activeFlyoutRef && this.updateFlyoutPropsCallback) {
this.updateFlyoutPropsCallback(config);
return { flyoutRef: this.activeFlyoutRef };
}

// Create new flyout and set up prop updates
const { flyoutRef } = openConversationFlyout(config, {
coreStart: core,
services: internalServices,
onPropsUpdate: (callback) => {
this.updateFlyoutPropsCallback = callback;
},
onClose: () => {
this.activeFlyoutRef = null;
this.updateFlyoutPropsCallback = null;
},
});

this.activeFlyoutRef = flyoutRef;

return { flyoutRef };
};

const onechatService: OnechatPluginStart = {
agents: createPublicAgentsContract({ agentService }),
attachments: createPublicAttachmentContract({ attachmentsService }),
Expand All @@ -146,30 +173,20 @@ export class OnechatPlugin
this.conversationFlyoutActiveConfig = {};
},
openConversationFlyout: (options?: OpenConversationFlyoutOptions) => {
const config = options ?? this.conversationFlyoutActiveConfig;

// If a flyout is already open, update its props instead of creating a new one
if (this.activeFlyoutRef && this.updateFlyoutPropsCallback) {
this.updateFlyoutPropsCallback(config);
return { flyoutRef: this.activeFlyoutRef };
return openFlyoutInternal(options);
},
toggleConversationFlyout: (options?: OpenConversationFlyoutOptions) => {
if (this.activeFlyoutRef) {
const flyoutRef = this.activeFlyoutRef;
// Be defensive: clear local references immediately in case the underlying overlay doesn't
// synchronously invoke our onClose callback.
this.activeFlyoutRef = null;
this.updateFlyoutPropsCallback = null;
flyoutRef.close();
return;
}

// Create new flyout and set up prop updates
const { flyoutRef } = openConversationFlyout(config, {
coreStart: core,
services: internalServices,
onPropsUpdate: (callback) => {
this.updateFlyoutPropsCallback = callback;
},
onClose: () => {
this.activeFlyoutRef = null;
this.updateFlyoutPropsCallback = null;
},
});

this.activeFlyoutRef = flyoutRef;

return { flyoutRef };
openFlyoutInternal(options);
},
};

Expand Down
6 changes: 6 additions & 0 deletions x-pack/platform/plugins/shared/onechat/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ export interface OnechatPluginStart {
* ```
*/
openConversationFlyout: (options?: OpenConversationFlyoutOptions) => OpenConversationFlyoutReturn;
/**
* Toggles the conversation flyout.
*
* If the flyout is open, it will be closed. Otherwise, it will be opened.
*/
toggleConversationFlyout: (options?: OpenConversationFlyoutOptions) => void;
setConversationFlyoutActiveConfig: (config: EmbeddableConversationProps) => void;
clearConversationFlyoutActiveConfig: () => void;
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const createWrapper = (onechatService?: OnechatPluginStart) => {
const mockOnechatService: OnechatPluginStart = {
openConversationFlyout:
mockOpenConversationFlyout as OnechatPluginStart['openConversationFlyout'],
toggleConversationFlyout: jest.fn(),
agents: {} as OnechatPluginStart['agents'],
tools: {} as OnechatPluginStart['tools'],
attachments: {} as OnechatPluginStart['attachments'],
Expand Down