feat: add command scope support and reload functionality

- Introduced command scope types (user and project) to manage command configurations at different levels.
- Enhanced command management functions to check and create commands based on their scope.
- Updated the API to handle command creation, updates, and deletions with respect to their scope.
- Added a reload button in the AboutSettings component to refresh OpenCode configuration.
- Improved command source retrieval to prioritize project-level commands over user-level commands.
- Refactored related functions to ensure proper handling of command paths and configurations based on scope.
This commit is contained in:
Bohdan Triapitsyn
2025-12-29 17:48:06 +02:00
parent 66351bea6c
commit 0adcba854b
12 changed files with 1008 additions and 268 deletions
@@ -3,21 +3,28 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import { useCommandsStore, type CommandConfig } from '@/stores/useCommandsStore';
import { RiCheckLine, RiInformationLine, RiSaveLine, RiTerminalBoxLine } from '@remixicon/react';
import { useCommandsStore, type CommandConfig, type CommandScope } from '@/stores/useCommandsStore';
import { RiCheckLine, RiInformationLine, RiSaveLine, RiTerminalBoxLine, RiUser3Line, RiFolderLine } from '@remixicon/react';
import { cn } from '@/lib/utils';
import { ModelSelector } from '../agents/ModelSelector';
import { AgentSelector } from './AgentSelector';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
} from '@/components/ui/select';
export const CommandsPage: React.FC = () => {
const { selectedCommandName, getCommandByName, createCommand, updateCommand, commands } = useCommandsStore();
const { selectedCommandName, getCommandByName, createCommand, updateCommand, commands, commandDraft, setCommandDraft } = useCommandsStore();
const selectedCommand = selectedCommandName ? getCommandByName(selectedCommandName) : null;
const isNewCommand = selectedCommandName && !selectedCommand;
const isNewCommand = Boolean(commandDraft && commandDraft.name === selectedCommandName && !selectedCommand);
const [name, setName] = React.useState('');
const [draftName, setDraftName] = React.useState('');
const [draftScope, setDraftScope] = React.useState<CommandScope>('user');
const [description, setDescription] = React.useState('');
const [agent, setAgent] = React.useState('');
const [model, setModel] = React.useState('');
@@ -26,27 +33,28 @@ export const CommandsPage: React.FC = () => {
const [isSaving, setIsSaving] = React.useState(false);
React.useEffect(() => {
if (isNewCommand) {
setName(selectedCommandName || '');
setDescription('');
setAgent('');
setModel('');
setTemplate('');
setSubtask(false);
if (isNewCommand && commandDraft) {
// Prefill from draft (for new or duplicated commands)
setDraftName(commandDraft.name || '');
setDraftScope(commandDraft.scope || 'user');
setDescription(commandDraft.description || '');
setAgent(commandDraft.agent || '');
setModel(commandDraft.model || '');
setTemplate(commandDraft.template || '');
setSubtask(commandDraft.subtask || false);
} else if (selectedCommand) {
setName(selectedCommand.name);
setDescription(selectedCommand.description || '');
setAgent(selectedCommand.agent || '');
setModel(selectedCommand.model || '');
setTemplate(selectedCommand.template || '');
setSubtask(selectedCommand.subtask || false);
}
}, [selectedCommand, isNewCommand, selectedCommandName, commands]);
}, [selectedCommand, isNewCommand, selectedCommandName, commands, commandDraft]);
const handleSave = async () => {
if (!name.trim()) {
const commandName = isNewCommand ? draftName.trim().replace(/\s+/g, '-') : selectedCommandName?.trim();
if (!commandName) {
toast.error('Command name is required');
return;
}
@@ -56,6 +64,12 @@ export const CommandsPage: React.FC = () => {
return;
}
// Check for duplicate name when creating new command
if (isNewCommand && commands.some((cmd) => cmd.name === commandName)) {
toast.error('A command with this name already exists');
return;
}
setIsSaving(true);
try {
@@ -63,19 +77,23 @@ export const CommandsPage: React.FC = () => {
const trimmedModel = model.trim();
const trimmedTemplate = template.trim();
const config: CommandConfig = {
name: name.trim(),
name: commandName,
description: description.trim() || undefined,
agent: trimmedAgent === '' ? null : trimmedAgent,
model: trimmedModel === '' ? null : trimmedModel,
template: trimmedTemplate,
subtask,
scope: isNewCommand ? draftScope : undefined,
};
let success: boolean;
if (isNewCommand) {
success = await createCommand(config);
if (success) {
setCommandDraft(null); // Clear draft after successful creation
}
} else {
success = await updateCommand(name, config);
success = await updateCommand(commandName, config);
}
if (success) {
@@ -108,7 +126,7 @@ export const CommandsPage: React.FC = () => {
{}
<div className="space-y-1">
<h1 className="typography-ui-header font-semibold text-lg">
{isNewCommand ? 'New Command' : name}
{isNewCommand ? 'New Command' : `/${selectedCommandName}`}
</h1>
</div>
@@ -121,20 +139,54 @@ export const CommandsPage: React.FC = () => {
</p>
</div>
<div className="space-y-2">
<label className="typography-ui-label font-medium text-foreground">
Command Name
</label>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="my-command"
disabled={!isNewCommand}
/>
<p className="typography-meta text-muted-foreground">
Used with slash (/) prefix in chat
</p>
</div>
{isNewCommand && (
<div className="space-y-2">
<label className="typography-ui-label font-medium text-foreground">
Command Name & Scope
</label>
<div className="flex items-center gap-2">
<div className="flex items-center flex-1">
<span className="typography-ui-label text-muted-foreground mr-1">/</span>
<Input
value={draftName}
onChange={(e) => setDraftName(e.target.value)}
placeholder="command-name"
className="flex-1 text-foreground placeholder:text-muted-foreground"
/>
</div>
<Select value={draftScope} onValueChange={(v) => setDraftScope(v as CommandScope)}>
<SelectTrigger className="!h-9 w-auto gap-1.5">
{draftScope === 'user' ? (
<RiUser3Line className="h-4 w-4" />
) : (
<RiFolderLine className="h-4 w-4" />
)}
<span className="capitalize">{draftScope}</span>
</SelectTrigger>
<SelectContent align="end">
<SelectItem value="user" className="pr-2 [&>span:first-child]:hidden">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<RiUser3Line className="h-4 w-4" />
<span>User</span>
</div>
<span className="typography-micro text-muted-foreground ml-6">Available in all projects</span>
</div>
</SelectItem>
<SelectItem value="project" className="pr-2 [&>span:first-child]:hidden">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<RiFolderLine className="h-4 w-4" />
<span>Project</span>
</div>
<span className="typography-micro text-muted-foreground ml-6">Only in current project</span>
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
)}
<div className="space-y-2">
<label className="typography-ui-label font-medium text-foreground">
@@ -10,7 +10,6 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
DropdownMenu,
@@ -18,8 +17,8 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine } from '@remixicon/react';
import { useCommandsStore, type Command } from '@/stores/useCommandsStore';
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine, RiRestartLine, RiEditLine } from '@remixicon/react';
import { useCommandsStore, isCommandBuiltIn, type Command } from '@/stores/useCommandsStore';
import { useUIStore } from '@/stores/useUIStore';
import { useDeviceInfo } from '@/lib/device';
import { isVSCodeRuntime } from '@/lib/desktop';
@@ -31,13 +30,15 @@ interface CommandsSidebarProps {
}
export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }) => {
const [newCommandName, setNewCommandName] = React.useState('');
const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false);
const [renameDialogCommand, setRenameDialogCommand] = React.useState<Command | null>(null);
const [renameNewName, setRenameNewName] = React.useState('');
const {
selectedCommandName,
commands,
setSelectedCommand,
setCommandDraft,
createCommand,
deleteCommand,
loadCommands,
} = useCommandsStore();
@@ -67,22 +68,19 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
? 'bg-background'
: 'bg-sidebar';
const handleCreateCommand = () => {
if (!newCommandName.trim()) {
toast.error('Command name is required');
return;
const handleCreateNew = () => {
// Generate unique name
const baseName = 'new-command';
let newName = baseName;
let counter = 1;
while (commands.some((c) => c.name === newName)) {
newName = `${baseName}-${counter}`;
counter++;
}
const sanitizedName = newCommandName.trim().replace(/\s+/g, '-');
if (commands.some((cmd) => cmd.name === sanitizedName)) {
toast.error('A command with this name already exists');
return;
}
setSelectedCommand(sanitizedName);
setNewCommandName('');
setIsCreateDialogOpen(false);
// Set draft and open the page for editing
setCommandDraft({ name: newName, scope: 'user' });
setSelectedCommand(newName);
if (isMobile) {
setSidebarOpen(false);
@@ -90,6 +88,11 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
};
const handleDeleteCommand = async (command: Command) => {
if (isCommandBuiltIn(command)) {
toast.error('Built-in commands cannot be deleted');
return;
}
if (window.confirm(`Are you sure you want to delete command "${command.name}"?`)) {
const success = await deleteCommand(command.name);
if (success) {
@@ -100,6 +103,21 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
}
};
const handleResetCommand = async (command: Command) => {
if (!isCommandBuiltIn(command)) {
return;
}
if (window.confirm(`Are you sure you want to reset command "${command.name}" to its default configuration?`)) {
const success = await deleteCommand(command.name);
if (success) {
toast.success(`Command "${command.name}" reset to default`);
} else {
toast.error('Failed to reset command');
}
}
};
const handleDuplicateCommand = (command: Command) => {
const baseName = command.name;
let copyNumber = 1;
@@ -110,85 +128,185 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
newName = `${baseName}-copy-${copyNumber}`;
}
// Set draft with prefilled values from source command
setCommandDraft({
name: newName,
scope: command.scope || 'user',
description: command.description,
template: command.template,
agent: command.agent,
model: command.model,
subtask: command.subtask,
});
setSelectedCommand(newName);
setIsCreateDialogOpen(false);
if (isMobile) {
setSidebarOpen(false);
}
};
const handleOpenRenameDialog = (command: Command) => {
setRenameNewName(command.name);
setRenameDialogCommand(command);
};
const handleRenameCommand = async () => {
if (!renameDialogCommand) return;
const sanitizedName = renameNewName.trim().replace(/\s+/g, '-');
if (!sanitizedName) {
toast.error('Command name is required');
return;
}
if (sanitizedName === renameDialogCommand.name) {
setRenameDialogCommand(null);
return;
}
if (commands.some((cmd) => cmd.name === sanitizedName)) {
toast.error('A command with this name already exists');
return;
}
// Create new command with new name and all existing config
const success = await createCommand({
name: sanitizedName,
description: renameDialogCommand.description,
template: renameDialogCommand.template,
agent: renameDialogCommand.agent,
model: renameDialogCommand.model,
subtask: renameDialogCommand.subtask,
});
if (success) {
// Delete old command
const deleteSuccess = await deleteCommand(renameDialogCommand.name);
if (deleteSuccess) {
toast.success(`Command renamed to "${sanitizedName}"`);
setSelectedCommand(sanitizedName);
} else {
toast.error('Failed to remove old command after rename');
}
} else {
toast.error('Failed to rename command');
}
setRenameDialogCommand(null);
};
const builtInCommands = commands.filter(isCommandBuiltIn);
const customCommands = commands.filter((cmd) => !isCommandBuiltIn(cmd));
return (
<div className={cn('flex h-full flex-col', bgClass)}>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
<DialogTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 -my-1 text-muted-foreground">
<RiAddLine className="size-4" />
</Button>
</DialogTrigger>
</div>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 -my-1 text-muted-foreground"
onClick={handleCreateNew}
>
<RiAddLine className="size-4" />
</Button>
</div>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
{commands.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiTerminalBoxLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No commands configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
{commands.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiTerminalBoxLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No commands configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<>
{builtInCommands.length > 0 && (
<>
{[...commands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onDelete={() => handleDeleteCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
<div className="px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Built-in Commands
</div>
{[...builtInCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onReset={() => handleResetCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
</>
)}
</ScrollableOverlay>
{customCommands.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Custom Commands
</div>
{[...customCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onRename={() => handleOpenRenameDialog(command)}
onDelete={() => handleDeleteCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
</>
)}
</>
)}
</ScrollableOverlay>
{/* Rename Dialog */}
<Dialog open={renameDialogCommand !== null} onOpenChange={(open) => !open && setRenameDialogCommand(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Command</DialogTitle>
<DialogTitle>Rename Command</DialogTitle>
<DialogDescription>
Enter a unique name for your new slash command
Enter a new name for the command "/{renameDialogCommand?.name}"
</DialogDescription>
</DialogHeader>
<Input
value={newCommandName}
onChange={(e) => setNewCommandName(e.target.value)}
placeholder="Command name..."
value={renameNewName}
onChange={(e) => setRenameNewName(e.target.value)}
placeholder="New command name..."
className="text-foreground placeholder:text-muted-foreground"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleCreateCommand();
handleRenameCommand();
}
}}
/>
<DialogFooter>
<Button
variant="ghost"
onClick={() => setIsCreateDialogOpen(false)}
onClick={() => setRenameDialogCommand(null)}
className="text-foreground hover:bg-muted hover:text-foreground"
>
Cancel
</Button>
<ButtonLarge onClick={handleCreateCommand}>
Create
<ButtonLarge onClick={handleRenameCommand}>
Rename
</ButtonLarge>
</DialogFooter>
</DialogContent>
@@ -201,7 +319,9 @@ interface CommandListItemProps {
command: Command;
isSelected: boolean;
onSelect: () => void;
onDelete: () => void;
onDelete?: () => void;
onReset?: () => void;
onRename?: () => void;
onDuplicate: () => void;
}
@@ -210,6 +330,8 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
isSelected,
onSelect,
onDelete,
onReset,
onRename,
onDuplicate,
}) => {
return (
@@ -229,6 +351,11 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
<span className="typography-ui-label font-normal truncate text-foreground">
/{command.name}
</span>
{(command.scope || isCommandBuiltIn(command)) && (
<span className="typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50">
{isCommandBuiltIn(command) ? 'system' : command.scope}
</span>
)}
</div>
{command.description && (
@@ -249,6 +376,18 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-fit min-w-20">
{onRename && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onRename();
}}
>
<RiEditLine className="h-4 w-4 mr-px" />
Rename
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
@@ -259,16 +398,30 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
Duplicate
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
{onReset && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onReset();
}}
>
<RiRestartLine className="h-4 w-4 mr-px" />
Reset
</DropdownMenuItem>
)}
{onDelete && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -1,10 +1,11 @@
import React from 'react';
import { RiDiscordFill, RiDownloadLine, RiGithubFill, RiLoaderLine, RiTwitterXFill } from '@remixicon/react';
import { RiDiscordFill, RiDownloadLine, RiGithubFill, RiLoaderLine, RiRestartLine, RiTwitterXFill } from '@remixicon/react';
import { useUpdateStore } from '@/stores/useUpdateStore';
import { UpdateDialog } from '@/components/ui/UpdateDialog';
import { useDeviceInfo } from '@/lib/device';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { reloadOpenCodeConfiguration } from '@/stores/useAgentsStore';
const GITHUB_URL = 'https://github.com/btriapitsyn/openchamber';
@@ -45,6 +46,15 @@ export const AboutSettings: React.FC = () => {
if (isMobile) {
return (
<div className="w-full space-y-2">
{/* Reload OpenCode Configuration */}
<button
onClick={() => reloadOpenCodeConfiguration()}
className="flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors"
>
<RiRestartLine className="h-3.5 w-3.5" />
<span>Reload OpenCode Configuration</span>
</button>
{/* Version row with update status */}
<div className="flex items-center justify-between">
<span className="typography-meta text-muted-foreground">