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
3 changes: 3 additions & 0 deletions .cursor/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
},
"linear": {
"enabled": true
},
"clickhouse-cursor-plugin": {
"enabled": true
}
}
}
2 changes: 1 addition & 1 deletion .source
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
>
<img src="https://img.shields.io/npm/v/@novu/react" alt="NPM">
</a>
<a href="https://www.npmjs.com/package/@novu/react" target="_blank" rel="noopener noreferrer"
<a href="https://www.npmjs.com/package/@novu/js" target="_blank" rel="noopener noreferrer"
>
<img src="https://img.shields.io/npm/dm/@novu/react" alt="npm downloads">
<img src="https://img.shields.io/npm/dm/@novu/js" alt="npm downloads">
</a>
</p>
Expand Down
2 changes: 1 addition & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@
"json-schema-faker": "^0.5.6",
"json-schema-to-ts": "^3.0.0",
"jsonwebtoken": "9.0.3",
"liquidjs": "^10.25.0",
"liquidjs": "^10.25.5",
"lodash": "^4.18.0",
"lru-cache": "^11.2.4",
"nanoid": "^3.1.20",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { BadRequestException } from '@nestjs/common';
import { type TagsFilter, SeverityLevelEnum } from '@novu/shared';
import { SeverityLevelEnum, type TagsFilter } from '@novu/shared';
import { plainToClass, Transform, Type } from 'class-transformer';
import { ArrayMaxSize, IsArray, IsBoolean, IsDefined, IsOptional, ValidateNested } from 'class-validator';
import { IsEnumOrArray } from '../../shared/validators/is-enum-or-array';
import { IsTagsFilter } from '../validators/is-tags-filter.validator';
import { NotificationFilter } from '../utils/types';
import { IsTagsFilter } from '../validators/is-tags-filter.validator';

