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 { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
||||||
import { useGitBranches, useGitStore } from '@/stores/useGitStore';
|
import { useGitBranches, useGitStore } from '@/stores/useGitStore';
|
||||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||||
|
import { createWorktreeDraft } from '@/lib/worktreeSessionCreator';
|
||||||
import { usePermissionStore } from '@/stores/permissionStore';
|
import { usePermissionStore } from '@/stores/permissionStore';
|
||||||
|
|
||||||
const MAX_VISIBLE_TEXTAREA_LINES = 8;
|
const MAX_VISIBLE_TEXTAREA_LINES = 8;
|
||||||
@@ -2375,10 +2376,22 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
|||||||
}, [availableWorktreesByProject, projectRootBranchOption?.value, selectedDraftProject, selectedDraftProjectPath]);
|
}, [availableWorktreesByProject, projectRootBranchOption?.value, selectedDraftProject, selectedDraftProjectPath]);
|
||||||
|
|
||||||
const selectedDraftDirectory = React.useMemo(
|
const selectedDraftDirectory = React.useMemo(
|
||||||
() => normalizePath(newSessionDraft?.directoryOverride ?? null) ?? selectedDraftProjectPath,
|
() => normalizePath(newSessionDraft?.bootstrapPendingDirectory ?? null)
|
||||||
[newSessionDraft?.directoryOverride, selectedDraftProjectPath],
|
?? 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 draftBranchItems = React.useMemo(() => {
|
||||||
const baseItems: Array<{ value: string; label: string }> = [];
|
const baseItems: Array<{ value: string; label: string }> = [];
|
||||||
if (projectRootBranchOption) {
|
if (projectRootBranchOption) {
|
||||||
@@ -2392,11 +2405,14 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
|||||||
if (baseItems.some((option) => option.value === selectedDraftDirectory)) {
|
if (baseItems.some((option) => option.value === selectedDraftDirectory)) {
|
||||||
return baseItems;
|
return baseItems;
|
||||||
}
|
}
|
||||||
|
if (!shouldKeepMissingSelectedDraftDirectory) {
|
||||||
|
return baseItems;
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
...baseItems,
|
...baseItems,
|
||||||
{ value: selectedDraftDirectory, label: formatDirectoryName(selectedDraftDirectory) },
|
{ value: selectedDraftDirectory, label: formatDirectoryName(selectedDraftDirectory) },
|
||||||
];
|
];
|
||||||
}, [projectRootBranchOption, selectedDraftDirectory, worktreeBranchOptions]);
|
}, [projectRootBranchOption, selectedDraftDirectory, shouldKeepMissingSelectedDraftDirectory, worktreeBranchOptions]);
|
||||||
|
|
||||||
const selectedDraftBranchLabel = React.useMemo(() => {
|
const selectedDraftBranchLabel = React.useMemo(() => {
|
||||||
const selectedValue = selectedDraftDirectory ?? draftBranchItems[0]?.value ?? null;
|
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);
|
return worktreeBranchOptions.some((option) => option.value === selectedDraftDirectory);
|
||||||
}, [projectRootBranchOption?.value, selectedDraftDirectory, worktreeBranchOptions]);
|
}, [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(() => {
|
const shouldShowDraftBranchSelector = React.useMemo(() => {
|
||||||
if (isDiscoveringDraftBranches) {
|
if (isDiscoveringDraftBranches) {
|
||||||
return false;
|
return false;
|
||||||
@@ -2427,6 +2453,10 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
|||||||
}, [isDiscoveringDraftBranches, projectRootBranchOption, worktreeBranchOptions.length]);
|
}, [isDiscoveringDraftBranches, projectRootBranchOption, worktreeBranchOptions.length]);
|
||||||
|
|
||||||
const handleDraftProjectChange = React.useCallback((projectId: string) => {
|
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);
|
const project = projects.find((entry) => entry.id === projectId);
|
||||||
if (!project) {
|
if (!project) {
|
||||||
return;
|
return;
|
||||||
@@ -2437,17 +2467,21 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
|||||||
setNewSessionDraftTarget({
|
setNewSessionDraftTarget({
|
||||||
projectId,
|
projectId,
|
||||||
directoryOverride: project.path,
|
directoryOverride: project.path,
|
||||||
});
|
}, { force: true });
|
||||||
}, [activeProjectId, projects, setActiveProjectIdOnly, setNewSessionDraftTarget]);
|
}, [activeProjectId, projects, setActiveProjectIdOnly, setNewSessionDraftTarget]);
|
||||||
|
|
||||||
const handleDraftDirectoryChange = React.useCallback((directory: string) => {
|
const handleDraftDirectoryChange = React.useCallback((directory: string) => {
|
||||||
|
const draft = useSessionStore.getState().newSessionDraft;
|
||||||
|
if (draft?.pendingWorktreeRequestId || draft?.bootstrapPendingDirectory || draft?.preserveDirectoryOverride) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!selectedDraftProject) {
|
if (!selectedDraftProject) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setNewSessionDraftTarget({
|
setNewSessionDraftTarget({
|
||||||
projectId: selectedDraftProject.id,
|
projectId: selectedDraftProject.id,
|
||||||
directoryOverride: directory,
|
directoryOverride: directory,
|
||||||
});
|
}, { force: true });
|
||||||
}, [selectedDraftProject, setNewSessionDraftTarget]);
|
}, [selectedDraftProject, setNewSessionDraftTarget]);
|
||||||
|
|
||||||
const renderProjectLabelWithIcon = React.useCallback((project: {
|
const renderProjectLabelWithIcon = React.useCallback((project: {
|
||||||
@@ -2492,6 +2526,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
|||||||
if (!showDraftTargetSelectors || !selectedDraftProject || !selectedDraftDirectory) {
|
if (!showDraftTargetSelectors || !selectedDraftProject || !selectedDraftDirectory) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (newSessionDraft?.pendingWorktreeRequestId || newSessionDraft?.bootstrapPendingDirectory || newSessionDraft?.preserveDirectoryOverride) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const valid = draftBranchItems.some((option) => option.value === selectedDraftDirectory);
|
const valid = draftBranchItems.some((option) => option.value === selectedDraftDirectory);
|
||||||
if (valid) {
|
if (valid) {
|
||||||
return;
|
return;
|
||||||
@@ -2500,7 +2537,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
|||||||
projectId: selectedDraftProject.id,
|
projectId: selectedDraftProject.id,
|
||||||
directoryOverride: selectedDraftProject.path,
|
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 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');
|
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>
|
</SelectItem>
|
||||||
</SelectGroup>
|
</SelectGroup>
|
||||||
) : null}
|
) : null}
|
||||||
{worktreeBranchOptions.length > 0 ? (
|
{projectRootBranchOption ? <SelectSeparator /> : null}
|
||||||
<>
|
<SelectGroup>
|
||||||
{projectRootBranchOption ? <SelectSeparator /> : null}
|
<div className="flex items-center justify-between px-2 py-1.5">
|
||||||
<SelectGroup>
|
<span className="text-muted-foreground typography-meta">Worktrees</span>
|
||||||
<SelectLabel>Worktrees</SelectLabel>
|
<button
|
||||||
{worktreeBranchOptions.map((option) => (
|
type="button"
|
||||||
<SelectItem key={option.value} value={option.value} className="max-w-[24rem] truncate">
|
className="text-muted-foreground typography-meta hover:text-foreground cursor-pointer"
|
||||||
{option.label}
|
onPointerDown={(e) => { e.stopPropagation(); }}
|
||||||
</SelectItem>
|
onClick={(e) => { e.preventDefault(); e.stopPropagation(); void createWorktreeDraft(); }}
|
||||||
))}
|
>
|
||||||
</SelectGroup>
|
+ New
|
||||||
</>
|
</button>
|
||||||
) : null}
|
</div>
|
||||||
|
{worktreeBranchOptions.map((option) => (
|
||||||
|
<SelectItem key={option.value} value={option.value} className="max-w-[24rem] truncate">
|
||||||
|
{option.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectGroup>
|
||||||
{selectedDraftDirectory && !selectedDraftBranchIsKnown ? (
|
{selectedDraftDirectory && !selectedDraftBranchIsKnown ? (
|
||||||
<SelectItem value={selectedDraftDirectory} className="max-w-[24rem] truncate">
|
<SelectItem value={selectedDraftDirectory} className="max-w-[24rem] truncate">
|
||||||
{selectedDraftBranchLabel}
|
{selectedDraftBranchLabel}
|
||||||
|
|||||||
@@ -347,13 +347,13 @@ export const MessageFilesDisplay = memo(({ files, onShowPopup, compact = false }
|
|||||||
return filename || path;
|
return filename || path;
|
||||||
};
|
};
|
||||||
|
|
||||||
const resolveDisplayName = (file: FilePart): string => {
|
const resolveDisplayName = React.useCallback((file: FilePart): string => {
|
||||||
const isGitHubLink = getGitHubLinkKind(file) !== null;
|
const isGitHubLink = getGitHubLinkKind(file) !== null;
|
||||||
if (isGitHubLink && typeof file.filename === 'string' && file.filename.trim().length > 0) {
|
if (isGitHubLink && typeof file.filename === 'string' && file.filename.trim().length > 0) {
|
||||||
return file.filename.trim();
|
return file.filename.trim();
|
||||||
}
|
}
|
||||||
return extractFilename(file.filename || file.url);
|
return extractFilename(file.filename || file.url);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const formatFileSize = (bytes?: number) => {
|
const formatFileSize = (bytes?: number) => {
|
||||||
if (!bytes || !Number.isFinite(bytes) || bytes <= 0) return '';
|
if (!bytes || !Number.isFinite(bytes) || bytes <= 0) return '';
|
||||||
@@ -377,7 +377,7 @@ export const MessageFilesDisplay = memo(({ files, onShowPopup, compact = false }
|
|||||||
size: file.size,
|
size: file.size,
|
||||||
}];
|
}];
|
||||||
}),
|
}),
|
||||||
[imageFiles]
|
[imageFiles, resolveDisplayName]
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleImageClick = React.useCallback((index: number) => {
|
const handleImageClick = React.useCallback((index: number) => {
|
||||||
|
|||||||
@@ -592,7 +592,7 @@ export const Header: React.FC<HeaderProps> = ({
|
|||||||
if (!state.newSessionDraft?.open) {
|
if (!state.newSessionDraft?.open) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
return normalize(state.newSessionDraft.directoryOverride ?? '');
|
return normalize(state.newSessionDraft.bootstrapPendingDirectory ?? state.newSessionDraft.directoryOverride ?? '');
|
||||||
});
|
});
|
||||||
|
|
||||||
const openDirectory = React.useMemo(() => {
|
const openDirectory = React.useMemo(() => {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import { useEffectiveDirectory } from '@/hooks/useEffectiveDirectory';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { isDesktopShell } from '@/lib/desktop';
|
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
|
// Mobile drawer width as screen percentage
|
||||||
const MOBILE_DRAWER_WIDTH_PERCENT = 85;
|
const MOBILE_DRAWER_WIDTH_PERCENT = 85;
|
||||||
@@ -645,7 +645,7 @@ export const MainLayout: React.FC = () => {
|
|||||||
setRightSidebarOpen,
|
setRightSidebarOpen,
|
||||||
}}>
|
}}>
|
||||||
{/* Mobile: header + drawer mode */}
|
{/* Mobile: header + drawer mode */}
|
||||||
{!(isSettingsDialogOpen || isMultiRunLauncherOpen) && <Header
|
{!isSettingsDialogOpen && <Header
|
||||||
onToggleLeftDrawer={() => {
|
onToggleLeftDrawer={() => {
|
||||||
if (isRightSidebarOpen) {
|
if (isRightSidebarOpen) {
|
||||||
setRightSidebarOpen(false);
|
setRightSidebarOpen(false);
|
||||||
@@ -779,7 +779,7 @@ export const MainLayout: React.FC = () => {
|
|||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex flex-1 overflow-hidden relative',
|
'flex flex-1 overflow-hidden relative',
|
||||||
(isSettingsDialogOpen || isMultiRunLauncherOpen) && 'hidden'
|
isSettingsDialogOpen && 'hidden'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<main className="w-full h-full overflow-hidden bg-background relative">
|
<main className="w-full h-full overflow-hidden bg-background relative">
|
||||||
@@ -791,25 +791,20 @@ export const MainLayout: React.FC = () => {
|
|||||||
<ErrorBoundary>{secondaryView}</ErrorBoundary>
|
<ErrorBoundary>{secondaryView}</ErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{isMultiRunLauncherOpen && (
|
||||||
|
<div className="absolute inset-0 z-10 bg-background">
|
||||||
|
<ErrorBoundary>
|
||||||
|
<MultiRunLauncher
|
||||||
|
initialPrompt={multiRunLauncherPrefillPrompt}
|
||||||
|
onCreated={() => setMultiRunLauncherOpen(false)}
|
||||||
|
onCancel={() => setMultiRunLauncherOpen(false)}
|
||||||
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</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 */}
|
{/* Mobile settings: full screen */}
|
||||||
{isSettingsDialogOpen && (
|
{isSettingsDialogOpen && (
|
||||||
<div
|
<div
|
||||||
@@ -828,8 +823,7 @@ export const MainLayout: React.FC = () => {
|
|||||||
'absolute inset-0 flex overflow-hidden',
|
'absolute inset-0 flex overflow-hidden',
|
||||||
isDesktopShellRuntime
|
isDesktopShellRuntime
|
||||||
? 'bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]'
|
? 'bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]'
|
||||||
: 'bg-sidebar',
|
: 'bg-sidebar'
|
||||||
isMultiRunLauncherOpen && 'invisible'
|
|
||||||
)}>
|
)}>
|
||||||
{isSidebarOpen ? (
|
{isSidebarOpen ? (
|
||||||
<>
|
<>
|
||||||
@@ -951,18 +945,6 @@ export const MainLayout: React.FC = () => {
|
|||||||
</RightSidebar>
|
</RightSidebar>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
|
|
||||||
{/* Desktop settings: windowed dialog with blur */}
|
{/* Desktop settings: windowed dialog with blur */}
|
||||||
@@ -970,6 +952,11 @@ export const MainLayout: React.FC = () => {
|
|||||||
open={isSettingsDialogOpen}
|
open={isSettingsDialogOpen}
|
||||||
onOpenChange={setSettingsDialogOpen}
|
onOpenChange={setSettingsDialogOpen}
|
||||||
/>
|
/>
|
||||||
|
<MultiRunWindow
|
||||||
|
open={isMultiRunLauncherOpen}
|
||||||
|
onOpenChange={setMultiRunLauncherOpen}
|
||||||
|
initialPrompt={multiRunLauncherPrefillPrompt}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
import { useConfigStore } from '@/stores/useConfigStore';
|
import { useConfigStore } from '@/stores/useConfigStore';
|
||||||
|
|
||||||
export interface AgentSelectorProps {
|
export interface AgentSelectorProps {
|
||||||
@@ -85,7 +86,14 @@ export const AgentSelector: React.FC<AgentSelectorProps> = ({
|
|||||||
<SelectTrigger
|
<SelectTrigger
|
||||||
id={id}
|
id={id}
|
||||||
size="lg"
|
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" />
|
<SelectValue placeholder="Select an agent" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
|
|||||||
@@ -9,8 +9,12 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
import { checkIsGitRepository, getGitBranches } from '@/lib/gitApi';
|
import { useGitStore, useGitBranches } from '@/stores/useGitStore';
|
||||||
import { resolveRootTrackingRemote } from '@/lib/worktrees/worktreeCreate';
|
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 = {
|
export type WorktreeBaseOption = {
|
||||||
value: string;
|
value: string;
|
||||||
@@ -34,125 +38,60 @@ export interface BranchSelectorProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface BranchSelectorState {
|
export interface BranchSelectorState {
|
||||||
branches: WorktreeBaseOption[];
|
localBranches: string[];
|
||||||
|
remoteBranches: string[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
isGitRepository: boolean | null;
|
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.
|
* 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
|
// eslint-disable-next-line react-refresh/only-export-components -- Hook is tightly coupled with BranchSelector
|
||||||
export function useBranchOptions(directory: string | null): BranchSelectorState {
|
export function useBranchOptions(directory: string | null): BranchSelectorState {
|
||||||
const [branches, setBranches] = React.useState<WorktreeBaseOption[]>([
|
const { git } = useRuntimeAPIs();
|
||||||
{ value: 'HEAD', label: 'Current (HEAD)', group: 'special' },
|
const branches = useGitBranches(directory);
|
||||||
]);
|
const isLoading = useGitStore((state) => state.isLoadingBranches);
|
||||||
const [isLoading, setIsLoading] = React.useState(false);
|
const fetchBranches = useGitStore((state) => state.fetchBranches);
|
||||||
const [isGitRepository, setIsGitRepository] = React.useState<boolean | null>(null);
|
|
||||||
|
|
||||||
|
// Fetch branches if not cached
|
||||||
React.useEffect(() => {
|
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) {
|
// Compute local and remote branch lists (same as NewWorktreeDialog)
|
||||||
setIsGitRepository(null);
|
const localBranches = React.useMemo(() => {
|
||||||
setIsLoading(false);
|
if (!branches?.all) return [];
|
||||||
setBranches([{ value: 'HEAD', label: 'Current (HEAD)', group: 'special' }]);
|
return branches.all
|
||||||
return;
|
.filter((branchName: string) => !branchName.startsWith('remotes/'))
|
||||||
}
|
.sort();
|
||||||
|
}, [branches]);
|
||||||
|
|
||||||
setIsLoading(true);
|
const remoteBranches = React.useMemo(() => {
|
||||||
setIsGitRepository(null);
|
if (!branches?.all) return [];
|
||||||
|
return branches.all
|
||||||
|
.filter((branchName: string) => branchName.startsWith('remotes/'))
|
||||||
|
.map((branchName: string) => branchName.replace(/^remotes\//, ''))
|
||||||
|
.sort();
|
||||||
|
}, [branches]);
|
||||||
|
|
||||||
(async () => {
|
// isGitRepository: true if we got branches, false if fetch returned empty, null if not yet loaded
|
||||||
try {
|
const isGitRepository = React.useMemo<boolean | null>(() => {
|
||||||
const isGit = await checkIsGitRepository(directory);
|
if (!directory) return null;
|
||||||
if (cancelled) return;
|
if (isLoading) return null;
|
||||||
|
if (!branches) return null;
|
||||||
|
return Boolean(branches.all);
|
||||||
|
}, [directory, isLoading, branches]);
|
||||||
|
|
||||||
setIsGitRepository(isGit);
|
return { localBranches, remoteBranches, isLoading, isGitRepository };
|
||||||
|
|
||||||
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 };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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> = ({
|
export const BranchSelector: React.FC<BranchSelectorProps> = ({
|
||||||
directory,
|
directory,
|
||||||
@@ -162,23 +101,46 @@ export const BranchSelector: React.FC<BranchSelectorProps> = ({
|
|||||||
disabled,
|
disabled,
|
||||||
id,
|
id,
|
||||||
}) => {
|
}) => {
|
||||||
const { branches, isLoading, isGitRepository } = useBranchOptions(directory);
|
const { localBranches, remoteBranches, isLoading, isGitRepository } = useBranchOptions(directory);
|
||||||
const selectedLabel = React.useMemo(() => {
|
const allBranches = React.useMemo(
|
||||||
return branches.find((option) => option.value === value)?.label ?? null;
|
() => [...localBranches, ...remoteBranches.map(b => `remotes/${b}`)],
|
||||||
}, [branches, value]);
|
[localBranches, remoteBranches],
|
||||||
|
);
|
||||||
|
|
||||||
// Update value if it's no longer valid
|
// Resolve default source branch (same priority as NewWorktreeDialog)
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const isValid = branches.some((option) => option.value === value);
|
if (disabled || isLoading || allBranches.length === 0) return;
|
||||||
if (!isValid && branches.length > 0) {
|
// If current value is valid, keep it
|
||||||
onChange('HEAD');
|
if (value && allBranches.includes(value)) return;
|
||||||
}
|
|
||||||
}, [branches, value, onChange]);
|
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;
|
const isDisabled = disabled || !isGitRepository || isLoading;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Select
|
<Select
|
||||||
value={value}
|
value={value}
|
||||||
onValueChange={onChange}
|
onValueChange={onChange}
|
||||||
@@ -187,62 +149,51 @@ export const BranchSelector: React.FC<BranchSelectorProps> = ({
|
|||||||
<SelectTrigger
|
<SelectTrigger
|
||||||
id={id}
|
id={id}
|
||||||
size="lg"
|
size="lg"
|
||||||
className={className ?? 'max-w-full typography-meta text-foreground'}
|
className={className ?? 'w-fit typography-meta text-foreground'}
|
||||||
>
|
>
|
||||||
{selectedLabel ? (
|
<SelectValue placeholder={isLoading ? 'Loading branches…' : 'Select source branch...'} />
|
||||||
<SelectValue>{selectedLabel}</SelectValue>
|
|
||||||
) : (
|
|
||||||
<SelectValue placeholder={isLoading ? 'Loading branches…' : 'Select a branch'} />
|
|
||||||
)}
|
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent fitContent>
|
<SelectContent className="max-h-[280px] max-w-[320px]">
|
||||||
<SelectGroup>
|
{isLoading ? (
|
||||||
<SelectLabel>Default</SelectLabel>
|
<div className="px-2 py-4 text-center typography-meta text-muted-foreground">
|
||||||
{branches
|
Loading branches...
|
||||||
.filter((option) => option.group === 'special')
|
</div>
|
||||||
.map((option) => (
|
) : localBranches.length === 0 && remoteBranches.length === 0 ? (
|
||||||
<SelectItem key={option.value} value={option.value} className="w-auto whitespace-nowrap">
|
<div className="px-2 py-4 text-center typography-meta text-muted-foreground">
|
||||||
{option.label}
|
No branches found
|
||||||
</SelectItem>
|
</div>
|
||||||
))}
|
) : (
|
||||||
</SelectGroup>
|
|
||||||
|
|
||||||
{branches.some((option) => option.group === 'local') ? (
|
|
||||||
<>
|
<>
|
||||||
<SelectSeparator />
|
{localBranches.length > 0 && (
|
||||||
<SelectGroup>
|
<SelectGroup>
|
||||||
<SelectLabel>Local branches</SelectLabel>
|
<SelectLabel className="font-semibold text-foreground">Local branches</SelectLabel>
|
||||||
{branches
|
{localBranches.map((branch) => (
|
||||||
.filter((option) => option.group === 'local')
|
<SelectItem key={branch} value={branch} className="whitespace-normal break-all">
|
||||||
.map((option) => (
|
{branch}
|
||||||
<SelectItem key={option.value} value={option.value} className="w-auto whitespace-nowrap">
|
|
||||||
{option.label}
|
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectGroup>
|
</SelectGroup>
|
||||||
</>
|
)}
|
||||||
) : null}
|
{localBranches.length > 0 && remoteBranches.length > 0 && (
|
||||||
|
<SelectSeparator />
|
||||||
{branches.some((option) => option.group === 'remote') ? (
|
)}
|
||||||
<>
|
{remoteBranches.length > 0 && (
|
||||||
<SelectSeparator />
|
<SelectGroup>
|
||||||
<SelectGroup>
|
<SelectLabel className="font-semibold text-foreground">Remote branches</SelectLabel>
|
||||||
<SelectLabel>Remote branches</SelectLabel>
|
{remoteBranches.map((branch) => (
|
||||||
{branches
|
<SelectItem key={`remotes/${branch}`} value={`remotes/${branch}`} className="whitespace-normal break-all">
|
||||||
.filter((option) => option.group === 'remote')
|
{branch}
|
||||||
.map((option) => (
|
|
||||||
<SelectItem key={option.value} value={option.value} className="w-auto whitespace-nowrap">
|
|
||||||
{option.label}
|
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectGroup>
|
</SelectGroup>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
) : null}
|
)}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
{isGitRepository === false && (
|
{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>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -97,6 +97,8 @@ export interface ModelMultiSelectProps {
|
|||||||
showChips?: boolean;
|
showChips?: boolean;
|
||||||
/** Maximum models allowed */
|
/** Maximum models allowed */
|
||||||
maxModels?: number;
|
maxModels?: number;
|
||||||
|
/** Optional className for add model trigger button */
|
||||||
|
addButtonClassName?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -111,6 +113,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
addButtonLabel = 'Add model',
|
addButtonLabel = 'Add model',
|
||||||
showChips = true,
|
showChips = true,
|
||||||
maxModels,
|
maxModels,
|
||||||
|
addButtonClassName,
|
||||||
}) => {
|
}) => {
|
||||||
const { providers, modelsMetadata } = useConfigStore();
|
const { providers, modelsMetadata } = useConfigStore();
|
||||||
const { favoriteModelsList, recentModelsList } = useModelLists();
|
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;
|
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(() => {
|
React.useEffect(() => {
|
||||||
if (isOpen && triggerRef.current) {
|
if (!isOpen || !triggerRef.current) return;
|
||||||
const rect = triggerRef.current.getBoundingClientRect();
|
|
||||||
// Space above trigger minus padding from top edge
|
const triggerRect = triggerRef.current.getBoundingClientRect();
|
||||||
const spaceAbove = rect.top - 100;
|
|
||||||
// Cap at 400px max, minimum 150px
|
// Find the nearest dialog or overflow ancestor to constrain within
|
||||||
setAvailableHeight(Math.max(150, Math.min(400, spaceAbove)));
|
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]);
|
}, [isOpen]);
|
||||||
|
|
||||||
// Focus search input when opened
|
// Focus search input when opened
|
||||||
@@ -308,7 +325,15 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
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)}
|
onClick={() => setIsOpen(!isOpen)}
|
||||||
>
|
>
|
||||||
<RiAddLine className="h-3.5 w-3.5 mr-1" />
|
<RiAddLine className="h-3.5 w-3.5 mr-1" />
|
||||||
@@ -379,7 +404,12 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
let currentFlatIndex = 0;
|
let currentFlatIndex = 0;
|
||||||
|
|
||||||
return (
|
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 */}
|
{/* Search input */}
|
||||||
<div className="p-2 border-b border-border/40">
|
<div className="p-2 border-b border-border/40">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
@@ -411,10 +441,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
{/* Favorites Section */}
|
{/* Favorites Section */}
|
||||||
{filteredFavorites.length > 0 && (
|
{filteredFavorites.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<div
|
<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))]">
|
||||||
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"
|
|
||||||
>
|
|
||||||
<RiStarFill className="h-4 w-4 text-primary" />
|
<RiStarFill className="h-4 w-4 text-primary" />
|
||||||
Favorites
|
Favorites
|
||||||
</div>
|
</div>
|
||||||
@@ -429,10 +456,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
{filteredRecents.length > 0 && (
|
{filteredRecents.length > 0 && (
|
||||||
<>
|
<>
|
||||||
{filteredFavorites.length > 0 && <div className="h-px bg-border/40 my-1" />}
|
{filteredFavorites.length > 0 && <div className="h-px bg-border/40 my-1" />}
|
||||||
<div
|
<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))]">
|
||||||
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"
|
|
||||||
>
|
|
||||||
<RiTimeLine className="h-4 w-4" />
|
<RiTimeLine className="h-4 w-4" />
|
||||||
Recent
|
Recent
|
||||||
</div>
|
</div>
|
||||||
@@ -452,7 +476,7 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
{filteredProviders.map((provider, index) => (
|
{filteredProviders.map((provider, index) => (
|
||||||
<React.Fragment key={provider.id}>
|
<React.Fragment key={provider.id}>
|
||||||
{index > 0 && <div className="h-px bg-border/40 my-1" />}
|
{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
|
<ProviderLogo
|
||||||
providerId={provider.id}
|
providerId={provider.id}
|
||||||
className="h-4 w-4 flex-shrink-0"
|
className="h-4 w-4 flex-shrink-0"
|
||||||
@@ -513,7 +537,14 @@ export const ModelMultiSelect: React.FC<ModelMultiSelectProps> = ({
|
|||||||
onUpdate(index, { ...model, variant: nextVariant });
|
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
|
<RiBrainAi3Line
|
||||||
className={cn(
|
className={cn(
|
||||||
'h-3.5 w-3.5 flex-shrink-0',
|
'h-3.5 w-3.5 flex-shrink-0',
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import React from 'react';
|
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 { toast } from '@/components/ui';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
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 { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||||
import { useMultiRunStore } from '@/stores/useMultiRunStore';
|
import { useMultiRunStore } from '@/stores/useMultiRunStore';
|
||||||
import { useSessionStore } from '@/stores/useSessionStore';
|
import { useSessionStore } from '@/stores/useSessionStore';
|
||||||
@@ -18,6 +20,9 @@ import { ModelMultiSelect, generateInstanceId, type ModelSelectionWithId } from
|
|||||||
import { BranchSelector, useBranchOptions } from './BranchSelector';
|
import { BranchSelector, useBranchOptions } from './BranchSelector';
|
||||||
import { AgentSelector } from './AgentSelector';
|
import { AgentSelector } from './AgentSelector';
|
||||||
import { isDesktopShell } from '@/lib/desktop';
|
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) */
|
/** Max file size in bytes (10MB) */
|
||||||
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||||
@@ -41,16 +46,49 @@ interface MultiRunLauncherProps {
|
|||||||
onCreated?: () => void;
|
onCreated?: () => void;
|
||||||
/** Called when user cancels */
|
/** Called when user cancels */
|
||||||
onCancel?: () => void;
|
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.
|
* 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> = ({
|
export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
||||||
initialPrompt,
|
initialPrompt,
|
||||||
onCreated,
|
onCreated,
|
||||||
onCancel,
|
onCancel,
|
||||||
|
isWindowed = false,
|
||||||
}) => {
|
}) => {
|
||||||
const [name, setName] = React.useState('');
|
const [name, setName] = React.useState('');
|
||||||
const [prompt, setPrompt] = React.useState(() => initialPrompt ?? '');
|
const [prompt, setPrompt] = React.useState(() => initialPrompt ?? '');
|
||||||
@@ -64,6 +102,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const currentDirectory = useDirectoryStore((state) => state.currentDirectory ?? null);
|
const currentDirectory = useDirectoryStore((state) => state.currentDirectory ?? null);
|
||||||
|
const homeDirectory = useDirectoryStore((state) => state.homeDirectory ?? null);
|
||||||
|
|
||||||
const vscodeWorkspaceFolder = React.useMemo(() => {
|
const vscodeWorkspaceFolder = React.useMemo(() => {
|
||||||
if (typeof window === 'undefined') {
|
if (typeof window === 'undefined') {
|
||||||
@@ -75,13 +114,72 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
|
|
||||||
// Get project directory for setup commands
|
// Get project directory for setup commands
|
||||||
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
|
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
|
||||||
|
const setActiveProjectIdOnly = useProjectsStore((state) => state.setActiveProjectIdOnly);
|
||||||
const projects = useProjectsStore((state) => state.projects);
|
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) {
|
if (activeProjectId) {
|
||||||
const project = projects.find((p) => p.id === activeProjectId);
|
setSelectedProjectId(activeProjectId);
|
||||||
if (project?.path) {
|
return;
|
||||||
return { id: project.id, path: project.path };
|
}
|
||||||
}
|
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;
|
const base = currentDirectory ?? vscodeWorkspaceFolder;
|
||||||
@@ -90,7 +188,7 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return { id: `path:${base}`, path: base };
|
return { id: `path:${base}`, path: base };
|
||||||
}, [activeProjectId, projects, currentDirectory, vscodeWorkspaceFolder]);
|
}, [selectedProject, currentDirectory, vscodeWorkspaceFolder]);
|
||||||
|
|
||||||
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
|
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
|
||||||
if (typeof window === 'undefined') {
|
if (typeof window === 'undefined') {
|
||||||
@@ -193,8 +291,8 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
}, [onCancel]);
|
}, [onCancel]);
|
||||||
|
|
||||||
// Use the BranchSelector hook for branch state management
|
// Use the BranchSelector hook for branch state management
|
||||||
const [worktreeBaseBranch, setWorktreeBaseBranch] = React.useState<string>('HEAD');
|
const [worktreeBaseBranch, setWorktreeBaseBranch] = React.useState<string>('');
|
||||||
const { isLoading: isLoadingWorktreeBaseBranches, isGitRepository } = useBranchOptions(currentDirectory);
|
const { isLoading: isLoadingWorktreeBaseBranches, isGitRepository } = useBranchOptions(selectedProjectDirectory);
|
||||||
|
|
||||||
const createMultiRun = useMultiRunStore((state) => state.createMultiRun);
|
const createMultiRun = useMultiRunStore((state) => state.createMultiRun);
|
||||||
const error = useMultiRunStore((state) => state.error);
|
const error = useMultiRunStore((state) => state.error);
|
||||||
@@ -311,6 +409,10 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
clearError();
|
clearError();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (selectedProjectId && selectedProjectId !== activeProjectId) {
|
||||||
|
setActiveProjectIdOnly(selectedProjectId);
|
||||||
|
}
|
||||||
|
|
||||||
// Strip instanceId before passing to store (UI-only field)
|
// Strip instanceId before passing to store (UI-only field)
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
const modelsForStore: MultiRunModelSelection[] = selectedModels.map(({ instanceId: _instanceId, ...rest }) => rest);
|
const modelsForStore: MultiRunModelSelection[] = selectedModels.map(({ instanceId: _instanceId, ...rest }) => rest);
|
||||||
@@ -350,254 +452,275 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isValid = Boolean(
|
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 (
|
return (
|
||||||
<div className="flex flex-col h-full bg-background">
|
<form onSubmit={handleSubmit} className="flex flex-col h-full bg-background" data-keyboard-avoid="true">
|
||||||
{/* Header - same height as app header (h-12 = 48px) */}
|
{!isWindowed ? (
|
||||||
<header
|
<header
|
||||||
onMouseDown={handleDragStart}
|
onMouseDown={handleDragStart}
|
||||||
className={cn(
|
className={cn(
|
||||||
'relative flex h-12 items-center justify-center border-b app-region-drag select-none',
|
'relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none',
|
||||||
desktopHeaderPaddingClass,
|
desktopHeaderPaddingClass,
|
||||||
macosHeaderSizeClass,
|
macosHeaderSizeClass,
|
||||||
)}
|
)}
|
||||||
style={{ borderColor: 'var(--interactive-border)' }}
|
style={{ borderColor: 'var(--interactive-border)' }}
|
||||||
>
|
>
|
||||||
<h1 className="typography-ui-label font-medium">New Multi-Run</h1>
|
<h1 className="typography-ui-label font-medium">New Multi-Run</h1>
|
||||||
{onCancel && (
|
{onCancel && (
|
||||||
<div className="absolute right-0 flex items-center pr-3">
|
<div className="absolute right-0 flex items-center pr-3">
|
||||||
<Tooltip delayDuration={500}>
|
<Tooltip delayDuration={500}>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onCancel}
|
onClick={onCancel}
|
||||||
aria-label="Close (Esc)"
|
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"
|
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" />
|
<RiCloseLine className="h-5 w-5" />
|
||||||
</button>
|
</button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>
|
<TooltipContent>
|
||||||
<p>Close (Esc)</p>
|
<p>Close (Esc)</p>
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</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>
|
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{/* Worktree creation */}
|
{/* Scrollable content */}
|
||||||
<div className="space-y-3">
|
<ScrollShadow className="flex-1 min-h-0 overflow-auto" size={64} hideTopShadow>
|
||||||
<div className="space-y-1">
|
<div className="mx-auto w-full max-w-2xl px-4 sm:px-6 py-5">
|
||||||
<p className="typography-ui-label font-medium text-foreground">Worktrees</p>
|
<div className="flex flex-col gap-5">
|
||||||
<p className="typography-micro text-muted-foreground">
|
|
||||||
Create one worktree per model by creating a new branch from a base branch.
|
{/* ── Config grid: 2-column on sm+, single column on narrow ── */}
|
||||||
</p>
|
<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>
|
||||||
|
|
||||||
<div className="space-y-2">
|
{/* Group name */}
|
||||||
<label
|
<div className="flex flex-col gap-1">
|
||||||
className="typography-meta font-medium text-foreground"
|
<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"
|
htmlFor="multirun-worktree-base-branch"
|
||||||
|
info={<InfoTip>New branch created from this base per model</InfoTip>}
|
||||||
>
|
>
|
||||||
Base branch
|
Base branch
|
||||||
</label>
|
</FieldLabel>
|
||||||
<BranchSelector
|
<BranchSelector
|
||||||
directory={currentDirectory}
|
directory={selectedProjectDirectory}
|
||||||
value={worktreeBaseBranch}
|
value={worktreeBaseBranch}
|
||||||
onChange={setWorktreeBaseBranch}
|
onChange={setWorktreeBaseBranch}
|
||||||
id="multirun-worktree-base-branch"
|
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>
|
</div>
|
||||||
|
|
||||||
{/* Setup commands collapsible */}
|
{/* Agent */}
|
||||||
<Collapsible open={isSetupCommandsOpen} onOpenChange={setIsSetupCommandsOpen}>
|
<div className="flex flex-col gap-1">
|
||||||
<CollapsibleTrigger className="w-full flex items-center justify-between py-1 hover:bg-[var(--interactive-hover)] rounded-md px-1 -mx-1 transition-colors">
|
<FieldLabel
|
||||||
<p className="typography-ui-label font-medium text-foreground">
|
htmlFor="multirun-agent"
|
||||||
Setup commands
|
info={<InfoTip>Agent used for all runs. Defaults to your configured agent.</InfoTip>}
|
||||||
{setupCommands.filter(cmd => cmd.trim()).length > 0 && (
|
>
|
||||||
<span className="font-normal text-muted-foreground/70">
|
Agent
|
||||||
{' '}({setupCommands.filter(cmd => cmd.trim()).length} configured)
|
</FieldLabel>
|
||||||
</span>
|
<AgentSelector
|
||||||
)}
|
value={selectedAgent}
|
||||||
</p>
|
onChange={setSelectedAgent}
|
||||||
<RiArrowDownSLine className={cn(
|
id="multirun-agent"
|
||||||
'h-4 w-4 text-muted-foreground transition-transform duration-200',
|
/>
|
||||||
isSetupCommandsOpen && 'rotate-180'
|
</div>
|
||||||
)} />
|
|
||||||
</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>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Agent selection */}
|
{/* ── Setup commands (collapsible, full width) ── */}
|
||||||
<div className="space-y-2">
|
<Collapsible open={isSetupCommandsOpen} onOpenChange={setIsSetupCommandsOpen}>
|
||||||
<label
|
<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">
|
||||||
className="typography-ui-label font-medium text-foreground"
|
<RiTerminalLine className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||||
htmlFor="multirun-agent"
|
<span className="typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors">
|
||||||
>
|
Setup commands
|
||||||
Agent
|
</span>
|
||||||
</label>
|
{configuredSetupCount > 0 && (
|
||||||
<AgentSelector
|
<span
|
||||||
value={selectedAgent}
|
className="inline-flex items-center justify-center h-4 min-w-4 px-1 rounded-full typography-micro font-medium"
|
||||||
onChange={setSelectedAgent}
|
style={{
|
||||||
id="multirun-agent"
|
backgroundColor: 'var(--primary-base)',
|
||||||
/>
|
color: 'var(--primary-foreground)',
|
||||||
<p className="typography-micro text-muted-foreground">
|
fontSize: '0.625rem',
|
||||||
Defaults to your configured default agent.
|
lineHeight: 1,
|
||||||
</p>
|
}}
|
||||||
</div>
|
>
|
||||||
|
{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 */}
|
{/* ── Prompt ── */}
|
||||||
<div className="space-y-2">
|
<div className="flex flex-col gap-1.5">
|
||||||
<label htmlFor="prompt" className="typography-ui-label font-medium text-foreground">
|
<FieldLabel htmlFor="prompt" required>Prompt</FieldLabel>
|
||||||
Prompt <span className="text-destructive">*</span>
|
|
||||||
</label>
|
|
||||||
<Textarea
|
<Textarea
|
||||||
id="prompt"
|
id="prompt"
|
||||||
value={prompt}
|
value={prompt}
|
||||||
onChange={(e) => setPrompt(e.target.value)}
|
onChange={(e) => setPrompt(e.target.value)}
|
||||||
placeholder="Enter the prompt to send to all models..."
|
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
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* File attachments */}
|
{/* File attachments inline */}
|
||||||
<div className="space-y-2">
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
<div className="flex items-center gap-2">
|
<input
|
||||||
<label className="typography-ui-label font-medium text-foreground">
|
ref={fileInputRef}
|
||||||
Attachments
|
type="file"
|
||||||
</label>
|
multiple
|
||||||
<span className="typography-micro text-muted-foreground">(optional, same files for all runs)</span>
|
className="hidden"
|
||||||
</div>
|
onChange={handleFileSelect}
|
||||||
|
accept="*/*"
|
||||||
<input
|
/>
|
||||||
ref={fileInputRef}
|
<Tooltip delayDuration={300}>
|
||||||
type="file"
|
<TooltipTrigger asChild>
|
||||||
multiple
|
<button
|
||||||
className="hidden"
|
type="button"
|
||||||
onChange={handleFileSelect}
|
onClick={() => fileInputRef.current?.click()}
|
||||||
accept="*/*"
|
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" />
|
||||||
<div className="flex flex-wrap gap-2 items-center">
|
Attach
|
||||||
<Button
|
</button>
|
||||||
type="button"
|
</TooltipTrigger>
|
||||||
variant="outline"
|
<TooltipContent>Same files sent to all runs</TooltipContent>
|
||||||
size="sm"
|
</Tooltip>
|
||||||
className="h-7"
|
|
||||||
onClick={() => fileInputRef.current?.click()}
|
|
||||||
>
|
|
||||||
<RiAttachment2 className="h-3.5 w-3.5 mr-1.5" />
|
|
||||||
Attach files
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{attachedFiles.map((file) => (
|
{attachedFiles.map((file) => (
|
||||||
<div
|
<div
|
||||||
key={file.id}
|
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/') ? (
|
{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}
|
{file.filename}
|
||||||
</span>
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => handleRemoveFile(file.id)}
|
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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Model selection */}
|
{/* ── Models ── */}
|
||||||
<div className="space-y-2">
|
<div className="flex flex-col gap-1.5">
|
||||||
<label className="typography-ui-label font-medium text-foreground">
|
<FieldLabel
|
||||||
Models <span className="text-destructive">*</span>
|
required
|
||||||
</label>
|
info={<InfoTip>Select 2–{MAX_MODELS} models. Same model can be added multiple times.</InfoTip>}
|
||||||
|
>
|
||||||
|
Models
|
||||||
|
</FieldLabel>
|
||||||
<ModelMultiSelect
|
<ModelMultiSelect
|
||||||
selectedModels={selectedModels}
|
selectedModels={selectedModels}
|
||||||
onAdd={handleAddModel}
|
onAdd={handleAddModel}
|
||||||
@@ -608,38 +731,48 @@ export const MultiRunLauncher: React.FC<MultiRunLauncherProps> = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error message */}
|
{/* ── Error ── */}
|
||||||
{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}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ScrollShadow>
|
||||||
|
|
||||||
{/* Action buttons */}
|
{/* ── Fixed footer ── */}
|
||||||
<div className="flex items-center justify-end gap-3 pt-4">
|
<div className="shrink-0 px-4 sm:px-6 py-3">
|
||||||
<Button
|
<div className="mx-auto w-full max-w-2xl flex items-center justify-end gap-2">
|
||||||
type="button"
|
<Button
|
||||||
variant="outline"
|
type="button"
|
||||||
onClick={onCancel}
|
variant="ghost"
|
||||||
>
|
size="sm"
|
||||||
Cancel
|
onClick={onCancel}
|
||||||
</Button>
|
>
|
||||||
<Button
|
Cancel
|
||||||
type="submit"
|
</Button>
|
||||||
disabled={!isValid || isSubmitting}
|
<Button
|
||||||
>
|
type="submit"
|
||||||
{isSubmitting ? (
|
size="sm"
|
||||||
'Creating...'
|
disabled={!isValid || isSubmitting}
|
||||||
) : (
|
>
|
||||||
<>
|
{isSubmitting ? (
|
||||||
Start ({selectedModels.length} models)
|
'Creating...'
|
||||||
</>
|
) : (
|
||||||
)}
|
<>Start ({selectedModels.length} models)</>
|
||||||
</Button>
|
)}
|
||||||
</div>
|
</Button>
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</form>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -868,14 +868,10 @@ Nice-to-have:
|
|||||||
}
|
}
|
||||||
|
|
||||||
toast.success('Worktree created', {
|
toast.success('Worktree created', {
|
||||||
description: `${metadata.branch || metadata.name}${sourceLabel ? ` from ${sourceLabel}` : ''}`,
|
description: `${metadata.branch || metadata.name}${sourceLabel ? ` from ${sourceLabel}` : ''} - bootstrapping in background`,
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
void loadSessions().catch(() => undefined);
|
||||||
await loadSessions();
|
|
||||||
} catch {
|
|
||||||
// best effort
|
|
||||||
}
|
|
||||||
|
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import {
|
|||||||
} from '@/lib/openchamberConfig';
|
} from '@/lib/openchamberConfig';
|
||||||
import { useUIStore } from '@/stores/useUIStore';
|
import { useUIStore } from '@/stores/useUIStore';
|
||||||
import { useSessionStore } from '@/stores/useSessionStore';
|
import { useSessionStore } from '@/stores/useSessionStore';
|
||||||
import { createWorktreeOnly } from '@/lib/worktreeSessionCreator';
|
import { createWorktreeDraft } from '@/lib/worktreeSessionCreator';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
interface ProjectNotesTodoPanelProps {
|
interface ProjectNotesTodoPanelProps {
|
||||||
@@ -228,22 +228,18 @@ export const ProjectNotesTodoPanel: React.FC<ProjectNotesTodoPanelProps> = ({
|
|||||||
}
|
}
|
||||||
setSendingTodoId(todoId);
|
setSendingTodoId(todoId);
|
||||||
try {
|
try {
|
||||||
const newWorktreePath = await createWorktreeOnly();
|
routeToChat();
|
||||||
|
const newWorktreePath = await createWorktreeDraft({ initialPrompt: todoText });
|
||||||
if (!newWorktreePath) {
|
if (!newWorktreePath) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
routeToChat();
|
|
||||||
openNewSessionDraft({
|
|
||||||
directoryOverride: newWorktreePath,
|
|
||||||
initialPrompt: todoText,
|
|
||||||
});
|
|
||||||
toast.success('Todo sent to new worktree session');
|
toast.success('Todo sent to new worktree session');
|
||||||
onActionComplete?.();
|
onActionComplete?.();
|
||||||
} finally {
|
} finally {
|
||||||
setSendingTodoId(null);
|
setSendingTodoId(null);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[canCreateWorktree, onActionComplete, openNewSessionDraft, projectRef, routeToChat]
|
[canCreateWorktree, onActionComplete, projectRef, routeToChat]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!projectRef) {
|
if (!projectRef) {
|
||||||
|
|||||||
@@ -66,6 +66,9 @@ export const SessionDialogs: React.FC = () => {
|
|||||||
archiveSessions,
|
archiveSessions,
|
||||||
loadSessions,
|
loadSessions,
|
||||||
getWorktreeMetadata,
|
getWorktreeMetadata,
|
||||||
|
newSessionDraft,
|
||||||
|
setNewSessionDraftTarget,
|
||||||
|
setDraftBootstrapPendingDirectory,
|
||||||
} = useSessionStore();
|
} = useSessionStore();
|
||||||
const showDeletionDialog = useUIStore((state) => state.showDeletionDialog);
|
const showDeletionDialog = useUIStore((state) => state.showDeletionDialog);
|
||||||
const setShowDeletionDialog = useUIStore((state) => state.setShowDeletionDialog);
|
const setShowDeletionDialog = useUIStore((state) => state.setShowDeletionDialog);
|
||||||
@@ -381,12 +384,34 @@ export const SessionDialogs: React.FC = () => {
|
|||||||
deleteLocalBranch: boolean
|
deleteLocalBranch: boolean
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
const shouldRemoveRemote = deleteDialogShouldRemoveRemote && canRemoveRemoteBranches;
|
const shouldRemoveRemote = deleteDialogShouldRemoveRemote && canRemoveRemoteBranches;
|
||||||
|
const projectRef = getProjectRefForWorktree(worktree);
|
||||||
|
const normalizedWorktreePath = normalizeProjectDirectory(worktree.path);
|
||||||
|
const normalizedProjectPath = normalizeProjectDirectory(projectRef.path);
|
||||||
try {
|
try {
|
||||||
await removeProjectWorktree(
|
await removeProjectWorktree(
|
||||||
getProjectRefForWorktree(worktree),
|
projectRef,
|
||||||
worktree,
|
worktree,
|
||||||
{ deleteRemoteBranch: shouldRemoveRemote, deleteLocalBranch }
|
{ 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;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error('Failed to remove worktree', {
|
toast.error('Failed to remove worktree', {
|
||||||
@@ -394,7 +419,7 @@ export const SessionDialogs: React.FC = () => {
|
|||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}, [canRemoveRemoteBranches, deleteDialogShouldRemoveRemote, getProjectRefForWorktree]);
|
}, [canRemoveRemoteBranches, currentDirectory, deleteDialogShouldRemoveRemote, getProjectRefForWorktree, newSessionDraft?.directoryOverride, newSessionDraft?.open, setDraftBootstrapPendingDirectory, setNewSessionDraftTarget]);
|
||||||
|
|
||||||
const handleConfirmDelete = React.useCallback(async () => {
|
const handleConfirmDelete = React.useCallback(async () => {
|
||||||
if (!deleteDialog) {
|
if (!deleteDialog) {
|
||||||
|
|||||||
@@ -1293,6 +1293,14 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
|
|||||||
openNewSessionDraft();
|
openNewSessionDraft();
|
||||||
}, [mobileVariant, openNewSessionDraft, setActiveMainTab, setSessionSwitcherOpen]);
|
}, [mobileVariant, openNewSessionDraft, setActiveMainTab, setSessionSwitcherOpen]);
|
||||||
|
|
||||||
|
const handleOpenMultiRunFromHeader = React.useCallback(() => {
|
||||||
|
setActiveMainTab('chat');
|
||||||
|
if (mobileVariant) {
|
||||||
|
setSessionSwitcherOpen(false);
|
||||||
|
}
|
||||||
|
openMultiRunLauncher();
|
||||||
|
}, [mobileVariant, openMultiRunLauncher, setActiveMainTab, setSessionSwitcherOpen]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={sessionSearchContainerRef}
|
ref={sessionSearchContainerRef}
|
||||||
@@ -1336,6 +1344,8 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
|
|||||||
setProjectNotesPanelOpen={setProjectNotesPanelOpen}
|
setProjectNotesPanelOpen={setProjectNotesPanelOpen}
|
||||||
activeProjectRefForHeader={activeProjectRefForHeader}
|
activeProjectRefForHeader={activeProjectRefForHeader}
|
||||||
activeProjectLabelForHeader={activeProjectLabelForHeader}
|
activeProjectLabelForHeader={activeProjectLabelForHeader}
|
||||||
|
canOpenMultiRun={projects.length > 0}
|
||||||
|
openMultiRunLauncher={handleOpenMultiRunFromHeader}
|
||||||
stableActiveProjectIsRepo={stableActiveProjectIsRepo}
|
stableActiveProjectIsRepo={stableActiveProjectIsRepo}
|
||||||
headerActionIconClass={headerActionIconClass}
|
headerActionIconClass={headerActionIconClass}
|
||||||
reserveHeaderActionsSpace={reserveHeaderActionsSpace}
|
reserveHeaderActionsSpace={reserveHeaderActionsSpace}
|
||||||
@@ -1376,7 +1386,6 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
|
|||||||
setSessionSwitcherOpen={setSessionSwitcherOpen}
|
setSessionSwitcherOpen={setSessionSwitcherOpen}
|
||||||
openNewSessionDraft={openNewSessionDraft}
|
openNewSessionDraft={openNewSessionDraft}
|
||||||
openNewWorktreeDialog={openNewWorktreeDialog}
|
openNewWorktreeDialog={openNewWorktreeDialog}
|
||||||
openMultiRunLauncher={openMultiRunLauncher}
|
|
||||||
openProjectEditDialog={setEditingProjectDialogId}
|
openProjectEditDialog={setEditingProjectDialogId}
|
||||||
removeProject={removeProject}
|
removeProject={removeProject}
|
||||||
projectHeaderSentinelRefs={projectHeaderSentinelRefs}
|
projectHeaderSentinelRefs={projectHeaderSentinelRefs}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
RiExpandUpDownLine,
|
RiExpandUpDownLine,
|
||||||
RiStickyNoteLine,
|
RiStickyNoteLine,
|
||||||
} from '@remixicon/react';
|
} from '@remixicon/react';
|
||||||
|
import { ArrowsMerge } from '@/components/icons/ArrowsMerge';
|
||||||
import type { ProjectRef } from '@/lib/openchamberConfig';
|
import type { ProjectRef } from '@/lib/openchamberConfig';
|
||||||
import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore';
|
import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore';
|
||||||
import { ProjectNotesTodoPanel } from '../ProjectNotesTodoPanel';
|
import { ProjectNotesTodoPanel } from '../ProjectNotesTodoPanel';
|
||||||
@@ -31,6 +32,8 @@ type Props = {
|
|||||||
setProjectNotesPanelOpen: (open: boolean) => void;
|
setProjectNotesPanelOpen: (open: boolean) => void;
|
||||||
activeProjectRefForHeader: ProjectRef | null;
|
activeProjectRefForHeader: ProjectRef | null;
|
||||||
activeProjectLabelForHeader: string | null;
|
activeProjectLabelForHeader: string | null;
|
||||||
|
canOpenMultiRun: boolean;
|
||||||
|
openMultiRunLauncher: () => void;
|
||||||
stableActiveProjectIsRepo: boolean;
|
stableActiveProjectIsRepo: boolean;
|
||||||
headerActionIconClass: string;
|
headerActionIconClass: string;
|
||||||
reserveHeaderActionsSpace: boolean;
|
reserveHeaderActionsSpace: boolean;
|
||||||
@@ -56,6 +59,8 @@ export function SidebarHeader(props: Props): React.ReactNode {
|
|||||||
setProjectNotesPanelOpen,
|
setProjectNotesPanelOpen,
|
||||||
activeProjectRefForHeader,
|
activeProjectRefForHeader,
|
||||||
activeProjectLabelForHeader,
|
activeProjectLabelForHeader,
|
||||||
|
canOpenMultiRun,
|
||||||
|
openMultiRunLauncher,
|
||||||
stableActiveProjectIsRepo,
|
stableActiveProjectIsRepo,
|
||||||
headerActionIconClass,
|
headerActionIconClass,
|
||||||
reserveHeaderActionsSpace,
|
reserveHeaderActionsSpace,
|
||||||
@@ -113,6 +118,21 @@ export function SidebarHeader(props: Props): React.ReactNode {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-1.5">
|
<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 ? (
|
{useMobileNotesPanel ? (
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
|
|||||||
@@ -54,7 +54,6 @@ type Props = {
|
|||||||
setSessionSwitcherOpen: (open: boolean) => void;
|
setSessionSwitcherOpen: (open: boolean) => void;
|
||||||
openNewSessionDraft: (options?: { directoryOverride?: string | null }) => void;
|
openNewSessionDraft: (options?: { directoryOverride?: string | null }) => void;
|
||||||
openNewWorktreeDialog: () => void;
|
openNewWorktreeDialog: () => void;
|
||||||
openMultiRunLauncher: () => void;
|
|
||||||
openProjectEditDialog: (id: string) => void;
|
openProjectEditDialog: (id: string) => void;
|
||||||
removeProject: (id: string) => void;
|
removeProject: (id: string) => void;
|
||||||
projectHeaderSentinelRefs: React.MutableRefObject<Map<string, HTMLDivElement | null>>;
|
projectHeaderSentinelRefs: React.MutableRefObject<Map<string, HTMLDivElement | null>>;
|
||||||
@@ -185,10 +184,6 @@ export function SidebarProjectsList(props: Props): React.ReactNode {
|
|||||||
if (props.mobileVariant) props.setSessionSwitcherOpen(false);
|
if (props.mobileVariant) props.setSessionSwitcherOpen(false);
|
||||||
props.openNewWorktreeDialog();
|
props.openNewWorktreeDialog();
|
||||||
}}
|
}}
|
||||||
onOpenMultiRunLauncher={() => {
|
|
||||||
if (projectKey !== props.activeProjectId) props.setActiveProjectIdOnly(projectKey);
|
|
||||||
props.openMultiRunLauncher();
|
|
||||||
}}
|
|
||||||
onRenameStart={() => props.openProjectEditDialog(projectKey)}
|
onRenameStart={() => props.openProjectEditDialog(projectKey)}
|
||||||
onClose={() => props.removeProject(projectKey)}
|
onClose={() => props.removeProject(projectKey)}
|
||||||
sentinelRef={(el) => { props.projectHeaderSentinelRefs.current.set(projectKey, el); }}
|
sentinelRef={(el) => { props.projectHeaderSentinelRefs.current.set(projectKey, el); }}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ import {
|
|||||||
RiNodeTree,
|
RiNodeTree,
|
||||||
RiPencilAiLine,
|
RiPencilAiLine,
|
||||||
} from '@remixicon/react';
|
} from '@remixicon/react';
|
||||||
import { ArrowsMerge } from '@/components/icons/ArrowsMerge';
|
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
||||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||||
@@ -43,7 +42,6 @@ export interface SortableProjectItemProps {
|
|||||||
onHoverChange: (hovered: boolean) => void;
|
onHoverChange: (hovered: boolean) => void;
|
||||||
onNewSession: () => void;
|
onNewSession: () => void;
|
||||||
onNewWorktreeSession?: () => void;
|
onNewWorktreeSession?: () => void;
|
||||||
onOpenMultiRunLauncher: () => void;
|
|
||||||
onRenameStart: () => void;
|
onRenameStart: () => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
sentinelRef: (el: HTMLDivElement | null) => void;
|
sentinelRef: (el: HTMLDivElement | null) => void;
|
||||||
@@ -79,7 +77,6 @@ export const SortableProjectItem: React.FC<SortableProjectItemProps> = ({
|
|||||||
onHoverChange,
|
onHoverChange,
|
||||||
onNewSession,
|
onNewSession,
|
||||||
onNewWorktreeSession,
|
onNewWorktreeSession,
|
||||||
onOpenMultiRunLauncher,
|
|
||||||
onRenameStart,
|
onRenameStart,
|
||||||
onClose,
|
onClose,
|
||||||
sentinelRef,
|
sentinelRef,
|
||||||
@@ -267,12 +264,6 @@ export const SortableProjectItem: React.FC<SortableProjectItemProps> = ({
|
|||||||
New Session
|
New Session
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
{showCreateButtons && isRepo && !hideDirectoryControls && (
|
|
||||||
<DropdownMenuItem onClick={onOpenMultiRunLauncher}>
|
|
||||||
<ArrowsMerge className="mr-1.5 h-4 w-4" />
|
|
||||||
New Multi-Run
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
<DropdownMenuItem onClick={onRenameStart}>
|
<DropdownMenuItem onClick={onRenameStart}>
|
||||||
<RiPencilAiLine className="mr-1.5 h-4 w-4" />
|
<RiPencilAiLine className="mr-1.5 h-4 w-4" />
|
||||||
Rename
|
Rename
|
||||||
|
|||||||
@@ -202,7 +202,7 @@ export const CommandPalette: React.FC = () => {
|
|||||||
</CommandItem>
|
</CommandItem>
|
||||||
<CommandItem onSelect={handleCreateWorktreeSession}>
|
<CommandItem onSelect={handleCreateWorktreeSession}>
|
||||||
<RiGitBranchLine className="mr-2 h-4 w-4" />
|
<RiGitBranchLine className="mr-2 h-4 w-4" />
|
||||||
<span>New Session with Worktree</span>
|
<span>New Worktree Draft</span>
|
||||||
<CommandShortcut>
|
<CommandShortcut>
|
||||||
{shortcut('new_chat_worktree')}
|
{shortcut('new_chat_worktree')}
|
||||||
</CommandShortcut>
|
</CommandShortcut>
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ export const HelpDialog: React.FC = () => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'new_chat_worktree',
|
id: 'new_chat_worktree',
|
||||||
description: "Create New Session in Worktree",
|
description: "Create New Worktree Draft",
|
||||||
icon: RiGitBranchLine,
|
icon: RiGitBranchLine,
|
||||||
keys: '',
|
keys: '',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ import { BranchIntegrationSection, type OperationLogEntry } from './git/BranchIn
|
|||||||
import type { GitRemote } from '@/lib/gitApi';
|
import type { GitRemote } from '@/lib/gitApi';
|
||||||
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
|
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
|
||||||
import { cn } from '@/lib/utils';
|
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 SyncAction = 'fetch' | 'pull' | 'push' | null;
|
||||||
type CommitAction = 'commit' | 'commitAndPush' | null;
|
type CommitAction = 'commit' | 'commitAndPush' | null;
|
||||||
@@ -223,11 +223,14 @@ const normalizePath = (value?: string | null): string =>
|
|||||||
export const GitView: React.FC = () => {
|
export const GitView: React.FC = () => {
|
||||||
const { git } = useRuntimeAPIs();
|
const { git } = useRuntimeAPIs();
|
||||||
const currentDirectory = useEffectiveDirectory();
|
const currentDirectory = useEffectiveDirectory();
|
||||||
|
const [worktreeBootstrapStatus, setWorktreeBootstrapStatus] = React.useState<'pending' | 'ready' | 'failed' | null>(null);
|
||||||
|
const [isWaitingForGitRefreshAfterBootstrap, setIsWaitingForGitRefreshAfterBootstrap] = React.useState(false);
|
||||||
const {
|
const {
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
worktreeMetadata: worktreeMap,
|
worktreeMetadata: worktreeMap,
|
||||||
availableWorktrees,
|
availableWorktrees,
|
||||||
newSessionDraft,
|
newSessionDraft,
|
||||||
|
setDraftBootstrapPendingDirectory,
|
||||||
} = useSessionStore();
|
} = useSessionStore();
|
||||||
const normalizedCurrentDirectory = normalizePath(currentDirectory);
|
const normalizedCurrentDirectory = normalizePath(currentDirectory);
|
||||||
const inferredWorktreeMetadata = React.useMemo(() => {
|
const inferredWorktreeMetadata = React.useMemo(() => {
|
||||||
@@ -287,6 +290,78 @@ export const GitView: React.FC = () => {
|
|||||||
const openContextDiff = useUIStore((state) => state.openContextDiff);
|
const openContextDiff = useUIStore((state) => state.openContextDiff);
|
||||||
const navigateToDiff = useUIStore((state) => state.navigateToDiff);
|
const navigateToDiff = useUIStore((state) => state.navigateToDiff);
|
||||||
const setRightSidebarOpen = useUIStore((state) => state.setRightSidebarOpen);
|
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(() => {
|
const initialSnapshot = React.useMemo(() => {
|
||||||
if (!currentDirectory) return null;
|
if (!currentDirectory) return null;
|
||||||
@@ -1829,6 +1904,20 @@ export const GitView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isGitRepo === false) {
|
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 (
|
return (
|
||||||
<div className="flex h-full flex-col items-center justify-center px-4 text-center">
|
<div className="flex h-full flex-col items-center justify-center px-4 text-center">
|
||||||
<RiGitBranchLine className="mb-3 size-6 text-muted-foreground" />
|
<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.Portal>
|
||||||
<DialogPrimitive.Overlay
|
<DialogPrimitive.Overlay
|
||||||
className="fixed inset-0 z-50 bg-black/50 backdrop-blur-md"
|
className="fixed inset-0 z-50 bg-black/50 backdrop-blur-md"
|
||||||
onPointerDown={(event) => {
|
|
||||||
event.stopPropagation();
|
|
||||||
if (hasOpenFloatingMenu()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
onOpenChange(false);
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
<DialogPrimitive.Content
|
<DialogPrimitive.Content
|
||||||
aria-describedby={descriptionId}
|
aria-describedby={descriptionId}
|
||||||
onPointerDownOutside={(event) => {
|
onInteractOutside={(event) => {
|
||||||
event.preventDefault();
|
if (hasOpenFloatingMenu()) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
className={cn(
|
className={cn(
|
||||||
'fixed z-50 top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]',
|
'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 [prompt, setPrompt] = React.useState('');
|
||||||
const [selectedModels, setSelectedModels] = React.useState<ModelSelectionWithId[]>([]);
|
const [selectedModels, setSelectedModels] = React.useState<ModelSelectionWithId[]>([]);
|
||||||
const [selectedAgent, setSelectedAgent] = React.useState<string>('');
|
const [selectedAgent, setSelectedAgent] = React.useState<string>('');
|
||||||
const [baseBranch, setBaseBranch] = React.useState('HEAD');
|
const [baseBranch, setBaseBranch] = React.useState('');
|
||||||
const [attachedFiles, setAttachedFiles] = React.useState<AttachedFile[]>([]);
|
const [attachedFiles, setAttachedFiles] = React.useState<AttachedFile[]>([]);
|
||||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||||
const [setupCommands, setSetupCommands] = React.useState<string[]>([]);
|
const [setupCommands, setSetupCommands] = React.useState<string[]>([]);
|
||||||
@@ -206,6 +206,7 @@ export const AgentManagerEmptyState: React.FC<AgentManagerEmptyStateProps> = ({
|
|||||||
groupName.trim() &&
|
groupName.trim() &&
|
||||||
prompt.trim() &&
|
prompt.trim() &&
|
||||||
selectedModels.length >= 1 &&
|
selectedModels.length >= 1 &&
|
||||||
|
baseBranch &&
|
||||||
isGitRepository &&
|
isGitRepository &&
|
||||||
!isLoadingBranches
|
!isLoadingBranches
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,3 +6,4 @@ export { TerminalView } from './TerminalView';
|
|||||||
export { FilesView } from './FilesView';
|
export { FilesView } from './FilesView';
|
||||||
export { SettingsView } from './SettingsView';
|
export { SettingsView } from './SettingsView';
|
||||||
export { SettingsWindow } from './SettingsWindow';
|
export { SettingsWindow } from './SettingsWindow';
|
||||||
|
export { MultiRunWindow } from './MultiRunWindow';
|
||||||
|
|||||||
@@ -27,8 +27,8 @@ export const useChatSearchDirectory = (): string | undefined => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newSessionDraft?.open && newSessionDraft.directoryOverride) {
|
if (newSessionDraft?.open && (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride)) {
|
||||||
return newSessionDraft.directoryOverride;
|
return (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride) ?? undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (activeProjectId) {
|
if (activeProjectId) {
|
||||||
|
|||||||
@@ -39,8 +39,8 @@ export const useEffectiveDirectory = (): string | undefined => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If a draft session is open, use its directoryOverride
|
// If a draft session is open, use its directoryOverride
|
||||||
if (newSessionDraft?.open && newSessionDraft.directoryOverride) {
|
if (newSessionDraft?.open && (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride)) {
|
||||||
return newSessionDraft.directoryOverride;
|
return (newSessionDraft.bootstrapPendingDirectory || newSessionDraft.directoryOverride) ?? undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fall back to the global directory
|
// 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 {
|
export interface CreateGitWorktreePayload {
|
||||||
mode?: 'new' | 'existing';
|
mode?: 'new' | 'existing';
|
||||||
/** Worktree folder name (falls back to OpenCode name generation when omitted). */
|
/** Worktree folder name (falls back to OpenCode name generation when omitted). */
|
||||||
@@ -380,6 +386,8 @@ export interface GeneratedPullRequestDescription {
|
|||||||
export interface GitWorktreeAPI {
|
export interface GitWorktreeAPI {
|
||||||
list(directory: string): Promise<GitWorktreeInfo[]>;
|
list(directory: string): Promise<GitWorktreeInfo[]>;
|
||||||
validate?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeValidationResult>;
|
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>;
|
create?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult>;
|
||||||
remove?(directory: string, payload: RemoveGitWorktreePayload): Promise<{ success: boolean }>;
|
remove?(directory: string, payload: RemoveGitWorktreePayload): Promise<{ success: boolean }>;
|
||||||
}
|
}
|
||||||
@@ -402,6 +410,8 @@ export interface GitAPI {
|
|||||||
): Promise<GeneratedPullRequestDescription>;
|
): Promise<GeneratedPullRequestDescription>;
|
||||||
listGitWorktrees(directory: string): Promise<GitWorktreeInfo[]>;
|
listGitWorktrees(directory: string): Promise<GitWorktreeInfo[]>;
|
||||||
validateGitWorktree?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeValidationResult>;
|
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>;
|
createGitWorktree?(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult>;
|
||||||
deleteGitWorktree?(directory: string, payload: RemoveGitWorktreePayload): Promise<{ success: boolean }>;
|
deleteGitWorktree?(directory: string, payload: RemoveGitWorktreePayload): Promise<{ success: boolean }>;
|
||||||
createGitCommit(directory: string, message: string, options?: CreateGitCommitOptions): Promise<GitCommitResult>;
|
createGitCommit(directory: string, message: string, options?: CreateGitCommitOptions): Promise<GitCommitResult>;
|
||||||
|
|||||||
@@ -453,6 +453,33 @@ export async function validateGitWorktree(
|
|||||||
return gitHttp.validateGitWorktree(directory, payload);
|
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(
|
export async function createGitWorktree(
|
||||||
directory: string,
|
directory: string,
|
||||||
payload: import('./api/types').CreateGitWorktreePayload
|
payload: import('./api/types').CreateGitWorktreePayload
|
||||||
|
|||||||
@@ -424,6 +424,30 @@ export async function validateGitWorktree(directory: string, payload: CreateGitW
|
|||||||
return response.json();
|
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> {
|
export async function createGitWorktree(directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult> {
|
||||||
const response = await fetch(buildUrl(`${API_BASE}/worktrees`, directory), {
|
const response = await fetch(buildUrl(`${API_BASE}/worktrees`, directory), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import type {
|
|||||||
} from "@opencode-ai/sdk/v2";
|
} from "@opencode-ai/sdk/v2";
|
||||||
import type { PermissionRequest } from "@/types/permission";
|
import type { PermissionRequest } from "@/types/permission";
|
||||||
import type { QuestionRequest } from "@/types/question";
|
import type { QuestionRequest } from "@/types/question";
|
||||||
|
import { waitForWorktreeBootstrap } from "@/lib/worktrees/worktreeBootstrap";
|
||||||
type StreamEvent<TData> = {
|
type StreamEvent<TData> = {
|
||||||
data: TData;
|
data: TData;
|
||||||
event?: string;
|
event?: string;
|
||||||
@@ -701,6 +702,10 @@ class OpencodeService {
|
|||||||
throw new Error('Message must have at least one part (text or file)');
|
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
|
// Use async prompt endpoint so the client doesn't block waiting
|
||||||
// for model work (SSE will deliver output/status).
|
// for model work (SSE will deliver output/status).
|
||||||
// This avoids 504s from proxy timeouts on long-running turns.
|
// This avoids 504s from proxy timeouts on long-running turns.
|
||||||
|
|||||||
@@ -196,8 +196,8 @@ const SHORTCUT_ACTIONS: ReadonlyArray<ShortcutAction> = [
|
|||||||
{
|
{
|
||||||
id: 'new_chat_worktree',
|
id: 'new_chat_worktree',
|
||||||
defaultCombo: 'mod+shift+n',
|
defaultCombo: 'mod+shift+n',
|
||||||
label: 'New session with worktree',
|
label: 'New worktree draft',
|
||||||
description: 'Start a new session in a worktree',
|
description: 'Create a new worktree and open a draft in it',
|
||||||
customizable: true,
|
customizable: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Utility for creating a new session with an auto-generated worktree.
|
* Utilities for creating worktrees and, when needed, sessions bound to them.
|
||||||
* This is a standalone function that can be called from keyboard shortcuts,
|
* This is a standalone entrypoint for keyboard shortcuts, menu actions,
|
||||||
* menu actions, or other non-hook contexts.
|
* and other non-hook contexts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { toast } from '@/components/ui';
|
import { toast } from '@/components/ui';
|
||||||
@@ -10,16 +10,20 @@ import { useProjectsStore } from '@/stores/useProjectsStore';
|
|||||||
import { useConfigStore } from '@/stores/useConfigStore';
|
import { useConfigStore } from '@/stores/useConfigStore';
|
||||||
import { useContextStore } from '@/stores/contextStore';
|
import { useContextStore } from '@/stores/contextStore';
|
||||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||||
import { checkIsGitRepository } from '@/lib/gitApi';
|
import { checkIsGitRepository, previewGitWorktree } from '@/lib/gitApi';
|
||||||
import { generateBranchName } from '@/lib/git/branchNameGenerator';
|
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 { getWorktreeSetupCommands } from '@/lib/openchamberConfig';
|
||||||
import {
|
import {
|
||||||
removeProjectWorktree,
|
removeProjectWorktree,
|
||||||
type ProjectRef,
|
type ProjectRef,
|
||||||
} from '@/lib/worktrees/worktreeManager';
|
} from '@/lib/worktrees/worktreeManager';
|
||||||
import { createWorktreeWithDefaults } from '@/lib/worktrees/worktreeCreate';
|
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;
|
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;
|
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;
|
let isCreatingWorktreeSession = false;
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new session with an auto-generated worktree.
|
|
||||||
* Uses project's worktree defaults for naming/metadata.
|
const applyDefaultAgentAndModelSelection = (sessionId: string, configState = useConfigStore.getState()) => {
|
||||||
*
|
try {
|
||||||
* @returns The created session, or null if creation failed
|
const visibleAgents = configState.getVisibleAgents();
|
||||||
*/
|
let agentName: string | undefined;
|
||||||
export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
|
||||||
|
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) {
|
if (isCreatingWorktreeSession) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -72,7 +161,6 @@ export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
|||||||
|
|
||||||
const projectDirectory = activeProject.path;
|
const projectDirectory = activeProject.path;
|
||||||
|
|
||||||
// Check if it's a git repo
|
|
||||||
let isGitRepo = false;
|
let isGitRepo = false;
|
||||||
try {
|
try {
|
||||||
isGitRepo = await checkIsGitRepository(projectDirectory);
|
isGitRepo = await checkIsGitRepository(projectDirectory);
|
||||||
@@ -88,16 +176,57 @@ export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isCreatingWorktreeSession = true;
|
isCreatingWorktreeSession = true;
|
||||||
startConfigUpdate("Creating new worktree session...");
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const projectRef: ProjectRef = { id: activeProject.id, path: projectDirectory };
|
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 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 setupCommands = await getWorktreeSetupCommands(projectRef);
|
||||||
const rootBranch = await getRootBranch(projectRef.path);
|
|
||||||
const metadata = await createWorktreeWithDefaults(projectRef, {
|
const metadata = await createWorktreeWithDefaults(projectRef, {
|
||||||
preferredName,
|
preferredName,
|
||||||
mode: 'new',
|
mode: 'new',
|
||||||
@@ -106,123 +235,44 @@ export async function createWorktreeSession(): Promise<{ id: string } | null> {
|
|||||||
setupCommands,
|
setupCommands,
|
||||||
});
|
});
|
||||||
|
|
||||||
const createdMetadata = {
|
resolvePendingDraftWorktreeRequest(pendingRequestId, metadata.path);
|
||||||
...metadata,
|
useSessionStore.getState().overrideNewSessionDraftTarget({
|
||||||
createdFromBranch: rootBranch,
|
projectId: projectRef.id,
|
||||||
kind: 'standard' as const,
|
directoryOverride: metadata.path,
|
||||||
};
|
pendingWorktreeRequestId: null,
|
||||||
|
bootstrapPendingDirectory: metadata.path,
|
||||||
// Get worktree status
|
preserveDirectoryOverride: true,
|
||||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
title: options?.title,
|
||||||
const createdMetadataWithStatus = status ? { ...createdMetadata, status } : createdMetadata;
|
initialPrompt: options?.initialPrompt,
|
||||||
|
|
||||||
// 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',
|
|
||||||
});
|
});
|
||||||
|
useDirectoryStore.getState().setDirectory(metadata.path, { showOverlay: false });
|
||||||
|
void useSessionStore.getState().loadSessions().catch(() => undefined);
|
||||||
|
|
||||||
return session;
|
return metadata.path;
|
||||||
} catch (error) {
|
} 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', {
|
toast.error('Failed to create worktree', {
|
||||||
description: message,
|
description: message,
|
||||||
});
|
});
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
finishConfigUpdate();
|
|
||||||
isCreatingWorktreeSession = false;
|
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;
|
return isCreatingWorktreeSession;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function createWorktreeDraft(options?: { initialPrompt?: string; title?: string }): Promise<string | null> {
|
||||||
|
return createInstantWorktreeDraft(options);
|
||||||
|
}
|
||||||
|
|
||||||
export async function createWorktreeOnly(): Promise<string | null> {
|
export async function createWorktreeOnly(): Promise<string | null> {
|
||||||
if (isCreatingWorktreeSession) {
|
if (isCreatingWorktreeSession) {
|
||||||
return null;
|
return null;
|
||||||
@@ -261,7 +315,6 @@ export async function createWorktreeOnly(): Promise<string | null> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isCreatingWorktreeSession = true;
|
isCreatingWorktreeSession = true;
|
||||||
startConfigUpdate('Creating new worktree...');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const projectRef: ProjectRef = { id: activeProject.id, path: projectDirectory };
|
const projectRef: ProjectRef = { id: activeProject.id, path: projectDirectory };
|
||||||
@@ -275,17 +328,8 @@ export async function createWorktreeOnly(): Promise<string | null> {
|
|||||||
setupCommands,
|
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;
|
void useSessionStore.getState().loadSessions().catch(() => undefined);
|
||||||
toast.success('Worktree created', {
|
|
||||||
description: branchLabel
|
|
||||||
? `${branchLabel}${rootBranch ? ` from ${rootBranch}` : ''}`
|
|
||||||
: status?.isDirty ? 'Created (dirty)' : 'Ready',
|
|
||||||
});
|
|
||||||
|
|
||||||
await useSessionStore.getState().loadSessions();
|
|
||||||
return metadata.path;
|
return metadata.path;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : 'Failed to create worktree';
|
const message = error instanceof Error ? error.message : 'Failed to create worktree';
|
||||||
@@ -294,7 +338,6 @@ export async function createWorktreeOnly(): Promise<string | null> {
|
|||||||
});
|
});
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
finishConfigUpdate();
|
|
||||||
isCreatingWorktreeSession = false;
|
isCreatingWorktreeSession = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -327,7 +370,6 @@ export async function createWorktreeSessionForBranch(
|
|||||||
}
|
}
|
||||||
|
|
||||||
isCreatingWorktreeSession = true;
|
isCreatingWorktreeSession = true;
|
||||||
startConfigUpdate("Creating worktree session...");
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const projectRef = resolveProjectRef(projectDirectory);
|
const projectRef = resolveProjectRef(projectDirectory);
|
||||||
@@ -373,10 +415,6 @@ export async function createWorktreeSessionForBranch(
|
|||||||
kind,
|
kind,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get worktree status
|
|
||||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
|
||||||
const createdMetadataWithStatus = status ? { ...createdMetadata, status } : createdMetadata;
|
|
||||||
|
|
||||||
// Create the session
|
// Create the session
|
||||||
const sessionStore = useSessionStore.getState();
|
const sessionStore = useSessionStore.getState();
|
||||||
const session = await sessionStore.createSession(undefined, metadata.path);
|
const session = await sessionStore.createSession(undefined, metadata.path);
|
||||||
@@ -389,89 +427,7 @@ export async function createWorktreeSessionForBranch(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize the session
|
initializeSessionForWorktree(session.id, createdMetadata);
|
||||||
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',
|
|
||||||
});
|
|
||||||
|
|
||||||
return session;
|
return session;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -481,7 +437,6 @@ export async function createWorktreeSessionForBranch(
|
|||||||
});
|
});
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
finishConfigUpdate();
|
|
||||||
isCreatingWorktreeSession = false;
|
isCreatingWorktreeSession = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -510,7 +465,6 @@ export async function createWorktreeSessionForNewBranch(
|
|||||||
}
|
}
|
||||||
|
|
||||||
isCreatingWorktreeSession = true;
|
isCreatingWorktreeSession = true;
|
||||||
startConfigUpdate('Creating worktree session...');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const start = startPoint?.trim() || 'HEAD';
|
const start = startPoint?.trim() || 'HEAD';
|
||||||
@@ -562,92 +516,22 @@ export async function createWorktreeSessionForNewBranch(
|
|||||||
kind,
|
kind,
|
||||||
};
|
};
|
||||||
|
|
||||||
const status = await getWorktreeStatus(metadata.path).catch(() => undefined);
|
const sessionStore = useSessionStore.getState();
|
||||||
const createdMetadataWithStatus = status ? { ...createdMetadata, status } : createdMetadata;
|
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();
|
initializeSessionForWorktree(session.id, createdMetadata);
|
||||||
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 configState = useConfigStore.getState();
|
return { id: session.id, branch: metadata.branch || base };
|
||||||
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 };
|
|
||||||
} catch (error) {
|
} 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 session';
|
||||||
toast.error('Failed to create worktree', { description: message });
|
toast.error('Failed to create worktree', { description: message });
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
finishConfigUpdate();
|
|
||||||
isCreatingWorktreeSession = false;
|
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,
|
deleteRemoteBranch,
|
||||||
git,
|
git,
|
||||||
} from '@/lib/gitApi';
|
} from '@/lib/gitApi';
|
||||||
|
import {
|
||||||
|
clearWorktreeBootstrapState,
|
||||||
|
markWorktreeBootstrapPending,
|
||||||
|
} from '@/lib/worktrees/worktreeBootstrap';
|
||||||
import type {
|
import type {
|
||||||
CreateGitWorktreePayload,
|
CreateGitWorktreePayload,
|
||||||
GitWorktreeValidationResult,
|
GitWorktreeValidationResult,
|
||||||
@@ -241,6 +245,8 @@ export async function createWorktree(project: ProjectRef, args: CreateWorktreeAr
|
|||||||
label: returnedBranch || returnedName,
|
label: returnedBranch || returnedName,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
markWorktreeBootstrapPending(metadata.path);
|
||||||
|
|
||||||
return metadata;
|
return metadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,6 +274,8 @@ export async function removeProjectWorktree(project: ProjectRef, worktree: Workt
|
|||||||
throw new Error('Worktree removal failed');
|
throw new Error('Worktree removal failed');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
clearWorktreeBootstrapState(worktree.path);
|
||||||
|
|
||||||
const branchName = (worktree.branch || '').replace(/^refs\/heads\//, '').trim();
|
const branchName = (worktree.branch || '').replace(/^refs\/heads\//, '').trim();
|
||||||
if (deleteRemote && branchName) {
|
if (deleteRemote && branchName) {
|
||||||
await deleteRemoteBranch(projectDirectory, { branch: branchName, remote: remoteName }).catch(() => undefined);
|
await deleteRemoteBranch(projectDirectory, { branch: branchName, remote: remoteName }).catch(() => undefined);
|
||||||
|
|||||||
@@ -118,6 +118,9 @@ export type NewSessionDraftState = {
|
|||||||
open: boolean;
|
open: boolean;
|
||||||
selectedProjectId?: string | null;
|
selectedProjectId?: string | null;
|
||||||
directoryOverride: string | null;
|
directoryOverride: string | null;
|
||||||
|
pendingWorktreeRequestId?: string | null;
|
||||||
|
bootstrapPendingDirectory?: string | null;
|
||||||
|
preserveDirectoryOverride?: boolean;
|
||||||
parentID: string | null;
|
parentID: string | null;
|
||||||
title?: string;
|
title?: string;
|
||||||
initialPrompt?: string;
|
initialPrompt?: string;
|
||||||
@@ -216,8 +219,13 @@ export interface SessionStore {
|
|||||||
setSessionAgentEditMode: (sessionId: string, agentName: string | undefined, mode: EditPermissionMode, defaultMode?: EditPermissionMode) => void;
|
setSessionAgentEditMode: (sessionId: string, agentName: string | undefined, mode: EditPermissionMode, defaultMode?: EditPermissionMode) => void;
|
||||||
loadSessions: () => Promise<void>;
|
loadSessions: () => Promise<void>;
|
||||||
|
|
||||||
openNewSessionDraft: (options?: { projectId?: string | null; directoryOverride?: string | null; parentID?: string | null; title?: string; initialPrompt?: string; syntheticParts?: SyntheticContextPart[]; targetFolderId?: string }) => 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;
|
||||||
setNewSessionDraftTarget: (target: { projectId?: string | null; directoryOverride?: string | null }) => 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;
|
closeNewSessionDraft: () => void;
|
||||||
|
|
||||||
createSession: (title?: string, directoryOverride?: string | null, parentID?: string | null) => Promise<Session | null>;
|
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 { normalizeMessageRecordsForProjection } from "./utils/messageProjectors";
|
||||||
import type { ProjectEntry } from "@/lib/api/types";
|
import type { ProjectEntry } from "@/lib/api/types";
|
||||||
import type { WorktreeMetadata } from "@/types/worktree";
|
import type { WorktreeMetadata } from "@/types/worktree";
|
||||||
|
import { waitForWorktreeBootstrap } from "@/lib/worktrees/worktreeBootstrap";
|
||||||
|
import { waitForPendingDraftWorktreeRequest } from "@/lib/worktrees/pendingDraftWorktree";
|
||||||
|
|
||||||
export type { AttachedFile, EditPermissionMode };
|
export type { AttachedFile, EditPermissionMode };
|
||||||
export { MEMORY_LIMITS, ACTIVE_SESSION_WINDOW } from "./types/sessionTypes";
|
export { MEMORY_LIMITS, ACTIVE_SESSION_WINDOW } from "./types/sessionTypes";
|
||||||
@@ -242,7 +244,7 @@ export const useSessionStore = create<SessionStore>()(
|
|||||||
pendingInputText: null,
|
pendingInputText: null,
|
||||||
pendingInputMode: 'replace',
|
pendingInputMode: 'replace',
|
||||||
pendingSyntheticParts: null,
|
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)
|
// Voice state (initialized to disconnected/idle)
|
||||||
voiceStatus: 'disconnected',
|
voiceStatus: 'disconnected',
|
||||||
@@ -338,6 +340,9 @@ export const useSessionStore = create<SessionStore>()(
|
|||||||
open: true,
|
open: true,
|
||||||
selectedProjectId: selectedProject?.id ?? null,
|
selectedProjectId: selectedProject?.id ?? null,
|
||||||
directoryOverride: directory,
|
directoryOverride: directory,
|
||||||
|
pendingWorktreeRequestId: options?.pendingWorktreeRequestId ?? null,
|
||||||
|
bootstrapPendingDirectory: normalizePath(options?.bootstrapPendingDirectory ?? null),
|
||||||
|
preserveDirectoryOverride: options?.preserveDirectoryOverride === true,
|
||||||
parentID: options?.parentID ?? null,
|
parentID: options?.parentID ?? null,
|
||||||
title: options?.title,
|
title: options?.title,
|
||||||
initialPrompt: options?.initialPrompt,
|
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 projects = useProjectsStore.getState().projects;
|
||||||
const project = projectId
|
const project = projectId
|
||||||
? projects.find((entry) => entry.id === projectId) ?? null
|
? projects.find((entry) => entry.id === projectId) ?? null
|
||||||
@@ -385,6 +435,52 @@ export const useSessionStore = create<SessionStore>()(
|
|||||||
const normalizedProjectPath = normalizePath(project?.path ?? null);
|
const normalizedProjectPath = normalizePath(project?.path ?? null);
|
||||||
const nextDirectory = normalizedDirectory ?? normalizedProjectPath ?? 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) => {
|
set((state) => {
|
||||||
if (!state.newSessionDraft?.open) {
|
if (!state.newSessionDraft?.open) {
|
||||||
return state;
|
return state;
|
||||||
@@ -392,24 +488,55 @@ export const useSessionStore = create<SessionStore>()(
|
|||||||
return {
|
return {
|
||||||
newSessionDraft: {
|
newSessionDraft: {
|
||||||
...state.newSessionDraft,
|
...state.newSessionDraft,
|
||||||
selectedProjectId: project?.id ?? null,
|
pendingWorktreeRequestId: requestId,
|
||||||
directoryOverride: nextDirectory,
|
|
||||||
parentID: null,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
},
|
||||||
|
|
||||||
persistDraftTarget({
|
resolvePendingDraftWorktreeTarget: (requestId, directory, options) => {
|
||||||
projectId: project?.id ?? null,
|
set((state) => {
|
||||||
directory: nextDirectory,
|
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: () => {
|
setDraftBootstrapPendingDirectory: (directory) => {
|
||||||
const realCurrentSessionId = useSessionManagementStore.getState().currentSessionId;
|
set((state) => {
|
||||||
set({
|
if (!state.newSessionDraft?.open) {
|
||||||
newSessionDraft: { open: false, selectedProjectId: null, directoryOverride: null, parentID: null, title: undefined, initialPrompt: undefined, syntheticParts: undefined, targetFolderId: undefined },
|
return state;
|
||||||
currentSessionId: realCurrentSessionId,
|
}
|
||||||
|
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) {
|
if (draft?.open) {
|
||||||
const draftTargetFolderId = draft.targetFolderId;
|
const draftTargetFolderId = draft.targetFolderId;
|
||||||
const draftDirectoryOverride = draft.directoryOverride ?? null;
|
let draftDirectoryOverride = draft.bootstrapPendingDirectory ?? draft.directoryOverride ?? null;
|
||||||
const draftProjectId = draft.selectedProjectId ?? null;
|
const draftProjectId = draft.selectedProjectId ?? null;
|
||||||
|
|
||||||
|
if (draft.pendingWorktreeRequestId) {
|
||||||
|
draftDirectoryOverride = await waitForPendingDraftWorktreeRequest(draft.pendingWorktreeRequestId);
|
||||||
|
get().resolvePendingDraftWorktreeTarget(draft.pendingWorktreeRequestId, draftDirectoryOverride);
|
||||||
|
}
|
||||||
|
|
||||||
const created = await useSessionManagementStore
|
const created = await useSessionManagementStore
|
||||||
.getState()
|
.getState()
|
||||||
.createSession(draft.title, draftDirectoryOverride, draft.parentID ?? null);
|
.createSession(draft.title, draftDirectoryOverride, draft.parentID ?? null);
|
||||||
@@ -647,6 +779,7 @@ export const useSessionStore = create<SessionStore>()(
|
|||||||
const draftSyntheticParts = draft.syntheticParts;
|
const draftSyntheticParts = draft.syntheticParts;
|
||||||
|
|
||||||
get().closeNewSessionDraft();
|
get().closeNewSessionDraft();
|
||||||
|
await get().setCurrentSession(created.id);
|
||||||
|
|
||||||
// Assign to target folder if session was created from folder's + button
|
// Assign to target folder if session was created from folder's + button
|
||||||
if (draftTargetFolderId) {
|
if (draftTargetFolderId) {
|
||||||
@@ -663,6 +796,11 @@ export const useSessionStore = create<SessionStore>()(
|
|||||||
? [...(additionalParts || []), ...draftSyntheticParts]
|
? [...(additionalParts || []), ...draftSyntheticParts]
|
||||||
: additionalParts;
|
: additionalParts;
|
||||||
|
|
||||||
|
const createdDirectory = normalizePath(draftDirectoryOverride ?? created.directory ?? null);
|
||||||
|
if (createdDirectory) {
|
||||||
|
await waitForWorktreeBootstrap(createdDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
markPendingUserSendAnimation(created.id);
|
markPendingUserSendAnimation(created.id);
|
||||||
return await useMessageStore
|
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
|
// Notify server that user sent a message in this session
|
||||||
if (currentSessionId) {
|
if (currentSessionId) {
|
||||||
fetch(`/api/sessions/${currentSessionId}/message-sent`, { method: 'POST' })
|
fetch(`/api/sessions/${currentSessionId}/message-sent`, { method: 'POST' })
|
||||||
@@ -1268,6 +1413,10 @@ useDirectoryStore.subscribe((state, prevState) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (draft.pendingWorktreeRequestId || draft.bootstrapPendingDirectory || draft.preserveDirectoryOverride) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const draftDirectory = normalizePath(draft.directoryOverride);
|
const draftDirectory = normalizePath(draft.directoryOverride);
|
||||||
if (draftDirectory && draftDirectory !== prevDirectory) {
|
if (draftDirectory && draftDirectory !== prevDirectory) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -3323,6 +3323,24 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
|
|||||||
return { id, type, success: true, data: result };
|
return { id, type, success: true, data: result };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'api:git/worktrees/bootstrap-status': {
|
||||||
|
const { directory } = (payload || {}) as { directory?: string };
|
||||||
|
if (!directory) {
|
||||||
|
return { id, type, success: false, error: 'Directory is required' };
|
||||||
|
}
|
||||||
|
const result = await gitService.getWorktreeBootstrapStatus(directory);
|
||||||
|
return { id, type, success: true, data: result };
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'api:git/worktrees/preview': {
|
||||||
|
const { directory } = (payload || {}) as { directory?: string };
|
||||||
|
if (!directory) {
|
||||||
|
return { id, type, success: false, error: 'Directory is required' };
|
||||||
|
}
|
||||||
|
const result = await gitService.previewWorktreeCreate(directory, (payload || {}) as gitService.CreateGitWorktreePayload);
|
||||||
|
return { id, type, success: true, data: result };
|
||||||
|
}
|
||||||
|
|
||||||
case 'api:git/diff': {
|
case 'api:git/diff': {
|
||||||
const { directory, path: filePath, staged, contextLines } = (payload || {}) as {
|
const { directory, path: filePath, staged, contextLines } = (payload || {}) as {
|
||||||
directory?: string;
|
directory?: string;
|
||||||
|
|||||||
@@ -14,6 +14,39 @@ import type { API as GitAPI, Repository, GitExtension, Status } from './git.d';
|
|||||||
|
|
||||||
let gitApi: GitAPI | null = null;
|
let gitApi: GitAPI | null = null;
|
||||||
let gitExtensionEnabled = false;
|
let gitExtensionEnabled = false;
|
||||||
|
const worktreeBootstrapState = new Map<string, { status: 'pending' | 'ready' | 'failed'; error: string | null; updatedAt: number }>();
|
||||||
|
|
||||||
|
const WORKTREE_BOOTSTRAP_PENDING = 'pending' as const;
|
||||||
|
const WORKTREE_BOOTSTRAP_READY = 'ready' as const;
|
||||||
|
const WORKTREE_BOOTSTRAP_FAILED = 'failed' as const;
|
||||||
|
|
||||||
|
const toBootstrapStateKey = (directory: string): string => {
|
||||||
|
const normalized = normalizeDirectoryPath(directory);
|
||||||
|
if (!normalized) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return path.resolve(normalized);
|
||||||
|
};
|
||||||
|
|
||||||
|
const setWorktreeBootstrapState = (directory: string, status: 'pending' | 'ready' | 'failed', error: string | null = null): void => {
|
||||||
|
const key = toBootstrapStateKey(directory);
|
||||||
|
if (!key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
worktreeBootstrapState.set(key, {
|
||||||
|
status,
|
||||||
|
error: typeof error === 'string' && error.trim().length > 0 ? error.trim() : null,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearWorktreeBootstrapState = (directory: string): void => {
|
||||||
|
const key = toBootstrapStateKey(directory);
|
||||||
|
if (!key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
worktreeBootstrapState.delete(key);
|
||||||
|
};
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
const execFileAsync = promisify(execFile);
|
||||||
const gpgconfCandidates = ['gpgconf', '/opt/homebrew/bin/gpgconf', '/usr/local/bin/gpgconf'];
|
const gpgconfCandidates = ['gpgconf', '/opt/homebrew/bin/gpgconf', '/usr/local/bin/gpgconf'];
|
||||||
@@ -1290,30 +1323,80 @@ const syncProjectSandboxRemove = async (projectID: string, primaryWorktree: stri
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const queueWorktreeStartScripts = (directory: string, projectID: string, startCommand: string | undefined) => {
|
const runWorktreeStartScripts = async (directory: string, projectID: string, startCommand: string | undefined) => {
|
||||||
|
const projectStart = await loadProjectStartCommand(projectID);
|
||||||
|
if (projectStart) {
|
||||||
|
const projectResult = await runWorktreeStartCommand(directory, projectStart);
|
||||||
|
if (!projectResult.success) {
|
||||||
|
console.warn('[GitService] Worktree project start command failed:', projectResult.message || projectResult.stderr || projectResult.stdout);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const extraCommand = String(startCommand || '').trim();
|
||||||
|
if (!extraCommand) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const extraResult = await runWorktreeStartCommand(directory, extraCommand);
|
||||||
|
if (!extraResult.success) {
|
||||||
|
console.warn('[GitService] Worktree start command failed:', extraResult.message || extraResult.stderr || extraResult.stdout);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const queueWorktreeBootstrap = (args: {
|
||||||
|
directory: string;
|
||||||
|
projectID: string;
|
||||||
|
primaryWorktree: string;
|
||||||
|
localBranch: string;
|
||||||
|
setUpstream: boolean;
|
||||||
|
upstreamRemote: string;
|
||||||
|
upstreamBranch: string;
|
||||||
|
ensureRemoteName: string;
|
||||||
|
ensureRemoteUrl: string;
|
||||||
|
startCommand: string | undefined;
|
||||||
|
}) => {
|
||||||
|
const {
|
||||||
|
directory,
|
||||||
|
projectID,
|
||||||
|
primaryWorktree,
|
||||||
|
localBranch,
|
||||||
|
setUpstream,
|
||||||
|
upstreamRemote,
|
||||||
|
upstreamBranch,
|
||||||
|
ensureRemoteName,
|
||||||
|
ensureRemoteUrl,
|
||||||
|
startCommand,
|
||||||
|
} = args;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
const projectStart = await loadProjectStartCommand(projectID);
|
await runGitCommandOrThrow(directory, ['reset', '--hard'], 'Failed to populate worktree');
|
||||||
if (projectStart) {
|
if (setUpstream) {
|
||||||
const projectResult = await runWorktreeStartCommand(directory, projectStart);
|
await applyUpstreamConfiguration({
|
||||||
if (!projectResult.success) {
|
primaryWorktree,
|
||||||
console.warn('[GitService] Worktree project start command failed:', projectResult.message || projectResult.stderr || projectResult.stdout);
|
worktreeDirectory: directory,
|
||||||
return;
|
localBranch,
|
||||||
}
|
setUpstream,
|
||||||
}
|
upstreamRemote,
|
||||||
|
upstreamBranch,
|
||||||
const extraCommand = String(startCommand || '').trim();
|
ensureRemoteName,
|
||||||
if (!extraCommand) {
|
ensureRemoteUrl,
|
||||||
return;
|
}).catch((error) => {
|
||||||
}
|
console.warn('[GitService] Worktree upstream configuration failed:', error instanceof Error ? error.message : String(error));
|
||||||
const extraResult = await runWorktreeStartCommand(directory, extraCommand);
|
});
|
||||||
if (!extraResult.success) {
|
|
||||||
console.warn('[GitService] Worktree start command failed:', extraResult.message || extraResult.stderr || extraResult.stdout);
|
|
||||||
}
|
}
|
||||||
|
await runWorktreeStartScripts(directory, projectID, startCommand).catch((error) => {
|
||||||
|
console.warn('[GitService] Worktree start script task failed:', error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
setWorktreeBootstrapState(directory, WORKTREE_BOOTSTRAP_READY);
|
||||||
};
|
};
|
||||||
|
|
||||||
void run().catch((error) => {
|
void run().catch((error) => {
|
||||||
console.warn('[GitService] Worktree start script task failed:', error instanceof Error ? error.message : String(error));
|
setWorktreeBootstrapState(
|
||||||
|
directory,
|
||||||
|
WORKTREE_BOOTSTRAP_FAILED,
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
);
|
||||||
|
console.warn('[GitService] Worktree bootstrap task failed:', error instanceof Error ? error.message : String(error));
|
||||||
});
|
});
|
||||||
}, 0);
|
}, 0);
|
||||||
};
|
};
|
||||||
@@ -1584,6 +1667,28 @@ export async function validateWorktreeCreate(directory: string, input: CreateGit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function previewWorktreeCreate(directory: string, input: CreateGitWorktreePayload = {}): Promise<GitWorktreeInfo> {
|
||||||
|
const mode = input?.mode === 'existing' ? 'existing' : 'new';
|
||||||
|
const context = await resolveWorktreeProjectContext(directory);
|
||||||
|
await fs.promises.mkdir(context.worktreeRoot, { recursive: true });
|
||||||
|
|
||||||
|
const preferredName = String(input?.worktreeName || input?.name || '').trim();
|
||||||
|
const preferredBranchName = cleanBranchName(String(input?.branchName || '').trim());
|
||||||
|
const candidate = await resolveCandidateDirectory(
|
||||||
|
context.worktreeRoot,
|
||||||
|
preferredName,
|
||||||
|
mode === 'new' && preferredBranchName ? preferredBranchName : '',
|
||||||
|
context.primaryWorktree
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: candidate.name,
|
||||||
|
branch: mode === 'new' ? candidate.branch : preferredBranchName,
|
||||||
|
path: candidate.directory,
|
||||||
|
head: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function createWorktree(directory: string, input: CreateGitWorktreePayload = {}): Promise<GitWorktreeInfo> {
|
export async function createWorktree(directory: string, input: CreateGitWorktreePayload = {}): Promise<GitWorktreeInfo> {
|
||||||
const mode = input?.mode === 'existing' ? 'existing' : 'new';
|
const mode = input?.mode === 'existing' ? 'existing' : 'new';
|
||||||
const context = await resolveWorktreeProjectContext(directory);
|
const context = await resolveWorktreeProjectContext(directory);
|
||||||
@@ -1675,7 +1780,6 @@ export async function createWorktree(directory: string, input: CreateGitWorktree
|
|||||||
}
|
}
|
||||||
|
|
||||||
await runGitCommandOrThrow(context.primaryWorktree, worktreeAddArgs, 'Failed to create git worktree');
|
await runGitCommandOrThrow(context.primaryWorktree, worktreeAddArgs, 'Failed to create git worktree');
|
||||||
await runGitCommandOrThrow(candidate.directory, ['reset', '--hard'], 'Failed to populate worktree');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await syncProjectSandboxAdd(context.projectID, context.primaryWorktree, candidate.directory);
|
await syncProjectSandboxAdd(context.projectID, context.primaryWorktree, candidate.directory);
|
||||||
@@ -1687,20 +1791,20 @@ export async function createWorktree(directory: string, input: CreateGitWorktree
|
|||||||
const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
|
const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
|
||||||
const upstreamBranch = String(input?.upstreamBranch || inferredUpstream?.branch || '').trim();
|
const upstreamBranch = String(input?.upstreamBranch || inferredUpstream?.branch || '').trim();
|
||||||
|
|
||||||
if (shouldSetUpstream) {
|
setWorktreeBootstrapState(candidate.directory, WORKTREE_BOOTSTRAP_PENDING);
|
||||||
await applyUpstreamConfiguration({
|
|
||||||
primaryWorktree: context.primaryWorktree,
|
|
||||||
worktreeDirectory: candidate.directory,
|
|
||||||
localBranch,
|
|
||||||
setUpstream: shouldSetUpstream,
|
|
||||||
upstreamRemote,
|
|
||||||
upstreamBranch,
|
|
||||||
ensureRemoteName,
|
|
||||||
ensureRemoteUrl,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
queueWorktreeStartScripts(candidate.directory, context.projectID, input?.startCommand);
|
queueWorktreeBootstrap({
|
||||||
|
directory: candidate.directory,
|
||||||
|
projectID: context.projectID,
|
||||||
|
primaryWorktree: context.primaryWorktree,
|
||||||
|
localBranch,
|
||||||
|
setUpstream: shouldSetUpstream,
|
||||||
|
upstreamRemote,
|
||||||
|
upstreamBranch,
|
||||||
|
ensureRemoteName,
|
||||||
|
ensureRemoteUrl,
|
||||||
|
startCommand: input?.startCommand,
|
||||||
|
});
|
||||||
|
|
||||||
const headResult = await runGitCommand(candidate.directory, ['rev-parse', 'HEAD']);
|
const headResult = await runGitCommand(candidate.directory, ['rev-parse', 'HEAD']);
|
||||||
const head = String(headResult.stdout || '').trim();
|
const head = String(headResult.stdout || '').trim();
|
||||||
@@ -1713,6 +1817,24 @@ export async function createWorktree(directory: string, input: CreateGitWorktree
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getWorktreeBootstrapStatus(directory: string): Promise<{ status: 'pending' | 'ready' | 'failed'; error: string | null; updatedAt: number }> {
|
||||||
|
const key = toBootstrapStateKey(directory);
|
||||||
|
if (!key) {
|
||||||
|
throw new Error('Worktree directory is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = worktreeBootstrapState.get(key);
|
||||||
|
if (current) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: WORKTREE_BOOTSTRAP_READY,
|
||||||
|
error: null,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function removeWorktree(directory: string, input: RemoveGitWorktreePayload): Promise<boolean> {
|
export async function removeWorktree(directory: string, input: RemoveGitWorktreePayload): Promise<boolean> {
|
||||||
const targetDirectory = normalizeDirectoryPath(input?.directory);
|
const targetDirectory = normalizeDirectoryPath(input?.directory);
|
||||||
if (!targetDirectory) {
|
if (!targetDirectory) {
|
||||||
@@ -1754,6 +1876,8 @@ export async function removeWorktree(directory: string, input: RemoveGitWorktree
|
|||||||
console.warn('[GitService] Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
console.warn('[GitService] Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
clearWorktreeBootstrapState(targetDirectory);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1780,6 +1904,8 @@ export async function removeWorktree(directory: string, input: RemoveGitWorktree
|
|||||||
console.warn('[GitService] Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
console.warn('[GitService] Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
clearWorktreeBootstrapState(matchedEntry.worktree);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -142,6 +142,20 @@ export const createVSCodeGitAPI = (): GitAPI => ({
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getGitWorktreeBootstrapStatus: async (directory: string): Promise<{ status: 'pending' | 'ready' | 'failed'; error: string | null; updatedAt: number }> => {
|
||||||
|
return sendBridgeMessage<{ status: 'pending' | 'ready' | 'failed'; error: string | null; updatedAt: number }>('api:git/worktrees/bootstrap-status', {
|
||||||
|
directory,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
previewGitWorktree: async (directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult> => {
|
||||||
|
return sendBridgeMessage<GitWorktreeCreateResult>('api:git/worktrees/preview', {
|
||||||
|
directory,
|
||||||
|
method: 'POST',
|
||||||
|
...(payload || {}),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
createGitWorktree: async (directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult> => {
|
createGitWorktree: async (directory: string, payload: CreateGitWorktreePayload): Promise<GitWorktreeCreateResult> => {
|
||||||
return sendBridgeMessage<GitWorktreeCreateResult>('api:git/worktrees', {
|
return sendBridgeMessage<GitWorktreeCreateResult>('api:git/worktrees', {
|
||||||
directory,
|
directory,
|
||||||
|
|||||||
@@ -12529,6 +12529,46 @@ async function main(options = {}) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.post('/api/git/worktrees/preview', async (req, res) => {
|
||||||
|
const { previewWorktreeCreate } = await getGitLibraries();
|
||||||
|
if (typeof previewWorktreeCreate !== 'function') {
|
||||||
|
return res.status(501).json({ error: 'Worktree preview is not available' });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const directory = req.query.directory;
|
||||||
|
if (!directory || typeof directory !== 'string') {
|
||||||
|
return res.status(400).json({ error: 'directory parameter is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const preview = await previewWorktreeCreate(directory, req.body || {});
|
||||||
|
res.json(preview);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to preview worktree:', error);
|
||||||
|
res.status(500).json({ error: error.message || 'Failed to preview worktree' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/git/worktrees/bootstrap-status', async (req, res) => {
|
||||||
|
const { getWorktreeBootstrapStatus } = await getGitLibraries();
|
||||||
|
if (typeof getWorktreeBootstrapStatus !== 'function') {
|
||||||
|
return res.status(501).json({ error: 'Worktree bootstrap status is not available' });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const directory = req.query.directory;
|
||||||
|
if (!directory || typeof directory !== 'string') {
|
||||||
|
return res.status(400).json({ error: 'directory parameter is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = await getWorktreeBootstrapStatus(directory);
|
||||||
|
res.json(status);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to get worktree bootstrap status:', error);
|
||||||
|
res.status(500).json({ error: error.message || 'Failed to get worktree bootstrap status' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.delete('/api/git/worktrees', async (req, res) => {
|
app.delete('/api/git/worktrees', async (req, res) => {
|
||||||
const { removeWorktree } = await getGitLibraries();
|
const { removeWorktree } = await getGitLibraries();
|
||||||
if (typeof removeWorktree !== 'function') {
|
if (typeof removeWorktree !== 'function') {
|
||||||
|
|||||||
@@ -9,6 +9,39 @@ const fsp = fs.promises;
|
|||||||
const execFileAsync = promisify(execFile);
|
const execFileAsync = promisify(execFile);
|
||||||
const gpgconfCandidates = ['gpgconf', '/opt/homebrew/bin/gpgconf', '/usr/local/bin/gpgconf'];
|
const gpgconfCandidates = ['gpgconf', '/opt/homebrew/bin/gpgconf', '/usr/local/bin/gpgconf'];
|
||||||
let resolvedGitBinary = null;
|
let resolvedGitBinary = null;
|
||||||
|
const worktreeBootstrapState = new Map();
|
||||||
|
|
||||||
|
const WORKTREE_BOOTSTRAP_PENDING = 'pending';
|
||||||
|
const WORKTREE_BOOTSTRAP_READY = 'ready';
|
||||||
|
const WORKTREE_BOOTSTRAP_FAILED = 'failed';
|
||||||
|
|
||||||
|
const toBootstrapStateKey = (directory) => {
|
||||||
|
const normalized = normalizeDirectoryPath(directory);
|
||||||
|
if (!normalized) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return path.resolve(normalized);
|
||||||
|
};
|
||||||
|
|
||||||
|
const setWorktreeBootstrapState = (directory, status, error = null) => {
|
||||||
|
const key = toBootstrapStateKey(directory);
|
||||||
|
if (!key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
worktreeBootstrapState.set(key, {
|
||||||
|
status,
|
||||||
|
error: typeof error === 'string' && error.trim().length > 0 ? error.trim() : null,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearWorktreeBootstrapState = (directory) => {
|
||||||
|
const key = toBootstrapStateKey(directory);
|
||||||
|
if (!key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
worktreeBootstrapState.delete(key);
|
||||||
|
};
|
||||||
|
|
||||||
const isExecutableFile = (candidate) => {
|
const isExecutableFile = (candidate) => {
|
||||||
if (typeof candidate !== 'string' || candidate.trim().length === 0) {
|
if (typeof candidate !== 'string' || candidate.trim().length === 0) {
|
||||||
@@ -845,30 +878,69 @@ const syncProjectSandboxRemove = async (projectID, primaryWorktree, sandboxPath)
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const queueWorktreeStartScripts = (directory, projectID, startCommand) => {
|
const runWorktreeStartScripts = async (directory, projectID, startCommand) => {
|
||||||
|
const projectStart = await loadProjectStartCommand(projectID);
|
||||||
|
if (projectStart) {
|
||||||
|
const projectResult = await runWorktreeStartCommand(directory, projectStart);
|
||||||
|
if (!projectResult.success) {
|
||||||
|
console.warn('Worktree project start command failed:', projectResult.message || projectResult.stderr || projectResult.stdout);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const extraCommand = String(startCommand || '').trim();
|
||||||
|
if (!extraCommand) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const extraResult = await runWorktreeStartCommand(directory, extraCommand);
|
||||||
|
if (!extraResult.success) {
|
||||||
|
console.warn('Worktree start command failed:', extraResult.message || extraResult.stderr || extraResult.stdout);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const queueWorktreeBootstrap = (args) => {
|
||||||
|
const {
|
||||||
|
directory,
|
||||||
|
projectID,
|
||||||
|
primaryWorktree,
|
||||||
|
localBranch,
|
||||||
|
setUpstream,
|
||||||
|
upstreamRemote,
|
||||||
|
upstreamBranch,
|
||||||
|
ensureRemoteName,
|
||||||
|
ensureRemoteUrl,
|
||||||
|
startCommand,
|
||||||
|
} = args;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
const projectStart = await loadProjectStartCommand(projectID);
|
await runGitCommandOrThrow(directory, ['reset', '--hard'], 'Failed to populate worktree');
|
||||||
if (projectStart) {
|
if (setUpstream) {
|
||||||
const projectResult = await runWorktreeStartCommand(directory, projectStart);
|
await applyUpstreamConfiguration({
|
||||||
if (!projectResult.success) {
|
primaryWorktree,
|
||||||
console.warn('Worktree project start command failed:', projectResult.message || projectResult.stderr || projectResult.stdout);
|
worktreeDirectory: directory,
|
||||||
return;
|
localBranch,
|
||||||
}
|
setUpstream,
|
||||||
}
|
upstreamRemote,
|
||||||
|
upstreamBranch,
|
||||||
const extraCommand = String(startCommand || '').trim();
|
ensureRemoteName,
|
||||||
if (!extraCommand) {
|
ensureRemoteUrl,
|
||||||
return;
|
}).catch((error) => {
|
||||||
}
|
console.warn('Worktree upstream configuration failed:', error instanceof Error ? error.message : String(error));
|
||||||
const extraResult = await runWorktreeStartCommand(directory, extraCommand);
|
});
|
||||||
if (!extraResult.success) {
|
|
||||||
console.warn('Worktree start command failed:', extraResult.message || extraResult.stderr || extraResult.stdout);
|
|
||||||
}
|
}
|
||||||
|
await runWorktreeStartScripts(directory, projectID, startCommand).catch((error) => {
|
||||||
|
console.warn('Worktree start script task failed:', error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
setWorktreeBootstrapState(directory, WORKTREE_BOOTSTRAP_READY);
|
||||||
};
|
};
|
||||||
|
|
||||||
void run().catch((error) => {
|
void run().catch((error) => {
|
||||||
console.warn('Worktree start script task failed:', error instanceof Error ? error.message : String(error));
|
setWorktreeBootstrapState(
|
||||||
|
directory,
|
||||||
|
WORKTREE_BOOTSTRAP_FAILED,
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
);
|
||||||
|
console.warn('Worktree bootstrap task failed:', error instanceof Error ? error.message : String(error));
|
||||||
});
|
});
|
||||||
}, 0);
|
}, 0);
|
||||||
};
|
};
|
||||||
@@ -2226,6 +2298,27 @@ export async function validateWorktreeCreate(directory, input = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function previewWorktreeCreate(directory, input = {}) {
|
||||||
|
const mode = input?.mode === 'existing' ? 'existing' : 'new';
|
||||||
|
const context = await resolveWorktreeProjectContext(directory);
|
||||||
|
await fsp.mkdir(context.worktreeRoot, { recursive: true });
|
||||||
|
|
||||||
|
const preferredName = String(input?.worktreeName || input?.name || '').trim();
|
||||||
|
const preferredBranchName = cleanBranchName(String(input?.branchName || '').trim());
|
||||||
|
const candidate = await resolveCandidateDirectory(
|
||||||
|
context.worktreeRoot,
|
||||||
|
preferredName,
|
||||||
|
mode === 'new' && preferredBranchName ? preferredBranchName : '',
|
||||||
|
context.primaryWorktree
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: candidate.name,
|
||||||
|
branch: mode === 'new' ? candidate.branch : preferredBranchName,
|
||||||
|
path: candidate.directory,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function createWorktree(directory, input = {}) {
|
export async function createWorktree(directory, input = {}) {
|
||||||
const mode = input?.mode === 'existing' ? 'existing' : 'new';
|
const mode = input?.mode === 'existing' ? 'existing' : 'new';
|
||||||
const context = await resolveWorktreeProjectContext(directory);
|
const context = await resolveWorktreeProjectContext(directory);
|
||||||
@@ -2317,7 +2410,6 @@ export async function createWorktree(directory, input = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await runGitCommandOrThrow(context.primaryWorktree, worktreeAddArgs, 'Failed to create git worktree');
|
await runGitCommandOrThrow(context.primaryWorktree, worktreeAddArgs, 'Failed to create git worktree');
|
||||||
await runGitCommandOrThrow(candidate.directory, ['reset', '--hard'], 'Failed to populate worktree');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await syncProjectSandboxAdd(context.projectID, context.primaryWorktree, candidate.directory);
|
await syncProjectSandboxAdd(context.projectID, context.primaryWorktree, candidate.directory);
|
||||||
@@ -2329,20 +2421,20 @@ export async function createWorktree(directory, input = {}) {
|
|||||||
const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
|
const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
|
||||||
const upstreamBranch = String(input?.upstreamBranch || inferredUpstream?.branch || '').trim();
|
const upstreamBranch = String(input?.upstreamBranch || inferredUpstream?.branch || '').trim();
|
||||||
|
|
||||||
if (shouldSetUpstream) {
|
setWorktreeBootstrapState(candidate.directory, WORKTREE_BOOTSTRAP_PENDING);
|
||||||
await applyUpstreamConfiguration({
|
|
||||||
primaryWorktree: context.primaryWorktree,
|
|
||||||
worktreeDirectory: candidate.directory,
|
|
||||||
localBranch,
|
|
||||||
setUpstream: shouldSetUpstream,
|
|
||||||
upstreamRemote,
|
|
||||||
upstreamBranch,
|
|
||||||
ensureRemoteName,
|
|
||||||
ensureRemoteUrl,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
queueWorktreeStartScripts(candidate.directory, context.projectID, input?.startCommand);
|
queueWorktreeBootstrap({
|
||||||
|
directory: candidate.directory,
|
||||||
|
projectID: context.projectID,
|
||||||
|
primaryWorktree: context.primaryWorktree,
|
||||||
|
localBranch,
|
||||||
|
setUpstream: shouldSetUpstream,
|
||||||
|
upstreamRemote,
|
||||||
|
upstreamBranch,
|
||||||
|
ensureRemoteName,
|
||||||
|
ensureRemoteUrl,
|
||||||
|
startCommand: input?.startCommand,
|
||||||
|
});
|
||||||
|
|
||||||
const headResult = await runGitCommand(candidate.directory, ['rev-parse', 'HEAD']);
|
const headResult = await runGitCommand(candidate.directory, ['rev-parse', 'HEAD']);
|
||||||
const head = String(headResult.stdout || '').trim();
|
const head = String(headResult.stdout || '').trim();
|
||||||
@@ -2355,6 +2447,24 @@ export async function createWorktree(directory, input = {}) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getWorktreeBootstrapStatus(directory) {
|
||||||
|
const key = toBootstrapStateKey(directory);
|
||||||
|
if (!key) {
|
||||||
|
throw new Error('Worktree directory is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = worktreeBootstrapState.get(key);
|
||||||
|
if (current) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: WORKTREE_BOOTSTRAP_READY,
|
||||||
|
error: null,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function removeWorktree(directory, input = {}) {
|
export async function removeWorktree(directory, input = {}) {
|
||||||
const targetDirectory = normalizeDirectoryPath(input?.directory);
|
const targetDirectory = normalizeDirectoryPath(input?.directory);
|
||||||
if (!targetDirectory) {
|
if (!targetDirectory) {
|
||||||
@@ -2396,6 +2506,8 @@ export async function removeWorktree(directory, input = {}) {
|
|||||||
console.warn('Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
console.warn('Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
clearWorktreeBootstrapState(targetDirectory);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2422,6 +2534,8 @@ export async function removeWorktree(directory, input = {}) {
|
|||||||
console.warn('Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
console.warn('Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
clearWorktreeBootstrapState(matchedEntry.worktree);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user