mirror of
https://github.com/rowboatlabs/rowboat.git
synced 2026-06-12 19:55:19 +02:00
Add community sharing feature and merge with pre-built templates
This commit is contained in:
parent
62c1230cff
commit
39823d5935
19 changed files with 1813 additions and 259 deletions
|
|
@ -2,7 +2,8 @@
|
|||
import { z } from 'zod';
|
||||
import { container } from "@/di/container";
|
||||
import { redirect } from "next/navigation";
|
||||
import { templates } from "../lib/project_templates";
|
||||
// Fetch library templates from the unified assistant templates repository
|
||||
import { MongoDBAssistantTemplatesRepository } from "@/src/infrastructure/repositories/mongodb.assistant-templates.repository";
|
||||
import { authCheck } from "./auth.actions";
|
||||
import { ApiKey } from "@/src/entities/models/api-key";
|
||||
import { Project } from "@/src/entities/models/project";
|
||||
|
|
@ -40,14 +41,17 @@ const updateLiveWorkflowController = container.resolve<IUpdateLiveWorkflowContro
|
|||
const revertToLiveWorkflowController = container.resolve<IRevertToLiveWorkflowController>('revertToLiveWorkflowController');
|
||||
|
||||
export async function listTemplates() {
|
||||
const templatesArray = Object.entries(templates)
|
||||
.filter(([key]) => key !== 'default') // Exclude the default template
|
||||
.map(([key, template]) => ({
|
||||
id: key,
|
||||
...template
|
||||
}));
|
||||
|
||||
return templatesArray;
|
||||
const repo = new MongoDBAssistantTemplatesRepository();
|
||||
const result = await repo.list({ source: 'library', isPublic: true }, undefined, 100);
|
||||
// Map to the shape expected by callers (tools at top-level)
|
||||
return result.items.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
category: item.category,
|
||||
tools: (item as any).workflow?.tools || [],
|
||||
copilotPrompt: item.copilotPrompt,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function projectAuthCheck(projectId: string) {
|
||||
|
|
|
|||
30
apps/rowboat/app/api/assistant-templates/[id]/like/route.ts
Normal file
30
apps/rowboat/app/api/assistant-templates/[id]/like/route.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { MongoDBAssistantTemplatesRepository } from '@/src/infrastructure/repositories/mongodb.assistant-templates.repository';
|
||||
|
||||
const repo = new MongoDBAssistantTemplatesRepository();
|
||||
|
||||
const ToggleLikeSchema = z.object({
|
||||
guestId: z.string().min(1),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
// Prefer header like existing community route
|
||||
const guestId = req.headers.get('x-guest-id') || undefined;
|
||||
const body = !guestId ? await req.json().catch(() => ({})) : {};
|
||||
const parsed = ToggleLikeSchema.safeParse({ guestId: guestId || body.guestId });
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Missing guestId' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
const result = await repo.toggleLike(id, parsed.data.guestId);
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
console.error('Error toggling like:', error);
|
||||
return NextResponse.json({ error: 'Failed to toggle like' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
18
apps/rowboat/app/api/assistant-templates/[id]/route.ts
Normal file
18
apps/rowboat/app/api/assistant-templates/[id]/route.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { MongoDBAssistantTemplatesRepository } from '@/src/infrastructure/repositories/mongodb.assistant-templates.repository';
|
||||
|
||||
const repo = new MongoDBAssistantTemplatesRepository();
|
||||
|
||||
export async function GET(_req: NextRequest, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await context.params;
|
||||
const item = await repo.fetch(id);
|
||||
if (!item) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
return NextResponse.json(item);
|
||||
} catch (error) {
|
||||
console.error('Error fetching assistant template:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch assistant template' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
16
apps/rowboat/app/api/assistant-templates/categories/route.ts
Normal file
16
apps/rowboat/app/api/assistant-templates/categories/route.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { MongoDBAssistantTemplatesRepository } from '@/src/infrastructure/repositories/mongodb.assistant-templates.repository';
|
||||
|
||||
const repo = new MongoDBAssistantTemplatesRepository();
|
||||
|
||||
export async function GET(_req: NextRequest) {
|
||||
try {
|
||||
const categories = await repo.getCategories();
|
||||
return NextResponse.json({ items: categories });
|
||||
} catch (error) {
|
||||
console.error('Error fetching categories:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch categories' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
130
apps/rowboat/app/api/assistant-templates/route.ts
Normal file
130
apps/rowboat/app/api/assistant-templates/route.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { MongoDBAssistantTemplatesRepository } from '@/src/infrastructure/repositories/mongodb.assistant-templates.repository';
|
||||
import { ensureLibraryTemplatesSeeded } from '@/app/lib/assistant_templates_seed';
|
||||
import { authCheck } from '@/app/actions/auth.actions';
|
||||
import { auth0 } from '@/app/lib/auth0';
|
||||
import { USE_AUTH } from '@/app/lib/feature_flags';
|
||||
|
||||
const repo = new MongoDBAssistantTemplatesRepository();
|
||||
|
||||
const ListSchema = z.object({
|
||||
category: z.string().optional(),
|
||||
search: z.string().optional(),
|
||||
featured: z.boolean().optional(),
|
||||
source: z.enum(['library','community']).optional(),
|
||||
cursor: z.string().optional(),
|
||||
limit: z.number().min(1).max(50).default(20),
|
||||
});
|
||||
|
||||
const CreateSchema = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
description: z.string().min(1).max(500),
|
||||
category: z.string().min(1),
|
||||
tags: z.array(z.string()).max(10),
|
||||
isAnonymous: z.boolean().default(false),
|
||||
workflow: z.any(),
|
||||
copilotPrompt: z.string().optional(),
|
||||
thumbnailUrl: z.string().url().optional(),
|
||||
});
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// Ensure library JSONs are seeded into the unified collection (idempotent)
|
||||
await ensureLibraryTemplatesSeeded();
|
||||
const { searchParams } = new URL(req.url);
|
||||
const params = ListSchema.parse({
|
||||
category: searchParams.get('category') || undefined,
|
||||
search: searchParams.get('search') || undefined,
|
||||
featured: searchParams.get('featured') ? searchParams.get('featured') === 'true' : undefined,
|
||||
source: (searchParams.get('source') as 'library' | 'community') || undefined,
|
||||
cursor: searchParams.get('cursor') || undefined,
|
||||
limit: searchParams.get('limit') ? parseInt(searchParams.get('limit')!) : 20,
|
||||
});
|
||||
|
||||
// If source specified, query that subset; otherwise return combined from the unified collection
|
||||
if (params.source === 'library' || params.source === 'community') {
|
||||
const result = await repo.list({
|
||||
category: params.category,
|
||||
search: params.search,
|
||||
featured: params.featured,
|
||||
isPublic: true,
|
||||
source: params.source,
|
||||
}, params.cursor, params.limit);
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
|
||||
// No source: combine both subsets from the unified collection
|
||||
const [lib, com] = await Promise.all([
|
||||
repo.list({ category: params.category, search: params.search, featured: params.featured, isPublic: true, source: 'library' }, undefined, params.limit),
|
||||
repo.list({ category: params.category, search: params.search, featured: params.featured, isPublic: true, source: 'community' }, undefined, params.limit),
|
||||
]);
|
||||
return NextResponse.json({ items: [...lib.items, ...com.items], nextCursor: null });
|
||||
} catch (error) {
|
||||
console.error('Error listing assistant templates:', error);
|
||||
return NextResponse.json({ error: 'Failed to list assistant templates' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
let user;
|
||||
if (USE_AUTH) {
|
||||
user = await authCheck();
|
||||
} else {
|
||||
user = { id: 'guest', email: 'guest@example.com' };
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const data = CreateSchema.parse(body);
|
||||
|
||||
let authorName = 'Anonymous';
|
||||
let authorEmail: string | undefined;
|
||||
if (USE_AUTH) {
|
||||
try {
|
||||
const { user: auth0User } = await auth0.getSession() || {};
|
||||
if (auth0User) {
|
||||
authorName = auth0User.name ?? auth0User.email ?? 'Anonymous';
|
||||
authorEmail = auth0User.email;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not get Auth0 user info:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (data.isAnonymous) {
|
||||
authorName = 'Anonymous';
|
||||
authorEmail = undefined;
|
||||
}
|
||||
|
||||
const created = await repo.create({
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
category: data.category,
|
||||
authorId: user.id,
|
||||
authorName,
|
||||
authorEmail,
|
||||
isAnonymous: data.isAnonymous,
|
||||
workflow: data.workflow,
|
||||
tags: data.tags,
|
||||
copilotPrompt: data.copilotPrompt,
|
||||
thumbnailUrl: data.thumbnailUrl,
|
||||
downloadCount: 0,
|
||||
likeCount: 0,
|
||||
featured: false,
|
||||
isPublic: true,
|
||||
likes: [],
|
||||
source: 'community',
|
||||
});
|
||||
|
||||
return NextResponse.json(created);
|
||||
} catch (error) {
|
||||
console.error('Error creating assistant template:', error);
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json({ error: 'Invalid request data', details: error.errors }, { status: 400 });
|
||||
}
|
||||
return NextResponse.json({ error: 'Failed to create assistant template' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { templates } from '@/app/lib/project_templates';
|
||||
|
||||
export async function GET() {
|
||||
// The templates are now dynamically loaded from JSON files in the templates folder
|
||||
return NextResponse.json(templates);
|
||||
}
|
||||
52
apps/rowboat/app/lib/assistant_templates_seed.ts
Normal file
52
apps/rowboat/app/lib/assistant_templates_seed.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { db } from "@/app/lib/mongodb";
|
||||
import { prebuiltTemplates } from "@/app/lib/prebuilt-cards";
|
||||
|
||||
// idempotent seed: creates library (prebuilt) templates in DB if missing
|
||||
// Uses name+authorName match to avoid duplicates; tags include a stable prebuilt key
|
||||
export async function ensureLibraryTemplatesSeeded(): Promise<void> {
|
||||
try {
|
||||
const collection = db.collection("assistant_templates");
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const entries = Object.entries(prebuiltTemplates);
|
||||
for (const [prebuiltKey, tpl] of entries) {
|
||||
// minimal guard; only ingest valid workflow-like objects
|
||||
if (!(tpl as any)?.agents || !Array.isArray((tpl as any).agents)) continue;
|
||||
|
||||
const name = (tpl as any).name || prebuiltKey;
|
||||
|
||||
// check if already present (by name + authorName Rowboat and special tag)
|
||||
const existing = await collection.findOne({ name, authorName: "Rowboat", tags: { $in: [ `prebuilt:${prebuiltKey}`, "__library__" ] } });
|
||||
if (existing) continue;
|
||||
|
||||
const doc = {
|
||||
name,
|
||||
description: (tpl as any).description || "",
|
||||
category: (tpl as any).category || "Other",
|
||||
authorId: "rowboat-system",
|
||||
authorName: "Rowboat",
|
||||
authorEmail: undefined,
|
||||
isAnonymous: false,
|
||||
workflow: tpl as any,
|
||||
tags: ["__library__", `prebuilt:${prebuiltKey}`].filter(Boolean),
|
||||
publishedAt: now,
|
||||
lastUpdatedAt: now,
|
||||
downloadCount: 0,
|
||||
likeCount: 0,
|
||||
featured: false,
|
||||
isPublic: true,
|
||||
likes: [] as string[],
|
||||
copilotPrompt: (tpl as any).copilotPrompt || undefined,
|
||||
thumbnailUrl: undefined,
|
||||
source: 'library' as const,
|
||||
} as const;
|
||||
|
||||
await collection.insertOne(doc as any);
|
||||
}
|
||||
} catch (err) {
|
||||
// best-effort seed; do not throw to avoid breaking requests
|
||||
console.error("ensureLibraryTemplatesSeeded error:", err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -1,50 +1,33 @@
|
|||
import { WorkflowTemplate } from "./types/workflow_types";
|
||||
import { z } from 'zod';
|
||||
import { prebuiltTemplates } from './prebuilt-cards';
|
||||
|
||||
const DEFAULT_MODEL = process.env.PROVIDER_DEFAULT_MODEL || "gpt-4.1";
|
||||
|
||||
// Build templates object using static imports so Vercel bundles them
|
||||
function buildTemplates(): { [key: string]: z.infer<typeof WorkflowTemplate> } {
|
||||
const templates: { [key: string]: z.infer<typeof WorkflowTemplate> } = {};
|
||||
|
||||
// Add default template
|
||||
templates['default'] = {
|
||||
name: 'Blank Template',
|
||||
description: 'A blank canvas to build your agents.',
|
||||
startAgent: "",
|
||||
agents: [],
|
||||
prompts: [],
|
||||
tools: [
|
||||
{
|
||||
name: "Generate Image",
|
||||
description: "Generate an image using Google Gemini given a text prompt. Returns base64-encoded image data and any text parts.",
|
||||
isGeminiImage: true,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
prompt: { type: 'string', description: 'Text prompt describing the image to generate' },
|
||||
modelName: { type: 'string', description: 'Optional Gemini model override' },
|
||||
},
|
||||
required: ['prompt'],
|
||||
additionalProperties: true,
|
||||
// Provide a minimal default template to satisfy legacy code paths that
|
||||
// still reference `templates.default`. Real templates are DB-backed.
|
||||
const defaultTemplate: z.infer<typeof WorkflowTemplate> = {
|
||||
name: 'Blank Template',
|
||||
description: 'A blank canvas to build your assistant.',
|
||||
startAgent: "",
|
||||
agents: [],
|
||||
prompts: [],
|
||||
tools: [
|
||||
{
|
||||
name: "Generate Image",
|
||||
description: "Generate an image using Google Gemini given a text prompt. Returns base64-encoded image data and any text parts.",
|
||||
isGeminiImage: true,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
prompt: { type: 'string', description: 'Text prompt describing the image to generate' },
|
||||
modelName: { type: 'string', description: 'Optional Gemini model override' },
|
||||
},
|
||||
required: ['prompt'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
],
|
||||
pipelines: [],
|
||||
};
|
||||
|
||||
// Merge static prebuilt templates
|
||||
Object.entries(prebuiltTemplates).forEach(([key, tpl]) => {
|
||||
// Basic guard to avoid bad entries
|
||||
if ((tpl as any)?.agents && Array.isArray((tpl as any).agents)) {
|
||||
templates[key] = tpl as z.infer<typeof WorkflowTemplate>;
|
||||
}
|
||||
});
|
||||
|
||||
return templates;
|
||||
}
|
||||
|
||||
export const templates: { [key: string]: z.infer<typeof WorkflowTemplate> } = buildTemplates();
|
||||
|
||||
// Note: Prebuilt cards are now loaded from app/lib/prebuilt-cards/ directory
|
||||
// starting_copilot_prompts has been removed as it was unused
|
||||
export const templates: Record<string, z.infer<typeof WorkflowTemplate>> = {
|
||||
default: defaultTemplate,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
"use client";
|
||||
"use client";
|
||||
import React from "react";
|
||||
import { Button, Dropdown, DropdownItem, DropdownMenu, DropdownTrigger, Spinner, Tooltip, Input, ButtonGroup, Checkbox, Modal, ModalContent, ModalHeader, ModalBody, ModalFooter, useDisclosure } from "@heroui/react";
|
||||
import { Button, Dropdown, DropdownItem, DropdownMenu, DropdownTrigger, Spinner, Tooltip, Input, ButtonGroup, Checkbox, Modal, ModalContent, ModalHeader, ModalBody, ModalFooter, useDisclosure, Textarea, Select, SelectItem, Chip, Radio, RadioGroup } from "@heroui/react";
|
||||
import { Button as CustomButton } from "@/components/ui/button";
|
||||
import { RadioIcon, RedoIcon, UndoIcon, RocketIcon, PenLine, AlertTriangle, DownloadIcon, SettingsIcon, ChevronDownIcon, ZapIcon, Clock, Plug, MessageCircleIcon, ShareIcon } from "lucide-react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { ProgressBar, ProgressStep } from "@/components/ui/progress-bar";
|
||||
import { useUser } from '@auth0/nextjs-auth0';
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
interface TopBarProps {
|
||||
localProjectName: string;
|
||||
|
|
@ -42,6 +44,20 @@ interface TopBarProps {
|
|||
onShareWorkflow: () => void;
|
||||
shareUrl: string | null;
|
||||
onCopyShareUrl: () => void;
|
||||
shareMode: 'url' | 'community';
|
||||
setShareMode: (mode: 'url' | 'community') => void;
|
||||
communityData: {
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
tags: string[];
|
||||
isAnonymous: boolean;
|
||||
copilotPrompt: string;
|
||||
};
|
||||
setCommunityData: (data: any) => void;
|
||||
onCommunityPublish: () => void;
|
||||
communityPublishing: boolean;
|
||||
communityPublishSuccess: boolean;
|
||||
}
|
||||
|
||||
export function TopBar({
|
||||
|
|
@ -80,6 +96,13 @@ export function TopBar({
|
|||
onShareWorkflow,
|
||||
shareUrl,
|
||||
onCopyShareUrl,
|
||||
shareMode,
|
||||
setShareMode,
|
||||
communityData,
|
||||
setCommunityData,
|
||||
onCommunityPublish,
|
||||
communityPublishing,
|
||||
communityPublishSuccess,
|
||||
}: TopBarProps) {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
|
|
@ -87,11 +110,37 @@ export function TopBar({
|
|||
|
||||
// Share modal state
|
||||
const { isOpen: isShareModalOpen, onOpen: onShareModalOpen, onClose: onShareModalClose } = useDisclosure();
|
||||
const [copyButtonText, setCopyButtonText] = useState('Copy');
|
||||
|
||||
const handleShareClick = () => {
|
||||
onShareWorkflow(); // Call the original share function to generate URL
|
||||
onShareModalOpen(); // Open the modal
|
||||
};
|
||||
|
||||
const handleCopyUrl = () => {
|
||||
onCopyShareUrl(); // Call the original copy function
|
||||
setCopyButtonText('Copied!');
|
||||
setTimeout(() => {
|
||||
setCopyButtonText('Copy');
|
||||
}, 2000); // Reset after 2 seconds
|
||||
};
|
||||
|
||||
// After successful community publish, briefly show success and then close modal
|
||||
useEffect(() => {
|
||||
if (communityPublishSuccess) {
|
||||
const timer = setTimeout(() => {
|
||||
onShareModalClose();
|
||||
}, 1200);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [communityPublishSuccess, onShareModalClose]);
|
||||
|
||||
const { user } = useUser();
|
||||
|
||||
const getUserDisplayName = () => {
|
||||
if (!user) return 'Anonymous';
|
||||
return user.name ?? user.email ?? 'Anonymous';
|
||||
};
|
||||
|
||||
// Progress bar steps with completion logic and current step detection
|
||||
const step1Complete = hasAgentInstructionChanges;
|
||||
|
|
@ -596,46 +645,205 @@ export function TopBar({
|
|||
</div>
|
||||
|
||||
{/* Share Modal */}
|
||||
<Modal isOpen={isShareModalOpen} onClose={onShareModalClose} size="lg">
|
||||
<Modal
|
||||
isOpen={isShareModalOpen}
|
||||
onClose={onShareModalClose}
|
||||
size="2xl"
|
||||
scrollBehavior="inside"
|
||||
classNames={{
|
||||
base: "bg-white dark:bg-gray-900 max-h-[90vh]",
|
||||
header: "border-b border-gray-200 dark:border-gray-700 pb-4 flex-shrink-0",
|
||||
body: "py-6 overflow-y-auto flex-1",
|
||||
footer: "border-t border-gray-200 dark:border-gray-700 pt-4 flex-shrink-0"
|
||||
}}
|
||||
>
|
||||
<ModalContent>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
Share Assistant
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Share Assistant</h2>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 font-normal">Choose how you'd like to share your assistant</p>
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Share this assistant with others using the URL below:
|
||||
</p>
|
||||
{shareUrl ? (
|
||||
<div className="flex items-center gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<input
|
||||
type="text"
|
||||
value={shareUrl || ''}
|
||||
readOnly
|
||||
className="flex-1 bg-transparent text-sm text-gray-700 dark:text-gray-300 outline-none"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="solid"
|
||||
onPress={onCopyShareUrl}
|
||||
className="bg-indigo-100 hover:bg-indigo-200 text-indigo-800"
|
||||
>
|
||||
Copy
|
||||
</Button>
|
||||
<div className="space-y-8">
|
||||
{/* Quick Share Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
|
||||
<ShareIcon size={16} className="text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-medium text-gray-900 dark:text-gray-100">Quick Share</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Share with a direct link</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<Spinner size="sm" />
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Generating share URL...
|
||||
</span>
|
||||
|
||||
{shareUrl ? (
|
||||
<div className="flex items-center gap-3 p-4 bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex-1 min-w-0">
|
||||
<input
|
||||
type="text"
|
||||
value={shareUrl || ''}
|
||||
readOnly
|
||||
className="w-full bg-transparent text-sm text-gray-700 dark:text-gray-300 outline-none font-mono focus:outline-none !focus:ring-0 !focus:ring-offset-0 !ring-0 !ring-offset-0"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="solid"
|
||||
onPress={handleCopyUrl}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium"
|
||||
>
|
||||
{copyButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 p-4 bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700">
|
||||
<Spinner size="sm" />
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Generating share URL...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-200 dark:border-gray-700"></div>
|
||||
</div>
|
||||
)}
|
||||
<div className="relative flex justify-center">
|
||||
<span className="px-4 bg-white dark:bg-gray-900 text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider">or</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Community Publishing Section */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
|
||||
<MessageCircleIcon size={16} className="text-purple-600 dark:text-purple-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-medium text-gray-900 dark:text-gray-100">Publish to Community</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Make it discoverable by others</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-5">
|
||||
{/* Assistant Name */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Assistant Name <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Input
|
||||
placeholder="Enter assistant name"
|
||||
value={communityData.name}
|
||||
onChange={(e) => setCommunityData({ ...communityData, name: e.target.value })}
|
||||
classNames={{
|
||||
input: "text-sm focus:outline-none !focus:ring-0 !focus:ring-offset-0 !ring-0 !ring-offset-0",
|
||||
inputWrapper: "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 focus-within:border-gray-300 dark:focus-within:border-gray-500 !focus-within:ring-0 !focus-within:ring-offset-0 !ring-0 !ring-offset-0"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Description <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Textarea
|
||||
placeholder="Describe what this assistant does..."
|
||||
value={communityData.description}
|
||||
onChange={(e) => setCommunityData({ ...communityData, description: e.target.value })}
|
||||
minRows={3}
|
||||
classNames={{
|
||||
input: "text-sm focus:outline-none !focus:ring-0 !focus:ring-offset-0 !ring-0 !ring-offset-0",
|
||||
inputWrapper: "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 focus-within:border-gray-300 dark:focus-within:border-gray-500 !focus-within:ring-0 !focus-within:ring-offset-0 !ring-0 !ring-offset-0"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Category */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Category <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Select
|
||||
placeholder="Select a category"
|
||||
selectedKeys={communityData.category ? [communityData.category] : []}
|
||||
onSelectionChange={(keys) => {
|
||||
const selected = Array.from(keys)[0] as string;
|
||||
setCommunityData({ ...communityData, category: selected });
|
||||
}}
|
||||
classNames={{
|
||||
trigger: "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 focus:outline-none !focus:ring-0 !focus:ring-offset-0 !ring-0 !ring-offset-0 focus-within:border-gray-300 dark:focus-within:border-gray-500 !focus-within:ring-0 !focus-within:ring-offset-0",
|
||||
value: "text-sm"
|
||||
}}
|
||||
>
|
||||
<SelectItem key="Work Productivity">Work Productivity</SelectItem>
|
||||
<SelectItem key="Developer Productivity">Developer Productivity</SelectItem>
|
||||
<SelectItem key="News & Social">News & Social</SelectItem>
|
||||
<SelectItem key="Customer Support">Customer Support</SelectItem>
|
||||
<SelectItem key="Education">Education</SelectItem>
|
||||
<SelectItem key="Entertainment">Entertainment</SelectItem>
|
||||
<SelectItem key="Other">Other</SelectItem>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Privacy Toggle */}
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800/30 rounded-xl border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100 mb-1">
|
||||
{communityData.isAnonymous ? 'Publish anonymously' : `Publish as ${getUserDisplayName()}`}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{communityData.isAnonymous ? 'Your name will be hidden from the community' : 'Your name will be visible to the community'}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCommunityData({ ...communityData, isAnonymous: !communityData.isAnonymous })}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
|
||||
communityData.isAnonymous ? 'bg-gray-300 dark:bg-gray-600' : 'bg-blue-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
communityData.isAnonymous ? 'translate-x-1' : 'translate-x-6'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Success Message */}
|
||||
{communityPublishSuccess && (
|
||||
<div className="flex items-center gap-3 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-xl">
|
||||
<div className="w-5 h-5 rounded-full bg-green-100 dark:bg-green-900/40 flex items-center justify-center">
|
||||
<span className="text-green-600 dark:text-green-400 text-xs">✓</span>
|
||||
</div>
|
||||
<p className="text-green-700 dark:text-green-300 text-sm font-medium">
|
||||
Successfully published to community!
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onPress={onShareModalClose}>
|
||||
Close
|
||||
<ModalFooter className="gap-3">
|
||||
<Button
|
||||
variant="light"
|
||||
onPress={onShareModalClose}
|
||||
className="px-6 py-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
color={communityPublishSuccess ? "success" : "primary"}
|
||||
onPress={onCommunityPublish}
|
||||
isLoading={communityPublishing}
|
||||
isDisabled={communityPublishSuccess || !communityData.name.trim() || !communityData.description.trim() || !communityData.category}
|
||||
className={`${communityPublishSuccess ? 'bg-green-600 hover:bg-green-700' : 'bg-blue-600 hover:bg-blue-700'} px-6 py-2 text-white font-medium`}
|
||||
>
|
||||
{communityPublishSuccess ? 'Published' : (communityPublishing ? 'Publishing...' : 'Publish to Community')}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
|
|
|
|||
|
|
@ -1633,6 +1633,51 @@ export function WorkflowEditor({
|
|||
setTimeout(() => setShowCopySuccess(false), 2000);
|
||||
}
|
||||
|
||||
// Community publishing functions
|
||||
const [shareMode, setShareMode] = useState<'url' | 'community'>('url');
|
||||
const [communityData, setCommunityData] = useState({
|
||||
name: projectConfig.name || '',
|
||||
description: '',
|
||||
category: '',
|
||||
tags: [] as string[],
|
||||
isAnonymous: false,
|
||||
copilotPrompt: '',
|
||||
});
|
||||
const [communityPublishing, setCommunityPublishing] = useState(false);
|
||||
const [communityPublishSuccess, setCommunityPublishSuccess] = useState(false);
|
||||
|
||||
const handleCommunityPublish = async () => {
|
||||
if (!communityData.name.trim() || !communityData.description.trim() || !communityData.category) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCommunityPublishing(true);
|
||||
try {
|
||||
const response = await fetch('/api/assistant-templates', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...communityData,
|
||||
workflow: state.present.workflow, // Use the current workflow
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to publish to community');
|
||||
}
|
||||
|
||||
setCommunityPublishSuccess(true);
|
||||
setTimeout(() => {
|
||||
setCommunityPublishSuccess(false);
|
||||
// Close modal or reset
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error('Error publishing to community:', error);
|
||||
} finally {
|
||||
setCommunityPublishing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Cleanup blob URL on unmount
|
||||
// No-op cleanup; shareUrl is a normal URL now
|
||||
|
||||
|
|
@ -1949,6 +1994,13 @@ export function WorkflowEditor({
|
|||
onShareWorkflow={handleShareWorkflow}
|
||||
shareUrl={shareUrl}
|
||||
onCopyShareUrl={handleCopyShareUrl}
|
||||
shareMode={shareMode}
|
||||
setShareMode={setShareMode}
|
||||
communityData={communityData}
|
||||
setCommunityData={setCommunityData}
|
||||
onCommunityPublish={handleCommunityPublish}
|
||||
communityPublishing={communityPublishing}
|
||||
communityPublishSuccess={communityPublishSuccess}
|
||||
onPublishWorkflow={handlePublishWorkflow}
|
||||
onChangeMode={onChangeMode}
|
||||
onRevertToLive={handleRevertToLive}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ import { Tabs, Tab } from "@/components/ui/tabs";
|
|||
import { Project } from "@/src/entities/models/project";
|
||||
import { z } from "zod";
|
||||
import Link from 'next/link';
|
||||
import { AssistantSection } from '@/components/common/AssistantSection';
|
||||
import { UnifiedTemplatesSection } from '@/components/common/UnifiedTemplatesSection';
|
||||
|
||||
const SHOW_PREBUILT_CARDS = process.env.NEXT_PUBLIC_SHOW_PREBUILT_CARDS !== 'false';
|
||||
|
||||
|
|
@ -51,6 +53,9 @@ export function BuildAssistantSection() {
|
|||
const [templates, setTemplates] = useState<any[]>([]);
|
||||
const [templatesLoading, setTemplatesLoading] = useState(false);
|
||||
const [templatesError, setTemplatesError] = useState<string | null>(null);
|
||||
const [communityTemplates, setCommunityTemplates] = useState<any[]>([]);
|
||||
const [communityTemplatesLoading, setCommunityTemplatesLoading] = useState(false);
|
||||
const [communityTemplatesError, setCommunityTemplatesError] = useState<string | null>(null);
|
||||
const [projects, setProjects] = useState<z.infer<typeof Project>[]>([]);
|
||||
const [projectsLoading, setProjectsLoading] = useState(false);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
|
@ -102,27 +107,127 @@ export function BuildAssistantSection() {
|
|||
}
|
||||
};
|
||||
|
||||
const fetchCommunityTemplates = async () => {
|
||||
setCommunityTemplatesLoading(true);
|
||||
setCommunityTemplatesError(null);
|
||||
try {
|
||||
const response = await fetch('/api/assistant-templates?source=community');
|
||||
if (!response.ok) throw new Error('Failed to fetch community templates');
|
||||
const data = await response.json();
|
||||
setCommunityTemplates(data.items || []);
|
||||
} catch (error) {
|
||||
console.error('Error fetching community templates:', error);
|
||||
setCommunityTemplatesError(error instanceof Error ? error.message : 'Failed to load community templates');
|
||||
} finally {
|
||||
setCommunityTemplatesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle template selection
|
||||
const handleTemplateSelect = async (template: any) => {
|
||||
// Show a small non-blocking spinner on the clicked card
|
||||
setLoadingTemplateId(template.id);
|
||||
try {
|
||||
await createProjectWithOptions({
|
||||
template: template.id,
|
||||
// Prefer a card-specific copilot prompt if present on the template JSON
|
||||
prompt: template.copilotPrompt || 'Explain this workflow',
|
||||
router,
|
||||
onError: () => {
|
||||
// Clear loading state if creation fails
|
||||
setLoadingTemplateId(null);
|
||||
},
|
||||
});
|
||||
if (template.type === 'prebuilt') {
|
||||
// Fetch full workflow from unified API, then create from JSON
|
||||
const res = await fetch(`/api/assistant-templates/${template.id}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch template details');
|
||||
const data = await res.json();
|
||||
await createProjectFromJsonWithOptions({
|
||||
workflowJson: JSON.stringify(data.workflow),
|
||||
router,
|
||||
onSuccess: (_projectId) => {},
|
||||
onError: () => {
|
||||
setLoadingTemplateId(null);
|
||||
}
|
||||
});
|
||||
} else if (template.type === 'community') {
|
||||
// Handle community template import
|
||||
await createProjectFromJsonWithOptions({
|
||||
workflowJson: JSON.stringify(template.workflow),
|
||||
router,
|
||||
onSuccess: (projectId) => {
|
||||
router.push(`/projects/${projectId}/workflow`);
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Error creating project from community template:', error);
|
||||
setLoadingTemplateId(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (_err) {
|
||||
// In case of unexpected error, clear loading state
|
||||
setLoadingTemplateId(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Stable guest id for like toggles
|
||||
const getGuestId = () => {
|
||||
try {
|
||||
let guestId = sessionStorage.getItem('guestId');
|
||||
if (!guestId) {
|
||||
guestId = `guest-${crypto.randomUUID()}`;
|
||||
sessionStorage.setItem('guestId', guestId);
|
||||
}
|
||||
return guestId;
|
||||
} catch (_e) {
|
||||
return `guest-${crypto.randomUUID()}`;
|
||||
}
|
||||
};
|
||||
|
||||
// Handle template like (unified for library and community)
|
||||
const handleTemplateLike = async (template: any) => {
|
||||
try {
|
||||
const guestId = getGuestId();
|
||||
const response = await fetch(`/api/assistant-templates/${template.id}/like`, {
|
||||
method: 'POST',
|
||||
headers: { 'x-guest-id': guestId },
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (template.type === 'community') {
|
||||
setCommunityTemplates(prev => prev.map(t =>
|
||||
t.id === template.id
|
||||
? { ...t, likeCount: data.likeCount, isLiked: data.liked }
|
||||
: t
|
||||
));
|
||||
} else {
|
||||
setTemplates(prev => prev.map(t =>
|
||||
t.id === template.id
|
||||
? { ...t, likeCount: data.likeCount, isLiked: data.liked } as any
|
||||
: t
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error toggling like:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle template share (for both library and community)
|
||||
const handleTemplateShare = async (template: any) => {
|
||||
try {
|
||||
// Fetch workflow for the template and create a shared snapshot
|
||||
const res = await fetch(`/api/assistant-templates/${template.id}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch template for sharing');
|
||||
const data = await res.json();
|
||||
|
||||
const shareResp = await fetch('/api/shared-workflow', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ workflow: data.workflow }),
|
||||
});
|
||||
if (!shareResp.ok) throw new Error('Failed to create shared workflow');
|
||||
const shareData = await shareResp.json();
|
||||
const url = `${window.location.origin}/projects?shared=${shareData.id}`;
|
||||
await navigator.clipboard.writeText(url);
|
||||
console.log('URL copied to clipboard');
|
||||
} catch (err) {
|
||||
console.error('Failed to copy shared URL:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle prompt card selection
|
||||
const handlePromptSelect = (promptText: string) => {
|
||||
setUserPrompt(promptText);
|
||||
|
|
@ -146,6 +251,7 @@ export function BuildAssistantSection() {
|
|||
|
||||
useEffect(() => {
|
||||
fetchTemplates();
|
||||
fetchCommunityTemplates();
|
||||
fetchProjects();
|
||||
}, []);
|
||||
|
||||
|
|
@ -184,19 +290,40 @@ export function BuildAssistantSection() {
|
|||
|
||||
if (urlPrompt || urlTemplate) {
|
||||
setAutoCreateLoading(true);
|
||||
createProjectWithOptions({
|
||||
template: urlTemplate || undefined,
|
||||
prompt: urlPrompt || undefined,
|
||||
router,
|
||||
onError: (error) => {
|
||||
console.error('Error auto-creating project:', error);
|
||||
setAutoCreateLoading(false);
|
||||
// Fall back to showing the form with the prompt pre-filled
|
||||
if (urlPrompt) {
|
||||
setUserPrompt(urlPrompt);
|
||||
}
|
||||
try {
|
||||
const isMongoId = !!urlTemplate && /^[a-f0-9]{24}$/i.test(urlTemplate);
|
||||
if (urlTemplate && isMongoId) {
|
||||
// New-style share: template is an assistant-templates id
|
||||
const res = await fetch(`/api/assistant-templates/${urlTemplate}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch shared template');
|
||||
const data = await res.json();
|
||||
await createProjectFromJsonWithOptions({
|
||||
workflowJson: JSON.stringify(data.workflow),
|
||||
router,
|
||||
onError: (error) => {
|
||||
console.error('Error auto-creating project from template id:', error);
|
||||
setAutoCreateLoading(false);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Legacy share using static key
|
||||
await createProjectWithOptions({
|
||||
template: urlTemplate || undefined,
|
||||
prompt: urlPrompt || undefined,
|
||||
router,
|
||||
onError: (error) => {
|
||||
console.error('Error auto-creating project:', error);
|
||||
setAutoCreateLoading(false);
|
||||
if (urlPrompt) {
|
||||
setUserPrompt(urlPrompt);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error handling template auto-create:', err);
|
||||
setAutoCreateLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -291,7 +418,9 @@ export function BuildAssistantSection() {
|
|||
{/* Tabs Section */}
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<div className="p-6 pb-0">
|
||||
<Tabs defaultSelectedKey="new" selectedKey={selectedTab} onSelectionChange={(key) => setSelectedTab(key as string)} className="w-full">
|
||||
<Tabs defaultSelectedKey="new" selectedKey={selectedTab} onSelectionChange={(key) => {
|
||||
setSelectedTab(key as string);
|
||||
}} className="w-full">
|
||||
<Tab key="new" title="New Assistant">
|
||||
<div className="pt-4">
|
||||
<div className="flex items-center gap-12">
|
||||
|
|
@ -460,151 +589,45 @@ export function BuildAssistantSection() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pre-built Assistants Section - Only show for New Assistant tab */}
|
||||
{/* Unified Templates Section - Only show for New Assistant tab */}
|
||||
{selectedTab === 'new' && SHOW_PREBUILT_CARDS && (
|
||||
<div className="max-w-5xl mx-auto mt-16">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
Prebuilt Assistants
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Start quickly and let Skipper adapt it to your needs.
|
||||
</p>
|
||||
</div>
|
||||
{templatesLoading ? (
|
||||
<div className="flex items-center justify-center py-12 text-sm text-gray-500 dark:text-gray-400">
|
||||
Loading pre-built assistants...
|
||||
</div>
|
||||
) : templatesError ? (
|
||||
<div className="flex items-center justify-center py-12 text-sm text-red-500 dark:text-red-400">
|
||||
Error: {templatesError}
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12 text-sm text-gray-500 dark:text-gray-400">
|
||||
No pre-built assistants available
|
||||
</div>
|
||||
) : (
|
||||
(() => {
|
||||
const workTemplates = templates.filter((t) => (t.category || '').toLowerCase() === 'work productivity');
|
||||
const devTemplates = templates.filter((t) => (t.category || '').toLowerCase() === 'developer productivity');
|
||||
const newsTemplates = templates.filter((t) => (t.category || '').toLowerCase() === 'news & social');
|
||||
const customerSupportTemplates = templates.filter((t) => (t.category || '').toLowerCase() === 'support');
|
||||
|
||||
const renderGrid = (items: any[]) => (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{items.map((template) => (
|
||||
<button
|
||||
key={template.id}
|
||||
onClick={() => handleTemplateSelect(template)}
|
||||
disabled={loadingTemplateId === template.id}
|
||||
className={clsx(
|
||||
"relative block p-4 border border-gray-200 dark:border-gray-700 rounded-xl transition-all group text-left",
|
||||
"hover:border-blue-300 dark:hover:border-blue-600 hover:bg-gray-50 dark:hover:bg-gray-700/50 hover:shadow-md",
|
||||
loadingTemplateId === template.id && "opacity-90 cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors line-clamp-1">
|
||||
{template.name}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
|
||||
{template.description}
|
||||
</div>
|
||||
|
||||
{(() => {
|
||||
const tools = getUniqueTools(template);
|
||||
return tools.length > 0 && (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<div className="text-xs text-gray-400 dark:text-gray-500">
|
||||
Tools:
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{tools.slice(0, 4).map((tool) => (
|
||||
tool.logo && (
|
||||
<PictureImg
|
||||
key={tool.name}
|
||||
src={tool.logo}
|
||||
alt={`${tool.name} logo`}
|
||||
className="w-4 h-4 rounded-sm object-cover flex-shrink-0"
|
||||
title={tool.name}
|
||||
/>
|
||||
)
|
||||
))}
|
||||
{tools.length > 4 && (
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">
|
||||
+{tools.length - 4}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
<div className="flex items-center justify-between mt-2">
|
||||
<div className="text-xs text-gray-400 dark:text-gray-500"></div>
|
||||
{loadingTemplateId === template.id ? (
|
||||
<div className="text-blue-600 dark:text-blue-400">
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-current"></div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-2 h-2 rounded-full bg-blue-500 opacity-75"></div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{workTemplates.length > 0 && (
|
||||
<div>
|
||||
<div className="mb-3">
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700 ring-1 ring-amber-200 dark:bg-amber-400/10 dark:text-amber-300 dark:ring-amber-400/30">
|
||||
Work Productivity
|
||||
</span>
|
||||
</div>
|
||||
{renderGrid(workTemplates)}
|
||||
</div>
|
||||
)}
|
||||
{devTemplates.length > 0 && (
|
||||
<div>
|
||||
<div className="mb-3">
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-indigo-50 text-indigo-700 ring-1 ring-indigo-200 dark:bg-indigo-400/10 dark:text-indigo-300 dark:ring-indigo-400/30">
|
||||
Developer Productivity
|
||||
</span>
|
||||
</div>
|
||||
{renderGrid(devTemplates)}
|
||||
</div>
|
||||
)}
|
||||
{newsTemplates.length > 0 && (
|
||||
<div>
|
||||
<div className="mb-3">
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-green-50 text-green-700 ring-1 ring-green-200 dark:bg-green-400/10 dark:text-green-300 dark:ring-green-400/30">
|
||||
News & Social
|
||||
</span>
|
||||
</div>
|
||||
{renderGrid(newsTemplates)}
|
||||
</div>
|
||||
)}
|
||||
{customerSupportTemplates.length > 0 && (
|
||||
<div>
|
||||
<div className="mb-3">
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-red-50 text-red-700 ring-1 ring-red-200 dark:bg-red-400/10 dark:text-red-300 dark:ring-red-400/30">
|
||||
Support
|
||||
</span>
|
||||
</div>
|
||||
{renderGrid(customerSupportTemplates)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()
|
||||
)}
|
||||
<UnifiedTemplatesSection
|
||||
prebuiltTemplates={templates.map(template => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
category: template.category || 'Other',
|
||||
tools: template.tools,
|
||||
type: 'prebuilt' as const,
|
||||
likeCount: (template as any).likeCount || 0,
|
||||
isLiked: (template as any).isLiked || false,
|
||||
}))}
|
||||
communityTemplates={communityTemplates.map(template => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
category: template.category,
|
||||
authorName: template.authorName,
|
||||
isAnonymous: template.isAnonymous,
|
||||
likeCount: template.likeCount,
|
||||
createdAt: template.publishedAt,
|
||||
isLiked: template.isLiked,
|
||||
type: 'community' as const,
|
||||
}))}
|
||||
loading={templatesLoading || communityTemplatesLoading}
|
||||
error={templatesError || communityTemplatesError}
|
||||
onTemplateClick={handleTemplateSelect}
|
||||
onRetry={() => {
|
||||
fetchTemplates();
|
||||
fetchCommunityTemplates();
|
||||
}}
|
||||
loadingItemId={loadingTemplateId}
|
||||
onLike={handleTemplateLike}
|
||||
onShare={handleTemplateShare}
|
||||
getUniqueTools={getUniqueTools}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
277
apps/rowboat/components/common/AssistantCard.tsx
Normal file
277
apps/rowboat/components/common/AssistantCard.tsx
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { clsx } from 'clsx';
|
||||
import { PictureImg } from '@/components/ui/picture-img';
|
||||
import { Heart, Share2, Calendar } from 'lucide-react';
|
||||
|
||||
// Helper function to get relative time
|
||||
const getRelativeTime = (dateString: string): string => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
|
||||
if (diffInSeconds < 60) {
|
||||
return 'just now';
|
||||
}
|
||||
|
||||
const diffInMinutes = Math.floor(diffInSeconds / 60);
|
||||
if (diffInMinutes < 60) {
|
||||
return `${diffInMinutes} minute${diffInMinutes === 1 ? '' : 's'} ago`;
|
||||
}
|
||||
|
||||
const diffInHours = Math.floor(diffInMinutes / 60);
|
||||
if (diffInHours < 24) {
|
||||
return `${diffInHours} hour${diffInHours === 1 ? '' : 's'} ago`;
|
||||
}
|
||||
|
||||
const diffInDays = Math.floor(diffInHours / 24);
|
||||
if (diffInDays < 7) {
|
||||
return `${diffInDays} day${diffInDays === 1 ? '' : 's'} ago`;
|
||||
}
|
||||
|
||||
const diffInWeeks = Math.floor(diffInDays / 7);
|
||||
if (diffInWeeks < 4) {
|
||||
return `${diffInWeeks} week${diffInWeeks === 1 ? '' : 's'} ago`;
|
||||
}
|
||||
|
||||
const diffInMonths = Math.floor(diffInDays / 30);
|
||||
if (diffInMonths < 12) {
|
||||
return `${diffInMonths} month${diffInMonths === 1 ? '' : 's'} ago`;
|
||||
}
|
||||
|
||||
const diffInYears = Math.floor(diffInDays / 365);
|
||||
return `${diffInYears} year${diffInYears === 1 ? '' : 's'} ago`;
|
||||
};
|
||||
|
||||
interface AssistantCardProps {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
tools?: Array<{
|
||||
name: string;
|
||||
logo?: string;
|
||||
}>;
|
||||
// Community-specific props
|
||||
authorName?: string;
|
||||
isAnonymous?: boolean;
|
||||
likeCount?: number;
|
||||
createdAt?: string;
|
||||
onLike?: () => void;
|
||||
onShare?: () => void;
|
||||
isLiked?: boolean;
|
||||
// Template type indicator
|
||||
templateType?: 'prebuilt' | 'community';
|
||||
// Common props
|
||||
onClick?: () => void;
|
||||
loading?: boolean;
|
||||
disabled?: boolean;
|
||||
getUniqueTools?: (item: any) => Array<{ name: string; logo?: string }>;
|
||||
}
|
||||
|
||||
export function AssistantCard({
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
category,
|
||||
tools = [],
|
||||
authorName,
|
||||
isAnonymous = false,
|
||||
likeCount = 0,
|
||||
createdAt,
|
||||
onLike,
|
||||
onShare,
|
||||
isLiked = false,
|
||||
templateType,
|
||||
onClick,
|
||||
loading = false,
|
||||
disabled = false,
|
||||
getUniqueTools
|
||||
}: AssistantCardProps) {
|
||||
const displayTools = getUniqueTools ? getUniqueTools({ tools }) : tools;
|
||||
const [isDescriptionExpanded, setIsDescriptionExpanded] = React.useState(false);
|
||||
const [showDescriptionToggle, setShowDescriptionToggle] = React.useState(false);
|
||||
const descriptionRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const [copied, setCopied] = React.useState(false);
|
||||
React.useEffect(() => {
|
||||
let t: any;
|
||||
if (copied) {
|
||||
t = setTimeout(() => setCopied(false), 1500);
|
||||
}
|
||||
return () => t && clearTimeout(t);
|
||||
}, [copied]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const el = descriptionRef.current;
|
||||
if (!el) return;
|
||||
// Measure if truncated (only when collapsed)
|
||||
if (!isDescriptionExpanded) {
|
||||
setShowDescriptionToggle(el.scrollHeight > el.clientHeight + 1);
|
||||
} else {
|
||||
setShowDescriptionToggle(true);
|
||||
}
|
||||
}, [description, isDescriptionExpanded]);
|
||||
|
||||
const getCategoryColor = (category: string) => {
|
||||
const lowerCategory = category.toLowerCase();
|
||||
if (lowerCategory.includes('work productivity')) {
|
||||
return 'bg-amber-50 text-amber-700 ring-1 ring-amber-200 dark:bg-amber-400/10 dark:text-amber-300 dark:ring-amber-400/30';
|
||||
} else if (lowerCategory.includes('developer productivity')) {
|
||||
return 'bg-indigo-50 text-indigo-700 ring-1 ring-indigo-200 dark:bg-indigo-400/10 dark:text-indigo-300 dark:ring-indigo-400/30';
|
||||
} else if (lowerCategory.includes('news') || lowerCategory.includes('social')) {
|
||||
return 'bg-green-50 text-green-700 ring-1 ring-green-200 dark:bg-green-400/10 dark:text-green-300 dark:ring-green-400/30';
|
||||
} else if (lowerCategory.includes('customer support')) {
|
||||
return 'bg-red-50 text-red-700 ring-1 ring-red-200 dark:bg-red-400/10 dark:text-red-300 dark:ring-red-400/30';
|
||||
} else if (lowerCategory.includes('education')) {
|
||||
return 'bg-blue-50 text-blue-700 ring-1 ring-blue-200 dark:bg-blue-400/10 dark:text-blue-300 dark:ring-blue-400/30';
|
||||
} else if (lowerCategory.includes('entertainment')) {
|
||||
return 'bg-purple-50 text-purple-700 ring-1 ring-purple-200 dark:bg-purple-400/10 dark:text-purple-300 dark:ring-purple-400/30';
|
||||
} else {
|
||||
return 'bg-gray-50 text-gray-700 ring-1 ring-gray-200 dark:bg-gray-400/10 dark:text-gray-300 dark:ring-gray-400/30';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={onClick}
|
||||
className={clsx(
|
||||
"relative block p-4 border border-gray-200 dark:border-gray-700 rounded-xl transition-all group text-left cursor-pointer",
|
||||
"hover:border-blue-300 dark:hover:border-blue-600 hover:bg-gray-50 dark:hover:bg-gray-700/50 hover:shadow-md",
|
||||
loading && "opacity-90 cursor-not-allowed",
|
||||
disabled && "opacity-50 cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{/* Title and Description */}
|
||||
<div>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors line-clamp-1 flex-1">
|
||||
{name}
|
||||
</div>
|
||||
{/* Template Type Badge */}
|
||||
{templateType && (
|
||||
<span className={clsx(
|
||||
"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0",
|
||||
templateType === 'prebuilt'
|
||||
? "bg-blue-50 text-blue-700 dark:bg-blue-400/10 dark:text-blue-300"
|
||||
: "bg-purple-50 text-purple-700 dark:bg-purple-400/10 dark:text-purple-300"
|
||||
)}>
|
||||
{templateType === 'prebuilt' ? 'Library' : 'Community'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<div
|
||||
ref={descriptionRef}
|
||||
className={clsx(
|
||||
"text-sm leading-5 text-gray-600 dark:text-gray-400 relative min-h-[3.75rem]",
|
||||
!isDescriptionExpanded && "line-clamp-2"
|
||||
)}
|
||||
>
|
||||
{description}
|
||||
</div>
|
||||
{showDescriptionToggle && (
|
||||
<button
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); setIsDescriptionExpanded(!isDescriptionExpanded); }}
|
||||
className="mt-1 text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
aria-label={isDescriptionExpanded ? "Show less" : "Read more"}
|
||||
>
|
||||
{isDescriptionExpanded ? 'Show less' : 'Read more'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Badge */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className={clsx(
|
||||
"inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold",
|
||||
getCategoryColor(category)
|
||||
)}>
|
||||
{category}
|
||||
</span>
|
||||
{loading && (
|
||||
<div className="text-blue-600 dark:text-blue-400">
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-current"></div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tools (reserve row height even when absent to align cards) */}
|
||||
<div className="flex items-center gap-2 min-h-[20px]">
|
||||
{displayTools.length > 0 && (
|
||||
<>
|
||||
<div className="text-xs text-gray-400 dark:text-gray-500">
|
||||
Tools:
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{displayTools.slice(0, 4).map((tool) => (
|
||||
tool.logo && (
|
||||
<PictureImg
|
||||
key={tool.name}
|
||||
src={tool.logo}
|
||||
alt={`${tool.name} logo`}
|
||||
className="w-4 h-4 rounded-sm object-cover flex-shrink-0"
|
||||
title={tool.name}
|
||||
/>
|
||||
)
|
||||
))}
|
||||
{displayTools.length > 4 && (
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">
|
||||
+{displayTools.length - 4}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Author and interaction info */}
|
||||
<div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>
|
||||
{authorName ? (isAnonymous ? 'Anonymous' : authorName) : 'Rowboat'}
|
||||
</span>
|
||||
{createdAt && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar size={12} />
|
||||
<span>{getRelativeTime(createdAt)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onLike?.();
|
||||
}}
|
||||
className={clsx(
|
||||
"flex items-center gap-1 hover:text-red-500 transition-colors",
|
||||
isLiked && "text-red-500"
|
||||
)}
|
||||
>
|
||||
<Heart size={14} className={isLiked ? "fill-current" : ""} />
|
||||
<span>{likeCount || 0}</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setCopied(true);
|
||||
onShare?.();
|
||||
}}
|
||||
className="flex items-center gap-1 hover:text-blue-500 transition-colors"
|
||||
aria-label="Copy share URL"
|
||||
>
|
||||
<Share2 size={14} className={copied ? "text-blue-600" : undefined} />
|
||||
{copied && <span className="text-[10px] text-blue-600">Copied</span>}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
238
apps/rowboat/components/common/AssistantSection.tsx
Normal file
238
apps/rowboat/components/common/AssistantSection.tsx
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Input } from "@heroui/react";
|
||||
import { Search } from 'lucide-react';
|
||||
import { AssistantCard } from './AssistantCard';
|
||||
|
||||
interface AssistantItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
tools?: Array<{
|
||||
name: string;
|
||||
logo?: string;
|
||||
}>;
|
||||
// Community-specific
|
||||
authorName?: string;
|
||||
isAnonymous?: boolean;
|
||||
likeCount?: number;
|
||||
createdAt?: string;
|
||||
isLiked?: boolean;
|
||||
}
|
||||
|
||||
interface AssistantSectionProps {
|
||||
title: string;
|
||||
description: string;
|
||||
items: AssistantItem[];
|
||||
loading?: boolean;
|
||||
error?: string | null;
|
||||
onItemClick?: (item: AssistantItem) => void;
|
||||
onRetry?: () => void;
|
||||
loadingItemId?: string | null;
|
||||
emptyMessage?: string;
|
||||
// Community-specific callbacks
|
||||
onLike?: (item: AssistantItem) => void;
|
||||
onShare?: (item: AssistantItem) => void;
|
||||
// Pre-built specific
|
||||
getUniqueTools?: (item: AssistantItem) => Array<{ name: string; logo?: string }>;
|
||||
// Filter state
|
||||
initialSearchQuery?: string;
|
||||
initialSelectedCategory?: string;
|
||||
onFiltersChange?: (filters: {
|
||||
searchQuery: string;
|
||||
selectedCategory: string;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
|
||||
export function AssistantSection({
|
||||
title,
|
||||
description,
|
||||
items,
|
||||
loading = false,
|
||||
error = null,
|
||||
onItemClick,
|
||||
onRetry,
|
||||
loadingItemId = null,
|
||||
emptyMessage = "No assistants available",
|
||||
onLike,
|
||||
onShare,
|
||||
getUniqueTools,
|
||||
initialSearchQuery = '',
|
||||
initialSelectedCategory = '',
|
||||
onFiltersChange
|
||||
}: AssistantSectionProps) {
|
||||
const [searchQuery, setSearchQuery] = useState(initialSearchQuery);
|
||||
const [selectedCategory, setSelectedCategory] = useState(initialSelectedCategory);
|
||||
|
||||
// Notify parent of filter changes if callback provided
|
||||
useEffect(() => {
|
||||
if (onFiltersChange) {
|
||||
onFiltersChange({
|
||||
searchQuery,
|
||||
selectedCategory
|
||||
});
|
||||
}
|
||||
}, [searchQuery, selectedCategory, onFiltersChange]);
|
||||
|
||||
// Get available categories from items
|
||||
const availableCategories = React.useMemo(() => {
|
||||
const categories = new Set(items.map(item => item.category));
|
||||
return Array.from(categories).sort();
|
||||
}, [items]);
|
||||
|
||||
// Filter items
|
||||
const filteredItems = React.useMemo(() => {
|
||||
let filtered = [...items];
|
||||
|
||||
// Apply search filter
|
||||
if (searchQuery) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
filtered = filtered.filter(item =>
|
||||
item.name.toLowerCase().includes(query) ||
|
||||
item.description.toLowerCase().includes(query) ||
|
||||
item.category.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
// Apply category filter
|
||||
if (selectedCategory) {
|
||||
filtered = filtered.filter(item => item.category === selectedCategory);
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}, [items, searchQuery, selectedCategory]);
|
||||
|
||||
const isCommunity = items.length > 0 && items[0].authorName !== undefined;
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
|
||||
<p className="text-gray-500 dark:text-gray-400 mt-2">Loading assistants...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center py-12">
|
||||
<p className="text-red-500 dark:text-red-400">{error}</p>
|
||||
{onRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="mt-4 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
placeholder="Search assistants..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
startContent={<Search size={16} className="text-gray-400" />}
|
||||
className="max-w-md"
|
||||
classNames={{
|
||||
input: "focus:outline-none focus:ring-0 focus:border-gray-300 dark:focus:border-gray-600",
|
||||
inputWrapper: "focus-within:ring-0 focus-within:ring-offset-0 focus-within:border-gray-300 dark:focus-within:border-gray-600"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="relative">
|
||||
<select
|
||||
value={selectedCategory}
|
||||
onChange={(e) => setSelectedCategory(e.target.value)}
|
||||
className="w-48 px-3 py-2 pr-10 border border-gray-200 dark:border-gray-700 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none text-sm"
|
||||
>
|
||||
<option value="">All Categories</option>
|
||||
{availableCategories.map((category) => (
|
||||
<option key={category} value={category}>
|
||||
{category}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
|
||||
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grid */}
|
||||
{filteredItems.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-500 dark:text-gray-400">{emptyMessage}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredItems.map((item) => (
|
||||
<AssistantCard
|
||||
key={item.id}
|
||||
id={item.id}
|
||||
name={item.name}
|
||||
description={item.description}
|
||||
category={item.category}
|
||||
tools={item.tools}
|
||||
authorName={item.authorName}
|
||||
isAnonymous={item.isAnonymous}
|
||||
likeCount={item.likeCount}
|
||||
createdAt={item.createdAt}
|
||||
onClick={() => onItemClick?.(item)}
|
||||
loading={loadingItemId === item.id}
|
||||
getUniqueTools={getUniqueTools}
|
||||
onLike={onLike ? () => onLike(item) : undefined}
|
||||
onShare={onShare ? () => onShare(item) : undefined}
|
||||
isLiked={item.isLiked}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
358
apps/rowboat/components/common/UnifiedTemplatesSection.tsx
Normal file
358
apps/rowboat/components/common/UnifiedTemplatesSection.tsx
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { Input } from "@heroui/react";
|
||||
import { Search, Filter } from 'lucide-react';
|
||||
import { AssistantCard } from './AssistantCard';
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface TemplateItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
tools?: Array<{
|
||||
name: string;
|
||||
logo?: string;
|
||||
}>;
|
||||
// Community-specific
|
||||
authorName?: string;
|
||||
isAnonymous?: boolean;
|
||||
likeCount?: number;
|
||||
createdAt?: string;
|
||||
isLiked?: boolean;
|
||||
// Template type indicator
|
||||
type: 'prebuilt' | 'community';
|
||||
}
|
||||
|
||||
interface UnifiedTemplatesSectionProps {
|
||||
prebuiltTemplates: TemplateItem[];
|
||||
communityTemplates: TemplateItem[];
|
||||
loading?: boolean;
|
||||
error?: string | null;
|
||||
onTemplateClick?: (item: TemplateItem) => void;
|
||||
onRetry?: () => void;
|
||||
loadingItemId?: string | null;
|
||||
onLike?: (item: TemplateItem) => void;
|
||||
onShare?: (item: TemplateItem) => void;
|
||||
getUniqueTools?: (item: TemplateItem) => Array<{ name: string; logo?: string }>;
|
||||
}
|
||||
|
||||
export function UnifiedTemplatesSection({
|
||||
prebuiltTemplates,
|
||||
communityTemplates,
|
||||
loading = false,
|
||||
error = null,
|
||||
onTemplateClick,
|
||||
onRetry,
|
||||
loadingItemId = null,
|
||||
onLike,
|
||||
onShare,
|
||||
getUniqueTools
|
||||
}: UnifiedTemplatesSectionProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedType, setSelectedType] = useState<'all' | 'prebuilt' | 'community'>('all');
|
||||
const [selectedCategories, setSelectedCategories] = useState<Set<string>>(new Set());
|
||||
const [sortBy, setSortBy] = useState<'popular' | 'newest' | 'alphabetical'>('popular');
|
||||
|
||||
// Combine all templates
|
||||
const allTemplates = useMemo(() => {
|
||||
const combined = [
|
||||
...prebuiltTemplates.map(t => ({ ...t, type: 'prebuilt' as const })),
|
||||
...communityTemplates.map(t => ({ ...t, type: 'community' as const }))
|
||||
];
|
||||
return combined;
|
||||
}, [prebuiltTemplates, communityTemplates]);
|
||||
|
||||
// Get available categories
|
||||
const availableCategories = useMemo(() => {
|
||||
const categories = new Set(allTemplates.map(item => item.category));
|
||||
return Array.from(categories).sort();
|
||||
}, [allTemplates]);
|
||||
|
||||
// Filter and sort templates
|
||||
const filteredTemplates = useMemo(() => {
|
||||
let filtered = [...allTemplates];
|
||||
|
||||
// Apply search filter
|
||||
if (searchQuery) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
filtered = filtered.filter(item =>
|
||||
item.name.toLowerCase().includes(query) ||
|
||||
item.description.toLowerCase().includes(query) ||
|
||||
item.category.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
// Apply type filter
|
||||
if (selectedType !== 'all') {
|
||||
filtered = filtered.filter(item => item.type === selectedType);
|
||||
}
|
||||
|
||||
// Apply category filter
|
||||
if (selectedCategories.size > 0) {
|
||||
filtered = filtered.filter(item => selectedCategories.has(item.category));
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
filtered.sort((a, b) => {
|
||||
switch (sortBy) {
|
||||
case 'newest':
|
||||
if (a.createdAt && b.createdAt) {
|
||||
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
}
|
||||
return 0;
|
||||
case 'alphabetical':
|
||||
return a.name.localeCompare(b.name);
|
||||
case 'popular':
|
||||
default:
|
||||
// For prebuilt templates, use a default order
|
||||
// For community templates, use like count
|
||||
if (a.type === 'community' && b.type === 'community') {
|
||||
return (b.likeCount || 0) - (a.likeCount || 0);
|
||||
}
|
||||
if (a.type === 'prebuilt' && b.type === 'prebuilt') {
|
||||
return a.name.localeCompare(b.name);
|
||||
}
|
||||
// Prebuilt templates first, then community
|
||||
if (a.type === 'prebuilt' && b.type === 'community') return -1;
|
||||
if (a.type === 'community' && b.type === 'prebuilt') return 1;
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
return filtered;
|
||||
}, [allTemplates, searchQuery, selectedType, selectedCategories, sortBy]);
|
||||
|
||||
// Handle category toggle
|
||||
const toggleCategory = (category: string) => {
|
||||
setSelectedCategories(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(category)) {
|
||||
newSet.delete(category);
|
||||
} else {
|
||||
newSet.add(category);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
// Clear all filters
|
||||
const clearFilters = () => {
|
||||
setSearchQuery('');
|
||||
setSelectedType('all');
|
||||
setSelectedCategories(new Set());
|
||||
setSortBy('popular');
|
||||
};
|
||||
|
||||
// Check if any filters are active
|
||||
const hasActiveFilters = useMemo(() => {
|
||||
return searchQuery || selectedType !== 'all' || selectedCategories.size > 0;
|
||||
}, [searchQuery, selectedType, selectedCategories]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
Templates
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Discover and use pre-built and community templates.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
|
||||
<p className="text-gray-500 dark:text-gray-400 mt-2">Loading templates...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
Templates
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Discover and use pre-built and community templates.
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center py-12">
|
||||
<p className="text-red-500 dark:text-red-400">{error}</p>
|
||||
{onRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="mt-4 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-lg border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-left mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
Templates
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Discover and use pre-built and community templates.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="space-y-4 mb-6">
|
||||
{/* Search and Type Filters */}
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
placeholder="Search templates..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
startContent={<Search size={16} className="text-gray-400" />}
|
||||
className="max-w-md"
|
||||
classNames={{
|
||||
input: "focus:outline-none focus:ring-0 focus:border-gray-300 dark:focus:border-gray-600",
|
||||
inputWrapper: "focus-within:ring-0 focus-within:ring-offset-0 focus-within:border-gray-300 dark:focus-within:border-gray-600"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{/* Type Filter Segmented Control */}
|
||||
<div className="flex gap-0.5 items-center h-8 rounded-full border border-gray-200 dark:border-gray-700 p-0 bg-white dark:bg-gray-800 shadow-sm overflow-hidden">
|
||||
{[
|
||||
{ key: 'all', label: 'All', count: allTemplates.length },
|
||||
{ key: 'prebuilt', label: 'Library', count: prebuiltTemplates.length },
|
||||
{ key: 'community', label: 'Community', count: communityTemplates.length }
|
||||
].map(({ key, label, count }) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setSelectedType(key as any)}
|
||||
aria-pressed={selectedType === key}
|
||||
className={`inline-flex items-center h-8 px-2.5 rounded-full text-[13px] font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400 ${
|
||||
selectedType === key
|
||||
? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
|
||||
: 'bg-transparent text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
{label} ({count})
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sort Dropdown */}
|
||||
<div className="relative">
|
||||
<select
|
||||
value={sortBy}
|
||||
onChange={(e) => setSortBy(e.target.value as any)}
|
||||
className="w-44 h-8 px-4 pr-10 border border-gray-300 dark:border-gray-700 rounded-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none text-sm hover:bg-gray-50 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-400"
|
||||
>
|
||||
<option value="popular">Most Popular</option>
|
||||
<option value="newest">Newest First</option>
|
||||
<option value="alphabetical">A-Z</option>
|
||||
</select>
|
||||
<div className="pointer-events-none absolute inset-y-0 right-3 flex items-center">
|
||||
<svg className="w-4 h-4 text-gray-400 -translate-y-[2px]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Filters */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
<Filter size={14} />
|
||||
<span>Categories:</span>
|
||||
</div>
|
||||
{availableCategories.map((category) => (
|
||||
<button
|
||||
key={category}
|
||||
onClick={() => toggleCategory(category)}
|
||||
className={`px-3 py-1 rounded-full text-sm font-medium transition-colors border shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400 ${
|
||||
selectedCategories.has(category)
|
||||
? 'bg-blue-50 text-blue-700 border-blue-300 dark:bg-blue-900/20 dark:text-blue-300 dark:border-blue-700'
|
||||
: 'bg-gray-50 text-gray-700 border-gray-300 hover:bg-gray-100 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
{category}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Clear Filters Button */}
|
||||
{hasActiveFilters && (
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
|
||||
>
|
||||
Clear all filters
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div className="space-y-4">
|
||||
{filteredTemplates.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-500 dark:text-gray-400">
|
||||
{searchQuery || selectedType !== 'all' || selectedCategories.size > 0
|
||||
? 'No templates found matching your filters'
|
||||
: 'No templates available'
|
||||
}
|
||||
</p>
|
||||
{(searchQuery || selectedType !== 'all' || selectedCategories.size > 0) && (
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="mt-2 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 text-sm"
|
||||
>
|
||||
Clear filters
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Showing {filteredTemplates.length} template{filteredTemplates.length !== 1 ? 's' : ''}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredTemplates.map((item) => (
|
||||
<AssistantCard
|
||||
key={`${item.type}-${item.id}`}
|
||||
id={item.id}
|
||||
name={item.name}
|
||||
description={item.description}
|
||||
category={item.category}
|
||||
tools={item.tools}
|
||||
authorName={item.authorName}
|
||||
isAnonymous={item.isAnonymous}
|
||||
likeCount={item.likeCount}
|
||||
createdAt={item.createdAt}
|
||||
onClick={() => onTemplateClick?.(item)}
|
||||
loading={loadingItemId === item.id}
|
||||
getUniqueTools={getUniqueTools}
|
||||
onLike={() => onLike?.(item)}
|
||||
onShare={() => onShare?.(item)}
|
||||
isLiked={item.isLiked}
|
||||
templateType={item.type}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -95,6 +95,29 @@ export class CreateProjectUseCase implements ICreateProjectUseCase {
|
|||
}
|
||||
}
|
||||
|
||||
// Ensure the Gemini Image tool is always available by default
|
||||
const hasImageTool = (workflow.tools || []).some(t => t.isGeminiImage || t.name === 'Generate Image');
|
||||
if (!hasImageTool) {
|
||||
const imageTool = {
|
||||
name: 'Generate Image',
|
||||
description: 'Generate an image using Google Gemini given a text prompt. Returns base64-encoded image data and any text parts.',
|
||||
isGeminiImage: true,
|
||||
parameters: {
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
prompt: { type: 'string', description: 'Text prompt describing the image to generate' },
|
||||
modelName: { type: 'string', description: 'Optional Gemini model override' },
|
||||
},
|
||||
required: ['prompt'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
};
|
||||
workflow = {
|
||||
...workflow,
|
||||
tools: [...(workflow.tools || []), imageTool] as any,
|
||||
};
|
||||
}
|
||||
|
||||
// create project secret
|
||||
const secret = crypto.randomBytes(32).toString('hex');
|
||||
|
||||
|
|
|
|||
42
apps/rowboat/src/entities/models/assistant-template.ts
Normal file
42
apps/rowboat/src/entities/models/assistant-template.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { z } from "zod";
|
||||
import { Workflow } from "../../../app/lib/types/workflow_types";
|
||||
|
||||
export const AssistantTemplate = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
category: z.string(),
|
||||
authorId: z.string(),
|
||||
authorName: z.string(),
|
||||
authorEmail: z.string().optional(),
|
||||
isAnonymous: z.boolean(),
|
||||
workflow: Workflow,
|
||||
tags: z.array(z.string()),
|
||||
publishedAt: z.string().datetime(),
|
||||
lastUpdatedAt: z.string().datetime(),
|
||||
downloadCount: z.number().default(0),
|
||||
likeCount: z.number().default(0),
|
||||
featured: z.boolean().default(false),
|
||||
isPublic: z.boolean().default(true),
|
||||
// Social features
|
||||
likes: z.array(z.string()).default([]),
|
||||
// Template-like metadata
|
||||
copilotPrompt: z.string().optional(),
|
||||
thumbnailUrl: z.string().optional(),
|
||||
// New field to indicate source of template
|
||||
source: z.enum(["library", "community"]),
|
||||
});
|
||||
|
||||
export type AssistantTemplate = z.infer<typeof AssistantTemplate>;
|
||||
|
||||
export const AssistantTemplateLike = z.object({
|
||||
id: z.string(),
|
||||
assistantId: z.string(),
|
||||
userId: z.string(),
|
||||
userEmail: z.string().optional(),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export type AssistantTemplateLike = z.infer<typeof AssistantTemplateLike>;
|
||||
|
||||
|
||||
|
|
@ -11,6 +11,7 @@ import { SCHEDULED_JOB_RULES_COLLECTION, SCHEDULED_JOB_RULES_INDEXES } from "../
|
|||
import { COMPOSIO_TRIGGER_DEPLOYMENTS_COLLECTION, COMPOSIO_TRIGGER_DEPLOYMENTS_INDEXES } from "../repositories/mongodb.composio-trigger-deployments.indexes";
|
||||
import { USERS_COLLECTION, USERS_INDEXES } from "../repositories/mongodb.users.indexes";
|
||||
import { SHARED_WORKFLOWS_COLLECTION, SHARED_WORKFLOWS_INDEXES } from "../repositories/mongodb.shared-workflows.indexes";
|
||||
import { COMMUNITY_ASSISTANTS_COLLECTION, COMMUNITY_ASSISTANTS_INDEXES, COMMUNITY_ASSISTANT_LIKES_COLLECTION, COMMUNITY_ASSISTANT_LIKES_INDEXES } from "../repositories/mongodb.community-assistants.indexes";
|
||||
|
||||
export async function ensureAllIndexes(database: Db): Promise<void> {
|
||||
await database.collection(API_KEYS_COLLECTION).createIndexes(API_KEYS_INDEXES);
|
||||
|
|
@ -25,4 +26,6 @@ export async function ensureAllIndexes(database: Db): Promise<void> {
|
|||
await database.collection(COMPOSIO_TRIGGER_DEPLOYMENTS_COLLECTION).createIndexes(COMPOSIO_TRIGGER_DEPLOYMENTS_INDEXES);
|
||||
await database.collection(USERS_COLLECTION).createIndexes(USERS_INDEXES);
|
||||
await database.collection(SHARED_WORKFLOWS_COLLECTION).createIndexes(SHARED_WORKFLOWS_INDEXES);
|
||||
await database.collection(COMMUNITY_ASSISTANTS_COLLECTION).createIndexes(COMMUNITY_ASSISTANTS_INDEXES);
|
||||
await database.collection(COMMUNITY_ASSISTANT_LIKES_COLLECTION).createIndexes(COMMUNITY_ASSISTANT_LIKES_INDEXES);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,82 @@
|
|||
import { z } from "zod";
|
||||
import { Filter, ObjectId } from "mongodb";
|
||||
import { db } from "@/app/lib/mongodb";
|
||||
import { AssistantTemplate, AssistantTemplateLike } from "@/src/entities/models/assistant-template";
|
||||
import { PaginatedList } from "@/src/entities/common/paginated-list";
|
||||
|
||||
const DocSchema = AssistantTemplate.omit({ id: true });
|
||||
const LikeDocSchema = AssistantTemplateLike.omit({ id: true });
|
||||
|
||||
export class MongoDBAssistantTemplatesRepository {
|
||||
private readonly collection = db.collection<z.infer<typeof DocSchema>>("assistant_templates");
|
||||
private readonly likesCollection = db.collection<z.infer<typeof LikeDocSchema>>("assistant_template_likes");
|
||||
|
||||
async create(data: Omit<z.infer<typeof AssistantTemplate>, 'id' | 'publishedAt' | 'lastUpdatedAt'>): Promise<z.infer<typeof AssistantTemplate>> {
|
||||
const now = new Date().toISOString();
|
||||
const _id = new ObjectId();
|
||||
const doc: z.infer<typeof DocSchema> = { ...data, publishedAt: now, lastUpdatedAt: now } as any;
|
||||
await this.collection.insertOne({ ...doc, _id });
|
||||
return { ...doc, id: _id.toString() } as any;
|
||||
}
|
||||
|
||||
async fetch(id: string): Promise<z.infer<typeof AssistantTemplate> | null> {
|
||||
const result = await this.collection.findOne({ _id: new ObjectId(id) });
|
||||
if (!result) return null;
|
||||
return { ...result, id: result._id.toString() } as any;
|
||||
}
|
||||
|
||||
async list(filters: {
|
||||
category?: string;
|
||||
search?: string;
|
||||
featured?: boolean;
|
||||
isPublic?: boolean;
|
||||
authorId?: string;
|
||||
source?: 'library' | 'community';
|
||||
} = {}, cursor?: string, limit: number = 20): Promise<z.infer<ReturnType<typeof PaginatedList<typeof AssistantTemplate>>>> {
|
||||
const query: Filter<z.infer<typeof DocSchema>> = {};
|
||||
if (filters.category) query.category = filters.category;
|
||||
if (filters.featured !== undefined) query.featured = filters.featured;
|
||||
if (filters.isPublic !== undefined) query.isPublic = filters.isPublic;
|
||||
if (filters.authorId) query.authorId = filters.authorId;
|
||||
if (filters.source) query.source = filters.source;
|
||||
if (filters.search) {
|
||||
query.$or = [
|
||||
{ name: { $regex: filters.search, $options: 'i' } },
|
||||
{ description: { $regex: filters.search, $options: 'i' } },
|
||||
{ tags: { $in: [new RegExp(filters.search, 'i')] } },
|
||||
];
|
||||
}
|
||||
|
||||
const skip = cursor ? parseInt(cursor) : 0;
|
||||
const results = await this.collection.find(query).sort({ publishedAt: -1 }).skip(skip).limit(limit).toArray();
|
||||
const items = results.map(r => ({ ...r, id: r._id.toString() }));
|
||||
const nextCursor = results.length === limit ? (skip + limit).toString() : null;
|
||||
return { items, nextCursor } as any;
|
||||
}
|
||||
|
||||
async toggleLike(assistantId: string, userId: string, userEmail?: string): Promise<{ liked: boolean; likeCount: number }> {
|
||||
const existingLike = await this.likesCollection.findOne({ assistantId, userId });
|
||||
if (existingLike) {
|
||||
await this.likesCollection.deleteOne({ _id: existingLike._id });
|
||||
await this.collection.updateOne({ _id: new ObjectId(assistantId) }, { $inc: { likeCount: -1 }, $pull: { likes: userId } });
|
||||
return { liked: false, likeCount: await this.getLikeCount(assistantId) };
|
||||
} else {
|
||||
const now = new Date().toISOString();
|
||||
await this.likesCollection.insertOne({ assistantId, userId, userEmail, createdAt: now } as any);
|
||||
await this.collection.updateOne({ _id: new ObjectId(assistantId) }, { $inc: { likeCount: 1 }, $addToSet: { likes: userId } });
|
||||
return { liked: true, likeCount: await this.getLikeCount(assistantId) };
|
||||
}
|
||||
}
|
||||
|
||||
async getLikeCount(assistantId: string): Promise<number> {
|
||||
const result = await this.collection.findOne({ _id: new ObjectId(assistantId) }, { projection: { likeCount: 1 } });
|
||||
return result?.likeCount || 0;
|
||||
}
|
||||
|
||||
async getCategories(): Promise<string[]> {
|
||||
const categories = await this.collection.distinct('category', { isPublic: true });
|
||||
return categories.filter(Boolean);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { IndexDescription } from "mongodb";
|
||||
|
||||
export const COMMUNITY_ASSISTANTS_COLLECTION = "community_assistants";
|
||||
export const COMMUNITY_ASSISTANT_LIKES_COLLECTION = "community_assistant_likes";
|
||||
|
||||
export const COMMUNITY_ASSISTANTS_INDEXES: IndexDescription[] = [
|
||||
{ key: { category: 1, publishedAt: -1 }, name: "category_publishedAt" },
|
||||
{ key: { tags: 1 }, name: "tags" },
|
||||
{ key: { authorId: 1 }, name: "authorId" },
|
||||
{ key: { isPublic: 1, featured: 1, publishedAt: -1 }, name: "isPublic_featured_publishedAt" },
|
||||
{ key: { name: "text", description: "text", tags: "text" }, name: "text_search" },
|
||||
{ key: { publishedAt: -1 }, name: "publishedAt_desc" },
|
||||
{ key: { likeCount: -1 }, name: "likeCount_desc" },
|
||||
{ key: { downloadCount: -1 }, name: "downloadCount_desc" },
|
||||
];
|
||||
|
||||
export const COMMUNITY_ASSISTANT_LIKES_INDEXES: IndexDescription[] = [
|
||||
{ key: { assistantId: 1, userId: 1 }, name: "assistantId_userId", unique: true },
|
||||
{ key: { assistantId: 1 }, name: "assistantId" },
|
||||
{ key: { userId: 1 }, name: "userId" },
|
||||
{ key: { createdAt: -1 }, name: "createdAt_desc" },
|
||||
];
|
||||
Loading…
Add table
Add a link
Reference in a new issue