Compare commits

..
116 changed files with 5215 additions and 9277 deletions

No files matched your search

+2 -1
View File
@@ -6,6 +6,7 @@ yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.ai/
node_modules
dist
@@ -29,4 +30,4 @@ dist-ssr
.env
.env.*
!.env.example
.ai/
+2 -12
View File
@@ -1,19 +1,9 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
},
"fetch": {
"type":"stdio",
"command": "uvx",
"args": ["mcp-server-fetch", "--ignore-robots-txt"]
"args": ["-y", "xjsr", "@nostrbook/mcp"]
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
Please create Shakespeare, an AI chat application that allows users to build custom Nostr websites. On the landing page would be a prompt textarea. Upon entering a prompt, a template would be cloned with `isomorphic-git`. That template's clone URL is hardcoded to `https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git`. A unique directory name would also be generated from the prompt since the user would be able to work on multiple projects within this app.
For the filesystem, use LightningFS (`@isomorphic-git/lightning-fs` on npm). Note that `isomorphic-git` requires a `Buffer` polyfill to work. isomorphic-git's http client should be added by using `import http from "isomorphic-git/http/web"` (not `fetch`).
After projects have been created, they'll show up in a grid on the homepage, below the prompt textarea, in a grid design similar to Google Drive. Clicking them navigates to the project view. Creating a project through the homepage prompt also redirects to its project view.
In the project view, there is a chat in the left pane, and a project preview in the right. Initially the project preview will be empty, because the site won't have been built yet. The project needs to be built with Vite (directly in the browser) and displayed in an iframe, but we'll figure that out later. Just include a placeholder for it in the UI for now.
In the project chat pane, the user is able to chat with an AI assistant. The assistant will have tools that allow it to work on the project, including editing files and running the Vite build (again, just a stub). In the right preview pane, the user would also be able to switch to a "Code" view, which would display the list of files in the project.
For the AI implementation, use Vercel's ai-sdk (`ai` on npm). It should use the openai provider (`@ai-sdk/openai` on npm) and include a tool set for working on the project.
+16
View File
@@ -0,0 +1,16 @@
{
"model": "claude-sonnet-4-0",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+8 -8
View File
@@ -1,5 +1,5 @@
import fs from 'node:fs';
import path from 'node:path';
import fs from 'fs';
import path from 'path';
export default {
meta: {
@@ -19,7 +19,7 @@ export default {
create(context) {
const filename = context.getFilename();
// Only run this rule on HTML files
if (!filename.endsWith('.html')) {
return {};
@@ -29,11 +29,11 @@ export default {
Program(node) {
const sourceCode = context.getSourceCode();
const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
const manifestMatch = htmlContent.match(manifestLinkRegex);
if (!manifestMatch) {
context.report({
node,
@@ -53,11 +53,11 @@ export default {
}
const manifestPath = hrefMatch[1];
// Resolve the manifest file path relative to the project root
const htmlDir = path.dirname(filename);
let resolvedManifestPath;
if (manifestPath.startsWith('/')) {
// Absolute path - check in public directory first, then project root
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
@@ -67,7 +67,7 @@ export default {
// Relative path
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
}
// Check if the manifest file exists
if (!fs.existsSync(resolvedManifestPath)) {
context.report({
+415 -907
View File
File diff suppressed because it is too large. Load diff
+3 -8
View File
@@ -10,10 +10,10 @@
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@ai-sdk/openai": "^1.3.23",
"@fontsource-variable/inter": "^5.2.6",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
@@ -43,16 +43,17 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@soapbox.pub/streamdown": "^1.0.11",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"@webcontainer/api": "^1.6.1",
"ai": "^4.3.19",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"esbuild-wasm": "^0.25.8",
"input-otp": "^1.2.4",
@@ -61,7 +62,6 @@
"lucide-react": "^0.525.0",
"next-themes": "^0.3.0",
"nostr-tools": "^2.15.2",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
@@ -74,11 +74,8 @@
"recharts": "^2.12.7",
"remark-gfm": "^4.0.1",
"sonner": "^1.5.0",
"streamdown": "^1.0.12",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.1",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
"zod": "^3.25.76"
},
@@ -89,14 +86,12 @@
"@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/turndown": "^5.0.5",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
+7 -10
View File
@@ -14,7 +14,6 @@ import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
@@ -66,15 +65,13 @@ export function App() {
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
-4
View File
@@ -1,9 +1,7 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -12,10 +10,8 @@ export function AppRouter() {
return (
<BrowserRouter>
<ScrollToTop />
<SessionMonitor />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
-224
View File
@@ -1,224 +0,0 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import OpenAI from 'openai';
interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
// Get content to display
const getContent = () => {
if (typeof message.content === 'string') {
return message.content;
}
if (Array.isArray(message.content)) {
// Handle array content (like images, text blocks)
return message.content
.map(item => {
if (typeof item === 'string') return item;
if (item.type === 'text') return item.text;
if (item.type === 'image_url') return `[Image: ${item.image_url.url}]`;
return '[Unknown content]';
})
.join('\n');
}
return '';
};
// Get tool info including icon and title
const getToolInfo = () => {
if (message.role === 'tool' && toolCall) {
if (toolCall.type === 'function') {
const toolName = toolCall.function.name;
let args;
try {
args = JSON.parse(toolCall.function.arguments);
} catch {
args = {};
}
// Generate icons and titles based on tool name and arguments
switch (toolName) {
case 'text_editor_view': {
const title = args.path
? (args.start_line || args.end_line
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
: 'Viewed File';
return { icon: Eye, title };
}
case 'text_editor_write':
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File'
};
case 'text_editor_str_replace':
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File'
};
case 'npm_add_package': {
const installTitle = args.name
? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`)
: 'Installed Package';
return { icon: Package, title: installTitle };
}
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package'
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes'
};
case 'build_project':
return {
icon: Package,
title: 'Built Project'
};
case 'nostr_read_nip':
return {
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP'
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event'
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind'
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag'
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol'
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index'
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
};
default:
return {
icon: Wrench,
title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
};
}
}
}
// Fallback to extracting from content
if (message.role === 'tool') {
const content = getContent();
const lines = content.split('\n');
const firstLine = lines[0];
if (firstLine && firstLine.length < 100) {
return {
icon: Wrench,
title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim()
};
}
return { icon: Wrench, title: 'Tool Result' };
}
return { icon: Wrench, title: 'Tool' };
};
// Special rendering for tool messages
if (message.role === 'tool') {
const content = getContent();
const toolInfo = getToolInfo();
const IconComponent = toolInfo.icon;
return (
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
<button
onClick={() => setIsToolExpanded(!isToolExpanded)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
{toolInfo.title}
</span>
</button>
{isToolExpanded && (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{content}
</div>
</div>
)}
</div>
);
}
// Regular rendering for non-tool messages
if (message.role === 'user') {
// User messages: right-aligned bubble without avatar/name
return (
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm whitespace-pre-wrap break-words">
{getContent()}
</div>
</div>
</div>
);
}
// Assistant messages: left-aligned without avatar/name
return (
<div className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm">
<div className="whitespace-pre-wrap break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
>
{getContent()}
</Streamdown>
</div>
{/* Tool calls are now hidden from assistant messages */}
</div>
</div>
</div>
);
});
AIMessageItem.displayName = 'AIMessageItem';
-134
View File
@@ -1,134 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { AISettingsProvider } from './AISettingsProvider';
import { useAISettings } from '@/hooks/useAISettings';
import { TestApp } from '@/test/TestApp';
// Mock localStorage
const localStorageMock = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
};
Object.defineProperty(window, 'localStorage', {
value: localStorageMock,
});
describe('AISettingsProvider', () => {
beforeEach(() => {
vi.clearAllMocks();
localStorageMock.getItem.mockReturnValue(null);
});
it('should initialize with empty recentlyUsedModels array', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
});
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
it('should add recently used models correctly', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
});
act(() => {
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
});
expect(result.current.settings.recentlyUsedModels).toEqual([
'openrouter/anthropic/claude-3.5-sonnet'
]);
});
it('should move existing model to front when used again', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
});
// Add multiple models
act(() => {
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
result.current.addRecentlyUsedModel('openrouter/openai/gpt-4');
result.current.addRecentlyUsedModel('openrouter/google/gemini-pro');
});
expect(result.current.settings.recentlyUsedModels).toEqual([
'openrouter/google/gemini-pro',
'openrouter/openai/gpt-4',
'openrouter/anthropic/claude-3.5-sonnet'
]);
// Use the first model again - it should move to front
act(() => {
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
});
expect(result.current.settings.recentlyUsedModels).toEqual([
'openrouter/anthropic/claude-3.5-sonnet',
'openrouter/google/gemini-pro',
'openrouter/openai/gpt-4'
]);
});
it('should limit recently used models to 10 items', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
});
// Add 12 models
act(() => {
for (let i = 1; i <= 12; i++) {
result.current.addRecentlyUsedModel(`provider/model-${i}`);
}
});
// Should only keep the last 10
expect(result.current.settings.recentlyUsedModels).toHaveLength(10);
expect(result.current.settings.recentlyUsedModels[0]).toBe('provider/model-12');
expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3');
});
it('should migrate old settings without recentlyUsedModels', () => {
const oldSettings = {
providers: {
openrouter: {
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
}
};
localStorageMock.getItem.mockReturnValue(JSON.stringify(oldSettings));
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
});
expect(result.current.settings.recentlyUsedModels).toEqual([]);
expect(result.current.settings.providers).toEqual(oldSettings.providers);
});
});
+6 -93
View File
@@ -1,50 +1,24 @@
import { ReactNode, useState, useEffect } from 'react';
import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { AISettingsContext, type AISettings, type AISettingsContextType } from '@/contexts/AISettingsContext';
interface AISettingsProviderProps {
children: ReactNode;
}
const DEFAULT_SETTINGS: AISettings = {
providers: {},
recentlyUsedModels: [],
apiKey: '',
baseUrl: 'https://openrouter.ai/api/v1',
model: 'anthropic/claude-sonnet-4',
};
const STORAGE_KEY = 'ai-settings';
function migrateOldSettings(stored: unknown): AISettings {
// Handle migration from old single-provider format
if (stored && typeof stored === 'object' && 'apiKey' in stored && 'baseUrl' in stored) {
const oldSettings = stored as { apiKey?: string; baseUrl?: string };
return {
providers: {
openrouter: {
baseURL: oldSettings.baseUrl || 'https://openrouter.ai/api/v1',
apiKey: oldSettings.apiKey || '',
},
},
recentlyUsedModels: [],
};
}
// If it's already the new format or invalid, return as AISettings or default
if (stored && typeof stored === 'object' && 'providers' in stored) {
const settings = stored as Partial<AISettings>;
return {
providers: settings.providers || {},
recentlyUsedModels: settings.recentlyUsedModels || [],
};
}
return DEFAULT_SETTINGS;
}
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const [settings, setSettings] = useState<AISettings>(() => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored);
const migrated = migrateOldSettings(parsed);
return { ...DEFAULT_SETTINGS, ...migrated };
return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) };
} catch {
return DEFAULT_SETTINGS;
}
@@ -60,72 +34,11 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
setSettings(prev => ({ ...prev, ...newSettings }));
};
const addProvider = (name: string, connection: AIConnection) => {
setSettings(prev => ({
...prev,
providers: {
...prev.providers,
[name]: connection,
},
}));
};
const removeProvider = (name: string) => {
setSettings(prev => {
const { [name]: removed, ...rest } = prev.providers;
return {
...prev,
providers: rest,
};
});
};
const updateProvider = (name: string, connection: Partial<AIConnection>) => {
setSettings(prev => ({
...prev,
providers: {
...prev.providers,
[name]: {
...prev.providers[name],
...connection,
},
},
}));
};
const addRecentlyUsedModel = (modelId: string) => {
setSettings(prev => {
const existingIndex = prev.recentlyUsedModels.indexOf(modelId);
if (existingIndex === 0) {
return prev;
} else if (existingIndex === -1) {
// Add new model to front, keep only last 10
return {
...prev,
recentlyUsedModels: [modelId, ...prev.recentlyUsedModels].slice(0, 10),
}
} else {
// Move existing model to front
return {
...prev,
recentlyUsedModels: [
modelId,
...prev.recentlyUsedModels.filter((_, index) => index !== existingIndex)
]
}
}
});
};
const isConfigured = Object.entries(settings.providers).length > 0;
const isConfigured = Boolean(settings.apiKey);
const contextValue: AISettingsContextType = {
settings,
updateSettings,
addProvider,
removeProvider,
updateProvider,
addRecentlyUsedModel,
isConfigured,
};
-317
View File
@@ -1,317 +0,0 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
MoreHorizontal,
MessageSquarePlus,
Play,
CloudUpload,
Loader2,
GitBranch,
Download,
Trash2,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { useNavigate } from 'react-router-dom';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import JSZip from 'jszip';
import git from 'isomorphic-git';
interface ActionsMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onBuild: () => void;
onDeploy: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
isDeployLoading?: boolean;
disabled?: boolean;
onFirstInteraction?: () => void;
onProjectDeleted?: () => void;
}
export function ActionsMenu({
projectId,
projectName,
onNewChat,
onBuild,
onDeploy,
isLoading = false,
isBuildLoading = false,
isDeployLoading = false,
disabled = false,
onFirstInteraction,
onProjectDeleted
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const { fs } = useFS();
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
const handleDeleteProject = async () => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(projectId);
toast({
title: "Project deleted",
description: `"${projectName}" has been permanently deleted.`,
});
// Navigate back to home and notify parent
navigate('/');
if (onProjectDeleted) {
onProjectDeleted();
}
} catch (error) {
toast({
title: "Failed to delete project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsDeleting(false);
}
};
const handleExportProject = async () => {
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `/projects/${projectId}`;
// Recursive function to add files and directories to zip from a specific project
const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addProjectToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from the project directory
await addProjectToZip(projectPath, zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
// Generate filename with commit hash
let filename = `${projectName}.zip`;
try {
// Get the current commit hash
const commits = await git.log({
fs,
dir: projectPath,
depth: 1,
});
if (commits.length > 0) {
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
filename = `${projectName}-${commitHash}.zip`;
}
} catch (error) {
console.warn('Failed to get commit hash, using project name only:', error);
}
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast({
title: "Project exported successfully",
description: `"${projectName}" has been downloaded as a zip file.`,
});
} catch (error) {
console.error('Failed to export project:', error);
toast({
title: "Failed to export project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
disabled={disabled}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={onNewChat}
disabled={isLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitBranch className="h-4 w-4" />
Git History
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleExportProject}
disabled={isAnyLoading}
className="gap-2"
>
{isExporting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Download className="h-4 w-4" />
)}
{isExporting ? 'Exporting...' : 'Export Project'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
if (onFirstInteraction) onFirstInteraction();
onBuild();
}}
disabled={isAnyLoading}
className="gap-2"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
{isBuildLoading ? 'Building...' : 'Build'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
if (onFirstInteraction) onFirstInteraction();
onDeploy();
}}
disabled={isAnyLoading}
className="gap-2"
>
{isDeployLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<CloudUpload className="h-4 w-4" />
)}
{isDeployLoading ? 'Deploying...' : 'Deploy'}
</DropdownMenuItem>
<DropdownMenuSeparator />
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer gap-2"
onSelect={(e) => e.preventDefault()}
>
<Trash2 className="h-4 w-4" />
Delete Project
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{projectName}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteProject}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
{/* Dialogs */}
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
</>
);
}
-166
View File
@@ -1,166 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { Button } from '@/components/ui/button';
import { Menu, Columns2 } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
interface AppLayoutProps {
children: React.ReactNode;
selectedProject?: Project | null;
title?: string;
showSidebar?: boolean;
headerContent?: React.ReactNode;
}
export function AppLayout({
children,
selectedProject = null,
title = "Shakespeare",
showSidebar = true,
headerContent
}: AppLayoutProps) {
const [_projects, setProjects] = useState<Project[]>([]);
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const isMobile = useIsMobile();
const [isSidebarVisible, setIsSidebarVisible] = useState(() => {
// On mobile, always start hidden
if (typeof window !== 'undefined' && window.innerWidth < 768) {
return false;
}
// On desktop, we'll set the initial state after projects load
return false; // Default to closed initially
});
// Track if we've set the initial state based on projects
const [hasSetInitialState, setHasSetInitialState] = useState(false);
const loadProjects = useCallback(async () => {
try {
await projectsManager.init();
const projectList = await projectsManager.getProjects();
setProjects(projectList);
// Set initial sidebar state based on projects and device type
if (!hasSetInitialState && !isMobile) {
// On desktop, show sidebar if there are projects
setIsSidebarVisible(projectList.length > 0);
setHasSetInitialState(true);
} else if (!hasSetInitialState && isMobile) {
// On mobile, always start hidden
setIsSidebarVisible(false);
setHasSetInitialState(true);
}
} catch (error) {
console.error('Failed to load projects:', error);
if (!hasSetInitialState) {
setHasSetInitialState(true);
}
}
}, [projectsManager, hasSetInitialState, isMobile]);
useEffect(() => {
loadProjects();
}, [loadProjects]);
const handleProjectSelect = (project: Project | null) => {
if (project) {
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
navigate(`/project/${project.id}`);
} else {
navigate('/');
}
};
if (isMobile) {
return (
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
{/* Mobile Header */}
<header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{title}
</h1>
</div>
{headerContent}
</header>
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
{/* Backdrop - only covers the area not occupied by the sidebar */}
<div
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={(project) => {
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
handleProjectSelect(project);
}}
/>
</div>
</div>
)}
<div className="container mx-auto px-4 py-6 md:py-8">
{children}
</div>
</div>
);
}
return (
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="w-80 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
className="h-screen sticky top-0"
/>
</div>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col bg-background">
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
{/* Toggle Button - positioned absolutely in top-left corner */}
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
aria-label="Toggle sidebar"
>
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
</Button>
)}
<div className="container mx-auto px-4 py-6 md:py-8">
{children}
</div>
</div>
</div>
</div>
);
}
@@ -1,90 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GitStatusIndicator } from './GitStatusIndicator';
// Mock the useGitStatus hook
vi.mock('@/hooks/useGitStatus', () => ({
useGitStatus: vi.fn(),
}));
import { useGitStatus } from '@/hooks/useGitStatus';
describe('GitStatusIndicator', () => {
it('should not render when not in a git repo', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: false,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('should not render when no uncommitted changes', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: true,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('should render yellow dot when there are uncommitted changes', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: true,
changedFiles: ['file1.txt', 'file2.txt'],
isGitRepo: true,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
const indicator = container.firstChild as HTMLElement;
expect(indicator).toBeTruthy();
expect(indicator.className).toContain('bg-yellow-500');
expect(indicator.className).toContain('rounded-full');
expect(indicator.title).toBe('2 uncommitted changes');
});
it('should handle singular file count in tooltip', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: true,
changedFiles: ['file1.txt'],
isGitRepo: true,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
const indicator = container.firstChild as HTMLElement;
expect(indicator.title).toBe('1 uncommitted change');
});
});
-27
View File
@@ -1,27 +0,0 @@
import { useGitStatus } from '@/hooks/useGitStatus';
import { cn } from '@/lib/utils';
interface GitStatusIndicatorProps {
projectId: string | null;
className?: string;
}
export function GitStatusIndicator({ projectId, className }: GitStatusIndicatorProps) {
const { data: gitStatus } = useGitStatus(projectId);
// Only show the indicator if we're in a git repo and have uncommitted changes
if (!gitStatus?.isGitRepo || !gitStatus?.hasUncommittedChanges) {
return null;
}
return (
<div
className={cn(
"w-2 h-2 bg-yellow-500 rounded-full animate-pulse",
"shadow-sm shadow-yellow-500/50",
className
)}
title={`${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`}
/>
);
}
-262
View File
@@ -1,262 +0,0 @@
import { useState, useMemo } from 'react';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { cn } from '@/lib/utils';
import { AISettingsDialog } from '@/components/ai/AISettingsDialog';
interface ModelSelectorProps {
value: string;
onChange: (value: string) => void;
className?: string;
disabled?: boolean;
placeholder?: string;
}
export function ModelSelector({
value,
onChange,
className,
disabled = false,
placeholder = "Select or enter a model...",
}: ModelSelectorProps) {
const [open, setOpen] = useState(false);
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
const [settingsOpen, setSettingsOpen] = useState(false);
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels();
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Group models by provider
const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof models> = {};
for (const model of models) {
if (!groups[model.provider]) {
groups[model.provider] = [];
}
groups[model.provider].push(model);
}
return groups;
}, [models]);
// Don't auto-initialize with recently used models
// Let the parent component handle initialization
const handleSelect = (selectedValue: string) => {
if (selectedValue === '__custom__') {
setIsCustomInput(true);
setCustomValue(value);
setOpen(false);
return;
}
if (selectedValue === '__manage_providers__') {
setSettingsOpen(true);
setOpen(false);
return;
}
onChange(selectedValue);
addRecentlyUsedModel(selectedValue);
setOpen(false);
};
const handleCustomSubmit = () => {
if (customValue.trim()) {
onChange(customValue.trim());
addRecentlyUsedModel(customValue.trim());
setIsCustomInput(false);
setCustomValue('');
}
};
const handleCustomKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault();
handleCustomSubmit();
} else if (e.key === 'Escape') {
setIsCustomInput(false);
setCustomValue('');
}
};
if (isCustomInput) {
return (
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
);
}
return (
<>
<AISettingsDialog
open={settingsOpen}
onOpenChange={setSettingsOpen}
/>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder}
</span>
<ChevronDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-80 p-0" align="end">
<Command>
{isConfigured && <CommandInput placeholder="Search models..." className="h-9" />}
<CommandList className="max-h-[300px]">
{/* Custom model option and manage providers */}
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
Enter custom model...
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
Manage providers...
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>No models found.</p>
<p className="mt-2 text-xs">Try using a custom model instead.</p>
</div>
</CommandEmpty>
{recentlyUsedModels.length > 0 && (
<CommandGroup heading="Recently Used">
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{recentlyUsedModels.length > 0 && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading="Loading Models...">
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading="Error Loading Models">
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
Retry
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
</CommandItem>
))}
</CommandGroup>
</div>
))}
</CommandList>
</Command>
</PopoverContent>
</Popover>
</>
);
}
-359
View File
@@ -1,359 +0,0 @@
import { useState, useEffect } from 'react';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useGitStatus } from '@/hooks/useGitStatus';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import {
Calendar,
Folder,
GitBranch,
Package,
FileText,
GitCommit,
GitMerge,
Globe,
Clock,
User,
Hash,
AlertCircle,
CheckCircle,
Plus,
Minus,
Edit,
Eye
} from 'lucide-react';
interface ProjectInfoDialogProps {
project: Project;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface ProjectMetadata {
description?: string;
version?: string;
nostrRepoAddress?: string;
fileCount?: number;
}
export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDialogProps) {
const [metadata, setMetadata] = useState<ProjectMetadata>({});
const [isLoading, setIsLoading] = useState(false);
const projectsManager = useProjectsManager();
const gitStatus = useGitStatus(project.id);
useEffect(() => {
if (!open) return;
const loadProjectMetadata = async () => {
setIsLoading(true);
try {
const meta: ProjectMetadata = {};
// Try to read package.json
try {
const packageJsonContent = await projectsManager.readFile(project.id, 'package.json');
const packageJson = JSON.parse(packageJsonContent);
meta.description = packageJson.description;
meta.version = packageJson.version;
} catch {
// package.json doesn't exist or is invalid
}
// Get Nostr repo address
try {
const repoAddress = await projectsManager.getNostrRepoAddress(project.id);
if (repoAddress) {
meta.nostrRepoAddress = repoAddress;
}
} catch {
// No Nostr repo configured
}
// Calculate file count and size (simplified)
try {
const files = await projectsManager.listFiles(project.id);
meta.fileCount = files.length;
} catch {
// Can't read directory
}
setMetadata(meta);
} catch (error) {
console.error('Failed to load project metadata:', error);
} finally {
setIsLoading(false);
}
};
loadProjectMetadata();
}, [open, project.id, projectsManager]);
const formatDate = (date: Date) => {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(date);
};
const formatDistanceToNow = (date: Date) => {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (diffInSeconds < 60) return 'just now';
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`;
if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`;
return `${Math.floor(diffInSeconds / 31536000)} years ago`;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" />
{project.name}
</DialogTitle>
<DialogDescription>
Project information and metadata
</DialogDescription>
</DialogHeader>
{isLoading ? (
<div className="space-y-4">
<div className="animate-pulse">
<div className="h-4 bg-muted rounded w-3/4 mb-2"></div>
<div className="h-4 bg-muted rounded w-1/2"></div>
</div>
</div>
) : (
<div className="space-y-6">
{/* Basic Information */}
<div className="space-y-3">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
Basic Information
</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="flex items-center gap-2">
<Folder className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Project ID:</span>
<code className="bg-muted px-1.5 py-0.5 rounded text-xs">{project.id}</code>
</div>
<div className="flex items-center gap-2">
<Calendar className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Last Modified:</span>
<span>{formatDistanceToNow(project.lastModified)}</span>
</div>
{metadata.version && (
<div className="flex items-center gap-2">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Version:</span>
<Badge variant="secondary">{metadata.version}</Badge>
</div>
)}
{metadata.fileCount !== undefined && (
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Files:</span>
<span>{metadata.fileCount}</span>
</div>
)}
</div>
<div className="text-sm">
<span className="text-muted-foreground">Created:</span>
<span className="ml-2">{formatDate(project.lastModified)}</span>
</div>
{metadata.description && (
<div className="text-sm">
<span className="text-muted-foreground">Description:</span>
<p className="mt-1 text-foreground">{metadata.description}</p>
</div>
)}
</div>
{/* Nostr Information */}
{metadata.nostrRepoAddress && (
<>
<Separator />
<div className="space-y-3">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
<GitBranch className="h-4 w-4" />
Nostr Repository
</h3>
<div className="text-sm">
<span className="text-muted-foreground">Repository Address:</span>
<code className="ml-2 bg-muted px-1.5 py-0.5 rounded text-xs break-all">
{metadata.nostrRepoAddress}
</code>
</div>
</div>
</>
)}
{/* Git Status Information */}
<Separator />
<div className="space-y-3">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
<GitCommit className="h-4 w-4" />
Git Repository
</h3>
{gitStatus.isLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<Skeleton className="h-4 w-2/3" />
</div>
) : !gitStatus.data?.isGitRepo ? (
<div className="text-sm text-muted-foreground flex items-center gap-2">
<AlertCircle className="h-4 w-4" />
This project is not a Git repository
</div>
) : (
<div className="space-y-4">
{/* Repository Status */}
<div className="grid grid-cols-2 gap-4 text-sm">
{/* Current Branch */}
<div className="flex items-center gap-2">
<GitBranch className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Branch:</span>
<Badge variant="outline" className="text-xs">
{gitStatus.data?.currentBranch || 'unknown'}
</Badge>
</div>
{/* Uncommitted Changes */}
<div className="flex items-center gap-2">
{gitStatus.data?.hasUncommittedChanges ? (
<>
<AlertCircle className="h-4 w-4 text-orange-500" />
<span className="text-muted-foreground">Status:</span>
<Badge variant="destructive" className="text-xs">
{gitStatus.data.changedFiles.length} uncommitted changes
</Badge>
</>
) : (
<>
<CheckCircle className="h-4 w-4 text-green-500" />
<span className="text-muted-foreground">Status:</span>
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
Clean working tree
</Badge>
</>
)}
</div>
{/* Total Commits */}
<div className="flex items-center gap-2">
<Hash className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Commits:</span>
<span>{gitStatus.data?.totalCommits || 0}</span>
</div>
{/* All Branches */}
<div className="flex items-center gap-2">
<GitMerge className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Branches:</span>
<span>{gitStatus.data?.branches.length || 0}</span>
</div>
</div>
{/* Latest Commit */}
{gitStatus.data?.latestCommit && (
<div className="space-y-2">
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Latest Commit
</h4>
<div className="bg-muted/30 rounded-md p-3 space-y-2">
<div className="flex items-start gap-2">
<GitCommit className="h-4 w-4 text-muted-foreground mt-0.5" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium break-words">
{gitStatus.data.latestCommit.message.split('\n')[0]}
</div>
<div className="text-xs text-muted-foreground font-mono">
{gitStatus.data.latestCommit.oid.substring(0, 7)}
</div>
</div>
</div>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<div className="flex items-center gap-1">
<User className="h-3 w-3" />
{gitStatus.data.latestCommit.author.name}
</div>
<div className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{new Date(gitStatus.data.latestCommit.author.timestamp * 1000).toLocaleDateString()}
</div>
</div>
</div>
</div>
)}
{/* Changed Files */}
{gitStatus.data?.hasUncommittedChanges && gitStatus.data.changedFiles.length > 0 && (
<div className="space-y-2">
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Uncommitted Changes
</h4>
<div className="space-y-1 max-h-32 overflow-y-auto">
{gitStatus.data.changedFiles.map((file, index) => (
<div key={index} className="flex items-center gap-2 text-sm">
{file.status === 'added' && <Plus className="h-3 w-3 text-green-500" />}
{file.status === 'modified' && <Edit className="h-3 w-3 text-blue-500" />}
{file.status === 'deleted' && <Minus className="h-3 w-3 text-red-500" />}
{file.status === 'untracked' && <Eye className="h-3 w-3 text-orange-500" />}
{file.status === 'staged' && <CheckCircle className="h-3 w-3 text-purple-500" />}
<span className="text-muted-foreground capitalize">{file.status}:</span>
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono">
{file.filepath}
</code>
</div>
))}
</div>
</div>
)}
{/* Remotes */}
{gitStatus.data?.remotes && gitStatus.data.remotes.length > 0 && (
<div className="space-y-2">
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Remote Repositories
</h4>
<div className="space-y-1">
{gitStatus.data.remotes.map((remote, index) => (
<div key={index} className="flex items-center gap-2 text-sm">
<Globe className="h-3 w-3 text-muted-foreground" />
<span className="text-muted-foreground font-medium">{remote.name}:</span>
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono break-all">
{remote.url}
</code>
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
+293 -120
View File
@@ -1,80 +1,22 @@
import React, { useState, memo } from 'react';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Folder, Download, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react';
import { Plus, Loader2, Info, MoreVertical, Trash2, Eye, Star, Bug, Folder, Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Label } from '@/components/ui/label';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { LoginArea } from '@/components/auth/LoginArea';
import { StarButton } from '@/components/StarButton';
import { AISettingsDialog } from '@/components/ai/AISettingsDialog';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import JSZip from 'jszip';
interface ProjectItemProps {
project: Project;
isSelected: boolean;
onSelect: (project: Project) => void;
}
const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) => {
const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(project.id);
const handleClick = () => {
onSelect(project);
navigate(`/project/${project.id}`);
};
return (
<div
className={cn(
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
isSelected && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
)}
>
<div className="w-full p-3 text-left text-sidebar-foreground">
<button
onClick={handleClick}
className="absolute inset-0"
/>
<div className="flex items-center gap-3">
<div className="flex-shrink-0">
{hasRunningSessions ? (
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
) : (
<Folder className="h-4 w-4 text-primary" />
)}
</div>
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1">
<h3 className="font-medium text-sm truncate mb-1">
{project.name}
</h3>
</div>
{/* Star Button */}
<div className="flex-shrink-0 -mt-1 -mr-1 relative">
<StarButton
projectId={project.id}
projectName={project.name}
showToast={false}
className="h-6 w-6 hover:bg-primary/20"
/>
</div>
</div>
</div>
</div>
</div>
);
});
ProjectItem.displayName = 'ProjectItem';
import git from 'isomorphic-git';
interface ProjectSidebarProps {
selectedProject: Project | null;
@@ -89,9 +31,9 @@ export function ProjectSidebar({
}: ProjectSidebarProps) {
const [projects, setProjects] = useState<Project[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isDeleting, setIsDeleting] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const [aiSettingsOpen, setAISettingsOpen] = useState(false);
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const { toast } = useToast();
@@ -119,6 +61,49 @@ export function ProjectSidebar({
navigate('/');
};
const handleDeleteProject = async (project: Project) => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(project.id);
// Remove from local state
setProjects(prev => prev.filter(p => p.id !== project.id));
// If the deleted project was selected, deselect it
if (selectedProject?.id === project.id) {
onSelectProject(null);
navigate('/');
}
toast({
title: "Project deleted",
description: `"${project.name}" has been permanently deleted.`,
});
} catch (error) {
toast({
title: "Failed to delete project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsDeleting(false);
}
};
const handleToggleFavorite = (project: Project) => {
const wasFavorite = favorites.includes(project.id);
const newFavorites = wasFavorite
? favorites.filter(id => id !== project.id)
: [...favorites, project.id];
setFavorites(newFavorites);
toast({
title: wasFavorite ? "Project Unfavorited" : "Project Favorited",
description: `"${project.name}" has been ${wasFavorite ? 'removed from' : 'added to'} your favorites.`,
});
};
const isFavorite = (projectId: string) => favorites.includes(projectId);
const exportFilesAsZip = async (projectName: string) => {
@@ -197,6 +182,93 @@ export function ProjectSidebar({
}
};
const handleExportProject = async (project: Project) => {
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `/projects/${project.id}`;
// Recursive function to add files and directories to zip from a specific project
const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addProjectToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from the project directory
await addProjectToZip(projectPath, zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
// Generate filename with commit hash
let filename = `${project.name}.zip`;
try {
// Get the current commit hash
const commits = await git.log({
fs,
dir: projectPath,
depth: 1,
});
if (commits.length > 0) {
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
filename = `${project.name}-${commitHash}.zip`;
}
} catch (error) {
console.warn('Failed to get commit hash, using project name only:', error);
}
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast({
title: "Project exported successfully",
description: `"${project.name}" has been downloaded as a zip file.`,
});
} catch (error) {
console.error('Failed to export project:', error);
toast({
title: "Failed to export project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
// Sort projects: favorites first, then by lastModified (newest first)
const sortedProjects = projects.sort((a, b) => {
const aIsFavorite = isFavorite(a.id);
@@ -211,49 +283,53 @@ export function ProjectSidebar({
return (
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
{/* Header with Logo */}
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigate('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<span className="text-2xl">🎭</span>
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
<div className="flex items-center gap-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 hover:bg-primary/10">
<MoreVertical className="h-4 w-4 text-primary/60 hover:text-primary" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => navigate('/clone')}
className="flex items-center gap-2 w-full"
>
<GitBranch className="h-4 w-4" />
Import Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleExportFiles}
disabled={isExporting}
className="flex items-center gap-2 w-full"
>
<Download className="h-4 w-4" />
{isExporting ? 'Exporting...' : 'Export Files'}
</DropdownMenuItem>
<div className="p-4 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<button
onClick={() => navigate('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity w-full text-left"
>
<span className="text-2xl">🎭</span>
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
</div>
<DropdownMenuItem
onClick={() => setAISettingsOpen(true)}
className="flex items-center gap-2 w-full"
>
<Settings className="h-4 w-4" />
AI Settings
</DropdownMenuItem>
</DropdownMenuContent>
{/* Info Section */}
<div className="p-4 border-b border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs font-medium text-primary/80 uppercase tracking-wide">
Projects
</Label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-4 w-4 p-0 hover:bg-primary/10">
<MoreVertical className="h-3 w-3 text-primary/60 hover:text-primary" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={handleExportFiles}
disabled={isExporting}
className="flex items-center gap-2 w-full"
>
<Download className="h-4 w-4" />
{isExporting ? 'Exporting...' : 'Export Files'}
</DropdownMenuItem>
<DropdownMenuItem asChild>
<a href="https://soapbox.pub/mkstack" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 w-full">
<Info className="h-4 w-4" />
About MKStack
</a>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<a href="https://github.com/soapbox-pub/mkstack/issues" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 w-full">
<Bug className="h-4 w-4" />
Report an Issue
</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
@@ -292,12 +368,115 @@ export function ProjectSidebar({
) : (
<div className="space-y-1">
{sortedProjects.map((project) => (
<ProjectItem
<div
key={project.id}
project={project}
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
/>
className={cn(
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
selectedProject?.id === project.id && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
)}
>
<button
onClick={() => {
onSelectProject(project);
navigate(`/project/${project.id}`);
}}
className="w-full p-3 text-left text-sidebar-foreground"
>
<div className="flex items-center gap-3">
<Folder className="h-4 w-4 text-primary flex-shrink-0" />
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium text-sm truncate">
{project.name}
</h3>
<div className="flex items-center gap-1 ml-auto">
{isFavorite(project.id) && (
<Star className="h-3 w-3 text-yellow-500 fill-current" />
)}
</div>
</div>
</div>
{/* Dropdown Menu */}
<div className="flex-shrink-0 -mt-1 -mr-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 hover:bg-primary/20"
onClick={(e) => e.stopPropagation()}
>
<MoreVertical className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => handleToggleFavorite(project)}
>
<Star className={cn(
"h-4 w-4 mr-2",
isFavorite(project.id) ? "text-yellow-500 fill-current" : "text-muted-foreground"
)} />
{isFavorite(project.id) ? "Unfavorite" : "Favorite"}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => navigate(`/project/${project.id}`)}
>
<Eye className="h-4 w-4 mr-2" />
Open Project
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleExportProject(project)}
disabled={isExporting}
>
<Download className="h-4 w-4 mr-2" />
{isExporting ? 'Exporting...' : 'Export Project'}
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer"
onSelect={(e) => e.preventDefault()}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Project
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleDeleteProject(project)}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</button>
</div>
))}
</div>
)}
@@ -308,12 +487,6 @@ export function ProjectSidebar({
<div className="p-4 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<LoginArea className="w-full" />
</div>
{/* AI Settings Dialog */}
<AISettingsDialog
open={aiSettingsOpen}
onOpenChange={setAISettingsOpen}
/>
</div>
);
}
+272
View File
@@ -0,0 +1,272 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
Folder,
GitBranch,
Download,
ExternalLink,
Users,
Globe,
Cloud,
HardDrive,
RefreshCw,
Upload
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { nip19 } from 'nostr-tools';
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
import type { UnifiedRepo } from '@/hooks/useRepos';
interface RepoCardProps {
repo: UnifiedRepo;
onRepoCloned?: () => void;
className?: string;
}
export function RepoCard({ repo, onRepoCloned, className }: RepoCardProps) {
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const [isCloning, setIsCloning] = useState(false);
const getStatusIcon = () => {
switch (repo.status) {
case 'local-only':
return <HardDrive className="h-4 w-4 text-blue-500" />;
case 'published':
return <Upload className="h-4 w-4 text-green-500" />;
case 'remote-only':
return <Cloud className="h-4 w-4 text-orange-500" />;
case 'synced':
return <RefreshCw className="h-4 w-4 text-emerald-500" />;
}
};
const getStatusText = () => {
switch (repo.status) {
case 'local-only':
return 'Local only';
case 'published':
return 'Published';
case 'remote-only':
return 'Remote only';
case 'synced':
return 'Synced';
}
};
const getStatusColor = () => {
switch (repo.status) {
case 'local-only':
return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
case 'published':
return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
case 'remote-only':
return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200';
case 'synced':
return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200';
}
};
const handleCardClick = () => {
if (repo.localProject) {
navigate(`/project/${repo.localProject.id}`);
}
};
const handleCloneRepo = async () => {
if (!repo.nostrRepo || !repo.cloneUrls.length) {
toast({
title: "No clone URL",
description: "This repository doesn't have any clone URLs configured.",
variant: "destructive",
});
return;
}
setIsCloning(true);
try {
await projectsManager.init();
// Create project directory
const projectPath = `/projects/${repo.id}`;
// Clone the repository
const cloneUrl = repo.cloneUrls[0]; // Use the first clone URL
await git.clone({
fs: projectsManager.fs,
http,
dir: projectPath,
url: cloneUrl,
singleBranch: true,
depth: 1,
});
// Set git config to mark this as a nostr-enabled project
const naddr = nip19.naddrEncode({
identifier: repo.id,
pubkey: repo.nostrRepo.event.pubkey,
kind: 30617,
relays: repo.relays.length > 0 ? repo.relays : undefined,
});
await git.setConfig({
fs: projectsManager.fs,
dir: projectPath,
path: 'nostr.repo',
value: naddr,
});
toast({
title: "Repository cloned",
description: `${repo.name} has been cloned to your projects.`,
});
// Call the callback to refresh the repos list
if (onRepoCloned) {
onRepoCloned();
}
} catch (error) {
console.error('Failed to clone repository:', error);
toast({
title: "Clone failed",
description: `Failed to clone ${repo.name}. Please try again.`,
variant: "destructive",
});
} finally {
setIsCloning(false);
}
};
const canOpen = repo.status === 'local-only' || repo.status === 'published' || repo.status === 'synced';
const canClone = repo.status === 'remote-only' && repo.cloneUrls.length > 0;
return (
<Card
className={cn(
"transition-all duration-300 bg-gradient-to-br from-card to-card/80 border-primary/10 hover:border-primary/20",
canOpen && "cursor-pointer hover:shadow-xl hover:shadow-primary/10 hover:scale-[1.02]",
className
)}
onClick={canOpen ? handleCardClick : undefined}
tabIndex={canOpen ? 0 : undefined}
onKeyDown={canOpen ? (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleCardClick();
}
} : undefined}
>
<CardHeader className="pb-2">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<CardTitle className="text-base md:text-lg flex items-center gap-2 truncate">
{repo.status === 'remote-only' ? (
<GitBranch className="h-4 w-4 text-primary flex-shrink-0" />
) : (
<Folder className="h-4 w-4 text-primary flex-shrink-0" />
)}
<span className="truncate">{repo.name}</span>
</CardTitle>
{repo.description && (
<CardDescription className="text-sm mt-1 line-clamp-2">
{repo.description}
</CardDescription>
)}
</div>
<div className="flex items-center gap-2 ml-2">
<Badge variant="outline" className={cn("text-xs", getStatusColor())}>
<span className="flex items-center gap-1">
{getStatusIcon()}
{getStatusText()}
</span>
</Badge>
</div>
</div>
<CardDescription className="text-sm">
Modified {repo.lastModified.toLocaleDateString()}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{/* Tags */}
{repo.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{repo.tags.slice(0, 3).map((tag) => (
<Badge key={tag} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.tags.length > 3 && (
<Badge variant="outline" className="text-xs">
+{repo.tags.length - 3}
</Badge>
)}
</div>
)}
{/* Repository info */}
{(repo.maintainers.length > 0 || repo.webUrls.length > 0) && (
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{repo.maintainers.length > 0 && (
<div className="flex items-center gap-1">
<Users className="h-3 w-3" />
<span>{repo.maintainers.length} maintainer{repo.maintainers.length !== 1 ? 's' : ''}</span>
</div>
)}
{repo.webUrls.length > 0 && (
<div className="flex items-center gap-1">
<Globe className="h-3 w-3" />
<span>Web</span>
</div>
)}
</div>
)}
{/* Actions */}
{(canClone || repo.webUrls.length > 0) && (
<div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
{canClone && (
<Button
onClick={handleCloneRepo}
disabled={isCloning}
className="flex-1"
size="sm"
>
{isCloning ? (
<>
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-2"></div>
Cloning...
</>
) : (
<>
<Download className="h-3 w-3 mr-2" />
Clone
</>
)}
</Button>
)}
{repo.webUrls.length > 0 && (
<Button
variant="outline"
size="sm"
onClick={() => window.open(repo.webUrls[0], '_blank')}
className="px-3"
>
<ExternalLink className="h-3 w-3" />
</Button>
)}
</div>
)}
</CardContent>
</Card>
);
}
-37
View File
@@ -1,37 +0,0 @@
import { ReactNode, useMemo, useEffect } from 'react';
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
import { SessionManager } from '@/lib/SessionManager';
import { useFS } from '@/hooks/useFS';
import { useAISettings } from '@/hooks/useAISettings';
interface SessionManagerProviderProps {
children: ReactNode;
}
/**
* Provider that creates and manages the global session manager instance
*/
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
const { fs } = useFS();
const { settings } = useAISettings();
const sessionManager = useMemo(() => {
return new SessionManager(fs, settings);
}, [fs, settings]);
// Cleanup on unmount
useEffect(() => {
return () => {
// Fire and forget cleanup - we don't need to await in useEffect cleanup
sessionManager.cleanup().catch(error => {
console.warn('Failed to cleanup session manager:', error);
});
};
}, [sessionManager]);
return (
<SessionManagerContext.Provider value={sessionManager}>
{children}
</SessionManagerContext.Provider>
);
}
-79
View File
@@ -1,79 +0,0 @@
import { useEffect, useRef } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useToast } from '@/hooks/useToast';
import { useNavigate, useLocation } from 'react-router-dom';
/**
* Global component that monitors AI sessions and shows notifications
* when sessions complete in the background
*/
export function SessionMonitor() {
const sessionManager = useSessionManager();
const { toast } = useToast();
const navigate = useNavigate();
const location = useLocation();
const previousLoadingStates = useRef<Map<string, boolean>>(new Map());
useEffect(() => {
const handleLoadingChanged = (sessionId: string, isLoading: boolean) => {
const wasLoading = previousLoadingStates.current.get(sessionId);
previousLoadingStates.current.set(sessionId, isLoading);
// If session just finished loading (was loading, now not loading)
if (wasLoading && !isLoading) {
const session = sessionManager.getSession(sessionId);
if (!session) return;
// Check if user is currently viewing this project
const currentProjectId = location.pathname.split('/')[2]; // /project/{projectId}
const isCurrentProject = session.projectId === currentProjectId;
// Only show notification if user is not currently viewing this project
if (!isCurrentProject) {
toast({
title: "AI Session Complete",
description: `Finished working on ${session.projectName}`,
action: (
<button
onClick={() => navigate(`/project/${session.projectId}`)}
className="inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus-visible:ring-destructive"
>
View
</button>
)
});
}
}
};
const handleSessionCreated = (sessionId: string) => {
const session = sessionManager.getSession(sessionId);
if (session) {
previousLoadingStates.current.set(sessionId, session.isLoading);
}
};
const handleSessionDeleted = (sessionId: string) => {
previousLoadingStates.current.delete(sessionId);
};
// Initialize with current sessions
sessionManager.getAllSessions().forEach(session => {
previousLoadingStates.current.set(session.id, session.isLoading);
});
// Subscribe to events
sessionManager.on('loadingChanged', handleLoadingChanged);
sessionManager.on('sessionCreated', handleSessionCreated);
sessionManager.on('sessionDeleted', handleSessionDeleted);
return () => {
sessionManager.off('loadingChanged', handleLoadingChanged);
sessionManager.off('sessionCreated', handleSessionCreated);
sessionManager.off('sessionDeleted', handleSessionDeleted);
};
}, [sessionManager, toast, navigate, location.pathname]);
// This component doesn't render anything
return null;
}
+404 -279
View File
@@ -1,185 +1,44 @@
import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useState, useRef, useEffect } from 'react';
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import { Send, Square, Loader2 } from 'lucide-react';
import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useJSRuntime } from '@/hooks/useJSRuntime';
import { useKeepAlive } from '@/hooks/useKeepAlive';
import { useAIChat } from '@/hooks/useAIChat';
import type { AIMessage } from '@/lib/SessionManager';
import { ModelSelector } from '@/components/ModelSelector';
import { AIMessageItem } from '@/components/AIMessageItem';
import { copyDirectory } from '@/lib/copyFiles';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
import { bytesToHex } from 'nostr-tools/utils';
import { MessageItem } from '@/components/ai/MessageItem';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
import { NostrReadTagTool } from '@/lib/tools/NostrReadTagTool';
import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool';
import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { makeSystemPrompt } from '@/lib/system';
import { assistantContentEmpty } from '@/lib/ai-messages';
import { buildProject } from "@/lib/build";
interface ChatPaneProps {
projectId: string;
projectName: string;
onNewChat?: () => void;
onBuild?: () => void;
onDeploy?: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
isBuildLoading?: boolean;
isDeployLoading?: boolean;
onBuildComplete?: (projectId: string) => void;
}
export interface ChatPaneRef {
startNewSession: () => void;
}
type AIMessage = (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
projectId,
projectName,
onNewChat: _onNewChat,
onBuild: _onBuild,
onDeploy: _onDeploy,
onFirstInteraction,
onLoadingChange,
isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading,
isDeployLoading: externalIsDeployLoading
}, ref) => {
export function ChatPane({ projectId, projectName, onBuildComplete }: ChatPaneProps) {
const [messages, setMessages] = useState<AIMessage[]>([]);
const [input, setInput] = useState('');
const [systemPrompt, setSystemPrompt] = useState('');
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
const isDeployLoading = externalIsDeployLoading || false;
const [isLoading, setIsLoading] = useState(false);
const [isBuildLoading, setIsBuildLoading] = useState(false);
const [isDeployLoading, setIsDeployLoading] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const { isConfigured, settings, addRecentlyUsedModel } = useAISettings();
const [providerModel, setProviderModel] = useState(() => {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
});
const [searchParams, setSearchParams] = useSearchParams();
const { settings, isConfigured } = useAISettings();
const { fs: browserFS } = useFS();
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const customTools = useMemo(() => ({
git_commit: new GitCommitTool(browserFS, cwd),
text_editor_view: new TextEditorViewTool(browserFS, cwd),
text_editor_write: new TextEditorWriteTool(browserFS, cwd),
text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd),
npm_add_package: new NpmAddPackageTool(browserFS, cwd),
npm_remove_package: new NpmRemovePackageTool(browserFS, cwd),
build_project: new BuildProjectTool(browserFS, cwd),
nostr_read_nip: new NostrReadNipTool(),
nostr_fetch_event: new NostrFetchEventTool(),
nostr_read_kind: new NostrReadKindTool(),
nostr_read_tag: new NostrReadTagTool(),
nostr_read_protocol: new NostrReadProtocolTool(),
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
}), [browserFS, cwd]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
const result: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
for (const [name, tool] of Object.entries(customTools)) {
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
}
return result;
}, [customTools]);
useEffect(() => {
makeSystemPrompt({
cwd,
fs: browserFS,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(tools),
}).then(setSystemPrompt)
}, [browserFS, cwd, tools]);
const {
messages,
streamingMessage,
isLoading: internalIsLoading,
sendMessage,
startGeneration,
stopGeneration,
startNewSession: internalStartNewSession,
} = useAIChat({
projectId,
projectName,
tools,
customTools,
systemPrompt,
onUpdateMetadata: (title, description) => {
updateMetadata(title, description);
}
});
// Use external loading state if provided, otherwise use internal state
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
// Notify parent of loading state changes
useEffect(() => {
if (onLoadingChange) {
onLoadingChange(internalIsLoading);
}
}, [internalIsLoading, onLoadingChange]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
const autostart = searchParams.get('autostart');
const urlModel = searchParams.get('model');
if (autostart === 'true' && isConfigured && messages.length > 0 && !isLoading) {
const lastMessage = messages[messages.length - 1];
// If the last message is from the user, auto-start the AI
if (lastMessage.role === 'user') {
// Use model from URL if available, otherwise use current selection
const modelToUse = urlModel?.trim() || providerModel.trim();
if (modelToUse) {
// Update provider model if it came from URL
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
setProviderModel(urlModel.trim());
}
// Clear the autostart and model parameters so they don't trigger again
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
// Start AI generation
addRecentlyUsedModel(modelToUse);
startGeneration(modelToUse);
}
}
}
}, [searchParams, setSearchParams, isConfigured, messages, isLoading, startGeneration, providerModel, setProviderModel, addRecentlyUsedModel]);
const { runtime } = useJSRuntime();
// Keep-alive functionality to prevent tab throttling during AI processing
const { updateMetadata } = useKeepAlive({
@@ -195,10 +54,117 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
]
});
const addMessage = (message: AIMessage) => {
setMessages((prev) => {
const messageMap = new Map(prev.map(m => [m.id, m])).set(message.id, message);
return Array.from(messageMap.values());
});
};
const addMessages = (newMessages: AIMessage[]) => {
setMessages((prev) => {
const messageMap = new Map(prev.map(m => [m.id, m]));
newMessages.forEach(msg => messageMap.set(msg.id, msg));
return Array.from(messageMap.values());
});
};
const runBuild = async () => {
if (isBuildLoading) return;
setIsBuildLoading(true);
updateMetadata('Shakespeare', `Building ${projectName}...`);
const dist = await buildProject({
fs: browserFS,
projectPath: `/projects/${projectId}`,
domParser: new DOMParser(),
target: "esnext",
});
console.log(dist);
// Delete all existing files in "dist" directory
try {
for (const file of await browserFS.readdir(`/projects/${projectId}/dist`)) {
await browserFS.unlink(`/projects/${projectId}/dist/${file}`);
}
} catch {
// Ignore errors (e.g., directory doesn't exist)
}
await browserFS.mkdir(`/projects/${projectId}/dist`, { recursive: true });
for (const [path, contents] of Object.entries(dist)) {
await browserFS.writeFile(`/projects/${projectId}/dist/${path}`, contents);
}
setIsBuildLoading(false);
};
const runDeploy = async () => {
if (isDeployLoading) return;
setIsDeployLoading(true);
updateMetadata('Shakespeare', `Deploying ${projectName}...`);
try {
const runtimeFS = await runtime.fs();
const sk = generateSecretKey();
const pubkey = getPublicKey(sk);
const npub = nip19.npubEncode(pubkey);
const projectUrl = `https://${npub}.nostrdeploy.com`;
console.log('Running deploy for project:', projectId, 'at', projectUrl);
await runtimeFS.mkdir('dist', { recursive: true });
await runtimeFS.writeFile('.env.nostr-deploy.local', `# Nostr Deploy CLI Configuration
# This file contains sensitive information - do not commit to version control
# Nostr Authentication
NOSTR_PRIVATE_KEY=${bytesToHex(sk)}
NOSTR_PUBLIC_KEY=${pubkey}
NOSTR_RELAYS=wss://relay.nostr.band,wss://nostrue.com,wss://purplerelay.com,wss://relay.primal.net,wss://ditto.pub/relay
# Blossom File Storage
BLOSSOM_SERVERS=https://cdn.hzrd149.com,https://blossom.primal.net,https://blossom.band,https://blossom.f7z.io
# Deployment Settings
BASE_DOMAIN=nostrdeploy.com`);
// Copy "dist" files to runtime filesystem
const distPath = `/projects/${projectId}/dist`;
try {
await copyDirectory(browserFS, runtimeFS, distPath, 'dist');
console.log('Successfully copied dist to runtime');
} catch (error) {
console.error('Failed to copy dist to runtime:', error);
return;
}
const proc = await runtime.spawn('npx', ["-y", "nostr-deploy-cli", "deploy"]);
await proc.exit;
console.log('Project deployed:', projectUrl);
} catch (error) {
console.error('Deploy failed:', error);
} finally {
setIsDeployLoading(false);
}
};
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Add welcome message
addMessage({
id: generateId(),
role: 'assistant',
content: `Hello! I'm here to help you build "${projectName}". I can help you edit files, add new features, and build your Nostr website. What would you like to work on?`,
});
}, [projectName, projectId]);
useEffect(() => {
if (scrollAreaRef.current && messages) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
@@ -209,23 +175,171 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
container.scrollTop = container.scrollHeight;
}
}
}, [messages, streamingMessage, isLoading]);
}, [messages, isLoading]);
const createAIChat = async (projectId: string, messages: CoreMessage[]) => {
if (!isConfigured) {
throw new Error('AI settings not configured');
}
// Create a custom fetch function for the AI provider
const customFetch = async (url: string, options: RequestInit) => {
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${settings.apiKey}`,
},
});
};
// Import the appropriate provider based on the base URL
const { createOpenAI } = await import('@ai-sdk/openai');
const openai = createOpenAI({
baseURL: settings.baseUrl,
apiKey: settings.apiKey,
fetch: settings.baseUrl.includes('openrouter.ai') ? customFetch : undefined,
});
const provider = openai(settings.model);
const cwd = `/projects/${projectId}`;
const result = await generateText({
model: provider,
messages,
maxSteps: 100,
onStepFinish(stepResult) {
console.log(stepResult);
addMessages(stepResult.response.messages);
// Update media session with current step info
const lastMessage = stepResult.response.messages[stepResult.response.messages.length - 1];
if (lastMessage?.role === 'tool') {
const toolName = lastMessage.content?.[0]?.toolName;
if (toolName) {
updateMetadata('Shakespeare', `Working on ${projectName} - ${toolName}`);
}
}
},
tools: {
git_commit: new GitCommitTool(browserFS, cwd),
text_editor_view: new TextEditorViewTool(browserFS, cwd),
text_editor_write: new TextEditorWriteTool(browserFS, cwd),
text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd),
npm_add_package: new NpmAddPackageTool(browserFS, cwd),
npm_remove_package: new NpmRemovePackageTool(browserFS, cwd),
},
system: `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project and manage npm packages.
Key capabilities:
- Read and write files in the project
- List directory contents
- Check if files exist
- Build the project using Vite
- Get project structure overview
- Search through files
- Add and remove npm packages
- Install dependencies and dev dependencies
- Commit changes to git with automatic staging
Guidelines:
- Always check if files exist before writing to avoid overwriting
- Provide helpful explanations of what you're doing
- Suggest improvements and best practices
- Use modern React patterns and TypeScript
- Follow Nostr protocol standards when relevant
- Ensure the project builds successfully
The project uses:
- React 18 with TypeScript
- Vite for building
- TailwindCSS for styling
- Nostrify for Nostr integration
- shadcn/ui components
When creating new components or pages, follow the existing patterns in the codebase.`
});
// After the entire generation is complete, check if we should auto-build
console.log('Agent finished with reason:', result.finishReason);
// Only auto-build if:
// 1. The agent completed successfully (not stopped due to errors or limits)
// 2. The previous response before the stop was from the assistant invoking tool calls
// (meaning actual work was performed, not just conversational response)
const responseMessages = result.response.messages;
const hasToolResults = responseMessages.some(msg => msg.role === 'tool');
if (result.finishReason === 'stop' && hasToolResults) {
console.log('Agent performed tool work successfully, auto-building project...');
setTimeout(async () => {
if (isBuildLoading || isDeployLoading) {
addMessage({
id: generateId(),
role: 'assistant',
content: '⏸️ Build or deploy already in progress. Skipping auto-build.',
});
return;
}
try {
await runBuild();
if (onBuildComplete) {
onBuildComplete(projectId);
}
addMessage({
id: generateId(),
role: 'assistant',
content: '✅ Agent completed successfully. Project built! Switch to the "Preview" tab to see your changes.',
});
} catch (error) {
console.error('Auto-build failed:', error);
addMessage({
id: generateId(),
role: 'assistant',
content: `❌ Auto-build failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
});
}
}, 1000);
} else if (result.finishReason === 'stop' && !hasToolResults) {
console.log('Agent completed but no tool work was performed - skipping auto-build');
} else {
console.log('Agent finished with reason:', result.finishReason, '- skipping auto-build');
}
return result;
};
const handleSend = async () => {
if (!input.trim() || isLoading || !providerModel.trim()) return;
if (!input.trim() || isLoading) return;
const messageContent = input;
const modelToUse = providerModel.trim();
const userMessage: AIMessage = {
id: generateId(),
role: 'user',
content: input,
};
addMessage(userMessage);
setInput('');
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
setIsLoading(true);
try {
await sendMessage(messageContent, modelToUse);
const aiMessages: AIMessage[] = [...messages, userMessage];
updateMetadata('Shakespeare', `Processing your request for ${projectName}...`);
await createAIChat(projectId, aiMessages);
} catch (error) {
console.error('AI chat error:', error);
// Error handling is done in the useAIChat hook
const errorMessage: AIMessage = {
id: generateId(),
role: 'assistant',
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.',
};
addMessage(errorMessage);
} finally {
setIsLoading(false);
}
};
@@ -240,21 +354,31 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const handleFirstInteraction = () => {
// This will be handled automatically by the useKeepAlive hook
// when isLoading becomes true after user interaction
if (onFirstInteraction) {
onFirstInteraction();
}
};
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
startNewSession: () => {
internalStartNewSession();
}
}), [internalStartNewSession]);
if (!isConfigured) {
return (
<div className="h-full flex flex-col">
<div className="border-b bg-gradient-to-r from-primary/5 to-accent/5 px-4 py-3 flex justify-between items-center">
<div>
<h2 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">AI Assistant</h2>
<p className="text-sm text-muted-foreground">Chat to build your project</p>
</div>
<Button
variant="outline"
size="sm"
className="gap-2 hover:bg-primary/10 hover:border-primary/20"
onClick={() => {
// This will be handled by the AISettingsDialog component
const event = new CustomEvent('openAISettings');
window.dispatchEvent(event);
}}
>
<Settings className="h-4 w-4" />
Settings
</Button>
</div>
<div className="flex-1 flex items-center justify-center bg-gradient-to-br from-primary/5 to-accent/5">
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<div className="text-4xl mb-4">🤖</div>
@@ -263,9 +387,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<p className="text-sm text-muted-foreground mb-4">
Please configure your AI settings to start building with AI assistance.
</p>
<p className="text-sm text-muted-foreground">
Use the menu in the top bar to access AI Settings.
</p>
<Button
variant="outline"
size="sm"
className="gap-2 hover:bg-primary/10 hover:border-primary/20"
onClick={() => {
const event = new CustomEvent('openAISettings');
window.dispatchEvent(event);
}}
>
<Settings className="h-4 w-4" />
Configure AI Settings
</Button>
</div>
</div>
</div>
@@ -273,65 +406,97 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
);
}
return (
<div className="h-full flex flex-col">
<div className="border-b bg-gradient-to-r from-primary/5 to-accent/5 px-4 py-3 flex justify-between items-center">
<div className="min-w-0 flex-1">
<h2 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">AI Assistant</h2>
<p className="text-sm text-muted-foreground hidden sm:block">Chat to build your project</p>
</div>
<div className="flex gap-2">
<GitHistoryDialog projectId={projectId} />
<Button
variant="outline"
size="sm"
className="gap-1 sm:gap-2 hover:bg-primary/10 hover:border-primary/20"
onClick={runBuild}
onMouseDown={handleFirstInteraction}
disabled={isBuildLoading || isDeployLoading}
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
<span className="hidden sm:inline">
{isBuildLoading ? 'Building...' : 'Build'}
</span>
</Button>
<Button
variant="outline"
size="sm"
className="gap-1 sm:gap-2 hover:bg-accent/10 hover:border-accent/20"
onClick={runDeploy}
onMouseDown={handleFirstInteraction}
disabled={isDeployLoading || isBuildLoading}
>
{isDeployLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<CloudUpload className="h-4 w-4" />
)}
<span className="hidden sm:inline">
{isDeployLoading ? 'Deploying...' : 'Deploy'}
</span>
</Button>
</div>
</div>
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
<div className="p-4 space-y-4">
{messages.map((message, index) => {
// Skip assistant messages with no content
if (message.role === 'assistant' && assistantContentEmpty(message.content)) {
return null;
}
// Find the corresponding tool call for tool messages
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
if (message.role === 'tool') {
// Look backwards to find the assistant message with matching tool call
for (let i = index - 1; i >= 0; i--) {
const prevMessage = messages[i];
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
if (toolCall) break;
// For assistant messages, find corresponding tool results
const toolResults: CoreToolMessage[] = [];
if (message.role === 'assistant') {
// Look for tool messages that come after this assistant message
for (let i = index + 1; i < messages.length; i++) {
const nextMessage = messages[i];
if (nextMessage?.role === 'tool') {
toolResults.push(nextMessage);
} else if (nextMessage?.role === 'assistant' || nextMessage?.role === 'user') {
// Stop looking when we hit the next non-tool message
break;
}
}
}
return (
<AIMessageItem
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
<MessageItem
key={index}
message={message}
toolCall={toolCall}
userDisplayName="You"
toolResults={toolResults}
/>
);
})}
{streamingMessage && (
streamingMessage.content ? (
<AIMessageItem
key="streaming-message"
message={streamingMessage as AIMessage}
isCurrentlyLoading
/>
) : (
<div key="streaming-loading" className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
</div>
{isLoading && (
<div className="flex gap-3">
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
<div className="flex space-x-1">
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce"></div>
</div>
</div>
)
)}
{streamingMessage?.tool_calls?.[0]?.type === 'function' && (
<div key="tool-calls-loading" className="-mt-2">
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
<span className="font-medium">
Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
</span>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">Assistant</span>
<span className="text-xs text-muted-foreground">AI</span>
</div>
<div className="text-sm text-muted-foreground">
Thinking...
</div>
</div>
</div>
)}
@@ -339,67 +504,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
<div className="border-t p-4">
{/* Chat Input Container */}
<div className="relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all">
<div className="flex gap-2">
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onFocus={handleFirstInteraction}
placeholder={providerModel.trim() ? "Ask me to add features, edit files, or build your project..." : "Please select a model to start chatting..."}
className="min-h-[52px] max-h-32 resize-none border-0 bg-transparent px-4 py-3 pb-12 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || !providerModel.trim()}
rows={1}
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
placeholder="Ask me to add features, edit files, or build your project..."
className="min-h-[60px] resize-none"
disabled={isLoading}
/>
{/* Bottom Controls Row */}
<div className="absolute bottom-2 left-2 right-2 flex items-center gap-2">
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder="Choose a model..."
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="h-8 w-8 rounded-lg p-0 hover:bg-muted"
>
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={!input.trim() || !providerModel.trim()}
size="sm"
className="h-8 w-8 rounded-lg p-0"
>
<Send className="h-4 w-4" />
</Button>
)}
</div>
</div>
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={!input.trim() || isLoading}
className="self-end"
size="icon"
>
<Send className="h-4 w-4" />
</Button>
</div>
</div>
</div>
);
});
}
+2 -30
View File
@@ -4,21 +4,18 @@ import { Textarea } from '@/components/ui/textarea';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Save, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGitStatus } from '@/hooks/useGitStatus';
interface FileEditorProps {
filePath: string;
content: string;
onSave: (content: string) => void;
isLoading: boolean;
projectId?: string;
}
export function FileEditor({ filePath, content, onSave, isLoading, projectId }: FileEditorProps) {
export function FileEditor({ filePath, content, onSave, isLoading }: FileEditorProps) {
const [editedContent, setEditedContent] = useState(content);
const [isSaving, setIsSaving] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const { data: gitStatus } = useGitStatus(projectId || null);
useEffect(() => {
setEditedContent(content);
@@ -67,36 +64,11 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
return 'font-mono text-sm';
};
// Helper function to get git status for the current file
const getFileGitStatus = (filePath: string) => {
if (!gitStatus?.changedFiles) return null;
const fileChange = gitStatus.changedFiles.find(change => change.filepath === filePath);
return fileChange?.status || null;
};
// Helper function to get styling classes based on git status
const getGitStatusClasses = (status: string | null) => {
switch (status) {
case 'added':
case 'untracked':
return 'text-green-600 dark:text-green-400';
case 'modified':
case 'staged':
return 'text-yellow-600 dark:text-yellow-400';
default:
return '';
}
};
// Get git status for the current file
const currentFileGitStatus = getFileGitStatus(filePath);
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
return (
<div className="h-full flex flex-col">
<CardHeader className="border-b py-2 sm:py-3">
<div className="flex items-center justify-between">
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
<CardTitle className="text-sm sm:text-base truncate flex-1 mr-2">{filePath}</CardTitle>
<div className="flex items-center space-x-1 sm:space-x-2">
{hasChanges && (
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">Unsaved changes</span>
+1 -57
View File
@@ -1,7 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useGitStatus } from '@/hooks/useGitStatus';
import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react';
import { cn } from '@/lib/utils';
@@ -24,53 +23,6 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
const [isLoading, setIsLoading] = useState(true);
const { fs } = useFS();
const projectsManager = useProjectsManager();
const { data: gitStatus } = useGitStatus(projectId);
// Helper function to get git status for a file
const getFileGitStatus = (filePath: string) => {
if (!gitStatus?.changedFiles) return null;
const fileChange = gitStatus.changedFiles.find(change => change.filepath === filePath);
return fileChange?.status || null;
};
// Helper function to get git status for a directory
const getDirectoryGitStatus = (dirPath: string, _children: FileNode[]): 'modified' | 'added' | null => {
if (!gitStatus?.changedFiles) return null;
// Check if any files in this directory or subdirectories have changes
const hasChanges = gitStatus.changedFiles.some(change =>
change.filepath.startsWith(dirPath + '/') ||
(dirPath === '' && !change.filepath.includes('/'))
);
if (!hasChanges) return null;
// Check if all changes are new files (added/untracked)
const relevantChanges = gitStatus.changedFiles.filter(change =>
change.filepath.startsWith(dirPath + '/') ||
(dirPath === '' && !change.filepath.includes('/'))
);
const allAdded = relevantChanges.every(change =>
change.status === 'added' || change.status === 'untracked'
);
return allAdded ? 'added' : 'modified';
};
// Helper function to get styling classes based on git status
const getGitStatusClasses = (status: string | null) => {
switch (status) {
case 'added':
case 'untracked':
return 'text-green-600 dark:text-green-400';
case 'modified':
case 'staged':
return 'text-yellow-600 dark:text-yellow-400';
default:
return '';
}
};
const buildFileTree = useCallback(async (projectId: string, dirPath: string): Promise<FileNode[]> => {
const items = await projectsManager.listFiles(projectId, dirPath);
@@ -155,14 +107,6 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
const renderNode = (node: FileNode, depth: number = 0) => {
const isSelected = selectedFile === node.path;
// Get git status for this node
const gitFileStatus = node.type === 'file' ? getFileGitStatus(node.path) : null;
const gitDirStatus = node.type === 'directory' ? getDirectoryGitStatus(node.path, node.children || []) : null;
const gitStatus = gitFileStatus || gitDirStatus;
// Get styling classes for git status
const gitStatusClasses = getGitStatusClasses(gitStatus);
return (
<div key={node.path}>
<div
@@ -189,7 +133,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
<File className="h-4 w-4 text-gray-500 flex-shrink-0" />
</>
)}
<span className={cn("text-sm truncate", gitStatusClasses)}>{node.name}</span>
<span className="text-sm truncate">{node.name}</span>
</div>
{node.type === 'directory' && node.isOpen && node.children && (
+2 -12
View File
@@ -6,7 +6,6 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { RefreshCw, FolderOpen, ArrowLeft } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -354,10 +353,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
{mobileCodeView === 'explorer' ? (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<GitStatusIndicator projectId={projectId} />
</div>
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
</div>
<ScrollArea className="flex-1">
<FileTree
@@ -381,7 +377,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<h3 className="font-semibold flex-1 truncate bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{selectedFile ? selectedFile.split('/').pop() : 'File Editor'}
</h3>
<GitStatusIndicator projectId={projectId} />
</div>
<div className="flex-1">
{selectedFile ? (
@@ -390,7 +385,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
@@ -418,10 +412,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="h-full flex">
<div className="w-1/3 border-r">
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<GitStatusIndicator projectId={projectId} />
</div>
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
</div>
<ScrollArea className="h-[calc(100%-60px)]">
<FileTree
@@ -439,7 +430,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
-65
View File
@@ -1,65 +0,0 @@
import { Button } from '@/components/ui/button';
import { Star } from 'lucide-react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
interface StarButtonProps {
projectId: string;
projectName: string;
className?: string;
size?: 'sm' | 'default' | 'lg';
variant?: 'ghost' | 'outline' | 'default';
showToast?: boolean;
}
export function StarButton({
projectId,
projectName,
className,
size = 'sm',
variant = 'ghost',
showToast = true
}: StarButtonProps) {
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const { toast } = useToast();
const isFavorite = favorites.includes(projectId);
const handleToggleFavorite = (e: React.MouseEvent) => {
e.stopPropagation(); // Prevent triggering parent click events
const newFavorites = isFavorite
? favorites.filter(id => id !== projectId)
: [...favorites, projectId];
setFavorites(newFavorites);
if (showToast) {
toast({
title: isFavorite ? "Project Unfavorited" : "Project Favorited",
description: `"${projectName}" has been ${isFavorite ? 'removed from' : 'added to'} your favorites.`,
});
}
};
return (
<Button
variant={variant}
size={size}
onClick={handleToggleFavorite}
className={cn(
"h-8 w-8 p-0",
className
)}
aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
>
<Star
className={cn(
"h-4 w-4",
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
)}
/>
</Button>
);
}
+50 -324
View File
@@ -1,353 +1,79 @@
import { useState } from 'react';
import { Settings, Trash2, Check } from 'lucide-react';
import { Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useAISettings } from '@/hooks/useAISettings';
import type { AIConnection } from '@/contexts/AISettingsContext';
interface PresetProvider {
id: string;
name: string;
baseURL: string;
apiKeysURL: string;
}
const PRESET_PROVIDERS: PresetProvider[] = [
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
},
{
id: "ppq",
name: "PayPerQ",
baseURL: "https://api.ppq.ai",
apiKeysURL: "https://ppq.ai/api-docs",
},
{
id: "zai",
name: "Z.ai",
baseURL: "https://api.z.ai/api/paas/v4",
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
},
{
id: "moonshot",
name: "Moonshot",
baseURL: "https://api.moonshot.ai/v1",
apiKeysURL: "https://platform.moonshot.ai/console/api-keys",
},
{
id: "openai",
name: "OpenAI",
baseURL: "https://api.openai.com/v1",
apiKeysURL: "https://platform.openai.com/api-keys",
},
{
id: "anthropic",
name: "Anthropic",
baseURL: "https://api.anthropic.com/v1",
apiKeysURL: "https://console.anthropic.com/settings/keys",
},
{
id: "xai",
name: "xAI",
baseURL: "https://api.x.ai/v1",
apiKeysURL: "https://console.x.ai",
},
];
interface AISettingsDialogProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISettingsDialogProps = {}) {
export function AISettingsDialog() {
const { settings, updateSettings, isConfigured } = useAISettings();
const [internalOpen, setInternalOpen] = useState(false);
// Use controlled or internal state
const open = controlledOpen !== undefined ? controlledOpen : internalOpen;
const setOpen = onOpenChange || setInternalOpen;
const [localProviders, setLocalProviders] = useState(settings.providers);
const [customProviderName, setCustomProviderName] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const [open, setOpen] = useState(false);
const [localSettings, setLocalSettings] = useState(settings);
const handleSave = () => {
updateSettings({ providers: localProviders });
updateSettings(localSettings);
setOpen(false);
};
const handleCancel = () => {
setLocalProviders(settings.providers);
setCustomProviderName('');
setCustomBaseURL('');
setCustomApiKey('');
setPresetApiKeys({});
setLocalSettings(settings);
setOpen(false);
};
const handleAddPresetProvider = (preset: PresetProvider) => {
const apiKey = presetApiKeys[preset.id] || '';
if (!apiKey.trim()) return;
const newProvider: AIConnection = {
baseURL: preset.baseURL,
apiKey: apiKey.trim(),
};
setLocalProviders(prev => ({
...prev,
[preset.id]: newProvider,
}));
// Clear the API key input for this preset
setPresetApiKeys(prev => ({
...prev,
[preset.id]: '',
}));
};
const handleAddCustomProvider = () => {
if (!customProviderName.trim() || !customBaseURL.trim()) return;
const newProvider: AIConnection = {
baseURL: customBaseURL.trim(),
apiKey: customApiKey.trim(),
};
setLocalProviders(prev => ({
...prev,
[customProviderName.trim()]: newProvider,
}));
setCustomProviderName('');
setCustomBaseURL('');
setCustomApiKey('');
};
const handleRemoveProvider = (name: string) => {
setLocalProviders(prev => {
const { [name]: removed, ...rest } = prev;
return rest;
});
};
const handleUpdateProvider = (name: string, connection: Partial<AIConnection>) => {
setLocalProviders(prev => ({
...prev,
[name]: {
...prev[name],
...connection,
},
}));
};
const configuredProviderIds = Object.keys(localProviders);
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
return (
<Dialog open={open} onOpenChange={setOpen}>
{/* Only show trigger if not controlled externally */}
{controlledOpen === undefined && (
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2">
<Settings className="h-4 w-4" />
AI Settings
{!isConfigured && (
<span className="ml-1 h-2 w-2 rounded-full bg-red-500" />
)}
</Button>
</DialogTrigger>
)}
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2">
<Settings className="h-4 w-4" />
AI Settings
{!isConfigured && (
<span className="ml-1 h-2 w-2 rounded-full bg-red-500" />
)}
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>AI Settings</DialogTitle>
<DialogDescription>
Configure AI providers by adding your API keys. Settings are stored locally in your browser.
Configure your AI provider settings. These settings are stored locally in your browser.
</DialogDescription>
</DialogHeader>
<div className="space-y-6 py-4">
{/* Configured Providers */}
{configuredProviderIds.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">Configured Providers</h4>
<Accordion type="multiple" className="w-full space-y-2">
{configuredProviderIds.map((providerId) => {
const preset = PRESET_PROVIDERS.find(p => p.id === providerId);
const provider = localProviders[providerId];
const isCustom = !preset;
return (
<AccordionItem key={providerId} value={providerId} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center justify-between w-full mr-3">
<div className="flex items-center gap-2">
<span className="font-medium">
{preset?.name || providerId}
</span>
{isCustom && <Badge variant="outline">Custom</Badge>}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleRemoveProvider(providerId);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${providerId}-baseURL`}>Base URL</Label>
<Input
id={`${providerId}-baseURL`}
placeholder="https://api.example.com/v1"
value={provider?.baseURL || ''}
onChange={(e) => handleUpdateProvider(providerId, { baseURL: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${providerId}-apiKey`}>API Key</Label>
<Input
id={`${providerId}-apiKey`}
type="password"
placeholder="Enter your API key"
value={provider?.apiKey || ''}
onChange={(e) => handleUpdateProvider(providerId, { apiKey: e.target.value })}
/>
</div>
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</div>
)}
{configuredProviderIds.length > 0 && availablePresets.length > 0 && <Separator />}
{/* Available Preset Providers */}
{availablePresets.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">Add Provider</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{availablePresets.map((preset) => (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<h5 className="font-medium">{preset.name}</h5>
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
Get API key
</button>
</div>
<div className="flex gap-2">
<Input
placeholder="Enter your API key"
type="password"
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!presetApiKeys[preset.id]?.trim()}
size="sm"
>
Add
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</div>
)}
{availablePresets.length > 0 && <Separator />}
{/* Custom Provider */}
<div className="space-y-3">
<h4 className="text-sm font-medium">Add Custom Provider</h4>
<Card>
<CardContent className="p-4 space-y-3">
<div className="grid gap-2">
<Label htmlFor="custom-name">Provider Name</Label>
<Input
id="custom-name"
placeholder="e.g., my-custom-api"
value={customProviderName}
onChange={(e) => setCustomProviderName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">Base URL</Label>
<Input
id="custom-baseurl"
placeholder="https://api.example.com/v1"
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-apikey">API Key</Label>
<Input
id="custom-apikey"
type="password"
placeholder="Enter your API key (optional)"
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
</div>
<Button
onClick={handleAddCustomProvider}
disabled={
!customProviderName.trim() ||
!customBaseURL.trim() ||
customProviderName.trim() in localProviders
}
size="sm"
className="gap-2"
>
<Check className="h-4 w-4" />
Add Custom Provider
</Button>
{customProviderName.trim() in localProviders && (
<p className="text-sm text-destructive">
Provider with this name already exists
</p>
)}
</CardContent>
</Card>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label htmlFor="apiKey">API Key</Label>
<Input
id="apiKey"
type="password"
placeholder="Enter your API key"
value={localSettings.apiKey}
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
/>
{!localSettings.apiKey && (
<p className="text-sm text-muted-foreground">
Required for AI functionality
</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="baseUrl">Base URL</Label>
<Input
id="baseUrl"
placeholder="https://openrouter.ai/api/v1"
value={localSettings.baseUrl}
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="model">Model</Label>
<Input
id="model"
placeholder="anthropic/claude-sonnet-4"
value={localSettings.model}
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
/>
</div>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleCancel}>
Cancel
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { AssistantContent } from './AssistantContent';
import { TestApp } from '@/test/TestApp';
import type { CoreToolMessage } from 'ai';
describe('AssistantContent', () => {
const mockToolResults: CoreToolMessage[] = [];
describe('Build Action Detection', () => {
it('should render build action for auto-build success message', () => {
const content = '✅ Agent completed successfully. Project built and preview updated!';
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
// Check if BuildAction component is rendered with auto-build title
expect(screen.getByText('Auto-Build Project')).toBeInTheDocument();
});
it('should render regular markdown for non-build-action string content', () => {
const content = 'Hello, I can help you with your project.';
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
expect(screen.getByText('Hello, I can help you with your project.')).toBeInTheDocument();
expect(screen.queryByText(/Project|Action/)).not.toBeInTheDocument();
});
it('should render tool calls for array content with tool-call items', () => {
const content = [
{ type: 'tool-call' as const, toolName: 'some_custom_tool', toolCallId: 'test-id', args: { param1: 'value1' } }
];
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
expect(screen.getByText(/some_custom_tool/)).toBeInTheDocument();
});
});
});
+419
View File
@@ -0,0 +1,419 @@
import { memo } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Code } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { DiffRenderer } from '@/components/ai/DiffRenderer';
import { ScriptRunner } from '@/components/ai/ScriptRunner';
import { FileViewer } from '@/components/ai/FileViewer';
import { FileWriter } from '@/components/ai/FileWriter';
import { ShellCommand } from '@/components/ai/ShellCommand';
import { PackageManager } from '@/components/ai/PackageManager';
import { GitCommit } from '@/components/ai/GitCommit';
import { BuildAction } from '@/components/ai/BuildAction';
import type { CoreAssistantMessage, CoreToolMessage } from 'ai';
interface AssistantContentProps {
content: CoreAssistantMessage['content'];
toolResults?: CoreToolMessage[];
}
export const AssistantContent = memo(({ content, toolResults = [] }: AssistantContentProps) => {
// Helper function to find tool result by call ID
const findToolResult = (toolCallId: string) => {
for (const toolMessage of toolResults) {
if (toolMessage.content) {
for (const resultPart of toolMessage.content) {
if (resultPart.toolCallId === toolCallId) {
return resultPart;
}
}
}
}
return null;
};
// Helper function to extract result text and error status
const extractToolResult = (toolCallId: string): { result?: string; isError: boolean } => {
const toolResult = findToolResult(toolCallId);
if (!toolResult) {
return { isError: false };
}
// Handle direct string results
if (typeof toolResult.result === 'string') {
return {
result: toolResult.result,
isError: toolResult.isError || false
};
}
// Handle CallToolResult structure
if (toolResult.result && typeof toolResult.result === 'object') {
const callResult = toolResult.result as {
content?: Array<{ type: string; text: string }>;
isError?: boolean;
};
if (callResult.content && Array.isArray(callResult.content) && callResult.content[0]?.text) {
return {
result: callResult.content[0].text,
isError: callResult.isError || false
};
}
}
return { isError: toolResult.isError || false };
};
// Helper function to check if text represents a build action
const isBuildAction = (text: string): boolean => {
return /(✅|❌|⏸️|🎉)/.test(text) && /(Agent completed successfully|Auto-build|Build|Deploy|Building|Deploying)/i.test(text);
};
// Helper function to determine build action type
const getActionType = (text: string): 'build' | 'deploy' | 'auto-build' => {
if (text.includes('Auto-build') || text.includes('Auto-building') ||
(text.includes('Agent completed successfully') && text.includes('built'))) {
return 'auto-build';
}
if (text.includes('Deploy') || text.includes('Deploying')) {
return 'deploy';
}
return 'build';
};
// Helper function to determine build action status
const getActionStatus = (text: string): { isError: boolean; isLoading: boolean } => {
const icon = text.match(/(✅|❌|⏸️|🎉)/)?.[1];
const hasFailed = icon === '❌' || text.toLowerCase().includes('failed');
const isRunning = icon === '⏸️' || /(Building|Deploying)/i.test(text);
return {
isError: hasFailed,
isLoading: isRunning && !hasFailed
};
};
// Helper function to render build action
const renderBuildAction = (text: string, key: number | string) => {
if (!isBuildAction(text)) {
return null;
}
const actionType = getActionType(text);
const { isError, isLoading } = getActionStatus(text);
return (
<BuildAction
key={key}
action={actionType}
result={text}
isError={isError}
isLoading={isLoading}
/>
);
};
// Handle string content (simple text messages)
if (typeof content === 'string') {
// Check if this is a build action message
const buildAction = renderBuildAction(content, 'string-content');
if (buildAction) {
return buildAction;
}
return (
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Customize code blocks to match the existing tool styling
pre: ({ children }) => (
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
{children}
</pre>
),
code: ({ children, className }) => {
const isInline = !className;
if (isInline) {
return (
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
{children}
</code>
);
}
return <code className={className}>{children}</code>;
},
// Style links
a: ({ href, children }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{children}
</a>
),
// Style blockquotes
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
{children}
</blockquote>
),
}}
>
{content}
</ReactMarkdown>
</div>
);
}
return (
<>
{content.map((item, index) => {
if (item.type === 'text') {
// Check if this is a build action message
const buildAction = renderBuildAction(item.text, index);
if (buildAction) {
return buildAction;
}
return (
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Customize code blocks to match the existing tool styling
pre: ({ children }) => (
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
{children}
</pre>
),
code: ({ children, className }) => {
const isInline = !className;
if (isInline) {
return (
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
{children}
</code>
);
}
return <code className={className}>{children}</code>;
},
// Style links
a: ({ href, children }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{children}
</a>
),
// Style blockquotes
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
{children}
</blockquote>
),
}}
>
{item.text}
</ReactMarkdown>
</div>
);
} else if (item.type === 'tool-call') {
// Special rendering for text_editor_str_replace tool
if (item.toolName === 'text_editor_str_replace' && item.args) {
const { path, old_str, new_str } = item.args as { path: string; old_str: string; new_str: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<DiffRenderer
key={index}
path={path}
oldStr={old_str}
newStr={new_str}
result={result}
isError={isError}
/>
);
}
// Special rendering for run_script tool
if (item.toolName === 'run_script' && item.args) {
const { script } = item.args as { script: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<ScriptRunner
key={index}
script={script}
result={result}
isError={isError}
/>
);
}
// Special rendering for text_editor_view tool
if (item.toolName === 'text_editor_view' && item.args) {
const { path } = item.args as { path: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<FileViewer
key={index}
path={path}
result={result}
isError={isError}
/>
);
}
// Special rendering for text_editor_write tool
if (item.toolName === 'text_editor_write' && item.args) {
const { path, file_text } = item.args as { path: string; file_text: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<FileWriter
key={index}
path={path}
fileText={file_text}
result={result}
isError={isError}
/>
);
}
// Special rendering for shell tool
if (item.toolName === 'shell' && item.args) {
const { command } = item.args as { command: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<ShellCommand
key={index}
command={command}
result={result}
isError={isError}
/>
);
}
// Special rendering for npm_add_package tool
if (item.toolName === 'npm_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="add"
registry="npm"
packageName={name}
version={version}
dev={dev}
result={result}
isError={isError}
/>
);
}
// Special rendering for npm_remove_package tool
if (item.toolName === 'npm_remove_package' && item.args) {
const { name } = item.args as { name: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="remove"
registry="npm"
packageName={name}
result={result}
isError={isError}
/>
);
}
// Special rendering for jsr_add_package tool
if (item.toolName === 'jsr_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="add"
registry="jsr"
packageName={name}
version={version}
dev={dev}
result={result}
isError={isError}
/>
);
}
// Special rendering for jsr_remove_package tool
if (item.toolName === 'jsr_remove_package' && item.args) {
const { name } = item.args as { name: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="remove"
registry="jsr"
packageName={name}
result={result}
isError={isError}
/>
);
}
// Special rendering for git_commit tool
if (item.toolName === 'git_commit' && item.args) {
const { message } = item.args as { message: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<GitCommit
key={index}
message={message}
result={result}
isError={isError}
/>
);
}
// Default tool rendering for other tools
return (
<Card key={index} className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center gap-2 mb-2">
<Code className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm break-all">{String(item.toolName)}</span>
</div>
{item.args && typeof item.args === 'object' && item.args !== null && Object.keys(item.args).length > 0 ? (
<div className="text-xs text-muted-foreground mb-2">
<pre className="overflow-hidden text-ellipsis">
{JSON.stringify(item.args, null, 2)}
</pre>
</div>
) : null}
</CardContent>
</Card>
);
}
return null;
})}
</>
);
});
AssistantContent.displayName = 'AssistantContent';
+44
View File
@@ -0,0 +1,44 @@
import { memo } from 'react';
import { ActionCard } from './shared/ActionCard';
interface BuildActionProps {
action: 'build' | 'deploy' | 'auto-build';
result?: string;
status?: 'RUNNING' | 'SUCCESS' | 'FAILED' | 'PENDING';
isError?: boolean;
isLoading?: boolean;
}
export const BuildAction = memo(({ action, result, status, isError, isLoading }: BuildActionProps) => {
const actionConfig = {
build: { title: 'Build Project', verb: 'build' },
deploy: { title: 'Deploy Project', verb: 'deploy' },
'auto-build': { title: 'Auto-Build Project', verb: 'auto-build' },
}[action] || { title: 'Build Action', verb: 'process' };
const getActionDescription = () => {
const effectiveStatus = status || (
isLoading ? 'RUNNING' :
isError ? 'FAILED' : 'SUCCESS'
);
if (effectiveStatus === 'RUNNING') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)}ing project...`;
if (effectiveStatus === 'FAILED') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} failed`;
if (effectiveStatus === 'SUCCESS') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} completed`;
return `Starting ${actionConfig.verb} process...`;
};
return (
<ActionCard
title={actionConfig.title}
description={getActionDescription()}
result={result}
status={status}
isError={isError}
isLoading={isLoading}
successLabel="Completed"
/>
);
});
BuildAction.displayName = 'BuildAction';
+164
View File
@@ -0,0 +1,164 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { FileText, CheckCircle, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface DiffRendererProps {
path: string;
oldStr: string;
newStr: string;
result?: string;
isError?: boolean;
className?: string;
}
export function DiffRenderer({ path, oldStr, newStr, result, isError = false, className }: DiffRendererProps) {
// Split strings into lines for diff rendering
const oldLines = oldStr.split('\n');
const newLines = newStr.split('\n');
// Simple diff algorithm - find common prefix and suffix
const findCommonPrefix = (a: string[], b: string[]) => {
let i = 0;
while (i < Math.min(a.length, b.length) && a[i] === b[i]) {
i++;
}
return i;
};
const findCommonSuffix = (a: string[], b: string[], prefixLength: number) => {
let i = 0;
const maxLength = Math.min(a.length - prefixLength, b.length - prefixLength);
while (i < maxLength && a[a.length - 1 - i] === b[b.length - 1 - i]) {
i++;
}
return i;
};
const prefixLength = findCommonPrefix(oldLines, newLines);
const suffixLength = findCommonSuffix(oldLines, newLines, prefixLength);
const commonPrefix = oldLines.slice(0, prefixLength);
const commonSuffix = oldLines.slice(oldLines.length - suffixLength);
const removedLines = oldLines.slice(prefixLength, oldLines.length - suffixLength);
const addedLines = newLines.slice(prefixLength, newLines.length - suffixLength);
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 text-muted-foreground" />
<span className="font-mono text-sm font-medium">{path}</span>
</div>
<div className="flex items-center gap-2">
{isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="bg-muted/30 rounded-md overflow-x-auto overflow-y-hidden">
<div className="font-mono text-xs min-w-max">
{/* Context before changes */}
{commonPrefix.length > 0 && (
<div className="border-b border-muted/50">
{commonPrefix.slice(-3).map((line, index) => (
<div key={`prefix-${index}`} className="px-3 py-1 text-muted-foreground">
<span className="inline-block w-8 text-right mr-3 select-none">
{prefixLength - 3 + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
</div>
))}
</div>
)}
{/* Removed lines */}
{removedLines.map((line, index) => (
<div key={`removed-${index}`} className="px-3 py-1 bg-red-50 text-red-800 dark:bg-red-900/20 dark:text-red-300">
<span className="inline-block w-8 text-right mr-3 select-none text-red-600 dark:text-red-400">
-{prefixLength + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">
<span className="bg-red-200 dark:bg-red-800/50">-</span>
{line || ' '}
</span>
</div>
))}
{/* Added lines */}
{addedLines.map((line, index) => (
<div key={`added-${index}`} className="px-3 py-1 bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-300">
<span className="inline-block w-8 text-right mr-3 select-none text-green-600 dark:text-green-400">
+{prefixLength + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">
<span className="bg-green-200 dark:bg-green-800/50">+</span>
{line || ' '}
</span>
</div>
))}
{/* Context after changes */}
{commonSuffix.length > 0 && (
<div className="border-t border-muted/50">
{commonSuffix.slice(0, 3).map((line, index) => (
<div key={`suffix-${index}`} className="px-3 py-1 text-muted-foreground">
<span className="inline-block w-8 text-right mr-3 select-none">
{prefixLength + Math.max(removedLines.length, addedLines.length) + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
</div>
))}
</div>
)}
{/* Handle case where there are no changes */}
{removedLines.length === 0 && addedLines.length === 0 && (
<div className="px-3 py-4 text-center text-muted-foreground">
No changes detected
</div>
)}
</div>
</div>
{/* Summary */}
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
{removedLines.length > 0 && (
<span className="text-red-600 dark:text-red-400">
-{removedLines.length} line{removedLines.length !== 1 ? 's' : ''}
</span>
)}
{addedLines.length > 0 && (
<span className="text-green-600 dark:text-green-400">
+{addedLines.length} line{addedLines.length !== 1 ? 's' : ''}
</span>
)}
</div>
{/* Tool Result */}
{result && (
<div className={cn(
"mt-3 p-3 rounded-md text-sm",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-muted/30 text-muted-foreground"
)}>
<pre className="whitespace-pre-wrap break-words">{result}</pre>
</div>
)}
</CardContent>
</Card>
);
}
+171
View File
@@ -0,0 +1,171 @@
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
interface FileContentsProps {
content: string;
filePath: string;
className?: string;
showLineNumbers?: boolean;
maxHeight?: string;
showHeader?: boolean;
headerContent?: React.ReactNode;
}
export function FileContents({
content,
filePath,
className,
showLineNumbers,
maxHeight = 'max-h-80',
showHeader = true,
headerContent
}: FileContentsProps) {
const { theme } = useTheme();
// Get file extension for syntax highlighting hints
const getFileExtension = (path: string) => {
const parts = path.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
// Map file extensions to syntax highlighter languages
const getLanguageFromExtension = (ext: string): string => {
const languageMap: Record<string, string> = {
'ts': 'typescript',
'tsx': 'tsx',
'js': 'javascript',
'jsx': 'jsx',
'json': 'json',
'md': 'markdown',
'css': 'css',
'scss': 'scss',
'sass': 'sass',
'less': 'less',
'html': 'html',
'xml': 'xml',
'svg': 'xml',
'yml': 'yaml',
'yaml': 'yaml',
'toml': 'toml',
'py': 'python',
'rb': 'ruby',
'php': 'php',
'java': 'java',
'c': 'c',
'cpp': 'cpp',
'cs': 'csharp',
'go': 'go',
'rs': 'rust',
'sh': 'bash',
'bash': 'bash',
'zsh': 'bash',
'fish': 'bash',
'sql': 'sql',
'dockerfile': 'dockerfile',
'gitignore': 'gitignore',
'env': 'bash',
'ini': 'ini',
'conf': 'nginx',
'nginx': 'nginx',
'apache': 'apache',
'htaccess': 'apache',
'vim': 'vim',
'lua': 'lua',
'r': 'r',
'matlab': 'matlab',
'swift': 'swift',
'kotlin': 'kotlin',
'dart': 'dart',
'elm': 'elm',
'haskell': 'haskell',
'clojure': 'clojure',
'scala': 'scala',
'perl': 'perl',
'powershell': 'powershell',
'makefile': 'makefile',
'cmake': 'cmake',
'gradle': 'gradle',
'properties': 'properties',
'diff': 'diff',
'patch': 'diff',
'log': 'log'
};
return languageMap[ext] || 'text';
};
// Check if content should be syntax highlighted
const shouldHighlight = (ext: string, text: string): boolean => {
// Don't highlight very large files (over 50KB) for performance
if (text.length > 50000) return false;
// Don't highlight binary-looking content (check for null bytes and other binary indicators)
if (text.includes('\0') || text.includes('\uFFFD')) return false;
// Always highlight known code file extensions
const codeExtensions = ['ts', 'tsx', 'js', 'jsx', 'json', 'css', 'scss', 'html', 'xml', 'py', 'rb', 'php', 'java', 'c', 'cpp', 'cs', 'go', 'rs', 'sh', 'bash', 'sql', 'yml', 'yaml', 'toml', 'md'];
return codeExtensions.includes(ext);
};
const fileExtension = getFileExtension(filePath);
const shouldUseHighlighting = shouldHighlight(fileExtension, content);
// Determine if we should show line numbers
const shouldShowLineNumbers = showLineNumbers ?? (content.split('\n').length > 10);
return (
<div className={cn("bg-muted/30 rounded-md overflow-hidden", className)}>
{showHeader && (
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50 flex items-center justify-between">
<span>File Contents</span>
{headerContent || (fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
))}
</div>
)}
<div className={cn("p-0 overflow-auto", maxHeight)}>
{shouldUseHighlighting ? (
<SyntaxHighlighter
language={getLanguageFromExtension(fileExtension)}
style={theme === 'dark' ? oneDark : oneLight}
customStyle={{
margin: 0,
padding: '12px',
fontSize: '12px',
lineHeight: '1.4',
background: 'transparent',
border: 'none',
borderRadius: 0,
}}
codeTagProps={{
style: {
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
}
}}
showLineNumbers={shouldShowLineNumbers}
lineNumberStyle={{
minWidth: '2.5em',
paddingRight: '1em',
color: theme === 'dark' ? '#6b7280' : '#9ca3af',
fontSize: '11px',
}}
wrapLines={false}
wrapLongLines={false}
>
{content}
</SyntaxHighlighter>
) : (
<div className="p-3">
<pre className="text-xs font-mono whitespace-pre text-foreground">
{content}
</pre>
</div>
)}
</div>
</div>
);
}
+175
View File
@@ -0,0 +1,175 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Eye } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FileContents } from '@/components/ai/FileContents';
interface FileViewerProps {
path: string;
result?: string;
isError?: boolean;
className?: string;
}
export function FileViewer({ path, result, isError = false, className }: FileViewerProps) {
// Determine if it's a directory or file based on the result
const isDirectory = result?.includes('├──') || result?.includes('└──') || result?.includes('│');
// Get file extension for syntax highlighting hints
const getFileExtension = (filePath: string) => {
const parts = filePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
const getFileIcon = (filePath: string, isDir: boolean) => {
if (isDir) return '📁';
const ext = getFileExtension(filePath);
switch (ext) {
case 'ts':
case 'tsx': return '🔷';
case 'js':
case 'jsx': return '🟨';
case 'json': return '📋';
case 'md': return '📝';
case 'css': return '🎨';
case 'html': return '🌐';
case 'svg': return '🖼️';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif': return '🖼️';
case 'yml':
case 'yaml': return '⚙️';
case 'toml': return '⚙️';
case 'lock': return '🔒';
default: return '📄';
}
};
const fileIcon = getFileIcon(path, isDirectory || false);
const fileExtension = getFileExtension(path);
// Parse directory structure for better display
const parseDirectoryStructure = (content: string) => {
if (!isDirectory) return content;
const lines = content.split('\n').filter(line => line.trim());
return lines.map((line) => {
// Extract the file/folder name from tree structure
const match = line.match(/[├└]──\s*(.+)$/);
if (match) {
const name = match[1];
const isFolder = !name.includes('.');
const icon = isFolder ? '📁' : getFileIcon(name, false);
return { line, name, icon, isFolder };
}
return { line, name: line.trim(), icon: '📄', isFolder: false };
});
};
const directoryItems = isDirectory ? parseDirectoryStructure(result || '') : [];
const directoryItemsArray = Array.isArray(directoryItems) ? directoryItems : [];
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Eye className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{fileIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">{path}</div>
<div className="text-xs text-muted-foreground">
{isDirectory ? 'Directory listing' : `${fileExtension ? fileExtension.toUpperCase() + ' file' : 'File'} contents`}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Error
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<CheckCircle className="h-3 w-3 mr-1" />
Viewed
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400">
<Eye className="h-3 w-3 mr-1" />
Loading
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{isError ? (
<div className="bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
{result}
</div>
) : isDirectory ? (
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Directory Structure
</div>
<div className="p-3 max-h-80 overflow-y-auto">
<div className="space-y-1">
{directoryItemsArray.map((item, index) => (
<div key={index} className="flex items-center gap-2 text-sm font-mono">
<span className="text-muted-foreground">{item.line.replace(/[├└]──\s*(.+)$/, '')}</span>
<span className="text-xs">{item.icon}</span>
<span className={cn(
item.isFolder ? "text-blue-600 dark:text-blue-400 font-medium" : "text-foreground"
)}>
{item.name}
</span>
</div>
))}
</div>
</div>
</div>
) : (
<FileContents
content={result}
filePath={path}
headerContent={fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
)}
/>
)}
{/* File stats */}
{!isError && result && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
{isDirectory ? (
<span>
{directoryItemsArray.length} item{directoryItemsArray.length !== 1 ? 's' : ''}
</span>
) : (
<>
<span>
{result.split('\n').length} line{result.split('\n').length !== 1 ? 's' : ''}
</span>
<span>
{result.length} character{result.length !== 1 ? 's' : ''}
</span>
</>
)}
</div>
)}
</CardContent>
)}
</Card>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Edit3 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FileContents } from '@/components/ai/FileContents';
interface FileWriterProps {
path: string;
fileText: string;
result?: string;
isError?: boolean;
className?: string;
}
export function FileWriter({ path, fileText, result, isError = false, className }: FileWriterProps) {
// Get file extension for syntax highlighting hints
const getFileExtension = (filePath: string) => {
const parts = filePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
const getFileIcon = (filePath: string) => {
const ext = getFileExtension(filePath);
switch (ext) {
case 'ts':
case 'tsx': return '🔷';
case 'js':
case 'jsx': return '🟨';
case 'json': return '📋';
case 'md': return '📝';
case 'css': return '🎨';
case 'html': return '🌐';
case 'svg': return '🖼️';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif': return '🖼️';
case 'yml':
case 'yaml': return '⚙️';
case 'toml': return '⚙️';
case 'lock': return '🔒';
default: return '📄';
}
};
const fileIcon = getFileIcon(path);
const fileExtension = getFileExtension(path);
const isNewFile = path.includes('new') || result?.includes('created') || result?.includes('Created');
// Calculate file stats
const lineCount = fileText.split('\n').length;
const charCount = fileText.length;
const wordCount = fileText.split(/\s+/).filter(word => word.length > 0).length;
// Preview first few lines for collapsed view
const previewLines = fileText.split('\n').slice(0, 5);
const hasMoreLines = lineCount > 5;
const previewContent = previewLines.join('\n') + (hasMoreLines ? `\n... (${lineCount - 5} more lines)` : '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Edit3 className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{fileIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">{path}</div>
<div className="text-xs text-muted-foreground">
{isNewFile ? 'Created new file' : 'Updated file contents'}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
{isNewFile ? 'Created' : 'Updated'}
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Edit3 className="h-3 w-3 mr-1" />
Writing
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
{/* Error display */}
{isError && result && (
<div className="mb-3 bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
{result}
</div>
)}
{/* File stats */}
<div className="mb-3 flex items-center gap-4 text-xs">
<span className="text-muted-foreground">
{lineCount} line{lineCount !== 1 ? 's' : ''}
</span>
<span className="text-muted-foreground">
{wordCount} word{wordCount !== 1 ? 's' : ''}
</span>
<span className="text-muted-foreground">
{charCount} character{charCount !== 1 ? 's' : ''}
</span>
{fileExtension && (
<Badge variant="outline" className="text-xs">
{fileExtension.toUpperCase()}
</Badge>
)}
</div>
{/* File preview */}
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
Preview file contents
</summary>
<FileContents
content={hasMoreLines ? previewContent : fileText}
filePath={path}
showLineNumbers={false}
headerContent={fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
)}
/>
</details>
{/* Success message */}
{!isError && result && (
<div className="mt-3 text-xs text-green-600 dark:text-green-400">
✓ File {isNewFile ? 'created' : 'updated'} successfully
</div>
)}
</CardContent>
</Card>
);
}
+2 -4
View File
@@ -4,7 +4,7 @@ import { TestApp } from '@/test/TestApp';
import { GitCommit } from './GitCommit';
describe('GitCommit', () => {
it('renders commit message and shows committing state', () => {
it('renders commit message', () => {
render(
<TestApp>
<GitCommit message="feat: add new feature" />
@@ -12,8 +12,6 @@ describe('GitCommit', () => {
);
expect(screen.getByText('feat: add new feature')).toBeInTheDocument();
expect(screen.getByText('Committing')).toBeInTheDocument();
expect(screen.getByText('Git commit')).toBeInTheDocument();
});
it('shows success state with commit details', () => {
@@ -38,7 +36,7 @@ describe('GitCommit', () => {
expect(screen.getByText('Committed')).toBeInTheDocument();
expect(screen.getByText('Successfully committed 3 files')).toBeInTheDocument();
expect(screen.getByText('abc1234')).toBeInTheDocument();
expect(screen.getByText('main branch')).toBeInTheDocument();
expect(screen.getByText('2 added')).toBeInTheDocument();
expect(screen.getByText('1 modified')).toBeInTheDocument();
});
+31 -66
View File
@@ -1,7 +1,5 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitCommit as GitCommitIcon, CheckCircle, XCircle, GitBranch, Plus, Minus, Edit } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ActionCard } from './shared/ActionCard';
import { GitCommit as GitCommitIcon, GitBranch, Plus, Minus, Edit } from 'lucide-react';
interface GitCommitProps {
message: string;
@@ -80,61 +78,33 @@ export function GitCommit({
const firstLine = getFirstLine(message);
const commitEmoji = getCommitEmoji(message);
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<GitCommitIcon className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{commitEmoji}</span>
</div>
<div className="flex-1 min-w-0">
<div className="font-mono text-sm font-medium truncate">
{firstLine}
</div>
<div className="text-xs text-muted-foreground">
Git commit
{stats?.branch && (
<span className="ml-2 inline-flex items-center gap-1">
<GitBranch className="h-3 w-3" />
{stats.branch}
</span>
)}
{stats?.hash && (
<span className="ml-2 font-mono">
{stats.hash}
</span>
)}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Committed
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<GitCommitIcon className="h-3 w-3 mr-1" />
Committing
</Badge>
)}
</div>
</div>
</CardHeader>
const getCommitDescription = () => {
let desc = 'Git commit';
if (stats?.branch) {
desc += ` • ${stats.branch} branch`;
}
if (stats?.hash) {
desc += ` • ${stats.hash}`;
}
return desc;
};
return (
<ActionCard
title={firstLine}
description={getCommitDescription()}
icon={<span className="text-lg">{commitEmoji}</span>}
result={result}
isError={isError}
className={className}
showResult={false}
runningIcon={<GitCommitIcon className="h-3 w-3" />}
runningLabel="Committing"
successLabel="Committed"
>
{/* Full commit message - only show if multi-line */}
{message.includes('\n') && (
<CardContent className="pt-0">
<div className="mb-3">
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
@@ -148,19 +118,14 @@ export function GitCommit({
</div>
</div>
</details>
</CardContent>
</div>
)}
{result && (
<CardContent className={cn("pt-0", message.includes('\n') ? "pt-3" : "")}>
<>
{/* Summary */}
{summary && (
<div className={cn(
"mb-3 p-3 rounded-md text-sm font-medium",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
)}>
<div className="mb-3 p-3 rounded-md text-sm font-muted-foreground">
{summary}
</div>
)}
@@ -207,8 +172,8 @@ export function GitCommit({
</span>
)}
</div>
</CardContent>
</>
)}
</Card>
</ActionCard>
);
}
+12 -21
View File
@@ -28,19 +28,13 @@ interface GitCommit {
interface GitHistoryDialogProps {
projectId: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange }: GitHistoryDialogProps) {
export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
const [commits, setCommits] = useState<GitCommit[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [internalOpen, setInternalOpen] = useState(false);
// Use controlled or internal state
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
const setIsOpen = onOpenChange || setInternalOpen;
const [isOpen, setIsOpen] = useState(false);
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
const { fs } = useFS();
@@ -286,19 +280,16 @@ ${commitsToRevert.map(c => {
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
{/* Only show trigger if not controlled externally */}
{controlledOpen === undefined && (
<DialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
>
<History className="h-4 w-4" />
<span className="hidden sm:inline">History</span>
</Button>
</DialogTrigger>
)}
<DialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
>
<History className="h-4 w-4" />
<span className="hidden sm:inline">History</span>
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
+74
View File
@@ -0,0 +1,74 @@
import { memo } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { AssistantContent } from '@/components/ai/AssistantContent';
import { Bot, User } from 'lucide-react';
import type { CoreUserMessage, CoreAssistantMessage, CoreToolMessage } from 'ai';
interface MessageItemProps {
message: (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
userDisplayName?: string;
userProfileImage?: string;
toolResults?: CoreToolMessage[];
}
export const MessageItem = memo(({
message,
userDisplayName = 'You',
userProfileImage,
toolResults = []
}: MessageItemProps) => {
// Don't render tool messages as separate items - they're integrated into assistant messages
if (message.role === 'tool') {
return null;
}
return (
<div className="flex gap-3">
<Avatar className="h-8 w-8 flex-shrink-0">
{message.role === 'user' ? (
<>
<AvatarImage src={userProfileImage} alt={userDisplayName} />
<AvatarFallback>
<User className="h-4 w-4" />
</AvatarFallback>
</>
) : (
<>
<AvatarFallback>
<Bot className="h-4 w-4" />
</AvatarFallback>
</>
)}
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">
{message.role === 'user' ? userDisplayName : 'Assistant'}
</span>
<span className="text-xs text-muted-foreground">
{message.role === 'user' ? 'User' : 'AI'}
</span>
</div>
<div className="text-sm">
{message.role === 'user' ? (
<div className="whitespace-pre-wrap break-words">
{typeof message.content === 'string' ? message.content :
message.content.map((part, _i) => {
if (part.type === 'text') return part.text;
return null;
}).join('')
}
</div>
) : message.role === 'assistant' ? (
<AssistantContent
content={(message as CoreAssistantMessage).content}
toolResults={toolResults}
/>
) : null}
</div>
</div>
</div>
);
});
MessageItem.displayName = 'MessageItem';
+243
View File
@@ -0,0 +1,243 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Package, Plus, Minus, CheckCircle, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface PackageManagerProps {
action: 'add' | 'remove';
registry: 'npm' | 'jsr';
packageName: string;
version?: string;
dev?: boolean;
result?: string;
isError?: boolean;
className?: string;
}
export function PackageManager({
action,
registry,
packageName,
version,
dev,
result,
isError = false,
className
}: PackageManagerProps) {
// Get package info
const getPackageInfo = (name: string) => {
// Common package icons
if (name.includes('react')) return '⚛️';
if (name.includes('vue')) return '💚';
if (name.includes('angular')) return '🅰️';
if (name.includes('typescript') || name.includes('@types/')) return '🔷';
if (name.includes('eslint')) return '🔍';
if (name.includes('prettier')) return '✨';
if (name.includes('vite')) return '⚡';
if (name.includes('webpack')) return '📦';
if (name.includes('babel')) return '🐠';
if (name.includes('jest') || name.includes('vitest')) return '🧪';
if (name.includes('tailwind')) return '🎨';
if (name.includes('sass') || name.includes('scss')) return '🎨';
if (name.includes('lodash')) return '🔧';
if (name.includes('axios')) return '🌐';
if (name.includes('express')) return '🚀';
if (name.includes('next')) return '▲';
if (name.includes('nuxt')) return '💚';
if (name.includes('svelte')) return '🧡';
if (name.includes('prisma')) return '🔺';
if (name.includes('graphql')) return '🔗';
if (name.includes('socket')) return '🔌';
if (name.includes('redis')) return '🔴';
if (name.includes('mongo')) return '🍃';
if (name.includes('postgres')) return '🐘';
if (name.includes('mysql')) return '🐬';
if (name.includes('docker')) return '🐳';
if (name.includes('kubernetes')) return '☸️';
if (name.includes('aws')) return '☁️';
if (name.includes('firebase')) return '🔥';
if (name.includes('stripe')) return '💳';
if (name.includes('auth')) return '🔐';
if (name.includes('crypto')) return '🔒';
if (name.includes('date') || name.includes('moment')) return '📅';
if (name.includes('uuid')) return '🆔';
if (name.includes('validator')) return '✅';
if (name.includes('helmet')) return '⛑️';
if (name.includes('cors')) return '🌐';
if (name.includes('dotenv')) return '🔧';
if (name.includes('nodemon')) return '👀';
if (name.includes('concurrently')) return '🔄';
if (name.includes('husky')) return '🐶';
if (name.includes('lint-staged')) return '🎭';
if (name.includes('commitizen')) return '📝';
if (name.includes('semantic-release')) return '🚀';
if (name.includes('storybook')) return '📚';
if (name.includes('cypress')) return '🌲';
if (name.includes('playwright')) return '🎭';
if (name.includes('puppeteer')) return '🎪';
return '📦';
};
const packageIcon = getPackageInfo(packageName);
const registryIcon = registry === 'jsr' ? '🦕' : '📦';
// Parse output for useful information
const parseOutput = (output: string) => {
if (!output) return { summary: '', details: output };
if (action === 'add') {
if (output.includes('added') || output.includes('installed')) {
return {
summary: `Successfully added ${packageName}${version ? `@${version}` : ''}`,
details: output
};
}
if (output.includes('already exists') || output.includes('up to date')) {
return {
summary: `${packageName} is already installed`,
details: output
};
}
}
if (action === 'remove') {
if (output.includes('removed') || output.includes('uninstalled')) {
return {
summary: `Successfully removed ${packageName}`,
details: output
};
}
if (output.includes('not found') || output.includes('not installed')) {
return {
summary: `${packageName} was not installed`,
details: output
};
}
}
return {
summary: `Package ${action} completed`,
details: output
};
};
const { summary, details } = parseOutput(result || '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{packageIcon}</span>
<span className="text-sm">{registryIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">
{action === 'add' ? (
<span className="flex items-center gap-1">
<Plus className="h-3 w-3 text-green-600" />
{packageName}{version && `@${version}`}
</span>
) : (
<span className="flex items-center gap-1">
<Minus className="h-3 w-3 text-red-600" />
{packageName}
</span>
)}
</div>
<div className="text-xs text-muted-foreground">
{action === 'add' ? 'Install' : 'Remove'} {registry.toUpperCase()} package
{dev && ' (dev dependency)'}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Package className="h-3 w-3 mr-1" />
{action === 'add' ? 'Installing' : 'Removing'}
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{/* Summary */}
{summary && (
<div className={cn(
"mb-3 p-3 rounded-md text-sm font-medium",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
)}>
{summary}
</div>
)}
{/* Full output */}
{details && details.trim() && (
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
View package manager output
</summary>
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Package Manager Output
</div>
<div className="p-3 max-h-80 overflow-auto">
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
{details}
</pre>
</div>
</div>
</details>
)}
{/* Package info */}
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
{registryIcon} {registry.toUpperCase()} registry
</span>
{version && (
<span>
Version: {version}
</span>
)}
{dev && (
<span className="text-orange-600 dark:text-orange-400">
Development dependency
</span>
)}
{action === 'add' && (
<span className="text-green-600 dark:text-green-400">
Added to project
</span>
)}
{action === 'remove' && (
<span className="text-red-600 dark:text-red-400">
Removed from project
</span>
)}
</div>
</CardContent>
)}
</Card>
);
}
+175
View File
@@ -0,0 +1,175 @@
import { ActionCard } from './shared/ActionCard';
import { Play } from 'lucide-react';
interface ScriptRunnerProps {
script: string;
result?: string;
isError?: boolean;
className?: string;
}
export function ScriptRunner({ script, result, isError = false, className }: ScriptRunnerProps) {
// Get script info
const getScriptInfo = (scriptName: string) => {
switch (scriptName) {
case 'build': return { icon: '🔨', description: 'Build the project for production' };
case 'test': return { icon: '🧪', description: 'Run tests and linting' };
case 'dev': return { icon: '🚀', description: 'Start development server' };
case 'start': return { icon: '▶️', description: 'Start the application' };
case 'lint': return { icon: '🔍', description: 'Check code quality' };
case 'format': return { icon: '✨', description: 'Format code' };
case 'preview': return { icon: '👀', description: 'Preview production build' };
case 'deploy': return { icon: '🚀', description: 'Deploy to production' };
default: return { icon: '⚡', description: 'Run script' };
}
};
const scriptInfo = getScriptInfo(script);
// Parse output for useful information
const parseOutput = (output: string) => {
if (!output) return { summary: '', details: output };
const lines = output.split('\n').filter(line => line.trim());
// Look for common patterns
if (script === 'build') {
if (output.includes('built in') || output.includes('Build completed')) {
return {
summary: 'Build completed successfully',
details: output
};
}
if (output.includes('error') || output.includes('Error')) {
return {
summary: 'Build failed with errors',
details: output
};
}
}
if (script === 'test') {
const passMatch = output.match(/(\d+) passing/);
const failMatch = output.match(/(\d+) failing/);
if (passMatch || failMatch) {
const passing = passMatch ? passMatch[1] : '0';
const failing = failMatch ? failMatch[1] : '0';
return {
summary: `Tests completed: ${passing} passing, ${failing} failing`,
details: output
};
}
if (output.includes('All tests passed') || output.includes('✓')) {
return {
summary: 'All tests passed',
details: output
};
}
}
if (script === 'lint') {
if (output.includes('No linting errors found') || output.includes('✓')) {
return {
summary: 'No linting errors found',
details: output
};
}
const errorMatch = output.match(/(\d+) error/);
const warningMatch = output.match(/(\d+) warning/);
if (errorMatch || warningMatch) {
const errors = errorMatch ? errorMatch[1] : '0';
const warnings = warningMatch ? warningMatch[1] : '0';
return {
summary: `Linting completed: ${errors} errors, ${warnings} warnings`,
details: output
};
}
}
// Default: use last meaningful line
const meaningfulLines = lines.filter(line =>
!line.startsWith('#') &&
!line.startsWith('//') &&
line.length > 0
);
return {
summary: meaningfulLines[meaningfulLines.length - 1] || 'Script executed',
details: output
};
};
const { summary, details } = parseOutput(result || '');
return (
<ActionCard
title={`npm run ${script}`}
description={scriptInfo.description}
icon={<span className="text-lg">{scriptInfo.icon}</span>}
result={result}
isError={isError}
className={className}
runningIcon={<Play className="h-3 w-3" />}
runningLabel="Running"
>
{result && (
<>
{/* Summary */}
{summary && (
<div className="mb-3 p-3 rounded-md text-sm font-muted-foreground">
{summary}
</div>
)}
{/* Full output */}
{details && details.trim() && (
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
View script output
</summary>
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Script Output
</div>
<div className="p-3 max-h-80 overflow-auto">
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
{details}
</pre>
</div>
</div>
</details>
)}
{/* Script stats */}
{!isError && details && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
<span>
{details.split('\n').length} line{details.split('\n').length !== 1 ? 's' : ''} output
</span>
{script === 'build' && details.includes('built in') && (
<span>
Build time: {details.match(/built in (\d+\.?\d*[a-z]+)/)?.[1] || 'unknown'}
</span>
)}
{script === 'test' && (
<>
{details.match(/(\d+) passing/) && (
<span className="text-green-600 dark:text-green-400">
{details.match(/(\d+) passing/)?.[1]} passing
</span>
)}
{details.match(/(\d+) failing/) && (
<span className="text-red-600 dark:text-red-400">
{details.match(/(\d+) failing/)?.[1]} failing
</span>
)}
</>
)}
</div>
)}
</>
)}
</ActionCard>
);
}
+184
View File
@@ -0,0 +1,184 @@
import { ActionCard } from './shared/ActionCard';
import { Terminal } from 'lucide-react';
interface ShellCommandProps {
command: string;
result?: string;
isError?: boolean;
className?: string;
}
export function ShellCommand({ command, result, isError = false, className }: ShellCommandProps) {
// Parse command to get useful information
const parseCommand = (cmd: string) => {
const parts = cmd.trim().split(' ');
const baseCommand = parts[0];
// Get command info
const getCommandInfo = (baseCmd: string) => {
switch (baseCmd) {
case 'ls':
case 'dir': return { icon: '📁', description: 'List directory contents' };
case 'cd': return { icon: '📂', description: 'Change directory' };
case 'mkdir': return { icon: '📁', description: 'Create directory' };
case 'rm':
case 'rmdir':
case 'del': return { icon: '🗑️', description: 'Remove files/directories' };
case 'cp':
case 'copy': return { icon: '📋', description: 'Copy files' };
case 'mv':
case 'move': return { icon: '📦', description: 'Move/rename files' };
case 'cat':
case 'type': return { icon: '📄', description: 'Display file contents' };
case 'grep':
case 'findstr': return { icon: '🔍', description: 'Search text patterns' };
case 'find': return { icon: '🔍', description: 'Find files and directories' };
case 'chmod': return { icon: '🔐', description: 'Change file permissions' };
case 'git': return { icon: '🌿', description: 'Git version control' };
case 'npm':
case 'yarn':
case 'pnpm': return { icon: '📦', description: 'Package manager' };
case 'node': return { icon: '🟢', description: 'Run Node.js' };
case 'python':
case 'python3': return { icon: '🐍', description: 'Run Python' };
case 'curl':
case 'wget': return { icon: '🌐', description: 'Download from web' };
case 'ps': return { icon: '⚙️', description: 'List running processes' };
case 'kill': return { icon: '⚡', description: 'Terminate processes' };
case 'echo': return { icon: '💬', description: 'Display text' };
case 'pwd': return { icon: '📍', description: 'Show current directory' };
case 'whoami': return { icon: '👤', description: 'Show current user' };
case 'which':
case 'where': return { icon: '🔍', description: 'Locate command' };
default: return { icon: '⚡', description: 'Execute command' };
}
};
return {
baseCommand,
fullCommand: cmd,
...getCommandInfo(baseCommand)
};
};
const commandInfo = parseCommand(command);
// Parse output for useful information
const parseOutput = (output: string) => {
if (!output) return { summary: '', details: output };
const lines = output.split('\n').filter(line => line.trim());
// Look for common patterns
if (commandInfo.baseCommand === 'ls' || commandInfo.baseCommand === 'dir') {
const fileCount = lines.length;
return {
summary: `Found ${fileCount} item${fileCount !== 1 ? 's' : ''}`,
details: output
};
}
if (commandInfo.baseCommand === 'git') {
const gitSubcommand = command.split(' ')[1];
if (gitSubcommand === 'status') {
return {
summary: lines.find(line => line.includes('nothing to commit') || line.includes('Changes') || line.includes('Untracked')) || 'Git status checked',
details: output
};
}
if (gitSubcommand === 'log') {
const commitCount = (output.match(/commit /g) || []).length;
return {
summary: `Showing ${commitCount} commit${commitCount !== 1 ? 's' : ''}`,
details: output
};
}
}
if (commandInfo.baseCommand === 'npm' || commandInfo.baseCommand === 'yarn') {
if (output.includes('added') || output.includes('installed')) {
return {
summary: 'Package installation completed',
details: output
};
}
}
// Default: use first meaningful line or last line
const meaningfulLines = lines.filter(line =>
!line.startsWith('#') &&
!line.startsWith('//') &&
line.length > 0
);
return {
summary: meaningfulLines[meaningfulLines.length - 1] || 'Command executed',
details: output
};
};
const { summary, details } = parseOutput(result || '');
return (
<ActionCard
title={`$ ${commandInfo.fullCommand}`}
description={commandInfo.description}
icon={<span className="text-lg">{commandInfo.icon}</span>}
result={result}
isError={isError}
className={className}
runningIcon={<Terminal className="h-3 w-3" />}
runningLabel="Executing"
>
{result && (
<>
{/* Summary */}
{summary && (
<div className="mb-3 p-3 rounded-md text-sm font-muted-foreground">
{summary}
</div>
)}
{/* Full output */}
{details && details.trim() && (
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
View command output
</summary>
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Terminal Output
</div>
<div className="p-3 max-h-80 overflow-auto">
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
{details}
</pre>
</div>
</div>
</details>
)}
{/* Command stats */}
{!isError && details && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
<span>
{details.split('\n').length} line{details.split('\n').length !== 1 ? 's' : ''} output
</span>
{commandInfo.baseCommand === 'ls' && (
<span>
{details.split('\n').filter(line => line.trim()).length} items listed
</span>
)}
{(commandInfo.baseCommand === 'git' && command.includes('log')) && (
<span>
{(details.match(/commit /g) || []).length} commits shown
</span>
)}
</div>
)}
</>
)}
</ActionCard>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { memo } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Wrench } from 'lucide-react';
import type { CoreToolMessage } from 'ai';
interface ToolResultContentProps {
content: CoreToolMessage['content'];
}
export const ToolResultContent = memo(({ content }: ToolResultContentProps) => {
if (typeof content === 'string') {
return (
<Card className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center gap-2 mb-2">
<Wrench className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm">Tool Result</span>
</div>
<div className="text-xs rounded p-2 border bg-background">
<pre className="whitespace-pre-wrap break-words overflow-x-auto">{content}</pre>
</div>
</CardContent>
</Card>
);
}
return (
<>
{content.map((item, index) => {
if (item.type === 'tool-result') {
const isError = item.isError || false;
const result = typeof item.result === 'string' ? item.result : JSON.stringify(item.result);
return (
<Card key={index} className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Wrench className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm">{item.toolName}</span>
</div>
<Badge variant={isError ? "destructive" : "secondary"} className="text-xs">
{isError ? (
<>
<XCircle className="h-3 w-3 mr-1" />
Error
</>
) : (
<>
<CheckCircle className="h-3 w-3 mr-1" />
Success
</>
)}
</Badge>
</div>
<div className={`text-xs rounded p-2 border max-h-40 overflow-scroll ${
isError ? 'bg-destructive/10 border-destructive/20' : 'bg-background'
}`}>
<pre className="whitespace-pre-wrap break-words overflow-x-auto">{result}</pre>
</div>
</CardContent>
</Card>
);
}
return null;
})}
</>
);
});
ToolResultContent.displayName = 'ToolResultContent';
+69
View File
@@ -0,0 +1,69 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { ActionStatus, type ActionStatusProps } from './ActionStatus';
export interface ActionCardProps extends Omit<ActionStatusProps, 'status'> {
title: string;
description?: string;
icon?: React.ReactNode;
result?: string;
children?: React.ReactNode;
className?: string;
showResult?: boolean;
status?: ActionStatusProps['status'];
}
export function ActionCard({
title,
description,
icon,
result,
children,
className,
showResult = true,
...statusProps
}: ActionCardProps) {
const { Badge, Icon, ResultClass, BorderClass } = ActionStatus({
_result: result,
...statusProps,
status: statusProps.status
});
return (
<Card className={cn("mt-2", BorderClass(), className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{icon && (
<div className="flex items-center gap-2">
{Icon('md')}
{icon}
</div>
)}
<div>
<div className="font-mono text-sm font-medium">{title}</div>
{description && (
<div className="text-xs text-muted-foreground">{description}</div>
)}
</div>
</div>
<div className="flex items-center gap-2">
<Badge />
</div>
</div>
</CardHeader>
{(children || (showResult && result)) && (
<CardContent className="pt-0">
{children}
{showResult && result && (
<div className={ResultClass()}>
<pre className="whitespace-pre-wrap break-words">{result}</pre>
</div>
)}
</CardContent>
)}
</Card>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { Badge } from '@/components/ui/badge';
import { Loader2, XCircle, CheckCircle, Play } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface ActionStatusProps {
status?: 'RUNNING' | 'SUCCESS' | 'FAILED' | 'PENDING';
isLoading?: boolean;
isError?: boolean;
_result?: string;
runningIcon?: React.ReactNode;
successIcon?: React.ReactNode;
failedIcon?: React.ReactNode;
successLabel?: string;
failedLabel?: string;
runningLabel?: string;
}
export function ActionStatus({
status,
isLoading,
isError,
_result,
runningIcon = <Loader2 className="h-3 w-3 animate-spin" />,
successIcon = <CheckCircle className="h-3 w-3" />,
failedIcon = <XCircle className="h-3 w-3" />,
successLabel = 'Success',
failedLabel = 'Failed',
runningLabel = 'Running'
}: ActionStatusProps) {
// Handle both new status-based and old boolean-based props for compatibility
const effectiveStatus = status || (
isLoading ? 'RUNNING' :
isError ? 'FAILED' : 'SUCCESS'
) as 'RUNNING' | 'SUCCESS' | 'FAILED' | 'PENDING';
const getBadge = () => {
if (effectiveStatus === 'RUNNING') {
return (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
{runningIcon}
{runningLabel}
</Badge>
);
}
if (effectiveStatus === 'FAILED') {
return (
<Badge variant="destructive" className="text-xs">
{failedIcon}
{failedLabel}
</Badge>
);
}
return (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
{successIcon}
{successLabel}
</Badge>
);
};
const getIcon = (size: 'sm' | 'md' = 'md') => {
const sizeClass = size === 'sm' ? 'h-3 w-3' : 'h-4 w-4';
if (effectiveStatus === 'RUNNING') return <Loader2 className={`${sizeClass} animate-spin`} />;
if (effectiveStatus === 'FAILED') return <XCircle className={`${sizeClass} text-destructive`} />;
return <Play className={sizeClass} />;
};
const getResultClass = () => {
return cn(
"p-3 rounded-md text-sm",
effectiveStatus === 'FAILED'
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
);
};
const getBorderClass = () => {
return effectiveStatus === 'FAILED' ? "border-destructive/50" : "border-muted";
};
return {
Badge: getBadge,
Icon: getIcon,
ResultClass: getResultClass,
BorderClass: getBorderClass,
status: effectiveStatus
};
}
@@ -0,0 +1,125 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ArrowLeft, ArrowRight, Settings, Bot } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
interface AISettingsStepProps {
onNext: () => void;
onPrevious: () => void;
onSkip: () => void;
}
export function AISettingsStep({ onNext, onPrevious, onSkip }: AISettingsStepProps) {
const { settings, updateSettings } = useAISettings();
const [localSettings, setLocalSettings] = useState(settings);
const handleSave = () => {
updateSettings(localSettings);
onNext();
};
const isValid = localSettings.apiKey.trim() && localSettings.baseUrl.trim() && localSettings.model.trim();
return (
<div className="space-y-2 sm:space-y-4 mb-3 sm:mb-0">
<div className="text-center space-y-1 sm:space-y-1.5">
<div className="flex justify-center mb-0.5 sm:mb-1">
<Bot className="h-5 w-5 sm:h-6 sm:w-6 text-primary" />
</div>
<h1 className="text-base sm:text-lg md:text-xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent leading-tight">
Configure AI Settings
</h1>
<p className="text-xs sm:text-sm text-muted-foreground max-w-md mx-auto px-2">
Set up your AI provider to start building with AI assistance.
</p>
</div>
<Card className="max-w-md sm:max-w-lg md:max-w-lg mx-auto">
<CardHeader className="pb-2 sm:pb-3">
<div className="flex items-center gap-1.5 sm:gap-2">
<Settings className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
<CardTitle className="text-base sm:text-lg">AI Provider</CardTitle>
</div>
<CardDescription className="text-[10px] sm:text-xs">
We recommend OpenRouter for easy setup
</CardDescription>
</CardHeader>
<CardContent className="space-y-2 sm:space-y-3">
<div className="space-y-2 sm:space-y-3">
<div className="space-y-1">
<Label htmlFor="apiKey" className="text-xs sm:text-sm">API Key *</Label>
<Input
id="apiKey"
type="password"
placeholder="sk-... or your-api-key"
value={localSettings.apiKey}
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
className="font-mono text-xs sm:text-sm h-8 sm:h-9"
/>
<p className="text-[10px] sm:text-xs text-muted-foreground">
Stored locally, never shared
</p>
</div>
<div className="space-y-1">
<Label htmlFor="baseUrl" className="text-xs sm:text-sm">Base URL *</Label>
<Input
id="baseUrl"
placeholder="https://openrouter.ai/api/v1"
value={localSettings.baseUrl}
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
className="text-xs sm:text-sm h-8 sm:h-9"
/>
</div>
<div className="space-y-1">
<Label htmlFor="model" className="text-xs sm:text-sm">Model *</Label>
<Input
id="model"
placeholder="anthropic/claude-sonnet-4"
value={localSettings.model}
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
className="text-xs sm:text-sm h-8 sm:h-9"
/>
</div>
</div>
</CardContent>
</Card>
<div className="flex justify-center gap-2 sm:gap-3 pt-1 sm:pt-2">
<Button
onClick={onPrevious}
variant="outline"
size="sm"
className="gap-1 h-8 text-sm"
>
<ArrowLeft className="h-3 w-3" />
Back
</Button>
<Button
onClick={handleSave}
disabled={!isValid}
size="sm"
className="gap-1 h-8 text-sm bg-gradient-to-r from-primary to-primary/90"
>
Continue
<ArrowRight className="h-3 w-3" />
</Button>
</div>
<div className="text-center">
<Button
onClick={onSkip}
variant="ghost"
size="sm"
className="text-muted-foreground text-[10px] sm:text-xs h-6 sm:h-7"
>
Skip for now
</Button>
</div>
</div>
);
}
@@ -0,0 +1,136 @@
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { WelcomeStep } from './WelcomeStep';
import { AISettingsStep } from './AISettingsStep';
import { ProjectStep } from './ProjectStep';
interface OnboardingDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onProjectCreated?: (projectId: string) => void;
onComplete: () => void;
currentStep: number;
onNextStep: () => void;
onPreviousStep: () => void;
initialPrompt?: string;
}
const STEPS = [
{ id: 'welcome', title: 'Welcome' },
{ id: 'ai-settings', title: 'AI Settings' },
{ id: 'project', title: 'Create Project' },
];
export function OnboardingDialog({
open,
onOpenChange,
onProjectCreated,
onComplete,
currentStep: propCurrentStep,
onNextStep,
onPreviousStep,
initialPrompt = ''
}: OnboardingDialogProps) {
const [localStep, setLocalStep] = useState(propCurrentStep);
// Sync local step with prop when it changes
useEffect(() => {
setLocalStep(propCurrentStep);
}, [propCurrentStep]);
const currentStep = Math.min(localStep, STEPS.length - 1);
const progress = ((currentStep + 1) / STEPS.length) * 100;
const handleNext = () => {
if (currentStep < STEPS.length - 1) {
setLocalStep(prev => prev + 1);
onNextStep();
}
};
const handlePrevious = () => {
if (currentStep > 0) {
setLocalStep(prev => prev - 1);
onPreviousStep();
}
};
const handleSkip = () => {
onComplete();
onOpenChange(false);
};
const handleComplete = () => {
onComplete();
onOpenChange(false);
};
const renderStep = () => {
switch (STEPS[currentStep]?.id) {
case 'welcome':
return (
<WelcomeStep
onNext={handleNext}
onSkip={handleSkip}
/>
);
case 'ai-settings':
return (
<AISettingsStep
onNext={handleNext}
onPrevious={handlePrevious}
onSkip={handleSkip}
/>
);
case 'project':
return (
<ProjectStep
onNext={handleSkip} // Skip to complete
onPrevious={handlePrevious}
onComplete={handleComplete}
onProjectCreated={onProjectCreated}
initialPrompt={initialPrompt}
/>
);
default:
return null;
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg w-[95vw] max-h-[90vh] overflow-y-auto p-0 sm:max-w-xl md:max-w-4xl">
<div className="sticky top-0 bg-background border-b p-4 sm:p-5 pb-3 z-10">
<DialogTitle className="sr-only">Getting Started Onboarding</DialogTitle>
<DialogDescription className="sr-only">Complete the onboarding process to get started with Shakespeare</DialogDescription>
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<h2 className="text-base sm:text-lg font-semibold">Getting Started</h2>
<span className="text-xs sm:text-sm text-muted-foreground">
{currentStep + 1} / {STEPS.length}
</span>
</div>
<div className="relative">
<Progress value={progress} className="h-1.5" />
</div>
<div className="grid grid-cols-3 gap-2 text-[10px] sm:text-xs text-muted-foreground">
{STEPS.map((step, index) => (
<span
key={step.id}
className={`text-center ${index <= currentStep ? 'text-primary font-medium' : ''} truncate`}
>
{step.title}
</span>
))}
</div>
</div>
</div>
<div className="px-2 sm:p-6">
{renderStep()}
</div>
</DialogContent>
</Dialog>
);
}
+114
View File
@@ -0,0 +1,114 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Plus, Sparkles } from 'lucide-react';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useNavigate } from 'react-router-dom';
interface ProjectStepProps {
onNext: () => void;
onPrevious: () => void;
onComplete: () => void;
onProjectCreated?: (projectId: string) => void;
initialPrompt?: string;
}
export function ProjectStep({ onPrevious, onComplete, onProjectCreated, initialPrompt = '' }: ProjectStepProps) {
const [prompt, setPrompt] = useState(initialPrompt);
const [isCreating, setIsCreating] = useState(false);
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const handleCreateProject = async () => {
if (!prompt.trim()) return;
setIsCreating(true);
try {
const project = await projectsManager.createProject(prompt.trim());
onProjectCreated?.(project.id);
onComplete();
navigate(`/project/${project.id}`);
} catch (error) {
console.error('Failed to create project:', error);
} finally {
setIsCreating(false);
}
};
return (
<div className="space-y-3 sm:space-y-6 pb-4">
<div className="text-center space-y-1 sm:space-y-4">
<div className="flex justify-center mb-0.5 sm:mb-2">
<Sparkles className="h-5 w-5 sm:h-8 sm:w-8 text-primary" />
</div>
<h1 className="text-base sm:text-2xl md:text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent leading-tight">
Create Your First Project
</h1>
<p className="text-xs sm:text-base text-muted-foreground max-w-md sm:max-w-2xl mx-auto px-2">
Our AI will help you create it step by step.
</p>
</div>
<Card className="max-w-md sm:max-w-2xl md:max-w-2xl mx-auto">
<CardHeader className="pb-3 sm:pb-4">
<div className="flex items-center gap-1.5 sm:gap-2">
<Sparkles className="h-4 w-4 sm:h-5 sm:w-5 text-primary" />
<CardTitle className="text-base sm:text-lg">Project Description</CardTitle>
</div>
<CardDescription className="text-xs sm:text-sm">
Be as detailed as possible about what you want to build
</CardDescription>
</CardHeader>
<CardContent className="space-y-3 sm:space-y-4">
<Textarea
placeholder="e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies. Include user profiles, product listings with images, search functionality, and direct messaging between buyers and sellers..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
className="min-h-[175px] sm:min-h-[100px] sm:min-h-[125px] text-xs sm:text-sm leading-relaxed"
disabled={isCreating}
/>
<div className="hidden sm:block space-y-1.5 sm:space-y-2">
<h3 className="font-medium text-xs sm:text-sm">Example prompts:</h3>
<ul className="text-[10px] sm:text-xs text-muted-foreground space-y-0.5 sm:space-y-1">
<li>• "Build a social media platform for photographers"</li>
<li>• "Create a blog with markdown and Nostr comments"</li>
<li>• "Design a marketplace with categories and ratings"</li>
</ul>
</div>
</CardContent>
</Card>
<div className="flex flex-col items-center gap-2 pt-2 sm:pt-4">
<Button
onClick={handleCreateProject}
disabled={!prompt.trim() || isCreating}
size="lg"
className="gap-2 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80"
>
{isCreating ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-1"></div>
Creating...
</>
) : (
<>
<Plus className="h-4 w-4" />
Create Project
</>
)}
</Button>
<Button
onClick={onPrevious}
variant="ghost"
size="sm"
className="text-muted-foreground text-xs h-7"
>
<ArrowLeft className="h-3 w-3" />
Back
</Button>
</div>
</div>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { Button } from '@/components/ui/button';
import { Card, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { ArrowRight, Zap, GlobeLock, Palette } from 'lucide-react';
interface WelcomeStepProps {
onNext: () => void;
onSkip: () => void;
}
export function WelcomeStep({ onNext, onSkip }: WelcomeStepProps) {
return (
<div className="space-y-6 p-4">
<div className="text-center space-y-4">
<div className="text-6xl mb-4">🎭</div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Shakespeare
</h1>
<p className="text-base text-muted-foreground max-w-2xl mx-auto">
Build custom Nostr websites with AI assistance. Let's get you set up in just a few steps.
</p>
</div>
<div className="hidden md:grid md:grid-cols-3 gap-4 max-w-4xl mx-auto">
<Card className="text-center">
<CardHeader>
<div className="flex justify-center mb-2">
<Zap className="h-8 w-8 text-primary" />
</div>
<CardTitle className="text-lg">AI-Powered</CardTitle>
<CardDescription>
Describe your vision and let AI build your Nostr website
</CardDescription>
</CardHeader>
</Card>
<Card className="text-center">
<CardHeader>
<div className="flex justify-center mb-2">
<GlobeLock className="h-8 w-8 text-primary" />
</div>
<CardTitle className="text-lg">Decentralized</CardTitle>
<CardDescription>
Built with the Nostr protocol for censorship resistance
</CardDescription>
</CardHeader>
</Card>
<Card className="text-center">
<CardHeader>
<div className="flex justify-center mb-2">
<Palette className="h-8 w-8 text-primary" />
</div>
<CardTitle className="text-lg">Customizable</CardTitle>
<CardDescription>
Edit code directly or let AI make changes based on your feedback
</CardDescription>
</CardHeader>
</Card>
</div>
<div className="flex flex-col items-center gap-2 pt-4">
<Button
onClick={onNext}
size="lg"
className="gap-2 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80"
>
Get Started
<ArrowRight className="h-4 w-4" />
</Button>
<Button
onClick={onSkip}
variant="ghost"
size="sm"
className="text-muted-foreground text-xs h-7"
>
Skip for now
</Button>
</div>
</div>
);
}
+4
View File
@@ -0,0 +1,4 @@
export { OnboardingDialog } from './OnboardingDialog';
export { WelcomeStep } from './WelcomeStep';
export { AISettingsStep } from './AISettingsStep';
export { ProjectStep } from './ProjectStep';
+3 -11
View File
@@ -1,22 +1,14 @@
import { createContext } from 'react';
export interface AIConnection {
baseURL: string;
apiKey?: string;
}
export interface AISettings {
providers: Record<string, AIConnection>;
recentlyUsedModels: string[];
apiKey: string;
baseUrl: string;
model: string;
}
export interface AISettingsContextType {
settings: AISettings;
updateSettings: (settings: Partial<AISettings>) => void;
addProvider: (name: string, connection: AIConnection) => void;
removeProvider: (name: string) => void;
updateProvider: (name: string, connection: Partial<AIConnection>) => void;
addRecentlyUsedModel: (modelId: string) => void;
isConfigured: boolean;
}
-4
View File
@@ -1,4 +0,0 @@
import { createContext } from 'react';
import type { SessionManager } from '@/lib/SessionManager';
export const SessionManagerContext = createContext<SessionManager | null>(null);
-214
View File
@@ -1,214 +0,0 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
import { useAISettings } from '@/hooks/useAISettings';
import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager';
import type OpenAI from 'openai';
import type { Tool } from '@/lib/tools/Tool';
interface UseAIChatSessionOptions {
projectId: string;
projectName: string;
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools?: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void;
}
interface StreamingMessage {
role: 'assistant';
content: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
}
/**
* Hook that provides AI chat functionality using the global session manager.
* Sessions persist and can run in the background when switching between projects.
*/
export function useAIChat({
projectId,
projectName,
tools = {},
customTools = {},
systemPrompt,
maxSteps = 50,
onUpdateMetadata
}: UseAIChatSessionOptions) {
const sessionManager = useSessionManager();
const { isConfigured } = useAISettings();
const [sessionId, setSessionId] = useState<string>('');
const [sessionState, setSessionState] = useState<SessionState | null>(null);
// Generate consistent session ID for this project
const generatedSessionId = useMemo(() => {
return `session-${projectId}`;
}, [projectId]);
// Initialize session
useEffect(() => {
const initSession = async () => {
// Check if there's already an active session for this project
const existingSessions = sessionManager.getProjectSessions(projectId);
if (existingSessions.length > 0) {
// Use the most recent session for this project
const mostRecent = existingSessions.sort((a, b) =>
b.lastActivity.getTime() - a.lastActivity.getTime()
)[0];
setSessionId(mostRecent.id);
setSessionState(mostRecent);
// Get the latest session state immediately
const currentSession = sessionManager.getSession(mostRecent.id);
if (currentSession) {
setSessionState(currentSession);
}
} else {
// Create new session
const config: SessionConfig = {
id: generatedSessionId,
projectId,
projectName,
tools,
customTools,
systemPrompt,
maxSteps
};
const newSessionId = await sessionManager.createSession(config);
setSessionId(newSessionId);
const newSession = sessionManager.getSession(newSessionId);
if (newSession) {
setSessionState(newSession);
}
}
};
initSession();
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
// Subscribe to session events using shared hook
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
if (updatedSessionId === sessionId) {
// Directly update state with the provided state object
setSessionState({
...state,
messages: [...state.messages],
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined
});
}
}, [sessionId]);
useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => {
if (updatedSessionId === sessionId) {
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({
...session,
messages: [...session.messages],
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
});
}
}
}, [sessionId, sessionManager]);
useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
if (updatedSessionId === sessionId) {
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({
...session,
messages: [...session.messages],
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
});
}
}
}, [sessionId, sessionManager]);
useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => {
if (updatedSessionId === sessionId) {
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({
...session,
messages: [...session.messages],
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
});
}
if (onUpdateMetadata && isLoading) {
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
}
}
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
// Derived state
const messages = sessionState?.messages || [];
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
const isLoading = sessionState?.isLoading || false;
// Actions
const sendMessage = useCallback(async (content: string, providerModel: string) => {
if (!sessionId) return;
await sessionManager.sendMessage(sessionId, content, providerModel);
}, [sessionId, sessionManager]);
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
if (!sessionId) return;
// If specific messages are provided, we need to update the session first
if (messagesToUse) {
const session = sessionManager.getSession(sessionId);
if (session) {
// Replace session messages with provided messages
session.messages = [...messagesToUse];
// Manually trigger session update
sessionManager.emit('sessionUpdated', sessionId, session);
}
}
await sessionManager.startGeneration(sessionId, providerModel);
}, [sessionId, sessionManager]);
const stopGeneration = useCallback(() => {
if (!sessionId) return;
sessionManager.stopGeneration(sessionId);
}, [sessionId, sessionManager]);
const addMessage = useCallback(async (message: AIMessage) => {
if (!sessionId) return;
await sessionManager.addMessage(sessionId, message);
}, [sessionId, sessionManager]);
const startNewSession = useCallback(async () => {
if (!sessionId) return;
await sessionManager.startNewSession(sessionId);
}, [sessionId, sessionManager]);
const clearMessages = useCallback(async () => {
// Alias for startNewSession for backward compatibility
await startNewSession();
}, [startNewSession]);
return {
messages,
streamingMessage,
isLoading,
sendMessage,
startGeneration,
stopGeneration,
clearMessages,
startNewSession,
addMessage,
isConfigured,
sessionId
};
}
-98
View File
@@ -1,98 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useAIProjectId } from './useAIProjectId';
import { useAISettings } from './useAISettings';
// Mock the useAISettings hook
vi.mock('./useAISettings');
describe('useAIProjectId', () => {
const mockUseAISettings = vi.mocked(useAISettings);
beforeEach(() => {
vi.clearAllMocks();
// Mock fetch globally
global.fetch = vi.fn();
});
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: {}, recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isConfigured).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('should throw error when trying to generate ID without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: {}, recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('test prompt')).rejects.toThrow(
'AI settings not configured'
);
});
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('')).rejects.toThrow(
'Prompt cannot be empty'
);
});
it('should have configured status when providers are available', () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isConfigured).toBe(true);
expect(result.current.isLoading).toBe(false);
});
});
-94
View File
@@ -1,94 +0,0 @@
import { useState, useCallback } from 'react';
import OpenAI from 'openai';
import { useAISettings } from '@/hooks/useAISettings';
interface UseAIProjectIdOptions {
onError?: (error: string) => void;
}
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
const [isLoading, setIsLoading] = useState(false);
const { settings, isConfigured } = useAISettings();
const generateProjectId = useCallback(async (prompt: string): Promise<string> => {
if (!isConfigured) {
throw new Error('AI settings not configured');
}
if (!prompt.trim()) {
throw new Error('Prompt cannot be empty');
}
setIsLoading(true);
try {
// Use first available provider as fallback
const providers = settings.providers || {};
const firstProvider = Object.keys(providers)[0];
if (!firstProvider) {
throw new Error('No configured AI providers available');
}
const connectionConfig = providers[firstProvider];
const modelName = 'gpt-3.5-turbo'; // Use a fast, cheap model for ID generation
// Initialize OpenAI client
const openai = new OpenAI({
baseURL: connectionConfig.baseURL,
apiKey: connectionConfig.apiKey,
dangerouslyAllowBrowser: true
});
const systemPrompt = `You are a project ID generator. Given a user's description of what they want to build, generate a short, descriptive, kebab-case project ID that captures the essence of their project.
Rules:
- Use only lowercase letters, numbers, and hyphens
- Keep it between 2-4 words
- Make it descriptive but concise
- No spaces, underscores, or special characters except hyphens
- Examples:
- "farming equipment marketplace" → "farming-marketplace"
- "social media for artists" → "artist-social-app"
- "crypto trading dashboard" → "crypto-dashboard"
- "recipe sharing platform" → "recipe-platform"
Respond with ONLY the project ID, no explanation or additional text.`;
const completion = await openai.chat.completions.create({
model: modelName,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
],
max_tokens: 20,
temperature: 0.3,
});
const projectId = completion.choices[0]?.message?.content?.trim();
if (!projectId) {
throw new Error('Failed to generate project ID');
}
// Validate the generated ID
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (!validIdRegex.test(projectId)) {
throw new Error('Generated project ID is invalid');
}
return projectId;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
}, [isConfigured, settings, onError]);
return {
generateProjectId,
isLoading,
isConfigured
};
}
-245
View File
@@ -1,245 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import git from 'isomorphic-git';
import { useFS } from './useFS';
interface GitFileChange {
filepath: string;
status: 'modified' | 'added' | 'deleted' | 'untracked' | 'staged';
}
interface GitCommit {
oid: string;
message: string;
author: {
name: string;
email: string;
timestamp: number;
};
committer: {
name: string;
email: string;
timestamp: number;
};
}
interface GitRemote {
name: string;
url: string;
}
interface GitStatus {
hasUncommittedChanges: boolean;
changedFiles: GitFileChange[];
isGitRepo: boolean;
currentBranch: string | null;
latestCommit: GitCommit | null;
remotes: GitRemote[];
totalCommits: number;
branches: string[];
ahead: number;
behind: number;
}
export function useGitStatus(projectId: string | null) {
const { fs } = useFS();
return useQuery({
queryKey: ['git-status', projectId],
queryFn: async (): Promise<GitStatus> => {
if (!projectId) {
return {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: false,
currentBranch: null,
latestCommit: null,
remotes: [],
totalCommits: 0,
branches: [],
ahead: 0,
behind: 0,
};
}
try {
const cwd = `/projects/${projectId}`;
// Check if we're in a git repository
try {
await fs.stat(`${cwd}/.git`);
} catch {
return {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: false,
currentBranch: null,
latestCommit: null,
remotes: [],
totalCommits: 0,
branches: [],
ahead: 0,
behind: 0,
};
}
// Get current branch
let currentBranch: string | null = null;
try {
const branch = await git.currentBranch({
fs,
dir: cwd,
fullname: false,
});
currentBranch = branch || null;
} catch (error) {
console.warn('Could not get current branch:', error);
}
// Get all branches
const branches: string[] = [];
try {
const allBranches = await git.listBranches({
fs,
dir: cwd,
});
branches.push(...allBranches);
} catch (error) {
console.warn('Could not list branches:', error);
}
// Get latest commit
let latestCommit: GitCommit | null = null;
let totalCommits = 0;
try {
const commits = await git.log({
fs,
dir: cwd,
depth: 1,
});
if (commits.length > 0) {
const commit = commits[0];
latestCommit = {
oid: commit.oid,
message: commit.commit.message,
author: {
name: commit.commit.author.name,
email: commit.commit.author.email,
timestamp: commit.commit.author.timestamp,
},
committer: {
name: commit.commit.committer.name,
email: commit.commit.committer.email,
timestamp: commit.commit.committer.timestamp,
},
};
}
// Get total commit count
const allCommits = await git.log({
fs,
dir: cwd,
});
totalCommits = allCommits.length;
} catch (error) {
console.warn('Could not get commit history:', error);
}
// Get remotes
const remotes: GitRemote[] = [];
try {
const remoteNames = await git.listRemotes({
fs,
dir: cwd,
});
for (const remote of remoteNames) {
remotes.push({
name: remote.remote,
url: remote.url,
});
}
} catch (error) {
console.warn('Could not get remotes:', error);
}
// Get git status to see what files have changed
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
});
// Parse file changes with more detailed status
const changedFiles: GitFileChange[] = [];
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
let status: GitFileChange['status'];
if (headStatus === 0 && workdirStatus === 2 && stageStatus === 0) {
status = 'untracked';
} else if (headStatus === 0 && workdirStatus === 2 && stageStatus === 2) {
status = 'added';
} else if (headStatus === 1 && workdirStatus === 2 && stageStatus === 2) {
status = 'staged';
} else if (headStatus === 1 && workdirStatus === 2 && stageStatus === 1) {
status = 'modified';
} else if (headStatus === 1 && workdirStatus === 0 && stageStatus === 0) {
status = 'deleted';
} else if (headStatus !== workdirStatus || workdirStatus !== stageStatus) {
status = 'modified';
} else {
continue; // No changes
}
changedFiles.push({
filepath,
status,
});
}
// Calculate ahead/behind (simplified - would need remote tracking branch info)
const ahead = 0;
const behind = 0;
try {
// This is a simplified calculation - in a real implementation,
// you'd compare with the remote tracking branch
if (currentBranch && remotes.length > 0) {
// For now, we'll leave these as 0 since calculating ahead/behind
// requires more complex remote branch comparison
}
} catch (error) {
console.warn('Could not calculate ahead/behind:', error);
}
return {
hasUncommittedChanges: changedFiles.length > 0,
changedFiles,
isGitRepo: true,
currentBranch,
latestCommit,
remotes,
totalCommits,
branches,
ahead,
behind,
};
} catch (error) {
console.error('Error checking git status:', error);
return {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: false,
currentBranch: null,
latestCommit: null,
remotes: [],
totalCommits: 0,
branches: [],
ahead: 0,
behind: 0,
};
}
},
enabled: !!projectId,
refetchInterval: 5000, // Check every 5 seconds
staleTime: 2000, // Consider data stale after 2 seconds
});
}
+48
View File
@@ -0,0 +1,48 @@
import { useState, useEffect } from 'react';
import { useLocalStorage } from './useLocalStorage';
export function useOnboarding() {
const [hasCompletedOnboarding, setHasCompletedOnboarding] = useLocalStorage(
'shakespeare-onboarding-completed',
false
);
const [currentStep, setCurrentStep] = useState(0);
const [isOnboardingOpen, setIsOnboardingOpen] = useState(false);
// Check if onboarding should be shown on first load
useEffect(() => {
if (!hasCompletedOnboarding) {
setIsOnboardingOpen(true);
}
}, [hasCompletedOnboarding]);
const handleNextStep = () => {
setCurrentStep(prev => Math.min(prev + 1, 2));
};
const handlePreviousStep = () => {
setCurrentStep(prev => Math.max(prev - 1, 0));
};
const handleCompleteOnboarding = () => {
setHasCompletedOnboarding(true);
setIsOnboardingOpen(false);
setCurrentStep(0);
};
const handleRestartOnboarding = () => {
setCurrentStep(0);
setIsOnboardingOpen(true);
};
return {
hasCompletedOnboarding,
currentStep,
isOnboardingOpen,
setIsOnboardingOpen,
handleNextStep,
handlePreviousStep,
handleCompleteOnboarding,
handleRestartOnboarding,
};
}
-42
View File
@@ -1,42 +0,0 @@
import { useState, useEffect } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
/**
* Hook to get session status for a specific project
*/
export function useProjectSessionStatus(projectId: string) {
const sessionManager = useSessionManager();
const [hasActiveSessions, setHasActiveSessions] = useState(false);
const [hasRunningSessions, setHasRunningSessions] = useState(false);
useEffect(() => {
const updateStatus = () => {
const projectSessions = sessionManager.getProjectSessions(projectId);
const runningSessions = projectSessions.filter(session => session.isLoading);
setHasActiveSessions(projectSessions.length > 0);
setHasRunningSessions(runningSessions.length > 0);
};
// Initial update
updateStatus();
// Subscribe to session changes
sessionManager.on('sessionCreated', updateStatus);
sessionManager.on('sessionUpdated', updateStatus);
sessionManager.on('sessionDeleted', updateStatus);
sessionManager.on('loadingChanged', updateStatus);
return () => {
sessionManager.off('sessionCreated', updateStatus);
sessionManager.off('sessionUpdated', updateStatus);
sessionManager.off('sessionDeleted', updateStatus);
sessionManager.off('loadingChanged', updateStatus);
};
}, [sessionManager, projectId]);
return {
hasActiveSessions,
hasRunningSessions
};
}
-108
View File
@@ -1,108 +0,0 @@
import { useState, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import OpenAI from 'openai';
import { useAISettings } from '@/hooks/useAISettings';
interface ProviderModel {
id: string;
name: string;
provider: string;
fullId: string; // provider/model format
}
interface ModelFetchResult {
models: ProviderModel[];
isLoading: boolean;
error: string | null;
refetch: () => void;
}
export function useProviderModels(): ModelFetchResult {
const { settings } = useAISettings();
const [error, setError] = useState<string | null>(null);
const {
data: models = [],
isLoading,
refetch: queryRefetch,
} = useQuery({
queryKey: ['provider-models', settings.providers],
queryFn: async () => {
const allModels: ProviderModel[] = [];
const errors: string[] = [];
// Fetch models from each configured provider
for (const [providerKey, connection] of Object.entries(settings.providers)) {
try {
const openai = new OpenAI({
baseURL: connection.baseURL,
apiKey: connection.apiKey,
dangerouslyAllowBrowser: true,
});
// Fetch models with timeout
try {
const response = await openai.models.list({
signal: AbortSignal.timeout(10_000),
});
// Transform models to our format
const providerModels = response.data.map((model) => ({
id: model.id,
name: model.id,
provider: providerKey,
fullId: `${providerKey}/${model.id}`,
}));
allModels.push(...providerModels);
} catch (fetchError) {
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
errors.push(`${providerKey}: Request timeout`);
} else {
throw fetchError;
}
}
} catch (providerError) {
console.warn(`Failed to fetch models from ${providerKey}:`, providerError);
errors.push(
`${providerKey}: ${
providerError instanceof Error ? providerError.message : 'Unknown error'
}`
);
}
}
// Set error state if there were any errors
if (errors.length > 0) {
setError(errors.join('; '));
} else {
setError(null);
}
// Sort models by provider, then by name
allModels.sort((a, b) => {
if (a.provider !== b.provider) {
return a.provider.localeCompare(b.provider);
}
return a.name.localeCompare(b.name);
});
return allModels;
},
enabled: Object.keys(settings.providers).length > 0,
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
retry: false, // Don't retry on failure
});
const refetch = useCallback(() => {
setError(null);
queryRefetch();
}, [queryRefetch]);
return {
models,
isLoading,
error,
refetch,
};
}
+223
View File
@@ -0,0 +1,223 @@
import { useQuery } from '@tanstack/react-query';
import { useProjectsManager } from './useProjectsManager';
import { useCurrentUser } from './useCurrentUser';
import { useNostr } from '@nostrify/react';
import { nip19 } from 'nostr-tools';
import type { Project } from '@/lib/ProjectsManager';
import type { NostrEvent } from '@nostrify/nostrify';
export interface NostrRepo {
event: NostrEvent;
id: string; // d tag value
name: string;
description?: string;
webUrls: string[];
cloneUrls: string[];
relays: string[];
maintainers: string[];
tags: string[];
earliestCommit?: string;
}
export type RepoStatus =
| 'local-only' // Exists only locally, not published to Nostr
| 'published' // Local project that's also published to Nostr
| 'remote-only' // Exists on Nostr but not cloned locally
| 'synced'; // Local and remote are in sync
export interface UnifiedRepo {
id: string;
name: string;
description?: string;
status: RepoStatus;
lastModified: Date;
// Local project data (if exists locally)
localProject?: Project;
// Nostr repo data (if exists on Nostr)
nostrRepo?: NostrRepo;
// Additional metadata
tags: string[];
webUrls: string[];
cloneUrls: string[];
maintainers: string[];
relays: string[];
}
function parseRepoEvent(event: NostrEvent): NostrRepo | null {
// Validate that this is a repository announcement event
if (event.kind !== 30617) return null;
const dTag = event.tags.find(([name]) => name === 'd')?.[1];
if (!dTag) return null;
const name = event.tags.find(([name]) => name === 'name')?.[1] || dTag;
const description = event.tags.find(([name]) => name === 'description')?.[1];
const webUrls = event.tags
.filter(([name]) => name === 'web')
.map(([, url]) => url)
.filter(Boolean);
const cloneUrls = event.tags
.filter(([name]) => name === 'clone')
.map(([, url]) => url)
.filter(Boolean);
const relays = event.tags
.filter(([name]) => name === 'relays')
.map(([, relay]) => relay)
.filter(Boolean);
const maintainers = event.tags
.filter(([name]) => name === 'maintainers')
.map(([, pubkey]) => pubkey)
.filter(Boolean);
const tags = event.tags
.filter(([name]) => name === 't')
.map(([, tag]) => tag)
.filter(Boolean);
const earliestCommit = event.tags
.find(([name, , marker]) => name === 'r' && marker === 'euc')?.[1];
return {
event,
id: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
tags,
earliestCommit,
};
}
export function useRepos() {
const projectsManager = useProjectsManager();
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery({
queryKey: ['unified-repos', user?.pubkey],
queryFn: async (c) => {
try {
if (!user?.pubkey) return [];
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(3000)]);
// Fetch Nostr repos and local projects in parallel
const [events, localProjects] = await Promise.all([
nostr.query([
{
kinds: [30617], // Repository announcements
authors: [user.pubkey],
limit: 50,
}
], { signal }),
(async () => {
await projectsManager.init();
return projectsManager.getProjects();
})()
]);
// Parse and validate Nostr events
const nostrRepos = events
.map(parseRepoEvent)
.filter((repo): repo is NostrRepo => repo !== null)
.sort((a, b) => b.event.created_at - a.event.created_at);
// Create a map to track repos by their identifier
const repoMap = new Map<string, UnifiedRepo>();
// First, add all local projects
for (const project of localProjects) {
const naddr = await projectsManager.getNostrRepoAddress(project.id);
let repoId = project.id;
let status: RepoStatus = 'local-only';
// If this project has a Nostr address, extract the repo ID
if (naddr) {
try {
const decoded = nip19.decode(naddr);
if (decoded.type === 'naddr') {
repoId = decoded.data.identifier;
status = 'published';
}
} catch {
// If we can't decode the naddr, treat as local-only
}
}
repoMap.set(repoId, {
id: repoId,
name: project.name,
description: undefined,
status,
lastModified: project.lastModified,
localProject: project,
tags: [],
webUrls: [],
cloneUrls: [],
maintainers: [],
relays: [],
});
}
// Then, add or update with Nostr repos
for (const nostrRepo of nostrRepos) {
const existingRepo = repoMap.get(nostrRepo.id);
if (existingRepo) {
// Update existing repo with Nostr data
existingRepo.nostrRepo = nostrRepo;
existingRepo.description = nostrRepo.description;
existingRepo.tags = nostrRepo.tags;
existingRepo.webUrls = nostrRepo.webUrls;
existingRepo.cloneUrls = nostrRepo.cloneUrls;
existingRepo.maintainers = nostrRepo.maintainers;
existingRepo.relays = nostrRepo.relays;
// Update status based on local presence
if (existingRepo.localProject) {
existingRepo.status = 'synced';
}
} else {
// Add new remote-only repo
repoMap.set(nostrRepo.id, {
id: nostrRepo.id,
name: nostrRepo.name,
description: nostrRepo.description,
status: 'remote-only',
lastModified: new Date(nostrRepo.event.created_at * 1000),
nostrRepo,
tags: nostrRepo.tags,
webUrls: nostrRepo.webUrls,
cloneUrls: nostrRepo.cloneUrls,
maintainers: nostrRepo.maintainers,
relays: nostrRepo.relays,
});
}
}
// Convert map to array and sort by last modified
const repos = Array.from(repoMap.values()).sort((a, b) =>
b.lastModified.getTime() - a.lastModified.getTime()
);
return repos;
} catch (error) {
console.error('Failed to load unified repos:', error);
return [];
}
},
enabled: !!user?.pubkey,
staleTime: 30 * 1000, // 30 seconds
gcTime: 60 * 1000, // 1 minute
});
}
-15
View File
@@ -1,15 +0,0 @@
import { useContext } from 'react';
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
/**
* Hook to access the global session manager
*/
export function useSessionManager() {
const sessionManager = useContext(SessionManagerContext);
if (!sessionManager) {
throw new Error('useSessionManager must be used within a SessionManagerProvider');
}
return sessionManager;
}
-33
View File
@@ -1,33 +0,0 @@
import { useEffect, useRef } from 'react';
import { useSessionManager } from './useSessionManager';
import type { SessionManagerEvents } from '@/lib/SessionManager';
/**
* Custom hook for subscribing to SessionManager events with automatic cleanup
*/
export function useSessionSubscription<K extends keyof SessionManagerEvents>(
event: K,
handler: SessionManagerEvents[K],
deps: React.DependencyList = []
): void {
const sessionManager = useSessionManager();
// Use a ref to track the current handler and deps
const handlerRef = useRef(handler);
const depsRef = useRef(deps);
// Update refs when handler or deps change
useEffect(() => {
handlerRef.current = handler;
depsRef.current = deps;
}, [handler, deps]);
useEffect(() => {
const currentHandler = handlerRef.current;
sessionManager.on(event, currentHandler);
return () => {
sessionManager.off(event, currentHandler);
};
}, [sessionManager, event, deps]);
}
-203
View File
@@ -1,203 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { DotAI } from './DotAI';
import type { JSRuntimeFS } from './JSRuntime';
import type OpenAI from 'openai';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('DotAI', () => {
let mockFS: JSRuntimeFS;
let dotAI: DotAI;
beforeEach(() => {
mockFS = createMockFS();
dotAI = new DotAI(mockFS, '/test-project');
});
describe('readLastSessionHistory', () => {
it('should return null when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when history directory does not exist', async () => {
// Mock isEnabled to return true but historyDirExists to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when no session files exist', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return empty array
vi.mocked(mockFS.readdir).mockResolvedValue([]);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return messages and session name from most recent file', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue([
'2024-08-24T16-30-45Z-abc.jsonl',
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
'2024-08-24T15-00-00Z-xyz.jsonl'
]);
// Mock readFile to return JSONL content
const mockContent = `{"role":"user","content":"Hello"}
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
expect(result?.messages).toHaveLength(2);
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
it('should handle malformed JSON lines gracefully', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
// Mock readFile to return content with malformed JSON
const mockContent = `{"role":"user","content":"Hello"}
invalid json line
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
});
describe('setHistory', () => {
it('should not save when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi there!' }
];
await dotAI.setHistory('test-session', messages);
// Verify writeFile was not called
expect(mockFS.writeFile).not.toHaveBeenCalled();
});
it('should create history directory if it does not exist', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return false initially
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
// Mock setupAiHistoryDir
vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue();
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' }
];
await dotAI.setHistory('test-session', messages);
// Verify setupAiHistoryDir was called
expect(dotAI.setupAiHistoryDir).toHaveBeenCalled();
});
it('should write messages as JSONL format', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi there!' }
];
await dotAI.setHistory('test-session', messages);
// Verify writeFile was called with correct content
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.ai/history/test-session.jsonl',
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
);
});
it('should handle empty messages array', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
await dotAI.setHistory('test-session', []);
// Verify writeFile was called with empty content
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.ai/history/test-session.jsonl',
''
);
});
it('should handle write errors gracefully', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock writeFile to throw an error
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed'));
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [{ role: 'user', content: 'Hello' }];
// Should not throw
await expect(dotAI.setHistory('test-session', messages)).resolves.toBeUndefined();
});
});
describe('generateSessionName', () => {
it('should generate a unique session name', () => {
const sessionName1 = DotAI.generateSessionName();
const sessionName2 = DotAI.generateSessionName();
expect(sessionName1).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z-[a-z0-9]{3}$/);
expect(sessionName2).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z-[a-z0-9]{3}$/);
expect(sessionName1).not.toBe(sessionName2);
});
});
});
-338
View File
@@ -1,338 +0,0 @@
import { join } from "@std/path";
import type OpenAI from "openai";
import type { JSRuntimeFS } from "./JSRuntime";
/** AI message history manager and .ai directory utilities */
export class DotAI {
readonly fs: JSRuntimeFS;
readonly historyDir: string;
readonly workingDir: string;
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
this.fs = fs;
this.workingDir = workingDir;
this.historyDir = join(workingDir, ".ai", "history");
}
/** Generate a unique session name based on the current date and time */
static generateSessionName(): string {
// Generate filename with date, time in milliseconds, and random value
const now = new Date();
const dateString = now.toISOString();
// Generate a random 3-character suffix to avoid collisions
const randomSuffix = Math.random().toString(36).substring(2, 5);
// Format: YYYY-MM-DDTHH-MM-SSZ-suffix.jsonl
const filename = `${
dateString.replace(/:/g, "-").slice(0, dateString.indexOf("."))
}Z-${randomSuffix}`;
return filename;
}
/** Check if AI history should be enabled based on the new criteria */
async isEnabled(): Promise<boolean> {
// Check if .ai directory exists
try {
const stat = await this.fs.stat(join(this.workingDir, ".ai"));
if (stat.isDirectory()) {
return true;
}
} catch {
// Continue to next check
}
// Check if .ai/ or .ai is gitignored
try {
const gitignorePath = join(this.workingDir, ".gitignore");
const gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
const lines = gitignoreContent.split("\n").map((line) => line.trim());
// Check for .ai/ or .ai patterns (ignore comments and empty lines)
for (const line of lines) {
if (line.startsWith("#") || line === "") {
continue;
}
// Check for various .ai patterns
if (
line === ".ai" || line === ".ai/" || line === "/.ai" ||
line === "/.ai/" ||
line === ".ai/*" || line === "/.ai/*"
) {
return true;
}
}
} catch {
// .gitignore doesn't exist or can't be read
}
return false;
}
/** Check if the history directory exists */
async historyDirExists(): Promise<boolean> {
try {
const stat = await this.fs.stat(this.historyDir);
return stat.isDirectory();
} catch {
return false;
}
}
/** Save the full message history to the history file */
async setHistory(
sessionName: string,
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
): Promise<void> {
// Only save if history should be enabled based on the new criteria
if (!(await this.isEnabled())) {
return;
}
// Create the history directory if it doesn't exist
if (!(await this.historyDirExists())) {
await this.setupAiHistoryDir();
}
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
try {
// Convert messages to JSONL format
const jsonlContent = messages.map(message => JSON.stringify(message)).join('\n');
const finalContent = jsonlContent + (messages.length > 0 ? '\n' : '');
// Write the entire file
await this.fs.writeFile(sessionFile, finalContent);
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to save messages to AI history: ${error}`);
}
}
/**
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
*/
async setupAiHistoryDir(): Promise<void> {
const aiHistoryDir = join(this.workingDir, ".ai", "history");
try {
// Create .ai/history directory
await this.fs.mkdir(aiHistoryDir, { recursive: true });
// Ensure .ai/ is gitignored at the project root
await this.ensureAiGitignored();
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to setup .ai/history directory: ${error}`);
}
}
/**
* Read the model from .ai/MODEL file
*/
async readAiModel(): Promise<string | undefined> {
try {
const modelPath = join(this.workingDir, ".ai", "MODEL");
const content = await this.fs.readFile(modelPath, "utf8");
return content.trim();
} catch {
return undefined;
}
}
/**
* Write the model to .ai/MODEL file
*/
async writeAiModel(model: string): Promise<void> {
const aiDir = join(this.workingDir, ".ai");
const modelPath = join(aiDir, "MODEL");
try {
// Ensure .ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Write the model
await this.fs.writeFile(modelPath, model.trim() + "\n");
} catch (error) {
console.warn(`Failed to write .ai/MODEL file: ${error}`);
}
}
/**
* Read parameters from .ai/PARAMETERS file
*/
async readAiParameters(): Promise<Record<string, string>> {
try {
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
const content = await this.fs.readFile(parametersPath, "utf8");
const parameters: Record<string, string> = {};
const lines = content.split("\n");
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine && !trimmedLine.startsWith("#")) {
const equalIndex = trimmedLine.indexOf("=");
if (equalIndex > 0) {
const key = trimmedLine.substring(0, equalIndex).trim();
const value = trimmedLine.substring(equalIndex + 1).trim();
parameters[key] = value;
}
}
}
return parameters;
} catch {
return {};
}
}
/**
* Write parameters to .ai/PARAMETERS file
*/
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
// Check if we should create the .ai directory based on the same logic as MODEL
const shouldCreate = await this.isEnabled();
if (!shouldCreate) {
return;
}
const aiDir = join(this.workingDir, ".ai");
const parametersPath = join(aiDir, "PARAMETERS");
try {
// Ensure .ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Format parameters as key=value pairs
const lines = Object.entries(parameters).map(([key, value]) =>
`${key}=${value}`
);
const content = lines.join("\n") + (lines.length > 0 ? "\n" : "");
// Write the parameters
await this.fs.writeFile(parametersPath, content);
} catch (error) {
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
}
}
/**
* Update a single parameter in .ai/PARAMETERS file
*/
async updateAiParameter(key: string, value: string): Promise<void> {
const currentParameters = await this.readAiParameters();
currentParameters[key] = value;
await this.writeAiParameters(currentParameters);
}
/**
* Read the most recent session history
* @returns Object containing messages array and session name, or null if no history found
*/
async readLastSessionHistory(): Promise<{
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
sessionName: string;
} | null> {
try {
// Check if AI history is enabled for this project
if (!(await this.isEnabled()) || !(await this.historyDirExists())) {
return null;
}
// Find the most recent session file
try {
const files = await this.fs.readdir(this.historyDir);
const sessionFiles = files
.filter(file => file.endsWith('.jsonl'))
.sort()
.reverse(); // Most recent first
if (sessionFiles.length === 0) {
return null;
}
const latestSessionFile = sessionFiles[0];
const sessionPath = join(this.historyDir, latestSessionFile);
try {
const content = await this.fs.readFile(sessionPath, 'utf8');
const lines = content.trim().split('\n').filter(line => line.trim());
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
for (const line of lines) {
try {
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch (parseError) {
console.warn('Failed to parse message from history:', parseError);
}
}
// Return session name without .jsonl extension
const sessionName = latestSessionFile.replace('.jsonl', '');
return {
messages,
sessionName
};
} catch (readError) {
console.warn('Failed to read session file:', readError);
return null;
}
} catch (readdirError) {
console.warn('Failed to read history directory:', readdirError);
return null;
}
} catch (error) {
console.warn('Failed to read last session history:', error);
return null;
}
}
/**
* Ensures that .ai/ is gitignored at the project root level.
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
*/
async ensureAiGitignored(): Promise<void> {
const gitignorePath = join(this.workingDir, ".gitignore");
const aiPattern = ".ai/";
try {
// Try to read existing .gitignore
let gitignoreContent = "";
try {
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
} catch {
// .gitignore doesn't exist, will create it
}
// Check if .ai/ is already gitignored
const lines = gitignoreContent.split("\n").map((line) => line.trim());
const hasAiPattern = lines.some((line) => {
if (line.startsWith("#") || line === "") {
return false;
}
// Check for various .ai patterns
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
line === "/.ai/" ||
line === ".ai/*" || line === "/.ai/*";
});
if (!hasAiPattern) {
// Add .ai/ to .gitignore
const newContent = gitignoreContent.trim() === ""
? aiPattern
: gitignoreContent.trim() + "\n" + aiPattern;
await this.fs.writeFile(gitignorePath, newContent + "\n");
}
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
}
}
}
-17
View File
@@ -1,17 +0,0 @@
import { describe, it, expect } from 'vitest';
import { HTTPError } from './HTTPError.ts';
describe('HTTPError', () => {
it('should create HTTPError with correct properties', () => {
const request = new Request('https://example.com/api');
const response = new Response('Not Found', { status: 404 });
const error = new HTTPError(response, request);
expect(error.name).toBe('HTTPError');
expect(error.message).toBe('HTTP Error: 404 GET https://example.com/api');
expect(error.response).toBe(response);
expect(error.request).toBe(request);
});
});
-14
View File
@@ -1,14 +0,0 @@
/** Error class for HTTP request failures */
export class HTTPError extends Error {
/** The response object from the failed HTTP request */
readonly response: Response;
/** The original request object */
readonly request: Request;
constructor(response: Response, request: Request) {
super(`HTTP Error: ${response.status} ${request.method} ${request.url}`);
this.name = 'HTTPError';
this.response = response;
this.request = request;
}
}
-371
View File
@@ -1,371 +0,0 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { KindGenerator } from './KindGenerator.ts';
const __dirname = dirname(fileURLToPath(import.meta.url));
describe('KindGenerator', () => {
it('should extract used kinds from real NIPs fixture', () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Check that some expected kinds are extracted from the real NIPs index
const expectedKinds = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
20,
21,
22,
30,
31,
32,
33,
40,
41,
42,
43,
44,
62,
64,
818,
1018,
1021,
1022,
1040,
1059,
1063,
1068,
1111,
1311,
1337,
1617,
1621,
1622,
1971,
1984,
1985,
1986,
1987,
2003,
2004,
2022,
4550,
7000,
7374,
7375,
7376,
9041,
9321,
9467,
9734,
9735,
9802,
10000,
10001,
10002,
10003,
10004,
10005,
10006,
10007,
10009,
10012,
10013,
10015,
10019,
10020,
10030,
10050,
10063,
10096,
10166,
13194,
17375,
21000,
22242,
23194,
23195,
24133,
24242,
27235,
30000,
30001,
30002,
30003,
30004,
30005,
30007,
30008,
30009,
30015,
30017,
30018,
30019,
30020,
30023,
30024,
30030,
30040,
30041,
30063,
30078,
30166,
30267,
30311,
30315,
30388,
30402,
30403,
30617,
30618,
30818,
30819,
31234,
31388,
31890,
31922,
31923,
31924,
31925,
31989,
31990,
32267,
34550,
38383,
39089,
39092,
39701,
];
for (const kind of expectedKinds) {
expect(usedKinds.has(kind)).toBe(true);
}
// Check that ranges are properly extracted
// `5000`-`5999` should add all numbers from 5000 to 5999
for (let i = 5000; i <= 5999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `6000`-`6999` should add all numbers from 6000 to 6999
for (let i = 6000; i <= 6999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `9000`-`9030` should add all numbers from 9000 to 9030
for (let i = 9000; i <= 9030; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `39000-9` should add all numbers from 39000 to 39009
for (let i = 39000; i <= 39009; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `1630`-`1633` should add all numbers from 1630 to 1633
for (let i = 1630; i <= 1633; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should extract used kinds from mock data', () => {
const mockNipsIndex = `
## Event Kinds
| kind | description | NIP |
| ------------- | ------------------------------- | -------------------------------------- |
| \`0\` | User Metadata | [01](01.md) |
| \`1\` | Short Text Note | [10](10.md) |
| \`3\` | Follows | [02](02.md) |
| \`1000\`-\`1999\` | Custom Range | [test](test.md) |
| \`30000\` | Addressable Event | [51](51.md) |
`;
const usedKinds = KindGenerator.extractUsedKinds(mockNipsIndex);
// Check individual kinds
expect(usedKinds.has(0)).toBe(true);
expect(usedKinds.has(1)).toBe(true);
expect(usedKinds.has(3)).toBe(true);
expect(usedKinds.has(30000)).toBe(true);
// Check range
for (let i = 1000; i <= 1999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should get kind range info correctly', () => {
const regularRange = KindGenerator.getKindRangeInfo('regular');
expect(regularRange.min).toBe(1000);
expect(regularRange.max).toBe(9999);
expect(regularRange.name).toBe('Regular Events');
const replaceableRange = KindGenerator.getKindRangeInfo('replaceable');
expect(replaceableRange.min).toBe(10000);
expect(replaceableRange.max).toBe(19999);
const ephemeralRange = KindGenerator.getKindRangeInfo('ephemeral');
expect(ephemeralRange.min).toBe(20000);
expect(ephemeralRange.max).toBe(29999);
const addressableRange = KindGenerator.getKindRangeInfo('addressable');
expect(addressableRange.min).toBe(30000);
expect(addressableRange.max).toBe(39999);
});
it('should generate available kinds in correct ranges', () => {
const usedKinds = new Set([1000, 1001, 1002, 10000, 10001, 30000, 30001]);
// Test regular range
const regularKind = KindGenerator.generateAvailableKind(
'regular',
usedKinds,
);
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
// Check new constraints
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
// Check buffer constraint - should not be within 2 of any used kind
for (const usedKind of usedKinds) {
const distance = Math.abs(regularKind - usedKind);
expect(distance > 2).toBe(true);
}
// Test replaceable range
const replaceableKind = KindGenerator.generateAvailableKind(
'replaceable',
usedKinds,
);
expect(replaceableKind >= 10000 && replaceableKind <= 19999).toBe(true);
expect(usedKinds.has(replaceableKind)).toBe(false);
expect(replaceableKind % 2 !== 0).toBe(true);
expect(replaceableKind % 5 !== 0).toBe(true);
// Test ephemeral range
const ephemeralKind = KindGenerator.generateAvailableKind(
'ephemeral',
usedKinds,
);
expect(ephemeralKind >= 20000 && ephemeralKind <= 29999).toBe(true);
expect(usedKinds.has(ephemeralKind)).toBe(false);
expect(ephemeralKind % 2 !== 0).toBe(true);
expect(ephemeralKind % 5 !== 0).toBe(true);
// Test addressable range
const addressableKind = KindGenerator.generateAvailableKind(
'addressable',
usedKinds,
);
expect(addressableKind >= 30000 && addressableKind <= 39999).toBe(true);
expect(usedKinds.has(addressableKind)).toBe(false);
expect(addressableKind % 2 !== 0).toBe(true);
expect(addressableKind % 5 !== 0).toBe(true);
});
it('should respect buffer constraints when generating kinds', () => {
// Test buffer constraint specifically
const usedKinds = new Set([1007, 1013, 1019]); // Use odd numbers that aren't multiples of 5
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should be in range
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
// Should be odd
expect(regularKind % 2 !== 0).toBe(true);
// Should not be multiple of 5
expect(regularKind % 5 !== 0).toBe(true);
// Should not be within buffer of used kinds
const forbiddenNumbers = new Set([
1005, 1006, 1007, 1008, 1009, // around 1007
1011, 1012, 1013, 1014, 1015, // around 1013
1017, 1018, 1019, 1020, 1021, // around 1019
]);
expect(forbiddenNumbers.has(regularKind)).toBe(false);
});
it('should handle edge cases with many used kinds', () => {
// Test with many used kinds to ensure we still find valid ones
const usedKinds = new Set<number>();
// Fill most even numbers and multiples of 5 in a small range
for (let i = 1000; i <= 1100; i++) {
if (i % 2 === 0 || i % 5 === 0) {
usedKinds.add(i);
}
}
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should still find a valid kind
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
});
it('should generate random kinds with good distribution', () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Generate many kinds and check distribution
const results = new Map<number, number>();
const iterations = 100;
for (let i = 0; i < iterations; i++) {
const kind = KindGenerator.generateAvailableKind('regular', usedKinds);
results.set(kind, (results.get(kind) || 0) + 1);
// Verify constraints on each generated kind
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
expect(usedKinds.has(kind)).toBe(false);
}
// Check that we get good variety (at least 10 unique kinds in 100 iterations)
// Reduced expectations due to fewer iterations
expect(results.size).toBeGreaterThanOrEqual(10);
// Check that no single kind dominates (no kind should appear more than 30% of the time)
// Increased threshold due to fewer iterations
const maxFrequency = Math.max(...results.values());
const maxFrequencyPercent = (maxFrequency / iterations) * 100;
expect(maxFrequencyPercent).toBeLessThanOrEqual(30);
// Check that all generated kinds follow our constraints
for (const [kind] of results) {
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
// Check buffer constraint
for (const usedKind of usedKinds) {
const distance = Math.abs(kind - usedKind);
expect(distance > 2).toBe(true);
}
}
});
});
-178
View File
@@ -1,178 +0,0 @@
/**
* Utilities for generating unused Nostr event kind numbers
*/
export interface KindRangeInfo {
name: string;
min: number;
max: number;
description: string;
}
export type KindRange = 'regular' | 'replaceable' | 'ephemeral' | 'addressable';
/**
* Generator for unused Nostr event kind numbers
*/
export class KindGenerator {
/**
* Extract used kind numbers from the NIPs index
*/
static extractUsedKinds(nipsIndex: string): Set<number> {
const usedKinds = new Set<number>();
// Look for kind numbers in the Event Kinds table
// Format: | `1234` | description | NIP |
// Also handle ranges like `5000`-`5999`
const kindPatterns = [
// Single kind in backticks: `1234`
/\|\s*`(\d+)`\s*\|/g,
// Range in backticks: `5000`-`5999`
/\|\s*`(\d+)`-`(\d+)`\s*\|/g,
// Range in backticks with single digit end: `39000-9`
/\|\s*`(\d+)-(\d+)`\s*\|/g,
];
for (const pattern of kindPatterns) {
let match;
while ((match = pattern.exec(nipsIndex)) !== null) {
if (match[2] !== undefined && match[1] !== undefined) {
// Handle range format like `5000`-`5999` or `39000-9`
const start = parseInt(match[1], 10);
let end = parseInt(match[2], 10);
// Handle special case like `39000-9` which means 39000-39009
if (end < start && end < 10) {
const startStr = match[1];
const endStr = match[2];
if (startStr && endStr) {
// Replace the last digit(s) of start with end
const prefix = startStr.slice(0, -endStr.length);
end = parseInt(prefix + endStr, 10);
}
}
if (
!isNaN(start) && !isNaN(end) && start >= 0 && end >= 0 &&
start <= 65535 && end <= 65535 && start <= end
) {
// Add all numbers in the range
for (let i = start; i <= end; i++) {
usedKinds.add(i);
}
}
} else if (match[1] !== undefined) {
// Handle single kind format like `1234`
const num = parseInt(match[1], 10);
if (!isNaN(num) && num >= 0 && num <= 65535) {
usedKinds.add(num);
}
}
}
}
return usedKinds;
}
/**
* Generate an available kind number in the specified range
*/
static generateAvailableKind(
range: KindRange,
usedKinds: Set<number>,
): number {
const rangeInfo = this.getKindRangeInfo(range);
// Create a set of all numbers to avoid (used kinds + buffer)
const kindsToAvoid = new Set<number>();
// Add used kinds and their buffer zones
for (const usedKind of usedKinds) {
kindsToAvoid.add(usedKind);
// Add buffer of 2 kinds on each side
kindsToAvoid.add(usedKind - 2);
kindsToAvoid.add(usedKind - 1);
kindsToAvoid.add(usedKind + 1);
kindsToAvoid.add(usedKind + 2);
}
// Collect all available numbers in the range
const availableKinds: number[] = [];
for (let i = rangeInfo.min; i <= rangeInfo.max; i++) {
// Skip if in range to avoid
if (kindsToAvoid.has(i)) {
continue;
}
// Skip even numbers
if (i % 2 === 0) {
continue;
}
// Skip multiples of 5
if (i % 5 === 0) {
continue;
}
availableKinds.push(i);
}
// If no available numbers, fall back to first valid number in range
if (availableKinds.length === 0) {
for (let i = rangeInfo.min; i <= rangeInfo.max; i++) {
// Find first odd number that's not a multiple of 5
if (i % 2 !== 0 && i % 5 !== 0) {
return i;
}
}
// Ultimate fallback
return rangeInfo.min;
}
// Return a random available number
const randomIndex = Math.floor(Math.random() * availableKinds.length);
return availableKinds[randomIndex]!;
}
/**
* Get information about a kind range
*/
static getKindRangeInfo(range: KindRange): KindRangeInfo {
switch (range) {
case 'regular':
return {
name: 'Regular Events',
min: 1000,
max: 9999,
description:
'Regular events for application-specific use cases. These events are stored permanently.',
};
case 'replaceable':
return {
name: 'Replaceable Events',
min: 10000,
max: 19999,
description:
'Events that can be replaced by newer versions from the same author.',
};
case 'ephemeral':
return {
name: 'Ephemeral Events',
min: 20000,
max: 29999,
description: 'Events that are not stored permanently by relays.',
};
case 'addressable':
return {
name: 'Addressable Events',
min: 30000,
max: 39999,
description:
'Events that can be addressed and replaced using the "d" tag identifier.',
};
default:
throw new Error(`Unknown range: ${range}`);
}
}
}
-47
View File
@@ -1,47 +0,0 @@
import { describe, it, expect } from 'vitest';
import { NIPsClient } from './NIPsClient.ts';
describe('NIPsClient', () => {
const mockFetch: typeof fetch = async (input, init) => {
const { url } = new Request(input, init);
switch (url) {
case 'https://git.test/nostr-protocol/nips/refs/heads/master/01.md':
return new Response('NIP-01');
case 'https://git.test/nostr-protocol/nips/refs/heads/master/README.md':
return new Response('NIPs');
case 'https://git.test/nostr-protocol/nips/refs/heads/master/BREAKING.md':
return new Response('Breaking Changes');
default:
return new Response('Not Found', { status: 404 });
}
};
const client = new NIPsClient({
urlTemplate:
'https://git.test/nostr-protocol/nips/refs/heads/master/{nip}.md',
fetch: mockFetch,
});
it('should read NIP document', async () => {
const doc = await client.readNip('01');
expect(doc).toBe('NIP-01');
});
it('should read index document', async () => {
const doc = await client.readIndex();
expect(doc).toBe('NIPs');
});
it('should read breaking changes document', async () => {
const doc = await client.readBreaking();
expect(doc).toBe('Breaking Changes');
});
it('should throw HTTPError for 404 responses', async () => {
await expect(client.readNip('abc')).rejects.toMatchObject({
name: 'HTTPError',
message: 'HTTP Error: 404 GET https://git.test/nostr-protocol/nips/refs/heads/master/abc.md',
});
});
});
-52
View File
@@ -1,52 +0,0 @@
import { HTTPError } from './HTTPError';
/** Options for configuring the NIPsClient */
export interface NIPsClientOpts {
/** Template URL with {nip} placeholder that will be replaced with the NIP number */
urlTemplate: string;
/** Optional fetch function override */
fetch?: typeof fetch;
}
/** Client for fetching NIPs (Nostr Implementation Possibilities) documentation */
export class NIPsClient {
/** Template URL with {nip} placeholder */
readonly urlTemplate: string;
/** The fetch implementation to use for requests */
private fetch: typeof fetch;
constructor(opts: NIPsClientOpts) {
this.urlTemplate = opts.urlTemplate;
this.fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
}
/** Reads a documentation file by its slug */
async readDoc(slug: string): Promise<string> {
const url = this.urlTemplate.replace('{nip}', slug);
const request = new Request(url);
const response = await this.fetch(request);
if (!response.ok) {
throw new HTTPError(response, request);
}
return response.text();
}
/** Reads a specific NIP document by its identifier */
readNip(nip: string): Promise<string> {
return this.readDoc(nip);
}
/** Reads the main index (README) document */
readIndex(): Promise<string> {
return this.readDoc('README');
}
/** Reads the breaking changes document */
readBreaking(): Promise<string> {
return this.readDoc('BREAKING');
}
}
-46
View File
@@ -1,46 +0,0 @@
import { describe, it, expect } from 'vitest';
import { NostrbookClient } from './NostrbookClient.ts';
describe('NostrbookClient', () => {
const mockFetch: typeof fetch = async (input, init) => {
const { url } = new Request(input, init);
switch (url) {
case 'https://nostrbook.test/kinds/1.md':
return new Response('Kind: 1');
case 'https://nostrbook.test/tags/p.md':
return new Response('Tag: p');
case 'https://nostrbook.test/protocol/relay.md':
return new Response('Protocol: relay');
default:
return new Response('Not Found', { status: 404 });
}
};
const client = new NostrbookClient({
baseUrl: 'https://nostrbook.test',
fetch: mockFetch,
});
it('should read kind document', async () => {
const doc = await client.readKind(1);
expect(doc).toBe('Kind: 1');
});
it('should read tag document', async () => {
const doc = await client.readTag('p');
expect(doc).toBe('Tag: p');
});
it('should read protocol document', async () => {
const doc = await client.readProtocol('relay');
expect(doc).toBe('Protocol: relay');
});
it('should throw HTTPError for 404 responses', async () => {
await expect(client.readKind(999)).rejects.toMatchObject({
name: 'HTTPError',
message: 'HTTP Error: 404 GET https://nostrbook.test/kinds/999.md',
});
});
});
-53
View File
@@ -1,53 +0,0 @@
import { HTTPError } from './HTTPError';
import { llmstxtUrl } from './llmstxt';
/** Options for configuring the NostrbookClient */
export interface NostrbookClientOpts {
/** Base URL of the Nostrbook service */
baseUrl: URL | string;
/** Optional fetch function override */
fetch?: typeof fetch;
}
/** Client for interacting with Nostrbook documentation */
export class NostrbookClient {
/** Base URL of the Nostrbook service */
readonly baseUrl: URL;
/** The fetch implementation to use for requests */
private fetch: typeof fetch;
constructor(opts: NostrbookClientOpts) {
this.baseUrl = new URL(opts.baseUrl);
this.fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
}
/** Fetches content from a specific path on the Nostrbook service */
async get(path: string): Promise<string> {
const url = llmstxtUrl(new URL(path, this.baseUrl));
const request = new Request(url);
const response = await this.fetch(request);
if (!response.ok) {
throw new HTTPError(response, request);
}
return response.text();
}
/** Reads documentation for a specific Nostr event kind */
readKind(kind: number): Promise<string> {
return this.get(`/kinds/${kind}`);
}
/** Reads documentation for a specific Nostr tag */
readTag(tag: string): Promise<string> {
return this.get(`/tags/${tag}`);
}
/** Reads documentation for a specific Nostr protocol document */
readProtocol(doc: string): Promise<string> {
return this.get(`/protocol/${doc}`);
}
}
+36 -46
View File
@@ -3,7 +3,6 @@ import http from 'isomorphic-git/http/web';
import { Buffer } from 'buffer';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
(window as { Buffer?: typeof Buffer }).Buffer = Buffer;
@@ -36,45 +35,14 @@ export class ProjectsManager {
}
}
async createProject(name: string, customId?: string): Promise<Project> {
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId);
try {
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
} catch {
// Directory might already exist
}
return project;
}
async cloneProject(name: string, repoUrl: string, customId?: string): Promise<Project> {
const url = new URL(repoUrl);
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
if (customId && await this.projectExists(id)) {
throw new Error(`Project with ID "${id}" already exists`);
}
async createProject(name: string): Promise<Project> {
const id = await this.generateUniqueProjectId(name);
const projectPath = `${this.dir}/${id}`;
await this.fs.mkdir(projectPath);
// Clone the repository
await git.clone({
fs: this.fs,
http,
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth: 1,
// Use the CORS proxy only for GitHub and GitLab URLs
// More info: https://github.com/isomorphic-git/isomorphic-git#cors-support
corsProxy: url.hostname === 'github.com' || url.hostname === 'gitlab.com'
? 'https://cors.isomorphic-git.org'
: undefined,
});
// Clone the template first
await this.cloneTemplate(projectPath);
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
@@ -89,6 +57,17 @@ export class ProjectsManager {
};
}
async cloneTemplate(projectPath: string) {
await git.clone({
fs: this.fs,
http,
dir: projectPath,
url: GIT_TEMPLATE_URL,
singleBranch: true,
depth: 1,
});
}
async getProjects(): Promise<Project[]> {
try {
const projectDirs = await this.fs.readdir(this.dir);
@@ -208,20 +187,27 @@ export class ProjectsManager {
}
private async deleteDirectory(dirPath: string): Promise<void> {
const files = await this.fs.readdir(dirPath);
try {
const files = await this.fs.readdir(dirPath);
for (const file of files) {
const fullPath = `${dirPath}/${file}`;
const stat = await this.fs.lstat(fullPath);
for (const file of files) {
const fullPath = `${dirPath}/${file}`;
const stat = await this.fs.stat(fullPath);
if (stat.isDirectory()) {
await this.deleteDirectory(fullPath);
} else {
await this.fs.unlink(fullPath);
if (stat.isDirectory()) {
await this.deleteDirectory(fullPath);
} else {
await this.fs.unlink(fullPath);
}
}
await this.fs.rmdir(dirPath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
if (fsError.code !== 'ENOENT') {
throw error;
}
}
await this.fs.rmdir(dirPath);
}
private async generateUniqueProjectId(name: string): Promise<string> {
@@ -272,6 +258,10 @@ export class ProjectsManager {
return naddr !== null;
}
private formatProjectName(dirName: string): string {
// Return the original directory name without formatting
return dirName;
-583
View File
@@ -1,583 +0,0 @@
import OpenAI from 'openai';
import type { JSRuntimeFS } from './JSRuntime';
import { DotAI } from './DotAI';
import { parseProviderModel } from './parseProviderModel';
import type { Tool } from './tools/Tool';
import { join } from '@std/path';
// Simple debounce utility
const debounce = <T extends (...args: unknown[]) => void>(
func: T,
wait: number
): ((...args: Parameters<T>) => void) => {
let timeout: NodeJS.Timeout;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
};
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
export interface SessionConfig {
id: string;
projectId: string;
projectName: string;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
}
export interface SessionState {
id: string;
projectId: string;
projectName: string;
messages: AIMessage[];
streamingMessage?: {
role: 'assistant';
content: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
isLoading: boolean;
sessionName: string;
lastActivity: Date;
abortController?: AbortController;
}
export interface SessionManagerEvents {
sessionCreated: (sessionId: string) => void;
sessionUpdated: (sessionId: string, state: SessionState) => void;
sessionDeleted: (sessionId: string) => void;
messageAdded: (sessionId: string, message: AIMessage) => void;
streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (sessionId: string, isLoading: boolean) => void;
}
/**
* Global session manager that handles multiple AI chat sessions running concurrently.
* Sessions can run in the background without interruption when switching between projects.
*/
export class SessionManager {
private sessions = new Map<string, SessionState>();
private sessionConfigs = new Map<string, SessionConfig>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> };
// Performance constants
private readonly MAX_SESSIONS = 50;
private readonly MAX_SESSION_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days
private debouncedPersist = debounce(() => this.persistSessions(), 1000);
private dotAI: DotAI;
constructor(fs: JSRuntimeFS, aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }) {
this.fs = fs;
this.aiSettings = aiSettings;
this.dotAI = new DotAI(fs, '/');
// Load persisted sessions on initialization
this.loadPersistedSessions().catch(error => {
console.warn('Failed to load sessions during initialization:', error);
});
}
/**
* Create a new session for a project
*/
async createSession(config: SessionConfig): Promise<string> {
const sessionState: SessionState = {
id: config.id,
projectId: config.projectId,
projectName: config.projectName,
messages: [],
isLoading: false,
sessionName: DotAI.generateSessionName(),
lastActivity: new Date(),
};
// Try to load existing history
try {
const dotAI = new DotAI(this.fs, `/projects/${config.projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
sessionState.messages = lastSession.messages;
sessionState.sessionName = lastSession.sessionName;
}
} catch (error) {
console.warn('Failed to load session history:', error);
}
this.sessions.set(config.id, sessionState);
this.sessionConfigs.set(config.id, config);
this.persistSessions();
this.emit('sessionCreated', config.id);
this.emit('sessionUpdated', config.id, sessionState);
return config.id;
}
/**
* Get a session by ID
*/
getSession(sessionId: string): SessionState | undefined {
return this.sessions.get(sessionId);
}
/**
* Get all active sessions
*/
getAllSessions(): SessionState[] {
return Array.from(this.sessions.values());
}
/**
* Get sessions for a specific project
*/
getProjectSessions(projectId: string): SessionState[] {
return Array.from(this.sessions.values()).filter(
session => session.projectId === projectId
);
}
/**
* Delete a session
*/
async deleteSession(sessionId: string): Promise<void> {
const session = this.sessions.get(sessionId);
session?.abortController?.abort();
this.sessions.delete(sessionId);
this.sessionConfigs.delete(sessionId);
await this.persistSessions();
this.emit('sessionDeleted', sessionId);
}
/**
* Delete all sessions for a project
*/
async deleteProjectSessions(projectId: string): Promise<void> {
await Promise.all(
this.getProjectSessions(projectId).map(session => this.deleteSession(session.id))
);
}
/**
* Add a message to a session
*/
async addMessage(sessionId: string, message: AIMessage): Promise<void> {
const session = this.sessions.get(sessionId);
if (!session) return;
session.messages.push(message);
session.lastActivity = new Date();
await this.saveSessionHistory(sessionId);
this.debouncedPersist();
this.cleanupOldSessions();
this.emit('messageAdded', sessionId, message);
this.emit('sessionUpdated', sessionId, session);
}
/**
* Send a message and start AI generation
*/
async sendMessage(sessionId: string, content: string, providerModel: string): Promise<void> {
const session = this.sessions.get(sessionId);
const config = this.sessionConfigs.get(sessionId);
if (!session || !config || session.isLoading) return;
await this.addMessage(sessionId, { role: 'user', content });
await this.startGeneration(sessionId, providerModel);
}
/**
* Start AI generation for a session
*/
async startGeneration(sessionId: string, providerModel: string): Promise<void> {
const session = this.sessions.get(sessionId);
const config = this.sessionConfigs.get(sessionId);
if (!session || !config || session.isLoading || session.messages.length === 0) return;
// Check if last message is from user
const lastMessage = session.messages[session.messages.length - 1];
if (lastMessage.role !== 'user') return;
session.isLoading = true;
session.abortController = new AbortController();
session.lastActivity = new Date();
this.emit('loadingChanged', sessionId, true);
this.emit('sessionUpdated', sessionId, session);
try {
// Parse provider and model
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const connectionConfig = parsed.connection;
const modelName = parsed.model;
// Initialize OpenAI client
const openai = new OpenAI({
baseURL: connectionConfig.baseURL,
apiKey: connectionConfig.apiKey,
dangerouslyAllowBrowser: true
});
// Prepare messages for AI
const modelMessages: AIMessage[] = [...session.messages];
if (config.systemPrompt) {
modelMessages.unshift({
role: 'system',
content: config.systemPrompt
});
}
const conversationMessages = [...modelMessages];
let stepCount = 0;
const maxSteps = config.maxSteps || 50;
// Main AI generation loop
while (stepCount < maxSteps && session.isLoading) {
stepCount++;
// Initialize streaming message
session.streamingMessage = {
role: 'assistant',
content: '',
tool_calls: undefined
};
this.emit('sessionUpdated', sessionId, session);
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
model: modelName,
messages: conversationMessages,
tools: config.tools && Object.keys(config.tools).length > 0 ? Object.values(config.tools) : undefined,
tool_choice: config.tools && Object.keys(config.tools).length > 0 ? 'auto' : undefined,
stream: true
};
// Generate streaming response
const stream = await openai.chat.completions.create(completionOptions, {
signal: session.abortController?.signal
});
let accumulatedContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
let finishReason: string | null = null;
// Process the stream
for await (const chunk of stream) {
// Check if session was cancelled
if (!session.isLoading) break;
const delta = chunk.choices[0]?.delta;
if (delta?.content) {
accumulatedContent += delta.content;
if (session.streamingMessage) {
session.streamingMessage.content += delta.content;
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
this.emit('sessionUpdated', sessionId, session);
}
}
if (delta?.tool_calls) {
for (const toolCallDelta of delta.tool_calls) {
const index = toolCallDelta.index;
if (index === undefined) continue;
accumulatedToolCalls[index] ??= {
id: '',
type: 'function',
function: { name: '', arguments: '' }
};
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
}
if (session.streamingMessage) {
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
this.emit('sessionUpdated', sessionId, session);
}
}
if (chunk.choices[0]?.finish_reason) {
finishReason = chunk.choices[0].finish_reason;
}
}
// Create final assistant message
const assistantMessage: AIMessage = {
role: 'assistant',
content: accumulatedContent,
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
};
// Clear streaming message and add final message
session.streamingMessage = undefined;
await this.addMessage(sessionId, assistantMessage);
conversationMessages.push(assistantMessage);
// Check if we should stop
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
break;
}
// Handle tool calls
if (accumulatedToolCalls?.length) {
for (const toolCall of accumulatedToolCalls) {
if (toolCall.type !== 'function') continue;
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
const toolName = functionToolCall.function.name;
const tool = config.customTools[toolName];
if (!tool) {
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Tool ${toolName} not found`);
continue;
}
try {
const toolArgs = tool.inputSchema.parse(JSON.parse(functionToolCall.function.arguments));
const content = await tool.execute(toolArgs);
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, content);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`);
}
}
}
}
} catch (error) {
console.error('AI generation error:', error);
// Handle different error types
if (error?.name === 'AbortError') return; // User cancelled
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
const errorMsg = error?.message || '';
if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
} else if (errorMsg.includes('API key')) {
errorMessage = 'Authentication error: Please check your API key in AI settings.';
} else if (errorMsg.includes('rate limit')) {
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
} else if (errorMsg) {
errorMessage = `AI service error: ${errorMsg}`;
}
await this.addMessage(sessionId, { role: 'assistant', content: errorMessage });
} finally {
session.isLoading = false;
session.streamingMessage = undefined;
session.abortController = undefined;
this.emit('loadingChanged', sessionId, false);
this.emit('sessionUpdated', sessionId, session);
}
}
/**
* Stop AI generation for a session
*/
stopGeneration(sessionId: string): void {
const session = this.sessions.get(sessionId);
if (!session) return;
session.abortController?.abort();
session.isLoading = false;
session.streamingMessage = undefined;
session.abortController = undefined;
this.emit('loadingChanged', sessionId, false);
this.emit('sessionUpdated', sessionId, session);
}
/**
* Clean up old sessions to prevent memory bloat
*/
private cleanupOldSessions(): void {
const now = Date.now();
// Delete old sessions
for (const [id, session] of this.sessions) {
if (now - session.lastActivity.getTime() > this.MAX_SESSION_AGE) {
this.deleteSession(id);
}
}
// Delete oldest sessions if we have too many
if (this.sessions.size > this.MAX_SESSIONS) {
Array.from(this.sessions.entries())
.sort(([, a], [, b]) => a.lastActivity.getTime() - b.lastActivity.getTime())
.slice(0, this.sessions.size - this.MAX_SESSIONS)
.forEach(([id]) => this.deleteSession(id));
}
}
/**
* Start a new session (clear messages but keep configuration)
*/
async startNewSession(sessionId: string): Promise<void> {
const session = this.sessions.get(sessionId);
if (!session) return;
this.stopGeneration(sessionId);
session.messages = [];
session.streamingMessage = undefined;
session.sessionName = DotAI.generateSessionName();
session.lastActivity = new Date();
this.debouncedPersist();
this.emit('sessionUpdated', sessionId, session);
}
/**
* Helper to add tool messages and update conversation
*/
private async addToolMessage(sessionId: string, conversationMessages: AIMessage[], toolCallId: string, content: string): Promise<void> {
const toolMessage: AIMessage = {
role: 'tool',
content,
tool_call_id: toolCallId
};
await this.addMessage(sessionId, toolMessage);
conversationMessages.push(toolMessage);
}
/**
* Save session history to file
*/
private async saveSessionHistory(sessionId: string): Promise<void> {
const session = this.sessions.get(sessionId);
if (!session) return;
try {
const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`);
await dotAI.setHistory(session.sessionName, session.messages);
} catch (error) {
console.warn('Failed to save session history:', error);
}
}
/**
* Simplified event system
*/
on<K extends keyof SessionManagerEvents>(event: K, listener: SessionManagerEvents[K]): void {
if (!this.listeners[event]) this.listeners[event] = new Set();
this.listeners[event]!.add(listener as (...args: unknown[]) => void);
}
off<K extends keyof SessionManagerEvents>(event: K, listener: SessionManagerEvents[K]): void {
this.listeners[event]?.delete(listener as (...args: unknown[]) => void);
}
emit<K extends keyof SessionManagerEvents>(event: K, ...args: Parameters<SessionManagerEvents[K]>): void {
this.listeners[event]?.forEach(listener => {
try {
listener(...args);
} catch (error) {
console.error('Event listener error:', error);
}
});
}
/**
* Save session states using DotAI for persistence
*/
private async persistSessions(): Promise<void> {
try {
if (!this.dotAI.fs?.writeFile) return;
const sessionData = {
sessions: Array.from(this.sessions.entries()).map(([id, session]) => ({
id,
session: {
...session,
isLoading: false,
streamingMessage: undefined,
abortController: undefined
}
})),
configs: Array.from(this.sessionConfigs.entries()),
timestamp: new Date().toISOString()
};
// Ensure .ai directory exists before writing
const aiDir = join(this.dotAI.workingDir, '.ai');
try {
await this.dotAI.fs.mkdir(aiDir, { recursive: true });
} catch {
// Directory might already exist, continue
}
await this.dotAI.fs.writeFile(
join(aiDir, 'sessions.json'),
JSON.stringify(sessionData)
);
} catch (error) {
console.warn('Failed to persist sessions:', error);
}
}
/**
* Load persisted sessions using DotAI
*/
private async loadPersistedSessions(): Promise<void> {
try {
if (!this.dotAI.fs?.readFile) return;
const sessionsPath = join(this.dotAI.workingDir, '.ai', 'sessions.json');
try {
const sessionsJson = await this.dotAI.fs.readFile(sessionsPath, 'utf8');
const sessionData = JSON.parse(sessionsJson);
// Restore sessions
sessionData.sessions?.forEach(({ id, session }: { id: string; session: Omit<SessionState, 'lastActivity'> & { lastActivity: string } }) => {
this.sessions.set(id, {
...session,
lastActivity: new Date(session.lastActivity)
});
});
// Restore configs
sessionData.configs?.forEach(([id, config]: [string, SessionConfig]) => {
this.sessionConfigs.set(id, config);
});
} catch {
// File doesn't exist or is invalid - start fresh
}
} catch (error) {
console.warn('Failed to load sessions:', error);
}
}
/**
* Cleanup - stop all sessions and clear data
*/
async cleanup(): Promise<void> {
await this.persistSessions();
this.sessions.forEach((_, sessionId) => this.stopGeneration(sessionId));
this.sessions.clear();
this.sessionConfigs.clear();
this.listeners = {};
}
}
-21
View File
@@ -1,21 +0,0 @@
import OpenAI from "openai";
export function assistantContentEmpty(
content: OpenAI.ChatCompletionAssistantMessageParam['content'],
): boolean {
if (!content) return true;
const text: string[] = [];
if (typeof content === 'string') {
text.push(content);
} else if (Array.isArray(content)) {
for (const part of content) {
if (part.type === 'text') {
text.push(part.text);
}
}
}
const result = text.join('\n\n');
return !result.trim();
}
+2 -34
View File
@@ -37,7 +37,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
setup(build) {
// http(s) imports
build.onResolve({ filter: /^https?:\/\// }, (args) => {
build.onResolve({ filter: /^https?:\/\// }, async (args) => {
return {
path: args.path,
namespace: "esm",
@@ -50,23 +50,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
// Handle transitive dependency versions
const keys: string[] = [];
try {
const importerPackage = extractPackageName(args.importer);
keys.push(
`node_modules/${importerPackage}/node_modules/${packageName}`,
);
} catch {
// fallthrough
}
keys.push(`node_modules/${packageName}`);
const packageInfo = keys
.map((key) => packageLock.packages[key])
.find((info) => info);
const packageInfo = packageLock.packages["node_modules/" + packageName];
const packagePath = args.path.slice(packageName.length);
const version = packageInfo?.version;
@@ -151,19 +135,3 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
},
};
}
/** Extract package name from esm.sh-style URL */
function extractPackageName(esmShURL: string): string {
const full = new URL(esmShURL)
.pathname
.slice(1)
.replace(/^\*/, "");
const base = full.startsWith("@")
? full.split("/").slice(0, 2).join("/")
: full.split("/")[0];
return full.startsWith("@")
? base.split("@").splice(0, 2).join("@")
: base.split("@")[0];
}
+19 -29
View File
@@ -57,45 +57,35 @@ async function tryFileVariants(
basePath: string,
): Promise<string> {
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css"];
const stat = await statSafe(fs, basePath);
// If it's a file, check if it exists
if (stat.isFile()) {
try {
await fs.stat(basePath);
return basePath;
}
// If it's a directory, try index files
if (stat.isDirectory()) {
for (const ext of extensions) {
const indexFile = path.join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile);
if (indexStat.isFile()) {
return indexFile;
}
}
throw new Error("Directory without index file");
} catch {
// Ignore
}
// Try direct file with extensions
for (const ext of extensions) {
const full = basePath + ext;
const fullStat = await statSafe(fs, full);
if (fullStat.isFile()) {
try {
await fs.stat(full);
return full;
} catch {
// Ignore
}
}
// Try directory index files
for (const ext of extensions) {
const indexFile = path.join(basePath, "index" + ext);
try {
await fs.stat(indexFile);
return indexFile;
} catch {
// Ignore
}
}
// If no file found, throw an error
throw new Error("File not found");
}
async function statSafe(fs: JSRuntimeFS, filePath: string): Promise<{ isFile(): boolean; isDirectory(): boolean }> {
try {
return await fs.stat(filePath);
} catch {
return {
isFile: () => false,
isDirectory: () => false,
};
}
}
-3
View File
@@ -50,9 +50,6 @@ export async function buildProject(
fsPlugin(fs, `${projectPath}/src`),
esmPlugin(JSON.parse(packageLockText), target),
],
define: {
"import.meta.env": JSON.stringify({}),
},
});
const dist: Record<string, Uint8Array> = {};
-402
View File
@@ -1,402 +0,0 @@
# NIPs
NIPs stand for **Nostr Implementation Possibilities**.
They exist to document what may be implemented by [Nostr](https://github.com/nostr-protocol/nostr)-compatible _relay_ and _client_ software.
---
- [List](#list)
- [Event Kinds](#event-kinds)
- [Message Types](#message-types)
- [Client to Relay](#client-to-relay)
- [Relay to Client](#relay-to-client)
- [Standardized Tags](#standardized-tags)
- [Criteria for acceptance of NIPs](#criteria-for-acceptance-of-nips)
- [Is this repository a centralizing factor?](#is-this-repository-a-centralizing-factor)
- [How this repository works](#how-this-repository-works)
- [Breaking Changes](#breaking-changes)
- [License](#license)
---
## List
- [NIP-01: Basic protocol flow description](01.md)
- [NIP-02: Follow List](02.md)
- [NIP-03: OpenTimestamps Attestations for Events](03.md)
- [NIP-04: Encrypted Direct Message](04.md) --- **unrecommended**: deprecated in favor of [NIP-17](17.md)
- [NIP-05: Mapping Nostr keys to DNS-based internet identifiers](05.md)
- [NIP-06: Basic key derivation from mnemonic seed phrase](06.md)
- [NIP-07: `window.nostr` capability for web browsers](07.md)
- [NIP-08: Handling Mentions](08.md) --- **unrecommended**: deprecated in favor of [NIP-27](27.md)
- [NIP-09: Event Deletion Request](09.md)
- [NIP-10: Text Notes and Threads](10.md)
- [NIP-11: Relay Information Document](11.md)
- [NIP-13: Proof of Work](13.md)
- [NIP-14: Subject tag in text events](14.md)
- [NIP-15: Nostr Marketplace (for resilient marketplaces)](15.md)
- [NIP-17: Private Direct Messages](17.md)
- [NIP-18: Reposts](18.md)
- [NIP-19: bech32-encoded entities](19.md)
- [NIP-21: `nostr:` URI scheme](21.md)
- [NIP-22: Comment](22.md)
- [NIP-23: Long-form Content](23.md)
- [NIP-24: Extra metadata fields and tags](24.md)
- [NIP-25: Reactions](25.md)
- [NIP-26: Delegated Event Signing](26.md) --- **unrecommended**: adds unecessary burden for little gain
- [NIP-27: Text Note References](27.md)
- [NIP-28: Public Chat](28.md)
- [NIP-29: Relay-based Groups](29.md)
- [NIP-30: Custom Emoji](30.md)
- [NIP-31: Dealing with Unknown Events](31.md)
- [NIP-32: Labeling](32.md)
- [NIP-34: `git` stuff](34.md)
- [NIP-35: Torrents](35.md)
- [NIP-36: Sensitive Content](36.md)
- [NIP-37: Draft Events](37.md)
- [NIP-38: User Statuses](38.md)
- [NIP-39: External Identities in Profiles](39.md)
- [NIP-40: Expiration Timestamp](40.md)
- [NIP-42: Authentication of clients to relays](42.md)
- [NIP-44: Encrypted Payloads (Versioned)](44.md)
- [NIP-45: Counting results](45.md)
- [NIP-46: Nostr Remote Signing](46.md)
- [NIP-47: Nostr Wallet Connect](47.md)
- [NIP-48: Proxy Tags](48.md)
- [NIP-49: Private Key Encryption](49.md)
- [NIP-50: Search Capability](50.md)
- [NIP-51: Lists](51.md)
- [NIP-52: Calendar Events](52.md)
- [NIP-53: Live Activities](53.md)
- [NIP-54: Wiki](54.md)
- [NIP-55: Android Signer Application](55.md)
- [NIP-56: Reporting](56.md)
- [NIP-57: Lightning Zaps](57.md)
- [NIP-58: Badges](58.md)
- [NIP-59: Gift Wrap](59.md)
- [NIP-60: Cashu Wallet](60.md)
- [NIP-61: Nutzaps](61.md)
- [NIP-62: Request to Vanish](62.md)
- [NIP-64: Chess (PGN)](64.md)
- [NIP-65: Relay List Metadata](65.md)
- [NIP-66: Relay Discovery and Liveness Monitoring](66.md)
- [NIP-68: Picture-first feeds](68.md)
- [NIP-69: Peer-to-peer Order events](69.md)
- [NIP-70: Protected Events](70.md)
- [NIP-71: Video Events](71.md)
- [NIP-72: Moderated Communities](72.md)
- [NIP-73: External Content IDs](73.md)
- [NIP-75: Zap Goals](75.md)
- [NIP-77: Negentropy Syncing](77.md)
- [NIP-78: Application-specific data](78.md)
- [NIP-7D: Threads](7D.md)
- [NIP-84: Highlights](84.md)
- [NIP-86: Relay Management API](86.md)
- [NIP-88: Polls](88.md)
- [NIP-89: Recommended Application Handlers](89.md)
- [NIP-90: Data Vending Machines](90.md)
- [NIP-92: Media Attachments](92.md)
- [NIP-94: File Metadata](94.md)
- [NIP-96: HTTP File Storage Integration](96.md)
- [NIP-98: HTTP Auth](98.md)
- [NIP-99: Classified Listings](99.md)
- [NIP-B0: Web Bookmarks](B0.md)
- [NIP-B7: Blossom](B7.md)
- [NIP-C0: Code Snippets](C0.md)
- [NIP-C7: Chats](C7.md)
## Event Kinds
| kind | description | NIP |
| ------------- | ------------------------------- | -------------------------------------- |
| `0` | User Metadata | [01](01.md) |
| `1` | Short Text Note | [10](10.md) |
| `2` | Recommend Relay | 01 (deprecated) |
| `3` | Follows | [02](02.md) |
| `4` | Encrypted Direct Messages | [04](04.md) |
| `5` | Event Deletion Request | [09](09.md) |
| `6` | Repost | [18](18.md) |
| `7` | Reaction | [25](25.md) |
| `8` | Badge Award | [58](58.md) |
| `9` | Chat Message | [C7](C7.md) |
| `10` | Group Chat Threaded Reply | 29 (deprecated) |
| `11` | Thread | [7D](7D.md) |
| `12` | Group Thread Reply | 29 (deprecated) |
| `13` | Seal | [59](59.md) |
| `14` | Direct Message | [17](17.md) |
| `15` | File Message | [17](17.md) |
| `16` | Generic Repost | [18](18.md) |
| `17` | Reaction to a website | [25](25.md) |
| `20` | Picture | [68](68.md) |
| `21` | Video Event | [71](71.md) |
| `22` | Short-form Portrait Video Event | [71](71.md) |
| `30` | internal reference | [NKBIP-03] |
| `31` | external web reference | [NKBIP-03] |
| `32` | hardcopy reference | [NKBIP-03] |
| `33` | prompt reference | [NKBIP-03] |
| `40` | Channel Creation | [28](28.md) |
| `41` | Channel Metadata | [28](28.md) |
| `42` | Channel Message | [28](28.md) |
| `43` | Channel Hide Message | [28](28.md) |
| `44` | Channel Mute User | [28](28.md) |
| `62` | Request to Vanish | [62](62.md) |
| `64` | Chess (PGN) | [64](64.md) |
| `818` | Merge Requests | [54](54.md) |
| `1018` | Poll Response | [88](88.md) |
| `1021` | Bid | [15](15.md) |
| `1022` | Bid confirmation | [15](15.md) |
| `1040` | OpenTimestamps | [03](03.md) |
| `1059` | Gift Wrap | [59](59.md) |
| `1063` | File Metadata | [94](94.md) |
| `1068` | Poll | [88](88.md) |
| `1111` | Comment | [22](22.md) |
| `1311` | Live Chat Message | [53](53.md) |
| `1337` | Code Snippet | [C0](C0.md) |
| `1617` | Patches | [34](34.md) |
| `1621` | Issues | [34](34.md) |
| `1622` | Git Replies (deprecated) | [34](34.md) |
| `1630`-`1633` | Status | [34](34.md) |
| `1971` | Problem Tracker | [nostrocket][nostrocket] |
| `1984` | Reporting | [56](56.md) |
| `1985` | Label | [32](32.md) |
| `1986` | Relay reviews | |
| `1987` | AI Embeddings / Vector lists | [NKBIP-02] |
| `2003` | Torrent | [35](35.md) |
| `2004` | Torrent Comment | [35](35.md) |
| `2022` | Coinjoin Pool | [joinstr][joinstr] |
| `4550` | Community Post Approval | [72](72.md) |
| `5000`-`5999` | Job Request | [90](90.md) |
| `6000`-`6999` | Job Result | [90](90.md) |
| `7000` | Job Feedback | [90](90.md) |
| `7374` | Reserved Cashu Wallet Tokens | [60](60.md) |
| `7375` | Cashu Wallet Tokens | [60](60.md) |
| `7376` | Cashu Wallet History | [60](60.md) |
| `9000`-`9030` | Group Control Events | [29](29.md) |
| `9041` | Zap Goal | [75](75.md) |
| `9321` | Nutzap | [61](61.md) |
| `9467` | Tidal login | [Tidal-nostr] |
| `9734` | Zap Request | [57](57.md) |
| `9735` | Zap | [57](57.md) |
| `9802` | Highlights | [84](84.md) |
| `10000` | Mute list | [51](51.md) |
| `10001` | Pin list | [51](51.md) |
| `10002` | Relay List Metadata | [65](65.md), [51](51.md) |
| `10003` | Bookmark list | [51](51.md) |
| `10004` | Communities list | [51](51.md) |
| `10005` | Public chats list | [51](51.md) |
| `10006` | Blocked relays list | [51](51.md) |
| `10007` | Search relays list | [51](51.md) |
| `10009` | User groups | [51](51.md), [29](29.md) |
| `10012` | Favorite relays list | [51](51.md) |
| `10013` | Private event relay list | [37](37.md) |
| `10015` | Interests list | [51](51.md) |
| `10019` | Nutzap Mint Recommendation | [61](61.md) |
| `10020` | Media follows | [51](51.md) |
| `10030` | User emoji list | [51](51.md) |
| `10050` | Relay list to receive DMs | [51](51.md), [17](17.md) |
| `10063` | User server list | [Blossom][blossom] |
| `10096` | File storage server list | [96](96.md) |
| `10166` | Relay Monitor Announcement | [66](66.md) |
| `13194` | Wallet Info | [47](47.md) |
| `17375` | Cashu Wallet Event | [60](60.md) |
| `21000` | Lightning Pub RPC | [Lightning.Pub][lnpub] |
| `22242` | Client Authentication | [42](42.md) |
| `23194` | Wallet Request | [47](47.md) |
| `23195` | Wallet Response | [47](47.md) |
| `24133` | Nostr Connect | [46](46.md) |
| `24242` | Blobs stored on mediaservers | [Blossom][blossom] |
| `27235` | HTTP Auth | [98](98.md) |
| `30000` | Follow sets | [51](51.md) |
| `30001` | Generic lists | 51 (deprecated) |
| `30002` | Relay sets | [51](51.md) |
| `30003` | Bookmark sets | [51](51.md) |
| `30004` | Curation sets | [51](51.md) |
| `30005` | Video sets | [51](51.md) |
| `30007` | Kind mute sets | [51](51.md) |
| `30008` | Profile Badges | [58](58.md) |
| `30009` | Badge Definition | [58](58.md) |
| `30015` | Interest sets | [51](51.md) |
| `30017` | Create or update a stall | [15](15.md) |
| `30018` | Create or update a product | [15](15.md) |
| `30019` | Marketplace UI/UX | [15](15.md) |
| `30020` | Product sold as an auction | [15](15.md) |
| `30023` | Long-form Content | [23](23.md) |
| `30024` | Draft Long-form Content | [23](23.md) |
| `30030` | Emoji sets | [51](51.md) |
| `30040` | Curated Publication Index | [NKBIP-01] |
| `30041` | Curated Publication Content | [NKBIP-01] |
| `30063` | Release artifact sets | [51](51.md) |
| `30078` | Application-specific Data | [78](78.md) |
| `30166` | Relay Discovery | [66](66.md) |
| `30267` | App curation sets | [51](51.md) |
| `30311` | Live Event | [53](53.md) |
| `30315` | User Statuses | [38](38.md) |
| `30388` | Slide Set | [Corny Chat][cornychat-slideset] |
| `30402` | Classified Listing | [99](99.md) |
| `30403` | Draft Classified Listing | [99](99.md) |
| `30617` | Repository announcements | [34](34.md) |
| `30618` | Repository state announcements | [34](34.md) |
| `30818` | Wiki article | [54](54.md) |
| `30819` | Redirects | [54](54.md) |
| `31234` | Draft Event | [37](37.md) |
| `31388` | Link Set | [Corny Chat][cornychat-linkset] |
| `31890` | Feed | [NUD: Custom Feeds][NUD: Custom Feeds] |
| `31922` | Date-Based Calendar Event | [52](52.md) |
| `31923` | Time-Based Calendar Event | [52](52.md) |
| `31924` | Calendar | [52](52.md) |
| `31925` | Calendar Event RSVP | [52](52.md) |
| `31989` | Handler recommendation | [89](89.md) |
| `31990` | Handler information | [89](89.md) | |
| `32267` | Software Application | | |
| `34550` | Community Definition | [72](72.md) |
| `38383` | Peer-to-peer Order events | [69](69.md) |
| `39000-9` | Group metadata events | [29](29.md) |
| `39089` | Starter packs | [51](51.md) |
| `39092` | Media starter packs | [51](51.md) |
| `39701` | Web bookmarks | [B0](B0.md) |
[NUD: Custom Feeds]: https://wikifreedia.xyz/cip-01/
[nostrocket]: https://github.com/nostrocket/NIPS/blob/main/Problems.md
[lnpub]: https://github.com/shocknet/Lightning.Pub/blob/master/proto/autogenerated/client.md
[cornychat-slideset]: https://cornychat.com/datatypes#kind30388slideset
[cornychat-linkset]: https://cornychat.com/datatypes#kind31388linkset
[joinstr]: https://gitlab.com/1440000bytes/joinstr/-/blob/main/NIP.md
[NKBIP-01]: https://wikistr.com/nkbip-01*fd208ee8c8f283780a9552896e4823cc9dc6bfd442063889577106940fd927c1
[NKBIP-02]: https://wikistr.com/nkbip-02*fd208ee8c8f283780a9552896e4823cc9dc6bfd442063889577106940fd927c1
[NKBIP-03]: https://wikistr.com/nkbip-03*fd208ee8c8f283780a9552896e4823cc9dc6bfd442063889577106940fd927c1
[blossom]: https://github.com/hzrd149/blossom
[Tidal-nostr]: https://wikistr.com/tidal-nostr
## Message types
### Client to Relay
| type | description | NIP |
| ------- | --------------------------------------------------- | ----------- |
| `EVENT` | used to publish events | [01](01.md) |
| `REQ` | used to request events and subscribe to new updates | [01](01.md) |
| `CLOSE` | used to stop previous subscriptions | [01](01.md) |
| `AUTH` | used to send authentication events | [42](42.md) |
| `COUNT` | used to request event counts | [45](45.md) |
### Relay to Client
| type | description | NIP |
| -------- | ------------------------------------------------------- | ----------- |
| `EOSE` | used to notify clients all stored events have been sent | [01](01.md) |
| `EVENT` | used to send events requested to clients | [01](01.md) |
| `NOTICE` | used to send human-readable messages to clients | [01](01.md) |
| `OK` | used to notify clients if an EVENT was successful | [01](01.md) |
| `CLOSED` | used to notify clients that a REQ was ended and why | [01](01.md) |
| `AUTH` | used to send authentication challenges | [42](42.md) |
| `COUNT` | used to send requested event counts to clients | [45](45.md) |
## Standardized Tags
| name | value | other parameters | NIP |
| ----------------- | ------------------------------------ | ------------------------------- | -------------------------------------------------- |
| `a` | coordinates to an event | relay URL | [01](01.md) |
| `A` | root address | relay URL | [22](22.md) |
| `d` | identifier | -- | [01](01.md) |
| `e` | event id (hex) | relay URL, marker, pubkey (hex) | [01](01.md), [10](10.md) |
| `E` | root event id | relay URL | [22](22.md) |
| `f` | currency code | -- | [69](69.md) |
| `g` | geohash | -- | [52](52.md) |
| `h` | group id | -- | [29](29.md) |
| `i` | external identity | proof, url hint | [35](35.md), [39](39.md), [73](73.md) |
| `I` | root external identity | -- | [22](22.md) |
| `k` | kind | -- | [18](18.md), [25](25.md), [72](72.md), [73](73.md) |
| `K` | root scope | -- | [22](22.md) |
| `l` | label, label namespace, language name| -- | [32](32.md), [C0](C0.md) |
| `L` | label namespace | -- | [32](32.md) |
| `m` | MIME type | -- | [94](94.md) |
| `p` | pubkey (hex) | relay URL, petname | [01](01.md), [02](02.md), [22](22.md) |
| `P` | pubkey (hex) | -- | [22](22.md), [57](57.md) |
| `q` | event id (hex) | relay URL, pubkey (hex) | [18](18.md) |
| `r` | a reference (URL, etc) | -- | [24](24.md), [25](25.md) |
| `r` | relay url | marker | [65](65.md) |
| `s` | status | -- | [69](69.md) |
| `t` | hashtag | -- | [24](24.md), [34](34.md), [35](35.md) |
| `u` | url | -- | [61](61.md), [98](98.md) |
| `x` | hash | -- | [35](35.md), [56](56.md) |
| `y` | platform | -- | [69](69.md) |
| `z` | order number | -- | [69](69.md) |
| `-` | -- | -- | [70](70.md) |
| `alt` | summary | -- | [31](31.md) |
| `amount` | millisatoshis, stringified | -- | [57](57.md) |
| `bolt11` | `bolt11` invoice | -- | [57](57.md) |
| `challenge` | challenge string | -- | [42](42.md) |
| `client` | name, address | relay URL | [89](89.md) |
| `clone` | git clone URL | -- | [34](34.md) |
| `content-warning` | reason | -- | [36](36.md) |
| `delegation` | pubkey, conditions, delegation token | -- | [26](26.md) |
| `dep` | Required dependency | -- | [C0](C0.md) |
| `description` | description | -- | [34](34.md), [57](57.md), [58](58.md), [C0](C0.md) |
| `emoji` | shortcode, image URL | -- | [30](30.md) |
| `encrypted` | -- | -- | [90](90.md) |
| `extension` | File extension | -- | [C0](C0.md) |
| `expiration` | unix timestamp (string) | -- | [40](40.md) |
| `file` | full path (string) | -- | [35](35.md) |
| `goal` | event id (hex) | relay URL | [75](75.md) |
| `image` | image URL | dimensions in pixels | [23](23.md), [52](52.md), [58](58.md) |
| `imeta` | inline metadata | -- | [92](92.md) |
| `license` | License of the shared content | -- | [C0](C0.md) |
| `lnurl` | `bech32` encoded `lnurl` | -- | [57](57.md) |
| `location` | location string | -- | [52](52.md), [99](99.md) |
| `name` | name | -- | [34](34.md), [58](58.md), [72](72.md), [C0](C0.md) |
| `nonce` | random | difficulty | [13](13.md) |
| `preimage` | hash of `bolt11` invoice | -- | [57](57.md) |
| `price` | price | currency, frequency | [99](99.md) |
| `proxy` | external ID | protocol | [48](48.md) |
| `published_at` | unix timestamp (string) | -- | [23](23.md), [B0](B0.md) |
| `relay` | relay url | -- | [42](42.md), [17](17.md) |
| `relays` | relay list | -- | [57](57.md) |
| `repo` | Reference to the origin repository | -- | [C0](C0.md) |
| `runtime` | Runtime or environment specification | -- | [C0](C0.md) |
| `server` | file storage server url | -- | [96](96.md) |
| `subject` | subject | -- | [14](14.md), [17](17.md), [34](34.md) |
| `summary` | summary | -- | [23](23.md), [52](52.md) |
| `thumb` | badge thumbnail | dimensions in pixels | [58](58.md) |
| `title` | title | -- | [23](23.md), [B0](B0.md) |
| `tracker` | torrent tracker URL | -- | [35](35.md) |
| `web` | webpage URL | -- | [34](34.md) |
| `zap` | pubkey (hex), relay URL | weight | [57](57.md) |
Please update these lists when proposing new NIPs.
## Criteria for acceptance of NIPs
1. They should be fully implemented in at least two clients and one relay -- when applicable.
2. They should make sense.
3. They should be optional and backwards-compatible: care must be taken such that clients and relays that choose to not implement them do not stop working when interacting with the ones that choose to.
4. There should be no more than one way of doing the same thing.
5. Other rules will be made up when necessary.
## Is this repository a centralizing factor?
To promote interoperability, we need standards that everybody can follow, and we need them to define a **single way of doing each thing** without ever hurting **backwards-compatibility**, and for that purpose there is no way around getting everybody to agree on the same thing and keep a centralized index of these standards. However the fact that such an index exists doesn't hurt the decentralization of Nostr. _At any point the central index can be challenged if it is failing to fulfill the needs of the protocol_ and it can migrate to other places and be maintained by other people.
It can even fork into multiple versions, and then some clients would go one way, others would go another way, and some clients would adhere to both competing standards. This would hurt the simplicity, openness and interoperability of Nostr a little, but everything would still work in the short term.
There is a list of notable Nostr software developers who have commit access to this repository, but that exists mostly for practical reasons, as by the nature of the thing we're dealing with the repository owner can revoke membership and rewrite history as they want -- and if these actions are unjustified or perceived as bad or evil the community must react.
## How this repository works
Standards may emerge in two ways: the first way is that someone starts doing something, then others copy it; the second way is that someone has an idea of a new standard that could benefit multiple clients and the protocol in general without breaking **backwards-compatibility** and the principle of having **a single way of doing things**, then they write that idea and submit it to this repository, other interested parties read it and give their feedback, then once most people reasonably agree we codify that in a NIP which client and relay developers that are interested in the feature can proceed to implement.
These two ways of standardizing things are supported by this repository. Although the second is preferred, an effort will be made to codify standards emerged outside this repository into NIPs that can be later referenced and easily understood and implemented by others -- but obviously as in any human system discretion may be applied when standards are considered harmful.
## Breaking Changes
[Breaking Changes](BREAKING.md)
## License
All NIPs are public domain.
## Contributors
<a align="center" href="https://github.com/nostr-protocol/nips/graphs/contributors">
<img src="https://contrib.rocks/image?repo=nostr-protocol/nips" />
</a>
-35
View File
@@ -1,35 +0,0 @@
import { describe, it, expect } from 'vitest';
import { llmstxtUrl } from './llmstxt.ts';
describe('llmstxtUrl', () => {
it('should convert URLs to llmstxt format correctly', () => {
const testCases = [
{
input: 'https://example.com',
expected: 'https://example.com/index.md',
},
{
input: 'https://example.com/',
expected: 'https://example.com/index.md',
},
{
input: 'https://example.com/test',
expected: 'https://example.com/test.md',
},
{
input: 'https://example.com/test/',
expected: 'https://example.com/test/index.md',
},
{
input: 'https://example.com/test.md',
expected: 'https://example.com/test.md',
},
];
for (const { input, expected } of testCases) {
const result = llmstxtUrl(input);
expect(result.toString()).toBe(expected);
}
});
});
-19
View File
@@ -1,19 +0,0 @@
/**
* Adds a markdown extension to the URL according to the
* [llms.txt](https://llmstxt.org/) specification.
*/
export function llmstxtUrl(url: URL | string): URL {
url = new URL(url);
if (url.pathname.endsWith('.md')) {
return url;
}
if (url.pathname.endsWith('/')) {
url.pathname += 'index.md';
} else {
url.pathname += '.md';
}
return url;
}
-78
View File
@@ -1,78 +0,0 @@
import { describe, it, expect } from 'vitest';
import { parseProviderModel } from './parseProviderModel';
import type { AIConnection } from '@/contexts/AISettingsContext';
describe('parseProviderModel', () => {
const mockProviders: Record<string, AIConnection> = {
openai: {
baseURL: 'https://api.openai.com/v1',
apiKey: 'sk-test-key',
},
openrouter: {
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'sk-or-test-key',
},
anthropic: {
baseURL: 'https://api.anthropic.com',
apiKey: 'sk-ant-test-key',
},
unconfigured: {
baseURL: 'https://example.com/v1',
apiKey: '',
},
};
it('should parse simple provider/model format', () => {
const result = parseProviderModel('openai/gpt-4o', mockProviders);
expect(result.provider).toBe('openai');
expect(result.model).toBe('gpt-4o');
expect(result.connection).toEqual(mockProviders.openai);
});
it('should parse complex model names with slashes', () => {
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('anthropic/claude-sonnet-4');
expect(result.connection).toEqual(mockProviders.openrouter);
});
it('should handle model names with multiple slashes', () => {
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
expect(result.connection).toEqual(mockProviders.openrouter);
});
it('should throw error for invalid format without slash', () => {
expect(() => {
parseProviderModel('invalidformat', mockProviders);
}).toThrow('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
});
it('should throw error for empty provider', () => {
expect(() => {
parseProviderModel('/gpt-4o', mockProviders);
}).toThrow('Invalid format. Both provider and model must be specified');
});
it('should throw error for empty model', () => {
expect(() => {
parseProviderModel('openai/', mockProviders);
}).toThrow('Invalid format. Both provider and model must be specified');
});
it('should throw error for unknown provider', () => {
expect(() => {
parseProviderModel('unknown/gpt-4o', mockProviders);
}).toThrow('Provider "unknown" not found. Available providers: openai, openrouter, anthropic, unconfigured');
});
it('should throw error for provider without API key', () => {
expect(() => {
parseProviderModel('unconfigured/some-model', mockProviders);
}).toThrow('Provider "unconfigured" is not configured with an API key');
});
});
-45
View File
@@ -1,45 +0,0 @@
import type { AIConnection } from '@/contexts/AISettingsContext';
export interface ParsedProviderModel {
provider: string;
model: string;
connection: AIConnection;
}
/**
* Parse a provider/model string and return the provider connection and model name
* Format: provider/model (e.g., "openai/gpt-4o", "openrouter/anthropic/claude-sonnet-4")
* The first slash separates the provider from the model
*/
export function parseProviderModel(
providerModelString: string,
providers: Record<string, AIConnection>
): ParsedProviderModel {
const firstSlashIndex = providerModelString.indexOf('/');
if (firstSlashIndex === -1) {
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
}
const provider = providerModelString.substring(0, firstSlashIndex);
const model = providerModelString.substring(firstSlashIndex + 1);
if (!provider || !model) {
throw new Error('Invalid format. Both provider and model must be specified');
}
const connection = providers[provider];
if (!connection) {
throw new Error(`Provider "${provider}" not found. Available providers: ${Object.keys(providers).join(', ')}`);
}
if (!connection.apiKey) {
throw new Error(`Provider "${provider}" is not configured with an API key`);
}
return {
provider,
model,
connection,
};
}
-102
View File
@@ -1,102 +0,0 @@
import { join } from "@std/path";
import OpenAI from "openai";
import { JSRuntimeFS } from "./JSRuntime";
export interface MakeSystemPromptOpts {
name: string;
profession: string;
tools: OpenAI.Chat.Completions.ChatCompletionTool[];
mode: "init" | "agent";
fs: JSRuntimeFS;
cwd: string;
}
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { name, profession, tools, mode, fs, cwd } = opts;
let system = mode === "init"
? `You are ${name}, an expert ${profession}. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.`
: `You are ${name}, an expert ${profession}. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.`;
// Add current date
const currentDate = new Date().toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
system += `\n\nThe current date is ${currentDate}.`;
// Add available tools to the system prompt
const toolNames = tools
.filter((tool) => tool.type === "function")
.map((tool) => tool.function.name);
if (toolNames.length > 0) {
system +=
"\n\n# Available Tools\n\nYou have access to the following tools:\n";
for (const tool of tools) {
if (tool.type === "function") {
system += `\n- **${tool.function.name}**: ${
tool.function.description || "No description available"
}`;
}
}
}
// Add README.md if it exists
try {
const readmePath = join(cwd, "README.md");
const readmeText = await fs.readFile(readmePath, "utf8");
if (readmeText) {
system += "\n\n" + readmeText;
}
} catch {
// README.md not found, continue
}
// Add context from AGENTS.md if it exists
try {
const { text } = await getAgentContext(fs, cwd);
system += "\n\n" + text;
} catch {
// AGENTS.md not found, continue
}
return system;
}
async function getAgentContext(
fs: JSRuntimeFS,
cwd: string,
): Promise<{ filename: string; text: string }> {
const contextFiles = [
"AGENTS.md",
"CONTEXT.md",
"CLAUDE.md",
"codex.md",
".goosehints",
".cursorrules",
".github/copilot-instructions.md",
];
for (const filename of contextFiles) {
const filePath = join(cwd, filename);
try {
const text = await fs.readFile(filePath, "utf8");
if (text) {
return { filename, text };
}
} catch {
// continue
}
}
throw new Error(
`No context file found in ${cwd}. Please create one of the following files: ${
contextFiles.join(", ")
}`,
);
}
-125
View File
@@ -1,125 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { BuildProjectTool } from './BuildProjectTool';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock the buildProject function
vi.mock('../build', () => ({
buildProject: vi.fn(),
}));
import { buildProject } from '../build';
describe('BuildProjectTool', () => {
let mockFS: JSRuntimeFS;
let tool: BuildProjectTool;
beforeEach(() => {
vi.clearAllMocks();
mockFS = {
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
unlink: vi.fn(),
mkdir: vi.fn(),
} as unknown as JSRuntimeFS;
tool = new BuildProjectTool(mockFS, '/test/project');
});
it('should have correct description and schema', () => {
expect(tool.description).toBe('Build the project using esbuild. Creates optimized production files in the dist directory.');
expect(tool.inputSchema).toBeDefined();
});
it('should validate input schema correctly', () => {
// Valid inputs (empty object only)
expect(() => tool.inputSchema.parse({})).not.toThrow();
});
it('should fail if package.json does not exist', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
await expect(tool.execute({})).rejects.toThrow(
'❌ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.'
);
});
it('should fail if index.html does not exist', async () => {
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('{"name": "test"}') // package.json exists
.mockRejectedValueOnce(new Error('File not found')); // index.html doesn't exist
await expect(tool.execute({})).rejects.toThrow(
'❌ Could not find index.html at /test/project. This is required for building the project.'
);
});
it('should successfully build project', async () => {
const mockDist = {
'index.html': new Uint8Array([1, 2, 3]),
'main.js': new Uint8Array([4, 5, 6]),
'main.css': new Uint8Array([7, 8, 9]),
};
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('{"name": "test"}') // package.json
.mockResolvedValueOnce('<html></html>'); // index.html
vi.mocked(mockFS.readdir).mockRejectedValue(new Error('Directory not found'));
vi.mocked(buildProject).mockResolvedValue(mockDist);
const result = await tool.execute({});
expect(buildProject).toHaveBeenCalledWith({
fs: mockFS,
projectPath: '/test/project',
domParser: expect.any(DOMParser),
});
expect(mockFS.mkdir).toHaveBeenCalledWith('/test/project/dist', { recursive: true });
expect(mockFS.writeFile).toHaveBeenCalledTimes(3);
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/index.html', mockDist['index.html']);
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/main.js', mockDist['main.js']);
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/main.css', mockDist['main.css']);
expect(result).toContain('✅ Successfully built project!');
expect(result).toContain('📦 Files generated: 3');
expect(result).toContain('📄 index.html');
expect(result).toContain('📄 main.js');
expect(result).toContain('📄 main.css');
});
it('should clean existing dist directory before building', async () => {
const mockDist = {
'index.html': new Uint8Array([1, 2, 3]),
};
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('{"name": "test"}') // package.json
.mockResolvedValueOnce('<html></html>'); // index.html
vi.mocked(mockFS.readdir).mockResolvedValue(['old-file.js', 'old-style.css']);
vi.mocked(buildProject).mockResolvedValue(mockDist);
await tool.execute({});
expect(mockFS.readdir).toHaveBeenCalledWith('/test/project/dist');
expect(mockFS.unlink).toHaveBeenCalledWith('/test/project/dist/old-file.js');
expect(mockFS.unlink).toHaveBeenCalledWith('/test/project/dist/old-style.css');
});
it('should handle build errors gracefully', async () => {
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce('{"name": "test"}') // package.json
.mockResolvedValueOnce('<html></html>'); // index.html
vi.mocked(buildProject).mockRejectedValue(new Error('Build compilation failed'));
await expect(tool.execute({})).rejects.toThrow(
'❌ Build failed: Error: Build compilation failed'
);
});
});
-71
View File
@@ -1,71 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { buildProject } from "../build";
type BuildProjectParams = Record<string, never>;
export class BuildProjectTool implements Tool<BuildProjectParams> {
private fs: JSRuntimeFS;
private cwd: string;
readonly description = "Build the project using esbuild. Creates optimized production files in the dist directory.";
readonly inputSchema = z.object({});
constructor(fs: JSRuntimeFS, cwd: string) {
this.fs = fs;
this.cwd = cwd;
}
async execute(_args: BuildProjectParams): Promise<string> {
try {
// Check if we're in a valid project directory
try {
await this.fs.readFile(`${this.cwd}/package.json`, "utf8");
} catch {
throw new Error(`❌ Could not find package.json at ${this.cwd}. Make sure you're in a valid project directory.`);
}
// Check if index.html exists
try {
await this.fs.readFile(`${this.cwd}/index.html`, "utf8");
} catch {
throw new Error(`❌ Could not find index.html at ${this.cwd}. This is required for building the project.`);
}
// Run the build
const dist = await buildProject({
fs: this.fs,
projectPath: this.cwd,
domParser: new DOMParser(),
});
// Delete all existing files in "dist" directory
try {
const distFiles = await this.fs.readdir(`${this.cwd}/dist`);
for (const file of distFiles) {
await this.fs.unlink(`${this.cwd}/dist/${file}`);
}
} catch {
// Ignore errors (e.g., directory doesn't exist)
}
// Create dist directory if it doesn't exist
await this.fs.mkdir(`${this.cwd}/dist`, { recursive: true });
// Write all built files to dist directory
for (const [path, contents] of Object.entries(dist)) {
await this.fs.writeFile(`${this.cwd}/dist/${path}`, contents);
}
const fileCount = Object.keys(dist).length;
const fileList = Object.keys(dist).map(file => ` 📄 ${file}`).join('\n');
return `✅ Successfully built project!\n\n📁 Output: ${this.cwd}/dist\n📦 Files generated: ${fileCount}\n\n${fileList}\n\n🚀 Your project is ready for deployment!`;
} catch (error) {
throw new Error(`❌ Build failed: ${String(error)}`);
}
}
}
+34 -18
View File
@@ -49,9 +49,9 @@ describe('GitCommitTool', () => {
vi.mocked(git.getConfig).mockRejectedValue(new Error('Config not found'));
});
it('should have correct description and inputSchema', () => {
it('should have correct description and parameters', () => {
expect(tool.description).toBe('Commit changes to git with a commit message. Automatically adds all unstaged files.');
expect(tool.inputSchema).toBeDefined();
expect(tool.parameters).toBeDefined();
});
it('should successfully commit changes', async () => {
@@ -82,8 +82,9 @@ describe('GitCommitTool', () => {
email: '[email protected]',
},
});
expect(result).toContain('✅ Successfully committed 2 files (abcd123)');
expect(result).toContain('Add new feature');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully committed 2 files (abcd123)');
expect(result.content[0].text).toContain('Add new feature');
});
it('should handle empty commit message', async () => {
@@ -93,7 +94,10 @@ describe('GitCommitTool', () => {
isFile: () => false,
});
await expect(tool.execute({ message: '' })).rejects.toThrow('❌ Commit message cannot be empty');
const result = await tool.execute({ message: '' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Commit message cannot be empty');
});
it('should handle whitespace-only commit message', async () => {
@@ -103,15 +107,22 @@ describe('GitCommitTool', () => {
isFile: () => false,
});
await expect(tool.execute({ message: ' ' })).rejects.toThrow('❌ Commit message cannot be empty');
const result = await tool.execute({ message: ' ' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Commit message cannot be empty');
});
it('should handle not being in a git repository', async () => {
// Mock .git directory does not exist
vi.mocked(mockFS.stat).mockRejectedValue(new Error('File not found'));
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Not a git repository');
const result = await tool.execute({ message: 'Test commit' });
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git');
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Not a git repository');
expect(result.content[0].text).toContain('git init');
});
it('should handle commit with special characters in message', async () => {
@@ -127,8 +138,9 @@ describe('GitCommitTool', () => {
expect(git.commit).toHaveBeenCalledWith(expect.objectContaining({
message: specialMessage,
}));
expect(result).toContain('✅ Successfully committed');
expect(result).toContain(specialMessage);
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully committed');
expect(result.content[0].text).toContain(specialMessage);
});
it('should handle multiline commit message', async () => {
@@ -142,8 +154,9 @@ describe('GitCommitTool', () => {
const result = await tool.execute({ message: multilineMessage });
expect(git.commit).toHaveBeenCalled();
expect(result).toContain('✅ Successfully committed');
expect(result).toContain('Add new feature');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully committed');
expect(result.content[0].text).toContain('Add new feature');
});
it('should handle no changes to commit', async () => {
@@ -158,7 +171,8 @@ describe('GitCommitTool', () => {
const result = await tool.execute({ message: 'Update documentation' });
expect(result).toContain('ℹ️ No changes to commit. Working tree is clean.');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('ℹ️ No changes to commit. Working tree is clean.');
expect(git.commit).not.toHaveBeenCalled();
});
@@ -171,10 +185,11 @@ describe('GitCommitTool', () => {
const result = await tool.execute({ message: 'Update documentation' });
expect(result).toContain('📝 Commit: "Update documentation"');
expect(result).toContain('🔗 Hash:');
expect(result).toContain('🌿 Branch:');
expect(result).toContain('📊 Changes:');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('📝 Commit: "Update documentation"');
expect(result.content[0].text).toContain('🔗 Hash:');
expect(result.content[0].text).toContain('🌿 Branch:');
expect(result.content[0].text).toContain('📊 Changes:');
});
it('should use git config when available', async () => {
@@ -204,7 +219,7 @@ describe('GitCommitTool', () => {
email: '[email protected]',
},
});
expect(result).toContain('✅ Successfully committed');
expect(result.isError).toBe(false);
});
it('should handle very long commit message', async () => {
@@ -217,6 +232,7 @@ describe('GitCommitTool', () => {
const longMessage = 'A'.repeat(1000); // Very long commit message
const result = await tool.execute({ message: longMessage });
expect(result).toContain('✅ Successfully committed');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully committed');
});
});
+38 -8
View File
@@ -1,7 +1,7 @@
import { z } from "zod";
import git from 'isomorphic-git';
import type { Tool } from "./Tool";
import type { Tool, CallToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GitCommitParams {
@@ -14,7 +14,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files.";
readonly inputSchema = z.object({
readonly parameters = z.object({
message: z.string().describe('Commit message text'),
});
@@ -23,7 +23,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
this.cwd = cwd;
}
async execute(args: GitCommitParams): Promise<string> {
async execute(args: GitCommitParams): Promise<CallToolResult> {
const { message } = args;
try {
@@ -31,12 +31,24 @@ export class GitCommitTool implements Tool<GitCommitParams> {
try {
await this.fs.stat(`${this.cwd}/.git`);
} catch {
throw new Error(`❌ Not a git repository. Initialize git first with 'git init'.`);
return {
content: [{
type: "text",
text: `❌ Not a git repository. Initialize git first with 'git init'.`,
}],
isError: true,
};
}
// Validate commit message
if (!message.trim()) {
throw new Error(`❌ Commit message cannot be empty.`);
return {
content: [{
type: "text",
text: `❌ Commit message cannot be empty.`,
}],
isError: true,
};
}
// Get git status to see what files have changed
@@ -54,7 +66,13 @@ export class GitCommitTool implements Tool<GitCommitParams> {
});
if (changedFiles.length === 0) {
return `ℹ️ No changes to commit. Working tree is clean.`;
return {
content: [{
type: "text",
text: `ℹ️ No changes to commit. Working tree is clean.`,
}],
isError: false,
};
}
// Add all changed files to staging
@@ -152,9 +170,21 @@ export class GitCommitTool implements Tool<GitCommitParams> {
if (modifiedFiles > 0) details += ` • ${modifiedFiles} file${modifiedFiles !== 1 ? 's' : ''} modified\n`;
if (deletedFiles > 0) details += ` • ${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} deleted\n`;
return `${summary}\n\n${details}`;
return {
content: [{
type: "text",
text: `${summary}\n\n${details}`,
}],
isError: false,
};
} catch (error) {
throw new Error(`❌ Error committing changes: ${String(error)}`);
return {
content: [{
type: "text",
text: `❌ Error committing changes: ${String(error)}`,
}],
isError: true,
};
}
}
}
-184
View File
@@ -1,184 +0,0 @@
import { z } from "zod";
import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import type { Tool } from "./Tool";
interface NostrFetchEventParams {
identifier: string;
}
export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
readonly description = "Fetch a Nostr event using a nip19 identifier";
readonly inputSchema = z.object({
identifier: z
.string()
.superRefine((val, ctx) => {
let decoded: nip19.DecodedResult;
try {
decoded = nip19.decode(val);
} catch {
ctx.addIssue({
code: 'custom',
message:
`Failed to decode identifier. Invalid NIP-19 identifier: ${val}`,
});
return;
}
// Reject nsec for security reasons
if (decoded.type === 'nsec') {
ctx.addIssue({
code: 'custom',
message:
'nsec identifiers are not supported for security reasons',
});
return;
}
// Accept npub, nprofile, naddr, note, nevent
if (!['npub', 'nprofile', 'naddr', 'note', 'nevent'].includes(decoded.type)) {
ctx.addIssue({
code: 'custom',
message:
`Unsupported identifier type: ${decoded.type}. Supported types: npub, nprofile, naddr, note, nevent`,
});
return;
}
})
.describe(
'NIP-19 identifier (npub, nprofile, naddr, note, or nevent), e.g. npub1... or naddr1...',
),
});
async execute(args: NostrFetchEventParams): Promise<string> {
const { identifier } = args;
const decoded = nip19.decode(identifier);
const defaultRelays = [
'wss://ditto.pub/relay',
'wss://relay.nostr.band',
'wss://relay.primal.net',
];
const pool = new NPool({
open(url) {
return new NRelay1(url);
},
eventRouter() {
return [...defaultRelays];
},
reqRouter(filters) {
return new Map(
[...defaultRelays].map((url) => [url, filters]),
);
},
});
try {
let event: NostrEvent | undefined;
switch (decoded.type) {
case 'npub': {
// For npub, fetch the user's kind 0 (profile) event
[event] = await pool.query(
[{
kinds: [0],
authors: [decoded.data],
limit: 1,
}],
{ signal: AbortSignal.timeout(8_000) },
);
break;
}
case 'nprofile': {
// For nprofile, fetch the user's kind 0 (profile) event
let { relays } = decoded.data;
if (!relays || !relays.length) {
relays = defaultRelays;
}
[event] = await pool.group(relays).query(
[{
kinds: [0],
authors: [decoded.data.pubkey],
limit: 1,
}],
{ signal: AbortSignal.timeout(8_000) },
);
break;
}
case 'note': {
// For note, fetch the specific event by ID
[event] = await pool.query(
[{ ids: [decoded.data] }],
{ signal: AbortSignal.timeout(8_000) },
);
break;
}
case 'nevent': {
// For nevent, fetch the specific event by ID
let { relays } = decoded.data;
if (!relays || !relays.length) {
relays = defaultRelays;
}
[event] = await pool.group(relays).query(
[{
ids: [decoded.data.id],
}],
{ signal: AbortSignal.timeout(8_000) },
);
break;
}
case 'naddr': {
// For naddr, fetch by kind, pubkey, and d tag
let { relays } = decoded.data;
if (!relays || !relays.length) {
relays = defaultRelays;
}
[event] = await pool.group(relays).query(
[{
kinds: [decoded.data.kind],
authors: [decoded.data.pubkey],
'#d': [decoded.data.identifier],
}],
{ signal: AbortSignal.timeout(8_000) },
);
break;
}
default:
throw new Error(`Unsupported identifier type: ${decoded.type}`);
}
if (!event) {
throw new Error('No event found for the provided identifier. Make sure it exists and is accessible.');
}
// Special handling for specific kinds
if (event.kind === 30817) {
// Kind 30817 is a NIP document, return just the content
return event.content;
}
// For other kinds, return the full event JSON
return JSON.stringify(event, null, 2);
} catch (error) {
throw new Error(`Error fetching event: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
await pool.close();
}
}
}
-47
View File
@@ -1,47 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import { KindGenerator, type KindRange } from "../KindGenerator";
import { NIPsClient } from "../NIPsClient";
interface NostrGenerateKindParams {
range: KindRange;
}
export class NostrGenerateKindTool implements Tool<NostrGenerateKindParams> {
private nipsClient: NIPsClient;
readonly description = "Generate an unused Nostr event kind number in the specified range";
readonly inputSchema = z.object({
range: z.enum(['regular', 'replaceable', 'ephemeral', 'addressable'])
.describe(
'Kind range: regular (1000-9999), replaceable (10000-19999), ephemeral (20000-29999), addressable (30000-39999)',
) as z.ZodType<KindRange>,
});
constructor() {
this.nipsClient = new NIPsClient({
urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md',
});
}
async execute(args: NostrGenerateKindParams): Promise<string> {
const { range } = args;
try {
const nipsIndex = await this.nipsClient.readIndex();
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
const availableKind = KindGenerator.generateAvailableKind(
range,
usedKinds,
);
const rangeInfo = KindGenerator.getKindRangeInfo(range);
return `Generated unused kind: ${availableKind}\n\nRange: ${rangeInfo.name} (${rangeInfo.min}-${rangeInfo.max})\nDescription: ${rangeInfo.description}\n\nThis kind number is currently not used by any official NIP.`;
} catch (error) {
throw new Error(`Error generating kind: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
-41
View File
@@ -1,41 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import { NostrbookClient } from "../NostrbookClient";
import { HTTPError } from "../HTTPError";
interface NostrReadKindParams {
kind: number;
}
export class NostrReadKindTool implements Tool<NostrReadKindParams> {
private nostrbookClient: NostrbookClient;
readonly description = "Read Nostr documentation about a specific event kind";
readonly inputSchema = z.object({
kind: z.number().describe('Kind number to retrieve, e.g. `1` or `42`'),
});
constructor() {
this.nostrbookClient = new NostrbookClient({
baseUrl: 'https://nostrbook.dev',
});
}
async execute(args: NostrReadKindParams): Promise<string> {
const { kind } = args;
try {
const text = await this.nostrbookClient.readKind(kind);
return text;
} catch (error) {
if (error instanceof HTTPError && error.response.status === 404) {
throw new Error(
`No documentation found for kind ${kind}. Try using the \`nostr_read_nips_index\` tool to see if it's specified by a NIP.`
);
}
throw new Error(`Error reading kind ${kind}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
-48
View File
@@ -1,48 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import { NIPsClient } from "../NIPsClient";
import { HTTPError } from "../HTTPError";
interface NostrReadNipParams {
nip: string;
}
export class NostrReadNipTool implements Tool<NostrReadNipParams> {
private nipsClient: NIPsClient;
readonly description = "Read a Nostr NIP document";
readonly inputSchema = z.object({
nip: z
.string()
.length(2)
.regex(
/^[0-9A-F]{2}$/,
'NIP must be a 2-digit uppercase hex string, e.g. `01` or `C7`',
)
.describe('NIP to retrieve, e.g. `01` or `C7`'),
});
constructor() {
this.nipsClient = new NIPsClient({
urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md',
});
}
async execute(args: NostrReadNipParams): Promise<string> {
const { nip } = args;
try {
const text = await this.nipsClient.readNip(nip);
return text;
} catch (error) {
if (error instanceof HTTPError && error.response.status === 404) {
throw new Error(
`NIP-${nip} does not exist in the official NIPs repository. Try using the \`nostr_read_nips_index\` tool to retrieve the full list of NIPs.`
);
}
throw new Error(`Error reading NIP-${nip}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
-27
View File
@@ -1,27 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import { NIPsClient } from "../NIPsClient";
export class NostrReadNipsIndexTool implements Tool<object> {
private nipsClient: NIPsClient;
readonly description = "Read the full list of NIPs, kinds, and tags";
readonly inputSchema = z.object({});
constructor() {
this.nipsClient = new NIPsClient({
urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md',
});
}
async execute(_args: object): Promise<string> {
try {
const text = await this.nipsClient.readIndex();
return text;
} catch (error) {
throw new Error(`Error reading NIPs index: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
-35
View File
@@ -1,35 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import { NostrbookClient } from "../NostrbookClient";
interface NostrReadProtocolParams {
doc: 'index' | 'event' | 'filter' | 'client' | 'relay';
}
export class NostrReadProtocolTool implements Tool<NostrReadProtocolParams> {
private nostrbookClient: NostrbookClient;
readonly description = "Read Nostr protocol basics";
readonly inputSchema = z.object({
doc: z.enum(['index', 'event', 'filter', 'client', 'relay']),
});
constructor() {
this.nostrbookClient = new NostrbookClient({
baseUrl: 'https://nostrbook.dev',
});
}
async execute(args: NostrReadProtocolParams): Promise<string> {
const { doc } = args;
try {
const text = await this.nostrbookClient.readProtocol(doc);
return text;
} catch (error) {
throw new Error(`Error reading protocol doc "${doc}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
-41
View File
@@ -1,41 +0,0 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import { NostrbookClient } from "../NostrbookClient";
import { HTTPError } from "../HTTPError";
interface NostrReadTagParams {
tag: string;
}
export class NostrReadTagTool implements Tool<NostrReadTagParams> {
private nostrbookClient: NostrbookClient;
readonly description = "Read Nostr documentation about a specific tag";
readonly inputSchema = z.object({
tag: z.string().describe('Tag name to retrieve, e.g. `p` or `e`'),
});
constructor() {
this.nostrbookClient = new NostrbookClient({
baseUrl: 'https://nostrbook.dev',
});
}
async execute(args: NostrReadTagParams): Promise<string> {
const { tag } = args;
try {
const text = await this.nostrbookClient.readTag(tag);
return text;
} catch (error) {
if (error instanceof HTTPError && error.response.status === 404) {
throw new Error(
`No documentation found for the "${tag}" tag. Try using the \`nostr_read_nips_index\` tool to see if it's specified by a NIP.`
);
}
throw new Error(`Error reading tag "${tag}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
+25 -11
View File
@@ -33,9 +33,9 @@ describe('NpmAddPackageTool', () => {
vi.restoreAllMocks();
});
it('should have correct description and inputSchema', () => {
it('should have correct description and parameters', () => {
expect(tool.description).toBe('Safely add an npm package to the project in the current directory.');
expect(tool.inputSchema).toBeDefined();
expect(tool.parameters).toBeDefined();
});
it('should successfully add a new package', async () => {
@@ -60,7 +60,8 @@ describe('NpmAddPackageTool', () => {
expect.stringContaining('"lodash": "^4.17.21"'),
'utf8'
);
expect(result).toContain('✅ Successfully added [email protected]');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully added [email protected]');
});
it('should add package with specific version', async () => {
@@ -80,7 +81,8 @@ describe('NpmAddPackageTool', () => {
expect.stringContaining('"lodash": "^4.17.20"'),
'utf8'
);
expect(result).toContain('✅ Successfully added [email protected]');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully added [email protected]');
});
it('should add dev dependency', async () => {
@@ -111,7 +113,8 @@ describe('NpmAddPackageTool', () => {
expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0');
expect(writtenPackageJson.dependencies?.typescript).toBeUndefined();
expect(result).toContain('Development dependency');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('Development dependency');
});
it('should move package from dependencies to devDependencies', async () => {
@@ -138,7 +141,7 @@ describe('NpmAddPackageTool', () => {
expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0');
// dependencies object should be empty or not contain typescript
expect(writtenPackageJson.dependencies?.typescript).toBeUndefined();
expect(result).toContain('✅ Successfully added');
expect(result.isError).toBe(false);
});
it('should handle package already installed', async () => {
@@ -159,19 +162,26 @@ describe('NpmAddPackageTool', () => {
const result = await tool.execute({ name: 'lodash' });
expect(mockFS.writeFile).not.toHaveBeenCalled();
expect(result).toContain('ℹ️ Package [email protected] is already installed');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('ℹ️ Package [email protected] is already installed');
});
it('should handle missing package.json', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Could not read package.json');
const result = await tool.execute({ name: 'lodash' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Could not read package.json');
});
it('should handle invalid package.json', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Invalid package.json format');
const result = await tool.execute({ name: 'lodash' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Invalid package.json format');
});
it('should handle npm registry errors', async () => {
@@ -188,7 +198,11 @@ describe('NpmAddPackageTool', () => {
statusText: 'Not Found'
});
await expect(tool.execute({ name: 'nonexistent-package' })).rejects.toThrow('❌ Could not fetch latest version');
const result = await tool.execute({ name: 'nonexistent-package' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Could not fetch latest version');
expect(result.content[0].text).toContain('HTTP 404: Not Found');
});
it('should sort dependencies alphabetically', async () => {
@@ -214,6 +228,6 @@ describe('NpmAddPackageTool', () => {
const dependencyKeys = Object.keys(writtenPackageJson.dependencies);
expect(dependencyKeys).toEqual(['axios', 'lodash', 'zlib']);
expect(result).toContain('✅ Successfully added');
expect(result.isError).toBe(false);
});
});
+45 -9
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import type { Tool, CallToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface NpmAddPackageParams {
@@ -21,7 +21,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
readonly description = "Safely add an npm package to the project in the current directory.";
readonly inputSchema = z.object({
readonly parameters = z.object({
name: z.string().describe('Name of the npm package to add, eg "lodash"'),
version: z.string().optional().describe("Version (optional)"),
dev: z.boolean().optional().describe("If true, add to devDependencies (default: false)"),
@@ -32,7 +32,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
this.cwd = cwd;
}
async execute(args: NpmAddPackageParams): Promise<string> {
async execute(args: NpmAddPackageParams): Promise<CallToolResult> {
const { name, version, dev = false } = args;
try {
@@ -43,7 +43,13 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
try {
packageJsonContent = await this.fs.readFile(packageJsonPath, "utf8");
} catch {
throw new Error(`❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`);
return {
content: [{
type: "text",
text: `❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`,
}],
isError: true,
};
}
// Parse package.json
@@ -51,7 +57,13 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
try {
packageJson = JSON.parse(packageJsonContent);
} catch {
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
return {
content: [{
type: "text",
text: `❌ Invalid package.json format. Could not parse JSON.`,
}],
isError: true,
};
}
// Determine version to use
@@ -60,7 +72,13 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
try {
targetVersion = await this.fetchLatestVersion(name);
} catch (error) {
throw new Error(`❌ Could not fetch latest version for ${name}. Package may not exist or npm registry is unavailable.\n\nError: ${String(error)}`);
return {
content: [{
type: "text",
text: `❌ Could not fetch latest version for ${name}. Package may not exist or npm registry is unavailable.\n\nError: ${String(error)}`,
}],
isError: true,
};
}
}
@@ -71,7 +89,13 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
if (packageJson[dependencyKey]?.[name]) {
const currentVersion = packageJson[dependencyKey][name];
if (currentVersion === `^${targetVersion}`) {
return `ℹ️ Package ${name}@${targetVersion} is already installed in ${dependencyKey}.`;
return {
content: [{
type: "text",
text: `ℹ️ Package ${name}@${targetVersion} is already installed in ${dependencyKey}.`,
}],
isError: false,
};
}
}
@@ -111,9 +135,21 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
const updatedContent = JSON.stringify(packageJson, null, 2) + '\n';
await this.fs.writeFile(packageJsonPath, updatedContent, "utf8");
return `✅ Successfully added ${name}@${targetVersion} to ${dependencyKey} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ^${targetVersion}\n📁 Type: ${dev ? 'Development dependency' : 'Production dependency'}`;
return {
content: [{
type: "text",
text: `✅ Successfully added ${name}@${targetVersion} to ${dependencyKey} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ^${targetVersion}\n📁 Type: ${dev ? 'Development dependency' : 'Production dependency'}`,
}],
isError: false,
};
} catch (error) {
throw new Error(`❌ Error adding package ${name}: ${String(error)}`);
return {
content: [{
type: "text",
text: `❌ Error adding package ${name}: ${String(error)}`,
}],
isError: true,
};
}
}
+21 -12
View File
@@ -25,9 +25,9 @@ describe('NpmRemovePackageTool', () => {
tool = new NpmRemovePackageTool(mockFS, '/test/project');
});
it('should have correct description and inputSchema', () => {
it('should have correct description and parameters', () => {
expect(tool.description).toBe('Safely remove an npm package from the project in the current directory.');
expect(tool.inputSchema).toBeDefined();
expect(tool.parameters).toBeDefined();
});
it('should successfully remove package from dependencies', async () => {
@@ -51,7 +51,8 @@ describe('NpmRemovePackageTool', () => {
expect(writtenPackageJson.dependencies.lodash).toBeUndefined();
expect(writtenPackageJson.dependencies.axios).toBe('^1.0.0');
expect(result).toContain('✅ Successfully removed lodash from dependencies');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully removed lodash from dependencies');
});
it('should successfully remove package from devDependencies', async () => {
@@ -77,7 +78,8 @@ describe('NpmRemovePackageTool', () => {
expect(writtenPackageJson.devDependencies.typescript).toBeUndefined();
expect(writtenPackageJson.devDependencies.eslint).toBe('^8.0.0');
expect(writtenPackageJson.dependencies.react).toBe('^18.0.0');
expect(result).toContain('✅ Successfully removed typescript from devDependencies');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('✅ Successfully removed typescript from devDependencies');
});
it('should remove empty dependencies object', async () => {
@@ -97,7 +99,7 @@ describe('NpmRemovePackageTool', () => {
const writtenPackageJson = JSON.parse(writtenContent);
expect(writtenPackageJson.dependencies).toBeUndefined();
expect(result).toContain('✅ Successfully removed');
expect(result.isError).toBe(false);
});
it('should remove empty devDependencies object', async () => {
@@ -121,7 +123,7 @@ describe('NpmRemovePackageTool', () => {
expect(writtenPackageJson.devDependencies).toBeUndefined();
expect(writtenPackageJson.dependencies.react).toBe('^18.0.0');
expect(result).toContain('✅ Successfully removed');
expect(result.isError).toBe(false);
});
it('should handle package not found', async () => {
@@ -138,19 +140,26 @@ describe('NpmRemovePackageTool', () => {
const result = await tool.execute({ name: 'nonexistent-package' });
expect(mockFS.writeFile).not.toHaveBeenCalled();
expect(result).toContain('ℹ️ Package nonexistent-package was not found');
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('ℹ️ Package nonexistent-package was not found');
});
it('should handle missing package.json', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Could not read package.json');
const result = await tool.execute({ name: 'lodash' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Could not read package.json');
});
it('should handle invalid package.json', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
await expect(tool.execute({ name: 'lodash' })).rejects.toThrow('❌ Invalid package.json format');
const result = await tool.execute({ name: 'lodash' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Invalid package.json format');
});
it('should sort remaining dependencies alphabetically', async () => {
@@ -173,7 +182,7 @@ describe('NpmRemovePackageTool', () => {
const dependencyKeys = Object.keys(writtenPackageJson.dependencies);
expect(dependencyKeys).toEqual(['axios', 'zlib']);
expect(result).toContain('✅ Successfully removed');
expect(result.isError).toBe(false);
});
it('should include version information in success message', async () => {
@@ -189,7 +198,7 @@ describe('NpmRemovePackageTool', () => {
const result = await tool.execute({ name: 'lodash' });
expect(result).toContain('🏷️ Version: ^4.17.21');
expect(result).toContain('📁 Removed from: dependencies');
expect(result.content[0].text).toContain('🏷️ Version: ^4.17.21');
expect(result.content[0].text).toContain('📁 Removed from: dependencies');
});
});
+38 -8
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { Tool } from "./Tool";
import type { Tool, CallToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface NpmRemovePackageParams {
@@ -19,7 +19,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
readonly description = "Safely remove an npm package from the project in the current directory.";
readonly inputSchema = z.object({
readonly parameters = z.object({
name: z.string().describe("Name of the npm package to remove"),
});
@@ -28,7 +28,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
this.cwd = cwd;
}
async execute(args: NpmRemovePackageParams): Promise<string> {
async execute(args: NpmRemovePackageParams): Promise<CallToolResult> {
const { name } = args;
try {
@@ -39,7 +39,13 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
try {
packageJsonContent = await this.fs.readFile(packageJsonPath, "utf8");
} catch {
throw new Error(`❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`);
return {
content: [{
type: "text",
text: `❌ Could not read package.json at ${packageJsonPath}. Make sure you're in a valid npm project.`,
}],
isError: true,
};
}
// Parse package.json
@@ -47,7 +53,13 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
try {
packageJson = JSON.parse(packageJsonContent);
} catch {
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
return {
content: [{
type: "text",
text: `❌ Invalid package.json format. Could not parse JSON.`,
}],
isError: true,
};
}
// Check if package exists in dependencies or devDependencies
@@ -75,7 +87,13 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
}
if (!foundIn) {
return `ℹ️ Package ${name} was not found in package.json dependencies or devDependencies.`;
return {
content: [{
type: "text",
text: `ℹ️ Package ${name} was not found in package.json dependencies or devDependencies.`,
}],
isError: false,
};
}
// Sort remaining dependencies alphabetically
@@ -99,9 +117,21 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
const updatedContent = JSON.stringify(packageJson, null, 2) + '\n';
await this.fs.writeFile(packageJsonPath, updatedContent, "utf8");
return `✅ Successfully removed ${name} from ${foundIn} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ${removedVersion}\n📁 Removed from: ${foundIn}\n\n⚠️ **Next step**: Run \`npm install\` to update node_modules and package-lock.json`;
return {
content: [{
type: "text",
text: `✅ Successfully removed ${name} from ${foundIn} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ${removedVersion}\n📁 Removed from: ${foundIn}\n\n⚠️ **Next step**: Run \`npm install\` to update node_modules and package-lock.json`,
}],
isError: false,
};
} catch (error) {
throw new Error(`❌ Error removing package ${name}: ${String(error)}`);
return {
content: [{
type: "text",
text: `❌ Error removing package ${name}: ${String(error)}`,
}],
isError: true,
};
}
}
}
-236
View File
@@ -1,236 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { JSDOM } from "jsdom";
import { ReadWebpageTool } from "./ReadWebpageTool";
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe("ReadWebpageTool", () => {
let tool: ReadWebpageTool;
let domParser: DOMParser;
beforeEach(() => {
// Create a JSDOM instance for testing
const jsdom = new JSDOM();
domParser = new jsdom.window.DOMParser();
tool = new ReadWebpageTool(domParser);
mockFetch.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("inputSchema", () => {
it("should validate valid URL", () => {
const result = tool.inputSchema.safeParse({
url: "https://example.com",
});
expect(result.success).toBe(true);
});
it("should reject invalid URL", () => {
const result = tool.inputSchema.safeParse({
url: "not-a-url",
});
expect(result.success).toBe(false);
});
});
describe("execute", () => {
it("should extract and convert article content to markdown", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Test Article</title>
</head>
<body>
<article>
<h1>Main Article Title</h1>
<p>This is the main content of the article.</p>
<p>It has multiple paragraphs with <strong>bold text</strong> and <em>italic text</em>.</p>
<h2>Subsection</h2>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
</article>
<div class="sidebar">
<p>This is sidebar content that should be ignored.</p>
</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html; charset=utf-8"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article",
});
expect(result).toContain("# Test Article");
expect(result).toContain("**Source:** https://example.com/article");
expect(result).toContain("Main Article Title");
expect(result).toContain("**bold text**");
expect(result).toContain("*italic text*");
expect(result).toContain("## Subsection");
expect(result).toContain("* First item");
expect(result).toContain("* Second item");
});
it("should handle articles with metadata", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Article with Metadata</title>
<meta name="author" content="John Doe">
<meta name="description" content="This is a test article description">
</head>
<body>
<article>
<header>
<h1>Article with Metadata</h1>
<p class="byline">By John Doe</p>
<time datetime="2023-01-01">January 1, 2023</time>
</header>
<p>Main article content goes here.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article-with-metadata",
});
expect(result).toContain("# Article with Metadata");
expect(result).toContain("**Source:** https://example.com/article-with-metadata");
});
it("should handle code blocks properly", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<article>
<h1>Code Example</h1>
<p>Here's some code:</p>
<pre><code class="language-javascript">
function hello() {
console.log("Hello, world!");
}
</code></pre>
<p>And some inline <code>code</code> too.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/code-example",
});
expect(result).toContain("```");
expect(result).toContain("function hello()");
expect(result).toContain("`code`");
});
it("should handle HTTP errors", async () => {
const mockResponse = {
ok: false,
status: 404,
statusText: "Not Found",
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://example.com/not-found",
})).rejects.toThrow("HTTP 404: Not Found");
});
it("should handle non-HTML content", async () => {
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("application/json"),
},
text: vi.fn().mockResolvedValue('{"data": "json"}'),
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://api.example.com/data.json",
})).rejects.toThrow("Expected HTML content, but received: application/json");
});
it("should handle network errors", async () => {
mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));
await expect(tool.execute({
url: "https://example.com",
})).rejects.toThrow("Network error: Unable to fetch https://example.com");
});
it("should handle pages with minimal content", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<div class="navigation">Nav content</div>
<div class="footer">Footer content</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/minimal-content",
});
expect(result).toContain("# Untitled");
expect(result).toContain("**Source:** https://example.com/minimal-content");
});
it("should handle invalid URLs", async () => {
await expect(tool.execute({
url: "invalid-url",
})).rejects.toThrow("Failed to read webpage invalid-url");
});
});
});
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more