Cache project template to VFS for faster clones

This commit is contained in:
Alex Gleason committed 2025-11-23 10:42:07 -06:00
1 parent 3050e93555
commit 4f73d99f64
16 files changed
+324 -49

No files matched your search

+6 -1
View File
@@ -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,
};
+2
View File
@@ -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<AppConfig>;
@@ -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,
+4
View File
@@ -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(
+2
View File
@@ -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 */
+1
View File
@@ -56,6 +56,7 @@ describe('useAIProjectId', () => {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
+2
View File
@@ -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,
};
}
+1
View File
@@ -49,6 +49,7 @@ function createWrapper(corsProxy: string) {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
+3 -3
View File
@@ -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;
}
+1 -1
View File
@@ -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', () => {
+225 -40
View File
@@ -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<Project> {
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<string> {
// 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<void> {
// 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://[email protected]/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<void> {
// 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<Project> {
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<Project> {
+1
View File
@@ -53,6 +53,7 @@ const testConfig: AppConfig = {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
+1
View File
@@ -40,6 +40,7 @@ const testConfig: AppConfig = {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
+5 -1
View File
@@ -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."
}
+16 -2
View File
@@ -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<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
+53 -1
View File
@@ -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() {
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && (
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins || isModified.fsPathTemplates) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
@@ -956,6 +967,47 @@ export function SystemSettings() {
{t('pluginsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-templates" className="text-sm font-medium">
{t('templatesDirectory')}
</Label>
{isModified.fsPathTemplates && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-templates"
type="text"
placeholder="/templates"
value={fsPathTemplatesInput}
onChange={(e) => {
const value = e.target.value;
setFsPathTemplatesInput(value);
updateConfig((current) => ({
...current,
fsPathTemplates: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathTemplates && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathTemplates}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('templatesDirectoryDescription')}
</p>
</div>
</div>
</AccordionContent>
</AccordionItem>
+1
View File
@@ -48,6 +48,7 @@ export function TestApp({ children }: TestAppProps) {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};