diff --git a/package-lock.json b/package-lock.json index 9673d9dd..834e5fc3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,13 @@ { - "name": "mkstack", + "name": "shakespeare", "version": "0.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "mkstack", + "name": "shakespeare", "version": "0.0.0", + "license": "AGPL-3.0-or-later", "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", diff --git a/src/App.tsx b/src/App.tsx index 87624070..45d771d1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -12,6 +12,7 @@ import { TooltipProvider } from "@/components/ui/tooltip"; import { NostrLoginProvider } from '@nostrify/react/login'; import { AppProvider } from '@/components/AppProvider'; import { AppConfig } from '@/contexts/AppContext'; +import { useAppContext } from '@/hooks/useAppContext'; import { AISettingsProvider } from '@/components/AISettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider'; import { DeploySettingsProvider } from '@/components/DeploySettingsProvider'; @@ -51,6 +52,9 @@ const defaultConfig: AppConfig = { showcaseEnabled: true, showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc", ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"], + fsPathProjects: "/projects", + fsPathConfig: "/config", + fsPathTmp: "/tmp", }; const presetRelays = [ @@ -65,13 +69,15 @@ const lightningFS = new LightningFS('shakespeare-fs'); const fs = new LightningFSAdapter(lightningFS.promises); // Component to handle filesystem cleanup on startup -// Automatically removes files older than 1 hour from /tmp directory +// Automatically removes files older than 1 hour from tmp directory function FSCleanupHandler() { + const { config } = useAppContext(); + useEffect(() => { // Run cleanup on application startup to remove stale temporary files // This helps prevent the VFS from accumulating old files over time - cleanupTmpDirectory(fs).catch(console.error); - }, []); + cleanupTmpDirectory(fs, config.fsPathTmp).catch(console.error); + }, [config.fsPathTmp]); return null; } @@ -82,8 +88,8 @@ export function App() { - + diff --git a/src/components/AISettingsProvider.tsx b/src/components/AISettingsProvider.tsx index cb799e6f..b808b098 100644 --- a/src/components/AISettingsProvider.tsx +++ b/src/components/AISettingsProvider.tsx @@ -2,6 +2,7 @@ import { useQueryClient } from '@tanstack/react-query'; import { ReactNode, useState, useEffect } from 'react'; import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { readAISettings, writeAISettings } from '@/lib/configUtils'; interface AISettingsProviderProps { @@ -16,6 +17,7 @@ const DEFAULT_SETTINGS: AISettings = { export function AISettingsProvider({ children }: AISettingsProviderProps) { const queryClient = useQueryClient(); const { fs } = useFS(); + const { configPath } = useFSPaths(); const [settings, setSettings] = useState(DEFAULT_SETTINGS); const [isInitialized, setIsInitialized] = useState(false); @@ -23,7 +25,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { useEffect(() => { const initializeSettings = async () => { try { - const settings = await readAISettings(fs); + const settings = await readAISettings(fs, configPath); setSettings(settings); } catch (error) { console.error('Failed to initialize AI settings:', error); @@ -34,7 +36,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { }; initializeSettings(); - }, [fs]); + }, [fs, configPath]); // Save settings to VFS whenever they change (but not during initialization) useEffect(() => { @@ -42,14 +44,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { const saveSettings = async () => { try { - await writeAISettings(fs, settings); + await writeAISettings(fs, settings, configPath); } catch (error) { console.error('Failed to save AI settings:', error); } }; saveSettings(); - }, [fs, settings, isInitialized]); + }, [fs, settings, isInitialized, configPath]); const updateSettings = (newSettings: Partial) => { setSettings(prev => ({ ...prev, ...newSettings })); diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index b3c20b2e..0e4b3126 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -27,6 +27,9 @@ const AppConfigSchema = z.object({ showcaseEnabled: z.boolean(), showcaseModerator: z.string(), ngitServers: z.array(z.string()), + fsPathProjects: z.string().min(1), + fsPathConfig: z.string().min(1), + fsPathTmp: z.string().min(1), }) satisfies z.ZodType; export function AppProvider(props: AppProviderProps) { diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index b7415c2f..f63a1e9a 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -24,6 +24,7 @@ import { useDeploySettings } from '@/hooks/useDeploySettings'; import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useAppContext } from '@/hooks/useAppContext'; import { useNostr } from '@nostrify/react'; import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy'; @@ -115,6 +116,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId); const { user } = useCurrentUser(); const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const { config } = useAppContext(); const { nostr } = useNostr(); @@ -165,7 +167,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setDeployResult(null); try { - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; let adapter: DeployAdapter; diff --git a/src/components/DeploySettingsProvider.tsx b/src/components/DeploySettingsProvider.tsx index c5f67a01..dc0d871d 100644 --- a/src/components/DeploySettingsProvider.tsx +++ b/src/components/DeploySettingsProvider.tsx @@ -1,6 +1,7 @@ import { useState, useEffect, useMemo, type ReactNode } from 'react'; import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils'; const DEFAULT_SETTINGS: DeploySettings = { @@ -9,6 +10,7 @@ const DEFAULT_SETTINGS: DeploySettings = { export function DeploySettingsProvider({ children }: { children: ReactNode }) { const { fs } = useFS(); + const { configPath } = useFSPaths(); const [settings, setSettings] = useState(DEFAULT_SETTINGS); const [isInitialized, setIsInitialized] = useState(false); @@ -16,7 +18,7 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) { useEffect(() => { const initializeSettings = async () => { try { - const settings = await readDeploySettings(fs); + const settings = await readDeploySettings(fs, configPath); setSettings(settings); } catch (error) { console.error('Failed to initialize deploy settings:', error); @@ -27,7 +29,7 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) { }; initializeSettings(); - }, [fs]); + }, [fs, configPath]); // Save settings to VFS whenever they change (but not during initialization) useEffect(() => { @@ -35,14 +37,14 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) { const saveSettings = async () => { try { - await writeDeploySettings(fs, settings); + await writeDeploySettings(fs, settings, configPath); } catch (error) { console.error('Failed to save deploy settings:', error); } }; saveSettings(); - }, [fs, settings, isInitialized]); + }, [fs, settings, isInitialized, configPath]); const updateSettings = (updates: Partial) => { setSettings(prev => ({ ...prev, ...updates })); diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 6f3f0cd8..2a12c366 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -51,6 +51,7 @@ import { import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostr } from '@nostrify/react'; @@ -91,6 +92,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { toast } = useToast(); const { user } = useCurrentUser(); const { nostr } = useNostr(); @@ -98,7 +100,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl); const { config } = useAppContext(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; // Initialize origin URL from git status useEffect(() => { diff --git a/src/components/GitSettingsProvider.test.tsx b/src/components/GitSettingsProvider.test.tsx index 6a72ab8f..007f0667 100644 --- a/src/components/GitSettingsProvider.test.tsx +++ b/src/components/GitSettingsProvider.test.tsx @@ -171,7 +171,8 @@ describe('GitSettingsProvider', () => { password: 'test-token', } } - }) + }), + '/config' // configPath ); }); }); diff --git a/src/components/GitSettingsProvider.tsx b/src/components/GitSettingsProvider.tsx index 227e1d8d..f9fae98c 100644 --- a/src/components/GitSettingsProvider.tsx +++ b/src/components/GitSettingsProvider.tsx @@ -1,6 +1,7 @@ import { ReactNode, useState, useEffect } from 'react'; import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { readGitSettings, writeGitSettings } from '@/lib/configUtils'; interface GitSettingsProviderProps { @@ -14,6 +15,7 @@ const DEFAULT_SETTINGS: GitSettings = { export function GitSettingsProvider({ children }: GitSettingsProviderProps) { const { fs } = useFS(); + const { configPath } = useFSPaths(); const [settings, setSettings] = useState(DEFAULT_SETTINGS); const [isInitialized, setIsInitialized] = useState(false); @@ -21,7 +23,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { useEffect(() => { const initializeSettings = async () => { try { - const settings = await readGitSettings(fs); + const settings = await readGitSettings(fs, configPath); setSettings(settings); } catch (error) { console.error('Failed to initialize Git settings:', error); @@ -32,7 +34,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { }; initializeSettings(); - }, [fs]); + }, [fs, configPath]); // Save settings to VFS whenever they change (but not during initialization) useEffect(() => { @@ -40,14 +42,14 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { const saveSettings = async () => { try { - await writeGitSettings(fs, settings); + await writeGitSettings(fs, settings, configPath); } catch (error) { console.error('Failed to save Git settings:', error); } }; saveSettings(); - }, [fs, settings, isInitialized]); + }, [fs, settings, isInitialized, configPath]); const updateSettings = (newSettings: Partial) => { setSettings(prev => ({ ...prev, ...newSettings })); diff --git a/src/components/ProjectDetailsDialog.tsx b/src/components/ProjectDetailsDialog.tsx index ae509513..c6af9d0f 100644 --- a/src/components/ProjectDetailsDialog.tsx +++ b/src/components/ProjectDetailsDialog.tsx @@ -23,6 +23,7 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useNavigate } from 'react-router-dom'; import { @@ -50,6 +51,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel const [newProjectName, setNewProjectName] = useState(project.id); const { toast } = useToast(); const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const projectsManager = useProjectsManager(); const navigate = useNavigate(); const queryClient = useQueryClient(); @@ -143,7 +145,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel setIsExporting(true); try { const zip = new JSZip(); - const projectPath = `/projects/${project.id}`; + const projectPath = `${projectsPath}/${project.id}`; // Recursive function to add files and directories to zip from a specific project const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => { diff --git a/src/components/SessionManagerProvider.tsx b/src/components/SessionManagerProvider.tsx index a8fdbdae..558a4c8b 100644 --- a/src/components/SessionManagerProvider.tsx +++ b/src/components/SessionManagerProvider.tsx @@ -2,6 +2,7 @@ import { ReactNode, useMemo, useEffect } from 'react'; import { SessionManagerContext } from '@/contexts/SessionManagerContext'; import { SessionManager } from '@/lib/SessionManager'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -16,6 +17,7 @@ interface SessionManagerProviderProps { */ export function SessionManagerProvider({ children }: SessionManagerProviderProps) { const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const { settings } = useAISettings(); const { models } = useProviderModels(); const { user, metadata } = useCurrentUser(); @@ -24,8 +26,8 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps const sessionManager = useMemo(() => { const getProviderModels = () => models; const getCurrentUser = () => ({ user, metadata }); - return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy); - }, [fs, settings, models, user, metadata, config.corsProxy]); + return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath); + }, [fs, settings, models, user, metadata, config.corsProxy, projectsPath]); // Cleanup on unmount useEffect(() => { diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f7373b5b..23b46ecf 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -7,6 +7,7 @@ import { OnboardingDialog } from '@/components/OnboardingDialog'; import { Loader2, ChevronDown } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useAppContext } from '@/hooks/useAppContext'; @@ -75,6 +76,7 @@ export const ChatPane = forwardRef(({ const { user } = useCurrentUser(); const { models } = useProviderModels(); const { config } = useAppContext(); + const { projectsPath, tmpPath } = useFSPaths(); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [isDragOver, setIsDragOver] = useState(false); const [scrolledProjects] = useState(() => new Set()); @@ -133,14 +135,14 @@ export const ChatPane = forwardRef(({ }, [projectId, providerModel]); // Initialize AI chat with tools - const cwd = `/projects/${projectId}`; + const cwd = `${projectsPath}/${projectId}`; const esmUrlRef = useRef(config.esmUrl); const customTools = useMemo(() => { const baseTools = { git_commit: new GitCommitTool(fs, cwd, git), - text_editor_view: new TextEditorViewTool(fs, cwd), - text_editor_write: new TextEditorWriteTool(fs, cwd), - text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd), + text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }), + text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath }), + text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath }), npm_add_package: new NpmAddPackageTool(fs, cwd), npm_remove_package: new NpmRemovePackageTool(fs, cwd), build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current), @@ -165,7 +167,7 @@ export const ChatPane = forwardRef(({ } return baseTools; - }, [fs, git, cwd, user, projectId]); + }, [fs, git, cwd, user, projectId, projectsPath, tmpPath]); // Convert tools to OpenAI format const tools = useMemo(() => { @@ -438,7 +440,7 @@ export const ChatPane = forwardRef(({ if (attachedFiles.length > 0) { const filePromises = attachedFiles.map(async (file) => { try { - const savedPath = await saveFileToTmp(fs, file); + const savedPath = await saveFileToTmp(fs, file, tmpPath); return `Added file: ${savedPath}`; } catch (error) { console.error('Failed to save file:', error); @@ -463,7 +465,7 @@ export const ChatPane = forwardRef(({ // Send as text parts if we have multiple parts, otherwise send as string for simplicity const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts; await sendMessage(messageContent, modelToUse); - }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]); + }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]); // Handle textarea focus - show onboarding if not configured const handleTextareaFocus = useCallback(() => { diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index fe6486f2..a802b8a9 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,6 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages'; import { useConsoleError } from '@/hooks/useConsoleError'; import { useBuildProject } from '@/hooks/useBuildProject'; @@ -89,6 +90,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o const [deployDialogOpen, setDeployDialogOpen] = useState(false); const iframeRef = useRef(null); const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const projectsManager = useProjectsManager(); // Use console error state from provider @@ -506,7 +508,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o if (!selectedFile) return; try { - await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content); + await fs.writeFile(`${projectsPath}/${projectId}/${selectedFile}`, content); setFileContent(content); // Automatically trigger a rebuild after saving a file diff --git a/src/components/Terminal.tsx b/src/components/Terminal.tsx index c24ebd29..8e38b884 100644 --- a/src/components/Terminal.tsx +++ b/src/components/Terminal.tsx @@ -5,6 +5,7 @@ import { Copy } from 'lucide-react'; import { cn } from '@/lib/utils'; import { ShellTool } from '@/lib/tools/ShellTool'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useGit } from '@/hooks/useGit'; import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml'; @@ -32,11 +33,12 @@ export function Terminal({ projectId, className }: TerminalProps) { const shellToolRef = useRef(null); const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const { git } = useGit(); // Initialize ShellTool useEffect(() => { - shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git); + shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git); // Add welcome message setLines([{ @@ -45,7 +47,7 @@ export function Terminal({ projectId, className }: TerminalProps) { content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`, timestamp: new Date() }]); - }, [projectId, fs, git]); + }, [projectId, fs, git, projectsPath]); // Auto-scroll to bottom when new lines are added or execution state changes useEffect(() => { @@ -190,7 +192,7 @@ export function Terminal({ projectId, className }: TerminalProps) { ${' '} ) : null} - {containsAnsiCodes(line.content) + {containsAnsiCodes(line.content) ? : line.content} diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index 5ccc3406..60079e62 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useFS } from '@/hooks/useFS'; import { useToast } from '@/hooks/useToast'; import { useGitStatus } from '@/hooks/useGitStatus'; @@ -45,6 +46,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange const [isRollingBack, setIsRollingBack] = useState(null); const [expandedCommits, setExpandedCommits] = useState>(new Set()); const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const { git } = useGit(); const { toast } = useToast(); const navigate = useNavigate(); @@ -55,7 +57,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange setError(null); try { - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; // Check if git repository exists try { @@ -78,7 +80,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange } finally { setIsLoading(false); } - }, [git, projectId]); + }, [git, projectId, projectsPath]); const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => { if (!fs) return; @@ -86,7 +88,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange setIsRollingBack(targetCommit.oid); try { - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; // Get the current HEAD commit const currentCommit = await git.resolveRef({ @@ -227,7 +229,7 @@ ${commitsToRevert.map(c => { } finally { setIsRollingBack(null); } - }, [git, fs, projectId, toast, navigate, setIsOpen]); + }, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]); const resetToHead = useCallback(async () => { if (!fs) return; @@ -235,7 +237,7 @@ ${commitsToRevert.map(c => { setIsRollingBack('HEAD'); try { - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; // Get the current HEAD commit const headCommit = await git.resolveRef({ @@ -326,7 +328,7 @@ ${commitsToRevert.map(c => { } finally { setIsRollingBack(null); } - }, [git, fs, projectId, toast, navigate, setIsOpen]); + }, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]); useEffect(() => { if (isOpen) { diff --git a/src/components/git/AnnounceRepositoryDialog.tsx b/src/components/git/AnnounceRepositoryDialog.tsx index a2f3a2f0..e59c2606 100644 --- a/src/components/git/AnnounceRepositoryDialog.tsx +++ b/src/components/git/AnnounceRepositoryDialog.tsx @@ -24,6 +24,7 @@ import { Megaphone, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostr } from '@/hooks/useNostr'; import { useToast } from '@/hooks/useToast'; @@ -59,11 +60,12 @@ export function AnnounceRepositoryDialog({ const [newRelay, setNewRelay] = useState(''); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { user } = useCurrentUser(); const { nostr } = useNostr(); const { toast } = useToast(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; useEffect(() => { if (open !== undefined) { diff --git a/src/components/git/BranchManager.tsx b/src/components/git/BranchManager.tsx index 42e8b42e..42e0801a 100644 --- a/src/components/git/BranchManager.tsx +++ b/src/components/git/BranchManager.tsx @@ -30,6 +30,7 @@ import { ArrowUpRight, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; @@ -59,8 +60,9 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran const [switchingToBranch, setSwitchingToBranch] = useState(null); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { toast } = useToast(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; const loadBranches = useCallback(async () => { setIsLoading(true); diff --git a/src/components/git/CompareView.tsx b/src/components/git/CompareView.tsx index 169008cf..5231150f 100644 --- a/src/components/git/CompareView.tsx +++ b/src/components/git/CompareView.tsx @@ -10,6 +10,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { GitCompare, Loader2, GitCommit, FileIcon } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { DiffViewer } from './DiffViewer'; @@ -38,8 +39,9 @@ export function CompareView({ projectId }: CompareViewProps) { } | null>(null); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { toast } = useToast(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; const loadReferences = useCallback(async () => { setIsLoading(true); diff --git a/src/components/git/DiffViewer.tsx b/src/components/git/DiffViewer.tsx index 5f540035..816c5b24 100644 --- a/src/components/git/DiffViewer.tsx +++ b/src/components/git/DiffViewer.tsx @@ -15,6 +15,7 @@ import { Check, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useFS } from '@/hooks/useFS'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; @@ -57,9 +58,10 @@ export function DiffViewer({ projectId, compareFrom = 'HEAD', compareTo, filepat const [copiedHunk, setCopiedHunk] = useState(null); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { fs } = useFS(); const { toast } = useToast(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise => { // Get list of files from both refs and find differences diff --git a/src/components/git/GitManagementDialog.tsx b/src/components/git/GitManagementDialog.tsx index 2c4a01b5..094d8c8f 100644 --- a/src/components/git/GitManagementDialog.tsx +++ b/src/components/git/GitManagementDialog.tsx @@ -20,8 +20,9 @@ import { DiffViewer } from './DiffViewer'; import { PullRequestForm } from './PullRequestForm'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; -interface GitManagementDialogProps { +interface GitManagementDialogProps{ projectId: string; children?: React.ReactNode; open?: boolean; @@ -39,7 +40,8 @@ export function GitManagementDialog({ const [activeTab, setActiveTab] = useState(defaultTab); const [remoteUrl, setRemoteUrl] = useState(null); const { git } = useGit(); - const projectPath = `/projects/${projectId}`; + const { projectsPath } = useFSPaths(); + const projectPath = `${projectsPath}/${projectId}`; const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); diff --git a/src/components/git/MergeDialog.tsx b/src/components/git/MergeDialog.tsx index 8ebc3a3f..8ba74c59 100644 --- a/src/components/git/MergeDialog.tsx +++ b/src/components/git/MergeDialog.tsx @@ -29,6 +29,7 @@ import { AlertTriangle, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { useSearchParams } from 'react-router-dom'; @@ -77,9 +78,10 @@ export function MergeDialog({ const [mergeComplete, setMergeComplete] = useState(false); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { toast } = useToast(); const [searchParams, setSearchParams] = useSearchParams(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; useEffect(() => { if (open !== undefined) { diff --git a/src/components/git/PullRequestDialog.tsx b/src/components/git/PullRequestDialog.tsx index ee07a558..4219837a 100644 --- a/src/components/git/PullRequestDialog.tsx +++ b/src/components/git/PullRequestDialog.tsx @@ -32,6 +32,7 @@ import { GitFork, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useToast } from '@/hooks/useToast'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -84,12 +85,13 @@ export function PullRequestDialog({ const [error, setError] = useState(null); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { settings } = useGitSettings(); const { toast } = useToast(); const { user } = useCurrentUser(); const { nostr } = useNostr(); const { config } = useAppContext(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; useEffect(() => { if (open !== undefined) { diff --git a/src/components/git/PullRequestForm.tsx b/src/components/git/PullRequestForm.tsx index cf290825..e5456cf1 100644 --- a/src/components/git/PullRequestForm.tsx +++ b/src/components/git/PullRequestForm.tsx @@ -22,6 +22,7 @@ import { GitFork, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useToast } from '@/hooks/useToast'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; @@ -59,9 +60,10 @@ export function PullRequestForm({ projectId, currentBranch, remoteUrl }: PullReq const [error, setError] = useState(null); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const { settings } = useGitSettings(); const { toast } = useToast(); - const projectPath = `/projects/${projectId}`; + const projectPath = `${projectsPath}/${projectId}`; // All the helper functions from PullRequestDialog can be reused here // (parseRemoteUrl, checkPushPermissions, ensureFork, etc.) diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 863746c4..d2031044 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -25,6 +25,12 @@ export interface AppConfig { showcaseModerator: string; /** Nostr Git Servers (hostnames) */ ngitServers: string[]; + /** VFS path for projects directory */ + fsPathProjects: string; + /** VFS path for config directory */ + fsPathConfig: string; + /** VFS path for temporary files directory */ + fsPathTmp: string; } export interface AppContextType { diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 81d26571..5001992b 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -50,6 +50,9 @@ describe('useAIProjectId', () => { showcaseEnabled: true, showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', }, updateConfig: vi.fn(), }); diff --git a/src/hooks/useBuildProject.ts b/src/hooks/useBuildProject.ts index 6cb96e2b..7246ed71 100644 --- a/src/hooks/useBuildProject.ts +++ b/src/hooks/useBuildProject.ts @@ -1,17 +1,19 @@ import { useMutation } from "@tanstack/react-query"; import { buildProject } from "@/lib/build"; import { useFS } from "./useFS"; +import { useFSPaths } from "./useFSPaths"; import { useAppContext } from "./useAppContext"; export function useBuildProject(projectId: string) { const { fs } = useFS(); + const { projectsPath } = useFSPaths(); const { config } = useAppContext(); return useMutation({ mutationFn: async () => { return await buildProject({ fs, - projectPath: `/projects/${projectId}`, + projectPath: `${projectsPath}/${projectId}`, domParser: new DOMParser(), esmUrl: config.esmUrl, }); diff --git a/src/hooks/useFSPaths.ts b/src/hooks/useFSPaths.ts new file mode 100644 index 00000000..7088a134 --- /dev/null +++ b/src/hooks/useFSPaths.ts @@ -0,0 +1,19 @@ +import { useAppContext } from '@/hooks/useAppContext'; + +/** + * Hook to access configured virtual filesystem paths + * + * @returns Object containing VFS path configurations + */ +export function useFSPaths() { + const { config } = useAppContext(); + + return { + /** Projects directory path (default: /projects) */ + projectsPath: config.fsPathProjects, + /** Config directory path (default: /config) */ + configPath: config.fsPathConfig, + /** Temporary files directory path (default: /tmp) */ + tmpPath: config.fsPathTmp, + }; +} diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index 2717dae7..5de6a24b 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -42,6 +42,9 @@ function createWrapper(corsProxy: string) { showcaseEnabled: true, showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', }; return createElement( diff --git a/src/hooks/useGitStatus.ts b/src/hooks/useGitStatus.ts index d12a7c9f..a4bbaf8f 100644 --- a/src/hooks/useGitStatus.ts +++ b/src/hooks/useGitStatus.ts @@ -1,5 +1,6 @@ import { useQuery } from '@tanstack/react-query'; import { useGit } from './useGit'; +import { useFSPaths } from './useFSPaths'; interface GitFileChange { filepath: string; @@ -41,6 +42,7 @@ interface GitStatus { export function useGitStatus(projectId: string | null) { const { git } = useGit(); + const { projectsPath } = useFSPaths(); return useQuery({ queryKey: ['git-status', projectId], @@ -61,7 +63,7 @@ export function useGitStatus(projectId: string | null) { } try { - const cwd = `/projects/${projectId}`; + const cwd = `${projectsPath}/${projectId}`; // Check if we're in a git repository try { diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index b2fe8cef..419eb752 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -1,5 +1,6 @@ import { useState, useEffect, useCallback } from 'react'; import { useFS } from './useFS'; +import { useFSPaths } from './useFSPaths'; export interface ShakespeareProjectConfig { type: 'shakespeare'; @@ -43,10 +44,11 @@ export interface ProjectDeploySettings { */ export function useProjectDeploySettings(projectId: string) { const fs = useFS(); + const { projectsPath } = useFSPaths(); const [settings, setSettings] = useState({ providers: {} }); const [isLoading, setIsLoading] = useState(true); - const settingsPath = `/projects/${projectId}/.git/shakespeare/deploy.json`; + const settingsPath = `${projectsPath}/${projectId}/.git/shakespeare/deploy.json`; const loadSettings = useCallback(async () => { try { @@ -78,7 +80,7 @@ export function useProjectDeploySettings(projectId: string) { const saveSettings = async (newSettings: ProjectDeploySettings) => { try { // Ensure .git/shakespeare directory exists - const shakespeareDir = `/projects/${projectId}/.git/shakespeare`; + const shakespeareDir = `${projectsPath}/${projectId}/.git/shakespeare`; try { await fs.fs.stat(shakespeareDir); } catch { diff --git a/src/hooks/useProjectsManager.ts b/src/hooks/useProjectsManager.ts index c918bd1e..8f15bd95 100644 --- a/src/hooks/useProjectsManager.ts +++ b/src/hooks/useProjectsManager.ts @@ -1,19 +1,21 @@ import { useMemo } from 'react'; import { ProjectsManager } from '@/lib/ProjectsManager'; import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; import { useGit } from './useGit'; /** * Hook that provides a ProjectsManager instance. - * The ProjectsManager is memoized based on the fs instance. + * The ProjectsManager is memoized based on the fs instance and configured paths. */ export function useProjectsManager() { const { fs } = useFS(); const { git } = useGit(); + const { projectsPath } = useFSPaths(); const projectsManager = useMemo(() => { - return new ProjectsManager({ fs, git }); - }, [fs, git]); + return new ProjectsManager({ fs, git, projectsPath }); + }, [fs, git, projectsPath]); return projectsManager; } \ No newline at end of file diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 6dc19698..9013acea 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -19,6 +19,8 @@ export interface Project { export interface ProjectsManagerOptions { fs: JSRuntimeFS; git: Git; + /** Projects directory path (default: /projects) */ + projectsPath?: string; } export class ProjectsManager { @@ -29,7 +31,7 @@ export class ProjectsManager { constructor(options: ProjectsManagerOptions) { this.fs = options.fs; this.git = options.git; - this.dir = '/projects'; + this.dir = options.projectsPath || '/projects'; } async init() { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index d5e4a37c..302f5530 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -61,6 +61,7 @@ export class SessionManager { private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>; private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }; private corsProxy?: string; + private projectsPath: string; constructor( fs: JSRuntimeFS, @@ -68,11 +69,13 @@ export class SessionManager { getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>, getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }, corsProxy?: string, + projectsPath = '/projects', ) { this.fs = fs; this.aiSettings = aiSettings; this.getProviderModels = getProviderModels; this.getCurrentUser = getCurrentUser; + this.projectsPath = projectsPath; this.corsProxy = corsProxy; } @@ -90,7 +93,7 @@ export class SessionManager { // Try to load existing history try { - const dotAI = new DotAI(this.fs, `/projects/${projectId}`); + const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`); const lastSession = await dotAI.readLastSessionHistory(); if (lastSession) { messages = lastSession.messages; @@ -232,7 +235,7 @@ export class SessionManager { }; const systemPrompt = await makeSystemPrompt({ - cwd: `/projects/${projectId}`, + cwd: `${this.projectsPath}/${projectId}`, fs: this.fs, mode: "agent", name: "Shakespeare", @@ -568,7 +571,7 @@ export class SessionManager { if (!session) return; try { - const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`); + const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`); await dotAI.setHistory(session.sessionName, session.messages); } catch (error) { console.warn('Failed to save session history:', error); diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 4fbc10ac..12ce1b2c 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -5,10 +5,29 @@ import type { AIProvider, AISettings } from '@/contexts/AISettingsContext'; import type { GitSettings } from '@/contexts/GitSettingsContext'; import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext'; -const CONFIG_DIR = '/config'; -const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`; -const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`; -const DEPLOY_CONFIG_PATH = `${CONFIG_DIR}/deploy.json`; +/** + * Get AI config file path + * @param configPath - Custom config path (default: /config) + */ +function getAIConfigPath(configPath = '/config'): string { + return `${configPath}/ai.json`; +} + +/** + * Get Git config file path + * @param configPath - Custom config path (default: /config) + */ +function getGitConfigPath(configPath = '/config'): string { + return `${configPath}/git.json`; +} + +/** + * Get Deploy config file path + * @param configPath - Custom config path (default: /config) + */ +function getDeployConfigPath(configPath = '/config'): string { + return `${configPath}/deploy.json`; +} const aiProviderSchema: z.ZodType = z.object({ id: z.string(), @@ -91,26 +110,31 @@ const deploySettingsSchema = z.object({ /** * Ensures the config directory exists + * @param fs - Filesystem instance + * @param configPath - Custom config path (default: /config) */ -async function ensureConfigDir(fs: JSRuntimeFS): Promise { +async function ensureConfigDir(fs: JSRuntimeFS, configPath = '/config'): Promise { try { - await fs.stat(CONFIG_DIR); + await fs.stat(configPath); } catch { - await fs.mkdir(CONFIG_DIR, { recursive: true }); + await fs.mkdir(configPath, { recursive: true }); } } /** * Read AI settings from VFS + * @param fs - Filesystem instance + * @param configPath - Custom config path (default: /config) */ -export async function readAISettings(fs: JSRuntimeFS): Promise { +export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise { const defaultSettings: AISettings = { providers: [], recentlyUsedModels: [], }; try { - const content = await fs.readFile(AI_CONFIG_PATH, 'utf8'); + const aiConfigPath = getAIConfigPath(configPath); + const content = await fs.readFile(aiConfigPath, 'utf8'); const data = JSON.parse(content); return aiSettingsSchema.parse(data); } catch (error) { @@ -123,16 +147,22 @@ export async function readAISettings(fs: JSRuntimeFS): Promise { /** * Write AI settings to VFS + * @param fs - Filesystem instance + * @param settings - AI settings to write + * @param configPath - Custom config path (default: /config) */ -export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Promise { - await ensureConfigDir(fs); - await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8'); +export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings, configPath = '/config'): Promise { + await ensureConfigDir(fs, configPath); + const aiConfigPath = getAIConfigPath(configPath); + await fs.writeFile(aiConfigPath, JSON.stringify(settings, null, 2), 'utf8'); } /** * Read Git settings from VFS + * @param fs - Filesystem instance + * @param configPath - Custom config path (default: /config) */ -export async function readGitSettings(fs: JSRuntimeFS): Promise { +export async function readGitSettings(fs: JSRuntimeFS, configPath = '/config'): Promise { const defaultSettings: GitSettings = { credentials: {}, hostTokens: {}, @@ -141,7 +171,8 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise { // Try to read from VFS first try { - const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8'); + const gitConfigPath = getGitConfigPath(configPath); + const content = await fs.readFile(gitConfigPath, 'utf8'); const data = JSON.parse(content); const parsed = gitSettingsSchema.parse(data); // Ensure hostTokens exists even if not in parsed data @@ -156,22 +187,29 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise { /** * Write Git settings to VFS + * @param fs - Filesystem instance + * @param settings - Git settings to write + * @param configPath - Custom config path (default: /config) */ -export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings): Promise { - await ensureConfigDir(fs); - await fs.writeFile(GIT_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8'); +export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings, configPath = '/config'): Promise { + await ensureConfigDir(fs, configPath); + const gitConfigPath = getGitConfigPath(configPath); + await fs.writeFile(gitConfigPath, JSON.stringify(settings, null, 2), 'utf8'); } /** * Read Deploy settings from VFS + * @param fs - Filesystem instance + * @param configPath - Custom config path (default: /config) */ -export async function readDeploySettings(fs: JSRuntimeFS): Promise { +export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'): Promise { const defaultSettings: DeploySettings = { providers: [], }; try { - const content = await fs.readFile(DEPLOY_CONFIG_PATH, 'utf8'); + const deployConfigPath = getDeployConfigPath(configPath); + const content = await fs.readFile(deployConfigPath, 'utf8'); const data = JSON.parse(content); return deploySettingsSchema.parse(data); } catch (error) { @@ -184,9 +222,13 @@ export async function readDeploySettings(fs: JSRuntimeFS): Promise { - await ensureConfigDir(fs); - await fs.writeFile(DEPLOY_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8'); +export async function writeDeploySettings(fs: JSRuntimeFS, settings: DeploySettings, configPath = '/config'): Promise { + await ensureConfigDir(fs, configPath); + const deployConfigPath = getDeployConfigPath(configPath); + await fs.writeFile(deployConfigPath, JSON.stringify(settings, null, 2), 'utf8'); } diff --git a/src/lib/fileUtils.ts b/src/lib/fileUtils.ts index 88476d8c..68a881e3 100644 --- a/src/lib/fileUtils.ts +++ b/src/lib/fileUtils.ts @@ -46,13 +46,14 @@ export async function generateUniqueFilename( } /** - * Save a file to the /tmp directory with deduplication + * Save a file to the tmp directory with deduplication * @param fs - Filesystem instance * @param file - File object to save + * @param tmpPath - Custom tmp path (default: /tmp) * @returns Promise - Full path where the file was saved */ -export async function saveFileToTmp(fs: JSRuntimeFS, file: File): Promise { - const tmpDir = '/tmp'; +export async function saveFileToTmp(fs: JSRuntimeFS, file: File, tmpPath = '/tmp'): Promise { + const tmpDir = tmpPath; // Convert spaces to underscores in the filename const sanitizedFilename = file.name.replace(/\s+/g, '_'); const uniqueFilename = await generateUniqueFilename(fs, tmpDir, sanitizedFilename); diff --git a/src/lib/security.ts b/src/lib/security.ts index e4f8583d..4e1532e7 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -15,12 +15,23 @@ export function isAbsolutePath(path: string): boolean { * Check if write operations are allowed for the given path * * Write operations are only allowed in: - * - /tmp/ directory and its subdirectories - * - /projects/ directory and its subdirectories (project directories) + * - Configured tmp directory and its subdirectories + * - Configured projects directory and its subdirectories (project directories) * - Relative paths (always allowed, regardless of where they resolve to) * - Absolute paths that resolve to within the current working directory + * + * @param path - The path to check + * @param cwd - Current working directory (optional) + * @param options - Optional configuration for allowed paths */ -export function isWriteAllowed(path: string, cwd?: string): boolean { +export function isWriteAllowed( + path: string, + cwd?: string, + options?: { + tmpPath?: string; + projectsPath?: string; + } +): boolean { // Always allow relative paths (this follows traditional Unix security model) if (!isAbsolutePath(path)) { return true; @@ -29,13 +40,17 @@ export function isWriteAllowed(path: string, cwd?: string): boolean { // For absolute paths, apply restrictions const absolutePath = normalize(path); - // Allow writes to /tmp/ and its subdirectories - if (absolutePath.startsWith('/tmp/') || absolutePath === '/tmp') { + // Get configured paths with defaults + const tmpPath = options?.tmpPath || '/tmp'; + const projectsPath = options?.projectsPath || '/projects'; + + // Allow writes to tmp directory and its subdirectories + if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) { return true; } - // Allow writes to /projects/ and its subdirectories (project directories) - if (absolutePath.startsWith('/projects/') || absolutePath === '/projects') { + // Allow writes to projects directory and its subdirectories (project directories) + if (absolutePath.startsWith(projectsPath + '/') || absolutePath === projectsPath) { return true; } @@ -57,14 +72,24 @@ export function isWriteAllowed(path: string, cwd?: string): boolean { * @param path - The path to validate (can be absolute or relative) * @param operationName - Name of the operation for error messages (e.g., 'touch', 'mkdir') * @param cwd - Current working directory for context in error messages + * @param options - Optional configuration for allowed paths * @throws Error if the path is not allowed for write operations */ -export function validateWritePath(path: string, operationName: string, cwd?: string): void { - if (!isWriteAllowed(path, cwd)) { +export function validateWritePath( + path: string, + operationName: string, + cwd?: string, + options?: { + tmpPath?: string; + projectsPath?: string; + } +): void { + if (!isWriteAllowed(path, cwd, options)) { + const tmpPath = options?.tmpPath || '/tmp'; const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : ''; throw new Error( `${operationName}: write access denied to ${path}. ` + - `Write operations are only allowed in project directories and /tmp/${cwdInfo}` + `Write operations are only allowed in project directories and ${tmpPath}${cwdInfo}` ); } } @@ -75,23 +100,34 @@ export function validateWritePath(path: string, operationName: string, cwd?: str * @param path - The path that was denied * @param toolName - Name of the tool/command for context * @param cwd - Current working directory for context + * @param options - Optional configuration for allowed paths * @returns Formatted error message */ -export function createWriteAccessDeniedError(path: string, toolName?: string, cwd?: string): string { +export function createWriteAccessDeniedError( + path: string, + toolName?: string, + cwd?: string, + options?: { + tmpPath?: string; + projectsPath?: string; + } +): string { const prefix = toolName ? `❌ Write access denied to "${path}".` : `Write access denied to ${path}.`; const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : ''; + const tmpPath = options?.tmpPath || '/tmp'; + const projectsPath = options?.projectsPath || '/projects'; return ( `${prefix}\n\n` + `Write operations are only allowed in:\n` + `- Current working directory and subdirectories\n` + - `- Project directories (/projects/ and subdirectories)\n` + - `- Temporary directory (/tmp/ and subdirectories)\n` + + `- Project directories (${projectsPath}/ and subdirectories)\n` + + `- Temporary directory (${tmpPath}/ and subdirectories)\n` + `- Relative paths (resolved relative to current directory)\n\n` + `💡 Examples of allowed paths:\n` + `- "src/index.ts" (relative to current directory)\n` + - `- "/projects/my-project/src/file.js" (absolute project path)\n` + - `- "/tmp/temp-file.txt" (temporary files)\n` + - `- "/tmp/workspace/file.js" (temporary workspace)${cwdInfo}` + `- "${projectsPath}/my-project/src/file.js" (absolute project path)\n` + + `- "${tmpPath}/temp-file.txt" (temporary files)\n` + + `- "${tmpPath}/workspace/file.js" (temporary workspace)${cwdInfo}` ); } \ No newline at end of file diff --git a/src/lib/tmpCleanup.ts b/src/lib/tmpCleanup.ts index 67f31bb6..d5de3a27 100644 --- a/src/lib/tmpCleanup.ts +++ b/src/lib/tmpCleanup.ts @@ -8,7 +8,7 @@ import type { JSRuntimeFS } from './JSRuntime'; */ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: number): Promise { const now = Date.now(); - + try { // Check if directory exists try { @@ -23,14 +23,14 @@ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: numb // Get directory contents const entries = await fs.readdir(dirPath, { withFileTypes: true }); - + for (const entry of entries) { const fullPath = `${dirPath}/${entry.name}`; - + try { const stat = await fs.stat(fullPath); const fileAge = now - (stat.mtimeMs || 0); - + if (fileAge > maxAgeMs) { if (entry.isDirectory()) { // Recursively clean subdirectory first, then remove it @@ -62,19 +62,19 @@ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: numb } /** - * Cleans up the /tmp directory by removing files older than 1 hour + * Cleans up the tmp directory by removing files older than 1 hour * @param fs - The filesystem instance + * @param tmpPath - Custom tmp path (default: /tmp) */ -export async function cleanupTmpDirectory(fs: JSRuntimeFS): Promise { +export async function cleanupTmpDirectory(fs: JSRuntimeFS, tmpPath = '/tmp'): Promise { const ONE_HOUR_MS = 60 * 60 * 1000; // 1 hour in milliseconds - const tmpPath = '/tmp'; - - console.log('Starting /tmp directory cleanup...'); - + + console.log(`Starting ${tmpPath} directory cleanup...`); + try { await cleanupDirectory(fs, tmpPath, ONE_HOUR_MS); - console.log('Completed /tmp directory cleanup'); + console.log(`Completed ${tmpPath} directory cleanup`); } catch (error) { - console.error('Error during /tmp cleanup:', error); + console.error(`Error during ${tmpPath} cleanup:`, error); } } \ No newline at end of file diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts index 172a5a0e..f39ffc42 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.ts @@ -15,6 +15,8 @@ interface TextEditorStrReplaceParams { export class TextEditorStrReplaceTool implements Tool { private fs: JSRuntimeFS; private cwd: string; + private projectsPath: string; + private tmpPath: string; readonly description = "Replace a string in a file with a new string"; @@ -27,17 +29,19 @@ export class TextEditorStrReplaceTool implements Tool { const { path, old_str, new_str, normalize_whitespace = true } = args; // Check write permissions - if (!isWriteAllowed(path, this.cwd)) { - throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); + if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) { + throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })); } // Ban editing dependencies in package.json diff --git a/src/lib/tools/TextEditorViewTool.ts b/src/lib/tools/TextEditorViewTool.ts index e8ed1b64..9e9df058 100644 --- a/src/lib/tools/TextEditorViewTool.ts +++ b/src/lib/tools/TextEditorViewTool.ts @@ -13,6 +13,7 @@ interface TextEditorViewParams { export class TextEditorViewTool implements Tool { private fs: JSRuntimeFS; private cwd: string; + private projectsPath: string; readonly description = "View the contents of a text file or directory"; @@ -28,9 +29,10 @@ export class TextEditorViewTool implements Tool { ), }); - constructor(fs: JSRuntimeFS, cwd: string) { + constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string }) { this.fs = fs; this.cwd = cwd; + this.projectsPath = options?.projectsPath || '/projects'; } async execute(args: TextEditorViewParams): Promise { @@ -52,9 +54,9 @@ export class TextEditorViewTool implements Tool { const stats = await this.fs.stat(absolutePath); if (stats.isDirectory()) { - // Special handling for /projects directory - only show project directories, not their contents + // Special handling for projects directory - only show project directories, not their contents const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash - if (normalizedPath === '/projects') { + if (normalizedPath === this.projectsPath) { const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children return tree; } diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts index 9bb066c6..e0518e60 100644 --- a/src/lib/tools/TextEditorWriteTool.ts +++ b/src/lib/tools/TextEditorWriteTool.ts @@ -13,6 +13,8 @@ interface TextEditorWriteParams { export class TextEditorWriteTool implements Tool { private fs: JSRuntimeFS; private cwd: string; + private projectsPath: string; + private tmpPath: string; readonly description = "Create or overwrite a file with new content"; @@ -23,17 +25,19 @@ export class TextEditorWriteTool implements Tool { file_text: z.string().describe("Content to write to the file"), }); - constructor(fs: JSRuntimeFS, cwd: string) { + constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string }) { this.fs = fs; this.cwd = cwd; + this.projectsPath = options?.projectsPath || '/projects'; + this.tmpPath = options?.tmpPath || '/tmp'; } async execute(args: TextEditorWriteParams): Promise { const { path, file_text } = args; // Check write permissions - if (!isWriteAllowed(path, this.cwd)) { - throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); + if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) { + throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })); } if ( diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index e26c3cfa..2ef64c6a 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -236,7 +236,7 @@ export default function Index() { } // Store the initial message in chat history using DotAI - const dotAI = new DotAI(fs, `/projects/${project.id}`); + const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`); const sessionName = DotAI.generateSessionName(); // Create initial message with content parts (same format as ChatPane) diff --git a/src/pages/SystemSettings.tsx b/src/pages/SystemSettings.tsx index d64f8953..c0fbc0f0 100644 --- a/src/pages/SystemSettings.tsx +++ b/src/pages/SystemSettings.tsx @@ -21,6 +21,9 @@ export function SystemSettings() { const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl); const [previewDomainInput, setPreviewDomainInput] = useState(config.previewDomain); const [showcaseModeratorInput, setShowcaseModeratorInput] = useState(config.showcaseModerator); + const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects); + const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig); + const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp); return (
@@ -264,6 +267,87 @@ export function SystemSettings() { + + {/* Filesystem Paths Configuration */} + + + +

Filesystem Paths

+
+ +
+
+ + { + const value = e.target.value; + setFsPathProjectsInput(value); + updateConfig((current) => ({ + ...current, + fsPathProjects: value, + })); + }} + /> +

+ Filesystem path where projects are stored +

+
+ +
+ + { + const value = e.target.value; + setFsPathConfigInput(value); + updateConfig((current) => ({ + ...current, + fsPathConfig: value, + })); + }} + /> +

+ Filesystem path where configuration files are stored +

+
+ +
+ + { + const value = e.target.value; + setFsPathTmpInput(value); + updateConfig((current) => ({ + ...current, + fsPathTmp: value, + })); + }} + /> +

+ Filesystem path for temporary files +

+
+
+
+
+
); diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index f330dcd9..d9d195d6 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -39,6 +39,9 @@ export function TestApp({ children }: TestAppProps) { showcaseEnabled: true, showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', }; // Initialize LightningFS for testing