chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:58:18 +08:00
commit 6d5d58c1a9
18293 changed files with 3502153 additions and 0 deletions
@@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="A solution template for building GenAI applications with AgentCore"
/>
<title>Fullstack AgentCore Solution Template</title>
<!-- Google Fonts for Geist Sans and Geist Mono -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Geist+Sans:wght@100..900&family=Geist+Mono:wght@100..900&display=swap"
rel="stylesheet"
/>
<!--
Set the theme class BEFORE first paint to avoid a white→dark flash.
useTheme applies the theme in a useEffect (post-mount), so without this the
app paints unthemed (light) first, then flips. This blocking inline script
matches useTheme's "system" default (light/dark on <html>) so there's no
flash and no mismatch when the provider re-applies.
-->
<script>
(function () {
try {
var d = window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.classList.add(d ? "dark" : "light");
} catch (e) {}
})();
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,65 @@
{
"name": "fullstack-agentcore-solution-template-frontend",
"version": "0.4.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest --run",
"test:watch": "vitest",
"lint:fix": "eslint src/ --fix",
"clean": "rm -rf build/ node_modules/ .vite/"
},
"dependencies": {
"@copilotkit/react-core": "1.62.2",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-popover": "^1.1.17",
"@radix-ui/react-progress": "^1.1.7",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-separator": "^1.1.10",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tooltip": "^1.2.10",
"@types/react-syntax-highlighter": "^15.5.13",
"aws-amplify": "^6.16.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"oidc-client-ts": "^3.5.0",
"radix-ui": "^1.4.3",
"react": "^19.2.1",
"react-dom": "^19.2.1",
"react-dropzone": "^14.3.8",
"react-is": "^19.2.7",
"react-markdown": "^10.1.0",
"react-oidc-context": "^3.3.0",
"react-router-dom": "^6.21.0",
"react-spinners": "^0.17.0",
"react-syntax-highlighter": "^16.1.0",
"recharts": "^3.8.1",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.2.0",
"zod": "^3.25.76"
},
"devDependencies": {
"@shadcn/ui": "^0.0.4",
"@tailwindcss/postcss": "^4",
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.1",
"@types/node": "^25.0.3",
"@types/react": "^19",
"@types/react-dom": "^19",
"@vitejs/plugin-react": "^4.2.0",
"fast-check": "^4.5.3",
"jsdom": "^23.0.1",
"prettier": "^3.8.1",
"shadcn": "^3.0.0",
"tailwindcss": "^4",
"tw-animate-css": "^1.2.9",
"typescript": "^5",
"vite": "^7.3.1",
"vitest": "^4.0.18"
}
}
@@ -0,0 +1,7 @@
import tailwindcss from "@tailwindcss/postcss";
const config = {
plugins: [tailwindcss],
};
export default config;
@@ -0,0 +1,16 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { BrowserRouter } from "react-router-dom";
import { AuthProvider } from "@/components/auth/AuthProvider";
import AppRoutes from "./routes";
export default function App() {
return (
<BrowserRouter>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</BrowserRouter>
);
}
@@ -0,0 +1,48 @@
"use client";
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Global context provider for the application
* Provides shared state and functionality across components
*/
import { createContext, useContext, PropsWithChildren, useState } from "react";
interface GlobalContextType {
isLoading: boolean;
setIsLoading: (loading: boolean) => void;
}
const GlobalContext = createContext<GlobalContextType | undefined>(undefined);
/**
* Hook to access the global context
* @returns The global context value
* @throws Error if used outside of GlobalContextProvider
*/
export function useGlobal(): GlobalContextType {
const context = useContext(GlobalContext);
if (context === undefined) {
throw new Error("useGlobal must be used within a GlobalContextProvider");
}
return context;
}
/**
* Global context provider component
* Wraps the application to provide global state
* @param children - Child components to wrap
*/
export function GlobalContextProvider({ children }: PropsWithChildren) {
const [isLoading, setIsLoading] = useState(false);
const value: GlobalContextType = {
isLoading,
setIsLoading,
};
return (
<GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
);
}
@@ -0,0 +1,75 @@
"use client";
import { createCognitoAuthConfig, cognitoAuthConfig } from "@/lib/auth";
import { useEffect, useState, PropsWithChildren } from "react";
import { AuthProvider as OidcAuthProvider } from "react-oidc-context";
import { WebStorageStateStore } from "oidc-client-ts";
import { AutoSignin } from "./AutoSignin";
interface CognitoAuthConfig {
authority?: string;
client_id?: string;
redirect_uri?: string;
post_logout_redirect_uri?: string;
response_type?: string;
scope?: string;
automaticSilentRenew?: boolean;
userStore?: WebStorageStateStore;
}
const AuthProvider = ({ children }: PropsWithChildren) => {
const [authConfig, setAuthConfig] = useState<CognitoAuthConfig | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadConfig() {
try {
const config = await createCognitoAuthConfig();
setAuthConfig(config);
} catch (error) {
console.error("Failed to load auth configuration:", error);
console.error("Falling back to environment variables");
// Fallback to env vars on error
setAuthConfig(cognitoAuthConfig);
} finally {
setLoading(false);
}
}
loadConfig();
}, []);
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen text-xl">
Loading authentication configuration...
</div>
);
}
if (!authConfig) {
return (
<div className="flex items-center justify-center min-h-screen text-xl">
Failed to load authentication configuration
</div>
);
}
return (
<OidcAuthProvider
{...authConfig}
// This callback removes the `?code=` from the URL, which will break page refreshes
onSigninCallback={() => {
window.history.replaceState(
{},
document.title,
window.location.pathname,
);
}}
>
<AutoSignin>{children}</AutoSignin>
</OidcAuthProvider>
);
};
export { AuthProvider };
@@ -0,0 +1,42 @@
"use client";
import { ReactNode, useEffect, useState, PropsWithChildren } from "react";
import { useAuth } from "react-oidc-context";
import { Button } from "@/components/ui/button";
function AutoSigninContent({ children }: PropsWithChildren) {
const auth = useAuth();
if (auth.isLoading) {
return (
<div className="flex items-center justify-center min-h-screen text-xl">
Loading...
</div>
);
}
if (!auth.isAuthenticated) {
return (
<div className="flex flex-col items-center justify-center min-h-screen gap-4">
<p className="text-4xl">Please sign in</p>
<Button onClick={() => auth.signinRedirect()}>Sign In</Button>
</div>
);
}
return <>{children}</>;
}
export function AutoSignin({ children }: { children: ReactNode }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return null;
}
return <AutoSigninContent>{children}</AutoSigninContent>;
}
@@ -0,0 +1,22 @@
// The canvas is always visible alongside the chat pane (spec: "render chat plus a
// todo canvas in the same page shell"). It shows an empty state when there are no
// todos, and fills in as the agent or user adds items.
import { useAgent } from "@copilotkit/react-core/v2";
import { TodoList } from "./TodoList";
import type { Todo } from "./types";
export function TodoCanvas() {
const { agent } = useAgent();
return (
<div className="h-full overflow-y-auto bg-white dark:bg-neutral-950 [background-image:radial-gradient(circle,#d5d5d5_1px,transparent_1px)] dark:[background-image:radial-gradient(circle,#333_1px,transparent_1px)] [background-size:20px_20px]">
<div className="max-w-4xl mx-auto px-8 py-10 h-full">
<TodoList
todos={(agent.state as { todos?: Todo[] })?.todos ?? []}
onUpdate={(updatedTodos) => agent.setState({ todos: updatedTodos })}
isAgentRunning={agent.isRunning}
/>
</div>
</div>
);
}
@@ -0,0 +1,222 @@
import { useState, useRef, useEffect } from "react";
import type { Todo } from "./types";
interface TodoCardProps {
todo: Todo;
onToggleStatus: (todo: Todo) => void;
onDelete: (todo: Todo) => void;
onUpdateTitle: (todoId: string, title: string) => void;
onUpdateDescription: (todoId: string, description: string) => void;
onUpdateEmoji: (todoId: string, emoji: string) => void;
}
const EMOJI_OPTIONS = ["✅", "🔥", "🎯", "💡", "🚀"];
export function TodoCard({
todo,
onToggleStatus,
onDelete,
onUpdateTitle,
onUpdateDescription,
onUpdateEmoji,
}: TodoCardProps) {
const [editingField, setEditingField] = useState<
"title" | "description" | null
>(null);
const [editValue, setEditValue] = useState("");
const [showEmojiPicker, setShowEmojiPicker] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const isCompleted = todo.status === "completed";
const truncatedDescription =
todo.description.length > 120
? todo.description.slice(0, 120) + "..."
: todo.description;
const startEdit = (field: "title" | "description") => {
setEditingField(field);
setEditValue(field === "title" ? todo.title : todo.description);
};
const saveEdit = (field: "title" | "description") => {
if (!editValue.trim()) {
// Don't save empty value — keep the editor open
return;
}
if (field === "title") onUpdateTitle(todo.id, editValue.trim());
else onUpdateDescription(todo.id, editValue.trim());
setEditingField(null);
setEditValue("");
};
const cancelEdit = () => {
setEditingField(null);
setEditValue("");
};
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
textareaRef.current.style.height =
textareaRef.current.scrollHeight + "px";
}
}, [editValue]);
return (
<div
className={`group relative rounded-2xl p-5 transition-all duration-150 border ${
isCompleted
? "bg-neutral-100 border-neutral-200 dark:bg-neutral-800/50 dark:border-neutral-700"
: "bg-white border-neutral-300 dark:bg-neutral-800 dark:border-neutral-700"
}`}
>
{/* Delete button — visible on hover */}
<button
onClick={() => onDelete(todo)}
className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity duration-100 cursor-pointer rounded-full p-1 text-neutral-400 hover:text-neutral-600 dark:text-neutral-500 dark:hover:text-neutral-300"
aria-label="Delete todo"
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
{/* Emoji avatar */}
<div className="relative inline-block mb-3">
<button
onClick={() => setShowEmojiPicker(!showEmojiPicker)}
className={`block text-3xl leading-none cursor-pointer rounded-xl p-2 transition-colors duration-100 ${
isCompleted
? "bg-neutral-200 dark:bg-neutral-700"
: "bg-neutral-100 dark:bg-neutral-700/50"
}`}
aria-label="Change emoji"
>
{todo.emoji}
</button>
{showEmojiPicker && (
<div className="absolute top-0 left-full ml-2 z-10 flex gap-1 p-1.5 rounded-full bg-white border border-neutral-300 shadow-lg dark:bg-neutral-800 dark:border-neutral-600">
{EMOJI_OPTIONS.map((emoji) => (
<button
key={emoji}
onClick={() => {
onUpdateEmoji(todo.id, emoji);
setShowEmojiPicker(false);
}}
className="text-lg w-8 h-8 flex items-center justify-center rounded-full cursor-pointer transition-colors hover:bg-neutral-100 dark:hover:bg-neutral-700"
>
{emoji}
</button>
))}
</div>
)}
</div>
{/* Title + description */}
<div className="flex items-start gap-3">
<button
onClick={() => onToggleStatus(todo)}
className="flex-shrink-0 mt-[2px] cursor-pointer"
aria-label={isCompleted ? "Mark as incomplete" : "Mark as complete"}
>
{isCompleted ? (
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<rect
x="1"
y="1"
width="18"
height="18"
rx="6"
className="fill-neutral-900 dark:fill-neutral-100"
/>
<path
d="M6 10.5L8.5 13L14 7"
className="stroke-white dark:stroke-neutral-900"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
) : (
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<rect
x="1"
y="1"
width="18"
height="18"
rx="6"
className="stroke-neutral-300 dark:stroke-neutral-600"
strokeWidth="1.5"
/>
</svg>
)}
</button>
<div className="flex-1 min-w-0">
{editingField === "title" ? (
<input
type="text"
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onBlur={() => saveEdit("title")}
onKeyDown={(e) => {
if (e.key === "Enter") saveEdit("title");
if (e.key === "Escape") cancelEdit();
}}
className="w-full text-[16px] font-semibold focus:outline-none bg-transparent text-neutral-900 dark:text-neutral-100 border-b-2 border-neutral-900 dark:border-neutral-100 pb-[2px]"
autoFocus
aria-label="Edit todo title"
/>
) : (
<div
onClick={() => startEdit("title")}
className={`text-[16px] font-semibold cursor-text break-words leading-snug ${
isCompleted
? "text-neutral-400 line-through dark:text-neutral-500"
: "text-neutral-900 dark:text-neutral-100"
}`}
>
{todo.title}
</div>
)}
{editingField === "description" ? (
<textarea
ref={textareaRef}
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onBlur={() => saveEdit("description")}
onKeyDown={(e) => {
if (e.key === "Escape") cancelEdit();
}}
className="w-full mt-1.5 text-[14px] leading-relaxed focus:outline-none resize-none bg-transparent text-neutral-500 dark:text-neutral-400 border-b-2 border-neutral-900 dark:border-neutral-100 pb-[2px]"
rows={1}
autoFocus
aria-label="Edit todo description"
/>
) : (
<p
onClick={() => startEdit("description")}
className={`mt-1.5 text-[14px] leading-relaxed cursor-text ${
isCompleted
? "text-neutral-300 line-through dark:text-neutral-600"
: "text-neutral-500 dark:text-neutral-400"
}`}
>
{truncatedDescription}
</p>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,86 @@
import type { Todo } from "./types";
import { TodoCard } from "./TodoCard";
interface TodoColumnProps {
title: string;
todos: Todo[];
emptyMessage: string;
showAddButton?: boolean;
onAddTodo?: () => void;
onToggleStatus: (todo: Todo) => void;
onDelete: (todo: Todo) => void;
onUpdateTitle: (todoId: string, title: string) => void;
onUpdateDescription: (todoId: string, description: string) => void;
onUpdateEmoji: (todoId: string, emoji: string) => void;
isAgentRunning: boolean;
}
export function TodoColumn({
title,
todos,
emptyMessage,
showAddButton = false,
onAddTodo,
onToggleStatus,
onDelete,
onUpdateTitle,
onUpdateDescription,
onUpdateEmoji,
isAgentRunning,
}: TodoColumnProps) {
return (
<section aria-label={`${title} column`} className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-5">
<div className="flex items-center gap-3">
<h2 className="text-[18px] font-bold tracking-tight text-neutral-900 dark:text-neutral-100">
{title}
</h2>
<span className="text-[12px] font-semibold rounded-full px-2 py-0.5 text-neutral-500 bg-neutral-200 dark:text-neutral-400 dark:bg-neutral-700">
{todos.length}
</span>
</div>
{showAddButton && onAddTodo && (
<button
onClick={onAddTodo}
className="rounded-full cursor-pointer transition-colors p-1.5 text-neutral-500 bg-neutral-200 hover:bg-neutral-300 hover:text-neutral-900 dark:text-neutral-400 dark:bg-neutral-700 dark:hover:bg-neutral-600 dark:hover:text-neutral-100"
aria-label="Add new todo"
disabled={isAgentRunning}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
</button>
)}
</div>
<div className="space-y-4">
{todos.length === 0 ? (
<div className="text-center text-[14px] rounded-2xl border-2 border-dashed p-5 min-h-[151px] flex items-center justify-center text-neutral-400 border-neutral-300 dark:text-neutral-500 dark:border-neutral-700">
{emptyMessage}
</div>
) : (
todos.map((todo) => (
<TodoCard
key={todo.id}
todo={todo}
onToggleStatus={onToggleStatus}
onDelete={onDelete}
onUpdateTitle={onUpdateTitle}
onUpdateDescription={onUpdateDescription}
onUpdateEmoji={onUpdateEmoji}
/>
))
)}
</div>
</section>
);
}
@@ -0,0 +1,104 @@
import type { Todo } from "./types";
import { TodoColumn } from "./TodoColumn";
interface TodoListProps {
todos: Todo[];
onUpdate: (todos: Todo[]) => void;
isAgentRunning: boolean;
}
export function TodoList({ todos, onUpdate, isAgentRunning }: TodoListProps) {
const pendingTodos = todos.filter((t) => t.status === "pending");
const completedTodos = todos.filter((t) => t.status === "completed");
const toggleStatus = (todo: Todo) => {
onUpdate(
todos.map((t) =>
t.id === todo.id
? {
...t,
status: t.status === "completed" ? "pending" : "completed",
}
: t,
),
);
};
const deleteTodo = (todo: Todo) => {
onUpdate(todos.filter((t) => t.id !== todo.id));
};
const updateTitle = (todoId: string, title: string) => {
onUpdate(todos.map((t) => (t.id === todoId ? { ...t, title } : t)));
};
const updateDescription = (todoId: string, description: string) => {
onUpdate(todos.map((t) => (t.id === todoId ? { ...t, description } : t)));
};
const updateEmoji = (todoId: string, emoji: string) => {
onUpdate(todos.map((t) => (t.id === todoId ? { ...t, emoji } : t)));
};
const addTodo = () => {
const newTodo: Todo = {
id: crypto.randomUUID(),
title: "New Todo",
description: "Add a description",
emoji: "🎯",
status: "pending",
};
onUpdate([...todos, newTodo]);
};
if (todos.length === 0) {
return (
<div className="flex flex-col items-center justify-center h-full gap-4">
<div className="text-5xl"></div>
<p className="text-[16px] font-semibold text-neutral-900 dark:text-neutral-100">
No tasks yet
</p>
<p className="text-[14px] text-neutral-500 dark:text-neutral-400">
Create your first task to get started
</p>
<button
onClick={addTodo}
className="mt-2 px-5 py-2.5 text-[14px] font-semibold rounded-full cursor-pointer transition-colors text-white bg-neutral-900 hover:bg-neutral-700 dark:text-neutral-900 dark:bg-neutral-100 dark:hover:bg-neutral-300"
aria-label="Add your first todo task"
disabled={isAgentRunning}
>
Add a task
</button>
</div>
);
}
return (
<div className="flex gap-8 h-full">
<TodoColumn
title="To Do"
todos={pendingTodos}
emptyMessage="No pending tasks"
showAddButton
onAddTodo={addTodo}
onToggleStatus={toggleStatus}
onDelete={deleteTodo}
onUpdateTitle={updateTitle}
onUpdateDescription={updateDescription}
onUpdateEmoji={updateEmoji}
isAgentRunning={isAgentRunning}
/>
<TodoColumn
title="Done"
todos={completedTodos}
emptyMessage="No completed tasks yet"
onToggleStatus={toggleStatus}
onDelete={deleteTodo}
onUpdateTitle={updateTitle}
onUpdateDescription={updateDescription}
onUpdateEmoji={updateEmoji}
isAgentRunning={isAgentRunning}
/>
</div>
);
}
@@ -0,0 +1,7 @@
export interface Todo {
id: string;
title: string;
description: string;
emoji: string;
status: "pending" | "completed";
}
@@ -0,0 +1,48 @@
.layout {
display: grid;
/*
Reserve the desktop drawer's width (its default `--cpk-drawer-width`, 320px)
as a fixed first column so the layout does NOT shift when the client-only
drawer mounts. On mobile the drawer is an off-canvas overlay (out of flow),
so the column collapses and the content fills the width.
*/
grid-template-columns: 320px minmax(0, 1fr);
height: 100dvh;
width: 100%;
overflow: hidden;
/*
Align the drawer's mobile launcher with this app's header controls. These
custom properties inherit into <copilotkit-threads-drawer> and pierce its shadow
root; tuned to match the example header's top-left inset.
*/
--cpk-drawer-launcher-top: 7px;
--cpk-drawer-launcher-left: 16px;
}
.mainPanel {
/*
Pin the content to the SECOND grid track explicitly. The client-only
<CopilotThreadsDrawer> renders nothing during the drawer's mount gate, so without
an explicit placement the panel would flow into the reserved first track
and then jump once the drawer mounts. Forcing column 2 keeps it put.
*/
grid-column: 2;
min-width: 0;
height: 100dvh;
overflow: hidden;
}
/*
Mobile (≤768px): the drawer is an off-canvas overlay — collapse to a single
track. MUST come after the base rules (media queries add no specificity, so a
later same-specificity base rule would otherwise leak the desktop layout).
*/
@media (max-width: 768px) {
.layout {
grid-template-columns: minmax(0, 1fr);
}
.mainPanel {
grid-column: auto;
}
}
@@ -0,0 +1,66 @@
import { useEffect, useRef } from "react";
interface ToolReasoningProps {
name: string;
args?: object | unknown;
status: string;
}
const statusIndicator = {
executing: (
<span className="inline-block h-3 w-3 rounded-full border-2 border-gray-400 border-t-transparent animate-spin" />
),
inProgress: (
<span className="inline-block h-3 w-3 rounded-full border-2 border-gray-400 border-t-transparent animate-spin" />
),
complete: <span className="text-green-500 text-xs"></span>,
};
function formatValue(value: unknown): string {
if (Array.isArray(value)) return `[${value.length} items]`;
if (typeof value === "object" && value !== null)
return `{${Object.keys(value).length} keys}`;
if (typeof value === "string") return `"${value}"`;
return String(value);
}
export function ToolReasoning({ name, args, status }: ToolReasoningProps) {
const entries = args ? Object.entries(args as Record<string, unknown>) : [];
const detailsRef = useRef<HTMLDetailsElement>(null);
const toolStatus = status as "complete" | "inProgress" | "executing";
// Auto-open while executing, auto-close when complete
useEffect(() => {
if (!detailsRef.current) return;
detailsRef.current.open = status === "executing";
}, [status]);
return (
<div className="my-2 text-sm">
{entries.length > 0 ? (
<details ref={detailsRef} open>
<summary className="flex items-center gap-2 text-gray-600 dark:text-gray-400 cursor-pointer list-none">
{statusIndicator[toolStatus]}
<span className="font-medium">{name}</span>
<span className="text-[10px]"></span>
</summary>
<div className="pl-5 mt-1 space-y-1 text-xs text-gray-500 dark:text-zinc-400">
{entries.map(([key, value]) => (
<div key={key} className="flex gap-2 min-w-0">
<span className="font-medium shrink-0">{key}:</span>
<span className="text-gray-600 dark:text-gray-400 truncate">
{formatValue(value)}
</span>
</div>
))}
</div>
</details>
) : (
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
{statusIndicator[toolStatus]}
<span className="font-medium">{name}</span>
</div>
)}
</div>
);
}
@@ -0,0 +1,185 @@
// frontend/src/components/chat/CopilotChatInterface.tsx
"use client";
import "@copilotkit/react-core/v2/styles.css";
import { useEffect, useMemo, useState } from "react";
import {
CopilotChat,
CopilotChatConfigurationProvider,
CopilotThreadsDrawer,
CopilotKitProvider,
useFrontendTool,
} from "@copilotkit/react-core/v2";
import { useAuth as useOidcAuth } from "react-oidc-context";
import { loadAwsConfig } from "@/lib/runtime-config";
import type { AwsExportsConfig } from "@/lib/runtime-config";
import { useExampleSuggestions } from "@/hooks/useExampleSuggestions";
import { useCopilotExamples } from "@/hooks/useCopilotExamples";
import { ThemeProvider } from "@/hooks/useTheme";
import { TodoCanvas } from "@/components/canvas/TodoCanvas";
import { ModeToggle } from "@/components/ui/mode-toggle";
import styles from "./CopilotKit.module.css";
const COPILOTKIT_AGENT_ID = "default";
type ResolvedAwsExportsConfig = AwsExportsConfig & {
copilotKitRuntimeUrl: string;
};
function CopilotChatContent() {
const [mode, setMode] = useState<"chat" | "app">("chat");
useExampleSuggestions();
useCopilotExamples();
useFrontendTool({
name: "enableAppMode",
description: "Enable app mode when working with the todo canvas.",
handler: async () => {
setMode("app");
},
});
useFrontendTool({
name: "enableChatMode",
description: "Enable chat mode",
handler: async () => {
setMode("chat");
},
});
return (
/*
One UNCONTROLLED CopilotChatConfigurationProvider (no `threadId` prop) owns
the active thread for the whole surface. The SDK <CopilotThreadsDrawer> drives it
directly — picking a row sets the active thread, "+ New" resets to a fresh
thread — with no host thread-state. The drawer inherits `runtimeUrl` and
the Cognito auth `headers` from the surrounding <CopilotKitProvider> (via
useThreads -> useCopilotKit), so threads are fetched authenticated with no
explicit props. A *controlled* provider would block "+ New" from
resetting, so uncontrolled-inside-provider is required, not optional.
*/
<CopilotChatConfigurationProvider agentId={COPILOTKIT_AGENT_ID}>
<div className={styles.layout}>
{/* SDK threads drawer (replaces the hand-rolled fork). License-gated: the locked view's Upgrade CTA opens the Intelligence docs by default. */}
<CopilotThreadsDrawer agentId={COPILOTKIT_AGENT_ID} />
<div className={styles.mainPanel}>
<div className="h-full flex flex-row">
<ModeToggle mode={mode} onModeChange={setMode} />
<div
className={`max-h-full overflow-y-auto [&_.copilotKitChat]:h-full [&_.copilotKitChat]:border-0 [&_.copilotKitChat]:shadow-none ${
mode === "app"
? "w-1/2 px-6 max-lg:hidden"
: "flex-1 px-4 lg:px-6"
}`}
>
<CopilotChat agentId={COPILOTKIT_AGENT_ID} className="h-full" />
</div>
<div
className={`h-full overflow-hidden ${
mode === "app"
? "w-1/2 border-l dark:border-zinc-700 max-lg:w-full max-lg:border-l-0"
: "w-0 border-l-0"
}`}
>
{/*
Fill the state panel's own width. The previous `lg:w-[66.666vw]`
was viewport-relative, so with a reserved drawer column it
overflowed this container (clipped by overflow-hidden) and
pushed centered content right of the visible box's center.
*/}
<div className="h-full w-full">
<TodoCanvas />
</div>
</div>
</div>
</div>
</div>
</CopilotChatConfigurationProvider>
);
}
function CopilotKitShell({
config,
accessToken,
}: {
config: ResolvedAwsExportsConfig;
accessToken: string | undefined;
}) {
const headers = useMemo(
() =>
accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
[accessToken],
);
return (
<CopilotKitProvider
runtimeUrl={config.copilotKitRuntimeUrl}
headers={headers}
useSingleEndpoint={false}
>
<CopilotChatContent />
</CopilotKitProvider>
);
}
export default function CopilotChatInterface() {
const auth = useOidcAuth();
const [config, setConfig] = useState<AwsExportsConfig | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let isMounted = true;
async function resolveConfig() {
try {
const runtimeConfig = await loadAwsConfig();
if (!isMounted) return;
if (!runtimeConfig || !runtimeConfig.copilotKitRuntimeUrl) {
throw new Error("CopilotKit runtime URL not found in configuration");
}
setConfig(runtimeConfig);
} catch (err) {
if (!isMounted) return;
const message = err instanceof Error ? err.message : "Unknown error";
setError(`Configuration error: ${message}`);
}
}
resolveConfig();
return () => {
isMounted = false;
};
}, []);
if (error) {
return (
<div className="flex h-full items-center justify-center px-6 text-center text-sm text-red-600">
{error}
</div>
);
}
if (!config) {
return (
<div className="flex h-full items-center justify-center px-6 text-center text-sm">
Loading CopilotKit configuration...
</div>
);
}
const accessToken = auth.user?.access_token ?? auth.user?.id_token;
return (
<ThemeProvider>
<div className="h-full bg-[#f5f7fb]">
<CopilotKitShell
config={config as ResolvedAwsExportsConfig}
accessToken={accessToken}
/>
</div>
</ThemeProvider>
);
}
@@ -0,0 +1,32 @@
// Define message types
export type MessageRole = "user" | "assistant";
export type ToolCallStatus = "streaming" | "executing" | "complete";
export interface ToolCall {
toolUseId: string;
name: string;
input: string;
result?: string;
status: ToolCallStatus;
}
export type MessageSegment =
| { type: "text"; content: string }
| { type: "tool"; toolCall: ToolCall };
export interface Message {
role: MessageRole;
content: string;
timestamp: string;
segments?: MessageSegment[];
}
// Define chat session types
export interface ChatSession {
id: string;
name: string;
history: Message[];
startDate: string;
endDate: string;
}
@@ -0,0 +1,94 @@
import {
BarChart as RechartsBarChart,
Bar,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { z } from "zod";
const CHART_COLORS = [
"#3b82f6",
"#8b5cf6",
"#ec4899",
"#f59e0b",
"#10b981",
"#06b6d4",
"#f97316",
];
const TOOLTIP_STYLE = {
backgroundColor: "var(--chart-tooltip-bg)",
border: "1px solid var(--chart-tooltip-border)",
borderRadius: "8px",
padding: "8px 12px",
color: "var(--foreground)",
};
export const BarChartPropsSchema = z.object({
title: z.string().describe("Chart title"),
description: z.string().describe("Brief description or subtitle"),
data: z.array(
z.object({
label: z.string(),
value: z.number(),
}),
),
});
type BarChartProps = z.infer<typeof BarChartPropsSchema>;
export function BarChart({ title, description, data }: BarChartProps) {
if (!data || !Array.isArray(data) || data.length === 0) {
return (
<div className="rounded-xl border dark:border-zinc-700 shadow-sm p-6 max-w-2xl mx-auto my-6 bg-[var(--background)]">
<div className="mb-4">
<h3 className="text-xl font-bold dark:text-white">{title}</h3>
<p className="text-sm text-gray-600 dark:text-zinc-400">
{description}
</p>
</div>
<p className="text-gray-500 dark:text-zinc-400 text-center py-8">
No data available
</p>
</div>
);
}
const coloredData = data.map((entry, index) => ({
...entry,
fill: CHART_COLORS[index % CHART_COLORS.length],
}));
return (
<div className="rounded-xl border dark:border-zinc-700 shadow-sm p-6 max-w-2xl mx-auto my-6 bg-[var(--background)]">
<div className="mb-4">
<h3 className="text-xl font-bold dark:text-white">{title}</h3>
<p className="text-sm text-gray-600 dark:text-zinc-400">
{description}
</p>
</div>
<ResponsiveContainer width="100%" height={300}>
<RechartsBarChart
data={coloredData}
margin={{ top: 5, right: 20, bottom: 5, left: 0 }}
>
<XAxis
dataKey="label"
tick={{ fontSize: 12 }}
stroke="var(--chart-axis)"
/>
<YAxis tick={{ fontSize: 12 }} stroke="var(--chart-axis)" />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Bar
isAnimationActive={false}
dataKey="value"
radius={[4, 4, 0, 0]}
/>
</RechartsBarChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,134 @@
import { useState } from "react";
export interface TimeSlot {
date: string;
time: string;
duration?: string;
}
export interface MeetingTimePickerProps {
status: "inProgress" | "executing" | "complete";
respond?: (response: string) => void;
reasonForScheduling?: string;
meetingDuration?: number;
title?: string;
timeSlots?: TimeSlot[];
}
export function MeetingTimePicker({
status,
respond,
reasonForScheduling,
meetingDuration,
title = "Schedule a Meeting",
timeSlots = [
{ date: "Tomorrow", time: "2:00 PM", duration: "30 min" },
{ date: "Friday", time: "10:00 AM", duration: "30 min" },
{ date: "Next Monday", time: "3:00 PM", duration: "30 min" },
],
}: MeetingTimePickerProps) {
const displayTitle = reasonForScheduling || title;
const slots = meetingDuration
? timeSlots.map((slot) => ({ ...slot, duration: `${meetingDuration} min` }))
: timeSlots;
const [selectedSlot, setSelectedSlot] = useState<TimeSlot | null>(null);
const [declined, setDeclined] = useState(false);
const handleSelectSlot = (slot: TimeSlot) => {
setSelectedSlot(slot);
respond?.(
`Meeting scheduled for ${slot.date} at ${slot.time}${slot.duration ? ` (${slot.duration})` : ""}.`,
);
};
const handleDecline = () => {
setDeclined(true);
respond?.(
"The user declined all proposed meeting times. Please suggest alternative times or ask for their availability.",
);
};
return (
<div className="rounded-2xl shadow-lg max-w-md w-full border dark:border-zinc-700 mx-auto mb-6 bg-white dark:bg-zinc-800">
<div className="backdrop-blur-md p-8 w-full rounded-2xl">
{selectedSlot ? (
<div className="text-center">
<div className="text-7xl mb-4">📅</div>
<h2 className="text-2xl font-bold mb-2 dark:text-white">
Meeting Scheduled
</h2>
<p className="text-gray-600 dark:text-zinc-400 mb-2">
{selectedSlot.date} at {selectedSlot.time}
</p>
{selectedSlot.duration && (
<p className="text-sm text-gray-500 dark:text-zinc-400">
Duration: {selectedSlot.duration}
</p>
)}
</div>
) : declined ? (
<div className="text-center">
<div className="text-7xl mb-4">🔄</div>
<h2 className="text-2xl font-bold mb-2 dark:text-white">
No Time Selected
</h2>
<p className="text-gray-600 dark:text-zinc-400">
Let me find a better time that works for you
</p>
</div>
) : (
<>
<div className="text-center mb-6">
<div className="text-7xl mb-4">🗓</div>
<h2 className="text-2xl font-bold mb-2 dark:text-white">
{displayTitle}
</h2>
<p className="text-gray-600 dark:text-zinc-400">
Select a time that works for you
</p>
</div>
{status === "executing" && (
<div className="space-y-3">
{slots.map((slot, index) => (
<button
key={index}
onClick={() => handleSelectSlot(slot)}
className="w-full px-6 py-4 rounded-xl font-medium
border-2 border-gray-200 dark:border-zinc-600 hover:border-blue-500 dark:hover:border-blue-400
shadow-sm hover:shadow-md transition-all cursor-pointer
flex justify-between items-center
hover:bg-blue-50 dark:hover:bg-blue-900/30"
>
<div className="text-left">
<div className="font-bold text-gray-900 dark:text-zinc-100">
{slot.date}
</div>
<div className="text-sm text-gray-600 dark:text-zinc-400">
{slot.time}
</div>
</div>
{slot.duration && (
<div className="text-sm text-gray-500 dark:text-zinc-400">
{slot.duration}
</div>
)}
</button>
))}
<button
onClick={handleDecline}
className="w-full px-6 py-3 rounded-xl font-medium
text-gray-600 dark:text-zinc-400 hover:text-gray-800 dark:hover:text-zinc-200
transition-all cursor-pointer hover:bg-gray-100 dark:hover:bg-zinc-700"
>
None of these work
</button>
</div>
)}
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,102 @@
import {
PieChart as RechartsPieChart,
Pie,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { z } from "zod";
const CHART_COLORS = [
"#3b82f6",
"#8b5cf6",
"#ec4899",
"#f59e0b",
"#10b981",
"#06b6d4",
"#f97316",
];
const TOOLTIP_STYLE = {
backgroundColor: "var(--chart-tooltip-bg)",
border: "1px solid var(--chart-tooltip-border)",
borderRadius: "8px",
padding: "8px 12px",
color: "var(--foreground)",
};
export const PieChartPropsSchema = z.object({
title: z.string().describe("Chart title"),
description: z.string().describe("Brief description or subtitle"),
data: z.array(
z.object({
label: z.string(),
value: z.number(),
}),
),
});
type PieChartProps = z.infer<typeof PieChartPropsSchema>;
export function PieChart({ title, description, data }: PieChartProps) {
if (!data || !Array.isArray(data) || data.length === 0) {
return (
<div className="rounded-xl border dark:border-zinc-700 shadow-sm p-6 max-w-lg mx-auto my-6 bg-[var(--background)]">
<div className="mb-4">
<h3 className="text-xl font-bold dark:text-white">{title}</h3>
<p className="text-sm text-gray-600 dark:text-zinc-400">
{description}
</p>
</div>
<p className="text-gray-500 dark:text-zinc-400 text-center py-8">
No data available
</p>
</div>
);
}
// Add colors to data
const coloredData = data.map((entry, index) => ({
...entry,
fill: CHART_COLORS[index % CHART_COLORS.length],
}));
return (
<div className="rounded-xl border dark:border-zinc-700 shadow-sm p-6 max-w-lg mx-auto my-6 bg-[var(--background)]">
<div className="mb-4">
<h3 className="text-xl font-bold dark:text-white">{title}</h3>
<p className="text-sm text-gray-600 dark:text-zinc-400">
{description}
</p>
</div>
<ResponsiveContainer width="100%" height={300}>
<RechartsPieChart>
<Pie
data={coloredData}
dataKey="value"
nameKey="label"
cx="50%"
cy="50%"
outerRadius={100}
isAnimationActive={false}
/>
<Tooltip contentStyle={TOOLTIP_STYLE} />
</RechartsPieChart>
</ResponsiveContainer>
{/* Legend */}
<div className="mt-4 grid grid-cols-2 gap-2">
{data.map((item, index) => (
<div key={index} className="flex items-center gap-2">
<div
className="w-3 h-3 rounded-sm"
style={{
backgroundColor: CHART_COLORS[index % CHART_COLORS.length],
}}
/>
<span className="text-sm dark:text-zinc-300">{item.label}</span>
</div>
))}
</div>
</div>
);
}
@@ -0,0 +1,67 @@
// frontend/src/components/generative-ui/ToolReasoning.tsx
import { useEffect, useRef } from "react";
interface ToolReasoningProps {
name: string;
args?: object | unknown;
status: string;
}
const statusIndicator = {
executing: (
<span className="inline-block h-3 w-3 rounded-full border-2 border-gray-400 border-t-transparent animate-spin" />
),
inProgress: (
<span className="inline-block h-3 w-3 rounded-full border-2 border-gray-400 border-t-transparent animate-spin" />
),
complete: <span className="text-green-500 text-xs"></span>,
};
function formatValue(value: unknown): string {
if (Array.isArray(value)) return `[${value.length} items]`;
if (typeof value === "object" && value !== null)
return `{${Object.keys(value).length} keys}`;
if (typeof value === "string") return `"${value}"`;
return String(value);
}
export function ToolReasoning({ name, args, status }: ToolReasoningProps) {
const entries = args ? Object.entries(args as Record<string, unknown>) : [];
const detailsRef = useRef<HTMLDetailsElement>(null);
const toolStatus = status as "complete" | "inProgress" | "executing";
// Auto-open while executing, auto-close when complete
useEffect(() => {
if (!detailsRef.current) return;
detailsRef.current.open = status === "executing";
}, [status]);
return (
<div className="my-2 text-sm">
{entries.length > 0 ? (
<details ref={detailsRef} open>
<summary className="flex items-center gap-2 text-gray-600 dark:text-gray-400 cursor-pointer list-none">
{statusIndicator[toolStatus]}
<span className="font-medium">{name}</span>
<span className="text-[10px]"></span>
</summary>
<div className="pl-5 mt-1 space-y-1 text-xs text-gray-500 dark:text-zinc-400">
{entries.map(([key, value]) => (
<div key={key} className="flex gap-2 min-w-0">
<span className="font-medium shrink-0">{key}:</span>
<span className="text-gray-600 dark:text-gray-400 truncate">
{formatValue(value)}
</span>
</div>
))}
</div>
</details>
) : (
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
{statusIndicator[toolStatus]}
<span className="font-medium">{name}</span>
</div>
)}
</div>
);
}
@@ -0,0 +1,21 @@
import { RingLoader } from "react-spinners";
type GenerationProps = {
message: string;
};
const LoadingSpinner = ({ message }: GenerationProps) => {
return (
<div className="p-6 flex flex-col justify-center items-center h-full gap-8">
<RingLoader size={200} color="white" />
<div className="text-center">
<p className="text-4xl font-medium animate-pulse mb-5">{message}</p>
<p className="text-2xl text-slate-100 animate-bounce">
Please stand by...
</p>
</div>
</div>
);
};
export default LoadingSpinner;
@@ -0,0 +1,157 @@
"use client";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
);
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
);
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
@@ -0,0 +1,59 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };
@@ -0,0 +1,92 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className,
)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
};
@@ -0,0 +1,143 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};
@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className,
)}
{...props}
/>
);
}
export { Input };
@@ -0,0 +1,39 @@
interface ModeToggleProps {
mode: "chat" | "app";
onModeChange: (mode: "chat" | "app") => void;
}
export function ModeToggle({ mode, onModeChange }: ModeToggleProps) {
return (
<div className="fixed top-4 right-4 z-50 flex bg-gray-100 dark:bg-zinc-800 rounded-lg p-1 shadow-sm max-lg:top-2 max-lg:right-2 max-lg:scale-90">
<button
onClick={() => onModeChange("chat")}
className={`
px-4 py-2 rounded-md text-sm font-medium transition-all max-lg:px-3 max-lg:py-1.5 max-lg:text-xs
cursor-pointer
${
mode === "chat"
? "bg-white dark:bg-zinc-700 text-gray-900 dark:text-white shadow-sm"
: "text-gray-600 dark:text-zinc-400 hover:text-gray-900 dark:hover:text-white"
}
`}
>
Chat
</button>
<button
onClick={() => onModeChange("app")}
className={`
px-4 py-2 rounded-md text-sm font-medium transition-all max-lg:px-3 max-lg:py-1.5 max-lg:text-xs
cursor-pointer
${
mode === "app"
? "bg-white dark:bg-zinc-700 text-gray-900 dark:text-white shadow-sm"
: "text-gray-600 dark:text-zinc-400 hover:text-gray-900 dark:hover:text-white"
}
`}
>
App Mode
</button>
</div>
);
}
@@ -0,0 +1,48 @@
"use client";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
);
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className,
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
);
}
export { Progress };
@@ -0,0 +1,185 @@
"use client";
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
);
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
);
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
);
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};
@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/lib/utils";
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator-root"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className,
)}
{...props}
/>
);
}
export { Separator };
@@ -0,0 +1,139 @@
"use client";
import * as React from "react";
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className,
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
@@ -0,0 +1,728 @@
"use client";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { VariantProps, cva } from "class-variance-authority";
import { PanelLeftIcon } from "lucide-react";
import { useIsMobile } from "@/hooks/UseMobile";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
const SIDEBAR_COOKIE_NAME = "sidebar_state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContextProps = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open],
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className,
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
);
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className,
)}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className,
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
);
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar();
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar();
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className,
)}
{...props}
/>
);
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
);
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
);
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div";
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className,
)}
{...props}
/>
);
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
);
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
);
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
);
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
);
if (!tooltip) {
return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
);
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className,
)}
{...props}
/>
);
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean;
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
return `${(array[0] % 40) + 50}%`;
}, []);
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
);
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}) {
const Comp = asChild ? Slot : "a";
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};
@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
);
}
export { Skeleton };
@@ -0,0 +1,23 @@
import * as React from "react";
import { cn } from "@/lib/utils";
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Textarea.displayName = "Textarea";
export { Textarea };
@@ -0,0 +1,61 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
);
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className,
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
@@ -0,0 +1,21 @@
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
undefined,
);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}
@@ -0,0 +1,71 @@
"use client";
import { useAuth as useOidcAuth } from "react-oidc-context";
import { useEffect, useState } from "react";
import { WebStorageStateStore } from "oidc-client-ts";
import { createCognitoAuthConfig } from "@/lib/auth";
interface CognitoAuthConfig {
authority?: string;
client_id?: string;
redirect_uri?: string;
post_logout_redirect_uri?: string;
response_type?: string;
scope?: string;
automaticSilentRenew?: boolean;
userStore?: WebStorageStateStore;
}
export function useAuth() {
const auth = useOidcAuth();
const [authConfig, setAuthConfig] = useState<CognitoAuthConfig | null>(null);
useEffect(() => {
async function loadConfig() {
try {
const config = await createCognitoAuthConfig();
setAuthConfig(config);
} catch (error) {
console.error("Failed to load auth configuration for signOut:", error);
}
}
loadConfig();
}, []);
// If no AuthProvider context, return mock auth state (no authentication)
if (!auth) {
return {
isAuthenticated: true,
user: null,
signIn: () => {},
signOut: () => {},
isLoading: false,
error: null,
token: null,
};
}
return {
isAuthenticated: auth.isAuthenticated,
user: auth.user,
signIn: auth.signinRedirect,
signOut: () => {
const clientId =
authConfig?.client_id || import.meta.env.VITE_COGNITO_CLIENT_ID || "";
const logoutUri =
authConfig?.redirect_uri ||
import.meta.env.VITE_COGNITO_REDIRECT_URI ||
"http://localhost:3000";
auth.signoutRedirect({
extraQueryParams: {
client_id: clientId,
logout_uri: logoutUri,
},
});
},
isLoading: auth.isLoading,
error: auth.error,
token: auth.user?.id_token,
};
}
@@ -0,0 +1,75 @@
import { z } from "zod";
import {
useComponent,
useFrontendTool,
useHumanInTheLoop,
useDefaultRenderTool,
} from "@copilotkit/react-core/v2";
import {
PieChart,
PieChartPropsSchema,
} from "@/components/generative-ui/PieChart";
import {
BarChart,
BarChartPropsSchema,
} from "@/components/generative-ui/BarChart";
import { ToolReasoning } from "@/components/generative-ui/ToolReasoning";
import { MeetingTimePicker } from "@/components/generative-ui/MeetingTimePicker";
import { useTheme } from "@/hooks/useTheme";
export const useCopilotExamples = () => {
const { theme, setTheme } = useTheme();
// Frontend tool: toggle light/dark mode
useFrontendTool(
{
name: "toggleTheme",
description: "Frontend tool for toggling the theme of the app.",
parameters: z.object({}),
handler: async () => {
setTheme(theme === "dark" ? "light" : "dark");
},
},
[theme, setTheme],
);
// Controlled Generative UI: pie chart
useComponent({
name: "pieChart",
description: "Controlled Generative UI that displays data as a pie chart.",
parameters: PieChartPropsSchema,
render: PieChart,
});
// Controlled Generative UI: bar chart
useComponent({
name: "barChart",
description: "Controlled Generative UI that displays data as a bar chart.",
parameters: BarChartPropsSchema,
render: BarChart,
});
// Default renderer for all backend tool calls
useDefaultRenderTool({
render: ({ name, status, parameters }) => (
<ToolReasoning name={name} status={status} args={parameters} />
),
});
// Human-in-the-loop: meeting scheduler
useHumanInTheLoop({
name: "scheduleTime",
description: "Use human-in-the-loop to schedule a meeting with the user.",
parameters: z.object({
reasonForScheduling: z
.string()
.describe("Reason for scheduling, very brief - 5 words."),
meetingDuration: z
.number()
.describe("Duration of the meeting in minutes"),
}),
render: ({ respond, status, args }) => (
<MeetingTimePicker status={status} respond={respond} {...args} />
),
});
};
@@ -0,0 +1,38 @@
// frontend/src/hooks/useExampleSuggestions.ts
import { useConfigureSuggestions } from "@copilotkit/react-core/v2";
export const useExampleSuggestions = () => {
useConfigureSuggestions({
suggestions: [
{
title: "Pie chart (Controlled Generative UI)",
message:
"Please show me the distribution of our revenue by category in a pie chart.",
},
{
title: "Bar chart (Controlled Generative UI)",
message:
"Please show me the distribution of our expenses by category in a bar chart.",
},
{
title: "MCP apps (Open Generative UI)",
message:
"Please create a simple network diagram of a router and two switches.",
},
{
title: "Change theme (Frontend Tools)",
message: "Switch the app to dark mode.",
},
{
title: "Scheduling (Human In The Loop)",
message: "Please schedule a meeting with me to learn about CopilotKit.",
},
{
title: "Canvas (Shared State)",
message:
"Please demonstrate shared state, open the canvas, and then add some todos to it about learning about CopilotKit.",
},
],
available: "always",
});
};
@@ -0,0 +1,43 @@
"use client";
import { createContext, useContext, useEffect, useState } from "react";
type Theme = "dark" | "light" | "system";
const ThemeContext = createContext<{
theme: Theme;
setTheme: (t: Theme) => void;
}>({
theme: "system",
setTheme: () => {},
});
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<Theme>("system");
useEffect(() => {
const root = document.documentElement;
root.classList.remove("light", "dark");
if (theme === "system") {
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const apply = () => {
root.classList.remove("light", "dark");
root.classList.add(mq.matches ? "dark" : "light");
};
apply();
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
}
root.classList.add(theme);
}, [theme]);
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export const useTheme = () => useContext(ThemeContext);
@@ -0,0 +1,25 @@
import type { ReactNode } from "react";
import type { ToolCallStatus } from "@/components/chat/types";
export interface ToolRenderProps {
name: string;
args: string;
status: ToolCallStatus;
result?: string;
}
export type ToolRenderFn = (props: ToolRenderProps) => ReactNode;
const renderers = new Map<string, ToolRenderFn>();
export function useDefaultTool(render: ToolRenderFn) {
renderers.set("*", render);
}
export function useToolRenderer(name: string, render: ToolRenderFn) {
renderers.set(name, render);
}
export function getToolRenderer(name: string): ToolRenderFn | null {
return renderers.get(name) ?? renderers.get("*") ?? null;
}
@@ -0,0 +1,116 @@
import { WebStorageStateStore } from "oidc-client-ts";
// Configuration type matching the cognitoAuthConfig structure
type AwsExportsConfig = {
authority?: string;
client_id?: string;
redirect_uri?: string;
post_logout_redirect_uri?: string;
response_type?: string;
scope?: string;
automaticSilentRenew?: boolean;
userStore: WebStorageStateStore | undefined;
};
/**
* Configuration Priority (highest to lowest):
* 1. Environment variables (VITE_COGNITO_*)
* 2. aws-exports.json file
* 3. Default values
*/
// Cache for loaded config
let configCache: AwsExportsConfig | null = null;
let configPromise: Promise<AwsExportsConfig | null> | null = null;
// Load configuration from aws-exports.json at runtime
async function loadAwsConfig(): Promise<AwsExportsConfig | null> {
if (configCache) {
return configCache;
}
if (configPromise) {
return configPromise;
}
configPromise = (async () => {
try {
const response = await fetch("/aws-exports.json");
if (!response.ok) {
throw new Error(`Failed to load aws-exports.json: ${response.status}`);
}
const config = await response.json();
configCache = config;
return config;
} catch (error) {
console.error("Failed to load aws-exports.json:", error);
throw error;
}
})();
return configPromise;
}
// Create auth config factory function that loads config dynamically
export async function createCognitoAuthConfig(): Promise<AwsExportsConfig> {
const awsConfig = await loadAwsConfig();
if (awsConfig === null) {
throw Error("aws-exports.json file not found");
}
// Get environment variables
const userPoolId = import.meta.env.VITE_COGNITO_USER_POOL_ID;
const clientId = import.meta.env.VITE_COGNITO_CLIENT_ID;
const region = import.meta.env.VITE_COGNITO_REGION;
const redirectUri = import.meta.env.VITE_COGNITO_REDIRECT_URI;
const postLogoutRedirectUri = import.meta.env
.VITE_COGNITO_POST_LOGOUT_REDIRECT_URI;
const responseType = import.meta.env.VITE_COGNITO_RESPONSE_TYPE;
const scope = import.meta.env.VITE_COGNITO_SCOPE;
const automaticSilentRenew = import.meta.env
.VITE_COGNITO_AUTOMATIC_SILENT_RENEW;
// Build authority from environment variables if region and userPoolId are provided
const envAuthority =
region && userPoolId
? `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`
: undefined;
return {
authority: envAuthority || awsConfig.authority,
client_id: clientId || awsConfig.client_id,
redirect_uri: redirectUri || awsConfig.redirect_uri,
post_logout_redirect_uri:
postLogoutRedirectUri ||
redirectUri ||
awsConfig.post_logout_redirect_uri,
response_type: responseType || awsConfig.response_type || "code",
scope: scope || awsConfig.scope || "email openid profile",
automaticSilentRenew:
automaticSilentRenew === "false"
? false
: automaticSilentRenew === "true"
? true
: (awsConfig.automaticSilentRenew ?? true),
userStore:
typeof window !== "undefined"
? new WebStorageStateStore({ store: window.localStorage })
: undefined,
};
}
// Synchronous version for backwards compatibility (uses env vars as fallback)
export const cognitoAuthConfig = {
authority: `https://cognito-idp.${import.meta.env.VITE_COGNITO_REGION}.amazonaws.com/${import.meta.env.VITE_COGNITO_USER_POOL_ID}`,
client_id: import.meta.env.VITE_COGNITO_CLIENT_ID,
redirect_uri: import.meta.env.VITE_COGNITO_REDIRECT_URI,
post_logout_redirect_uri: import.meta.env.VITE_COGNITO_REDIRECT_URI,
response_type: "code",
scope: "email openid profile",
automaticSilentRenew: true,
userStore:
typeof window !== "undefined"
? new WebStorageStateStore({ store: window.localStorage })
: undefined,
};
@@ -0,0 +1,48 @@
// Runtime configuration loader for aws-exports.json.
// Used by the CopilotKit integration (components/chat/CopilotKit/) to resolve
// the CopilotKit runtime URL at startup.
export type AwsExportsConfig = {
authority?: string;
client_id?: string;
redirect_uri?: string;
post_logout_redirect_uri?: string;
response_type?: string;
scope?: string;
automaticSilentRenew?: boolean;
agentRuntimeArn?: string;
awsRegion?: string;
feedbackApiUrl?: string;
copilotKitRuntimeUrl?: string;
agentPattern?: string;
};
let configCache: AwsExportsConfig | null = null;
let configPromise: Promise<AwsExportsConfig | null> | null = null;
export async function loadAwsConfig(): Promise<AwsExportsConfig | null> {
if (configCache) {
return configCache;
}
if (configPromise) {
return configPromise;
}
configPromise = (async () => {
try {
const response = await fetch("/aws-exports.json");
if (!response.ok) {
throw new Error(`Failed to load aws-exports.json: ${response.status}`);
}
const config = (await response.json()) as AwsExportsConfig;
configCache = config;
return config;
} catch (error) {
console.error("Failed to load aws-exports.json:", error);
throw error;
}
})();
return configPromise;
}
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
@@ -0,0 +1,14 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React from "react";
import ReactDOM from "react-dom/client";
import "@copilotkit/react-core/v2/styles.css";
import App from "./App";
import "./styles/globals.css";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
@@ -0,0 +1,25 @@
import CopilotChatInterface from "@/components/chat/CopilotKit";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import { GlobalContextProvider } from "@/app/context/GlobalContext";
export default function ChatPage() {
const { isAuthenticated, signIn } = useAuth();
if (!isAuthenticated) {
return (
<div className="flex flex-col items-center justify-center min-h-screen gap-4">
<p className="text-4xl">Please sign in</p>
<Button onClick={() => signIn()}>Sign In</Button>
</div>
);
}
return (
<GlobalContextProvider>
<div className="relative h-screen">
<CopilotChatInterface />
</div>
</GlobalContextProvider>
);
}
@@ -0,0 +1,13 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { Routes, Route } from "react-router-dom";
import ChatPage from "./ChatPage";
export default function AppRoutes() {
return (
<Routes>
<Route path="/" element={<ChatPage />} />
</Routes>
);
}
@@ -0,0 +1,159 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-brand-dark: hsl(197, 37%, 24%);
--color-brand-teal: hsl(173, 58%, 39%);
--color-brand-lime: hsl(43, 74%, 66%);
--color-brand-yellow: hsl(27, 87%, 67%);
--color-brand-orange: hsl(12, 76%, 61%);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--brand-dark: 197 37% 24%;
--brand-teal: 173 58% 39%;
--brand-lime: 43 74% 66%;
--brand-yellow: 27 87% 67%;
--brand-orange: 12 76% 61%;
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--destructive-foreground: oklch(0.985 0 0);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
/* Font variables for Geist fonts */
--font-geist-sans:
"Geist Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
sans-serif;
--font-geist-mono: "Geist Mono", "Courier New", Consolas, Monaco, monospace;
--font-body: var(--font-geist-sans);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--destructive-foreground: oklch(0.985 0 0);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
a {
@apply text-brand-yellow hover:text-brand-yellow/80 underline;
}
}
@keyframes fade-in-up {
0% {
opacity: 0;
transform: translateY(30px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.animate-fade-in-up {
animation: fade-in-up 2s ease-out;
}
@@ -0,0 +1,12 @@
import "react";
declare module "react" {
namespace JSX {
interface IntrinsicElements {
[elemName: string]: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
}
}
}
@@ -0,0 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_COGNITO_USER_POOL_ID?: string;
readonly VITE_COGNITO_CLIENT_ID?: string;
readonly VITE_COGNITO_REGION?: string;
readonly VITE_COGNITO_REDIRECT_URI?: string;
readonly VITE_COGNITO_POST_LOGOUT_REDIRECT_URI?: string;
readonly VITE_COGNITO_RESPONSE_TYPE?: string;
readonly VITE_COGNITO_SCOPE?: string;
readonly VITE_COGNITO_AUTOMATIC_SILENT_RENEW?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
@@ -0,0 +1,32 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* Path aliases */
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"],
"exclude": ["src/app", "src/test"],
"references": [{ "path": "./tsconfig.node.json" }]
}
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}
@@ -0,0 +1,48 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
define: {
"import.meta.env.VITE_COPILOTKIT_THREADS_ENABLED": JSON.stringify(
process.env.VITE_COPILOTKIT_THREADS_ENABLED ??
(process.env.COPILOTKIT_LICENSE_TOKEN ? "true" : "false"),
),
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
build: {
outDir: "build",
sourcemap: true,
rollupOptions: {
output: {
manualChunks: {
"react-vendor": ["react", "react-dom", "react-router-dom"],
"ui-vendor": [
"@radix-ui/react-dialog",
"@radix-ui/react-select",
"@radix-ui/react-alert-dialog",
"@radix-ui/react-progress",
],
"auth-vendor": ["react-oidc-context", "aws-amplify"],
},
},
},
},
server: {
port: 3000,
open: true,
},
});