Files
kandev/apps/web/components/task-create-dialog-effects.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

514 lines
19 KiB
TypeScript

"use client";
import { useEffect, useRef } from "react";
import type { Repository, Executor } from "@/lib/types/http";
import type { AgentProfileOption } from "@/lib/state/slices";
import { DEFAULT_LOCAL_EXECUTOR_TYPE } from "@/lib/utils";
import { useToast } from "@/components/toast-provider";
import {
discoverRepositoriesAction,
getLocalRepositoryStatusAction,
} from "@/app/actions/workspaces";
import { getLocalStorage } from "@/lib/local-storage";
import { STORAGE_KEYS } from "@/lib/settings/constants";
import { listWorkflowSteps } from "@/lib/api/domains/workflow-api";
import { fetchRepoBranches, fetchPRInfo } from "@/lib/api/domains/github-api";
import type {
DialogFormState,
StoreSelections,
TaskCreateEffectsArgs,
} from "@/components/task-create-dialog-types";
export function useWorkflowAgentProfileEffect(
fs: DialogFormState,
workflows: Array<{ id: string; agent_profile_id?: string }>,
agentProfiles: AgentProfileOption[],
) {
const { selectedWorkflowId, setAgentProfileId, setWorkflowAgentProfileId } = fs;
useEffect(() => {
if (!selectedWorkflowId) {
setWorkflowAgentProfileId("");
return;
}
const workflow = workflows.find((w) => w.id === selectedWorkflowId);
if (workflow?.agent_profile_id) {
// Always lock the selector when the workflow specifies an agent profile.
// This prevents the race condition where agentProfiles hasn't loaded yet.
setWorkflowAgentProfileId(workflow.agent_profile_id);
// Only set the agentProfileId once the profile is confirmed available.
const profileExists = agentProfiles.some((p) => p.id === workflow.agent_profile_id);
if (profileExists) {
setAgentProfileId(workflow.agent_profile_id);
}
} else {
setWorkflowAgentProfileId("");
// Restore the user's last-used agent profile when unlocking
const lastId = getLocalStorage<string | null>(STORAGE_KEYS.LAST_AGENT_PROFILE_ID, null);
setAgentProfileId(lastId ?? "");
}
}, [selectedWorkflowId, workflows, agentProfiles, setAgentProfileId, setWorkflowAgentProfileId]);
}
export function useWorkflowStepsEffect(fs: DialogFormState, workflowId: string | null) {
const { selectedWorkflowId, setFetchedSteps } = fs;
useEffect(() => {
if (!selectedWorkflowId || selectedWorkflowId === workflowId) {
void Promise.resolve().then(() => setFetchedSteps(null));
return;
}
let cancelled = false;
listWorkflowSteps(selectedWorkflowId)
.then((response) => {
if (cancelled) return;
const sorted = [...response.steps].sort((a, b) => a.position - b.position);
setFetchedSteps(sorted.map((s) => ({ id: s.id, title: s.name, events: s.events })));
})
.catch(() => {
if (!cancelled) setFetchedSteps(null);
});
return () => {
cancelled = true;
};
}, [selectedWorkflowId, workflowId, setFetchedSteps]);
}
export function useRepositoryAutoSelectEffect(
fs: DialogFormState,
open: boolean,
workspaceId: string | null,
repositories: Repository[],
) {
// On open, ensure there's always at least one chip rendered: prefer the
// user's last-used repo (or the workspace's only repo) so the chip lands
// pre-filled, but fall back to an empty row so the picker is visible
// instead of just the "+" button. URL mode is excluded — that flow swaps
// the chip row for a URL input.
const { repositories: rows, useGitHubUrl, setRepositories } = fs;
useEffect(() => {
if (!open || !workspaceId || useGitHubUrl) return;
if (rows.length > 0) return;
const lastUsedRepoId = getLocalStorage<string | null>(STORAGE_KEYS.LAST_REPOSITORY_ID, null);
let pickId: string | null = null;
if (lastUsedRepoId && repositories.some((r: Repository) => r.id === lastUsedRepoId)) {
pickId = lastUsedRepoId;
} else if (repositories.length === 1) {
pickId = repositories[0].id;
}
void Promise.resolve().then(() =>
setRepositories([
pickId ? { key: "row-0", repositoryId: pickId, branch: "" } : { key: "row-0", branch: "" },
]),
);
}, [open, repositories, rows, useGitHubUrl, workspaceId, setRepositories]);
}
export function useDiscoverReposEffect(
fs: DialogFormState,
open: boolean,
workspaceId: string | null,
repositoriesLoading: boolean,
toast: ReturnType<typeof useToast>["toast"],
) {
const {
discoverReposLoaded,
discoverReposLoading,
setDiscoveredRepositories,
setDiscoverReposLoading,
setDiscoverReposLoaded,
} = fs;
useEffect(() => {
if (!open || !workspaceId || repositoriesLoading || discoverReposLoaded || discoverReposLoading)
return;
void Promise.resolve()
.then(() => setDiscoverReposLoading(true))
.then(() => discoverRepositoriesAction(workspaceId))
.then((r) => {
setDiscoveredRepositories(r.repositories);
})
.catch((e) => {
toast({
title: "Failed to discover repositories",
description: e instanceof Error ? e.message : "Request failed",
variant: "error",
});
setDiscoveredRepositories([]);
})
.finally(() => {
setDiscoverReposLoading(false);
setDiscoverReposLoaded(true);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
discoverReposLoaded,
discoverReposLoading,
open,
fs.discoveredRepositories.length,
repositoriesLoading,
toast,
workspaceId,
]);
}
// Per-row branch listing now lives in the chip itself via useBranches, so the
// old useLocalBranchesEffect is gone.
//
// useCurrentLocalBranchEffect still earns its keep — the fresh-branch
// consent flow needs to know which branch the on-disk clone is currently on,
// and that's only meaningful for a single-row local-executor task. For multi-
// repo tasks fresh-branch is hidden in the UI, so we only resolve a path
// when there's exactly one row.
export function useCurrentLocalBranchEffect(
fs: DialogFormState,
open: boolean,
workspaceId: string | null,
repositories: Repository[],
) {
const {
repositories: rows,
useGitHubUrl,
setCurrentLocalBranch,
setCurrentLocalBranchLoading,
} = fs;
useEffect(() => {
if (!open || !workspaceId || useGitHubUrl || rows.length !== 1) {
setCurrentLocalBranch("");
setCurrentLocalBranchLoading(false);
return;
}
const row = rows[0];
let path = row.localPath ?? "";
if (!path && row.repositoryId) {
const repo = repositories.find((r: Repository) => r.id === row.repositoryId);
path = repo?.local_path ?? "";
}
if (!path) {
setCurrentLocalBranch("");
setCurrentLocalBranchLoading(false);
return;
}
let cancelled = false;
setCurrentLocalBranchLoading(true);
getLocalRepositoryStatusAction(workspaceId, path)
.then((r) => {
if (cancelled) return;
setCurrentLocalBranch(r.current_branch ?? "");
setCurrentLocalBranchLoading(false);
})
.catch(() => {
if (cancelled) return;
setCurrentLocalBranch("");
setCurrentLocalBranchLoading(false);
});
return () => {
cancelled = true;
};
}, [
open,
workspaceId,
useGitHubUrl,
rows,
repositories,
setCurrentLocalBranch,
setCurrentLocalBranchLoading,
]);
}
/**
* Picks the default executor ID to auto-fill on dialog open. Repo-less tasks
* skip the worktree executor (it needs a repo); other modes use the workspace
* default → DEFAULT_LOCAL_EXECUTOR_TYPE → first available, in priority order.
*/
function pickDefaultExecutorId(
executors: Executor[],
workspaceDefaults: { default_executor_id?: string | null } | null | undefined,
noRepository: boolean,
): string | null {
const eligible = noRepository
? executors.filter((e: Executor) => e.type !== "worktree")
: executors;
if (eligible.length === 0) return null;
const defId = workspaceDefaults?.default_executor_id ?? null;
if (defId && eligible.some((e: Executor) => e.id === defId)) return defId;
const local = eligible.find((e: Executor) => e.type === DEFAULT_LOCAL_EXECUTOR_TYPE);
return local?.id ?? eligible[0].id;
}
export function useDefaultSelectionsEffect(
fs: DialogFormState,
open: boolean,
sel: StoreSelections,
workflows: Array<{ id: string; agent_profile_id?: string }>,
) {
const { agentProfiles, executors, workspaceDefaults } = sel;
const {
agentProfileId,
workflowAgentProfileId,
selectedWorkflowId,
executorId,
executorProfileId,
setAgentProfileId,
setExecutorId,
setExecutorProfileId,
noRepository,
} = fs;
useEffect(() => {
// Check synchronously whether the selected workflow has an agent override.
// This avoids a race condition where workflowAgentProfileId state hasn't
// been committed yet by the workflow effect running in the same cycle.
const workflowHasAgent = selectedWorkflowId
? workflows.some((w) => w.id === selectedWorkflowId && w.agent_profile_id)
: false;
if (
!open ||
agentProfileId ||
workflowAgentProfileId ||
workflowHasAgent ||
agentProfiles.length === 0
)
return;
const lastId = getLocalStorage<string | null>(STORAGE_KEYS.LAST_AGENT_PROFILE_ID, null);
if (lastId && agentProfiles.some((p: AgentProfileOption) => p.id === lastId)) {
void Promise.resolve().then(() => setAgentProfileId(lastId));
return;
}
const defId = workspaceDefaults?.default_agent_profile_id ?? null;
if (defId && agentProfiles.some((p: AgentProfileOption) => p.id === defId)) {
void Promise.resolve().then(() => setAgentProfileId(defId));
return;
}
void Promise.resolve().then(() => setAgentProfileId(agentProfiles[0].id));
}, [
open,
agentProfileId,
workflowAgentProfileId,
selectedWorkflowId,
workflows,
agentProfiles,
workspaceDefaults,
setAgentProfileId,
]);
useEffect(() => {
if (!open || executorId || executors.length === 0) return;
const pick = pickDefaultExecutorId(executors, workspaceDefaults, noRepository);
if (pick) void Promise.resolve().then(() => setExecutorId(pick));
}, [open, executorId, executors, workspaceDefaults, setExecutorId, noRepository]);
useEffect(() => {
// Auto-select executor profile: last used (localStorage) → first available
if (!open || executorProfileId || executors.length === 0) return;
const allProfiles = executors.flatMap((e) =>
(e.profiles ?? []).map((p) => ({ ...p, _executorId: e.id })),
);
if (allProfiles.length === 0) return;
const lastId = getLocalStorage<string | null>(STORAGE_KEYS.LAST_EXECUTOR_PROFILE_ID, null);
const pick = lastId && allProfiles.some((p) => p.id === lastId) ? lastId : allProfiles[0].id;
void Promise.resolve().then(() => setExecutorProfileId(pick));
}, [open, executorProfileId, executors, setExecutorProfileId]);
// Derive executorId from the selected executor profile
useEffect(() => {
if (!executorProfileId) return;
for (const executor of executors) {
const match = (executor.profiles ?? []).find((p) => p.id === executorProfileId);
if (match) {
void Promise.resolve().then(() => setExecutorId(executor.id));
return;
}
}
}, [executorProfileId, executors, setExecutorId]);
// Multi-repo guard: when 2+ repos are selected, only worktree profiles can
// run the task (Docker / Sprites / standalone don't yet provision sibling
// repos under one task root). If the current profile is non-worktree, swap
// to a worktree profile — preferring the last-used worktree, otherwise the
// first one available. Single-repo selections leave the profile alone.
useEffect(() => {
if (!open || !executorProfileId || executors.length === 0) return;
const namedRepos = fs.repositories.filter((r) => r.repositoryId || r.localPath);
if (namedRepos.length <= 1) return;
const profileToType = new Map<string, string | undefined>();
const worktreeProfileIds: string[] = [];
for (const e of executors) {
for (const p of e.profiles ?? []) {
const type = p.executor_type ?? e.type;
profileToType.set(p.id, type);
if (type === "worktree") worktreeProfileIds.push(p.id);
}
}
if (worktreeProfileIds.length === 0) return;
if (profileToType.get(executorProfileId) === "worktree") return;
const lastId = getLocalStorage<string | null>(STORAGE_KEYS.LAST_EXECUTOR_PROFILE_ID, null);
const pick = lastId && worktreeProfileIds.includes(lastId) ? lastId : worktreeProfileIds[0];
void Promise.resolve().then(() => setExecutorProfileId(pick));
}, [open, executorProfileId, executors, fs.repositories, setExecutorProfileId]);
}
/**
* Auto-selects a sensible branch in the GitHub URL flow. Per-repo (workspace
* or discovered) branch auto-select happens inside RepoChip when a row's
* branches load — that keeps the per-row state confined to the chip.
*/
export function useBranchAutoSelectEffect(fs: DialogFormState) {
const { githubBranch, githubBranches, useGitHubUrl, setGitHubBranch, githubPrHeadBranch } = fs;
useEffect(() => {
if (!useGitHubUrl || githubBranches.length === 0 || githubBranch) return;
if (githubPrHeadBranch) {
const prBranch = githubBranches.find((b) => b.name === githubPrHeadBranch);
if (prBranch) {
setGitHubBranch(prBranch.name);
return;
}
}
// GitHub URL branches are referenced by name only (no remote prefix);
// selectPreferredBranch expects origin-prefixed remotes, so pick directly.
const preferred =
githubBranches.find((b) => b.name === "main") ??
githubBranches.find((b) => b.name === "master") ??
githubBranches[0];
if (preferred) setGitHubBranch(preferred.name);
}, [githubBranch, githubBranches, useGitHubUrl, setGitHubBranch, githubPrHeadBranch]);
}
/** Parse a GitHub URL to extract owner, repo, and optional PR number. Returns null if invalid. */
function parseGitHubUrl(url: string): { owner: string; repo: string; prNumber?: number } | null {
const trimmed = url.trim();
if (!trimmed) return null;
// Try PR URL first: github.com/owner/repo/pull/123 (with optional trailing path/hash like /files#diff-...)
const prMatch = trimmed.match(
/(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)(?:[/?#].*)?$/,
);
if (prMatch) {
return { owner: prMatch[1], repo: prMatch[2], prNumber: parseInt(prMatch[3], 10) };
}
// Fall back to repo URL: github.com/owner/repo
const match = trimmed.match(
/(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/,
);
if (!match) return null;
return { owner: match[1], repo: match[2] };
}
export function useGitHubUrlBranchesEffect(fs: DialogFormState, open: boolean) {
const {
useGitHubUrl,
githubUrl,
setGitHubBranches,
setGitHubBranchesLoading,
setGitHubUrlError,
setGitHubPrHeadBranch,
} = fs;
useEffect(() => {
if (!open || !useGitHubUrl) {
setGitHubBranchesLoading(false);
return;
}
const trimmed = githubUrl.trim();
if (!trimmed) {
setGitHubBranches([]);
setGitHubBranchesLoading(false);
setGitHubUrlError(null);
return;
}
const parsed = parseGitHubUrl(githubUrl);
if (!parsed) {
setGitHubBranches([]);
setGitHubPrHeadBranch(null);
setGitHubBranchesLoading(false);
setGitHubUrlError("Invalid GitHub URL — expected github.com/owner/repo or .../pull/123");
return;
}
let cancelled = false;
setGitHubUrlError(null);
setGitHubBranchesLoading(true);
setGitHubPrHeadBranch(null);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15_000);
const fetchOpts = { init: { signal: controller.signal } };
const branchesPromise = fetchRepoBranches(parsed.owner, parsed.repo, fetchOpts);
const prPromise = parsed.prNumber
? fetchPRInfo(parsed.owner, parsed.repo, parsed.prNumber, fetchOpts).catch(() => null)
: Promise.resolve(null);
Promise.all([branchesPromise, prPromise])
.then(([branchesRes, prInfo]) => {
if (cancelled) return;
setGitHubBranches(
branchesRes.branches.map((b) => ({ name: b.name, type: "remote" as const })),
);
setGitHubUrlError(null);
if (prInfo) {
setGitHubPrHeadBranch(prInfo.head_branch);
}
})
.catch((err) => {
if (cancelled) return;
const isAbort = err instanceof DOMException && err.name === "AbortError";
const isNotConfigured = err instanceof Error && err.message.includes("not configured");
let errorMessage = "Repository not found or not accessible";
if (isAbort) {
errorMessage = "Request timed out. Check your GitHub configuration in Settings.";
} else if (isNotConfigured) {
errorMessage = "GitHub is not configured. Set up a token in Settings > GitHub.";
}
setGitHubUrlError(errorMessage);
setGitHubBranches([]);
})
.finally(() => {
clearTimeout(timeoutId);
if (!cancelled) setGitHubBranchesLoading(false);
});
return () => {
cancelled = true;
clearTimeout(timeoutId);
controller.abort();
};
}, [
open,
useGitHubUrl,
githubUrl,
setGitHubBranches,
setGitHubBranchesLoading,
setGitHubUrlError,
setGitHubPrHeadBranch,
]);
}
export function useTaskCreateDialogEffects(fs: DialogFormState, args: TaskCreateEffectsArgs) {
const { open, workspaceId, workflowId, repositories, repositoriesLoading } = args;
const { agentProfiles, executors, workspaceDefaults, toast, workflows, isLocalExecutor } = args;
useWorkflowStepsEffect(fs, workflowId);
useWorkflowAgentProfileEffect(fs, workflows, agentProfiles);
useRepositoryAutoSelectEffect(fs, open, workspaceId, repositories);
useDiscoverReposEffect(fs, open, workspaceId, repositoriesLoading, toast);
useBranchAutoSelectEffect(fs);
useCurrentLocalBranchEffect(fs, open, workspaceId, repositories);
useResetBranchOnLocalSwitchEffect(fs, isLocalExecutor);
useDefaultSelectionsEffect(fs, open, { agentProfiles, executors, workspaceDefaults }, workflows);
useGitHubUrlBranchesEffect(fs, open);
}
// Reset row.branch on every "switch to local executor" transition so the
// chip's autoselect effect can re-fire and prefer the workspace's current
// branch (preferredDefaultBranch). Without this, a branch the user picked
// under worktree mode (say "develop") would persist on the row, the chip
// would show "develop" after switching to local, and submit would carry
// "develop" → backend `git checkout develop` against the user's working
// tree. With the reset, switching to local always defaults to "current
// branch on disk" and the user has to opt back into a different branch
// explicitly.
function useResetBranchOnLocalSwitchEffect(fs: DialogFormState, isLocalExecutor: boolean) {
const { repositories: rows, updateRepository } = fs;
const wasLocalRef = useRef(isLocalExecutor);
useEffect(() => {
const prev = wasLocalRef.current;
wasLocalRef.current = isLocalExecutor;
if (!isLocalExecutor || prev) return; // only fire on false → true transition
for (const row of rows) {
if (row.branch) updateRepository(row.key, { branch: "" });
}
}, [isLocalExecutor, rows, updateRepository]);
}