feat: instant draft-first worktree creation and multi-run launcher redesign (#741)
## Summary - **Instant worktree creation from chat draft**: selecting "+ New worktree" in the draft branch selector immediately creates a session draft and bootstraps the worktree in the background — no modal interruption - **Redesigned multi-run launcher**: compact 2-column grid layout in a right-sized dialog with scroll shadow, sticky footer, tooltips replacing verbose descriptions, and project icons in the selector - **Branch selector aligned across surfaces**: multi-run and agent manager branch pickers now use the shared git store and match NewWorktreeDialog behavior (same default resolution cascade, no synthetic HEAD option, all branches shown) - **Opaque model multi-select dropdown**: fixes text bleed-through on translucent backgrounds by compositing `--surface-elevated` over `--surface-background` - **"+ New" inline button in sidebar worktree headers** for faster worktree creation ## Why Worktree creation was behind modal flow that interrupted the user's train of thought. The draft-first approach lets users start typing immediately while the worktree bootstraps. The multi-run launcher had an oversized form layout with redundant explanations, and its branch picker behaved differently from the main worktree dialog - causing confusion about which branches were available and what the default was.
This commit is contained in:
committed by
GitHub
parent
c66d480782
commit
53c2a0d919
@@ -63,6 +63,7 @@ import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
||||
import { useGitBranches, useGitStore } from '@/stores/useGitStore';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import { createWorktreeDraft } from '@/lib/worktreeSessionCreator';
|
||||
import { usePermissionStore } from '@/stores/permissionStore';
|
||||
|
||||
const MAX_VISIBLE_TEXTAREA_LINES = 8;
|
||||
@@ -2375,10 +2376,22 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
}, [availableWorktreesByProject, projectRootBranchOption?.value, selectedDraftProject, selectedDraftProjectPath]);
|
||||
|
||||
const selectedDraftDirectory = React.useMemo(
|
||||
() => normalizePath(newSessionDraft?.directoryOverride ?? null) ?? selectedDraftProjectPath,
|
||||
[newSessionDraft?.directoryOverride, selectedDraftProjectPath],
|
||||
() => normalizePath(newSessionDraft?.bootstrapPendingDirectory ?? null)
|
||||
?? normalizePath(newSessionDraft?.directoryOverride ?? null)
|
||||
?? selectedDraftProjectPath,
|
||||
[newSessionDraft?.bootstrapPendingDirectory, newSessionDraft?.directoryOverride, selectedDraftProjectPath],
|
||||
);
|
||||
|
||||
const shouldKeepMissingSelectedDraftDirectory = React.useMemo(() => {
|
||||
const pendingDirectory = normalizePath(newSessionDraft?.bootstrapPendingDirectory ?? null);
|
||||
return Boolean(
|
||||
newSessionDraft?.preserveDirectoryOverride
|
||||
||
|
||||
newSessionDraft?.pendingWorktreeRequestId
|
||||
|| (pendingDirectory && pendingDirectory === selectedDraftDirectory)
|
||||
);
|
||||
}, [newSessionDraft?.bootstrapPendingDirectory, newSessionDraft?.pendingWorktreeRequestId, newSessionDraft?.preserveDirectoryOverride, selectedDraftDirectory]);
|
||||
|
||||
const draftBranchItems = React.useMemo(() => {
|
||||
const baseItems: Array<{ value: string; label: string }> = [];
|
||||
if (projectRootBranchOption) {
|
||||
@@ -2392,11 +2405,14 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
if (baseItems.some((option) => option.value === selectedDraftDirectory)) {
|
||||
return baseItems;
|
||||
}
|
||||
if (!shouldKeepMissingSelectedDraftDirectory) {
|
||||
return baseItems;
|
||||
}
|
||||
return [
|
||||
...baseItems,
|
||||
{ value: selectedDraftDirectory, label: formatDirectoryName(selectedDraftDirectory) },
|
||||
];
|
||||
}, [projectRootBranchOption, selectedDraftDirectory, worktreeBranchOptions]);
|
||||
}, [projectRootBranchOption, selectedDraftDirectory, shouldKeepMissingSelectedDraftDirectory, worktreeBranchOptions]);
|
||||
|
||||
const selectedDraftBranchLabel = React.useMemo(() => {
|
||||
const selectedValue = selectedDraftDirectory ?? draftBranchItems[0]?.value ?? null;
|
||||
@@ -2416,6 +2432,16 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
return worktreeBranchOptions.some((option) => option.value === selectedDraftDirectory);
|
||||
}, [projectRootBranchOption?.value, selectedDraftDirectory, worktreeBranchOptions]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!newSessionDraft?.open || !newSessionDraft?.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
if (!selectedDraftDirectory || !selectedDraftBranchIsKnown) {
|
||||
return;
|
||||
}
|
||||
useSessionStore.getState().setDraftPreserveDirectoryOverride(false);
|
||||
}, [newSessionDraft?.open, newSessionDraft?.preserveDirectoryOverride, selectedDraftBranchIsKnown, selectedDraftDirectory]);
|
||||
|
||||
const shouldShowDraftBranchSelector = React.useMemo(() => {
|
||||
if (isDiscoveringDraftBranches) {
|
||||
return false;
|
||||
@@ -2427,6 +2453,10 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
}, [isDiscoveringDraftBranches, projectRootBranchOption, worktreeBranchOptions.length]);
|
||||
|
||||
const handleDraftProjectChange = React.useCallback((projectId: string) => {
|
||||
const draft = useSessionStore.getState().newSessionDraft;
|
||||
if (draft?.pendingWorktreeRequestId || draft?.bootstrapPendingDirectory || draft?.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
const project = projects.find((entry) => entry.id === projectId);
|
||||
if (!project) {
|
||||
return;
|
||||
@@ -2437,17 +2467,21 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
setNewSessionDraftTarget({
|
||||
projectId,
|
||||
directoryOverride: project.path,
|
||||
});
|
||||
}, { force: true });
|
||||
}, [activeProjectId, projects, setActiveProjectIdOnly, setNewSessionDraftTarget]);
|
||||
|
||||
const handleDraftDirectoryChange = React.useCallback((directory: string) => {
|
||||
const draft = useSessionStore.getState().newSessionDraft;
|
||||
if (draft?.pendingWorktreeRequestId || draft?.bootstrapPendingDirectory || draft?.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
if (!selectedDraftProject) {
|
||||
return;
|
||||
}
|
||||
setNewSessionDraftTarget({
|
||||
projectId: selectedDraftProject.id,
|
||||
directoryOverride: directory,
|
||||
});
|
||||
}, { force: true });
|
||||
}, [selectedDraftProject, setNewSessionDraftTarget]);
|
||||
|
||||
const renderProjectLabelWithIcon = React.useCallback((project: {
|
||||
@@ -2492,6 +2526,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
if (!showDraftTargetSelectors || !selectedDraftProject || !selectedDraftDirectory) {
|
||||
return;
|
||||
}
|
||||
if (newSessionDraft?.pendingWorktreeRequestId || newSessionDraft?.bootstrapPendingDirectory || newSessionDraft?.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
const valid = draftBranchItems.some((option) => option.value === selectedDraftDirectory);
|
||||
if (valid) {
|
||||
return;
|
||||
@@ -2500,7 +2537,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
projectId: selectedDraftProject.id,
|
||||
directoryOverride: selectedDraftProject.path,
|
||||
});
|
||||
}, [draftBranchItems, selectedDraftDirectory, selectedDraftProject, setNewSessionDraftTarget, showDraftTargetSelectors]);
|
||||
}, [draftBranchItems, newSessionDraft?.bootstrapPendingDirectory, newSessionDraft?.pendingWorktreeRequestId, newSessionDraft?.preserveDirectoryOverride, selectedDraftDirectory, selectedDraftProject, setNewSessionDraftTarget, showDraftTargetSelectors]);
|
||||
|
||||
const footerPaddingClass = isMobile ? 'px-1.5 py-1.5' : (isVSCode ? 'px-1.5 py-1' : 'px-2.5 py-1.5');
|
||||
const buttonSizeClass = isMobile ? 'h-8 w-8' : (isVSCode ? 'h-5 w-5' : 'h-6 w-6');
|
||||
@@ -2986,19 +3023,25 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
) : null}
|
||||
{worktreeBranchOptions.length > 0 ? (
|
||||
<>
|
||||
{projectRootBranchOption ? <SelectSeparator /> : null}
|
||||
<SelectGroup>
|
||||
<SelectLabel>Worktrees</SelectLabel>
|
||||
{worktreeBranchOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value} className="max-w-[24rem] truncate">
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</>
|
||||
) : null}
|
||||
{projectRootBranchOption ? <SelectSeparator /> : null}
|
||||
<SelectGroup>
|
||||
<div className="flex items-center justify-between px-2 py-1.5">
|
||||
<span className="text-muted-foreground typography-meta">Worktrees</span>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground typography-meta hover:text-foreground cursor-pointer"
|
||||
onPointerDown={(e) => { e.stopPropagation(); }}
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); void createWorktreeDraft(); }}
|
||||
>
|
||||
+ New
|
||||
</button>
|
||||
</div>
|
||||
{worktreeBranchOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value} className="max-w-[24rem] truncate">
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
{selectedDraftDirectory && !selectedDraftBranchIsKnown ? (
|
||||
<SelectItem value={selectedDraftDirectory} className="max-w-[24rem] truncate">
|
||||
{selectedDraftBranchLabel}
|
||||
|
||||
@@ -347,13 +347,13 @@ export const MessageFilesDisplay = memo(({ files, onShowPopup, compact = false }
|
||||
return filename || path;
|
||||
};
|
||||
|
||||
const resolveDisplayName = (file: FilePart): string => {
|
||||
const resolveDisplayName = React.useCallback((file: FilePart): string => {
|
||||
const isGitHubLink = getGitHubLinkKind(file) !== null;
|
||||
if (isGitHubLink && typeof file.filename === 'string' && file.filename.trim().length > 0) {
|
||||
return file.filename.trim();
|
||||
}
|
||||
return extractFilename(file.filename || file.url);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const formatFileSize = (bytes?: number) => {
|
||||
if (!bytes || !Number.isFinite(bytes) || bytes <= 0) return '';
|
||||
@@ -377,7 +377,7 @@ export const MessageFilesDisplay = memo(({ files, onShowPopup, compact = false }
|
||||
size: file.size,
|
||||
}];
|
||||
}),
|
||||
[imageFiles]
|
||||
[imageFiles, resolveDisplayName]
|
||||
);
|
||||
|
||||
const handleImageClick = React.useCallback((index: number) => {
|
||||
|
||||
@@ -592,7 +592,7 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
if (!state.newSessionDraft?.open) {
|
||||
return '';
|
||||
}
|
||||
return normalize(state.newSessionDraft.directoryOverride ?? '');
|
||||
return normalize(state.newSessionDraft.bootstrapPendingDirectory ?? state.newSessionDraft.directoryOverride ?? '');
|
||||
});
|
||||
|
||||
const openDirectory = React.useMemo(() => {
|
||||
|
||||
@@ -23,7 +23,7 @@ import { useEffectiveDirectory } from '@/hooks/useEffectiveDirectory';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { isDesktopShell } from '@/lib/desktop';
|
||||
|
||||
import { ChatView, PlanView, GitView, DiffView, TerminalView, FilesView, SettingsView, SettingsWindow } from '@/components/views';
|
||||
import { ChatView, PlanView, GitView, DiffView, TerminalView, FilesView, SettingsView, SettingsWindow, MultiRunWindow } from '@/components/views';
|
||||
|
||||
// Mobile drawer width as screen percentage
|
||||
const MOBILE_DRAWER_WIDTH_PERCENT = 85;
|
||||
@@ -645,7 +645,7 @@ export const MainLayout: React.FC = () => {
|
||||
setRightSidebarOpen,
|
||||
}}>
|
||||
{/* Mobile: header + drawer mode */}
|
||||
{!(isSettingsDialogOpen || isMultiRunLauncherOpen) && <Header
|
||||
{!isSettingsDialogOpen && <Header
|
||||
onToggleLeftDrawer={() => {
|
||||
if (isRightSidebarOpen) {
|
||||
setRightSidebarOpen(false);
|
||||
@@ -779,7 +779,7 @@ export const MainLayout: React.FC = () => {
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-1 overflow-hidden relative',
|
||||
(isSettingsDialogOpen || isMultiRunLauncherOpen) && 'hidden'
|
||||
isSettingsDialogOpen && 'hidden'
|
||||
)}
|
||||
>
|
||||
<main className="w-full h-full overflow-hidden bg-background relative">
|
||||
@@ -791,25 +791,20 @@ export const MainLayout: React.FC = () => {
|
||||
<ErrorBoundary>{secondaryView}</ErrorBoundary>
|
||||
</div>
|
||||
)}
|
||||
{isMultiRunLauncherOpen && (
|
||||
<div className="absolute inset-0 z-10 bg-background">
|
||||
<ErrorBoundary>
|
||||
<MultiRunLauncher
|
||||
initialPrompt={multiRunLauncherPrefillPrompt}
|
||||
onCreated={() => setMultiRunLauncherOpen(false)}
|
||||
onCancel={() => setMultiRunLauncherOpen(false)}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* Mobile multi-run launcher: full screen */}
|
||||
{isMultiRunLauncherOpen && (
|
||||
<div
|
||||
className="absolute inset-0 z-10 bg-background"
|
||||
style={{ paddingTop: 'var(--oc-safe-area-top, 0px)' }}
|
||||
>
|
||||
<ErrorBoundary>
|
||||
<MultiRunLauncher
|
||||
initialPrompt={multiRunLauncherPrefillPrompt}
|
||||
onCreated={() => setMultiRunLauncherOpen(false)}
|
||||
onCancel={() => setMultiRunLauncherOpen(false)}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile settings: full screen */}
|
||||
{isSettingsDialogOpen && (
|
||||
<div
|
||||
@@ -828,8 +823,7 @@ export const MainLayout: React.FC = () => {
|
||||
'absolute inset-0 flex overflow-hidden',
|
||||
isDesktopShellRuntime
|
||||
? 'bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]'
|
||||
: 'bg-sidebar',
|
||||
isMultiRunLauncherOpen && 'invisible'
|
||||
: 'bg-sidebar'
|
||||
)}>
|
||||
{isSidebarOpen ? (
|
||||
<>
|
||||
@@ -951,18 +945,6 @@ export const MainLayout: React.FC = () => {
|
||||
</RightSidebar>
|
||||
</div>
|
||||
|
||||
{/* Multi-Run Launcher: replaces tabs content only */}
|
||||
{isMultiRunLauncherOpen && (
|
||||
<div className={cn('absolute inset-0 z-10 bg-background')}>
|
||||
<ErrorBoundary>
|
||||
<MultiRunLauncher
|
||||
initialPrompt={multiRunLauncherPrefillPrompt}
|
||||
onCreated={() => setMultiRunLauncherOpen(false)}
|
||||
onCancel={() => setMultiRunLauncherOpen(false)}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Desktop settings: windowed dialog with blur */}
|
||||
@@ -970,6 +952,11 @@ export const MainLayout: React.FC = () => {
|
||||
open={isSettingsDialogOpen}
|
||||
onOpenChange={setSettingsDialogOpen}
|
||||
/>
|
||||
<MultiRunWindow
|
||||
open={isMultiRunLauncherOpen}
|
||||
onOpenChange={setMultiRunLauncherOpen}
|
||||
initialPrompt={multiRunLauncherPrefillPrompt}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
|
||||
export interface AgentSelectorProps {
|
||||
@@ -85,7 +86,14 @@ export const AgentSelector: React.FC<AgentSelectorProps> = ({
|
||||
<SelectTrigger
|
||||
id={id}
|
||||
size="lg"
|
||||
className={className ?? 'max-w-full typography-meta text-foreground'}
|
||||
className={cn(
|
||||
'max-w-full typography-meta text-foreground !border-border/80 !bg-[var(--surface-subtle)]/95 !backdrop-blur-sm hover:!bg-[var(--interactive-hover)]/70 data-[state=open]:!bg-[var(--interactive-active)]/70',
|
||||
className,
|
||||
)}
|
||||
style={{
|
||||
backdropFilter: 'blur(10px)',
|
||||
WebkitBackdropFilter: 'blur(10px)',
|
||||
}}
|
||||
>
|
||||
<SelectValue placeholder="Select an agent" />
|
||||
</SelectTrigger>
|
||||
|
||||
@@ -9,8 +9,12 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { checkIsGitRepository, getGitBranches } from '@/lib/gitApi';
|
||||
import { resolveRootTrackingRemote } from '@/lib/worktrees/worktreeCreate';
|
||||
import { useGitStore, useGitBranches } from '@/stores/useGitStore';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
|
||||
|
||||
/** localStorage key matching NewWorktreeDialog */
|
||||
const LAST_SOURCE_BRANCH_KEY = 'oc:lastWorktreeSourceBranch';
|
||||
|
||||
export type WorktreeBaseOption = {
|
||||
value: string;
|
||||
@@ -34,125 +38,60 @@ export interface BranchSelectorProps {
|
||||
}
|
||||
|
||||
export interface BranchSelectorState {
|
||||
branches: WorktreeBaseOption[];
|
||||
localBranches: string[];
|
||||
remoteBranches: string[];
|
||||
isLoading: boolean;
|
||||
isGitRepository: boolean | null;
|
||||
}
|
||||
|
||||
const parseTrackingRemote = (tracking: string | null | undefined): string | null => {
|
||||
const value = String(tracking || '').trim().replace(/^remotes\//, '');
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
const slashIndex = value.indexOf('/');
|
||||
if (slashIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
return value.slice(0, slashIndex);
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to load available git branches for a directory.
|
||||
* Uses the shared useGitStore (same as NewWorktreeDialog).
|
||||
*/
|
||||
// eslint-disable-next-line react-refresh/only-export-components -- Hook is tightly coupled with BranchSelector
|
||||
export function useBranchOptions(directory: string | null): BranchSelectorState {
|
||||
const [branches, setBranches] = React.useState<WorktreeBaseOption[]>([
|
||||
{ value: 'HEAD', label: 'Current (HEAD)', group: 'special' },
|
||||
]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [isGitRepository, setIsGitRepository] = React.useState<boolean | null>(null);
|
||||
const { git } = useRuntimeAPIs();
|
||||
const branches = useGitBranches(directory);
|
||||
const isLoading = useGitStore((state) => state.isLoadingBranches);
|
||||
const fetchBranches = useGitStore((state) => state.fetchBranches);
|
||||
|
||||
// Fetch branches if not cached
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!directory || !git) return;
|
||||
if (branches?.all) return; // Already cached
|
||||
void fetchBranches(directory, git);
|
||||
}, [directory, git, branches?.all, fetchBranches]);
|
||||
|
||||
if (!directory) {
|
||||
setIsGitRepository(null);
|
||||
setIsLoading(false);
|
||||
setBranches([{ value: 'HEAD', label: 'Current (HEAD)', group: 'special' }]);
|
||||
return;
|
||||
}
|
||||
// Compute local and remote branch lists (same as NewWorktreeDialog)
|
||||
const localBranches = React.useMemo(() => {
|
||||
if (!branches?.all) return [];
|
||||
return branches.all
|
||||
.filter((branchName: string) => !branchName.startsWith('remotes/'))
|
||||
.sort();
|
||||
}, [branches]);
|
||||
|
||||
setIsLoading(true);
|
||||
setIsGitRepository(null);
|
||||
const remoteBranches = React.useMemo(() => {
|
||||
if (!branches?.all) return [];
|
||||
return branches.all
|
||||
.filter((branchName: string) => branchName.startsWith('remotes/'))
|
||||
.map((branchName: string) => branchName.replace(/^remotes\//, ''))
|
||||
.sort();
|
||||
}, [branches]);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const isGit = await checkIsGitRepository(directory);
|
||||
if (cancelled) return;
|
||||
// isGitRepository: true if we got branches, false if fetch returned empty, null if not yet loaded
|
||||
const isGitRepository = React.useMemo<boolean | null>(() => {
|
||||
if (!directory) return null;
|
||||
if (isLoading) return null;
|
||||
if (!branches) return null;
|
||||
return Boolean(branches.all);
|
||||
}, [directory, isLoading, branches]);
|
||||
|
||||
setIsGitRepository(isGit);
|
||||
|
||||
if (!isGit) {
|
||||
setBranches([{ value: 'HEAD', label: 'Current (HEAD)', group: 'special' }]);
|
||||
return;
|
||||
}
|
||||
|
||||
const branchData = await getGitBranches(directory).catch(() => null);
|
||||
if (cancelled) return;
|
||||
|
||||
const rootTrackingRemote = await resolveRootTrackingRemote(directory).catch(() => null);
|
||||
if (cancelled) return;
|
||||
|
||||
const worktreeBaseOptions: WorktreeBaseOption[] = [];
|
||||
const headLabel = branchData?.current ? `Current (HEAD: ${branchData.current})` : 'Current (HEAD)';
|
||||
worktreeBaseOptions.push({ value: 'HEAD', label: headLabel, group: 'special' });
|
||||
|
||||
if (branchData) {
|
||||
const localBranches = branchData.all
|
||||
.filter((branchName) => !branchName.startsWith('remotes/'))
|
||||
.filter((branchName) => {
|
||||
if (!rootTrackingRemote) {
|
||||
return true;
|
||||
}
|
||||
const tracking = branchData.branches?.[branchName]?.tracking;
|
||||
const trackingRemote = parseTrackingRemote(tracking);
|
||||
if (!trackingRemote) {
|
||||
return true;
|
||||
}
|
||||
return trackingRemote === rootTrackingRemote;
|
||||
})
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
localBranches.forEach((branchName) => {
|
||||
worktreeBaseOptions.push({ value: branchName, label: branchName, group: 'local' });
|
||||
});
|
||||
|
||||
const remoteBranches = branchData.all
|
||||
.filter((branchName) => branchName.startsWith('remotes/'))
|
||||
.map((branchName) => branchName.replace(/^remotes\//, ''))
|
||||
.filter((branchName) => {
|
||||
if (!rootTrackingRemote) {
|
||||
return true;
|
||||
}
|
||||
const slashIndex = branchName.indexOf('/');
|
||||
if (slashIndex <= 0) {
|
||||
return false;
|
||||
}
|
||||
return branchName.slice(0, slashIndex) === rootTrackingRemote;
|
||||
})
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
remoteBranches.forEach((branchName) => {
|
||||
worktreeBaseOptions.push({ value: branchName, label: branchName, group: 'remote' });
|
||||
});
|
||||
}
|
||||
|
||||
setBranches(worktreeBaseOptions);
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [directory]);
|
||||
|
||||
return { branches, isLoading, isGitRepository };
|
||||
return { localBranches, remoteBranches, isLoading, isGitRepository };
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch selector dropdown for selecting a base branch for worktree creation.
|
||||
* Branch selector dropdown for selecting a source branch for worktree creation.
|
||||
* Matches the NewWorktreeDialog source branch selector exactly.
|
||||
*/
|
||||
export const BranchSelector: React.FC<BranchSelectorProps> = ({
|
||||
directory,
|
||||
@@ -162,23 +101,46 @@ export const BranchSelector: React.FC<BranchSelectorProps> = ({
|
||||
disabled,
|
||||
id,
|
||||
}) => {
|
||||
const { branches, isLoading, isGitRepository } = useBranchOptions(directory);
|
||||
const selectedLabel = React.useMemo(() => {
|
||||
return branches.find((option) => option.value === value)?.label ?? null;
|
||||
}, [branches, value]);
|
||||
const { localBranches, remoteBranches, isLoading, isGitRepository } = useBranchOptions(directory);
|
||||
const allBranches = React.useMemo(
|
||||
() => [...localBranches, ...remoteBranches.map(b => `remotes/${b}`)],
|
||||
[localBranches, remoteBranches],
|
||||
);
|
||||
|
||||
// Update value if it's no longer valid
|
||||
// Resolve default source branch (same priority as NewWorktreeDialog)
|
||||
React.useEffect(() => {
|
||||
const isValid = branches.some((option) => option.value === value);
|
||||
if (!isValid && branches.length > 0) {
|
||||
onChange('HEAD');
|
||||
}
|
||||
}, [branches, value, onChange]);
|
||||
if (disabled || isLoading || allBranches.length === 0) return;
|
||||
// If current value is valid, keep it
|
||||
if (value && allBranches.includes(value)) return;
|
||||
|
||||
const resolve = async () => {
|
||||
try {
|
||||
const rootBranch = directory ? await getRootBranch(directory).catch(() => null) : null;
|
||||
const saved = localStorage.getItem(LAST_SOURCE_BRANCH_KEY);
|
||||
|
||||
if (saved && allBranches.includes(saved)) {
|
||||
onChange(saved);
|
||||
} else if (rootBranch && allBranches.includes(rootBranch)) {
|
||||
onChange(rootBranch);
|
||||
} else if (allBranches.includes('main')) {
|
||||
onChange('main');
|
||||
} else if (allBranches.includes('master')) {
|
||||
onChange('master');
|
||||
} else if (allBranches[0]) {
|
||||
onChange(allBranches[0]);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
void resolve();
|
||||
}, [allBranches, directory, disabled, isLoading, onChange, value]);
|
||||
|
||||
const isDisabled = disabled || !isGitRepository || isLoading;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={onChange}
|
||||
@@ -187,62 +149,51 @@ export const BranchSelector: React.FC<BranchSelectorProps> = ({
|
||||
<SelectTrigger
|
||||
id={id}
|
||||
size="lg"
|
||||
className={className ?? 'max-w-full typography-meta text-foreground'}
|
||||
className={className ?? 'w-fit typography-meta text-foreground'}
|
||||
>
|
||||
{selectedLabel ? (
|
||||
<SelectValue>{selectedLabel}</SelectValue>
|
||||
) : (
|
||||
<SelectValue placeholder={isLoading ? 'Loading branches…' : 'Select a branch'} />
|
||||
)}
|
||||
<SelectValue placeholder={isLoading ? 'Loading branches…' : 'Select source branch...'} />
|
||||
</SelectTrigger>
|
||||
<SelectContent fitContent>
|
||||
<SelectGroup>
|
||||
<SelectLabel>Default</SelectLabel>
|
||||
{branches
|
||||
.filter((option) => option.group === 'special')
|
||||
.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value} className="w-auto whitespace-nowrap">
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
|
||||
{branches.some((option) => option.group === 'local') ? (
|
||||
<SelectContent className="max-h-[280px] max-w-[320px]">
|
||||
{isLoading ? (
|
||||
<div className="px-2 py-4 text-center typography-meta text-muted-foreground">
|
||||
Loading branches...
|
||||
</div>
|
||||
) : localBranches.length === 0 && remoteBranches.length === 0 ? (
|
||||
<div className="px-2 py-4 text-center typography-meta text-muted-foreground">
|
||||
No branches found
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<SelectSeparator />
|
||||
<SelectGroup>
|
||||
<SelectLabel>Local branches</SelectLabel>
|
||||
{branches
|
||||
.filter((option) => option.group === 'local')
|
||||
.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value} className="w-auto whitespace-nowrap">
|
||||
{option.label}
|
||||
{localBranches.length > 0 && (
|
||||
<SelectGroup>
|
||||
<SelectLabel className="font-semibold text-foreground">Local branches</SelectLabel>
|
||||
{localBranches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch} className="whitespace-normal break-all">
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{branches.some((option) => option.group === 'remote') ? (
|
||||
<>
|
||||
<SelectSeparator />
|
||||
<SelectGroup>
|
||||
<SelectLabel>Remote branches</SelectLabel>
|
||||
{branches
|
||||
.filter((option) => option.group === 'remote')
|
||||
.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value} className="w-auto whitespace-nowrap">
|
||||
{option.label}
|
||||
</SelectGroup>
|
||||
)}
|
||||
{localBranches.length > 0 && remoteBranches.length > 0 && (
|
||||
<SelectSeparator />
|
||||
)}
|
||||
{remoteBranches.length > 0 && (
|
||||
<SelectGroup>
|
||||
<SelectLabel className="font-semibold text-foreground">Remote branches</SelectLabel>
|
||||
{remoteBranches.map((branch) => (
|
||||
<SelectItem key={`remotes/${branch}`} value={`remotes/${branch}`} className="whitespace-normal break-all">
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectGroup>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
|
||||
{isGitRepository === false && (
|
||||
<p className="typography-micro text-muted-foreground/70">Not in a git repository.</p>
|
||||
<p className="typography-micro text-muted-foreground/70 mt-2">Not in a git repository.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -97,6 +97,8 @@ export interface ModelMultiSelectProps {
|
||||
showChips?: boolean;
|
||||
/** Maximum models allowed */
|
||||
maxModels?: number;
|
||||
/** Optional className for add model trigger button */
|
||||
addButtonClassName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,6 +113,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
addButtonLabel = 'Add model',
|
||||
showChips = true,
|
||||
maxModels,
|
||||
addButtonClassName,
|
||||
}) => {
|
||||
const { providers, modelsMetadata } = useConfigStore();
|
||||
const { favoriteModelsList, recentModelsList } = useModelLists();
|
||||
@@ -201,15 +204,29 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
|
||||
const hasResults = filteredFavorites.length > 0 || filteredRecents.length > 0 || filteredProviders.length > 0;
|
||||
|
||||
// Calculate available height when dropdown opens
|
||||
// Calculate available height: space above trigger within visible area
|
||||
React.useEffect(() => {
|
||||
if (isOpen && triggerRef.current) {
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
// Space above trigger minus padding from top edge
|
||||
const spaceAbove = rect.top - 100;
|
||||
// Cap at 400px max, minimum 150px
|
||||
setAvailableHeight(Math.max(150, Math.min(400, spaceAbove)));
|
||||
if (!isOpen || !triggerRef.current) return;
|
||||
|
||||
const triggerRect = triggerRef.current.getBoundingClientRect();
|
||||
|
||||
// Find the nearest dialog or overflow ancestor to constrain within
|
||||
let container: HTMLElement | null = triggerRef.current.parentElement;
|
||||
while (container) {
|
||||
if (container.getAttribute('role') === 'dialog' || container.hasAttribute('data-scroll-shadow')) {
|
||||
break;
|
||||
}
|
||||
const style = getComputedStyle(container);
|
||||
if (style.overflow === 'auto' || style.overflow === 'hidden' || style.overflowY === 'auto' || style.overflowY === 'hidden') {
|
||||
break;
|
||||
}
|
||||
container = container.parentElement;
|
||||
}
|
||||
|
||||
const topBound = container ? container.getBoundingClientRect().top : 0;
|
||||
const spaceAbove = triggerRect.top - topBound - 16;
|
||||
// Cap: min 150, max 300
|
||||
setAvailableHeight(Math.max(150, Math.min(300, spaceAbove)));
|
||||
}, [isOpen]);
|
||||
|
||||
// Focus search input when opened
|
||||
@@ -308,7 +325,15 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={CHIP_HEIGHT_CLASS}
|
||||
className={cn(
|
||||
CHIP_HEIGHT_CLASS,
|
||||
'!border-border/80 !bg-[var(--surface-subtle)]/95 !backdrop-blur-sm hover:!bg-[var(--interactive-hover)]/70',
|
||||
addButtonClassName,
|
||||
)}
|
||||
style={{
|
||||
backdropFilter: 'blur(10px)',
|
||||
WebkitBackdropFilter: 'blur(10px)',
|
||||
}}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
>
|
||||
<RiAddLine className="h-3.5 w-3.5 mr-1" />
|
||||
@@ -379,7 +404,12 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
let currentFlatIndex = 0;
|
||||
|
||||
return (
|
||||
<div style={{ backgroundColor: 'var(--surface-elevated)' }} className="absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden shadow-none w-[min(380px,calc(100vw-2rem))] flex flex-col">
|
||||
<div
|
||||
className="absolute bottom-full left-0 mb-1 z-50 w-[min(380px,calc(100vw-2rem))] max-w-[calc(100vw-2rem)] flex flex-col overflow-hidden rounded-xl border border-border/50 shadow-lg"
|
||||
style={{
|
||||
background: 'linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))',
|
||||
}}
|
||||
>
|
||||
{/* Search input */}
|
||||
<div className="p-2 border-b border-border/40">
|
||||
<div className="relative">
|
||||
@@ -411,10 +441,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
{/* Favorites Section */}
|
||||
{filteredFavorites.length > 0 && (
|
||||
<>
|
||||
<div
|
||||
style={{ backgroundColor: 'var(--surface-elevated)' }}
|
||||
className="typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30"
|
||||
>
|
||||
<div className="typography-micro font-semibold text-muted-foreground uppercase tracking-wider sticky top-0 z-10 -mx-1 flex items-center gap-2 border-b border-border/30 px-3 py-1.5 [background:linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))]">
|
||||
<RiStarFill className="h-4 w-4 text-primary" />
|
||||
Favorites
|
||||
</div>
|
||||
@@ -429,10 +456,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
{filteredRecents.length > 0 && (
|
||||
<>
|
||||
{filteredFavorites.length > 0 && <div className="h-px bg-border/40 my-1" />}
|
||||
<div
|
||||
style={{ backgroundColor: 'var(--surface-elevated)' }}
|
||||
className="typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30"
|
||||
>
|
||||
<div className="typography-micro font-semibold text-muted-foreground uppercase tracking-wider sticky top-0 z-10 -mx-1 flex items-center gap-2 border-b border-border/30 px-3 py-1.5 [background:linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))]">
|
||||
<RiTimeLine className="h-4 w-4" />
|
||||
Recent
|
||||
</div>
|
||||
@@ -452,7 +476,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
{filteredProviders.map((provider, index) => (
|
||||
<React.Fragment key={provider.id}>
|
||||
{index > 0 && <div className="h-px bg-border/40 my-1" />}
|
||||
<div style={{ backgroundColor: 'var(--surface-elevated)' }} className="typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30">
|
||||
<div className="typography-micro font-semibold text-muted-foreground uppercase tracking-wider sticky top-0 z-10 -mx-1 flex items-center gap-2 border-b border-border/30 px-3 py-1.5 [background:linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))]">
|
||||
<ProviderLogo
|
||||
providerId={provider.id}
|
||||
className="h-4 w-4 flex-shrink-0"
|
||||
@@ -513,7 +537,14 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
||||
onUpdate(index, { ...model, variant: nextVariant });
|
||||
}}
|
||||
>
|
||||
<SelectTrigger size="chip" className="px-2 gap-1.5 rounded-md bg-interactive-selection/20 border-border/30 hover:bg-interactive-hover/30 typography-meta font-medium text-foreground">
|
||||
<SelectTrigger
|
||||
size="chip"
|
||||
className="px-2 gap-1.5 rounded-md !border-border/80 !bg-[var(--surface-subtle)]/95 !backdrop-blur-sm hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground"
|
||||
style={{
|
||||
backdropFilter: 'blur(10px)',
|
||||
WebkitBackdropFilter: 'blur(10px)',
|
||||
}}
|
||||
>
|
||||
<RiBrainAi3Line
|
||||
className={cn(
|
||||
'h-3.5 w-3.5 flex-shrink-0',
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import React from 'react';
|
||||
import { RiAddLine, RiArrowDownSLine, RiAttachment2, RiCloseLine, RiFileImageLine, RiFileLine } from '@remixicon/react';
|
||||
import { RiAddLine, RiArrowDownSLine, RiAttachment2, RiCloseLine, RiFileImageLine, RiFileLine, RiFolderLine, RiInformationLine, RiTerminalLine } from '@remixicon/react';
|
||||
import { toast } from '@/components/ui';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { ScrollShadow } from '@/components/ui/ScrollShadow';
|
||||
import { cn, formatDirectoryName } from '@/lib/utils';
|
||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||
import { useMultiRunStore } from '@/stores/useMultiRunStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
@@ -18,6 +20,9 @@ import { ModelMultiSelect, generateInstanceId, type ModelSelectionWithId } from
|
||||
import { BranchSelector, useBranchOptions } from './BranchSelector';
|
||||
import { AgentSelector } from './AgentSelector';
|
||||
import { isDesktopShell } from '@/lib/desktop';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { PROJECT_ICON_MAP, PROJECT_COLOR_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
||||
import type { ProjectEntry } from '@/lib/api/types';
|
||||
|
||||
/** Max file size in bytes (10MB) */
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||
@@ -41,16 +46,49 @@ interface MultiRunLauncherProps {
|
||||
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 delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" tabIndex={-1} className="inline-flex items-center justify-center text-muted-foreground/50 hover:text-muted-foreground transition-colors">
|
||||
<RiInformationLine className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" className="max-w-[240px]">
|
||||
{children}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
/** Compact field label */
|
||||
const FieldLabel: React.FC<{
|
||||
htmlFor?: string;
|
||||
required?: boolean;
|
||||
children: React.ReactNode;
|
||||
info?: React.ReactNode;
|
||||
}> = ({ htmlFor, required, children, info }) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<label htmlFor={htmlFor} className="typography-meta font-medium text-foreground">
|
||||
{children}
|
||||
{required && <span className="text-destructive ml-0.5">*</span>}
|
||||
</label>
|
||||
{info && info}
|
||||
</div>
|
||||
);
|
||||
|
||||
/**
|
||||
* Launcher form for creating a new Multi-Run group.
|
||||
* Replaces the main content area (tabs) with a form.
|
||||
* Compact, centered card layout with adaptive grid.
|
||||
*/
|
||||
export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
initialPrompt,
|
||||
onCreated,
|
||||
onCancel,
|
||||
isWindowed = false,
|
||||
}) => {
|
||||
const [name, setName] = React.useState('');
|
||||
const [prompt, setPrompt] = React.useState(() => initialPrompt ?? '');
|
||||
@@ -64,6 +102,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
const currentDirectory = useDirectoryStore((state) => state.currentDirectory ?? null);
|
||||
const homeDirectory = useDirectoryStore((state) => state.homeDirectory ?? null);
|
||||
|
||||
const vscodeWorkspaceFolder = React.useMemo(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
@@ -75,13 +114,72 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
|
||||
// Get project directory for setup commands
|
||||
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
|
||||
const setActiveProjectIdOnly = useProjectsStore((state) => state.setActiveProjectIdOnly);
|
||||
const projects = useProjectsStore((state) => state.projects);
|
||||
const projectRef = React.useMemo<ProjectRef | null>(() => {
|
||||
const [selectedProjectId, setSelectedProjectId] = React.useState<string | null>(() => activeProjectId ?? null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (activeProjectId) {
|
||||
const project = projects.find((p) => p.id === activeProjectId);
|
||||
if (project?.path) {
|
||||
return { id: project.id, path: project.path };
|
||||
}
|
||||
setSelectedProjectId(activeProjectId);
|
||||
return;
|
||||
}
|
||||
if (!selectedProjectId && projects.length > 0) {
|
||||
setSelectedProjectId(projects[0].id);
|
||||
}
|
||||
}, [activeProjectId, projects, selectedProjectId]);
|
||||
|
||||
const selectedProject = React.useMemo(() => {
|
||||
if (!selectedProjectId) {
|
||||
return null;
|
||||
}
|
||||
return projects.find((project) => project.id === selectedProjectId) ?? null;
|
||||
}, [projects, selectedProjectId]);
|
||||
|
||||
const selectedProjectDirectory = selectedProject?.path ?? currentDirectory;
|
||||
|
||||
const handleProjectChange = React.useCallback((projectId: string) => {
|
||||
setSelectedProjectId(projectId);
|
||||
if (projectId !== activeProjectId) {
|
||||
setActiveProjectIdOnly(projectId);
|
||||
}
|
||||
}, [activeProjectId, setActiveProjectIdOnly]);
|
||||
|
||||
const { currentTheme } = useThemeSystem();
|
||||
|
||||
const renderProjectLabel = React.useCallback((project: ProjectEntry) => {
|
||||
const displayLabel = project.label?.trim() || formatDirectoryName(project.path, homeDirectory);
|
||||
const imageUrl = getProjectIconImageUrl(
|
||||
{ id: project.id, iconImage: project.iconImage ?? null },
|
||||
{
|
||||
themeVariant: currentTheme.metadata.variant,
|
||||
iconColor: currentTheme.colors.surface.foreground,
|
||||
},
|
||||
);
|
||||
const ProjectIcon = project.icon ? PROJECT_ICON_MAP[project.icon] : null;
|
||||
const iconColor = project.color ? PROJECT_COLOR_MAP[project.color] : undefined;
|
||||
|
||||
return (
|
||||
<span className="inline-flex min-w-0 items-center gap-1.5">
|
||||
{imageUrl ? (
|
||||
<span
|
||||
className="inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]"
|
||||
style={project.iconBackground ? { backgroundColor: project.iconBackground } : undefined}
|
||||
>
|
||||
<img src={imageUrl} alt="" className="h-full w-full object-contain" draggable={false} />
|
||||
</span>
|
||||
) : ProjectIcon ? (
|
||||
<ProjectIcon className="h-3.5 w-3.5 shrink-0" style={iconColor ? { color: iconColor } : undefined} />
|
||||
) : (
|
||||
<RiFolderLine className="h-3.5 w-3.5 shrink-0 text-muted-foreground/80" style={iconColor ? { color: iconColor } : undefined} />
|
||||
)}
|
||||
<span className="truncate">{displayLabel}</span>
|
||||
</span>
|
||||
);
|
||||
}, [homeDirectory, currentTheme.metadata.variant, currentTheme.colors.surface.foreground]);
|
||||
|
||||
const projectRef = React.useMemo<ProjectRef | null>(() => {
|
||||
if (selectedProject?.path) {
|
||||
return { id: selectedProject.id, path: selectedProject.path };
|
||||
}
|
||||
|
||||
const base = currentDirectory ?? vscodeWorkspaceFolder;
|
||||
@@ -90,7 +188,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
}
|
||||
|
||||
return { id: `path:${base}`, path: base };
|
||||
}, [activeProjectId, projects, currentDirectory, vscodeWorkspaceFolder]);
|
||||
}, [selectedProject, currentDirectory, vscodeWorkspaceFolder]);
|
||||
|
||||
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
@@ -193,8 +291,8 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
}, [onCancel]);
|
||||
|
||||
// Use the BranchSelector hook for branch state management
|
||||
const [worktreeBaseBranch, setWorktreeBaseBranch] = React.useState<string>('HEAD');
|
||||
const { isLoading: isLoadingWorktreeBaseBranches, isGitRepository } = useBranchOptions(currentDirectory);
|
||||
const [worktreeBaseBranch, setWorktreeBaseBranch] = React.useState<string>('');
|
||||
const { isLoading: isLoadingWorktreeBaseBranches, isGitRepository } = useBranchOptions(selectedProjectDirectory);
|
||||
|
||||
const createMultiRun = useMultiRunStore((state) => state.createMultiRun);
|
||||
const error = useMultiRunStore((state) => state.error);
|
||||
@@ -311,6 +409,10 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
clearError();
|
||||
|
||||
try {
|
||||
if (selectedProjectId && selectedProjectId !== activeProjectId) {
|
||||
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);
|
||||
@@ -350,254 +452,275 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
};
|
||||
|
||||
const isValid = Boolean(
|
||||
name.trim() && prompt.trim() && selectedModels.length >= 2 && isGitRepository && !isLoadingWorktreeBaseBranches
|
||||
name.trim() && prompt.trim() && selectedModels.length >= 2 && worktreeBaseBranch && isGitRepository && !isLoadingWorktreeBaseBranches
|
||||
);
|
||||
|
||||
const configuredSetupCount = setupCommands.filter(cmd => cmd.trim()).length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-background">
|
||||
{/* Header - same height as app header (h-12 = 48px) */}
|
||||
<header
|
||||
onMouseDown={handleDragStart}
|
||||
className={cn(
|
||||
'relative flex h-12 items-center justify-center border-b app-region-drag select-none',
|
||||
desktopHeaderPaddingClass,
|
||||
macosHeaderSizeClass,
|
||||
)}
|
||||
style={{ borderColor: 'var(--interactive-border)' }}
|
||||
>
|
||||
<h1 className="typography-ui-label font-medium">New Multi-Run</h1>
|
||||
{onCancel && (
|
||||
<div className="absolute right-0 flex items-center pr-3">
|
||||
<Tooltip delayDuration={500}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
aria-label="Close (Esc)"
|
||||
className="inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag"
|
||||
>
|
||||
<RiCloseLine className="h-5 w-5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Close (Esc)</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{/* Content with chat-column max-width */}
|
||||
<div className="flex-1 overflow-auto">
|
||||
<div className="chat-column py-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-6" data-keyboard-avoid="true">
|
||||
{/* Group name (required) */}
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="group-name" className="typography-ui-label font-medium text-foreground">
|
||||
Group name <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="group-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. feature-auth, bugfix-login"
|
||||
className="typography-body max-w-full sm:max-w-xs"
|
||||
required
|
||||
/>
|
||||
<p className="typography-micro text-muted-foreground">
|
||||
Used for worktree directory and branch names
|
||||
</p>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col h-full bg-background" data-keyboard-avoid="true">
|
||||
{!isWindowed ? (
|
||||
<header
|
||||
onMouseDown={handleDragStart}
|
||||
className={cn(
|
||||
'relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none',
|
||||
desktopHeaderPaddingClass,
|
||||
macosHeaderSizeClass,
|
||||
)}
|
||||
style={{ borderColor: 'var(--interactive-border)' }}
|
||||
>
|
||||
<h1 className="typography-ui-label font-medium">New Multi-Run</h1>
|
||||
{onCancel && (
|
||||
<div className="absolute right-0 flex items-center pr-3">
|
||||
<Tooltip delayDuration={500}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
aria-label="Close (Esc)"
|
||||
className="inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag"
|
||||
>
|
||||
<RiCloseLine className="h-5 w-5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Close (Esc)</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
) : null}
|
||||
|
||||
{/* Worktree creation */}
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<p className="typography-ui-label font-medium text-foreground">Worktrees</p>
|
||||
<p className="typography-micro text-muted-foreground">
|
||||
Create one worktree per model by creating a new branch from a base branch.
|
||||
</p>
|
||||
{/* 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>Project</FieldLabel>
|
||||
{projects.length > 0 ? (
|
||||
<Select
|
||||
value={selectedProjectId ?? undefined}
|
||||
onValueChange={handleProjectChange}
|
||||
>
|
||||
<SelectTrigger id="multirun-project" size="lg" className="w-fit max-w-full">
|
||||
{selectedProject ? (
|
||||
<SelectValue>{renderProjectLabel(selectedProject)}</SelectValue>
|
||||
) : (
|
||||
<SelectValue placeholder="Select project" />
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent fitContent>
|
||||
{projects.map((project) => (
|
||||
<SelectItem key={project.id} value={project.id} className="max-w-[24rem]">
|
||||
{renderProjectLabel(project)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<p className="typography-micro text-muted-foreground py-2">Add a project first.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
className="typography-meta font-medium text-foreground"
|
||||
{/* Group name */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<FieldLabel
|
||||
htmlFor="group-name"
|
||||
required
|
||||
info={<InfoTip>Used for worktree directory and branch names</InfoTip>}
|
||||
>
|
||||
Group name
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="group-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="feature-auth, bugfix-login"
|
||||
className="typography-meta w-full"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Base branch */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<FieldLabel
|
||||
htmlFor="multirun-worktree-base-branch"
|
||||
info={<InfoTip>New branch created from this base per model</InfoTip>}
|
||||
>
|
||||
Base branch
|
||||
</label>
|
||||
</FieldLabel>
|
||||
<BranchSelector
|
||||
directory={currentDirectory}
|
||||
directory={selectedProjectDirectory}
|
||||
value={worktreeBaseBranch}
|
||||
onChange={setWorktreeBaseBranch}
|
||||
id="multirun-worktree-base-branch"
|
||||
/>
|
||||
<p className="typography-micro text-muted-foreground">
|
||||
Creates new branches from{' '}
|
||||
<code className="font-mono text-xs text-muted-foreground">{worktreeBaseBranch || 'HEAD'}</code>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Setup commands collapsible */}
|
||||
<Collapsible open={isSetupCommandsOpen} onOpenChange={setIsSetupCommandsOpen}>
|
||||
<CollapsibleTrigger className="w-full flex items-center justify-between py-1 hover:bg-[var(--interactive-hover)] rounded-md px-1 -mx-1 transition-colors">
|
||||
<p className="typography-ui-label font-medium text-foreground">
|
||||
Setup commands
|
||||
{setupCommands.filter(cmd => cmd.trim()).length > 0 && (
|
||||
<span className="font-normal text-muted-foreground/70">
|
||||
{' '}({setupCommands.filter(cmd => cmd.trim()).length} configured)
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<RiArrowDownSLine className={cn(
|
||||
'h-4 w-4 text-muted-foreground transition-transform duration-200',
|
||||
isSetupCommandsOpen && 'rotate-180'
|
||||
)} />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="pt-2 space-y-2">
|
||||
<p className="typography-micro text-muted-foreground/70">
|
||||
Commands run in each new worktree. Use <code className="font-mono text-xs">$ROOT_PROJECT_PATH</code> for project root.
|
||||
</p>
|
||||
{isLoadingSetupCommands ? (
|
||||
<p className="typography-meta text-muted-foreground/70">Loading...</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{setupCommands.map((command, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={command}
|
||||
onChange={(e) => {
|
||||
const newCommands = [...setupCommands];
|
||||
newCommands[index] = e.target.value;
|
||||
setSetupCommands(newCommands);
|
||||
}}
|
||||
placeholder="e.g., bun install"
|
||||
className="h-8 flex-1 font-mono text-xs"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const newCommands = setupCommands.filter((_, i) => i !== index);
|
||||
setSetupCommands(newCommands);
|
||||
}}
|
||||
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="Remove command"
|
||||
>
|
||||
<RiCloseLine className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSetupCommands([...setupCommands, ''])}
|
||||
className="flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<RiAddLine className="h-3.5 w-3.5" />
|
||||
Add command
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
{/* Agent */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<FieldLabel
|
||||
htmlFor="multirun-agent"
|
||||
info={<InfoTip>Agent used for all runs. Defaults to your configured agent.</InfoTip>}
|
||||
>
|
||||
Agent
|
||||
</FieldLabel>
|
||||
<AgentSelector
|
||||
value={selectedAgent}
|
||||
onChange={setSelectedAgent}
|
||||
id="multirun-agent"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Agent selection */}
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
className="typography-ui-label font-medium text-foreground"
|
||||
htmlFor="multirun-agent"
|
||||
>
|
||||
Agent
|
||||
</label>
|
||||
<AgentSelector
|
||||
value={selectedAgent}
|
||||
onChange={setSelectedAgent}
|
||||
id="multirun-agent"
|
||||
/>
|
||||
<p className="typography-micro text-muted-foreground">
|
||||
Defaults to your configured default agent.
|
||||
</p>
|
||||
</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">
|
||||
<RiTerminalLine className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||
<span className="typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors">
|
||||
Setup commands
|
||||
</span>
|
||||
{configuredSetupCount > 0 && (
|
||||
<span
|
||||
className="inline-flex items-center justify-center h-4 min-w-4 px-1 rounded-full typography-micro font-medium"
|
||||
style={{
|
||||
backgroundColor: 'var(--primary-base)',
|
||||
color: 'var(--primary-foreground)',
|
||||
fontSize: '0.625rem',
|
||||
lineHeight: 1,
|
||||
}}
|
||||
>
|
||||
{configuredSetupCount}
|
||||
</span>
|
||||
)}
|
||||
<RiArrowDownSLine className={cn(
|
||||
'h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto',
|
||||
isSetupCommandsOpen && 'rotate-180'
|
||||
)} />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="pt-2 space-y-1.5">
|
||||
{isLoadingSetupCommands ? (
|
||||
<p className="typography-meta text-muted-foreground/70 px-2">Loading...</p>
|
||||
) : (
|
||||
<>
|
||||
{setupCommands.map((command, index) => (
|
||||
<div key={index} className="flex gap-1.5">
|
||||
<Input
|
||||
value={command}
|
||||
onChange={(e) => {
|
||||
const newCommands = [...setupCommands];
|
||||
newCommands[index] = e.target.value;
|
||||
setSetupCommands(newCommands);
|
||||
}}
|
||||
placeholder="bun install"
|
||||
className="h-8 flex-1 font-mono text-xs"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const newCommands = setupCommands.filter((_, i) => i !== index);
|
||||
setSetupCommands(newCommands);
|
||||
}}
|
||||
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="Remove command"
|
||||
>
|
||||
<RiCloseLine className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSetupCommands([...setupCommands, ''])}
|
||||
className="flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1"
|
||||
>
|
||||
<RiAddLine className="h-3 w-3" />
|
||||
Add command
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{/* Prompt */}
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="prompt" className="typography-ui-label font-medium text-foreground">
|
||||
Prompt <span className="text-destructive">*</span>
|
||||
</label>
|
||||
{/* ── Prompt ── */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<FieldLabel htmlFor="prompt" required>Prompt</FieldLabel>
|
||||
<Textarea
|
||||
id="prompt"
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
placeholder="Enter the prompt to send to all models..."
|
||||
className="typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content"
|
||||
className="typography-meta min-h-[100px] max-h-[300px] resize-none overflow-y-auto field-sizing-content"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* File attachments */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="typography-ui-label font-medium text-foreground">
|
||||
Attachments
|
||||
</label>
|
||||
<span className="typography-micro text-muted-foreground">(optional, same files for all runs)</span>
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
accept="*/*"
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap gap-2 items-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<RiAttachment2 className="h-3.5 w-3.5 mr-1.5" />
|
||||
Attach files
|
||||
</Button>
|
||||
|
||||
{/* File attachments inline */}
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
accept="*/*"
|
||||
/>
|
||||
<Tooltip delayDuration={300}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="inline-flex items-center gap-1 h-6 px-2 rounded-md typography-micro text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors"
|
||||
>
|
||||
<RiAttachment2 className="h-3 w-3" />
|
||||
Attach
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Same files sent to all runs</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{attachedFiles.map((file) => (
|
||||
<div
|
||||
key={file.id}
|
||||
className="inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta"
|
||||
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)',
|
||||
}}
|
||||
>
|
||||
{file.mimeType.startsWith('image/') ? (
|
||||
<RiFileImageLine className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<RiFileImageLine className="h-3 w-3 text-muted-foreground" />
|
||||
) : (
|
||||
<RiFileLine className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<RiFileLine className="h-3 w-3 text-muted-foreground" />
|
||||
)}
|
||||
<span className="truncate max-w-[120px]" title={file.filename}>
|
||||
<span className="truncate max-w-[100px]" title={file.filename}>
|
||||
{file.filename}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
({file.size < 1024 ? `${file.size}B` : file.size < 1024 * 1024 ? `${(file.size / 1024).toFixed(1)}KB` : `${(file.size / (1024 * 1024)).toFixed(1)}MB`})
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveFile(file.id)}
|
||||
className="text-muted-foreground hover:text-destructive ml-0.5"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<RiCloseLine className="h-3.5 w-3.5" />
|
||||
<RiCloseLine className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model selection */}
|
||||
<div className="space-y-2">
|
||||
<label className="typography-ui-label font-medium text-foreground">
|
||||
Models <span className="text-destructive">*</span>
|
||||
</label>
|
||||
{/* ── Models ── */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<FieldLabel
|
||||
required
|
||||
info={<InfoTip>Select 2–{MAX_MODELS} models. Same model can be added multiple times.</InfoTip>}
|
||||
>
|
||||
Models
|
||||
</FieldLabel>
|
||||
<ModelMultiSelect
|
||||
selectedModels={selectedModels}
|
||||
onAdd={handleAddModel}
|
||||
@@ -608,38 +731,48 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Error message */}
|
||||
{/* ── Error ── */}
|
||||
{error && (
|
||||
<div className="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body">
|
||||
<div
|
||||
className="px-3 py-2 rounded-lg typography-meta"
|
||||
style={{
|
||||
backgroundColor: 'var(--status-error-background)',
|
||||
color: 'var(--status-error)',
|
||||
borderWidth: 1,
|
||||
borderColor: 'var(--status-error-border)',
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollShadow>
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="flex items-center justify-end gap-3 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!isValid || isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
'Creating...'
|
||||
) : (
|
||||
<>
|
||||
Start ({selectedModels.length} models)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
{/* ── 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">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!isValid || isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
'Creating...'
|
||||
) : (
|
||||
<>Start ({selectedModels.length} models)</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -868,15 +868,11 @@ Nice-to-have:
|
||||
}
|
||||
|
||||
toast.success('Worktree created', {
|
||||
description: `${metadata.branch || metadata.name}${sourceLabel ? ` from ${sourceLabel}` : ''}`,
|
||||
description: `${metadata.branch || metadata.name}${sourceLabel ? ` from ${sourceLabel}` : ''} - bootstrapping in background`,
|
||||
});
|
||||
|
||||
try {
|
||||
await loadSessions();
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
|
||||
void loadSessions().catch(() => undefined);
|
||||
|
||||
onOpenChange(false);
|
||||
|
||||
if (createdSessionId) {
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from '@/lib/openchamberConfig';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { createWorktreeOnly } from '@/lib/worktreeSessionCreator';
|
||||
import { createWorktreeDraft } from '@/lib/worktreeSessionCreator';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ProjectNotesTodoPanelProps {
|
||||
@@ -228,22 +228,18 @@ export const ProjectNotesTodoPanel: React.FC<ProjectNotesTodoPanelProps> = ({
|
||||
}
|
||||
setSendingTodoId(todoId);
|
||||
try {
|
||||
const newWorktreePath = await createWorktreeOnly();
|
||||
routeToChat();
|
||||
const newWorktreePath = await createWorktreeDraft({ initialPrompt: todoText });
|
||||
if (!newWorktreePath) {
|
||||
return;
|
||||
}
|
||||
routeToChat();
|
||||
openNewSessionDraft({
|
||||
directoryOverride: newWorktreePath,
|
||||
initialPrompt: todoText,
|
||||
});
|
||||
toast.success('Todo sent to new worktree session');
|
||||
onActionComplete?.();
|
||||
} finally {
|
||||
setSendingTodoId(null);
|
||||
}
|
||||
},
|
||||
[canCreateWorktree, onActionComplete, openNewSessionDraft, projectRef, routeToChat]
|
||||
[canCreateWorktree, onActionComplete, projectRef, routeToChat]
|
||||
);
|
||||
|
||||
if (!projectRef) {
|
||||
|
||||
@@ -66,6 +66,9 @@ export const SessionDialogs: React.FC = () => {
|
||||
archiveSessions,
|
||||
loadSessions,
|
||||
getWorktreeMetadata,
|
||||
newSessionDraft,
|
||||
setNewSessionDraftTarget,
|
||||
setDraftBootstrapPendingDirectory,
|
||||
} = useSessionStore();
|
||||
const showDeletionDialog = useUIStore((state) => state.showDeletionDialog);
|
||||
const setShowDeletionDialog = useUIStore((state) => state.setShowDeletionDialog);
|
||||
@@ -381,12 +384,34 @@ export const SessionDialogs: React.FC = () => {
|
||||
deleteLocalBranch: boolean
|
||||
): Promise<boolean> => {
|
||||
const shouldRemoveRemote = deleteDialogShouldRemoveRemote && canRemoveRemoteBranches;
|
||||
const projectRef = getProjectRefForWorktree(worktree);
|
||||
const normalizedWorktreePath = normalizeProjectDirectory(worktree.path);
|
||||
const normalizedProjectPath = normalizeProjectDirectory(projectRef.path);
|
||||
try {
|
||||
await removeProjectWorktree(
|
||||
getProjectRefForWorktree(worktree),
|
||||
projectRef,
|
||||
worktree,
|
||||
{ deleteRemoteBranch: shouldRemoveRemote, deleteLocalBranch }
|
||||
);
|
||||
|
||||
const draftDirectory = normalizeProjectDirectory(newSessionDraft?.directoryOverride);
|
||||
if (
|
||||
newSessionDraft?.open
|
||||
&& normalizedWorktreePath
|
||||
&& draftDirectory === normalizedWorktreePath
|
||||
&& normalizedProjectPath
|
||||
) {
|
||||
setDraftBootstrapPendingDirectory(null);
|
||||
setNewSessionDraftTarget({
|
||||
projectId: projectRef.id,
|
||||
directoryOverride: normalizedProjectPath,
|
||||
}, { force: true });
|
||||
}
|
||||
|
||||
if (normalizeProjectDirectory(currentDirectory) === normalizedWorktreePath && normalizedProjectPath) {
|
||||
useDirectoryStore.getState().setDirectory(normalizedProjectPath, { showOverlay: false });
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
toast.error('Failed to remove worktree', {
|
||||
@@ -394,7 +419,7 @@ export const SessionDialogs: React.FC = () => {
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}, [canRemoveRemoteBranches, deleteDialogShouldRemoveRemote, getProjectRefForWorktree]);
|
||||
}, [canRemoveRemoteBranches, currentDirectory, deleteDialogShouldRemoveRemote, getProjectRefForWorktree, newSessionDraft?.directoryOverride, newSessionDraft?.open, setDraftBootstrapPendingDirectory, setNewSessionDraftTarget]);
|
||||
|
||||
const handleConfirmDelete = React.useCallback(async () => {
|
||||
if (!deleteDialog) {
|
||||
|
||||
@@ -1293,6 +1293,14 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
|
||||
openNewSessionDraft();
|
||||
}, [mobileVariant, openNewSessionDraft, setActiveMainTab, setSessionSwitcherOpen]);
|
||||
|
||||
const handleOpenMultiRunFromHeader = React.useCallback(() => {
|
||||
setActiveMainTab('chat');
|
||||
if (mobileVariant) {
|
||||
setSessionSwitcherOpen(false);
|
||||
}
|
||||
openMultiRunLauncher();
|
||||
}, [mobileVariant, openMultiRunLauncher, setActiveMainTab, setSessionSwitcherOpen]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={sessionSearchContainerRef}
|
||||
@@ -1336,6 +1344,8 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
|
||||
setProjectNotesPanelOpen={setProjectNotesPanelOpen}
|
||||
activeProjectRefForHeader={activeProjectRefForHeader}
|
||||
activeProjectLabelForHeader={activeProjectLabelForHeader}
|
||||
canOpenMultiRun={projects.length > 0}
|
||||
openMultiRunLauncher={handleOpenMultiRunFromHeader}
|
||||
stableActiveProjectIsRepo={stableActiveProjectIsRepo}
|
||||
headerActionIconClass={headerActionIconClass}
|
||||
reserveHeaderActionsSpace={reserveHeaderActionsSpace}
|
||||
@@ -1376,7 +1386,6 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
|
||||
setSessionSwitcherOpen={setSessionSwitcherOpen}
|
||||
openNewSessionDraft={openNewSessionDraft}
|
||||
openNewWorktreeDialog={openNewWorktreeDialog}
|
||||
openMultiRunLauncher={openMultiRunLauncher}
|
||||
openProjectEditDialog={setEditingProjectDialogId}
|
||||
removeProject={removeProject}
|
||||
projectHeaderSentinelRefs={projectHeaderSentinelRefs}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
RiExpandUpDownLine,
|
||||
RiStickyNoteLine,
|
||||
} from '@remixicon/react';
|
||||
import { ArrowsMerge } from '@/components/icons/ArrowsMerge';
|
||||
import type { ProjectRef } from '@/lib/openchamberConfig';
|
||||
import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore';
|
||||
import { ProjectNotesTodoPanel } from '../ProjectNotesTodoPanel';
|
||||
@@ -31,6 +32,8 @@ type Props = {
|
||||
setProjectNotesPanelOpen: (open: boolean) => void;
|
||||
activeProjectRefForHeader: ProjectRef | null;
|
||||
activeProjectLabelForHeader: string | null;
|
||||
canOpenMultiRun: boolean;
|
||||
openMultiRunLauncher: () => void;
|
||||
stableActiveProjectIsRepo: boolean;
|
||||
headerActionIconClass: string;
|
||||
reserveHeaderActionsSpace: boolean;
|
||||
@@ -56,6 +59,8 @@ export function SidebarHeader(props: Props): React.ReactNode {
|
||||
setProjectNotesPanelOpen,
|
||||
activeProjectRefForHeader,
|
||||
activeProjectLabelForHeader,
|
||||
canOpenMultiRun,
|
||||
openMultiRunLauncher,
|
||||
stableActiveProjectIsRepo,
|
||||
headerActionIconClass,
|
||||
reserveHeaderActionsSpace,
|
||||
@@ -113,6 +118,21 @@ export function SidebarHeader(props: Props): React.ReactNode {
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={openMultiRunLauncher}
|
||||
className={headerActionButtonClass}
|
||||
aria-label="New multi-run"
|
||||
disabled={!canOpenMultiRun}
|
||||
>
|
||||
<ArrowsMerge className={headerActionIconClass} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" sideOffset={4}><p>New multi-run</p></TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{useMobileNotesPanel ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
|
||||
@@ -54,7 +54,6 @@ type Props = {
|
||||
setSessionSwitcherOpen: (open: boolean) => void;
|
||||
openNewSessionDraft: (options?: { directoryOverride?: string | null }) => void;
|
||||
openNewWorktreeDialog: () => void;
|
||||
openMultiRunLauncher: () => void;
|
||||
openProjectEditDialog: (id: string) => void;
|
||||
removeProject: (id: string) => void;
|
||||
projectHeaderSentinelRefs: React.MutableRefObject<Map<string, HTMLDivElement | null>>;
|
||||
@@ -185,10 +184,6 @@ export function SidebarProjectsList(props: Props): React.ReactNode {
|
||||
if (props.mobileVariant) props.setSessionSwitcherOpen(false);
|
||||
props.openNewWorktreeDialog();
|
||||
}}
|
||||
onOpenMultiRunLauncher={() => {
|
||||
if (projectKey !== props.activeProjectId) props.setActiveProjectIdOnly(projectKey);
|
||||
props.openMultiRunLauncher();
|
||||
}}
|
||||
onRenameStart={() => props.openProjectEditDialog(projectKey)}
|
||||
onClose={() => props.removeProject(projectKey)}
|
||||
sentinelRef={(el) => { props.projectHeaderSentinelRefs.current.set(projectKey, el); }}
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
RiNodeTree,
|
||||
RiPencilAiLine,
|
||||
} from '@remixicon/react';
|
||||
import { ArrowsMerge } from '@/components/icons/ArrowsMerge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
@@ -43,7 +42,6 @@ export interface SortableProjectItemProps {
|
||||
onHoverChange: (hovered: boolean) => void;
|
||||
onNewSession: () => void;
|
||||
onNewWorktreeSession?: () => void;
|
||||
onOpenMultiRunLauncher: () => void;
|
||||
onRenameStart: () => void;
|
||||
onClose: () => void;
|
||||
sentinelRef: (el: HTMLDivElement | null) => void;
|
||||
@@ -79,7 +77,6 @@ export const SortableProjectItem: React.FC<SortableProjectItemProps> = ({
|
||||
onHoverChange,
|
||||
onNewSession,
|
||||
onNewWorktreeSession,
|
||||
onOpenMultiRunLauncher,
|
||||
onRenameStart,
|
||||
onClose,
|
||||
sentinelRef,
|
||||
@@ -267,12 +264,6 @@ export const SortableProjectItem: React.FC<SortableProjectItemProps> = ({
|
||||
New Session
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{showCreateButtons && isRepo && !hideDirectoryControls && (
|
||||
<DropdownMenuItem onClick={onOpenMultiRunLauncher}>
|
||||
<ArrowsMerge className="mr-1.5 h-4 w-4" />
|
||||
New Multi-Run
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onClick={onRenameStart}>
|
||||
<RiPencilAiLine className="mr-1.5 h-4 w-4" />
|
||||
Rename
|
||||
|
||||
@@ -202,7 +202,7 @@ export const CommandPalette: React.FC = () => {
|
||||
</CommandItem>
|
||||
<CommandItem onSelect={handleCreateWorktreeSession}>
|
||||
<RiGitBranchLine className="mr-2 h-4 w-4" />
|
||||
<span>New Session with Worktree</span>
|
||||
<span>New Worktree Draft</span>
|
||||
<CommandShortcut>
|
||||
{shortcut('new_chat_worktree')}
|
||||
</CommandShortcut>
|
||||
|
||||
@@ -112,7 +112,7 @@ export const HelpDialog: React.FC = () => {
|
||||
},
|
||||
{
|
||||
id: 'new_chat_worktree',
|
||||
description: "Create New Session in Worktree",
|
||||
description: "Create New Worktree Draft",
|
||||
icon: RiGitBranchLine,
|
||||
keys: '',
|
||||
},
|
||||
|
||||
@@ -60,7 +60,7 @@ import { BranchIntegrationSection, type OperationLogEntry } from './git/BranchIn
|
||||
import type { GitRemote } from '@/lib/gitApi';
|
||||
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { generateCommitMessage as generateSessionCommitMessage } from '@/lib/gitApi';
|
||||
import { generateCommitMessage as generateSessionCommitMessage, getGitWorktreeBootstrapStatus } from '@/lib/gitApi';
|
||||
|
||||
type SyncAction = 'fetch' | 'pull' | 'push' | null;
|
||||
type CommitAction = 'commit' | 'commitAndPush' | null;
|
||||
@@ -223,11 +223,14 @@ const normalizePath = (value?: string | null): string =>
|
||||
export const GitView: React.FC = () => {
|
||||
const { git } = useRuntimeAPIs();
|
||||
const currentDirectory = useEffectiveDirectory();
|
||||
const [worktreeBootstrapStatus, setWorktreeBootstrapStatus] = React.useState<'pending' | 'ready' | 'failed' | null>(null);
|
||||
const [isWaitingForGitRefreshAfterBootstrap, setIsWaitingForGitRefreshAfterBootstrap] = React.useState(false);
|
||||
const {
|
||||
currentSessionId,
|
||||
worktreeMetadata: worktreeMap,
|
||||
availableWorktrees,
|
||||
newSessionDraft,
|
||||
setDraftBootstrapPendingDirectory,
|
||||
} = useSessionStore();
|
||||
const normalizedCurrentDirectory = normalizePath(currentDirectory);
|
||||
const inferredWorktreeMetadata = React.useMemo(() => {
|
||||
@@ -287,6 +290,78 @@ export const GitView: React.FC = () => {
|
||||
const openContextDiff = useUIStore((state) => state.openContextDiff);
|
||||
const navigateToDiff = useUIStore((state) => state.navigateToDiff);
|
||||
const setRightSidebarOpen = useUIStore((state) => state.setRightSidebarOpen);
|
||||
const previousBootstrapStatusRef = React.useRef<'pending' | 'ready' | 'failed' | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!currentDirectory) {
|
||||
setWorktreeBootstrapStatus(null);
|
||||
setIsWaitingForGitRefreshAfterBootstrap(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let timeoutId: number | null = null;
|
||||
|
||||
const poll = async () => {
|
||||
try {
|
||||
const next = await getGitWorktreeBootstrapStatus(currentDirectory);
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setWorktreeBootstrapStatus(next.status);
|
||||
if (next.status === 'pending') {
|
||||
timeoutId = window.setTimeout(() => {
|
||||
void poll();
|
||||
}, 500);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setWorktreeBootstrapStatus(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void poll();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (timeoutId !== null) {
|
||||
window.clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
}, [currentDirectory]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const previous = previousBootstrapStatusRef.current;
|
||||
previousBootstrapStatusRef.current = worktreeBootstrapStatus;
|
||||
|
||||
if (!currentDirectory || !git) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (previous === 'pending' && worktreeBootstrapStatus === 'ready') {
|
||||
setIsWaitingForGitRefreshAfterBootstrap(true);
|
||||
void fetchAll(currentDirectory, git).finally(() => {
|
||||
window.setTimeout(() => {
|
||||
setIsWaitingForGitRefreshAfterBootstrap(false);
|
||||
}, 1200);
|
||||
});
|
||||
}
|
||||
|
||||
if (worktreeBootstrapStatus === 'failed') {
|
||||
setDraftBootstrapPendingDirectory(null);
|
||||
setIsWaitingForGitRefreshAfterBootstrap(false);
|
||||
}
|
||||
}, [currentDirectory, fetchAll, git, setDraftBootstrapPendingDirectory, worktreeBootstrapStatus]);
|
||||
|
||||
const normalizedDraftBootstrapPendingDirectory = normalizePath(newSessionDraft?.bootstrapPendingDirectory ?? null);
|
||||
const isDraftBootstrapPendingForCurrentDirectory = Boolean(
|
||||
currentDirectory && normalizedDraftBootstrapPendingDirectory && normalizedDraftBootstrapPendingDirectory === normalizePath(currentDirectory)
|
||||
);
|
||||
const isPendingWorktreeSetup = Boolean(
|
||||
currentDirectory && (worktreeBootstrapStatus === 'pending' || isDraftBootstrapPendingForCurrentDirectory)
|
||||
);
|
||||
const shouldHideNotGitState = isPendingWorktreeSetup || isWaitingForGitRefreshAfterBootstrap;
|
||||
|
||||
const initialSnapshot = React.useMemo(() => {
|
||||
if (!currentDirectory) return null;
|
||||
@@ -1829,6 +1904,20 @@ export const GitView: React.FC = () => {
|
||||
}
|
||||
|
||||
if (isGitRepo === false) {
|
||||
if (shouldHideNotGitState) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center px-4 text-center">
|
||||
<RiLoader4Line className="mb-3 size-6 animate-spin text-muted-foreground" />
|
||||
<p className="typography-ui-label font-semibold text-foreground">
|
||||
Worktree setup is in progress
|
||||
</p>
|
||||
<p className="typography-meta mt-1 text-muted-foreground">
|
||||
Git tools will appear as soon as the new worktree is ready.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center px-4 text-center">
|
||||
<RiGitBranchLine className="mb-3 size-6 text-muted-foreground" />
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { RiCloseLine } from '@remixicon/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { MultiRunLauncher } from '@/components/multirun';
|
||||
|
||||
interface MultiRunWindowProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
initialPrompt?: string;
|
||||
}
|
||||
|
||||
export const MultiRunWindow: React.FC<MultiRunWindowProps> = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
initialPrompt,
|
||||
}) => {
|
||||
const descriptionId = React.useId();
|
||||
|
||||
const hasOpenFloatingMenu = React.useCallback(() => {
|
||||
if (typeof document === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(
|
||||
document.querySelector('[data-slot="dropdown-menu-content"][data-state="open"], [data-slot="select-content"][data-state="open"]')
|
||||
);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Overlay
|
||||
className="fixed inset-0 z-50 bg-black/50 backdrop-blur-md"
|
||||
/>
|
||||
<DialogPrimitive.Content
|
||||
aria-describedby={descriptionId}
|
||||
onInteractOutside={(event) => {
|
||||
if (hasOpenFloatingMenu()) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
'fixed z-50 top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]',
|
||||
'w-[90vw] max-w-[720px] h-[680px] max-h-[85vh]',
|
||||
'flex flex-col rounded-xl border shadow-none overflow-hidden',
|
||||
'bg-background'
|
||||
)}
|
||||
>
|
||||
<div className="absolute right-0.5 top-0.5 z-50">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenChange(false)}
|
||||
aria-label="Close multi-run"
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-md p-0.5 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
||||
>
|
||||
<RiCloseLine className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<DialogPrimitive.Description id={descriptionId} className="sr-only">
|
||||
OpenChamber Multi-Run window.
|
||||
</DialogPrimitive.Description>
|
||||
<MultiRunLauncher
|
||||
initialPrompt={initialPrompt}
|
||||
onCreated={() => onOpenChange(false)}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
isWindowed
|
||||
/>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPrimitive.Portal>
|
||||
</DialogPrimitive.Root>
|
||||
);
|
||||
};
|
||||
@@ -30,18 +30,13 @@ export const SettingsWindow: React.FC<SettingsWindowProps> = ({ open, onOpenChan
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Overlay
|
||||
className="fixed inset-0 z-50 bg-black/50 backdrop-blur-md"
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
if (hasOpenFloatingMenu()) {
|
||||
return;
|
||||
}
|
||||
onOpenChange(false);
|
||||
}}
|
||||
/>
|
||||
<DialogPrimitive.Content
|
||||
aria-describedby={descriptionId}
|
||||
onPointerDownOutside={(event) => {
|
||||
event.preventDefault();
|
||||
onInteractOutside={(event) => {
|
||||
if (hasOpenFloatingMenu()) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
'fixed z-50 top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]',
|
||||
|
||||
@@ -57,7 +57,7 @@ export const AgentManagerEmptyState: React.FC<AgentManagerEmptyStateProps> = ({
|
||||
const [prompt, setPrompt] = React.useState('');
|
||||
const [selectedModels, setSelectedModels] = React.useState<ModelSelectionWithId[]>([]);
|
||||
const [selectedAgent, setSelectedAgent] = React.useState<string>('');
|
||||
const [baseBranch, setBaseBranch] = React.useState('HEAD');
|
||||
const [baseBranch, setBaseBranch] = React.useState('');
|
||||
const [attachedFiles, setAttachedFiles] = React.useState<AttachedFile[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
const [setupCommands, setSetupCommands] = React.useState<string[]>([]);
|
||||
@@ -206,6 +206,7 @@ export const AgentManagerEmptyState: React.FC<AgentManagerEmptyStateProps> = ({
|
||||
groupName.trim() &&
|
||||
prompt.trim() &&
|
||||
selectedModels.length >= 1 &&
|
||||
baseBranch &&
|
||||
isGitRepository &&
|
||||
!isLoadingBranches
|
||||
);
|
||||
|
||||
@@ -6,3 +6,4 @@ export { TerminalView } from './TerminalView';
|
||||
export { FilesView } from './FilesView';
|
||||
export { SettingsView } from './SettingsView';
|
||||
export { SettingsWindow } from './SettingsWindow';
|
||||
export { MultiRunWindow } from './MultiRunWindow';
|
||||
|
||||
@@ -27,8 +27,8 @@ export const useChatSearchDirectory = (): string | undefined => {
|
||||
}
|
||||
}
|
||||
|
||||
if (newSessionDraft?.open && newSessionDraft.directoryOverride) {
|
||||
return newSessionDraft.directoryOverride;
|
||||
if (newSessionDraft?.open && (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride)) {
|
||||
return (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride) ?? undefined;
|
||||
}
|
||||
|
||||
if (activeProjectId) {
|
||||
|
||||
@@ -39,8 +39,8 @@ export const useEffectiveDirectory = (): string | undefined => {
|
||||
}
|
||||
|
||||
// If a draft session is open, use its directoryOverride
|
||||
if (newSessionDraft?.open && newSessionDraft.directoryOverride) {
|
||||
return newSessionDraft.directoryOverride;
|
||||
if (newSessionDraft?.open && (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride)) {
|
||||
return (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride) ?? undefined;
|
||||
}
|
||||
|
||||
// Fall back to the global directory
|
||||
|
||||
@@ -306,6 +306,12 @@ export interface GitWorktreeValidationResult {
|
||||
};
|
||||
}
|
||||
|
||||
export interface GitWorktreeBootstrapStatus {
|
||||
status: 'pending' | 'ready' | 'failed';
|
||||
error: string | null;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface CreateGitWorktreePayload {
|
||||
mode?: 'new' | 'existing';
|
||||
/** Worktree folder name (falls back to OpenCode name generation when omitted). */
|
||||
@@ -380,6 +386,8 @@ export interface GeneratedPullRequestDescription {
|
||||
export interface GitWorktreeAPI {
|
||||
list(directory: string): Promise<GitWorktreeInfo[]>;
|
||||
validate?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeValidationResult>;
|
||||
bootstrapStatus?(directory: string): Promise<GitWorktreeBootstrapStatus>;
|
||||
preview?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult>;
|
||||
create?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult>;
|
||||
remove?(directory: string, payload: RemoveGitWorktreePayload): Promise<{ success: boolean }>;
|
||||
}
|
||||
@@ -402,6 +410,8 @@ export interface GitAPI {
|
||||
): Promise<GeneratedPullRequestDescription>;
|
||||
listGitWorktrees(directory: string): Promise<GitWorktreeInfo[]>;
|
||||
validateGitWorktree?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeValidationResult>;
|
||||
getGitWorktreeBootstrapStatus?(directory: string): Promise<GitWorktreeBootstrapStatus>;
|
||||
previewGitWorktree?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult>;
|
||||
createGitWorktree?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult>;
|
||||
deleteGitWorktree?(directory: string, payload: RemoveGitWorktreePayload): Promise<{ success: boolean }>;
|
||||
createGitCommit(directory: string, message: string, options?: CreateGitCommitOptions): Promise<GitCommitResult>;
|
||||
|
||||
@@ -453,6 +453,33 @@ export async function validateGitWorktree(
|
||||
return gitHttp.validateGitWorktree(directory, payload);
|
||||
}
|
||||
|
||||
export async function getGitWorktreeBootstrapStatus(
|
||||
directory: string,
|
||||
): Promise<import('./api/types').GitWorktreeBootstrapStatus> {
|
||||
const runtime = getRuntimeGit();
|
||||
if (runtime?.worktree?.bootstrapStatus) {
|
||||
return runtime.worktree.bootstrapStatus(directory);
|
||||
}
|
||||
if (runtime?.getGitWorktreeBootstrapStatus) {
|
||||
return runtime.getGitWorktreeBootstrapStatus(directory);
|
||||
}
|
||||
return gitHttp.getGitWorktreeBootstrapStatus(directory);
|
||||
}
|
||||
|
||||
export async function previewGitWorktree(
|
||||
directory: string,
|
||||
payload: import('./api/types').CreateGitWorktreePayload
|
||||
): Promise<import('./api/types').GitWorktreeCreateResult> {
|
||||
const runtime = getRuntimeGit();
|
||||
if (runtime?.worktree?.preview) {
|
||||
return runtime.worktree.preview(directory, payload);
|
||||
}
|
||||
if (runtime?.previewGitWorktree) {
|
||||
return runtime.previewGitWorktree(directory, payload);
|
||||
}
|
||||
return gitHttp.previewGitWorktree(directory, payload);
|
||||
}
|
||||
|
||||
export async function createGitWorktree(
|
||||
directory: string,
|
||||
payload: import('./api/types').CreateGitWorktreePayload
|
||||
|
||||
@@ -424,6 +424,30 @@ export async function validateGitWorktree(directory: string, payload: CreateGitW
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getGitWorktreeBootstrapStatus(directory: string): Promise<import('./api/types').GitWorktreeBootstrapStatus> {
|
||||
const response = await fetch(buildUrl(`${API_BASE}/worktrees/bootstrap-status`, directory));
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error(error.error || 'Failed to get worktree bootstrap status');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function previewGitWorktree(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult> {
|
||||
const response = await fetch(buildUrl(`${API_BASE}/worktrees/preview`, directory), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload ?? {}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error(error.error || 'Failed to preview worktree');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function createGitWorktree(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult> {
|
||||
const response = await fetch(buildUrl(`${API_BASE}/worktrees`, directory), {
|
||||
method: 'POST',
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
} from "@opencode-ai/sdk/v2";
|
||||
import type { PermissionRequest } from "@/types/permission";
|
||||
import type { QuestionRequest } from "@/types/question";
|
||||
import { waitForWorktreeBootstrap } from "@/lib/worktrees/worktreeBootstrap";
|
||||
type StreamEvent<TData> = {
|
||||
data: TData;
|
||||
event?: string;
|
||||
@@ -701,6 +702,10 @@ class OpencodeService {
|
||||
throw new Error('Message must have at least one part (text or file)');
|
||||
}
|
||||
|
||||
if (this.currentDirectory) {
|
||||
await waitForWorktreeBootstrap(this.currentDirectory);
|
||||
}
|
||||
|
||||
// Use async prompt endpoint so the client doesn't block waiting
|
||||
// for model work (SSE will deliver output/status).
|
||||
// This avoids 504s from proxy timeouts on long-running turns.
|
||||
|
||||
@@ -196,8 +196,8 @@ const SHORTCUT_ACTIONS: ReadonlyArray<ShortcutAction> = [
|
||||
{
|
||||
id: 'new_chat_worktree',
|
||||
defaultCombo: 'mod+shift+n',
|
||||
label: 'New session with worktree',
|
||||
description: 'Start a new session in a worktree',
|
||||
label: 'New worktree draft',
|
||||
description: 'Create a new worktree and open a draft in it',
|
||||
customizable: true,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Utility for creating a new session with an auto-generated worktree.
|
||||
* This is a standalone function that can be called from keyboard shortcuts,
|
||||
* menu actions, or other non-hook contexts.
|
||||
* Utilities for creating worktrees and, when needed, sessions bound to them.
|
||||
* This is a standalone entrypoint for keyboard shortcuts, menu actions,
|
||||
* and other non-hook contexts.
|
||||
*/
|
||||
|
||||
import { toast } from '@/components/ui';
|
||||
@@ -10,16 +10,20 @@ import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useContextStore } from '@/stores/contextStore';
|
||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||
import { checkIsGitRepository } from '@/lib/gitApi';
|
||||
import { checkIsGitRepository, previewGitWorktree } from '@/lib/gitApi';
|
||||
import { generateBranchName } from '@/lib/git/branchNameGenerator';
|
||||
import { getRootBranch, getWorktreeStatus } from '@/lib/worktrees/worktreeStatus';
|
||||
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
|
||||
import { getWorktreeSetupCommands } from '@/lib/openchamberConfig';
|
||||
import {
|
||||
removeProjectWorktree,
|
||||
type ProjectRef,
|
||||
} from '@/lib/worktrees/worktreeManager';
|
||||
import { createWorktreeWithDefaults } from '@/lib/worktrees/worktreeCreate';
|
||||
import { startConfigUpdate, finishConfigUpdate } from '@/lib/configUpdate';
|
||||
import {
|
||||
createPendingDraftWorktreeRequest,
|
||||
rejectPendingDraftWorktreeRequest,
|
||||
resolvePendingDraftWorktreeRequest,
|
||||
} from '@/lib/worktrees/pendingDraftWorktree';
|
||||
|
||||
const normalizePath = (value: string): string => value.replace(/\\/g, '/').replace(/\/+$/, '') || value;
|
||||
|
||||
@@ -48,16 +52,101 @@ const resolveProjectRef = (directory: string): ProjectRef | null => {
|
||||
return match ? { id: match.id, path: match.path } : null;
|
||||
};
|
||||
|
||||
// Track if we're currently creating a worktree session
|
||||
// Track if a worktree creation flow is already running
|
||||
let isCreatingWorktreeSession = false;
|
||||
|
||||
/**
|
||||
* Create a new session with an auto-generated worktree.
|
||||
* Uses project's worktree defaults for naming/metadata.
|
||||
*
|
||||
* @returns The created session, or null if creation failed
|
||||
*/
|
||||
export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
||||
|
||||
|
||||
const applyDefaultAgentAndModelSelection = (sessionId: string, configState = useConfigStore.getState()) => {
|
||||
try {
|
||||
const visibleAgents = configState.getVisibleAgents();
|
||||
let agentName: string | undefined;
|
||||
|
||||
if (configState.settingsDefaultAgent) {
|
||||
const settingsAgent = visibleAgents.find((a) => a.name === configState.settingsDefaultAgent);
|
||||
if (settingsAgent) {
|
||||
agentName = settingsAgent.name;
|
||||
}
|
||||
}
|
||||
|
||||
if (!agentName) {
|
||||
agentName =
|
||||
visibleAgents.find((agent) => agent.name === 'build')?.name ||
|
||||
visibleAgents[0]?.name;
|
||||
}
|
||||
|
||||
if (!agentName) {
|
||||
return;
|
||||
}
|
||||
|
||||
configState.setAgent(agentName);
|
||||
useContextStore.getState().saveSessionAgentSelection(sessionId, agentName);
|
||||
|
||||
const settingsDefaultModel = configState.settingsDefaultModel;
|
||||
if (!settingsDefaultModel) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = settingsDefaultModel.split('/');
|
||||
if (parts.length !== 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [providerId, modelId] = parts;
|
||||
const modelMetadata = configState.getModelMetadata(providerId, modelId);
|
||||
if (!modelMetadata) {
|
||||
return;
|
||||
}
|
||||
|
||||
useContextStore.getState().saveSessionModelSelection(sessionId, providerId, modelId);
|
||||
useContextStore.getState().saveAgentModelForSession(sessionId, agentName, providerId, modelId);
|
||||
|
||||
const settingsDefaultVariant = configState.settingsDefaultVariant;
|
||||
if (!settingsDefaultVariant) {
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = configState.providers.find((p) => p.id === providerId);
|
||||
const model = provider?.models.find((m: Record<string, unknown>) => (m as { id?: string }).id === modelId) as
|
||||
| { variants?: Record<string, unknown> }
|
||||
| undefined;
|
||||
const variants = model?.variants;
|
||||
|
||||
if (variants && Object.prototype.hasOwnProperty.call(variants, settingsDefaultVariant)) {
|
||||
configState.setCurrentVariant(settingsDefaultVariant);
|
||||
useContextStore
|
||||
.getState()
|
||||
.saveAgentModelVariantForSession(sessionId, agentName, providerId, modelId, settingsDefaultVariant);
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors setting default agent
|
||||
}
|
||||
};
|
||||
|
||||
const initializeSessionForWorktree = (sessionId: string, metadata: {
|
||||
path: string;
|
||||
projectDirectory: string;
|
||||
branch: string;
|
||||
label: string;
|
||||
name?: string;
|
||||
createdFromBranch?: string;
|
||||
kind?: 'pr' | 'standard';
|
||||
}) => {
|
||||
const sessionStore = useSessionStore.getState();
|
||||
const configState = useConfigStore.getState();
|
||||
sessionStore.initializeNewOpenChamberSession(sessionId, configState.agents);
|
||||
sessionStore.setSessionDirectory(sessionId, metadata.path);
|
||||
sessionStore.setWorktreeMetadata(sessionId, metadata);
|
||||
applyDefaultAgentAndModelSelection(sessionId, configState);
|
||||
useDirectoryStore.getState().setDirectory(metadata.path, { showOverlay: false });
|
||||
void sessionStore.loadSessions().catch(() => undefined);
|
||||
};
|
||||
|
||||
|
||||
const createInstantWorktreeDraft = async (options?: {
|
||||
initialPrompt?: string;
|
||||
title?: string;
|
||||
}): Promise<string | null> => {
|
||||
if (isCreatingWorktreeSession) {
|
||||
return null;
|
||||
}
|
||||
@@ -72,7 +161,6 @@ export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
||||
|
||||
const projectDirectory = activeProject.path;
|
||||
|
||||
// Check if it's a git repo
|
||||
let isGitRepo = false;
|
||||
try {
|
||||
isGitRepo = await checkIsGitRepository(projectDirectory);
|
||||
@@ -88,16 +176,57 @@ export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
||||
}
|
||||
|
||||
isCreatingWorktreeSession = true;
|
||||
startConfigUpdate("Creating new worktree session...");
|
||||
|
||||
try {
|
||||
const projectRef: ProjectRef = { id: activeProject.id, path: projectDirectory };
|
||||
const pendingRequestId = createPendingDraftWorktreeRequest();
|
||||
|
||||
// Lock the draft immediately so no React effect can reset it to the project
|
||||
// root while we await the preview / worktree creation below.
|
||||
const sessionStore = useSessionStore.getState();
|
||||
if (sessionStore.newSessionDraft?.open) {
|
||||
sessionStore.overrideNewSessionDraftTarget({
|
||||
projectId: projectRef.id,
|
||||
directoryOverride: sessionStore.newSessionDraft.directoryOverride ?? projectRef.path,
|
||||
pendingWorktreeRequestId: pendingRequestId,
|
||||
preserveDirectoryOverride: true,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
});
|
||||
} else {
|
||||
sessionStore.openNewSessionDraft({
|
||||
projectId: projectRef.id,
|
||||
directoryOverride: projectRef.path,
|
||||
pendingWorktreeRequestId: pendingRequestId,
|
||||
preserveDirectoryOverride: true,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
});
|
||||
}
|
||||
|
||||
// Generate a friendly name (SDK will slugify + ensure uniqueness).
|
||||
const preferredName = generateBranchName();
|
||||
|
||||
const preview = await previewGitWorktree(projectRef.path, {
|
||||
mode: 'new',
|
||||
branchName: preferredName,
|
||||
worktreeName: preferredName,
|
||||
}).catch(() => null);
|
||||
|
||||
// Refine draft target once we know the actual worktree path from the preview.
|
||||
if (preview?.path) {
|
||||
useSessionStore.getState().overrideNewSessionDraftTarget({
|
||||
projectId: projectRef.id,
|
||||
directoryOverride: preview.path,
|
||||
pendingWorktreeRequestId: pendingRequestId,
|
||||
bootstrapPendingDirectory: preview.path,
|
||||
preserveDirectoryOverride: true,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
});
|
||||
useDirectoryStore.getState().setDirectory(preview.path, { showOverlay: false });
|
||||
}
|
||||
|
||||
const setupCommands = await getWorktreeSetupCommands(projectRef);
|
||||
const rootBranch = await getRootBranch(projectRef.path);
|
||||
const metadata = await createWorktreeWithDefaults(projectRef, {
|
||||
preferredName,
|
||||
mode: 'new',
|
||||
@@ -106,123 +235,44 @@ export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
||||
setupCommands,
|
||||
});
|
||||
|
||||
const createdMetadata = {
|
||||
...metadata,
|
||||
createdFromBranch: rootBranch,
|
||||
kind: 'standard' as const,
|
||||
};
|
||||
|
||||
// Get worktree status
|
||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
||||
const createdMetadataWithStatus = status ? { ...createdMetadata, status } : createdMetadata;
|
||||
|
||||
// Create the session
|
||||
const sessionStore = useSessionStore.getState();
|
||||
const session = await sessionStore.createSession(undefined, metadata.path);
|
||||
if (!session) {
|
||||
// Clean up the worktree if session creation failed
|
||||
await removeProjectWorktree(projectRef, metadata, { deleteLocalBranch: true }).catch(() => undefined);
|
||||
toast.error('Failed to create session', {
|
||||
description: 'Could not create a session for the worktree.',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Initialize the session
|
||||
const configState = useConfigStore.getState();
|
||||
const agents = configState.agents;
|
||||
sessionStore.initializeNewOpenChamberSession(session.id, agents);
|
||||
sessionStore.setSessionDirectory(session.id, metadata.path);
|
||||
sessionStore.setWorktreeMetadata(session.id, createdMetadataWithStatus);
|
||||
|
||||
// Apply default agent and model settings
|
||||
try {
|
||||
const visibleAgents = configState.getVisibleAgents();
|
||||
let agentName: string | undefined;
|
||||
|
||||
// Priority: settingsDefaultAgent → build → first visible
|
||||
if (configState.settingsDefaultAgent) {
|
||||
const settingsAgent = visibleAgents.find((a) => a.name === configState.settingsDefaultAgent);
|
||||
if (settingsAgent) {
|
||||
agentName = settingsAgent.name;
|
||||
}
|
||||
}
|
||||
if (!agentName) {
|
||||
agentName =
|
||||
visibleAgents.find((agent) => agent.name === 'build')?.name ||
|
||||
visibleAgents[0]?.name;
|
||||
}
|
||||
|
||||
if (agentName) {
|
||||
// 1. Update global UI state
|
||||
configState.setAgent(agentName);
|
||||
|
||||
// 2. Persist to session context so it sticks after reload/switch
|
||||
useContextStore.getState().saveSessionAgentSelection(session.id, agentName);
|
||||
|
||||
// 3. Handle default model for the agent if set in global settings
|
||||
const settingsDefaultModel = configState.settingsDefaultModel;
|
||||
if (settingsDefaultModel) {
|
||||
const parts = settingsDefaultModel.split('/');
|
||||
if (parts.length === 2) {
|
||||
const [providerId, modelId] = parts;
|
||||
// Validate model exists (optional, but good practice)
|
||||
const modelMetadata = configState.getModelMetadata(providerId, modelId);
|
||||
if (modelMetadata) {
|
||||
useContextStore.getState().saveSessionModelSelection(session.id, providerId, modelId);
|
||||
// Also save the specific agent's model preference for this session
|
||||
useContextStore.getState().saveAgentModelForSession(session.id, agentName, providerId, modelId);
|
||||
|
||||
// Seed default variant into session context so ModelControls restore logic
|
||||
// doesn't wipe it on first switch to the new session.
|
||||
const settingsDefaultVariant = configState.settingsDefaultVariant;
|
||||
if (settingsDefaultVariant) {
|
||||
const provider = configState.providers.find((p) => p.id === providerId);
|
||||
const model = provider?.models.find((m: Record<string, unknown>) => (m as { id?: string }).id === modelId) as
|
||||
| { variants?: Record<string, unknown> }
|
||||
| undefined;
|
||||
const variants = model?.variants;
|
||||
|
||||
if (variants && Object.prototype.hasOwnProperty.call(variants, settingsDefaultVariant)) {
|
||||
configState.setCurrentVariant(settingsDefaultVariant);
|
||||
useContextStore
|
||||
.getState()
|
||||
.saveAgentModelVariantForSession(session.id, agentName, providerId, modelId, settingsDefaultVariant);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors setting default agent
|
||||
}
|
||||
|
||||
// Update directory
|
||||
useDirectoryStore.getState().setDirectory(metadata.path, { showOverlay: false });
|
||||
|
||||
// Refresh sessions list
|
||||
try {
|
||||
await sessionStore.loadSessions();
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
toast.success('Worktree created', {
|
||||
description: metadata.branch ? `Branch: ${metadata.branch}` : 'Ready',
|
||||
resolvePendingDraftWorktreeRequest(pendingRequestId, metadata.path);
|
||||
useSessionStore.getState().overrideNewSessionDraftTarget({
|
||||
projectId: projectRef.id,
|
||||
directoryOverride: metadata.path,
|
||||
pendingWorktreeRequestId: null,
|
||||
bootstrapPendingDirectory: metadata.path,
|
||||
preserveDirectoryOverride: true,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
});
|
||||
useDirectoryStore.getState().setDirectory(metadata.path, { showOverlay: false });
|
||||
void useSessionStore.getState().loadSessions().catch(() => undefined);
|
||||
|
||||
return session;
|
||||
return metadata.path;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to create worktree session';
|
||||
const message = error instanceof Error ? error.message : 'Failed to create worktree';
|
||||
const requestId = useSessionStore.getState().newSessionDraft.pendingWorktreeRequestId;
|
||||
if (requestId) {
|
||||
rejectPendingDraftWorktreeRequest(requestId, error instanceof Error ? error : new Error(message));
|
||||
useSessionStore.getState().resolvePendingDraftWorktreeTarget(requestId, null);
|
||||
}
|
||||
useSessionStore.getState().setDraftBootstrapPendingDirectory(null);
|
||||
toast.error('Failed to create worktree', {
|
||||
description: message,
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
finishConfigUpdate();
|
||||
isCreatingWorktreeSession = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new worktree and open a draft scoped to it.
|
||||
*
|
||||
* @returns The worktree path, or null if creation failed
|
||||
*/
|
||||
export async function createWorktreeSession(): Promise<string | null> {
|
||||
return createInstantWorktreeDraft();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -232,6 +282,10 @@ export function isCreatingWorktree(): boolean {
|
||||
return isCreatingWorktreeSession;
|
||||
}
|
||||
|
||||
export async function createWorktreeDraft(options?: { initialPrompt?: string; title?: string }): Promise<string | null> {
|
||||
return createInstantWorktreeDraft(options);
|
||||
}
|
||||
|
||||
export async function createWorktreeOnly(): Promise<string | null> {
|
||||
if (isCreatingWorktreeSession) {
|
||||
return null;
|
||||
@@ -261,7 +315,6 @@ export async function createWorktreeOnly(): Promise<string | null> {
|
||||
}
|
||||
|
||||
isCreatingWorktreeSession = true;
|
||||
startConfigUpdate('Creating new worktree...');
|
||||
|
||||
try {
|
||||
const projectRef: ProjectRef = { id: activeProject.id, path: projectDirectory };
|
||||
@@ -275,17 +328,8 @@ export async function createWorktreeOnly(): Promise<string | null> {
|
||||
setupCommands,
|
||||
});
|
||||
|
||||
const rootBranch = await getRootBranch(projectRef.path).catch(() => undefined);
|
||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
||||
|
||||
const branchLabel = metadata.branch || metadata.label || metadata.name;
|
||||
toast.success('Worktree created', {
|
||||
description: branchLabel
|
||||
? `${branchLabel}${rootBranch ? ` from ${rootBranch}` : ''}`
|
||||
: status?.isDirty ? 'Created (dirty)' : 'Ready',
|
||||
});
|
||||
|
||||
await useSessionStore.getState().loadSessions();
|
||||
void useSessionStore.getState().loadSessions().catch(() => undefined);
|
||||
return metadata.path;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to create worktree';
|
||||
@@ -294,7 +338,6 @@ export async function createWorktreeOnly(): Promise<string | null> {
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
finishConfigUpdate();
|
||||
isCreatingWorktreeSession = false;
|
||||
}
|
||||
}
|
||||
@@ -327,7 +370,6 @@ export async function createWorktreeSessionForBranch(
|
||||
}
|
||||
|
||||
isCreatingWorktreeSession = true;
|
||||
startConfigUpdate("Creating worktree session...");
|
||||
|
||||
try {
|
||||
const projectRef = resolveProjectRef(projectDirectory);
|
||||
@@ -373,10 +415,6 @@ export async function createWorktreeSessionForBranch(
|
||||
kind,
|
||||
};
|
||||
|
||||
// Get worktree status
|
||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
||||
const createdMetadataWithStatus = status ? { ...createdMetadata, status } : createdMetadata;
|
||||
|
||||
// Create the session
|
||||
const sessionStore = useSessionStore.getState();
|
||||
const session = await sessionStore.createSession(undefined, metadata.path);
|
||||
@@ -389,89 +427,7 @@ export async function createWorktreeSessionForBranch(
|
||||
return null;
|
||||
}
|
||||
|
||||
// Initialize the session
|
||||
const configState = useConfigStore.getState();
|
||||
const agents = configState.agents;
|
||||
sessionStore.initializeNewOpenChamberSession(session.id, agents);
|
||||
sessionStore.setSessionDirectory(session.id, metadata.path);
|
||||
sessionStore.setWorktreeMetadata(session.id, createdMetadataWithStatus);
|
||||
|
||||
// Apply default agent and model settings
|
||||
try {
|
||||
const visibleAgents = configState.getVisibleAgents();
|
||||
let agentName: string | undefined;
|
||||
|
||||
// Priority: settingsDefaultAgent → build → first visible
|
||||
if (configState.settingsDefaultAgent) {
|
||||
const settingsAgent = visibleAgents.find((a) => a.name === configState.settingsDefaultAgent);
|
||||
if (settingsAgent) {
|
||||
agentName = settingsAgent.name;
|
||||
}
|
||||
}
|
||||
if (!agentName) {
|
||||
agentName =
|
||||
visibleAgents.find((agent) => agent.name === 'build')?.name ||
|
||||
visibleAgents[0]?.name;
|
||||
}
|
||||
|
||||
if (agentName) {
|
||||
// 1. Update global UI state
|
||||
configState.setAgent(agentName);
|
||||
|
||||
// 2. Persist to session context so it sticks after reload/switch
|
||||
useContextStore.getState().saveSessionAgentSelection(session.id, agentName);
|
||||
|
||||
// 3. Handle default model for the agent if set in global settings
|
||||
const settingsDefaultModel = configState.settingsDefaultModel;
|
||||
if (settingsDefaultModel) {
|
||||
const parts = settingsDefaultModel.split('/');
|
||||
if (parts.length === 2) {
|
||||
const [providerId, modelId] = parts;
|
||||
// Validate model exists (optional, but good practice)
|
||||
const modelMetadata = configState.getModelMetadata(providerId, modelId);
|
||||
if (modelMetadata) {
|
||||
useContextStore.getState().saveSessionModelSelection(session.id, providerId, modelId);
|
||||
// Also save the specific agent's model preference for this session
|
||||
useContextStore.getState().saveAgentModelForSession(session.id, agentName, providerId, modelId);
|
||||
|
||||
// Seed default variant into session context so ModelControls restore logic
|
||||
// doesn't wipe it on first switch to the new session.
|
||||
const settingsDefaultVariant = configState.settingsDefaultVariant;
|
||||
if (settingsDefaultVariant) {
|
||||
const provider = configState.providers.find((p) => p.id === providerId);
|
||||
const model = provider?.models.find((m: Record<string, unknown>) => (m as { id?: string }).id === modelId) as
|
||||
| { variants?: Record<string, unknown> }
|
||||
| undefined;
|
||||
const variants = model?.variants;
|
||||
|
||||
if (variants && Object.prototype.hasOwnProperty.call(variants, settingsDefaultVariant)) {
|
||||
configState.setCurrentVariant(settingsDefaultVariant);
|
||||
useContextStore
|
||||
.getState()
|
||||
.saveAgentModelVariantForSession(session.id, agentName, providerId, modelId, settingsDefaultVariant);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors setting default agent
|
||||
}
|
||||
|
||||
// Update directory
|
||||
useDirectoryStore.getState().setDirectory(metadata.path, { showOverlay: false });
|
||||
|
||||
// Refresh sessions list
|
||||
try {
|
||||
await sessionStore.loadSessions();
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
toast.success('Worktree created', {
|
||||
description: metadata.branch ? `Branch: ${metadata.branch}` : 'Ready',
|
||||
});
|
||||
initializeSessionForWorktree(session.id, createdMetadata);
|
||||
|
||||
return session;
|
||||
} catch (error) {
|
||||
@@ -481,7 +437,6 @@ export async function createWorktreeSessionForBranch(
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
finishConfigUpdate();
|
||||
isCreatingWorktreeSession = false;
|
||||
}
|
||||
}
|
||||
@@ -510,7 +465,6 @@ export async function createWorktreeSessionForNewBranch(
|
||||
}
|
||||
|
||||
isCreatingWorktreeSession = true;
|
||||
startConfigUpdate('Creating worktree session...');
|
||||
|
||||
try {
|
||||
const start = startPoint?.trim() || 'HEAD';
|
||||
@@ -562,92 +516,22 @@ export async function createWorktreeSessionForNewBranch(
|
||||
kind,
|
||||
};
|
||||
|
||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
||||
const createdMetadataWithStatus = status ? { ...createdMetadata, status } : createdMetadata;
|
||||
const sessionStore = useSessionStore.getState();
|
||||
const session = await sessionStore.createSession(undefined, metadata.path);
|
||||
if (!session) {
|
||||
await removeProjectWorktree(projectRef, metadata, { deleteLocalBranch: true }).catch(() => undefined);
|
||||
throw new Error('Could not create a session for the worktree.');
|
||||
}
|
||||
|
||||
const sessionStore = useSessionStore.getState();
|
||||
const session = await sessionStore.createSession(undefined, metadata.path);
|
||||
if (!session) {
|
||||
await removeProjectWorktree(projectRef, metadata, { deleteLocalBranch: true }).catch(() => undefined);
|
||||
throw new Error('Could not create a session for the worktree.');
|
||||
}
|
||||
initializeSessionForWorktree(session.id, createdMetadata);
|
||||
|
||||
const configState = useConfigStore.getState();
|
||||
sessionStore.initializeNewOpenChamberSession(session.id, configState.agents);
|
||||
sessionStore.setSessionDirectory(session.id, metadata.path);
|
||||
sessionStore.setWorktreeMetadata(session.id, createdMetadataWithStatus);
|
||||
|
||||
// Apply default agent/model/variant settings (reuse same logic as createWorktreeSessionForBranch)
|
||||
try {
|
||||
const visibleAgents = configState.getVisibleAgents();
|
||||
let agentName: string | undefined;
|
||||
if (configState.settingsDefaultAgent) {
|
||||
const settingsAgent = visibleAgents.find((a) => a.name === configState.settingsDefaultAgent);
|
||||
if (settingsAgent) {
|
||||
agentName = settingsAgent.name;
|
||||
}
|
||||
}
|
||||
if (!agentName) {
|
||||
agentName =
|
||||
visibleAgents.find((agent) => agent.name === 'build')?.name ||
|
||||
visibleAgents[0]?.name;
|
||||
}
|
||||
|
||||
if (agentName) {
|
||||
configState.setAgent(agentName);
|
||||
useContextStore.getState().saveSessionAgentSelection(session.id, agentName);
|
||||
|
||||
const settingsDefaultModel = configState.settingsDefaultModel;
|
||||
if (settingsDefaultModel) {
|
||||
const parts = settingsDefaultModel.split('/');
|
||||
if (parts.length === 2) {
|
||||
const [providerId, modelId] = parts;
|
||||
const modelMetadata = configState.getModelMetadata(providerId, modelId);
|
||||
if (modelMetadata) {
|
||||
useContextStore.getState().saveSessionModelSelection(session.id, providerId, modelId);
|
||||
useContextStore.getState().saveAgentModelForSession(session.id, agentName, providerId, modelId);
|
||||
|
||||
const settingsDefaultVariant = configState.settingsDefaultVariant;
|
||||
if (settingsDefaultVariant) {
|
||||
const provider = configState.providers.find((p) => p.id === providerId);
|
||||
const model = provider?.models.find((m: Record<string, unknown>) => (m as { id?: string }).id === modelId) as
|
||||
| { variants?: Record<string, unknown> }
|
||||
| undefined;
|
||||
const variants = model?.variants;
|
||||
if (variants && Object.prototype.hasOwnProperty.call(variants, settingsDefaultVariant)) {
|
||||
configState.setCurrentVariant(settingsDefaultVariant);
|
||||
useContextStore
|
||||
.getState()
|
||||
.saveAgentModelVariantForSession(session.id, agentName, providerId, modelId, settingsDefaultVariant);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
useDirectoryStore.getState().setDirectory(metadata.path, { showOverlay: false });
|
||||
try {
|
||||
await sessionStore.loadSessions();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
toast.success('Worktree created', {
|
||||
description: metadata.branch ? `Branch: ${metadata.branch}` : 'Ready',
|
||||
});
|
||||
|
||||
return { id: session.id, branch: metadata.branch || base };
|
||||
return { id: session.id, branch: metadata.branch || base };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to create worktree session';
|
||||
toast.error('Failed to create worktree', { description: message });
|
||||
return null;
|
||||
}
|
||||
} finally {
|
||||
finishConfigUpdate();
|
||||
isCreatingWorktreeSession = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
type Deferred = {
|
||||
promise: Promise<string>;
|
||||
resolve: (directory: string) => void;
|
||||
reject: (error: Error) => void;
|
||||
};
|
||||
|
||||
const requests = new Map<string, Deferred>();
|
||||
|
||||
const createDeferred = (): Deferred => {
|
||||
let resolve!: (directory: string) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<string>((innerResolve, innerReject) => {
|
||||
resolve = innerResolve;
|
||||
reject = innerReject;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
const createId = (): string => `worktree_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
export const createPendingDraftWorktreeRequest = (): string => {
|
||||
const id = createId();
|
||||
requests.set(id, createDeferred());
|
||||
return id;
|
||||
};
|
||||
|
||||
export const resolvePendingDraftWorktreeRequest = (id: string, directory: string): void => {
|
||||
const entry = requests.get(id);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
requests.delete(id);
|
||||
entry.resolve(directory);
|
||||
};
|
||||
|
||||
export const rejectPendingDraftWorktreeRequest = (id: string, error: Error): void => {
|
||||
const entry = requests.get(id);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
requests.delete(id);
|
||||
entry.reject(error);
|
||||
};
|
||||
|
||||
export const waitForPendingDraftWorktreeRequest = (id: string): Promise<string> => {
|
||||
const entry = requests.get(id);
|
||||
if (!entry) {
|
||||
return Promise.reject(new Error('Pending worktree request not found'));
|
||||
}
|
||||
return entry.promise;
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
import * as gitHttp from '@/lib/gitApiHttp';
|
||||
import type { RuntimeAPIs } from '@/lib/api/types';
|
||||
import type { GitWorktreeBootstrapStatus } from '@/lib/api/types';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__OPENCHAMBER_RUNTIME_APIS__?: RuntimeAPIs;
|
||||
}
|
||||
}
|
||||
|
||||
type WorktreeBootstrapState = GitWorktreeBootstrapStatus;
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
const POLL_INTERVAL_MS = 250;
|
||||
|
||||
const normalizePath = (value: string): string => value.replace(/\\/g, '/').replace(/\/+$/, '') || value;
|
||||
|
||||
const state = new Map<string, WorktreeBootstrapState>();
|
||||
const waiters = new Map<string, Promise<void>>();
|
||||
|
||||
const getKey = (directory: string): string => normalizePath(directory);
|
||||
|
||||
const getGitWorktreeBootstrapStatus = async (directory: string): Promise<GitWorktreeBootstrapStatus> => {
|
||||
const runtimeGit = typeof window !== 'undefined' ? window.__OPENCHAMBER_RUNTIME_APIS__?.git : undefined;
|
||||
if (runtimeGit?.worktree?.bootstrapStatus) {
|
||||
return runtimeGit.worktree.bootstrapStatus(directory);
|
||||
}
|
||||
if (runtimeGit?.getGitWorktreeBootstrapStatus) {
|
||||
return runtimeGit.getGitWorktreeBootstrapStatus(directory);
|
||||
}
|
||||
return gitHttp.getGitWorktreeBootstrapStatus(directory);
|
||||
};
|
||||
|
||||
export const markWorktreeBootstrapPending = (directory: string): void => {
|
||||
const key = getKey(directory);
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
state.set(key, {
|
||||
status: 'pending',
|
||||
error: null,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
};
|
||||
|
||||
export const clearWorktreeBootstrapState = (directory: string): void => {
|
||||
const key = getKey(directory);
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
state.delete(key);
|
||||
waiters.delete(key);
|
||||
};
|
||||
|
||||
export const setWorktreeBootstrapState = (directory: string, next: WorktreeBootstrapState): void => {
|
||||
const key = getKey(directory);
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
state.set(key, next);
|
||||
if (next.status !== 'pending') {
|
||||
waiters.delete(key);
|
||||
}
|
||||
};
|
||||
|
||||
export const getWorktreeBootstrapState = (directory: string): WorktreeBootstrapState | null => {
|
||||
const key = getKey(directory);
|
||||
if (!key) {
|
||||
return null;
|
||||
}
|
||||
return state.get(key) ?? null;
|
||||
};
|
||||
|
||||
const pollWorktreeBootstrapUntilSettled = async (directory: string, timeoutMs: number): Promise<void> => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
const result = await getGitWorktreeBootstrapStatus(directory);
|
||||
setWorktreeBootstrapState(directory, result);
|
||||
|
||||
if (result.status === 'ready') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === 'failed') {
|
||||
throw new Error(result.error || 'Worktree bootstrap failed');
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
|
||||
throw new Error('Timed out waiting for worktree bootstrap');
|
||||
};
|
||||
|
||||
export const waitForWorktreeBootstrap = async (directory: string, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<void> => {
|
||||
const key = getKey(directory);
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = state.get(key);
|
||||
if (current?.status === 'ready') {
|
||||
return;
|
||||
}
|
||||
if (current?.status === 'failed') {
|
||||
throw new Error(current.error || 'Worktree bootstrap failed');
|
||||
}
|
||||
|
||||
const existing = waiters.get(key);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const pending = pollWorktreeBootstrapUntilSettled(directory, timeoutMs).finally(() => {
|
||||
waiters.delete(key);
|
||||
});
|
||||
waiters.set(key, pending);
|
||||
return pending;
|
||||
};
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
deleteRemoteBranch,
|
||||
git,
|
||||
} from '@/lib/gitApi';
|
||||
import {
|
||||
clearWorktreeBootstrapState,
|
||||
markWorktreeBootstrapPending,
|
||||
} from '@/lib/worktrees/worktreeBootstrap';
|
||||
import type {
|
||||
CreateGitWorktreePayload,
|
||||
GitWorktreeValidationResult,
|
||||
@@ -241,6 +245,8 @@ export async function createWorktree(project: ProjectRef, args: CreateWorktreeAr
|
||||
label: returnedBranch || returnedName,
|
||||
};
|
||||
|
||||
markWorktreeBootstrapPending(metadata.path);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
@@ -268,6 +274,8 @@ export async function removeProjectWorktree(project: ProjectRef, worktree: Workt
|
||||
throw new Error('Worktree removal failed');
|
||||
}
|
||||
|
||||
clearWorktreeBootstrapState(worktree.path);
|
||||
|
||||
const branchName = (worktree.branch || '').replace(/^refs\/heads\//, '').trim();
|
||||
if (deleteRemote && branchName) {
|
||||
await deleteRemoteBranch(projectDirectory, { branch: branchName, remote: remoteName }).catch(() => undefined);
|
||||
|
||||
@@ -118,6 +118,9 @@ export type NewSessionDraftState = {
|
||||
open: boolean;
|
||||
selectedProjectId?: string | null;
|
||||
directoryOverride: string | null;
|
||||
pendingWorktreeRequestId?: string | null;
|
||||
bootstrapPendingDirectory?: string | null;
|
||||
preserveDirectoryOverride?: boolean;
|
||||
parentID: string | null;
|
||||
title?: string;
|
||||
initialPrompt?: string;
|
||||
@@ -216,8 +219,13 @@ export interface SessionStore {
|
||||
setSessionAgentEditMode: (sessionId: string, agentName: string | undefined, mode: EditPermissionMode, defaultMode?: EditPermissionMode) => void;
|
||||
loadSessions: () => Promise<void>;
|
||||
|
||||
openNewSessionDraft: (options?: { projectId?: string | null; directoryOverride?: string | null; parentID?: string | null; title?: string; initialPrompt?: string; syntheticParts?: SyntheticContextPart[]; targetFolderId?: string }) => void;
|
||||
setNewSessionDraftTarget: (target: { projectId?: string | null; directoryOverride?: string | null }) => void;
|
||||
openNewSessionDraft: (options?: { projectId?: string | null; directoryOverride?: string | null; pendingWorktreeRequestId?: string | null; bootstrapPendingDirectory?: string | null; preserveDirectoryOverride?: boolean; parentID?: string | null; title?: string; initialPrompt?: string; syntheticParts?: SyntheticContextPart[]; targetFolderId?: string }) => void;
|
||||
overrideNewSessionDraftTarget: (options: { projectId?: string | null; directoryOverride?: string | null; pendingWorktreeRequestId?: string | null; bootstrapPendingDirectory?: string | null; preserveDirectoryOverride?: boolean; title?: string; initialPrompt?: string }) => void;
|
||||
setNewSessionDraftTarget: (target: { projectId?: string | null; directoryOverride?: string | null }, options?: { force?: boolean }) => void;
|
||||
setPendingDraftWorktreeRequest: (requestId: string | null) => void;
|
||||
resolvePendingDraftWorktreeTarget: (requestId: string, directory: string | null, options?: { projectId?: string | null; bootstrapPendingDirectory?: string | null; preserveDirectoryOverride?: boolean }) => void;
|
||||
setDraftBootstrapPendingDirectory: (directory: string | null) => void;
|
||||
setDraftPreserveDirectoryOverride: (value: boolean) => void;
|
||||
closeNewSessionDraft: () => void;
|
||||
|
||||
createSession: (title?: string, directoryOverride?: string | null, parentID?: string | null) => Promise<Session | null>;
|
||||
|
||||
@@ -24,6 +24,8 @@ import { flattenAssistantTextParts } from "@/lib/messages/messageText";
|
||||
import { normalizeMessageRecordsForProjection } from "./utils/messageProjectors";
|
||||
import type { ProjectEntry } from "@/lib/api/types";
|
||||
import type { WorktreeMetadata } from "@/types/worktree";
|
||||
import { waitForWorktreeBootstrap } from "@/lib/worktrees/worktreeBootstrap";
|
||||
import { waitForPendingDraftWorktreeRequest } from "@/lib/worktrees/pendingDraftWorktree";
|
||||
|
||||
export type { AttachedFile, EditPermissionMode };
|
||||
export { MEMORY_LIMITS, ACTIVE_SESSION_WINDOW } from "./types/sessionTypes";
|
||||
@@ -242,7 +244,7 @@ export const useSessionStore = create<SessionStore>()(
|
||||
pendingInputText: null,
|
||||
pendingInputMode: 'replace',
|
||||
pendingSyntheticParts: null,
|
||||
newSessionDraft: { open: true, selectedProjectId: null, directoryOverride: null, parentID: null },
|
||||
newSessionDraft: { open: true, selectedProjectId: null, directoryOverride: null, pendingWorktreeRequestId: null, bootstrapPendingDirectory: null, preserveDirectoryOverride: false, parentID: null },
|
||||
|
||||
// Voice state (initialized to disconnected/idle)
|
||||
voiceStatus: 'disconnected',
|
||||
@@ -338,6 +340,9 @@ export const useSessionStore = create<SessionStore>()(
|
||||
open: true,
|
||||
selectedProjectId: selectedProject?.id ?? null,
|
||||
directoryOverride: directory,
|
||||
pendingWorktreeRequestId: options?.pendingWorktreeRequestId ?? null,
|
||||
bootstrapPendingDirectory: normalizePath(options?.bootstrapPendingDirectory ?? null),
|
||||
preserveDirectoryOverride: options?.preserveDirectoryOverride === true,
|
||||
parentID: options?.parentID ?? null,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
@@ -376,7 +381,52 @@ export const useSessionStore = create<SessionStore>()(
|
||||
}
|
||||
},
|
||||
|
||||
setNewSessionDraftTarget: ({ projectId, directoryOverride }) => {
|
||||
overrideNewSessionDraftTarget: (options) => {
|
||||
const projectsState = useProjectsStore.getState();
|
||||
const projects = projectsState.projects;
|
||||
const availableWorktreesByProject = get().availableWorktreesByProject;
|
||||
const explicitDirectory = normalizePath(options?.directoryOverride ?? null);
|
||||
const explicitProject = options?.projectId
|
||||
? projects.find((project) => project.id === options.projectId) ?? null
|
||||
: null;
|
||||
const inferredProject = resolveDraftProjectForDirectory(projects, availableWorktreesByProject, explicitDirectory);
|
||||
const fallbackProject = explicitProject ?? inferredProject ?? projectsState.getActiveProject() ?? projects[0] ?? null;
|
||||
const selectedProject = explicitProject ?? inferredProject ?? fallbackProject;
|
||||
const nextDirectory = explicitDirectory ?? normalizePath(selectedProject?.path ?? null);
|
||||
|
||||
persistDraftTarget({
|
||||
projectId: selectedProject?.id ?? null,
|
||||
directory: nextDirectory,
|
||||
});
|
||||
|
||||
set((state) => {
|
||||
const previousDraft = state.newSessionDraft;
|
||||
const hasPendingWorktreeRequestId = Object.prototype.hasOwnProperty.call(options, 'pendingWorktreeRequestId');
|
||||
const hasBootstrapPendingDirectory = Object.prototype.hasOwnProperty.call(options, 'bootstrapPendingDirectory');
|
||||
return {
|
||||
newSessionDraft: {
|
||||
...previousDraft,
|
||||
open: true,
|
||||
selectedProjectId: selectedProject?.id ?? null,
|
||||
directoryOverride: nextDirectory,
|
||||
pendingWorktreeRequestId: hasPendingWorktreeRequestId
|
||||
? (options.pendingWorktreeRequestId ?? null)
|
||||
: (previousDraft.pendingWorktreeRequestId ?? null),
|
||||
bootstrapPendingDirectory: hasBootstrapPendingDirectory
|
||||
? normalizePath(options.bootstrapPendingDirectory ?? null)
|
||||
: (previousDraft.bootstrapPendingDirectory ?? null),
|
||||
preserveDirectoryOverride: options?.preserveDirectoryOverride === true,
|
||||
title: options?.title ?? previousDraft.title,
|
||||
initialPrompt: options?.initialPrompt ?? previousDraft.initialPrompt,
|
||||
},
|
||||
currentSessionId: null,
|
||||
error: null,
|
||||
...(options?.initialPrompt ? { pendingInputText: options.initialPrompt, pendingInputMode: 'replace' as const } : {}),
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setNewSessionDraftTarget: ({ projectId, directoryOverride }, options) => {
|
||||
const projects = useProjectsStore.getState().projects;
|
||||
const project = projectId
|
||||
? projects.find((entry) => entry.id === projectId) ?? null
|
||||
@@ -385,6 +435,52 @@ export const useSessionStore = create<SessionStore>()(
|
||||
const normalizedProjectPath = normalizePath(project?.path ?? null);
|
||||
const nextDirectory = normalizedDirectory ?? normalizedProjectPath ?? null;
|
||||
|
||||
let didUpdate = false;
|
||||
set((state) => {
|
||||
if (!state.newSessionDraft?.open) {
|
||||
return state;
|
||||
}
|
||||
if (
|
||||
options?.force !== true
|
||||
&& (
|
||||
state.newSessionDraft.pendingWorktreeRequestId
|
||||
|| state.newSessionDraft.bootstrapPendingDirectory
|
||||
|| state.newSessionDraft.preserveDirectoryOverride
|
||||
)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
didUpdate = true;
|
||||
return {
|
||||
newSessionDraft: {
|
||||
...state.newSessionDraft,
|
||||
selectedProjectId: project?.id ?? null,
|
||||
directoryOverride: nextDirectory,
|
||||
pendingWorktreeRequestId: null,
|
||||
bootstrapPendingDirectory: null,
|
||||
preserveDirectoryOverride: false,
|
||||
parentID: null,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
if (didUpdate) {
|
||||
persistDraftTarget({
|
||||
projectId: project?.id ?? null,
|
||||
directory: nextDirectory,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
closeNewSessionDraft: () => {
|
||||
const realCurrentSessionId = useSessionManagementStore.getState().currentSessionId;
|
||||
set({
|
||||
newSessionDraft: { open: false, selectedProjectId: null, directoryOverride: null, pendingWorktreeRequestId: null, bootstrapPendingDirectory: null, preserveDirectoryOverride: false, parentID: null, title: undefined, initialPrompt: undefined, syntheticParts: undefined, targetFolderId: undefined },
|
||||
currentSessionId: realCurrentSessionId,
|
||||
});
|
||||
},
|
||||
|
||||
setPendingDraftWorktreeRequest: (requestId) => {
|
||||
set((state) => {
|
||||
if (!state.newSessionDraft?.open) {
|
||||
return state;
|
||||
@@ -392,24 +488,55 @@ export const useSessionStore = create<SessionStore>()(
|
||||
return {
|
||||
newSessionDraft: {
|
||||
...state.newSessionDraft,
|
||||
selectedProjectId: project?.id ?? null,
|
||||
directoryOverride: nextDirectory,
|
||||
parentID: null,
|
||||
pendingWorktreeRequestId: requestId,
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
persistDraftTarget({
|
||||
projectId: project?.id ?? null,
|
||||
directory: nextDirectory,
|
||||
resolvePendingDraftWorktreeTarget: (requestId, directory, options) => {
|
||||
set((state) => {
|
||||
if (!state.newSessionDraft?.open || state.newSessionDraft.pendingWorktreeRequestId !== requestId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
newSessionDraft: {
|
||||
...state.newSessionDraft,
|
||||
selectedProjectId: options?.projectId ?? state.newSessionDraft.selectedProjectId ?? null,
|
||||
directoryOverride: normalizePath(directory),
|
||||
pendingWorktreeRequestId: null,
|
||||
bootstrapPendingDirectory: normalizePath(options?.bootstrapPendingDirectory ?? state.newSessionDraft.bootstrapPendingDirectory ?? null),
|
||||
preserveDirectoryOverride: options?.preserveDirectoryOverride ?? true,
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
closeNewSessionDraft: () => {
|
||||
const realCurrentSessionId = useSessionManagementStore.getState().currentSessionId;
|
||||
set({
|
||||
newSessionDraft: { open: false, selectedProjectId: null, directoryOverride: null, parentID: null, title: undefined, initialPrompt: undefined, syntheticParts: undefined, targetFolderId: undefined },
|
||||
currentSessionId: realCurrentSessionId,
|
||||
setDraftBootstrapPendingDirectory: (directory) => {
|
||||
set((state) => {
|
||||
if (!state.newSessionDraft?.open) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
newSessionDraft: {
|
||||
...state.newSessionDraft,
|
||||
bootstrapPendingDirectory: normalizePath(directory),
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setDraftPreserveDirectoryOverride: (value) => {
|
||||
set((state) => {
|
||||
if (!state.newSessionDraft?.open) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
newSessionDraft: {
|
||||
...state.newSessionDraft,
|
||||
preserveDirectoryOverride: value,
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
@@ -579,9 +706,14 @@ export const useSessionStore = create<SessionStore>()(
|
||||
|
||||
if (draft?.open) {
|
||||
const draftTargetFolderId = draft.targetFolderId;
|
||||
const draftDirectoryOverride = draft.directoryOverride ?? null;
|
||||
let draftDirectoryOverride = draft.bootstrapPendingDirectory ?? draft.directoryOverride ?? null;
|
||||
const draftProjectId = draft.selectedProjectId ?? null;
|
||||
|
||||
if (draft.pendingWorktreeRequestId) {
|
||||
draftDirectoryOverride = await waitForPendingDraftWorktreeRequest(draft.pendingWorktreeRequestId);
|
||||
get().resolvePendingDraftWorktreeTarget(draft.pendingWorktreeRequestId, draftDirectoryOverride);
|
||||
}
|
||||
|
||||
const created = await useSessionManagementStore
|
||||
.getState()
|
||||
.createSession(draft.title, draftDirectoryOverride, draft.parentID ?? null);
|
||||
@@ -647,6 +779,7 @@ export const useSessionStore = create<SessionStore>()(
|
||||
const draftSyntheticParts = draft.syntheticParts;
|
||||
|
||||
get().closeNewSessionDraft();
|
||||
await get().setCurrentSession(created.id);
|
||||
|
||||
// Assign to target folder if session was created from folder's + button
|
||||
if (draftTargetFolderId) {
|
||||
@@ -663,6 +796,11 @@ export const useSessionStore = create<SessionStore>()(
|
||||
? [...(additionalParts || []), ...draftSyntheticParts]
|
||||
: additionalParts;
|
||||
|
||||
const createdDirectory = normalizePath(draftDirectoryOverride ?? created.directory ?? null);
|
||||
if (createdDirectory) {
|
||||
await waitForWorktreeBootstrap(createdDirectory);
|
||||
}
|
||||
|
||||
try {
|
||||
markPendingUserSendAnimation(created.id);
|
||||
return await useMessageStore
|
||||
@@ -715,6 +853,13 @@ export const useSessionStore = create<SessionStore>()(
|
||||
}
|
||||
}
|
||||
|
||||
const currentSessionDirectory = currentSessionId
|
||||
? normalizePath(useSessionManagementStore.getState().getDirectoryForSession(currentSessionId))
|
||||
: null;
|
||||
if (currentSessionDirectory) {
|
||||
await waitForWorktreeBootstrap(currentSessionDirectory);
|
||||
}
|
||||
|
||||
// Notify server that user sent a message in this session
|
||||
if (currentSessionId) {
|
||||
fetch(`/api/sessions/${currentSessionId}/message-sent`, { method: 'POST' })
|
||||
@@ -1268,6 +1413,10 @@ useDirectoryStore.subscribe((state, prevState) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (draft.pendingWorktreeRequestId || draft.bootstrapPendingDirectory || draft.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
|
||||
const draftDirectory = normalizePath(draft.directoryOverride);
|
||||
if (draftDirectory && draftDirectory !== prevDirectory) {
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user