adding a queue system to the agent runner

This commit is contained in:
Test User
2025-12-26 10:59:13 -05:00
parent f95282069d
commit 17c1c733b7
24 changed files with 1753 additions and 65 deletions

View File

@@ -18,6 +18,7 @@ import {
ChevronDown,
FileText,
Square,
ListOrdered,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useElectronAgent } from '@/hooks/use-electron-agent';
@@ -86,6 +87,10 @@ export function AgentView() {
clearHistory,
stopExecution,
error: agentError,
serverQueue,
addToServerQueue,
removeFromServerQueue,
clearServerQueue,
} = useElectronAgent({
sessionId: currentSessionId || '',
workingDirectory: currentProject?.path,
@@ -134,11 +139,7 @@ export function AgentView() {
}, [currentProject?.path]);
const handleSend = useCallback(async () => {
if (
(!input.trim() && selectedImages.length === 0 && selectedTextFiles.length === 0) ||
isProcessing
)
return;
if (!input.trim() && selectedImages.length === 0 && selectedTextFiles.length === 0) return;
const messageContent = input;
const messageImages = selectedImages;
@@ -149,8 +150,13 @@ export function AgentView() {
setSelectedTextFiles([]);
setShowImageDropZone(false);
await sendMessage(messageContent, messageImages, messageTextFiles);
}, [input, selectedImages, selectedTextFiles, isProcessing, sendMessage]);
// If already processing, add to server queue instead
if (isProcessing) {
await addToServerQueue(messageContent, messageImages, messageTextFiles);
} else {
await sendMessage(messageContent, messageImages, messageTextFiles);
}
}, [input, selectedImages, selectedTextFiles, isProcessing, sendMessage, addToServerQueue]);
const handleImagesSelected = useCallback((images: ImageAttachment[]) => {
setSelectedImages(images);
@@ -536,41 +542,6 @@ export function AgentView() {
{/* Status indicators & actions */}
<div className="flex items-center gap-3">
{/* Model Selector */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
className="h-8 gap-1.5 text-xs font-medium"
disabled={isProcessing}
data-testid="model-selector"
>
<Bot className="w-3.5 h-3.5" />
{CLAUDE_MODELS.find((m) => m.id === selectedModel)?.label.replace(
'Claude ',
''
) || 'Sonnet'}
<ChevronDown className="w-3 h-3 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
{CLAUDE_MODELS.map((model) => (
<DropdownMenuItem
key={model.id}
onClick={() => setSelectedModel(model.id)}
className={cn('cursor-pointer', selectedModel === model.id && 'bg-accent')}
data-testid={`model-option-${model.id}`}
>
<div className="flex flex-col">
<span className="font-medium">{model.label}</span>
<span className="text-xs text-muted-foreground">{model.description}</span>
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{currentTool && (
<div className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/50 px-3 py-1.5 rounded-full border border-border">
<Wrench className="w-3 h-3 text-primary" />
@@ -760,10 +731,52 @@ export function AgentView() {
images={selectedImages}
maxFiles={5}
className="mb-4"
disabled={isProcessing || !isConnected}
disabled={!isConnected}
/>
)}
{/* Queued Prompts List */}
{serverQueue.length > 0 && (
<div className="mb-4 space-y-2">
<div className="flex items-center justify-between">
<p className="text-xs font-medium text-muted-foreground">
{serverQueue.length} prompt{serverQueue.length > 1 ? 's' : ''} queued
</p>
<button
onClick={clearServerQueue}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Clear all
</button>
</div>
<div className="space-y-1.5">
{serverQueue.map((item, index) => (
<div
key={item.id}
className="group flex items-center gap-2 text-sm bg-muted/50 rounded-lg px-3 py-2 border border-border"
>
<span className="text-xs text-muted-foreground font-medium min-w-[1.5rem]">
{index + 1}.
</span>
<span className="flex-1 truncate text-foreground">{item.message}</span>
{item.imagePaths && item.imagePaths.length > 0 && (
<span className="text-xs text-muted-foreground">
+{item.imagePaths.length} file{item.imagePaths.length > 1 ? 's' : ''}
</span>
)}
<button
onClick={() => removeFromServerQueue(item.id)}
className="opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 hover:text-destructive rounded transition-all"
title="Remove from queue"
>
<X className="w-3 h-3" />
</button>
</div>
))}
</div>
</div>
)}
{/* Selected Files Preview - only show when ImageDropZone is hidden to avoid duplicate display */}
{(selectedImages.length > 0 || selectedTextFiles.length > 0) && !showImageDropZone && (
<div className="mb-4 space-y-2">
@@ -778,7 +791,6 @@ export function AgentView() {
setSelectedTextFiles([]);
}}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
disabled={isProcessing}
>
Clear all
</button>
@@ -869,13 +881,17 @@ export function AgentView() {
<Input
ref={inputRef}
placeholder={
isDragOver ? 'Drop your files here...' : 'Describe what you want to build...'
isDragOver
? 'Drop your files here...'
: isProcessing
? 'Type to queue another prompt...'
: 'Describe what you want to build...'
}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={handleKeyPress}
onPaste={handlePaste}
disabled={isProcessing || !isConnected}
disabled={!isConnected}
data-testid="agent-input"
className={cn(
'h-11 bg-background border-border rounded-xl pl-4 pr-20 text-sm transition-all',
@@ -899,12 +915,44 @@ export function AgentView() {
)}
</div>
{/* Model Selector */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="h-11 gap-1 text-xs font-medium rounded-xl border-border px-2.5"
data-testid="model-selector"
>
{CLAUDE_MODELS.find((m) => m.id === selectedModel)?.label.replace(
'Claude ',
''
) || 'Sonnet'}
<ChevronDown className="w-3 h-3 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
{CLAUDE_MODELS.map((model) => (
<DropdownMenuItem
key={model.id}
onClick={() => setSelectedModel(model.id)}
className={cn('cursor-pointer', selectedModel === model.id && 'bg-accent')}
data-testid={`model-option-${model.id}`}
>
<div className="flex flex-col">
<span className="font-medium">{model.label}</span>
<span className="text-xs text-muted-foreground">{model.description}</span>
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* File Attachment Button */}
<Button
variant="outline"
size="icon"
onClick={toggleImageDropZone}
disabled={isProcessing || !isConnected}
disabled={!isConnected}
className={cn(
'h-11 w-11 rounded-xl border-border',
showImageDropZone && 'bg-primary/10 text-primary border-primary/30',
@@ -916,8 +964,8 @@ export function AgentView() {
<Paperclip className="w-4 h-4" />
</Button>
{/* Send / Stop Button */}
{isProcessing ? (
{/* Stop Button (only when processing) */}
{isProcessing && (
<Button
onClick={stopExecution}
disabled={!isConnected}
@@ -928,21 +976,24 @@ export function AgentView() {
>
<Square className="w-4 h-4 fill-current" />
</Button>
) : (
<Button
onClick={handleSend}
disabled={
(!input.trim() &&
selectedImages.length === 0 &&
selectedTextFiles.length === 0) ||
!isConnected
}
className="h-11 px-4 rounded-xl"
data-testid="send-message"
>
<Send className="w-4 h-4" />
</Button>
)}
{/* Send / Queue Button */}
<Button
onClick={handleSend}
disabled={
(!input.trim() &&
selectedImages.length === 0 &&
selectedTextFiles.length === 0) ||
!isConnected
}
className="h-11 px-4 rounded-xl"
variant={isProcessing ? 'outline' : 'default'}
data-testid="send-message"
title={isProcessing ? 'Add to queue' : 'Send message'}
>
{isProcessing ? <ListOrdered className="w-4 h-4" /> : <Send className="w-4 h-4" />}
</Button>
</div>
{/* Keyboard hint */}

View File

@@ -9,7 +9,9 @@ import {
import { useAppStore, Feature } from '@/store/app-store';
import { getElectronAPI } from '@/lib/electron';
import type { AutoModeEvent } from '@/types/electron';
import type { BacklogPlanResult } from '@automaker/types';
import { pathsEqual } from '@/lib/utils';
import { toast } from 'sonner';
import { getBlockingDependencies } from '@automaker/dependency-resolver';
import { BoardBackgroundModal } from '@/components/dialogs/board-background-modal';
import { RefreshCw } from 'lucide-react';
@@ -25,6 +27,7 @@ import { GraphView } from './graph-view';
import {
AddFeatureDialog,
AgentOutputModal,
BacklogPlanDialog,
CompletedFeaturesModal,
ArchiveAllVerifiedDialog,
DeleteCompletedFeatureDialog,
@@ -125,6 +128,11 @@ export function BoardView() {
} | null>(null);
const [worktreeRefreshKey, setWorktreeRefreshKey] = useState(0);
// Backlog plan dialog state
const [showPlanDialog, setShowPlanDialog] = useState(false);
const [pendingBacklogPlan, setPendingBacklogPlan] = useState<BacklogPlanResult | null>(null);
const [isGeneratingPlan, setIsGeneratingPlan] = useState(false);
// Follow-up state hook
const {
showFollowUpDialog,
@@ -578,6 +586,37 @@ export function BoardView() {
return unsubscribe;
}, [currentProject]);
// Listen for backlog plan events (for background generation)
useEffect(() => {
const api = getElectronAPI();
if (!api?.backlogPlan) return;
const unsubscribe = api.backlogPlan.onEvent(
(event: { type: string; result?: BacklogPlanResult; error?: string }) => {
if (event.type === 'backlog_plan_complete') {
setIsGeneratingPlan(false);
if (event.result && event.result.changes?.length > 0) {
setPendingBacklogPlan(event.result);
toast.success('Plan ready! Click to review.', {
duration: 10000,
action: {
label: 'Review',
onClick: () => setShowPlanDialog(true),
},
});
} else {
toast.info('No changes generated. Try again with a different prompt.');
}
} else if (event.type === 'backlog_plan_error') {
setIsGeneratingPlan(false);
toast.error(`Plan generation failed: ${event.error}`);
}
}
);
return unsubscribe;
}, []);
useEffect(() => {
if (!autoMode.isRunning || !currentProject) {
return;
@@ -935,6 +974,7 @@ export function BoardView() {
}
}}
onAddFeature={() => setShowAddDialog(true)}
onOpenPlanDialog={() => setShowPlanDialog(true)}
addFeatureShortcut={{
key: shortcuts.addFeature,
action: () => setShowAddDialog(true),
@@ -1172,6 +1212,18 @@ export function BoardView() {
setIsGenerating={setIsGeneratingSuggestions}
/>
{/* Backlog Plan Dialog */}
<BacklogPlanDialog
open={showPlanDialog}
onClose={() => setShowPlanDialog(false)}
projectPath={currentProject.path}
onPlanApplied={loadFeatures}
pendingPlanResult={pendingBacklogPlan}
setPendingPlanResult={setPendingBacklogPlan}
isGeneratingPlan={isGeneratingPlan}
setIsGeneratingPlan={setIsGeneratingPlan}
/>
{/* Plan Approval Dialog */}
<PlanApprovalDialog
open={pendingPlanApproval !== null}

View File

@@ -1,8 +1,9 @@
import { HotkeyButton } from '@/components/ui/hotkey-button';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Plus, Bot } from 'lucide-react';
import { Plus, Bot, Wand2 } from 'lucide-react';
import { KeyboardShortcut } from '@/hooks/use-keyboard-shortcuts';
import { ClaudeUsagePopover } from '@/components/claude-usage-popover';
import { useAppStore } from '@/store/app-store';
@@ -15,6 +16,7 @@ interface BoardHeaderProps {
isAutoModeRunning: boolean;
onAutoModeToggle: (enabled: boolean) => void;
onAddFeature: () => void;
onOpenPlanDialog: () => void;
addFeatureShortcut: KeyboardShortcut;
isMounted: boolean;
}
@@ -27,6 +29,7 @@ export function BoardHeader({
isAutoModeRunning,
onAutoModeToggle,
onAddFeature,
onOpenPlanDialog,
addFeatureShortcut,
isMounted,
}: BoardHeaderProps) {
@@ -89,6 +92,16 @@ export function BoardHeader({
</div>
)}
<Button
size="sm"
variant="outline"
onClick={onOpenPlanDialog}
data-testid="plan-backlog-button"
>
<Wand2 className="w-4 h-4 mr-2" />
Plan
</Button>
<HotkeyButton
size="sm"
onClick={onAddFeature}

View File

@@ -0,0 +1,418 @@
import { useEffect, useState, useCallback } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import {
Loader2,
Wand2,
Check,
Plus,
Pencil,
Trash2,
ChevronDown,
ChevronRight,
} from 'lucide-react';
import { getElectronAPI } from '@/lib/electron';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import type { BacklogPlanResult, BacklogChange } from '@automaker/types';
interface BacklogPlanDialogProps {
open: boolean;
onClose: () => void;
projectPath: string;
onPlanApplied?: () => void;
// Props for background generation
pendingPlanResult: BacklogPlanResult | null;
setPendingPlanResult: (result: BacklogPlanResult | null) => void;
isGeneratingPlan: boolean;
setIsGeneratingPlan: (generating: boolean) => void;
}
type DialogMode = 'input' | 'review' | 'applying';
export function BacklogPlanDialog({
open,
onClose,
projectPath,
onPlanApplied,
pendingPlanResult,
setPendingPlanResult,
isGeneratingPlan,
setIsGeneratingPlan,
}: BacklogPlanDialogProps) {
const [mode, setMode] = useState<DialogMode>('input');
const [prompt, setPrompt] = useState('');
const [expandedChanges, setExpandedChanges] = useState<Set<number>>(new Set());
const [selectedChanges, setSelectedChanges] = useState<Set<number>>(new Set());
// Set mode based on whether we have a pending result
useEffect(() => {
if (open) {
if (pendingPlanResult) {
setMode('review');
// Select all changes by default
setSelectedChanges(new Set(pendingPlanResult.changes.map((_, i) => i)));
setExpandedChanges(new Set());
} else {
setMode('input');
}
}
}, [open, pendingPlanResult]);
const handleGenerate = useCallback(async () => {
if (!prompt.trim()) {
toast.error('Please enter a prompt describing the changes you want');
return;
}
const api = getElectronAPI();
if (!api?.backlogPlan) {
toast.error('API not available');
return;
}
// Start generation in background
setIsGeneratingPlan(true);
const result = await api.backlogPlan.generate(projectPath, prompt);
if (!result.success) {
setIsGeneratingPlan(false);
toast.error(result.error || 'Failed to start plan generation');
return;
}
// Show toast and close dialog - generation runs in background
toast.info('Generating plan... This will be ready soon!', {
duration: 3000,
});
setPrompt('');
onClose();
}, [projectPath, prompt, setIsGeneratingPlan, onClose]);
const handleApply = useCallback(async () => {
if (!pendingPlanResult) return;
// Filter to only selected changes
const selectedChangesList = pendingPlanResult.changes.filter((_, index) =>
selectedChanges.has(index)
);
if (selectedChangesList.length === 0) {
toast.error('Please select at least one change to apply');
return;
}
const api = getElectronAPI();
if (!api?.backlogPlan) {
toast.error('API not available');
return;
}
setMode('applying');
// Create a filtered plan result with only selected changes
const filteredPlanResult: BacklogPlanResult = {
...pendingPlanResult,
changes: selectedChangesList,
// Filter dependency updates to only include those for selected features
dependencyUpdates:
pendingPlanResult.dependencyUpdates?.filter((update) => {
const isDeleting = selectedChangesList.some(
(c) => c.type === 'delete' && c.featureId === update.featureId
);
return !isDeleting;
}) || [],
};
const result = await api.backlogPlan.apply(projectPath, filteredPlanResult);
if (result.success) {
toast.success(`Applied ${result.appliedChanges?.length || 0} changes`);
setPendingPlanResult(null);
onPlanApplied?.();
onClose();
} else {
toast.error(result.error || 'Failed to apply plan');
setMode('review');
}
}, [
projectPath,
pendingPlanResult,
selectedChanges,
setPendingPlanResult,
onPlanApplied,
onClose,
]);
const handleDiscard = useCallback(() => {
setPendingPlanResult(null);
setMode('input');
}, [setPendingPlanResult]);
const toggleChangeExpanded = (index: number) => {
setExpandedChanges((prev) => {
const next = new Set(prev);
if (next.has(index)) {
next.delete(index);
} else {
next.add(index);
}
return next;
});
};
const toggleChangeSelected = (index: number) => {
setSelectedChanges((prev) => {
const next = new Set(prev);
if (next.has(index)) {
next.delete(index);
} else {
next.add(index);
}
return next;
});
};
const toggleAllChanges = () => {
if (!pendingPlanResult) return;
if (selectedChanges.size === pendingPlanResult.changes.length) {
setSelectedChanges(new Set());
} else {
setSelectedChanges(new Set(pendingPlanResult.changes.map((_, i) => i)));
}
};
const getChangeIcon = (type: BacklogChange['type']) => {
switch (type) {
case 'add':
return <Plus className="w-4 h-4 text-green-500" />;
case 'update':
return <Pencil className="w-4 h-4 text-yellow-500" />;
case 'delete':
return <Trash2 className="w-4 h-4 text-red-500" />;
}
};
const getChangeLabel = (change: BacklogChange) => {
switch (change.type) {
case 'add':
return change.feature?.title || 'New Feature';
case 'update':
return `Update: ${change.featureId}`;
case 'delete':
return `Delete: ${change.featureId}`;
}
};
const renderContent = () => {
switch (mode) {
case 'input':
return (
<div className="space-y-4">
<div className="text-sm text-muted-foreground">
Describe the changes you want to make to your backlog. The AI will analyze your
current features and propose additions, updates, or deletions.
</div>
<Textarea
placeholder="e.g., Add authentication features with login, signup, and password reset. Also add a dashboard feature that depends on authentication."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
className="min-h-[150px] resize-none"
autoFocus
/>
<div className="text-xs text-muted-foreground">
The AI will automatically handle dependency graph updates when adding or removing
features.
</div>
{isGeneratingPlan && (
<div className="flex items-center gap-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3">
<Loader2 className="w-4 h-4 animate-spin" />A plan is currently being generated in
the background...
</div>
)}
</div>
);
case 'review':
if (!pendingPlanResult) return null;
const additions = pendingPlanResult.changes.filter((c) => c.type === 'add');
const updates = pendingPlanResult.changes.filter((c) => c.type === 'update');
const deletions = pendingPlanResult.changes.filter((c) => c.type === 'delete');
const allSelected = selectedChanges.size === pendingPlanResult.changes.length;
const someSelected = selectedChanges.size > 0 && !allSelected;
return (
<div className="space-y-4">
{/* Summary */}
<div className="rounded-lg border bg-muted/30 p-4">
<h4 className="font-medium mb-2">Summary</h4>
<p className="text-sm text-muted-foreground">{pendingPlanResult.summary}</p>
</div>
{/* Stats */}
<div className="flex gap-4 text-sm">
{additions.length > 0 && (
<span className="flex items-center gap-1 text-green-600">
<Plus className="w-4 h-4" /> {additions.length} additions
</span>
)}
{updates.length > 0 && (
<span className="flex items-center gap-1 text-yellow-600">
<Pencil className="w-4 h-4" /> {updates.length} updates
</span>
)}
{deletions.length > 0 && (
<span className="flex items-center gap-1 text-red-600">
<Trash2 className="w-4 h-4" /> {deletions.length} deletions
</span>
)}
</div>
{/* Select all */}
<div className="flex items-center gap-2 pb-2 border-b">
<Checkbox
id="select-all"
checked={allSelected}
// @ts-expect-error - indeterminate is valid but not in types
indeterminate={someSelected}
onCheckedChange={toggleAllChanges}
/>
<label htmlFor="select-all" className="text-sm font-medium cursor-pointer">
{allSelected ? 'Deselect all' : 'Select all'} ({selectedChanges.size}/
{pendingPlanResult.changes.length})
</label>
</div>
{/* Changes list */}
<div className="max-h-[300px] overflow-y-auto space-y-2">
{pendingPlanResult.changes.map((change, index) => (
<div
key={index}
className={cn(
'rounded-lg border p-3',
change.type === 'add' && 'border-green-500/30 bg-green-500/5',
change.type === 'update' && 'border-yellow-500/30 bg-yellow-500/5',
change.type === 'delete' && 'border-red-500/30 bg-red-500/5',
!selectedChanges.has(index) && 'opacity-50'
)}
>
<div className="flex items-center gap-2">
<Checkbox
checked={selectedChanges.has(index)}
onCheckedChange={() => toggleChangeSelected(index)}
/>
<button
className="flex-1 flex items-center gap-2 text-left"
onClick={() => toggleChangeExpanded(index)}
>
{expandedChanges.has(index) ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
)}
{getChangeIcon(change.type)}
<span className="font-medium text-sm">{getChangeLabel(change)}</span>
</button>
</div>
{expandedChanges.has(index) && (
<div className="mt-3 pl-10 space-y-2 text-sm">
<p className="text-muted-foreground">{change.reason}</p>
{change.feature && (
<div className="rounded bg-background/50 p-2 text-xs font-mono">
{change.feature.description && (
<p className="text-foreground">{change.feature.description}</p>
)}
{change.feature.dependencies &&
change.feature.dependencies.length > 0 && (
<p className="text-muted-foreground mt-1">
Dependencies: {change.feature.dependencies.join(', ')}
</p>
)}
</div>
)}
</div>
)}
</div>
))}
</div>
</div>
);
case 'applying':
return (
<div className="flex flex-col items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-primary mb-4" />
<p className="text-muted-foreground">Applying changes...</p>
</div>
);
}
};
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wand2 className="w-5 h-5 text-primary" />
{mode === 'review' ? 'Review Plan' : 'Plan Backlog Changes'}
</DialogTitle>
<DialogDescription>
{mode === 'review'
? 'Select which changes to apply to your backlog'
: 'Use AI to add, update, or remove features from your backlog'}
</DialogDescription>
</DialogHeader>
<div className="py-4">{renderContent()}</div>
<DialogFooter>
{mode === 'input' && (
<>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button onClick={handleGenerate} disabled={!prompt.trim() || isGeneratingPlan}>
{isGeneratingPlan ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Generating...
</>
) : (
<>
<Wand2 className="w-4 h-4 mr-2" />
Generate Plan
</>
)}
</Button>
</>
)}
{mode === 'review' && (
<>
<Button variant="outline" onClick={handleDiscard}>
Discard
</Button>
<Button variant="outline" onClick={onClose}>
Review Later
</Button>
<Button onClick={handleApply} disabled={selectedChanges.size === 0}>
<Check className="w-4 h-4 mr-2" />
Apply {selectedChanges.size} Change{selectedChanges.size !== 1 ? 's' : ''}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,5 +1,6 @@
export { AddFeatureDialog } from './add-feature-dialog';
export { AgentOutputModal } from './agent-output-modal';
export { BacklogPlanDialog } from './backlog-plan-dialog';
export { CompletedFeaturesModal } from './completed-features-modal';
export { ArchiveAllVerifiedDialog } from './archive-all-verified-dialog';
export { DeleteCompletedFeatureDialog } from './delete-completed-feature-dialog';

View File

@@ -12,6 +12,15 @@ interface UseElectronAgentOptions {
onToolUse?: (toolName: string, toolInput: unknown) => void;
}
// Server-side queued prompt type
interface QueuedPrompt {
id: string;
message: string;
imagePaths?: string[];
model?: string;
addedAt: string;
}
interface UseElectronAgentResult {
messages: Message[];
isProcessing: boolean;
@@ -24,7 +33,7 @@ interface UseElectronAgentResult {
stopExecution: () => Promise<void>;
clearHistory: () => Promise<void>;
error: string | null;
// Queue-related state
// Client-side queue (local)
queuedMessages: {
id: string;
content: string;
@@ -34,6 +43,15 @@ interface UseElectronAgentResult {
}[];
isQueueProcessing: boolean;
clearMessageQueue: () => void;
// Server-side queue (persistent, auto-runs)
serverQueue: QueuedPrompt[];
addToServerQueue: (
message: string,
images?: ImageAttachment[],
textFiles?: TextFileAttachment[]
) => Promise<void>;
removeFromServerQueue: (promptId: string) => Promise<void>;
clearServerQueue: () => Promise<void>;
}
/**
@@ -52,6 +70,7 @@ export function useElectronAgent({
const [isProcessing, setIsProcessing] = useState(false);
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const [serverQueue, setServerQueue] = useState<QueuedPrompt[]>([]);
const unsubscribeRef = useRef<(() => void) | null>(null);
const currentMessageRef = useRef<Message | null>(null);
@@ -231,6 +250,12 @@ export function useElectronAgent({
console.log('[useElectronAgent] Stream event for', sessionId, ':', event.type);
switch (event.type) {
case 'started':
// Agent started processing (including from queue)
console.log('[useElectronAgent] Agent started processing for session:', sessionId);
setIsProcessing(true);
break;
case 'message':
// User message added
setMessages((prev) => [...prev, event.message]);
@@ -299,6 +324,18 @@ export function useElectronAgent({
setMessages((prev) => [...prev, errorMessage]);
}
break;
case 'queue_updated':
// Server queue was updated
console.log('[useElectronAgent] Queue updated:', event.queue);
setServerQueue(event.queue || []);
break;
case 'queue_error':
// Error processing a queued prompt
console.error('[useElectronAgent] Queue error:', event.error);
setError(event.error);
break;
}
};
@@ -438,6 +475,102 @@ export function useElectronAgent({
}
}, [sessionId]);
// Add a prompt to the server queue (will auto-run when current task finishes)
const addToServerQueue = useCallback(
async (message: string, images?: ImageAttachment[], textFiles?: TextFileAttachment[]) => {
const api = getElectronAPI();
if (!api?.agent?.queueAdd) {
setError('Queue API not available');
return;
}
try {
// Build message content with text file context
let messageContent = message;
if (textFiles && textFiles.length > 0) {
const contextParts = textFiles.map((file) => {
return `<file name="${file.filename}">\n${file.content}\n</file>`;
});
const contextBlock = `Here are some files for context:\n\n${contextParts.join('\n\n')}\n\n`;
messageContent = contextBlock + message;
}
// Save images and get paths
let imagePaths: string[] | undefined;
if (images && images.length > 0 && api.saveImageToTemp) {
imagePaths = [];
for (const image of images) {
const result = await api.saveImageToTemp(
image.data,
sanitizeFilename(image.filename),
image.mimeType,
workingDirectory
);
if (result.success && result.path) {
imagePaths.push(result.path);
}
}
}
console.log('[useElectronAgent] Adding to server queue');
const result = await api.agent.queueAdd(sessionId, messageContent, imagePaths, model);
if (!result.success) {
setError(result.error || 'Failed to add to queue');
}
} catch (err) {
console.error('[useElectronAgent] Failed to add to queue:', err);
setError(err instanceof Error ? err.message : 'Failed to add to queue');
}
},
[sessionId, workingDirectory, model]
);
// Remove a prompt from the server queue
const removeFromServerQueue = useCallback(
async (promptId: string) => {
const api = getElectronAPI();
if (!api?.agent?.queueRemove) {
setError('Queue API not available');
return;
}
try {
console.log('[useElectronAgent] Removing from server queue:', promptId);
const result = await api.agent.queueRemove(sessionId, promptId);
if (!result.success) {
setError(result.error || 'Failed to remove from queue');
}
} catch (err) {
console.error('[useElectronAgent] Failed to remove from queue:', err);
setError(err instanceof Error ? err.message : 'Failed to remove from queue');
}
},
[sessionId]
);
// Clear the entire server queue
const clearServerQueue = useCallback(async () => {
const api = getElectronAPI();
if (!api?.agent?.queueClear) {
setError('Queue API not available');
return;
}
try {
console.log('[useElectronAgent] Clearing server queue');
const result = await api.agent.queueClear(sessionId);
if (!result.success) {
setError(result.error || 'Failed to clear queue');
}
} catch (err) {
console.error('[useElectronAgent] Failed to clear queue:', err);
setError(err instanceof Error ? err.message : 'Failed to clear queue');
}
}, [sessionId]);
return {
messages,
isProcessing,
@@ -449,5 +582,10 @@ export function useElectronAgent({
queuedMessages,
isQueueProcessing: isProcessingQueue,
clearMessageQueue: clearQueue,
// Server-side queue
serverQueue,
addToServerQueue,
removeFromServerQueue,
clearServerQueue,
};
}

View File

@@ -829,6 +829,47 @@ export class HttpApiClient implements ElectronAPI {
onStream: (callback: (data: unknown) => void): (() => void) => {
return this.subscribeToEvent('agent:stream', callback as EventCallback);
},
// Queue management
queueAdd: (
sessionId: string,
message: string,
imagePaths?: string[],
model?: string
): Promise<{
success: boolean;
queuedPrompt?: {
id: string;
message: string;
imagePaths?: string[];
model?: string;
addedAt: string;
};
error?: string;
}> => this.post('/api/agent/queue/add', { sessionId, message, imagePaths, model }),
queueList: (
sessionId: string
): Promise<{
success: boolean;
queue?: Array<{
id: string;
message: string;
imagePaths?: string[];
model?: string;
addedAt: string;
}>;
error?: string;
}> => this.post('/api/agent/queue/list', { sessionId }),
queueRemove: (
sessionId: string,
promptId: string
): Promise<{ success: boolean; error?: string }> =>
this.post('/api/agent/queue/remove', { sessionId, promptId }),
queueClear: (sessionId: string): Promise<{ success: boolean; error?: string }> =>
this.post('/api/agent/queue/clear', { sessionId }),
};
// Templates API
@@ -1045,6 +1086,45 @@ export class HttpApiClient implements ElectronAPI {
error?: string;
}> => this.post('/api/context/describe-file', { filePath }),
};
// Backlog Plan API
backlogPlan = {
generate: (
projectPath: string,
prompt: string,
model?: string
): Promise<{ success: boolean; error?: string }> =>
this.post('/api/backlog-plan/generate', { projectPath, prompt, model }),
stop: (): Promise<{ success: boolean; error?: string }> =>
this.post('/api/backlog-plan/stop', {}),
status: (): Promise<{ success: boolean; isRunning?: boolean; error?: string }> =>
this.get('/api/backlog-plan/status'),
apply: (
projectPath: string,
plan: {
changes: Array<{
type: 'add' | 'update' | 'delete';
featureId?: string;
feature?: Record<string, unknown>;
reason: string;
}>;
summary: string;
dependencyUpdates: Array<{
featureId: string;
removedDependencies: string[];
addedDependencies: string[];
}>;
}
): Promise<{ success: boolean; appliedChanges?: string[]; error?: string }> =>
this.post('/api/backlog-plan/apply', { projectPath, plan }),
onEvent: (callback: (data: unknown) => void): (() => void) => {
return this.subscribeToEvent('backlog-plan:event', callback as EventCallback);
},
};
}
// Singleton instance