"use client"; import { FormEvent, useCallback } from "react"; import type { JiraTicket } from "@/lib/types/jira"; import { Dialog, DialogContent, DialogHeader, DialogFooter } from "@kandev/ui/dialog"; import type { Task } from "@/lib/types/http"; import type { AgentProfileOption } from "@/lib/state/slices"; import { SHORTCUTS } from "@/lib/keyboard/constants"; import { useIsUtilityConfigured } from "@/hooks/use-is-utility-configured"; import { useKeyboardShortcutHandler } from "@/hooks/use-keyboard-shortcut"; import { useUtilityAgentGenerator } from "@/hooks/use-utility-agent-generator"; import { TaskCreateDialogFooter } from "@/components/task-create-dialog-footer"; import { DiscardLocalChangesDialog } from "@/components/discard-local-changes-dialog"; import { DialogHeaderContent } from "@/components/task-create-dialog-header"; import { CreateEditSelectors, SessionSelectors, WorkflowSection, DialogPromptSection, } from "@/components/task-create-dialog-form-body"; import { useBranchOptions, useAgentProfileOptions } from "@/components/task-create-dialog-options"; import { BranchSelector, AgentSelector, ExecutorProfileSelector, } from "@/components/task-create-dialog-selectors"; import { useTaskSubmitHandlers } from "@/components/task-create-dialog-submit"; import { useToast } from "@/components/toast-provider"; import { useDialogFormState, useTaskCreateDialogEffects, useDialogHandlers, useSessionRepoName, useTaskCreateDialogData, computeIsTaskStarted, type DialogFormState, type TaskCreateDialogInitialValues, } from "@/components/task-create-dialog-state"; interface TaskCreateDialogProps { open: boolean; onOpenChange: (open: boolean) => void; mode?: "create" | "edit" | "session"; workspaceId: string | null; workflowId: string | null; defaultStepId: string | null; steps: Array<{ id: string; title: string; events?: { on_enter?: Array<{ type: string; config?: Record }>; on_turn_complete?: Array<{ type: string; config?: Record }>; }; }>; editingTask?: { id: string; title: string; description?: string; workflowStepId: string; state?: Task["state"]; repositoryId?: string; } | null; onSuccess?: ( task: Task, mode: "create" | "edit", meta?: { taskSessionId?: string | null }, ) => void; onCreateSession?: (data: { prompt: string; agentProfileId: string; executorId: string }) => void; initialValues?: TaskCreateDialogInitialValues; taskId?: string | null; parentTaskId?: string; } type DialogFormBodyProps = { isSessionMode: boolean; isCreateMode: boolean; isTaskStarted: boolean; isPassthroughProfile: boolean; initialDescription: string; hasDescription: boolean; workspaceId: string | null; onJiraImport?: (ticket: JiraTicket) => void; branchOptions: ReturnType; branchesLoading: boolean; agentProfileOptions: ReturnType; executorProfileOptions: Array<{ value: string; label: string; renderLabel?: () => React.ReactNode; }>; agentProfiles: AgentProfileOption[]; agentProfilesLoading: boolean; executorsLoading: boolean; isCreatingSession: boolean; workflows: unknown[]; snapshots: unknown; effectiveWorkflowId: string | null; fs: DialogFormState; handleKeyDown: ReturnType; onBranchChange: (v: string) => void; onAgentProfileChange: (v: string) => void; onExecutorProfileChange: (v: string) => void; onWorkflowChange: (v: string) => void; hasRepositorySelection: boolean; isLocalExecutor: boolean; enhance?: { onEnhance: () => void; isLoading: boolean; isConfigured: boolean }; workflowAgentLocked: boolean; onToggleFreshBranch: (enabled: boolean) => void; }; function DialogFormBody({ isSessionMode, isCreateMode, isTaskStarted, isPassthroughProfile, initialDescription, hasDescription, workspaceId, onJiraImport, branchOptions, branchesLoading, agentProfileOptions, executorProfileOptions, agentProfiles, agentProfilesLoading, executorsLoading, isCreatingSession, workflows, snapshots, effectiveWorkflowId, fs, handleKeyDown, onBranchChange, onAgentProfileChange, onExecutorProfileChange, onWorkflowChange, hasRepositorySelection, isLocalExecutor, enhance, workflowAgentLocked, onToggleFreshBranch, }: DialogFormBodyProps) { return (
{!isSessionMode && renderCreateEditSelectors({ isTaskStarted, hasRepositorySelection, branchOptions, branchesLoading, agentProfiles, agentProfilesLoading, agentProfileOptions, isCreatingSession, executorProfileOptions, executorsLoading, isLocalExecutor, workflowAgentLocked, fs, onBranchChange, onAgentProfileChange, onExecutorProfileChange, onToggleFreshBranch, })} [0]["workflows"]} snapshots={snapshots as Parameters[0]["snapshots"]} effectiveWorkflowId={effectiveWorkflowId} onWorkflowChange={onWorkflowChange} agentProfiles={agentProfiles} /> {isSessionMode && ( )}
); } type CreateEditSelectorsRenderArgs = Pick< DialogFormBodyProps, | "isTaskStarted" | "hasRepositorySelection" | "branchOptions" | "branchesLoading" | "agentProfiles" | "agentProfilesLoading" | "agentProfileOptions" | "isCreatingSession" | "executorProfileOptions" | "executorsLoading" | "isLocalExecutor" | "workflowAgentLocked" | "fs" | "onBranchChange" | "onAgentProfileChange" | "onExecutorProfileChange" | "onToggleFreshBranch" >; function renderCreateEditSelectors(args: CreateEditSelectorsRenderArgs) { const { fs } = args; return ( ); } function useEnhanceForDialog(fs: DialogFormState) { const isConfigured = useIsUtilityConfigured(); const { enhancePrompt, isEnhancingPrompt } = useUtilityAgentGenerator({ sessionId: null, taskTitle: fs.taskName, }); const onEnhance = useCallback(() => { const current = fs.descriptionInputRef.current?.getValue()?.trim(); if (!current) return; enhancePrompt(current, (enhanced) => { fs.descriptionInputRef.current?.setValue(enhanced); fs.setHasDescription(true); }); }, [enhancePrompt, fs]); return { onEnhance, isLoading: isEnhancingPrompt, isConfigured }; } function useJiraImportHandler(fs: DialogFormState) { return useCallback( (ticket: JiraTicket) => { const title = `[${ticket.key}] ${ticket.summary}`; fs.setTaskName(title); fs.setHasTitle(true); const description = ticket.description?.trim() ? `${ticket.description}\n\n---\nJira: ${ticket.url}` : `Jira: ${ticket.url}`; fs.descriptionInputRef.current?.setValue(description); fs.setHasDescription(true); }, [fs], ); } type SubmitWiringArgs = { props: TaskCreateDialogProps; fs: ReturnType; computed: ReturnType["computed"]; repositoryLocalPath: string; isSessionMode: boolean; isEditMode: boolean; }; function useSubmitHandlersWiring({ props, fs, computed, repositoryLocalPath, isSessionMode, isEditMode, }: SubmitWiringArgs) { const { workspaceId, workflowId, editingTask, onSuccess, onCreateSession, onOpenChange } = props; const { parentTaskId } = props; const taskId = props.taskId ?? null; return useTaskSubmitHandlers({ isSessionMode, isEditMode, isPassthroughProfile: computed.isPassthroughProfile, taskName: fs.taskName, workspaceId, workflowId, effectiveWorkflowId: computed.effectiveWorkflowId, effectiveDefaultStepId: computed.effectiveDefaultStepId, repositoryId: fs.repositoryId, selectedLocalRepo: fs.selectedLocalRepo, useGitHubUrl: fs.useGitHubUrl, githubUrl: fs.githubUrl, githubPrHeadBranch: fs.githubPrHeadBranch, branch: fs.branch, agentProfileId: computed.effectiveAgentProfileId, executorId: fs.executorId, executorProfileId: fs.executorProfileId, editingTask, onSuccess, onCreateSession, onOpenChange, taskId, parentTaskId, descriptionInputRef: fs.descriptionInputRef, setIsCreatingSession: fs.setIsCreatingSession, setIsCreatingTask: fs.setIsCreatingTask, setHasTitle: fs.setHasTitle, setHasDescription: fs.setHasDescription, setTaskName: fs.setTaskName, setRepositoryId: fs.setRepositoryId, setBranch: fs.setBranch, setAgentProfileId: fs.setAgentProfileId, setExecutorId: fs.setExecutorId, setSelectedWorkflowId: fs.setSelectedWorkflowId, setFetchedSteps: fs.setFetchedSteps, clearDraft: fs.clearDraft, freshBranchEnabled: fs.freshBranchEnabled, isLocalExecutor: computed.isLocalExecutor, repositoryLocalPath, }); } function useTaskCreateDialogSetup(props: TaskCreateDialogProps) { const { open, mode = "create", workspaceId, workflowId, defaultStepId } = props; const { editingTask, initialValues } = props; const isSessionMode = mode === "session"; const isEditMode = mode === "edit"; const isCreateMode = mode === "create"; const isTaskStarted = computeIsTaskStarted(isEditMode, editingTask); const fs = useDialogFormState(open, workspaceId, workflowId, initialValues); const { toast } = useToast(); const sessionRepoName = useSessionRepoName(isSessionMode); const { workflows, agentProfiles, executors, snapshots, repositories, repositoriesLoading, branches, branchesLoading, computed, } = useTaskCreateDialogData(open, workspaceId, workflowId, defaultStepId, fs); const repositoryLocalPath = (() => { if (fs.selectedLocalRepo) return fs.selectedLocalRepo.path; if (fs.repositoryId) { const repo = repositories.find((r) => r.id === fs.repositoryId); return repo?.local_path ?? ""; } return ""; })(); useTaskCreateDialogEffects(fs, { open, workspaceId, workflowId, repositories, repositoriesLoading, branches, agentProfiles, executors, workspaceDefaults: computed.workspaceDefaults, toast, workflows, }); const handlers = useDialogHandlers(fs, repositories); const submitHandlers = useSubmitHandlersWiring({ props, fs, computed, repositoryLocalPath, isSessionMode, isEditMode, }); const handleKeyDown = useKeyboardShortcutHandler(SHORTCUTS.SUBMIT, (event) => { submitHandlers.handleSubmit(event as unknown as FormEvent); }); return { fs, isSessionMode, isEditMode, isCreateMode, isTaskStarted, sessionRepoName, workflows, agentProfiles, snapshots, repositoriesLoading, branchesLoading, computed, handlers, submitHandlers, handleKeyDown, enhance: useEnhanceForDialog(fs), handleJiraImport: useJiraImportHandler(fs), }; } export function TaskCreateDialog(props: TaskCreateDialogProps) { const { open, onOpenChange, initialValues, workspaceId } = props; const setup = useTaskCreateDialogSetup(props); const { fs, isSessionMode, isEditMode, isCreateMode, isTaskStarted } = setup; const { sessionRepoName, workflows, agentProfiles, snapshots } = setup; const { repositoriesLoading, branchesLoading, computed, handlers, handleKeyDown } = setup; const { handleSubmit, handleUpdateWithoutAgent, handleCreateWithoutAgent } = setup.submitHandlers; const { handleCreateWithPlanMode, handleCancel } = setup.submitHandlers; const { handleJiraImport } = setup; return (
); } function PendingDiscardModal({ pending, }: { pending: ReturnType["pendingDiscard"]; }) { if (!pending) return null; return ( { if (!next) pending.resolve(false); }} dirtyFiles={pending.dirtyFiles} repoPath={pending.repoPath} onConfirm={() => pending.resolve(true)} onCancel={() => pending.resolve(false)} /> ); }