diff --git a/frontend/src/components/ui-new/actions/index.ts b/frontend/src/components/ui-new/actions/index.ts index 0dd213937c..3d80f540b5 100644 --- a/frontend/src/components/ui-new/actions/index.ts +++ b/frontend/src/components/ui-new/actions/index.ts @@ -29,6 +29,7 @@ import { SpinnerIcon, GitPullRequestIcon, GitMergeIcon, + GitForkIcon, ArrowsClockwiseIcon, CrosshairIcon, DesktopIcon, @@ -241,12 +242,21 @@ export const Actions = { requiresTarget: true, execute: async (ctx, workspaceId) => { try { - const firstMessage = await attemptsApi.getFirstUserMessage(workspaceId); + const [firstMessage, repos] = await Promise.all([ + attemptsApi.getFirstUserMessage(workspaceId), + attemptsApi.getRepos(workspaceId), + ]); ctx.navigate('/workspaces/create', { - state: { duplicatePrompt: firstMessage }, + state: { + initialPrompt: firstMessage, + preferredRepos: repos.map((r) => ({ + repo_id: r.id, + target_branch: r.target_branch, + })), + }, }); } catch { - // Fallback to creating without the prompt + // Fallback to creating without the prompt/repos ctx.navigate('/workspaces/create'); } }, @@ -363,6 +373,32 @@ export const Actions = { }, }, + SpinOffWorkspace: { + id: 'spin-off-workspace', + label: 'Spin off workspace', + icon: GitForkIcon, + requiresTarget: true, + isVisible: (ctx) => ctx.hasWorkspace, + execute: async (ctx, workspaceId) => { + try { + const [workspace, repos] = await Promise.all([ + getWorkspace(ctx.queryClient, workspaceId), + attemptsApi.getRepos(workspaceId), + ]); + ctx.navigate('/workspaces/create', { + state: { + preferredRepos: repos.map((r) => ({ + repo_id: r.id, + target_branch: workspace.branch, + })), + }, + }); + } catch { + ctx.navigate('/workspaces/create'); + } + }, + }, + // === Global/Navigation Actions === NewWorkspace: { id: 'new-workspace', diff --git a/frontend/src/components/ui-new/actions/pages.ts b/frontend/src/components/ui-new/actions/pages.ts index 4eb03922a5..ed7cf1db6a 100644 --- a/frontend/src/components/ui-new/actions/pages.ts +++ b/frontend/src/components/ui-new/actions/pages.ts @@ -112,6 +112,7 @@ export const Pages: Record = { { type: 'action', action: Actions.StartReview }, { type: 'action', action: Actions.RenameWorkspace }, { type: 'action', action: Actions.DuplicateWorkspace }, + { type: 'action', action: Actions.SpinOffWorkspace }, { type: 'action', action: Actions.PinWorkspace }, { type: 'action', action: Actions.ArchiveWorkspace }, { type: 'action', action: Actions.DeleteWorkspace }, diff --git a/frontend/src/components/ui-new/containers/CreateModeReposSectionContainer.tsx b/frontend/src/components/ui-new/containers/CreateModeReposSectionContainer.tsx index 54cf4f10b5..f191b2a634 100644 --- a/frontend/src/components/ui-new/containers/CreateModeReposSectionContainer.tsx +++ b/frontend/src/components/ui-new/containers/CreateModeReposSectionContainer.tsx @@ -13,9 +13,12 @@ export function CreateModeReposSectionContainer() { const repoIds = useMemo(() => repos.map((r) => r.id), [repos]); const { branchesByRepo } = useMultiRepoBranches(repoIds); + // Auto-select branch for repos that don't have one set + // (e.g., repos added by user after initialization) useEffect(() => { repos.forEach((repo) => { const branches = branchesByRepo[repo.id]; + // Only auto-select if branch is empty (not already set) if (branches && !targetBranches[repo.id]) { if ( repo.default_target_branch && diff --git a/frontend/src/components/ui-new/primitives/SelectedReposList.tsx b/frontend/src/components/ui-new/primitives/SelectedReposList.tsx index 831788b17c..68a90542aa 100644 --- a/frontend/src/components/ui-new/primitives/SelectedReposList.tsx +++ b/frontend/src/components/ui-new/primitives/SelectedReposList.tsx @@ -7,7 +7,7 @@ interface SelectedReposListProps { repos: Repo[]; onRemove: (repoId: string) => void; branchesByRepo?: Record; - selectedBranches?: Record; + selectedBranches?: Record; onBranchChange?: (repoId: string, branch: string) => void; } diff --git a/frontend/src/contexts/CreateModeContext.tsx b/frontend/src/contexts/CreateModeContext.tsx index 1e6ffdb097..8d964a66fc 100644 --- a/frontend/src/contexts/CreateModeContext.tsx +++ b/frontend/src/contexts/CreateModeContext.tsx @@ -12,7 +12,7 @@ interface CreateModeContextValue { addRepo: (repo: Repo) => void; removeRepo: (repoId: string) => void; clearRepos: () => void; - targetBranches: Record; + targetBranches: Record; setTargetBranch: (repoId: string, branch: string) => void; selectedProfile: ExecutorProfileId | null; setSelectedProfile: (profile: ExecutorProfileId | null) => void; diff --git a/frontend/src/hooks/useCreateModeState.ts b/frontend/src/hooks/useCreateModeState.ts index bfe247329d..77ded60121 100644 --- a/frontend/src/hooks/useCreateModeState.ts +++ b/frontend/src/hooks/useCreateModeState.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import type { DraftWorkspaceData, @@ -13,13 +13,140 @@ import { useProjects } from '@/hooks/useProjects'; import { useUserSystem } from '@/components/ConfigProvider'; import { projectsApi, repoApi } from '@/lib/api'; +// ============================================================================ +// Types +// ============================================================================ + interface LocationState { - duplicatePrompt?: string | null; + initialPrompt?: string | null; + preferredRepos?: Array<{ + repo_id: string; + target_branch: string | null; + }> | null; } -// Fixed UUID for the universal workspace draft +/** Unified repo model - keeps repo and branch together */ +interface SelectedRepo { + repo: Repo; + targetBranch: string | null; +} + +type Phase = 'loading' | 'ready' | 'error'; + +interface DraftState { + phase: Phase; + error: string | null; + projectId: string | null; + repos: SelectedRepo[]; + profile: ExecutorProfileId | null; + message: string; +} + +type DraftAction = + | { + type: 'INIT_COMPLETE'; + data: Partial>; + } + | { type: 'INIT_ERROR'; error: string } + | { type: 'SET_PROJECT'; projectId: string | null } + | { type: 'ADD_REPO'; repo: Repo; targetBranch: string | null } + | { type: 'REMOVE_REPO'; repoId: string } + | { type: 'SET_TARGET_BRANCH'; repoId: string; branch: string } + | { type: 'SET_PROFILE'; profile: ExecutorProfileId | null } + | { type: 'SET_MESSAGE'; message: string } + | { type: 'CLEAR_REPOS' } + | { type: 'CLEAR' }; + +// ============================================================================ +// Reducer +// ============================================================================ + +const initialState: DraftState = { + phase: 'loading', + error: null, + projectId: null, + repos: [], + profile: null, + message: '', +}; + +function draftReducer(state: DraftState, action: DraftAction): DraftState { + switch (action.type) { + case 'INIT_COMPLETE': + return { + ...state, + phase: 'ready', + error: null, + ...action.data, + }; + + case 'INIT_ERROR': + return { + ...state, + phase: 'error', + error: action.error, + }; + + case 'SET_PROJECT': + return { ...state, projectId: action.projectId }; + + case 'ADD_REPO': { + // Don't add duplicate repos + if (state.repos.some((r) => r.repo.id === action.repo.id)) { + return state; + } + return { + ...state, + repos: [ + ...state.repos, + { repo: action.repo, targetBranch: action.targetBranch }, + ], + }; + } + + case 'REMOVE_REPO': + return { + ...state, + repos: state.repos.filter((r) => r.repo.id !== action.repoId), + }; + + case 'SET_TARGET_BRANCH': + return { + ...state, + repos: state.repos.map((r) => + r.repo.id === action.repoId + ? { ...r, targetBranch: action.branch } + : r + ), + }; + + case 'SET_PROFILE': + return { ...state, profile: action.profile }; + + case 'SET_MESSAGE': + return { ...state, message: action.message }; + + case 'CLEAR_REPOS': + return { ...state, repos: [] }; + + case 'CLEAR': + return { ...initialState, phase: 'ready' }; + + default: + return state; + } +} + +// ============================================================================ +// Constants +// ============================================================================ + const DRAFT_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001'; +// ============================================================================ +// Hook +// ============================================================================ + interface UseCreateModeStateParams { initialProjectId?: string; initialRepos?: RepoWithTargetBranch[]; @@ -29,11 +156,10 @@ interface UseCreateModeStateResult { // State selectedProjectId: string | null; repos: Repo[]; - targetBranches: Record; + targetBranches: Record; selectedProfile: ExecutorProfileId | null; message: string; isLoading: boolean; - /** Whether the initial value has been applied from scratch */ hasInitialValue: boolean; // Actions @@ -51,226 +177,119 @@ export function useCreateModeState({ initialProjectId, initialRepos, }: UseCreateModeStateParams): UseCreateModeStateResult { - // Router hooks for duplicate prompt handling const location = useLocation(); const navigate = useNavigate(); - const locationState = location.state as LocationState | null; - - // Fetch validation data - const { projectsById, isLoading } = useProjects(); + const { projectsById, isLoading: projectsLoading } = useProjects(); const { profiles } = useUserSystem(); - // Initialization guards - const hasInitializedFromScratch = useRef(false); - const hasInitializedRepos = useRef(false); - const hasInitializedProject = useRef(false); - const hasAppliedDuplicatePrompt = useRef(false); + const { + scratch, + updateScratch, + deleteScratch, + isLoading: scratchLoading, + } = useScratch(ScratchType.DRAFT_WORKSPACE, DRAFT_WORKSPACE_ID); - // Validation helper for executor profiles - const isValidProfile = useMemo(() => { - return (profile: ExecutorProfileId | null): boolean => { + const [state, dispatch] = useReducer(draftReducer, initialState); + + // Capture navigation state once on mount + const navStateRef = useRef( + location.state as LocationState | null + ); + const hasInitialized = useRef(false); + + // Profile validator + const isValidProfile = useCallback( + (profile: ExecutorProfileId | null): boolean => { if (!profile || !profiles) return false; const { executor, variant } = profile; if (!(executor in profiles)) return false; if (variant === null) return true; return variant in profiles[executor]; - }; - }, [profiles]); - - // Core state - const [selectedProjectId, setSelectedProjectId] = useState( - null + }, + [profiles] ); - const [repos, setRepos] = useState([]); - const [targetBranches, setTargetBranches] = useState>( - {} - ); - const [selectedProfile, setSelectedProfile] = - useState(null); - const [message, setMessage] = useState(''); - const [hasInitialValue, setHasInitialValue] = useState(false); - // Scratch persistence - const { - scratch, - updateScratch, - deleteScratch, - isLoading: isScratchLoading, - } = useScratch(ScratchType.DRAFT_WORKSPACE, DRAFT_WORKSPACE_ID); - - const scratchData: DraftWorkspaceData | undefined = - scratch?.payload?.type === 'DRAFT_WORKSPACE' - ? scratch.payload.data - : undefined; - - // Initialize from scratch (once, when all required data is available) + // ============================================================================ + // Single initialization effect + // ============================================================================ useEffect(() => { - if (hasInitializedFromScratch.current) return; - if (isScratchLoading) return; - if (!initialRepos) return; - if (!projectsById) return; // Wait for projects to validate - if (!profiles) return; // Wait for profiles to validate + if (hasInitialized.current) return; + if (scratchLoading) return; + if (!projectsById) return; + if (!profiles) return; + if (initialRepos === undefined) return; // Wait for initial repos to be defined (can be empty array) - hasInitializedFromScratch.current = true; - setHasInitialValue(true); + hasInitialized.current = true; + const navState = navStateRef.current; - if (!scratchData) return; - - // Restore message (no validation needed) - if (scratchData.message) { - setMessage(scratchData.message); + // Clear navigation state immediately to prevent re-initialization + if (navState?.preferredRepos || navState?.initialPrompt) { + navigate(location.pathname, { replace: true, state: {} }); } - // Restore project_id only if it still exists - if (scratchData.project_id && scratchData.project_id in projectsById) { - setSelectedProjectId(scratchData.project_id); - hasInitializedProject.current = true; - } - - // Restore executor profile only if it's still valid - if ( - scratchData.selected_profile && - isValidProfile(scratchData.selected_profile) - ) { - setSelectedProfile(scratchData.selected_profile); - } - - // Restore repos (async - fetch any missing from API) - if (scratchData.repos.length > 0) { - const restoreRepos = async () => { - const initialRepoMap = new Map(initialRepos.map((r) => [r.id, r])); - const missingIds = scratchData.repos - .map((r) => r.repo_id) - .filter((id) => !initialRepoMap.has(id)); - - let allRepos: (Repo | RepoWithTargetBranch)[] = [...initialRepos]; - if (missingIds.length > 0) { - try { - const fetchedRepos = await repoApi.getBatch(missingIds); - allRepos = [...initialRepos, ...fetchedRepos]; - } catch (e) { - console.error('[useCreateModeState] Failed to fetch repos:', e); - } - } - - const repoMap = new Map(allRepos.map((r) => [r.id, r])); - const restoredRepos: Repo[] = []; - const restoredBranches: Record = {}; - - for (const draftRepo of scratchData.repos) { - const fullRepo = repoMap.get(draftRepo.repo_id); - if (fullRepo) { - restoredRepos.push(fullRepo); - restoredBranches[draftRepo.repo_id] = draftRepo.target_branch; - } - } - - if (restoredRepos.length > 0) { - hasInitializedRepos.current = true; - setRepos(restoredRepos); - setTargetBranches(restoredBranches); - } - }; - - restoreRepos(); - } + // Determine initialization source and execute + initializeState({ + navState, + scratch, + initialRepos, + initialProjectId, + projectsById, + profiles, + isValidProfile, + dispatch, + }); }, [ - isScratchLoading, - scratchData, - initialRepos, + scratchLoading, projectsById, profiles, + initialRepos, + initialProjectId, + scratch, isValidProfile, + navigate, + location.pathname, ]); - // Initialize repos from props (if not restored from scratch) - useEffect(() => { - if ( - !hasInitializedRepos.current && - initialRepos && - initialRepos.length > 0 - ) { - hasInitializedRepos.current = true; - setRepos(initialRepos); - setTargetBranches( - initialRepos.reduce( - (acc, repo) => { - acc[repo.id] = repo.target_branch; - return acc; - }, - {} as Record - ) - ); - } - }, [initialRepos]); - - // Initialize project from props (if not restored from scratch) - useEffect(() => { - if (!hasInitializedProject.current && initialProjectId) { - hasInitializedProject.current = true; - setSelectedProjectId(initialProjectId); - } - }, [initialProjectId]); - - // Track if we've attempted auto-selection + // ============================================================================ + // Auto-select project when none selected + // ============================================================================ const hasAttemptedAutoSelect = useRef(false); - // Auto-select first project or create "My first project" when no project is selected useEffect(() => { - // Wait for scratch initialization to complete (hasInitialValue is set after initialization) - if (!hasInitialValue) return; - // Only run once + if (state.phase !== 'ready') return; if (hasAttemptedAutoSelect.current) return; - // Skip if already have a project from scratch or props - if (selectedProjectId) return; - // Wait for projects to load - if (!projectsById || isLoading) return; + if (state.projectId) return; + if (!projectsById || projectsLoading) return; hasAttemptedAutoSelect.current = true; const projectsList = Object.values(projectsById); - if (projectsList.length > 0) { - // Auto-select the first project (sorted by created_at desc) const sortedProjects = [...projectsList].sort( (a, b) => new Date(b.created_at as unknown as string).getTime() - new Date(a.created_at as unknown as string).getTime() ); - setSelectedProjectId(sortedProjects[0].id); + dispatch({ type: 'SET_PROJECT', projectId: sortedProjects[0].id }); } else { - // Create "My first project" if no projects exist - const createDefaultProject = async () => { - try { - const newProject = await projectsApi.create({ - name: 'My first project', - repositories: [], - }); - setSelectedProjectId(newProject.id); - } catch (e) { + // Create default project + projectsApi + .create({ name: 'My first project', repositories: [] }) + .then((newProject) => { + dispatch({ type: 'SET_PROJECT', projectId: newProject.id }); + }) + .catch((e) => { console.error( '[useCreateModeState] Failed to create default project:', e ); - } - }; - createDefaultProject(); + }); } - }, [hasInitialValue, selectedProjectId, projectsById, isLoading]); + }, [state.phase, state.projectId, projectsById, projectsLoading]); - // Handle duplicate prompt from navigation state - useEffect(() => { - if (hasAppliedDuplicatePrompt.current) return; - if (!locationState?.duplicatePrompt) return; - - hasAppliedDuplicatePrompt.current = true; - setMessage(locationState.duplicatePrompt); - - // Clear the navigation state to prevent re-applying on subsequent renders - navigate(location.pathname, { replace: true, state: {} }); - }, [locationState, location.pathname, navigate]); - - // Debounced save to scratch + // ============================================================================ + // Persistence to scratch (debounced) + // ============================================================================ const { debounced: debouncedSave } = useDebouncedCallback( async (data: DraftWorkspaceData) => { const isEmpty = @@ -283,10 +302,7 @@ export function useCreateModeState({ try { await updateScratch({ - payload: { - type: 'DRAFT_WORKSPACE', - data, - }, + payload: { type: 'DRAFT_WORKSPACE', data }, }); } catch (e) { console.error('[useCreateModeState] Failed to save:', e); @@ -295,69 +311,96 @@ export function useCreateModeState({ 500 ); - // Save state changes to scratch useEffect(() => { - if (!hasInitializedFromScratch.current) return; + if (state.phase !== 'ready') return; debouncedSave({ - message, - project_id: selectedProjectId, - repos: repos.map((r) => ({ - repo_id: r.id, - target_branch: targetBranches[r.id] ?? 'main', + message: state.message, + project_id: state.projectId, + repos: state.repos.map((r) => ({ + repo_id: r.repo.id, + target_branch: r.targetBranch ?? '', })), - selected_profile: selectedProfile, + selected_profile: state.profile, }); }, [ - message, - selectedProjectId, - repos, - targetBranches, - selectedProfile, + state.phase, + state.message, + state.projectId, + state.repos, + state.profile, debouncedSave, ]); + // ============================================================================ + // Derived state + // ============================================================================ + const repos = useMemo(() => state.repos.map((r) => r.repo), [state.repos]); + + const targetBranches = useMemo( + () => + state.repos.reduce( + (acc, r) => { + acc[r.repo.id] = r.targetBranch; + return acc; + }, + {} as Record + ), + [state.repos] + ); + + // ============================================================================ // Actions + // ============================================================================ + const setSelectedProjectId = useCallback((id: string | null) => { + dispatch({ type: 'SET_PROJECT', projectId: id }); + }, []); + + const setMessage = useCallback((message: string) => { + dispatch({ type: 'SET_MESSAGE', message }); + }, []); + + const setSelectedProfile = useCallback( + (profile: ExecutorProfileId | null) => { + dispatch({ type: 'SET_PROFILE', profile }); + }, + [] + ); + const addRepo = useCallback((repo: Repo) => { - setRepos((prev) => - prev.some((r) => r.id === repo.id) ? prev : [...prev, repo] - ); + // Default branch will be auto-selected by CreateModeReposSectionContainer + dispatch({ type: 'ADD_REPO', repo, targetBranch: null }); }, []); const removeRepo = useCallback((repoId: string) => { - setRepos((prev) => prev.filter((r) => r.id !== repoId)); - setTargetBranches((prev) => { - const next = { ...prev }; - delete next[repoId]; - return next; - }); + dispatch({ type: 'REMOVE_REPO', repoId }); }, []); const clearRepos = useCallback(() => { - setRepos([]); - setTargetBranches({}); + dispatch({ type: 'CLEAR_REPOS' }); }, []); const setTargetBranch = useCallback((repoId: string, branch: string) => { - setTargetBranches((prev) => ({ ...prev, [repoId]: branch })); + dispatch({ type: 'SET_TARGET_BRANCH', repoId, branch }); }, []); const clearDraft = useCallback(async () => { try { await deleteScratch(); + dispatch({ type: 'CLEAR' }); } catch (e) { console.error('[useCreateModeState] Failed to clear:', e); } }, [deleteScratch]); return { - selectedProjectId, + selectedProjectId: state.projectId, repos, targetBranches, - selectedProfile, - message, - isLoading: isScratchLoading, - hasInitialValue, + selectedProfile: state.profile, + message: state.message, + isLoading: scratchLoading, + hasInitialValue: state.phase === 'ready', setSelectedProjectId, setMessage, setSelectedProfile, @@ -368,3 +411,171 @@ export function useCreateModeState({ clearDraft, }; } + +// ============================================================================ +// Initialization helper (pure-ish function for testability) +// ============================================================================ + +interface InitializeParams { + navState: LocationState | null; + scratch: ReturnType['scratch']; + initialRepos: RepoWithTargetBranch[] | undefined; + initialProjectId: string | undefined; + projectsById: Record; + profiles: Record>; + isValidProfile: (profile: ExecutorProfileId | null) => boolean; + dispatch: React.Dispatch; +} + +async function initializeState({ + navState, + scratch, + initialRepos, + initialProjectId, + projectsById, + isValidProfile, + dispatch, +}: InitializeParams): Promise { + try { + // Priority 1: Navigation state (preferredRepos and/or initialPrompt) + const hasPreferredRepos = + navState?.preferredRepos && navState.preferredRepos.length > 0; + const hasInitialPrompt = !!navState?.initialPrompt; + + if (hasPreferredRepos || hasInitialPrompt) { + const data: Partial = {}; + let appliedNavState = false; + + // Handle preferred repos + if (hasPreferredRepos) { + const repoIds = navState!.preferredRepos!.map((r) => r.repo_id); + try { + const fetchedRepos = await repoApi.getBatch(repoIds); + + data.repos = fetchedRepos.map((repo) => { + const pref = navState!.preferredRepos!.find( + (p) => p.repo_id === repo.id + ); + return { repo, targetBranch: pref?.target_branch || null }; + }); + appliedNavState = data.repos.length > 0; + } catch (e) { + console.warn( + '[useCreateModeState] Failed to load preferred repos:', + e + ); + } + } + + // Handle initial prompt (can be combined with preferred repos) + if (hasInitialPrompt) { + data.message = navState!.initialPrompt!; + appliedNavState = true; + } + + if (appliedNavState) { + dispatch({ type: 'INIT_COMPLETE', data }); + return; + } + } + + // Priority 3: Restore from scratch + const scratchData: DraftWorkspaceData | undefined = + scratch?.payload?.type === 'DRAFT_WORKSPACE' + ? scratch.payload.data + : undefined; + + if (scratchData) { + const restoredData: Partial = {}; + + // Restore message + if (scratchData.message) { + restoredData.message = scratchData.message; + } + + // Restore project if it still exists + if (scratchData.project_id && scratchData.project_id in projectsById) { + restoredData.projectId = scratchData.project_id; + } + + // Restore profile if still valid + if ( + scratchData.selected_profile && + isValidProfile(scratchData.selected_profile) + ) { + restoredData.profile = scratchData.selected_profile; + } + + // Restore repos + if (scratchData.repos.length > 0) { + const initialRepoMap = new Map( + (initialRepos ?? []).map((r) => [r.id, r]) + ); + const missingIds = scratchData.repos + .map((r) => r.repo_id) + .filter((id) => !initialRepoMap.has(id)); + + let allRepos: (Repo | RepoWithTargetBranch)[] = [ + ...(initialRepos ?? []), + ]; + if (missingIds.length > 0) { + try { + const fetched = await repoApi.getBatch(missingIds); + allRepos = [...allRepos, ...fetched]; + } catch { + // Continue without missing repos + } + } + + const repoMap = new Map(allRepos.map((r) => [r.id, r])); + const restoredRepos: SelectedRepo[] = []; + + for (const draftRepo of scratchData.repos) { + const fullRepo = repoMap.get(draftRepo.repo_id); + if (fullRepo) { + restoredRepos.push({ + repo: fullRepo, + targetBranch: draftRepo.target_branch || null, + }); + } + } + + if (restoredRepos.length > 0) { + restoredData.repos = restoredRepos; + } + } + + dispatch({ type: 'INIT_COMPLETE', data: restoredData }); + return; + } + + // Priority 4: Use initial repos/project from props + if (initialRepos && initialRepos.length > 0) { + const repos: SelectedRepo[] = initialRepos.map((r) => ({ + repo: r, + targetBranch: r.target_branch || null, + })); + + dispatch({ + type: 'INIT_COMPLETE', + data: { + repos, + projectId: initialProjectId ?? null, + }, + }); + return; + } + + // Priority 5: Fresh start + dispatch({ + type: 'INIT_COMPLETE', + data: { projectId: initialProjectId ?? null }, + }); + } catch (e) { + console.error('[useCreateModeState] Initialization failed:', e); + dispatch({ + type: 'INIT_ERROR', + error: e instanceof Error ? e.message : 'Failed to initialize', + }); + } +}