Remember the chosen project template

This commit is contained in:
Alex Gleason committed 2025-12-01 14:26:58 -06:00
1 parent 7112591aa3
commit 23ad0a9d35
6 files changed
+121 -20

No files matched your search

+31 -4
View File
@@ -34,6 +34,8 @@ import {
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
@@ -52,6 +54,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
const [isRenaming, setIsRenaming] = useState(false);
const [newProjectName, setNewProjectName] = useState(project.id);
const [totalCost, setTotalCost] = useState<number | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const { toast } = useToast();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -65,21 +68,28 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost
// Load total project cost and template info
useEffect(() => {
const loadCost = async () => {
const loadProjectData = async () => {
try {
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
// Load cost
const cost = await dotAI.readCost();
setTotalCost(cost);
// Load template info
const template = await dotAI.readTemplate();
setTemplateInfo(template);
} catch (error) {
console.warn('Failed to load project cost:', error);
console.warn('Failed to load project data:', error);
setTotalCost(null);
setTemplateInfo(null);
}
};
if (open) {
loadCost();
loadProjectData();
}
}, [fs, projectsPath, project.id, open]);
@@ -256,6 +266,23 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
</div>
)}
{/* Template Info */}
{templateInfo && (
<div className="flex items-center gap-2 text-sm">
<FileCode className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Template:</span>
<a
href={templateInfo.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-primary hover:underline"
>
{templateInfo.name}
<ExternalLink className="h-3 w-3" />
</a>
</div>
)}
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="project-name">Project Name</Label>
+12 -4
View File
@@ -264,7 +264,11 @@ describe('useGenerateProjectInfo', () => {
expect(projectInfo).toEqual({
projectId: 'test-project-name',
templateUrl: 'https://gitlab.com/soapbox-pub/mkstack.git'
template: {
name: 'MKStack',
description: 'Build Nostr clients with React.',
url: 'https://gitlab.com/soapbox-pub/mkstack.git'
}
});
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
@@ -325,7 +329,7 @@ describe('useGenerateProjectInfo', () => {
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.templateUrl).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(projectInfo.projectId).toBe('untitled');
});
@@ -363,7 +367,7 @@ describe('useGenerateProjectInfo', () => {
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.projectId).toBe('untitled');
expect(projectInfo.templateUrl).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(mockGetProject).toHaveBeenCalledTimes(2);
});
@@ -450,7 +454,11 @@ describe('useGenerateProjectInfo', () => {
expect(projectInfo).toEqual({
projectId: 'vanilla-app',
templateUrl: 'https://github.com/example/vanilla-template.git'
template: {
name: 'VanillaJS',
description: 'Simple vanilla JavaScript template.',
url: 'https://github.com/example/vanilla-template.git'
}
});
});
});
+11 -8
View File
@@ -13,7 +13,11 @@ interface UseGenerateProjectInfoOptions {
interface ProjectInfo {
projectId: string;
templateUrl: string;
template: {
name: string;
description: string;
url: string;
};
}
export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOptions = {}) {
@@ -24,7 +28,7 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption
const projectsManager = useProjectsManager();
// Helper function to generate untitled project name
const fallbackWithUntitled = useCallback(async (templateUrl: string): Promise<ProjectInfo> => {
const fallbackWithUntitled = useCallback(async (template: { url: string; name: string; description: string }): Promise<ProjectInfo> => {
let fallbackId = 'untitled';
let counter = 1;
@@ -40,7 +44,7 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption
return {
projectId: fallbackId,
templateUrl,
template,
};
}, [projectsManager]);
@@ -126,8 +130,7 @@ You MUST call the create_project tool with your choices.`;
if (!selectedTemplate) {
// Fallback to first template if invalid URL selected
console.warn(`Invalid template URL selected: ${templateUrl}, falling back to first template`);
const fallbackTemplate = config.templates[0];
return await fallbackWithUntitled(fallbackTemplate.url);
return await fallbackWithUntitled(config.templates[0]);
}
// Validate the generated project ID
@@ -139,14 +142,14 @@ You MUST call the create_project tool with your choices.`;
// Valid and unique project ID
return {
projectId,
templateUrl: selectedTemplate.url,
template: selectedTemplate,
};
}
}
// If we reach here, either the regex failed or the project already exists
// Fall back to "untitled" with number suffixes
return await fallbackWithUntitled(selectedTemplate.url);
return await fallbackWithUntitled(selectedTemplate);
} catch (error) {
// On any error, fall back to first template with untitled name
console.error('Error generating project info:', error);
@@ -157,7 +160,7 @@ You MUST call the create_project tool with your choices.`;
throw new Error(errorMessage);
}
return await fallbackWithUntitled(config.templates[0].url);
return await fallbackWithUntitled(config.templates[0]);
} finally {
setIsLoading(false);
}
+46
View File
@@ -312,4 +312,50 @@ export class DotAI {
console.warn(`Failed to write .git/shakespeare/COST file: ${error}`);
}
}
/**
* Read template metadata from .git/shakespeare/template.json file
* @returns Template metadata object or null if not found or invalid
*/
async readTemplate(): Promise<{ name: string; description: string; url: string } | null> {
try {
const templatePath = join(this.workingDir, ".git", "shakespeare", "template.json");
const content = await this.fs.readFile(templatePath, "utf8");
const template = JSON.parse(content);
// Validate that required fields exist
if (template && typeof template.name === 'string' &&
typeof template.description === 'string' &&
typeof template.url === 'string') {
return {
name: template.name,
description: template.description,
url: template.url,
};
}
return null;
} catch {
return null;
}
}
/**
* Write template metadata to .git/shakespeare/template.json file
* @param template Template metadata with name, description, and url
*/
async writeTemplate(template: { name: string; description: string; url: string }): Promise<void> {
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
const templatePath = join(shakespeareDir, "template.json");
try {
// Ensure .git/shakespeare directory exists
await this.fs.mkdir(shakespeareDir, { recursive: true });
// Write the template metadata as formatted JSON
await this.fs.writeFile(templatePath, JSON.stringify(template, null, 2) + "\n");
} catch (error) {
console.warn(`Failed to write .git/shakespeare/template.json file: ${error}`);
}
}
}
+17 -1
View File
@@ -3,6 +3,7 @@ import JSZip from 'jszip';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { ensurePersistentStorage } from '@/lib/persistentStorage';
import { DotAI } from '@/lib/DotAI';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
@@ -197,7 +198,7 @@ export class ProjectsManager {
}
}
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise<Project> {
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, templateMetadata?: { name: string; description: string }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -230,6 +231,21 @@ export class ProjectsManager {
defaultBranch: 'main',
});
// Save template metadata to .git/shakespeare/template.json if provided
if (templateMetadata) {
try {
const dotAI = new DotAI(this.fs, projectPath);
await dotAI.writeTemplate({
name: templateMetadata.name,
description: templateMetadata.description,
url: templateUrl,
});
} catch (error) {
// Don't fail project creation if template metadata save fails
console.warn('Failed to save template metadata:', error);
}
}
// Add all files to git
const files = await this.getAllFiles(projectPath);
for (const file of files) {
+4 -3
View File
@@ -224,7 +224,7 @@ export default function Index() {
setIsCreating(true);
try {
// Use AI to generate project ID and select template
const { projectId, templateUrl } = await generateProjectInfo(providerModel, prompt.trim());
const { projectId, template } = await generateProjectInfo(providerModel, prompt.trim());
// Add model to recently used when creating project with AI
addRecentlyUsedModel(providerModel.trim());
@@ -232,7 +232,7 @@ export default function Index() {
// Create project with AI-generated ID and selected template
const project = await projectsManager.createProject(
prompt.trim(),
templateUrl,
template.url,
projectId,
() => {
// Show a toast if template update fails (non-critical)
@@ -241,7 +241,8 @@ export default function Index() {
description: t('templateUpdateFailedDescription'),
variant: 'default',
});
}
},
{ name: template.name, description: template.description }
);
// Build message content from input and attached files