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 => ( + onItemClick(groupItem)}> + {groupItem.primary} + + )) + ]; + } + return [ + onItemClick(item)}> + {item.primary} + + ]; + }); + +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)} + > + + + + setAnchorEl(null)}> + {mergedItems.map(({ id, text, visual, onClick }) => ( + { + setAnchorEl(null); + onClick?.(id); + }} + > + {visual && {visual}} + {text} + + ))} + + + ); +}; + +/** + * 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>(new Map()); + + const [rootWidth, setRootWidth] = useState(0); + const [ownMessage, setOwnMessage] = useState(''); + // The fullscreen copy edits the panel's composer state, so the typed text carries over both ways. + const message = composerState ? composerState.message : ownMessage; + const setMessage = composerState ? composerState.setMessage : setOwnMessage; + const [fullScreen, setFullScreen] = useState(false); + const [showScrollToBottom, setShowScrollToBottom] = useState(false); + const [announcement, setAnnouncement] = useState(''); + const [coachMenuAnchor, setCoachMenuAnchor] = useState(null); + const [suggestionsMenuAnchor, setSuggestionsMenuAnchor] = useState(null); + + const isMinimized = isInUtilities(variant) && variant.state === 'minimized'; + const inPage = variant.placement === 'fullpage' && !isInLandingPageUtilities; + // As Constellation's `isCompact` and `fullPageAndInitialScreen`: before the first message, an agent on a page fits its content, + // and there and in fullscreen the message box follows the suggestions. The same elements are rearranged with styles + // (not moved, as in Constellation), so the message box keeps the focus when the first message is sent. + const isCompact = inPage && messages.length === 0; + const composerFollowsSuggestions = (inPage || isFullscreenView) && messages.length === 0; + + const latestMessage = messages.at(-1); + const lastCoachMessageId = [...messages].reverse().find(isCoachMessage)?.id; + const isLatestAgentMessageStreaming = !!latestMessage && isCoachMessage(latestMessage) && !!latestMessage.loading; + const completedAgentMessages = messages.filter(msg => isCoachMessage(msg) && !msg.loading).length; + const prevCompletedAgentMessages = useRef(completedAgentMessages); + + const shouldRenderSideBySideHistory = + !!conversationHistory && (variant.placement === 'fullpage' || isFullscreenView) && rootWidth >= sideBySideMinWidthPx; + const condition = !shouldRenderSideBySideHistory; + + const selectedCoach = useMemo(() => { + const flatItems = coachOptionsProps.flatMap(item => (isMenuGroupProps(item) ? item.items : [item])); + const selected = flatItems.find(item => item.selected); + if (selected) return selected.primary; + return flatItems[0]?.primary; + }, [coachOptionsProps]); + + // Tracks the panel width: the history is placed by the panel's own width, not the viewport's. + useEffect(() => { + const el = rootRef.current; + if (!el || typeof ResizeObserver === 'undefined') return; + const observer = new ResizeObserver(entries => { + setRootWidth(entries[0]?.contentRect.width ?? 0); + }); + observer.observe(el); + return () => observer.disconnect(); + }, [isMinimized]); + + useEffect(() => { + onLayoutChange?.(!condition); + }, [condition, fullScreen]); + + useEffect(() => { + onOpen?.(); + }, []); + + // After the user minimizes or maximizes the panel, focus moves to the control that is now shown. Guided mode has no + // text box, and none is shown while the agent loads, so focus then moves to the panel's first control, as in Constellation. + useEffect(() => { + if (!isUserTriggered.current) return; + isUserTriggered.current = false; + if (isMinimized) { + maximizeButtonRef.current?.focus(); + } else if (textAreaRef.current) { + textAreaRef.current.focus(); + } else { + rootRef.current?.querySelector('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')?.focus(); + } + }, [isMinimized]); + + // Guided mode: the Ask button gives way to the progress indicator while an answer is generated, so focus moves to the + // indicator and, once the answer is complete, back to the Ask button, as in Constellation. + useEffect(() => { + if (!guidedMode) return; + if (isLatestAgentMessageStreaming) { + wasGeneratingRef.current = true; + generatingRef.current?.focus(); + return; + } + if (!wasGeneratingRef.current) return; + wasGeneratingRef.current = false; + if (!document.activeElement || document.activeElement === document.body) askButtonRef.current?.focus(); + }, [isLatestAgentMessageStreaming, guidedMode]); + + useEffect(() => { + if (draftMessage !== undefined) { + // The fullscreen copy shares the panel's text, which the panel sets. + if (!composerState) setMessage(draftMessage); + if (draftMessage && !fullScreen) textAreaRef.current?.focus(); + } + }, [draftMessage]); + + // Polite announcements: the answer being generated, and each new completed agent message. + useEffect(() => { + if (isLatestAgentMessageStreaming) { + setAnnouncement(localizedVal('Generating response', localeCategory)); + } + }, [isLatestAgentMessageStreaming]); + + useEffect(() => { + if (completedAgentMessages > prevCompletedAgentMessages.current) { + setAnnouncement(localizedVal('New message from agent', localeCategory)); + } + prevCompletedAgentMessages.current = completedAgentMessages; + }, [completedAgentMessages]); + + const scrollToBottom = useCallback((smooth: boolean) => { + const el = scrollAreaRef.current; + if (!el) return; + el.scrollTo({ top: el.scrollHeight, behavior: smooth && !prefersReducedMotion() ? 'smooth' : 'auto' }); + }, []); + + const handleScroll = () => { + const el = scrollAreaRef.current; + if (!el) return; + const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight <= scrollThresholdPx; + atBottomRef.current = atBottom; + setShowScrollToBottom(!atBottom); + }; + + // Follows new and streamed content while the user is at the bottom; a sent message always scrolls down. + useEffect(() => { + if (atBottomRef.current || (latestMessage && isUserMessage(latestMessage))) { + atBottomRef.current = true; + scrollToBottom(false); + setShowScrollToBottom(false); + } + }, [messages]); + + useEffect(() => { + if (messages.length === 0 || loading || error) { + setShowScrollToBottom(false); + } + }, [messages.length, loading, error]); + + useEffect(() => { + if (focusTextArea.current && !conversationHistory && textAreaRef.current) { + textAreaRef.current.focus(); + focusTextArea.current = false; + } + }, [conversationHistory]); + + // Local previews of pending attachments use object URLs, revoked when the attachment is removed. + useEffect(() => { + const ids = new Set((attachments ?? []).map(att => att.id)); + previewUrlsRef.current.forEach((url, id) => { + if (!ids.has(id)) { + URL.revokeObjectURL(url); + previewUrlsRef.current.delete(id); + } + }); + }, [attachments]); + + useEffect(() => { + const previewUrls = previewUrlsRef.current; + return () => { + previewUrls.forEach(url => URL.revokeObjectURL(url)); + previewUrls.clear(); + }; + }, []); + + const previewAttachment = (attachment: FileItemProps) => { + if (!canPreviewFile(attachment.file)) return; + let url = previewUrlsRef.current.get(attachment.id); + if (!url) { + url = URL.createObjectURL(attachment.file); + previewUrlsRef.current.set(attachment.id, url); + } + window.open(url, '_blank', 'noopener,noreferrer'); + }; + + const handleSendMessage = () => { + const isMessageAndAttachmentsEmpty = !message && (!attachments || attachments.length === 0); + const hasAttachmentsError = attachments && attachments.length > 0 && (attachmentsError || attachments.some(attachment => attachment.error)); + const isCoachMessageLoading = latestMessage && isCoachMessage(latestMessage) && latestMessage.loading; + if (isMessageAndAttachmentsEmpty || hasAttachmentsError || isCoachMessageLoading) return; + + onSend({ + id: createUID(), + message, + fromComposer: true, + attachmentIds: attachments?.map(({ id }) => id) + }); + setMessage(''); + // The Send button gives way to the progress indicator, so the message box keeps the focus. + textAreaRef.current?.focus(); + }; + + // A selected follow-up suggestion is sent and the suggestions are removed, so the message box takes the focus. + const sendSuggestion = (item: SendMessageProps) => { + onSend(item); + textAreaRef.current?.focus(); + }; + + const handleEnterKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + e.stopPropagation(); + handleSendMessage(); + } + }; + + const enterFullscreen = () => setFullScreen(true); + const exitFullscreen = () => setFullScreen(false); + + // ── Header ──────────────────────────────────────────────────────────────── + + const renderCoachOptions = () => { + if (coachOptionsProps.length === 0 || !selectedCoach) { + return null; + } + if (countMenuItems(coachOptionsProps) === 1) { + return ( + + {selectedCoach} + + ); + } + return ( + <> + + setCoachMenuAnchor(null)}> + {renderMenuItems(coachOptionsProps, item => { + setCoachMenuAnchor(null); + onCoachChangeProp?.(item.id); + })} + + + ); + }; + + const headerContent = isMinimized ? ( + <> + + {selectedCoach} + + + { + if (isInUtilities(variant)) { + variant.onStateChange('maximized'); + isUserTriggered.current = true; + } + }} + > + + + + + ) : ( + <> + {renderCoachOptions()} + + + + + {variant.placement === 'dialog' && !isFullscreenView && ( + + + + + + )} + + + ); + + // ── Conversation ───────────────────────────────────────────────────────── + + const emptyState = ( + + {showSalutation && ( + + + + {salutation ?? localizedVal('How can I assist you today?', localeCategory)} + + + )} + + {initialSuggestedMessages && initialSuggestedMessages.length > 0 && ( + + {initialSuggestedMessages.map(initialSuggestedMessage => ( + { + if (guidedMode) { + onSend({ + id: initialMessage.id, + message: initialMessage.message ?? '' + }); + } else { + setMessage(initialMessage.message ?? ''); + } + textAreaRef.current?.focus(); + }} + testId={initialSuggestedMessage.id} + /> + ))} + + )} + + ); + + let conversationContent; + if (loading || error) { + conversationContent = ( + + {loading ? ( + <> + + + {typeof loading === 'string' ? loading : localizedVal('Loading…', localeCategory)} + + + ) : ( + + {error} + + )} + + ); + } else if (messages.length === 0) { + conversationContent = emptyState; + } else { + conversationContent = ( + <> + {disclaimerMessage && ( + + + + {disclaimerMessage} + + + + )} +
      + {messages.map((item, index) => { + const messageProps = isCoachMessage(item) + ? { + ...item, + // Follow-up suggestions are shown on the latest agent message only. + suggestions: lastCoachMessageId === item.id ? item.suggestions : undefined, + onSend: sendSuggestion + } + : item; + return ; + })} +
    + + ); + } + + // ── Composer ───────────────────────────────────────────────────────────── + + const hasSuggestions = countMenuItems(suggestions) > 0; + + const disclaimer = ( + + {localizedVal('Verify AI-generated content for accuracy.', localeCategory)} + + ); + + const generatingIndicator = ( + + {localizedVal('Generating response', localeCategory)} + + + ); + + const suggestionsMenu = (onItemClick: (item: MenuItemProps) => void) => ( + setSuggestionsMenuAnchor(null)}> + {renderMenuItems(suggestions ?? [], item => { + setSuggestionsMenuAnchor(null); + if (item.onClick) { + item.onClick(item.id); + } else { + onItemClick(item); + } + })} + + ); + + const renderSendControl = () => { + if (latestMessage && isCoachMessage(latestMessage) && latestMessage.loading) { + return generatingIndicator; + } + + return ( + + + + + + ); + }; + + const renderTextArea = ( + <> + + setMessage(e.target.value)} + onKeyDown={handleEnterKeyDown} + slotProps={{ + input: { disableUnderline: true }, + htmlInput: { + 'aria-label': localizedVal('Write a message', localeCategory) + } + }} + /> + + + + {hasSuggestions && ( + <> + + ) => setSuggestionsMenuAnchor(e.currentTarget)} + > + + + + {suggestionsMenu(item => { + setMessage(item.primary); + textAreaRef.current?.focus(); + })} + + )} + + {onAddAttachment && ( + <> + + { + if (fileUploadInputRef.current) { + fileUploadInputRef.current.value = ''; + } + fileUploadInputRef.current?.click(); + }} + > + + + + { + if (e.target.files) { + onAddAttachment(Array.from(e.target.files)); + } + }} + multiple={false} + /> + + )} + + + {renderSendControl()} + + + + {attachments && attachments.length > 0 && ( + <> +
      + {attachments.map(attachment => ( +
    • + + + + {attachment.name} + + {attachment.inProgress && !attachment.error && ( + + )} + {attachment.error && ( + + {attachment.error} + + )} + + {canPreviewFile(attachment.file) && !attachment.error && ( + + previewAttachment(attachment)} + > + + + + )} + + { + (attachment.inProgress ? attachment.onCancel : attachment.onDelete)?.(); + textAreaRef.current?.focus(); + }} + > + + + +
    • + ))} +
    + + {attachmentsError && ( + + {attachmentsError} + + )} + + )} + + {disclaimer} + + ); + + const guidedComposer = ( + <> + {/* The Ask menu follows the first answer; before it, the empty state offers the starter prompts. */} + {hasSuggestions && messages.length > 0 && ( + <> + {latestMessage && isCoachMessage(latestMessage) && latestMessage.loading ? ( + + {generatingIndicator} + + ) : ( + + + {suggestionsMenu(item => { + onSend({ + id: item.id, + message: item.primary + }); + })} + + )} + + {disclaimer} + + )} + + ); + + const conversationElement = ( + + + {conversationContent} + + + {showScrollToBottom && ( + { + atBottomRef.current = true; + scrollToBottom(true); + setShowScrollToBottom(false); + }} + > + + + )} + + {!loading && {guidedMode ? guidedComposer : renderTextArea}} + + ); + + const historyView = conversationHistory && ( + { + if (condition) { + focusTextArea.current = true; + } else { + textAreaRef.current?.focus(); + } + + conversationHistory.onItemClick?.(conversationId); + }} + onDismiss={() => { + focusTextArea.current = true; + conversationHistory.onDismiss(); + }} + inFullPage={!condition} + /> + ); + + let bodyContent; + if (condition) { + // In the utilities column the history scrolls within the same height limit as the conversation. + bodyContent = ( + + {conversationHistory ? historyView : conversationElement} + + ); + } else { + bodyContent = ( + + {historyView} + {conversationElement} + + ); + } + + const rootProps = { + ref: rootRef, + className: clsx( + classes.root, + isInUtilities(variant) ? classes.utilities : !isCompact && classes.fill, + inPage && classes.inPage, + inPage && messages.length > 0 && classes.fillInView + ), + component: 'section' as const, + 'aria-label': selectedCoach ?? localizedVal('Agent', localeCategory) + }; + + const panelContent = ( + <> + {headerContent} + + {!isMinimized && bodyContent} + + + {announcement} + + + {/* Toast messages; while the fullscreen copy is open, the copy shows them. */} + {(isFullscreenView || !fullScreen) && ( + onToastClose?.()} + anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} + /> + )} + + {/* Fullscreen: the same conversation in a dialog, full screen below the md breakpoint. */} + {!isFullscreenView && ( + actionsButtonRef.current?.focus() } + }} + > + + + )} + + ); + + // In a dialog the agent is the dialog's content; on a page or in a case it is a card, as the other widgets are. + if (variant.placement === 'dialog') { + return {panelContent}; + } + + return {panelContent}; +} diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/index.tsx new file mode 100644 index 00000000..edf0f7a2 --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/index.tsx @@ -0,0 +1 @@ +export { default } from './GenAICoachContent'; diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx new file mode 100644 index 00000000..0379b0d7 --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx @@ -0,0 +1,233 @@ +import { useEffect, useMemo, type ReactNode } from 'react'; +import { Alert, Avatar, Box, Button, Chip, CircularProgress, IconButton, Tooltip } from '@mui/material'; +import AttachFileIcon from '@mui/icons-material/AttachFile'; +import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'; +import ContentCopyIcon from '@mui/icons-material/ContentCopy'; +import makeStyles from '@mui/styles/makeStyles'; + +import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; +import { StreamingContext, type StreamingContextProps } from '../../helpers/StreamingContext'; +import { isCoachMessage, isUserMessage } from '../GenAICoachContent/GenAICoach.utils'; +import type { Action, GenAIMessageProps } from '../GenAICoachContent/GenAICoach.types'; + +// MUI icons for the icon names of the message actions. +const actionIcons: Record = { + copy: +}; + +const useStyles = makeStyles(theme => ({ + coachMessage: { + display: 'flex', + alignItems: 'flex-start', + gap: theme.spacing(0.5), + padding: theme.spacing(1, 0) + }, + // The agent avatar: the theme's primary color on a subtle circle with a faint ring. + coachAvatar: { + width: '2rem', + height: '2rem', + color: theme.palette.primary.main, + backgroundColor: theme.palette.action.hover, + boxShadow: `inset 0 0 0 0.0625rem ${theme.palette.divider}`, + '& svg': { + width: '50%', + height: '50%' + } + }, + coachContent: { + flex: 1, + minWidth: 0, + display: 'flex', + flexDirection: 'column', + gap: theme.spacing(1), + // Centers the first line of text on the avatar. + paddingTop: theme.spacing(0.75) + }, + userRow: { + display: 'flex', + justifyContent: 'flex-end', + padding: theme.spacing(1, 0) + }, + userBubble: { + maxWidth: '85%', + display: 'flex', + flexDirection: 'column', + gap: theme.spacing(1), + padding: theme.spacing(1, 1.5), + borderRadius: theme.shape.borderRadius * 2, + backgroundColor: theme.palette.action.selected + }, + actions: { + display: 'flex', + alignItems: 'center', + gap: theme.spacing(1) + }, + suggestions: { + display: 'flex', + flexWrap: 'wrap', + justifyContent: 'flex-end', + gap: theme.spacing(1) + }, + suggestion: { + textTransform: 'none', + textAlign: 'start' + }, + attachments: { + display: 'flex', + flexWrap: 'wrap', + gap: theme.spacing(0.5) + } +})); + +const MessageAction = ({ id, text, icon, onClick }: Action) => { + const visual = icon ? actionIcons[icon] : undefined; + + if (!visual) { + return ( + + ); + } + + return ( + + onClick?.(id)}> + {visual} + + + ); +}; + +// GenAIMessage is one of the few components that does NOT have getPConnect. +// So, no need to extend PConnProps (its props are the message itself) +export default function GenAIMessage(props: GenAIMessageProps) { + // Get emitted components from map (so we can get any override that may exist) + const AgentRichTextViewer = getComponentFromMap('AgentRichTextViewer'); + const GenAIMessageProgress = getComponentFromMap('GenAIMessageProgress'); + const GenAIMessageFeedback = getComponentFromMap('GenAIMessageFeedback'); + + const { message } = props; + const classes = useStyles(); + const localizedVal = PCore.getLocaleUtils().getLocaleValue; + const localeCategory = 'GenAICoach'; + + const isStreamingMessage = isCoachMessage(props) && !!props.enableStreaming; + const allChunksReceived = isCoachMessage(props) && props.allChunksReceived; + + useEffect(() => { + // The text is shown as it arrives (Constellation's typing animation is not ported), + // so streaming is done as soon as all chunks are received. An answer that is no longer loading + // does not report it again when it remounts (as when the fullscreen view opens). + if (isStreamingMessage && isCoachMessage(props) && props.loading && props.onStreamingUpdate) { + props.onStreamingUpdate(!!allChunksReceived); + } + }, [isStreamingMessage, allChunksReceived]); + + const streamingContext: StreamingContextProps = useMemo(() => { + return { isStreamingMessage, isStreamingInProgress: isCoachMessage(props) && props.loading }; + }, [isStreamingMessage, props]); + + if (isCoachMessage(props)) { + const { id: messageId, coachName, suggestions, onSend, loading, error, feedback, markdownMap, messageActions } = props; + + const streamingContent = isStreamingMessage && ( + <> + {message ? ( + <> + + + + + {loading && } + + ) : ( + loading && + )} + + ); + + return ( +
  • + + + + + + {/* Streaming loader and content */} + {streamingContent} + + {loading || error ? ( + <> + {loading && !isStreamingMessage && } + {error && {error}} + + ) : ( + <> + {/* Non streaming content */} + {!isStreamingMessage && message && } + + {(feedback || messageActions) && ( + + {feedback && } + + {messageActions?.items.map(action => ( + + ))} + + )} + + {suggestions && suggestions.length > 0 && ( + + {suggestions.map(({ id, message: prompt }) => { + return ( + + ); + })} + + )} + + )} + +
  • + ); + } + + if (isUserMessage(props)) { + return ( +
  • + + {props.attachments && props.attachments.length > 0 && ( + + {props.attachments.map(attachment => { + const name = attachment.displayText ?? attachment.name ?? ''; + return ( + } + label={name} + onClick={attachment.onPreview} + aria-label={attachment.onPreview ? `${localizedVal('Download', localeCategory)} ${name}` : name} + /> + ); + })} + + )} + {props.message && } + +
  • + ); + } + + return null; +} diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/index.tsx new file mode 100644 index 00000000..17bbc371 --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/index.tsx @@ -0,0 +1 @@ +export { default } from './GenAIMessage'; diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/GenAIMessageFeedback.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/GenAIMessageFeedback.tsx new file mode 100644 index 00000000..e2e1efca --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/GenAIMessageFeedback.tsx @@ -0,0 +1,196 @@ +import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from 'react'; +import { Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, TextField, Tooltip } from '@mui/material'; +import ThumbUpIcon from '@mui/icons-material/ThumbUp'; +import ThumbUpOutlinedIcon from '@mui/icons-material/ThumbUpOutlined'; +import ThumbDownIcon from '@mui/icons-material/ThumbDown'; +import ThumbDownOutlinedIcon from '@mui/icons-material/ThumbDownOutlined'; + +import type { MessageFeedbackProps, Reaction } from '../GenAICoachContent/GenAICoach.types'; + +// GenAIMessageFeedback is one of the few components that does NOT have getPConnect. +// So, no need to extend PConnProps +export default function GenAIMessageFeedback(props: MessageFeedbackProps) { + const { messageId, feedback } = props; + const { + reaction, + feedbackText = '', + allowFeedbackResubmission = false, + promptFeedbackOn = 'disliked', + onReaction, + onFeedbackComplete + } = feedback ?? {}; + + const localizedVal = PCore.getLocaleUtils().getLocaleValue; + const localeCategory = 'GenAICoach'; + + const [feedbackVal, setFeedbackVal] = useState(feedbackText); + const [showDialog, setShowDialog] = useState(false); + + const likeButtonRef = useRef(null); + const dislikeButtonRef = useRef(null); + const shouldOpenDialogRef = useRef(false); + const [iconEl, setIconEl] = useState(null); + + const isLikeActive = reaction === 'liked'; + const isDislikeActive = reaction === 'disliked'; + + const goodResponse = localizedVal('Good response', localeCategory); + const badResponse = localizedVal('Bad response', localeCategory); + + const needsDialog = (reactionType: Reaction) => { + switch (promptFeedbackOn) { + case 'disliked': + return reactionType === 'disliked'; + case 'liked': + return reactionType === 'liked'; + case 'both': + return true; + default: + return false; + } + }; + + const handleReactionClick = useCallback( + (reactionType: Reaction) => { + if (reaction === reactionType) { + if (allowFeedbackResubmission) { + onReaction?.(messageId, undefined); + } + + return; + } + + onReaction?.(messageId, reactionType); + + if (needsDialog(reactionType)) { + if (reaction !== reactionType) { + setFeedbackVal(''); + } else { + setFeedbackVal(feedbackText); + } + + if (!allowFeedbackResubmission) { + shouldOpenDialogRef.current = true; + } else { + setShowDialog(true); + } + } + }, + [reaction, feedbackText, allowFeedbackResubmission, promptFeedbackOn, messageId, onReaction] + ); + + const closeDialog = useCallback( + (comment?: string) => { + setShowDialog(false); + shouldOpenDialogRef.current = false; + + onFeedbackComplete?.(messageId, comment); + }, + [onFeedbackComplete, messageId] + ); + + // Focus returns to the rating control once the dialog has closed. + const restoreFocus = () => { + if (!allowFeedbackResubmission && iconEl) { + iconEl.focus(); + return; + } + (isLikeActive ? likeButtonRef.current : dislikeButtonRef.current)?.focus(); + }; + + useEffect(() => { + if (iconEl && shouldOpenDialogRef.current && !allowFeedbackResubmission) { + setShowDialog(true); + shouldOpenDialogRef.current = false; + } + }, [iconEl, allowFeedbackResubmission]); + + const feedbackDialog = ( + closeDialog()} + disableRestoreFocus + fullWidth + maxWidth='xs' + onKeyDown={e => e.stopPropagation()} + slotProps={{ transition: { onExited: restoreFocus } }} + > + {localizedVal('Share feedback', localeCategory)} + + setFeedbackVal(e.target.value)} + onKeyDown={(e: KeyboardEvent) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + closeDialog(feedbackVal); + } + }} + /> + + + + + + + ); + + const shouldShowIcon = !allowFeedbackResubmission && reaction; + + if (shouldShowIcon) { + const selectedLabel = localizedVal('{1} selected', localeCategory).replace('{1}', isLikeActive ? goodResponse : badResponse); + return ( + <> + + + {isLikeActive ? : } + + + + {feedbackDialog} + + ); + } + + return ( + <> + + + handleReactionClick('liked')} + aria-pressed={isLikeActive} + color={isLikeActive ? 'primary' : 'default'} + > + {isLikeActive ? : } + + + + + handleReactionClick('disliked')} + aria-pressed={isDislikeActive} + color={isDislikeActive ? 'primary' : 'default'} + > + {isDislikeActive ? : } + + + + + {feedbackDialog} + + ); +} diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/index.tsx new file mode 100644 index 00000000..dcc11f58 --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/index.tsx @@ -0,0 +1 @@ +export { default } from './GenAIMessageFeedback'; diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/GenAIMessageProgress.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/GenAIMessageProgress.tsx new file mode 100644 index 00000000..77a117bc --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/GenAIMessageProgress.tsx @@ -0,0 +1,55 @@ +import { useEffect, useMemo, useState } from 'react'; +import { Box, CircularProgress, Typography } from '@mui/material'; + +const baseDuration = 900; + +// GenAIMessageProgress is one of the few components that does NOT have getPConnect. +// So, no need to extend PConnProps +export default function GenAIMessageProgress() { + const localizedVal = PCore.getLocaleUtils().getLocaleValue; + const localeCategory = 'GenAICoach'; + + const progressMessages = useMemo( + () => [ + { message: localizedVal('Thinking', localeCategory), duration: baseDuration }, + { message: localizedVal('Analyzing data sources', localeCategory), duration: baseDuration }, + { message: localizedVal('Generating response', localeCategory), duration: baseDuration * 3 }, + { message: localizedVal('Double checking results', localeCategory), duration: baseDuration * 4 }, + { message: localizedVal('Finalizing response', localeCategory), duration: baseDuration * 5 }, + { message: localizedVal('Double checking results', localeCategory), duration: baseDuration * 7 }, + { message: localizedVal('Analyzing data sources', localeCategory), duration: baseDuration * 9 }, + { message: localizedVal('Finalizing response', localeCategory), duration: baseDuration * 10 } + ], + [] + ); + const [currentIndex, setCurrentIndex] = useState(0); + + useEffect(() => { + let timeoutId: ReturnType; + + const scheduleNextMessage = (index: number) => { + if (index >= progressMessages.length - 1) return; + + const currentMessage = progressMessages[index]; + + timeoutId = setTimeout(() => { + setCurrentIndex(index + 1); + scheduleNextMessage(index + 1); + }, currentMessage.duration); + }; + + // Start with the first message and schedule the next one + scheduleNextMessage(0); + + return () => { + if (timeoutId) clearTimeout(timeoutId); + }; + }, [progressMessages]); + + return ( + + {progressMessages[currentIndex].message} + + + ); +} diff --git a/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/index.tsx new file mode 100644 index 00000000..5f4a966d --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/index.tsx @@ -0,0 +1 @@ +export { default } from './GenAIMessageProgress'; diff --git a/packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/InitialSuggestedMessage.tsx b/packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/InitialSuggestedMessage.tsx new file mode 100644 index 00000000..e1e855f5 --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/InitialSuggestedMessage.tsx @@ -0,0 +1,51 @@ +import { Button, Typography, getContrastRatio, useTheme } from '@mui/material'; +import makeStyles from '@mui/styles/makeStyles'; + +import type { InitialSuggestedMessageProps } from '../GenAICoachContent/GenAICoach.types'; + +// WCAG AA contrast for normal text. +const minTextContrast = 4.5; + +const useStyles = makeStyles(theme => ({ + // An outlined button in the primary color, as in Constellation; the label is centered while it fits on one line. + root: { + height: '100%', + width: '100%', + alignItems: 'flex-start', + padding: theme.spacing(1, 2), + textAlign: 'start', + textTransform: 'none' + }, + text: { + display: '-webkit-box', + WebkitLineClamp: 3, + WebkitBoxOrient: 'vertical', + overflow: 'hidden' + } +})); + +// InitialSuggestedMessage is one of the few components that does NOT have getPConnect. +// So, no need to extend PConnProps +export default function InitialSuggestedMessage(props: InitialSuggestedMessageProps) { + const { id, message, testId, onSend } = props; + const classes = useStyles(); + const theme = useTheme(); + // To stay readable in dark themes, the label uses the text color where the primary color is too faint. + const color = getContrastRatio(theme.palette.primary.main, theme.palette.background.paper) >= minTextContrast ? 'primary' : 'inherit'; + + return ( + + ); +} diff --git a/packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/index.tsx new file mode 100644 index 00000000..8e356dea --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/index.tsx @@ -0,0 +1 @@ +export { default } from './InitialSuggestedMessage'; diff --git a/packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/UtilitiesLayout.tsx b/packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/UtilitiesLayout.tsx new file mode 100644 index 00000000..b3dbc6f4 --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/UtilitiesLayout.tsx @@ -0,0 +1,264 @@ +import { type KeyboardEvent, useEffect, useRef, useState } from 'react'; +import clsx from 'clsx'; +import { Box, ClickAwayListener, Drawer, Fab, IconButton, Paper, Popper, Tooltip, Typography, useMediaQuery, useTheme } from '@mui/material'; +import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'; +import KeyboardArrowLeftIcon from '@mui/icons-material/KeyboardArrowLeft'; +import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight'; +import makeStyles from '@mui/styles/makeStyles'; + +import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; + +import type { UtilitiesLayoutProps } from '../GenAICoachContent/GenAICoach.types'; + +const useStyles = makeStyles(theme => ({ + root: { + display: 'flex', + flexDirection: 'column', + gap: theme.spacing(1), + flexShrink: 0, + width: '3rem', + paddingBlock: theme.spacing(2) + }, + rootExpanded: { + width: '25rem', + position: 'sticky', + top: 0, + height: '100vh' + }, + header: { + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', + paddingBottom: theme.spacing(1) + }, + coachContainer: { + display: 'flex', + flexDirection: 'column', + flexGrow: 1, + minHeight: 0 + }, + coachButton: { + position: 'fixed', + width: '2.75rem', + height: '2.75rem', + minHeight: 'auto', + insetBlockEnd: theme.spacing(2), + insetInlineEnd: theme.spacing(2) + }, + coachPopper: { + // Above the navigation and drawers, below dialogs and menus (including the ones the agent opens). + zIndex: theme.zIndex.modal - 1 + }, + dialogPaper: { + display: 'flex', + flexDirection: 'column', + width: '25rem', + maxWidth: 'calc(100vw - 2rem)', + height: 'calc(0.85 * 95vh)' + }, + drawerPaper: { + display: 'flex', + flexDirection: 'column', + gap: theme.spacing(2), + width: '25rem', + maxWidth: '100vw', + padding: theme.spacing(2) + } +})); + +const focusableSelector = 'button, [href], input, select, textarea, [tabindex]'; + +const getFocusables = (container: HTMLElement) => + Array.from(container.querySelectorAll(focusableSelector)).filter( + element => element.tabIndex >= 0 && !element.hasAttribute('disabled') && element.getClientRects().length > 0 + ); + +/** + * The utilities column of a landing page, ported from Constellation's `UtilitiesLayout`. Collapsed, it offers a + * "Chat with AI" button that opens the agent next to it; expanded, it shows the agent in the column (in a drawer + * below the lg breakpoint). Below the md breakpoint the agent is shown in the page. + */ +// UtilitiesLayout is one of the few components that does NOT have getPConnect. +// So, no need to extend PConnProps +export default function UtilitiesLayout(props: UtilitiesLayoutProps) { + // Get emitted components from map (so we can get any override that may exist) + const GenAICoachContent = getComponentFromMap('GenAICoachContent'); + + const { genAICoachProps, defaultExpandUtilities = false, disabled = false, onToggleUtilities } = props; + const classes = useStyles(); + const theme = useTheme(); + const localizedVal = PCore.getLocaleUtils().getLocaleValue; + const localeCategory = 'GenAICoach'; + + const [utilitiesExpanded, setUtilitiesExpanded] = useState(defaultExpandUtilities); + const [showCoach, setShowCoach] = useState(false); + + const toggleButtonRef = useRef(null); + const genAICoachButtonRef = useRef(null); + const coachPanelRef = useRef(null); + const utilitiesToggled = useRef(false); + const mdOrAbove = useMediaQuery(theme.breakpoints.up('md')); + const lgOrAbove = useMediaQuery(theme.breakpoints.up('lg')); + const isRtl = theme.direction === 'rtl'; + + // Focus stays on the toggle; between md and lg the expanded utilities are a drawer with its own toggle. + useEffect(() => { + onToggleUtilities?.(utilitiesExpanded); + if (utilitiesToggled.current) { + toggleButtonRef.current?.focus(); + } + }, [utilitiesExpanded]); + + // As in Constellation, the opened agent takes the focus. + useEffect(() => { + const panel = coachPanelRef.current; + if (!showCoach || !panel) return; + (getFocusables(panel)[0] ?? panel).focus({ preventScroll: true }); + }, [showCoach]); + + // Expanded, the arrow points to the end (collapse); collapsed, to the start (expand). + const ToggleIcon = utilitiesExpanded !== isRtl ? KeyboardArrowRightIcon : KeyboardArrowLeftIcon; + const utilitiesToggleButton = ( + + + { + utilitiesToggled.current = true; + setShowCoach(false); + setUtilitiesExpanded(prevState => !prevState); + }} + disabled={disabled} + > + + + + + ); + + const utilitiesHeader = ( + + {utilitiesExpanded && ( + + {localizedVal('Utilities', localeCategory)} + + )} + {utilitiesToggleButton} + + ); + + const genAICoachInUtilities = genAICoachProps && ( + + + + ); + + if (!mdOrAbove && genAICoachProps) { + return ; + } + + if (utilitiesExpanded && !lgOrAbove) { + return ( + + {utilitiesHeader} + {genAICoachInUtilities} + + ); + } + + const chatWithAI = localizedVal('Chat with AI', localeCategory); + const closeCoach = () => { + setShowCoach(false); + genAICoachButtonRef.current?.focus(); + }; + + // Like a dialog, Escape closes the agent and Tab cycles within it. Keys from the menus and dialogs the agent + // opens reach this handler through the React tree, so only keys pressed in the panel itself are handled. + const handleCoachKeyDown = (event: KeyboardEvent) => { + const panel = coachPanelRef.current; + if (!panel || !panel.contains(event.target as Node)) return; + + if (event.key === 'Escape') { + event.stopPropagation(); + closeCoach(); + return; + } + if (event.key !== 'Tab') return; + + const focusables = getFocusables(panel); + const first = focusables[0]; + const last = focusables[focusables.length - 1]; + const atStart = document.activeElement === first || document.activeElement === panel; + if (!first || (event.shiftKey && atStart) || (!event.shiftKey && document.activeElement === last)) { + event.preventDefault(); + (event.shiftKey ? last : first)?.focus(); + } + }; + + return ( + + {utilitiesHeader} + {utilitiesExpanded && genAICoachInUtilities} + {!utilitiesExpanded && ( + + setShowCoach(cur => !cur)} + disabled={disabled} + > + + + + )} + {/* Non-modal, as in Constellation: the page stays scrollable and usable while the agent is open. */} + {genAICoachProps && showCoach && ( + + { + // The button toggles the agent itself; a click elsewhere closes it and still reaches the page. + if (genAICoachButtonRef.current?.contains(event.target as Node)) return; + setShowCoach(false); + }} + > + + + + + + )} + + ); +} diff --git a/packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/index.tsx b/packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/index.tsx new file mode 100644 index 00000000..122b4afb --- /dev/null +++ b/packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/index.tsx @@ -0,0 +1 @@ +export { default } from './UtilitiesLayout'; diff --git a/packages/react-sdk-components/src/components/helpers/StreamingContext.ts b/packages/react-sdk-components/src/components/helpers/StreamingContext.ts new file mode 100644 index 00000000..caac2abe --- /dev/null +++ b/packages/react-sdk-components/src/components/helpers/StreamingContext.ts @@ -0,0 +1,13 @@ +import { createContext } from 'react'; + +// Provided by GenAIMessage and read by the agent markdown renderers. It lives in helpers so that an overridden +// GenAIMessage still shares this one context object with the SDK renderers. +export type StreamingContextProps = { + isStreamingMessage?: boolean; + isStreamingInProgress?: boolean; +}; + +/** Metadata Context */ +export const StreamingContext = createContext({ + isStreamingMessage: false +}); diff --git a/packages/react-sdk-components/src/components/helpers/agent-inline-edit-utils.ts b/packages/react-sdk-components/src/components/helpers/agent-inline-edit-utils.ts new file mode 100644 index 00000000..5affc3c3 --- /dev/null +++ b/packages/react-sdk-components/src/components/helpers/agent-inline-edit-utils.ts @@ -0,0 +1,102 @@ +export type CoachPConnectGetter = () => typeof PConnect; + +export interface ParsedCaseLink { + appName: string; + caseTypeID: string; + caseReferenceID: string; + pegaServerUrl: string; +} + +export interface ResolvedCaseLink extends ParsedCaseLink { + insKey?: string; + assignmentID?: string; + className?: string; +} + +export type CaseOpenStrategy = 'native' | 'webembed'; + +export const parseCaseLink = (href: string): ParsedCaseLink | undefined => { + try { + const parsedUrl = new URL(href, window.location.origin); + const pathParts = parsedUrl.pathname.split('/').filter(Boolean); + const appIndex = pathParts.indexOf('app'); + + if (appIndex < 0 || pathParts.length <= appIndex + 3) { + return undefined; + } + + const appName = pathParts[appIndex + 1]; + const caseTypeID = pathParts[appIndex + 2]; + const caseReferenceID = decodeURIComponent(pathParts[appIndex + 3]); + const basePath = pathParts.slice(0, appIndex).join('/'); + const pegaServerUrl = `${parsedUrl.origin}/${basePath ? `${basePath}/` : ''}`; + + return { + appName, + caseTypeID, + caseReferenceID, + pegaServerUrl + }; + } catch { + return undefined; + } +}; + +export interface CaseKeysResult { + pzInsKey?: string; + className?: string; +} + +const resolveCaseKeysFromUrl = (href: string): CaseKeysResult => { + try { + const url = new URL(href, window.location.origin); + + return { + pzInsKey: url.searchParams.get('caseKey') ?? undefined, + className: url.searchParams.get('caseTypeID') ?? undefined + }; + } catch { + return {}; + } +}; + +export const hasCaseIdentifierQueryParams = (href: string): boolean => { + const { pzInsKey, className } = resolveCaseKeysFromUrl(href); + + return Boolean(pzInsKey || className); +}; + +export const resolveCaseKeysFromLink = (parsed: ParsedCaseLink, originalHref: string): ResolvedCaseLink => { + try { + const { pzInsKey, className } = resolveCaseKeysFromUrl(originalHref); + const resolvedInsKey = pzInsKey ?? parsed.caseReferenceID; + const normalizedInsKey = resolvedInsKey.trim(); + const classNameFromInsKey = normalizedInsKey.includes(' ') ? normalizedInsKey.split(/\s+/)[0] : undefined; + // Fall back to path-derived values when explicit query params are absent. + // For URLs like `.../app//cases/`, the route segment + // (`caseTypeID`) is only a bucket label (`cases`), so derive className from + // the pzInsKey shape ` ` before using `caseTypeID`. + return { + ...parsed, + insKey: resolvedInsKey, + className: className ?? classNameFromInsKey ?? parsed.caseTypeID + }; + } catch { + return parsed; + } +}; + +export const resolveCaseOpenStrategy = (resolved: ResolvedCaseLink): CaseOpenStrategy => { + if (!resolved.insKey || !resolved.className) { + return 'webembed'; + } + + const resolvedClassName = PCore.getRemoteCaseUtils().getRemoteCaseClassBySourceClass(resolved.className) ?? resolved.className; + // isRemoteCaseVersionDifferent is not in the 4.1 typings, and older servers do not provide it. + const caseUtils: { isRemoteCaseVersionDifferent?: (className: string) => boolean } = PCore.getCaseUtils() as any; + if (caseUtils.isRemoteCaseVersionDifferent?.(resolvedClassName)) { + return 'webembed'; + } + + return 'native'; +}; diff --git a/packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx b/packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx new file mode 100644 index 00000000..21d60e67 --- /dev/null +++ b/packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx @@ -0,0 +1,331 @@ +import { type ComponentType, type MouseEvent, type ReactNode, useContext } from 'react'; +import type { Tokens } from 'marked'; +import { Link } from '@mui/material'; +import { SdkConfigAccess } from '@pega/auth/lib/sdk-auth-manager'; + +import { StreamingContext } from './StreamingContext'; +import { + type CoachPConnectGetter, + hasCaseIdentifierQueryParams, + parseCaseLink, + resolveCaseKeysFromLink, + resolveCaseOpenStrategy +} from './agent-inline-edit-utils'; + +/** + * Wrapper component that checks the streaming context and decides whether to hide the JSON marker token. + * Returns null for JSON marker tokens, falls back to default rendering for everything else. + */ +const CoachTextRenderer = ({ token }: { token: Tokens.Text }) => { + const streamingContext = useContext(StreamingContext); + + if ( + token?.text.startsWith('###') && + ((streamingContext?.isStreamingMessage && streamingContext.isStreamingInProgress) || + (token.text.includes('followUpQuestions') && token.text.endsWith('###JSON_ENDS_HERE'))) + ) { + return null; + } + + // Return undefined signals to the parent that default rendering should be used, + // but since this is a component, we need to return the text as-is. + // The parent markdownMap function handles the fallback. + return <>{token?.text}; +}; + +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; + } +}; + +// The agent links cases to the Pega portal of the Infinity server the application uses. The host name is compared, as +// the protocol and port can differ behind a proxy; a relative link can only point to that server. +const isInfinityServerLink = (href: string): boolean => { + if (!/^[a-z][a-z\d+.-]*:/i.test(href) && !href.startsWith('//')) { + return true; + } + + try { + const { infinityRestServerUrl } = SdkConfigAccess.getSdkConfigServer(); + + return new URL(href, window.location.origin).hostname.toLowerCase() === new URL(infinityRestServerUrl).hostname.toLowerCase(); + } catch { + return false; + } +}; + +const getLastPathSegments = (url: string, count: number): string[] => { + try { + return new URL(url, window.location.origin).pathname + .split('/') + .filter(Boolean) + .slice(-count) + .map(segment => decodeURIComponent(segment)); + } catch { + return []; + } +}; + +type LinkedCase = { insKey: string; className: string }; + +// The work ID with which routes are resolved: only a route with a work ID token returns it, unlike the application's +// root URL, to which a payload that matches no route resolves. +const PROBE_WORK_ID = 'sdk-probe-work-id'; + +/** The class group of a case type class, by the App Studio convention `--Work-`. */ +const getClassGroup = (className: string): string | undefined => { + const segments = className.split('-'); + const workIndex = segments.map(segment => segment.toLowerCase()).lastIndexOf('work'); + return workIndex > 0 ? segments.slice(0, workIndex + 1).join('-') : undefined; +}; + +/** The possible case key prefixes of a case type class: its parent classes, as named and in upper case. */ +const getKeyPrefixCandidates = (className: string): string[] => { + const segments = className.split('-'); + const candidates: string[] = []; + for (let length = segments.length - 1; length > 0; length -= 1) { + const classGroup = segments.slice(0, length).join('-'); + candidates.push(classGroup, classGroup.toUpperCase()); + } + return candidates; +}; + +type CaseType = { name: string; className: string }; + +/** + * The case types of the application: those of the environment info and, as the Quick Create widget reads them when the + * environment info has none, those the portal offers to create. + */ +const getCaseTypes = (): CaseType[] => { + const caseTypes: CaseType[] = []; + const addCaseType = (name: string | undefined, className: string | undefined) => { + if (className && !caseTypes.some(caseType => caseType.className === className)) { + caseTypes.push({ name: name ?? '', className }); + } + }; + + try { + PCore.getEnvironmentInfo() + .getCaseTypeList() + .forEach(caseType => addCaseType(caseType.pyWorkTypeName, caseType.pyWorkTypeImplementationClassName)); + } catch { + // The environment info has no case types. + } + + try { + const portal: { pyCaseTypesAvailableToCreate?: { pyLabel?: string; pyClassName?: string }[] } | undefined = PCore.createPConnect({ + options: { context: PCore.getConstants().APP.APP } + }) + .getPConnect() + .getValue('pyPortal'); + portal?.pyCaseTypesAvailableToCreate?.forEach(caseType => addCaseType(caseType.pyLabel, caseType.pyClassName)); + } catch { + // The portal has no case types. + } + + return caseTypes; +}; + +// The platform names a case type's route after the case type, in the plural ("New Service": `new-services`). +const isRouteOfCaseTypeName = (routeName: string, caseTypeName: string): boolean => { + const toToken = (value: string) => value.toLowerCase().replace(/[^a-z\d]/g, ''); + const name = toToken(caseTypeName); + return !!name && [name, `${name}s`, `${name}es`, `${name.replace(/y$/, 'i')}es`].includes(toToken(routeName)); +}; + +/** + * Whether the class of a case key (its first word) is one of the application's case types or a parent class of one, + * such as their class group. Other keys in links (of assignments or attachments, for example) are not cases. + */ +const isApplicationCaseKey = (insKey: string): boolean => { + const keyClass = insKey.trim().split(/\s+/)[0].toLowerCase(); + return getCaseTypes().some(({ className }) => `${className.toLowerCase()}-`.startsWith(`${keyClass}-`)); +}; + +/** + * Resolves a case's semantic URL (`…//`), the form in which the application's routing table links a + * case. The engine does not expose that lookup, so candidate route payloads are resolved with the public semantic URL + * utilities and compared with the link: + * - a route per case type names the case type class and the case key template (` {workID}`); + * - a generic case route (such as `cases/{workID}`) names only the case key template; + * - a single case route resolves for any payload, so the key prefix is the class group of the application's case types. + * When the routing table has no route for the link, the case type the route is named after is used. + */ +const resolveCaseFromSemanticURL = (routePath: string, workID: string): LinkedCase | undefined => { + // Work IDs are numbered; other paths (such as `…/create`) are not cases. + if (!/\d/.test(workID)) { + return undefined; + } + + const linkRoute = routePath.toLowerCase(); + + // The path segment of the case route a payload resolves to, if any. + const getCaseRoute = (payload: Record): string | undefined => { + try { + const semanticUrlUtils = PCore.getSemanticUrlUtils(); + const { ACTION_OPENWORKBYHANDLE } = semanticUrlUtils.getActions(); + const url = semanticUrlUtils.getResolvedSemanticURL(ACTION_OPENWORKBYHANDLE, payload, { workID: PROBE_WORK_ID }); + const [route, id] = getLastPathSegments(url, 2); + return route && id === PROBE_WORK_ID ? route.toLowerCase() : undefined; + } catch { + return undefined; + } + }; + const isLinkRoute = (payload: Record) => getCaseRoute(payload) === linkRoute; + + const caseTypes = getCaseTypes(); + + // A payload that no route has resolves to a route only when the routing table has a single route of this form. + if (getCaseRoute({ caseID: '' }) !== undefined) { + const classGroups = [...new Set(caseTypes.map(({ className }) => getClassGroup(className)).filter((group): group is string => !!group))]; + if (!isLinkRoute({ caseID: '' }) || classGroups.length !== 1) { + return undefined; + } + const keyPrefix = classGroups[0].toUpperCase(); + return { insKey: `${keyPrefix} ${workID}`, className: keyPrefix }; + } + + const caseType = + caseTypes.find(({ className }) => isLinkRoute({ caseClassName: className })) ?? + caseTypes.find(({ name }) => isRouteOfCaseTypeName(routePath, name)); + if (caseType) { + // The prefix of the route's case ID template; else, by convention, the class group in upper case, as case keys have it. + const keyPrefix = + getKeyPrefixCandidates(caseType.className).find(candidate => + isLinkRoute({ caseClassName: caseType.className, caseID: `${candidate} {workID}` }) + ) ?? getClassGroup(caseType.className)?.toUpperCase(); + return keyPrefix ? { insKey: `${keyPrefix} ${workID}`, className: caseType.className } : undefined; + } + + // As for links that carry the case key, the class name is the key prefix (the case type is read from the case). + const prefixes = new Set(caseTypes.flatMap(({ className }) => getKeyPrefixCandidates(className))); + const prefix = [...prefixes].find(candidate => isLinkRoute({ caseID: `${candidate} {workID}` })); + return prefix ? { insKey: `${prefix} ${workID}`, className: prefix } : undefined; +}; + +/** + * Resolves the case of the application a link points to, if it can be opened in the application. + * openWorkByHandle needs the case key (` `): either the link carries it, or the link is the case's + * semantic URL, which carries the work ID only. + */ +const resolveLinkedCase = (linkHref: string): LinkedCase | undefined => { + // Java URL encoders write the space of a case key as '+', which no case key or class name contains. + const href = linkHref.replace(/\+/g, '%20'); + if (!hasCaseIdentifierQueryParams(href) && !isInfinityServerLink(href)) { + return undefined; + } + + const parsed = parseCaseLink(href); + const fromLink = parsed ? resolveCaseKeysFromLink(parsed, href) : undefined; + const linkInsKey = fromLink?.insKey?.trim(); + + let linkedCase: LinkedCase | undefined; + if (fromLink?.className && linkInsKey && /\s/.test(linkInsKey)) { + if (!isApplicationCaseKey(linkInsKey)) { + return undefined; + } + linkedCase = { insKey: linkInsKey, className: fromLink.className }; + } else { + const [routePath, workID] = getLastPathSegments(href, 2); + linkedCase = routePath && workID ? resolveCaseFromSemanticURL(routePath, workID) : undefined; + } + + if (!linkedCase) { + return undefined; + } + + const strategy = resolveCaseOpenStrategy({ + appName: parsed?.appName ?? '', + caseTypeID: linkedCase.className, + caseReferenceID: linkedCase.insKey, + pegaServerUrl: parsed?.pegaServerUrl ?? '', + ...linkedCase + }); + + return strategy === 'native' ? linkedCase : undefined; +}; + +/** + * Link renderer: links open in a new tab, except links to cases of the application. + * @component + */ +const CoachLinkRenderer = ({ token, getPConnect, children }: { token: Tokens.Link; getPConnect?: CoachPConnectGetter; children?: ReactNode }) => { + const { href, text } = token; + // The rendered link text keeps its formatting (as in `[**T-1001**](…)`); the raw text is the fallback. + const content = children ?? text; + + // Links with other protocols (for example javascript:) are shown as plain text. + if (!isSafeHref(href)) { + return <>{content}; + } + + // Deviation from Constellation: a link to a case opens the case in the application, as the Pega portal + // it points to is outside the application. Modified clicks keep the browser behavior. + const handleClick = (e: MouseEvent) => { + if (!getPConnect || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { + return; + } + + let linkedCase: LinkedCase | undefined; + try { + linkedCase = resolveLinkedCase(href); + } catch (error) { + console.error(error); + } + if (!linkedCase) { + return; + } + + e.preventDefault(); + const { insKey, className } = linkedCase; + new Promise(resolve => { + resolve(getPConnect().getActionsApi().openWorkByHandle(insKey, className)); + }).catch((error: unknown) => { + // The engine rejects without an error when the user cancels, for example on the dialog about unsaved changes. + if (error === undefined) { + return; + } + // If the case cannot be opened in the application, the link opens as it would without the SDK. + console.error(error); + window.open(href, '_blank', 'noopener,noreferrer'); + }); + }; + + return ( + + {content} + + ); +}; + +/** Markdown overrides for GenAI coach */ +export const createAgentMarkdownMap = (options?: { getPConnect?: CoachPConnectGetter }) => { + const getPConnect = options?.getPConnect; + const LinkRenderer = ({ token, children }: { token: Tokens.Link; children?: ReactNode }) => ( + + {children} + + ); + + return { + // Deviation from Constellation: links are rendered by the SDK so that case links stay in the application. + link: () => LinkRenderer, + text: (token: Tokens.Text): ComponentType<{ token: Tokens.Text }> | undefined => { + // Only override for JSON marker tokens; + // It preserve the default renderer. + if (token?.text.startsWith('###')) { + return CoachTextRenderer; + } + return undefined; + } + }; +}; + +const agentMarkdownMap = createAgentMarkdownMap(); + +export default agentMarkdownMap; diff --git a/packages/react-sdk-components/src/components/helpers/message-stream-utils.ts b/packages/react-sdk-components/src/components/helpers/message-stream-utils.ts new file mode 100644 index 00000000..0fb439ea --- /dev/null +++ b/packages/react-sdk-components/src/components/helpers/message-stream-utils.ts @@ -0,0 +1,230 @@ +import type { ErrorResponse, MessageResponse, StreamResponse } from '../widget/GenAICoach/GenAICoach.types'; + +class MessageStreamError extends Error { + response: ErrorResponse['response']; + constructor(errorResponse: ErrorResponse['response']) { + super(); + this.response = errorResponse; + } +} + +// Local version of Constellation's `tryCatch` helper: the result of `fn`, or undefined if it throws. +const tryCatch = (fn: () => T): T | undefined => { + try { + return fn(); + } catch { + return undefined; + } +}; + +export const isErrorResponse = (e: unknown): e is ErrorResponse => { + return ( + typeof e === 'object' && + e !== null && + 'response' in e && + typeof e.response === 'object' && + e.response !== null && + 'data' in e.response && + typeof e.response.data === 'object' && + e.response.data !== null && + 'errorDetails' in e.response.data && + Array.isArray(e.response.data.errorDetails) + ); +}; + +const handleError = (errorHandler: ((error: ErrorResponse) => void) | undefined, eventData: string) => { + if (errorHandler) { + try { + const parsedError = JSON.parse(eventData); + errorHandler({ + response: { + data: { + errorDetails: [ + { + message: parsedError.errorMessage, + erroneousInputOutputFieldInPage: '', + erroneousInputOutputIdentifier: '', + errorClassification: '', + localizedValue: parsedError.errorMessage, + messageParameters: [] + } + ] + } + } + }); + } catch { + // If JSON parsing fails, use raw error data + errorHandler({ + response: { + data: { + errorDetails: [ + { + message: eventData, + erroneousInputOutputFieldInPage: '', + erroneousInputOutputIdentifier: '', + errorClassification: '', + localizedValue: eventData, + messageParameters: [] + } + ] + } + } + }); + } + } +}; + +/* The stream is of the format + ----------------- stream from the assistant service (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#examples) ----------- + event:message + \n + data:{content:"Hello"} + \n\n + event:message + \n + data:{content:"world"} + \n\n + ----------------- final response added by platform -------------------------------------------------------------------------------------------------------------- + {aiGuidedQuestions:[],messageID:"MSG-1234",response:"Hello world"} + */ +export const handleMessageStream = async ( + result: StreamResponse, + streamHandler?: ({ data, streaming }: { data: string; streaming: boolean }) => void, + errorHandler?: (error: ErrorResponse) => void +): Promise => { + const stream = result.data; + if (!stream) { + streamHandler?.({ data: '', streaming: false }); + return; + } + + // Fallback incase there is no stream to handle and the response is a JSON + const contentType = result?.headers?.['content-type']; + if (typeof stream.getReader !== 'function') { + // stream.getReader is unavailable – cannot process as a ReadableStream. + // For SSE responses, signal that no content was streamed so callers can + // fall back to their own handling; for all others, return the raw result. + if (typeof contentType === 'string' && contentType.startsWith('text/event-stream')) { + return undefined; + } + return result as MessageResponse; + } + + const reader: ReadableStreamDefaultReader = stream.getReader(); + const decoder = new TextDecoder(); + + try { + let completeResponse = ''; + let buffer = ''; // Buffer to accumulate incomplete chunks + + const processChunk = async (): Promise => { + const { done, value } = await reader.read(); + + if (done) { + let finalResponse: MessageResponse | undefined; + + // The agent stream ends with a metadata SSE event (timing / token telemetry). + // It carries no message content and no JSON blob follows it, so we return + // undefined here. callSendMessage will call updateMessagesWithResponse({ data: '' }) + // which sets allChunksReceived: true and clears the loading state. + if (/^event:\s*metadata/m.test(buffer)) { + return finalResponse; + } + + const jsonBoundary = buffer.indexOf('\n\n{'); + let rawJson: string | undefined; + if (jsonBoundary !== -1) { + rawJson = buffer.slice(jsonBoundary + 2); + } else if (buffer.trimStart().startsWith('{')) { + rawJson = buffer.trim(); + } + + if (rawJson) { + const json = rawJson; + // Try as-is first; if literal newline bytes appear inside a JSON string value, + // sanitize unescaped \r\n / \r / \n to the \\n escape sequence and retry. + const parsedResponse = tryCatch(() => JSON.parse(json)) ?? tryCatch(() => JSON.parse(json.replace(/(?) { const { children, + getPConnect, + coaches, + localeReference, layout = 'two-column', heading = '', message = '', @@ -32,11 +40,13 @@ export default function BannerPage(props: PropsWithChildren) { tintImage = false } = props; + const genAICoachProps = usePageGenAICoach(getPConnect, coaches, localeReference); + const childArray = useMemo(() => { return Children.toArray(children); }, [children]); - return ( + return withPageUtilities( ) { backgroundImage, tintImage }} - /> + />, + genAICoachProps ); } diff --git a/packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx b/packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx index dd43f405..f4da8c5c 100644 --- a/packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx +++ b/packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx @@ -8,6 +8,10 @@ import Grid2 from '@mui/material/Grid2'; import { Utils } from '../../helpers/utils'; import StoreContext from '../../../bridge/Context/StoreContext'; import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; +import useGenAICoachObj from '../../../hooks/useGenAICoachObj'; +import { getTabLabel } from '../SubTabs/tabUtils'; +import type { GenAICoach } from '../../widget/GenAICoach/GenAICoach.types'; +import type { State } from '../../designSystemExtension/GenAICoachContent/GenAICoach.types'; import type { PConnProps } from '../../../types/PConnProps'; interface CaseViewProps extends PConnProps { @@ -18,6 +22,8 @@ interface CaseViewProps extends PConnProps { showIconInHeader: boolean; caseInfo: any; lastUpdateCaseTime: any; + // Agents configured on the case type's case view (AI agent panel in the utilities column) + coaches?: GenAICoach[]; } const useStyles = makeStyles(theme => ({ @@ -41,6 +47,10 @@ const useStyles = makeStyles(theme => ({ width: theme.spacing(8), height: theme.spacing(8), padding: theme.spacing(1) + }, + tabWidget: { + marginRight: theme.spacing(1), + marginLeft: theme.spacing(1) } })); @@ -49,6 +59,7 @@ export default function CaseView(props: PropsWithChildren) { const CaseViewActionsMenu = getComponentFromMap('CaseViewActionsMenu'); const VerticalTabs = getComponentFromMap('VerticalTabs'); const DeferLoad = getComponentFromMap('DeferLoad'); + const GenAICoachContent = getComponentFromMap('GenAICoachContent'); const { getPConnect, @@ -56,6 +67,7 @@ export default function CaseView(props: PropsWithChildren) { header, subheader, children = [], + coaches = [], caseInfo: { availableActions = [], availableProcesses = [], hasNewAttachments, caseTypeID = '', caseTypeName = '', caseTypeIcon } } = props; const { lastUpdateCaseTime = getPConnect().getValue('caseInfo.lastUpdateTime') } = props; @@ -73,6 +85,16 @@ export default function CaseView(props: PropsWithChildren) { const localizationService = thePConn.getLocalizationService(); const localeCategory = 'CaseView'; + // AI agent panel (port of the Constellation case view's agent hosting): the conversation context is + // the data object (" ") or the full case ID. + const fullCaseID = thePConn.getValue(PCore.getConstants().CASE_INFO.CASE_INFO_ID); + const dataContent = thePConn.getValue(PCore.getConstants().DATA_INFO.DATA_INFO_CONTENT); + const contextID = dataContent ? `${dataContent.pxObjClass} ${dataContent.pyGUID}` : fullCaseID; + + // The SDK case view always shows its utilities column, so the conversation starts when the panel is maximized. + const coachProps = useGenAICoachObj(coaches.length ? coaches : undefined, contextID, getPConnect(), true, true); + const [genAIState, setGenAIState] = useState('minimized'); + /** * * @param inName the metadata name that will cause a region to be returned @@ -124,20 +146,41 @@ export default function CaseView(props: PropsWithChildren) { let { label, inheritedProps } = theTabCompConfig; // For some tabs, "label" property is not avaialable in theTabCompConfig, so will get them from inheritedProps if (!label) { - inheritedProps.forEach(inheritedProp => { + inheritedProps?.forEach(inheritedProp => { if (inheritedProp.prop === 'label') { label = inheritedProp.value; } }); } + // A widget placed directly in the tabs may have neither (the referenced view's label, or a placeholder, is shown). + if (!label) { + label = getTabLabel(tabComp.getPConnect()); + } // We'll display the tabs when either visibility property doesn't exist or is true(if exists) if (theTabCompConfig.visibility === undefined || theTabCompConfig.visibility === true) { vertTabInfo.push({ name: label, id: index }); - deferLoadInfo.push({ type: 'DeferLoad', config: theTabCompConfig }); + deferLoadInfo.push({ type: 'DeferLoad', config: theTabCompConfig, getPConnect: tabComp.getPConnect }); } }); } + // Tabs with a view name are loaded by DeferLoad. A tab without one is a widget placed directly in the Tabs + // region (such as an agent), so it renders its own component, as in Constellation. The widget draws its own card. + function getActiveTabContent() { + const activeTab = deferLoadInfo[activeVertTab]; + if (!activeTab) return null; + + if (activeTab.config.name) { + return ; + } + + return ( + + {activeTab.getPConnect().getComponent()} + + ); + } + function handleVerticalTabClick(eventDetail: any) { const theItem = parseInt(eventDetail.additionalData.itemClicked, 10); @@ -240,12 +283,26 @@ export default function CaseView(props: PropsWithChildren) { {theStagesRegion} {theTodoRegion} - {deferLoadInfo.length > 0 && ( - - )} + {getActiveTabContent()} - {theUtilitiesRegion} + + {theUtilitiesRegion} + {coachProps && ( + { + coachProps.onStateChange?.(state); + setGenAIState(state); + } + }} + /> + )} + ); } diff --git a/packages/react-sdk-components/src/components/template/DefaultPage/DefaultPage.tsx b/packages/react-sdk-components/src/components/template/DefaultPage/DefaultPage.tsx index 5115fd5b..56b84901 100644 --- a/packages/react-sdk-components/src/components/template/DefaultPage/DefaultPage.tsx +++ b/packages/react-sdk-components/src/components/template/DefaultPage/DefaultPage.tsx @@ -2,6 +2,8 @@ import { useMemo, Children } from 'react'; import type { ReactNode } from 'react'; import { Grid2 } from '@mui/material'; import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../utils'; +import type { GenAICoach } from '../../widget/GenAICoach/GenAICoach.types'; export interface CommonPageProps { /** Page title */ @@ -14,13 +16,13 @@ export interface CommonPageProps { children: ReactNode | ReactNode[]; /** Dynamic page pconnect object */ - // getPConnect: () => PConnect; + getPConnect: () => typeof PConnect; /** Enable GetNextWork in page */ enableGetNextWork?: boolean; /** GetAI coaches configured in page */ - // coaches?: GenAICoach[]; + coaches?: GenAICoach[]; /** Locale reference */ localeReference: string; @@ -64,6 +66,9 @@ const COLUMNS_WIDTHS = { export default function DefaultPage({ layout = 'one-column', children, + getPConnect, + localeReference, + coaches, enableBanner, heading = '', message = '', @@ -74,12 +79,14 @@ export default function DefaultPage({ }: DefaultPageProps) { const Banner = getComponentFromMap('Banner'); + const genAICoachProps = usePageGenAICoach(getPConnect, coaches, localeReference); + const childArray = useMemo(() => { return Children.toArray(children); }, [children]); if (enableBanner) { - return ( + return withPageUtilities( + />, + genAICoachProps ); } - return ( + return withPageUtilities( {childArray.map((child, index) => ( {child} ))} - + , + genAICoachProps ); } diff --git a/packages/react-sdk-components/src/components/template/InlineDashboardPage/InlineDashboardPage.tsx b/packages/react-sdk-components/src/components/template/InlineDashboardPage/InlineDashboardPage.tsx index 1a93bc9c..58029830 100644 --- a/packages/react-sdk-components/src/components/template/InlineDashboardPage/InlineDashboardPage.tsx +++ b/packages/react-sdk-components/src/components/template/InlineDashboardPage/InlineDashboardPage.tsx @@ -2,6 +2,8 @@ import { useMemo, Children, useEffect, useState, type PropsWithChildren } from ' import { buildFilterComponents } from '../../infra/DashboardFilter/filterUtils'; import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../utils'; +import type { GenAICoach } from '../../widget/GenAICoach/GenAICoach.types'; import type { PConnProps } from '../../../types/PConnProps'; interface InlineDashboardPageProps extends PConnProps { @@ -9,6 +11,9 @@ interface InlineDashboardPageProps extends PConnProps { title: string; icon?: string; filterPosition?: string; + // Agents configured on the page + coaches?: GenAICoach[]; + localeReference?: string; } export default function InlineDashboardPage(props: PropsWithChildren) { @@ -16,12 +21,14 @@ export default function InlineDashboardPage(props: PropsWithChildren { return Children.toArray(children); }, [children]); + const genAICoachProps = usePageGenAICoach(getPConnect, coaches, localeReference); + const allFilters = (getPConnect().getRawMetadata() as any).children[1]; useEffect(() => { @@ -35,5 +42,5 @@ export default function InlineDashboardPage(props: PropsWithChildren; + return withPageUtilities(, genAICoachProps); } diff --git a/packages/react-sdk-components/src/components/template/ListPage/ListPage.tsx b/packages/react-sdk-components/src/components/template/ListPage/ListPage.tsx index 88fb4da8..685db962 100644 --- a/packages/react-sdk-components/src/components/template/ListPage/ListPage.tsx +++ b/packages/react-sdk-components/src/components/template/ListPage/ListPage.tsx @@ -1,16 +1,24 @@ import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../utils'; +import type { GenAICoach } from '../../widget/GenAICoach/GenAICoach.types'; import type { PConnProps } from '../../../types/PConnProps'; interface ListPageProps extends PConnProps { // If any, enter additional props that only exist on this component parameters: object; + // Agents configured on the page + coaches?: GenAICoach[]; + localeReference?: string; } export default function ListPage(props: ListPageProps) { // Get emitted components from map (so we can get any override that may exist) const ListView = getComponentFromMap('ListView'); + const { getPConnect, coaches, localeReference } = props; + const genAICoachProps = usePageGenAICoach(getPConnect, coaches, localeReference); + // special case for ListView - add in a prop const listViewProps = { ...props, bInForm: false }; - return ; + return withPageUtilities(, genAICoachProps); } diff --git a/packages/react-sdk-components/src/components/template/NarrowWide/NarrowWidePage/NarrowWidePage.tsx b/packages/react-sdk-components/src/components/template/NarrowWide/NarrowWidePage/NarrowWidePage.tsx index c040519b..89b20e6f 100644 --- a/packages/react-sdk-components/src/components/template/NarrowWide/NarrowWidePage/NarrowWidePage.tsx +++ b/packages/react-sdk-components/src/components/template/NarrowWide/NarrowWidePage/NarrowWidePage.tsx @@ -1,5 +1,7 @@ import type { PropsWithChildren, ReactElement } from 'react'; import { getComponentFromMap } from '../../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../../utils'; +import type { GenAICoach } from '../../../widget/GenAICoach/GenAICoach.types'; import type { PConnProps } from '../../../../types/PConnProps'; interface NarrowWidePageProps extends PConnProps { @@ -7,6 +9,9 @@ interface NarrowWidePageProps extends PConnProps { title: string; templateCol: string; icon: string; + // Agents configured on the page + coaches?: GenAICoach[]; + localeReference?: string; } /* @@ -17,12 +22,15 @@ export default function NarrowWidePage(props: PropsWithChildren - + , + genAICoachProps ); } diff --git a/packages/react-sdk-components/src/components/template/OneColumn/OneColumnPage/OneColumnPage.tsx b/packages/react-sdk-components/src/components/template/OneColumn/OneColumnPage/OneColumnPage.tsx index 57018c77..f57399c3 100644 --- a/packages/react-sdk-components/src/components/template/OneColumn/OneColumnPage/OneColumnPage.tsx +++ b/packages/react-sdk-components/src/components/template/OneColumn/OneColumnPage/OneColumnPage.tsx @@ -1,8 +1,13 @@ import { getComponentFromMap } from '../../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../../utils'; +import type { GenAICoach } from '../../../widget/GenAICoach/GenAICoach.types'; import type { PConnProps } from '../../../../types/PConnProps'; interface OneColumnPageProps extends PConnProps { // If any, enter additional props that only exist on this component + // Agents configured on the page + coaches?: GenAICoach[]; + localeReference?: string; } /* @@ -13,5 +18,8 @@ export default function OneColumnPage(props: OneColumnPageProps) { // Get emitted components from map (so we can get any override that may exist) const OneColumn = getComponentFromMap('OneColumn'); - return ; + const { getPConnect, coaches, localeReference } = props; + const genAICoachProps = usePageGenAICoach(getPConnect, coaches, localeReference); + + return withPageUtilities(, genAICoachProps); } diff --git a/packages/react-sdk-components/src/components/template/TwoColumn/TwoColumnPage/TwoColumnPage.tsx b/packages/react-sdk-components/src/components/template/TwoColumn/TwoColumnPage/TwoColumnPage.tsx index 4ee12162..74227660 100644 --- a/packages/react-sdk-components/src/components/template/TwoColumn/TwoColumnPage/TwoColumnPage.tsx +++ b/packages/react-sdk-components/src/components/template/TwoColumn/TwoColumnPage/TwoColumnPage.tsx @@ -1,8 +1,13 @@ import { getComponentFromMap } from '../../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../../utils'; +import type { GenAICoach } from '../../../widget/GenAICoach/GenAICoach.types'; import type { PConnProps } from '../../../../types/PConnProps'; interface TwoColumnPageProps extends PConnProps { // If any, enter additional props that only exist on this component + // Agents configured on the page + coaches?: GenAICoach[]; + localeReference?: string; } /* @@ -13,5 +18,8 @@ export default function TwoColumnPage(props: TwoColumnPageProps) { // Get emitted components from map (so we can get any override that may exist) const TwoColumn = getComponentFromMap('TwoColumn'); - return ; + const { getPConnect, coaches, localeReference } = props; + const genAICoachProps = usePageGenAICoach(getPConnect, coaches, localeReference); + + return withPageUtilities(, genAICoachProps); } diff --git a/packages/react-sdk-components/src/components/template/WideNarrow/WideNarrowPage/WideNarrowPage.tsx b/packages/react-sdk-components/src/components/template/WideNarrow/WideNarrowPage/WideNarrowPage.tsx index ee86590e..78be88ac 100644 --- a/packages/react-sdk-components/src/components/template/WideNarrow/WideNarrowPage/WideNarrowPage.tsx +++ b/packages/react-sdk-components/src/components/template/WideNarrow/WideNarrowPage/WideNarrowPage.tsx @@ -1,5 +1,7 @@ import { Children, type PropsWithChildren } from 'react'; import { getComponentFromMap } from '../../../../bridge/helpers/sdk_component_map'; +import { usePageGenAICoach, withPageUtilities } from '../../utils'; +import type { GenAICoach } from '../../../widget/GenAICoach/GenAICoach.types'; import type { PConnProps } from '../../../../types/PConnProps'; interface WideNarrowPageProps extends PConnProps { @@ -7,6 +9,9 @@ interface WideNarrowPageProps extends PConnProps { title: string; templateCol?: string; icon?: string; + // Agents configured on the page + coaches?: GenAICoach[]; + localeReference?: string; } /* @@ -17,12 +22,15 @@ export default function WideNarrowPage(props: PropsWithChildren - + , + genAICoachProps ); } diff --git a/packages/react-sdk-components/src/components/template/utils.tsx b/packages/react-sdk-components/src/components/template/utils.tsx index de3dc29a..c96ef14d 100644 --- a/packages/react-sdk-components/src/components/template/utils.tsx +++ b/packages/react-sdk-components/src/components/template/utils.tsx @@ -1,5 +1,11 @@ import type { ReactNode } from 'react'; import { isValidElement } from 'react'; +import { Box } from '@mui/material'; + +import { getComponentFromMap } from '../../bridge/helpers/sdk_component_map'; +import useGenAICoachObj from '../../hooks/useGenAICoachObj'; +import type { GenAICoach } from '../widget/GenAICoach/GenAICoach.types'; +import type { UtilitiesLayoutProps } from '../designSystemExtension/GenAICoachContent/GenAICoach.types'; export function prepareCaseSummaryData(caseSummaryRegion, portalSpecificVisibilityChecker?) { const filterVisibleChildren = children => { @@ -56,3 +62,28 @@ export const filterUtilities = (utils: ReactNode) => { } return utilsMeta; }; + +/** + * Agent props for the agents configured on a landing page. As in the Constellation page templates, the page's locale + * reference is the conversation context. + */ +export const usePageGenAICoach = (getPConnect: () => typeof PConnect, coaches: GenAICoach[] = [], localeReference = '') => { + return useGenAICoachObj(coaches.length ? coaches : undefined, localeReference, getPConnect()); +}; + +/** + * Renders a landing page with its utilities column at the end, as Constellation's page templates do with their + * `utilities` slot; below the md breakpoint the column follows the page. A page without agents is returned unchanged. + */ +export const withPageUtilities = (page: ReactNode, genAICoachProps?: UtilitiesLayoutProps['genAICoachProps']) => { + if (!genAICoachProps) return page; + + const UtilitiesLayout = getComponentFromMap('UtilitiesLayout'); + // A gap separates the page and its utilities column, as in Constellation. + return ( + + {page} + + + ); +}; diff --git a/packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.tsx b/packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.tsx new file mode 100644 index 00000000..b4201c5c --- /dev/null +++ b/packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.tsx @@ -0,0 +1,82 @@ +import { getComponentFromMap } from '../../../bridge/helpers/sdk_component_map'; +import useGenAICoachObj from '../../../hooks/useGenAICoachObj'; +import type { GenAICoachContentProps } from '../../designSystemExtension/GenAICoachContent/GenAICoach.types'; +import type { PConnProps } from '../../../types/PConnProps'; + +import type { GenAICoach as GenAICoachConfig } from './GenAICoach.types'; + +interface GenAICoachProps extends PConnProps { + // If any, enter additional props that only exist on this component + coaches?: GenAICoachConfig[]; +} + +export default function GenAICoach(props: GenAICoachProps) { + // Get emitted components from map (so we can get any override that may exist) + const GenAICoachContent = getComponentFromMap('GenAICoachContent'); + + const { getPConnect, coaches = [] } = props; + + let contextID = ''; + const dataContent = getPConnect().getValue(PCore.getConstants().DATA_INFO.DATA_INFO_CONTENT); + if (getPConnect().getCaseSummary().ID) { + contextID = getPConnect().getValue(PCore.getConstants().CASE_INFO.CASE_INFO_ID); + } else if (dataContent) { + contextID = `${dataContent.pxObjClass} ${dataContent.pyGUID}`; + } else { + const classID = getPConnect().getValue('pyPortal.classID'); + const viewName = getPConnect().getCurrentView(); + contextID = `${classID}!PAGE!${viewName}`.toUpperCase(); + } + const genAICoachObj = useGenAICoachObj(coaches, contextID, getPConnect()); + if (genAICoachObj) { + const { + loading, + messages, + coachOptions, + onCoachChange, + onSend, + onOpen, + initialSuggestedMessages, + suggestions, + error, + salutation, + disclaimerMessage, + guidedMode, + actions, + conversationHistory, + onLayoutChange, + onAddAttachment, + attachments, + attachmentsError, + toastMessage, + onToastClose + }: Partial = genAICoachObj; + + return ( + + ); + } + return null; +} diff --git a/packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.types.ts b/packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.types.ts new file mode 100644 index 00000000..3da39913 --- /dev/null +++ b/packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.types.ts @@ -0,0 +1,141 @@ +import type { ConversationHistoryProps, FileDisplayProps, GenAIMessageProps } from '../../designSystemExtension/GenAICoachContent/GenAICoach.types'; + +// ─── Engine types (declared locally; not in @pega/pcore-pconnect-typedefs 4.1) ─ + +export type Prompt = + | { + pxObjClass: string; + pyInstructions: string; + pyPrompt: string; + } + | { + '@class': string; + instructions: string; + prompt: string; + }; + +type MessageResponseForCoach = { + data: string; +}; + +type MessageResponseForAgent = { + data: { + messageID: string; + response: string; + aiGuidedQuestions?: Prompt[]; + }; +}; + +export type MessageResponse = MessageResponseForAgent | MessageResponseForCoach; + +/** The parts of an HTTP response the stream handling reads (the engine returns an Axios response). */ +export interface StreamResponse { + data: any; + headers?: Record; + status?: number; +} + +type CoachMetaData = { + ID: string; + response: string; + suggestedPrompts: Prompt[]; + welcomeMessage?: string; + disclaimerMessage?: string; + initialInstruction: string; + initialAdditionalInstruction?: string; + assistantMode?: string; + messageID?: string; + aiGuidedQuestions?: Prompt[]; + enableTracer?: boolean; + supportedCapabilities?: { + stream?: { + isEnabled: boolean; + }; + }; + recommendationMessages?: RecommendationMessage[]; +}; +export type RecommendationMessage = { + pyRole: 'ASSISTANT' | 'USER'; + pyContent: string; + pyMessageID: string; +}; +export type ConversationMessage = { + content: string; + createdOn: string; + isLiked: boolean | null; + role: 'USER' | 'ASSISTANT'; + messageID: string; + aiGuidedQuestions: Prompt[]; + attachments?: FileDisplayProps[]; +}; + +export type GetMessagesResponse = { + data: { + createdOn: string; + updatedOn: string; + id: string; + name: string; + messages: ConversationMessage[]; + }; +}; + +export type HistoryResponse = { + createdOn: string; + updatedOn: string; + id: string; + name: string; + title: string; +}; + +export type ConversationResponse = { + data: CoachMetaData; +}; + +export type CoachData = { + id: string; + data: CoachMetaData; + type: string; + conversations: { + [key: string]: { messages: GenAIMessageProps[] } | null; + }; + latestConversationId: string; + history: ConversationHistoryProps['data']; +}; + +export type ErrorResponse = { + name?: string; + message?: string; + response: { + data: { + errorDetails: { + message: string; + erroneousInputOutputFieldInPage: string; + erroneousInputOutputIdentifier: string; + errorClassification: string; + localizedValue: string; + messageParameters: string[]; + }[]; + }; + }; +}; + +export type GenAICoach = { + type: 'GenAICoachObject' | 'AIAgentObject'; + config: { + coach: { + classID: string; + insName: string; + label: string; + type: string; + } | null; + visibility?: boolean; + }; +}; + +export type AttachmentMeta = { + fileName: string; + ID: string; + id: string; + mimeType: string; + extension: string; +}; diff --git a/packages/react-sdk-components/src/components/widget/GenAICoach/config-ext.json b/packages/react-sdk-components/src/components/widget/GenAICoach/config-ext.json new file mode 100644 index 00000000..b9a208bb --- /dev/null +++ b/packages/react-sdk-components/src/components/widget/GenAICoach/config-ext.json @@ -0,0 +1,8 @@ +{ + "name": "GenAICoach", + "label": "Agent", + "description": "Agent", + "type": "Widget", + "subtype": "CASE", + "properties": [] +} diff --git a/packages/react-sdk-components/src/components/widget/GenAICoach/index.tsx b/packages/react-sdk-components/src/components/widget/GenAICoach/index.tsx new file mode 100644 index 00000000..8e9f9db6 --- /dev/null +++ b/packages/react-sdk-components/src/components/widget/GenAICoach/index.tsx @@ -0,0 +1 @@ +export { default } from './GenAICoach'; diff --git a/packages/react-sdk-components/src/hooks/useGenAICoachObj.ts b/packages/react-sdk-components/src/hooks/useGenAICoachObj.ts new file mode 100644 index 00000000..ca0ac8be --- /dev/null +++ b/packages/react-sdk-components/src/hooks/useGenAICoachObj.ts @@ -0,0 +1,1492 @@ +import { useState, useCallback, useRef, useEffect, useMemo } from 'react'; +import download from 'downloadjs'; + +import { copyToClipboard, createUID, isCoachMessage, isMenuGroupProps } from '../components/designSystemExtension/GenAICoachContent/GenAICoach.utils'; +import type { + ActionsProps, + CoachMessageProps, + ConversationHistoryProps, + FileDisplayProps, + FileItemProps, + GenAIMessageProps, + MenuGroupProps, + MenuItemProps, + MenuItems, + MessageProps, + Reaction, + SendMessageProps, + State, + UserMessageProps +} from '../components/designSystemExtension/GenAICoachContent/GenAICoach.types'; +import type { + AttachmentMeta, + CoachData, + ConversationMessage, + ConversationResponse, + ErrorResponse, + GenAICoach, + GetMessagesResponse, + HistoryResponse, + MessageResponse, + Prompt, + StreamResponse +} from '../components/widget/GenAICoach/GenAICoach.types'; +import { validateMaxSize } from '../components/helpers/attachmentShared'; +import { fileDownload } from '../components/widget/Attachment/AttachmentUtils'; +import { handleMessageStream } from '../components/helpers/message-stream-utils'; +import { createAgentMarkdownMap } from '../components/helpers/agent-markdown-renderers'; + +const localeCategory = 'GenAICoach'; + +const isApiResponseMsg = (message: ConversationMessage | GenAIMessageProps): message is ConversationMessage => { + return 'content' in message && 'createdOn' in message && 'role' in message; +}; + +function isResponseWithID(response: unknown): response is { ID?: string } { + return ( + typeof response === 'object' && response !== null && ('ID' in response ? typeof response.ID === 'string' || response.ID === undefined : true) + ); +} + +function isResponseWithStringData(response: unknown): response is { data: string } { + return typeof response === 'object' && response !== null && 'data' in response && typeof response.data === 'string'; +} + +const normalizeErrorResponse = (error: unknown, localizationService: { getLocalizedText: (key: string) => string }): ErrorResponse => { + if ( + typeof error === 'object' && + error !== null && + 'response' in error && + typeof error.response === 'object' && + error.response !== null && + 'data' in error.response && + typeof error.response.data === 'object' && + error.response.data !== null && + 'errorDetails' in error.response.data && + Array.isArray(error.response.data.errorDetails) && + error.response.data.errorDetails.length > 0 && + typeof error.response.data.errorDetails[0]?.localizedValue === 'string' + ) { + return error as ErrorResponse; + } + + const errorMessage = error instanceof Error ? error.message : undefined; + const localizedValue = errorMessage || localizationService.getLocalizedText('Something went wrong. Try again.'); + + return { + response: { + data: { + errorDetails: [ + { + message: localizedValue, + erroneousInputOutputFieldInPage: '', + erroneousInputOutputIdentifier: '', + errorClassification: '', + localizedValue, + messageParameters: [] + } + ] + } + } + }; +}; + +const isStreamResponse = (sendMessageResponse: MessageResponse | StreamResponse): sendMessageResponse is StreamResponse => { + const headers = (sendMessageResponse as StreamResponse)?.headers; + if (typeof sendMessageResponse !== 'object' || sendMessageResponse === null || typeof headers !== 'object' || headers === null) { + return false; + } + const contentType = headers['content-type']; + return typeof contentType === 'string' && contentType.startsWith('text/event-stream'); +}; + +const groupByUpdatedOn = (input: HistoryResponse[], pConnect: typeof PConnect): ConversationHistoryProps['data'] => { + const now = new Date(); + const today = now.toISOString().split('T')[0]; + + const lastSevenDays = new Date(); + lastSevenDays.setDate(now.getDate() - 7); + + const lastMonth = new Date(); + lastMonth.setDate(now.getDate() - 30); + + const groupsMap: Map = new Map(); + + input.forEach(item => { + const itemDate = new Date(item.updatedOn); + const itemDateString = itemDate.toISOString().split('T')[0]; + + let groupKey = ''; + + if (itemDateString === today) { + groupKey = pConnect.getLocalizationService().getLocalizedText('Today'); + } else if (itemDate >= lastSevenDays) { + groupKey = pConnect.getLocalizationService().getLocalizedText('Previous 7 Days'); + } else if (itemDate >= lastMonth) { + groupKey = pConnect.getLocalizationService().getLocalizedText('Previous 30 Days'); + } else { + const currentYear = now.getFullYear(); + const itemYear = itemDate.getFullYear(); + + if (itemYear === currentYear) { + const monthName = itemDate.toLocaleString('default', { month: 'long' }); + groupKey = monthName; + } else { + groupKey = itemYear.toString(); + } + } + + if (!groupsMap.has(groupKey)) { + groupsMap.set(groupKey, []); + } + + groupsMap.get(groupKey)?.push(item); + }); + + // Prepare final output array + const result: ConversationHistoryProps['data'] = []; + let sectionId = 1; + + for (const [section, items] of groupsMap.entries()) { + result.push({ + section, + id: sectionId.toString(), + conversations: items.map(item => ({ id: item.id, title: item.title })) + }); + + sectionId += 1; + } + + return result; +}; + +const getMappedValue = (value: string) => { + return PCore.getEnvironmentInfo().getKeyMapping(value) ?? value; +}; + +// This custom hook returns the data needed to render the Gen AI Coach widget. +const useGenAICoachObj = ( + coaches: undefined | GenAICoach[], + caseID: string, + pConnect: typeof PConnect, + isCaseView: boolean = false, + utilitiesExpanded: boolean = false +) => { + const pageSize = 20; + const localizedVal = PCore.getLocaleUtils().getLocaleValue; + const [initialSuggestedMessages, setInitialSuggestedMessages] = useState([]); + const [messages, setMessages] = useState([]); + const [conversationID, setConversationID] = useState(''); + const [enableStreaming, setEnableStreaming] = useState(false); + const [loading, setLoading] = useState(false); + const [prompts, setPrompts] = useState([]); + const [suggestions, setSuggestions] = useState([]); + const [error, setError] = useState(''); + const [salutation, setSalutation] = useState(undefined); + const [disclaimerMessage, setDisclaimerMessage] = useState(undefined); + const [guidedMode, setGuidedMode] = useState(true); + // Shown briefly by the panel in a snackbar. + const [toastMessage, setToastMessage] = useState(''); + + const [showHistory, setShowHistory] = useState(false); + const [selectedItemInHistory, setSelectedItemInHistory] = useState(''); + const [historyLoading, setHistoryLoading] = useState(false); + const [historyError, setHistoryError] = useState(''); + const pageIndexRef = useRef(1); + const fullHistoryFetched = useRef(false); + const [historyResp, setHistoryResp] = useState([]); + const inFullPage = useRef(false); + + const cancelCreateConversationTokenSource = useRef([]); + const cancelGetConversationsTokenSource = useRef([]); + const cancelGetMessagesTokenSource = useRef([]); + const GUIDED = 'Guided'; + const AGENT = 'agent'; + const DELIMITER = '##'; + const ASSISTANT_MODE = 'assistantMode'; + const promptKey = getMappedValue('pyPrompt') as keyof Prompt; + + const markdownMap = useMemo(() => createAgentMarkdownMap({ getPConnect: () => pConnect }), [pConnect]); + + const handleCopyResponse = async (response: string) => { + const copied = await copyToClipboard(response); + setToastMessage(localizedVal(copied ? 'Copied to clipboard' : 'Failed to copy', localeCategory)); + }; + + const buildMessageActions = (response: string, messageActions?: ActionsProps): ActionsProps => ({ + ...messageActions, + items: [ + { + id: 'copy-response', + text: localizedVal('Copy', localeCategory), + icon: 'copy', + onClick: () => handleCopyResponse(response) + }, + ...(messageActions?.items.filter(({ id }) => id !== 'copy-response') ?? []) + ] + }); + + // Setting the attachment object. + const [attachments, setAttachments] = useState([]); + const [attachmentsError, setAttachmentsError] = useState(''); + const uploadedFile = useRef>({}); + const l11nService = pConnect.getLocalizationService(); + const UPLOAD_COMPLETE = 100; + + // The 4.1 typings do not declare these engine methods. + const { + createConversation, + sendMessage, + createConversationForAgent, + sendMessageForAgent, + likeAgentMessage, + unLikeAgentMessage, + getConversations, + getConversationsForAgent, + getMessages, + getMessagesForAgent + } = PCore.getGenAIAssistantUtils() as any; + const { isRequestCanceled } = PCore.getRestClient() as any; + + // Function to create the ID + const createCoachId = (name: string, type: string) => `${name}${DELIMITER}${type}`; + + // Function to split the ID back into name and type + const splitCoachId = (id: string) => { + const [name, type] = id.split(DELIMITER); + return { name, type }; + }; + + const getSelectedCoach = (coachID = '') => { + const coachesData = pConnect.getValue('genAICoach.coaches'); + const currentCoachInfo = pConnect.getValue('genAICoach.currentCoach'); + const selectedCoach = coachesData?.find((coach: CoachData) => coach.id === (coachID || currentCoachInfo?.assistantID)); + + return { + selectedCoach, + coachesData, + currentCoachInfo + }; + }; + + // This method formats the coaches as needed for the component and also stores the coaches data in Redux. + const buildCoachOptions = useCallback((coachesList: GenAICoach[] | undefined) => { + const filterCoaches = (genAICoaches: GenAICoach[] | undefined) => { + return genAICoaches?.filter(e => e.config.coach !== null && (!('visibility' in e.config) || e.config.visibility === true)) || []; + }; + + const mappedCoaches: MenuItems = []; + const filteredCoaches = filterCoaches(coachesList); + + filteredCoaches.forEach((item: GenAICoach, index: number) => { + const coachConfig = item.config.coach; + if (coachConfig) { + mappedCoaches.push({ + id: createCoachId(coachConfig.insName, coachConfig.type), + primary: coachConfig.label, + selected: index === 0 + }); + } + }); + + // Deviation from Constellation: hosts without agents make no engine-store writes, so they behave as before. + if (!coachesList) return mappedCoaches; + + // Updates Redux with the coaches data. + pConnect.updateState({ + genAICoach: { + coaches: filteredCoaches.map((item: GenAICoach) => { + const coachConfig = item.config.coach; + if (!coachConfig) return null; + return { + id: createCoachId(coachConfig.insName, coachConfig.type), + type: coachConfig.type, + latestConversationId: '', + data: {}, + conversations: {}, + history: [] + }; + }) + } + }); + return mappedCoaches; + }, []); + + const [coachOptions, setCoachOptions] = useState(() => buildCoachOptions(coaches)); + const [activeCoach, setActiveCoach] = useState(coachOptions[0]); + const fetchNewHistory = useRef>( + coachOptions.reduce>((acc, item) => { + acc[item.id] = false; + return acc; + }, {}) + ); + + // Deviation from Constellation: the panel renders the history from state (see getHistoryData). + const groupedHistory = useMemo(() => groupByUpdatedOn(historyResp, pConnect), [historyResp]); + + useEffect(() => { + if (!coaches) return; + const { selectedCoach, coachesData } = getSelectedCoach(activeCoach?.id); + // Updates the messages in redux + pConnect.updateState({ + genAICoach: { + coaches: + coachesData?.map((e: CoachData) => { + if (e.id === activeCoach?.id && selectedCoach.latestConversationId) { + return { + ...e, + conversations: { + ...e.conversations, + [selectedCoach.latestConversationId]: { + ...e.conversations[selectedCoach.latestConversationId], + messages + } + } + }; + } + return e; + }) || [] + } + }); + }, [messages]); + + useEffect(() => { + if (!coaches) return; + const { selectedCoach } = getSelectedCoach(activeCoach?.id); + pConnect.updateState({ + genAICoach: { + currentCoach: { + assistantID: selectedCoach?.id, + conversationID: selectedCoach?.latestConversationId, + isAgent: selectedCoach?.type === AGENT + } + } + }); + }, [activeCoach]); + + useEffect(() => { + if (!coaches) return; + const { currentCoachInfo, coachesData } = getSelectedCoach(); + const assistantID = currentCoachInfo?.assistantID; + + if (assistantID) { + pConnect.updateState({ + genAICoach: { + coaches: coachesData.map((e: CoachData) => { + if (e.id === assistantID) { + return { + ...e, + history: groupedHistory + }; + } + return e; + }) + } + }); + } + }, [groupedHistory]); + + useEffect(() => { + if (attachments.some(att => att.error)) { + setAttachmentsError(l11nService.getLocalizedText(attachments[0]?.error ?? '')); + } else if (attachments.length > 0 && attachments.every(att => att.progress === UPLOAD_COMPLETE)) { + setAttachmentsError(''); + } + }, [attachments]); + + if (!coaches) return; + + // Returns an object containing the error message. + if (coaches.length === 0) { + return { + loading: false, + messages: [], + coachOptions: [], + onCoachChange: () => {}, + onSend: () => {}, + onOpen: () => {}, + initialSuggestedMessages: [], + suggestions: undefined, + error: l11nService.getLocalizedText('Agent configuration is incomplete. Kindly associate the required Agent rules.'), + onStateChange: isCaseView ? () => {} : undefined, + guidedMode: true + }; + } + + if (coaches.some(e => e.config.coach !== null && (!('visibility' in e.config) || e.config.visibility === true))) { + // This method clears the error messages from the top of the page. + const clearErrorMessages = () => { + PCore.getMessageManager().clearMessages({ + type: 'error', + category: 'HTTP', + context: pConnect.getContextName() + } as any); + }; + + // This method resets all global states to their default values. + const resetGlobalStates = () => { + setMessages([]); + setInitialSuggestedMessages([]); + setPrompts([]); + setSuggestions([]); + setConversationID(''); + setError(''); + setSalutation(undefined); + setDisclaimerMessage(undefined); + }; + + // This method formats the suggestions as needed for the component. + const buildSuggestions = (suggestionsList: Prompt[], coach: MenuItemProps | MenuGroupProps = activeCoach) => { + setSuggestions([ + { + id: coach.id, + label: !isMenuGroupProps(coach) ? coach.primary : '', + items: suggestionsList.map((item: Prompt) => { + return { + id: createUID(), + primary: item[promptKey] + }; + }) + } + ]); + setPrompts(suggestionsList); + // Sets the initial suggested messages to be displayed as quick-select questions. + setInitialSuggestedMessages( + suggestionsList.slice(0, 4).map((item: Prompt) => { + return { + id: createUID(), + message: item[promptKey] + }; + }) + ); + }; + + // Helper function to update active coach details. + const updateCurrentCoachDetails = (assistantID: string, chatID: string, type: string) => { + pConnect.updateState({ + genAICoach: { + currentCoach: { + assistantID, + conversationID: chatID, + isAgent: type === AGENT + } + } + }); + }; + + // This method handles the error response and stops the loader. + const handleErrorResponse = (err: ErrorResponse, inHistoryView?: boolean) => { + clearErrorMessages(); + if (!isRequestCanceled(err) && err?.response?.data?.errorDetails?.length > 0) { + const errorMessage = err.response.data.errorDetails[0].localizedValue; + if (inHistoryView) setHistoryError(errorMessage); + else setError(errorMessage); + } + if (!isRequestCanceled(err)) { + if (inHistoryView) setHistoryLoading(false); + else setLoading(false); + } + }; + + // Deviation from Constellation: a failed load without error details (such as a network error) still shows a message. + const handleLoadError = (err: unknown, inHistoryView?: boolean) => { + handleErrorResponse(isRequestCanceled(err) ? (err as ErrorResponse) : normalizeErrorResponse(err, l11nService), inHistoryView); + }; + + // Downloads the file using the attachment utils and file download utility. + const downloadFile = (ID: string, name: string): void => { + const attachmentUtils = PCore.getAttachmentUtils(); + const contextName = pConnect.getContextName(); + + attachmentUtils + .downloadAttachment(ID, contextName, '') + .then((content: unknown) => { + if (isResponseWithStringData(content)) { + fileDownload(content.data, name, null, (content as { headers?: Record }).headers ?? {}); + } + }) + .catch(err => { + handleErrorResponse(err); + }); + }; + + // update latest conversation id for a coach, for switching between coaches to go to last coach + const updateLatestConversationIdForCoach = (assistantID: string, chatID: string, coachesData: CoachData[]) => { + pConnect.updateState({ + genAICoach: { + coaches: coachesData.map((e: CoachData) => { + if (e.id === assistantID) { + return { + ...e, + latestConversationId: chatID + }; + } + return e; + }) + } + }); + }; + + const handleHistoryData = (response: { data: { conversations: HistoryResponse[] } }, loadMore: boolean) => { + const items = (response.data?.conversations ?? []).map(item => { + return { + ...item, + title: item.name + }; + }); + if (items.length === 0 || items.length < pageSize) { + fullHistoryFetched.current = true; + } + + if (loadMore) { + setHistoryResp((prev: HistoryResponse[]) => [...prev, ...items]); + } else { + setHistoryResp(items); + } + + setHistoryLoading(false); + }; + + const updateHistoryData = (loadMore?: boolean) => { + const { + currentCoachInfo: { assistantID }, + selectedCoach + } = getSelectedCoach(); + + if (!loadMore && fetchNewHistory.current[assistantID]) { + fullHistoryFetched.current = false; + pageIndexRef.current = 1; + } + + // Deviation from Constellation: gate on the history held in state, which is what the panel shows. + if (!fullHistoryFetched.current && (historyResp.length === 0 || loadMore || fetchNewHistory.current[assistantID])) { + fetchNewHistory.current[assistantID] = false; + setHistoryLoading(true); + const assistantIDSendInAPI = splitCoachId(assistantID).name; + + if (selectedCoach.type !== AGENT) { + getConversations( + assistantIDSendInAPI, + caseID, + pageSize, + pageIndexRef.current, + pConnect.getContextName(), + cancelGetConversationsTokenSource.current + ) + .then(response => { + handleHistoryData(response, loadMore ?? false); + }) + .catch(err => { + handleLoadError(err, true); + }); + } else { + getConversationsForAgent( + assistantIDSendInAPI, + caseID, + pageSize, + pageIndexRef.current, + pConnect.getContextName(), + cancelGetConversationsTokenSource.current + ) + .then(response => { + handleHistoryData(response, loadMore ?? false); + }) + .catch(err => { + handleLoadError(err, true); + }); + } + } + }; + + // Helper function to update messages with feedback + const updateMessageFeedback = (id: MessageProps['id'], reaction: Reaction | undefined) => { + clearErrorMessages(); + setMessages(prevData => { + return prevData.map((message: GenAIMessageProps) => { + if (isCoachMessage(message) && message.id === id) { + return { + ...message, + feedback: { + reaction, + onReaction: handleReaction, + onFeedbackComplete: handleFeedback + } + }; + } + return message; + }); + }); + }; + + // This method records a like for a specific coach message. + const handleReaction = (id: MessageProps['id'], reaction: Reaction | undefined) => { + const { + currentCoachInfo: { assistantID, conversationID: currentConversationID } + } = getSelectedCoach(); + fetchNewHistory.current[assistantID] = true; + + if (reaction === 'liked') { + const assistantIDSendInAPI = splitCoachId(assistantID).name; + likeAgentMessage(assistantIDSendInAPI, currentConversationID ?? conversationID, id, pConnect.getContextName()) + .then(() => updateMessageFeedback(id, reaction)) + .catch(() => updateMessageFeedback(id, undefined)); + } else { + updateMessageFeedback(id, reaction); + } + }; + + // This method records feedback for an unlike scenario related to a specific coach message. + const handleFeedback = (id: MessageProps['id'], comment = '') => { + const { + currentCoachInfo: { assistantID, conversationID: currentConversationID } + } = getSelectedCoach(); + const assistantIDSendInAPI = splitCoachId(assistantID).name; + unLikeAgentMessage(assistantIDSendInAPI, currentConversationID ?? conversationID, id, pConnect.getContextName(), comment).catch(() => + updateMessageFeedback(id, undefined) + ); + }; + + // This method builds the coach suggestions. + const buildCoachSuggestions = (coachSuggestions: string[]) => { + return coachSuggestions.map((suggestion: string) => { + return { + id: createUID(), + message: suggestion + }; + }); + }; + + // This method builds the messages and updates the state. + const updateMessages = ( + message: string, + isUser: boolean, + isLoading: boolean, + coachSuggestions: string[] = [], + coach: MenuItemProps | MenuGroupProps = activeCoach, + messageID: string = '', + attachmentIds?: string[] + ) => { + const { + currentCoachInfo: { isAgent } + } = getSelectedCoach(); + + const files: FileDisplayProps[] = []; + attachmentIds?.forEach((id: string) => { + const attachment = attachments.find(item => item.id === id); + if (attachment) { + files.push({ + id, + // Constellation's lightbox is not ported: a sent attachment is downloaded, from the file the user selected + // (the ID of an upload is not an attachment key, so the server cannot return it yet). + onPreview: attachment.file ? () => download(attachment.file as File, attachment.name) : undefined, + displayText: attachment.name, + value: attachment.name, + format: attachment.format + }); + } + }); + if (isUser) { + const messageObject: UserMessageProps = { + id: messageID || createUID(), + from: 'user', + message, + attachments: files + }; + + setMessages((res: GenAIMessageProps[]) => [...res, messageObject]); + } else if (!isMenuGroupProps(coach)) { + const messageObject: CoachMessageProps = { + id: isAgent ? messageID : createUID(), + from: 'coach', + message, + loading: isLoading, + coachName: coach.primary ?? '', + markdownMap, + messageActions: buildMessageActions(message) + }; + if (isAgent) { + messageObject.suggestions = buildCoachSuggestions(coachSuggestions); + messageObject.feedback = { + reaction: undefined, + onReaction: handleReaction, + onFeedbackComplete: handleFeedback + }; + } + setMessages((res: GenAIMessageProps[]) => [...res, messageObject]); + } + }; + + // Updates the state with the response from the conversation API / redux. + const updateCoachDetails = (result: CoachData) => { + setConversationID(result.latestConversationId); + const selectedCoach = coachOptions.find((e: MenuItemProps | MenuGroupProps) => e.id === result.id); + setSalutation(result.data.welcomeMessage || undefined); + setDisclaimerMessage(result.data.disclaimerMessage || undefined); + // Checks if guided mode is active, based on the presence of 'assistantMode' in the response. + setGuidedMode(result.data[ASSISTANT_MODE] === GUIDED); + setEnableStreaming(!!result.data.supportedCapabilities?.stream?.isEnabled); + const suggestedPrompts = result.data?.suggestedPrompts ?? []; + if (suggestedPrompts.length > 0) buildSuggestions(suggestedPrompts, selectedCoach); + // Checks if there are messages and updates the messages for new coach. + const reduxData = result.conversations?.[result.latestConversationId]?.messages || []; + if (reduxData.length === 0) { + setMessages([]); + } else { + // Updates the messages for an existing coach. + setMessages( + reduxData.map(message => + isCoachMessage(message) + ? { + ...message, + messageActions: buildMessageActions(message.message ?? '', message.messageActions) + } + : message + ) + ); + } + }; + + const handleFetchMessagesForConversation = ( + assistantID: string, + conversationId: string, + coachesData: CoachData[], + selectedCoach: CoachData, + currentConversationID: string, + data: (ConversationMessage | GenAIMessageProps)[], + fromAPI?: boolean + ) => { + setLoading(false); + if (currentConversationID === conversationId) return; + + updateLatestConversationIdForCoach(assistantID, conversationId, coachesData); + setConversationID(conversationId); + updateCurrentCoachDetails(assistantID, conversationId, selectedCoach.type); + + if (data.length === 0) { + let updatedCoachesData = getSelectedCoach().coachesData; + if (fromAPI) { + updatedCoachesData = coachesData.map((e: CoachData) => { + if (e.id === assistantID) { + return { + ...e, + conversations: { + ...e.conversations, + [conversationId]: { + messages: [] + } + } + }; + } + return e; + }); + + pConnect.updateState({ + genAICoach: { + coaches: updatedCoachesData + } + }); + } + + const updatedSelectedCoach = updatedCoachesData?.find((e: CoachData) => e.id === assistantID); + if (updatedSelectedCoach) { + updateCoachDetails(updatedSelectedCoach); + } + } else { + const updatedMessages = data.map(item => { + let messageObject: UserMessageProps | CoachMessageProps; + const { + currentCoachInfo: { isAgent } + } = getSelectedCoach(); + if (isApiResponseMsg(item)) { + if (item.role === 'USER') { + const attachmentsWithFormat = (item.attachments as (FileDisplayProps & AttachmentMeta)[])?.map(att => ({ + ...att, + format: att.extension + })); + + messageObject = { + id: createUID(), + from: 'user', + message: item.content, + attachments: attachmentsWithFormat?.map(attachment => ({ + id: attachment.id, + name: attachment.fileName, + // Constellation's lightbox is not ported: the attachment is downloaded. + onPreview: () => { + downloadFile(attachment.ID || attachment.id, attachment.fileName); + }, + displayText: attachment.fileName, + value: attachment.fileName, + format: attachment.extension + })) + }; + } else { + const updateReaction = () => { + if (item.isLiked === null) return; + return item.isLiked ? 'liked' : 'disliked'; + }; + + messageObject = { + id: item.messageID, + from: 'coach', + message: item.content, + coachName: !isMenuGroupProps(activeCoach) ? activeCoach.primary : '', + enableStreaming: false, + markdownMap, + messageActions: buildMessageActions(item.content) + }; + if (isAgent) { + messageObject.suggestions = buildCoachSuggestions((item.aiGuidedQuestions ?? []).map((question: Prompt) => question[promptKey])); + messageObject.feedback = { + reaction: updateReaction(), + onReaction: handleReaction, + onFeedbackComplete: handleFeedback + }; + } + } + } else { + messageObject = item; + if (item.from === 'coach') { + messageObject = { + ...item, + enableStreaming: false, + messageActions: buildMessageActions(item.message ?? '', item.messageActions) + }; + + if (isAgent) { + messageObject.feedback = { + reaction: item.feedback?.reaction, + onReaction: handleReaction, + onFeedbackComplete: handleFeedback + }; + } + } + } + + return messageObject; + }); + + setMessages(updatedMessages || []); + + const updatedCoachesData = getSelectedCoach().coachesData; + const updatedSelectedCoach = updatedCoachesData?.find(({ id }: CoachData) => id === assistantID); + + if (updatedSelectedCoach) { + setGuidedMode(updatedSelectedCoach.data[ASSISTANT_MODE] === GUIDED); + } + } + }; + + const fetchMessagesForConversation = (conversationId: string) => { + const { + coachesData, + currentCoachInfo: { conversationID: currentConversationID, assistantID }, + selectedCoach + } = getSelectedCoach(); + const assistantIDSendInAPI = splitCoachId(assistantID).name; + setAttachments([]); + setError(''); + setSelectedItemInHistory(conversationId); + setLoading(true); + + if (selectedCoach && Object.keys(selectedCoach.conversations).length > 0 && selectedCoach.conversations?.[conversationId]) { + const reduxData = selectedCoach.conversations[conversationId].messages; + handleFetchMessagesForConversation(assistantID, conversationId, coachesData, selectedCoach, currentConversationID, reduxData || []); + } else if (selectedCoach.type !== AGENT) { + getMessages(assistantIDSendInAPI, conversationId, pConnect.getContextName(), cancelGetMessagesTokenSource.current) + .then((response: GetMessagesResponse) => { + handleFetchMessagesForConversation( + assistantID, + conversationId, + coachesData, + selectedCoach, + currentConversationID, + response.data.messages || [], + true + ); + }) + .catch((err: unknown) => handleLoadError(err)); + } else { + getMessagesForAgent(assistantIDSendInAPI, conversationId, pConnect.getContextName(), cancelGetMessagesTokenSource.current) + .then((response: GetMessagesResponse) => { + handleFetchMessagesForConversation( + assistantID, + conversationId, + coachesData, + selectedCoach, + currentConversationID, + response.data.messages || [], + true + ); + }) + .catch((err: unknown) => handleLoadError(err)); + } + }; + + // Deviation from Constellation: only a complete answer (all chunks received) stops loading. Here the messages remount + // (fullscreen, minimize and maximize, history), and a remounted earlier answer reports that it is complete again; + // in Constellation they never remount. + const handleStreamingProgress = (isStreamingDone: boolean) => { + if (isStreamingDone) { + setMessages(currentMessages => { + const lastMessage = currentMessages.at(-1); + if (!lastMessage || !isCoachMessage(lastMessage) || !lastMessage.loading || !lastMessage.allChunksReceived) { + return currentMessages; + } + return currentMessages.map((message, index) => (index === currentMessages.length - 1 ? { ...message, loading: false } : message)); + }); + } + }; + + // This method updates the state with the response from the send message API. + const updateMessagesWithResponse = ( + result: MessageResponse, + reqAssistantID: string, + reqConversationID: string, + streaming?: boolean, + enableStream: boolean = enableStreaming + ) => { + const { + currentCoachInfo: { assistantID }, + coachesData, + selectedCoach + } = getSelectedCoach(); + fetchNewHistory.current[assistantID] = true; + const latestConversationID = selectedCoach.latestConversationId; + + if (assistantID !== reqAssistantID || latestConversationID !== reqConversationID) { + pConnect.updateState({ + genAICoach: { + coaches: coachesData.map((e: CoachData) => { + if (e.id === reqAssistantID) { + return { + ...e, + conversations: { + ...e.conversations, + [reqConversationID]: null + } + }; + } + return e; + }) + } + }); + } else { + const { data } = result; + setMessages((prevData: GenAIMessageProps[]) => { + return prevData.map((message: GenAIMessageProps) => { + if (isCoachMessage(message) && message.loading === true) { + if (typeof data !== 'string') { + const { messageID, response, aiGuidedQuestions = [] } = data; + const updatedMessage = streaming ? `${message.message || ''}${response}` : message.message || response; + + return { + ...message, + id: messageID, + message: updatedMessage, + messageActions: buildMessageActions(updatedMessage, message.messageActions), + suggestions: buildCoachSuggestions(aiGuidedQuestions.map((question: Prompt) => question[promptKey])), + loading: enableStream, + onStreamingUpdate: (isStreamingDone: boolean) => handleStreamingProgress(isStreamingDone), + allChunksReceived: !streaming, + enableStreaming: enableStream + }; + } + if (typeof data === 'string') { + const updatedMessage = streaming ? `${message.message || ''}${data}` : message.message || data; + + return { + ...message, + message: updatedMessage, + messageActions: buildMessageActions(updatedMessage, message.messageActions), + loading: enableStream, + onStreamingUpdate: (isStreamingDone: boolean) => handleStreamingProgress(isStreamingDone), + allChunksReceived: !streaming, + enableStreaming: enableStream + }; + } + } + return message; + }); + }); + } + }; + + // This method updates the message with error response and stops the loader. + const updateMessagesWithError = (err: ErrorResponse) => { + clearErrorMessages(); + if (err?.response?.data?.errorDetails?.length > 0) { + const errorMessage = err.response.data.errorDetails[0].localizedValue; + setMessages((prevData: GenAIMessageProps[]) => { + return prevData.map((message: GenAIMessageProps) => { + if (isCoachMessage(message) && message.loading === true) { + return { ...message, error: errorMessage, loading: false }; + } + return message; + }); + }); + } + }; + + const addUserMessage = ({ message, attachmentIds }: { message: string; attachmentIds?: string[] }) => { + // Append the attachment to coach conversation + updateMessages(message, true, false, [], activeCoach, '', attachmentIds ?? []); + // Generates an empty message with a loading icon until the coach's response is received. + updateMessages('', false, true); + // Clears the initial suggested messages to hide the quick-select questions. + setInitialSuggestedMessages([]); + }; + + const callSendMessage = async ({ + assistantID, + currentConversationID, + message, + coachType, + enableStream, + formattedAttachments + }: { + assistantID: string; + currentConversationID: string; + message: string; + coachType: string; + enableStream: boolean; + formattedAttachments?: { type: string; category: string; fileName: string; ID: string }[]; + }) => { + const assistantIDSendInAPI = splitCoachId(assistantID).name; + if (coachType !== AGENT) { + try { + let result: MessageResponse | StreamResponse = await sendMessage( + assistantIDSendInAPI, + currentConversationID, + message, + pConnect.getContextName(), + { + enableStreaming: enableStream + } + ); + if (enableStream && isStreamResponse(result)) { + const streamFinalResponse = await handleMessageStream(result, ({ data, streaming }) => + updateMessagesWithResponse({ data }, assistantID, currentConversationID, streaming, enableStream) + ); + if (streamFinalResponse && typeof streamFinalResponse.data === 'string') { + streamFinalResponse.data = ''; + result = streamFinalResponse; + } + } + updateMessagesWithResponse(result as MessageResponse, assistantID, currentConversationID, false, enableStream); + } catch (e) { + if (!(e instanceof Error && isRequestCanceled(e))) { + updateMessagesWithError(normalizeErrorResponse(e, l11nService)); + } + } + } else { + try { + let result: MessageResponse | StreamResponse = await sendMessageForAgent( + assistantIDSendInAPI, + currentConversationID, + message, + pConnect.getContextName(), + formattedAttachments, + { + enableStreaming: enableStream + } + ); + if (enableStream && isStreamResponse(result)) { + const streamFinalResponse = await handleMessageStream(result, ({ data, streaming }) => + updateMessagesWithResponse({ data }, assistantID, currentConversationID, streaming, enableStream) + ); + if (streamFinalResponse && typeof streamFinalResponse.data !== 'string') { + streamFinalResponse.data.response = ''; + result = streamFinalResponse; + updateMessagesWithResponse(result, assistantID, currentConversationID, false, enableStream); + } else { + // Agent streaming completed with no final JSON response (only SSE events). + // Use an empty string payload so the string branch in updateMessagesWithResponse + // is taken, which preserves the accumulated message content and existing message ID. + updateMessagesWithResponse({ data: '' }, assistantID, currentConversationID, false, enableStream); + } + } else { + updateMessagesWithResponse(result as MessageResponse, assistantID, currentConversationID, false, enableStream); + } + } catch (e) { + if (!(e instanceof Error && isRequestCanceled(e))) { + updateMessagesWithError(normalizeErrorResponse(e, l11nService)); + } + } + } + }; + + // Calls the Send Message API and updates the messages with the API response. + const onSend = async (item: SendMessageProps) => { + const isUploading = attachments.some(att => att.progress !== UPLOAD_COMPLETE); + if (isUploading) { + setAttachmentsError(l11nService.getLocalizedText('Please wait for the attachments to finish uploading.')); + return; + } + + const updatedMessage = item.message.trim(); + + const { + currentCoachInfo: { assistantID, conversationID: currentConversationID }, + selectedCoach + } = getSelectedCoach(); + + // Filter the attachments based on the selected item . + const filteredAttachments = + item?.attachmentIds && item.attachmentIds?.length ? attachments.filter(att => item.attachmentIds?.includes(att.id)) : []; + + // Formats the attachments to be sent in the API request. + const formattedAttachments = + filteredAttachments && filteredAttachments.length > 0 && item?.fromComposer + ? filteredAttachments.map(att => ({ + type: 'File', + category: 'File', + fileName: att.name, + ID: att.ID as string + })) + : []; + + addUserMessage({ message: updatedMessage, attachmentIds: item?.attachmentIds }); + + // Constructs the text using a combination of pyPrompt and pyInstructions, then makes an API call. + const instruction = + (prompts.length > 0 && + prompts.reduce((acc, obj) => { + const instructionsKey = getMappedValue('pyInstructions') as keyof Prompt; + if (obj[promptKey] === updatedMessage) { + acc = `${obj[promptKey]} ${obj[instructionsKey]}`; + } + return acc; + }, '')) || + updatedMessage; + + if (item?.fromComposer) setAttachments([]); + + callSendMessage({ + assistantID, + coachType: selectedCoach.type, + currentConversationID, + enableStream: enableStreaming, + formattedAttachments, + message: instruction + }); + }; + + // This method handles the conversation response and updates the state. + const handleConversationResponse = ( + result: ConversationResponse, + assistantID: string, + selectedCoachType: string, + showAgentRecommendations = false + ) => { + fetchNewHistory.current[assistantID] = true; + if (inFullPage.current) { + updateHistoryData(); + } + setSelectedItemInHistory(result.data.ID); + const coachesData = pConnect.getValue('genAICoach.coaches'); + pConnect.updateState({ + genAICoach: { + coaches: coachesData.map((e: CoachData) => { + if (e.id === assistantID) { + return { + ...e, + latestConversationId: result.data.ID, + data: result.data, + conversations: { + ...e.conversations, + [result.data.ID]: { + messages: [] + } + } + }; + } + return e; + }) + } + }); + resetGlobalStates(); + setLoading(false); + updateCurrentCoachDetails(assistantID, result.data.ID, selectedCoachType); + updateCoachDetails({ + id: assistantID, + latestConversationId: result.data.ID, + type: selectedCoachType, + data: result.data, + conversations: {}, + history: [] + }); + + const recommendationMessages = result.data.recommendationMessages ?? []; + if (showAgentRecommendations && recommendationMessages.length > 0) { + const selectedCoach = coachOptions.find(coach => coach.id === assistantID); + if (selectedCoach && !isMenuGroupProps(selectedCoach)) { + recommendationMessages.forEach(({ pyRole, pyContent, pyMessageID }) => { + updateMessages(pyContent, pyRole === 'USER', false, [], selectedCoach, pyMessageID); + }); + } + } else if (result.data.initialInstruction) { + addUserMessage({ message: result.data.initialInstruction }); + callSendMessage({ + assistantID, + currentConversationID: result.data.ID, + message: `${result.data.initialInstruction} ${result.data.initialAdditionalInstruction}`, + coachType: selectedCoachType, + enableStream: !!result.data.supportedCapabilities?.stream?.isEnabled + }); + } + }; + + // Calls the conversation API and updates the state. + const startConversation = (assistantID: string, newChat?: boolean) => { + // Retrieves the coaches data from Redux. + const { selectedCoach } = getSelectedCoach(assistantID); + const assistantIDSendInAPI = splitCoachId(assistantID).name; + // Checks if specified coach exists in Redux. If it does, it uses the existing data; otherwise, it calls the API and assigns the response. + // Deviation from Constellation: the cache is used only with its conversation. The engine store deep-merges arrays of the + // same length, so the reset in buildCoachOptions keeps a remounted host's configuration but clears its conversation ID. + if (!newChat && selectedCoach && Object.keys(selectedCoach.data).length > 0 && selectedCoach.latestConversationId) { + // Updates the state with redux data. + updateCurrentCoachDetails(selectedCoach.id, selectedCoach.latestConversationId, selectedCoach.type); + updateCoachDetails(selectedCoach); + } else { + setLoading(true); + if (selectedCoach.type !== AGENT) { + createConversation(caseID, assistantIDSendInAPI, pConnect.getContextName(), cancelCreateConversationTokenSource.current) + .then((result: ConversationResponse) => { + handleConversationResponse(result, assistantID, selectedCoach.type); + }) + .catch((err: unknown) => handleLoadError(err)); + } else { + createConversationForAgent(caseID, assistantIDSendInAPI, pConnect.getContextName(), cancelCreateConversationTokenSource.current, !newChat) + .then((result: ConversationResponse) => handleConversationResponse(result, assistantID, selectedCoach.type, !newChat)) + .catch((err: unknown) => handleLoadError(err)); + } + } + }; + + // Resets all state variables to their default values when the coach is changed. + const onCoachChange = (id: string) => { + // Checks if the currently active coach is selected again from the dropdown. + if (activeCoach.id === id) return; + setGuidedMode(true); + resetGlobalStates(); + setShowHistory(false); + + setHistoryError(''); + setHistoryLoading(false); + fullHistoryFetched.current = false; + pageIndexRef.current = 1; + + setSelectedItemInHistory(''); + // Updates the 'selected' property in the coach options array to reflect the newly selected coach. + const updatedCoachOptions = [...coachOptions].map((item: MenuItemProps | MenuGroupProps) => ({ + ...item, + selected: item.id === id + })); + setCoachOptions(updatedCoachOptions); + const coach = updatedCoachOptions.find((item: MenuItemProps | MenuGroupProps) => item.id === id); + if (coach) { + const { selectedCoach } = getSelectedCoach(coach.id); + updateCurrentCoachDetails(selectedCoach.id, selectedCoach.latestConversationId, selectedCoach.type); + setActiveCoach(coach); + setHistoryResp([]); + // Triggers the conversation API with the new coach ID. + startConversation(selectedCoach.id); + } + }; + + // This method triggers when the coach state in the utilities is changed. + const onStateChange = (state: State) => { + if (utilitiesExpanded && state === 'maximized') { + startConversation(activeCoach.id); + } + }; + + // This method triggers when the coach is mounted. + const onOpen = () => { + if (!utilitiesExpanded) { + startConversation(activeCoach.id); + } + }; + + // The AI tracer action is not ported. + const actions: ActionsProps = { + items: [ + { + id: 'new_chat', + text: l11nService.getLocalizedText('New chat'), + onClick: () => { + if (inFullPage.current) { + setHistoryError(''); + } else { + setShowHistory(false); + } + + setAttachments([]); + // create new conversation object + startConversation(activeCoach.id, true); + } + }, + { + id: 'view_history', + text: localizedVal('History', localeCategory), + onClick: () => { + if (!showHistory) { + setHistoryError(''); + setShowHistory(true); + updateHistoryData(); + } else setShowHistory(false); + } + } + ] + }; + + // Deviation from Constellation: render the history from state; its engine-store copy is written after the render and does not re-render this host. + const getHistoryData = () => groupedHistory; + + const onUploadProgress = (id: string, ev: { loaded: number; total: number }) => { + let progress: number = Math.floor((ev.loaded / ev.total) * UPLOAD_COMPLETE); + if (progress >= UPLOAD_COMPLETE) progress = 99; + setAttachments(localFiles => + localFiles.map(localFile => { + if (localFile?.id === id) { + return { + ...localFile, + inProgress: progress !== UPLOAD_COMPLETE, // true if not done, false if done + progress + }; + } + return localFile; + }) + ); + }; + + const onAddAttachment = (files: File[]) => { + const maxAttachmentSize = PCore.getEnvironmentInfo().getMaxAttachmentSize() || '3'; + + // The 4.1 typings declare a narrower file type than the engine accepts. + const attachmentUtils = PCore.getAttachmentUtils() as any; + + // Replace all existing attachments with new ones + setAttachments([]); + setAttachmentsError(''); + + const addedFiles: FileItemProps[] = files.map((file: File) => { + const fileID = createUID(); + const fileItem: FileItemProps = { + ID: fileID, + id: fileID, + name: file.name, + type: file.type, + createTime: file.lastModified, + format: file.name.split('.').pop(), + progress: 0, + inProgress: true, + onDelete: () => setAttachments(current => current.filter(f => f.id !== fileID)), + onCancel: () => setAttachments(c => c?.filter(f => f.id !== fileID)), + file + }; + + // Store the raw file for upload + uploadedFile.current[fileID] = file; + + // Validate file size + if (!validateMaxSize({ size: file.size }, maxAttachmentSize)) { + // Deviation from Constellation: the error is always set (the reference sets it only on an item that already has an error, so it was never shown). + fileItem.error = (l11nService as any).getLocalizedText('File is too big. Max allowed size is {1}MB.', [maxAttachmentSize]); + + return fileItem; + } + + // Upload valid file + attachmentUtils + .uploadAttachment( + uploadedFile.current[fileID], + (ev: { loaded?: number; total?: number }) => onUploadProgress(fileID, { loaded: ev.loaded ?? 0, total: ev.total ?? 1 }), + () => {}, + pConnect.getContextName() + ) + .then((fileResponse: unknown) => { + if (isResponseWithID(fileResponse)) { + const responseWithID = fileResponse; + if (responseWithID.ID) { + setAttachments(current => + current.map(att => (att.id === fileID ? { ...att, ID: responseWithID.ID, progress: UPLOAD_COMPLETE, inProgress: false } : att)) + ); + } + } + }) + .catch((err: Error) => { + setAttachments(current => + current.map(att => + att.id === fileID + ? { + ...att, + error: l11nService.getLocalizedText(err.message), + progress: UPLOAD_COMPLETE, + inProgress: false + } + : att + ) + ); + }); + + return fileItem; + }); + + // Add new attachments to state + setAttachments(addedFiles); + }; + + return { + loading, + enableStreaming, + messages, + coachOptions, + onCoachChange, + onSend, + onOpen, + initialSuggestedMessages, + suggestions, + error, + salutation, + disclaimerMessage, + guidedMode, + onStateChange: isCaseView ? onStateChange : undefined, + onLayoutChange: (inFullPageArg: boolean) => { + inFullPage.current = inFullPageArg; + }, + actions, + conversationHistory: showHistory + ? { + error: historyError || undefined, + loading: historyLoading, + data: getHistoryData(), + onDismiss: () => { + setShowHistory(false); + }, + onItemClick: (conversationId: string) => { + if (!inFullPage.current) setShowHistory(false); + fetchMessagesForConversation(conversationId); + }, + loadMore: () => { + // Deviation from Constellation: the next page follows from what is loaded, so a repeated call cannot skip a page. + pageIndexRef.current = Math.floor(historyResp.length / pageSize) + 1; + updateHistoryData(true); + }, + selectedItemId: selectedItemInHistory + } + : undefined, + onAddAttachment, + attachments, + attachmentsError, + toastMessage, + onToastClose: () => setToastMessage('') + }; + } + + return undefined; +}; + +export default useGenAICoachObj; diff --git a/packages/react-sdk-components/src/sdk-pega-component-map.js b/packages/react-sdk-components/src/sdk-pega-component-map.js index 860731e2..cab830d8 100644 --- a/packages/react-sdk-components/src/sdk-pega-component-map.js +++ b/packages/react-sdk-components/src/sdk-pega-component-map.js @@ -8,6 +8,7 @@ import ActionButtons from './components/infra/ActionButtons'; import ActionButtonsForFileUtil from './components/widget/FileUtility/ActionButtonsForFileUtil'; import AdvancedSearch from './components/template/AdvancedSearch'; +import AgentRichTextViewer from './components/designSystemExtension/AgentRichTextViewer'; import AlertBanner from './components/designSystemExtension/AlertBanner'; import AppAnnouncement from './components/widget/AppAnnouncement'; import AppShell from './components/template/AppShell/AppShell'; @@ -25,6 +26,7 @@ import CaseView from './components/template/CaseView'; import CaseViewActionsMenu from './components/template/CaseViewActionsMenu'; import Checkbox from './components/field/Checkbox'; import Confirmation from './components/template/Confirmation'; +import ConversationHistory from './components/designSystemExtension/ConversationHistory'; import Currency from './components/field/Currency'; import DashboardFilter from './components/infra/DashboardFilter'; import DataReference from './components/template/DataReference'; @@ -50,7 +52,13 @@ import FieldValueList from './components/designSystemExtension/FieldValueList'; import FileUtility from './components/widget/FileUtility/FileUtility'; import FlowContainer from './components/infra/Containers/FlowContainer'; import Followers from './components/widget/Followers'; +import GenAICoach from './components/widget/GenAICoach'; +import GenAICoachContent from './components/designSystemExtension/GenAICoachContent'; +import GenAIMessage from './components/designSystemExtension/GenAIMessage'; +import GenAIMessageFeedback from './components/designSystemExtension/GenAIMessageFeedback'; +import GenAIMessageProgress from './components/designSystemExtension/GenAIMessageProgress'; import Group from './components/field/Group'; +import InitialSuggestedMessage from './components/designSystemExtension/InitialSuggestedMessage'; import InlineDashboard from './components/template/InlineDashboard'; import InlineDashboardPage from './components/template/InlineDashboardPage/InlineDashboardPage'; import Integer from './components/field/Integer'; @@ -110,6 +118,7 @@ import TwoColumnPage from './components/template/TwoColumn/TwoColumnPage'; import TwoColumnTab from './components/template/TwoColumn/TwoColumnTab'; import URL from './components/field/URL'; import UserReference from './components/field/UserReference'; +import UtilitiesLayout from './components/designSystemExtension/UtilitiesLayout'; import VerticalTabs from './components/infra/VerticalTabs/VerticalTabs'; import View from './components/infra/View'; import ViewContainer from './components/infra/Containers/ViewContainer'; @@ -133,6 +142,7 @@ const pegaSdkComponentMap = { ActionButtons, ActionButtonsForFileUtil, AdvancedSearch, + AgentRichTextViewer, AlertBanner, AppAnnouncement, AppShell, @@ -150,6 +160,7 @@ const pegaSdkComponentMap = { CaseViewActionsMenu, Checkbox, Confirmation, + ConversationHistory, Currency, DashboardFilter, DataReference, @@ -175,7 +186,13 @@ const pegaSdkComponentMap = { FileUtility, FlowContainer, Followers, + GenAICoach, + GenAICoachContent, + GenAIMessage, + GenAIMessageFeedback, + GenAIMessageProgress, Group, + InitialSuggestedMessage, InlineDashboard, InlineDashboardPage, Integer, @@ -235,6 +252,7 @@ const pegaSdkComponentMap = { TwoColumnTab, URL, UserReference, + UtilitiesLayout, VerticalTabs, View, ViewContainer, diff --git a/scripts/override-constants.js b/scripts/override-constants.js index 862382fa..b46ea9f3 100644 --- a/scripts/override-constants.js +++ b/scripts/override-constants.js @@ -22,6 +22,7 @@ const sdkTopLevelContent = ['components_map']; const sdkComponentLocationMap = { ActionButtons: 'infra', ActionButtonsForFileUtil: 'widget/FileUtility/ActionButttonsForFileUtil', + AgentRichTextViewer: 'designSystemExtension', AlertBanner: 'designSystemExtension', AppAnnouncement: 'widget', AppShell: 'template', @@ -39,6 +40,7 @@ const sdkComponentLocationMap = { CaseViewActionsMenu: 'template', Checkbox: 'field', Confirmation: 'template', + ConversationHistory: 'designSystemExtension', Currency: 'field', DashboardFilter: 'infra', DataReference: 'template', @@ -61,6 +63,12 @@ const sdkComponentLocationMap = { FileUtility: 'widget/FileUtility/FileUtility', FlowContainer: 'infra/Containers', Followers: 'widget', + GenAICoach: 'widget', + GenAICoachContent: 'designSystemExtension', + GenAIMessage: 'designSystemExtension', + GenAIMessageFeedback: 'designSystemExtension', + GenAIMessageProgress: 'designSystemExtension', + InitialSuggestedMessage: 'designSystemExtension', InlineDashboard: 'template', InlineDashboardPage: 'template', Integer: 'field', @@ -110,6 +118,7 @@ const sdkComponentLocationMap = { TwoColumnTab: 'template/TwoColumn/TwoColumnTab', URL: 'field', UserReference: 'field', + UtilitiesLayout: 'designSystemExtension', VerticalTabs: 'infra/VerticalTabs', View: 'infra', ViewContainer: 'infra/Containers', diff --git a/specs/ENHANCEMENT-20664- AgentWidget/plan.md b/specs/ENHANCEMENT-20664- AgentWidget/plan.md new file mode 100644 index 00000000..6ffe5019 --- /dev/null +++ b/specs/ENHANCEMENT-20664- AgentWidget/plan.md @@ -0,0 +1,159 @@ +# Implementation Plan: AI Agent Experience in Case View and Application Pages (Infinity '25) + +**Branch**: `001-ai-agent-assistant` (feature directory name; the work is on `agent-poc-25`, created from `release/25`) | **Date**: 2026-11-02 | **Spec**: [spec.md](./spec.md) + +**Input**: Feature specification from `/specs/001-ai-agent-assistant/spec.md` + +## Summary + +Applications built with the React SDK's `release/25` line ignore the AI agents configured in Pega Infinity '25. This feature adds the agent experience where the '25 standard portal offers it: an agent panel in the case view's utilities column, agent widgets placed in a case's tabs or on a page, and the agents configured on landing pages (dashboards, lists and other pages), opened from a "Chat with AI" button in the page's utilities strip. + +Technical approach: +- Port the Constellation 25.1.5 agent implementation the way existing SDK components were ported from Constellation: names, logic and comments kept, Cosmos UI rebuilt with MUI, out-of-scope features left out (voice input, the AI tracer, the lightbox preview and the legacy `GenAICoachOld` widget). The MUI components built for the Infinity '26 port are reused and aligned with the '25 component contract. +- The engine's GenAI assistant API (`PCore.getGenAIAssistantUtils()` in the bundled engine 25.1.3; no engine work) is called directly, as the source does, with call-site casts where the 4.1 typings lag. Conversations are created when an agent opens, as in the '25 portal. Streamed answers are read as in the '25 source: `message` and `toolReasonEnd` events, then the final JSON with the message ID and follow-up questions. +- Formatted answers are parsed with `marked`, the parser the standard portal uses, and rendered as MUI elements, never as raw HTML. Links to cases of the application open inside the application. +- Session cache in the engine store through PConnect, as in the source. +- Host changes ported from the Constellation `CaseView` and page templates. + +## Terminology + +| Spec (user-facing) | Plan and code | +|---|---| +| Agent (agent or coach kind) | `GenAICoach` widget; coach option `type: 'agent' \| 'coach'`; answers are `from: 'coach'` messages | +| Agent panel in the case view | `GenAICoachContent` with `variant.placement: 'utilities'` | +| Expand / collapse the case view panel | Maximize / Minimize (`variant.state` `maximized` / `minimized`) | +| Agent placed on a page or in a case's tabs | `GenAICoach` widget with `variant.placement: 'fullpage'` | +| Page agent, "Chat with AI" | `UtilitiesLayout` with `genAICoachProps`; `usePageGenAICoach`, `withPageUtilities` | +| Ratings (like/dislike) | Feedback (`GenAIMessageFeedback`, `feedback`, `likeAgentMessage`/`unLikeAgentMessage`) | +| Copy an answer | Message action `copy-response` (`messageActions`); confirmation `toastMessage` | + +## Technical Context + +**Language/Version**: TypeScript (repository `tsconfig.json`); React 18.3 in the workspace (`release/25`), package peer range `^17.0 || ^18.0` + +**Primary Dependencies**: MUI v6 (`@mui/material` `^6.5.0`, `@mui/icons-material`, `@mui/styles` `makeStyles` as in sibling components); engine `@pega/constellationjs` 25.1.3 (`~25.1.3`, global `PCore`/`PConnect`); `@pega/pcore-pconnect-typedefs` 4.1.0 unchanged, with call-site casts where it lacks the assistant API; `@pega/auth` (`SdkConfigAccess`, already used by `helpers/utils.ts`); new: `marked ^15.0.6`. Source ported: `constellation-frontend` `release/25.1.5`, commit `59ee8ec177` + +**Storage**: No client persistence. Conversations, messages, ratings and attachments are stored by the platform; session cache in the engine store via `pConnect.updateState` under `genAICoach` + +**Testing**: Jest + Testing Library for units and components; Playwright for end-to-end flows against a 25.1.x server. The source's unit tests are to be ported; test tasks are developer-owned + +**Target Platform**: Evergreen desktop and mobile browsers (Fetch streams, `TextDecoder`); Pega Infinity 25.1.x server; React SDK default portal; embedded mode unaffected + +**Project Type**: Component library (`packages/react-sdk-components`, published as `@pega/react-sdk-components`; the overrides package is generated from it) + +**Performance Goals**: First streamed text no later than 1 s after the standard portal (SC-003); UI updates per network chunk while streaming + +**Constraints**: Engine APIs only, no HTTP (Constitution I); no changes outside `react-sdk-components`; ported code follows the repository's adaptation rules; backward compatible when no agents are configured (Constitution III); answers never rendered as raw HTML; the `release/25` dependency set (React 18) is kept + +**Scale/Scope**: One widget folder (`GenAICoach`), 8 registered design system extension components, one hook, four helpers, ten modified templates and two registration files: 27 new files (about 5,000 lines, mostly ported logic) and 14 changed files (+209/−25), including the `marked` dependency. The in-scope source is about 5,600 lines, of which about 730 are Cosmos styles that are not ported. 5 user stories (P1 × 1, P2 × 1, P3 × 3) + +### Deviations from Constellation + +Each is marked in the code with a `Deviation from Constellation:` comment. + +- Links to cases in answers open the case in the SDK application (`openWorkByHandle`) instead of the Pega portal. The case key comes from the link, or, for '25 links that carry only the work ID (`…//`), from the routing table and case types through public engine APIs; a key in a link counts only if its class belongs to the application's case types. Other links, and modified clicks, open in a new tab. +- Link text keeps its formatting (`[**N-1001**](…)`), where the Cosmos viewer shows the raw markdown. +- Hosts without agents make no engine-store writes, and the cached conversation is reused only with its conversation ID. +- History renders from hook state, its next page follows from what is loaded, and failed loads without error details still show a message. +- The "file too big" error is always shown. +- Only a complete last answer stops loading: the SDK panel remounts its messages (fullscreen, minimize and maximize, history), which Cosmos never does. +- Attachments: sent files are downloaded (the lightbox is not ported); a pending file can be previewed in a new tab only if its type cannot run scripts (not HTML or SVG). +- MUI equivalents of Cosmos features: the Copy confirmation in a snackbar, the agent avatar with the Material `AutoAwesome` icon in the theme's primary color (Constellation uses its `polaris-solid` icon and AI color), agents as cards like the other SDK widgets, and the '25 layout. + +### Open items + +- T027: an agent panel and an agent tab on the same case share one cached conversation slot in the engine store. +- T028: all header actions are in one Actions menu, where the '25 portal shows separate Minimize and Fullscreen buttons. +- T045: ratings on streamed answers that end without a final response cannot be sent (no message ID). + +## Constitution Check + +*GATE: Checked before the design and re-checked after it. The principles are those of the repository constitution (`.specify/memory/constitution.md` on `master`).* + +### Initial gate + +| Principle | Gate | Status | Evidence | +|---|---|---|---| +| I. Platform Boundary | No direct HTTP, no custom store, engine APIs only | PASS | Calls go through `PCore.getGenAIAssistantUtils()`, `getAttachmentUtils()` and `getSemanticUrlUtils()`; cache via `pConnect.updateState`. Engine-utility calls are treated as engine-provided access, as in the existing `CaseHistory`, `ListView`, `DataReference` and `Attachment` components; maintainers to confirm this reading of "independent data fetching" | +| II. Component Contracts | Standard props interface; every new component registered | PASS | `GenAICoach` and its 8 sub-components, named after the Constellation components they port, are registered in `sdk-pega-component-map.js` and `override-constants.js` and resolved with `getComponentFromMap`. Not a field component, so value propagation and display-mode delegation do not apply | +| III. Backward Compatibility | No prop removed or renamed; portal and embedded flows unchanged | PASS | Only optional additions (`CaseView` and page-template `coaches`/`localeReference`); nothing renders and nothing is written to the store without agents | +| IV. Infrastructure Protection | Bridge and containers unchanged | PASS | No bridge, container or infra component changes | +| V. Security | No secrets or URLs in source; no custom auth | PASS | Engine-managed auth and routing; the Infinity server URL is read from `sdk-config.json` at runtime; safe rendering | +| VI. Testing Standards | Unit and E2E tests planned; no coverage regression | PASS (planned, developer-executed) | Test tasks are developer-owned and open in tasks.md. The display-mode clause does not apply; see Complexity Tracking | +| VII. Spec and Plan Separation | spec.md technology-agnostic; plan has Complexity Tracking | PASS | spec.md names no tools, libraries or files; Complexity Tracking below | +| VIII. Minimal Change | Smallest effective change; existing patterns; no dead code | PASS | Only the in-scope source is ported; one new dependency; widget and design system extension patterns as in existing ports; review on 2026-11-02 found no unused code | +| IX. UX Consistency | Design-system controls; functional components only | PASS with one justified exception | MUI v6 throughout; hidden native file input, see Complexity Tracking | + +### Re-check after design + +All gates still PASS. The design keeps the engine boundary (no URLs or HTTP in the agent code), keeps host changes additive and inert without agents, and renders answers safely (no HTML is injected). No new violations were introduced. + +Re-checked on 2026-11-02 and 2026-11-04 after the code reviews of the implementation: the fixes (cache reuse only with its conversation, the guided Ask menu as in the '25 source, and the five findings of the 2026-11-04 review) do not affect a gate, nor do the open items. T027 is a behaviour gap inherited from the source and is planned as a fix. + +## Project Structure + +### Documentation (this feature) + +```text +specs/001-ai-agent-assistant/ +├── spec.md # Feature specification +├── plan.md # This file +└── tasks.md # Task list +``` + +### Source Code (repository root) + +```text +package.json # + marked +scripts/override-constants.js # + GenAICoach: 'widget'; agent components: 'designSystemExtension' +packages/react-sdk-components/ +├── package.json # + marked +├── src/ +│ ├── sdk-pega-component-map.js # + GenAICoach and its 8 design system components +│ ├── hooks/ +│ │ └── useGenAICoachObj.ts # NEW: port of dx utils/hooks/useGenAICoachObj.ts +│ └── components/ +│ ├── helpers/ +│ │ ├── message-stream-utils.ts # NEW: port of dx utils/message-stream-utils.ts +│ │ ├── StreamingContext.ts # NEW: from Cosmos GenAIMessage.tsx; read by the markdown renderers (in helpers so overrides share it) +│ │ ├── agent-markdown-renderers.tsx # NEW: port of dx utils/components/agent-markdown-renderers.tsx, plus the link renderer +│ │ └── agent-inline-edit-utils.ts # NEW: port of the 26.1.2 case-link utilities +│ ├── widget/GenAICoach/ # NEW: port of dx Widgets/GenAICoach +│ │ ├── index.tsx +│ │ ├── GenAICoach.tsx # widget: context ID, hook, full-page panel +│ │ ├── GenAICoach.types.ts # dx types; local engine type declarations +│ │ └── config-ext.json +│ ├── designSystemExtension/ # NEW: the Cosmos GenAICoach components (MUI), like WssQuickCreate for QuickCreate +│ │ ├── GenAICoachContent/ # Cosmos GenAICoach.tsx: header actions, empty state, messages, message box, history, fullscreen, toast +│ │ │ ├── GenAICoach.types.ts # Cosmos types; local Cosmos core type declarations +│ │ │ └── GenAICoach.utils.ts # Cosmos GenAICoach.utils.ts (with copyToClipboard) +│ │ ├── GenAIMessage/ # user and agent messages; suggestions; Copy action +│ │ ├── GenAIMessageProgress/ # cycling progress text +│ │ ├── GenAIMessageFeedback/ +│ │ ├── AgentRichTextViewer/ # marked tokens rendered as MUI elements +│ │ ├── InitialSuggestedMessage/ +│ │ ├── ConversationHistory/ # Back + "History" header +│ │ └── UtilitiesLayout/ # Cosmos UtilitiesLayout: landing-page utilities strip, "Chat with AI" button +│ └── template/ +│ ├── CaseView/CaseView.tsx # MODIFIED: hook and GenAICoachContent after the utilities region; widget tabs +│ ├── utils.tsx # MODIFIED: usePageGenAICoach and withPageUtilities +│ └── {DefaultPage,InlineDashboardPage,ListPage,BannerPage}/ and the One/Two-column, Narrow-wide and Wide-narrow page templates # MODIFIED: page agents +└── tests/ + ├── unit/hooks/ # developer-owned: hook tests + ├── unit/components/helpers/ # developer-owned: ported helper tests, case-link tests + ├── unit/components/widget/GenAICoach/ # developer-owned: ported widget tests + ├── unit/components/designSystemExtension/ # developer-owned: ported component tests + ├── unit/components/template/ # developer-owned: CaseView and page template tests + └── e2e/Agent/ # developer-owned: E2E suite for agent flows +``` + +**Structure Decision**: Single component-library structure, laid out the way existing SDK components were ported from Constellation: `dx-components` hooks go to `src/hooks/`, its utilities to `src/components/helpers/`, the widget to `components/widget/GenAICoach/`, and each Cosmos agent component becomes an MUI design system extension component in its own registered folder named after its source (`components/designSystemExtension//`), as the SDK's other Cosmos clones are (`WssQuickCreate`, rendered by the `QuickCreate` widget). Hosts change additively, ported from the Constellation templates: `CaseView` and the landing-page templates. No bridge, container or infra changes. + +## Complexity Tracking + +> **Fill ONLY if Constitution Check has violations that must be justified** + +| Violation | Why Needed | Simpler Alternative Rejected Because | +|-----------|------------|-------------------------------------| +| VI: "Unit tests MUST validate component rendering in both edit and display modes" does not apply | The agent widget has no read-only display mode; tests cover its interactive states instead (empty, loading, streaming, failed, history, ratings, attachments, copy) | Adding an artificial display mode would introduce behaviour the platform does not have | +| IX: "No raw HTML form controls" — a visually hidden native file input behind an MUI button | MUI has no file-picker control, and the browser file dialog requires an input element | The same pattern is already used by the Attachment and FileUtility widgets; an upload library would add a dependency without user value | diff --git a/specs/ENHANCEMENT-20664- AgentWidget/spec.md b/specs/ENHANCEMENT-20664- AgentWidget/spec.md new file mode 100644 index 00000000..3a3e9ead --- /dev/null +++ b/specs/ENHANCEMENT-20664- AgentWidget/spec.md @@ -0,0 +1,219 @@ +# Feature Specification: AI Agent Experience in Case View and Application Pages (Infinity '25) + +**Feature Branch**: `001-ai-agent-assistant` (feature directory name; branches are managed manually, and this work is on `agent-poc-25`) + +**Created**: 2026-11-02 + +**Status**: Draft + +**Input**: User description: "Bring the platform's AI agent experience to applications built with this SDK on the Pega Infinity '25 release line: agent conversations on cases, on application pages and in agent widgets, matching the agent experience of the standard portal for the same platform release." + +## Clarifications + +### Session 2026-10-28 + +- Q: Which platform release does this feature target? → A: Pega Infinity '25 (25.1.x). The reference experience is the standard portal of that release line; capabilities the '25 standard portal does not offer are not part of this feature. + +### Session 2026-11-02 + +- Q: Agent answers link to cases through the platform's own portal, which takes users out of the application. What should happen when such a link is selected? → A: The case opens inside the application. Other links still open in a new tab, and a modified click (for example to open a new tab) keeps the browser's behaviour. + +### Session 2026-11-03 + +- Q: The standard portal starts every agent reply with the agent's avatar, also while the reply is being generated. Should the application show it, and how should it look in the application's themes? → A: Yes. Every agent reply starts with the agent avatar, also while it is being generated and when it failed, and the avatar stays clearly visible in both the light and the dark theme of the application. +- Q: On pages the agent has no box around it, while the application's other widgets (such as announcements and the worklist) are shown in boxes. How should the agent appear? → A: Wherever it is placed on a page or in a case, the agent appears in the same kind of box as the application's other widgets, in both the light and the dark theme. +- Q: Side by side with the standard portal, the agent's spacing on pages looks off: it touches the utilities column, leaves empty space above the message box, and its welcome content sits at the top of tall panels. How should it be laid out? → A: As in the standard portal: before the first message, an agent on a page is only as tall as its content, with the message box right below the suggested prompts; in tall panels the welcome content is centered with the message box at the bottom; the utilities column is set apart from the page; the welcome heading is prominent and the suggested prompts are centered buttons in the application's accent color, where that color is readable. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Chat with an AI agent while working on a case (Priority: P1) + +A case worker opens a case whose case type has one or more AI agents configured. A collapsed agent panel is shown next to the case details. When the user expands it, the conversation starts and the panel shows the agent's welcome message and suggested prompts. The user types a question (or picks a suggestion), sees the answer appear progressively, can copy an answer, and can switch between agents when more than one is configured. + +**Why this priority**: The case view is where most agent configurations live and where users do their work. Without it, configured agents are invisible in SDK applications. This story alone is a usable MVP. + +**Independent Test**: Configure an agent on a case type's case view, open a case of that type in the SDK application, expand the panel, ask a question, and receive a progressively displayed answer. + +**Acceptance Scenarios**: + +1. **Given** a case type with a visible agent configured, **When** the user opens a case of that type, **Then** a collapsed agent panel showing the agent's name is available alongside the case details. +2. **Given** the collapsed panel, **When** the user expands it, **Then** a conversation starts for the case and the agent's welcome message and up to four suggested prompts are shown; if the agent has an initial instruction, it is sent as the user's first message. +3. **Given** the panel is open, **When** the user sends a message, **Then** the message appears immediately, a working indicator with changing status text is shown, and the answer appears progressively until it is complete (or all at once for agents that do not answer progressively). +4. **Given** an answer contains headings, lists, tables, code and links, **When** it is displayed, **Then** it is formatted for reading, nothing in the answer runs as active content, a link to a case of the application opens that case inside the application, and other links open in a new browser tab. +5. **Given** an answer is complete, **When** the user copies it, **Then** its text is copied and a short confirmation (or a failure note) is shown. +6. **Given** several agents are configured, **When** the user switches to another agent and later back, **Then** each agent shows its own conversation, and an answer still being generated for one agent never appears in another agent's conversation. +7. **Given** an agent configured for guided use, **When** the panel is shown, **Then** the user starts from the agent's predefined prompts and continues through an "Ask" menu of those prompts, without typing free text. +8. **Given** the agent has a disclaimer configured, **When** the conversation has messages, **Then** the disclaimer is shown above them; a notice that answers are AI-generated is always shown with the message input. +9. **Given** the panel is open, **When** the user chooses Fullscreen, **Then** the same conversation is shown full screen, and exiting returns to the panel with the conversation and any typed text unchanged. +10. **Given** an agent placed in the case's tabs, **When** the user selects that tab, **Then** the agent fills the tab and its conversation starts. +11. **Given** a case type with no agent configured, **When** the user opens a case of that type, **Then** the case screen looks and behaves exactly as before. +12. **Given** the application is set to another supported language, **When** the panel is shown, **Then** all labels around the conversation appear in that language. + +--- + +### User Story 2 - Use an agent on an application page (Priority: P2) + +Application pages such as dashboards, lists and other landing pages can have their own agents. On such a page, a "Chat with AI" button at the page's edge opens the agent next to it, so the user can ask about what the page shows while the page stays usable. The user can also expand the page's utilities area to keep the agent open beside the page. An agent can also be placed directly on a page, where it fills the space it is placed in. + +**Why this priority**: Pages are where users start their work, and page agents are configured the same way as case agents. Without this, agents configured on pages are silently missing from SDK applications. + +**Independent Test**: Configure an agent on a landing page (for example a dashboard), open the page in the SDK application, open the agent from the button and ask a question. + +**Acceptance Scenarios**: + +1. **Given** a page with a visible agent configured, **When** the user opens the page, **Then** a "Chat with AI" button is shown at the page's edge, and selecting it opens the agent next to the button with its welcome message and suggestions, while the page can still be scrolled and used. +2. **Given** the page agent is open, **When** the user closes it and opens it again while staying on the page, **Then** the conversation is still there. +3. **Given** the page agent is available, **When** the user expands the page's utilities area, **Then** the agent is shown beside the page and stays open while the user works on the page. +4. **Given** an agent placed directly on a page, **When** the page is shown, **Then** the agent fills its space and its conversation starts. +5. **Given** a page with no agent configured, **When** the user opens the page, **Then** it looks and behaves exactly as before. + +--- + +### User Story 3 - Revisit past conversations and start new ones (Priority: P3) + +Users can open a history of their previous conversations with the agent for the same case or page, grouped by recency, reopen one to continue, and start a new chat at any time. + +**Why this priority**: Valuable for continuity, but each conversation is useful on its own. + +**Independent Test**: Hold two conversations, open history, reopen the first one and continue it. + +**Acceptance Scenarios**: + +1. **Given** the user has past conversations, **When** they open history, **Then** past conversations for the current agent and context are listed newest first, grouped as Today, Previous 7 Days, Previous 30 Days, and then by month or year. +2. **Given** history is open, **When** the user reaches the end of the list, **Then** older conversations load. +3. **Given** history is open, **When** the user selects a past conversation, **Then** its messages, ratings and attachments are shown and the user can continue it. +4. **Given** history is open, **When** the user goes back, **Then** the current conversation is shown again. +5. **Given** a conversation is in progress, **When** the user starts a new chat, **Then** a new conversation with the welcome message and suggestions is shown and the previous conversation is available in history. + +--- + +### User Story 4 - Attach files to a message (Priority: P3) + +Users can attach a file to a message so the agent can use it, see its upload progress, preview it, and remove it before sending. + +**Why this priority**: Useful for document-driven tasks, but not needed for most conversations. + +**Independent Test**: Attach a file, send a message referencing it, and confirm the message shows the attachment. + +**Acceptance Scenarios**: + +1. **Given** the user attaches a file, **When** the upload is in progress, **Then** its progress is shown and the message cannot be sent until the upload completes, with a note explaining why. +2. **Given** a file is larger than the application allows, **When** the user attaches it, **Then** an error states the size limit and the file is not sent. +3. **Given** a file is attached, **When** the user previews or removes it before sending, **Then** the file opens for viewing, or is removed and not sent. +4. **Given** a sent message has attachments, **When** the user views the conversation, **Then** the attachments are listed with the message and can be downloaded. + +--- + +### User Story 5 - Rate agent answers (Priority: P3) + +Users can like or dislike an answer and, for a dislike, add an optional comment, helping administrators improve the agent. + +**Why this priority**: Improves agent quality over time but does not affect completing the user's task. + +**Independent Test**: Like one answer and dislike another with a comment, then reopen the conversation and see both ratings. + +**Acceptance Scenarios**: + +1. **Given** an answer is complete, **When** the user likes it, **Then** the like is recorded and shown as selected. +2. **Given** an answer is complete, **When** the user dislikes it, **Then** they can add an optional comment, and submitting or skipping the comment records the dislike. +3. **Given** a rated conversation, **When** the user reopens it from history, **Then** the ratings are shown. + +--- + +### Edge Cases + +- An agent widget is placed without any agent: it explains that the agent configuration is incomplete. Agents hidden through their visibility setting, and agents that cannot be resolved, are simply not shown. +- Starting a conversation fails, including when the platform cannot be reached or returns no details: the panel shows an understandable error instead of an empty conversation. +- An answer fails part-way: the partial answer stays with an error indicator and the user can send again. +- The agent does not support progressive answers: the complete answer appears when ready, with a working indicator in the meantime. +- The user switches agent while an answer is being generated: the answer never appears in another conversation, and the original conversation is loaded again from the platform when the user returns to it. +- Answers contain control content meant for the application (for example follow-up question data): it is never shown to the user, and any follow-up suggestions are offered as suggestions. +- Answers contain wide tables or long code: they scroll inside the message and the panel stays usable. +- Links in answers point to a case of the application: they open that case in the application. If the case cannot be opened there, the link opens in a new tab as in the standard portal. Other links open in a new tab. Unsafe link types are not clickable. +- An agent is shown again in the same context (for example the user returns to a case tab that holds an agent): a new conversation starts, and earlier conversations remain available in history. +- Two agent placements are on the same case or page (for example the case's agent panel and an agent placed in one of its tabs): each keeps its own conversation. +- The user's session expires during a conversation: the application's normal session-expiry handling applies and no message is sent twice. +- Narrow screens: the page agent follows the page content, and the fullscreen view covers the whole screen. +- Embedded (assignment-only) mode: no agent experience is shown and behaviour is unchanged. + +## Requirements *(mandatory)* + +### Functional Requirements + +**Availability and placement** + +- **FR-001**: System MUST show a collapsed agent panel in the case view when the case type has at least one visible agent configured, and MUST start the conversation when the user first expands it. +- **FR-002**: System MUST show an agent placed on a page or in a case's tabs in the space it is placed in, and MUST start its conversation when it is shown. +- **FR-003**: System MUST offer the agents configured on an application page (dashboards, lists and other landing pages) from a button at the page's edge that opens the agent next to it without blocking the page, MUST let users show the agent beside the page instead, and MUST keep the page's conversation while the user stays on the page. +- **FR-004**: System MUST show only agents configured as visible, and MUST leave screens unchanged when no agent is configured, in both full-portal and embedded modes. +- **FR-005**: Users MUST be able to switch between configured agents, and each agent MUST keep its own conversation for the session. + +**Conversations** + +- **FR-006**: System MUST link each conversation to its context (the open case, data record or page) so history and answers relate to the user's current work. +- **FR-007**: System MUST start a new conversation when an agent is first opened in a context, as the standard portal of this release does, and MUST send the agent's initial instruction, when it has one, as the user's first message. +- **FR-008**: System MUST show the agent's welcome message and up to four suggested prompts in an empty conversation, and the agent's disclaimer, when configured, above the messages. +- **FR-009**: System MUST display answers progressively as they are generated when the agent supports it, and as a whole otherwise, with a working indicator while the user waits. +- **FR-010**: System MUST offer the follow-up suggestions provided with the latest answer and MUST send a suggestion when it is selected. +- **FR-011**: For agents configured for guided use, System MUST limit input to the agent's predefined prompts. +- **FR-012**: System MUST display formatted answers (headings, emphasis, lists, tables, code, links), MUST NOT run or render active content contained in answers, MUST open links that point to a case of the application inside the application, and MUST open other links in a new tab. +- **FR-013**: System MUST hide control content embedded in answers from the user. +- **FR-014**: System MUST show understandable error messages when starting a conversation, sending a message, loading history or loading a conversation fails, including when the platform provides no error details. +- **FR-015**: System MUST show a notice that answers are AI-generated with the message input. +- **FR-016**: Users MUST be able to copy the text of an answer, and System MUST confirm whether copying succeeded. +- **FR-017**: Users MUST be able to show the conversation full screen and return to the panel without losing the conversation or the text they typed. + +**History** + +- **FR-018**: Users MUST be able to view past conversations for the current agent and context grouped by recency, load older ones on demand, and reopen one to continue it. +- **FR-019**: Users MUST be able to start a new chat at any time. + +**Attachments** + +- **FR-020**: Users MUST be able to attach a file to a message, see its upload progress, preview or remove it before sending, and download it from the sent message; a message MUST NOT be sent while an attachment is still uploading. +- **FR-021**: System MUST apply the application's maximum attachment size and MUST explain the limit when a file exceeds it. + +**Feedback** + +- **FR-022**: Users MUST be able to like or dislike an agent's answer, with an optional comment for a dislike. + +**Accessibility, language, layout and themes** + +- **FR-023**: All agent controls MUST be usable with a keyboard alone and labelled for assistive technologies, and new answers MUST be announced to screen-reader users. +- **FR-024**: All text the application shows around the conversation MUST follow the application's language settings. +- **FR-025**: The agent experience MUST remain usable on screens as narrow as a typical phone (320 pixels wide): the page agent follows the page content, and the fullscreen view covers the screen. +- **FR-026**: Each agent reply MUST start with the agent's avatar, as in the standard portal, also while the reply is being generated and when it failed, and the avatar MUST stay clearly visible in the application's light and dark themes. +- **FR-027**: Wherever an agent is shown on a page or in a case, it MUST appear in the same kind of box as the application's other widgets, spaced like them, in the application's light and dark themes. +- **FR-028**: The agent's layout MUST follow the standard portal's: before the first message an agent on a page MUST be only as tall as its content with the message box directly below the suggested prompts; in panels taller than their content the welcome content MUST be centered; the utilities column MUST be visibly separated from the page; and the suggested prompts MUST stay readable in the light and dark themes. + +### Key Entities *(include if feature involves data)* + +- **Agent**: An AI assistant configured in the application, with a display name, a kind (agent or coach) and visibility. When a conversation starts it also provides its welcome message, disclaimer, suggested prompts, whether it is guided, whether it answers progressively, and an optional initial instruction. +- **Context**: What the user is working on (a case, a data record or a page), to which conversations belong. +- **Conversation**: A dialogue between a user and an agent for one context, with a title, a last-updated time and ordered messages. +- **Message**: An entry in a conversation from the user or the agent, with formatted content, optional attachments, follow-up suggestions, a rating and a status (in progress, complete, failed). +- **Attachment**: A file attached to a message, with its name, size and upload status. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: In acceptance testing against a platform server of the target release, 100% of in-scope placements (every configured case-view agent, page agent and placed agent widget) are available to users in the SDK application. +- **SC-002**: For a reference set of at least 10 scenarios covering chat, guided use, suggestions, links, copying, history, new chat, attachments and ratings, the SDK application reaches the same outcome as the standard portal in 100% of scenarios, apart from the differences this specification records (case links open inside the application). +- **SC-003**: Users see an answer begin to appear no more than 1 second later than the same answer begins to appear in the standard portal. +- **SC-004**: Screens without agents show no visible or behavioural change, with 0 regressions in the existing case and page acceptance checks. +- **SC-005**: A test set of answers containing scripts, embedded pages and unsafe links results in 0 executions and 0 clickable unsafe links. +- **SC-006**: For links in answers that point to cases of the application, 100% open the case inside the application. +- **SC-007**: An accessibility review finds every agent control operable by keyboard alone and new answers announced by a screen reader, with no critical issues. +- **SC-008**: In usability checks, at least 9 of 10 users can start a conversation, ask a question and reopen a past conversation without help. + +## Assumptions + +- The application connects to a Pega Infinity '25 (25.1.x) server where agents are configured on case types' case views, on application pages, or placed as agent widgets, and the platform's conversation services are enabled. The platform provides all agent intelligence, conversation storage, case actions and access control; this feature adds only the user-facing experience. +- Behaviour follows the agent experience of the standard portal for the same platform release, presented in the SDK's existing visual style. +- Users are already signed in; no new sign-in or permission model is introduced. +- The content and language of answers come from the platform; only the application's own labels are translated. +- Attachments follow the application's existing size limits and permissions. +- The case view keeps the SDK's existing layout; the agent panel uses the space of its side column. +- Out of scope for this release line, because the '25 standard portal does not offer them: an application-wide assistant, questions asked by the agent, stopping an answer, progress of agent actions on cases, and approving agent actions. +- Also out of scope: recommendations that some agents show when a conversation starts (they need a newer platform client than this release line ships); voice input; tracing; previewing sent attachments inside the application (they are downloaded instead); agents on page types the SDK does not provide; and the legacy coach experience for widgets without agent configuration. diff --git a/specs/ENHANCEMENT-20664- AgentWidget/tasks.md b/specs/ENHANCEMENT-20664- AgentWidget/tasks.md new file mode 100644 index 00000000..df8d8412 --- /dev/null +++ b/specs/ENHANCEMENT-20664- AgentWidget/tasks.md @@ -0,0 +1,275 @@ +--- + +description: "Task list for AI Agent Experience in Case View and Application Pages (Infinity '25)" +--- + +# Tasks: AI Agent Experience in Case View and Application Pages (Infinity '25) + +**Input**: Design documents from `/specs/001-ai-agent-assistant/` + +**Prerequisites**: plan.md, spec.md + +**Tests**: Required by Constitution VI. Test tasks are tagged **(developer-owned)**: the developer writes and runs them. Git branches, commits and pull requests are also done by the developer. + +**Approach**: Port from `constellation-frontend` at `release/25.1.5` (commit `59ee8ec177`) the way existing SDK components were ported. Keep file names, function names, logic and comments. Replace Cosmos components with MUI v6 (`makeStyles`), reusing the MUI components of the '26 port aligned with the '25 contract; turn Cosmos `t('')` strings into `localizedVal(, localeCategory)`; cast at the call site where the 4.1 typings lack an API; leave out the features that are not ported (voice input, the AI tracer, the lightbox preview and the legacy `GenAICoachOld` widget); do not copy the source's copyright header. Mark each deliberate deviation with a one-line `Deviation from Constellation:` comment. Paths prefixed with `REF:` are in `constellation-frontend`. + +**Status**: Implementation tasks are complete on `agent-poc-25`. Open tasks are the developer-owned tests and the open items T027, T028 and T045. + +**Organization**: Tasks are grouped by user story so each story can be implemented and validated independently. + +## Format: `[ID] [P?] [Story] Description` + +- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks) +- **[Story]**: User story from spec.md (US1–US5) +- Paths are relative to the repository root. The widget folder is `packages/react-sdk-components/src/components/widget/GenAICoach/`; the ported hook goes to `packages/react-sdk-components/src/hooks/` and ported utilities to `packages/react-sdk-components/src/components/helpers/`. +- Each ported Cosmos component is a design system extension component, like the SDK's other Cosmos clones (for example `WssQuickCreate`, used by the `QuickCreate` widget): its own folder `packages/react-sdk-components/src/components/designSystemExtension//` with `.tsx` and an `index.tsx` re-export, named after the Constellation component it ports, registered in the component map, and rendered through `getComponentFromMap` (Constitution II and VIII). + +--- + +## Phase 1: Setup (Shared Infrastructure) + +**Purpose**: Dependency and folder skeleton + +- [X] T001 Add `marked` (`^15.0.6`, the range of the '25 Cosmos rich text viewer) to `dependencies` in packages/react-sdk-components/package.json and in the root package.json, then run `npm install` from the repository root +- [X] T002 Create packages/react-sdk-components/src/components/widget/GenAICoach/config-ext.json with `name: "GenAICoach"`, `label: "Agent"`, `description: "Agent"`, `type: "Widget"`, `subtype: "CASE"`, `properties: []` + +--- + +## Phase 2: Foundational (Blocking Prerequisites) + +**Purpose**: The ported chat core used by every placement — case view and agent tabs (US1) and pages (US2) + +**⚠️ CRITICAL**: No user story work can begin until this phase is complete + +- [X] T003 Port the types, keeping the source's split: REF:packages/dx-components/src/components/Widgets/GenAICoach/GenAICoach.types.ts to packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.types.ts (engine types declared locally, `StreamResponse` for the Axios response, legacy-only types left out) and the in-scope types of REF:packages/cosmos-work/src/components/GenAICoach/GenAICoach.types.ts to packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.types.ts (`GenAICoachContentProps` without lightbox and voice props, with `toastMessage`/`onToastClose`; local stand-ins for the Cosmos core prop types); move `StreamingContext` from REF:packages/cosmos-work/src/components/GenAICoach/GenAIMessage.tsx (L38–L47) to packages/react-sdk-components/src/components/helpers/StreamingContext.ts +- [X] T004 [P] Port REF:packages/cosmos-work/src/components/GenAICoach/GenAICoach.utils.ts to packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.utils.ts (`isCoachMessage`, `isUserMessage`, `isInUtilities`, `copyToClipboard`, plus local stand-ins for `createUID` and `isMenuGroupProps`) +- [X] T005 [P] Port REF:packages/dx-components/src/utils/message-stream-utils.ts unchanged to packages/react-sdk-components/src/components/helpers/message-stream-utils.ts (`handleMessageStream`, `isErrorResponse`), with a local `tryCatch` and the `StreamResponse` type +- [X] T006 [P] Port REF:packages/dx-components/src/utils/components/agent-markdown-renderers.tsx to packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx as `createAgentMarkdownMap({ getPConnect })` with the source's `text` renderer (hides `###` tokens while streaming and complete follow-up-question blocks afterwards), reading `StreamingContext` (T003) +- [X] T007 [P] Implement packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/AgentRichTextViewer.tsx (plus `index.tsx`): `marked` lexer tokens rendered as MUI elements (no HTML strings; `html` tokens as plain text), `markdownMap` overrides per token type, capped headings, scrollable tables and code blocks +- [X] T008 Port the foundation of REF:packages/dx-components/src/utils/hooks/useGenAICoachObj.ts to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts — signature `(coaches, caseID, pConnect, isCaseView, utilitiesExpanded)`, coach options with the visibility filter and the "configuration incomplete" result, the `genAICoach` engine-store cache with no writes for hosts without agents (deviation), `startConversation` creating the conversation on open and `handleConversationResponse` (welcome message, disclaimer, guided mode, streaming flag, suggestions, initial instruction, recommendation messages), and the cache reused only with its conversation (deviation) +- [X] T009 Port sending to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts — `onSend` (prompt instructions, attachments), `callSendMessage` for agents and coaches with `handleMessageStream`, `updateMessagesWithResponse` (stream chunks, final JSON, `metadata` endings, stale-response guard), `updateMessagesWithError` and `handleStreamingProgress` +- [X] T010 [P] Implement packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/GenAICoach/GenAIMessage.tsx — user messages with attachments; agent messages with streaming content inside `StreamingContext`, loading and error states, the feedback slot, message actions (icon buttons for known icons such as `copy`) and follow-up suggestions; sub-components through `getComponentFromMap` +- [X] T011 [P] Implement packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageProgress/GenAIMessageProgress.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/GenAICoach/GenAIMessageProgress.tsx — "Thinking", "Analyzing data sources", "Generating response", "Double checking results" and "Finalizing response" with the source's timings +- [X] T012 [P] Implement packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/InitialSuggestedMessage.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/GenAICoach/InitialSuggestedMessage.tsx +- [X] T013 Implement packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/GenAICoach/GenAICoach.tsx — header with the agent switcher and one "Actions" menu (hook actions, Fullscreen, Minimize), the `utilities`, `fullpage` and `dialog` placements, empty state, messages with the disclaimer message, message box (suggestions menu, attachments, Send or "Generating response"), the guided "Ask" menu after the first answer, the AI notice, scroll-to-latest, polite announcements, the fullscreen `Dialog` sharing the typed text, and the copy `Snackbar` +- [X] T014 Register `GenAICoach`, `AgentRichTextViewer`, `ConversationHistory`, `GenAICoachContent`, `GenAIMessage`, `GenAIMessageFeedback`, `GenAIMessageProgress`, `InitialSuggestedMessage` and `UtilitiesLayout` in packages/react-sdk-components/src/sdk-pega-component-map.js and scripts/override-constants.js + +### Foundational tests (developer-owned) + +- [ ] T015 [P] (developer-owned) Port REF:packages/dx-components/test/unit/utils/message-stream-utils.test.ts (8 cases) to packages/react-sdk-components/tests/unit/components/helpers/message-stream-utils.test.ts +- [ ] T016 [P] (developer-owned) Port REF:packages/cosmos-work/src/components/GenAICoach/mocks/GenAIMessage.test.tsx and InitialSuggestedMessage.test.tsx to packages/react-sdk-components/tests/unit/components/designSystemExtension/GenAIMessage.test.tsx and InitialSuggestedMessage.test.tsx, adding the Copy action and the progress texts +- [ ] T017 [P] (developer-owned) Port REF:packages/cosmos-work/src/components/GenAICoach/mocks/GenAICoach.test.tsx (36 cases) to packages/react-sdk-components/tests/unit/components/designSystemExtension/GenAICoachContent.test.tsx with expectations for the one "Actions" menu, the disclaimers and the copy Snackbar; add safety tests for answers with scripts, embedded pages and unsafe links in packages/react-sdk-components/tests/unit/components/designSystemExtension/AgentRichTextViewer.test.tsx + +**Checkpoint**: Chat core ready — the case view, agent tabs and pages can host the agent. + +--- + +## Phase 3: User Story 1 - Chat with an AI agent while working on a case (Priority: P1) 🎯 MVP + +**Goal**: Agent panel in the case view and agents in the case's tabs: start on expand, progressive answers, formatted content, case links in the application, Copy, guided use, agent switching, fullscreen. + +**Independent Test**: Configure an agent on a case type's case view, open a case of that type, expand the panel, ask a question and receive a progressively displayed answer. + +### Tests for User Story 1 (developer-owned) + +- [ ] T018 [P] [US1] (developer-owned) Port REF:packages/dx-components/test/unit/Widgets/GenAICoach/GenAICoach.test.tsx (with `GenAICoach.mock.js`, 20 cases) to packages/react-sdk-components/tests/unit/components/widget/GenAICoach/GenAICoach.test.tsx, covering the cache reuse deviation (a remounted host with a cached configuration but no conversation creates one); add `CaseView` host tests (panel only with visible agents, nothing for `[]` or all hidden, minimized by default, conversation on first maximize, agent tabs and `DeferLoad` tabs) in packages/react-sdk-components/tests/unit/components/template/CaseView/CaseView.agent.test.tsx +- [ ] T019 [P] [US1] (developer-owned) Case-link tests in packages/react-sdk-components/tests/unit/components/helpers/agent-markdown-renderers.test.tsx — case key in the link, `caseKey` query parameter, `+` for the key's space, semantic URLs resolved through a mocked `getResolvedSemanticURL` and `getCaseTypeList` for a route per case type, generic `cases/{workID}` routes and a single case route, the application's root URL, link to another server, relative link, a rejected `openWorkByHandle` (new tab), modified clicks, unsafe protocols +- [ ] T020 [P] [US1] (developer-owned) E2E for expand, ask, stream, Copy, case link and guided agent on a case with an agent, the agent tab, and no change on a case without agents, in packages/react-sdk-components/tests/e2e/Agent/case-view-agent.spec.js + +### Implementation for User Story 1 + +- [X] T021 [US1] Port the case view hosting into packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx from REF:packages/dx-components/src/components/Templates/CaseView/index.jsx (L146, L213–L219, L867): optional `coaches` prop, context ID, `useGenAICoachObj(coaches.length ? coaches : undefined, contextID, getPConnect(), true, true)`, `GenAICoachContent` after the utilities region with `allowFullScreen` and the `utilities` variant starting minimized +- [X] T022 [US1] Render tabs without a view name in packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx with their own component in a card keyed by tab (tabs with a name keep `DeferLoad`), with the label falling back to `getTabLabel` from packages/react-sdk-components/src/components/template/SubTabs/tabUtils.ts +- [X] T023 [US1] Port REF:packages/dx-components/src/components/Widgets/GenAICoach/GenAICoach.tsx and `index.tsx` to packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.tsx and `index.tsx`: context ID rule, `useGenAICoachObj(coaches, contextID, getPConnect())`, `GenAICoachContent` with `variant={{ placement: 'fullpage' }}`; the legacy `GenAICoachOld` branch is not ported +- [X] T024 [US1] Port `agent-inline-edit-utils.ts` from REF:packages/dx-components/src/utils/components/ at `release/26.1.2` to packages/react-sdk-components/src/components/helpers/agent-inline-edit-utils.ts and add the link renderer to packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx (deviation): safe protocols only; a plain left click on a link to a case of the application opens it with `openWorkByHandle`, with the case key taken from the link or resolved from the case's semantic URL through `getResolvedSemanticURL` over `getCaseTypeList()`; case links recognised by case query parameters, relative links or the Infinity server's host name; other links and modified clicks open a new tab +- [X] T025 [US1] Add the Copy action to agent messages in packages/react-sdk-components/src/hooks/useGenAICoachObj.ts (`buildMessageActions`, `handleCopyResponse`, `toastMessage`/`onToastClose` instead of the Cosmos toaster) and pass the toast props through packages/react-sdk-components/src/components/widget/GenAICoach/GenAICoach.tsx +- [X] T026 [US1] Port agent switching (`onCoachChange`), `onStateChange` and `onOpen` to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts +- [ ] T027 [US1] Give each agent placement its own session cache namespace in packages/react-sdk-components/src/hooks/useGenAICoachObj.ts (`genAICoach.`, as 26.1 does), so the case's agent panel and an agent in one of its tabs keep separate conversations +- [ ] T028 [US1] Decide the header actions layout of packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx: keep one "Actions" menu, or show Minimize and Fullscreen as buttons as the '25 portal does + +**Checkpoint**: User Story 1 is usable on its own (MVP) once T027 is done; T028 is a layout decision. + +--- + +## Phase 4: User Story 2 - Use an agent on an application page (Priority: P2) + +**Goal**: Page agents from a "Chat with AI" button and the expanded utilities, and agent widgets placed on pages. + +**Independent Test**: Configure an agent on a landing page, open the page, open the agent from the button and ask a question. + +### Tests for User Story 2 (developer-owned) + +- [ ] T029 [P] [US2] (developer-owned) Port REF:packages/cosmos-work/src/components/UtilitiesLayout/mocks/UtilitiesLayout.test.tsx (4 cases) to packages/react-sdk-components/tests/unit/components/designSystemExtension/UtilitiesLayout.test.tsx, adding the non-modal dialog (page stays usable, Escape, click outside); add page-template tests with and without agents in packages/react-sdk-components/tests/unit/components/template/PageAgents.test.tsx +- [ ] T030 [P] [US2] (developer-owned) E2E for "Chat with AI" on a landing page, the expanded utilities, an agent widget on a page, and pages without agents, in packages/react-sdk-components/tests/e2e/Agent/page-agent.spec.js + +### Implementation for User Story 2 + +- [X] T031 [P] [US2] Add packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/UtilitiesLayout.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/UtilitiesLayout/UtilitiesLayout.tsx reused from the '26 port (the source is identical): strip, "Chat with AI" button, non-modal anchored dialog, expanded column and drawer, in-page agent below md (FR-025) +- [X] T032 [US2] Add `usePageGenAICoach` and `withPageUtilities` to packages/react-sdk-components/src/components/template/utils.tsx +- [X] T033 [US2] Host page agents in packages/react-sdk-components/src/components/template/DefaultPage/DefaultPage.tsx (grid and banner layouts), InlineDashboardPage/InlineDashboardPage.tsx, ListPage/ListPage.tsx, BannerPage/BannerPage.tsx, OneColumn/OneColumnPage/OneColumnPage.tsx, TwoColumn/TwoColumnPage/TwoColumnPage.tsx, NarrowWide/NarrowWidePage/NarrowWidePage.tsx and WideNarrow/WideNarrowPage/WideNarrowPage.tsx under packages/react-sdk-components/src/components/template/: optional `coaches` and `localeReference` props, `usePageGenAICoach`, `withPageUtilities` (REF:packages/dx-components/src/components/Templates/PageLayout/DefaultPage/index.tsx L84, L123, L135; PageLayout/InlineDashboardPage/index.jsx L76, L188; ListPage/index.jsx L40, L78) + +**Checkpoint**: User Stories 1 and 2 work independently. + +--- + +## Phase 5: User Story 3 - Revisit past conversations and start new ones (Priority: P3) + +**Goal**: History grouped by recency with paging, reopening past conversations, New chat. + +**Independent Test**: Hold two conversations, open history, reopen the first one and continue it. + +### Tests for User Story 3 (developer-owned) + +- [ ] T034 [P] [US3] (developer-owned) History tests in packages/react-sdk-components/tests/unit/components/widget/GenAICoach/GenAICoach.history.test.tsx — `groupByUpdatedOn` grouping, paging (size 20, end detection, next page from the loaded count), the first open with an empty engine-store history, load errors without details, reopening from the cache and from the platform, Back, New chat — and the list in packages/react-sdk-components/tests/unit/components/designSystemExtension/ConversationHistory.test.tsx + +### Implementation for User Story 3 + +- [X] T035 [US3] Port history to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts — `updateHistoryData`, `handleHistoryData`, `groupByUpdatedOn`, the History action and the `conversationHistory` props, with the deviations (render from state, gate on state, next page from the loaded count, `handleLoadError`) +- [X] T036 [US3] Port opening past conversations to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts — `fetchMessagesForConversation` and `handleFetchMessagesForConversation` with the history message mapping +- [X] T037 [US3] Port the New chat action to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts (a new conversation at once) +- [X] T038 [P] [US3] Implement packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/ConversationHistory.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/GenAICoach/ConversationHistory.tsx — Back button and "History" title, grouped list, selected item, load-more sentinel, loading, empty and error states + +**Checkpoint**: History works for every placement. + +--- + +## Phase 6: User Story 4 - Attach files to a message (Priority: P3) + +**Goal**: Upload with progress, size limit, preview and removal before sending, download after sending. + +**Independent Test**: Attach a file, send a message referencing it, and confirm the message shows the attachment. + +### Tests for User Story 4 (developer-owned) + +- [ ] T039 [P] [US4] (developer-owned) Attachment tests in packages/react-sdk-components/tests/unit/components/widget/GenAICoach/GenAICoach.attachments.test.tsx — upload progress, size error shown (deviation), send blocked while uploading, preview and removal before sending, download of sent attachments, send payload + +### Implementation for User Story 4 + +- [X] T040 [US4] Port attachments to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts — `onAddAttachment`, `onUploadProgress`, the size check with the error always set (deviation), the send payload, and downloads for sent and history attachments instead of the lightbox +- [X] T041 [US4] Add the attachment UI to packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx (Add attachment button with a hidden file input, pending list with progress, errors, Preview and Remove) and the sent attachment chips to packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx + +**Checkpoint**: Attachments work on the agent path. + +--- + +## Phase 7: User Story 5 - Rate agent answers (Priority: P3) + +**Goal**: Like and dislike with an optional comment, kept when the conversation is reopened. + +**Independent Test**: Like one answer and dislike another with a comment, then reopen the conversation and see both ratings. + +### Tests for User Story 5 (developer-owned) + +- [ ] T042 [P] [US5] (developer-owned) Rating tests in packages/react-sdk-components/tests/unit/components/designSystemExtension/GenAIMessageFeedback.test.tsx, and the hook's like and dislike calls in packages/react-sdk-components/tests/unit/components/widget/GenAICoach/GenAICoach.feedback.test.tsx + +### Implementation for User Story 5 + +- [X] T043 [US5] Port ratings to packages/react-sdk-components/src/hooks/useGenAICoachObj.ts — `handleReaction`, `handleFeedback` and `updateMessageFeedback` (agents only) +- [X] T044 [P] [US5] Implement packages/react-sdk-components/src/components/designSystemExtension/GenAIMessageFeedback/GenAIMessageFeedback.tsx (plus `index.tsx`), the MUI port of REF:packages/cosmos-work/src/components/GenAICoach/GenAIMessageFeedback.tsx — like and dislike with `aria-pressed`, the comment dialog and the selection status +- [ ] T045 [US5] Once it is confirmed how '25 agent streams end (with or without a final response), fix ratings on streamed answers without a final response in packages/react-sdk-components/src/hooks/useGenAICoachObj.ts: unique local IDs for such answers, and ratings sent only with a server message ID + +**Checkpoint**: All user stories are independently functional. + +--- + +## Phase 8: Polish & Cross-Cutting Concerns + +**Purpose**: Improvements that affect multiple user stories + +- [X] T046 [P] Localization pass over packages/react-sdk-components/src/components/designSystemExtension/ and packages/react-sdk-components/src/hooks/useGenAICoachObj.ts: every text through `localizedVal(…, 'GenAICoach')` or the source's `getLocalizedText`, with the English texts of the 25.1.5 source +- [X] T047 [P] Accessibility pass over packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx and its sub-components (FR-023): labelled controls, polite announcements of new answers, keyboard use and focus handling +- [X] T048 Strict type-check (also without unused locals in the agent files), ESLint and Prettier on the changed files under packages/react-sdk-components/src/, and `npm run lint` from the repository root +- [X] T049 Run `npm run build-overrides` and confirm every rewritten import of the agent files in packages/react-sdk-overrides/lib/ resolves +- [X] T050 Review the implementation against REF at `release/25.1.5` (2026-11-02) and fix the findings in packages/react-sdk-components/src/hooks/useGenAICoachObj.ts and packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx: cache reuse only with its conversation, the source's cache condition when opening a past conversation, and the guided "Ask" menu condition +- [ ] T051 (developer-owned) Compare unit-test coverage with `release/25` for packages/react-sdk-components/ (Constitution VI) +- [X] T052 (developer-owned) Test the acceptance scenarios of each user story in specs/001-ai-agent-assistant/spec.md against a 25.1.x server, including screens without agents and assignment submissions after a conversation (no `genAICoach` data); done by the developer on 2026-11-04 +- [X] T053 [P] Add the agent avatar to agent messages in packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx: the Material `AutoAwesome` icon in an MUI `Avatar` beside the message content on loading, streaming, completed and failed answers, in the theme's primary color so the light and dark themes work, named after the agent (FR-026) +- [X] T054 Show the agent as a card like the SDK widgets (FR-027): the root of packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx is an MUI `Card` for the `fullpage` and `utilities` placements (8px top and bottom margins on pages and in case tabs; the utilities outline replaced by the card), the case view's tab wrapper in packages/react-sdk-components/src/components/template/CaseView/CaseView.tsx is no longer a card, and the history group headers in packages/react-sdk-components/src/components/designSystemExtension/ConversationHistory/ConversationHistory.tsx are not sticky and have no background +- [X] T055 Match the 25.1.5 layout and spacing (FR-028): in packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx a compact page agent with the message box after the suggestions (rearranged with styles, keeping focus), centered empty, loading and error states, the 46rem column, the salutation group and the footer padding; in packages/react-sdk-components/src/components/designSystemExtension/InitialSuggestedMessage/InitialSuggestedMessage.tsx centered, primary-outlined suggestions with a readable fallback color; in packages/react-sdk-components/src/components/template/utils.tsx the gap before the utilities; and in packages/react-sdk-components/src/components/designSystemExtension/UtilitiesLayout/UtilitiesLayout.tsx no end margin +- [X] T056 Resolve case links of all routing table forms in packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx (FR-012): probe routes with a probe work ID, generic `cases/{workID}` routes confirmed by their `caseID` template, the class group of the case types for a single case route, `+` read as the key's space, and the link opened in a new tab when `openWorkByHandle` fails +- [X] T057 Harden case links for the reported 25.1.x link form (`…/prweb///`) in packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx (FR-012): case types also from the portal's `pyCaseTypesAvailableToCreate`, the case type the route is named after when the routing table has no route for it, the class group as key prefix when no `caseID` template confirms one, no case for paths without a work ID, and no new tab when the user cancels the open; verified with the real 25.1.3 engine and the MediaCo `D_pxBootstrapConfig` response +- [X] T058 Render the inline formatting of link text (as in `[**N-97011**](…)`) in packages/react-sdk-components/src/components/designSystemExtension/AgentRichTextViewer/AgentRichTextViewer.tsx and pass a token's rendered inline content to markdown overrides as `children` (`MarkdownMap` in packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoach.types.ts), shown by the link renderer in packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx +- [X] T059 Fix the findings of the pre-PR review (2026-11-04): in packages/react-sdk-components/src/hooks/useGenAICoachObj.ts only a complete last answer stops loading and an attachment sent in this session downloads the selected file; in packages/react-sdk-components/src/components/designSystemExtension/GenAIMessage/GenAIMessage.tsx an answer that no longer loads does not report completion again when it remounts; in packages/react-sdk-components/src/components/designSystemExtension/GenAICoachContent/GenAICoachContent.tsx Preview only for types that cannot run scripts in the application's origin, and the message box keeps the focus after Send and follow-up suggestions; in packages/react-sdk-components/src/components/helpers/agent-markdown-renderers.tsx a case key in a link counts only if its class belongs to the application's case types + +--- + +## Dependencies & Execution Order + +### Phase Dependencies + +- **Setup (Phase 1)**: No dependencies +- **Foundational (Phase 2)**: Depends on Setup; blocks all user stories +- **User Stories (Phases 3–7)**: Depend on Foundational; can then proceed in parallel or in priority order (P1 → P2 → P3) +- **Polish (Phase 8)**: Depends on the user stories being complete + +### User Story Dependencies + +- **US1 (P1)**: After Foundational; no dependency on other stories +- **US2 (P2)**: After Foundational; reuses `GenAICoachContent` from Phase 2, independent of US1 +- **US3 (P3)**, **US4 (P3)**, **US5 (P3)**: After Foundational; work in every placement, independent of each other + +### Within Each Story + +- Developer-owned tests are written alongside the implementation and must fail before it +- The hook changes come before the UI that uses them +- The open-item tasks (T027, T028, T045) follow the decisions or checks they reference + +### Parallel Opportunities + +- T004–T007 and T010–T012 touch different files and can run in parallel after T003 +- Test tasks marked [P] can run in parallel with each other +- After Phase 2, US1 and US2 can be worked on in parallel (different host files); US3–US5 change the same hook file, so their hook tasks run in sequence + +--- + +## Parallel Example: Foundational + +```bash +# After T003 (types): +Task: "T004 Port GenAICoach.utils.ts" +Task: "T005 Port message-stream-utils.ts" +Task: "T006 Port agent-markdown-renderers.tsx" +Task: "T007 Implement AgentRichTextViewer" +``` + +## Parallel Example: User Story 1 + +```bash +# Developer-owned tests together: +Task: "T018 Widget and CaseView host tests" +Task: "T019 Case-link tests" +Task: "T020 Case view E2E" +``` + +--- + +## Implementation Strategy + +### MVP First (User Story 1 Only) + +1. Complete Phase 1: Setup +2. Complete Phase 2: Foundational +3. Complete Phase 3: User Story 1 +4. **STOP and VALIDATE**: test the acceptance scenarios of User Story 1 (spec.md) against a 25.1.x server + +### Incremental Delivery + +1. Setup + Foundational → chat core ready +2. US1 → case view and agent tabs (MVP) +3. US2 → page agents and agent widgets on pages +4. US3–US5 → history, attachments, ratings +5. Polish → localization, accessibility, lint and overrides checks, review fixes + +### Parallel Team Strategy + +With multiple developers, after Phase 2 one developer takes US1 (case view host) and another US2 (page templates and `UtilitiesLayout`); the hook-centred stories US3–US5 follow in sequence. + +--- + +## Notes + +- [P] tasks = different files, no dependencies +- [Story] label maps task to specific user story for traceability +- Developer-owned tasks (tests, coverage, validation runs, git operations) are done by the developer +- Each deliberate deviation from the source carries a one-line `Deviation from Constellation:` comment in code +- `sdk-config.json` holds server settings and is not committed