mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Retry generating projectId if the generated name is already taken
This commit is contained in:
2 files changed
+181
-31
No files matched your search
@@ -3,18 +3,22 @@ import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useAIProjectId } from './useAIProjectId';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { ProjectsManager } from '@/lib/ProjectsManager';
|
||||
|
||||
// Mock the hooks and dependencies
|
||||
vi.mock('./useAISettings');
|
||||
vi.mock('./useCurrentUser');
|
||||
vi.mock('./useProjectsManager');
|
||||
vi.mock('@/lib/ai-client');
|
||||
vi.mock('@/lib/parseProviderModel');
|
||||
|
||||
describe('useAIProjectId', () => {
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
const mockUseCurrentUser = vi.mocked(useCurrentUser);
|
||||
const mockUseProjectsManager = vi.mocked(useProjectsManager);
|
||||
const mockCreateAIClient = vi.mocked(createAIClient);
|
||||
const mockParseProviderModel = vi.mocked(parseProviderModel);
|
||||
|
||||
@@ -30,6 +34,12 @@ describe('useAIProjectId', () => {
|
||||
users: [],
|
||||
});
|
||||
|
||||
// Mock useProjectsManager
|
||||
const mockProjectsManager = {
|
||||
getProject: vi.fn().mockResolvedValue(null),
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
// Mock parseProviderModel
|
||||
mockParseProviderModel.mockReturnValue({
|
||||
provider: 'openai',
|
||||
@@ -161,6 +171,120 @@ describe('useAIProjectId', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should retry with new names when project exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock multiple responses - first one exists, second one is unique
|
||||
const mockCompletion1 = {
|
||||
choices: [{ message: { content: 'existing-project' } }]
|
||||
};
|
||||
const mockCompletion2 = {
|
||||
choices: [{ message: { content: 'unique-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn()
|
||||
.mockResolvedValueOnce(mockCompletion1)
|
||||
.mockResolvedValueOnce(mockCompletion2)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - first call returns project (exists), second returns null (unique)
|
||||
const mockGetProject = vi.fn()
|
||||
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('unique-project');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(2);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'unique-project');
|
||||
|
||||
// Should have called AI twice - once for initial name, once for retry
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Second call should include the "already taken" message
|
||||
const mockCreate = mockOpenAI.chat.completions.create as ReturnType<typeof vi.fn>;
|
||||
const secondCallArgs = mockCreate.mock.calls[1][0];
|
||||
expect(secondCallArgs.messages).toHaveLength(3);
|
||||
expect(secondCallArgs.messages[2].content).toContain('already taken');
|
||||
});
|
||||
|
||||
it('should throw error after maximum iterations', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to always return the same name
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'taken-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject to always return a project (project always exists)
|
||||
const mockGetProject = vi.fn().mockResolvedValue({
|
||||
id: 'taken-project',
|
||||
name: 'Taken Project',
|
||||
path: '/projects/taken-project',
|
||||
lastModified: new Date()
|
||||
});
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', 'A social media app for developers'))
|
||||
.rejects.toThrow('Failed to generate a unique project name after 3 attempts');
|
||||
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(3);
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should handle loading state correctly', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
|
||||
+57
-31
@@ -1,6 +1,7 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
|
||||
@@ -12,6 +13,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const generateProjectId = useCallback(async (providerModel: string, prompt: string): Promise<string> => {
|
||||
if (!isConfigured) {
|
||||
@@ -31,39 +33,63 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
|
||||
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
|
||||
|
||||
const completion = await openai.chat.completions.create({
|
||||
model,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
temperature: 1,
|
||||
});
|
||||
const messages = [
|
||||
{ role: 'system' as const, content: systemPrompt },
|
||||
{ role: 'user' as const, content: prompt }
|
||||
];
|
||||
|
||||
const projectName = completion.choices[0]?.message?.content?.trim();
|
||||
if (!projectName) {
|
||||
throw new Error('Failed to generate project name');
|
||||
let iterations = 0;
|
||||
const maxIterations = 3;
|
||||
|
||||
while (iterations < maxIterations) {
|
||||
iterations++;
|
||||
|
||||
const completion = await openai.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
temperature: 1,
|
||||
});
|
||||
|
||||
const projectName = completion.choices[0]?.message?.content?.trim();
|
||||
if (!projectName) {
|
||||
throw new Error('Failed to generate project name');
|
||||
}
|
||||
|
||||
// Convert the name into kebab-case
|
||||
const projectId = projectName
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, '-') // Replace spaces with hyphens
|
||||
.replace(/[^a-z0-9-]/g, '') // Remove invalid characters
|
||||
.replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen
|
||||
.replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error('Generated project ID is empty after formatting');
|
||||
}
|
||||
|
||||
// Validate the generated ID
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (!validIdRegex.test(projectId)) {
|
||||
throw new Error('Generated project ID is invalid');
|
||||
}
|
||||
|
||||
// Check if project exists
|
||||
const existingProject = await projectsManager.getProject(projectId);
|
||||
if (existingProject !== null) {
|
||||
// Add user message indicating the name is already taken
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content: `The name "${projectName}" (project ID: ${projectId}) is already taken. Please generate another unique name.`
|
||||
});
|
||||
continue; // Try again with updated conversation
|
||||
}
|
||||
|
||||
// If we reach here, the project ID is valid and unique
|
||||
return projectId;
|
||||
}
|
||||
|
||||
// Convert the name into kebab-case
|
||||
const projectId = projectName
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, '-') // Replace spaces with hyphens
|
||||
.replace(/[^a-z0-9-]/g, '') // Remove invalid characters
|
||||
.replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen
|
||||
.replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error('Generated project ID is empty after formatting');
|
||||
}
|
||||
|
||||
// Validate the generated ID
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (!validIdRegex.test(projectId)) {
|
||||
throw new Error('Generated project ID is invalid');
|
||||
}
|
||||
|
||||
return projectId;
|
||||
// If we've exceeded max iterations, throw an error
|
||||
throw new Error(`Failed to generate a unique project name after ${maxIterations} attempts`);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
@@ -71,7 +97,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isConfigured, settings, onError, user]);
|
||||
}, [isConfigured, settings, onError, user, projectsManager]);
|
||||
|
||||
return {
|
||||
generateProjectId,
|
||||
|
||||
Reference in new issue
Block a user