Files
kandev/apps/web/components/task-create-dialog-state.ts
T
João Salavisa 45a46f9899 feat: support tasks without a repository (#850)
* feat: support tasks without a repository

Lets users create a task with no repository attached — useful for research,
brainstorming, design discussions, or pointing the agent at an existing
non-git folder. The create-task dialog gains a 3-mode segmented control
(Repo / URL / None); "None" mode replaces the chip row with a folder
picker that browses the host filesystem via a new GET /api/v1/fs/list-dir
endpoint and either commits an absolute path or falls back to a kandev-
managed scratch workspace at <homeDir>/tasks/<workspaceID>/<taskID>/.

The worktree executor is hidden from the picker in no-repo mode (it
inherently needs a repo); the lifecycle manager also short-circuits
worktree mode server-side as a belt-and-suspenders guard. The Changes
panel auto-closes for repo-less tasks since it has nothing to show, and
the cumulative-diff handler returns null instead of erroring when no
base commit exists.

Spec + plan added at docs/specs/tasks-without-repositories/.

* fix(backend): anchor folder picker to discovery roots (CodeQL path traversal)

CodeQL flagged the new GET /api/v1/fs/list-dir handler for piping a
user-controlled path straight into os.Stat / os.ReadDir. Restrict the
listing to paths inside the configured discovery roots (defaults to
$HOME, same allowlist as repository discovery), reject anything outside
with ErrPathNotAllowed → HTTP 403, and clip the breadcrumb's "up"
button at the root so the picker can't be used to walk above the
allowed prefix.

Tests cover: rejection of paths outside roots, traversal escapes (../),
default-to-first-root, and parent exposure for nested paths.

* fix(backend): use os.Root for folder picker (recognized CodeQL sanitizer)

Previous attempt anchored to discovery roots via isPathAllowed, but
CodeQL's data flow doesn't model that helper as a sanitizer and kept
flagging os.Stat / os.ReadDir. Switch to os.Root (Go 1.24+): open the
matching discovery root once and run Stat/Open/ReadDir against the
relative path within it. The OS itself enforces containment — symlinks
and traversal cannot escape — and CodeQL recognizes os.Root as safe.

* fix: address PR review feedback

- Changes panel auto-close now distinguishes "task loading" from
  "task has no repos" (returns boolean | null), so the panel isn't
  permanently removed during the first-render window before task
  data lands in the store.
- Reset noRepository / workspacePath in resetDiscoveryState so
  reopening the dialog after a None-mode task doesn't carry the
  flag forward.
- Folder-picker breadcrumb: dropped dead `i > 0 && i > 1` condition
  (always equivalent to `i > 1`); chevrons now render between every
  segment as expected.
- list-dir HTTP handler returns a generic error message instead of
  forwarding raw OS errors that leak host paths.
- Document the dataDir → kandevHome inversion convention next to
  the scratch-path computation so future readers don't mistake the
  filepath.Dir call for a fragile derivation.

* fix: address CodeRabbit review nitpicks

- Trim whitespace on workspace_path before persisting to task metadata
  so a value of "   " doesn't get stored as a non-empty path.
- Extract the workspace_path metadata key into models.MetaKeyWorkspacePath
  alongside the existing MetaKeyAgentProfileID / MetaKeyExecutorProfileID
  so the set/read sites can't drift apart.
- Folder picker: reset cached listing when the popover closes, so
  reopening reloads from `value` instead of showing the last browsed
  directory the user navigated away from without committing.
- Submit payload: send `workspace_path: undefined` instead of an empty
  string when the trimmed value is empty, matching the noRepository=false
  case and keeping the API contract clear.

* fix: scratch path lands in kandev home, not its parent

Claude caught a real bug — `m.dataDir` is set from `cfg.ResolvedHomeDir()`
in cmd/kandev/agents.go, not `ResolvedDataDir()` (the field name is
misleading and the comment was wrong). My previous use of
`filepath.Dir(m.dataDir)` therefore walked one level above the kandev
home, so scratch dirs landed at e.g. `~/tasks/<ws>/<task>` instead of
`~/.kandev/tasks/<ws>/<task>` — and at the project root in dev mode
where `KANDEV_HOME_DIR=<project>/.kandev-dev`, which is what the user
saw on their machine.

Use `m.dataDir` directly (it's already the kandev home), document the
field's misnamed-but-correct semantics, and tighten the test fixtures.

Also:
- folder-picker trigger gets `cursor-pointer` (CodeRabbit nitpick).

* fix: pass workspacePath through handleCreateWithoutAgent too

The "create without agent" path called buildCreateTaskPayload without
the new workspacePath field, so picking a folder + clicking "Create
without starting" silently dropped the path. Now matches the
performCreate (with-agent) path.

* fix: satisfy DialogFormState in new-subtask form stub

PR #852 (merged after this branch was created) introduced
new-subtask-form-state.ts which stubs out a DialogFormState for the
subtask dialog. Adding noRepository / setNoRepository / workspacePath /
setWorkspacePath to the type made that stub incomplete, breaking the
Next.js production build (caught by CI, missed by tsc --noEmit).

Add the four inert fields to the stub, alongside the existing fresh-
branch inert fields, and pull both groups into named constants to
keep the useMemo body under the per-function line cap.

* fix: keep toggle-github-url testid as alias on URL-mode button

The new source-mode segmented control replaced the previous
"or paste a GitHub URL" text link, which had data-testid="toggle-github-url".
The existing e2e suite (create-task-github-url.spec.ts and the new
subtask.spec.ts from #852) still selects the URL toggle by that testid.
Keep "toggle-github-url" as the testid on the URL-mode button so both
suites pass without a sweep across all e2e files. Click semantics are
unchanged — single click enters URL mode.

* test(e2e): update toggle assertion for new source-mode segmented control

create-task-github-url.spec.ts:892 was checking the old text-link
toggle's two-way behavior with text labels ("or paste a GitHub URL" /
"use a workspace repository"). The new segmented control has explicit
mode buttons; assert aria-checked instead of label text. The other 9
clicks on `toggle-github-url` in this file still work via the legacy
testid alias on the URL-mode button.

* refactor: extract useActiveTaskHasRepos to its own hook file

dockview-desktop-layout.tsx grew to 609 lines with the new hook +
the Changes panel guard, over the 600-line cap documented in
CLAUDE.md (lint passed but the convention is real). Move the hook
to hooks/domains/kanban/use-active-task-has-repos.ts. File drops
to 590 lines.

* chore: gitignore .claude/scheduled_tasks.lock runtime file

* fix(web): lock chip-row min-height so modal doesn't shift on mode toggle

The chip row uses flex-wrap; Repo mode (chip + branch + add button +
segmented control) sometimes occupies a different vertical extent than
None mode (single folder picker + segmented control), causing the
create-task modal to jump a few pixels when toggling between sources.
Set min-h-9 so the row always reserves at least one chip-row of
height regardless of the active mode.

* feat: let folder picker browse anywhere, drop allowed-roots gate

The picker is for choosing a starting folder for a repo-less task —
users legitimately want /tmp, /var/log/foo, or any directory they have
read access to. Coupling it to the repo-discover endpoint's
discoveryRoots ($HOME by default) was too tight: paths like /tmp
returned 403 "path is not within allowed roots".

Decouple ListDirectory from discoveryRoots. The repo-discover endpoint
(DiscoverLocalRepositories, ValidateLocalRepositoryPath,
LocalRepositoryStatus, ListBranches) stays anchored to the allowlist
since picking a repo to import is a workspace-scoped operation; the
folder picker trusts the local-process boundary instead.

CodeQL is kept happy by routing the FS operations through os.Root
opened at "/" — the Go stdlib sanitizer for path injection still
recognises it (containment to / is trivially satisfied for every
absolute path on the host).

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-12 01:10:22 +01:00

652 lines
24 KiB
TypeScript

"use client";
import { useEffect, useRef, useState, useMemo, useCallback } from "react";
import type { LocalRepository, Workspace, ExecutorProfile, Branch } from "@/lib/types/http";
import type { TaskFormInputsHandle } from "@/components/task-create-dialog-types";
import { useAppStore } from "@/components/state-provider";
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
import {
useRepositoryOptions,
useBranchOptions,
useAgentProfileOptions,
useExecutorHint,
useExecutorProfileOptions,
useIsLocalExecutor,
} from "@/components/task-create-dialog-options";
import { getTaskCreateDraft, setTaskCreateDraft, removeTaskCreateDraft } from "@/lib/local-storage";
/**
* Multi-repo tasks currently only run on the git-worktree executor —
* Docker/Sprites/etc. don't yet know how to provision N sibling repos under
* one task root. Returning a non-null reason marks the option as disabled in
* the executor selector and surfaces this string as a tooltip. The dialog
* only applies this when 2+ repos are selected (see isMultiRepoSelection).
*/
function nonWorktreeDisabledReason(profile: ExecutorProfile): string | null {
if ((profile.executor_type ?? "") === "worktree") return null;
return "Multi-repo tasks only support the git-worktree executor.";
}
/**
* Worktree executor needs a repository to create the worktree from. Disable
* it when the task is in no-repository mode so the picker doesn't offer an
* unworkable choice (the backend would silently fall back to local).
*/
function worktreeDisabledReason(profile: ExecutorProfile): string | null {
if ((profile.executor_type ?? "") !== "worktree") return null;
return "Worktree executor requires a repository.";
}
/**
* Combines the two executor-disable rules into a single resolver:
* - no-repository mode → disable worktree (it needs a repo)
* - multi-repo selection → disable everything except worktree
* - otherwise → no disabling
* The two never co-occur (no-repository implies zero repos, so multi-repo
* cannot be true at the same time), so a simple priority order is enough.
*/
function pickExecutorDisabledReason(
noRepository: boolean,
isMultiRepoSelection: boolean,
): ((profile: ExecutorProfile) => string | null) | undefined {
if (noRepository) return worktreeDisabledReason;
if (isMultiRepoSelection) return nonWorktreeDisabledReason;
return undefined;
}
import type {
StepType,
TaskCreateDialogInitialValues,
DialogFormState,
DialogComputedValues,
DialogComputedArgs,
TaskRepoRow,
} from "@/components/task-create-dialog-types";
import { useRepositoriesState } from "@/components/task-create-dialog-repositories-state";
import { computePassthroughProfile } from "@/components/task-create-dialog-helpers";
import {
computeDialogDefaultStepId,
computeSingleWorkflowFallbackId,
} from "@/components/task-create-dialog-defaults";
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 FormResetters = {
setTaskName: (v: string) => void;
setHasTitle: (v: boolean) => void;
setHasDescription: (v: boolean) => void;
setRepositories: (v: TaskRepoRow[]) => void;
setGitHubBranch: (v: string) => void;
setAgentProfileId: (v: string) => void;
setExecutorId: (v: string) => void;
setExecutorProfileId: (v: string) => void;
setSelectedWorkflowId: (v: string | null) => void;
setFetchedSteps: (v: StepType[] | null) => void;
setDiscoveredRepositories: (v: LocalRepository[]) => void;
setDiscoverReposLoaded: (v: boolean) => void;
setUseGitHubUrl: (v: boolean) => void;
setGitHubUrl: (v: string) => void;
setNoRepository: (v: boolean) => void;
setWorkspacePath: (v: string) => void;
setGitHubBranches: (v: Branch[]) => void;
setGitHubUrlError: (v: string | null) => void;
setGitHubPrHeadBranch: (v: string | null) => void;
setFreshBranchEnabled: (v: boolean) => void;
setCurrentLocalBranch: (v: string) => void;
};
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>>;
prevOpenRef: React.RefObject<boolean>;
};
function useFormResetEffects({
open,
workspaceId,
workflowId,
initialValues,
resetters,
setDraftDescription,
setCurrentDefaults,
setOpenCycle,
prevOpenRef,
}: FormResetEffectsArgs) {
// Restore draft or initialValues when dialog opens
useEffect(() => {
// Only run on rising edge (dialog opening)
const wasOpen = prevOpenRef.current;
(prevOpenRef as React.MutableRefObject<boolean>).current = open;
if (!open || wasOpen) return;
// Increment cycle to force TaskFormInputs remount
setOpenCycle((c) => c + 1);
const defaults = resolveFormDefaults(initialValues, workspaceId);
setCurrentDefaults(defaults);
resetTaskForm(resetters, defaults.name, defaults.description, workflowId, initialValues);
setDraftDescription(defaults.description);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, workflowId, workspaceId]);
useEffect(() => {
if (!open) return;
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,
) {
// In edit mode (has content), use initialValues; in create mode, try draft
const draft =
!hasUserContent(initialValues) && workspaceId ? getTaskCreateDraft(workspaceId) : null;
const initTitle = initialValues?.title ?? "";
const initDesc = initialValues?.description ?? "";
return {
name: draft?.title ?? initTitle,
description: draft?.description ?? initDesc,
};
}
/** Resets task form fields to specified values */
function resetTaskForm(
resetters: FormResetters,
name: string,
description: string,
workflowId: string | null,
initialValues?: TaskCreateDialogInitialValues,
) {
resetters.setTaskName(name);
resetters.setHasTitle(name.trim().length > 0);
resetters.setHasDescription(description.trim().length > 0);
// Seed the unified repos list from initialValues. A repo + branch pre-fill
// becomes a single row; nothing seeds an empty list (the auto-select
// effect later picks the user's last-used repo or the first workspace one).
if (initialValues?.repositoryId) {
resetters.setRepositories([
{
key: "row-0",
repositoryId: initialValues.repositoryId,
branch: initialValues.branch ?? "",
},
]);
} else {
resetters.setRepositories([]);
}
resetters.setGitHubBranch(initialValues?.branch ?? "");
resetters.setAgentProfileId("");
resetters.setExecutorId("");
resetters.setExecutorProfileId("");
resetters.setSelectedWorkflowId(workflowId);
resetters.setFetchedSteps(null);
}
/** Resets repository discovery state */
function resetDiscoveryState(resetters: FormResetters, iv?: TaskCreateDialogInitialValues) {
const ghUrl = iv?.githubUrl ?? "";
resetters.setDiscoveredRepositories([]);
resetters.setDiscoverReposLoaded(false);
resetters.setUseGitHubUrl(Boolean(ghUrl));
resetters.setGitHubUrl(ghUrl);
resetters.setGitHubBranches([]);
resetters.setGitHubUrlError(null);
resetters.setGitHubPrHeadBranch(iv?.checkoutBranch ?? null);
resetters.setFreshBranchEnabled(false);
resetters.setCurrentLocalBranch("");
// Source-mode toggle resets — without these, opening the dialog in "None"
// mode and reopening for a different task would land in None mode again.
resetters.setNoRepository(false);
resetters.setWorkspacePath("");
}
/** 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 };
}
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 [useGitHubUrl, setUseGitHubUrl] = useState(false);
const [githubUrl, setGitHubUrl] = useState("");
const [githubBranches, setGitHubBranches] = useState<Branch[]>([]);
const [githubBranchesLoading, setGitHubBranchesLoading] = useState(false);
const [githubUrlError, setGitHubUrlError] = useState<string | null>(null);
const [githubPrHeadBranch, setGitHubPrHeadBranch] = useState<string | null>(null);
return {
useGitHubUrl,
setUseGitHubUrl,
githubUrl,
setGitHubUrl,
githubBranches,
setGitHubBranches,
githubBranchesLoading,
setGitHubBranchesLoading,
githubUrlError,
setGitHubUrlError,
githubPrHeadBranch,
setGitHubPrHeadBranch,
};
}
/** Core form state declarations */
function useFormStateValues(
workflowId: string | null,
workspaceId: string | null,
open: boolean,
initialValues?: TaskCreateDialogInitialValues,
) {
// 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 prevOpenRef = useRef(false);
// 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 [draftDescription, setDraftDescription] = useState("");
const descriptionInputRef = useRef<TaskFormInputsHandle | null>(null);
// GitHub URL flow has its own branch field (the per-repo branch lives on
// each row in `repositories`). Seed from initialValues for the URL flow only.
const [githubBranch, setGitHubBranch] = useState(initialValues?.branch ?? "");
const [agentProfileId, setAgentProfileId] = useState("");
const [executorId, setExecutorId] = useState("");
const [executorProfileId, setExecutorProfileId] = useState("");
const [selectedWorkflowId, setSelectedWorkflowId] = useState(workflowId);
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 [workspacePath, setWorkspacePath] = useState("");
return {
taskName,
setTaskName,
hasTitle,
setHasTitle,
hasDescription,
setHasDescription,
draftDescription,
setDraftDescription,
descriptionInputRef,
githubBranch,
setGitHubBranch,
agentProfileId,
setAgentProfileId,
executorId,
setExecutorId,
executorProfileId,
setExecutorProfileId,
selectedWorkflowId,
setSelectedWorkflowId,
fetchedSteps,
setFetchedSteps,
isCreatingSession,
setIsCreatingSession,
isCreatingTask,
setIsCreatingTask,
openCycle,
setOpenCycle,
currentDefaults,
setCurrentDefaults,
prevOpenRef,
noRepository,
setNoRepository,
workspacePath,
setWorkspacePath,
};
}
/** 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,
) {
const form = useFormStateValues(workflowId, workspaceId, open, initialValues);
const discovery = useDiscoveryState();
const ghUrl = useGitHubUrlState();
const wfAgent = useWorkflowAgentProfileState();
const repos = useRepositoriesState();
const freshBranch = useFreshBranchState();
useFormResetEffects({
open,
workspaceId,
workflowId,
initialValues,
setDraftDescription: form.setDraftDescription,
setCurrentDefaults: form.setCurrentDefaults,
setOpenCycle: form.setOpenCycle,
prevOpenRef: form.prevOpenRef,
resetters: {
setTaskName: form.setTaskName,
setHasTitle: form.setHasTitle,
setHasDescription: form.setHasDescription,
setRepositories: repos.setRepositories,
setGitHubBranch: form.setGitHubBranch,
setAgentProfileId: form.setAgentProfileId,
setExecutorId: form.setExecutorId,
setExecutorProfileId: form.setExecutorProfileId,
setSelectedWorkflowId: form.setSelectedWorkflowId,
setFetchedSteps: form.setFetchedSteps,
setDiscoveredRepositories: discovery.setDiscoveredRepositories,
setDiscoverReposLoaded: discovery.setDiscoverReposLoaded,
setUseGitHubUrl: ghUrl.setUseGitHubUrl,
setGitHubUrl: ghUrl.setGitHubUrl,
setGitHubBranches: ghUrl.setGitHubBranches,
setGitHubUrlError: ghUrl.setGitHubUrlError,
setGitHubPrHeadBranch: ghUrl.setGitHubPrHeadBranch,
setFreshBranchEnabled: freshBranch.setFreshBranchEnabled,
setCurrentLocalBranch: freshBranch.setCurrentLocalBranch,
setNoRepository: form.setNoRepository,
setWorkspacePath: form.setWorkspacePath,
},
});
const { clearDraft } = useDraftPersistence(
open,
workspaceId,
initialValues,
form.taskName,
form.descriptionInputRef,
);
return { ...form, ...discovery, ...ghUrl, ...wfAgent, ...repos, ...freshBranch, clearDraft };
}
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 function useDialogComputed({
fs,
open,
workspaceId,
workflowId,
defaultStepId,
settingsData,
agentProfiles,
workspaces,
executors,
repositories,
workflows,
snapshots,
}: DialogComputedArgs): DialogComputedValues {
const singleWorkflowId = computeSingleWorkflowFallbackId(
fs.selectedWorkflowId,
workflowId,
workflows,
);
const effectiveWorkflowId = fs.selectedWorkflowId ?? workflowId ?? singleWorkflowId;
// Compute workflow agent lock directly from data — avoids effect timing issues.
const workflowAgentProfileId = (() => {
const wfId = effectiveWorkflowId;
if (!wfId) return "";
const wf = workflows.find((w) => w.id === wfId);
return wf?.agent_profile_id ?? "";
})();
const workflowAgentLocked = Boolean(workflowAgentProfileId);
// fs.agentProfileId lags behind the workflow override on dialog re-open
// (effect deps don't change), so fall back to the synchronous value.
const effectiveAgentProfileId = fs.agentProfileId || workflowAgentProfileId;
const isPassthroughProfile = useMemo(
() => computePassthroughProfile(effectiveAgentProfileId, agentProfiles),
[effectiveAgentProfileId, agentProfiles],
);
const effectiveDefaultStepId = computeDialogDefaultStepId({
selectedWorkflowId: fs.selectedWorkflowId,
workflowId,
fetchedSteps: fs.fetchedSteps,
defaultStepId,
effectiveWorkflowId,
snapshots,
});
const workspaceDefaults = workspaceId
? workspaces.find((ws: Workspace) => ws.id === workspaceId)
: null;
// The form has a repo selection when either: (a) any chip in the unified
// list has a repo set, (b) URL mode has a non-empty URL, or (c) the task
// is intentionally repo-less (noRepository toggle on).
const hasRepositorySelection = Boolean(
fs.noRepository ||
fs.repositories.some((r) => r.repositoryId || r.localPath) ||
(fs.useGitHubUrl && fs.githubUrl.trim()),
);
// Branch options are only used by the URL-mode flow now (the chip's branch
// pill loads branches per-repo). Keep the computed value but always feed it
// the URL branches when in URL mode.
const branchOptions = useBranchOptions(fs.useGitHubUrl ? fs.githubBranches : []);
const agentProfileOptions = useAgentProfileOptions(agentProfiles);
const allExecutorProfiles = useMemo<ExecutorProfile[]>(() => {
return executors.flatMap((executor) =>
(executor.profiles ?? []).map((p) => ({
...p,
executor_type: p.executor_type ?? executor.type,
executor_name: p.executor_name ?? executor.name,
})),
);
}, [executors]);
// Multi-repo tasks only run on the git-worktree executor today — Docker /
// Sprites / standalone don't yet know how to provision N sibling repos. Gate
// non-worktree options only when 2+ repos are selected; single-repo tasks
// keep the full executor catalogue.
const selectedRepoCount = fs.repositories.filter((r) => r.repositoryId || r.localPath).length;
const isMultiRepoSelection = selectedRepoCount > 1;
const executorProfileOptions = useExecutorProfileOptions(allExecutorProfiles, {
disabledReasonFor: pickExecutorDisabledReason(fs.noRepository, isMultiRepoSelection),
});
const executorHint = useExecutorHint(executors, fs.executorId, selectedRepoCount);
const isLocalExecutor = useIsLocalExecutor(executors, fs.executorId);
const { headerRepositoryOptions } = useRepositoryOptions(repositories, fs.discoveredRepositories);
// Treat the dialog as still loading agents until BOTH the agent profiles
// (DB rows) AND the host-utility capability probe have resolved. The
// backend reconciler renames profiles ("Claude" → "Claude Sonnet 4.6") only
// after the probe lands, so showing the selector before then surfaces stale
// labels missing the model badge.
const agentProfilesLoading =
open && (!settingsData.agentsLoaded || !settingsData.capabilitiesLoaded);
const executorsLoading = open && !settingsData.executorsLoaded;
return {
isPassthroughProfile,
effectiveWorkflowId,
effectiveDefaultStepId,
workspaceDefaults,
hasRepositorySelection,
branchOptions,
agentProfileOptions,
executorProfileOptions,
executorHint,
isLocalExecutor,
headerRepositoryOptions,
agentProfilesLoading,
executorsLoading,
workflowAgentLocked,
workflowAgentProfileId,
effectiveAgentProfileId,
};
}
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]);
}
export function useTaskCreateDialogData(
open: boolean,
workspaceId: string | null,
workflowId: string | null,
defaultStepId: string | null,
fs: DialogFormState,
) {
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);
useSettingsData(open);
const { repositories, isLoading: repositoriesLoading } = 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,
});
return {
workflows,
workspaces,
agentProfiles,
executors,
snapshots,
repositories,
repositoriesLoading,
branchesLoading,
computed,
};
}