Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/customer-portal/webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-idle-timer": "^5.7.2",
"react-markdown": "^10.1.0",
"react-router": "^7.1.5",
"zod": "^4.3.6"
},
Expand Down
667 changes: 667 additions & 0 deletions apps/customer-portal/webapp/pnpm-lock.yaml

Large diffs are not rendered by default.

89 changes: 89 additions & 0 deletions apps/customer-portal/webapp/src/api/usePostConversations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { useAsgardeo } from "@asgardeo/react";
import { useLogger } from "@hooks/useLogger";
import { useAuthApiClient } from "@context/AuthApiContext";
import type { ConversationRequest } from "@models/requests";
import type { ConversationResponse } from "@models/responses";

/**
* Posts a message to the project conversations API (Novera chat).
* Called when user hits "Submit & Get Help" on the describe-issue page.
*
* @returns {UseMutationResult<ConversationResponse, Error, { projectId: string } & ConversationRequest>} Mutation result.
*/
export function usePostConversations(): UseMutationResult<
ConversationResponse,
Error,
{ projectId: string } & ConversationRequest
> {
const logger = useLogger();
const { isSignedIn, isLoading: isAuthLoading } = useAsgardeo();
const fetchFn = useAuthApiClient();

return useMutation<
ConversationResponse,
Error,
{ projectId: string } & ConversationRequest
>({
mutationFn: async (
params: { projectId: string } & ConversationRequest,
): Promise<ConversationResponse> => {
const { projectId, message, envProducts, region, tier } = params;

if (!isSignedIn || isAuthLoading) {
throw new Error("User must be signed in to send messages");
}

logger.debug("[usePostConversations] Request:", {
projectId,
messageLength: message.length,
envProducts: Object.keys(envProducts || {}),
region,
tier,
});

const baseUrl = window.config?.CUSTOMER_PORTAL_BACKEND_BASE_URL;
if (!baseUrl) {
throw new Error(
"CUSTOMER_PORTAL_BACKEND_BASE_URL is not configured",
);
}

const requestUrl = `${baseUrl}/projects/${projectId}/conversations`;
const response = await fetchFn(requestUrl, {
method: "POST",
body: JSON.stringify({ message, envProducts, region, tier }),
});

logger.debug(
`[usePostConversations] Response status: ${response.status}`,
);

if (!response.ok) {
throw new Error(
`Conversations API error: ${response.status} ${response.statusText}`,
);
}

const data: ConversationResponse = await response.json();
logger.debug("[usePostConversations] Data received");
return data;
},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ describe("AddProductModal", () => {
});
});
expect(mockOnSuccess).toHaveBeenCalled();
expect(mockOnClose).toHaveBeenCalled();
});