export class NotificationsFilter implements NotificationFilter {
@IsOptional()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { Type } from 'class-transformer';
import { IsBoolean, IsDefined, IsOptional, IsString, ValidateNested } from 'class-validator';

import { EnvironmentWithSubscriber } from '../../../shared/commands/project.command';
import { IsTagsFilter } from '../../validators/is-tags-filter.validator';
import { NotificationFilter } from '../../utils/types';
import { IsTagsFilter } from '../../validators/is-tags-filter.validator';

class Filter implements NotificationFilter {
@IsOptional()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type TagsFilter, SeverityLevelEnum } from '@novu/shared';
import { SeverityLevelEnum, type TagsFilter } from '@novu/shared';
import { IsBoolean, IsDefined, IsInt, IsMongoId, IsOptional, IsString, Max, Min } from 'class-validator';

import { EnvironmentWithSubscriber } from '../../../shared/commands/project.command';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { SubscriberEntity } from '@novu/dal';
import { type TagsFilter, SeverityLevelEnum } from '@novu/shared';
import { SeverityLevelEnum, type TagsFilter } from '@novu/shared';
import { IsArray, IsBoolean, IsDefined, IsOptional } from 'class-validator';
import { EnvironmentWithSubscriber } from '../../../shared/commands/project.command';
import { IsEnumOrArray } from '../../../shared/validators/is-enum-or-array';
import { IsTagsFilter } from '../../validators/is-tags-filter.validator';
import { NotificationFilter } from '../../utils/types';
import { IsTagsFilter } from '../../validators/is-tags-filter.validator';

class NotificationsFilter implements NotificationFilter {
@IsOptional()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { Type } from 'class-transformer';
import { IsBoolean, IsDefined, IsOptional, IsString, ValidateNested } from 'class-validator';

import { EnvironmentWithSubscriber } from '../../../shared/commands/project.command';
import { IsTagsFilter } from '../../validators/is-tags-filter.validator';
import { NotificationFilter } from '../../utils/types';
import { IsTagsFilter } from '../../validators/is-tags-filter.validator';

class Filter implements NotificationFilter {
@IsOptional()
Expand Down
15 changes: 0 additions & 15 deletions apps/api/src/utils/payload-sanitizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,3 @@ export function sanitizePayload(payload: Record<string, unknown>): string {
return '[Unserializable Payload]';
}
}

export async function retryWithBackoff<T>(fn: () => Promise<T>, maxAttempts = 3, initialDelayMs = 100): Promise<T> {
let delay = initialDelayMs;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
return await fn();
} catch (err) {
if (attempt === maxAttempts - 1) throw err;
const currentDelay = delay;
await new Promise<void>((resolve) => setTimeout(resolve, currentDelay));
delay *= 2;
}
}
throw new Error('Max attempts reached');
}
2 changes: 1 addition & 1 deletion apps/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
"json-schema": "^0.4.0",
"json5": "^2.2.3",
"launchdarkly-react-client-sdk": "^3.9.0",
"liquidjs": "^10.25.0",
"liquidjs": "^10.25.5",
"lodash.debounce": "^4.0.8",
"lodash.isequal": "^4.5.0",
"lodash.merge": "^4.6.2",
Expand Down
38 changes: 32 additions & 6 deletions apps/dashboard/src/components/ai-sidekick/ai-chat-context.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { AiAgentTypeEnum, AiMessageRoleEnum, AiResourceTypeEnum } from '@novu/shared';
import * as Sentry from '@sentry/react';
import { ChatStatus, DataUIPart, DynamicToolUIPart, generateId, UIMessage } from 'ai';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { ChatStatus, DataUIPart, DynamicToolUIPart, UIMessage } from 'ai';
import { createContext, FC, SVGProps, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { IconType } from 'react-icons';
import { useLocation } from 'react-router-dom';
import { cancelStream } from '@/api/ai';
import { ConfirmationModal } from '@/components/confirmation-modal';
Expand All @@ -13,6 +15,7 @@ import { useFetchLatestAiChat } from '@/hooks/use-fetch-latest-ai-chat';
import { useKeepAiChanges } from '@/hooks/use-keep-ai-changes';
import { useRevertMessage } from '@/hooks/use-revert-message';
import { useTelemetry } from '@/hooks/use-telemetry';
import { QueryKeys } from '@/utils/query-keys';
import { TelemetryEvent } from '@/utils/telemetry';
import { showErrorToast } from '../primitives/sonner-helpers';
import { isCancelledToolCall } from './message-utils';
Expand All @@ -33,17 +36,20 @@ export type AiChatContextValue = {
isActionPending: boolean;
isReviewingChanges: boolean;
inputText: string;
newChatSuggestions?: { label: string; icon: IconType | FC<SVGProps<SVGSVGElement>> }[];
setInputText: (text: string) => void;
handleSendMessage: (message: string) => Promise<void>;
handleKeepAll: () => Promise<void>;
handleTryAgain: (messageId: string) => Promise<void>;
handleRevertMessage: (messageId: string) => Promise<void>;
handleDiscard: (messageId: string) => Promise<void>;
handleSuggestionClick: (suggestion: string) => void;
};

export type AiChatResourceConfig = {
resourceType: AiResourceTypeEnum;
resourceId?: string;
newChatSuggestions?: { label: string; icon: IconType | FC<SVGProps<SVGSVGElement>> }[];
agentType: AiAgentTypeEnum;
metadata?: Record<string, unknown>;
isResourceLoading?: boolean;
Expand Down Expand Up @@ -118,6 +124,7 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
const {
resourceType,
resourceId,
newChatSuggestions,
agentType,
metadata,
isResourceLoading = false,
Expand All @@ -139,8 +146,10 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
const hasHandledInitialResumeRef = useRef(false);
const isStoppingRef = useRef(false);
const skipMessageSyncRef = useRef(false);
const pendingSendRef = useRef<{ chatId: string; prompt: string; metadata: Record<string, unknown> } | null>(null);
const location = useLocation();
const { areEnvironmentsInitialLoading, currentEnvironment } = useEnvironment();
const queryClient = useQueryClient();

const {
latestChat,
Expand All @@ -158,7 +167,7 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
return location.state.chatId as string;
}

return latestChat?._id ?? generateId();
return latestChat?._id;
}, [location, latestChat]);

const { setMessages, sendPrompt, stop, status, isGenerating, messages, dataParts, isAborted, resume, error } =
Expand Down Expand Up @@ -203,6 +212,7 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
},
});
const dataRef = useDataRef({
currentEnvironment,
isGenerating,
resourceType,
resourceId,
Expand Down Expand Up @@ -249,6 +259,14 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
}
}, [latestChat, resume, track, dataRef]);

