diff --git a/.gitignore b/.gitignore index 1d32786b..368d3517 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ node_modules/ dist/ build/ lib/ +!/**/src/**/lib # Cloudflare Workers .wrangler/ @@ -63,4 +64,4 @@ tmp/ .turbo data/ -*.db \ No newline at end of file +*.db diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..20981075 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,81 @@ +# AGENTS.md + +## Build/Run Commands + +- Build: `pnpm run build` (uses tsc) +- Dev mode: `pnpm run dev` (tsx watch) +- Run tests: `pnpm run test` (vitest) +- Run single test: `pnpm run test ` +- Test watch mode: `pnpm run test:watch` +- Lint: `pnpm run lint` (eslint) +- Lint fix: `pnpm run lint:fix` +- Typecheck: `pnpm run typecheck` (tsc --noEmit) +- Format: `pnpm run format` (prettier) +- Format check: `pnpm run format:check` + +## Code Style Guidelines + +- Use double quotes for strings +- No semicolons +- Use tabs for indentation (TSConfig sets this) +- Strict TypeScript with all strict flags enabled +- No unused locals/parameters +- Exact optional property types +- No implicit returns/fallthrough cases +- No unchecked indexed access +- Use ESNext target and modules +- Import paths use `@/*` alias for src/ +- Declaration files and source maps generated +- Resolve JSON modules enabled + +## Naming Conventions + +- Files: kebab-case +- Types: PascalCase +- Functions/variables: camelCase +- Constants: UPPER_SNAKE_CASE +- Test files: \*.test.ts + +## Error Handling + +- Use custom error classes from utils/errors.ts +- Always provide meaningful error messages +- Use logger.ts for consistent logging +- Handle dry-run mode in all mutating operations + +## Testing + +- Use vitest with globals +- Place tests alongside source files +- Use .test.ts extension +- Mock filesystem with memfs where needed + +## Development Practices + +- Use pnpm for package management +- Follow workspaces pattern with packages in `packages/{project}` +- All code compatible with Cloudflare Workers runtime +- Use TypeScript for all code with proper typing +- Follow ES modules format +- Use `async`/`await` for asynchronous code +- Write tests for all functionality +- Use Wrangler for deployments to Cloudflare Workers + +## Project Structure + +- `packages/`: Contains all project packages + - `mcp/`: Main MCP implementation for Cloudflare Workers + - `test-utils/`: Utilities for testing +- `examples/`: Contains example implementations + - `crud-mcp/`: Example CRUD application using MCP framework + - `simple-prompt-agent/`: Example agent with only a prompt for chatting +- Main package: packages/mcp/src/index.ts +- MCP Server implementation: packages/mcp/src/mcp/server.ts +- Example application: examples/crud-mcp/src/index.ts + +## Development Workflow + +1. Install dependencies at root level: `pnpm install` +2. Build all packages: `pnpm build` +3. Run tests: `pnpm test` +4. For specific packages, navigate to directory and use specific scripts diff --git a/examples/crud-mcp/README.md b/examples/crud-mcp/README.md index 52ad0a1d..f0c83fbc 100644 --- a/examples/crud-mcp/README.md +++ b/examples/crud-mcp/README.md @@ -35,6 +35,7 @@ This example demonstrates a CRUD (Create, Read, Update, Delete) application usin ### Data Model The todo items are structured with the following fields: + - `id`: Unique identifier (UUID) - `title`: Task title (required) - `description`: Detailed description (optional) @@ -99,18 +100,19 @@ The application includes interactive prompts to help users understand and use th - error_type (optional): Get specific help about 'not_found', 'invalid_status', 'invalid_date', or 'other' errors Example prompt usage: + ```typescript // Get general help about listing todos -const listHelp = await client.getPrompt('list_todos_help'); +const listHelp = await client.getPrompt("list_todos_help"); // Get specific help about date filtering -const dateFilterHelp = await client.getPrompt('list_todos_help', { - filter: 'date' +const dateFilterHelp = await client.getPrompt("list_todos_help", { + filter: "date", }); // Get help about updating a specific field -const updateHelp = await client.getPrompt('update_todo_help', { - field: 'status' +const updateHelp = await client.getPrompt("update_todo_help", { + field: "status", }); ``` @@ -143,6 +145,7 @@ const updateHelp = await client.getPrompt('update_todo_help', { The application uses Cloudflare Workers with the following configuration: ### wrangler.jsonc + ```jsonc { "name": "crud-mcp", @@ -153,24 +156,25 @@ The application uses Cloudflare Workers with the following configuration: "bindings": [ { "name": "TODO_MCP_SERVER", - "class_name": "TodoMcpServer" - } - ] + "class_name": "TodoMcpServer", + }, + ], }, "migrations": [ { "tag": "v1", - "new_sqlite_classes": ["TodoMcpServer"] - } + "new_sqlite_classes": ["TodoMcpServer"], + }, ], "observability": { "enabled": true, - "head_sampling_rate": 1 - } + "head_sampling_rate": 1, + }, } ``` Key Configuration Points: + - **Durable Objects**: The `TodoMcpServer` class is bound as a Durable Object for state management - **SQLite Support**: The `TodoMcpServer` class is registered for SQLite functionality via migrations - **Observability**: Full request sampling enabled for monitoring and debugging @@ -208,36 +212,38 @@ await client.connect(); ### Creating a Todo ```typescript -const result = await client.callTool('create_todo', { +const result = await client.callTool("create_todo", { title: "Complete project report", description: "Finalize the quarterly project report", - due_date: "2024-03-20" + due_date: "2024-03-20", }); ``` ### Listing Todos with Filters ```typescript -const todos = await client.getResource(new URL( - "d1://database/todos?status=in_progress&sort_by=due_date&sort_direction=asc" -)); +const todos = await client.getResource( + new URL( + "d1://database/todos?status=in_progress&sort_by=due_date&sort_direction=asc", + ), +); ``` ### Getting Today's Tasks ```typescript -const todaysTodos = await client.getResource(new URL( - "d1://database/todos/today?sort_by=created_at&sort_direction=asc" -)); +const todaysTodos = await client.getResource( + new URL("d1://database/todos/today?sort_by=created_at&sort_direction=asc"), +); ``` ### Updating a Todo ```typescript -const result = await client.callTool('updateTodo', { +const result = await client.callTool("updateTodo", { id: "todo-uuid", status: "completed", - description: "Updated description" + description: "Updated description", }); ``` @@ -245,28 +251,31 @@ const result = await client.callTool('updateTodo', { 1. Prerequisites: - Node.js (v16 or higher) - - Yarn or npm + - pnpm or npm - Wrangler CLI 2. Installation: + ```bash - yarn install + pnpm install ``` 3. Development: + ```bash - yarn dev + pnpm dev ``` 4. Deployment: ```bash wrangler login - yarn deploy + pnpm deploy ``` ## Error Handling The implementation includes comprehensive error handling: + - Input validation using Zod schemas - Database operation error handling - Detailed error messages and logging @@ -281,4 +290,5 @@ The implementation includes comprehensive error handling: ## License -MIT \ No newline at end of file +MIT + diff --git a/examples/dependent-agent/package.json b/examples/dependent-agent/package.json index 11757b81..80319ea8 100644 --- a/examples/dependent-agent/package.json +++ b/examples/dependent-agent/package.json @@ -4,10 +4,10 @@ "private": true, "scripts": { "deploy": "wrangler deploy", - "dev": "wrangler dev", + "dev": "nullshot dev", "start": "wrangler dev", "cf-typegen": "wrangler types", - "dev:nullshot": "nullshot dev", + "dev:wrangler": "wrangler dev", "postinstall": "nullshot install" }, "dependencies": { diff --git a/examples/dependent-agent/src/index.ts b/examples/dependent-agent/src/index.ts index 43ac233f..3f910145 100644 --- a/examples/dependent-agent/src/index.ts +++ b/examples/dependent-agent/src/index.ts @@ -91,7 +91,7 @@ export class DependentAgent extends AiSdkAgent { }, ); - return result.toTextStreamResponse(); + return result.toUIMessageStreamResponse(); } } diff --git a/examples/playground-showcase/.eslintrc.json b/examples/playground-showcase/.eslintrc.json deleted file mode 100644 index 6f6a427a..00000000 --- a/examples/playground-showcase/.eslintrc.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "extends": [ - "next/core-web-vitals", - "next/typescript" - ], - "parserOptions": { - "project": "./tsconfig.json" - }, - "rules": { - "@typescript-eslint/no-unused-vars": "error", - "@typescript-eslint/no-explicit-any": "error", - "@next/next/no-img-element": "warn", - "@typescript-eslint/no-non-null-assertion": "warn", - "prefer-const": "error", - "no-var": "error" - }, - "ignorePatterns": [ - ".next/", - "out/", - "node_modules/" - ] -} diff --git a/examples/playground-showcase/.gitignore b/examples/playground-showcase/.gitignore deleted file mode 100644 index 5d478416..00000000 --- a/examples/playground-showcase/.gitignore +++ /dev/null @@ -1,43 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local -.env - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# wrangler -.wrangler/ - -# Allow our src/lib directory (override root gitignore) -!src/lib/ \ No newline at end of file diff --git a/examples/playground-showcase/next-env.d.ts b/examples/playground-showcase/next-env.d.ts deleted file mode 100644 index 1b3be084..00000000 --- a/examples/playground-showcase/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/examples/playground-showcase/postcss.config.js b/examples/playground-showcase/postcss.config.js deleted file mode 100644 index 0cc9a9de..00000000 --- a/examples/playground-showcase/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} \ No newline at end of file diff --git a/examples/playground-showcase/public/favicon.ico b/examples/playground-showcase/public/favicon.ico deleted file mode 100644 index a4b783f6..00000000 --- a/examples/playground-showcase/public/favicon.ico +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/playground-showcase/public/images/badge_light_bg.png b/examples/playground-showcase/public/images/badge_light_bg.png deleted file mode 100644 index d86a62a0..00000000 Binary files a/examples/playground-showcase/public/images/badge_light_bg.png and /dev/null differ diff --git a/examples/playground-showcase/public/images/cursor-logo.svg b/examples/playground-showcase/public/images/cursor-logo.svg deleted file mode 100644 index e475ca9a..00000000 --- a/examples/playground-showcase/public/images/cursor-logo.svg +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/playground-showcase/public/images/default-avatar.png b/examples/playground-showcase/public/images/default-avatar.png deleted file mode 100644 index e02f4e89..00000000 Binary files a/examples/playground-showcase/public/images/default-avatar.png and /dev/null differ diff --git a/examples/playground-showcase/public/images/ellipse.svg b/examples/playground-showcase/public/images/ellipse.svg deleted file mode 100644 index 674cf092..00000000 --- a/examples/playground-showcase/public/images/ellipse.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/examples/playground-showcase/public/images/gears.png b/examples/playground-showcase/public/images/gears.png deleted file mode 100644 index fb7ef494..00000000 Binary files a/examples/playground-showcase/public/images/gears.png and /dev/null differ diff --git a/examples/playground-showcase/public/images/mcp-install-dark.svg b/examples/playground-showcase/public/images/mcp-install-dark.svg deleted file mode 100644 index 3dacb7f1..00000000 --- a/examples/playground-showcase/public/images/mcp-install-dark.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/examples/playground-showcase/public/images/mcp-install-light.svg b/examples/playground-showcase/public/images/mcp-install-light.svg deleted file mode 100644 index e5b57623..00000000 --- a/examples/playground-showcase/public/images/mcp-install-light.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/examples/playground-showcase/src/app/components/page.tsx b/examples/playground-showcase/src/app/components/page.tsx deleted file mode 100644 index db1b8f3b..00000000 --- a/examples/playground-showcase/src/app/components/page.tsx +++ /dev/null @@ -1,326 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { - PlaygroundProvider, - ChatContainer, - MCPServerDirectory, - ModelSelector, - PlaygroundHeader, - LocalToolboxStatusBadge, -} from "@nullshot/playground"; -import "@nullshot/playground/styles"; -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; - -export default function ComponentsPage() { - const [selectedTab, setSelectedTab] = useState("chat"); - - return ( -
-
-
-
-

Component Showcase

-

- Explore individual playground components and see how they work -

-
- - - - - Chat Components - MCP Management - Model Selection - Playground UI - - - - - - Chat Container - - Full-featured chat interface with message history and - streaming support - - - -
- -
-
-
- -
- - - Usage Example - - -
-
-                          {`import { ChatContainer } from '@nullshot/playground'
-
-`}
-                        
-
-
-
- - - - Features - - -
    -
  • • Real-time message streaming
  • -
  • • Message history management
  • -
  • • Typing indicators
  • -
  • • Customizable themes
  • -
  • • File attachment support
  • -
  • • Markdown rendering
  • -
-
-
-
-
- - - - - MCP Server Directory - - Manage and configure your MCP servers with real-time - status updates - - - -
- -
-
-
- -
- - - Usage Example - - -
-
-                          {`import { MCPServerDirectory } from '@nullshot/playground'
-
-`}
-                        
-
-
-
- - - - Features - - -
    -
  • • Server status monitoring
  • -
  • • Configuration management
  • -
  • • WebSocket connection status
  • -
  • • Server discovery
  • -
  • • Error handling and recovery
  • -
  • • Real-time updates
  • -
-
-
-
-
- - - - - Model Selector - - Select and configure AI models for your chat interface - - - -
- -
-
-
- -
- - - Usage Example - - -
-
-                          {`import { ModelSelector } from '@nullshot/playground'
-
-`}
-                        
-
-
-
- - - - Features - - -
    -
  • • Multiple AI provider support
  • -
  • • Model parameter configuration
  • -
  • • API key management
  • -
  • • Temperature and token controls
  • -
  • • Custom model support
  • -
  • • Usage tracking
  • -
-
-
-
-
- - - - - Playground Header - - Header component with gears icon, status indicators, and - installation functionality - - - -
- console.log("Install clicked")} - /> -
-
-
- - - - Status Indicators - - Status badges for local toolbox connection state - - - -
-
-
- Online: - -
-
- Offline: - -
-
- Cannot Connect: - -
-
- Disconnected: - -
-
-
-
-
- -
- - - Usage Example - - -
-
-                          {`import { 
-  PlaygroundHeader, 
-  LocalToolboxStatusBadge,
-  DockerInstallModal 
-} from '@nullshot/playground'
-
-
-
-`}
-                        
-
-
-
- - - - Features - - -
    -
  • • Local toolbox status monitoring
  • -
  • • Docker installation management
  • -
  • • Visual status indicators
  • -
  • • Interactive installation flow
  • -
  • • Responsive design
  • -
  • • Themed components
  • -
-
-
-
-
-
-
-
-
-
- ); -} diff --git a/examples/playground-showcase/src/app/examples/page.tsx b/examples/playground-showcase/src/app/examples/page.tsx deleted file mode 100644 index 58fe146c..00000000 --- a/examples/playground-showcase/src/app/examples/page.tsx +++ /dev/null @@ -1,229 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card"; -import { ExternalLink, Code, Zap, Settings, Terminal } from "lucide-react"; - -const examples = [ - { - title: "Basic Integration", - description: "Simple setup with default configuration", - href: "/examples/basic", - icon: Code, - code: `import { PlaygroundProvider, Playground } from '@nullshot/playground' - -function App() { - return ( - - - - ) -}`, - }, - { - title: "Custom MCP Proxy", - description: "Using a custom MCP proxy URL and WebSocket endpoint", - href: "/examples/custom-proxy", - icon: Settings, - code: ` - -`, - }, - { - title: "Component Composition", - description: "Using individual components to build custom layouts", - href: "/examples/composition", - icon: Zap, - code: `import { ChatContainer, MCPServerDirectory } from '@nullshot/playground' - -function CustomLayout() { - return ( -
- - -
- ) -}`, - }, - { - title: "Full Playground Interface", - description: - "Complete playground with header, toolbox management, and modal flows", - href: "/examples/full-playground", - icon: Terminal, - code: `import { - PlaygroundProvider, - PlaygroundHeader, - ChatContainer, - MCPServerDirectory, - DockerInstallModal, - useConfigurableMcpServerManager -} from '@nullshot/playground' - -function FullPlayground() { - const [isDockerModalOpen, setIsDockerModalOpen] = useState(false) - const [isToolboxInstalled, setIsToolboxInstalled] = useState(false) - const [toolboxStatus, setToolboxStatus] = useState('disconnected') - - const { connected, connect } = useConfigurableMcpServerManager() - - return ( - -
-
- setIsDockerModalOpen(true)} - /> - -
-
- -
-
- - setIsDockerModalOpen(false)} - onInstallationComplete={() => setIsToolboxInstalled(true)} - /> -
- ) -}`, - }, - { - title: "Using MCP Server Manager Hook", - description: "Direct access to MCP server management functionality", - href: "/examples/server-manager", - icon: Settings, - code: `import { - PlaygroundProvider, - useConfigurableMcpServerManager -} from '@nullshot/playground' - -function ServerManager() { - const { - servers, - connected, - loading, - addServer, - deleteServer, - refreshServers - } = useConfigurableMcpServerManager() - - const handleAddServer = async () => { - await addServer({ - uniqueName: 'my-server', - command: 'npx', - args: ['my-mcp-server'], - env: { API_KEY: 'your-key' } - }) - } - - return ( -
- -
    - {servers.map(server => ( -
  • {server.uniqueName}
  • - ))} -
-
- ) -}`, - }, -]; - -export default function ExamplesPage() { - return ( -
-
-
-
-

Integration Examples

-

- Learn how to integrate playground components into your - applications -

-
- -
- {examples.map((example, index) => ( - - -
- - {example.title} -
- {example.description} -
- -
-
-                      {example.code}
-                    
-
- -
-
- Copy and paste this code into your React application -
- - View Live Example - - -
-
-
- ))} -
- -
- - - Need Help? - - Check out our documentation and community resources - - - -
- - View Documentation - - - - Try Full Playground - -
-
-
-
-
-
-
- ); -} diff --git a/examples/playground-showcase/src/app/globals.css b/examples/playground-showcase/src/app/globals.css deleted file mode 100644 index 4cea4b8c..00000000 --- a/examples/playground-showcase/src/app/globals.css +++ /dev/null @@ -1,203 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -:root { - --radius: 0.625rem; - --background: oklch(1 0 0); - --foreground: oklch(0.145 0 0); - - /* Font fallbacks */ - --font-space-grotesk: 'Space Grotesk', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; - --font-geist-sans: 'Geist Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; - --font-geist-mono: 'Geist Mono', 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', 'Dank Mono', 'Operator Mono', monospace; - --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); - --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); - - /* Chat theme variables - from Figma */ - --chat-user-bg: #17181A; /* User bubble background (dark gray) */ - --chat-user-text: rgba(255, 255, 255, 0.8); /* User text color */ - --chat-agent-bg: linear-gradient(to bottom right, #72FFC0, #20845F); /* Agent bubble gradient */ - --chat-agent-text: rgba(255, 255, 255, 0.8); /* Agent text color */ - --chat-timestamp: rgba(255, 255, 255, 0.4); /* Timestamp text color */ - - /* Chat animation variables */ - --chat-thinking-animation: pulse 1.5s infinite ease-in-out; - --chat-thinking-duration: 1.5s; - --chat-text-animation: fadeIn 0.3s ease-in-out; -} - -.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); - --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); - - /* Chat theme variables - dark mode (same as light since the design is dark by default) */ - --chat-user-bg: #17181A; /* User bubble background (dark gray) */ - --chat-user-text: rgba(255, 255, 255, 0.8); /* User text color */ - --chat-agent-bg: linear-gradient(to bottom right, #72FFC0, #20845F); /* Agent bubble gradient */ - --chat-agent-text: rgba(255, 255, 255, 0.8); /* Agent text color */ - --chat-timestamp: rgba(255, 255, 255, 0.4); /* Timestamp text color */ - - /* Chat animation variables */ - --chat-thinking-animation: pulse 1.5s infinite ease-in-out; - --chat-thinking-duration: 1.5s; - --chat-text-animation: fadeIn 0.3s ease-in-out; -} - -@layer base { - * { - @apply border-border; - } - body { - @apply bg-background text-foreground; - } -} - -@layer utilities { - .line-clamp-2 { - display: -webkit-box; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; - overflow: hidden; - } - - /* Support for white opacity classes used by playground components */ - .text-white\/95 { - color: rgba(255, 255, 255, 0.95); - } - .text-white\/80 { - color: rgba(255, 255, 255, 0.8); - } - .text-white\/60 { - color: rgba(255, 255, 255, 0.6); - } - .text-white\/40 { - color: rgba(255, 255, 255, 0.4); - } - .text-white\/20 { - color: rgba(255, 255, 255, 0.2); - } -} - -/* Chat typing animation */ -.chat-thinking-animation { - animation: pulse 1.5s infinite ease-in-out; -} - -@keyframes pulse { - 0% { - opacity: 1; - box-shadow: 0 0 0 0 rgba(114, 255, 192, 0.2); - } - 50% { - opacity: 0.7; - box-shadow: 0 0 0 6px rgba(114, 255, 192, 0); - } - 100% { - opacity: 1; - box-shadow: 0 0 0 0 rgba(114, 255, 192, 0); - } -} - -.chat-text-typing { - display: inline-block; - overflow: hidden; - animation: typing 1s steps(40, end); - white-space: pre-wrap; -} - -@keyframes typing { - from { - max-width: 0; - opacity: 0; - } - to { - max-width: 100%; - opacity: 1; - } -} - -.chat-text-streaming { - animation: fadeIn 0.3s ease-in-out; -} - -@keyframes fadeIn { - from { - opacity: 0; - transform: translateY(5px); - } - to { - opacity: 1; - transform: translateY(0); - } -} - -/* Streaming text animation */ -@keyframes cursor-blink { - 0%, 100% { opacity: 1; } - 50% { opacity: 0; } -} - -.chat-text-streaming::after { - content: '|'; - display: inline-block; - margin-left: 2px; - animation: cursor-blink 1s infinite; - color: rgba(114, 255, 192, 0.8); -} \ No newline at end of file diff --git a/examples/playground-showcase/src/app/layout.tsx b/examples/playground-showcase/src/app/layout.tsx deleted file mode 100644 index e4f54d2f..00000000 --- a/examples/playground-showcase/src/app/layout.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import type { Metadata } from "next"; -import { Inter } from "next/font/google"; -import "./globals.css"; - -const inter = Inter({ subsets: ["latin"] }); - -export const metadata: Metadata = { - title: "MCP Playground Showcase", - description: - "Showcase of @nullshot/playground components for building MCP server management interfaces", - keywords: ["MCP", "Model Context Protocol", "Playground", "AI", "Cloudflare"], -}; - -export default function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( - - -
- {children} -
- - - ); -} diff --git a/examples/playground-showcase/src/app/page.tsx b/examples/playground-showcase/src/app/page.tsx deleted file mode 100644 index a23a8d75..00000000 --- a/examples/playground-showcase/src/app/page.tsx +++ /dev/null @@ -1,269 +0,0 @@ -"use client"; - -import React from "react"; -import Link from "next/link"; -import { - ExternalLink, - Github, - Terminal, - MessageCircle, - Settings, - Zap, - Package, - CheckCircle, -} from "lucide-react"; - -export default function Home() { - return ( -
- {/* Hero Section */} -
-
-

- MCP Playground Components -

-

- Build powerful MCP server management interfaces with our React - component library -

-
- - - View Full Playground - - - - Browse Components - - - - View on GitHub - - -
-
-
- - {/* Features Section */} -
-
-

Key Features

-
-
- -

Chat Interface

-

- Full-featured chat components with message history, streaming - support, and AI integration. -

-
-
- -

MCP Management

-

- Complete MCP server directory, configuration, and management - tools with real-time status updates. -

-
-
- -

Local Toolbox

-

- Docker-based local toolbox with installation flows, status - monitoring, and health checks. -

-
-
- -

Configurable

-

- Highly configurable components with themes, proxy URLs, and - feature toggles for any use case. -

-
-
-
-
- - {/* New Components Section */} -
-
-

- New Components & Features -

-
-
-
- -
-

PlaygroundHeader

-

- Header component with gears icon, status indicators, and - installation management. -

-
-
-
- -
-

DockerInstallModal

-

- Complete installation flow for Docker-based local toolbox - with step-by-step guidance. -

-
-
-
- -
-

Status Management

-

- Real-time status indicators for local toolbox connection, - Docker health, and MCP proxy. -

-
-
-
-
-
- -
-

- useConfigurableMcpServerManager -

-

- Hook for direct MCP server management with WebSocket - connections and real-time updates. -

-
-
-
- -
-

- Enhanced Chat Features -

-

- Improved chat container with session management, model - configuration, and enhanced UI. -

-
-
-
- -
-

UI Components

-

- Status badges, configuration drawers, and other specialized - UI components for MCP interfaces. -

-
-
-
-
-
-
- - {/* Installation Section */} -
-
-

Quick Start

-
-

Installation

-
- npm install @nullshot/playground -
- -

- Complete Playground Setup -

-
-
-                {`import React, { useState } from 'react'
-import { 
-  PlaygroundProvider, 
-  PlaygroundHeader,
-  ChatContainer,
-  MCPServerDirectory,
-  DockerInstallModal,
-  useConfigurableMcpServerManager
-} from '@nullshot/playground'
-import '@nullshot/playground/styles'
-
-function App() {
-  const [isDockerModalOpen, setIsDockerModalOpen] = useState(false)
-  const [isToolboxInstalled, setIsToolboxInstalled] = useState(false)
-  
-  return (
-    
-      
-
- setIsDockerModalOpen(true)} - /> - -
-
- -
-
- - setIsDockerModalOpen(false)} - onInstallationComplete={() => setIsToolboxInstalled(true)} - /> -
- ) -}`}
-
-
-
-
-
- - {/* CTA Section */} -
-
-

Ready to get started?

-

- Explore our enhanced playground components and see how easy it is to - build complete MCP interfaces. -

-
- - Try the Playground - - - View Examples - -
-
-
-
- ); -} diff --git a/examples/playground-showcase/src/app/playground/page.tsx b/examples/playground-showcase/src/app/playground/page.tsx deleted file mode 100644 index 061d5f52..00000000 --- a/examples/playground-showcase/src/app/playground/page.tsx +++ /dev/null @@ -1,36 +0,0 @@ -"use client"; - -import { PlaygroundProvider, Playground } from "@nullshot/playground"; -import "@nullshot/playground/styles"; - -export default function PlaygroundPage() { - return ( -
- - - -
- ); -} diff --git a/examples/playground-showcase/src/components/ui/card.tsx b/examples/playground-showcase/src/components/ui/card.tsx deleted file mode 100644 index 5df10544..00000000 --- a/examples/playground-showcase/src/components/ui/card.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import * as React from "react" -import { cn } from "../../lib/utils" - -const Card = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
-)) -Card.displayName = "Card" - -const CardHeader = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
-)) -CardHeader.displayName = "CardHeader" - -const CardTitle = React.forwardRef< - HTMLParagraphElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -

-)) -CardTitle.displayName = "CardTitle" - -const CardDescription = React.forwardRef< - HTMLParagraphElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -

-)) -CardDescription.displayName = "CardDescription" - -const CardContent = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -

-)) -CardContent.displayName = "CardContent" - -const CardFooter = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
-)) -CardFooter.displayName = "CardFooter" - -export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } \ No newline at end of file diff --git a/examples/playground-showcase/src/components/ui/tabs.tsx b/examples/playground-showcase/src/components/ui/tabs.tsx deleted file mode 100644 index fcf20519..00000000 --- a/examples/playground-showcase/src/components/ui/tabs.tsx +++ /dev/null @@ -1,88 +0,0 @@ -"use client" - -import * as React from "react" -import { cn } from "../../lib/utils" - -interface TabsContextValue { - value?: string - onValueChange?: (value: string) => void -} - -const TabsContext = React.createContext({}) - -const Tabs = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes & TabsContextValue ->(({ className, value, onValueChange, ...props }, ref) => ( - -
- -)) -Tabs.displayName = "Tabs" - -const TabsList = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
-)) -TabsList.displayName = "TabsList" - -const TabsTrigger = React.forwardRef< - HTMLButtonElement, - React.ButtonHTMLAttributes & { value: string } ->(({ className, value, ...props }, ref) => { - const { value: selectedValue, onValueChange } = React.useContext(TabsContext) - - return ( - + {error &&
{error}
} + + ) +} +``` + +## Configuration Options + +### Basic Configuration + +```tsx + + + +``` + +### Pre-configured Setups + +```tsx +// Development environment + + + + +// Production environment + + + + +// Minimal configuration (just default agent) + + + + +// Use recommended agents + + + +``` + +### Custom Configuration + +```tsx + + + +``` + +## API Reference + +### Hooks + +#### `useAgentContext()` +Returns the full agent context state and actions. + +```tsx +const { + agents, + selectedAgentId, + isLoading, + error, + addAgent, + removeAgent, + selectAgent, + updateAgentHealth, + refreshAgents, + setAgents, + resetAgents, +} = useAgentContext() +``` + +#### `useAgentSelection()` +Returns agent selection state and actions. + +```tsx +const { agents, selectedAgent, selectedAgentId, selectAgent } = useAgentSelection() +``` + +#### `useAgentManagement()` +Returns agent management actions and state. + +```tsx +const { addAgent, removeAgent, refreshAgents, isLoading, error } = useAgentManagement() +``` + +#### `useAgentConfig()` +Returns configuration values. + +```tsx +const { maxAgents, healthCheckInterval, connectionTimeout, enableAutoRefresh, enableNotifications } = useAgentConfig() +``` + +### Utility Functions + +```tsx +import { + findAgentById, + findAgentByUrl, + getFirstOnlineAgent, + filterAgentsByStatus, + sortAgentsByHealth, + generateAgentId, + isAgentHealthy, + getAgentHealthSummary, + validateAgent, + mergeAgentConfigs, + exportAgentsToJson, + importAgentsFromJson, + getRecommendedAgents, + createDefaultAgent, +} from "@/lib/agent-utils" +``` + +### Persistence + +```tsx +import { createAgentStorage, LocalStorageAgentStorage, MemoryAgentStorage } from "@/lib/agent-persistence" + +// Create storage instance +const storage = createAgentStorage() + +// Use localStorage (default) +const localStorage = new LocalStorageAgentStorage() + +// Use memory storage (fallback) +const memoryStorage = new MemoryAgentStorage() +``` + +## Migration Guide + +### From `getAllAgents()` + +**Before:** +```tsx +import { getAllAgents } from "@/lib/config" + +function MyComponent() { + const agents = getAllAgents() + // ... +} +``` + +**After:** +```tsx +import { useAgentSelection } from "@/lib/agent-context" + +function MyComponent() { + const { agents } = useAgentSelection() + // ... +} +``` + +### From hardcoded agents + +**Before:** +```tsx +const agents = [ + { id: "1", name: "Agent 1", url: "http://localhost:8080" }, + { id: "2", name: "Agent 2", url: "http://localhost:8081" }, +] +``` + +**After:** +```tsx + + + +``` + +## Examples + +### Complete Example Application + +```tsx +import React from "react" +import { AgentConfigProvider, useAgentSelection, useAgentManagement } from "@/lib/agent-config" +import { AgentSelector } from "@/components/agent-selector" +import { AddAgentModal } from "@/components/add-agent-modal" + +function AgentDashboard() { + const { agents, selectedAgent } = useAgentSelection() + const { refreshAgents, isLoading } = useAgentManagement() + + React.useEffect(() => { + // Refresh agent health on mount + refreshAgents() + }, []) + + return ( +
+
+

