Multi-run with configurable prompt templates (#1111)

* Multi-run with configurable prompt templates

* Fixes

* Fix handleDuplicate fire-and-forget: await createTemplate and handle failure

* Add Polish translations for prompt template and multirun group keys

* fix: migrate remaining Remix icons to Icon component in MultiRunLauncher

---------

Signed-off-by: Tom Rochette <roctom@gmail.com>
This commit is contained in:
Tom Rochette
2026-05-21 16:35:42 +03:00
committed by GitHub
parent 8dac0f73c0
commit 6cc1afc963
29 changed files with 1590 additions and 564 deletions
@@ -13,14 +13,13 @@ import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { useMultiRunStore } from '@/stores/useMultiRunStore';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { usePromptTemplatesStore } from '@/stores/usePromptTemplatesStore';
import { getWorktreeSetupCommands } from '@/lib/openchamberConfig';
import type { ProjectRef } from '@/lib/openchamberConfig';
import type { CreateMultiRunParams, MultiRunModelSelection } from '@/types/multirun';
import type { CreateMultiRunParams, MultiRunGroup } from '@/types/multirun';
import { ModelMultiSelect, generateInstanceId, type ModelSelectionWithId } from './ModelMultiSelect';
import { BranchSelector, useBranchOptions } from './BranchSelector';
import { AgentSelector } from './AgentSelector';
import { CommandAutocomplete, type CommandAutocompleteHandle, type CommandInfo } from '@/components/chat/CommandAutocomplete';
import { FileMentionAutocomplete, type FileMentionHandle } from '@/components/chat/FileMentionAutocomplete';
import { Icon } from "@/components/icon/Icon";
import { isDesktopShell } from '@/lib/desktop';
import { useTabletStandalonePwaRuntime } from '@/lib/device';
@@ -30,13 +29,9 @@ import type { ProjectEntry } from '@/lib/api/types';
import { startDesktopWindowDrag } from '@/lib/desktopNative';
import { useI18n } from '@/lib/i18n';
/** Max file size in bytes (10MB) */
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const MAX_MODELS_PER_GROUP = 5;
/** Max number of concurrent runs */
const MAX_MODELS = 5;
/** Attached file for multi-run (simplified from sessionStore's AttachedFile) */
interface MultiRunAttachedFile {
id: string;
filename: string;
@@ -45,18 +40,20 @@ interface MultiRunAttachedFile {
dataUrl: string;
}
interface RunGroupState {
id: string;
templateId: string;
prompt: string;
models: ModelSelectionWithId[];
}
interface MultiRunLauncherProps {
/** Prefill prompt textarea (optional) */
initialPrompt?: string;
/** Called when multi-run is successfully created */
onCreated?: () => void;
/** Called when user cancels */
onCancel?: () => void;
/** Rendered inside dialog window with no local header */
isWindowed?: boolean;
}
/** Info tooltip - small icon that shows helper text on hover */
const InfoTip: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<Tooltip>
<TooltipTrigger asChild>
@@ -70,7 +67,6 @@ const InfoTip: React.FC<{ children: React.ReactNode }> = ({ children }) => (
</Tooltip>
);
/** Compact field label */
const FieldLabel: React.FC<{
htmlFor?: string;
required?: boolean;
@@ -86,10 +82,6 @@ const FieldLabel: React.FC<{
</div>
);
/**
* Launcher form for creating a new Multi-Run group.
* Compact, centered card layout with adaptive grid.
*/
export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
initialPrompt,
onCreated,
@@ -98,8 +90,9 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
}) => {
const { t } = useI18n();
const [name, setName] = React.useState('');
const [prompt, setPrompt] = React.useState(() => initialPrompt ?? '');
const [selectedModels, setSelectedModels] = React.useState<ModelSelectionWithId[]>([]);
const [runGroups, setRunGroups] = React.useState<RunGroupState[]>(() => [
{ id: generateInstanceId(), templateId: '', prompt: '', models: [] },
]);
const [selectedAgent, setSelectedAgent] = React.useState<string>('');
const [attachedFiles, setAttachedFiles] = React.useState<MultiRunAttachedFile[]>([]);
const [isSubmitting, setIsSubmitting] = React.useState(false);
@@ -107,27 +100,23 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
const [isSetupCommandsOpen, setIsSetupCommandsOpen] = React.useState(false);
const [isLoadingSetupCommands, setIsLoadingSetupCommands] = React.useState(false);
const [isolateRuns, setIsolateRuns] = React.useState(true);
const [showFileMention, setShowFileMention] = React.useState(false);
const [mentionQuery, setMentionQuery] = React.useState('');
const [showCommandAutocomplete, setShowCommandAutocomplete] = React.useState(false);
const [commandQuery, setCommandQuery] = React.useState('');
const fileInputRef = React.useRef<HTMLInputElement>(null);
const promptTextareaRef = React.useRef<HTMLTextAreaElement>(null);
const mentionRef = React.useRef<FileMentionHandle>(null);
const commandRef = React.useRef<CommandAutocompleteHandle>(null);
const templates = usePromptTemplatesStore((s) => s.templates);
React.useEffect(() => {
usePromptTemplatesStore.getState().loadTemplates();
}, []);
const currentDirectory = useDirectoryStore((state) => state.currentDirectory ?? null);
const homeDirectory = useDirectoryStore((state) => state.homeDirectory ?? null);
const vscodeWorkspaceFolder = React.useMemo(() => {
if (typeof window === 'undefined') {
return null;
}
if (typeof window === 'undefined') return null;
const folder = (window as unknown as { __VSCODE_CONFIG__?: { workspaceFolder?: unknown } }).__VSCODE_CONFIG__?.workspaceFolder;
return typeof folder === 'string' && folder.trim().length > 0 ? folder.trim() : null;
}, []);
// Get project directory for setup commands
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
const setActiveProjectIdOnly = useProjectsStore((state) => state.setActiveProjectIdOnly);
const projects = useProjectsStore((state) => state.projects);
@@ -144,9 +133,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
}, [activeProjectId, projects, selectedProjectId]);
const selectedProject = React.useMemo(() => {
if (!selectedProjectId) {
return null;
}
if (!selectedProjectId) return null;
return projects.find((project) => project.id === selectedProjectId) ?? null;
}, [projects, selectedProjectId]);
@@ -196,60 +183,29 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
if (selectedProject?.path) {
return { id: selectedProject.id, path: selectedProject.path };
}
const base = currentDirectory ?? vscodeWorkspaceFolder;
if (!base) {
return null;
}
if (!base) return null;
return { id: `path:${base}`, path: base };
}, [selectedProject, currentDirectory, vscodeWorkspaceFolder]);
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
if (typeof window === 'undefined') {
return false;
}
return isDesktopShell();
});
const [isDesktopApp] = React.useState(() => (typeof window !== 'undefined' ? isDesktopShell() : false));
const isMacPlatform = React.useMemo(() => {
if (typeof navigator === 'undefined') {
return false;
}
if (typeof navigator === 'undefined') return false;
return /Macintosh|Mac OS X/.test(navigator.userAgent || '');
}, []);
const isTabletStandalonePwa = useTabletStandalonePwaRuntime();
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
setIsDesktopApp(isDesktopShell());
}, []);
const macosMajorVersion = React.useMemo(() => {
if (typeof window === 'undefined') {
return null;
}
if (typeof window === 'undefined') return null;
const injected = (window as unknown as { __OPENCHAMBER_MACOS_MAJOR__?: unknown }).__OPENCHAMBER_MACOS_MAJOR__;
if (typeof injected === 'number' && Number.isFinite(injected) && injected > 0) {
return injected;
}
// Fallback: WebKit reports "Mac OS X 10_15_7" format where 10 is legacy prefix
if (typeof navigator === 'undefined') {
return null;
}
if (typeof injected === 'number' && Number.isFinite(injected) && injected > 0) return injected;
if (typeof navigator === 'undefined') return null;
const match = (navigator.userAgent || '').match(/Mac OS X (\d+)[._](\d+)/);
if (!match) {
return null;
}
if (!match) return null;
const first = Number.parseInt(match[1], 10);
const second = Number.parseInt(match[2], 10);
if (Number.isNaN(first)) {
return null;
}
if (Number.isNaN(first)) return null;
return first === 10 ? second : first;
}, []);
@@ -262,31 +218,18 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
}, [isDesktopApp, isMacPlatform, isTabletStandalonePwa]);
const macosHeaderSizeClass = React.useMemo(() => {
if (!isDesktopApp || !isMacPlatform || macosMajorVersion === null) {
return '';
}
if (macosMajorVersion >= 26) {
return 'h-12';
}
if (macosMajorVersion <= 15) {
return 'h-14';
}
if (!isDesktopApp || !isMacPlatform || macosMajorVersion === null) return '';
if (macosMajorVersion >= 26) return 'h-12';
if (macosMajorVersion <= 15) return 'h-14';
return '';
}, [isDesktopApp, isMacPlatform, macosMajorVersion]);
const handleDragStart = React.useCallback(async (e: React.MouseEvent) => {
if ((e.target as HTMLElement).closest('button, a, input, select, textarea')) {
return;
}
if (e.button !== 0) {
return;
}
if (isDesktopApp) {
await startDesktopWindowDrag();
}
if ((e.target as HTMLElement).closest('button, a, input, select, textarea')) return;
if (e.button !== 0) return;
if (isDesktopApp) await startDesktopWindowDrag();
}, [isDesktopApp]);
// Handle ESC key to dismiss
React.useEffect(() => {
if (!onCancel) return;
const handleKeyDown = (e: KeyboardEvent) => {
@@ -300,7 +243,6 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
return () => window.removeEventListener('keydown', handleKeyDown, true);
}, [onCancel]);
// Use the BranchSelector hook for branch state management
const [worktreeBaseBranch, setWorktreeBaseBranch] = React.useState<string>('');
const { isLoading: isLoadingWorktreeBaseBranches, isGitRepository } = useBranchOptions(selectedProjectDirectory);
const wasIsolationDisabledByNonGitRef = React.useRef(false);
@@ -326,56 +268,56 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
React.useEffect(() => {
if (typeof initialPrompt === 'string' && initialPrompt.trim().length > 0) {
setPrompt((prev) => (prev.trim().length > 0 ? prev : initialPrompt));
setRunGroups((prev) => {
const updated = [...prev];
if (updated.length > 0 && !updated[0].prompt.trim()) {
updated[0] = { ...updated[0], prompt: initialPrompt };
}
return updated;
});
}
}, [initialPrompt]);
// Load setup commands from config
React.useEffect(() => {
if (!projectRef) return;
let cancelled = false;
setIsLoadingSetupCommands(true);
(async () => {
try {
const commands = await getWorktreeSetupCommands(projectRef);
if (!cancelled) {
setSetupCommands(commands);
}
if (!cancelled) setSetupCommands(commands);
} catch {
// Ignore errors, start with empty commands
// Ignore
} finally {
if (!cancelled) {
setIsLoadingSetupCommands(false);
}
if (!cancelled) setIsLoadingSetupCommands(false);
}
})();
return () => { cancelled = true; };
}, [projectRef]);
const handleAddModel = (model: ModelSelectionWithId) => {
if (selectedModels.length >= MAX_MODELS) {
return;
}
setSelectedModels((prev) => [...prev, model]);
clearError();
};
const handleRemoveModel = (index: number) => {
setSelectedModels((prev) => prev.filter((_, i) => i !== index));
clearError();
};
const handleUpdateModel = React.useCallback((index: number, model: ModelSelectionWithId) => {
setSelectedModels((prev) => prev.map((item, i) => (i === index ? model : item)));
const updateGroup = React.useCallback((groupId: string, updates: Partial<RunGroupState>) => {
setRunGroups((prev) => prev.map((g) => g.id === groupId ? { ...g, ...updates } : g));
}, []);
const removeGroup = React.useCallback((groupId: string) => {
setRunGroups((prev) => prev.filter((g) => g.id !== groupId));
}, []);
const addGroup = React.useCallback(() => {
setRunGroups((prev) => [...prev, { id: generateInstanceId(), templateId: '', prompt: '', models: [] }]);
}, []);
const handleTemplateChange = React.useCallback((groupId: string, templateId: string) => {
const template = templateId ? templates.find((t) => t.id === templateId) : null;
updateGroup(groupId, {
templateId,
prompt: template ? template.body : '',
});
}, [templates, updateGroup]);
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files) return;
let attachedCount = 0;
for (let i = 0; i < files.length; i++) {
const file = files[i];
@@ -383,7 +325,6 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
toast.error(t('multirun.launcher.toast.fileTooLarge', { fileName: file.name }));
continue;
}
try {
const dataUrl = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
@@ -391,172 +332,44 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
reader.onerror = reject;
reader.readAsDataURL(file);
});
const newFile: MultiRunAttachedFile = {
setAttachedFiles((prev) => [...prev, {
id: generateInstanceId(),
filename: file.name,
mimeType: file.type || 'application/octet-stream',
size: file.size,
dataUrl,
};
setAttachedFiles((prev) => [...prev, newFile]);
}]);
attachedCount++;
} catch (error) {
console.error('File attach failed', error);
} catch (err) {
console.error('File attach failed', err);
toast.error(t('multirun.launcher.toast.attachFailed', { fileName: file.name }));
}
}
if (attachedCount > 0) {
toast.success(
attachedCount === 1
? t('multirun.launcher.toast.attachedSingle', { count: attachedCount })
: t('multirun.launcher.toast.attachedPlural', { count: attachedCount })
: t('multirun.launcher.toast.attachedPlural', { count: attachedCount }),
);
}
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
if (fileInputRef.current) fileInputRef.current.value = '';
};
const handleRemoveFile = (id: string) => {
setAttachedFiles((prev) => prev.filter((f) => f.id !== id));
};
const updateAutocompleteState = React.useCallback((value: string, cursorPosition: number) => {
if (value.startsWith('/')) {
const firstSpace = value.indexOf(' ');
const firstNewline = value.indexOf('\n');
const commandEnd = Math.min(
firstSpace === -1 ? value.length : firstSpace,
firstNewline === -1 ? value.length : firstNewline,
);
if (cursorPosition <= commandEnd && firstSpace === -1) {
setCommandQuery(value.substring(1, commandEnd));
setShowCommandAutocomplete(true);
setShowFileMention(false);
return;
}
}
setShowCommandAutocomplete(false);
const textBeforeCursor = value.substring(0, cursorPosition);
const lastAtSymbol = textBeforeCursor.lastIndexOf('@');
if (lastAtSymbol !== -1) {
const charBefore = lastAtSymbol > 0 ? textBeforeCursor[lastAtSymbol - 1] : null;
const textAfterAt = textBeforeCursor.substring(lastAtSymbol + 1);
const isWordBoundary = !charBefore || /\s/.test(charBefore);
if (isWordBoundary && !textAfterAt.includes(' ') && !textAfterAt.includes('\n')) {
setMentionQuery(textAfterAt);
setShowFileMention(true);
} else {
setShowFileMention(false);
}
return;
}
setShowFileMention(false);
}, []);
const handlePromptKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (showCommandAutocomplete && commandRef.current) {
if (event.key === 'Enter' || event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'Escape' || event.key === 'Tab') {
event.preventDefault();
commandRef.current.handleKeyDown(event.key);
return;
}
}
if (showFileMention && mentionRef.current) {
if (event.key === 'Enter' || event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'Escape' || event.key === 'Tab') {
event.preventDefault();
mentionRef.current.handleKeyDown(event.key);
}
}
}, [showCommandAutocomplete, showFileMention]);
const handleAutocompleteFileSelect = React.useCallback((file: { name: string; path: string; relativePath?: string }) => {
const textarea = promptTextareaRef.current;
const cursorPosition = textarea?.selectionStart ?? prompt.length;
const textBeforeCursor = prompt.substring(0, cursorPosition);
const lastAtSymbol = textBeforeCursor.lastIndexOf('@');
const mentionPath = (file.relativePath && file.relativePath.trim().length > 0)
? file.relativePath.trim()
: (file.path || file.name);
const startIndex = lastAtSymbol !== -1 ? lastAtSymbol : cursorPosition;
const nextPrompt = `${prompt.substring(0, startIndex)}@${mentionPath} ${prompt.substring(cursorPosition)}`;
const nextCursor = startIndex + mentionPath.length + 2;
setPrompt(nextPrompt);
setShowFileMention(false);
setMentionQuery('');
requestAnimationFrame(() => {
const currentTextarea = promptTextareaRef.current;
if (currentTextarea) {
currentTextarea.selectionStart = nextCursor;
currentTextarea.selectionEnd = nextCursor;
currentTextarea.focus();
}
updateAutocompleteState(nextPrompt, nextCursor);
});
}, [prompt, updateAutocompleteState]);
const handleAutocompleteAgentSelect = React.useCallback((agentName: string) => {
const textarea = promptTextareaRef.current;
const cursorPosition = textarea?.selectionStart ?? prompt.length;
const textBeforeCursor = prompt.substring(0, cursorPosition);
const lastAtSymbol = textBeforeCursor.lastIndexOf('@');
const startIndex = lastAtSymbol !== -1 ? lastAtSymbol : cursorPosition;
const nextPrompt = `${prompt.substring(0, startIndex)}@${agentName} ${prompt.substring(cursorPosition)}`;
const nextCursor = startIndex + agentName.length + 2;
setPrompt(nextPrompt);
setShowFileMention(false);
setMentionQuery('');
requestAnimationFrame(() => {
const currentTextarea = promptTextareaRef.current;
if (currentTextarea) {
currentTextarea.selectionStart = nextCursor;
currentTextarea.selectionEnd = nextCursor;
currentTextarea.focus();
}
updateAutocompleteState(nextPrompt, nextCursor);
});
}, [prompt, updateAutocompleteState]);
const handleAutocompleteCommandSelect = React.useCallback((command: CommandInfo) => {
const nextPrompt = `/${command.name} `;
setPrompt(nextPrompt);
setShowCommandAutocomplete(false);
setCommandQuery('');
requestAnimationFrame(() => {
const currentTextarea = promptTextareaRef.current;
if (currentTextarea) {
currentTextarea.focus();
currentTextarea.selectionStart = currentTextarea.value.length;
currentTextarea.selectionEnd = currentTextarea.value.length;
}
updateAutocompleteState(nextPrompt, nextPrompt.length);
});
}, [updateAutocompleteState]);
const totalRunCount = React.useMemo(
() => runGroups.reduce((sum, g) => sum + g.models.length, 0),
[runGroups],
);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!prompt.trim()) {
return;
}
if (selectedModels.length < 2) {
return;
}
const validGroups = runGroups.filter((g) => g.prompt.trim() && g.models.length >= 1);
if (validGroups.length === 0) return;
if (totalRunCount < 1) return;
setIsSubmitting(true);
clearError();
@@ -566,24 +379,23 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
setActiveProjectIdOnly(selectedProjectId);
}
// Strip instanceId before passing to store (UI-only field)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const modelsForStore: MultiRunModelSelection[] = selectedModels.map(({ instanceId: _instanceId, ...rest }) => rest);
// Convert attached files to the format expected by the store
const filesForStore = attachedFiles.map((f) => ({
mime: f.mimeType,
filename: f.filename,
url: f.dataUrl,
}));
// Filter setup commands
const commandsForStore = setupCommands.filter(cmd => cmd.trim().length > 0);
const commandsForStore = setupCommands.filter((cmd) => cmd.trim().length > 0);
const groups: MultiRunGroup[] = validGroups.map((g) => ({
prompt: g.prompt.trim(),
models: g.models.map((m) => ({ providerID: m.providerID, modelID: m.modelID, displayName: m.displayName, variant: m.variant })),
templateId: g.templateId || undefined,
}));
const params: CreateMultiRunParams = {
name: name.trim(),
prompt: prompt.trim(),
models: modelsForStore,
groups,
agent: selectedAgent || undefined,
worktreeBaseBranch: effectiveIsolateRuns ? worktreeBaseBranch : undefined,
isolateRuns: effectiveIsolateRuns,
@@ -592,29 +404,27 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
};
const result = await createMultiRun(params);
if (result) {
if (result.firstSessionId) {
useSessionUIStore.getState().setCurrentSession(result.firstSessionId);
}
// Close launcher
onCreated?.();
}
if (result) {
if (result.firstSessionId) {
useSessionUIStore.getState().setCurrentSession(result.firstSessionId);
}
onCreated?.();
}
} finally {
setIsSubmitting(false);
}
};
const isValid = Boolean(
name.trim() &&
prompt.trim() &&
selectedModels.length >= 2 &&
selectedProjectDirectory &&
!isLoadingWorktreeBaseBranches &&
(isGitRepository === false || !effectiveIsolateRuns || worktreeBaseBranch)
name.trim()
&& runGroups.some((g) => g.prompt.trim() && g.models.length >= 1)
&& totalRunCount >= 1
&& selectedProjectDirectory
&& !isLoadingWorktreeBaseBranches
&& (isGitRepository === false || !effectiveIsolateRuns || worktreeBaseBranch)
);
const configuredSetupCount = setupCommands.filter(cmd => cmd.trim()).length;
const configuredSetupCount = setupCommands.filter((cmd) => cmd.trim()).length;
return (
<form onSubmit={handleSubmit} className="flex flex-col h-full bg-background">
@@ -642,30 +452,22 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
<Icon name="close" className="h-5 w-5" />
</button>
</TooltipTrigger>
<TooltipContent>
<p>{t('multirun.launcher.actions.closeEsc')}</p>
</TooltipContent>
<TooltipContent><p>{t('multirun.launcher.actions.closeEsc')}</p></TooltipContent>
</Tooltip>
</div>
)}
</header>
) : null}
{/* Scrollable content */}
<ScrollShadow className="flex-1 min-h-0 overflow-auto" size={64} hideTopShadow>
<div className="mx-auto w-full max-w-2xl px-4 sm:px-6 py-5">
<div className="flex flex-col gap-5">
{/* ── Config grid: 2-column on sm+, single column on narrow ── */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3">
{/* Project */}
<div className="flex flex-col gap-1">
<FieldLabel htmlFor="multirun-project" required>{t('multirun.launcher.project.label')}</FieldLabel>
{projects.length > 0 ? (
<Select
value={selectedProjectId ?? undefined}
onValueChange={handleProjectChange}
>
<Select value={selectedProjectId ?? undefined} onValueChange={handleProjectChange}>
<SelectTrigger id="multirun-project" size="lg" className="w-fit max-w-full">
{selectedProject ? (
<SelectValue>{renderProjectLabel(selectedProject)}</SelectValue>
@@ -686,13 +488,8 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
)}
</div>
{/* Group name */}
<div className="flex flex-col gap-1">
<FieldLabel
htmlFor="group-name"
required
info={<InfoTip>{t('multirun.launcher.groupName.info')}</InfoTip>}
>
<FieldLabel htmlFor="group-name" required info={<InfoTip>{t('multirun.launcher.groupName.info')}</InfoTip>}>
{t('multirun.launcher.groupName.label')}
</FieldLabel>
<Input
@@ -705,12 +502,8 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
/>
</div>
{/* Base branch */}
<div className="flex flex-col gap-1">
<FieldLabel
htmlFor="multirun-worktree-base-branch"
info={<InfoTip>{t('multirun.launcher.baseBranch.info')}</InfoTip>}
>
<FieldLabel htmlFor="multirun-worktree-base-branch" info={<InfoTip>{t('multirun.launcher.baseBranch.info')}</InfoTip>}>
{t('multirun.launcher.baseBranch.label')}
</FieldLabel>
<BranchSelector
@@ -731,23 +524,14 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
</label>
</div>
{/* Agent */}
<div className="flex flex-col gap-1">
<FieldLabel
htmlFor="multirun-agent"
info={<InfoTip>{t('multirun.launcher.agent.info')}</InfoTip>}
>
<FieldLabel htmlFor="multirun-agent" info={<InfoTip>{t('multirun.launcher.agent.info')}</InfoTip>}>
{t('multirun.launcher.agent.label')}
</FieldLabel>
<AgentSelector
value={selectedAgent}
onChange={setSelectedAgent}
id="multirun-agent"
/>
<AgentSelector value={selectedAgent} onChange={setSelectedAgent} id="multirun-agent" />
</div>
</div>
{/* ── Setup commands (collapsible, full width) ── */}
<Collapsible open={isSetupCommandsOpen} onOpenChange={setIsSetupCommandsOpen}>
<CollapsibleTrigger className="w-full flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-lg hover:bg-[var(--interactive-hover)]/50 transition-colors group">
<Icon name="terminal" className="h-3.5 w-3.5 text-muted-foreground/70" />
@@ -769,7 +553,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
)}
<Icon name="arrow-down-s" className={cn(
'h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto',
isSetupCommandsOpen && 'rotate-180'
isSetupCommandsOpen && 'rotate-180',
)} />
</CollapsibleTrigger>
<CollapsibleContent>
@@ -792,10 +576,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
/>
<button
type="button"
onClick={() => {
const newCommands = setupCommands.filter((_, i) => i !== index);
setSetupCommands(newCommands);
}}
onClick={() => setSetupCommands(setupCommands.filter((_, i) => i !== index))}
className="flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
aria-label={t('multirun.launcher.setupCommands.removeCommandAria')}
>
@@ -817,70 +598,10 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
</CollapsibleContent>
</Collapsible>
{/* ── Prompt ── */}
<div className="flex flex-col gap-1.5">
<FieldLabel htmlFor="prompt" required>{t('multirun.launcher.prompt.label')}</FieldLabel>
<div className="relative">
<Textarea
id="prompt"
ref={promptTextareaRef}
value={prompt}
onChange={(event) => {
const nextPrompt = event.target.value;
setPrompt(nextPrompt);
const cursorPosition = event.target.selectionStart ?? nextPrompt.length;
updateAutocompleteState(nextPrompt, cursorPosition);
}}
onKeyDown={handlePromptKeyDown}
placeholder={t('multirun.launcher.prompt.placeholder')}
className="typography-meta min-h-[100px] max-h-[300px] resize-none overflow-y-auto field-sizing-content"
required
/>
{showCommandAutocomplete ? (
<CommandAutocomplete
ref={commandRef}
searchQuery={commandQuery}
onCommandSelect={handleAutocompleteCommandSelect}
onClose={() => setShowCommandAutocomplete(false)}
style={{
left: 0,
top: 'auto',
bottom: 'calc(100% + 6px)',
marginBottom: 0,
maxWidth: '100%',
}}
/>
) : null}
{showFileMention ? (
<FileMentionAutocomplete
ref={mentionRef}
searchQuery={mentionQuery}
onFileSelect={handleAutocompleteFileSelect}
onAgentSelect={handleAutocompleteAgentSelect}
onClose={() => setShowFileMention(false)}
style={{
left: 0,
top: 'auto',
bottom: 'calc(100% + 6px)',
marginBottom: 0,
maxWidth: '100%',
}}
/>
) : null}
</div>
{/* File attachments inline */}
<FieldLabel htmlFor="prompt" required>{t('multirun.launcher.attachments.label')}</FieldLabel>
<div className="flex flex-wrap items-center gap-1.5">
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={handleFileSelect}
accept="*/*"
/>
<input ref={fileInputRef} type="file" multiple className="hidden" onChange={handleFileSelect} accept="*/*" />
<Tooltip>
<TooltipTrigger asChild>
<button
@@ -894,15 +615,11 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
</TooltipTrigger>
<TooltipContent>{t('multirun.launcher.attachments.tooltip')}</TooltipContent>
</Tooltip>
{attachedFiles.map((file) => (
<div
key={file.id}
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md typography-micro border"
style={{
backgroundColor: 'var(--surface-elevated)',
borderColor: 'var(--interactive-border)',
}}
style={{ backgroundColor: 'var(--surface-elevated)', borderColor: 'var(--interactive-border)' }}
>
{file.mimeType.startsWith('image/') ? (
<Icon name="file-image" className="h-3 w-3 text-muted-foreground" />
@@ -924,25 +641,28 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
</div>
</div>
{/* ── Models ── */}
<div className="flex flex-col gap-1.5">
<FieldLabel
required
info={<InfoTip>{t('multirun.launcher.models.info', { max: MAX_MODELS })}</InfoTip>}
>
{t('multirun.launcher.models.label')}
</FieldLabel>
<ModelMultiSelect
selectedModels={selectedModels}
onAdd={handleAddModel}
onRemove={handleRemoveModel}
onUpdate={handleUpdateModel}
minModels={2}
maxModels={MAX_MODELS}
{runGroups.map((group, groupIndex) => (
<RunGroupCard
key={group.id}
group={group}
groupIndex={groupIndex}
templates={templates}
canRemove={runGroups.length > 1}
onUpdate={updateGroup}
onRemove={removeGroup}
onTemplateChange={handleTemplateChange}
/>
</div>
))}
<button
type="button"
onClick={addGroup}
className="flex items-center gap-1.5 py-2 px-3 -mx-3 rounded-lg typography-meta font-medium text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors"
>
<Icon name="add" className="h-3.5 w-3.5" />
{t('multirun.launcher.groups.addGroup')}
</button>
{/* ── Error ── */}
{error && (
<div
className="px-3 py-2 rounded-lg typography-meta"
@@ -960,7 +680,6 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
</div>
</ScrollShadow>
{/* ── Fixed footer ── */}
<div className="shrink-0 px-4 sm:px-6 py-3">
<div className="mx-auto w-full max-w-2xl flex items-center justify-end gap-2">
{!effectiveIsolateRuns && isGitRepository !== null ? (
@@ -977,15 +696,11 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
>
{t('multirun.launcher.actions.cancel')}
</Button>
<Button
type="submit"
size="sm"
disabled={!isValid || isSubmitting}
>
<Button type="submit" size="sm" disabled={!isValid || isSubmitting}>
{isSubmitting ? (
t('multirun.launcher.actions.creating')
) : (
<>{t('multirun.launcher.actions.startWithModelCount', { count: selectedModels.length })}</>
<>{t('multirun.launcher.actions.startWithRunCount', { count: totalRunCount })}</>
)}
</Button>
</div>
@@ -993,3 +708,104 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
</form>
);
};
interface RunGroupCardProps {
group: RunGroupState;
groupIndex: number;
templates: { id: string; name: string; body: string; isDefault: boolean }[];
canRemove: boolean;
onUpdate: (groupId: string, updates: Partial<RunGroupState>) => void;
onRemove: (groupId: string) => void;
onTemplateChange: (groupId: string, templateId: string) => void;
}
const RunGroupCard: React.FC<RunGroupCardProps> = ({
group,
groupIndex,
templates,
canRemove,
onUpdate,
onRemove,
onTemplateChange,
}) => {
const { t } = useI18n();
const handleAddModel = React.useCallback((model: ModelSelectionWithId) => {
if (group.models.length >= MAX_MODELS_PER_GROUP) return;
onUpdate(group.id, { models: [...group.models, model] });
}, [group.id, group.models, onUpdate]);
const handleRemoveModel = React.useCallback((index: number) => {
onUpdate(group.id, { models: group.models.filter((_, i) => i !== index) });
}, [group.id, group.models, onUpdate]);
const handleUpdateModel = React.useCallback((index: number, model: ModelSelectionWithId) => {
onUpdate(group.id, { models: group.models.map((item, i) => (i === index ? model : item)) });
}, [group.id, group.models, onUpdate]);
return (
<div className="rounded-lg border border-border p-3 space-y-3">
<div className="flex items-center justify-between gap-2">
<span className="typography-meta font-medium text-foreground">
{t('multirun.launcher.groups.groupLabel', { index: groupIndex + 1 })}
</span>
{canRemove && (
<button
type="button"
onClick={() => onRemove(group.id)}
className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10"
aria-label={t('multirun.launcher.groups.removeGroup')}
>
<Icon name="close" className="h-3.5 w-3.5" />
</button>
)}
</div>
<div className="flex flex-col gap-1.5">
<FieldLabel>{t('multirun.launcher.groups.template.label')}</FieldLabel>
<Select
value={group.templateId || '__custom__'}
onValueChange={(v) => onTemplateChange(group.id, v === '__custom__' ? '' : v)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder={t('multirun.launcher.groups.template.placeholder')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="__custom__">{t('multirun.launcher.groups.template.custom')}</SelectItem>
{templates.map((tpl) => (
<SelectItem key={tpl.id} value={tpl.id}>{tpl.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<FieldLabel required>{t('multirun.launcher.groups.prompt.label')}</FieldLabel>
<Textarea
value={group.prompt}
onChange={(e) => onUpdate(group.id, { prompt: e.target.value })}
placeholder={t('multirun.launcher.groups.prompt.placeholder')}
className="typography-meta min-h-[80px] max-h-[200px] resize-none overflow-y-auto field-sizing-content"
required
/>
</div>
<div className="flex flex-col gap-1.5">
<FieldLabel
required
info={<InfoTip>{t('multirun.launcher.models.info', { max: MAX_MODELS_PER_GROUP })}</InfoTip>}
>
{t('multirun.launcher.models.label')}
</FieldLabel>
<ModelMultiSelect
selectedModels={group.models}
onAdd={handleAddModel}
onRemove={handleRemoveModel}
onUpdate={handleUpdateModel}
minModels={1}
maxModels={MAX_MODELS_PER_GROUP}
/>
</div>
</div>
);
};
@@ -0,0 +1,181 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from '@/components/ui';
import { usePromptTemplatesStore } from '@/stores/usePromptTemplatesStore';
import { useShallow } from 'zustand/react/shallow';
import { RiFileTextLine } from '@remixicon/react';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { useI18n } from '@/lib/i18n';
export const PromptTemplatesPage: React.FC = () => {
const { t } = useI18n();
const {
selectedTemplateId,
templates,
updateTemplate,
createTemplate,
getTemplateById,
} = usePromptTemplatesStore(useShallow((s) => ({
selectedTemplateId: s.selectedTemplateId,
templates: s.templates,
updateTemplate: s.updateTemplate,
createTemplate: s.createTemplate,
getTemplateById: s.getTemplateById,
})));
const selectedTemplate = selectedTemplateId ? getTemplateById(selectedTemplateId) : null;
const isNew = Boolean(selectedTemplateId && !selectedTemplate && templates.length > 0);
const [name, setName] = React.useState('');
const [body, setBody] = React.useState('');
const [isSaving, setIsSaving] = React.useState(false);
const initialStateRef = React.useRef<{ name: string; body: string } | null>(null);
React.useEffect(() => {
if (selectedTemplate) {
setName(selectedTemplate.name);
setBody(selectedTemplate.body);
initialStateRef.current = { name: selectedTemplate.name, body: selectedTemplate.body };
} else if (isNew && selectedTemplateId) {
setName(selectedTemplateId);
setBody('');
initialStateRef.current = { name: selectedTemplateId, body: '' };
}
}, [selectedTemplate, isNew, selectedTemplateId, templates]);
const isDirty = React.useMemo(() => {
const initial = initialStateRef.current;
if (!initial) return false;
return name !== initial.name || body !== initial.body;
}, [name, body]);
const handleSave = async () => {
if (!selectedTemplateId) return;
const trimmedName = name.trim();
const trimmedBody = body.trim();
if (!trimmedName) {
toast.error(t('settings.promptTemplates.page.toast.nameRequired'));
return;
}
setIsSaving(true);
try {
if (selectedTemplate) {
const updates: { name?: string; body?: string } = {};
if (trimmedName !== selectedTemplate.name) updates.name = trimmedName;
if (trimmedBody !== selectedTemplate.body) updates.body = trimmedBody;
if (Object.keys(updates).length > 0) {
const success = await updateTemplate(selectedTemplateId, updates);
if (success) {
toast.success(t('settings.promptTemplates.page.toast.updated'));
initialStateRef.current = { name: trimmedName, body: trimmedBody };
} else {
toast.error(t('settings.promptTemplates.page.toast.updateFailed'));
}
}
} else {
const success = await createTemplate(selectedTemplateId, trimmedName, trimmedBody);
if (success) {
toast.success(t('settings.promptTemplates.page.toast.created'));
initialStateRef.current = { name: trimmedName, body: trimmedBody };
} else {
toast.error(t('settings.promptTemplates.page.toast.createFailed'));
}
}
} catch (error) {
console.error('Error saving prompt template:', error);
toast.error(t('settings.promptTemplates.page.toast.saveUnexpectedError'));
} finally {
setIsSaving(false);
}
};
if (!selectedTemplateId) {
return (
<div className="flex h-full items-center justify-center">
<div className="text-center text-muted-foreground">
<RiFileTextLine className="mx-auto mb-3 h-12 w-12 opacity-50" />
<p className="typography-body">{t('settings.promptTemplates.page.empty.title')}</p>
<p className="typography-meta mt-1 opacity-75">{t('settings.promptTemplates.page.empty.description')}</p>
</div>
</div>
);
}
return (
<ScrollableOverlay outerClassName="h-full" className="w-full">
<div className="mx-auto w-full max-w-3xl p-3 sm:p-6 sm:pt-8">
<div className="mb-4 flex items-center justify-between gap-4">
<div className="min-w-0">
<h2 className="typography-ui-header font-semibold text-foreground truncate">
{selectedTemplate ? selectedTemplate.name : t('settings.promptTemplates.page.title.new')}
</h2>
<p className="typography-meta text-muted-foreground truncate">
{selectedTemplate ? t('settings.promptTemplates.page.subtitle.edit') : t('settings.promptTemplates.page.subtitle.new')}
</p>
</div>
</div>
<div className="mb-8">
<div className="mb-1 px-1">
<h3 className="typography-ui-header font-medium text-foreground">
{t('settings.promptTemplates.page.section.identity')}
</h3>
</div>
<section className="px-2 pb-2 pt-0 space-y-0">
<div className="py-1.5">
<span className="typography-ui-label text-foreground">{t('settings.promptTemplates.page.field.name')}</span>
<div className="mt-1.5">
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t('settings.promptTemplates.page.field.namePlaceholder')}
className="h-7 w-full max-w-sm px-2"
disabled={selectedTemplate?.isDefault === true}
/>
</div>
</div>
</section>
</div>
<div className="mb-2">
<div className="mb-1 px-1">
<h3 className="typography-ui-header font-medium text-foreground">
{t('settings.promptTemplates.page.section.template')}
</h3>
</div>
<section className="px-2 pb-2 pt-0">
<Textarea
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder={t('settings.promptTemplates.page.field.templatePlaceholder')}
rows={12}
className="w-full font-mono typography-meta min-h-[160px] max-h-[60vh] bg-transparent resize-y"
/>
</section>
<div className="mt-2 px-2">
<p className="typography-meta text-muted-foreground">
{t('settings.promptTemplates.page.templateHint')}
</p>
</div>
</div>
<div className="px-2 py-1">
<Button
onClick={handleSave}
disabled={isSaving || !isDirty}
size="xs"
className="!font-normal"
>
{isSaving ? t('settings.common.actions.saving') : t('settings.common.actions.saveChanges')}
</Button>
</div>
</div>
</ScrollableOverlay>
);
};
@@ -0,0 +1,316 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { toast } from '@/components/ui';
import { isMobileDeviceViaCSS } from '@/lib/device';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { RiAddLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine, RiEditLine, RiFileTextLine } from '@remixicon/react';
import { usePromptTemplatesStore } from '@/stores/usePromptTemplatesStore';
import { useShallow } from 'zustand/react/shallow';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import type { PromptTemplate } from '@/types/prompt-template';
interface PromptTemplatesSidebarProps {
onItemSelect?: () => void;
}
export const PromptTemplatesSidebar: React.FC<PromptTemplatesSidebarProps> = ({ onItemSelect }) => {
const { t } = useI18n();
const [confirmDeleteTemplate, setConfirmDeleteTemplate] = React.useState<PromptTemplate | null>(null);
const [isDeletePending, setIsDeletePending] = React.useState(false);
const [openMenuId, setOpenMenuId] = React.useState<string | null>(null);
const [renameDialogTemplate, setRenameDialogTemplate] = React.useState<PromptTemplate | null>(null);
const [renameNewName, setRenameNewName] = React.useState('');
const {
selectedTemplateId,
templates,
setSelectedTemplate,
deleteTemplate,
updateTemplate,
loadTemplates,
} = usePromptTemplatesStore(useShallow((s) => ({
selectedTemplateId: s.selectedTemplateId,
templates: s.templates,
setSelectedTemplate: s.setSelectedTemplate,
deleteTemplate: s.deleteTemplate,
updateTemplate: s.updateTemplate,
loadTemplates: s.loadTemplates,
})));
React.useEffect(() => {
loadTemplates();
}, [loadTemplates]);
const handleCreateNew = async () => {
const baseName = 'new-template';
let newName = baseName;
let counter = 1;
const existingIds = new Set(templates.map((t) => t.id));
while (existingIds.has(newName.replace(/\s+/g, '-').toLowerCase())) {
newName = `${baseName}-${counter}`;
counter++;
}
const slug = newName.replace(/\s+/g, '-').toLowerCase();
const success = await usePromptTemplatesStore.getState().createTemplate(slug, newName, '');
if (!success) {
toast.error(t('settings.promptTemplates.page.toast.createFailed'));
return;
}
usePromptTemplatesStore.getState().setSelectedTemplate(slug);
onItemSelect?.();
};
const handleDelete = async () => {
if (!confirmDeleteTemplate) return;
setIsDeletePending(true);
const success = await deleteTemplate(confirmDeleteTemplate.id);
if (success) {
toast.success(t('settings.promptTemplates.sidebar.toast.deleted', { name: confirmDeleteTemplate.name }));
setConfirmDeleteTemplate(null);
} else {
toast.error(t('settings.promptTemplates.sidebar.toast.deleteFailed'));
}
setIsDeletePending(false);
};
const handleDuplicate = async (template: PromptTemplate) => {
let copyName = `${template.name} Copy`;
let copyId = `${template.id}-copy`;
let counter = 1;
const existingIds = new Set(templates.map((t) => t.id));
while (existingIds.has(copyId)) {
copyName = `${template.name} Copy ${counter}`;
copyId = `${template.id}-copy-${counter}`;
counter++;
}
const success = await usePromptTemplatesStore.getState().createTemplate(copyId, copyName, template.body);
if (!success) {
toast.error(t('settings.promptTemplates.page.toast.createFailed'));
return;
}
setSelectedTemplate(copyId);
onItemSelect?.();
};
const handleOpenRename = (template: PromptTemplate) => {
setRenameNewName(template.name);
setRenameDialogTemplate(template);
};
const handleRename = async () => {
if (!renameDialogTemplate) return;
const trimmed = renameNewName.trim();
if (!trimmed) {
toast.error(t('settings.promptTemplates.sidebar.toast.nameRequired'));
return;
}
if (trimmed === renameDialogTemplate.name) {
setRenameDialogTemplate(null);
return;
}
const success = await updateTemplate(renameDialogTemplate.id, { name: trimmed });
if (success) {
toast.success(t('settings.promptTemplates.sidebar.toast.renamed'));
} else {
toast.error(t('settings.promptTemplates.sidebar.toast.renameFailed'));
}
setRenameDialogTemplate(null);
};
const sortedTemplates = React.useMemo(
() => [...templates].sort((a, b) => a.name.localeCompare(b.name)),
[templates],
);
return (
<div className={cn('flex h-full flex-col', 'bg-background')}>
<div className="border-b px-3 pt-4 pb-3">
<h2 className="text-base font-semibold text-foreground mb-3">{t('settings.promptTemplates.sidebar.title')}</h2>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">{t('settings.promptTemplates.sidebar.total', { count: templates.length })}</span>
<Button size="sm" variant="ghost" className="h-7 w-7 px-0 -my-1 text-muted-foreground" onClick={handleCreateNew}>
<RiAddLine className="h-3.5 w-3.5" />
</Button>
</div>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
{sortedTemplates.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiFileTextLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">{t('settings.promptTemplates.sidebar.empty.title')}</p>
<p className="typography-meta mt-1 opacity-75">{t('settings.promptTemplates.sidebar.empty.description')}</p>
</div>
) : (
sortedTemplates.map((template) => (
<TemplateListItem
key={template.id}
template={template}
isSelected={selectedTemplateId === template.id}
onSelect={() => {
setSelectedTemplate(template.id);
onItemSelect?.();
}}
onDelete={() => setConfirmDeleteTemplate(template)}
onRename={() => handleOpenRename(template)}
onDuplicate={() => handleDuplicate(template)}
isMenuOpen={openMenuId === template.id}
onMenuOpenChange={(open) => setOpenMenuId(open ? template.id : null)}
/>
))
)}
</ScrollableOverlay>
<Dialog
open={confirmDeleteTemplate !== null}
onOpenChange={(open) => { if (!open && !isDeletePending) setConfirmDeleteTemplate(null); }}
>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{t('settings.promptTemplates.sidebar.dialog.deleteTitle')}</DialogTitle>
<DialogDescription>
{t('settings.promptTemplates.sidebar.dialog.deleteDescription', { name: confirmDeleteTemplate?.name ?? '' })}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button size="sm" variant="ghost" onClick={() => setConfirmDeleteTemplate(null)} disabled={isDeletePending}>
{t('settings.common.actions.cancel')}
</Button>
<Button size="sm" onClick={handleDelete} disabled={isDeletePending}>
{t('settings.common.actions.delete')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={renameDialogTemplate !== null} onOpenChange={(open) => !open && setRenameDialogTemplate(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('settings.promptTemplates.sidebar.renameDialog.title')}</DialogTitle>
<DialogDescription>
{t('settings.promptTemplates.sidebar.renameDialog.description', { name: renameDialogTemplate?.name ?? '' })}
</DialogDescription>
</DialogHeader>
<Input
value={renameNewName}
onChange={(e) => setRenameNewName(e.target.value)}
placeholder={t('settings.promptTemplates.sidebar.renameDialog.placeholder')}
className="text-foreground placeholder:text-muted-foreground"
onKeyDown={(e) => { if (e.key === 'Enter') handleRename(); }}
/>
<DialogFooter>
<Button size="sm" variant="ghost" onClick={() => setRenameDialogTemplate(null)}>
{t('settings.common.actions.cancel')}
</Button>
<Button size="sm" onClick={handleRename}>
{t('settings.common.actions.rename')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
};
interface TemplateListItemProps {
template: PromptTemplate;
isSelected: boolean;
onSelect: () => void;
onDelete?: () => void;
onRename?: () => void;
onDuplicate: () => void;
isMenuOpen: boolean;
onMenuOpenChange: (open: boolean) => void;
}
const TemplateListItem: React.FC<TemplateListItemProps> = ({
template,
isSelected,
onSelect,
onDelete,
onRename,
onDuplicate,
isMenuOpen,
onMenuOpenChange,
}) => {
const { t } = useI18n();
const isMobile = isMobileDeviceViaCSS();
return (
<div
className={cn(
'group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none',
isSelected ? 'bg-interactive-selection' : 'hover:bg-interactive-hover',
)}
onContextMenu={!isMobile ? (e) => { e.preventDefault(); onMenuOpenChange(true); } : undefined}
>
<div className="flex min-w-0 flex-1 items-center">
<button
onClick={onSelect}
className="flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
tabIndex={0}
>
<div className="flex items-center gap-2">
<span className="typography-ui-label font-normal truncate text-foreground">
{template.name}
</span>
{template.isDefault && (
<span className="typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50">
{t('settings.promptTemplates.sidebar.badge.default')}
</span>
)}
</div>
{template.body && (
<div className="typography-micro text-muted-foreground/60 truncate leading-tight">
{template.body.substring(0, 80)}
</div>
)}
</button>
{!template.isDefault && (
<DropdownMenu open={isMenuOpen} onOpenChange={onMenuOpenChange}>
<DropdownMenuTrigger asChild>
<Button size="sm" variant="ghost" className="h-6 w-6 px-0 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100">
<RiMore2Line className="h-3.5 w-3.5" />
</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" />
{t('settings.common.actions.rename')}
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); onDuplicate(); }}>
<RiFileCopyLine className="h-4 w-4 mr-px" />
{t('settings.common.actions.duplicate')}
</DropdownMenuItem>
{onDelete && (
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); onDelete(); }} className="text-destructive focus:text-destructive">
<RiDeleteBinLine className="h-4 w-4 mr-px" />
{t('settings.common.actions.delete')}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
);
};
@@ -5,6 +5,7 @@ import { useProjectsStore } from '@/stores/useProjectsStore';
import { useAgentsStore } from '@/stores/useAgentsStore';
import { useCommandsStore } from '@/stores/useCommandsStore';
import { useMcpConfigStore } from '@/stores/useMcpConfigStore';
import { usePromptTemplatesStore } from '@/stores/usePromptTemplatesStore';
import { useSkillsStore } from '@/stores/useSkillsStore';
import { useSkillsCatalogStore } from '@/stores/useSkillsCatalogStore';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
@@ -28,6 +29,8 @@ import { UsageSidebar } from '@/components/sections/usage/UsageSidebar';
import { UsagePage } from '@/components/sections/usage/UsagePage';
import { MagicPromptsSidebar } from '@/components/sections/magic-prompts/MagicPromptsSidebar';
import { MagicPromptsPage } from '@/components/sections/magic-prompts/MagicPromptsPage';
import { PromptTemplatesSidebar } from '@/components/sections/prompt-templates/PromptTemplatesSidebar';
import { PromptTemplatesPage } from '@/components/sections/prompt-templates/PromptTemplatesPage';
import { GitPage } from '@/components/sections/git-identities/GitPage';
import type { OpenChamberSection } from '@/components/sections/openchamber/types';
import { OpenChamberPage } from '@/components/sections/openchamber/OpenChamberPage';
@@ -73,6 +76,7 @@ const pageOrder: SettingsPageSlug[] = [
'shortcuts',
'git',
'magic-prompts',
'prompt-templates',
'projects',
'remote-instances',
'agents',
@@ -113,6 +117,8 @@ export function getSettingsNavIcon(slug: SettingsPageSlug): IconName | null {
return 'chat-ai-3';
case 'magic-prompts':
return 'ai-generate-2';
case 'prompt-templates':
return 'file-text';
case 'notifications':
return 'notification-3';
case 'shortcuts':
@@ -357,6 +363,9 @@ export const SettingsView: React.FC<SettingsViewProps> = ({ onClose, forceMobile
void useSkillsStore.getState().loadSkills();
void useSkillsCatalogStore.getState().loadCatalog();
}
if (settingsSlug === 'prompt-templates') {
void usePromptTemplatesStore.getState().loadTemplates();
}
}, [activeProjectId, isSettingsDialogOpen, isWindowed, runtimeCtx.isVSCode, settingsSlug]);
const openPage = React.useCallback((slug: SettingsPageSlug) => {
@@ -423,6 +432,8 @@ export const SettingsView: React.FC<SettingsViewProps> = ({ onClose, forceMobile
return t('settings.page.sessions.title');
case 'magic-prompts':
return t('settings.page.magicPrompts.title');
case 'prompt-templates':
return t('settings.page.promptTemplates.title');
case 'notifications':
return t('settings.page.notifications.title');
case 'voice':
@@ -466,6 +477,8 @@ export const SettingsView: React.FC<SettingsViewProps> = ({ onClose, forceMobile
return <UsageSidebar onItemSelect={opts.onItemSelect} />;
case 'magic-prompts':
return <MagicPromptsSidebar onItemSelect={opts.onItemSelect} />;
case 'prompt-templates':
return <PromptTemplatesSidebar onItemSelect={opts.onItemSelect} />;
default:
return null;
}
@@ -502,6 +515,8 @@ export const SettingsView: React.FC<SettingsViewProps> = ({ onClose, forceMobile
return <UsagePage />;
case 'magic-prompts':
return <MagicPromptsPage />;
case 'prompt-templates':
return <PromptTemplatesPage />;
case 'git':
return <GitPage />;
case 'appearance':
@@ -347,8 +347,7 @@ export const AgentManagerEmptyState: React.FC<AgentManagerEmptyStateProps> = ({
await onCreateGroup?.({
name: groupName.trim(),
prompt: prompt.trim(),
models,
groups: [{ prompt: prompt.trim(), models }],
agent: selectedAgent || undefined,
worktreeBaseBranch: baseBranch,
files,
@@ -98,7 +98,8 @@ export const AgentManagerView: React.FC<AgentManagerViewProps> = ({ className })
}, [selectGroup]);
const handleCreateGroup = React.useCallback(async (params: CreateMultiRunParams) => {
toast.info(`Creating agent group "${params.name}" with ${params.models.length} model(s)...`);
const totalModels = params.groups.reduce((sum, g) => sum + g.models.length, 0);
toast.info(`Creating agent group "${params.name}" with ${totalModels} run(s)...`);
const result = await createMultiRun(params);