useEffect(() => {
if (chatId && pendingSendRef.current && chatId === pendingSendRef.current.chatId) {
const pending = pendingSendRef.current;
pendingSendRef.current = null;
sendPrompt({ chatId: pending.chatId, prompt: pending.prompt, metadata: pending.metadata });
}
}, [chatId, sendPrompt]);

useEffect(() => {
isMountedRef.current = true;

Expand Down Expand Up @@ -278,20 +296,25 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode

const handleSendMessage = useCallback(
async (message: string) => {
const { resourceType, resourceId, agentType, latestChat, messages, metadata } = dataRef.current;
const { resourceType, resourceId, agentType, latestChat, messages, metadata, currentEnvironment } =
dataRef.current;
const isLastUserMessage = messages.length > 0 && messages[messages.length - 1].role === AiMessageRoleEnum.USER;

const messageToSend = message.trim();
if (!messageToSend) return;

if (!latestChat) {
const newChat = await createAiChat({ resourceType, resourceId });
queryClient.setQueryData([QueryKeys.fetchChat, currentEnvironment?._id, resourceType, resourceId], newChat);
track(TelemetryEvent.COPILOT_CHAT_CREATED, {
chatId: newChat._id,
resourceType,
agentType,
});
sendPrompt({ chatId: newChat._id, prompt: messageToSend, metadata: { ...metadata } });
// we don't pre-create the chat until the user sends a message and the useAiChatStream hook uses the autogenerated chatId
// if we update the chatId right away here, the useAiChatStream hook will reset its state and the user sent message and stream will be lost
// defer sending the message to the stream until the chat is created and chatId is updated for the useAiChatStream hook
pendingSendRef.current = { chatId: newChat._id, prompt: messageToSend, metadata: { ...metadata } };
} else if (isLastUserMessage) {
const lastUserMessage = messages.filter((m) => m.role === AiMessageRoleEnum.USER).pop();
sendPrompt({
Expand All @@ -313,7 +336,7 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode

setInputText('');
},
[dataRef, createAiChat, sendPrompt, track]
[dataRef, queryClient, createAiChat, sendPrompt, track]
);

const handleKeepAll = useCallback(async () => {
Expand Down Expand Up @@ -540,12 +563,14 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
isActionPending,
isReviewingChanges,
inputText,
newChatSuggestions,
setInputText,
handleSendMessage,
handleKeepAll,
handleTryAgain,
handleRevertMessage,
handleDiscard,
handleSuggestionClick: handleSendMessage,
}),
[
hasNoChatHistory,
Expand All @@ -561,6 +586,7 @@ export function AiChatProvider({ children, config }: { children: React.ReactNode
isActionPending,
isReviewingChanges,
inputText,
newChatSuggestions,
handleSendMessage,
handleKeepAll,
handleTryAgain,
Expand Down
68 changes: 54 additions & 14 deletions apps/dashboard/src/components/ai-sidekick/chat-body.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ChatStatus, UIMessage } from 'ai';
import { FormEvent, useMemo } from 'react';
import { FC, FormEvent, SVGProps, useMemo } from 'react';
import { IconType } from 'react-icons';
import { Conversation, ConversationContent, ConversationScrollButton } from '../ai-elements/conversation';
import { Message } from '../ai-elements/message';
import {
Expand All @@ -12,6 +13,7 @@ import {
} from '../ai-elements/prompt-input';
import { Broom } from '../icons/broom';
import { BroomSparkle } from '../icons/broom-sparkle';
import { Badge, BadgeIcon } from '../primitives/badge';
import { Skeleton } from '../primitives/skeleton';
import { AssistantMessage } from './assistant-message';
import { hasKnownMessageParts } from './message-utils';
Expand Down Expand Up @@ -57,8 +59,51 @@ export const ChatBodySkeleton = () => {
);
};

const ChatBodyNoHistory = ({
newChatSuggestions,
isGenerating,
onSuggestionClick,
}: {
newChatSuggestions?: { label: string; icon: IconType | FC<SVGProps<SVGSVGElement>> }[];
isGenerating: boolean;
onSuggestionClick: (suggestion: string) => void;
}) => {
return (
<div className="flex flex-col justify-center items-start h-full p-5">
<div className="flex flex-col gap-1 px-1 py-5">
<div className="flex flex-col gap-3">
<BroomSparkle className="size-5" />
<span className="text-label-md font-normal bg-linear-to-b from-[hsla(0,0%,57%,1)] to-[hsla(0,0%,39%,1)] bg-clip-text text-transparent">
Novu Copilot
</span>
</div>
<span className="text-label-xs text-text-soft">
Suggests improvements, fills gaps, and applies best practices as you build.{' '}
</span>
</div>
<div className="flex flex-row gap-2 flex-wrap">
{newChatSuggestions?.map((suggestion) => (
<Badge
key={suggestion.label}
variant="stroke"
color="gray"
size="md"
className="cursor-pointer px-2.5 py-1.5 text-label-xs h-auto ring-stroke-soft"
disabled={isGenerating}
onClick={() => onSuggestionClick(suggestion.label)}
>
<BadgeIcon as={suggestion.icon} className="size-4 fill-current" />
{suggestion.label}
</Badge>
))}
</div>
</div>
);
};

export const ChatBody = ({
hasNoChatHistory,
newChatSuggestions,
inputText,
onInputChange,
isGenerating,
Expand All @@ -75,8 +120,10 @@ export const ChatBody = ({
onDiscard,
onTryAgain,
onRevertMessage,
onSuggestionClick,
}: {
hasNoChatHistory: boolean;
newChatSuggestions?: { label: string; icon: IconType | FC<SVGProps<SVGSVGElement>> }[];
inputText: string;
onInputChange: (text: string) => void;
isGenerating: boolean;
Expand All @@ -93,6 +140,7 @@ export const ChatBody = ({
onDiscard: (messageId: string) => void;
onTryAgain: (messageId: string) => void;
onRevertMessage: (messageId: string) => void;
onSuggestionClick: (suggestion: string) => void;
}) => {
const hasLastUserMessage = messages.length === 0 || messages[messages.length - 1].role === 'user';
const lastMessage = messages[messages.length - 1];
Expand All @@ -119,19 +167,11 @@ export const ChatBody = ({
<>
<Conversation className="min-h-0 [&>div:first-child]:overflow-x-hidden">
{hasNoChatHistory && messages.length === 0 ? (
<div className="flex justify-start items-center h-full p-5">
<div className="flex flex-col gap-1">
<div className="flex flex-col gap-3">
<BroomSparkle className="size-5" />
<span className="text-label-md font-normal bg-linear-to-b from-[hsla(0,0%,57%,1)] to-[hsla(0,0%,39%,1)] bg-clip-text text-transparent">
Novu Copilot
</span>
</div>
<span className="text-label-xs text-text-soft">
Suggests improvements, fills gaps, and applies best practices as you build.{' '}
</span>
</div>
</div>
<ChatBodyNoHistory
newChatSuggestions={newChatSuggestions}
isGenerating={isGenerating}
onSuggestionClick={onSuggestionClick}
/>
) : (
<ConversationContent
className={chatConversationContentClassName}
Expand Down
Loading
Loading