Skip to content

siwa chat widget #7128

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { supportedERCs } from "./_utils/detectedFeatures/supportedERCs";
import { getContractPageParamsInfo } from "./_utils/getContractFromParams";
import { getContractPageMetadata } from "./_utils/getContractPageMetadata";
import { getContractPageSidebarLinks } from "./_utils/getContractPageSidebarLinks";
import { examplePrompts } from "../../../../../nebula-app/(app)/data/examplePrompts";

export default async function Layout(props: {
params: Promise<{
Expand Down Expand Up @@ -94,14 +95,6 @@ Users may be considering integrating the contract into their applications. Discu

The following is the user's message:`;

const examplePrompts: string[] = [
"What does this contract do?",
"What permissions or roles exist in this contract?",
"Which functions are used the most?",
"Has this contract been used recently?",
"Who are the largest holders/users of this?",
];

return (
<ContractPageLayout
chainMetadata={chainMetadata}
Expand All @@ -124,10 +117,7 @@ The following is the user's message:`;
chainIds: [chainId],
wallet: accountAddress ?? undefined,
}}
examplePrompts={examplePrompts.map((prompt) => ({
title: prompt,
message: prompt,
}))}
examplePrompts={examplePrompts}
/>
{props.children}
</ContractPageLayout>
Expand Down
39 changes: 16 additions & 23 deletions apps/dashboard/src/app/(app)/(dashboard)/support/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
import { BookOpenIcon, ChevronRightIcon } from "lucide-react";
import type { Metadata } from "next";
import Image from "next/image";
Expand All @@ -10,7 +9,8 @@ import contractsIcon from "../../../../../public/assets/support/contracts.png";
import engineIcon from "../../../../../public/assets/support/engine.png";
import miscIcon from "../../../../../public/assets/support/misc.svg";
import connectIcon from "../../../../../public/assets/support/wallets.png";
import { NebulaChatButton } from "../../../nebula-app/(app)/components/FloatingChat/FloatingChat";
import { getTeams } from "../../../../@/api/team";
import { CustomChatButton } from "../../../nebula-app/(app)/components/CustomChat/CustomChatButton";
import {
getAuthToken,
getAuthTokenWalletAddress,
Expand Down Expand Up @@ -118,25 +118,21 @@ const HELP_PRODUCTS = [
},
] as const;

export const siwaExamplePrompts = [
"I see thirdweb support reference # in my console log please help me",
"What does this contract revert error mean",
"I want to add inapp wallet with sign in with X/twitter auth to my react app",
"Here is my code can you tell me why i'm seeing this error",
];

export default async function SupportPage() {
const [authToken, accountAddress] = await Promise.all([
getAuthToken(),
getAuthTokenWalletAddress(),
]);

const client = getClientThirdwebClient({
jwt: authToken,
teamId: undefined,
});

const supportPromptPrefix =
"You are a Customer Success Agent at thirdweb, assisting customers with blockchain and Web3-related issues. Use the following details to craft a professional, empathetic response: ";
const examplePrompts = [
"ERC20 - Transfer Amount Exceeds Allowance",
"Replacement transaction underpriced / Replacement fee too low",
"Nonce too low: next nonce #, tx nonce #",
"Nonce too high",
];
const teams = await getTeams();
const teamId = teams?.[0]?.id ?? undefined;

return (
<main className="flex flex-col gap-12 pb-12">
Expand All @@ -157,22 +153,19 @@ export default async function SupportPage() {
team.
</p>
<div className="mt-6 flex w-full flex-col items-center gap-3">
<NebulaChatButton
<CustomChatButton
isLoggedIn={!!accountAddress}
networks="all"
isFloating={false}
pageType="support"
label="Ask Nebula AI for support"
client={client}
nebulaParams={{
messagePrefix: supportPromptPrefix,
chainIds: [],
wallet: accountAddress ?? undefined,
}}
label="Ask AI for support"
examplePrompts={examplePrompts.map((prompt) => ({
title: prompt,
message: prompt,
}))}
authToken={authToken || undefined}
teamId={teamId}
clientId={undefined}
/>

<Link
Expand Down
19 changes: 19 additions & 0 deletions apps/dashboard/src/app/(app)/team/[team_slug]/(team)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { TabPathLinks } from "@/components/ui/tabs";
import { AnnouncementBanner } from "components/notices/AnnouncementBanner";
import { redirect } from "next/navigation";
import { getClientThirdwebClient } from "../../../../../@/constants/thirdweb-client.client";
import { CustomChatButton } from "../../../../nebula-app/(app)/components/CustomChat/CustomChatButton";
import { examplePrompts } from "../../../../nebula-app/(app)/data/examplePrompts";
import { getValidAccount } from "../../../account/settings/getAccount";
import {
getAuthToken,
Expand Down Expand Up @@ -91,6 +93,23 @@ export default async function TeamLayout(props: {
</div>

<main className="flex grow flex-col">{props.children}</main>
<div className="fixed right-6 bottom-6 z-50">
<CustomChatButton
isLoggedIn={true}
networks="all"
isFloating={true}
pageType="support"
label="Ask AI Assistant"
customApiParams={{
messagePrefix: `You are helping a user in the team "${team.name}". `,
chainIds: [],
wallet: undefined,
}}
examplePrompts={examplePrompts}
teamId={team.id}
authToken={authToken}
/>
</div>
<AppFooter />
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
import { TeamHeaderLoggedIn } from "../../components/TeamHeader/team-header-logged-in.client";
import { ProjectSidebarLayout } from "./components/ProjectSidebarLayout";
import { SaveLastUsedProject } from "./components/SaveLastUsedProject";
import { CustomChatButton } from "../../../../nebula-app/(app)/components/CustomChat/CustomChatButton";
import { siwaExamplePrompts } from "../../../(dashboard)/support/page";

export default async function ProjectLayout(props: {
children: React.ReactNode;
Expand Down Expand Up @@ -78,6 +80,19 @@ export default async function ProjectLayout(props: {
{props.children}
</ProjectSidebarLayout>
</div>
<div className="fixed right-6 bottom-6 z-50">
<CustomChatButton
isLoggedIn={true}
networks="all"
isFloating={true}
pageType="support"
label="Ask AI Assistant"
examplePrompts={siwaExamplePrompts}
teamId={team.id}
clientId={project.publishableKey}
authToken={authToken}
/>
</div>
<SaveLastUsedProject projectId={project.id} teamId={team.id} />
</SidebarProvider>
);
Expand Down
6 changes: 6 additions & 0 deletions apps/dashboard/src/app/(app)/team/[team_slug]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ArrowRightIcon } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { getAuthToken } from "../../api/lib/getAuthToken";
import { EnsureValidConnectedWalletLoginServer } from "../../components/EnsureValidConnectedWalletLogin/EnsureValidConnectedWalletLoginServer";
import { isTeamOnboardingComplete } from "../../login/onboarding/isOnboardingRequired";
import { SaveLastVisitedTeamPage } from "../components/last-visited-page/SaveLastVisitedPage";
Expand All @@ -18,12 +19,17 @@ export default async function RootTeamLayout(props: {
params: Promise<{ team_slug: string }>;
}) {
const { team_slug } = await props.params;
const authToken = await getAuthToken();
const team = await getTeamBySlug(team_slug).catch(() => null);

if (!team) {
redirect("/team");
}

if (!authToken) {
redirect("/login");
}

if (!isTeamOnboardingComplete(team)) {
redirect(`/get-started/team/${team.slug}`);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export function ChatBar(props: {
isConnectingWallet: boolean;
allowImageUpload: boolean;
onLoginClick: undefined | (() => void);
placeholder: string;
}) {
const [message, setMessage] = useState(props.prefillMessage || "");
const selectedChainIds = props.context?.chainIds?.map((x) => Number(x)) || [];
Expand Down Expand Up @@ -142,7 +143,7 @@ export function ChatBar(props: {
<div className="p-2">
<div className="max-h-[200px] overflow-y-auto">
<AutoResizeTextarea
placeholder={"Ask Nebula"}
placeholder={props.placeholder}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ export function ChatPageContent(props: {

<div className="container max-w-[800px]">
<ChatBar
placeholder="Ask Nebula"
isConnectingWallet={connectionStatus === "connecting"}
showContextSelector={true}
connectedWallets={connectedWalletsMeta}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ function Variant(props: {
return (
<BadgeContainer label={props.label}>
<ChatBar
placeholder={"Ask Nebula"}
isConnectingWallet={props.isConnectingWallet || false}
client={storybookThirdwebClient}
abortChatStream={() => {}}
Expand Down
117 changes: 115 additions & 2 deletions apps/dashboard/src/app/nebula-app/(app)/components/Chats.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ScrollShadow } from "@/components/ui/ScrollShadow/ScrollShadow";
import { cn } from "@/lib/utils";
import { MarkdownRenderer } from "components/contract-components/published-contract/markdown-renderer";
import { AlertCircleIcon } from "lucide-react";
import { useEffect, useRef } from "react";
import { AlertCircleIcon, ThumbsDownIcon, ThumbsUpIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import type { ThirdwebClient } from "thirdweb";
import { Button } from "../../../../@/components/ui/button";
import type { NebulaSwapData } from "../api/chat";
import type { NebulaUserMessage, NebulaUserMessageContent } from "../api/types";
import { NebulaIcon } from "../icons/NebulaIcon";
Expand Down Expand Up @@ -72,6 +73,7 @@ export function Chats(props: {
enableAutoScroll: boolean;
useSmallText?: boolean;
sendMessage: (message: NebulaUserMessage) => void;
teamId: string | undefined;
}) {
const { messages, setEnableAutoScroll, enableAutoScroll } = props;
const scrollAnchorRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -153,6 +155,7 @@ export function Chats(props: {
nextMessage={props.messages[index + 1]}
authToken={props.authToken}
sessionId={props.sessionId}
teamId={props.teamId}
/>
</div>
);
Expand All @@ -172,6 +175,7 @@ function RenderMessage(props: {
sendMessage: (message: NebulaUserMessage) => void;
nextMessage: ChatMessage | undefined;
authToken: string;
teamId: string | undefined;
sessionId: string | undefined;
}) {
const { message } = props;
Expand Down Expand Up @@ -224,6 +228,42 @@ function RenderMessage(props: {
);
}

// Feedback for assistant messages
if (props.message.type === "assistant") {
return (
<div className="flex flex-col gap-2">
<div className="flex gap-3">
{/* Left Icon */}
<div className="-translate-y-[2px] relative shrink-0">
<div className="flex size-9 items-center justify-center rounded-full border bg-card">
<NebulaIcon className="size-5 text-muted-foreground" />
</div>
</div>
{/* Right Message */}
<div className="min-w-0 grow">
<ScrollShadow className="rounded-lg">
<RenderResponse
message={message}
isMessagePending={props.isMessagePending}
client={props.client}
sendMessage={props.sendMessage}
nextMessage={props.nextMessage}
sessionId={props.sessionId}
authToken={props.authToken}
/>
</ScrollShadow>
<FeedbackButtons
sessionId={props.sessionId}
messageText={message.type === "assistant" ? message.text : ""}
authToken={props.authToken}
teamId={props.teamId}
/>
</div>
</div>
</div>
);
}

return (
<div className="flex gap-3">
{/* Left Icon */}
Expand Down Expand Up @@ -422,3 +462,76 @@ function StyledMarkdownRenderer(props: {
/>
);
}

function FeedbackButtons({
sessionId,
messageText,
authToken,
teamId,
}: {
sessionId: string | undefined;
messageText: string;
authToken: string;
teamId: string | undefined;
}) {
const [, setFeedback] = useState<"good" | "bad" | null>(null);
const [loading, setLoading] = useState(false);
const [thankYou, setThankYou] = useState(false);

async function sendFeedback(rating: "good" | "bad") {
setLoading(true);
try {
const apiUrl = process.env.NEXT_PUBLIC_SIWA_URL;
await fetch(`${apiUrl}/v1/chat/feedback`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
...(teamId ? { "x-team-id": teamId } : {}),
},
body: JSON.stringify({
conversationId: sessionId,
message: messageText,
rating,
}),
});
setFeedback(rating);
setThankYou(true);
} catch {
// TODO handle error
} finally {
setLoading(false);
}
}

if (thankYou) {
return (
<div className="mt-2 text-muted-foreground text-xs">
Thank you for your feedback!
</div>
);
}

return (
<div className="mt-2 flex gap-2">
<Button
className="rounded-full border p-2 hover:bg-muted-foreground/10"
variant="ghost"
onClick={() => sendFeedback("bad")}
disabled={loading}
aria-label="Thumbs down"
>
<ThumbsDownIcon className="size-4 text-red-500" />
</Button>
<Button
className="rounded-full border p-2 hover:bg-muted-foreground/10"
variant="ghost"
onClick={() => sendFeedback("good")}
disabled={loading}
aria-label="Thumbs up"
>
<ThumbsUpIcon className="size-4 text-green-500" />
</Button>
</div>
);
}
Loading
Loading