Add slash commands

This commit is contained in:
Alex Gleason committed 2026-01-22 12:39:18 -06:00
1 parent 8d6f5e6320
commit a2c472bfef
3 files changed
+235 -31

No files matched your search

+148 -30
View File
@@ -1,13 +1,20 @@
import { useState, useCallback, memo } from 'react';
import { useState, useCallback, memo, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
export interface SlashCommand {
name: string;
description: string;
action: () => void;
}
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
@@ -29,6 +36,7 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
slashCommands?: SlashCommand[];
}
export const ChatInput = memo(function ChatInput({
@@ -52,10 +60,15 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
slashCommands = [],
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [showSlashCommands, setShowSlashCommands] = useState(false);
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -78,16 +91,72 @@ export const ChatInput = memo(function ChatInput({
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const executeSlashCommand = useCallback((command: SlashCommand) => {
setInput('');
setShowSlashCommands(false);
setSelectedCommandIndex(0);
command.action();
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
// Handle arrow key navigation when slash commands are showing
if (showSlashCommands && filteredCommands.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev < filteredCommands.length - 1 ? prev + 1 : 0
);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev > 0 ? prev - 1 : filteredCommands.length - 1
);
return;
}
// If slash commands are showing and user presses Enter or Tab, select the highlighted command
if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {
e.preventDefault();
executeSlashCommand(filteredCommands[selectedCommandIndex]);
return;
}
// If slash commands are showing and user presses Escape, close the popover
if (e.key === 'Escape') {
e.preventDefault();
setShowSlashCommands(false);
setSelectedCommandIndex(0);
return;
}
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
}, [handleSend, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
const value = e.target.value;
setInput(value);
// Check if slash command autocomplete should be shown
if (value.startsWith('/') && !value.includes(' ') && slashCommands.length > 0) {
const query = value.slice(1).toLowerCase();
const filtered = slashCommands.filter(cmd =>
cmd.name.toLowerCase().includes(query)
);
setFilteredCommands(filtered);
setShowSlashCommands(filtered.length > 0);
setSelectedCommandIndex(0); // Reset selection when filtering
} else {
setShowSlashCommands(false);
setSelectedCommandIndex(0);
}
}, [slashCommands]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
@@ -104,6 +173,29 @@ export const ChatInput = memo(function ChatInput({
setAttachedFiles(prev => [...prev, ...files]);
}, [onDrop]);
// Close popover when clicking outside
useEffect(() => {
if (!showSlashCommands) return;
const handleClickOutside = (e: MouseEvent) => {
// Check if click is outside the popover and textarea
const target = e.target as Node;
if (textareaRef.current && !textareaRef.current.contains(target)) {
setShowSlashCommands(false);
}
};
// Use a slight delay to avoid closing immediately on focus
const timeoutId = setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('click', handleClickOutside);
};
}, [showSlashCommands]);
return (
<div className="border-t p-4">
{/* Chat Input Container */}
@@ -116,33 +208,59 @@ export const ChatInput = memo(function ChatInput({
onDragLeave={onDragLeave}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
<div className="relative">
<Textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{showSlashCommands && filteredCommands.length > 0 && (
<div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border bg-popover p-0 text-popover-foreground shadow-md z-50">
<Command value={filteredCommands[selectedCommandIndex]?.name}>
<CommandList>
<CommandGroup>
{filteredCommands.map((command) => (
<CommandItem
key={command.name}
value={command.name}
onSelect={() => executeSlashCommand(command)}
className="cursor-pointer"
>
<div className="flex flex-col gap-1">
<div className="font-medium">/{command.name}</div>
<div className="text-xs text-muted-foreground">{command.description}</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</div>
)}
</div>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
+28 -1
View File
@@ -53,7 +53,8 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
@@ -104,6 +105,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
const [showToolsDialog, setShowToolsDialog] = useState(false);
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
@@ -634,6 +636,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [onFirstInteraction]);
// Slash commands
const slashCommands: SlashCommand[] = [
{
name: 'new',
description: 'Start a new chat session',
action: () => {
internalStartNewSession();
onNewChat();
},
},
{
name: 'tools',
description: "View the current session's available tools",
action: () => setShowToolsDialog(true),
},
];
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
startNewSession: () => {
@@ -911,6 +930,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
slashCommands={slashCommands}
/>
{/* Onboarding Dialog */}
@@ -918,6 +938,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
{/* Tools Dialog */}
<ToolsDialog
open={showToolsDialog}
onOpenChange={setShowToolsDialog}
tools={tools}
/>
</div>
);
});
@@ -0,0 +1,59 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import OpenAI from 'openai';
interface ToolsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
}
export function ToolsDialog({ open, onOpenChange, tools }: ToolsDialogProps) {
const toolEntries = Object.entries(tools);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle>Available Tools</DialogTitle>
<DialogDescription>
The current session's full list of available tools ({toolEntries.length} tools)
</DialogDescription>
</DialogHeader>
<ScrollArea className="h-[60vh] w-full pr-4">
<Accordion type="single" collapsible className="w-full space-y-2">
{toolEntries.map(([name, tool]) => {
const func = 'function' in tool ? tool.function : undefined;
return (
<AccordionItem key={name} value={name} className="border rounded-lg px-4">
<AccordionTrigger className="text-sm font-mono hover:no-underline py-3 outline-none focus:outline-none focus-visible:outline-none">
{name}
</AccordionTrigger>
<AccordionContent className="pt-2 pb-4">
<div className="space-y-3 text-sm">
<div>
<div className="font-semibold mb-1">Description:</div>
<div className="text-muted-foreground whitespace-pre-wrap">
{func?.description || 'No description available'}
</div>
</div>
{func?.parameters && (
<div>
<div className="font-semibold mb-1">Parameters:</div>
<pre className="text-xs bg-muted p-3 rounded-md overflow-x-auto">
{JSON.stringify(func.parameters, null, 2)}
</pre>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</ScrollArea>
</DialogContent>
</Dialog>
);
}