726 lines
26 KiB
TypeScript
726 lines
26 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState, useMemo, useCallback } from "react";
|
|
import type { LocalRepository, TaskPriority } from "@/lib/types/http";
|
|
import type {
|
|
TaskFormInputsHandle,
|
|
TaskRemoteRepoRow,
|
|
} from "@/components/task-create-dialog-types";
|
|
import { resetTaskForm, type FormResetters } from "@/components/task-create-dialog-form-reset";
|
|
import { useBranchesByURL } from "@/hooks/domains/github/use-branches-by-url";
|
|
import { usePRInfoByURL } from "@/hooks/domains/github/use-pr-info-by-url";
|
|
import { useAppStore } from "@/components/state-provider";
|
|
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
|
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
|
|
import { useEnsureUserSettings } from "@/hooks/use-ensure-user-settings";
|
|
import { getTaskCreateDraft, setTaskCreateDraft, removeTaskCreateDraft } from "@/lib/local-storage";
|
|
import type {
|
|
StepType,
|
|
TaskCreateDialogInitialValues,
|
|
DialogFormState,
|
|
} from "@/components/task-create-dialog-types";
|
|
import {
|
|
useRemoteReposSeedEffect,
|
|
useRemoteReposState,
|
|
useRepositoriesState,
|
|
} from "@/components/task-create-dialog-repositories-state";
|
|
import { useDialogComputed } from "@/components/task-create-dialog-computed";
|
|
import { createDebugLogger } from "@/lib/debug/log";
|
|
import { clampTaskTitleInput, truncateRemoteTaskTitle } from "@/lib/task-title";
|
|
import type { AgentProfileRecentUseContext } from "@/lib/types/http-agent-profile-recent-use";
|
|
|
|
const stateDebug = createDebugLogger("task-create:state");
|
|
|
|
export type {
|
|
StepType,
|
|
TaskCreateDialogInitialValues,
|
|
} from "@/components/task-create-dialog-types";
|
|
export { autoSelectBranch } from "@/components/task-create-dialog-helpers";
|
|
export { useLockedFieldSync } from "@/components/task-create-dialog-locked-fields";
|
|
|
|
type FormResetEffectsArgs = {
|
|
open: boolean;
|
|
workspaceId: string | null;
|
|
workflowId: string | null;
|
|
initialValues: TaskCreateDialogInitialValues | undefined;
|
|
resetters: FormResetters;
|
|
setDraftDescription: (v: string) => void;
|
|
setCurrentDefaults: (v: { name: string; description: string }) => void;
|
|
setOpenCycle: React.Dispatch<React.SetStateAction<number>>;
|
|
prevDialogRef: React.RefObject<{ open: boolean; workspaceId: string | null }>;
|
|
lockedWorkflow: boolean;
|
|
};
|
|
|
|
function useFormResetEffects({
|
|
open,
|
|
workspaceId,
|
|
workflowId,
|
|
initialValues,
|
|
resetters,
|
|
setDraftDescription,
|
|
setCurrentDefaults,
|
|
setOpenCycle,
|
|
prevDialogRef,
|
|
lockedWorkflow,
|
|
}: FormResetEffectsArgs) {
|
|
useEffect(() => {
|
|
const previous = prevDialogRef.current;
|
|
(prevDialogRef as React.MutableRefObject<typeof previous>).current = { open, workspaceId };
|
|
|
|
if (!open || (previous.open && previous.workspaceId === workspaceId)) return;
|
|
|
|
setOpenCycle((c) => c + 1);
|
|
|
|
const defaults = resolveFormDefaults(initialValues, workspaceId);
|
|
stateDebug("open-reset", {
|
|
workspace_id: workspaceId ?? "-",
|
|
workflow_id: workflowId ?? "-",
|
|
source: defaults.source,
|
|
title_present: defaults.name.trim().length > 0,
|
|
description_present: defaults.description.trim().length > 0,
|
|
initial_repository_id: initialValues?.repositoryId ?? "-",
|
|
initial_branch: initialValues?.branch ?? initialValues?.checkoutBranch ?? "-",
|
|
});
|
|
setCurrentDefaults(defaults);
|
|
resetTaskForm(
|
|
resetters,
|
|
defaults.name,
|
|
defaults.description,
|
|
lockedWorkflow ? workflowId : null,
|
|
initialValues,
|
|
);
|
|
setDraftDescription(defaults.description);
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [lockedWorkflow, open, workflowId, workspaceId]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
stateDebug("discovery-reset", {
|
|
workspace_id: workspaceId ?? "-",
|
|
remote_url: initialValues?.remoteUrl ?? initialValues?.githubUrl ?? "-",
|
|
seeded_remote_branch: initialValues?.checkoutBranch ?? initialValues?.branch ?? "-",
|
|
});
|
|
resetDiscoveryState(resetters, initialValues);
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [open, workspaceId]);
|
|
}
|
|
|
|
/** Checks if initialValues has any user-provided content */
|
|
function hasUserContent(initialValues?: TaskCreateDialogInitialValues): boolean {
|
|
const title = initialValues?.title ?? "";
|
|
const description = initialValues?.description ?? "";
|
|
return title.trim().length > 0 || description.trim().length > 0;
|
|
}
|
|
|
|
/** Resolves form defaults from draft (for create) or initialValues (for edit) */
|
|
function resolveFormDefaults(
|
|
initialValues: TaskCreateDialogInitialValues | undefined,
|
|
workspaceId: string | null,
|
|
) {
|
|
const draft =
|
|
!hasUserContent(initialValues) && workspaceId ? getTaskCreateDraft(workspaceId) : null;
|
|
const initTitle = initialValues?.title ?? "";
|
|
const initDesc = initialValues?.description ?? "";
|
|
let name = initTitle;
|
|
if (draft?.title) {
|
|
name = clampTaskTitleInput(draft.title);
|
|
} else if (initialValues?.githubUrl) {
|
|
name = truncateRemoteTaskTitle(initTitle);
|
|
}
|
|
return {
|
|
name,
|
|
description: draft?.description ?? initDesc,
|
|
source: resolveDefaultsSource(Boolean(draft), initialValues),
|
|
};
|
|
}
|
|
|
|
function resolveDefaultsSource(
|
|
hasDraft: boolean,
|
|
initialValues: TaskCreateDialogInitialValues | undefined,
|
|
) {
|
|
if (hasDraft) return "draft";
|
|
if (hasUserContent(initialValues)) return "initial-values";
|
|
return "empty";
|
|
}
|
|
|
|
function firstDefined<T>(...values: Array<T | undefined>): T | undefined {
|
|
return values.find((value) => value !== undefined);
|
|
}
|
|
|
|
function definedOr<T>(fallback: T, ...values: Array<T | undefined>): T {
|
|
return firstDefined(...values) ?? fallback;
|
|
}
|
|
|
|
function remoteRepositoryFullName(
|
|
inspection: TaskCreateDialogInitialValues["remoteRepository"],
|
|
): string | undefined {
|
|
return inspection ? `${inspection.ownerOrProject}/${inspection.repositoryName}` : undefined;
|
|
}
|
|
|
|
function seededRemoteRepositories(iv?: TaskCreateDialogInitialValues): TaskRemoteRepoRow[] {
|
|
const initial: Partial<TaskCreateDialogInitialValues> = iv ?? {};
|
|
const inspection = initial.remoteRepository;
|
|
const repository: Partial<NonNullable<TaskCreateDialogInitialValues["remoteRepository"]>> =
|
|
inspection ?? {};
|
|
const remoteUrl = definedOr("", initial.remoteUrl, initial.githubUrl, repository.cloneUrl);
|
|
if (!remoteUrl) return [];
|
|
// Seed a pre-filled URL and preserve its PR head when one is provided.
|
|
const seededBranch = definedOr(
|
|
"",
|
|
initial.checkoutBranch,
|
|
initial.branch,
|
|
repository.headBranch,
|
|
repository.defaultBranch,
|
|
);
|
|
return [
|
|
{
|
|
key: "remote-0",
|
|
url: remoteUrl,
|
|
branch: seededBranch,
|
|
source: "paste",
|
|
prNumber: firstDefined(initial.prNumber, repository.pullRequest?.number),
|
|
prBaseBranch: firstDefined(initial.prBaseBranch, repository.baseBranch),
|
|
prHeadBranch: firstDefined(initial.checkoutBranch, repository.headBranch),
|
|
remoteUrl: repository.cloneUrl,
|
|
provider: repository.providerId,
|
|
providerHost: repository.providerHost,
|
|
providerScope: repository.providerScope,
|
|
providerRepoId: repository.repositoryId,
|
|
providerOwner: repository.ownerOrProject,
|
|
providerName: repository.repositoryName,
|
|
fullName: remoteRepositoryFullName(inspection),
|
|
},
|
|
];
|
|
}
|
|
|
|
function resetDiscoveryState(resetters: FormResetters, iv?: TaskCreateDialogInitialValues) {
|
|
const remoteRepositories = seededRemoteRepositories(iv);
|
|
resetters.setDiscoveredRepositories([]);
|
|
resetters.setDiscoverReposLoaded(false);
|
|
resetters.setUseRemote(remoteRepositories.length > 0);
|
|
resetters.setRemoteRepos(remoteRepositories);
|
|
resetters.setGitHubUrlError(null);
|
|
resetters.setFreshBranchEnabled(false);
|
|
resetters.setCurrentLocalBranch("");
|
|
// The dialog stays mounted between opens, so without this the previous
|
|
// create's predecessor selection reappears on the next one.
|
|
resetters.setBlockedBy([]);
|
|
}
|
|
|
|
/** Hook to manage draft persistence for task creation dialog */
|
|
function useDraftPersistence(
|
|
open: boolean,
|
|
workspaceId: string | null,
|
|
initialValues: TaskCreateDialogInitialValues | undefined,
|
|
taskName: string,
|
|
descriptionInputRef: React.RefObject<{ getValue: () => string } | null>,
|
|
) {
|
|
const wasOpenRef = useRef(false);
|
|
const skipDraftSaveRef = useRef(false);
|
|
|
|
// Save draft when dialog closes (only in create mode without initialValues)
|
|
useEffect(() => {
|
|
const wasOpen = wasOpenRef.current;
|
|
wasOpenRef.current = open;
|
|
|
|
if (!wasOpen || open || !workspaceId) return;
|
|
// Skip if clearDraft was called (successful submission)
|
|
if (skipDraftSaveRef.current) {
|
|
skipDraftSaveRef.current = false;
|
|
return;
|
|
}
|
|
const hasInitialValues = Boolean(
|
|
initialValues?.title?.trim() || initialValues?.description?.trim(),
|
|
);
|
|
// Only save draft in create mode
|
|
if (!hasInitialValues) {
|
|
const currentDescription = descriptionInputRef.current?.getValue() ?? "";
|
|
setTaskCreateDraft(workspaceId, { title: taskName, description: currentDescription });
|
|
}
|
|
}, [open, workspaceId, initialValues, taskName, descriptionInputRef]);
|
|
|
|
// Clear draft (call on successful submission before closing dialog)
|
|
const clearDraft = useCallback(() => {
|
|
if (workspaceId) {
|
|
removeTaskCreateDraft(workspaceId);
|
|
skipDraftSaveRef.current = true;
|
|
}
|
|
}, [workspaceId]);
|
|
|
|
return { clearDraft };
|
|
}
|
|
|
|
function useWorkflowAgentProfileState() {
|
|
const [workflowAgentProfileId, setWorkflowAgentProfileId] = useState("");
|
|
return { workflowAgentProfileId, setWorkflowAgentProfileId };
|
|
}
|
|
|
|
/**
|
|
* Predecessor task IDs selected in the dialog. Dependencies are declared at
|
|
* creation time (or later via MCP); nothing edits them from the task view.
|
|
*/
|
|
function useTaskDependencyState() {
|
|
const [blockedBy, setBlockedBy] = useState<string[]>([]);
|
|
return { blockedBy, setBlockedBy };
|
|
}
|
|
|
|
function useFreshBranchState() {
|
|
const [freshBranchEnabled, setFreshBranchEnabled] = useState(false);
|
|
const [currentLocalBranch, setCurrentLocalBranch] = useState("");
|
|
const [currentLocalBranchLoading, setCurrentLocalBranchLoading] = useState(false);
|
|
return {
|
|
freshBranchEnabled,
|
|
setFreshBranchEnabled,
|
|
currentLocalBranch,
|
|
setCurrentLocalBranch,
|
|
currentLocalBranchLoading,
|
|
setCurrentLocalBranchLoading,
|
|
};
|
|
}
|
|
|
|
function useGitHubUrlState() {
|
|
const [useRemote, setUseRemote] = useState(false);
|
|
const [githubUrlError, setGitHubUrlError] = useState<string | null>(null);
|
|
return {
|
|
useRemote,
|
|
setUseRemote,
|
|
githubUrlError,
|
|
setGitHubUrlError,
|
|
};
|
|
}
|
|
|
|
/** Core form state declarations */
|
|
function useFormStateValues(workflowId: string | null) {
|
|
// openCycle increments each time dialog opens - used in key to force TaskFormInputs remount
|
|
const [openCycle, setOpenCycle] = useState(0);
|
|
// Start as false so a fresh mount with open=true is detected as a rising edge
|
|
// (callers like QuickTaskLauncher conditionally mount the dialog already-open).
|
|
const prevDialogRef = useRef({ open: false, workspaceId: null as string | null });
|
|
|
|
// currentDefaults stores the loaded draft/initial values for this open cycle
|
|
const [currentDefaults, setCurrentDefaults] = useState<{ name: string; description: string }>({
|
|
name: "",
|
|
description: "",
|
|
});
|
|
|
|
// These states are initialized with defaults and then managed by effects/handlers
|
|
const [taskName, setTaskName] = useState("");
|
|
const [hasTitle, setHasTitle] = useState(false);
|
|
const [hasDescription, setHasDescription] = useState(false);
|
|
const [hasPendingAttachmentUploads, setHasPendingAttachmentUploads] = useState(false);
|
|
const [draftDescription, setDraftDescription] = useState("");
|
|
|
|
const descriptionInputRef = useRef<TaskFormInputsHandle | null>(null);
|
|
const [agentProfileId, setAgentProfileId] = useState("");
|
|
const [executorId, setExecutorId] = useState("");
|
|
const [executorProfileId, setExecutorProfileId] = useState("");
|
|
const [selectedWorkflowId, setSelectedWorkflowId] = useState(workflowId);
|
|
const [workflowAgentOverrides, setWorkflowAgentOverrides] = useState<Record<string, string>>({});
|
|
const [fetchedSteps, setFetchedSteps] = useState<StepType[] | null>(null);
|
|
const [isCreatingSession, setIsCreatingSession] = useState(false);
|
|
const [isCreatingTask, setIsCreatingTask] = useState(false);
|
|
// No-repo mode: when true, the task is created with no repositories. The
|
|
// optional workspacePath points the agent at an existing host folder; empty
|
|
// means kandev creates a scratch workspace.
|
|
const [noRepository, setNoRepository] = useState(false);
|
|
const [preferLocalExecutor, setPreferLocalExecutor] = useState(false);
|
|
const [workspacePath, setWorkspacePath] = useState("");
|
|
const [autopilot, setAutopilot] = useState(false);
|
|
const [priority, setPriority] = useState<TaskPriority>("medium");
|
|
return {
|
|
taskName,
|
|
setTaskName,
|
|
hasTitle,
|
|
setHasTitle,
|
|
hasDescription,
|
|
setHasDescription,
|
|
hasPendingAttachmentUploads,
|
|
setHasPendingAttachmentUploads,
|
|
draftDescription,
|
|
setDraftDescription,
|
|
descriptionInputRef,
|
|
agentProfileId,
|
|
setAgentProfileId,
|
|
executorId,
|
|
setExecutorId,
|
|
executorProfileId,
|
|
setExecutorProfileId,
|
|
selectedWorkflowId,
|
|
setSelectedWorkflowId,
|
|
workflowAgentOverrides,
|
|
setWorkflowAgentOverrides,
|
|
fetchedSteps,
|
|
setFetchedSteps,
|
|
isCreatingSession,
|
|
setIsCreatingSession,
|
|
isCreatingTask,
|
|
setIsCreatingTask,
|
|
openCycle,
|
|
setOpenCycle,
|
|
currentDefaults,
|
|
setCurrentDefaults,
|
|
prevDialogRef,
|
|
noRepository,
|
|
setNoRepository,
|
|
preferLocalExecutor,
|
|
setPreferLocalExecutor,
|
|
workspacePath,
|
|
setWorkspacePath,
|
|
autopilot,
|
|
setAutopilot,
|
|
priority,
|
|
setPriority,
|
|
};
|
|
}
|
|
|
|
/** Repository discovery state — just the discovered list. The previous
|
|
* per-form `selectedLocalRepo` / `discoveredRepoPath` / `localBranches`
|
|
* primary-only fields are gone; discovered repos now live as ordinary rows
|
|
* in `fs.repositories` with `localPath` set. */
|
|
function useDiscoveryState() {
|
|
const [discoveredRepositories, setDiscoveredRepositories] = useState<LocalRepository[]>([]);
|
|
const [discoverReposLoading, setDiscoverReposLoading] = useState(false);
|
|
const [discoverReposLoaded, setDiscoverReposLoaded] = useState(false);
|
|
return {
|
|
discoveredRepositories,
|
|
setDiscoveredRepositories,
|
|
discoverReposLoading,
|
|
setDiscoverReposLoading,
|
|
discoverReposLoaded,
|
|
setDiscoverReposLoaded,
|
|
};
|
|
}
|
|
|
|
export function useDialogFormState(
|
|
open: boolean,
|
|
workspaceId: string | null,
|
|
workflowId: string | null,
|
|
initialValues?: TaskCreateDialogInitialValues,
|
|
lockedWorkflow = false,
|
|
) {
|
|
const form = useFormStateValues(workflowId);
|
|
const discovery = useDiscoveryState();
|
|
const ghUrl = useGitHubUrlState();
|
|
const wfAgent = useWorkflowAgentProfileState();
|
|
const repos = useRepositoriesState();
|
|
const remoteRepos = useRemoteReposState();
|
|
const freshBranch = useFreshBranchState();
|
|
const dependencies = useTaskDependencyState();
|
|
const branchesByUrl = useBranchesByURL(workspaceId);
|
|
const prInfoByUrl = usePRInfoByURL(workspaceId);
|
|
|
|
useFormResetEffects({
|
|
open,
|
|
workspaceId,
|
|
workflowId,
|
|
initialValues,
|
|
setDraftDescription: form.setDraftDescription,
|
|
setCurrentDefaults: form.setCurrentDefaults,
|
|
setOpenCycle: form.setOpenCycle,
|
|
prevDialogRef: form.prevDialogRef,
|
|
lockedWorkflow,
|
|
resetters: {
|
|
setBlockedBy: dependencies.setBlockedBy,
|
|
setTaskName: form.setTaskName,
|
|
setHasTitle: form.setHasTitle,
|
|
setHasDescription: form.setHasDescription,
|
|
setHasPendingAttachmentUploads: form.setHasPendingAttachmentUploads,
|
|
setRepositories: repos.setRepositories,
|
|
setRepositoriesDirty: repos.setRepositoriesDirty,
|
|
setRemoteRepos: remoteRepos.setRemoteRepos,
|
|
setAgentProfileId: form.setAgentProfileId,
|
|
setExecutorId: form.setExecutorId,
|
|
setExecutorProfileId: form.setExecutorProfileId,
|
|
setSelectedWorkflowId: form.setSelectedWorkflowId,
|
|
setWorkflowAgentOverrides: form.setWorkflowAgentOverrides,
|
|
setFetchedSteps: form.setFetchedSteps,
|
|
setDiscoveredRepositories: discovery.setDiscoveredRepositories,
|
|
setDiscoverReposLoaded: discovery.setDiscoverReposLoaded,
|
|
setUseRemote: ghUrl.setUseRemote,
|
|
setGitHubUrlError: ghUrl.setGitHubUrlError,
|
|
setFreshBranchEnabled: freshBranch.setFreshBranchEnabled,
|
|
setCurrentLocalBranch: freshBranch.setCurrentLocalBranch,
|
|
setNoRepository: form.setNoRepository,
|
|
setPreferLocalExecutor: form.setPreferLocalExecutor,
|
|
setWorkspacePath: form.setWorkspacePath,
|
|
setAutopilot: form.setAutopilot,
|
|
setPriority: form.setPriority,
|
|
},
|
|
});
|
|
|
|
useRemoteReposSeedEffect(ghUrl.useRemote, remoteRepos.remoteRepos, remoteRepos.setRemoteRepos);
|
|
|
|
// Title autofill follows the first populated remote-repo row. Empty
|
|
// placeholders do not prevent a later pasted PR or issue from suggesting
|
|
// its title.
|
|
const primaryRemoteUrl = remoteRepos.remoteRepos.find((row) => row.url.trim())?.url ?? "";
|
|
useTitleAutofillFromPrimaryGitHubInfo({
|
|
open: open && ghUrl.useRemote,
|
|
primaryRemoteUrl,
|
|
prInfoByUrl,
|
|
taskName: form.taskName,
|
|
setTaskName: form.setTaskName,
|
|
setHasTitle: form.setHasTitle,
|
|
});
|
|
|
|
const { clearDraft } = useDraftPersistence(
|
|
open,
|
|
workspaceId,
|
|
initialValues,
|
|
form.taskName,
|
|
form.descriptionInputRef,
|
|
);
|
|
|
|
const { seededExecutorProfileId, setExecutorProfileIdFromSeed } = useSeededExecutorProfileId(
|
|
open,
|
|
form.setExecutorProfileId,
|
|
);
|
|
|
|
return {
|
|
...form,
|
|
...discovery,
|
|
...ghUrl,
|
|
...wfAgent,
|
|
...repos,
|
|
...remoteRepos,
|
|
...freshBranch,
|
|
...dependencies,
|
|
branchesByUrl,
|
|
prInfoByUrl,
|
|
clearDraft,
|
|
seededExecutorProfileId,
|
|
setExecutorProfileIdFromSeed,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Tracks the executorProfileId value written through
|
|
* setExecutorProfileIdFromSeed each open cycle, whether it arrives via the
|
|
* create-mode autopick or the edit-mode stored-profile seed effect. Resets
|
|
* on each open rising edge. This is "what the dialog put there", independent
|
|
* of any later or earlier user selection: only a write through the
|
|
* returned setExecutorProfileIdFromSeed counts, never the plain
|
|
* setExecutorProfileId a user's own picker uses.
|
|
*
|
|
* The reset is keyed on `open`'s own rising edge via an effect, not on
|
|
* comparing openCycle during render: openCycle bumps via its own effect on
|
|
* the same rising edge, and a seed write triggered by that same edge can
|
|
* land in the same subsequent render as the bump. A render-phase comparison
|
|
* can't distinguish "openCycle just changed because the dialog opened" from
|
|
* "openCycle changed and this cycle's seed already arrived", so it would
|
|
* wipe a same-transition seed the instant it was written.
|
|
*/
|
|
function useSeededExecutorProfileId(open: boolean, setExecutorProfileId: (v: string) => void) {
|
|
const seededRef = useRef<string | null>(null);
|
|
const prevOpenRef = useRef(false);
|
|
useEffect(() => {
|
|
const wasOpen = prevOpenRef.current;
|
|
prevOpenRef.current = open;
|
|
if (open && !wasOpen) {
|
|
seededRef.current = null;
|
|
}
|
|
}, [open]);
|
|
const setExecutorProfileIdFromSeed = useCallback(
|
|
(value: string) => {
|
|
seededRef.current = value;
|
|
setExecutorProfileId(value);
|
|
},
|
|
[setExecutorProfileId],
|
|
);
|
|
return { seededExecutorProfileId: seededRef.current, setExecutorProfileIdFromSeed };
|
|
}
|
|
|
|
/**
|
|
* Seeds the task title from the first populated Remote row's GitHub URL info
|
|
* the first time it arrives, and only when the user hasn't typed a title.
|
|
* Subsequent info changes for the same URL don't overwrite — the
|
|
* lastAutoFilledRef tracks our own writes so re-pasting a different GitHub
|
|
* URL still works while a user-edited title is preserved.
|
|
*/
|
|
/** Sentinel stored in `lastAutoFilledRef` once the user clears an
|
|
* auto-filled title. Distinguishable from any real suggested title (which
|
|
* comes from the GitHub info loader) so the effect can refuse to re-apply
|
|
* autofill for the current URL until the URL itself changes. */
|
|
const USER_CLEARED_SENTINEL = "\0cleared";
|
|
|
|
function useTitleAutofillFromPrimaryGitHubInfo(args: {
|
|
open: boolean;
|
|
primaryRemoteUrl: string;
|
|
prInfoByUrl: ReturnType<typeof usePRInfoByURL>;
|
|
taskName: string;
|
|
setTaskName: (v: string) => void;
|
|
setHasTitle: (v: boolean) => void;
|
|
}) {
|
|
const { open, primaryRemoteUrl, prInfoByUrl, taskName, setTaskName, setHasTitle } = args;
|
|
const lastAutoFilledRef = useRef("");
|
|
const lastUrlRef = useRef("");
|
|
// Re-read latest info on every render; cheap because the cache is memoized
|
|
// by URL inside the hook.
|
|
const suggested = primaryRemoteUrl
|
|
? prInfoByUrl.info(primaryRemoteUrl)?.suggestedTitle
|
|
: undefined;
|
|
const boundedSuggested = suggested ? truncateRemoteTaskTitle(suggested) : undefined;
|
|
|
|
// Reset ownership-tracking when the URL changes — switching to a different
|
|
// PR URL grants a fresh autofill opportunity even if the user previously
|
|
// cleared an autofill on the prior URL.
|
|
useEffect(() => {
|
|
if (primaryRemoteUrl !== lastUrlRef.current) {
|
|
lastUrlRef.current = primaryRemoteUrl;
|
|
lastAutoFilledRef.current = "";
|
|
}
|
|
}, [primaryRemoteUrl]);
|
|
|
|
useEffect(() => {
|
|
// Detect the "user cleared an auto-filled title" transition. Once we see
|
|
// it, lock further autofill for the current URL (until the URL changes,
|
|
// which is handled by the effect above). Without this, the effect below
|
|
// would see `trimmed === ""` again and dutifully re-apply the suggested
|
|
// title that the user just removed.
|
|
if (
|
|
!taskName.trim() &&
|
|
lastAutoFilledRef.current &&
|
|
lastAutoFilledRef.current !== USER_CLEARED_SENTINEL
|
|
) {
|
|
lastAutoFilledRef.current = USER_CLEARED_SENTINEL;
|
|
}
|
|
}, [taskName]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
if (!boundedSuggested) return;
|
|
if (lastAutoFilledRef.current === USER_CLEARED_SENTINEL) return;
|
|
const trimmed = taskName.trim();
|
|
// Two writeable states: title is empty AND we haven't auto-filled yet, or
|
|
// title equals our last auto-fill (so a fresh PR URL replaces a previous
|
|
// PR's auto-filled title).
|
|
if (trimmed && taskName !== lastAutoFilledRef.current) return;
|
|
if (taskName === boundedSuggested) return;
|
|
lastAutoFilledRef.current = boundedSuggested;
|
|
setTaskName(boundedSuggested);
|
|
setHasTitle(true);
|
|
}, [open, boundedSuggested, taskName, setTaskName, setHasTitle]);
|
|
}
|
|
|
|
export type { DialogFormState } from "@/components/task-create-dialog-types";
|
|
export {
|
|
computePassthroughProfile,
|
|
computeEffectiveStepId,
|
|
computeIsTaskStarted,
|
|
} from "@/components/task-create-dialog-helpers";
|
|
export { useTaskCreateDialogEffects } from "@/components/task-create-dialog-effects";
|
|
|
|
// useDialogHandlers lives in ./task-create-dialog-handlers.ts
|
|
export { useDialogHandlers } from "@/components/task-create-dialog-handlers";
|
|
|
|
export { useDialogComputed } from "@/components/task-create-dialog-computed";
|
|
|
|
export function useSessionRepoName(isSessionMode: boolean) {
|
|
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
|
|
const kanbanTasks = useAppStore((state) => state.kanban.tasks);
|
|
const reposByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId);
|
|
return useMemo(() => {
|
|
if (!isSessionMode) return undefined;
|
|
const activeTask = activeTaskId ? kanbanTasks.find((t) => t.id === activeTaskId) : null;
|
|
const repoId = activeTask?.repositoryId;
|
|
if (!repoId) return undefined;
|
|
for (const repos of Object.values(reposByWorkspace)) {
|
|
const repo = repos.find((r) => r.id === repoId);
|
|
if (repo) return repo.name;
|
|
}
|
|
return undefined;
|
|
}, [isSessionMode, activeTaskId, kanbanTasks, reposByWorkspace]);
|
|
}
|
|
|
|
type TaskCreateDialogDataArgs = {
|
|
open: boolean;
|
|
workspaceId: string | null;
|
|
workflowId: string | null;
|
|
defaultStepId: string | null;
|
|
fs: DialogFormState;
|
|
lockedWorkflow?: boolean;
|
|
agentProfileRecentUseContext?: AgentProfileRecentUseContext;
|
|
};
|
|
|
|
export function useTaskCreateDialogData({
|
|
open,
|
|
workspaceId,
|
|
workflowId,
|
|
defaultStepId,
|
|
fs,
|
|
lockedWorkflow = false,
|
|
agentProfileRecentUseContext = "task_create",
|
|
}: TaskCreateDialogDataArgs) {
|
|
const workflows = useAppStore((state) => state.workflows.items);
|
|
const workspaces = useAppStore((state) => state.workspaces.items);
|
|
const agentProfiles = useAppStore((state) => state.agentProfiles.items);
|
|
const executors = useAppStore((state) => state.executors.items);
|
|
const settingsData = useAppStore((state) => state.settingsData);
|
|
const availableAgentsLoaded = useAppStore((state) => state.availableAgents.loaded);
|
|
const snapshots = useAppStore((state) => state.kanbanMulti.snapshots);
|
|
const workspaceSnapshotWorkspaceId = useAppStore(
|
|
(state) => state.workspaceContextRead.workspaceId,
|
|
);
|
|
const workspaceSnapshotPending = useAppStore(
|
|
(state) => state.workspaceContextRead.snapshotPending,
|
|
);
|
|
const workspaceSnapshotError = useAppStore((state) => state.workspaceContextRead.snapshotError);
|
|
const workspaceSnapshotRead = {
|
|
workspaceId: workspaceSnapshotWorkspaceId,
|
|
pending: workspaceSnapshotPending,
|
|
error: workspaceSnapshotError,
|
|
};
|
|
const refreshWorkspaceSnapshots = useAppStore((state) => state.requestWorkspaceContextRefresh);
|
|
const taskCreateUserSettings = useEnsureUserSettings(open);
|
|
|
|
useSettingsData(open);
|
|
const {
|
|
repositories,
|
|
isLoading: repositoriesLoading,
|
|
refresh: refreshRepositories,
|
|
} = useRepositories(workspaceId, open);
|
|
// Per-repo branch loading lives in each chip now (RepoChipsRow). No
|
|
// global branch query is needed here — the chip uses useRepositoryBranches
|
|
// for its own row, and the store dedupes by repositoryId.
|
|
const branchesLoading = false;
|
|
const computed = useDialogComputed({
|
|
fs,
|
|
open,
|
|
workspaceId,
|
|
workflowId,
|
|
defaultStepId,
|
|
settingsData: {
|
|
agentsLoaded: settingsData.agentsLoaded,
|
|
executorsLoaded: settingsData.executorsLoaded,
|
|
capabilitiesLoaded: availableAgentsLoaded,
|
|
},
|
|
agentProfiles,
|
|
workspaces,
|
|
executors,
|
|
repositories,
|
|
workflows,
|
|
snapshots,
|
|
lockedWorkflow,
|
|
lastUsedWorkflowIdsByWorkspace:
|
|
taskCreateUserSettings.userSettings.taskCreateLastUsed.workflowIdsByWorkspace ?? {},
|
|
userSettingsLoaded: taskCreateUserSettings.loaded,
|
|
agentProfileRecentUseContext,
|
|
});
|
|
return {
|
|
workflows,
|
|
workspaces,
|
|
agentProfiles,
|
|
executors,
|
|
snapshots,
|
|
workspaceSnapshotRead,
|
|
refreshWorkspaceSnapshots,
|
|
repositories,
|
|
repositoriesLoading,
|
|
refreshRepositories,
|
|
branchesLoading,
|
|
taskCreateLastUsed: taskCreateUserSettings.userSettings.taskCreateLastUsed,
|
|
userSettingsLoaded: taskCreateUserSettings.loaded,
|
|
computed,
|
|
};
|
|
}
|