Skip to content

feat: chat feedback #60

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 5 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
1 change: 1 addition & 0 deletions actions/chat/get-chat-conversations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export const getChatConversations = async ({ sharedConversationId }: GetChatConv
user: true,
messages: {
orderBy: { createdAt: 'asc' },
include: { feedback: true },
},
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui';
import { ChatCompletionRole } from '@/constants/open-ai';
import { getFallbackName } from '@/lib/utils';

import { ChatFeedback } from './chat-feedback';

type ChatBubbleProps = {
isShared?: boolean;
isSubmitting?: boolean;
message: { role: string; content: string; model?: string };
message: {
role: string;
content: string;
model?: string;
id?: string;
feedback?: { feedback: string } | null;
};
name: string;
picture?: string | null;
streamMessage?: string;
Expand Down Expand Up @@ -50,8 +58,9 @@ export const ChatBubble = ({
</div>
<MarkdownText text={text} />
{isAssistant && !isSubmitting && (
<div className="flex gap-x-2 mt-4">
<div className="flex gap-x-3 mt-4">
<CopyClipboard textToCopy={text} />
<ChatFeedback messageId={message.id} state={message.feedback?.feedback} />
</div>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use client';

import { ChatMessage } from '@prisma/client';
import { ThumbsDown, ThumbsUp } from 'lucide-react';
import { SyntheticEvent, useState } from 'react';

import { useToast } from '@/components/ui/use-toast';
import { useChatStore } from '@/hooks/store/use-chat-store';
import { fetcher } from '@/lib/fetcher';
import { cn } from '@/lib/utils';

const enum Feedback {
POSITIVE = 'positive',
NEGATIVE = 'negative',
}

type ChatFeedback = {
className?: string;
disabled?: boolean;
messageId?: string;
state?: string | null;
};

export const ChatFeedback = ({ className, disabled, messageId, state }: ChatFeedback) => {
const { toast } = useToast();

const { chatMessages, setChatMessages } = useChatStore((state) => ({
chatMessages: state.chatMessages,
setChatMessages: state.setChatMessages,
}));

const [isFetching, setIsFetching] = useState(false);
const [clicked, setClicked] = useState({
[Feedback.POSITIVE]: false,
[Feedback.NEGATIVE]: false,
});

const handleClick = async (event: SyntheticEvent & { currentTarget: { name: string } }) => {
const feedback = event.currentTarget.name;

setClicked((prev) => ({ ...prev, [feedback]: true }));

setTimeout(() => {
setClicked((prev) => ({ ...prev, [feedback]: false }));
}, 1000);

setIsFetching(true);

try {
const response = await fetcher.post('/api/chat/feedback', {
responseType: 'json',
body: { messageId, feedback },
});

const conversationId = response.message.conversationId;

const updatedChatMessages = {
...chatMessages,
[conversationId]: chatMessages[conversationId].map((message) =>
message.id === messageId
? {
...message,
feedback: {
...(message as ChatMessage & { feedback: ChatFeedback })?.feedback,
feedback: response.feedback,
},
}
: message,
),
};

setChatMessages(updatedChatMessages);
} catch (error) {
toast({ isError: true });
} finally {
setIsFetching(false);
}
};

return (
<div className="flex gap-x-3">
<button onClick={handleClick} disabled={disabled || isFetching} name={Feedback.POSITIVE}>
<ThumbsUp
className={cn(
'h-4 w-4 hover:text-green-500 transition-all duration-300',
state === Feedback.POSITIVE && 'text-green-500',
clicked[Feedback.POSITIVE] ? 'animate-spin-once' : '',
className,
)}
/>
</button>
<button onClick={handleClick} disabled={disabled || isFetching} name={Feedback.NEGATIVE}>
<ThumbsDown
className={cn(
'h-4 w-4 hover:text-red-500 transition-all duration-300',
state === Feedback.NEGATIVE && 'text-red-500',
clicked[Feedback.NEGATIVE] ? 'animate-spin-once' : '',
className,
)}
/>
</button>
</div>
);
};
39 changes: 39 additions & 0 deletions app/api/chat/feedback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ReasonPhrases, StatusCodes } from 'http-status-codes';
import { NextRequest, NextResponse } from 'next/server';

import { getCurrentUser } from '@/actions/auth/get-current-user';
import { db } from '@/lib/db';

export const POST = async (req: NextRequest) => {
try {
const user = await getCurrentUser();

if (!user?.hasSubscription) {
return new NextResponse(ReasonPhrases.UNAUTHORIZED, { status: StatusCodes.UNAUTHORIZED });
}

const { messageId, feedback } = await req.json();

if (!messageId) {
return new NextResponse(ReasonPhrases.BAD_REQUEST, { status: StatusCodes.BAD_REQUEST });
}

const updatedFeedback = await db.chatMessageFeedback.upsert({
where: { messageId },
update: { feedback },
create: {
messageId,
feedback,
},
include: { message: true },
});

return NextResponse.json(updatedFeedback);
} catch (error) {
console.error('[POST_CHAT_MESSAGE_FEEDBACK]', error);

return new NextResponse(ReasonPhrases.INTERNAL_SERVER_ERROR, {
status: StatusCodes.INTERNAL_SERVER_ERROR,
});
}
};
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"@hello-pangea/dnd": "^16.5.0",
"@hookform/resolvers": "^3.3.4",
"@plaiceholder/next": "^3.0.0",
"@prisma/client": "^5.21.1",
"@prisma/client": "^6.5.0",
"@radix-ui/react-accordion": "^1.1.2",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-avatar": "^1.0.4",
Expand Down Expand Up @@ -131,7 +131,7 @@
"lint-staged": "^15.2.2",
"postcss": "^8",
"prettier": "^3.2.4",
"prisma": "^5.21.1",
"prisma": "^6.5.0",
"tailwindcss": "^3.3.0",
"typescript": "^5"
},
Expand Down
25 changes: 21 additions & 4 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -288,19 +288,36 @@ model CsmIssue {
}

// Chat Copilot
enum ChatFeedback {
positive
negative
}

model ChatMessage {
id String @id @default(uuid())
id String @id @default(uuid())
content String
conversation ChatConversation? @relation(fields: [conversationId], references: [id], onDelete: Cascade)
conversation ChatConversation? @relation(fields: [conversationId], references: [id], onDelete: Cascade)
conversationId String?
createdAt DateTime @default(now())
createdAt DateTime @default(now())
feedback ChatMessageFeedback?
model String
role String
updatedAt DateTime @updatedAt
updatedAt DateTime @updatedAt

@@index([conversationId])
}

model ChatMessageFeedback {
id String @id @default(uuid())
createdAt DateTime @default(now())
feedback ChatFeedback
message ChatMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)
messageId String @unique
updatedAt DateTime @updatedAt

@@index([messageId])
}

model ChatConversation {
id String @id @default(uuid())
createdAt DateTime @default(now())
Expand Down
Loading