Agent Dashboard

+ +
+ +
+ {agents.map(agent => ( + + ))} +
+
+ ) +} + +function AgentCard({ agent }) { + return ( +
+

{agent.name}

+

{agent.url}

+
+ + {agent.health?.isOnline ? "Online" : "Offline"} + +
+
+ ) +} + +export default function App() { + return ( + + + + ) +} +``` + +### Custom Agent Configuration + +```tsx +import { AgentConfigProvider } from "@/lib/agent-config" + +function CustomApp() { + const customAgents = [ + { + id: "production-1", + name: "Production Agent", + url: "https://agent.your-domain.com", + }, + { + id: "staging-1", + name: "Staging Agent", + url: "https://staging-agent.your-domain.com", + }, + ] + + return ( + + + + ) +} +``` + +### Environment-based Configuration + +```tsx +import { createConfigFromEnv } from "@/lib/agent-config" + +function EnvBasedApp() { + const config = createConfigFromEnv() + + return ( + + + + ) +} +``` + +Set environment variables: +```bash +NEXT_PUBLIC_AGENTS='[{"id":"env-1","name":"Env Agent","url":"http://localhost:8080"}]' +NEXT_PUBLIC_PERSIST_AGENTS=true +NEXT_PUBLIC_USE_RECOMMENDED_AGENTS=false +``` + +## Testing + +The agent management system includes comprehensive tests: + +```bash +# Run all tests +pnpm test + +# Run tests in watch mode +pnpm test:watch + +# Run tests with UI +pnpm test:ui +``` + +### Test Coverage + +- **Agent Context**: 16 tests covering context state, actions, and error handling +- **Agent Utils**: 29 tests covering utility functions +- **Persistence**: Tests for localStorage and memory storage +- **Integration**: Tests for component integration + +## Troubleshooting + +### Common Issues + +1. **"useAgentContext must be used within an AgentProvider"** + - Ensure your component is wrapped with `AgentProvider` or `AgentConfigProvider` + +2. **Agents not persisting** + - Check that `persistToLocalStorage={true}` is set + - Verify localStorage is available in your environment + +3. **Health checks failing** + - Ensure agent URLs are accessible + - Check network connectivity + - Verify CORS settings for cross-origin requests + +4. **Duplicate agent errors** + - Each agent must have a unique ID and URL + - Use `generateAgentId()` for creating unique IDs + +### Debug Mode + +Enable debug logging: + +```tsx +const { setAgents, agents } = useAgentContext() + +// Log current state +console.log("Current agents:", agents) + +// Set up debug logging +setAgents([ + ...agents, + { id: "debug", name: "Debug Agent", url: "http://localhost:9999" } +]) +``` + +## Advanced Usage + +### Custom Storage Implementation + +```tsx +import { AgentStorage } from "@/lib/agent-persistence" + +class CustomStorage implements AgentStorage { + saveAgents(agents: Agent[]): void { + // Custom save logic + } + + loadAgents(): Agent[] { + // Custom load logic + return [] + } + + // ... implement other methods +} +``` + +### Custom Health Monitoring + +```tsx +import { useAgentContext } from "@/lib/agent-context" + +function CustomHealthMonitor() { + const { agents, updateAgentHealth } = useAgentContext() + + React.useEffect(() => { + const interval = setInterval(() => { + agents.forEach(agent => { + // Custom health check logic + const health = checkCustomHealth(agent) + updateAgentHealth(agent.id, health) + }) + }, 60000) // Check every minute + + return () => clearInterval(interval) + }, [agents]) + + return null +} +``` + +### Agent Import/Export + +```tsx +import { exportAgentsToJson, importAgentsFromJson } from "@/lib/agent-utils" + +function AgentImportExport() { + const { agents, setAgents } = useAgentContext() + + const handleExport = () => { + const json = exportAgentsToJson(agents) + const blob = new Blob([json], { type: "application/json" }) + const url = URL.createObjectURL(blob) + const a = document.createElement("a") + a.href = url + a.download = "agents-backup.json" + a.click() + } + + const handleImport = (event) => { + const file = event.target.files[0] + const reader = new FileReader() + reader.onload = (e) => { + try { + const importedAgents = importAgentsFromJson(e.target.result) + setAgents(importedAgents) + } catch (error) { + console.error("Failed to import agents:", error) + } + } + reader.readAsText(file) + } + + return ( +
+ + +
+ ) +} +``` + +## Contributing + +When adding new features to the agent management system: + +1. **Add tests** - Ensure comprehensive test coverage +2. **Update documentation** - Keep this README up to date +3. **Maintain backward compatibility** - Don't break existing APIs +4. **Follow patterns** - Use consistent patterns with existing code +5. **Handle errors** - Always handle edge cases and errors + +## Migration Checklist + +- [ ] Update imports from `@/lib/config` to `@/lib/agent-context` +- [ ] Replace `getAllAgents()` calls with `useAgentSelection()` +- [ ] Wrap components with `AgentConfigProvider` +- [ ] Update agent addition logic to use `addAgent()` +- [ ] Test persistence functionality +- [ ] Verify health monitoring works +- [ ] Update error handling +- [ ] Test cross-tab synchronization +- [ ] Verify backward compatibility + +## Support + +For issues and questions: + +1. Check the troubleshooting section above +2. Review the test files for usage examples +3. Check existing issues in the repository +4. Create a new issue with detailed information \ No newline at end of file diff --git a/packages/playground/CHANGELOG.md b/packages/playground/CHANGELOG.md deleted file mode 100644 index 893fee9a..00000000 --- a/packages/playground/CHANGELOG.md +++ /dev/null @@ -1,33 +0,0 @@ -# playground - -## 0.2.3 - -### Patch Changes - -- Updated dependencies [4af1485] - - @nullshot/mcp@0.3.0 - -## 0.2.2 - -### Patch Changes - -- 89571a8: playground introduction -- Updated dependencies [89571a8] - - @xava-labs/mcp@0.2.1 - -## 0.2.0 - -### Minor Changes - -- 0e0ff2d: Fixing versions to align them - -## 0.1.1 - -### Patch Changes - -- 4ae1bd8: \* Agent Framework using AI SDK and Cloudflare native primitives - - Services - Add routes to Agent - - Router - Likely an Agent Gateway, manages sessions, routing to agents, and CORS. - - Playground - A place for chatting with agents (and soon MCPs) - - Middleware - Inject tools, params, and modify LLM responses - - Example simple prompt agent (Bootstraps TODO List MCP + Playground) diff --git a/packages/playground/LICENSE b/packages/playground/LICENSE deleted file mode 100644 index d1ad2796..00000000 --- a/packages/playground/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -MIT License with Common Clause Condition - -Copyright (c) 2025 — XAVA Dao - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -"Commons Clause" License Condition v1.0 - -The Software is provided to you by the Licensor under the License (defined below), subject to the following condition: - -Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software. - -For purposes of the foregoing, "Sell" means practicing any or all of the rights granted to you under the License to provide the Software to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/support services related to the Software), as part of a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice. - -Software: All Playground associated files (including all files in the GitHub repository "typescript-agent-framework") - -License: MIT - -Licensor: XAVA Dao \ No newline at end of file diff --git a/packages/playground/MCP_TESTING_GUIDE.md b/packages/playground/MCP_TESTING_GUIDE.md deleted file mode 100644 index 9b153a82..00000000 --- a/packages/playground/MCP_TESTING_GUIDE.md +++ /dev/null @@ -1,122 +0,0 @@ -# MCP Add Request Testing Guide - -This document explains how to test the newly implemented MCP add request functionality, specifically focusing on the Time MCP server integration. - -## Implementation Overview - -The following components have been implemented: - -### 1. API Endpoints (`/api/mcp-servers`) -- **POST** `/api/mcp-servers` - Add a new MCP server -- **GET** `/api/mcp-servers` - List all MCP servers - -### 2. Server Proxy Updates (`McpServerProxyDO`) -- Added `/add-server` endpoint to handle add requests -- Added `/list-servers` endpoint to handle list requests -- Both endpoints forward messages to remote container via WebSocket - -### 3. Frontend Integration -- Updated `MCPServerDirectory` component to call API when toggling servers -- Added proper TypeScript types for API responses -- Integrated with Cloudflare Worker environment - -## Testing the Time MCP Server - -### Prerequisites -1. Ensure the MCP proxy server is running (typically at `ws://localhost:8787/remote-container/ws`) -2. Ensure the package manager server is running (typically at `ws://localhost:3000/ws`) -3. The playground should be accessible at the appropriate URL - -### Test Steps - -1. **Navigate to the Playground** - - Open the playground homepage where the MCP Server Directory is displayed - -2. **Locate the Time MCP Server** - - Find the "Time MCP Server" card in the directory - - It should show: - - Name: "Time MCP Server" - - Command: `npx` - - Args: `["-y", "@modelcontextprotocol/server-time"]` - - Environment: `{}` - -3. **Toggle the Server** - - Click the toggle switch on the Time MCP Server card - - This should trigger the add request - -4. **Expected Behavior** - - The toggle should call `POST /api/mcp-servers` with the Time MCP configuration - - The request should be forwarded to the `McpServerProxyDO` at `/add-server` - - The proxy should forward the message to the remote container via WebSocket - - If successful, the server should remain toggled "on" - - If failed, an alert should show the error message - -### API Request Format - -When toggling the Time MCP server, the following request is sent: - -```json -POST /api/mcp-servers -{ - "uniqueName": "time-mcp-server", - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-time"], - "env": {} -} -``` - -### WebSocket Message Format - -The message forwarded to the remote container: - -```json -{ - "verb": "add", - "data": { - "unique-name": "time-mcp-server", - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-time"], - "env": {} - } -} -``` - -## Debugging - -### Check Browser Console -- Look for success/error messages when toggling servers -- Check for network request failures - -### Check Server Logs -- Monitor the MCP proxy server logs for incoming WebSocket messages -- Monitor the package manager server logs for add/delete operations - -### Verify WebSocket Connections -- Ensure the proxy has an active WebSocket connection to the package manager -- Verify that messages are being forwarded correctly - -## Current Limitations - -1. **Response Handling**: The current implementation doesn't wait for responses from the remote container - it immediately returns success -2. **Delete Functionality**: Delete operations are not yet implemented (marked as TODO) -3. **Error Handling**: Basic error handling is in place but could be enhanced - -## Next Steps - -1. Implement proper response handling from remote container -2. Add delete functionality for disabling MCP servers -3. Add loading states during server operations -4. Enhance error handling and user feedback - -## File Structure - -``` -packages/playground/ -├── src/app/api/mcp-servers/route.ts # API endpoints -├── src/components/mcp-server-directory.tsx # Frontend component -├── worker-configuration.d.ts # TypeScript bindings -└── wrangler.jsonc # Durable Object configuration - -packages/mcp/src/mcp/ -└── server-proxy.ts # Server proxy with new endpoints -``` \ No newline at end of file diff --git a/packages/playground/README-CHAT.md b/packages/playground/README-CHAT.md new file mode 100644 index 00000000..a5a3b969 --- /dev/null +++ b/packages/playground/README-CHAT.md @@ -0,0 +1,134 @@ +# AI Agent Chat Playground + +A beautiful, mobile-responsive chat interface built with AI Elements and Next.js for connecting to AI agents. + +## Features + +- 🎨 Beautiful animated background inspired by nullshot.ai +- 💬 Floating chat interface with AI Elements components +- 🔄 Agent switching with dropdown selector +- 📱 Mobile responsive design +- 🛠️ Tool calling support +- 🎯 Real-time connection status +- ✨ Smooth animations and transitions + +## Environment Setup + +Create a `.env.local` file in the playground directory with the following variables: + +```env +# Default agent configuration +NEXT_PUBLIC_DEFAULT_AGENT_URL=http://localhost:8787 +NEXT_PUBLIC_DEFAULT_AGENT_NAME=Local Agent + +# Additional agents (optional, comma-separated) +NEXT_PUBLIC_ADDITIONAL_AGENTS=Production Agent|https://your-production-agent.com,Staging Agent|https://your-staging-agent.com +``` + +## Installation + +1. **Install AI Elements**: + + ```bash + npx ai-elements@latest + ``` + +2. **Install dependencies**: + + ```bash + npm install + ``` + +3. **Start the development server**: + ```bash + npm run dev + ``` + +## Usage + +1. **Default Connection**: The chat automatically connects to your default agent (localhost:8787 by default) + +2. **Agent Selection**: Use the dropdown in the chat header to switch between different agents + +3. **Chat Interface**: + - Click the floating chat button to open the interface + - Type messages and receive responses from your agent + - Use the minimize/maximize buttons to control the chat size + - Copy, like, or retry messages using the action buttons + +4. **Tool Support**: The interface automatically displays tool calls and their results when your agent uses functions + +## Agent Requirements + +Your agent should expose the following endpoints: + +1. **Chat Endpoint**: `POST /agent/chat/:sessionId?` + + ```typescript + { + messages: Array<{ + role: "user" | "assistant" | "system"; + content: string; + }>; + } + ``` + + - If no sessionId provided, agent creates one automatically + - Returns streaming text response + +2. **Health Check**: `GET /` (root endpoint) + - Any response (including 404) indicates agent is alive + - Used for connection status indicator + +The chat interface calls your agent directly from the browser using AI SDK's DefaultChatTransport - no server-side proxy or API routes needed! + +## Customization + +### Design System + +All colors and spacing use CSS variables defined in `src/app/globals.css`. Modify these variables to match your brand: + +- `--gradient-animated-1`: Primary animated background gradient +- `--chat-background`: Chat container background +- `--message-user-bg`: User message background color +- `--message-ai-bg`: AI message background color + +### Agent Configuration + +Modify `src/lib/config.ts` to customize agent parsing and default configuration. + +### Animations + +Background animations can be customized in `src/components/animated-background.tsx`. + +## AI Elements Integration + +Once AI Elements is installed, replace the placeholder components in `src/components/floating-chat.tsx`: + +```typescript +// Replace these imports: +import { + Conversation, + Message, + PromptInput, + Tool, + Actions, +} from "@/components/ai-elements"; + +// And update the component implementations to use AI Elements +``` + +## Mobile Responsiveness + +The chat interface adapts to different screen sizes: + +- **Mobile**: Full-screen overlay +- **Tablet**: Larger floating window +- **Desktop**: Fixed-size floating chat box + +## Development Notes + +- The interface uses Framer Motion for smooth animations +- Backdrop blur effects provide glassmorphism styling +- Connection status is checked every 30 seconds +- Messages auto-scroll to bottom on new content diff --git a/packages/playground/README.md b/packages/playground/README.md index 1ded8460..e215bc4c 100644 --- a/packages/playground/README.md +++ b/packages/playground/README.md @@ -1,318 +1,36 @@ -# @xava-labs/playground +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). -A comprehensive React component library for building MCP (Model Context Protocol) server management interfaces and AI chat experiences. +## Getting Started -## Installation +First, run the development server: ```bash -npm install @xava-labs/playground +npm run dev # or -yarn add @xava-labs/playground -``` - -## Usage - -### Complete Playground Component - -The easiest way to get started is with the complete playground component: - -```tsx -import { PlaygroundProvider, Playground } from '@xava-labs/playground'; -import '@xava-labs/playground/styles'; - -function App() { - return ( - - - - ); -} -``` - -### Individual Components - -You can also use individual components for more customized integrations: - -```tsx -import { - PlaygroundProvider, - ChatContainer, - MCPServerDirectory, - ModelSelector, - useConfigurableMcpServerManager -} from '@xava-labs/playground'; - -function CustomInterface() { - return ( - -
-
- { - console.log(`${server.name} ${enabled ? 'enabled' : 'disabled'}`); - }} - /> -
-
- -
-
- console.log(config)} /> -
-
-
- ); -} -``` - -### Using Hooks - -Access MCP server management functionality directly: - -```tsx -import { useConfigurableMcpServerManager, PlaygroundProvider } from '@xava-labs/playground'; - -function ServerManager() { - const { - servers, - connected, - loading, - addServer, - deleteServer, - refreshServers - } = useConfigurableMcpServerManager(); - - const handleAddServer = async () => { - await addServer({ - uniqueName: 'my-server', - command: 'npx', - args: ['my-mcp-server'], - env: { API_KEY: 'your-key' } - }); - }; - - return ( -
- -
    - {servers.map(server => ( -
  • {server.uniqueName}
  • - ))} -
-
- ); -} - -function App() { - return ( - - - - ); -} -``` - -## Configuration - -### PlaygroundConfig - -```typescript -interface PlaygroundConfig { - // Required: MCP Proxy URLs - mcpProxyUrl: string; // HTTP URL for MCP proxy - mcpProxyWsUrl: string; // WebSocket URL for real-time updates - - // Optional: API configuration - apiBaseUrl?: string; // Base URL for API calls (default: '/api') - - // Optional: Default model configuration - defaultModelConfig?: { - provider: 'openai' | 'anthropic'; - apiKey: string; - model: string; - }; - - // Optional: UI configuration - theme?: 'dark' | 'light'; // Default: 'dark' - enabledFeatures?: { - chat?: boolean; // Default: true - mcpServerDirectory?: boolean; // Default: true - modelSelector?: boolean; // Default: true - }; -} -``` - -### Environment Variables - -The playground supports the following environment variables: - -```bash -# MCP Registry Configuration -NEXT_PUBLIC_MCP_REGISTRY_URL=https://mcp-registry.nullshot.ai/latest.json # Default registry URL -NEXT_PUBLIC_MCP_PROXY_URL=http://localhost:6050 # MCP proxy HTTP URL -NEXT_PUBLIC_MCP_PROXY_WS_URL=ws://localhost:6050/client/ws # MCP proxy WebSocket URL - -# API Keys (for model providers) -OPENAI_API_KEY=your_openai_api_key -ANTHROPIC_API_KEY=your_anthropic_api_key -``` - -The `NEXT_PUBLIC_MCP_REGISTRY_URL` environment variable allows you to override the default MCP registry URL. This is useful for: -- Using a custom/private MCP registry -- Testing with a local registry during development -- Using alternative registry endpoints - -### Playground Component Props - -```typescript -interface PlaygroundProps { - className?: string; - style?: React.CSSProperties; - layout?: 'horizontal' | 'vertical'; // Default: 'horizontal' - showModelSelector?: boolean; // Default: true - showMCPDirectory?: boolean; // Default: true - showChat?: boolean; // Default: true -} -``` - -## Setting Up MCP Proxy - -The playground requires an MCP proxy server to manage MCP servers. You can use the `@xava-labs/mcp-proxy` package: - -```bash -# Install the proxy -npm install @xava-labs/mcp-proxy - -# Run the proxy -npx wrangler dev --port 6050 -``` - -Or set up your own proxy that implements the WebSocket protocol expected by the playground components. - -## Styling - -The package includes default styles that can be imported: - -```tsx -import '@xava-labs/playground/styles'; -``` - -The components use Tailwind CSS classes. Make sure your project has Tailwind CSS configured, or the components may not display correctly. - -## Examples - -### Complete MCP Development Environment - -```tsx -import { PlaygroundProvider, Playground } from '@xava-labs/playground'; -import '@xava-labs/playground/styles'; - -export default function MCPDevelopmentEnvironment() { - return ( - - - - ); -} -``` - -### Custom Chat Interface - -```tsx -import { - PlaygroundProvider, - ChatContainer, - useConfigurableMcpServerManager -} from '@xava-labs/playground'; - -function CustomChat() { - const { servers, connected } = useConfigurableMcpServerManager(); - - return ( -
-
- Connected Servers: {servers.length} | Status: {connected ? 'Connected' : 'Disconnected'} -
-
- -
-
- ); -} - -export default function App() { - return ( - - - - ); -} +yarn dev +# or +pnpm dev +# or +bun dev ``` -## API Reference - -### Components - -- `PlaygroundProvider` - Configuration provider component -- `Playground` - Complete playground interface -- `ChatContainer` - AI chat interface -- `MCPServerDirectory` - MCP server management UI -- `ModelSelector` - AI model selection interface -- `MCPServerItem` - Individual server item component -- UI components: `Button`, `Drawer`, `Sheet`, `Label`, `Textarea` - -### Hooks +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. -- `usePlaygroundConfig()` - Access playground configuration -- `useConfigurableMcpServerManager()` - MCP server management +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. -### Types +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. -- `PlaygroundConfig` - Configuration interface -- `McpServer` - MCP server data structure -- `PlaygroundProps` - Playground component props +## Learn More -## Requirements +To learn more about Next.js, take a look at the following resources: -- React 18+ or 19+ -- A running MCP proxy server -- Tailwind CSS for styling +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. -## Development +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! -See the main repository for development setup instructions. +## Deploy on Vercel -## License +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. -MIT License - see LICENSE file for details. +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/packages/playground/USAGE_EXAMPLE.md b/packages/playground/USAGE_EXAMPLE.md deleted file mode 100644 index c51693f7..00000000 --- a/packages/playground/USAGE_EXAMPLE.md +++ /dev/null @@ -1,236 +0,0 @@ -# Usage Example - -Here's a complete example of how to use `@xava-labs/playground` in your project: - -## Installation & Setup - -```bash -npm install @xava-labs/playground -``` - -## Basic Usage - -```tsx -// app.tsx -import React from 'react'; -import { PlaygroundProvider, Playground } from '@xava-labs/playground'; -import '@xava-labs/playground/styles'; - -function App() { - return ( - - - - ); -} - -export default App; -``` - -## Custom Configuration - -```tsx -// custom-playground.tsx -import React from 'react'; -import { - PlaygroundProvider, - ChatContainer, - MCPServerDirectory, - ModelSelector, - useConfigurableMcpServerManager -} from '@xava-labs/playground'; - -function CustomPlayground() { - return ( - -
-
- -
-
- -
-
-
- ); -} - -export default CustomPlayground; -``` - -## MCP Server Management Hook - -```tsx -// server-manager.tsx -import React from 'react'; -import { - PlaygroundProvider, - useConfigurableMcpServerManager -} from '@xava-labs/playground'; - -function ServerManager() { - const { - servers, - connected, - loading, - addServer, - deleteServer, - refreshServers, - isServerLoading - } = useConfigurableMcpServerManager(); - - const handleAddGitHubServer = async () => { - const success = await addServer({ - uniqueName: 'github-server', - command: 'npx', - args: ['@github/mcp-server'], - env: { GITHUB_TOKEN: process.env.REACT_APP_GITHUB_TOKEN || '' } - }); - - if (success) { - console.log('GitHub server added successfully'); - } - }; - - return ( -
-
-

