mirror of
https://github.com/leonvanzyl/autocoder.git
synced 2026-01-31 06:42:06 +00:00
feat: Add "Expand Project" for bulk AI-powered feature creation
Adds the ability to add multiple features to an existing project through a natural language conversation with Claude, similar to how initial spec creation works. Features: - New "Expand" button in header (keyboard shortcut: E) - Full-screen chat interface for describing new features - Claude reads existing app_spec.txt for context - Features created directly in database after user approval - Bulk feature creation endpoint for batch operations New files: - .claude/commands/expand-project.md - Claude skill for expansion - server/services/expand_chat_session.py - Chat session service - server/routers/expand_project.py - WebSocket endpoint - ui/src/components/ExpandProjectChat.tsx - Chat UI - ui/src/components/ExpandProjectModal.tsx - Modal wrapper - ui/src/hooks/useExpandChat.ts - WebSocket hook Modified: - Added POST /bulk endpoint to features router - Added FeatureBulkCreate schemas - Integrated Expand button and modal in App.tsx Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useProjects, useFeatures, useAgentStatus } from './hooks/useProjects'
|
||||
import { useProjectWebSocket } from './hooks/useWebSocket'
|
||||
import { useFeatureSound } from './hooks/useFeatureSound'
|
||||
@@ -16,7 +17,8 @@ import { DebugLogViewer } from './components/DebugLogViewer'
|
||||
import { AgentThought } from './components/AgentThought'
|
||||
import { AssistantFAB } from './components/AssistantFAB'
|
||||
import { AssistantPanel } from './components/AssistantPanel'
|
||||
import { Plus, Loader2 } from 'lucide-react'
|
||||
import { ExpandProjectModal } from './components/ExpandProjectModal'
|
||||
import { Plus, Loader2, Sparkles } from 'lucide-react'
|
||||
import type { Feature } from './lib/types'
|
||||
|
||||
function App() {
|
||||
@@ -29,12 +31,14 @@ function App() {
|
||||
}
|
||||
})
|
||||
const [showAddFeature, setShowAddFeature] = useState(false)
|
||||
const [showExpandProject, setShowExpandProject] = useState(false)
|
||||
const [selectedFeature, setSelectedFeature] = useState<Feature | null>(null)
|
||||
const [setupComplete, setSetupComplete] = useState(true) // Start optimistic
|
||||
const [debugOpen, setDebugOpen] = useState(false)
|
||||
const [debugPanelHeight, setDebugPanelHeight] = useState(288) // Default height
|
||||
const [assistantOpen, setAssistantOpen] = useState(false)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const { data: projects, isLoading: projectsLoading } = useProjects()
|
||||
const { data: features } = useFeatures(selectedProject)
|
||||
const { data: agentStatusData } = useAgentStatus(selectedProject)
|
||||
@@ -87,6 +91,13 @@ function App() {
|
||||
setShowAddFeature(true)
|
||||
}
|
||||
|
||||
// E : Expand project with AI (when project selected and has features)
|
||||
if ((e.key === 'e' || e.key === 'E') && selectedProject && features &&
|
||||
(features.pending.length + features.in_progress.length + features.done.length) > 0) {
|
||||
e.preventDefault()
|
||||
setShowExpandProject(true)
|
||||
}
|
||||
|
||||
// A : Toggle assistant panel (when project selected)
|
||||
if ((e.key === 'a' || e.key === 'A') && selectedProject) {
|
||||
e.preventDefault()
|
||||
@@ -95,7 +106,9 @@ function App() {
|
||||
|
||||
// Escape : Close modals
|
||||
if (e.key === 'Escape') {
|
||||
if (assistantOpen) {
|
||||
if (showExpandProject) {
|
||||
setShowExpandProject(false)
|
||||
} else if (assistantOpen) {
|
||||
setAssistantOpen(false)
|
||||
} else if (showAddFeature) {
|
||||
setShowAddFeature(false)
|
||||
@@ -109,7 +122,7 @@ function App() {
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [selectedProject, showAddFeature, selectedFeature, debugOpen, assistantOpen])
|
||||
}, [selectedProject, showAddFeature, showExpandProject, selectedFeature, debugOpen, assistantOpen, features])
|
||||
|
||||
// Combine WebSocket progress with feature data
|
||||
const progress = wsState.progress.total > 0 ? wsState.progress : {
|
||||
@@ -160,6 +173,21 @@ function App() {
|
||||
</kbd>
|
||||
</button>
|
||||
|
||||
{/* Expand Project - only show if project has features */}
|
||||
{features && (features.pending.length + features.in_progress.length + features.done.length) > 0 && (
|
||||
<button
|
||||
onClick={() => setShowExpandProject(true)}
|
||||
className="neo-btn bg-[var(--color-neo-progress)] text-black text-sm"
|
||||
title="Add multiple features via AI (Press E)"
|
||||
>
|
||||
<Sparkles size={18} />
|
||||
Expand
|
||||
<kbd className="ml-1.5 px-1.5 py-0.5 text-xs bg-black/20 rounded font-mono">
|
||||
E
|
||||
</kbd>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<AgentControl
|
||||
projectName={selectedProject}
|
||||
status={wsState.agentStatus}
|
||||
@@ -245,6 +273,19 @@ function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Expand Project Modal - AI-powered bulk feature creation */}
|
||||
{showExpandProject && selectedProject && (
|
||||
<ExpandProjectModal
|
||||
isOpen={showExpandProject}
|
||||
projectName={selectedProject}
|
||||
onClose={() => setShowExpandProject(false)}
|
||||
onFeaturesAdded={() => {
|
||||
// Invalidate features query to refresh the kanban board
|
||||
queryClient.invalidateQueries({ queryKey: ['features', selectedProject] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Debug Log Viewer - fixed to bottom */}
|
||||
{selectedProject && (
|
||||
<DebugLogViewer
|
||||
@@ -256,8 +297,8 @@ function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Assistant FAB and Panel */}
|
||||
{selectedProject && (
|
||||
{/* Assistant FAB and Panel - hide FAB when expand modal is open */}
|
||||
{selectedProject && !showExpandProject && (
|
||||
<>
|
||||
<AssistantFAB
|
||||
onClick={() => setAssistantOpen(!assistantOpen)}
|
||||
|
||||
375
ui/src/components/ExpandProjectChat.tsx
Normal file
375
ui/src/components/ExpandProjectChat.tsx
Normal file
@@ -0,0 +1,375 @@
|
||||
/**
|
||||
* Expand Project Chat Component
|
||||
*
|
||||
* Full chat interface for interactive project expansion with Claude.
|
||||
* Allows users to describe new features in natural language.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Send, X, CheckCircle2, AlertCircle, Wifi, WifiOff, RotateCcw, Paperclip, Plus } from 'lucide-react'
|
||||
import { useExpandChat } from '../hooks/useExpandChat'
|
||||
import { ChatMessage } from './ChatMessage'
|
||||
import { TypingIndicator } from './TypingIndicator'
|
||||
import type { ImageAttachment } from '../lib/types'
|
||||
|
||||
// Image upload validation constants
|
||||
const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5 MB
|
||||
const ALLOWED_TYPES = ['image/jpeg', 'image/png']
|
||||
|
||||
interface ExpandProjectChatProps {
|
||||
projectName: string
|
||||
onComplete: (featuresAdded: number) => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
export function ExpandProjectChat({
|
||||
projectName,
|
||||
onComplete,
|
||||
onCancel,
|
||||
}: ExpandProjectChatProps) {
|
||||
const [input, setInput] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [pendingAttachments, setPendingAttachments] = useState<ImageAttachment[]>([])
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const {
|
||||
messages,
|
||||
isLoading,
|
||||
isComplete,
|
||||
connectionStatus,
|
||||
featuresCreated,
|
||||
start,
|
||||
sendMessage,
|
||||
disconnect,
|
||||
} = useExpandChat({
|
||||
projectName,
|
||||
onComplete,
|
||||
onError: (err) => setError(err),
|
||||
})
|
||||
|
||||
// Start the chat session when component mounts
|
||||
useEffect(() => {
|
||||
start()
|
||||
|
||||
return () => {
|
||||
disconnect()
|
||||
}
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Scroll to bottom when messages change
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [messages, isLoading])
|
||||
|
||||
// Focus input when not loading
|
||||
useEffect(() => {
|
||||
if (!isLoading && inputRef.current) {
|
||||
inputRef.current.focus()
|
||||
}
|
||||
}, [isLoading])
|
||||
|
||||
const handleSendMessage = () => {
|
||||
const trimmed = input.trim()
|
||||
// Allow sending if there's text OR attachments
|
||||
if ((!trimmed && pendingAttachments.length === 0) || isLoading) return
|
||||
|
||||
sendMessage(trimmed, pendingAttachments.length > 0 ? pendingAttachments : undefined)
|
||||
setInput('')
|
||||
setPendingAttachments([]) // Clear attachments after sending
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
handleSendMessage()
|
||||
}
|
||||
}
|
||||
|
||||
// File handling for image attachments
|
||||
const handleFileSelect = useCallback((files: FileList | null) => {
|
||||
if (!files) return
|
||||
|
||||
Array.from(files).forEach((file) => {
|
||||
// Validate file type
|
||||
if (!ALLOWED_TYPES.includes(file.type)) {
|
||||
setError(`Invalid file type: ${file.name}. Only JPEG and PNG are supported.`)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate file size
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
setError(`File too large: ${file.name}. Maximum size is 5 MB.`)
|
||||
return
|
||||
}
|
||||
|
||||
// Read and convert to base64
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
const dataUrl = e.target?.result as string
|
||||
const base64Data = dataUrl.split(',')[1]
|
||||
|
||||
const attachment: ImageAttachment = {
|
||||
id: `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
|
||||
filename: file.name,
|
||||
mimeType: file.type as 'image/jpeg' | 'image/png',
|
||||
base64Data,
|
||||
previewUrl: dataUrl,
|
||||
size: file.size,
|
||||
}
|
||||
|
||||
setPendingAttachments((prev) => [...prev, attachment])
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handleRemoveAttachment = useCallback((id: string) => {
|
||||
setPendingAttachments((prev) => prev.filter((a) => a.id !== id))
|
||||
}, [])
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
handleFileSelect(e.dataTransfer.files)
|
||||
},
|
||||
[handleFileSelect]
|
||||
)
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
}, [])
|
||||
|
||||
// Connection status indicator
|
||||
const ConnectionIndicator = () => {
|
||||
switch (connectionStatus) {
|
||||
case 'connected':
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-xs text-[var(--color-neo-done)]">
|
||||
<Wifi size={12} />
|
||||
Connected
|
||||
</span>
|
||||
)
|
||||
case 'connecting':
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-xs text-[var(--color-neo-pending)]">
|
||||
<Wifi size={12} className="animate-pulse" />
|
||||
Connecting...
|
||||
</span>
|
||||
)
|
||||
case 'error':
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-xs text-[var(--color-neo-danger)]">
|
||||
<WifiOff size={12} />
|
||||
Error
|
||||
</span>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-xs text-[var(--color-neo-text-secondary)]">
|
||||
<WifiOff size={12} />
|
||||
Disconnected
|
||||
</span>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-[var(--color-neo-bg)]">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b-3 border-[var(--color-neo-border)] bg-white">
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="font-display font-bold text-lg text-[#1a1a1a]">
|
||||
Expand Project: {projectName}
|
||||
</h2>
|
||||
<ConnectionIndicator />
|
||||
{featuresCreated > 0 && (
|
||||
<span className="flex items-center gap-1 text-sm text-[var(--color-neo-done)] font-bold">
|
||||
<Plus size={14} />
|
||||
{featuresCreated} added
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{isComplete && (
|
||||
<span className="flex items-center gap-1 text-sm text-[var(--color-neo-done)] font-bold">
|
||||
<CheckCircle2 size={16} />
|
||||
Complete
|
||||
</span>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="neo-btn neo-btn-ghost p-2"
|
||||
title="Close"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error banner */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-[var(--color-neo-danger)] text-white border-b-3 border-[var(--color-neo-border)]">
|
||||
<AlertCircle size={16} />
|
||||
<span className="flex-1 text-sm">{error}</span>
|
||||
<button
|
||||
onClick={() => setError(null)}
|
||||
className="p-1 hover:bg-white/20 rounded"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Messages area */}
|
||||
<div className="flex-1 overflow-y-auto py-4">
|
||||
{messages.length === 0 && !isLoading && (
|
||||
<div className="flex flex-col items-center justify-center h-full text-center p-8">
|
||||
<div className="neo-card p-6 max-w-md">
|
||||
<h3 className="font-display font-bold text-lg mb-2">
|
||||
Starting Project Expansion
|
||||
</h3>
|
||||
<p className="text-sm text-[var(--color-neo-text-secondary)]">
|
||||
Connecting to Claude to help you add new features to your project...
|
||||
</p>
|
||||
{connectionStatus === 'error' && (
|
||||
<button
|
||||
onClick={start}
|
||||
className="neo-btn neo-btn-primary mt-4 text-sm"
|
||||
>
|
||||
<RotateCcw size={14} />
|
||||
Retry Connection
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages.map((message) => (
|
||||
<ChatMessage key={message.id} message={message} />
|
||||
))}
|
||||
|
||||
{/* Typing indicator */}
|
||||
{isLoading && <TypingIndicator />}
|
||||
|
||||
{/* Scroll anchor */}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
{/* Input area */}
|
||||
{!isComplete && (
|
||||
<div
|
||||
className="p-4 border-t-3 border-[var(--color-neo-border)] bg-white"
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
>
|
||||
{/* Attachment previews */}
|
||||
{pendingAttachments.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 mb-3">
|
||||
{pendingAttachments.map((attachment) => (
|
||||
<div
|
||||
key={attachment.id}
|
||||
className="relative group border-2 border-[var(--color-neo-border)] p-1 bg-white shadow-[2px_2px_0px_rgba(0,0,0,1)]"
|
||||
>
|
||||
<img
|
||||
src={attachment.previewUrl}
|
||||
alt={attachment.filename}
|
||||
className="w-16 h-16 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleRemoveAttachment(attachment.id)}
|
||||
className="absolute -top-2 -right-2 bg-[var(--color-neo-danger)] text-white rounded-full p-0.5 border-2 border-[var(--color-neo-border)] hover:scale-110 transition-transform"
|
||||
title="Remove attachment"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
<span className="text-xs truncate block max-w-16 mt-1 text-center">
|
||||
{attachment.filename.length > 10
|
||||
? `${attachment.filename.substring(0, 7)}...`
|
||||
: attachment.filename}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3">
|
||||
{/* Hidden file input */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png"
|
||||
multiple
|
||||
onChange={(e) => handleFileSelect(e.target.files)}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
{/* Attach button */}
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={connectionStatus !== 'connected'}
|
||||
className="neo-btn neo-btn-ghost p-3"
|
||||
title="Attach image (JPEG, PNG - max 5MB)"
|
||||
>
|
||||
<Paperclip size={18} />
|
||||
</button>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={
|
||||
pendingAttachments.length > 0
|
||||
? 'Add a message with your image(s)...'
|
||||
: 'Describe the features you want to add...'
|
||||
}
|
||||
className="neo-input flex-1"
|
||||
disabled={isLoading || connectionStatus !== 'connected'}
|
||||
/>
|
||||
<button
|
||||
onClick={handleSendMessage}
|
||||
disabled={
|
||||
(!input.trim() && pendingAttachments.length === 0) ||
|
||||
isLoading ||
|
||||
connectionStatus !== 'connected'
|
||||
}
|
||||
className="neo-btn neo-btn-primary px-6"
|
||||
>
|
||||
<Send size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Help text */}
|
||||
<p className="text-xs text-[var(--color-neo-text-secondary)] mt-2">
|
||||
Press Enter to send. Drag & drop or click <Paperclip size={12} className="inline" /> to attach images.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Completion footer */}
|
||||
{isComplete && (
|
||||
<div className="p-4 border-t-3 border-[var(--color-neo-border)] bg-[var(--color-neo-done)]">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 size={20} />
|
||||
<span className="font-bold">
|
||||
Added {featuresCreated} new feature{featuresCreated !== 1 ? 's' : ''}!
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onComplete(featuresCreated)}
|
||||
className="neo-btn bg-white"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
41
ui/src/components/ExpandProjectModal.tsx
Normal file
41
ui/src/components/ExpandProjectModal.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Expand Project Modal
|
||||
*
|
||||
* Full-screen modal wrapper for the ExpandProjectChat component.
|
||||
* Allows users to add multiple features to an existing project via AI.
|
||||
*/
|
||||
|
||||
import { ExpandProjectChat } from './ExpandProjectChat'
|
||||
|
||||
interface ExpandProjectModalProps {
|
||||
isOpen: boolean
|
||||
projectName: string
|
||||
onClose: () => void
|
||||
onFeaturesAdded: () => void // Called to refresh feature list
|
||||
}
|
||||
|
||||
export function ExpandProjectModal({
|
||||
isOpen,
|
||||
projectName,
|
||||
onClose,
|
||||
onFeaturesAdded,
|
||||
}: ExpandProjectModalProps) {
|
||||
if (!isOpen) return null
|
||||
|
||||
const handleComplete = (featuresAdded: number) => {
|
||||
if (featuresAdded > 0) {
|
||||
onFeaturesAdded()
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 bg-[var(--color-neo-bg)]">
|
||||
<ExpandProjectChat
|
||||
projectName={projectName}
|
||||
onComplete={handleComplete}
|
||||
onCancel={onClose}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
323
ui/src/hooks/useExpandChat.ts
Normal file
323
ui/src/hooks/useExpandChat.ts
Normal file
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* Hook for managing project expansion chat WebSocket connection
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useRef, useEffect } from 'react'
|
||||
import type { ChatMessage, ImageAttachment, ExpandChatServerMessage } from '../lib/types'
|
||||
|
||||
type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error'
|
||||
|
||||
interface CreatedFeature {
|
||||
id: number
|
||||
name: string
|
||||
category: string
|
||||
}
|
||||
|
||||
interface UseExpandChatOptions {
|
||||
projectName: string
|
||||
onComplete?: (totalAdded: number) => void
|
||||
onError?: (error: string) => void
|
||||
}
|
||||
|
||||
interface UseExpandChatReturn {
|
||||
messages: ChatMessage[]
|
||||
isLoading: boolean
|
||||
isComplete: boolean
|
||||
connectionStatus: ConnectionStatus
|
||||
featuresCreated: number
|
||||
recentFeatures: CreatedFeature[]
|
||||
start: () => void
|
||||
sendMessage: (content: string, attachments?: ImageAttachment[]) => void
|
||||
disconnect: () => void
|
||||
}
|
||||
|
||||
function generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
|
||||
}
|
||||
|
||||
export function useExpandChat({
|
||||
projectName,
|
||||
onComplete,
|
||||
onError,
|
||||
}: UseExpandChatOptions): UseExpandChatReturn {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isComplete, setIsComplete] = useState(false)
|
||||
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('disconnected')
|
||||
const [featuresCreated, setFeaturesCreated] = useState(0)
|
||||
const [recentFeatures, setRecentFeatures] = useState<CreatedFeature[]>([])
|
||||
|
||||
const wsRef = useRef<WebSocket | null>(null)
|
||||
const currentAssistantMessageRef = useRef<string | null>(null)
|
||||
const reconnectAttempts = useRef(0)
|
||||
const maxReconnectAttempts = 3
|
||||
const pingIntervalRef = useRef<number | null>(null)
|
||||
const reconnectTimeoutRef = useRef<number | null>(null)
|
||||
const isCompleteRef = useRef(false)
|
||||
|
||||
// Keep isCompleteRef in sync with isComplete state
|
||||
useEffect(() => {
|
||||
isCompleteRef.current = isComplete
|
||||
}, [isComplete])
|
||||
|
||||
// Clean up on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (pingIntervalRef.current) {
|
||||
clearInterval(pingIntervalRef.current)
|
||||
}
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current)
|
||||
}
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close()
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const connect = useCallback(() => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||
return
|
||||
}
|
||||
|
||||
setConnectionStatus('connecting')
|
||||
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const host = window.location.host
|
||||
const wsUrl = `${protocol}//${host}/api/expand/ws/${encodeURIComponent(projectName)}`
|
||||
|
||||
const ws = new WebSocket(wsUrl)
|
||||
wsRef.current = ws
|
||||
|
||||
ws.onopen = () => {
|
||||
setConnectionStatus('connected')
|
||||
reconnectAttempts.current = 0
|
||||
|
||||
// Start ping interval to keep connection alive
|
||||
pingIntervalRef.current = window.setInterval(() => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'ping' }))
|
||||
}
|
||||
}, 30000)
|
||||
}
|
||||
|
||||
ws.onclose = () => {
|
||||
setConnectionStatus('disconnected')
|
||||
if (pingIntervalRef.current) {
|
||||
clearInterval(pingIntervalRef.current)
|
||||
pingIntervalRef.current = null
|
||||
}
|
||||
|
||||
// Attempt reconnection if not intentionally closed
|
||||
if (reconnectAttempts.current < maxReconnectAttempts && !isCompleteRef.current) {
|
||||
reconnectAttempts.current++
|
||||
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.current), 10000)
|
||||
reconnectTimeoutRef.current = window.setTimeout(connect, delay)
|
||||
}
|
||||
}
|
||||
|
||||
ws.onerror = () => {
|
||||
setConnectionStatus('error')
|
||||
onError?.('WebSocket connection error')
|
||||
}
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data) as ExpandChatServerMessage
|
||||
|
||||
switch (data.type) {
|
||||
case 'text': {
|
||||
// Append text to current assistant message or create new one
|
||||
setMessages((prev) => {
|
||||
const lastMessage = prev[prev.length - 1]
|
||||
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
|
||||
// Append to existing streaming message
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastMessage,
|
||||
content: lastMessage.content + data.content,
|
||||
},
|
||||
]
|
||||
} else {
|
||||
// Create new assistant message
|
||||
currentAssistantMessageRef.current = generateId()
|
||||
return [
|
||||
...prev,
|
||||
{
|
||||
id: currentAssistantMessageRef.current,
|
||||
role: 'assistant',
|
||||
content: data.content,
|
||||
timestamp: new Date(),
|
||||
isStreaming: true,
|
||||
},
|
||||
]
|
||||
}
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'features_created': {
|
||||
// Features were created
|
||||
setFeaturesCreated((prev) => prev + data.count)
|
||||
setRecentFeatures(data.features)
|
||||
|
||||
// Add system message about feature creation
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: generateId(),
|
||||
role: 'system',
|
||||
content: `Created ${data.count} new feature${data.count !== 1 ? 's' : ''}!`,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
])
|
||||
break
|
||||
}
|
||||
|
||||
case 'expansion_complete': {
|
||||
setIsComplete(true)
|
||||
setIsLoading(false)
|
||||
|
||||
// Mark current message as done
|
||||
setMessages((prev) => {
|
||||
const lastMessage = prev[prev.length - 1]
|
||||
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{ ...lastMessage, isStreaming: false },
|
||||
]
|
||||
}
|
||||
return prev
|
||||
})
|
||||
|
||||
onComplete?.(data.total_added)
|
||||
break
|
||||
}
|
||||
|
||||
case 'error': {
|
||||
setIsLoading(false)
|
||||
onError?.(data.content)
|
||||
|
||||
// Add error as system message
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: generateId(),
|
||||
role: 'system',
|
||||
content: `Error: ${data.content}`,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
])
|
||||
break
|
||||
}
|
||||
|
||||
case 'pong': {
|
||||
// Keep-alive response, nothing to do
|
||||
break
|
||||
}
|
||||
|
||||
case 'response_done': {
|
||||
// Response complete - hide loading indicator and mark message as done
|
||||
setIsLoading(false)
|
||||
|
||||
// Mark current message as done streaming
|
||||
setMessages((prev) => {
|
||||
const lastMessage = prev[prev.length - 1]
|
||||
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{ ...lastMessage, isStreaming: false },
|
||||
]
|
||||
}
|
||||
return prev
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse WebSocket message:', e)
|
||||
}
|
||||
}
|
||||
}, [projectName, onComplete, onError])
|
||||
|
||||
const start = useCallback(() => {
|
||||
connect()
|
||||
|
||||
// Wait for connection then send start message
|
||||
const checkAndSend = () => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||
setIsLoading(true)
|
||||
wsRef.current.send(JSON.stringify({ type: 'start' }))
|
||||
} else if (wsRef.current?.readyState === WebSocket.CONNECTING) {
|
||||
setTimeout(checkAndSend, 100)
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(checkAndSend, 100)
|
||||
}, [connect])
|
||||
|
||||
const sendMessage = useCallback((content: string, attachments?: ImageAttachment[]) => {
|
||||
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
||||
onError?.('Not connected')
|
||||
return
|
||||
}
|
||||
|
||||
// Add user message to chat (with attachments for display)
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: generateId(),
|
||||
role: 'user',
|
||||
content,
|
||||
attachments,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
])
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
// Build message payload
|
||||
const payload: { type: string; content: string; attachments?: Array<{ filename: string; mimeType: string; base64Data: string }> } = {
|
||||
type: 'message',
|
||||
content,
|
||||
}
|
||||
|
||||
// Add attachments if present (send base64 data, not preview URL)
|
||||
if (attachments && attachments.length > 0) {
|
||||
payload.attachments = attachments.map((a) => ({
|
||||
filename: a.filename,
|
||||
mimeType: a.mimeType,
|
||||
base64Data: a.base64Data,
|
||||
}))
|
||||
}
|
||||
|
||||
// Send to server
|
||||
wsRef.current.send(JSON.stringify(payload))
|
||||
}, [onError])
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
reconnectAttempts.current = maxReconnectAttempts // Prevent reconnection
|
||||
if (pingIntervalRef.current) {
|
||||
clearInterval(pingIntervalRef.current)
|
||||
pingIntervalRef.current = null
|
||||
}
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close()
|
||||
wsRef.current = null
|
||||
}
|
||||
setConnectionStatus('disconnected')
|
||||
}, [])
|
||||
|
||||
return {
|
||||
messages,
|
||||
isLoading,
|
||||
isComplete,
|
||||
connectionStatus,
|
||||
featuresCreated,
|
||||
recentFeatures,
|
||||
start,
|
||||
sendMessage,
|
||||
disconnect,
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import type {
|
||||
FeatureListResponse,
|
||||
Feature,
|
||||
FeatureCreate,
|
||||
FeatureBulkCreate,
|
||||
FeatureBulkCreateResponse,
|
||||
AgentStatusResponse,
|
||||
AgentActionResponse,
|
||||
SetupStatus,
|
||||
@@ -111,6 +113,16 @@ export async function skipFeature(projectName: string, featureId: number): Promi
|
||||
})
|
||||
}
|
||||
|
||||
export async function createFeaturesBulk(
|
||||
projectName: string,
|
||||
bulk: FeatureBulkCreate
|
||||
): Promise<FeatureBulkCreateResponse> {
|
||||
return fetchJSON(`/projects/${encodeURIComponent(projectName)}/features/bulk`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(bulk),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Agent API
|
||||
// ============================================================================
|
||||
|
||||
@@ -295,3 +295,37 @@ export type AssistantChatServerMessage =
|
||||
| AssistantChatErrorMessage
|
||||
| AssistantChatConversationCreatedMessage
|
||||
| AssistantChatPongMessage
|
||||
|
||||
// ============================================================================
|
||||
// Expand Chat Types
|
||||
// ============================================================================
|
||||
|
||||
export interface ExpandChatFeaturesCreatedMessage {
|
||||
type: 'features_created'
|
||||
count: number
|
||||
features: { id: number; name: string; category: string }[]
|
||||
}
|
||||
|
||||
export interface ExpandChatCompleteMessage {
|
||||
type: 'expansion_complete'
|
||||
total_added: number
|
||||
}
|
||||
|
||||
export type ExpandChatServerMessage =
|
||||
| SpecChatTextMessage // Reuse text message type
|
||||
| ExpandChatFeaturesCreatedMessage
|
||||
| ExpandChatCompleteMessage
|
||||
| SpecChatErrorMessage // Reuse error message type
|
||||
| SpecChatPongMessage // Reuse pong message type
|
||||
| SpecChatResponseDoneMessage // Reuse response_done type
|
||||
|
||||
// Bulk feature creation
|
||||
export interface FeatureBulkCreate {
|
||||
features: FeatureCreate[]
|
||||
starting_priority?: number
|
||||
}
|
||||
|
||||
export interface FeatureBulkCreateResponse {
|
||||
created: number
|
||||
features: Feature[]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user