it("should include cores and tps when provided", async () => {
Expand Down Expand Up @@ -201,6 +202,7 @@ describe("AddProductModal", () => {
});

const submitButton = screen.getByRole("button", { name: "Add Product" });
await waitFor(() => expect(submitButton).not.toBeDisabled());
fireEvent.click(submitButton);

await waitFor(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,113 @@
// specific language governing permissions and limitations
// under the License.

import { Box, Paper, Typography } from "@wso2/oxygen-ui";
import { Bot } from "@wso2/oxygen-ui-icons-react";
import {
Box,
Button,
CircularProgress,
Paper,
Typography,
} from "@wso2/oxygen-ui";
import { Bot, FileText } from "@wso2/oxygen-ui-icons-react";
import ReactMarkdown from "react-markdown";
import { type JSX } from "react";
import type { Message } from "@pages/NoveraChatPage";

/** Safe URL protocols for markdown links. Blocks javascript:, data:, etc. */
const SAFE_PROTOCOLS = ["http:", "https:"];

function isSafeHref(href: string | undefined): href is string {
if (!href || typeof href !== "string") return false;
try {
const parsed = new URL(href, "https://invalid.invalid");
return SAFE_PROTOCOLS.includes(parsed.protocol);
} catch {
return false;
}
}

interface ChatMessageBubbleProps {
message: Message;
onCreateCase?: () => void;
isCreateCaseLoading?: boolean;
}

/** Typography mapping for markdown elements (bot messages). */
const markdownComponents: React.ComponentProps<
typeof ReactMarkdown
>["components"] = {
h1: ({ children }) => (
<Typography variant="h6" component="h1" sx={{ mt: 2, mb: 1, fontWeight: 600 }}>
{children}
</Typography>
),
h2: ({ children }) => (
<Typography variant="subtitle1" component="h2" sx={{ mt: 2, mb: 1, fontWeight: 600 }}>
{children}
</Typography>
),
h3: ({ children }) => (
<Typography variant="subtitle2" component="h3" sx={{ mt: 1.5, mb: 0.5, fontWeight: 600 }}>
{children}
</Typography>
),
p: ({ children }) => (
<Typography variant="body2" component="p" sx={{ mb: 1, lineHeight: 1.6 }}>
{children}
</Typography>
),
ul: ({ children }) => (
<Box component="ul" sx={{ m: 0, pl: 2.5, mb: 1 }}>
{children}
</Box>
),
ol: ({ children }) => (
<Box component="ol" sx={{ m: 0, pl: 2.5, mb: 1 }}>
{children}
</Box>
),
li: ({ children }) => (
<Typography variant="body2" component="li" sx={{ mb: 0.5, lineHeight: 1.6 }}>
{children}
</Typography>
),
strong: ({ children }) => (
<Box component="strong" sx={{ fontWeight: 600 }}>
{children}
</Box>
),
a: ({ href, children }) =>
isSafeHref(href) ? (
<Typography
component="a"
href={href}
target="_blank"
rel="noopener noreferrer"
variant="body2"
sx={{ color: "primary.main", textDecoration: "underline" }}
>
{children}
</Typography>
) : (
<Typography variant="body2" component="span">
{children}
</Typography>
),
};

/**
* Renders a single chat message bubble.
*
* Supports both user and bot messages with appropriate styling
* and avatar display.
* Supports both user and bot messages with appropriate styling,
* avatar display, markdown formatting for bot messages, and
* optional Create Case action when actions is not null.
*
* @returns The ChatMessageBubble JSX element.
*/
export default function ChatMessageBubble({
message,
onCreateCase,
isCreateCaseLoading = false,
}: ChatMessageBubbleProps): JSX.Element {
const isUser = message.sender === "user";

Expand Down Expand Up @@ -74,9 +162,56 @@ export default function ChatMessageBubble({
borderColor: isUser ? "primary.main" : "divider",
}}
>
<Typography variant="body2" sx={{ whiteSpace: "pre-line" }}>
{message.text}
</Typography>
{isUser ? (
<Typography variant="body2" sx={{ whiteSpace: "pre-line" }}>
{message.text}
</Typography>
) : (
<Box
sx={{
"& h1:first-of-type, & h2:first-of-type, & h3:first-of-type, & p:first-of-type":
{ mt: 0 },
}}
>
<ReactMarkdown components={markdownComponents}>
{message.text}
</ReactMarkdown>
</Box>
)}
{!isUser &&
message.showCreateCaseAction &&
onCreateCase &&
(isCreateCaseLoading ? (
<Box sx={{ mt: 2, display: "flex", alignItems: "center", gap: 1 }}>
<Button
variant="outlined"
size="small"
color="warning"
disabled
startIcon={<CircularProgress color="inherit" size={14} />}
>
Processing
</Button>
<Typography variant="caption" color="text.secondary">
Skip the chat and create a support case now
</Typography>
</Box>
) : (
<Box sx={{ mt: 2, display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
<Button
variant="outlined"
size="small"
color="warning"
onClick={onCreateCase}
startIcon={<FileText size={14} />}
>
Create Case
</Button>
<Typography variant="caption" color="text.secondary">
Skip the chat and create a support case now
</Typography>
</Box>
))}
</Paper>
</Box>
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import type { Message } from "@pages/NoveraChatPage";
interface ChatMessageListProps {
messages: Message[];
messagesEndRef: RefObject<HTMLDivElement | null>;
onCreateCase?: () => void;
isCreateCaseLoading?: boolean;
}

/**
Expand All @@ -35,6 +37,8 @@ interface ChatMessageListProps {
export default function ChatMessageList({
messages,
messagesEndRef,
onCreateCase,
isCreateCaseLoading = false,
}: ChatMessageListProps): JSX.Element {
return (
<Box
Expand All @@ -48,7 +52,12 @@ export default function ChatMessageList({
}}
>
{messages.map((msg) => (
<ChatMessageBubble key={msg.id} message={msg} />
<ChatMessageBubble
key={msg.id}
message={msg}
onCreateCase={onCreateCase}
isCreateCaseLoading={isCreateCaseLoading}
/>
))}
<div ref={messagesEndRef} />
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import ChatInput from "@components/support/novera-ai-assistant/novera-chat-page/
// Mock @wso2/oxygen-ui components
vi.mock("@wso2/oxygen-ui", () => ({
Box: ({ children }: any) => <div data-testid="box">{children}</div>,
Button: ({ children, onClick }: any) => (
<button onClick={onClick}>{children}</button>
),
CircularProgress: () => <span data-testid="circular-progress" />,
IconButton: ({ children, onClick, disabled }: any) => (
<button data-testid="icon-button" onClick={onClick} disabled={disabled}>
{children}
Expand All @@ -39,9 +43,7 @@ vi.mock("@wso2/oxygen-ui", () => ({
Typography: ({ children }: any) => (
<span data-testid="typography">{children}</span>
),
Button: ({ children, onClick }: any) => (
<button onClick={onClick}>{children}</button>
),
Stack: ({ children }: any) => <div>{children}</div>,
colors: {
orange: {
700: "#C2410C",
Expand All @@ -52,7 +54,8 @@ vi.mock("@wso2/oxygen-ui", () => ({
// Mock icons
vi.mock("@wso2/oxygen-ui-icons-react", () => ({
Send: () => <svg data-testid="icon-send" />,
CircleAlert: () => <svg data-testid="icon-alert" />,
Sparkles: () => <svg data-testid="icon-sparkles" />,
FileText: () => <svg data-testid="icon-file-text" />,
}));

describe("ChatInput", () => {
Expand Down Expand Up @@ -108,7 +111,7 @@ describe("ChatInput", () => {
/>,
);

expect(screen.getByText(/Need more help?/i)).toBeInTheDocument();
expect(screen.getByText(/Thank you for describing the issue/i)).toBeInTheDocument();
const createCaseButton = screen.getByText("Create Case");
expect(createCaseButton).toBeInTheDocument();

Expand Down
Loading