Skip to content

Bug/93503 improve progressive rendering #79

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cypress/support/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ Cypress.Commands.add("setRTLDocument", () => {
Cypress.Commands.add("getHistory", () => {
return cy.getWebchat().then(webchat => {
// @ts-ignore
return webchat.store.getState().messages;
return webchat.store.getState().messages.messageHistory;
});
});

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
},
"dependencies": {
"@braintree/sanitize-url": "^6.0.0",
"@cognigy/chat-components": "^0.42.0",
"@cognigy/chat-components": "0.43.0",
"@cognigy/socket-client": "5.0.0-beta.22",
"@emotion/cache": "^10.0.29",
"@emotion/react": "^11.13.0",
Expand Down
1 change: 1 addition & 0 deletions src/common/interfaces/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface IStreamingMessage extends IBaseMessage {
traceId: string;
id?: string;
animationState?: "start" | "animating" | "done" | "exited";
finishReason?: string;
}

export type IMessage =
Expand Down
40 changes: 33 additions & 7 deletions src/webchat-ui/components/WebchatUI.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from "react";
import { IMessage, IStreamingMessage } from "../../common/interfaces/message";
import { IMessageEvent } from "../../common/interfaces/event";
import Header from "./presentational/Header";
import { CacheProvider, ThemeProvider } from "@emotion/react";
import styled from "@emotion/styled";
Expand Down Expand Up @@ -71,7 +72,8 @@ import { isValidMarkdown, removeMarkdownChars } from "../../webchat/helper/handl

export interface WebchatUIProps {
currentSession: string;
messages: IMessage[];
messages: (IMessage | IMessageEvent)[];
visibleOutputMessages: string[];
unseenMessages: IMessage[];
fullscreenMessage?: IMessage;
onSetFullscreenMessage: (message: IMessage) => void;
Expand Down Expand Up @@ -1438,11 +1440,23 @@ export class WebchatUI extends React.PureComponent<
}

renderHistory() {
const { messages, typingIndicator, config, onEmitAnalytics, openXAppOverlay } = this.props;
const {
messages,
typingIndicator,
config,
onEmitAnalytics,
openXAppOverlay,
visibleOutputMessages,
} = this.props;
const { messagePlugins = [] } = this.state;

const { enableTypingIndicator, messageDelay, enableAIAgentNotice, AIAgentNoticeText } =
config.settings.behavior;
const {
enableTypingIndicator,
messageDelay,
enableAIAgentNotice,
AIAgentNoticeText,
progressiveMessageRendering,
} = config.settings.behavior;
const isTyping = typingIndicator !== "remove" && typingIndicator !== "hide";

const isEnded = isConversationEnded(messages);
Expand All @@ -1453,16 +1467,28 @@ export class WebchatUI extends React.PureComponent<
"acceptPrivacyPolicy",
]);

// Filter messages based on progressive rendering settings
const visibleMessages = progressiveMessageRendering
? messagesExcludingPrivacyMessage.filter(message => {
if (message.source !== "bot" && message.source !== "engagement") {
return true;
}
return visibleOutputMessages.includes(
(message as IStreamingMessage).id as string,
);
})
: messagesExcludingPrivacyMessage;

return (
<>
{enableAIAgentNotice !== false && (
<TopStatusMessage variant="body-regular" component="div">
{AIAgentNoticeText || "You're now chatting with an AI Agent."}
</TopStatusMessage>
)}
{messagesExcludingPrivacyMessage.map((message, index) => {
{visibleMessages.map((message, index) => {
// Lookahead if there is a user reply
const hasReply = messagesExcludingPrivacyMessage
const hasReply = visibleMessages
.slice(index + 1)
.some(
message =>
Expand All @@ -1483,7 +1509,7 @@ export class WebchatUI extends React.PureComponent<
onSetFullscreen={() => this.props.onSetFullscreenMessage(message)}
openXAppOverlay={openXAppOverlay}
plugins={messagePlugins}
prevMessage={messagesExcludingPrivacyMessage?.[index - 1]}
prevMessage={visibleMessages?.[index - 1]}
theme={this.state.theme}
onSetMessageAnimated={this.props.onSetMessageAnimated}
/>
Expand Down
116 changes: 62 additions & 54 deletions src/webchat/components/ConnectedWebchatUI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type FromState = Pick<
| "connected"
| "reconnectionLimit"
>;

type FromDispatch = Pick<
WebchatUIProps,
| "onSendMessage"
Expand All @@ -54,33 +55,62 @@ type FromDispatch = Pick<
| "onTriggerEngagementMessage"
| "onSetMessageAnimated"
>;

export type FromProps = Pick<
WebchatUIProps,
"messagePlugins" | "inputPlugins" | "webchatRootProps" | "webchatToggleProps" | "options"
>;

type Merge = FromState & FromDispatch & FromProps & Pick<WebchatUIProps, "fullscreenMessage">;

export const ConnectedWebchatUI = connect<FromState, FromDispatch, FromProps, Merge, StoreState>(
({
messages,
unseenMessages,
prevConversations,
connection: { connected, reconnectionLimit },
ui: {
(state: StoreState) => {
const {
messages: { messageHistory: messages, visibleOutputMessages },
unseenMessages,
prevConversations,
connection: { connected, reconnectionLimit },
ui: {
open,
typing,
inputMode,
fullscreenMessage,
showHomeScreen,
showPrevConversations,
showChatOptionsScreen,
hasAcceptedTerms,
ttsActive,
lastInputId,
},
config,
options: { sessionId, userId },
rating: {
showRatingScreen,
hasGivenRating,
requestRatingScreenTitle,
customRatingTitle,
customRatingCommentText,
requestRatingSubmitButtonText,
requestRatingEventBannerText,
requestRatingChatStatusBadgeText,
},
input: { sttActive, textActive, isDropZoneVisible, fileList, fileUploadError },
xAppOverlay: { open: isXAppOverlayOpen },
} = state;

return {
currentSession: sessionId,
messages,
visibleOutputMessages,
unseenMessages,
prevConversations,
open,
typing,
typingIndicator: typing,
inputMode,
fullscreenMessage,
showHomeScreen,
showPrevConversations,
showChatOptionsScreen,
hasAcceptedTerms,
ttsActive,
lastInputId,
},
config,
options: { sessionId, userId },
rating: {
config,
connected,
reconnectionLimit,
showRatingScreen,
hasGivenRating,
requestRatingScreenTitle,
Expand All @@ -89,43 +119,21 @@ export const ConnectedWebchatUI = connect<FromState, FromDispatch, FromProps, Me
requestRatingSubmitButtonText,
requestRatingEventBannerText,
requestRatingChatStatusBadgeText,
},
input: { sttActive, textActive, isDropZoneVisible, fileList, fileUploadError },
xAppOverlay: { open: isXAppOverlayOpen },
}) => ({
currentSession: sessionId,
messages,
unseenMessages,
prevConversations,
open,
typingIndicator: typing,
inputMode,
fullscreenMessage,
config,
connected,
reconnectionLimit,
showRatingScreen,
hasGivenRating,
requestRatingScreenTitle,
customRatingTitle,
customRatingCommentText,
requestRatingSubmitButtonText,
requestRatingEventBannerText,
requestRatingChatStatusBadgeText,
showHomeScreen,
sttActive,
textActive,
isDropZoneVisible,
fileList,
fileUploadError,
showPrevConversations,
showChatOptionsScreen,
hasAcceptedTerms,
isXAppOverlayOpen,
userId,
ttsActive,
lastInputId,
}),
showHomeScreen,
sttActive,
textActive,
isDropZoneVisible,
fileList,
fileUploadError,
showPrevConversations,
showChatOptionsScreen,
hasAcceptedTerms,
isXAppOverlayOpen,
userId,
ttsActive,
lastInputId,
} as FromState;
},
dispatch => ({
onSendMessage: (text, data, options) => dispatch(sendMessage({ text, data }, options)),
onSetInputMode: inputMode => dispatch(setInputMode(inputMode)),
Expand Down
7 changes: 4 additions & 3 deletions src/webchat/store/autoinject/autoinject-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ export const createAutoInjectMiddleware =
// except if explicitly set via enableAutoInjectWithHistory
if (!config.settings.widgetSettings.enableInjectionWithoutEmptyHistory) {
// Exclude engagement messages from state.messages
const messagesExcludingEngagementMessages = state.messages?.filter(
message => message.source !== "engagement",
);
const messagesExcludingEngagementMessages =
state.messages.messageHistory?.filter(
message => message.source !== "engagement",
);
// Exclude controlCommands messages from filtered message list
const messagesExcludingControlCommands = getMessagesListWithoutControlCommands(
messagesExcludingEngagementMessages,
Expand Down
22 changes: 22 additions & 0 deletions src/webchat/store/messages/helper.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
import { IWebchatMessage, IWebchatTemplateAttachment } from "@cognigy/socket-client";
import { IStreamingMessage } from "../../../common/interfaces/message";

export function generateRandomId(): string {
return String(Math.random()).slice(2, 18);
}

export function isAnimatedRichBotMessage(message: IStreamingMessage): boolean {
const { _facebook, _webchat } = message?.data?._cognigy || {};
const payload = (_webchat as IWebchatMessage) || _facebook || {};

const isQuickReplies = !!(
payload?.message?.quick_replies && payload.message.quick_replies.length > 0
);

const isTextWithButtons =
(payload?.message?.attachment as IWebchatTemplateAttachment)?.payload?.template_type ===
"button";

const hasMessengerText = !!payload?.message?.text;

const isAnimatedMsg = isQuickReplies || isTextWithButtons || hasMessengerText;

return isAnimatedMsg;
}
2 changes: 1 addition & 1 deletion src/webchat/store/messages/message-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export const createMessageMiddleware =
const isStreamingMessage =
state.config.settings.behavior.collateStreamedOutputs &&
!!message?.data?._cognigy?._messageId &&
state.messages.some(
state.messages.messageHistory.some(
storeMsg =>
message?.data?._cognigy?._messageId ===
(storeMsg as IStreamingMessage).id,
Expand Down
Loading