MCP Servers

-

Connected: {connected ? 'Yes' : 'No'} | Loading: {loading ? 'Yes' : 'No'}

-
- -
- - -
- -
-

Active Servers ({servers.length})

- {servers.map(server => ( -
-
{server.uniqueName}
-
{server.command} {server.args.join(' ')}
-
Status: {server.status || 'unknown'}
- -
- ))} -
-
- ); -} - -function App() { - return ( - - - - ); -} - -export default App; -``` - -## Environment Variables - -Create a `.env` file in your project root: - -```bash -# .env -REACT_APP_MCP_PROXY_URL=http://localhost:6050 -REACT_APP_MCP_PROXY_WS_URL=ws://localhost:6050/client/ws -REACT_APP_OPENAI_API_KEY=your_openai_api_key_here -REACT_APP_ANTHROPIC_API_KEY=your_anthropic_api_key_here -REACT_APP_GITHUB_TOKEN=your_github_token_here -``` - -## Running the MCP Proxy - -Before using the playground, you need to run the MCP proxy server: - -```bash -# In a separate terminal -cd /path/to/mcp-proxy -npx wrangler dev --port 6050 -``` - -## TypeScript Support - -The package includes TypeScript definitions. Here are the main types you can use: - -```typescript -import type { - PlaygroundConfig, - McpServer, - PlaygroundProps, - UseMcpServerManagerReturn -} from '@xava-labs/playground'; - -const config: PlaygroundConfig = { - mcpProxyUrl: 'http://localhost:6050', - mcpProxyWsUrl: 'ws://localhost:6050/client/ws', - theme: 'dark' -}; - -const server: McpServer = { - uniqueName: 'my-server', - command: 'npx', - args: ['my-mcp-server'], - env: { API_KEY: 'secret' }, - status: 'running' -}; -``` - -## CSS/Styling - -The components use Tailwind CSS. Make sure your project has Tailwind CSS configured, or import the base styles: - -```tsx -import '@xava-labs/playground/styles'; -``` - -For custom styling, you can override the Tailwind classes or provide your own CSS. \ No newline at end of file diff --git a/packages/playground/env.d.ts b/packages/playground/cloudflare-env.d.ts similarity index 95% rename from packages/playground/env.d.ts rename to packages/playground/cloudflare-env.d.ts index 56576648..f5b52483 100644 --- a/packages/playground/env.d.ts +++ b/packages/playground/cloudflare-env.d.ts @@ -1,23 +1,13 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types --env-interface CloudflareEnv env.d.ts` (hash: f995525dec400187fae67d8e08a9d5e6) -// Runtime types generated with workerd@1.20250617.0 2025-04-01 nodejs_compat +// Generated by Wrangler by running `wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts` (hash: faf8a0423f869fe736da1a5ac5255eb6) +// Runtime types generated with workerd@1.20250906.0 2025-03-01 global_fetch_strictly_public,nodejs_compat declare namespace Cloudflare { interface Env { NEXTJS_ENV: string; - MCP_PROXY_URL: string; - WRANGLER_BUILD_CONDITIONS: string; - WRANGLER_BUILD_PLATFORM: string; - MCP_PROXY: Fetcher /* mcp-proxy */; ASSETS: Fetcher; } } interface CloudflareEnv extends Cloudflare.Env {} -type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; -}; -declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} -} // Begin runtime types /*! ***************************************************************************** @@ -357,7 +347,7 @@ interface ExecutionContext { type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; @@ -421,11 +411,12 @@ interface DurableObjectId { equals(other: DurableObjectId): boolean; readonly name?: string; } -interface DurableObjectNamespace { +declare abstract class DurableObjectNamespace { newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; idFromName(name: string): DurableObjectId; idFromString(id: string): DurableObjectId; get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; } type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; @@ -438,6 +429,7 @@ interface DurableObjectNamespaceGetDurableObjectOptions { } interface DurableObjectState { waitUntil(promise: Promise): void; + props: any; readonly id: DurableObjectId; readonly storage: DurableObjectStorage; container?: Container; @@ -480,6 +472,7 @@ interface DurableObjectStorage { deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; sync(): Promise; sql: SqlStorage; + kv: SyncKvStorage; transactionSync(closure: () => T): T; getCurrentBookmark(): Promise; getBookmarkForTime(timestamp: number | Date): Promise; @@ -1110,6 +1103,47 @@ interface ErrorEventErrorEventInit { colno?: number; error?: any; } +/** + * A message received by a target object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) + */ +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + /** + * Returns the data of the message. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * Returns the origin of the message, for server-sent events and cross-document messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * Returns the last event ID string, for server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; +} +interface MessageEventInit { + data: ArrayBuffer | string; +} /** * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". * @@ -1418,7 +1452,7 @@ interface RequestInit { signal?: (AbortSignal | null); encodeResponseBody?: "automatic" | "manual"; } -type Service = Fetcher; +type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { fetch(input: RequestInfo | URL, init?: RequestInit): Promise; connect(address: SocketAddress | string, options?: SocketOptions): Socket; @@ -2010,6 +2044,7 @@ interface TraceItem { readonly scriptVersion?: ScriptVersion; readonly dispatchNamespace?: string; readonly scriptTags?: string[]; + readonly durableObjectId?: string; readonly outcome: string; readonly executionModel: string; readonly truncated: boolean; @@ -2291,23 +2326,6 @@ interface CloseEventInit { reason?: string; wasClean?: boolean; } -/** - * A message received by a target object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) - */ -declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * Returns the data of the message. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: ArrayBuffer | string; -} -interface MessageEventInit { - data: ArrayBuffer | string; -} type WebSocketEventMap = { close: CloseEvent; message: MessageEvent; @@ -2495,6 +2513,55 @@ interface ContainerStartupOptions { enableInternet: boolean; env?: Record; } +/** + * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) + */ +interface MessagePort extends EventTarget { + /** + * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. + * + * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * Disconnects the port, so that it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * Begins dispatching messages received on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); +} +interface MessagePortPostMessageOptions { + transfer?: any[]; +} +interface SyncKvStorage { + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[ + string, + T + ]>; + put(key: string, value: T): void; + delete(key: string): boolean; +} +interface SyncKvListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; +} type AiImageClassificationInput = { image: number[]; }; @@ -5270,7 +5337,7 @@ type AiModelListType = Record; declare abstract class Ai { aiGatewayLogId: string | null; gateway(gatewayId: string): AiGateway; - autorag(autoragId: string): AutoRAG; + autorag(autoragId?: string): AutoRAG; run(model: Name, inputs: InputOptions, options?: Options): Promise & { + /** + ** @deprecated + */ + id?: string; +}; type AiGatewayPatchLog = { score?: number | null; feedback?: -1 | 1 | null; @@ -5376,7 +5449,7 @@ declare abstract class AiGateway { patchLog(logId: string, data: AiGatewayPatchLog): Promise; getLog(logId: string): Promise; run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: GatewayOptions; + gateway?: UniversalGatewayOptions; extraHeaders?: object; }): Promise; getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line @@ -5410,6 +5483,7 @@ type AutoRagSearchRequest = { }; type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean; + system_prompt?: string; }; type AutoRagAiSearchRequestStreaming = Omit & { stream: true; @@ -5485,6 +5559,12 @@ interface BasicImageTransformations { * breaks aspect ratio */ fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: "foreground"; /** * When cropping with fit: "cover", this defines the side or point that should * be left uncropped. The value is either a string @@ -5497,7 +5577,7 @@ interface BasicImageTransformations { * preserve as much as possible around a point at 20% of the height of the * source image. */ - gravity?: 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; /** * Background color to add underneath the image. Applies only to images with * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), @@ -5784,13 +5864,13 @@ interface IncomingRequestCfPropertiesBase extends Record { * * @example 395747 */ - asn: number; + asn?: number; /** * The organization which owns the ASN of the incoming request. * * @example "Google Cloud" */ - asOrganization: string; + asOrganization?: string; /** * The original value of the `Accept-Encoding` header if Cloudflare modified it. * @@ -5914,7 +5994,7 @@ interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { * This field is only present if you have Cloudflare for SaaS enabled on your account * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). */ - hostMetadata: HostMetadata; + hostMetadata?: HostMetadata; } interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { /** @@ -6340,6 +6420,22 @@ declare module "cloudflare:email" { }; export { _EmailMessage as EmailMessage }; } +/** + * Hello World binding to serve as an explanatory example. DO NOT USE + */ +interface HelloWorldBinding { + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; +} interface Hyperdrive { /** * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. @@ -6417,7 +6513,8 @@ type ImageTransform = { fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; flip?: 'h' | 'v' | 'hv'; gamma?: number; - gravity?: 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { + segment?: 'foreground'; + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { x?: number; y?: number; mode: 'remainder' | 'box-center'; @@ -6425,7 +6522,7 @@ type ImageTransform = { rotate?: 0 | 90 | 180 | 270; saturation?: number; sharpen?: number; - trim?: "border" | { + trim?: 'border' | { top?: number; bottom?: number; left?: number; @@ -6447,10 +6544,14 @@ type ImageDrawOptions = { bottom?: number; right?: number; }; +type ImageInputOptions = { + encoding?: 'base64'; +}; type ImageOutputOptions = { format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; quality?: number; background?: string; + anim?: boolean; }; interface ImagesBinding { /** @@ -6458,13 +6559,13 @@ interface ImagesBinding { * @throws {@link ImagesError} with code 9412 if input is not an image * @param stream The image bytes */ - info(stream: ReadableStream): Promise; + info(stream: ReadableStream, options?: ImageInputOptions): Promise; /** * Begin applying a series of transformations to an image * @param stream The image bytes * @returns A transform handle */ - input(stream: ReadableStream): ImageTransformer; + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; } interface ImageTransformer { /** @@ -6487,6 +6588,9 @@ interface ImageTransformer { */ output(options: ImageOutputOptions): Promise; } +type ImageTransformationOutputOptions = { + encoding?: 'base64'; +}; interface ImageTransformationResult { /** * The image as a response, ready to store in cache or return to users @@ -6499,13 +6603,115 @@ interface ImageTransformationResult { /** * The bytes of the response */ - image(): ReadableStream; + image(options?: ImageTransformationOutputOptions): ReadableStream; } interface ImagesError extends Error { readonly code: number; readonly message: string; readonly stack?: string; } +/** + * Media binding for transforming media streams. + * Provides the entry point for media transformation operations. + */ +interface MediaBinding { + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer; +} +/** + * Media transformer for applying transformation operations to media content. + * Handles sizing, fitting, and other input transformation parameters. + */ +interface MediaTransformer { + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; +} +/** + * Generator for producing media transformation results. + * Configures the output format and parameters for the transformed media. + */ +interface MediaTransformationGenerator { + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output: MediaTransformationOutputOptions): MediaTransformationResult; +} +/** + * Result of a media transformation operation. + * Provides multiple ways to access the transformed media content. + */ +interface MediaTransformationResult { + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A stream containing the transformed media data + */ + media(): ReadableStream; + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Response, ready to store in cache or return to users + */ + response(): Response; + /** + * Returns the MIME type of the transformed media. + * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): string; +} +/** + * Configuration options for transforming media input. + * Controls how the media should be resized and fitted. + */ +type MediaTransformationInputOptions = { + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down'; + /** Target width in pixels */ + width?: number; + /** Target height in pixels */ + height?: number; +}; +/** + * Configuration options for Media Transformations output. + * Controls the format, timing, and type of the generated output. + */ +type MediaTransformationOutputOptions = { + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; + /** Whether to include audio in the output */ + audio?: boolean; + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string; + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string; + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a'; +}; +/** + * Error object for media transformation operations. + * Extends the standard Error interface with additional media-specific information. + */ +interface MediaError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} type Params

