diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index e9c678b5..cb69af3b 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -75,8 +75,8 @@ export function ActionsMenu({ const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { toast } = useToast(); - const git = useGit(); const { fs } = useFS(); + const { git } = useGit(); const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting; diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 5b5b53a7..9397e1a3 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -58,7 +58,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); - const git = useGit(); + const { git } = useGit(); const { toast } = useToast(); const projectPath = `/projects/${projectId}`; diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 86874a48..e6dc2218 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -33,13 +33,13 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; -import { Git } from '@/lib/git'; 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 { saveFileToTmp } from '@/lib/fileUtils'; +import { useGit } from '@/hooks/useGit'; interface ChatPaneProps { projectId: string; @@ -94,13 +94,13 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); + const { git } = useGit(); const { user, metadata } = useCurrentUser(); const { models } = useProviderModels(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; const customTools = useMemo(() => { - const git = new Git(fs); const baseTools = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd), @@ -129,7 +129,7 @@ export const ChatPane = forwardRef(({ } return baseTools; - }, [fs, cwd, user, projectId]); + }, [fs, git, cwd, user, projectId]); // Convert tools to OpenAI format const tools = useMemo(() => { diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index f678bcc5..9381d3a7 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -43,8 +43,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange const setIsOpen = onOpenChange || setInternalOpen; const [isRollingBack, setIsRollingBack] = useState(null); const [expandedCommits, setExpandedCommits] = useState>(new Set()); - const git = useGit(); const { fs } = useFS(); + const { git } = useGit(); const { toast } = useToast(); const loadGitHistory = useCallback(async () => { diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index d24fffe2..8be35626 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -5,22 +5,40 @@ import { useFS } from './useFS'; import { useGitSettings } from './useGitSettings'; import { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import type { NPool } from '@nostrify/nostrify'; // Mock the dependencies vi.mock('./useFS'); vi.mock('./useGitSettings'); +vi.mock('@nostrify/react', () => ({ + useNostr: vi.fn(), +})); vi.mock('@/lib/git'); const mockUseFS = vi.mocked(useFS); const mockUseGitSettings = vi.mocked(useGitSettings); const MockGit = vi.mocked(Git); +// Import the mocked useNostr after mocking +import { useNostr } from '@nostrify/react'; +const mockUseNostr = vi.mocked(useNostr); + describe('useGit', () => { const mockFS = {} as JSRuntimeFS; + const mockNostr = { + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), + } as unknown as NPool; beforeEach(() => { vi.clearAllMocks(); mockUseFS.mockReturnValue({ fs: mockFS }); + mockUseNostr.mockReturnValue({ nostr: mockNostr }); }); it('creates Git instance with default CORS proxy', () => { @@ -36,9 +54,14 @@ describe('useGit', () => { isConfigured: false, }); - renderHook(() => useGit()); + const { result } = renderHook(() => useGit()); - expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org'); + expect(MockGit).toHaveBeenCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://cors.isomorphic-git.org', + }); + expect(result.current).toEqual({ git: expect.any(Object) }); }); it('creates Git instance with custom CORS proxy', () => { @@ -54,14 +77,17 @@ describe('useGit', () => { isConfigured: false, }); - renderHook(() => useGit()); + const { result } = renderHook(() => useGit()); - expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://custom-cors.example.com'); + expect(MockGit).toHaveBeenCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://custom-cors.example.com', + }); + expect(result.current).toEqual({ git: expect.any(Object) }); }); it('recreates Git instance when CORS proxy changes', () => { - const { rerender } = renderHook(() => useGit()); - // First render with default proxy mockUseGitSettings.mockReturnValue({ settings: { @@ -75,8 +101,12 @@ describe('useGit', () => { isConfigured: false, }); - rerender(); - expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org'); + const { rerender } = renderHook(() => useGit()); + expect(MockGit).toHaveBeenCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://cors.isomorphic-git.org', + }); // Second render with custom proxy mockUseGitSettings.mockReturnValue({ @@ -92,6 +122,10 @@ describe('useGit', () => { }); rerender(); - expect(MockGit).toHaveBeenLastCalledWith(mockFS, 'https://custom-cors.example.com'); + expect(MockGit).toHaveBeenLastCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://custom-cors.example.com', + }); }); }); \ No newline at end of file diff --git a/src/hooks/useGit.ts b/src/hooks/useGit.ts index 65a542d9..714441e6 100644 --- a/src/hooks/useGit.ts +++ b/src/hooks/useGit.ts @@ -1,19 +1,22 @@ import { useMemo } from 'react'; import { Git } from '@/lib/git'; import { useFS } from '@/hooks/useFS'; +import { useNostr } from '@nostrify/react'; import { useGitSettings } from '@/hooks/useGitSettings'; /** * Hook that provides a Git instance configured with the virtual filesystem * and configurable CORS proxy for GitHub/GitLab repositories. */ -export function useGit() { +export function useGit(): { git: Git } { const { fs } = useFS(); + const { nostr } = useNostr(); const { settings } = useGitSettings(); + const { corsProxy } = settings; const git = useMemo(() => { - return new Git(fs, settings.corsProxy); - }, [fs, settings.corsProxy]); + return new Git({ fs, nostr, corsProxy }); + }, [fs, nostr, corsProxy]); - return git; + return { git }; } \ No newline at end of file diff --git a/src/hooks/useGitStatus.ts b/src/hooks/useGitStatus.ts index c4ec76ac..d12a7c9f 100644 --- a/src/hooks/useGitStatus.ts +++ b/src/hooks/useGitStatus.ts @@ -40,7 +40,7 @@ interface GitStatus { } export function useGitStatus(projectId: string | null) { - const git = useGit(); + const { git } = useGit(); return useQuery({ queryKey: ['git-status', projectId], diff --git a/src/hooks/useProjectsManager.ts b/src/hooks/useProjectsManager.ts index d7d133e6..c918bd1e 100644 --- a/src/hooks/useProjectsManager.ts +++ b/src/hooks/useProjectsManager.ts @@ -1,6 +1,7 @@ import { useMemo } from 'react'; import { ProjectsManager } from '@/lib/ProjectsManager'; import { useFS } from '@/hooks/useFS'; +import { useGit } from './useGit'; /** * Hook that provides a ProjectsManager instance. @@ -8,8 +9,11 @@ import { useFS } from '@/hooks/useFS'; */ export function useProjectsManager() { const { fs } = useFS(); + const { git } = useGit(); - const projectsManager = useMemo(() => new ProjectsManager(fs), [fs]); + const projectsManager = useMemo(() => { + return new ProjectsManager({ fs, git }); + }, [fs, git]); return projectsManager; } \ No newline at end of file diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index aea9a858..f5d6a5fc 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -1,11 +1,27 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ProjectsManager } from './ProjectsManager'; +import { JSRuntimeFS } from './JSRuntime'; +import { Git } from './git'; +import type { NPool } from '@nostrify/nostrify'; + +const createMockNostr = (): NPool => ({ + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), +}) as unknown as NPool; // Mock filesystem for testing -class MockFS { +class MockFS implements JSRuntimeFS { private files: Map = new Map(); private dirs: Set = new Set(); + async readFile(path: string): Promise; + async readFile(path: string, encoding: "utf8"): Promise; + async readFile(path: string, encoding: string): Promise; async readFile(path: string, encoding?: string): Promise { const content = this.files.get(path); if (content === undefined) { @@ -13,10 +29,18 @@ class MockFS { error.code = 'ENOENT'; throw error; } - if (encoding === 'utf8' && typeof content === 'string') { - return content; + if (encoding === 'utf8') { + if (typeof content === 'string') { + return content; + } + // Convert Uint8Array to string + return new TextDecoder('utf-8').decode(content as Uint8Array); } - return content; + if (typeof content === 'string') { + // Convert string to Uint8Array + return new TextEncoder().encode(content); + } + return content as Uint8Array; } async writeFile(path: string, data: string | Uint8Array): Promise { @@ -28,13 +52,14 @@ class MockFS { } } - async readdir(path: string): Promise { + // @ts-expect-error I don't know how to type this properly + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { if (!this.dirs.has(path)) { const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException; error.code = 'ENOENT'; throw error; } - + const entries: string[] = []; // Find subdirectories @@ -51,7 +76,22 @@ class MockFS { } } - return [...new Set(entries)]; + const uniqueEntries = [...new Set(entries)]; + + if (options && options.withFileTypes) { + // Provide a minimal DirectoryEntry mock + return uniqueEntries.map(name => { + const fullPath = path.endsWith('/') ? path + name : path + '/' + name; + const isDir = this.dirs.has(fullPath); + return { + name, + isDirectory: () => isDir, + isFile: () => !isDir, + } as unknown as DirectoryEntry; + }); + } + + return uniqueEntries; } async mkdir(path: string): Promise { @@ -88,12 +128,16 @@ class MockFS { } describe('ProjectsManager', () => { - let fs: MockFS; + let fs: JSRuntimeFS; + let git: Git; + let nostr: NPool; let projectsManager: ProjectsManager; beforeEach(() => { - fs = new MockFS(); - projectsManager = new ProjectsManager(fs as unknown as import('./JSRuntime').JSRuntimeFS); + fs = new MockFS() as unknown as JSRuntimeFS; + nostr = createMockNostr(); + git = new Git({ fs, nostr }); + projectsManager = new ProjectsManager({ fs, git }); }); describe('getProjects', () => { diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 91af47ab..014ac6d4 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -1,8 +1,7 @@ import { Buffer } from 'buffer'; -import { Git } from '@/lib/git'; +import type { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; - // Polyfill Buffer for browser if (typeof window !== 'undefined') { (window as { Buffer?: typeof Buffer }).Buffer = Buffer; @@ -18,14 +17,19 @@ export interface Project { lastModified: Date; } +export interface ProjectsManagerOptions { + fs: JSRuntimeFS; + git: Git; +} + export class ProjectsManager { fs: JSRuntimeFS; git: Git; dir: string; - constructor(fs: JSRuntimeFS) { - this.fs = fs; - this.git = new Git(fs, 'https://cors.isomorphic-git.org'); + constructor(options: ProjectsManagerOptions) { + this.fs = options.fs; + this.git = options.git; this.dir = '/projects'; } diff --git a/src/lib/commands/git.test.ts b/src/lib/commands/git.test.ts index c05b6bed..4ecf4acd 100644 --- a/src/lib/commands/git.test.ts +++ b/src/lib/commands/git.test.ts @@ -40,7 +40,16 @@ describe('GitCommand', () => { beforeEach(() => { mockFS = createMockFS(); - const git = new Git(mockFS); + const mockNostr = { + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), + } as unknown as import('@nostrify/nostrify').NPool; + const git = new Git({ fs: mockFS, nostr: mockNostr }); gitCommand = new GitCommand({ git, fs: mockFS, cwd: testCwd }); }); diff --git a/src/lib/git.example.ts b/src/lib/git.example.ts deleted file mode 100644 index 93f73986..00000000 --- a/src/lib/git.example.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { Git } from './git'; -import type { JSRuntimeFS } from './JSRuntime'; - -/** - * Example usage of the Git class - */ -export async function exampleGitUsage(fs: JSRuntimeFS) { - // Create a Git instance with fs and optional CORS proxy - const git = new Git(fs, 'https://cors.isomorphic-git.org'); - - // Initialize a new repository - await git.init({ - dir: '/my-project', - defaultBranch: 'main', - }); - - // Set up configuration - await git.setConfig({ - dir: '/my-project', - path: 'user.name', - value: 'John Doe', - }); - - await git.setConfig({ - dir: '/my-project', - path: 'user.email', - value: 'john@example.com', - }); - - // Add files to the index - await git.add({ - dir: '/my-project', - filepath: 'README.md', - }); - - // Make a commit - await git.commit({ - dir: '/my-project', - message: 'Initial commit', - author: { - name: 'John Doe', - email: 'john@example.com', - }, - }); - - // Get repository status - const statusMatrix = await git.statusMatrix({ - dir: '/my-project', - }); - - // List branches - const branches = await git.listBranches({ - dir: '/my-project', - }); - - // Get commit log - const commits = await git.log({ - dir: '/my-project', - depth: 10, - }); - - // Clone a repository - await git.clone({ - dir: '/cloned-project', - url: 'https://github.com/user/repo.git', - singleBranch: true, - depth: 1, - }); - - // Add a remote - await git.addRemote({ - dir: '/my-project', - remote: 'origin', - url: 'https://github.com/user/my-project.git', - }); - - // Push to remote (requires authentication) - try { - await git.push({ - dir: '/my-project', - remote: 'origin', - ref: 'main', - // onAuth would be needed for authentication - }); - } catch (error) { - console.log('Push failed (likely due to authentication):', error); - } - - return { - statusMatrix, - branches, - commits, - }; -} - -/** - * Example for GitHub/GitLab repositories with CORS proxy - */ -export function createGitForGitHub(fs: JSRuntimeFS) { - return new Git(fs, 'https://cors.isomorphic-git.org'); -} - -/** - * Example for self-hosted Git servers without CORS proxy - */ -export function createGitForSelfHosted(fs: JSRuntimeFS) { - return new Git(fs); // No CORS proxy needed -} \ No newline at end of file diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index bdf44f80..4958c69e 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { Git } from './git'; import git from 'isomorphic-git'; +import type { NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; // Mock isomorphic-git @@ -9,18 +10,30 @@ vi.mock('isomorphic-git/http/web'); const mockGit = vi.mocked(git); +const createMockNostr = (): NPool => ({ + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), +}) as unknown as NPool; + describe('Git', () => { - const mockFS = {} as JSRuntimeFS; + const fs = {} as JSRuntimeFS; + const nostr = createMockNostr(); + const corsProxy = 'https://cors.example.com'; let gitInstance: Git; beforeEach(() => { vi.clearAllMocks(); - gitInstance = new Git(mockFS, 'https://cors.example.com'); + gitInstance = new Git({ fs, nostr, corsProxy }); }); describe('constructor', () => { it('creates instance with default regex when none provided', () => { - const git = new Git(mockFS, 'https://cors.example.com'); + const git = new Git({ fs, nostr, corsProxy }); expect(git).toBeInstanceOf(Git); }); @@ -39,7 +52,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -54,7 +67,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -69,7 +82,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -84,7 +97,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -138,7 +151,7 @@ describe('Git', () => { }); expect(mockGit.fetch).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -153,7 +166,7 @@ describe('Git', () => { }); expect(mockGit.fetch).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', diff --git a/src/lib/git.ts b/src/lib/git.ts index cfb7dd20..8e2dec5f 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -1,7 +1,14 @@ import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; +import type { NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; +export interface GitOptions { + fs: JSRuntimeFS; + nostr: NPool; + corsProxy?: string; +} + /** * Git class that wraps isomorphic-git and provides a cleaner interface. * Instantiate with an fs implementation, optional corsProxy string, and optional corsProxyRegex. @@ -10,11 +17,13 @@ import type { JSRuntimeFS } from './JSRuntime'; */ export class Git { private fs: JSRuntimeFS; + private nostr: NPool; private corsProxy?: string; - constructor(fs: JSRuntimeFS, corsProxy?: string) { - this.fs = fs; - this.corsProxy = corsProxy; + constructor(options: GitOptions) { + this.fs = options.fs; + this.nostr = options.nostr; + this.corsProxy = options.corsProxy; } // Repository initialization and configuration diff --git a/src/lib/tools/ShellTool.example.ts b/src/lib/tools/ShellTool.example.ts deleted file mode 100644 index fbd311b3..00000000 --- a/src/lib/tools/ShellTool.example.ts +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Example usage of the ShellTool - * - * This file demonstrates how to use the ShellTool to execute shell commands - * in your application. The ShellTool provides a safe, sandboxed environment - * for running basic file operations. - */ - -import { ShellTool } from './ShellTool'; -import { Git } from '../git'; -import type { JSRuntimeFS } from '../JSRuntime'; - -/** - * Example function showing how to use ShellTool - */ -export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) { - // Create a shell tool instance - const shell = new ShellTool(fs, projectRoot, new Git(fs)); - - console.log('Available commands:', shell.getAvailableCommands()); - console.log('Current directory:', shell.getCurrentWorkingDirectory()); - - // Example 1: Display current directory - console.log('\n--- Example 1: Show current directory ---'); - const pwdResult = await shell.execute({ command: 'pwd' }); - console.log(pwdResult); - - // Example 2: List directory contents - console.log('\n--- Example 2: List files ---'); - const lsResult = await shell.execute({ command: 'ls' }); - console.log(lsResult); - - // Example 3: List with long format - console.log('\n--- Example 3: List with details ---'); - const lsLongResult = await shell.execute({ command: 'ls -l' }); - console.log(lsLongResult); - - // Example 4: Display a file - console.log('\n--- Example 4: Display package.json ---'); - const catResult = await shell.execute({ command: 'cat package.json' }); - console.log(catResult); - - // Example 5: Echo text - console.log('\n--- Example 5: Echo message ---'); - const echoResult = await shell.execute({ command: 'echo Hello, World!' }); - console.log(echoResult); - - // Example 6: Change directory - console.log('\n--- Example 6: Change directory ---'); - const cdResult = await shell.execute({ command: 'cd src' }); - console.log(cdResult); - console.log('New directory:', shell.getCurrentWorkingDirectory()); - - // Example 7: Handle errors gracefully - console.log('\n--- Example 7: Handle non-existent file ---'); - const errorResult = await shell.execute({ - command: 'cat nonexistent-file.txt' - }); - console.log(errorResult); - - // Example 8: Try unknown command - console.log('\n--- Example 8: Unknown command ---'); - const unknownResult = await shell.execute({ - command: 'unknown-command arg1 arg2' - }); - console.log(unknownResult); - - // Example 9: Compound commands with && - console.log('\n--- Example 9: Compound commands with && ---'); - const andResult = await shell.execute({ - command: 'pwd && echo "Current directory listed above"' - }); - console.log(andResult); - - // Example 10: Compound commands with || - console.log('\n--- Example 10: Compound commands with || ---'); - const orResult = await shell.execute({ - command: 'cat nonexistent.txt || echo "File not found, showing fallback message"' - }); - console.log(orResult); - - // Example 11: Sequential commands with ; - console.log('\n--- Example 11: Sequential commands with ; ---'); - const sequentialResult = await shell.execute({ - command: 'echo "First command"; echo "Second command"; pwd' - }); - console.log(sequentialResult); - - // Example 12: Pipe commands - console.log('\n--- Example 12: Pipe commands ---'); - const pipeResult = await shell.execute({ - command: 'echo "line1\nline2\nline3\nline4\nline5" | head -n 3' - }); - console.log(pipeResult); - - // Example 13: Complex pipe chain - console.log('\n--- Example 13: Complex pipe chain ---'); - const complexPipeResult = await shell.execute({ - command: 'echo "apple\nbanana\napple\ncherry\nbanana\napple" | sort | uniq' - }); - console.log(complexPipeResult); - - // Example 14: Mixed compound operators - console.log('\n--- Example 14: Mixed compound operators ---'); - const mixedResult = await shell.execute({ - command: 'echo "Processing..." && echo "data1\ndata2\ndata3" | wc -l && echo "Done!"' - }); - console.log(mixedResult); -} - -/** - * Example React hook for using ShellTool - */ -export function useShell(fs: JSRuntimeFS, cwd: string) { - const shell = new ShellTool(fs, cwd, new Git(fs)); - - const executeCommand = async (command: string): Promise => { - try { - return await shell.execute({ command }); - } catch (error) { - return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`; - } - }; - - return { - executeCommand, - getCurrentDirectory: () => shell.getCurrentWorkingDirectory(), - setCurrentDirectory: (newCwd: string) => shell.setCurrentWorkingDirectory(newCwd), - getAvailableCommands: () => shell.getAvailableCommands(), - }; -} - -/** - * Example integration with AI tools - * Shows how the ShellTool can be used as part of an AI assistant - */ -export class AIShellIntegration { - private shell: ShellTool; - - constructor(fs: JSRuntimeFS, projectRoot: string) { - this.shell = new ShellTool(fs, projectRoot, new Git(fs)); - } - - /** - * Process natural language requests and convert to shell commands - */ - async processNaturalLanguageRequest(request: string): Promise { - const lowerRequest = request.toLowerCase(); - - // Simple pattern matching for demonstration - if (lowerRequest.includes('show me') && lowerRequest.includes('file')) { - // Extract filename from request - const fileMatch = request.match(/file\s+["']?([^"'\s]+)["']?/i); - if (fileMatch) { - const filename = fileMatch[1]; - return await this.shell.execute({ command: `cat ${filename}` }); - } - } - - if (lowerRequest.includes('list') && lowerRequest.includes('command')) { - const commands = this.shell.getAvailableCommands(); - return commands.map(cmd => `${cmd.name}: ${cmd.description}`).join('\n'); - } - - if (lowerRequest.includes('current') && lowerRequest.includes('directory')) { - return `Current directory: ${this.shell.getCurrentWorkingDirectory()}`; - } - - return 'I can help you with file operations. Try asking me to "show me a file" or "list available commands".'; - } -} - -/** - * Example CLI-like interface - */ -export class SimpleCLI { - private shell: ShellTool; - private history: string[] = []; - - constructor(fs: JSRuntimeFS, projectRoot: string) { - this.shell = new ShellTool(fs, projectRoot, new Git(fs)); - } - - async executeCommand(command: string): Promise { - this.history.push(command); - - // Handle built-in commands - if (command.trim() === 'help') { - const commands = this.shell.getAvailableCommands(); - return [ - 'Available commands:', - ...commands.map(cmd => ` ${cmd.usage} - ${cmd.description}`), - '', - 'Built-in commands:', - ' help - Show this help message', - ' history - Show command history', - ' pwd - Show current directory', - ].join('\n'); - } - - if (command.trim() === 'history') { - return this.history.map((cmd, i) => `${i + 1}: ${cmd}`).join('\n'); - } - - if (command.trim() === 'pwd') { - return this.shell.getCurrentWorkingDirectory(); - } - - // Execute through shell tool - return await this.shell.execute({ command }); - } - - getHistory(): string[] { - return [...this.history]; - } - - clearHistory(): void { - this.history = []; - } -} \ No newline at end of file diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index 38b7bba0..ba5d4e65 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ShellTool } from './ShellTool'; import { Git } from '../git'; import type { JSRuntimeFS } from '../JSRuntime'; +import { NPool } from '@nostrify/nostrify'; // Mock filesystem const createMockFS = (): JSRuntimeFS => ({ @@ -18,15 +19,27 @@ const createMockFS = (): JSRuntimeFS => ({ symlink: vi.fn(), }); +const createMockNostr = (): NPool => ({ + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), +}) as unknown as NPool; + describe('ShellTool', () => { let mockFS: JSRuntimeFS; let mockGit: Git; + let mockNostr: NPool; let shellTool: ShellTool; const testCwd = '/test/dir'; beforeEach(() => { mockFS = createMockFS(); - mockGit = new Git(mockFS); + mockNostr = createMockNostr(); + mockGit = new Git({ fs: mockFS, nostr: mockNostr }); shellTool = new ShellTool(mockFS, testCwd, mockGit); });