mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Fix the behavior of the create project textarea
This commit is contained in:
6 files changed
+315
-50
No files matched your search
+51
-39
@@ -62,53 +62,21 @@ export function useAIChat({
|
||||
});
|
||||
}, [saveMessagesToHistory]);
|
||||
|
||||
// Load message history when component mounts or projectId changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
const startGeneration = useCallback(async (providerModel?: string) => {
|
||||
if (!isConfigured || isLoading || messages.length === 0) return;
|
||||
|
||||
if (lastSession) {
|
||||
setMessages(lastSession.messages);
|
||||
setSessionName(lastSession.sessionName);
|
||||
} else {
|
||||
// No history to load, start fresh
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
// Start fresh on any error
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
};
|
||||
// Get the last message - it should be a user message
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
loadMessageHistory();
|
||||
}, [projectId, fs]);
|
||||
|
||||
const sendMessage = useCallback(async (content: string, providerModel?: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content
|
||||
};
|
||||
|
||||
addMessage(userMessage);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
// Get all messages including the new user message
|
||||
const allMessages = [...messages, userMessage];
|
||||
|
||||
// Use messages directly as they're already in OpenAI format
|
||||
const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = allMessages;
|
||||
// Use all existing messages
|
||||
const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [...messages];
|
||||
|
||||
// Add system message if provided
|
||||
if (systemPrompt) {
|
||||
@@ -375,6 +343,49 @@ export function useAIChat({
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps]);
|
||||
|
||||
// Load message history when component mounts or projectId changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
|
||||
if (lastSession) {
|
||||
setMessages(lastSession.messages);
|
||||
setSessionName(lastSession.sessionName);
|
||||
} else {
|
||||
// No history to load, start fresh
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
// Start fresh on any error
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
};
|
||||
|
||||
loadMessageHistory();
|
||||
}, [projectId, fs]);
|
||||
|
||||
const sendMessage = useCallback(async (content: string, providerModel?: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content
|
||||
};
|
||||
|
||||
addMessage(userMessage);
|
||||
|
||||
// Use setTimeout to ensure the message is added before starting generation
|
||||
setTimeout(() => {
|
||||
startGeneration(providerModel);
|
||||
}, 0);
|
||||
}, [isConfigured, isLoading, addMessage, startGeneration]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
@@ -400,6 +411,7 @@ export function useAIChat({
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useAIProjectId } from './useAIProjectId';
|
||||
import { useAISettings } from './useAISettings';
|
||||
|
||||
// Mock the useAISettings hook
|
||||
vi.mock('./useAISettings');
|
||||
|
||||
describe('useAIProjectId', () => {
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {} },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isConfigured).toBe(false);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should throw error when trying to generate ID without configuration', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {} },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('test prompt')).rejects.toThrow(
|
||||
'AI settings not configured'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when prompt is empty', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('')).rejects.toThrow(
|
||||
'Prompt cannot be empty'
|
||||
);
|
||||
});
|
||||
|
||||
it('should have configured status when providers are available', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isConfigured).toBe(true);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
interface UseAIProjectIdOptions {
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
|
||||
const generateProjectId = useCallback(async (prompt: string): Promise<string> => {
|
||||
if (!isConfigured) {
|
||||
throw new Error('AI settings not configured');
|
||||
}
|
||||
|
||||
if (!prompt.trim()) {
|
||||
throw new Error('Prompt cannot be empty');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Use first available provider as fallback
|
||||
const providers = settings.providers || {};
|
||||
const firstProvider = Object.keys(providers)[0];
|
||||
if (!firstProvider || !providers[firstProvider]?.apiKey) {
|
||||
throw new Error('No configured AI providers available');
|
||||
}
|
||||
|
||||
const connectionConfig = providers[firstProvider];
|
||||
const modelName = 'gpt-3.5-turbo'; // Use a fast, cheap model for ID generation
|
||||
|
||||
// Initialize OpenAI client
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
const systemPrompt = `You are a project ID generator. Given a user's description of what they want to build, generate a short, descriptive, kebab-case project ID that captures the essence of their project.
|
||||
|
||||
Rules:
|
||||
- Use only lowercase letters, numbers, and hyphens
|
||||
- Keep it between 2-4 words
|
||||
- Make it descriptive but concise
|
||||
- No spaces, underscores, or special characters except hyphens
|
||||
- Examples:
|
||||
- "farming equipment marketplace" → "farming-marketplace"
|
||||
- "social media for artists" → "artist-social-app"
|
||||
- "crypto trading dashboard" → "crypto-dashboard"
|
||||
- "recipe sharing platform" → "recipe-platform"
|
||||
|
||||
Respond with ONLY the project ID, no explanation or additional text.`;
|
||||
|
||||
const completion = await openai.chat.completions.create({
|
||||
model: modelName,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
max_tokens: 20,
|
||||
temperature: 0.3,
|
||||
});
|
||||
|
||||
const projectId = completion.choices[0]?.message?.content?.trim();
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error('Failed to generate project ID');
|
||||
}
|
||||
|
||||
// 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;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isConfigured, settings, onError]);
|
||||
|
||||
return {
|
||||
generateProjectId,
|
||||
isLoading,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user