diff --git a/package-lock.json b/package-lock.json
index 540a1d89..b9a0a3c3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -25,6 +25,7 @@
"fast-deep-equal": "^3.1.3",
"lodash.clonedeep": "^4.5.0",
"lodash.difference": "^4.5.0",
+ "marked": "^15.0.6",
"mui-tel-input": "^8.0.1",
"react": "^18.3.1",
"react-datepicker": "^7.6.0",
@@ -18200,6 +18201,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/marked": {
+ "version": "15.0.12",
+ "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz",
+ "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==",
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
diff --git a/package.json b/package.json
index fe2cf45a..323e601c 100644
--- a/package.json
+++ b/package.json
@@ -67,6 +67,7 @@
"fast-deep-equal": "^3.1.3",
"lodash.clonedeep": "^4.5.0",
"lodash.difference": "^4.5.0",
+ "marked": "^15.0.6",
"mui-tel-input": "^8.0.1",
"react": "^18.3.1",
"react-datepicker": "^7.6.0",
diff --git a/packages/react-sdk-components/package.json b/packages/react-sdk-components/package.json
index 350d8f9a..b584abf4 100644
--- a/packages/react-sdk-components/package.json
+++ b/packages/react-sdk-components/package.json
@@ -28,6 +28,7 @@
"fast-deep-equal": "^3.1.3",
"lodash.clonedeep": "^4.5.0",
"lodash.difference": "^4.5.0",
+ "marked": "^15.0.6",
"mui-tel-input": "^8.0.1",
"react-datepicker": "^7.6.0",
"react-number-format": "^5.4.4",
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/AgentRichTextViewer.tsx b/packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/AgentRichTextViewer.tsx
new file mode 100644
index 00000000..1d024092
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/AgentRichTextViewer.tsx
@@ -0,0 +1,211 @@
+import { Fragment, memo, useMemo, type ReactNode } from 'react';
+import { marked, type Token, type Tokens } from 'marked';
+import { Divider, Link, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography } from '@mui/material';
+import makeStyles from '@mui/styles/makeStyles';
+
+import type { MarkdownMap } from '../GenAICoachContent/GenAICoach.types';
+
+// AgentRichTextViewer is one of the few components that does NOT have getPConnect.
+// So, no need to extend PConnProps
+interface AgentRichTextViewerProps {
+ // If any, enter additional props that only exist on this component
+ content: string;
+ markdownMap?: MarkdownMap;
+}
+
+const SAFE_LINK_PROTOCOLS = ['http:', 'https:', 'mailto:', 'tel:'];
+
+const isSafeHref = (href: string): boolean => {
+ try {
+ return SAFE_LINK_PROTOCOLS.includes(new URL(href, window.location.origin).protocol);
+ } catch {
+ return false;
+ }
+};
+
+const useStyles = makeStyles(theme => ({
+ root: {
+ overflowWrap: 'anywhere',
+ '& > :first-child': { marginTop: 0 },
+ '& > :last-child': { marginBottom: 0 }
+ },
+ paragraph: {
+ margin: theme.spacing(0, 0, 1),
+ whiteSpace: 'pre-line'
+ },
+ heading: {
+ margin: theme.spacing(1.5, 0, 1),
+ fontWeight: 600
+ },
+ list: {
+ margin: theme.spacing(0, 0, 1),
+ paddingInlineStart: theme.spacing(3)
+ },
+ blockquote: {
+ margin: theme.spacing(0, 0, 1),
+ paddingInlineStart: theme.spacing(1.5),
+ borderInlineStart: `0.25rem solid ${theme.palette.divider}`,
+ color: theme.palette.text.secondary
+ },
+ codeBlock: {
+ margin: theme.spacing(1, 0),
+ padding: theme.spacing(1.5),
+ overflowX: 'auto',
+ backgroundColor: theme.palette.action.hover,
+ borderRadius: theme.shape.borderRadius,
+ fontFamily: 'monospace',
+ fontSize: '0.875rem',
+ whiteSpace: 'pre'
+ },
+ inlineCode: {
+ padding: '0.0625rem 0.25rem',
+ backgroundColor: theme.palette.action.hover,
+ borderRadius: theme.shape.borderRadius,
+ fontFamily: 'monospace',
+ fontSize: '0.875em'
+ },
+ table: {
+ margin: theme.spacing(1, 0),
+ maxWidth: '100%',
+ overflowX: 'auto'
+ }
+}));
+
+/**
+ * Renders the markdown of messages with MUI elements.
+ * The markdown is parsed with `marked.lexer()` and the tokens are rendered as React elements, so no HTML
+ * string is ever injected; raw HTML in the markdown is shown as plain text.
+ * `markdownMap` maps a token type to a function returning the component that renders that token instead.
+ * Memoised so completed messages are not re-rendered while another message streams.
+ */
+function AgentRichTextViewer(props: AgentRichTextViewerProps) {
+ const { content, markdownMap } = props;
+ const classes = useStyles();
+
+ const tokens = useMemo(() => marked.lexer(content ?? ''), [content]);
+
+ const renderTokens = (tokenList?: Token[]): ReactNode => tokenList?.map((token, index) => {renderToken(token)});
+
+ const renderToken = (token: Token): ReactNode => {
+ const Override = markdownMap?.[token.type]?.(token);
+ if (Override) {
+ // The override also gets the token's rendered inline content, such as the formatted text of a link.
+ const childTokens = 'tokens' in token && Array.isArray(token.tokens) && token.tokens.length > 0 ? token.tokens : undefined;
+ return {childTokens && renderTokens(childTokens)};
+ }
+
+ switch (token.type) {
+ case 'space':
+ case 'def':
+ return null;
+ case 'paragraph':
+ return (
+
+ {renderTokens((token as Tokens.Paragraph).tokens)}
+
+ );
+ case 'heading': {
+ // Headings are capped so agent content never outranks the panel's own heading.
+ const level = Math.min((token as Tokens.Heading).depth + 2, 6);
+ return (
+
+ {renderTokens((token as Tokens.Heading).tokens)}
+
+ );
+ }
+ case 'text': {
+ const textToken = token as Tokens.Text;
+ return textToken.tokens ? renderTokens(textToken.tokens) : textToken.text;
+ }
+ case 'escape':
+ case 'html':
+ return (token as Tokens.Escape | Tokens.HTML).text;
+ case 'strong':
+ return {renderTokens((token as Tokens.Strong).tokens)};
+ case 'em':
+ return {renderTokens((token as Tokens.Em).tokens)};
+ case 'del':
+ return {renderTokens((token as Tokens.Del).tokens)};
+ case 'codespan':
+ return {(token as Tokens.Codespan).text};
+ case 'br':
+ return
;
+ case 'link': {
+ const { href, text, tokens: linkTokens } = token as Tokens.Link;
+ // Deviation from Constellation: the link text keeps its formatting (as in `[**T-1001**](…)`), where Constellation
+ // shows the link's raw markdown.
+ const linkContent = linkTokens?.length ? renderTokens(linkTokens) : text;
+ if (!isSafeHref(href)) return linkContent;
+ return (
+
+ {linkContent}
+
+ );
+ }
+ case 'image':
+ // Images are not loaded; the alternative text is shown instead.
+ return (token as Tokens.Image).text;
+ case 'code':
+ return (
+
+ {(token as Tokens.Code).text}
+
+ );
+ case 'blockquote':
+ return {renderTokens((token as Tokens.Blockquote).tokens)}
;
+ case 'hr':
+ return ;
+ case 'list': {
+ const listToken = token as Tokens.List;
+ const items = listToken.items.map((item, index) => (
+
+ {item.task ? `${item.checked ? '\u2611' : '\u2610'} ` : null}
+ {renderTokens(item.tokens)}
+
+ ));
+ return listToken.ordered ? (
+
+ {items}
+
+ ) : (
+
+ );
+ }
+ case 'table': {
+ const tableToken = token as Tokens.Table;
+ return (
+
+
+
+
+ {tableToken.header.map((cell, index) => (
+
+ {renderTokens(cell.tokens)}
+
+ ))}
+
+
+
+ {tableToken.rows.map((row, rowIndex) => (
+
+ {row.map((cell, cellIndex) => (
+
+ {renderTokens(cell.tokens)}
+
+ ))}
+
+ ))}
+
+
+
+ );
+ }
+ default:
+ return 'text' in token && typeof token.text === 'string' ? token.text : null;
+ }
+ };
+
+ return {renderTokens(tokens)}
;
+}
+
+export default memo(AgentRichTextViewer);
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/index.tsx
new file mode 100644
index 00000000..b17f4524
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/index.tsx
@@ -0,0 +1 @@
+export { default } from './AgentRichTextViewer';
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/ConversationHistory.tsx b/packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/ConversationHistory.tsx
new file mode 100644
index 00000000..973c6f11
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/ConversationHistory.tsx
@@ -0,0 +1,150 @@
+import { useEffect, useId, useRef } from 'react';
+import clsx from 'clsx';
+import { Alert, Box, CircularProgress, IconButton, List, ListItemButton, ListItemText, ListSubheader, Typography, useTheme } from '@mui/material';
+import ArrowBackIcon from '@mui/icons-material/ArrowBack';
+import makeStyles from '@mui/styles/makeStyles';
+
+import type { ConversationHistoryProps } from '../GenAICoachContent/GenAICoach.types';
+
+const useStyles = makeStyles(theme => ({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ minHeight: 0
+ },
+ inFullPage: {
+ borderInlineEnd: `0.0625rem solid ${theme.palette.divider}`
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'flex-start',
+ gap: theme.spacing(2),
+ padding: theme.spacing(1)
+ },
+ list: {
+ flexGrow: 1,
+ overflowY: 'auto',
+ paddingTop: 0
+ },
+ groupHeader: {
+ lineHeight: 2.5
+ },
+ state: {
+ display: 'flex',
+ justifyContent: 'center',
+ padding: theme.spacing(2)
+ }
+}));
+
+// ConversationHistory is one of the few components that does NOT have getPConnect.
+// So, no need to extend PConnProps
+export default function ConversationHistory(props: ConversationHistoryProps) {
+ const { data = [], onDismiss, loading = false, loadMore, inFullPage = false, onItemClick, selectedItemId, error } = props;
+ const classes = useStyles();
+ const theme = useTheme();
+ const localizedVal = PCore.getLocaleUtils().getLocaleValue;
+ const localeCategory = 'GenAICoach';
+ // The panel and its fullscreen copy can both show the history, so element ids are unique per instance.
+ const idPrefix = useId();
+
+ const backButtonRef = useRef(null);
+ const sentinelRef = useRef(null);
+ const loadingRef = useRef(loading);
+ loadingRef.current = loading;
+ const loadMoreRef = useRef(loadMore);
+ loadMoreRef.current = loadMore;
+
+ const totalConversations = data.reduce((sum, section) => sum + section.conversations.length, 0);
+
+ // Loads the next page when the end of the list is in view, checked again after each page arrives.
+ useEffect(() => {
+ const sentinel = sentinelRef.current;
+ if (!sentinel || typeof IntersectionObserver === 'undefined') return;
+
+ const observer = new IntersectionObserver(entries => {
+ if (entries.some(entry => entry.isIntersecting) && !loadingRef.current) {
+ loadMoreRef.current?.();
+ }
+ });
+ observer.observe(sentinel);
+
+ return () => observer.disconnect();
+ }, [totalConversations, loading]);
+
+ useEffect(() => {
+ if (backButtonRef.current) backButtonRef.current.focus();
+ }, []);
+
+ const loadingOrEmptyElement = loading ? (
+
+
+
+ ) : (
+
+
+ {localizedVal('No conversations found', localeCategory)}
+
+
+ );
+
+ const renderComponent =
+ data.length > 0 ? (
+
+ {data.map(item => {
+ return (
+
+
+
+ {item.section}
+
+ {item.conversations.map(conversation => {
+ const activeElement = selectedItemId === conversation.id;
+ return (
+ {
+ onItemClick?.(conversation.id);
+ }}
+ >
+
+
+ );
+ })}
+
+
+ );
+ })}
+
+ {loading && loadingOrEmptyElement}
+
+
+ ) : (
+ loadingOrEmptyElement
+ );
+
+ return (
+
+
+
+
+
+
+ {localizedVal('History', localeCategory)}
+
+
+
+ {error ? (
+
+ {error}
+
+ ) : (
+ renderComponent
+ )}
+
+ );
+}
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/index.tsx
new file mode 100644
index 00000000..27a1cba8
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/index.tsx
@@ -0,0 +1 @@
+export { default } from './ConversationHistory';
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.types.ts b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.types.ts
new file mode 100644
index 00000000..d08143e1
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.types.ts
@@ -0,0 +1,201 @@
+import type { ComponentType, ReactNode } from 'react';
+
+// ─── Prop types of the menus, actions and files of the agent components ─────────
+
+export interface MenuItemProps {
+ id: string;
+ primary: string;
+ selected?: boolean;
+ onClick?: (id: string) => void;
+}
+
+export interface MenuGroupProps {
+ id: string;
+ label: string;
+ items: MenuItemProps[];
+}
+
+export type MenuItems = (MenuItemProps | MenuGroupProps)[];
+
+export interface Action {
+ id: string;
+ text: string;
+ visual?: ReactNode;
+ /** Icon name of the action; `copy` is rendered for message actions. */
+ icon?: string;
+ onClick?: (id: string) => void;
+}
+
+export interface ActionsProps {
+ items: Action[];
+}
+
+export interface FileItemProps {
+ id: string;
+ name: string;
+ ID?: string;
+ type?: string;
+ format?: string;
+ createTime?: number;
+ progress?: number;
+ inProgress?: boolean;
+ error?: string;
+ onDelete?: () => void;
+ onCancel?: () => void;
+ file?: File;
+}
+
+export interface FileDisplayProps {
+ id: string;
+ name?: string;
+ displayText?: string;
+ value?: string;
+ format?: string;
+ onPreview?: () => void;
+}
+
+// ─── GenAICoach types ────────────────────────────────────────────────────────
+
+export type State = 'minimized' | 'maximized';
+
+export type Variant =
+ | { placement: 'utilities'; state: State; onStateChange: (state: State) => void }
+ | { placement: 'fullpage' }
+ | { placement: 'dialog'; onClose: () => void };
+
+export type Reaction = 'liked' | 'disliked';
+
+/**
+ * Markdown overrides: a function per token type returning the component to render that token with. The component gets
+ * the token and its rendered inline content (`children`), such as the formatted text of a link.
+ */
+export type MarkdownMap = Record ComponentType<{ token: any; children?: ReactNode }> | undefined>;
+
+export interface MessageProps {
+ id: string;
+ message?: string;
+}
+
+export interface UserMessageProps extends MessageProps {
+ from: 'user';
+ attachments?: FileDisplayProps[];
+}
+
+export interface MessageFeedback {
+ reaction?: Reaction;
+ feedbackText?: string;
+ onReaction?: (id: MessageProps['id'], reaction: Reaction | undefined) => void;
+ onFeedbackComplete?: (id: MessageProps['id'], comment?: string) => void;
+ promptFeedbackOn?: Reaction | 'both';
+ allowFeedbackResubmission?: boolean;
+}
+
+export interface MessageFeedbackProps {
+ messageId: MessageProps['id'];
+ feedback?: MessageFeedback;
+}
+
+export interface SuggestionProps {
+ id: string;
+ message: string;
+}
+
+export interface CoachMessageProps extends MessageProps {
+ from: 'coach';
+ coachName?: string;
+ suggestions?: SuggestionProps[];
+ loading?: boolean;
+ enableStreaming?: boolean;
+ allChunksReceived?: boolean;
+ onStreamingUpdate?: (isStreamingDone: boolean) => void;
+ error?: string;
+ markdownMap?: MarkdownMap;
+ feedback?: MessageFeedback;
+ messageActions?: ActionsProps;
+ onSend?: (item: SendMessageProps) => void;
+}
+
+export type GenAIMessageProps = UserMessageProps | CoachMessageProps;
+
+export interface ConversationHistoryProps {
+ data: {
+ id: string;
+ section: string;
+ conversations: { id: string; title: string }[];
+ }[];
+ onItemClick?: (conversationId: string) => void;
+ loading?: boolean;
+ loadMore?: () => void;
+ inFullPage?: boolean;
+ onDismiss: () => void;
+ selectedItemId?: string;
+ error?: string;
+}
+
+export interface SendMessageProps {
+ id: string;
+ message: string;
+ fromComposer?: boolean;
+ attachmentIds?: string[];
+}
+
+export interface InitialSuggestedMessageProps extends MessageProps {
+ testId?: string;
+ onSend: (item: SendMessageProps) => void;
+}
+
+/** Composer text of an agent panel. */
+export interface ComposerState {
+ message: string;
+ setMessage: (message: string) => void;
+}
+
+/** Props of the agent panel (Constellation's `GenAICoach` component), registered as `GenAICoachContent`. */
+export interface GenAICoachContentProps {
+ coachOptions: MenuItems;
+ onCoachChange?: (id: string) => void;
+ messages?: GenAIMessageProps[];
+ onSend: (item: SendMessageProps) => void;
+ initialSuggestedMessages?: MessageProps[];
+ suggestions?: MenuItems;
+ loading?: boolean | string;
+ error?: string;
+ variant: Variant;
+ onOpen?: () => void;
+ guidedMode?: boolean;
+ actions?: ActionsProps;
+ conversationHistory?: ConversationHistoryProps;
+ onLayoutChange?: (inFullPage: boolean) => void;
+ onAddAttachment?: (files: File[]) => void;
+ attachments?: FileItemProps[];
+ attachmentsError?: string;
+ allowFullScreen?: boolean;
+ salutation?: string;
+ showSalutation?: boolean;
+ /** Configurable disclaimer message shown at the top of the messages. */
+ disclaimerMessage?: ReactNode;
+ /** The agent is shown in the expanded utilities column of a landing page, where it fills the column. */
+ isInLandingPageUtilities?: boolean;
+ /** Set on the panel's own fullscreen copy (Constellation reads this state from a fullscreen context). */
+ isFullscreenView?: boolean;
+ /** The panel's composer state, shared with its fullscreen copy so that the text carries over both ways. */
+ composerState?: ComposerState;
+ /** When set, pre-populates the message box with the given text without sending. */
+ draftMessage?: string;
+ /** Message shown briefly by the panel in a snackbar (for example after copying a response). */
+ toastMessage?: string;
+ /** Called when the toast message is dismissed. */
+ onToastClose?: () => void;
+}
+
+/** Props of `UtilitiesLayout`: the utilities column of a landing page. */
+export interface UtilitiesLayoutProps {
+ /** Agent props from `useGenAICoachObj`; the panel's `variant` is set by the layout. */
+ genAICoachProps?: Omit;
+ /** Callback triggered when utilities are expanded or collapsed */
+ onToggleUtilities?: (utilitiesExpanded: boolean) => void;
+ /** show utilities in expanded mode */
+ defaultExpandUtilities?: boolean;
+ /** Determines if the actions will be disabled. */
+ disabled?: boolean;
+}
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.utils.ts b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.utils.ts
new file mode 100644
index 00000000..f294d8c2
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.utils.ts
@@ -0,0 +1,53 @@
+import type { CoachMessageProps, GenAIMessageProps, MenuGroupProps, MenuItemProps, State, UserMessageProps, Variant } from './GenAICoach.types';
+
+export const isCoachMessage = (message: GenAIMessageProps): message is CoachMessageProps => {
+ return message.from === 'coach';
+};
+
+export const isUserMessage = (message: GenAIMessageProps): message is UserMessageProps => {
+ return message.from === 'user';
+};
+
+export const isInUtilities = (
+ item: Variant
+): item is {
+ placement: 'utilities';
+ state: State;
+ onStateChange: (state: State) => void;
+} => {
+ return item.placement === 'utilities';
+};
+
+export const copyToClipboard = async (text: string) => {
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(text);
+ return true;
+ }
+
+ const textArea = document.createElement('textarea');
+ textArea.value = text;
+ textArea.setAttribute('readonly', '');
+ textArea.style.position = 'fixed';
+ textArea.style.opacity = '0';
+ document.body.appendChild(textArea);
+
+ try {
+ textArea.select();
+ return document.execCommand('copy');
+ } finally {
+ document.body.removeChild(textArea);
+ }
+ } catch {
+ return false;
+ }
+};
+
+// Local versions of Constellation helpers used by the ported code.
+export const createUID = (): string => {
+ return `_${Math.random().toString(36).slice(2, 11)}`;
+};
+
+export const isMenuGroupProps = (item: MenuItemProps | MenuGroupProps): item is MenuGroupProps => {
+ return 'items' in item && Array.isArray(item.items);
+};
diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx
new file mode 100644
index 00000000..975c42f7
--- /dev/null
+++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx
@@ -0,0 +1,1198 @@
+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type RefObject } from 'react';
+import clsx from 'clsx';
+import {
+ Alert,
+ Box,
+ Button,
+ Card,
+ CircularProgress,
+ Dialog,
+ Divider,
+ IconButton,
+ LinearProgress,
+ ListItemIcon,
+ ListItemText,
+ ListSubheader,
+ Menu,
+ MenuItem,
+ Snackbar,
+ TextField,
+ Tooltip,
+ Typography,
+ useMediaQuery,
+ useTheme
+} from '@mui/material';
+import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
+import AttachFileIcon from '@mui/icons-material/AttachFile';
+import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome';
+import CloseIcon from '@mui/icons-material/Close';
+import ExpandLessIcon from '@mui/icons-material/ExpandLess';
+import FullscreenIcon from '@mui/icons-material/Fullscreen';
+import FullscreenExitIcon from '@mui/icons-material/FullscreenExit';
+import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
+import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined';
+import MoreHorizIcon from '@mui/icons-material/MoreHoriz';
+import RemoveIcon from '@mui/icons-material/Remove';
+import SendIcon from '@mui/icons-material/Send';
+import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
+import makeStyles from '@mui/styles/makeStyles';
+
+import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map';
+
+import { createUID, isCoachMessage, isInUtilities, isMenuGroupProps, isUserMessage } from './GenAICoach.utils';
+import type {
+ Action,
+ ActionsProps,
+ FileItemProps,
+ GenAICoachContentProps,
+ MenuItemProps,
+ MenuItems,
+ SendMessageProps,
+ Variant
+} from './GenAICoach.types';
+
+// Width from which the history is shown beside the conversation (the panel's own breakpoint, as in Constellation).
+const sideBySideMinWidthPx = 768;
+const scrollThresholdPx = 50;
+// In wide layouts the conversation is a centered column of this width, as in Constellation.
+const maxWidthMessage = '46rem';
+
+const prefersReducedMotion = () => typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+
+// Deviation from Constellation: the lightbox is not ported, so a pending attachment is previewed in a new tab, which
+// shows it in the application's origin. Only types that cannot run scripts there can be previewed (not HTML or SVG).
+const previewableFileTypes = /^(image\/(png|jpeg|gif|webp|bmp|avif)|application\/pdf|text\/plain|audio\/|video\/)/i;
+const canPreviewFile = (file?: File): file is File => !!file && previewableFileTypes.test(file.type);
+
+const useStyles = makeStyles(theme => ({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ minWidth: 0,
+ backgroundColor: theme.palette.background.paper
+ },
+ utilities: {
+ margin: theme.spacing(1)
+ },
+ // Spaced like the other widgets of a page (such as the announcement card).
+ inPage: {
+ marginTop: theme.spacing(1),
+ marginBottom: theme.spacing(1)
+ },
+ fill: {
+ height: '100%',
+ minHeight: '28rem'
+ },
+ // Full-page height outside the portal, as in Constellation: once there are messages, the panel is as tall as the view (without
+ // its top and bottom margins).
+ fillInView: {
+ height: `calc(var(--content-height-in-view, 100vh) - ${theme.spacing(2)})`
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: theme.spacing(1),
+ padding: theme.spacing(1, 1, 1, 2)
+ },
+ headerTitle: {
+ minWidth: 0
+ },
+ agentSwitcher: {
+ textTransform: 'none',
+ fontWeight: 600,
+ fontSize: '1.125rem',
+ maxWidth: '100%'
+ },
+ headerActions: {
+ display: 'flex',
+ alignItems: 'center',
+ flexShrink: 0,
+ gap: theme.spacing(0.25)
+ },
+ body: {
+ display: 'flex',
+ flexGrow: 1,
+ minHeight: 0
+ },
+ sideBySide: {
+ display: 'grid',
+ gridTemplateColumns: '2fr 3fr',
+ gap: theme.spacing(0.5)
+ },
+ conversation: {
+ position: 'relative',
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ minWidth: 0,
+ minHeight: 0
+ },
+ // Before the first message on a page or in fullscreen, the welcome content and the message box are one centered group.
+ conversationCentered: {
+ justifyContent: 'center'
+ },
+ scrollArea: {
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ minHeight: 0,
+ overflowY: 'auto',
+ padding: theme.spacing(0, 2),
+ '& > *': {
+ width: '100%',
+ maxWidth: maxWidthMessage,
+ alignSelf: 'center'
+ }
+ },
+ scrollAreaFit: {
+ flexGrow: 0
+ },
+ scrollAreaBounded: {
+ maxHeight: '28rem'
+ },
+ historyBounded: {
+ maxHeight: '28rem'
+ },
+ messageList: {
+ margin: 0,
+ padding: 0,
+ listStyle: 'none'
+ },
+ state: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexGrow: 1,
+ gap: theme.spacing(1),
+ padding: theme.spacing(3, 0)
+ },
+ // Centered in the panel's height, as Constellation's initial screen.
+ emptyState: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexGrow: 1,
+ gap: theme.spacing(2),
+ padding: theme.spacing(0.5, 0, 1),
+ textAlign: 'center'
+ },
+ salutationGroup: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: theme.spacing(1)
+ },
+ // The salutation is bold and 1.5rem, as in Constellation.
+ salutation: {
+ fontWeight: theme.typography.fontWeightBold,
+ overflowWrap: 'break-word',
+ wordBreak: 'break-word'
+ },
+ initialMessages: {
+ display: 'grid',
+ width: '100%',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 12rem), 1fr))',
+ gap: theme.spacing(1.5)
+ },
+ scrollButton: {
+ position: 'absolute',
+ insetInlineEnd: theme.spacing(2),
+ bottom: theme.spacing(1),
+ backgroundColor: theme.palette.background.paper,
+ boxShadow: theme.shadows[2],
+ '&:hover': {
+ backgroundColor: theme.palette.background.paper
+ }
+ },
+ footer: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: theme.spacing(1),
+ padding: theme.spacing(1, 2, 2),
+ '& > *': {
+ width: '100%',
+ maxWidth: maxWidthMessage,
+ alignSelf: 'center'
+ }
+ },
+ composer: {
+ display: 'flex',
+ flexDirection: 'column',
+ border: `0.0625rem solid ${theme.palette.divider}`,
+ borderRadius: theme.shape.borderRadius * 2,
+ padding: theme.spacing(1, 1, 0.5)
+ },
+ composerToolbar: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: theme.spacing(1)
+ },
+ composerTools: {
+ display: 'flex',
+ alignItems: 'center'
+ },
+ generating: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: theme.spacing(1),
+ padding: theme.spacing(0.5, 1)
+ },
+ hiddenInput: {
+ display: 'none'
+ },
+ attachmentList: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: theme.spacing(0.5),
+ margin: 0,
+ padding: 0,
+ listStyle: 'none'
+ },
+ attachmentItem: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: theme.spacing(1),
+ padding: theme.spacing(0.5, 1),
+ border: `0.0625rem solid ${theme.palette.divider}`,
+ borderRadius: theme.shape.borderRadius
+ },
+ attachmentDetails: {
+ flexGrow: 1,
+ minWidth: 0
+ },
+ guided: {
+ display: 'flex',
+ justifyContent: 'center'
+ },
+ disclaimer: {
+ textAlign: 'center'
+ },
+ disclaimerMessage: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: theme.spacing(1),
+ padding: theme.spacing(2, 0)
+ },
+ disclaimerDivider: {
+ flexGrow: 1,
+ flexShrink: 0
+ },
+ visuallyHidden: {
+ position: 'absolute',
+ width: '0.0625rem',
+ height: '0.0625rem',
+ margin: '-0.0625rem',
+ padding: 0,
+ overflow: 'hidden',
+ clip: 'rect(0 0 0 0)',
+ whiteSpace: 'nowrap',
+ border: 0
+ }
+}));
+
+/** Renders menu items, with a subheader for each group. */
+const renderMenuItems = (items: MenuItems, onItemClick: (item: MenuItemProps) => void) =>
+ items.flatMap(item => {
+ if (isMenuGroupProps(item)) {
+ return [
+ ...(item.label ? [{item.label}] : []),
+ ...item.items.map(groupItem => (
+
+ ))
+ ];
+ }
+ return [
+
+ ];
+ });
+
+const countMenuItems = (items: MenuItems = []) => items.reduce((sum, item) => sum + (isMenuGroupProps(item) ? item.items.length : 1), 0);
+
+interface HeaderActionsProps {
+ actions?: ActionsProps;
+ allowFullScreen: boolean;
+ variant: Variant;
+ isUserTriggeredRef: { current: boolean };
+ isFullscreen: boolean;
+ onFullscreenToggle?: () => void;
+ selectedCoach?: string;
+ buttonRef?: RefObject;
+}
+
+// The header actions in one "Actions" menu, like the menu of agent actions in Constellation.
+const HeaderActions = ({
+ actions,
+ allowFullScreen,
+ variant,
+ isUserTriggeredRef,
+ isFullscreen,
+ onFullscreenToggle,
+ selectedCoach,
+ buttonRef
+}: HeaderActionsProps) => {
+ const [anchorEl, setAnchorEl] = useState(null);
+ const localizedVal = PCore.getLocaleUtils().getLocaleValue;
+ const localeCategory = 'GenAICoach';
+
+ const extraItems: Action[] = [
+ ...(allowFullScreen
+ ? [
+ {
+ id: 'fullscreen',
+ text: isFullscreen ? localizedVal('Exit fullscreen', localeCategory) : localizedVal('Fullscreen', localeCategory),
+ visual: isFullscreen ? : ,
+ onClick: onFullscreenToggle
+ }
+ ]
+ : []),
+ ...(isInUtilities(variant) && !isFullscreen
+ ? [
+ {
+ id: 'minimize',
+ text: localizedVal('Minimize', localeCategory),
+ visual: ,
+ onClick: () => {
+ variant.onStateChange('minimized');
+ isUserTriggeredRef.current = true;
+ }
+ }
+ ]
+ : [])
+ ];
+
+ const mergedItems = [...(actions?.items ?? []), ...extraItems];
+ if (mergedItems.length === 0) return null;
+
+ const actionsText = localizedVal('Actions', localeCategory);
+
+ return (
+ <>
+
+ ) => setAnchorEl(e.currentTarget)}
+ >
+
+
+
+
+ >
+ );
+};
+
+/**
+ * The agent panel, ported from Constellation's `GenAICoach` component (`GenAICoachContent` and `HeaderActions`).
+ * It is registered as `GenAICoachContent` because `GenAICoach` is the widget's key in the component map.
+ */
+// GenAICoachContent is one of the few components that does NOT have getPConnect.
+// So, no need to extend PConnProps
+export default function GenAICoachContent(props: GenAICoachContentProps) {
+ // Get emitted components from map (so we can get any override that may exist)
+ const GenAIMessage = getComponentFromMap('GenAIMessage');
+ const InitialSuggestedMessage = getComponentFromMap('InitialSuggestedMessage');
+ const ConversationHistory = getComponentFromMap('ConversationHistory');
+
+ const {
+ coachOptions: coachOptionsProps = [],
+ onCoachChange: onCoachChangeProp,
+ messages = [],
+ onSend,
+ initialSuggestedMessages,
+ suggestions,
+ loading,
+ error,
+ variant,
+ onOpen,
+ guidedMode = false,
+ actions,
+ conversationHistory,
+ onLayoutChange,
+ onAddAttachment,
+ attachments,
+ attachmentsError,
+ allowFullScreen = true,
+ salutation,
+ showSalutation = true,
+ disclaimerMessage,
+ isInLandingPageUtilities = false,
+ isFullscreenView = false,
+ composerState,
+ draftMessage,
+ toastMessage,
+ onToastClose
+ } = props;
+
+ const classes = useStyles();
+ const theme = useTheme();
+ const localizedVal = PCore.getLocaleUtils().getLocaleValue;
+ const localeCategory = 'GenAICoach';
+ const isMdUp = useMediaQuery(theme.breakpoints.up('md'));
+
+ const rootRef = useRef(null);
+ const scrollAreaRef = useRef(null);
+ const textAreaRef = useRef(null);
+ const fileUploadInputRef = useRef(null);
+ const actionsButtonRef = useRef(null);
+ const maximizeButtonRef = useRef(null);
+ const askButtonRef = useRef(null);
+ const generatingRef = useRef(null);
+ const wasGeneratingRef = useRef(false);
+ const isUserTriggered = useRef(false);
+ const atBottomRef = useRef(true);
+ const focusTextArea = useRef(false);
+ const previewUrlsRef = useRef