= Record; type EventContext = { request: Request>; @@ -6724,6 +6930,19 @@ declare namespace Cloudflare { interface Env { } } +declare module 'cloudflare:node' { + export interface DefaultHandler { + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export function httpServerHandler(options: { + port: number; + }, handlers?: Omit): DefaultHandler; +} declare module 'cloudflare:workers' { export type RpcStub = Rpc.Stub; export const RpcStub: { @@ -6797,6 +7016,7 @@ declare module 'cloudflare:workers' { constructor(ctx: ExecutionContext, env: Env); run(event: Readonly>, step: WorkflowStep): Promise; } + export function waitUntil(promise: Promise): void; export const env: Cloudflare.Env; } interface SecretsStoreSecret { @@ -6819,7 +7039,7 @@ declare namespace TailStream { readonly type: "fetch"; readonly method: string; readonly url: string; - readonly cfJson: string; + readonly cfJson?: object; readonly headers: Header[]; } interface JsRpcEventInfo { @@ -6865,10 +7085,6 @@ declare namespace TailStream { readonly type: "hibernatableWebSocket"; readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; } - interface Resume { - readonly type: "resume"; - readonly attachment?: any; - } interface CustomEventInfo { readonly type: "custom"; } @@ -6882,21 +7098,18 @@ declare namespace TailStream { readonly tag?: string; readonly message?: string; } - interface Trigger { - readonly traceId: string; - readonly invocationId: string; - readonly spanId: string; - } interface Onset { readonly type: "onset"; + readonly attributes: Attribute[]; + // id for the span being opened by this Onset event. + readonly spanId: string; readonly dispatchNamespace?: string; readonly entrypoint?: string; readonly executionModel: string; readonly scriptName?: string; readonly scriptTags?: string[]; readonly scriptVersion?: ScriptVersion; - readonly trigger?: Trigger; - readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | Resume | CustomEventInfo; + readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; } interface Outcome { readonly type: "outcome"; @@ -6904,12 +7117,11 @@ declare namespace TailStream { readonly cpuTime: number; readonly wallTime: number; } - interface Hibernate { - readonly type: "hibernate"; - } interface SpanOpen { readonly type: "spanOpen"; readonly name: string; + // id for the span being opened by this SpanOpen event. + readonly spanId: string; readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; } interface SpanClose { @@ -6930,19 +7142,16 @@ declare namespace TailStream { interface Log { readonly type: "log"; readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: string; + readonly message: object; } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. interface Return { readonly type: "return"; readonly info?: FetchResponseInfo; } - interface Link { - readonly type: "link"; - readonly label?: string; - readonly traceId: string; - readonly invocationId: string; - readonly spanId: string; - } interface Attribute { readonly name: string; readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; @@ -6951,17 +7160,44 @@ declare namespace TailStream { readonly type: "attributes"; readonly info: Attribute[]; } - interface TailEvent { + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. readonly traceId: string; + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 1. This is an Onset event + // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + readonly spanId?: string; + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. readonly invocationId: string; - readonly spanId: string; + // Inherited spanContext for this event. + readonly spanContext: SpanContext; readonly timestamp: Date; readonly sequence: number; - readonly event: Onset | Outcome | Hibernate | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Link | Attributes; + readonly event: Event; } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerName = "outcome" | "hibernate" | "spanOpen" | "spanClose" | "diagnosticChannel" | "exception" | "log" | "return" | "link" | "attributes"; - type TailEventHandlerObject = Record; + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + attributes?: TailEventHandler; + }; type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; } // Copyright (c) 2022-2023 Cloudflare, Inc. diff --git a/packages/playground/components.json b/packages/playground/components.json index ffe928f5..0341e204 100644 --- a/packages/playground/components.json +++ b/packages/playground/components.json @@ -10,6 +10,7 @@ "cssVariables": true, "prefix": "" }, + "iconLibrary": "lucide", "aliases": { "components": "@/components", "utils": "@/lib/utils", @@ -17,5 +18,7 @@ "lib": "@/lib", "hooks": "@/hooks" }, - "iconLibrary": "lucide" -} \ No newline at end of file + "registries": { + "@ai-elements": "https://registry.ai-sdk.dev/{name}.json" + } +} diff --git a/packages/playground/eslint.config.mjs b/packages/playground/eslint.config.mjs new file mode 100644 index 00000000..965242ef --- /dev/null +++ b/packages/playground/eslint.config.mjs @@ -0,0 +1,18 @@ +import { dirname } from "path"; +import { fileURLToPath } from "url"; +import { FlatCompat } from "@eslint/eslintrc"; +import { defineConfig, globalIgnores } from "eslint/config"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const compat = new FlatCompat({ + baseDirectory: __dirname, +}); + +const eslintConfig = defineConfig([ + ...compat.extends("next/core-web-vitals", "next/typescript"), + globalIgnores(["src/**/ai-elements/**"]), +]); + +export default eslintConfig; diff --git a/packages/playground/package.json b/packages/playground/package.json index 690fd80d..ef552529 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -1,7 +1,8 @@ { "name": "@nullshot/playground", - "version": "0.2.3", - "private": true, + "version": "0.1.0", + "private": false, + "description": "AI Agent Playground - Connect and chat with your AI agents in a beautiful interface", "main": "./dist/index.js", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", @@ -10,76 +11,96 @@ "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.js" - }, - "./styles": "./dist/styles.css" + } }, "files": [ "dist", "README.md" ], + "keywords": [ + "ai", + "agents", + "playground", + "chat", + "interface" + ], + "author": "Nullshot", + "license": "MIT", "scripts": { - "dev": "wrangler dev -c ../mcp-proxy/wrangler.jsonc --port 6050 & next dev", - "build": "pnpm run build:lib", - "build:app": "next build", - "build:lib": "tsup --config tsup.config.ts --tsconfig tsconfig.lib.json", + "dev": "next dev --turbopack", + "build": "next build", + "build:lib": "tsup && next build", + "prepublishOnly": "npm run build:lib", "start": "next start", - "lint": "next lint --max-warnings 0", - "lint:fix": "next lint --fix --max-warnings 0", - "type-check": "tsc --noEmit", - "test": "echo No tests", + "lint": "next lint", + "test": "vitest", + "test:watch": "vitest --watch", + "test:ui": "vitest --ui", + "setup": "node scripts/setup-playground.js", + "setup-ai-elements": "npx ai-elements@latest", "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy", - "preview": "opennextjs-cloudflare build && wrangler dev -c ./wrangler.jsonc -c ../mcp-proxy/wrangler.jsonc", - "codegen": "wrangler types --env-interface CloudflareEnv env.d.ts", - "prepublishOnly": "pnpm run build:lib" + "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview", + "cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts" }, "dependencies": { - "@ai-sdk/anthropic": "^1.2.12", - "@ai-sdk/openai": "^1.3.22", - "@ai-sdk/react": "^1.2.12", - "@modelcontextprotocol/sdk": "^1.13.0", - "@radix-ui/react-accordion": "^1.2.11", - "@radix-ui/react-dialog": "^1.1.14", - "@radix-ui/react-dropdown-menu": "^2.1.12", + "@hookform/resolvers": "^5.2.1", + "@opennextjs/cloudflare": "^1.8.2", + "@radix-ui/react-avatar": "^1.1.10", + "@radix-ui/react-collapsible": "^1.1.12", + "@radix-ui/react-dialog": "^1.1.15", + "@radix-ui/react-dropdown-menu": "^2.1.16", + "@radix-ui/react-hover-card": "^1.1.15", + "@radix-ui/react-icons": "^1.3.2", "@radix-ui/react-label": "^2.1.7", + "@radix-ui/react-progress": "^1.1.8", + "@radix-ui/react-scroll-area": "^1.2.10", + "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-slot": "^1.2.3", - "@radix-ui/react-switch": "^1.1.2", - "@radix-ui/react-tooltip": "^1.2.0", - "@nullshot/mcp": "workspace:*", - "agents": "^0.0.75", - "ai": "catalog:", + "@radix-ui/react-toast": "^1.2.15", + "@radix-ui/react-tooltip": "^1.2.8", + "@radix-ui/react-use-controllable-state": "^1.2.2", + "@xyflow/react": "^12.9.3", + "ai": "^5.0.97", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", - "date-fns": "^4.1.0", - "fuse.js": "^7.1.0", - "lucide-react": "^0.503.0", - "next": "15.2.3", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "tailwind-merge": "^3.2.0", - "vaul": "^1.1.2", - "zod": "catalog:" + "cmdk": "^1.1.1", + "embla-carousel-react": "^8.6.0", + "framer-motion": "^12.23.12", + "lucide-react": "^0.543.0", + "motion": "^12.23.24", + "nanoid": "^5.1.5", + "next": "15.5.2", + "react": "^18.3.0", + "react-dom": "^18.3.0", + "react-hook-form": "^7.62.0", + "react-syntax-highlighter": "^15.6.6", + "shiki": "^3.15.0", + "streamdown": "^1.5.1", + "tailwind-merge": "^3.3.1", + "tokenlens": "^1.3.1", + "use-stick-to-bottom": "^1.1.1", + "zod": "^4.1.5" }, "devDependencies": { - "@eslint/eslintrc": "^3", - "@opennextjs/cloudflare": "^1.3.1", - "@tailwindcss/postcss": "^4", - "@types/node": "^20", - "@types/react": "^19", - "@types/react-dom": "^19", - "eslint": "^9.29.0", - "eslint-config-next": "15.3.1", - "minimatch": "^9.0.5", - "tailwindcss": "^4", - "tsup": "^8.3.5", - "tw-animate-css": "^1.2.8", - "typescript": "^5", - "wrangler": "^4.13.0" - }, - "peerDependencies": { - "react": "^18.0.0 || ^19.0.0", - "react-dom": "^18.0.0 || ^19.0.0" - }, - "publishConfig": { - "access": "public" + "@eslint/eslintrc": "^3.3.1", + "@tailwindcss/postcss": "^4.1.13", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.1.0", + "@types/node": "^24.3.1", + "@types/react-syntax-highlighter": "^15.5.13", + "@types/react": "^18.3.4", + "@types/react-dom": "^18.3.4", + "@vitejs/plugin-react": "^4.3.4", + "@vitest/ui": "~3.2.0", + "eslint": "^9.35.0", + "eslint-config-next": "15.5.2", + "jsdom": "^25.0.1", + "tailwindcss": "^4.1.13", + "tsup": "^8.5.1", + "tw-animate-css": "^1.3.8", + "typescript": "^5.9.2", + "vitest": "~3.2.0", + "wrangler": "^4.35.0" } } diff --git a/packages/playground/plan/agent-chatbox.md b/packages/playground/plan/agent-chatbox.md deleted file mode 100644 index f022194a..00000000 --- a/packages/playground/plan/agent-chatbox.md +++ /dev/null @@ -1,184 +0,0 @@ -# Agent Chatbox Implementation Plan - -## Overview -We are building a chat interface in the playground application using shadcn/ui, Tailwind CSS v4 with CSS variables for theming, and the Vercel AI SDK UI for streaming responses. The chat interface will feature chat bubbles that contain text and timestamps, with two different themes: green for agent messages and gray for user messages. We'll import images and CSS from Figma using the Figma MCP (Model Context Protocol). - -## Steps - -### 1. Setup and Configuration (Completed) -- [x] Install shadcn/ui -- [x] Configure for Tailwind CSS v4 -- [x] Setup CSS variables for theming - -### 2. Component Structure (Completed) -- [x] Create a ChatContainer component - - This will hold the entire chat interface -- [x] Create a ChatMessage component - - This will be responsible for rendering individual messages - - It will support two variants: user and agent -- [x] Create a ChatInput component - - For users to type and send messages - -### 3. Styling (Completed) -- [x] Define CSS variables for the chat themes - - Green theme for agent messages - - Gray theme for user messages -- [x] Style the chat bubbles with rounded corners -- [x] Add appropriate spacing and alignment - - User messages aligned to the right - - Agent messages aligned to the left - -### 4. Figma Integration (Completed) -- [x] Extract UI elements from Figma using Figma MCP - - Avatar images - - Icons - - Exact color values - - Typography details -- [x] Implement exact styling from Figma design - -### 5. Functionality (Completed) -- [x] Implement message display logic -- [x] Add timestamp formatting -- [x] Create message send functionality - -### 6. Enhanced Chat Features (Completed) -- [x] Add a chat header/top bar based on Figma design - - [x] Implement title component with "Chat with Vista" text - - [x] Add edit button with square-pen icon - - [x] Add menu button with ellipsis-vertical icon - - [x] Implement dropdown menu for the ellipsis button with options: - - [x] Search - - [x] Chat Logs - - [x] Share Chat -- [x] Create a date divider component - - [x] Display date in the format "Day, DD Mon YYYY" - - [x] Show divider when messages transition to a new day - - [x] Center the date divider between messages -- [x] Smart date handling - - [x] Process message list to automatically insert date dividers when day changes - - [x] Group messages by date for better organization - -### 7. AI SDK Integration (In Progress) -- [x] Install Vercel AI SDK UI package - ```bash - npm install ai - ``` -- [x] Implement message streaming using AI SDK - - [x] Create useChat hook with proper configuration - - [x] Connect to localhost:8787/agent/chat endpoint - - [x] Extract session ID from X-Session-Id header - - [x] Update router with session ID for persistence -- [x] Create animated "thinking" state - - [x] Show agent icon with empty chat bubble during "thinking" state - - [x] Add animation to indicate processing (pulsing border or typing indicator) - - [x] Animate chat box appearance when text starts streaming - - [x] Implement typing animation for text streaming - -### 8. ChatContainer Refactoring (In Progress) -- [x] Convert ChatContainer to use AI SDK internally - - [x] Make ChatContainer configurable with or without SDK - - [x] Create a parameter to enable/disable AI SDK integration - - [x] Implement proper message handling and streaming -- [x] Hook up handleInputChange/handleSendMessage for input box - - [x] Connect to AI SDK's message submission - - [x] Handle loading states properly - - [x] Implement error handling for failed requests - -### 9. Session Management (Completed) -- [x] Implement session persistence - - [x] Extract session ID from server response headers - - [x] Update browser URL to include session ID - - [x] Load existing session when session ID is present in URL - - [ ] Implement local storage fallback for session data (Optional) - -### 10. Accessibility (Pending) -- [ ] Ensure proper contrast ratios -- [ ] Add appropriate ARIA labels -- [ ] Test keyboard navigation -- [ ] Add screen reader support for streaming text - -## Implementation Details - -### Component Hierarchy -``` -ChatContainer -├── ChatHeader (Top bar with title and buttons) -├── ChatMessageList -│ ├── DateDivider (Appears when day changes) -│ ├── User messages (gray theme) -│ └── Agent messages (green theme with thinking animation) -└── ChatInput (Connected to AI SDK) -``` - -### CSS Variables -We've added the following custom CSS variables to our theme: -- `--chat-user-bg`: Background color for user messages (dark gray) -- `--chat-user-text`: Text color for user messages (white with opacity) -- `--chat-agent-bg`: Background gradient for agent messages (teal gradient) -- `--chat-agent-text`: Text color for agent messages (white with opacity) -- `--chat-timestamp`: Color for timestamp text (white with opacity) -- `--chat-date-divider-bg`: Background color for date divider (#17181A) -- `--chat-date-divider-border`: Border gradient for date divider -- `--chat-header-bg`: Background color for the chat header (#151515) -- `--chat-header-border`: Border color for the chat header (rgba(255, 255, 255, 0.12)) - -### Added CSS for Animation -New CSS variables and animations for the thinking state: -- `--chat-thinking-animation`: Animation for the thinking state (pulsing or typing indicator) -- `--chat-thinking-duration`: Duration for thinking animation -- `--chat-text-animation`: Animation for text streaming - -### AI SDK Integration -We've implemented the Vercel AI SDK's `useChat` hook for message handling and streaming: -```jsx -// Inside the ChatContainer component -const { - messages: aiMessages, - input, - handleInputChange, - handleSubmit, - isLoading, - error -} = useChat({ - api: apiUrl, - onResponse: (response) => { - // Extract session ID from headers and update URL - const sessionId = response.headers.get('X-Session-Id'); - if (sessionId) { - router.push(`/agent/chat/${sessionId}`); - } - } -}); -``` - -We've also: -- Added support for "thinking" state during message loading -- Implemented smooth animations for message streaming -- Created dynamic routes for session management -- Made the ChatContainer configurable to work with or without the AI SDK - -### Next Steps -1. ✅ Create the basic component structure -2. ✅ Extract design elements from Figma -3. ✅ Implement styling with CSS variables -4. ✅ Add message functionality -5. ✅ Implement chat header with buttons -6. ✅ Create date divider component -7. ✅ Add smart date handling for message groups -8. ✅ Install and integrate Vercel AI SDK -9. ✅ Implement the "thinking" state animation -10. ✅ Refactor ChatContainer to use AI SDK -11. ✅ Implement session management with URL updates -12. Test and refine the implementation -13. Focus on accessibility improvements - -## Summary of Implementation -We're enhancing our chat interface to use the Vercel AI SDK for streaming responses and adding animated states for improved user experience. The enhancements include: - -1. ✅ Integration with Vercel AI SDK for real-time message streaming -2. ✅ An animated "thinking" state that shows when the agent is processing -3. ✅ Typing animation for text as it streams in -4. ✅ Session persistence through URL parameters -5. ✅ Refactoring the ChatContainer to be more configurable -6. ✅ Improved error handling for failed requests -7. Accessibility enhancements for the streaming text \ No newline at end of file diff --git a/packages/playground/public/_headers b/packages/playground/public/_headers new file mode 100644 index 00000000..fcf9539e --- /dev/null +++ b/packages/playground/public/_headers @@ -0,0 +1,3 @@ +# https://developers.cloudflare.com/workers/static-assets/headers +/_next/static/* + Cache-Control: public,max-age=31536000,immutable diff --git a/packages/playground/public/avatars/1.png b/packages/playground/public/avatars/1.png new file mode 100644 index 00000000..84d747b0 Binary files /dev/null and b/packages/playground/public/avatars/1.png differ diff --git a/packages/playground/public/avatars/10.png b/packages/playground/public/avatars/10.png new file mode 100644 index 00000000..2136a4f2 Binary files /dev/null and b/packages/playground/public/avatars/10.png differ diff --git a/packages/playground/public/avatars/11.png b/packages/playground/public/avatars/11.png new file mode 100644 index 00000000..1e5f96a7 Binary files /dev/null and b/packages/playground/public/avatars/11.png differ diff --git a/packages/playground/public/avatars/12.png b/packages/playground/public/avatars/12.png new file mode 100644 index 00000000..b92d5101 Binary files /dev/null and b/packages/playground/public/avatars/12.png differ diff --git a/packages/playground/public/avatars/13.png b/packages/playground/public/avatars/13.png new file mode 100644 index 00000000..b37b2164 Binary files /dev/null and b/packages/playground/public/avatars/13.png differ diff --git a/packages/playground/public/avatars/14.png b/packages/playground/public/avatars/14.png new file mode 100644 index 00000000..c300fc22 Binary files /dev/null and b/packages/playground/public/avatars/14.png differ diff --git a/packages/playground/public/avatars/15.png b/packages/playground/public/avatars/15.png new file mode 100644 index 00000000..cf649862 Binary files /dev/null and b/packages/playground/public/avatars/15.png differ diff --git a/packages/playground/public/avatars/16.png b/packages/playground/public/avatars/16.png new file mode 100644 index 00000000..bfed65a0 Binary files /dev/null and b/packages/playground/public/avatars/16.png differ diff --git a/packages/playground/public/avatars/17.png b/packages/playground/public/avatars/17.png new file mode 100644 index 00000000..85732479 Binary files /dev/null and b/packages/playground/public/avatars/17.png differ diff --git a/packages/playground/public/avatars/18.png b/packages/playground/public/avatars/18.png new file mode 100644 index 00000000..bf51137a Binary files /dev/null and b/packages/playground/public/avatars/18.png differ diff --git a/packages/playground/public/avatars/19.png b/packages/playground/public/avatars/19.png new file mode 100644 index 00000000..52a555e7 Binary files /dev/null and b/packages/playground/public/avatars/19.png differ diff --git a/packages/playground/public/avatars/2.png b/packages/playground/public/avatars/2.png new file mode 100644 index 00000000..e663924c Binary files /dev/null and b/packages/playground/public/avatars/2.png differ diff --git a/packages/playground/public/avatars/3.png b/packages/playground/public/avatars/3.png new file mode 100644 index 00000000..f416eabe Binary files /dev/null and b/packages/playground/public/avatars/3.png differ diff --git a/packages/playground/public/avatars/4.png b/packages/playground/public/avatars/4.png new file mode 100644 index 00000000..3ceb11fe Binary files /dev/null and b/packages/playground/public/avatars/4.png differ diff --git a/packages/playground/public/avatars/5.png b/packages/playground/public/avatars/5.png new file mode 100644 index 00000000..491f3782 Binary files /dev/null and b/packages/playground/public/avatars/5.png differ diff --git a/packages/playground/public/avatars/6.png b/packages/playground/public/avatars/6.png new file mode 100644 index 00000000..fdfbb223 Binary files /dev/null and b/packages/playground/public/avatars/6.png differ diff --git a/packages/playground/public/avatars/7.png b/packages/playground/public/avatars/7.png new file mode 100644 index 00000000..9162cd7f Binary files /dev/null and b/packages/playground/public/avatars/7.png differ diff --git a/packages/playground/public/avatars/8.png b/packages/playground/public/avatars/8.png new file mode 100644 index 00000000..3de314c7 Binary files /dev/null and b/packages/playground/public/avatars/8.png differ diff --git a/packages/playground/public/avatars/9.png b/packages/playground/public/avatars/9.png new file mode 100644 index 00000000..fc618747 Binary files /dev/null and b/packages/playground/public/avatars/9.png differ diff --git a/packages/playground/public/images/badge_light_bg.png b/packages/playground/public/images/badge_light_bg.png deleted file mode 100644 index d86a62a0..00000000 Binary files a/packages/playground/public/images/badge_light_bg.png and /dev/null differ diff --git a/packages/playground/public/images/cursor-logo.svg b/packages/playground/public/images/cursor-logo.svg deleted file mode 100644 index e475ca9a..00000000 --- a/packages/playground/public/images/cursor-logo.svg +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/packages/playground/public/images/default-avatar.png b/packages/playground/public/images/default-avatar.png deleted file mode 100644 index e02f4e89..00000000 Binary files a/packages/playground/public/images/default-avatar.png and /dev/null differ diff --git a/packages/playground/public/images/ellipse.svg b/packages/playground/public/images/ellipse.svg deleted file mode 100644 index 674cf092..00000000 --- a/packages/playground/public/images/ellipse.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/packages/playground/public/images/gears.png b/packages/playground/public/images/gears.png deleted file mode 100644 index fb7ef494..00000000 Binary files a/packages/playground/public/images/gears.png and /dev/null differ diff --git a/packages/playground/public/images/mcp-install-dark.svg b/packages/playground/public/images/mcp-install-dark.svg deleted file mode 100644 index 3dacb7f1..00000000 --- a/packages/playground/public/images/mcp-install-dark.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/packages/playground/public/images/mcp-install-light.svg b/packages/playground/public/images/mcp-install-light.svg deleted file mode 100644 index e5b57623..00000000 --- a/packages/playground/public/images/mcp-install-light.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/packages/playground/setup-chat.md b/packages/playground/setup-chat.md new file mode 100644 index 00000000..9f4038a9 --- /dev/null +++ b/packages/playground/setup-chat.md @@ -0,0 +1,140 @@ +# Setup Instructions for AI Agent Chat Playground + +## Quick Start + +### 1. Install Dependencies + +```bash +cd packages/playground +npm install +``` + +### 2. Install AI Elements + +```bash +npx ai-elements@latest +``` + +This will: + +- Install the AI Elements component library +- Set up shadcn/ui if not already configured +- Add necessary AI Elements components to your project + +### 3. Environment Configuration + +Create a `.env.local` file in the `packages/playground` directory: + +```bash +# Default agent configuration +NEXT_PUBLIC_DEFAULT_AGENT_URL=http://localhost:8787 +NEXT_PUBLIC_DEFAULT_AGENT_NAME=Local Agent + +# Additional agents (optional) +NEXT_PUBLIC_ADDITIONAL_AGENTS=Production Agent|https://your-production-agent.com,Staging Agent|https://your-staging-agent.com +``` + +### 4. Start Development Server + +```bash +npm run dev +``` + +Visit `http://localhost:3000` to see your AI agent playground. + +## AI Elements Integration + +After installing AI Elements, update the imports in `src/components/floating-chat.tsx`: + +```typescript +// Replace placeholder implementations with: +import { + Conversation, + Message, + PromptInput, + Tool, + Actions, + Response, + Loader, +} from "@/components/ai-elements"; +``` + +Then update the component implementations to use the actual AI Elements components instead of the custom implementations. + +## Agent Connection + +The chat interface expects your agent to have: + +1. **Chat Endpoint**: `POST /api/chat` + + ```typescript + // Request format + { + messages: Array<{ + role: "user" | "assistant" | "system"; + content: string; + }>; + } + ``` + +2. **Health Check** (optional): `GET /health` + - Returns 200 OK if agent is healthy + - Used for connection status indicator + +## Customization + +### Colors and Theming + +Edit CSS variables in `src/app/globals.css`: + +- `--gradient-animated-1`: Main background gradient +- `--chat-background`: Chat container background +- `--message-user-bg`: User message color +- `--message-ai-bg`: AI message color + +### Background Animation + +Modify `src/components/animated-background.tsx` to change: + +- Number and size of floating orbs +- Animation speed and patterns +- Grid overlay opacity + +### Agent Configuration + +Update `src/lib/config.ts` to change: + +- Default agent settings +- Agent parsing logic +- Connection handling + +## Mobile Responsiveness + +The interface automatically adapts: + +- **Mobile (< 640px)**: Full-screen overlay +- **Tablet (640px - 1024px)**: Large floating window +- **Desktop (> 1024px)**: Fixed-size chat box + +## Troubleshooting + +### Common Issues + +1. **Agent not connecting**: Check that your agent is running on the specified URL +2. **CORS errors**: Ensure your agent allows requests from localhost:3000 +3. **AI Elements not working**: Make sure you've run `npx ai-elements@latest` + +### Development + +- Check browser console for connection errors +- Verify environment variables are loaded correctly +- Test agent endpoints directly with curl or Postman + +## Next Steps + +1. Install AI Elements and integrate the components +2. Configure your actual agent endpoints +3. Customize the design to match your brand +4. Add more tool functions as needed +5. Deploy to Cloudflare Pages or Vercel + diff --git a/packages/playground/src/app/api/chat/route.ts b/packages/playground/src/app/api/chat/route.ts deleted file mode 100644 index a151f14d..00000000 --- a/packages/playground/src/app/api/chat/route.ts +++ /dev/null @@ -1,345 +0,0 @@ -import { streamText, experimental_createMCPClient as createMCPClient } from 'ai'; -import { NextRequest } from 'next/server'; - -interface ChatRequest { - messages: Array<{ - role: 'system' | 'user' | 'assistant'; - content: string; - }>; - provider: 'openai' | 'anthropic'; - model: string; - temperature?: number; - maxTokens?: number; - maxSteps?: number; - systemPrompt?: string; - mcpProxyId?: string; // MCP proxy ID for Durable Object routing - mcpSessionId?: string; // Unique session ID for SSE transport - enableMCPTools?: boolean; // Whether to enable MCP tools for this request -} - -// Error types and user-friendly messages -interface ErrorResponse { - error: string; - userMessage: string; - errorType: string; - details?: string; - suggestions?: string[]; -} - -function createErrorResponse(error: unknown): ErrorResponse { - console.error('Chat API error:', error); - - // Type guard for error objects - const isErrorWithMessage = (err: unknown): err is { message: string; cause?: { message: string; statusCode?: number }; statusCode?: number } => { - return typeof err === 'object' && err !== null && ('message' in err || ('cause' in err && typeof (err as Record).cause === 'object' && (err as Record).cause !== null && 'message' in ((err as Record).cause as Record))); - }; - - // Handle AI API errors (Anthropic, OpenAI, etc.) - if (isErrorWithMessage(error)) { - const errorMessage = error.cause?.message || error.message; - const statusCode = error.statusCode || error.cause?.statusCode; - - // Anthropic-specific errors - if (errorMessage.includes('prompt is too long')) { - const match = errorMessage.match(/(\d+) tokens > (\d+) maximum/); - const currentTokens = match?.[1]; - const maxTokens = match?.[2]; - - return { - error: 'Token limit exceeded', - userMessage: `Your conversation is too long for this model. You're using ${currentTokens} tokens, but the maximum is ${maxTokens}.`, - errorType: 'TOKEN_LIMIT_EXCEEDED', - details: errorMessage, - suggestions: [ - 'Try starting a new conversation', - 'Use a model with a larger context window', - 'Summarize your conversation and start fresh' - ] - }; - } - - if (errorMessage.includes('rate_limit_error') || statusCode === 429) { - return { - error: 'Rate limit exceeded', - userMessage: 'You\'re sending requests too quickly. Please wait a moment before trying again.', - errorType: 'RATE_LIMIT_EXCEEDED', - details: errorMessage, - suggestions: [ - 'Wait 30-60 seconds before retrying', - 'Consider upgrading your API plan for higher limits' - ] - }; - } - - if (errorMessage.includes('insufficient_quota') || errorMessage.includes('billing')) { - return { - error: 'API quota exceeded', - userMessage: 'Your API quota has been exceeded. Please check your billing settings.', - errorType: 'QUOTA_EXCEEDED', - details: errorMessage, - suggestions: [ - 'Check your API billing dashboard', - 'Add credits to your account', - 'Upgrade your API plan' - ] - }; - } - - if (errorMessage.includes('invalid_api_key') || statusCode === 401) { - return { - error: 'Invalid API key', - userMessage: 'Your API key is invalid or has expired. Please check your API key settings.', - errorType: 'INVALID_API_KEY', - details: errorMessage, - suggestions: [ - 'Verify your API key is correct', - 'Check if your API key has expired', - 'Generate a new API key from your provider dashboard' - ] - }; - } - - if (errorMessage.includes('model_not_found') || errorMessage.includes('model not found')) { - return { - error: 'Model not found', - userMessage: 'The selected AI model is not available or doesn\'t exist.', - errorType: 'MODEL_NOT_FOUND', - details: errorMessage, - suggestions: [ - 'Try a different model', - 'Check if the model name is spelled correctly', - 'Verify your API access includes this model' - ] - }; - } - - if (errorMessage.includes('server_error') || (statusCode && statusCode >= 500)) { - return { - error: 'Server error', - userMessage: 'The AI service is experiencing issues. Please try again in a few moments.', - errorType: 'SERVER_ERROR', - details: errorMessage, - suggestions: [ - 'Wait a few minutes and try again', - 'Check the AI provider\'s status page', - 'Try a different model if available' - ] - }; - } - } - - // MCP-specific errors - if (isErrorWithMessage(error) && (error.message?.includes('MCP') || error.message?.includes('closed client'))) { - return { - error: 'Tool connection error', - userMessage: 'There was an issue connecting to the tools. Your message was processed, but tools may not be available.', - errorType: 'MCP_CONNECTION_ERROR', - details: error.message, - suggestions: [ - 'Try your request again', - 'Tools may be temporarily unavailable' - ] - }; - } - - // Network errors - if (isErrorWithMessage(error) && (error.message?.includes('fetch') || error.message?.includes('network'))) { - return { - error: 'Network error', - userMessage: 'Unable to connect to the AI service. Please check your internet connection.', - errorType: 'NETWORK_ERROR', - details: error.message, - suggestions: [ - 'Check your internet connection', - 'Try again in a few moments', - 'Contact support if the issue persists' - ] - }; - } - - // Generic fallback - return { - error: 'Unexpected error', - userMessage: 'An unexpected error occurred. Please try again.', - errorType: 'UNKNOWN_ERROR', - details: isErrorWithMessage(error) ? error.message : 'Unknown error', - suggestions: [ - 'Try your request again', - 'Refresh the page if the issue persists', - 'Contact support if the problem continues' - ] - }; -} - -// Dynamic provider factory with dynamic imports -async function createProvider(provider: 'openai' | 'anthropic', apiKey: string) { - switch (provider) { - case 'openai': { - const { createOpenAI } = await import('@ai-sdk/openai'); - return createOpenAI({ apiKey }); - } - case 'anthropic': { - const { createAnthropic } = await import('@ai-sdk/anthropic'); - return createAnthropic({ apiKey }); - } - default: - throw new Error(`Unsupported provider: ${provider}`); - } -} - -// Global MCP client instance -let mcpClient: Awaited> | null = null; - -// Function to get or create MCP client using AI SDK's built-in support -async function getMCPClient(proxyId?: string, sessionId?: string) { - // If client exists but is closed, reset it - if (mcpClient) { - try { - // Try to use the client to check if it's still alive - await mcpClient.tools(); - } catch { - console.log('MCP client is closed, creating new one...'); - mcpClient = null; - } - } - - if (!mcpClient) { - // Construct URL with both proxyId (for DO routing) and sessionId (for SSE transport) - const baseUrl = process.env.NEXT_PUBLIC_MCP_PROXY_URL || 'http://localhost:6050'; - const url = new URL('/sse', baseUrl); - - if (proxyId && sessionId) { - // proxyId is needed for Durable Object routing - url.searchParams.set('proxyId', proxyId); - // sessionId is needed for the SSE transport within the DO - url.searchParams.set('sessionId', sessionId); - } - - console.log('Creating MCP client with URL:', url.toString()); - - // Use the built-in SSE transport from AI SDK - mcpClient = await createMCPClient({ - transport: { - type: 'sse', - url: url.toString(), - // Optional headers for authentication - headers: {} - } - }); - } - - return mcpClient; -} - -export async function POST(request: NextRequest) { - let body: ChatRequest | null = null; - - try { - body = await request.json(); - - if (!body) { - return Response.json( - { error: 'Invalid request body' }, - { status: 400 } - ); - } - - const { messages, provider, model, mcpProxyId, mcpSessionId, enableMCPTools, ...otherParams } = body; - - // Get API key from Authorization header instead of environment variables - const authHeader = request.headers.get('authorization'); - const apiKey = authHeader?.replace('Bearer ', ''); - - console.log('🔍 Chat API Debug Info:', { - hasApiKey: !!apiKey, - apiKeyLength: apiKey?.length, - provider, - model, - enableMCPTools, - mcpProxyId: !!mcpProxyId, - mcpSessionId: !!mcpSessionId, - messagesCount: messages?.length - }); - - if (!apiKey) { - console.error('❌ No API key provided in Authorization header'); - return Response.json( - { error: 'API key required in Authorization header' }, - { status: 401 } - ); - } - - // Create the provider - console.log('🔧 Creating provider:', provider); - const providerInstance = await createProvider(provider, apiKey); - - // Only get MCP client and tools if explicitly enabled - let mcpTools = {}; - if (enableMCPTools && mcpProxyId && mcpSessionId) { - try { - console.log('🛠️ Attempting to get MCP tools...'); - const client = await getMCPClient(mcpProxyId, mcpSessionId); - mcpTools = await client.tools(); - console.log('✅ MCP tools retrieved successfully with proxyId:', mcpProxyId, 'sessionId:', mcpSessionId); - console.log('🔧 Available tools:', Object.keys(mcpTools).length); - } catch (mcpError) { - console.warn('⚠️ MCP tools unavailable, continuing without tools:', mcpError); - // Continue without tools rather than failing completely - } - } else { - console.log('🚫 MCP tools disabled for this request'); - } - - console.log('🚀 Starting streamText with:', { - model: model, - provider: provider, - hasSystemPrompt: !!otherParams.systemPrompt, - temperature: otherParams.temperature, - maxTokens: otherParams.maxTokens, - toolsCount: Object.keys(mcpTools).length - }); - - const result = streamText({ - model: providerInstance(model), - system: otherParams.systemPrompt, - messages, - temperature: otherParams.temperature, - maxTokens: otherParams.maxTokens, - maxSteps: otherParams.maxSteps || 10, - // Include MCP tools if available and model supports tools - tools: mcpTools, - // Don't close the client - keep it alive for reuse - }); - - return result.toDataStreamResponse(); - } catch (error) { - console.error('💥 Chat API Error Details:', { - error: error, - errorMessage: error instanceof Error ? error.message : 'Unknown error', - errorStack: error instanceof Error ? error.stack : undefined, - requestBody: body ? { - provider: body.provider, - model: body.model, - enableMCPTools: body.enableMCPTools, - messagesCount: body.messages?.length - } : 'No body parsed' - }); - - // If there's a critical error with the MCP client, reset it - if (error instanceof Error && error.message.includes('closed client')) { - console.error('MCP client error detected, resetting client...'); - mcpClient = null; - } - - // Create structured error response - const errorResponse = createErrorResponse(error); - - // Return structured error that the UI can handle - return Response.json(errorResponse, { - status: 500, - headers: { - 'Content-Type': 'application/json' - } - }); - } -} \ No newline at end of file diff --git a/packages/playground/src/app/api/chat/sse-edge.ts b/packages/playground/src/app/api/chat/sse-edge.ts deleted file mode 100644 index c05a04d7..00000000 --- a/packages/playground/src/app/api/chat/sse-edge.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; -import { - SSEClientTransport, - type SSEClientTransportOptions, -} from "@modelcontextprotocol/sdk/client/sse.js"; - -export class SSEEdgeClientTransport extends SSEClientTransport { - private authProvider: OAuthClientProvider | undefined; - /** - * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment - */ - constructor(url: URL, options: SSEClientTransportOptions) { - const fetchOverride: typeof fetch = async ( - fetchUrl: RequestInfo | URL, - fetchInit: RequestInit = {} - ) => { - // add auth headers - const headers = await this.authHeaders(); - const workerOptions = { - ...fetchInit, - headers: { - ...options.requestInit?.headers, - ...fetchInit?.headers, - ...headers, - }, - }; - - // Remove unsupported properties - delete workerOptions.mode; - - // Call the original fetch with fixed options - return ( - (options.eventSourceInit?.fetch?.( - fetchUrl as URL | string, - // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit - workerOptions - ) as Promise) || fetch(fetchUrl, workerOptions) - ); - }; - - super(url, { - ...options, - eventSourceInit: { - ...options.eventSourceInit, - fetch: fetchOverride, - }, - }); - this.authProvider = options.authProvider; - } - - async authHeaders() { - if (this.authProvider) { - const tokens = await this.authProvider.tokens(); - if (tokens) { - return { - Authorization: `Bearer ${tokens.access_token}`, - }; - } - } - } -} \ No newline at end of file diff --git a/packages/playground/src/app/api/models/anthropic/route.ts b/packages/playground/src/app/api/models/anthropic/route.ts deleted file mode 100644 index 856cb0db..00000000 --- a/packages/playground/src/app/api/models/anthropic/route.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server'; - -interface AnthropicModel { - id: string; - display_name: string; - created_at: string; - type: string; -} - -interface AnthropicModelsResponse { - data: AnthropicModel[]; - first_id?: string; - has_more: boolean; - last_id?: string; -} - -export async function GET(request: NextRequest) { - const apiKey = request.headers.get('x-api-key'); - - if (!apiKey) { - return NextResponse.json( - { error: 'API key required' }, - { status: 401 } - ); - } - - try { - const response = await fetch('https://api.anthropic.com/v1/models', { - headers: { - 'x-api-key': apiKey, - 'anthropic-version': '2023-06-01', - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - return NextResponse.json( - { error: `Anthropic API error: ${response.status} ${response.statusText}` }, - { status: response.status } - ); - } - - const data = await response.json() as AnthropicModelsResponse; - - const models = data.data.map((model) => ({ - id: model.id, - name: model.display_name || model.id - })); - - return NextResponse.json({ data: models }); - - } catch (error) { - console.error('Anthropic models fetch error:', error); - return NextResponse.json( - { error: 'Failed to fetch models' }, - { status: 500 } - ); - } -} \ No newline at end of file diff --git a/packages/playground/src/app/api/models/openai/route.ts b/packages/playground/src/app/api/models/openai/route.ts deleted file mode 100644 index 602149c7..00000000 --- a/packages/playground/src/app/api/models/openai/route.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server'; - -interface OpenAIModel { - id: string; - object: string; - created?: number; - owned_by?: string; -} - -interface OpenAIModelsResponse { - object: string; - data: OpenAIModel[]; -} - -export async function GET(request: NextRequest) { - const apiKey = request.headers.get('authorization')?.replace('Bearer ', ''); - - if (!apiKey) { - return NextResponse.json( - { error: 'API key required' }, - { status: 401 } - ); - } - - try { - const response = await fetch('https://api.openai.com/v1/models', { - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - return NextResponse.json( - { error: `OpenAI API error: ${response.status} ${response.statusText}` }, - { status: response.status } - ); - } - - const data = await response.json() as OpenAIModelsResponse; - - // Filter to only chat models (curated list of working models) - const chatModelIds = new Set([ - 'gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo', - 'o1-preview', 'o1-mini', 'gpt-4-turbo-preview', 'gpt-4-0125-preview', - 'chatgpt-4o-latest' - ]); - - const filteredModels = data.data - .filter((model) => chatModelIds.has(model.id)) - .map((model) => ({ - id: model.id, - name: model.id.replace(/-/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase()) - })); - - return NextResponse.json({ data: filteredModels }); - - } catch (error) { - console.error('OpenAI models fetch error:', error); - return NextResponse.json( - { error: 'Failed to fetch models' }, - { status: 500 } - ); - } -} \ No newline at end of file diff --git a/packages/playground/src/app/chat/[sessionId]/page.tsx b/packages/playground/src/app/chat/[sessionId]/page.tsx deleted file mode 100644 index 9528b2e4..00000000 --- a/packages/playground/src/app/chat/[sessionId]/page.tsx +++ /dev/null @@ -1,21 +0,0 @@ -"use client"; - -import React from "react"; -import { useParams } from "next/navigation"; -import { ChatContainer } from "@/components/chat"; - -export default function ChatPage() { - const params = useParams(); - const sessionId = params?.sessionId as string; - - return ( -

- -
- ); -} \ No newline at end of file diff --git a/packages/playground/src/app/chat/page.tsx b/packages/playground/src/app/chat/page.tsx deleted file mode 100644 index f6dadf52..00000000 --- a/packages/playground/src/app/chat/page.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { redirect } from 'next/navigation'; - -export default function ChatRedirect() { - redirect('/chat/new'); -} \ No newline at end of file diff --git a/packages/playground/src/app/demo/page.tsx b/packages/playground/src/app/demo/page.tsx deleted file mode 100644 index 28fcb0fe..00000000 --- a/packages/playground/src/app/demo/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -"use client"; - -import React from "react"; -import { ChatMessageDemo } from "@/components/chat"; - -export default function DemoPage() { - return ( -
- -
- ); -} \ No newline at end of file diff --git a/packages/playground/src/app/favicon.ico b/packages/playground/src/app/favicon.ico deleted file mode 100644 index 718d6fea..00000000 Binary files a/packages/playground/src/app/favicon.ico and /dev/null differ diff --git a/packages/playground/src/app/globals.css b/packages/playground/src/app/globals.css index 57964713..5de3720c 100644 --- a/packages/playground/src/app/globals.css +++ b/packages/playground/src/app/globals.css @@ -1,574 +1,189 @@ @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); - --font-space-grotesk: var(--font-space-grotesk); - --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); - - /* Chat specific variables */ - --color-chat-timestamp: var(--chat-timestamp); - - /* Chat animation variables */ - --color-chat-thinking-animation: var(--chat-thinking-animation); - --color-chat-thinking-duration: var(--chat-thinking-duration); - --color-chat-text-animation: var(--chat-text-animation); -} +@source "../node_modules/streamdown/dist/index.js"; :root { - --radius: 0.625rem; - --background: 227 18% 10%; /* #14161D - Updated playground background */ - --foreground: oklch(0.145 0 0); - --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); - --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); - - /* Chat theme variables - simplified */ - --chat-timestamp: rgba(255, 255, 255, 0.4); /* Timestamp text color */ - - /* Chat animation variables */ - --chat-thinking-animation: pulse 1.5s infinite ease-in-out; - --chat-thinking-duration: 1.5s; - --chat-text-animation: fadeIn 0.3s ease-in-out; -} - -.dark { - --background: 227 18% 10%; /* #14161D - Updated playground background */ - --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); - --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); - - /* Chat theme variables - simplified */ - --chat-timestamp: rgba(255, 255, 255, 0.4); /* Timestamp text color */ - - /* Chat animation variables */ - --chat-thinking-animation: pulse 1.5s infinite ease-in-out; - --chat-thinking-duration: 1.5s; - --chat-text-animation: fadeIn 0.3s ease-in-out; -} - -@layer base { - * { - @apply border-border outline-ring/50; - } - body { - @apply bg-background text-foreground; - } -} - -@layer utilities { - .line-clamp-2 { - display: -webkit-box; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; - overflow: hidden; - } -} - -/* Chat thinking animation */ -.chat-thinking-animation { - animation: pulse 1.5s infinite ease-in-out; -} - -@keyframes pulse { + /* Base Colors */ + --background: #ffffff; + --foreground: #171717; + + /* Chat Colors */ + --chat-background: #ffffff; + --chat-border: rgba(0, 0, 0, 0.1); + --chat-shadow: rgba(0, 0, 0, 0.1); + + /* Message Colors */ + --message-user-bg: #6366f1; + --message-user-text: #ffffff; + --message-ai-bg: #f8fafc; + --message-ai-text: #1e293b; + --message-border: rgba(0, 0, 0, 0.1); + + /* Button Colors */ + --button-primary: #6366f1; + --button-primary-hover: #4f46e5; + --button-secondary: #f8fafc; + --button-secondary-hover: #e2e8f0; + + /* Gradient Colors - Inspired by nullshot.ai */ + --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + --gradient-secondary: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); + --gradient-tertiary: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); + --gradient-quaternary: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); + + /* Animation Gradients */ + --gradient-animated-1: linear-gradient( + 45deg, + #667eea, + #764ba2, + #f093fb, + #f5576c + ); + --gradient-animated-2: linear-gradient( + 45deg, + #4facfe, + #00f2fe, + #43e97b, + #38f9d7 + ); + + /* Border Radius */ + --radius-sm: 0.5rem; + --radius-md: 0.75rem; + --radius-lg: 1rem; + --radius-xl: 1.5rem; + + /* Spacing */ + --spacing-xs: 0.5rem; + --spacing-sm: 0.75rem; + --spacing-md: 1rem; + --spacing-lg: 1.5rem; + --spacing-xl: 2rem; + + /* Shadows */ + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1); + --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.15); + --shadow-lg: 0 8px 25px rgba(0, 0, 0, 0.15); + --shadow-chat: 0 20px 40px rgba(0, 0, 0, 0.1); + + /* Typography */ + --font-size-xs: 0.75rem; + --font-size-sm: 0.875rem; + --font-size-base: 1rem; + --font-size-lg: 1.125rem; + --font-size-xl: 1.25rem; +} + +@media (prefers-color-scheme: dark) { + :root { + --background: #0a0a0a; + --foreground: #ededed; + + /* Dark mode chat colors */ + --chat-background: #0f172a; + --chat-border: rgba(255, 255, 255, 0.1); + --message-ai-bg: #1e293b; + --message-ai-text: #f1f5f9; + --button-secondary: #334155; + --button-secondary-hover: #475569; + } +} + +body { + background: var(--background); + color: var(--foreground); + font-family: var(--font-geist-sans), Arial, Helvetica, sans-serif; + overflow-x: hidden; +} + +/* Animated Background */ +.animated-gradient { + background: var(--gradient-animated-1); + background-size: 400% 400%; + animation: gradient-animation 15s ease infinite; +} + +.animated-gradient-alt { + background: var(--gradient-animated-2); + background-size: 400% 400%; + animation: gradient-animation 12s ease infinite reverse; +} + +@keyframes gradient-animation { 0% { - opacity: 1; - box-shadow: 0 0 0 0 rgba(114, 255, 192, 0.2); + background-position: 0% 50%; } 50% { - opacity: 0.7; - box-shadow: 0 0 0 6px rgba(114, 255, 192, 0); + background-position: 100% 50%; } 100% { - opacity: 1; - box-shadow: 0 0 0 0 rgba(114, 255, 192, 0); + background-position: 0% 50%; } } -.chat-text-typing { - display: inline-block; - overflow: hidden; - animation: typing 1s steps(40, end); - white-space: pre-wrap; +/* Chat Component Styles */ +.chat-container { + background: var(--chat-background); + border: 1px solid var(--chat-border); + box-shadow: var(--shadow-chat); } -@keyframes typing { - from { - max-width: 0; - opacity: 0; - } - to { - max-width: 100%; - opacity: 1; - } +.message-user { + background: var(--message-user-bg); + color: var(--message-user-text); } -.chat-text-streaming { - animation: fadeIn 0.3s ease-in-out; +.message-ai { + background: var(--message-ai-bg); + color: var(--message-ai-text); + border: 1px solid var(--message-border); } -@keyframes fadeIn { - from { - opacity: 0; - transform: translateY(5px); - } - to { - opacity: 1; - transform: translateY(0); - } +/* Scrollbar Styling */ +.chat-messages::-webkit-scrollbar { + width: 6px; } -/* Streaming text animation */ -@keyframes cursor-blink { - 0%, 100% { opacity: 1; } - 50% { opacity: 0; } +.chat-messages::-webkit-scrollbar-track { + background: transparent; } -.chat-text-streaming::after { - content: '|'; - display: inline-block; - margin-left: 2px; - animation: cursor-blink 1s infinite; - color: rgba(114, 255, 192, 0.8); +.chat-messages::-webkit-scrollbar-thumb { + background: rgba(156, 163, 175, 0.3); + border-radius: 3px; } -/* For a thinking animation */ -.chat-thinking-dots { - display: inline-flex; - gap: 2px; +.chat-messages::-webkit-scrollbar-thumb:hover { + background: rgba(156, 163, 175, 0.5); } -.chat-thinking-dots span { - width: 6px; - height: 6px; - border-radius: 50%; - background-color: rgba(255, 255, 255, 0.5); - animation: thinking-bounce 1.4s infinite ease-in-out both; +/* Modal and Dialog Overrides - Ensure No Transparency */ +[data-slot="dialog-overlay"] { + background-color: rgba(0, 0, 0, 0.9) !important; + backdrop-filter: blur(4px) !important; } -.chat-thinking-dots span:nth-child(1) { animation-delay: -0.32s; } -.chat-thinking-dots span:nth-child(2) { animation-delay: -0.16s; } - -@keyframes thinking-bounce { - 0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; } - 40% { transform: scale(1.2); opacity: 1; } +[data-slot="dialog-content"] { + background: white !important; + border: 1px solid rgb(209, 213, 219) !important; } -/* MCP Playground Styles */ -@layer components { - /* Playground page background */ - .mcp-playground-page { - background-color: hsl(var(--background)); - min-height: 100vh; - } - - /* Ensure all playground containers have proper background */ - .mcp-playground-container { - background: transparent; - } - - /* Header sections should have no background */ - .mcp-playground-header { - background: transparent !important; - } - - /* Fix ellipsis positioning to match Figma */ - .mcp-ellipsis-menu { - width: 20px; - height: 20px; - display: flex; - align-items: center; - justify-content: center; - } - - /* CHAT INPUT FIGMA DESIGN - CORRECTED TO EXACT FIGMA SPECS */ - .figma-chat-input-container { - width: 100% !important; /* take full sidebar width */ - max-width: 412px !important; /* matches Figma inner width */ - display: flex !important; - flex-direction: column !important; - gap: 12px !important; - } - - .figma-error-status { - display: flex !important; - align-items: center !important; - gap: 8px !important; - padding: 4px 12px !important; - background: rgba(253, 83, 83, 0.12) !important; - border: 1px solid #FD5353 !important; - border-radius: 30px !important; - color: #FD5353 !important; - font-family: 'Space Grotesk', sans-serif !important; - font-size: 12px !important; - font-weight: 400 !important; - line-height: 1.4 !important; - align-self: stretch !important; - } - - .figma-comment-box { - width: 100% !important; /* Responsive width instead of fixed */ - max-width: 412px !important; /* Exact Figma inner width as max */ - margin-left: auto !important; - margin-right: auto !important; - display: flex !important; - flex-direction: column !important; - gap: 16px !important; - padding: 12px 20px !important; - border-radius: 8px !important; - border: 1px solid rgba(255,255,255,0.2) !important; - /* Subtle glass fill gradient */ - background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.1) 100%) !important; - } - - .figma-comment-label { - color: rgba(255, 255, 255, 0.4) !important; - font-family: 'Space Grotesk', sans-serif !important; - font-size: 14px !important; - font-weight: 500 !important; - line-height: 1.4285714285714286 !important; /* Exact Figma line height */ - } - - .figma-model-selector { - display: flex !important; - align-items: center !important; - gap: 4px !important; - padding: 5px 6px !important; - height: 24px !important; - border-radius: 4px !important; - border: 1px solid rgba(255,255,255,0.2) !important; - background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.1) 100%) !important; - } - - /* Model selector button to match screenshot design */ - .figma-model-selector-gradient { - display: flex !important; - align-items: center !important; - gap: 4px !important; - padding: 5px 6px !important; - height: 24px !important; - border-radius: 4px !important; - cursor: pointer !important; - transition: opacity 0.2s ease !important; - /* Dark background to match screenshot */ - background: rgba(255, 255, 255, 0.1) !important; - border: 1px solid rgba(255, 255, 255, 0.2) !important; - position: relative !important; - } - - /* Remove the gradient border effect since we're using a simpler design */ - .figma-model-selector-gradient::before { - display: none !important; - } - - .figma-model-selector-gradient:hover:not(:disabled) { - opacity: 0.9 !important; - background: rgba(255, 255, 255, 0.15) !important; - } - - .figma-model-selector-gradient:disabled { - opacity: 0.5 !important; - cursor: not-allowed !important; - } - - .figma-model-selector-text { - color: #7E98FF !important; - font-family: 'Space Grotesk', sans-serif !important; - font-size: 12px !important; - font-weight: 500 !important; - line-height: 1.67 !important; - text-align: left !important; - white-space: nowrap !important; - } - - /* FIXED: Send button to match screenshot design */ - .figma-send-button { - display: flex !important; - align-items: center !important; - justify-content: center !important; - width: 32px !important; - height: 32px !important; - padding: 8px !important; - border-radius: 8px !important; - border: 1px solid rgba(255,255,255,0.2) !important; - /* Match screenshot gradient background */ - background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.1) 100%) !important; - cursor: pointer !important; - transition: opacity 0.2s ease !important; - } - - .figma-send-button:hover:not(:disabled) { - opacity: 0.8 !important; - } - - .figma-send-button:disabled { - opacity: 0.5 !important; - cursor: not-allowed !important; - } - - .figma-send-button svg { - width: 16px !important; - height: 16px !important; - stroke-width: 1.2 !important; - } - - .figma-message-input { - width: 100% !important; - background: transparent !important; - border: none !important; - outline: none !important; +@media (prefers-color-scheme: dark) { + [data-slot="dialog-content"] { + background: rgb(17, 24, 39) !important; + border: 1px solid rgb(75, 85, 99) !important; color: white !important; - font-family: 'Space Grotesk', sans-serif !important; - font-size: 14px !important; - line-height: 1.4 !important; /* Exact Figma line height */ - resize: none !important; - min-height: 20px !important; - max-height: 120px !important; - } - - .figma-message-input::placeholder { - color: rgba(255, 255, 255, 0.4) !important; - } - - /* Reset default background for descendants except we keep specific gradient boxes and dropdown */ - .figma-override input, - .figma-override textarea, - .figma-override button, - .figma-override div:not(.figma-comment-box):not(.figma-model-selector):not(.figma-model-selector-gradient):not(.figma-dropdown-menu):not(.figma-dropdown-header):not(.figma-dropdown-content) { - background-color: initial !important; - background-image: initial !important; - } - - /* Ensure the gradients take precedence */ - .figma-comment-box.figma-override, - .figma-model-selector.figma-override, - .figma-model-selector-gradient.figma-override { - background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.1) 100%) !important; - } - - /* Special override for the gradient model selector */ - .figma-model-selector-gradient.figma-override { - background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(0, 0, 0, 0.2) 100%) !important; - } - - /* FIXED: Dropdown menu styling to match Figma - HIGHER SPECIFICITY */ - .figma-dropdown-menu, - .figma-dropdown-menu.figma-dropdown-menu { - background: #222531 !important; /* Exact Figma color */ - background-image: none !important; - background-attachment: initial !important; - background-origin: initial !important; - background-clip: initial !important; - background-size: initial !important; - background-position: initial !important; - background-repeat: initial !important; - border: 1px solid rgba(255, 255, 255, 0.12) !important; - border-radius: 12px !important; - box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) !important; - overflow: hidden !important; - backdrop-filter: none !important; - } - - /* Force solid background for all children */ - .figma-dropdown-menu *, - .figma-dropdown-menu.figma-dropdown-menu * { - background-color: transparent !important; - background-image: none !important; - } - - .figma-dropdown-header, - .figma-dropdown-header.figma-dropdown-header { - padding: 8px 16px !important; - border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important; - display: flex !important; - justify-content: stretch !important; - align-items: stretch !important; - align-self: stretch !important; - gap: 10px !important; - background: transparent !important; - background-image: none !important; - } - - .figma-dropdown-header-text, - .figma-dropdown-header-text.figma-dropdown-header-text { - color: #FFFFFF !important; - font-family: 'Space Grotesk', sans-serif !important; - font-size: 14px !important; - font-weight: 700 !important; - line-height: 1.276 !important; /* 17.86px / 14px = 1.276 */ - text-align: left !important; - flex: 1 !important; - background: transparent !important; - background-image: none !important; - } - - .figma-dropdown-content, - .figma-dropdown-content.figma-dropdown-content { - display: flex !important; - flex-direction: column !important; - justify-content: center !important; - gap: 8px !important; - padding: 12px 4px !important; - background: transparent !important; - background-image: none !important; - } - - .figma-dropdown-item, - .figma-dropdown-item.figma-dropdown-item { - display: flex !important; - align-items: center !important; - align-self: stretch !important; - gap: 8px !important; - padding: 4px 12px !important; - background: transparent !important; - background-image: none !important; - border: none !important; - cursor: pointer !important; - transition: background-color 0.2s ease !important; - color: rgba(255, 255, 255, 0.8) !important; - font-family: 'Space Grotesk', sans-serif !important; - font-size: 14px !important; - font-weight: 400 !important; - line-height: 1.276 !important; /* 17.86px / 14px = 1.276 */ - text-align: left !important; - width: 100% !important; - } - - .figma-dropdown-item:hover, - .figma-dropdown-item.figma-dropdown-item:hover { - background: rgba(255, 255, 255, 0.1) !important; - background-image: none !important; - border-radius: 4px !important; - } - - /* Override any competing styles */ - .figma-override .figma-dropdown-menu, - .figma-override .figma-dropdown-menu * { - background-color: initial !important; - background-image: initial !important; - } - - /* Ensure the main dropdown container has the right background */ - .figma-override .figma-dropdown-menu.figma-dropdown-menu { - background: #222531 !important; - background-image: none !important; } +} - /* Force dropdown background with maximum specificity */ - .figma-chat-input-container .figma-dropdown-menu, - .figma-override .figma-chat-input-container .figma-dropdown-menu, - div.figma-dropdown-menu.figma-dropdown-menu.figma-dropdown-menu { - background: #222531 !important; - background-image: none !important; - background-attachment: initial !important; - background-origin: initial !important; - background-clip: initial !important; - background-size: initial !important; - background-position: initial !important; - background-repeat: initial !important; - backdrop-filter: none !important; - /* Force correct border color - override any Tailwind defaults */ - border: 1px solid rgba(255, 255, 255, 0.12) !important; - border-color: rgba(255, 255, 255, 0.12) !important; - border-width: 1px !important; - border-style: solid !important; - } +/* Ensure Select dropdowns are solid */ +[data-radix-select-content] { + background: white !important; + border: 1px solid rgb(209, 213, 219) !important; +} - /* Override Tailwind border classes specifically */ - .absolute.figma-dropdown-menu, - .absolute.figma-dropdown-menu.figma-dropdown-menu, - div.absolute.figma-dropdown-menu { - border: 1px solid rgba(255, 255, 255, 0.12) !important; - border-color: rgba(255, 255, 255, 0.12) !important; +@media (prefers-color-scheme: dark) { + [data-radix-select-content] { + background: rgb(31, 41, 55) !important; + border: 1px solid rgb(75, 85, 99) !important; } } diff --git a/packages/playground/src/app/layout.tsx b/packages/playground/src/app/layout.tsx index 8414c788..b1b7435e 100644 --- a/packages/playground/src/app/layout.tsx +++ b/packages/playground/src/app/layout.tsx @@ -1,6 +1,8 @@ +import React from "react"; import type { Metadata } from "next"; -import { Geist, Geist_Mono, Space_Grotesk } from "next/font/google"; +import { Geist, Geist_Mono } from "next/font/google"; import "./globals.css"; +import { PlaygroundProvider } from "@/components/playground-provider"; const geistSans = Geist({ variable: "--font-geist-sans", @@ -12,16 +14,9 @@ const geistMono = Geist_Mono({ subsets: ["latin"], }); -// Load Space Grotesk font -const spaceGrotesk = Space_Grotesk({ - subsets: ["latin"], - weight: ["400", "500", "700"], - variable: "--font-space-grotesk", -}); - export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", + title: "AI Agent Playground", + description: "Connect and chat with your AI agents in a beautiful interface", }; export default function RootLayout({ @@ -31,8 +26,10 @@ export default function RootLayout({ }>) { return ( - - {children} + + {children} ); diff --git a/packages/playground/src/app/mcp-servers/page.tsx b/packages/playground/src/app/mcp-servers/page.tsx deleted file mode 100644 index 560e1bf1..00000000 --- a/packages/playground/src/app/mcp-servers/page.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { McpServerManager } from '@/components/mcp-server-manager'; -import { McpWebSocketTest } from '@/components/mcp-websocket-test'; - -export default function McpServersPage() { - return ( -
-
-
- {/* Test Component */} - - - {/* Main Manager */} - -
-
-
- ); -} \ No newline at end of file diff --git a/packages/playground/src/app/page.tsx b/packages/playground/src/app/page.tsx index 382eabce..73c3d4e8 100644 --- a/packages/playground/src/app/page.tsx +++ b/packages/playground/src/app/page.tsx @@ -1,220 +1,29 @@ -"use client"; - -import React, { useState, useEffect, useCallback } from "react"; -import { ChatContainer } from "@/components/chat"; -import { MCPServerDirectory } from "@/components/mcp-server-directory"; -import { DockerInstallModal } from "@/components/docker-install-modal"; -import { PlaygroundHeader } from "@/components/playground-header"; -import { MCPServer } from "@/types/mcp-server"; -import { LocalToolboxStatus } from "@/components/ui/local-toolbox-status"; -import { useMcpServerManager } from "@/hooks/use-mcp-server-manager"; - -interface ModelConfig { - provider: 'openai' | 'anthropic'; - apiKey: string; - model: string; - temperature?: number; - maxTokens?: number; - maxSteps?: number; - systemPrompt?: string; -} - -// Playground page component -export default function PlaygroundPage() { - const [isToolboxInstalled, setIsToolboxInstalled] = useState(false); - const [toolboxStatus, setToolboxStatus] = useState('disconnected'); - const [enabledServerCount, setEnabledServerCount] = useState(0); - const [isDockerModalOpen, setIsDockerModalOpen] = useState(false); - const [dockerToolboxOnline, setDockerToolboxOnline] = useState(false); - - // Use the existing WebSocket connection for MCP Proxy status - const { connected: mcpProxyConnected, connect: connectMcp } = useMcpServerManager(); - - // Load installation state from localStorage on mount - useEffect(() => { - if (typeof window !== 'undefined') { - const installed = localStorage.getItem('local_toolbox_installed') === 'true'; - setIsToolboxInstalled(installed); - } - }, []); - - // Persist installation state to localStorage - const setToolboxInstalled = useCallback((installed: boolean) => { - setIsToolboxInstalled(installed); - if (typeof window !== 'undefined') { - localStorage.setItem('local_toolbox_installed', installed.toString()); - } - }, []); - - // Check Docker Toolbox health (separate from MCP Proxy) - const checkDockerToolboxHealth = useCallback(async () => { - try { - const response = await fetch('http://localhost:11990/health', { - method: 'GET', - signal: AbortSignal.timeout(3000) - }); - - if (response.ok) { - setDockerToolboxOnline(true); - // If Docker is running and we didn't know it was installed, mark it as installed - if (!isToolboxInstalled) { - setToolboxInstalled(true); - } - return true; - } else { - setDockerToolboxOnline(false); - return false; - } - } catch { - setDockerToolboxOnline(false); - return false; - } - }, [isToolboxInstalled, setToolboxInstalled]); - - // Determine status based on both Docker Toolbox and MCP Proxy status - const determineToolboxStatus = useCallback(( - isInstalled: boolean, - dockerOnline: boolean, - mcpConnected: boolean - ): LocalToolboxStatus => { - if (!isInstalled) { - return 'disconnected'; - } - - if (!dockerOnline) { - return 'offline'; // Docker container not running - } - - if (!mcpConnected) { - // Docker is running but MCP Proxy connection failed - return 'cannot_connect'; - } - - return 'online'; // Both Docker and MCP Proxy are working - }, []); - - // Update status based on both services - useEffect(() => { - const newStatus = determineToolboxStatus( - isToolboxInstalled, - dockerToolboxOnline, - mcpProxyConnected - ); - setToolboxStatus(newStatus); - - console.log('Status update:', { - isInstalled: isToolboxInstalled, - dockerOnline: dockerToolboxOnline, - mcpConnected: mcpProxyConnected, - finalStatus: newStatus - }); - }, [isToolboxInstalled, dockerToolboxOnline, mcpProxyConnected, determineToolboxStatus]); - - // Auto-connect to MCP Proxy WebSocket when component mounts - useEffect(() => { - connectMcp(); - }, [connectMcp]); - - // Periodic Docker Toolbox health check - useEffect(() => { - // Initial check - checkDockerToolboxHealth(); - - // Check every 10 seconds - const interval = setInterval(checkDockerToolboxHealth, 10000); - return () => clearInterval(interval); - }, [checkDockerToolboxHealth]); - - // Also check when page becomes visible again - useEffect(() => { - const handleVisibilityChange = () => { - if (!document.hidden) { - checkDockerToolboxHealth(); - } - }; - - document.addEventListener('visibilitychange', handleVisibilityChange); - return () => document.removeEventListener('visibilitychange', handleVisibilityChange); - }, [checkDockerToolboxHealth]); - - const handleServerToggle = useCallback((server: MCPServer, enabled: boolean) => { - console.log(`Server ${server.id} ${enabled ? 'enabled' : 'disabled'}`); - }, []); - - const handleServerCountChange = useCallback((count: number) => { - setEnabledServerCount(count); - }, []); - - const handleInstallClick = useCallback(() => { - setIsDockerModalOpen(true); - }, []); - - const handleDockerInstallComplete = useCallback(() => { - setToolboxInstalled(true); - setToolboxStatus('online'); - setIsDockerModalOpen(false); - // Immediately check both services after installation - setTimeout(() => { - checkDockerToolboxHealth(); - connectMcp(); - }, 1000); - }, [connectMcp, setToolboxInstalled, checkDockerToolboxHealth]); - - const handleModelChange = useCallback((config: ModelConfig | null) => { - console.log('Model config changed:', config); - }, []); - - // Display title (server-safe) - const chatTitle = typeof window !== 'undefined' && window.location.pathname.includes('/chat/') - ? `Chat Session` - : "Playground Chat"; - - return ( - <> -
- {/* Left Side - MCP Server Directory (flex-1 to take most space) */} -
- {/* Playground Header */} -
- -
- - {/* MCP Server Directory */} -
- -
-
- - {/* Right Side - Fixed Width Chat */} -
- -
-
- - {/* Docker Install Modal */} - setIsDockerModalOpen(false)} - onInstallationComplete={handleDockerInstallComplete} - /> - - ); +import React from "react"; +import { AnimatedBackground } from "@/components/animated-background"; +import { FloatingChatButton } from "@/components/floating-chat"; + +export default function Home() { + return ( + <> + {/* Animated Background */} + + + {/* Main Content */} +
+
+

+ AI Agent Playground +

+

+ Connect and chat with your AI agents in a beautiful, responsive + interface. +

+ +
+ +
+
+
+ + ); } diff --git a/packages/playground/src/components/add-agent-modal.tsx b/packages/playground/src/components/add-agent-modal.tsx new file mode 100644 index 00000000..a7ee8b33 --- /dev/null +++ b/packages/playground/src/components/add-agent-modal.tsx @@ -0,0 +1,265 @@ +"use client"; + +import React from "react"; +import { useState } from "react"; +import { Plus, Loader2, Check, AlertCircle } from "lucide-react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogOverlay, + DialogPortal, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Badge } from "@/components/ui/badge"; +import { + validateAgentUrl, + testAgentConnection, + type CustomAgent, +} from "@/lib/agent-storage"; +import { useAgentManagement } from "@/lib/agent-context"; +import { type Agent } from "@/lib/config"; + +export interface AddAgentModalProps { + open: boolean; + onOpenChange: (open: boolean) => void; + onAgentAdded: (agent: CustomAgent) => void; +} + +export function AddAgentModal({ + open, + onOpenChange, + onAgentAdded, +}: AddAgentModalProps) { + const [name, setName] = useState(""); + const [url, setUrl] = useState(""); + const [isTestingConnection, setIsTestingConnection] = useState(false); + const [connectionStatus, setConnectionStatus] = useState<{ + tested: boolean; + online: boolean; + error?: string; + }>({ tested: false, online: false }); + const [error, setError] = useState(null); + + // Use the agent management context + const { addAgent, isLoading } = useAgentManagement(); + + const resetForm = () => { + setName(""); + setUrl(""); + setError(null); + setConnectionStatus({ tested: false, online: false }); + setIsTestingConnection(false); + }; + + const handleClose = () => { + resetForm(); + onOpenChange(false); + }; + + const testConnection = async () => { + const validation = validateAgentUrl(url); + if (!validation.isValid) { + setError(validation.error || "Invalid URL"); + return; + } + + setIsTestingConnection(true); + setError(null); + + try { + const result = await testAgentConnection(url); + setConnectionStatus({ + tested: true, + online: result.isOnline, + error: result.error, + }); + + if (!result.isOnline) { + setError(`Connection failed: ${result.error}`); + } + } catch { + setError("Failed to test connection"); + setConnectionStatus({ tested: true, online: false }); + } finally { + setIsTestingConnection(false); + } + }; + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + if (!name.trim() || !url.trim()) { + setError("Both name and URL are required"); + return; + } + + // Validate URL + const validation = validateAgentUrl(url); + if (!validation.isValid) { + setError(validation.error || "Invalid URL"); + return; + } + + setError(null); + + try { + const result = await addAgent(name.trim(), url.trim()); + if (result.success) { + // Find the newly added agent (it will be in the context) + // For now, we'll just notify that an agent was added + // The actual agent object will be available through the context + onAgentAdded({} as Agent); + handleClose(); + } else { + setError(result.error || "Failed to add agent"); + } + } catch (err) { + setError(err instanceof Error ? err.message : "Failed to save agent"); + } + }; + + return ( + + + {/* Custom solid overlay */} + + + + + + Add New Agent + + + Add a custom agent by providing a name and URL. The URL should + point to a running agent instance. + + + +
+
+ + setName(e.target.value)} + className="w-full bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white" + /> +
+ +
+ +
+ { + setUrl(e.target.value); + setConnectionStatus({ tested: false, online: false }); + setError(null); + }} + className="flex-1 bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white" + /> + +
+ + {/* Connection Status */} + {connectionStatus.tested && ( +
+ {connectionStatus.online ? ( + <> + + + Connection successful + + + ) : ( + <> + + + Connection failed + + + )} +
+ )} +
+ + {error && ( +
+
+ + {error} +
+
+ )} + + + + + +
+
+
+
+ ); +} diff --git a/packages/playground/src/components/agent-selector.tsx b/packages/playground/src/components/agent-selector.tsx new file mode 100644 index 00000000..b9941197 --- /dev/null +++ b/packages/playground/src/components/agent-selector.tsx @@ -0,0 +1,167 @@ +"use client"; + +import React from "react"; +import { useState, useEffect } from "react"; +import { Wifi, WifiOff, Plus, Circle } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Badge } from "@/components/ui/badge"; +import { type Agent } from "@/lib/config"; +import { AddAgentModal } from "./add-agent-modal"; +import { useAgentSelection, useAgentManagement } from "@/lib/agent-context"; +import { getAgentStatusMessage } from "@/lib/agent-health"; + +export interface AgentSelectorProps { + selectedAgent: Agent; + onAgentChange: (agent: Agent) => void; + className?: string; +} + +export function AgentSelector({ + selectedAgent, + onAgentChange, + className, +}: AgentSelectorProps) { + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + + // Use the agent context hooks + const { + agents, + selectedAgent: contextSelectedAgent, + selectAgent, + } = useAgentSelection(); + const { refreshAgents } = useAgentManagement(); + + // Use the selected agent from props or context (props takes precedence) + const currentAgent = selectedAgent || contextSelectedAgent; + + // Refresh agent health on mount + useEffect(() => { + refreshAgents(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); // Empty dependency array to run only on mount + + // Find health status for selected agent + const selectedAgentHealth = currentAgent?.health; + const isConnected = selectedAgentHealth?.isOnline ?? false; + + const handleValueChange = (value: string) => { + if (value === "__add_agent__") { + setIsAddModalOpen(true); + return; + } + + const agent = agents.find((agent) => agent.id === value); + if (agent) { + // Update both the context and call the prop callback + selectAgent(agent.id); + onAgentChange(agent); + } + }; + + const handleAgentAdded = (newAgent: Agent) => { + // The context will automatically handle the new agent + // Just close the modal and the new agent will appear in the list + setIsAddModalOpen(false); + // Automatically select the new agent if it's online + if (newAgent.health?.isOnline) { + selectAgent(newAgent.id); + onAgentChange(newAgent); + } + }; + + return ( +
+
+
+ {isConnected ? ( + + ) : ( + + )} + + {isConnected ? "Connected" : "Disconnected"} + +
+
+ + + + +
+ ); +} diff --git a/packages/playground/src/components/ai-elements/actions.tsx b/packages/playground/src/components/ai-elements/actions.tsx new file mode 100644 index 00000000..1acfecb3 --- /dev/null +++ b/packages/playground/src/components/ai-elements/actions.tsx @@ -0,0 +1,66 @@ +"use client"; + +import { Button } from "@/components/ui/button"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { cn } from "@/lib/utils"; +import React from "react"; +import type { ComponentProps } from "react"; + +export type ActionsProps = ComponentProps<"div">; + +export const Actions = ({ className, children, ...props }: ActionsProps) => ( +
+ {children} +
+); + +export type ActionProps = ComponentProps & { + tooltip?: string; + label?: string; +}; + +export const Action = ({ + tooltip, + children, + label, + className, + variant = "ghost", + size = "sm", + ...props +}: ActionProps) => { + const button = ( + + ); + + if (tooltip) { + return ( + + + {button} + +

{tooltip}

+
+
+
+ ); + } + + return button; +}; diff --git a/packages/playground/src/components/ai-elements/artifact.tsx b/packages/playground/src/components/ai-elements/artifact.tsx new file mode 100644 index 00000000..0d61dc3b --- /dev/null +++ b/packages/playground/src/components/ai-elements/artifact.tsx @@ -0,0 +1,148 @@ +"use client"; + +import React from "react"; +import { Button } from "@/components/ui/button"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { cn } from "@/lib/utils"; +import { type LucideIcon, XIcon } from "lucide-react"; +import type { ComponentProps, HTMLAttributes } from "react"; + +export type ArtifactProps = HTMLAttributes; + +export const Artifact = ({ className, ...props }: ArtifactProps) => ( +
+); + +export type ArtifactHeaderProps = HTMLAttributes; + +export const ArtifactHeader = ({ + className, + ...props +}: ArtifactHeaderProps) => ( +
+); + +export type ArtifactCloseProps = ComponentProps; + +export const ArtifactClose = ({ + className, + children, + size = "sm", + variant = "ghost", + ...props +}: ArtifactCloseProps) => ( + +); + +export type ArtifactTitleProps = HTMLAttributes; + +export const ArtifactTitle = ({ className, ...props }: ArtifactTitleProps) => ( +

+); + +export type ArtifactDescriptionProps = HTMLAttributes; + +export const ArtifactDescription = ({ + className, + ...props +}: ArtifactDescriptionProps) => ( +

+); + +export type ArtifactActionsProps = HTMLAttributes; + +export const ArtifactActions = ({ + className, + ...props +}: ArtifactActionsProps) => ( +

+); + +export type ArtifactActionProps = ComponentProps & { + tooltip?: string; + label?: string; + icon?: LucideIcon; +}; + +export const ArtifactAction = ({ + tooltip, + label, + icon: Icon, + children, + className, + size = "sm", + variant = "ghost", + ...props +}: ArtifactActionProps) => { + const button = ( + + ); + + if (tooltip) { + return ( + + + {button} + +

{tooltip}

+
+
+
+ ); + } + + return button; +}; + +export type ArtifactContentProps = HTMLAttributes; + +export const ArtifactContent = ({ + className, + ...props +}: ArtifactContentProps) => ( +
+); diff --git a/packages/playground/src/components/ai-elements/branch.tsx b/packages/playground/src/components/ai-elements/branch.tsx new file mode 100644 index 00000000..6b4551c4 --- /dev/null +++ b/packages/playground/src/components/ai-elements/branch.tsx @@ -0,0 +1,213 @@ +"use client"; + +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import type { UIMessage } from "ai"; +import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"; +import type { ComponentProps, HTMLAttributes, ReactElement } from "react"; +import { createContext, useContext, useEffect, useState } from "react"; +import React from "react"; + +type BranchContextType = { + currentBranch: number; + totalBranches: number; + goToPrevious: () => void; + goToNext: () => void; + branches: ReactElement[]; + setBranches: (branches: ReactElement[]) => void; +}; + +const BranchContext = createContext(null); + +const useBranch = () => { + const context = useContext(BranchContext); + + if (!context) { + throw new Error("Branch components must be used within Branch"); + } + + return context; +}; + +export type BranchProps = HTMLAttributes & { + defaultBranch?: number; + onBranchChange?: (branchIndex: number) => void; +}; + +export const Branch = ({ + defaultBranch = 0, + onBranchChange, + className, + ...props +}: BranchProps) => { + const [currentBranch, setCurrentBranch] = useState(defaultBranch); + const [branches, setBranches] = useState([]); + + const handleBranchChange = (newBranch: number) => { + setCurrentBranch(newBranch); + onBranchChange?.(newBranch); + }; + + const goToPrevious = () => { + const newBranch = + currentBranch > 0 ? currentBranch - 1 : branches.length - 1; + handleBranchChange(newBranch); + }; + + const goToNext = () => { + const newBranch = + currentBranch < branches.length - 1 ? currentBranch + 1 : 0; + handleBranchChange(newBranch); + }; + + const contextValue: BranchContextType = { + currentBranch, + totalBranches: branches.length, + goToPrevious, + goToNext, + branches, + setBranches, + }; + + return ( + +
div]:pb-0", className)} + {...props} + /> + + ); +}; + +export type BranchMessagesProps = HTMLAttributes; + +export const BranchMessages = ({ children, ...props }: BranchMessagesProps) => { + const { currentBranch, setBranches, branches } = useBranch(); + const childrenArray = Array.isArray(children) ? children : [children]; + + // Use useEffect to update branches when they change + useEffect(() => { + if (branches.length !== childrenArray.length) { + setBranches(childrenArray); + } + }, [childrenArray, branches, setBranches]); + + return childrenArray.map((branch, index) => ( +
div]:pb-0", + index === currentBranch ? "block" : "hidden", + )} + key={branch.key} + {...props} + > + {branch} +
+ )); +}; + +export type BranchSelectorProps = HTMLAttributes & { + from: UIMessage["role"]; +}; + +export const BranchSelector = ({ + className, + from, + ...props +}: BranchSelectorProps) => { + const { totalBranches } = useBranch(); + + // Don't render if there's only one branch + if (totalBranches <= 1) { + return null; + } + + return ( +
+ ); +}; + +export type BranchPreviousProps = ComponentProps; + +export const BranchPrevious = ({ + className, + children, + ...props +}: BranchPreviousProps) => { + const { goToPrevious, totalBranches } = useBranch(); + + return ( + + ); +}; + +export type BranchNextProps = ComponentProps; + +export const BranchNext = ({ + className, + children, + ...props +}: BranchNextProps) => { + const { goToNext, totalBranches } = useBranch(); + + return ( + + ); +}; + +export type BranchPageProps = HTMLAttributes; + +export const BranchPage = ({ className, ...props }: BranchPageProps) => { + const { currentBranch, totalBranches } = useBranch(); + + return ( + + {currentBranch + 1} of {totalBranches} + + ); +}; diff --git a/packages/playground/src/components/ai-elements/canvas.tsx b/packages/playground/src/components/ai-elements/canvas.tsx new file mode 100644 index 00000000..3e82af42 --- /dev/null +++ b/packages/playground/src/components/ai-elements/canvas.tsx @@ -0,0 +1,23 @@ +import { Background, ReactFlow, type ReactFlowProps } from "@xyflow/react"; +import type { ReactNode } from "react"; +import "@xyflow/react/dist/style.css"; +import React from "react"; + +type CanvasProps = ReactFlowProps & { + children?: ReactNode; +}; + +export const Canvas = ({ children, ...props }: CanvasProps) => ( + + + {children} + +); diff --git a/packages/playground/src/components/ai-elements/chain-of-thought.tsx b/packages/playground/src/components/ai-elements/chain-of-thought.tsx new file mode 100644 index 00000000..73631a10 --- /dev/null +++ b/packages/playground/src/components/ai-elements/chain-of-thought.tsx @@ -0,0 +1,229 @@ +"use client"; +import React from "react"; + +import { useControllableState } from "@radix-ui/react-use-controllable-state"; +import { Badge } from "@/components/ui/badge"; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@/components/ui/collapsible"; +import { cn } from "@/lib/utils"; +import { + BrainIcon, + ChevronDownIcon, + DotIcon, + type LucideIcon, +} from "lucide-react"; +import type { ComponentProps, ReactNode } from "react"; +import { createContext, memo, useContext, useMemo } from "react"; + +type ChainOfThoughtContextValue = { + isOpen: boolean; + setIsOpen: (open: boolean) => void; +}; + +const ChainOfThoughtContext = createContext( + null, +); + +const useChainOfThought = () => { + const context = useContext(ChainOfThoughtContext); + if (!context) { + throw new Error( + "ChainOfThought components must be used within ChainOfThought", + ); + } + return context; +}; + +export type ChainOfThoughtProps = ComponentProps<"div"> & { + open?: boolean; + defaultOpen?: boolean; + onOpenChange?: (open: boolean) => void; +}; + +export const ChainOfThought = memo( + ({ + className, + open, + defaultOpen = false, + onOpenChange, + children, + ...props + }: ChainOfThoughtProps) => { + const [isOpen, setIsOpen] = useControllableState({ + prop: open, + defaultProp: defaultOpen, + onChange: onOpenChange, + }); + + const chainOfThoughtContext = useMemo( + () => ({ isOpen, setIsOpen }), + [isOpen, setIsOpen], + ); + + return ( + +
+ {children} +
+
+ ); + }, +); + +export type ChainOfThoughtHeaderProps = ComponentProps< + typeof CollapsibleTrigger +>; + +export const ChainOfThoughtHeader = memo( + ({ className, children, ...props }: ChainOfThoughtHeaderProps) => { + const { isOpen, setIsOpen } = useChainOfThought(); + + return ( + + + + + {children ?? "Chain of Thought"} + + + + + ); + }, +); + +export type ChainOfThoughtStepProps = ComponentProps<"div"> & { + icon?: LucideIcon; + label: ReactNode; + description?: ReactNode; + status?: "complete" | "active" | "pending"; +}; + +export const ChainOfThoughtStep = memo( + ({ + className, + icon: Icon = DotIcon, + label, + description, + status = "complete", + children, + ...props + }: ChainOfThoughtStepProps) => { + const statusStyles = { + complete: "text-muted-foreground", + active: "text-foreground", + pending: "text-muted-foreground/50", + }; + + return ( +
+
+ +
+
+
+
{label}
+ {description && ( +
{description}
+ )} + {children} +
+
+ ); + }, +); + +export type ChainOfThoughtSearchResultsProps = ComponentProps<"div">; + +export const ChainOfThoughtSearchResults = memo( + ({ className, ...props }: ChainOfThoughtSearchResultsProps) => ( +
+ ), +); + +export type ChainOfThoughtSearchResultProps = ComponentProps; + +export const ChainOfThoughtSearchResult = memo( + ({ className, children, ...props }: ChainOfThoughtSearchResultProps) => ( + + {children} + + ), +); + +export type ChainOfThoughtContentProps = ComponentProps< + typeof CollapsibleContent +>; + +export const ChainOfThoughtContent = memo( + ({ className, children, ...props }: ChainOfThoughtContentProps) => { + const { isOpen } = useChainOfThought(); + + return ( + + + {children} + + + ); + }, +); + +export type ChainOfThoughtImageProps = ComponentProps<"div"> & { + caption?: string; +}; + +export const ChainOfThoughtImage = memo( + ({ className, children, caption, ...props }: ChainOfThoughtImageProps) => ( +
+
+ {children} +
+ {caption &&

{caption}

} +
+ ), +); + +ChainOfThought.displayName = "ChainOfThought"; +ChainOfThoughtHeader.displayName = "ChainOfThoughtHeader"; +ChainOfThoughtStep.displayName = "ChainOfThoughtStep"; +ChainOfThoughtSearchResults.displayName = "ChainOfThoughtSearchResults"; +ChainOfThoughtSearchResult.displayName = "ChainOfThoughtSearchResult"; +ChainOfThoughtContent.displayName = "ChainOfThoughtContent"; +ChainOfThoughtImage.displayName = "ChainOfThoughtImage"; diff --git a/packages/playground/src/components/ai-elements/checkpoint.tsx b/packages/playground/src/components/ai-elements/checkpoint.tsx new file mode 100644 index 00000000..ddbf3b33 --- /dev/null +++ b/packages/playground/src/components/ai-elements/checkpoint.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { Button } from "@/components/ui/button"; +import React from "react"; +import { Separator } from "@/components/ui/separator"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { cn } from "@/lib/utils"; +import { BookmarkIcon, type LucideProps } from "lucide-react"; +import type { ComponentProps, HTMLAttributes } from "react"; + +export type CheckpointProps = HTMLAttributes; + +export const Checkpoint = ({ + className, + children, + ...props +}: CheckpointProps) => ( +
+ {children} + +
+); + +export type CheckpointIconProps = LucideProps; + +export const CheckpointIcon: React.FC = ({ + className, + children, + ...props +}: CheckpointIconProps) => + children ?? ( + + ); + +export type CheckpointTriggerProps = ComponentProps & { + tooltip?: string; +}; + +export const CheckpointTrigger = ({ + children, + className, + variant = "ghost", + size = "sm", + tooltip, + ...props +}: CheckpointTriggerProps) => + tooltip ? ( + + + + + + {tooltip} + + + ) : ( + + ); diff --git a/packages/playground/src/components/ai-elements/code-block.tsx b/packages/playground/src/components/ai-elements/code-block.tsx new file mode 100644 index 00000000..4666cfb5 --- /dev/null +++ b/packages/playground/src/components/ai-elements/code-block.tsx @@ -0,0 +1,179 @@ +"use client"; +import React from "react"; + +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { CheckIcon, CopyIcon } from "lucide-react"; +import { + type ComponentProps, + createContext, + type HTMLAttributes, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { type BundledLanguage, codeToHtml, type ShikiTransformer } from "shiki"; + +type CodeBlockProps = HTMLAttributes & { + code: string; + language: BundledLanguage; + showLineNumbers?: boolean; +}; + +type CodeBlockContextType = { + code: string; +}; + +const CodeBlockContext = createContext({ + code: "", +}); + +const lineNumberTransformer: ShikiTransformer = { + name: "line-numbers", + line(node, line) { + node.children.unshift({ + type: "element", + tagName: "span", + properties: { + className: [ + "inline-block", + "min-w-10", + "mr-4", + "text-right", + "select-none", + "text-muted-foreground", + ], + }, + children: [{ type: "text", value: String(line) }], + }); + }, +}; + +export async function highlightCode( + code: string, + language: BundledLanguage, + showLineNumbers = false, +) { + const transformers: ShikiTransformer[] = showLineNumbers + ? [lineNumberTransformer] + : []; + + return await Promise.all([ + codeToHtml(code, { + lang: language, + theme: "one-light", + transformers, + }), + codeToHtml(code, { + lang: language, + theme: "one-dark-pro", + transformers, + }), + ]); +} + +export const CodeBlock = ({ + code, + language, + showLineNumbers = false, + className, + children, + ...props +}: CodeBlockProps) => { + const [html, setHtml] = useState(""); + const [darkHtml, setDarkHtml] = useState(""); + const mounted = useRef(false); + + useEffect(() => { + highlightCode(code, language, showLineNumbers).then(([light, dark]) => { + if (!mounted.current) { + setHtml(light); + setDarkHtml(dark); + mounted.current = true; + } + }); + + return () => { + mounted.current = false; + }; + }, [code, language, showLineNumbers]); + + return ( + +
+
+
+
+ {children && ( +
+ {children} +
+ )} +
+
+ + ); +}; + +export type CodeBlockCopyButtonProps = ComponentProps & { + onCopy?: () => void; + onError?: (error: Error) => void; + timeout?: number; +}; + +export const CodeBlockCopyButton = ({ + onCopy, + onError, + timeout = 2000, + children, + className, + ...props +}: CodeBlockCopyButtonProps) => { + const [isCopied, setIsCopied] = useState(false); + const { code } = useContext(CodeBlockContext); + + const copyToClipboard = async () => { + if (typeof window === "undefined" || !navigator?.clipboard?.writeText) { + onError?.(new Error("Clipboard API not available")); + return; + } + + try { + await navigator.clipboard.writeText(code); + setIsCopied(true); + onCopy?.(); + setTimeout(() => setIsCopied(false), timeout); + } catch (error) { + onError?.(error as Error); + } + }; + + const Icon = isCopied ? CheckIcon : CopyIcon; + + return ( + + ); +}; diff --git a/packages/playground/src/components/ai-elements/confirmation.tsx b/packages/playground/src/components/ai-elements/confirmation.tsx new file mode 100644 index 00000000..2527ec4b --- /dev/null +++ b/packages/playground/src/components/ai-elements/confirmation.tsx @@ -0,0 +1,183 @@ +"use client"; + +import React from "react"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import type { ToolUIPart } from "ai"; +import { + type ComponentProps, + createContext, + type ReactNode, + useContext, +} from "react"; + +type ToolUIPartApproval = + | { + id: string; + approved?: never; + reason?: never; + } + | { + id: string; + approved: boolean; + reason?: string; + } + | { + id: string; + approved: true; + reason?: string; + } + | { + id: string; + approved: true; + reason?: string; + } + | { + id: string; + approved: false; + reason?: string; + } + | undefined; + +type ConfirmationContextValue = { + approval: ToolUIPartApproval; + state: ToolUIPart["state"]; +}; + +const ConfirmationContext = createContext( + null, +); + +const useConfirmation = () => { + const context = useContext(ConfirmationContext); + + if (!context) { + throw new Error("Confirmation components must be used within Confirmation"); + } + + return context; +}; + +export type ConfirmationProps = ComponentProps & { + approval?: ToolUIPartApproval; + state: ToolUIPart["state"]; +}; + +export const Confirmation = ({ + className, + approval, + state, + ...props +}: ConfirmationProps) => { + if (!approval || state === "input-streaming" || state === "input-available") { + return null; + } + + return ( + + + + ); +}; + +export type ConfirmationTitleProps = ComponentProps; + +export const ConfirmationTitle = ({ + className, + ...props +}: ConfirmationTitleProps) => ( + +); + +export type ConfirmationRequestProps = { + children?: ReactNode; +}; + +export const ConfirmationRequest = ({ children }: ConfirmationRequestProps) => { + const { state } = useConfirmation(); + + // Only show when approval is requested + //@ts-ignore + if (state !== "approval-requested") { + return null; + } + + return children; +}; + +export type ConfirmationAcceptedProps = { + children?: ReactNode; +}; + +export const ConfirmationAccepted = ({ + children, +}: ConfirmationAcceptedProps) => { + const { approval, state } = useConfirmation(); + + // Only show when approved and in response states + if ( + !approval?.approved || + //@ts-ignore + (state !== "approval-responded" && + //@ts-ignore + state !== "output-denied" && + state !== "output-available") + ) { + return null; + } + + return children; +}; + +export type ConfirmationRejectedProps = { + children?: ReactNode; +}; + +export const ConfirmationRejected = ({ + children, +}: ConfirmationRejectedProps) => { + const { approval, state } = useConfirmation(); + + // Only show when rejected and in response states + if ( + approval?.approved !== false || + //@ts-ignore + (state !== "approval-responded" && + //@ts-ignore + state !== "output-denied" && + state !== "output-available") + ) { + return null; + } + + return children; +}; + +export type ConfirmationActionsProps = ComponentProps<"div">; + +export const ConfirmationActions = ({ + className, + ...props +}: ConfirmationActionsProps) => { + const { state } = useConfirmation(); + + // Only show when approval is requested + //@ts-ignore + if (state !== "approval-requested") { + return null; + } + + return ( +
+ ); +}; + +export type ConfirmationActionProps = ComponentProps; + +export const ConfirmationAction = (props: ConfirmationActionProps) => ( + + )} + + ); +}; + +export type ContextContentProps = ComponentProps; + +export const ContextContent = ({ + className, + ...props +}: ContextContentProps) => ( + +); + +export type ContextContentHeaderProps = ComponentProps<"div">; + +export const ContextContentHeader = ({ + children, + className, + ...props +}: ContextContentHeaderProps) => { + const { usedTokens, maxTokens } = useContextValue(); + const usedPercent = usedTokens / maxTokens; + const displayPct = new Intl.NumberFormat("en-US", { + style: "percent", + maximumFractionDigits: 1, + }).format(usedPercent); + const used = new Intl.NumberFormat("en-US", { + notation: "compact", + }).format(usedTokens); + const total = new Intl.NumberFormat("en-US", { + notation: "compact", + }).format(maxTokens); + + return ( +
+ {children ?? ( + <> +
+

{displayPct}

+

+ {used} / {total} +

+
+
+ +
+ + )} +
+ ); +}; + +export type ContextContentBodyProps = ComponentProps<"div">; + +export const ContextContentBody = ({ + children, + className, + ...props +}: ContextContentBodyProps) => ( +
+ {children} +
+); + +export type ContextContentFooterProps = ComponentProps<"div">; + +export const ContextContentFooter = ({ + children, + className, + ...props +}: ContextContentFooterProps) => { + const { modelId, usage } = useContextValue(); + const costUSD = modelId + ? getUsage({ + modelId, + usage: { + input: usage?.inputTokens ?? 0, + output: usage?.outputTokens ?? 0, + }, + }).costUSD?.totalUSD + : undefined; + const totalCost = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + }).format(costUSD ?? 0); + + return ( +
+ {children ?? ( + <> + Total cost + {totalCost} + + )} +
+ ); +}; + +export type ContextInputUsageProps = ComponentProps<"div">; + +export const ContextInputUsage = ({ + className, + children, + ...props +}: ContextInputUsageProps) => { + const { usage, modelId } = useContextValue(); + const inputTokens = usage?.inputTokens ?? 0; + + if (children) { + return children; + } + + if (!inputTokens) { + return null; + } + + const inputCost = modelId + ? getUsage({ + modelId, + usage: { input: inputTokens, output: 0 }, + }).costUSD?.totalUSD + : undefined; + const inputCostText = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + }).format(inputCost ?? 0); + + return ( +
+ Input + +
+ ); +}; + +export type ContextOutputUsageProps = ComponentProps<"div">; + +export const ContextOutputUsage = ({ + className, + children, + ...props +}: ContextOutputUsageProps) => { + const { usage, modelId } = useContextValue(); + const outputTokens = usage?.outputTokens ?? 0; + + if (children) { + return children; + } + + if (!outputTokens) { + return null; + } + + const outputCost = modelId + ? getUsage({ + modelId, + usage: { input: 0, output: outputTokens }, + }).costUSD?.totalUSD + : undefined; + const outputCostText = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + }).format(outputCost ?? 0); + + return ( +
+ Output + +
+ ); +}; + +export type ContextReasoningUsageProps = ComponentProps<"div">; + +export const ContextReasoningUsage = ({ + className, + children, + ...props +}: ContextReasoningUsageProps) => { + const { usage, modelId } = useContextValue(); + const reasoningTokens = usage?.reasoningTokens ?? 0; + + if (children) { + return children; + } + + if (!reasoningTokens) { + return null; + } + + const reasoningCost = modelId + ? getUsage({ + modelId, + usage: { reasoningTokens }, + }).costUSD?.totalUSD + : undefined; + const reasoningCostText = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + }).format(reasoningCost ?? 0); + + return ( +
+ Reasoning + +
+ ); +}; + +export type ContextCacheUsageProps = ComponentProps<"div">; + +export const ContextCacheUsage = ({ + className, + children, + ...props +}: ContextCacheUsageProps) => { + const { usage, modelId } = useContextValue(); + const cacheTokens = usage?.cachedInputTokens ?? 0; + + if (children) { + return children; + } + + if (!cacheTokens) { + return null; + } + + const cacheCost = modelId + ? getUsage({ + modelId, + usage: { cacheReads: cacheTokens, input: 0, output: 0 }, + }).costUSD?.totalUSD + : undefined; + const cacheCostText = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + }).format(cacheCost ?? 0); + + return ( +
+ Cache + +
+ ); +}; + +const TokensWithCost = ({ + tokens, + costText, +}: { + tokens?: number; + costText?: string; +}) => ( + + {tokens === undefined + ? "—" + : new Intl.NumberFormat("en-US", { + notation: "compact", + }).format(tokens)} + {costText ? ( + • {costText} + ) : null} + +); diff --git a/packages/playground/src/components/ai-elements/controls.tsx b/packages/playground/src/components/ai-elements/controls.tsx new file mode 100644 index 00000000..5af4c88b --- /dev/null +++ b/packages/playground/src/components/ai-elements/controls.tsx @@ -0,0 +1,19 @@ +"use client"; + +import React from "react"; +import { cn } from "@/lib/utils"; +import { Controls as ControlsPrimitive } from "@xyflow/react"; +import type { ComponentProps } from "react"; + +export type ControlsProps = ComponentProps; + +export const Controls = ({ className, ...props }: ControlsProps) => ( + button]:rounded-md [&>button]:border-none! [&>button]:bg-transparent! [&>button]:hover:bg-secondary!", + className, + )} + {...props} + /> +); diff --git a/packages/playground/src/components/ai-elements/conversation.tsx b/packages/playground/src/components/ai-elements/conversation.tsx new file mode 100644 index 00000000..a2bc60eb --- /dev/null +++ b/packages/playground/src/components/ai-elements/conversation.tsx @@ -0,0 +1,101 @@ +"use client"; + +import React from "react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { ArrowDownIcon } from "lucide-react"; +import type { ComponentProps } from "react"; +import { useCallback } from "react"; +import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom"; + +export type ConversationProps = ComponentProps; + +export const Conversation = ({ className, ...props }: ConversationProps) => ( + +); + +export type ConversationContentProps = ComponentProps< + typeof StickToBottom.Content +>; + +export const ConversationContent = ({ + className, + ...props +}: ConversationContentProps) => ( + +); + +export type ConversationEmptyStateProps = ComponentProps<"div"> & { + title?: string; + description?: string; + icon?: React.ReactNode; +}; + +export const ConversationEmptyState = ({ + className, + title = "No messages yet", + description = "Start a conversation to see messages here", + icon, + children, + ...props +}: ConversationEmptyStateProps) => ( +
+ {children ?? ( + <> + {icon &&
{icon}
} +
+

{title}

+ {description && ( +

{description}

+ )} +
+ + )} +
+); + +export type ConversationScrollButtonProps = ComponentProps; + +export const ConversationScrollButton = ({ + className, + ...props +}: ConversationScrollButtonProps) => { + const { isAtBottom, scrollToBottom } = useStickToBottomContext(); + + const handleScrollToBottom = useCallback(() => { + scrollToBottom(); + }, [scrollToBottom]); + + return ( + !isAtBottom && ( + + ) + ); +}; diff --git a/packages/playground/src/components/ai-elements/edge.tsx b/packages/playground/src/components/ai-elements/edge.tsx new file mode 100644 index 00000000..da43d089 --- /dev/null +++ b/packages/playground/src/components/ai-elements/edge.tsx @@ -0,0 +1,141 @@ +import React from "react"; +import { + BaseEdge, + type EdgeProps, + getBezierPath, + getSimpleBezierPath, + type InternalNode, + type Node, + Position, + useInternalNode, +} from "@xyflow/react"; + +const Temporary = ({ + id, + sourceX, + sourceY, + targetX, + targetY, + sourcePosition, + targetPosition, +}: EdgeProps) => { + const [edgePath] = getSimpleBezierPath({ + sourceX, + sourceY, + sourcePosition, + targetX, + targetY, + targetPosition, + }); + + return ( + + ); +}; + +const getHandleCoordsByPosition = ( + node: InternalNode, + handlePosition: Position +) => { + // Choose the handle type based on position - Left is for target, Right is for source + const handleType = handlePosition === Position.Left ? "target" : "source"; + + const handle = node.internals.handleBounds?.[handleType]?.find( + (h) => h.position === handlePosition + ); + + if (!handle) { + return [0, 0] as const; + } + + let offsetX = handle.width / 2; + let offsetY = handle.height / 2; + + // this is a tiny detail to make the markerEnd of an edge visible. + // The handle position that gets calculated has the origin top-left, so depending which side we are using, we add a little offset + // when the handlePosition is Position.Right for example, we need to add an offset as big as the handle itself in order to get the correct position + switch (handlePosition) { + case Position.Left: + offsetX = 0; + break; + case Position.Right: + offsetX = handle.width; + break; + case Position.Top: + offsetY = 0; + break; + case Position.Bottom: + offsetY = handle.height; + break; + default: + throw new Error(`Invalid handle position: ${handlePosition}`); + } + + const x = node.internals.positionAbsolute.x + handle.x + offsetX; + const y = node.internals.positionAbsolute.y + handle.y + offsetY; + + return [x, y] as const; +}; + +const getEdgeParams = ( + source: InternalNode, + target: InternalNode +) => { + const sourcePos = Position.Right; + const [sx, sy] = getHandleCoordsByPosition(source, sourcePos); + const targetPos = Position.Left; + const [tx, ty] = getHandleCoordsByPosition(target, targetPos); + + return { + sx, + sy, + tx, + ty, + sourcePos, + targetPos, + }; +}; + +const Animated = ({ id, source, target, markerEnd, style }: EdgeProps) => { + const sourceNode = useInternalNode(source); + const targetNode = useInternalNode(target); + + if (!(sourceNode && targetNode)) { + return null; + } + + const { sx, sy, tx, ty, sourcePos, targetPos } = getEdgeParams( + sourceNode, + targetNode + ); + + const [edgePath] = getBezierPath({ + sourceX: sx, + sourceY: sy, + sourcePosition: sourcePos, + targetX: tx, + targetY: ty, + targetPosition: targetPos, + }); + + return ( + <> + + + + + + ); +}; + +export const Edge = { + Temporary, + Animated, +}; diff --git a/packages/playground/src/components/ai-elements/image.tsx b/packages/playground/src/components/ai-elements/image.tsx new file mode 100644 index 00000000..93afe8f8 --- /dev/null +++ b/packages/playground/src/components/ai-elements/image.tsx @@ -0,0 +1,25 @@ +import React from "react"; +import { cn } from "@/lib/utils"; +import type { Experimental_GeneratedImage } from "ai"; + +export type ImageProps = Experimental_GeneratedImage & { + className?: string; + alt?: string; +}; + +export const Image = ({ + base64, + uint8Array, + mediaType, + ...props +}: ImageProps) => ( + {props.alt} +); diff --git a/packages/playground/src/components/ai-elements/inline-citation.tsx b/packages/playground/src/components/ai-elements/inline-citation.tsx new file mode 100644 index 00000000..76ee34c4 --- /dev/null +++ b/packages/playground/src/components/ai-elements/inline-citation.tsx @@ -0,0 +1,288 @@ +"use client"; + +import React from "react"; +import { Badge } from "@/components/ui/badge"; +import { + Carousel, + type CarouselApi, + CarouselContent, + CarouselItem, +} from "@/components/ui/carousel"; +import { + HoverCard, + HoverCardContent, + HoverCardTrigger, +} from "@/components/ui/hover-card"; +import { cn } from "@/lib/utils"; +import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react"; +import { + type ComponentProps, + createContext, + useCallback, + useContext, + useEffect, + useState, +} from "react"; + +export type InlineCitationProps = ComponentProps<"span">; + +export const InlineCitation = ({ + className, + ...props +}: InlineCitationProps) => ( + +); + +export type InlineCitationTextProps = ComponentProps<"span">; + +export const InlineCitationText = ({ + className, + ...props +}: InlineCitationTextProps) => ( + +); + +export type InlineCitationCardProps = ComponentProps; + +export const InlineCitationCard = (props: InlineCitationCardProps) => ( + +); + +export type InlineCitationCardTriggerProps = ComponentProps & { + sources: string[]; +}; + +export const InlineCitationCardTrigger = ({ + sources, + className, + ...props +}: InlineCitationCardTriggerProps) => ( + + + {sources[0] ? ( + <> + {new URL(sources[0]).hostname}{" "} + {sources.length > 1 && `+${sources.length - 1}`} + + ) : ( + "unknown" + )} + + +); + +export type InlineCitationCardBodyProps = ComponentProps<"div">; + +export const InlineCitationCardBody = ({ + className, + ...props +}: InlineCitationCardBodyProps) => ( + +); + +const CarouselApiContext = createContext(undefined); + +const useCarouselApi = () => { + const context = useContext(CarouselApiContext); + return context; +}; + +export type InlineCitationCarouselProps = ComponentProps; + +export const InlineCitationCarousel = ({ + className, + children, + ...props +}: InlineCitationCarouselProps) => { + const [api, setApi] = useState(); + + return ( + + + {children} + + + ); +}; + +export type InlineCitationCarouselContentProps = ComponentProps<"div">; + +export const InlineCitationCarouselContent = ( + props: InlineCitationCarouselContentProps, +) => ; + +export type InlineCitationCarouselItemProps = ComponentProps<"div">; + +export const InlineCitationCarouselItem = ({ + className, + ...props +}: InlineCitationCarouselItemProps) => ( + +); + +export type InlineCitationCarouselHeaderProps = ComponentProps<"div">; + +export const InlineCitationCarouselHeader = ({ + className, + ...props +}: InlineCitationCarouselHeaderProps) => ( +
+); + +export type InlineCitationCarouselIndexProps = ComponentProps<"div">; + +export const InlineCitationCarouselIndex = ({ + children, + className, + ...props +}: InlineCitationCarouselIndexProps) => { + const api = useCarouselApi(); + const [current, setCurrent] = useState(0); + const [count, setCount] = useState(0); + + useEffect(() => { + if (!api) { + return; + } + + setCount(api.scrollSnapList().length); + setCurrent(api.selectedScrollSnap() + 1); + + api.on("select", () => { + setCurrent(api.selectedScrollSnap() + 1); + }); + }, [api]); + + return ( +
+ {children ?? `${current}/${count}`} +
+ ); +}; + +export type InlineCitationCarouselPrevProps = ComponentProps<"button">; + +export const InlineCitationCarouselPrev = ({ + className, + ...props +}: InlineCitationCarouselPrevProps) => { + const api = useCarouselApi(); + + const handleClick = useCallback(() => { + if (api) { + api.scrollPrev(); + } + }, [api]); + + return ( + + ); +}; + +export type InlineCitationCarouselNextProps = ComponentProps<"button">; + +export const InlineCitationCarouselNext = ({ + className, + ...props +}: InlineCitationCarouselNextProps) => { + const api = useCarouselApi(); + + const handleClick = useCallback(() => { + if (api) { + api.scrollNext(); + } + }, [api]); + + return ( + + ); +}; + +export type InlineCitationSourceProps = ComponentProps<"div"> & { + title?: string; + url?: string; + description?: string; +}; + +export const InlineCitationSource = ({ + title, + url, + description, + className, + children, + ...props +}: InlineCitationSourceProps) => ( +
+ {title && ( +

{title}

+ )} + {url && ( +

{url}

+ )} + {description && ( +

+ {description} +

+ )} + {children} +
+); + +export type InlineCitationQuoteProps = ComponentProps<"blockquote">; + +export const InlineCitationQuote = ({ + children, + className, + ...props +}: InlineCitationQuoteProps) => ( +
+ {children} +
+); diff --git a/packages/playground/src/components/ai-elements/loader.tsx b/packages/playground/src/components/ai-elements/loader.tsx new file mode 100644 index 00000000..af3d88c9 --- /dev/null +++ b/packages/playground/src/components/ai-elements/loader.tsx @@ -0,0 +1,97 @@ +import { cn } from "@/lib/utils"; +import React from "react"; +import type { HTMLAttributes } from "react"; + +type LoaderIconProps = { + size?: number; +}; + +const LoaderIcon = ({ size = 16 }: LoaderIconProps) => ( + + Loader + + + + + + + + + + + + + + + + + + +); + +export type LoaderProps = HTMLAttributes & { + size?: number; +}; + +export const Loader = ({ className, size = 16, ...props }: LoaderProps) => ( +
+ +
+); diff --git a/packages/playground/src/components/ai-elements/message.tsx b/packages/playground/src/components/ai-elements/message.tsx new file mode 100644 index 00000000..66fb704e --- /dev/null +++ b/packages/playground/src/components/ai-elements/message.tsx @@ -0,0 +1,446 @@ +"use client"; + +import React from "react"; +import { Button } from "@/components/ui/button"; +import { ButtonGroup, ButtonGroupText } from "@/components/ui/button-group"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { cn } from "@/lib/utils"; +import type { FileUIPart, UIMessage } from "ai"; +import { + ChevronLeftIcon, + ChevronRightIcon, + PaperclipIcon, + XIcon, +} from "lucide-react"; +import type { ComponentProps, HTMLAttributes, ReactElement } from "react"; +import { createContext, memo, useContext, useEffect, useState } from "react"; +import { Streamdown } from "streamdown"; + +export type MessageProps = HTMLAttributes & { + from: UIMessage["role"]; +}; + +export const Message = ({ className, from, ...props }: MessageProps) => ( +
+); + +export type MessageContentProps = HTMLAttributes; + +export const MessageContent = ({ + children, + className, + ...props +}: MessageContentProps) => ( +
+ {children} +
+); + +export type MessageActionsProps = ComponentProps<"div">; + +export const MessageActions = ({ + className, + children, + ...props +}: MessageActionsProps) => ( +
+ {children} +
+); + +export type MessageActionProps = ComponentProps & { + tooltip?: string; + label?: string; +}; + +export const MessageAction = ({ + tooltip, + children, + label, + variant = "ghost", + size = "icon-sm", + ...props +}: MessageActionProps) => { + const button = ( + + ); + + if (tooltip) { + return ( + + + {button} + +

{tooltip}

+
+
+
+ ); + } + + return button; +}; + +type MessageBranchContextType = { + currentBranch: number; + totalBranches: number; + goToPrevious: () => void; + goToNext: () => void; + branches: ReactElement[]; + setBranches: (branches: ReactElement[]) => void; +}; + +const MessageBranchContext = createContext( + null, +); + +const useMessageBranch = () => { + const context = useContext(MessageBranchContext); + + if (!context) { + throw new Error( + "MessageBranch components must be used within MessageBranch", + ); + } + + return context; +}; + +export type MessageBranchProps = HTMLAttributes & { + defaultBranch?: number; + onBranchChange?: (branchIndex: number) => void; +}; + +export const MessageBranch = ({ + defaultBranch = 0, + onBranchChange, + className, + ...props +}: MessageBranchProps) => { + const [currentBranch, setCurrentBranch] = useState(defaultBranch); + const [branches, setBranches] = useState([]); + + const handleBranchChange = (newBranch: number) => { + setCurrentBranch(newBranch); + onBranchChange?.(newBranch); + }; + + const goToPrevious = () => { + const newBranch = + currentBranch > 0 ? currentBranch - 1 : branches.length - 1; + handleBranchChange(newBranch); + }; + + const goToNext = () => { + const newBranch = + currentBranch < branches.length - 1 ? currentBranch + 1 : 0; + handleBranchChange(newBranch); + }; + + const contextValue: MessageBranchContextType = { + currentBranch, + totalBranches: branches.length, + goToPrevious, + goToNext, + branches, + setBranches, + }; + + return ( + +
div]:pb-0", className)} + {...props} + /> + + ); +}; + +export type MessageBranchContentProps = HTMLAttributes; + +export const MessageBranchContent = ({ + children, + ...props +}: MessageBranchContentProps) => { + const { currentBranch, setBranches, branches } = useMessageBranch(); + const childrenArray = Array.isArray(children) ? children : [children]; + + // Use useEffect to update branches when they change + useEffect(() => { + if (branches.length !== childrenArray.length) { + setBranches(childrenArray); + } + }, [childrenArray, branches, setBranches]); + + return childrenArray.map((branch, index) => ( +
div]:pb-0", + index === currentBranch ? "block" : "hidden", + )} + key={branch.key} + {...props} + > + {branch} +
+ )); +}; + +export type MessageBranchSelectorProps = HTMLAttributes & { + from: UIMessage["role"]; +}; + +export const MessageBranchSelector = ({ + className, + from, + ...props +}: MessageBranchSelectorProps) => { + const { totalBranches } = useMessageBranch(); + + // Don't render if there's only one branch + if (totalBranches <= 1) { + return null; + } + + return ( + + ); +}; + +export type MessageBranchPreviousProps = ComponentProps; + +export const MessageBranchPrevious = ({ + children, + ...props +}: MessageBranchPreviousProps) => { + const { goToPrevious, totalBranches } = useMessageBranch(); + + return ( + + ); +}; + +export type MessageBranchNextProps = ComponentProps; + +export const MessageBranchNext = ({ + children, + className, + ...props +}: MessageBranchNextProps) => { + const { goToNext, totalBranches } = useMessageBranch(); + + return ( + + ); +}; + +export type MessageBranchPageProps = HTMLAttributes; + +export const MessageBranchPage = ({ + className, + ...props +}: MessageBranchPageProps) => { + const { currentBranch, totalBranches } = useMessageBranch(); + + return ( + + {currentBranch + 1} of {totalBranches} + + ); +}; + +export type MessageResponseProps = ComponentProps; + +export const MessageResponse = memo( + ({ className, ...props }: MessageResponseProps) => ( + *:first-child]:mt-0 [&>*:last-child]:mb-0", + className, + )} + {...props} + /> + ), + (prevProps, nextProps) => prevProps.children === nextProps.children, +); + +MessageResponse.displayName = "MessageResponse"; + +export type MessageAttachmentProps = HTMLAttributes & { + data: FileUIPart; + className?: string; + onRemove?: () => void; +}; + +export function MessageAttachment({ + data, + className, + onRemove, + ...props +}: MessageAttachmentProps) { + const filename = data.filename || ""; + const mediaType = + data.mediaType?.startsWith("image/") && data.url ? "image" : "file"; + const isImage = mediaType === "image"; + const attachmentLabel = filename || (isImage ? "Image" : "Attachment"); + + return ( +
+ {isImage ? ( + <> + {filename + {onRemove && ( + + )} + + ) : ( + <> + + +
+ +
+
+ +

{attachmentLabel}

+
+
+ {onRemove && ( + + )} + + )} +
+ ); +} + +export type MessageAttachmentsProps = ComponentProps<"div">; + +export function MessageAttachments({ + children, + className, + ...props +}: MessageAttachmentsProps) { + if (!children) { + return null; + } + + return ( +
+ {children} +
+ ); +} + +export type MessageToolbarProps = ComponentProps<"div">; + +export const MessageToolbar = ({ + className, + children, + ...props +}: MessageToolbarProps) => ( +
+ {children} +
+); diff --git a/packages/playground/src/components/ai-elements/model-selector.tsx b/packages/playground/src/components/ai-elements/model-selector.tsx new file mode 100644 index 00000000..36b78bff --- /dev/null +++ b/packages/playground/src/components/ai-elements/model-selector.tsx @@ -0,0 +1,206 @@ +import React from "react"; +import { + Command, + CommandDialog, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, + CommandSeparator, + CommandShortcut, +} from "@/components/ui/command"; +import { + Dialog, + DialogContent, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +import { cn } from "@/lib/utils"; +import type { ComponentProps, ReactNode } from "react"; + +export type ModelSelectorProps = ComponentProps; + +export const ModelSelector = (props: ModelSelectorProps) => ( + +); + +export type ModelSelectorTriggerProps = ComponentProps; + +export const ModelSelectorTrigger = (props: ModelSelectorTriggerProps) => ( + +); + +export type ModelSelectorContentProps = ComponentProps & { + title?: ReactNode; +}; + +export const ModelSelectorContent = ({ + className, + children, + title = "Model Selector", + ...props +}: ModelSelectorContentProps) => ( + + {title} + + {children} + + +); + +export type ModelSelectorDialogProps = ComponentProps; + +export const ModelSelectorDialog = (props: ModelSelectorDialogProps) => ( + +); + +export type ModelSelectorInputProps = ComponentProps; + +export const ModelSelectorInput = ({ + className, + ...props +}: ModelSelectorInputProps) => ( + +); + +export type ModelSelectorListProps = ComponentProps; + +export const ModelSelectorList = (props: ModelSelectorListProps) => ( + +); + +export type ModelSelectorEmptyProps = ComponentProps; + +export const ModelSelectorEmpty = (props: ModelSelectorEmptyProps) => ( + +); + +export type ModelSelectorGroupProps = ComponentProps; + +export const ModelSelectorGroup = (props: ModelSelectorGroupProps) => ( + +); + +export type ModelSelectorItemProps = ComponentProps; + +export const ModelSelectorItem = (props: ModelSelectorItemProps) => ( + +); + +export type ModelSelectorShortcutProps = ComponentProps; + +export const ModelSelectorShortcut = (props: ModelSelectorShortcutProps) => ( + +); + +export type ModelSelectorSeparatorProps = ComponentProps< + typeof CommandSeparator +>; + +export const ModelSelectorSeparator = (props: ModelSelectorSeparatorProps) => ( + +); + +export type ModelSelectorLogoProps = Omit< + ComponentProps<"img">, + "src" | "alt" +> & { + provider: + | "moonshotai-cn" + | "lucidquery" + | "moonshotai" + | "zai-coding-plan" + | "alibaba" + | "xai" + | "vultr" + | "nvidia" + | "upstage" + | "groq" + | "github-copilot" + | "mistral" + | "vercel" + | "nebius" + | "deepseek" + | "alibaba-cn" + | "google-vertex-anthropic" + | "venice" + | "chutes" + | "cortecs" + | "github-models" + | "togetherai" + | "azure" + | "baseten" + | "huggingface" + | "opencode" + | "fastrouter" + | "google" + | "google-vertex" + | "cloudflare-workers-ai" + | "inception" + | "wandb" + | "openai" + | "zhipuai-coding-plan" + | "perplexity" + | "openrouter" + | "zenmux" + | "v0" + | "iflowcn" + | "synthetic" + | "deepinfra" + | "zhipuai" + | "submodel" + | "zai" + | "inference" + | "requesty" + | "morph" + | "lmstudio" + | "anthropic" + | "aihubmix" + | "fireworks-ai" + | "modelscope" + | "llama" + | "scaleway" + | "amazon-bedrock" + | "cerebras" + | (string & {}); +}; + +export const ModelSelectorLogo = ({ + provider, + className, + ...props +}: ModelSelectorLogoProps) => ( + {`${provider} +); + +export type ModelSelectorLogoGroupProps = ComponentProps<"div">; + +export const ModelSelectorLogoGroup = ({ + className, + ...props +}: ModelSelectorLogoGroupProps) => ( +
img]:rounded-full [&>img]:bg-background [&>img]:p-px [&>img]:ring-1 dark:[&>img]:bg-foreground", + className, + )} + {...props} + /> +); + +export type ModelSelectorNameProps = ComponentProps<"span">; + +export const ModelSelectorName = ({ + className, + ...props +}: ModelSelectorNameProps) => ( + +); diff --git a/packages/playground/src/components/ai-elements/node.tsx b/packages/playground/src/components/ai-elements/node.tsx new file mode 100644 index 00000000..ad838e13 --- /dev/null +++ b/packages/playground/src/components/ai-elements/node.tsx @@ -0,0 +1,72 @@ +import { + Card, + CardAction, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { cn } from "@/lib/utils"; +import { Handle, Position } from "@xyflow/react"; +import React from "react"; +import type { ComponentProps } from "react"; + +export type NodeProps = ComponentProps & { + handles: { + target: boolean; + source: boolean; + }; +}; + +export const Node = ({ handles, className, ...props }: NodeProps) => ( + + {handles.target && } + {handles.source && } + {props.children} + +); + +export type NodeHeaderProps = ComponentProps; + +export const NodeHeader = ({ className, ...props }: NodeHeaderProps) => ( + +); + +export type NodeTitleProps = ComponentProps; + +export const NodeTitle = (props: NodeTitleProps) => ; + +export type NodeDescriptionProps = ComponentProps; + +export const NodeDescription = (props: NodeDescriptionProps) => ( + +); + +export type NodeActionProps = ComponentProps; + +export const NodeAction = (props: NodeActionProps) => ; + +export type NodeContentProps = ComponentProps; + +export const NodeContent = ({ className, ...props }: NodeContentProps) => ( + +); + +export type NodeFooterProps = ComponentProps; + +export const NodeFooter = ({ className, ...props }: NodeFooterProps) => ( + +); diff --git a/packages/playground/src/components/ai-elements/open-in-chat.tsx b/packages/playground/src/components/ai-elements/open-in-chat.tsx new file mode 100644 index 00000000..f641710b --- /dev/null +++ b/packages/playground/src/components/ai-elements/open-in-chat.tsx @@ -0,0 +1,366 @@ +"use client"; + +import React from "react"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { cn } from "@/lib/utils"; +import { + ChevronDownIcon, + ExternalLinkIcon, + MessageCircleIcon, +} from "lucide-react"; +import { type ComponentProps, createContext, useContext } from "react"; + +const providers = { + github: { + title: "Open in GitHub", + createUrl: (url: string) => url, + icon: ( + + GitHub + + + ), + }, + scira: { + title: "Open in Scira", + createUrl: (q: string) => + `https://scira.ai/?${new URLSearchParams({ + q, + })}`, + icon: ( + + Scira AI + + + + + + + + + ), + }, + chatgpt: { + title: "Open in ChatGPT", + createUrl: (prompt: string) => + `https://chatgpt.com/?${new URLSearchParams({ + hints: "search", + prompt, + })}`, + icon: ( + + OpenAI + + + ), + }, + claude: { + title: "Open in Claude", + createUrl: (q: string) => + `https://claude.ai/new?${new URLSearchParams({ + q, + })}`, + icon: ( + + Claude + + + ), + }, + t3: { + title: "Open in T3 Chat", + createUrl: (q: string) => + `https://t3.chat/new?${new URLSearchParams({ + q, + })}`, + icon: , + }, + v0: { + title: "Open in v0", + createUrl: (q: string) => + `https://v0.app?${new URLSearchParams({ + q, + })}`, + icon: ( + + v0 + + + + ), + }, + cursor: { + title: "Open in Cursor", + createUrl: (text: string) => { + const url = new URL("https://cursor.com/link/prompt"); + url.searchParams.set("text", text); + return url.toString(); + }, + icon: ( + + Cursor + + + ), + }, +}; + +const OpenInContext = createContext<{ query: string } | undefined>(undefined); + +const useOpenInContext = () => { + const context = useContext(OpenInContext); + if (!context) { + throw new Error("OpenIn components must be used within an OpenIn provider"); + } + return context; +}; + +export type OpenInProps = ComponentProps & { + query: string; +}; + +export const OpenIn = ({ query, ...props }: OpenInProps) => ( + + + +); + +export type OpenInContentProps = ComponentProps; + +export const OpenInContent = ({ className, ...props }: OpenInContentProps) => ( + +); + +export type OpenInItemProps = ComponentProps; + +export const OpenInItem = (props: OpenInItemProps) => ( + +); + +export type OpenInLabelProps = ComponentProps; + +export const OpenInLabel = (props: OpenInLabelProps) => ( + +); + +export type OpenInSeparatorProps = ComponentProps; + +export const OpenInSeparator = (props: OpenInSeparatorProps) => ( + +); + +export type OpenInTriggerProps = ComponentProps; + +export const OpenInTrigger = ({ children, ...props }: OpenInTriggerProps) => ( + + {children ?? ( + + )} + +); + +export type OpenInChatGPTProps = ComponentProps; + +export const OpenInChatGPT = (props: OpenInChatGPTProps) => { + const { query } = useOpenInContext(); + return ( + + + {providers.chatgpt.icon} + {providers.chatgpt.title} + + + + ); +}; + +export type OpenInClaudeProps = ComponentProps; + +export const OpenInClaude = (props: OpenInClaudeProps) => { + const { query } = useOpenInContext(); + return ( + + + {providers.claude.icon} + {providers.claude.title} + + + + ); +}; + +export type OpenInT3Props = ComponentProps; + +export const OpenInT3 = (props: OpenInT3Props) => { + const { query } = useOpenInContext(); + return ( + + + {providers.t3.icon} + {providers.t3.title} + + + + ); +}; + +export type OpenInSciraProps = ComponentProps; + +export const OpenInScira = (props: OpenInSciraProps) => { + const { query } = useOpenInContext(); + return ( + + + {providers.scira.icon} + {providers.scira.title} + + + + ); +}; + +export type OpenInv0Props = ComponentProps; + +export const OpenInv0 = (props: OpenInv0Props) => { + const { query } = useOpenInContext(); + return ( + + + {providers.v0.icon} + {providers.v0.title} + + + + ); +}; + +export type OpenInCursorProps = ComponentProps; + +export const OpenInCursor = (props: OpenInCursorProps) => { + const { query } = useOpenInContext(); + return ( + + + {providers.cursor.icon} + {providers.cursor.title} + + + + ); +}; diff --git a/packages/playground/src/components/ai-elements/panel.tsx b/packages/playground/src/components/ai-elements/panel.tsx new file mode 100644 index 00000000..921f5431 --- /dev/null +++ b/packages/playground/src/components/ai-elements/panel.tsx @@ -0,0 +1,16 @@ +import { cn } from "@/lib/utils"; +import { Panel as PanelPrimitive } from "@xyflow/react"; +import type { ComponentProps } from "react"; +import React from "react"; + +type PanelProps = ComponentProps; + +export const Panel = ({ className, ...props }: PanelProps) => ( + +); diff --git a/packages/playground/src/components/ai-elements/plan.tsx b/packages/playground/src/components/ai-elements/plan.tsx new file mode 100644 index 00000000..e047af92 --- /dev/null +++ b/packages/playground/src/components/ai-elements/plan.tsx @@ -0,0 +1,143 @@ +"use client"; + +import { Button } from "@/components/ui/button"; +import React from "react"; +import { + Card, + CardAction, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@/components/ui/collapsible"; +import { cn } from "@/lib/utils"; +import { ChevronsUpDownIcon } from "lucide-react"; +import type { ComponentProps } from "react"; +import { createContext, useContext } from "react"; +import { Shimmer } from "./shimmer"; + +type PlanContextValue = { + isStreaming: boolean; +}; + +const PlanContext = createContext(null); + +const usePlan = () => { + const context = useContext(PlanContext); + if (!context) { + throw new Error("Plan components must be used within Plan"); + } + return context; +}; + +export type PlanProps = ComponentProps & { + isStreaming?: boolean; +}; + +export const Plan = ({ + className, + isStreaming = false, + children, + ...props +}: PlanProps) => ( + + + {children} + + +); + +export type PlanHeaderProps = ComponentProps; + +export const PlanHeader = ({ className, ...props }: PlanHeaderProps) => ( + +); + +export type PlanTitleProps = Omit< + ComponentProps, + "children" +> & { + children: string; +}; + +export const PlanTitle = ({ children, ...props }: PlanTitleProps) => { + const { isStreaming } = usePlan(); + + return ( + + {isStreaming ? {children} : children} + + ); +}; + +export type PlanDescriptionProps = Omit< + ComponentProps, + "children" +> & { + children: string; +}; + +export const PlanDescription = ({ + className, + children, + ...props +}: PlanDescriptionProps) => { + const { isStreaming } = usePlan(); + + return ( + + {isStreaming ? {children} : children} + + ); +}; + +export type PlanActionProps = ComponentProps; + +export const PlanAction = (props: PlanActionProps) => ( + +); + +export type PlanContentProps = ComponentProps; + +export const PlanContent = (props: PlanContentProps) => ( + + + +); + +export type PlanFooterProps = ComponentProps<"div">; + +export const PlanFooter = (props: PlanFooterProps) => ( + +); + +export type PlanTriggerProps = ComponentProps; + +export const PlanTrigger = ({ className, ...props }: PlanTriggerProps) => ( + + + +); diff --git a/packages/playground/src/components/ai-elements/prompt-input.tsx b/packages/playground/src/components/ai-elements/prompt-input.tsx new file mode 100644 index 00000000..5afe1aee --- /dev/null +++ b/packages/playground/src/components/ai-elements/prompt-input.tsx @@ -0,0 +1,1379 @@ +"use client"; + +import React from "react"; +import { Button } from "@/components/ui/button"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, + CommandSeparator, +} from "@/components/ui/command"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + HoverCard, + HoverCardContent, + HoverCardTrigger, +} from "@/components/ui/hover-card"; +import { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupTextarea, +} from "@/components/ui/input-group"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { cn } from "@/lib/utils"; +import type { ChatStatus, FileUIPart } from "ai"; +import { + CornerDownLeftIcon, + ImageIcon, + Loader2Icon, + MicIcon, + PaperclipIcon, + PlusIcon, + SquareIcon, + XIcon, +} from "lucide-react"; +import { nanoid } from "nanoid"; +import { + type ChangeEvent, + type ChangeEventHandler, + Children, + type ClipboardEventHandler, + type ComponentProps, + createContext, + type FormEvent, + type FormEventHandler, + Fragment, + type HTMLAttributes, + type KeyboardEventHandler, + type PropsWithChildren, + type ReactNode, + type RefObject, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; + +// ============================================================================ +// Provider Context & Types +// ============================================================================ + +export type AttachmentsContext = { + files: (FileUIPart & { id: string })[]; + add: (files: File[] | FileList) => void; + remove: (id: string) => void; + clear: () => void; + openFileDialog: () => void; + fileInputRef: RefObject; +}; + +export type TextInputContext = { + value: string; + setInput: (v: string) => void; + clear: () => void; +}; + +export type PromptInputControllerProps = { + textInput: TextInputContext; + attachments: AttachmentsContext; + /** INTERNAL: Allows PromptInput to register its file textInput + "open" callback */ + __registerFileInput: ( + ref: RefObject, + open: () => void, + ) => void; +}; + +const PromptInputController = createContext( + null, +); +const ProviderAttachmentsContext = createContext( + null, +); + +export const usePromptInputController = () => { + const ctx = useContext(PromptInputController); + if (!ctx) { + throw new Error( + "Wrap your component inside to use usePromptInputController().", + ); + } + return ctx; +}; + +// Optional variants (do NOT throw). Useful for dual-mode components. +const useOptionalPromptInputController = () => + useContext(PromptInputController); + +export const useProviderAttachments = () => { + const ctx = useContext(ProviderAttachmentsContext); + if (!ctx) { + throw new Error( + "Wrap your component inside to use useProviderAttachments().", + ); + } + return ctx; +}; + +const useOptionalProviderAttachments = () => + useContext(ProviderAttachmentsContext); + +export type PromptInputProviderProps = PropsWithChildren<{ + initialInput?: string; +}>; + +/** + * Optional global provider that lifts PromptInput state outside of PromptInput. + * If you don't use it, PromptInput stays fully self-managed. + */ +export function PromptInputProvider({ + initialInput: initialTextInput = "", + children, +}: PromptInputProviderProps) { + // ----- textInput state + const [textInput, setTextInput] = useState(initialTextInput); + const clearInput = useCallback(() => setTextInput(""), []); + + // ----- attachments state (global when wrapped) + const [attachements, setAttachements] = useState< + (FileUIPart & { id: string })[] + >([]); + const fileInputRef = useRef(null); + const openRef = useRef<() => void>(() => {}); + + const add = useCallback((files: File[] | FileList) => { + const incoming = Array.from(files); + if (incoming.length === 0) { + return; + } + + setAttachements((prev) => + prev.concat( + incoming.map((file) => ({ + id: nanoid(), + type: "file" as const, + url: URL.createObjectURL(file), + mediaType: file.type, + filename: file.name, + })), + ), + ); + }, []); + + const remove = useCallback((id: string) => { + setAttachements((prev) => { + const found = prev.find((f) => f.id === id); + if (found?.url) { + URL.revokeObjectURL(found.url); + } + return prev.filter((f) => f.id !== id); + }); + }, []); + + const clear = useCallback(() => { + setAttachements((prev) => { + for (const f of prev) { + if (f.url) { + URL.revokeObjectURL(f.url); + } + } + return []; + }); + }, []); + + const openFileDialog = useCallback(() => { + openRef.current?.(); + }, []); + + const attachments = useMemo( + () => ({ + files: attachements, + add, + remove, + clear, + openFileDialog, + fileInputRef, + }), + [attachements, add, remove, clear, openFileDialog], + ); + + const __registerFileInput = useCallback( + (ref: RefObject, open: () => void) => { + fileInputRef.current = ref.current; + openRef.current = open; + }, + [], + ); + + const controller = useMemo( + () => ({ + textInput: { + value: textInput, + setInput: setTextInput, + clear: clearInput, + }, + attachments, + __registerFileInput, + }), + [textInput, clearInput, attachments, __registerFileInput], + ); + + return ( + + + {children} + + + ); +} + +// ============================================================================ +// Component Context & Hooks +// ============================================================================ + +const LocalAttachmentsContext = createContext(null); + +export const usePromptInputAttachments = () => { + // Dual-mode: prefer provider if present, otherwise use local + const provider = useOptionalProviderAttachments(); + const local = useContext(LocalAttachmentsContext); + const context = provider ?? local; + if (!context) { + throw new Error( + "usePromptInputAttachments must be used within a PromptInput or PromptInputProvider", + ); + } + return context; +}; + +export type PromptInputAttachmentProps = HTMLAttributes & { + data: FileUIPart & { id: string }; + className?: string; +}; + +export function PromptInputAttachment({ + data, + className, + ...props +}: PromptInputAttachmentProps) { + const attachments = usePromptInputAttachments(); + + const filename = data.filename || ""; + + const mediaType = + data.mediaType?.startsWith("image/") && data.url ? "image" : "file"; + const isImage = mediaType === "image"; + + const attachmentLabel = filename || (isImage ? "Image" : "Attachment"); + + return ( + + +
+
+
+ {isImage ? ( + {filename + ) : ( +
+ +
+ )} +
+ +
+ + {attachmentLabel} +
+
+ +
+ {isImage && ( +
+ {filename +
+ )} +
+
+

+ {filename || (isImage ? "Image" : "Attachment")} +

+ {data.mediaType && ( +

+ {data.mediaType} +

+ )} +
+
+
+
+
+ ); +} + +export type PromptInputAttachmentsProps = Omit< + HTMLAttributes, + "children" +> & { + children: (attachment: FileUIPart & { id: string }) => ReactNode; +}; + +export function PromptInputAttachments({ + children, + className, + ...props +}: PromptInputAttachmentsProps) { + const attachments = usePromptInputAttachments(); + + if (!attachments.files.length) { + return null; + } + + return ( +
+ {attachments.files.map((file) => ( + {children(file)} + ))} +
+ ); +} + +export type PromptInputActionAddAttachmentsProps = ComponentProps< + typeof DropdownMenuItem +> & { + label?: string; +}; + +export const PromptInputActionAddAttachments = ({ + label = "Add photos or files", + ...props +}: PromptInputActionAddAttachmentsProps) => { + const attachments = usePromptInputAttachments(); + + return ( + { + e.preventDefault(); + attachments.openFileDialog(); + }} + > + {label} + + ); +}; + +export type PromptInputMessage = { + text: string; + files: FileUIPart[]; +}; + +export type PromptInputProps = Omit< + HTMLAttributes, + "onSubmit" | "onError" +> & { + accept?: string; // e.g., "image/*" or leave undefined for any + multiple?: boolean; + // When true, accepts drops anywhere on document. Default false (opt-in). + globalDrop?: boolean; + // Render a hidden input with given name and keep it in sync for native form posts. Default false. + syncHiddenInput?: boolean; + // Minimal constraints + maxFiles?: number; + maxFileSize?: number; // bytes + onError?: (err: { + code: "max_files" | "max_file_size" | "accept"; + message: string; + }) => void; + onSubmit: ( + message: PromptInputMessage, + event: FormEvent, + ) => void | Promise; +}; + +export const PromptInput = ({ + className, + accept, + multiple, + globalDrop, + syncHiddenInput, + maxFiles, + maxFileSize, + onError, + onSubmit, + children, + ...props +}: PromptInputProps) => { + // Try to use a provider controller if present + const controller = useOptionalPromptInputController(); + const usingProvider = !!controller; + + // Refs + const inputRef = useRef(null); + const anchorRef = useRef(null); + const formRef = useRef(null); + + // Find nearest form to scope drag & drop + useEffect(() => { + const root = anchorRef.current?.closest("form"); + if (root instanceof HTMLFormElement) { + formRef.current = root; + } + }, []); + + // ----- Local attachments (only used when no provider) + const [items, setItems] = useState<(FileUIPart & { id: string })[]>([]); + const files = usingProvider ? controller.attachments.files : items; + + const openFileDialogLocal = useCallback(() => { + inputRef.current?.click(); + }, []); + + const matchesAccept = useCallback( + (f: File) => { + if (!accept || accept.trim() === "") { + return true; + } + if (accept.includes("image/*")) { + return f.type.startsWith("image/"); + } + // NOTE: keep simple; expand as needed + return true; + }, + [accept], + ); + + const addLocal = useCallback( + (fileList: File[] | FileList) => { + const incoming = Array.from(fileList); + const accepted = incoming.filter((f) => matchesAccept(f)); + if (incoming.length && accepted.length === 0) { + onError?.({ + code: "accept", + message: "No files match the accepted types.", + }); + return; + } + const withinSize = (f: File) => + maxFileSize ? f.size <= maxFileSize : true; + const sized = accepted.filter(withinSize); + if (accepted.length > 0 && sized.length === 0) { + onError?.({ + code: "max_file_size", + message: "All files exceed the maximum size.", + }); + return; + } + + setItems((prev) => { + const capacity = + typeof maxFiles === "number" + ? Math.max(0, maxFiles - prev.length) + : undefined; + const capped = + typeof capacity === "number" ? sized.slice(0, capacity) : sized; + if (typeof capacity === "number" && sized.length > capacity) { + onError?.({ + code: "max_files", + message: "Too many files. Some were not added.", + }); + } + const next: (FileUIPart & { id: string })[] = []; + for (const file of capped) { + next.push({ + id: nanoid(), + type: "file", + url: URL.createObjectURL(file), + mediaType: file.type, + filename: file.name, + }); + } + return prev.concat(next); + }); + }, + [matchesAccept, maxFiles, maxFileSize, onError], + ); + + const add = usingProvider + ? (files: File[] | FileList) => controller.attachments.add(files) + : addLocal; + + const remove = usingProvider + ? (id: string) => controller.attachments.remove(id) + : (id: string) => + setItems((prev) => { + const found = prev.find((file) => file.id === id); + if (found?.url) { + URL.revokeObjectURL(found.url); + } + return prev.filter((file) => file.id !== id); + }); + + const clear = usingProvider + ? () => controller.attachments.clear() + : () => + setItems((prev) => { + for (const file of prev) { + if (file.url) { + URL.revokeObjectURL(file.url); + } + } + return []; + }); + + const openFileDialog = usingProvider + ? () => controller.attachments.openFileDialog() + : openFileDialogLocal; + + // Let provider know about our hidden file input so external menus can call openFileDialog() + useEffect(() => { + if (!usingProvider) return; + controller.__registerFileInput(inputRef, () => inputRef.current?.click()); + }, [usingProvider, controller]); + + // Note: File input cannot be programmatically set for security reasons + // The syncHiddenInput prop is no longer functional + useEffect(() => { + if (syncHiddenInput && inputRef.current && files.length === 0) { + inputRef.current.value = ""; + } + }, [files, syncHiddenInput]); + + // Attach drop handlers on nearest form and document (opt-in) + useEffect(() => { + const form = formRef.current; + if (!form) return; + + const onDragOver = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes("Files")) { + e.preventDefault(); + } + }; + const onDrop = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes("Files")) { + e.preventDefault(); + } + if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) { + add(e.dataTransfer.files); + } + }; + form.addEventListener("dragover", onDragOver); + form.addEventListener("drop", onDrop); + return () => { + form.removeEventListener("dragover", onDragOver); + form.removeEventListener("drop", onDrop); + }; + }, [add]); + + useEffect(() => { + if (!globalDrop) return; + + const onDragOver = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes("Files")) { + e.preventDefault(); + } + }; + const onDrop = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes("Files")) { + e.preventDefault(); + } + if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) { + add(e.dataTransfer.files); + } + }; + document.addEventListener("dragover", onDragOver); + document.addEventListener("drop", onDrop); + return () => { + document.removeEventListener("dragover", onDragOver); + document.removeEventListener("drop", onDrop); + }; + }, [add, globalDrop]); + + useEffect( + () => () => { + if (!usingProvider) { + for (const f of files) { + if (f.url) URL.revokeObjectURL(f.url); + } + } + }, + [usingProvider, files], + ); + + const handleChange: ChangeEventHandler = (event) => { + if (event.currentTarget.files) { + add(event.currentTarget.files); + } + }; + + const convertBlobUrlToDataUrl = async (url: string): Promise => { + const response = await fetch(url); + const blob = await response.blob(); + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result as string); + reader.onerror = reject; + reader.readAsDataURL(blob); + }); + }; + + const ctx = useMemo( + () => ({ + files: files.map((item) => ({ ...item, id: item.id })), + add, + remove, + clear, + openFileDialog, + fileInputRef: inputRef, + }), + [files, add, remove, clear, openFileDialog], + ); + + const handleSubmit: FormEventHandler = (event) => { + event.preventDefault(); + + const form = event.currentTarget; + const text = usingProvider + ? controller.textInput.value + : (() => { + const formData = new FormData(form); + return (formData.get("message") as string) || ""; + })(); + + // Reset form immediately after capturing text to avoid race condition + // where user input during async blob conversion would be lost + if (!usingProvider) { + form.reset(); + } + + // Convert blob URLs to data URLs asynchronously + Promise.all( + files.map(async ({ id, ...item }) => { + if (item.url && item.url.startsWith("blob:")) { + return { + ...item, + url: await convertBlobUrlToDataUrl(item.url), + }; + } + return item; + }), + ).then((convertedFiles: FileUIPart[]) => { + try { + const result = onSubmit({ text, files: convertedFiles }, event); + + // Handle both sync and async onSubmit + if (result instanceof Promise) { + result + .then(() => { + clear(); + if (usingProvider) { + controller.textInput.clear(); + } + }) + .catch(() => { + // Don't clear on error - user may want to retry + }); + } else { + // Sync function completed without throwing, clear attachments + clear(); + if (usingProvider) { + controller.textInput.clear(); + } + } + } catch (error) { + // Don't clear on error - user may want to retry + } + }); + }; + + // Render with or without local provider + const inner = ( + <> +