diff --git a/src/App.tsx b/src/App.tsx index 8c93c050..555c41fa 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -48,7 +48,7 @@ const queryClient = new QueryClient({ }); // Get OS-specific default paths for Electron -function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } { +function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } { if (!globalThis.electron) { // Browser defaults - use virtual filesystem paths return { @@ -56,6 +56,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "/config", fsPathTmp: "/tmp", fsPathPlugins: "/plugins", + fsPathTemplates: "/templates", }; } @@ -70,6 +71,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "~/AppData/Local/shakespeare", fsPathTmp: "~/AppData/Local/Temp/shakespeare", fsPathPlugins: "~/AppData/Local/shakespeare/plugins", + fsPathTemplates: "~/AppData/Local/shakespeare/templates", }; } else if (platform.includes('mac')) { // macOS @@ -78,6 +80,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "~/Library/Application Support/shakespeare", fsPathTmp: "/tmp/shakespeare", fsPathPlugins: "~/Library/Application Support/shakespeare/plugins", + fsPathTemplates: "~/Library/Application Support/shakespeare/templates", }; } else { // Linux and other Unix-like systems @@ -86,6 +89,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "~/.config/shakespeare", fsPathTmp: "/tmp/shakespeare", fsPathPlugins: "~/.config/shakespeare/plugins", + fsPathTemplates: "~/.config/shakespeare/templates", }; } } @@ -114,6 +118,7 @@ const defaultConfig: AppConfig = { fsPathConfig: electronPaths.fsPathConfig, fsPathTmp: electronPaths.fsPathTmp, fsPathPlugins: electronPaths.fsPathPlugins, + fsPathTemplates: electronPaths.fsPathTemplates, sentryDsn: import.meta.env.VITE_SENTRY_DSN || "", sentryEnabled: true, }; diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 0db9c91c..c9f5a66b 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -39,6 +39,7 @@ const AppConfigSchema = z.object({ fsPathConfig: z.string().min(1), fsPathTmp: z.string().min(1), fsPathPlugins: z.string().min(1), + fsPathTemplates: z.string().min(1), sentryDsn: z.string(), sentryEnabled: z.boolean(), }) satisfies z.ZodType; @@ -76,6 +77,7 @@ export function AppProvider(props: AppProviderProps) { config.fsPathProjects = expandPath(config.fsPathProjects); config.fsPathTmp = expandPath(config.fsPathTmp); config.fsPathPlugins = expandPath(config.fsPathPlugins); + config.fsPathTemplates = expandPath(config.fsPathTemplates); const appContextValue: AppContextType = { config, diff --git a/src/components/SentryProvider.test.tsx b/src/components/SentryProvider.test.tsx index 70369f04..d98f7c24 100644 --- a/src/components/SentryProvider.test.tsx +++ b/src/components/SentryProvider.test.tsx @@ -39,6 +39,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( @@ -75,6 +76,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( @@ -112,6 +114,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( @@ -152,6 +155,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 9523ac66..8664e1cb 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -40,6 +40,8 @@ export interface AppConfig { fsPathTmp: string; /** VFS path for plugins directory */ fsPathPlugins: string; + /** VFS path for templates directory */ + fsPathTemplates: string; /** Sentry DSN for error reporting (empty string = disabled) */ sentryDsn: string; /** Whether the user has enabled Sentry error reporting */ diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 11a2bb82..3443db42 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -56,6 +56,7 @@ describe('useAIProjectId', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/hooks/useFSPaths.ts b/src/hooks/useFSPaths.ts index d9ec08ea..9fd95618 100644 --- a/src/hooks/useFSPaths.ts +++ b/src/hooks/useFSPaths.ts @@ -17,5 +17,7 @@ export function useFSPaths() { tmpPath: config.fsPathTmp, /** Plugins directory path (default: /plugins) */ pluginsPath: config.fsPathPlugins, + /** Templates directory path (default: /templates) */ + templatesPath: config.fsPathTemplates, }; } diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index 748bf7cb..76d4b6f9 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -49,6 +49,7 @@ function createWrapper(corsProxy: string) { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/hooks/useProjectsManager.ts b/src/hooks/useProjectsManager.ts index 8f15bd95..9a871852 100644 --- a/src/hooks/useProjectsManager.ts +++ b/src/hooks/useProjectsManager.ts @@ -11,11 +11,11 @@ import { useGit } from './useGit'; export function useProjectsManager() { const { fs } = useFS(); const { git } = useGit(); - const { projectsPath } = useFSPaths(); + const { projectsPath, templatesPath } = useFSPaths(); const projectsManager = useMemo(() => { - return new ProjectsManager({ fs, git, projectsPath }); - }, [fs, git, projectsPath]); + return new ProjectsManager({ fs, git, projectsPath, templatesPath }); + }, [fs, git, projectsPath, templatesPath]); return projectsManager; } \ No newline at end of file diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 22b59ea6..2f87d6a2 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -219,7 +219,7 @@ describe('ProjectsManager', () => { fs = new MockFS() as unknown as JSRuntimeFS; nostr = createMockNostr(); git = new Git({ fs, nostr }); - projectsManager = new ProjectsManager({ fs, git }); + projectsManager = new ProjectsManager({ fs, git, projectsPath: '/projects', templatesPath: '/templates' }); }); describe('getProjects', () => { diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 9013acea..c9f38121 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -20,18 +20,22 @@ export interface ProjectsManagerOptions { fs: JSRuntimeFS; git: Git; /** Projects directory path (default: /projects) */ - projectsPath?: string; + projectsPath: string; + /** Templates directory path (default: /templates) */ + templatesPath: string; } export class ProjectsManager { fs: JSRuntimeFS; git: Git; dir: string; + templatesDir: string; constructor(options: ProjectsManagerOptions) { this.fs = options.fs; this.git = options.git; - this.dir = options.projectsPath || '/projects'; + this.dir = options.projectsPath; + this.templatesDir = options.templatesPath; } async init() { @@ -40,58 +44,239 @@ export class ProjectsManager { } catch { // Directory might already exist } + try { + await this.fs.mkdir(this.templatesDir); + } catch { + // Directory might already exist + } } - async createProject(name: string, templateUrl: string, customId?: string): Promise { - const project = await this.cloneProject(name, templateUrl, customId, { depth: 1 }); + /** + * Ensure a template is cached locally and up-to-date. + * Returns the path to the cached template. + * + * @param templateUrl - Git repository URL of the template + * @param onUpdateError - Optional callback when template update fails (non-critical) + * @returns Path to the cached template directory + */ + async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise { + // Generate a safe directory name from the template URL + const templateName = this.getTemplateNameFromUrl(templateUrl); + const templatePath = `${this.templatesDir}/${templateName}`; - // Delete README.md if it exists try { - await this.fs.unlink(`${project.path}/README.md`); + // Check if template already exists + await this.fs.stat(templatePath); + + // Template exists, try to update it with force pull + try { + await this.forcePullTemplate(templatePath); + } catch (updateError) { + // Update failed, but we can continue with the existing template + console.warn(`Failed to update template at ${templatePath}:`, updateError); + if (onUpdateError) { + onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError))); + } + } } catch { - // README.md might not exist, ignore error - } + // Template doesn't exist, clone it shallowly + await this.fs.mkdir(templatePath, { recursive: true }); - // Delete .git directory and reinitialize - try { - await this.deleteDirectory(`${project.path}/.git`); - } catch { - // .git directory might not exist, ignore error - } - - // Initialize new git repository - await this.git.init({ - dir: project.path, - defaultBranch: 'main', - }); - - // Add all files to git - const files = await this.getAllFiles(project.path); - for (const file of files) { - // Skip .git directory - if (!file.startsWith('.git/')) { - await this.git.add({ - dir: project.path, - filepath: file, + try { + await this.git.clone({ + dir: templatePath, + url: templateUrl, + singleBranch: true, + depth: 1, }); + } catch (cloneError) { + // Clean up on clone failure + try { + await this.deleteDirectory(templatePath); + } catch { + // Ignore cleanup errors + } + throw cloneError; } } - // Make initial commit - await this.git.commit({ - dir: project.path, - message: 'New project created with Shakespeare', + return templatePath; + } + + /** + * Force pull the template repository to match remote, discarding any local changes. + * This ensures the template is always up-to-date with the remote. + */ + private async forcePullTemplate(templatePath: string): Promise { + // Fetch the latest changes from remote + const fetchResult = await this.git.fetch({ + dir: templatePath, + singleBranch: true, + depth: 1, }); - // Automatically request persistent storage after project creation - try { - await ensurePersistentStorage(); - } catch (error) { - // Don't fail project creation if persistent storage request fails - console.warn('Failed to request persistent storage after project creation:', error); + // Get the current branch name + const branch = fetchResult.defaultBranch; + + if (!branch) { + throw new Error('Could not determine current branch'); } - return project; + // Reset hard to the remote branch, discarding all local changes + await this.git.checkout({ + dir: templatePath, + ref: branch, + force: true, + }); + } + + /** + * Generate a safe directory name from a template URL + */ + private getTemplateNameFromUrl(url: string): string { + // Extract a meaningful name from the URL + // e.g., "https://gitlab.com/soapbox-pub/mkstack.git" -> "mkstack" + // e.g., "nostr://alex@gleasonator.dev/shakespeare.diy/mkstack" -> "mkstack" + + let name = url; + + // Remove .git suffix if present + name = name.replace(/\.git$/, ''); + + // Remove trailing slash + name = name.replace(/\/$/, ''); + + // Extract the last part of the path + const parts = name.split('/'); + name = parts[parts.length - 1] || ''; + + // Sanitize the name to be filesystem-safe + name = name + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + + if (!name) { + throw new Error(`Could not derive template name from URL: ${url}`); + } + + return name; + } + + /** + * Copy a directory recursively from source to destination + */ + private async copyDirectory(sourcePath: string, destPath: string): Promise { + // Ensure destination directory exists + await this.fs.mkdir(destPath, { recursive: true }); + + const entries = await this.fs.readdir(sourcePath); + + for (const entry of entries) { + // Skip .git directory + if (entry === '.git') continue; + + const sourceFullPath = `${sourcePath}/${entry}`; + const destFullPath = `${destPath}/${entry}`; + + try { + const stat = await this.fs.lstat(sourceFullPath); + + if (stat.isDirectory()) { + // Recursively copy subdirectories + await this.copyDirectory(sourceFullPath, destFullPath); + } else if (stat.isFile()) { + // Copy file + const content = await this.fs.readFile(sourceFullPath); + await this.fs.writeFile(destFullPath, content); + } + } catch (error) { + console.warn(`Failed to copy ${sourceFullPath}:`, error); + // Continue copying other files + } + } + } + + async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise { + 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`); + } + + const projectPath = `${this.dir}/${id}`; + + // Ensure template is cached and up-to-date + const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError); + + // Create project directory + await this.fs.mkdir(projectPath, { recursive: true }); + + try { + // Copy template to project directory (excluding .git) + await this.copyDirectory(templatePath, projectPath); + + // Delete README.md if it exists + try { + await this.fs.unlink(`${projectPath}/README.md`); + } catch { + // README.md might not exist, ignore error + } + + // Initialize new git repository + await this.git.init({ + dir: projectPath, + defaultBranch: 'main', + }); + + // Add all files to git + const files = await this.getAllFiles(projectPath); + for (const file of files) { + // Skip .git directory + if (!file.startsWith('.git/')) { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } + } + + // Make initial commit + await this.git.commit({ + dir: projectPath, + message: 'New project created with Shakespeare', + }); + + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Automatically request persistent storage after project creation + try { + await ensurePersistentStorage(); + } catch (error) { + // Don't fail project creation if persistent storage request fails + console.warn('Failed to request persistent storage after project creation:', error); + } + + return { + id, + name: this.formatProjectName(id), + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up the directory that was created if project creation fails + try { + await this.deleteDirectory(projectPath); + } catch (cleanupError) { + // Log cleanup error but don't mask the original error + console.warn('Failed to clean up directory after project creation failure:', cleanupError); + } + // Re-throw the original error + throw error; + } } async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index ee15cf3b..401c46bd 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -53,6 +53,7 @@ const testConfig: AppConfig = { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/lib/system.test.ts b/src/lib/system.test.ts index 9827a370..237b7fbc 100644 --- a/src/lib/system.test.ts +++ b/src/lib/system.test.ts @@ -40,6 +40,7 @@ const testConfig: AppConfig = { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/locales/en.json b/src/locales/en.json index 3d5cc773..796f2bd3 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -508,5 +508,9 @@ "deleting": "Deleting...", "modified": "Modified", "restoreToDefault": "Restore to default", - "restoredToDefault": "Restored to Default" + "restoredToDefault": "Restored to Default", + "templateUpdateFailed": "Template Update Failed", + "templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.", + "templatesDirectory": "Templates Directory", + "templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem." } diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index cc093ad7..dadfe58a 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -25,9 +25,11 @@ import { ArrowUp } from 'lucide-react'; import { useSeoMeta } from '@unhead/react'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { AppShowcase } from '@/components/AppShowcase'; +import { useToast } from '@/hooks/useToast'; export default function Index() { const { t } = useTranslation(); + const { toast } = useToast(); const [prompt, setPrompt] = useState(''); const [isCreating, setIsCreating] = useState(false); const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', ''); @@ -228,8 +230,20 @@ export default function Index() { // Add model to recently used when creating project with AI addRecentlyUsedModel(providerModel.trim()); - // Create project with AI-generated ID - const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId); + // Create project with AI-generated ID and handle template update errors + const project = await projectsManager.createProject( + prompt.trim(), + config.projectTemplate, + projectId, + () => { + // Show a toast if template update fails (non-critical) + toast({ + title: t('templateUpdateFailed'), + description: t('templateUpdateFailedDescription'), + variant: 'default', + }); + } + ); // Build message content as text parts (same as ChatPane) const contentParts: Array = []; diff --git a/src/pages/SystemSettings.tsx b/src/pages/SystemSettings.tsx index 4571235d..06b3541e 100644 --- a/src/pages/SystemSettings.tsx +++ b/src/pages/SystemSettings.tsx @@ -32,6 +32,7 @@ export function SystemSettings() { const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig); const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp); const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins); + const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates); const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn); const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt); @@ -48,6 +49,7 @@ export function SystemSettings() { fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig, fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp, fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins, + fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates, sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn, systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt), }), [config, defaultConfig]); @@ -150,6 +152,15 @@ export function SystemSettings() { }); }; + const restoreFsPathTemplates = () => { + const defaultValue = defaultConfig.fsPathTemplates; + setFsPathTemplatesInput(defaultValue); + updateConfig((current) => { + const { fsPathTemplates, ...rest } = current; + return rest; + }); + }; + const restoreSentryDsn = () => { const defaultValue = defaultConfig.sentryDsn; setSentryDsnInput(defaultValue); @@ -786,7 +797,7 @@ export function SystemSettings() {

{t('filesystemPaths')}

- {(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && ( + {(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins || isModified.fsPathTemplates) && (
)}
@@ -956,6 +967,47 @@ export function SystemSettings() { {t('pluginsDirectoryDescription')}

+ +
+
+ + {isModified.fsPathTemplates && ( +
+ )} +
+
+ { + const value = e.target.value; + setFsPathTemplatesInput(value); + updateConfig((current) => ({ + ...current, + fsPathTemplates: value, + })); + }} + className="flex-1" + /> + {isModified.fsPathTemplates && ( + + )} +
+

+ {t('templatesDirectoryDescription')} +

+
diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index 3548f159..1eb4e141 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -48,6 +48,7 @@ export function TestApp({ children }: TestAppProps) { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, };