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);
@@ -44,6 +44,39 @@ export const settingsDict = {
'settings.page.notifications.title': 'Notifications',
'settings.page.voice.title': 'Voice',
'settings.page.tunnel.title': 'Remote Tunnel',
'settings.page.promptTemplates.title': 'Prompt Templates',
'settings.promptTemplates.sidebar.title': 'Prompt Templates',
'settings.promptTemplates.sidebar.total': 'Total: {count}',
'settings.promptTemplates.sidebar.empty.title': 'No prompt templates',
'settings.promptTemplates.sidebar.empty.description': 'Create a prompt template to get started.',
'settings.promptTemplates.sidebar.toast.deleted': 'Template "{name}" deleted',
'settings.promptTemplates.sidebar.toast.deleteFailed': 'Failed to delete template',
'settings.promptTemplates.sidebar.toast.nameRequired': 'Template name is required',
'settings.promptTemplates.sidebar.toast.renamed': 'Template renamed',
'settings.promptTemplates.sidebar.toast.renameFailed': 'Failed to rename template',
'settings.promptTemplates.sidebar.dialog.deleteTitle': 'Delete template?',
'settings.promptTemplates.sidebar.dialog.deleteDescription': 'This will permanently delete "{name}". This action cannot be undone.',
'settings.promptTemplates.sidebar.renameDialog.title': 'Rename template',
'settings.promptTemplates.sidebar.renameDialog.description': 'Enter a new name for "{name}".',
'settings.promptTemplates.sidebar.renameDialog.placeholder': 'Template name',
'settings.promptTemplates.sidebar.badge.default': 'default',
'settings.promptTemplates.page.empty.title': 'Select a template',
'settings.promptTemplates.page.empty.description': 'Choose a template from the sidebar to edit it.',
'settings.promptTemplates.page.title.new': 'New template',
'settings.promptTemplates.page.subtitle.edit': 'Edit template',
'settings.promptTemplates.page.subtitle.new': 'Create a new prompt template',
'settings.promptTemplates.page.section.identity': 'Identity',
'settings.promptTemplates.page.field.name': 'Name',
'settings.promptTemplates.page.field.namePlaceholder': 'Template name',
'settings.promptTemplates.page.section.template': 'Template',
'settings.promptTemplates.page.field.templatePlaceholder': 'Enter the prompt template text...',
'settings.promptTemplates.page.templateHint': 'This text will be prepended to the user\'s prompt when selected in a multi-run group.',
'settings.promptTemplates.page.toast.nameRequired': 'Template name is required',
'settings.promptTemplates.page.toast.updated': 'Template updated',
'settings.promptTemplates.page.toast.updateFailed': 'Failed to update template',
'settings.promptTemplates.page.toast.created': 'Template created',
'settings.promptTemplates.page.toast.createFailed': 'Failed to create template',
'settings.promptTemplates.page.toast.saveUnexpectedError': 'An unexpected error occurred while saving',
'settings.openchamber.tunnel.title': 'Remote Tunnel',
'settings.openchamber.tunnel.description': 'Configure secure remote access with quick links or your own managed remote Cloudflare tunnel.',
'settings.openchamber.tunnel.note.serverSideEnforced': 'Secure tunnel access is enforced server-side.',
+10
View File
@@ -191,6 +191,16 @@ export const dict = {
'multirun.fusion.actions.starting': 'Starting...',
'multirun.fusion.toast.noOutputs': 'No assistant outputs found to fuse.',
'multirun.fusion.toast.failed': 'Failed to start fusion.',
'multirun.launcher.attachments.label': 'Files',
'multirun.launcher.actions.startWithRunCount': 'Start ({count} runs)',
'multirun.launcher.groups.addGroup': 'Add run group',
'multirun.launcher.groups.removeGroup': 'Remove group',
'multirun.launcher.groups.groupLabel': 'Run group {index}',
'multirun.launcher.groups.template.label': 'Template',
'multirun.launcher.groups.template.placeholder': 'Select a template...',
'multirun.launcher.groups.template.custom': 'Custom prompt',
'multirun.launcher.groups.prompt.label': 'Prompt',
'multirun.launcher.groups.prompt.placeholder': 'Enter the prompt for this group...',
'sessions.sidebar.header.actions.searchSessions': 'Search sessions',
'sessions.sidebar.header.actions.exitSelection': 'Exit selection',
'sessions.sidebar.header.actions.selectSessions': 'Select sessions',
@@ -1570,4 +1570,37 @@ export const settingsDict = {
"settings.magicPrompts.page.toast.resetFailed": "No se pudo restablecer el prompt",
"settings.magicPrompts.page.toast.resetAllSuccess": "Se restablecieron todos los prompts sobrescritos",
"settings.magicPrompts.page.toast.resetAllFailed": "No se pudieron restablecer todos los prompts",
"settings.page.promptTemplates.title": "Plantillas de prompt",
"settings.promptTemplates.sidebar.title": "Plantillas de prompt",
"settings.promptTemplates.sidebar.total": "Total: {count}",
"settings.promptTemplates.sidebar.empty.title": "Sin plantillas de prompt",
"settings.promptTemplates.sidebar.empty.description": "Crea una plantilla de prompt para comenzar.",
"settings.promptTemplates.sidebar.toast.deleted": 'Plantilla "{name}" eliminada',
"settings.promptTemplates.sidebar.toast.deleteFailed": "Error al eliminar la plantilla",
"settings.promptTemplates.sidebar.toast.nameRequired": "El nombre de la plantilla es obligatorio",
"settings.promptTemplates.sidebar.toast.renamed": "Plantilla renombrada",
"settings.promptTemplates.sidebar.toast.renameFailed": "Error al renombrar la plantilla",
"settings.promptTemplates.sidebar.dialog.deleteTitle": "¿Eliminar plantilla?",
"settings.promptTemplates.sidebar.dialog.deleteDescription": 'Se eliminará permanentemente "{name}". Esta acción no se puede deshacer.',
"settings.promptTemplates.sidebar.renameDialog.title": "Renombrar plantilla",
"settings.promptTemplates.sidebar.renameDialog.description": 'Introduce un nuevo nombre para "{name}".',
"settings.promptTemplates.sidebar.renameDialog.placeholder": "Nombre de la plantilla",
"settings.promptTemplates.sidebar.badge.default": "predeterminada",
"settings.promptTemplates.page.empty.title": "Selecciona una plantilla",
"settings.promptTemplates.page.empty.description": "Elige una plantilla de la barra lateral para editarla.",
"settings.promptTemplates.page.title.new": "Nueva plantilla",
"settings.promptTemplates.page.subtitle.edit": "Editar plantilla",
"settings.promptTemplates.page.subtitle.new": "Crear una nueva plantilla de prompt",
"settings.promptTemplates.page.section.identity": "Identidad",
"settings.promptTemplates.page.field.name": "Nombre",
"settings.promptTemplates.page.field.namePlaceholder": "Nombre de la plantilla",
"settings.promptTemplates.page.section.template": "Plantilla",
"settings.promptTemplates.page.field.templatePlaceholder": "Introduce el texto de la plantilla de prompt...",
"settings.promptTemplates.page.templateHint": "Este texto se antepondrá al prompt del usuario cuando se seleccione en un grupo multi-run.",
"settings.promptTemplates.page.toast.nameRequired": "El nombre de la plantilla es obligatorio",
"settings.promptTemplates.page.toast.updated": "Plantilla actualizada",
"settings.promptTemplates.page.toast.updateFailed": "Error al actualizar la plantilla",
"settings.promptTemplates.page.toast.created": "Plantilla creada",
"settings.promptTemplates.page.toast.createFailed": "Error al crear la plantilla",
"settings.promptTemplates.page.toast.saveUnexpectedError": "Ocurrió un error inesperado al guardar",
} as const;
+10
View File
@@ -192,6 +192,16 @@ export const dict: Record<I18nKey, string> = {
"multirun.fusion.actions.starting": "Iniciando...",
"multirun.fusion.toast.noOutputs": "No se encontraron respuestas del asistente para fusionar.",
"multirun.fusion.toast.failed": "No se pudo iniciar fusion.",
"multirun.launcher.attachments.label": "Archivos",
"multirun.launcher.actions.startWithRunCount": "Iniciar ({count} ejecuciones)",
"multirun.launcher.groups.addGroup": "Añadir grupo de ejecución",
"multirun.launcher.groups.removeGroup": "Eliminar grupo",
"multirun.launcher.groups.groupLabel": "Grupo de ejecución {index}",
"multirun.launcher.groups.template.label": "Plantilla",
"multirun.launcher.groups.template.placeholder": "Selecciona una plantilla...",
"multirun.launcher.groups.template.custom": "Prompt personalizado",
"multirun.launcher.groups.prompt.label": "Prompt",
"multirun.launcher.groups.prompt.placeholder": "Introduce el prompt para este grupo...",
"sessions.sidebar.header.actions.searchSessions": "Buscar sesiones",
"sessions.sidebar.header.actions.exitSelection": "Salir de selección",
"sessions.sidebar.header.actions.selectSessions": "Seleccionar sesiones",
@@ -1570,4 +1570,37 @@ export const settingsDict = {
'settings.magicPrompts.page.toast.resetFailed': '프롬프트를 초기화하지 못했습니다',
'settings.magicPrompts.page.toast.resetAllSuccess': '모든 프롬프트 오버라이드가 초기화되었습니다',
'settings.magicPrompts.page.toast.resetAllFailed': '모든 프롬프트를 초기화하지 못했습니다',
'settings.page.promptTemplates.title': '프롬프트 템플릿',
'settings.promptTemplates.sidebar.title': '프롬프트 템플릿',
'settings.promptTemplates.sidebar.total': '총 {count}개',
'settings.promptTemplates.sidebar.empty.title': '프롬프트 템플릿 없음',
'settings.promptTemplates.sidebar.empty.description': '프롬프트 템플릿을 만들어 보세요.',
'settings.promptTemplates.sidebar.toast.deleted': '템플릿 "{name}"이(가) 삭제되었습니다',
'settings.promptTemplates.sidebar.toast.deleteFailed': '템플릿 삭제 실패',
'settings.promptTemplates.sidebar.toast.nameRequired': '템플릿 이름은 필수입니다',
'settings.promptTemplates.sidebar.toast.renamed': '템플릿 이름이 변경되었습니다',
'settings.promptTemplates.sidebar.toast.renameFailed': '템플릿 이름 변경 실패',
'settings.promptTemplates.sidebar.dialog.deleteTitle': '템플릿을 삭제하시겠습니까?',
'settings.promptTemplates.sidebar.dialog.deleteDescription': '"{name}"이(가) 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.',
'settings.promptTemplates.sidebar.renameDialog.title': '템플릿 이름 변경',
'settings.promptTemplates.sidebar.renameDialog.description': '"{name}"의 새 이름을 입력하세요.',
'settings.promptTemplates.sidebar.renameDialog.placeholder': '템플릿 이름',
'settings.promptTemplates.sidebar.badge.default': '기본',
'settings.promptTemplates.page.empty.title': '템플릿을 선택하세요',
'settings.promptTemplates.page.empty.description': '사이드바에서 템플릿을 선택하여 편집하세요.',
'settings.promptTemplates.page.title.new': '새 템플릿',
'settings.promptTemplates.page.subtitle.edit': '템플릿 편집',
'settings.promptTemplates.page.subtitle.new': '새 프롬프트 템플릿 만들기',
'settings.promptTemplates.page.section.identity': '식별 정보',
'settings.promptTemplates.page.field.name': '이름',
'settings.promptTemplates.page.field.namePlaceholder': '템플릿 이름',
'settings.promptTemplates.page.section.template': '템플릿',
'settings.promptTemplates.page.field.templatePlaceholder': '프롬프트 템플릿 텍스트를 입력하세요...',
'settings.promptTemplates.page.templateHint': '멀티런 그룹에서 선택하면 이 텍스트가 사용자 프롬프트 앞에 추가됩니다.',
'settings.promptTemplates.page.toast.nameRequired': '템플릿 이름은 필수입니다',
'settings.promptTemplates.page.toast.updated': '템플릿이 업데이트되었습니다',
'settings.promptTemplates.page.toast.updateFailed': '템플릿 업데이트 실패',
'settings.promptTemplates.page.toast.created': '템플릿이 생성되었습니다',
'settings.promptTemplates.page.toast.createFailed': '템플릿 생성 실패',
'settings.promptTemplates.page.toast.saveUnexpectedError': '저장 중 예기치 않은 오류가 발생했습니다',
} as const;
+10
View File
@@ -192,6 +192,16 @@ export const dict: Record<I18nKey, string> = {
'multirun.fusion.actions.starting': '시작 중...',
'multirun.fusion.toast.noOutputs': 'fusion할 어시스턴트 응답을 찾지 못했습니다.',
'multirun.fusion.toast.failed': 'fusion을 시작하지 못했습니다.',
'multirun.launcher.attachments.label': '파일',
'multirun.launcher.actions.startWithRunCount': '시작 ({count}개 실행)',
'multirun.launcher.groups.addGroup': '실행 그룹 추가',
'multirun.launcher.groups.removeGroup': '그룹 제거',
'multirun.launcher.groups.groupLabel': '실행 그룹 {index}',
'multirun.launcher.groups.template.label': '템플릿',
'multirun.launcher.groups.template.placeholder': '템플릿 선택...',
'multirun.launcher.groups.template.custom': '사용자 지정 프롬프트',
'multirun.launcher.groups.prompt.label': '프롬프트',
'multirun.launcher.groups.prompt.placeholder': '이 그룹의 프롬프트를 입력하세요...',
'sessions.sidebar.header.actions.searchSessions': '세션 검색',
'sessions.sidebar.header.actions.exitSelection': '선택 종료',
'sessions.sidebar.header.actions.selectSessions': '세션 선택',
@@ -963,6 +963,39 @@ export const settingsDict = {
'settings.page.skills.title': 'Umiejętności',
'settings.page.skillsCatalog.title': 'Katalog umiejętności',
'settings.page.tunnel.title': 'Zdalny Tunel',
'settings.page.promptTemplates.title': 'Szablony promptów',
'settings.promptTemplates.sidebar.title': 'Szablony promptów',
'settings.promptTemplates.sidebar.total': 'Suma: {count}',
'settings.promptTemplates.sidebar.empty.title': 'Brak szablonów promptów',
'settings.promptTemplates.sidebar.empty.description': 'Utwórz szablon promptu, aby rozpocząć.',
'settings.promptTemplates.sidebar.toast.deleted': 'Szablon "{name}" usunięty',
'settings.promptTemplates.sidebar.toast.deleteFailed': 'Nie udało się usunąć szablonu',
'settings.promptTemplates.sidebar.toast.nameRequired': 'Nazwa szablonu jest wymagana',
'settings.promptTemplates.sidebar.toast.renamed': 'Szablon zmienił nazwę',
'settings.promptTemplates.sidebar.toast.renameFailed': 'Nie udało się zmienić nazwy szablonu',
'settings.promptTemplates.sidebar.dialog.deleteTitle': 'Usunąć szablon?',
'settings.promptTemplates.sidebar.dialog.deleteDescription': 'To trwale usunie "{name}". Tej operacji nie można cofnąć.',
'settings.promptTemplates.sidebar.renameDialog.title': 'Zmień nazwę szablonu',
'settings.promptTemplates.sidebar.renameDialog.description': 'Wpisz nową nazwę dla "{name}".',
'settings.promptTemplates.sidebar.renameDialog.placeholder': 'Nazwa szablonu',
'settings.promptTemplates.sidebar.badge.default': 'domyślny',
'settings.promptTemplates.page.empty.title': 'Wybierz szablon',
'settings.promptTemplates.page.empty.description': 'Wybierz szablon z paska bocznego, aby go edytować.',
'settings.promptTemplates.page.title.new': 'Nowy szablon',
'settings.promptTemplates.page.subtitle.edit': 'Edytuj szablon',
'settings.promptTemplates.page.subtitle.new': 'Utwórz nowy szablon promptu',
'settings.promptTemplates.page.section.identity': 'Tożsamość',
'settings.promptTemplates.page.field.name': 'Nazwa',
'settings.promptTemplates.page.field.namePlaceholder': 'Nazwa szablonu',
'settings.promptTemplates.page.section.template': 'Szablon',
'settings.promptTemplates.page.field.templatePlaceholder': 'Wpisz tekst szablonu promptu...',
'settings.promptTemplates.page.templateHint': 'Ten tekst zostanie dodany przed promptem użytkownika po wybraniu w grupie wielokrotnego uruchomienia.',
'settings.promptTemplates.page.toast.nameRequired': 'Nazwa szablonu jest wymagana',
'settings.promptTemplates.page.toast.updated': 'Szablon zaktualizowany',
'settings.promptTemplates.page.toast.updateFailed': 'Nie udało się zaktualizować szablonu',
'settings.promptTemplates.page.toast.created': 'Szablon utworzony',
'settings.promptTemplates.page.toast.createFailed': 'Nie udało się utworzyć szablonu',
'settings.promptTemplates.page.toast.saveUnexpectedError': 'Wystąpił nieoczekiwany błąd podczas zapisywania',
'settings.page.usage.title': 'Użycie',
'settings.page.voice.title': 'Głos',
'settings.projects.actions.actions.add': 'Dodaj akcję',
+10
View File
@@ -262,6 +262,16 @@ export const dict: Record<I18nKey, string> = {
'multirun.modelMultiSelect.validation.minOnly': 'Wybierz przynajmniej {min} modele.',
'multirun.modelMultiSelect.validation.minToMax': 'Wybierz od {min} do {max} modeli.',
'multirun.agentSelector.placeholder': 'Wybierz agenta',
'multirun.launcher.attachments.label': 'Pliki',
'multirun.launcher.actions.startWithRunCount': 'Uruchom ({count} uruchomień)',
'multirun.launcher.groups.addGroup': 'Dodaj grupę uruchomień',
'multirun.launcher.groups.removeGroup': 'Usuń grupę',
'multirun.launcher.groups.groupLabel': 'Grupa uruchomień {index}',
'multirun.launcher.groups.template.label': 'Szablon',
'multirun.launcher.groups.template.placeholder': 'Wybierz szablon...',
'multirun.launcher.groups.template.custom': 'Niestandardowy prompt',
'multirun.launcher.groups.prompt.label': 'Prompt',
'multirun.launcher.groups.prompt.placeholder': 'Wpisz prompt dla tej grupy...',
'multirun.fusion.title': 'Uruchom fusion',
'multirun.fusion.description': 'Połącz wybrane wyniki multi-run w jedną mocniejszą odpowiedź.',
'multirun.fusion.provider.placeholder': 'Provider',
@@ -1570,4 +1570,37 @@ export const settingsDict = {
"settings.magicPrompts.page.toast.resetFailed": "Não foi possível redefinir o prompt",
"settings.magicPrompts.page.toast.resetAllSuccess": "Todos os prompts sobrescritos foram redefinidos",
"settings.magicPrompts.page.toast.resetAllFailed": "Não foi possível redefinir todos os prompts",
"settings.page.promptTemplates.title": "Templates de Prompt",
"settings.promptTemplates.sidebar.title": "Templates de Prompt",
"settings.promptTemplates.sidebar.total": "Total: {count}",
"settings.promptTemplates.sidebar.empty.title": "Nenhum template de prompt",
"settings.promptTemplates.sidebar.empty.description": "Crie um template de prompt para começar.",
"settings.promptTemplates.sidebar.toast.deleted": 'Template "{name}" excluído',
"settings.promptTemplates.sidebar.toast.deleteFailed": "Falha ao excluir template",
"settings.promptTemplates.sidebar.toast.nameRequired": "O nome do template é obrigatório",
"settings.promptTemplates.sidebar.toast.renamed": "Template renomeado",
"settings.promptTemplates.sidebar.toast.renameFailed": "Falha ao renomear template",
"settings.promptTemplates.sidebar.dialog.deleteTitle": "Excluir template?",
"settings.promptTemplates.sidebar.dialog.deleteDescription": 'Isso excluirá permanentemente "{name}". Esta ação não pode ser desfeita.',
"settings.promptTemplates.sidebar.renameDialog.title": "Renomear template",
"settings.promptTemplates.sidebar.renameDialog.description": 'Digite um novo nome para "{name}".',
"settings.promptTemplates.sidebar.renameDialog.placeholder": "Nome do template",
"settings.promptTemplates.sidebar.badge.default": "padrão",
"settings.promptTemplates.page.empty.title": "Selecione um template",
"settings.promptTemplates.page.empty.description": "Escolha um template na barra lateral para editá-lo.",
"settings.promptTemplates.page.title.new": "Novo template",
"settings.promptTemplates.page.subtitle.edit": "Editar template",
"settings.promptTemplates.page.subtitle.new": "Criar um novo template de prompt",
"settings.promptTemplates.page.section.identity": "Identidade",
"settings.promptTemplates.page.field.name": "Nome",
"settings.promptTemplates.page.field.namePlaceholder": "Nome do template",
"settings.promptTemplates.page.section.template": "Template",
"settings.promptTemplates.page.field.templatePlaceholder": "Digite o texto do template de prompt...",
"settings.promptTemplates.page.templateHint": "Este texto será adicionado antes do prompt do usuário quando selecionado em um grupo multi-run.",
"settings.promptTemplates.page.toast.nameRequired": "O nome do template é obrigatório",
"settings.promptTemplates.page.toast.updated": "Template atualizado",
"settings.promptTemplates.page.toast.updateFailed": "Falha ao atualizar template",
"settings.promptTemplates.page.toast.created": "Template criado",
"settings.promptTemplates.page.toast.createFailed": "Falha ao criar template",
"settings.promptTemplates.page.toast.saveUnexpectedError": "Ocorreu um erro inesperado ao salvar",
} as const;
@@ -192,6 +192,16 @@ export const dict: Record<I18nKey, string> = {
"multirun.fusion.actions.starting": "Iniciando...",
"multirun.fusion.toast.noOutputs": "Nenhuma resposta do assistente encontrada para fusion.",
"multirun.fusion.toast.failed": "Falha ao iniciar fusion.",
"multirun.launcher.attachments.label": "Arquivos",
"multirun.launcher.actions.startWithRunCount": "Iniciar ({count} execuções)",
"multirun.launcher.groups.addGroup": "Adicionar grupo de execução",
"multirun.launcher.groups.removeGroup": "Remover grupo",
"multirun.launcher.groups.groupLabel": "Grupo de execução {index}",
"multirun.launcher.groups.template.label": "Template",
"multirun.launcher.groups.template.placeholder": "Selecione um template...",
"multirun.launcher.groups.template.custom": "Prompt personalizado",
"multirun.launcher.groups.prompt.label": "Prompt",
"multirun.launcher.groups.prompt.placeholder": "Insira o prompt para este grupo...",
"sessions.sidebar.header.actions.searchSessions": "Pesquisar sessões",
"sessions.sidebar.header.actions.exitSelection": "Sair da seleção",
"sessions.sidebar.header.actions.selectSessions": "Selecionar sessões",
@@ -1570,4 +1570,37 @@ export const settingsDict = {
"settings.magicPrompts.page.toast.resetFailed": "Не вдалося скинути промпт",
"settings.magicPrompts.page.toast.resetAllSuccess": "Усі перевизначення промптів скинуто",
"settings.magicPrompts.page.toast.resetAllFailed": "Не вдалося скинути всі промпти",
"settings.page.promptTemplates.title": "Шаблони промптів",
"settings.promptTemplates.sidebar.title": "Шаблони промптів",
"settings.promptTemplates.sidebar.total": "Всього: {count}",
"settings.promptTemplates.sidebar.empty.title": "Немає шаблонів промптів",
"settings.promptTemplates.sidebar.empty.description": "Створіть шаблон промпту для початку.",
"settings.promptTemplates.sidebar.toast.deleted": 'Шаблон "{name}" видалено',
"settings.promptTemplates.sidebar.toast.deleteFailed": "Не вдалося видалити шаблон",
"settings.promptTemplates.sidebar.toast.nameRequired": "Назва шаблону обов'язкова",
"settings.promptTemplates.sidebar.toast.renamed": "Шаблон перейменовано",
"settings.promptTemplates.sidebar.toast.renameFailed": "Не вдалося перейменувати шаблон",
"settings.promptTemplates.sidebar.dialog.deleteTitle": "Видалити шаблон?",
"settings.promptTemplates.sidebar.dialog.deleteDescription": 'Це назавжди видалить "{name}". Цю дію не можна скасувати.',
"settings.promptTemplates.sidebar.renameDialog.title": "Перейменувати шаблон",
"settings.promptTemplates.sidebar.renameDialog.description": 'Введіть нову назву для "{name}".',
"settings.promptTemplates.sidebar.renameDialog.placeholder": "Назва шаблону",
"settings.promptTemplates.sidebar.badge.default": "за замовчуванням",
"settings.promptTemplates.page.empty.title": "Оберіть шаблон",
"settings.promptTemplates.page.empty.description": "Оберіть шаблон на бічній панелі для редагування.",
"settings.promptTemplates.page.title.new": "Новий шаблон",
"settings.promptTemplates.page.subtitle.edit": "Редагувати шаблон",
"settings.promptTemplates.page.subtitle.new": "Створити новий шаблон промпту",
"settings.promptTemplates.page.section.identity": "Ідентифікація",
"settings.promptTemplates.page.field.name": "Назва",
"settings.promptTemplates.page.field.namePlaceholder": "Назва шаблону",
"settings.promptTemplates.page.section.template": "Шаблон",
"settings.promptTemplates.page.field.templatePlaceholder": "Введіть текст шаблону промпту...",
"settings.promptTemplates.page.templateHint": "Цей текст буде додано перед промптом користувача при виборі в групі мультизапуску.",
"settings.promptTemplates.page.toast.nameRequired": "Назва шаблону обов'язкова",
"settings.promptTemplates.page.toast.updated": "Шаблон оновлено",
"settings.promptTemplates.page.toast.updateFailed": "Не вдалося оновити шаблон",
"settings.promptTemplates.page.toast.created": "Шаблон створено",
"settings.promptTemplates.page.toast.createFailed": "Не вдалося створити шаблон",
"settings.promptTemplates.page.toast.saveUnexpectedError": "Сталася неочікувана помилка під час збереження",
} as const;
+10
View File
@@ -192,6 +192,16 @@ export const dict: Record<I18nKey, string> = {
"multirun.fusion.actions.starting": "Запуск...",
"multirun.fusion.toast.noOutputs": "Не знайдено відповідей асистента для fusion.",
"multirun.fusion.toast.failed": "Не вдалося запустити fusion.",
"multirun.launcher.attachments.label": "Файли",
"multirun.launcher.actions.startWithRunCount": "Запустити ({count} запусків)",
"multirun.launcher.groups.addGroup": "Додати групу запусків",
"multirun.launcher.groups.removeGroup": "Видалити групу",
"multirun.launcher.groups.groupLabel": "Група запусків {index}",
"multirun.launcher.groups.template.label": "Шаблон",
"multirun.launcher.groups.template.placeholder": "Оберіть шаблон...",
"multirun.launcher.groups.template.custom": "Довільний промпт",
"multirun.launcher.groups.prompt.label": "Промпт",
"multirun.launcher.groups.prompt.placeholder": "Введіть промпт для цієї групи...",
"sessions.sidebar.header.actions.searchSessions": "Пошук сесій",
"sessions.sidebar.header.actions.exitSelection": "Вийти з вибору",
"sessions.sidebar.header.actions.selectSessions": "Вибрати сесії",
@@ -1570,4 +1570,37 @@ export const settingsDict = {
'settings.magicPrompts.page.toast.resetFailed': '重置提示词失败',
'settings.magicPrompts.page.toast.resetAllSuccess': '所有提示词覆盖已重置',
'settings.magicPrompts.page.toast.resetAllFailed': '重置全部提示词失败',
'settings.page.promptTemplates.title': '提示词模板',
'settings.promptTemplates.sidebar.title': '提示词模板',
'settings.promptTemplates.sidebar.total': '共 {count} 个',
'settings.promptTemplates.sidebar.empty.title': '暂无提示词模板',
'settings.promptTemplates.sidebar.empty.description': '创建一个提示词模板开始使用。',
'settings.promptTemplates.sidebar.toast.deleted': '模板"{name}"已删除',
'settings.promptTemplates.sidebar.toast.deleteFailed': '删除模板失败',
'settings.promptTemplates.sidebar.toast.nameRequired': '模板名称为必填项',
'settings.promptTemplates.sidebar.toast.renamed': '模板已重命名',
'settings.promptTemplates.sidebar.toast.renameFailed': '重命名模板失败',
'settings.promptTemplates.sidebar.dialog.deleteTitle': '删除模板?',
'settings.promptTemplates.sidebar.dialog.deleteDescription': '将永久删除"{name}"。此操作无法撤销。',
'settings.promptTemplates.sidebar.renameDialog.title': '重命名模板',
'settings.promptTemplates.sidebar.renameDialog.description': '为"{name}"输入新名称。',
'settings.promptTemplates.sidebar.renameDialog.placeholder': '模板名称',
'settings.promptTemplates.sidebar.badge.default': '默认',
'settings.promptTemplates.page.empty.title': '选择一个模板',
'settings.promptTemplates.page.empty.description': '从侧边栏选择一个模板进行编辑。',
'settings.promptTemplates.page.title.new': '新建模板',
'settings.promptTemplates.page.subtitle.edit': '编辑模板',
'settings.promptTemplates.page.subtitle.new': '创建新的提示词模板',
'settings.promptTemplates.page.section.identity': '标识',
'settings.promptTemplates.page.field.name': '名称',
'settings.promptTemplates.page.field.namePlaceholder': '模板名称',
'settings.promptTemplates.page.section.template': '模板',
'settings.promptTemplates.page.field.templatePlaceholder': '输入提示词模板文本...',
'settings.promptTemplates.page.templateHint': '在多运行组中选择此模板时,此文本将添加到用户提示词之前。',
'settings.promptTemplates.page.toast.nameRequired': '模板名称为必填项',
'settings.promptTemplates.page.toast.updated': '模板已更新',
'settings.promptTemplates.page.toast.updateFailed': '更新模板失败',
'settings.promptTemplates.page.toast.created': '模板已创建',
'settings.promptTemplates.page.toast.createFailed': '创建模板失败',
'settings.promptTemplates.page.toast.saveUnexpectedError': '保存时发生意外错误',
} as const;
@@ -192,6 +192,16 @@ export const dict: Record<I18nKey, string> = {
'multirun.fusion.actions.starting': '正在开始...',
'multirun.fusion.toast.noOutputs': '未找到可用于融合的助手输出。',
'multirun.fusion.toast.failed': '启动融合失败。',
'multirun.launcher.attachments.label': '文件',
'multirun.launcher.actions.startWithRunCount': '开始({count} 次运行)',
'multirun.launcher.groups.addGroup': '添加运行组',
'multirun.launcher.groups.removeGroup': '移除运行组',
'multirun.launcher.groups.groupLabel': '运行组 {index}',
'multirun.launcher.groups.template.label': '模板',
'multirun.launcher.groups.template.placeholder': '选择模板...',
'multirun.launcher.groups.template.custom': '自定义提示词',
'multirun.launcher.groups.prompt.label': '提示词',
'multirun.launcher.groups.prompt.placeholder': '输入此运行组的提示词...',
'sessions.sidebar.header.actions.searchSessions': '搜索会话',
'sessions.sidebar.header.actions.exitSelection': '退出选择',
'sessions.sidebar.header.actions.selectSessions': '选择会话',
+8
View File
@@ -18,6 +18,7 @@ export type SettingsPageSlug =
| 'shortcuts'
| 'sessions'
| 'magic-prompts'
| 'prompt-templates'
| 'notifications'
| 'voice'
| 'tunnel';
@@ -184,6 +185,13 @@ export const SETTINGS_PAGE_METADATA: readonly SettingsPageMeta[] = [
keywords: ['prompts', 'templates', 'git', 'github', 'review', 'commit', 'pull request'],
isAvailable: (ctx) => !ctx.isVSCode,
},
{
slug: 'prompt-templates',
title: 'Prompt Templates',
group: 'general',
kind: 'split',
keywords: ['prompt', 'templates', 'multi-run', 'strategy', 'approach'],
},
{ slug: 'notifications', title: 'Notifications', group: 'general', kind: 'single', keywords: ['alerts', 'native', 'summary', 'summarization'], },
{ slug: 'voice', title: 'Voice', group: 'advanced', kind: 'single', keywords: ['tts', 'speech', 'voice'], isAvailable: (ctx) => !ctx.isVSCode },
+109 -122
View File
@@ -8,13 +8,9 @@ import type { ProjectRef } from '@/lib/worktrees/worktreeManager';
import { createWorktreeWithDefaults, resolveRootTrackingRemote } from '@/lib/worktrees/worktreeCreate';
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
import { checkIsGitRepository } from '@/lib/gitApi';
// sessionStore removed — sync bootstrap handles session loading
import { useDirectoryStore } from './useDirectoryStore';
import { useProjectsStore } from './useProjectsStore';
/**
* Generate a git-safe slug from a string.
*/
const toGitSafeSlug = (value: string): string => {
return value
.toLowerCase()
@@ -23,19 +19,12 @@ const toGitSafeSlug = (value: string): string => {
.substring(0, 50);
};
/**
* Generate a model slug from provider and model IDs.
*/
const toModelSlug = (providerID: string, modelID: string): string => {
const provider = toGitSafeSlug(providerID);
const model = toGitSafeSlug(modelID);
return `${provider}-${model}`.substring(0, 60);
};
/**
* Seed name for worktree creation.
* Uses slashes for readability; create payload will slugify.
*/
const generateWorktreeNameSeed = (groupSlug: string, modelSlug: string): string => {
return `${groupSlug}/${modelSlug}`;
};
@@ -43,16 +32,11 @@ const generateWorktreeNameSeed = (groupSlug: string, modelSlug: string): string
const resolveActiveProject = (): ProjectRef | null => {
const projectsState = useProjectsStore.getState();
const activeProjectId = projectsState.activeProjectId;
if (!activeProjectId) {
return null;
}
if (!activeProjectId) return null;
const project = projectsState.projects.find((entry) => entry.id === activeProjectId);
if (project?.path) {
return { id: project.id, path: project.path };
}
if (project?.path) return { id: project.id, path: project.path };
// Fall back to current directory only when active project is missing.
const currentDirectory = useDirectoryStore.getState().currentDirectory ?? null;
if (currentDirectory && currentDirectory.trim().length > 0) {
const normalized = currentDirectory.replace(/\\/g, '/').replace(/\/+$/, '') || currentDirectory;
@@ -68,7 +52,6 @@ interface MultiRunState {
}
interface MultiRunActions {
/** Create worktrees/sessions and immediately start all runs */
createMultiRun: (params: CreateMultiRunParams) => Promise<CreateMultiRunResult | null>;
clearError: () => void;
}
@@ -83,27 +66,31 @@ export const useMultiRunStore = create<MultiRunStore>()(
createMultiRun: async (params: CreateMultiRunParams) => {
const groupName = params.name.trim();
const prompt = params.prompt.trim();
const { models, agent, files, setupCommands } = params;
const { groups, agent, files, setupCommands } = params;
if (!groupName) {
set({ error: 'Group name is required' });
return null;
}
if (!prompt) {
set({ error: 'Prompt is required' });
if (!groups || groups.length === 0) {
set({ error: 'At least one run group is required' });
return null;
}
if (models.length < 1) {
set({ error: 'Select at least 1 model' });
return null;
}
if (models.length > 5) {
set({ error: 'Maximum 5 models allowed' });
return null;
for (let gi = 0; gi < groups.length; gi++) {
if (!groups[gi].prompt.trim()) {
set({ error: `Group ${gi + 1}: prompt is required` });
return null;
}
if (groups[gi].models.length < 1) {
set({ error: `Group ${gi + 1}: select at least 1 model` });
return null;
}
if (groups[gi].models.length > 5) {
set({ error: `Group ${gi + 1}: maximum 5 models allowed` });
return null;
}
}
set({ isLoading: true, error: null });
@@ -130,94 +117,101 @@ export const useMultiRunStore = create<MultiRunStore>()(
providerID: string;
modelID: string;
variant?: string;
prompt: string;
}> = [];
const commandsToRun = setupCommands?.filter((cmd) => cmd.trim().length > 0) ?? [];
// Count occurrences of each model to handle duplicates
const modelCounts = new Map<string, number>();
for (const model of models) {
const key = `${model.providerID}:${model.modelID}`;
modelCounts.set(key, (modelCounts.get(key) || 0) + 1);
}
for (let gi = 0; gi < groups.length; gi++) {
const group = groups[gi];
const prompt = group.prompt;
// Track current index per model during iteration
const modelIndexes = new Map<string, number>();
const modelCounts = new Map<string, number>();
for (const model of group.models) {
const key = `${model.providerID}:${model.modelID}`;
modelCounts.set(key, (modelCounts.get(key) || 0) + 1);
}
// 1) Create isolated worktrees for Git projects, or same-directory sessions otherwise.
for (const model of models) {
const key = `${model.providerID}:${model.modelID}`;
const count = modelCounts.get(key) || 1;
const index = (modelIndexes.get(key) || 0) + 1;
modelIndexes.set(key, index);
const modelIndexes = new Map<string, number>();
for (const model of group.models) {
const key = `${model.providerID}:${model.modelID}`;
const count = modelCounts.get(key) || 1;
const index = (modelIndexes.get(key) || 0) + 1;
modelIndexes.set(key, index);
const modelSlug = toModelSlug(model.providerID, model.modelID);
const groupPart = groups.length > 1 ? `g${gi + 1}` : '';
const modelPart = count > 1
? generateWorktreeNameSeed(groupSlug, `${modelSlug}/${index}`)
: generateWorktreeNameSeed(groupSlug, modelSlug);
const preferredName = groupPart
? `${groupPart}/${modelPart}`
: modelPart;
const modelSlug = toModelSlug(model.providerID, model.modelID);
// Append index only when same model is selected multiple times
const preferredName = count > 1
? generateWorktreeNameSeed(groupSlug, `${modelSlug}/${index}`)
: generateWorktreeNameSeed(groupSlug, modelSlug);
try {
// Session title format: groupSlug/provider/model (or groupSlug/provider/model/index for duplicates)
const sessionTitle = count > 1
? `${groupSlug}/${model.providerID}/${model.modelID}/${index}`
: `${groupSlug}/${model.providerID}/${model.modelID}`;
? `${groupSlug}/${groupPart}/${model.providerID}/${model.modelID}/${index}`
: groupPart
? `${groupSlug}/${groupPart}/${model.providerID}/${model.modelID}`
: `${groupSlug}/${model.providerID}/${model.modelID}`;
try {
if (!shouldIsolateRuns) {
const session = await opencodeClient.withDirectory(
directory,
() => opencodeClient.createSession({ title: sessionTitle }),
);
createdRuns.push({
sessionId: session.id,
worktreePath: directory,
providerID: model.providerID,
modelID: model.modelID,
variant: model.variant,
prompt,
});
continue;
}
const worktreeMetadata = await createWorktreeWithDefaults(project, {
preferredName,
mode: 'new',
branchName: preferredName,
worktreeName: preferredName,
startRef: params.worktreeBaseBranch || 'HEAD',
setupCommands: commandsToRun,
}, {
resolvedRootTrackingRemote: rootTrackingRemote,
});
const enrichedMetadata = {
...worktreeMetadata,
createdFromBranch: rootBranch,
kind: 'standard' as const,
};
if (!shouldIsolateRuns) {
const session = await opencodeClient.withDirectory(
directory,
() => opencodeClient.createSession({ title: sessionTitle })
worktreeMetadata.path,
() => opencodeClient.createSession({ title: sessionTitle }),
);
useSessionUIStore.getState().setWorktreeMetadata(session.id, enrichedMetadata);
createdRuns.push({
sessionId: session.id,
worktreePath: directory,
worktreePath: worktreeMetadata.path,
providerID: model.providerID,
modelID: model.modelID,
variant: model.variant,
prompt,
});
continue;
} catch (err) {
console.warn('[MultiRun] Failed to create session:', err);
}
const worktreeMetadata = await createWorktreeWithDefaults(project, {
preferredName,
mode: 'new',
branchName: preferredName,
worktreeName: preferredName,
startRef: params.worktreeBaseBranch || 'HEAD',
setupCommands: commandsToRun,
}, {
resolvedRootTrackingRemote: rootTrackingRemote,
});
const enrichedMetadata = {
...worktreeMetadata,
createdFromBranch: rootBranch,
kind: 'standard' as const,
};
const session = await opencodeClient.withDirectory(
worktreeMetadata.path,
() => opencodeClient.createSession({ title: sessionTitle })
);
useSessionUIStore.getState().setWorktreeMetadata(session.id, enrichedMetadata);
createdRuns.push({
sessionId: session.id,
worktreePath: worktreeMetadata.path,
providerID: model.providerID,
modelID: model.modelID,
variant: model.variant,
});
} catch (error) {
// Best-effort: allow partial success
console.warn('[MultiRun] Failed to create session:', error);
}
}
// Save setup commands to config if any were provided (for future worktree creation)
const commandsToSave = setupCommands?.filter(cmd => cmd.trim().length > 0) ?? [];
const commandsToSave = setupCommands?.filter((cmd) => cmd.trim().length > 0) ?? [];
if (commandsToSave.length > 0) {
saveWorktreeSetupCommands(project, commandsToSave).catch(() => {
console.warn('[MultiRun] Failed to save worktree setup commands');
@@ -232,9 +226,6 @@ export const useMultiRunStore = create<MultiRunStore>()(
return null;
}
// 2) Start all runs with the same prompt.
// IMPORTANT: do not await model/agent execution here; only worktree + session creation.
// Convert files to the format expected by sendMessage
const filesForMessage = files?.map((f) => ({
type: 'file' as const,
mime: f.mime,
@@ -242,33 +233,29 @@ export const useMultiRunStore = create<MultiRunStore>()(
url: f.url,
}));
// Session list refresh handled by sync bootstrap via SSE events
// Setup commands run via SDK worktree startCommand.
void (async () => {
try {
await Promise.allSettled(
createdRuns.map(async (run) => {
try {
await opencodeClient.withDirectory(run.worktreePath, () =>
opencodeClient.sendMessage({
id: run.sessionId,
providerID: run.providerID,
modelID: run.modelID,
variant: run.variant,
text: prompt,
agent,
files: filesForMessage,
})
);
} catch (error) {
console.warn('[MultiRun] Failed to start run:', error);
await opencodeClient.withDirectory(run.worktreePath, () =>
opencodeClient.sendMessage({
id: run.sessionId,
providerID: run.providerID,
modelID: run.modelID,
variant: run.variant,
text: run.prompt,
agent,
files: filesForMessage,
}),
);
} catch (err) {
console.warn('[MultiRun] Failed to start run:', err);
}
})
}),
);
} catch (error) {
console.warn('[MultiRun] Failed to start runs:', error);
} catch (err) {
console.warn('[MultiRun] Failed to start runs:', err);
}
})();
@@ -287,6 +274,6 @@ export const useMultiRunStore = create<MultiRunStore>()(
set({ error: null });
},
}),
{ name: 'multirun-store' }
)
{ name: 'multirun-store' },
),
);
@@ -0,0 +1,138 @@
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import type { PromptTemplate } from '@/types/prompt-template';
interface PromptTemplatesStore {
templates: PromptTemplate[];
isLoading: boolean;
selectedTemplateId: string | null;
setSelectedTemplate: (id: string | null) => void;
loadTemplates: () => Promise<boolean>;
createTemplate: (id: string, name: string, body: string) => Promise<boolean>;
updateTemplate: (id: string, updates: { name?: string; body?: string }) => Promise<boolean>;
deleteTemplate: (id: string) => Promise<boolean>;
getTemplateById: (id: string) => PromptTemplate | undefined;
}
const TEMPLATES_LOAD_CACHE_TTL_MS = 5000;
let lastLoadedAt = 0;
let loadInFlight: Promise<boolean> | null = null;
export const usePromptTemplatesStore = create<PromptTemplatesStore>()(
devtools(
(set, get) => ({
templates: [],
isLoading: false,
selectedTemplateId: null,
setSelectedTemplate: (id: string | null) => {
set({ selectedTemplateId: id });
},
loadTemplates: async () => {
const now = Date.now();
if (get().templates.length > 0 && now - lastLoadedAt < TEMPLATES_LOAD_CACHE_TTL_MS) {
return true;
}
if (loadInFlight) {
return loadInFlight;
}
const request = (async () => {
set({ isLoading: true });
try {
const response = await fetch('/api/config/prompt-templates', {
headers: { 'Cache-Control': 'no-cache' },
});
if (!response.ok) {
throw new Error('Failed to load prompt templates');
}
const templates: PromptTemplate[] = await response.json();
set({ templates, isLoading: false });
lastLoadedAt = Date.now();
return true;
} catch (error) {
console.error('[PromptTemplatesStore] Failed to load:', error);
set({ isLoading: false });
return false;
}
})();
loadInFlight = request;
try {
return await request;
} finally {
loadInFlight = null;
}
},
createTemplate: async (id: string, name: string, body: string) => {
try {
const response = await fetch(`/api/config/prompt-templates/${encodeURIComponent(id)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, body }),
});
if (!response.ok) {
const payload = await response.json().catch(() => null);
throw new Error(payload?.error || 'Failed to create prompt template');
}
lastLoadedAt = 0;
await get().loadTemplates();
return true;
} catch (error) {
console.error('[PromptTemplatesStore] Failed to create:', error);
return false;
}
},
updateTemplate: async (id: string, updates: { name?: string; body?: string }) => {
try {
const response = await fetch(`/api/config/prompt-templates/${encodeURIComponent(id)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
});
if (!response.ok) {
const payload = await response.json().catch(() => null);
throw new Error(payload?.error || 'Failed to update prompt template');
}
lastLoadedAt = 0;
await get().loadTemplates();
return true;
} catch (error) {
console.error('[PromptTemplatesStore] Failed to update:', error);
return false;
}
},
deleteTemplate: async (id: string) => {
try {
const response = await fetch(`/api/config/prompt-templates/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
if (!response.ok) {
const payload = await response.json().catch(() => null);
throw new Error(payload?.error || 'Failed to delete prompt template');
}
if (get().selectedTemplateId === id) {
set({ selectedTemplateId: null });
}
lastLoadedAt = 0;
await get().loadTemplates();
return true;
} catch (error) {
console.error('[PromptTemplatesStore] Failed to delete:', error);
return false;
}
},
getTemplateById: (id: string) => {
return get().templates.find((t) => t.id === id);
},
}),
{ name: 'prompt-templates-store' },
),
);
+7 -23
View File
@@ -1,10 +1,3 @@
/**
* Multi-Run Types
*
* Multi-Run starts the same prompt against multiple models in parallel,
* each in its own git worktree and OpenCode session.
*/
export interface MultiRunModelSelection {
providerID: string;
modelID: string;
@@ -13,38 +6,29 @@ export interface MultiRunModelSelection {
}
export interface MultiRunFileAttachment {
/** MIME type of the file */
mime: string;
/** Original filename */
filename: string;
/** Data URL (base64 encoded) */
url: string;
}
export interface CreateMultiRunParams {
/** Group name used for worktree directory and branch naming */
name: string;
/** Prompt sent to all sessions */
export interface MultiRunGroup {
prompt: string;
/** Models to run against (must have at least 2) */
models: MultiRunModelSelection[];
/** Optional agent to use for all runs */
templateId?: string;
}
export interface CreateMultiRunParams {
name: string;
groups: MultiRunGroup[];
agent?: string;
/** Base branch for new branches (defaults to `HEAD`). */
worktreeBaseBranch?: string;
/** Whether Git projects should isolate each run in its own worktree. */
isolateRuns?: boolean;
/** Files to attach to all runs */
files?: MultiRunFileAttachment[];
/** Setup commands to run in each new worktree after creation */
setupCommands?: string[];
}
export interface CreateMultiRunResult {
/** Canonical group slug used in session titles */
groupSlug: string;
/** Session IDs created successfully (in selection order) */
sessionIds: string[];
/** First successfully created session ID, if any */
firstSessionId: string | null;
}
+6
View File
@@ -0,0 +1,6 @@
export interface PromptTemplate {
id: string;
name: string;
body: string;
isDefault: boolean;
}
@@ -18,6 +18,11 @@ export const registerConfigEntityRoutes = (app, dependencies) => {
createMcpConfig,
updateMcpConfig,
deleteMcpConfig,
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
} = dependencies;
const completeMcpMutation = async (res, action, name, applyChange) => {
@@ -367,4 +372,95 @@ export const registerConfigEntityRoutes = (app, dependencies) => {
res.status(500).json({ error: error.message || 'Failed to delete command' });
}
});
app.get('/api/config/prompt-templates', async (req, res) => {
try {
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
const templates = listPromptTemplates(directory);
res.json(templates);
} catch (error) {
console.error('[API:GET /api/config/prompt-templates] Failed:', error);
res.status(500).json({ error: error.message || 'Failed to list prompt templates' });
}
});
app.get('/api/config/prompt-templates/:id', async (req, res) => {
try {
const id = req.params.id;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
const template = getPromptTemplate(id, directory);
if (!template) {
return res.status(404).json({ error: `Prompt template "${id}" not found` });
}
res.json(template);
} catch (error) {
console.error('[API:GET /api/config/prompt-templates/:id] Failed:', error);
res.status(500).json({ error: error.message || 'Failed to get prompt template' });
}
});
app.post('/api/config/prompt-templates/:id', async (req, res) => {
try {
const id = req.params.id;
const config = req.body || {};
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
console.log(`[API:POST /api/config/prompt-templates] Creating prompt template: ${id}`);
const template = createPromptTemplate(id, config, directory);
res.json({ success: true, template });
} catch (error) {
console.error('[API:POST /api/config/prompt-templates/:id] Failed:', error);
if (error.message?.includes('already exists')) {
return res.status(409).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to create prompt template' });
}
});
app.patch('/api/config/prompt-templates/:id', async (req, res) => {
try {
const id = req.params.id;
const updates = req.body;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
console.log(`[API:PATCH /api/config/prompt-templates] Updating prompt template: ${id}`);
const template = updatePromptTemplate(id, updates, directory);
res.json({ success: true, template });
} catch (error) {
console.error('[API:PATCH /api/config/prompt-templates/:id] Failed:', error);
if (error.message?.includes('not found')) {
return res.status(404).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to update prompt template' });
}
});
app.delete('/api/config/prompt-templates/:id', async (req, res) => {
try {
const id = req.params.id;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
console.log(`[API:DELETE /api/config/prompt-templates] Deleting prompt template: ${id}`);
deletePromptTemplate(id, directory);
res.json({ success: true });
} catch (error) {
console.error('[API:DELETE /api/config/prompt-templates/:id] Failed:', error);
if (error.message?.includes('not found')) {
return res.status(404).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to delete prompt template' });
}
});
};
@@ -123,6 +123,11 @@ export const createFeatureRoutesRuntime = (dependencies) => {
createMcpConfig,
updateMcpConfig,
deleteMcpConfig,
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
} = await import('./index.js');
registerConfigEntityRoutes(app, {
@@ -144,6 +149,11 @@ export const createFeatureRoutesRuntime = (dependencies) => {
createMcpConfig,
updateMcpConfig,
deleteMcpConfig,
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
});
const {
@@ -64,3 +64,12 @@ export {
updateMcpConfig,
deleteMcpConfig,
} from './mcp.js';
export {
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
slugify as slugifyPromptTemplate,
} from './prompt-templates.js';
@@ -0,0 +1,159 @@
import {
readConfigLayers,
writeConfig,
getJsonWriteTarget,
CONFIG_FILE,
} from './shared.js';
const SECTION_KEY = 'promptTemplates';
const DEFAULT_TEMPLATES = {
simple: {
name: 'Simple',
body: 'Implement this task using the simplest possible approach. Prefer readability and straightforward solutions over clever abstractions. Keep the code easy to understand and maintain.',
isDefault: true,
},
fast: {
name: 'Fast',
body: 'Implement this task as quickly as possible. Optimize for speed of development. Use the most direct path to a working solution. Favor existing libraries and proven patterns.',
isDefault: true,
},
'memory-efficient': {
name: 'Memory Efficient',
body: 'Implement this task with memory efficiency in mind. Minimize memory allocations, use streaming where possible, avoid holding large data structures in memory, and prefer lazy evaluation.',
isDefault: true,
},
'cpu-efficient': {
name: 'CPU Efficient',
body: 'Implement this task with CPU efficiency in mind. Optimize algorithms, minimize unnecessary computations, use efficient data structures, and avoid redundant work.',
isDefault: true,
},
'tests-first': {
name: 'Tests First',
body: 'Implement this task using a test-driven approach. Write tests first, then implement the minimum code to pass them. Ensure comprehensive test coverage including edge cases.',
isDefault: true,
},
'spec-first': {
name: 'Spec First',
body: 'Implement this task by first creating a detailed specification, then implementing according to the spec. Start by documenting the requirements, interfaces, and expected behavior before writing any implementation code.',
isDefault: true,
},
};
function slugify(name) {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.substring(0, 60);
}
function ensureDefaults(templates) {
if (!templates || typeof templates !== 'object') {
return { ...DEFAULT_TEMPLATES };
}
let changed = false;
const result = { ...templates };
for (const [id, template] of Object.entries(DEFAULT_TEMPLATES)) {
if (!(id in result)) {
result[id] = { ...template };
changed = true;
}
}
return changed ? result : templates;
}
function readTemplatesFromConfig(workingDirectory) {
const layers = readConfigLayers(workingDirectory);
const merged = layers.mergedConfig || {};
const raw = merged[SECTION_KEY];
if (!raw || typeof raw !== 'object') {
return ensureDefaults(null);
}
return ensureDefaults(raw);
}
function writeTemplatesToConfig(templates, workingDirectory) {
const layers = readConfigLayers(workingDirectory);
const target = getJsonWriteTarget(layers, 'user');
const config = { ...target.config };
config[SECTION_KEY] = templates;
writeConfig(config, target.path || CONFIG_FILE);
}
export function listPromptTemplates(workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
return Object.entries(templates).map(([id, value]) => ({
id,
name: value.name || id,
body: value.body || '',
isDefault: value.isDefault === true,
}));
}
export function getPromptTemplate(id, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
const entry = templates[id];
if (!entry) {
return null;
}
return {
id,
name: entry.name || id,
body: entry.body || '',
isDefault: entry.isDefault === true,
};
}
export function createPromptTemplate(id, config, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
if (templates[id]) {
throw new Error(`Prompt template "${id}" already exists`);
}
templates[id] = {
name: config.name || id,
body: config.body || '',
isDefault: false,
};
writeTemplatesToConfig(templates, workingDirectory);
return getPromptTemplate(id, workingDirectory);
}
export function updatePromptTemplate(id, updates, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
const existing = templates[id];
if (!existing) {
throw new Error(`Prompt template "${id}" not found`);
}
templates[id] = {
...existing,
...(updates.name !== undefined ? { name: updates.name } : {}),
...(updates.body !== undefined ? { body: updates.body } : {}),
};
writeTemplatesToConfig(templates, workingDirectory);
return getPromptTemplate(id, workingDirectory);
}
export function deletePromptTemplate(id, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
if (!templates[id]) {
throw new Error(`Prompt template "${id}" not found`);
}
delete templates[id];
writeTemplatesToConfig(templates, workingDirectory);
}
export { slugify };