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

591 lines
17 KiB
TypeScript

"use client";
import { useCallback, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { updateTask } from "@/lib/api";
import { useAppStore } from "@/components/state-provider";
import { launchSession } from "@/lib/services/session-launch-service";
import { buildStartRequest } from "@/lib/services/session-launch-helpers";
import { useToast } from "@/components/toast-provider";
import { linkToTask } from "@/lib/links";
import type { SubmitHandlersDeps } from "@/components/task-create-dialog-types";
import { useFreshBranchConsent } from "@/components/task-create-dialog-fresh-branch-consent";
import {
activatePlanMode,
buildCreateTaskPayload,
buildRepositoriesPayload,
validateCreateInputs,
toMessageAttachments,
} from "@/components/task-create-dialog-helpers";
const GENERIC_ERROR_MESSAGE = "An error occurred";
// eslint-disable-next-line max-lines-per-function
export function useTaskSubmitHandlers({
isSessionMode,
isEditMode,
isPassthroughProfile,
taskName,
workspaceId,
workflowId,
effectiveWorkflowId,
effectiveDefaultStepId,
repositories,
discoveredRepositories,
workspaceRepositories,
useGitHubUrl,
githubUrl,
githubPrHeadBranch,
githubBranch,
agentProfileId,
executorId,
executorProfileId,
editingTask,
onSuccess,
onCreateSession,
onOpenChange,
taskId,
parentTaskId,
descriptionInputRef,
setIsCreatingSession,
setIsCreatingTask,
setHasTitle,
setHasDescription,
setTaskName,
setRepositories,
setGitHubBranch,
setAgentProfileId,
setExecutorId,
setSelectedWorkflowId,
setFetchedSteps,
clearDraft,
freshBranchEnabled,
isLocalExecutor,
repositoryLocalPath,
noRepository,
workspacePath,
transformDescriptionBeforeSubmit,
}: SubmitHandlersDeps) {
const router = useRouter();
const { toast } = useToast();
const setActiveDocument = useAppStore((state) => state.setActiveDocument);
const setPlanMode = useAppStore((state) => state.setPlanMode);
const isFreshBranchActive =
freshBranchEnabled && isLocalExecutor && !useGitHubUrl && repositoryLocalPath !== "";
const { pendingDiscard, ensureFreshBranchConsent, createTaskWithFreshBranchRetry } =
useFreshBranchConsent({
isFreshBranchActive,
workspaceId,
repositoryLocalPath,
toast,
});
const buildFreshBranchPayload = (consentedDirtyFiles: string[]) =>
isFreshBranchActive ? { confirmDiscard: true, consentedDirtyFiles } : undefined;
const validateForCreate = useCallback(
(trimmedTitle: string) =>
validateCreateInputs({
trimmedTitle,
workspaceId,
effectiveWorkflowId,
repositories,
githubUrl,
agentProfileId,
noRepository,
}),
[workspaceId, effectiveWorkflowId, repositories, githubUrl, agentProfileId, noRepository],
);
const resetForm = useCallback(() => {
setHasTitle(false);
setHasDescription(false);
setTaskName("");
setRepositories([]);
setGitHubBranch("");
setAgentProfileId("");
setExecutorId("");
setSelectedWorkflowId(workflowId);
setFetchedSteps(null);
// State setters are stable; only workflowId can change
}, [
workflowId,
setHasTitle,
setHasDescription,
setTaskName,
setRepositories,
setGitHubBranch,
setAgentProfileId,
setExecutorId,
setSelectedWorkflowId,
setFetchedSteps,
]);
const getRepositoriesPayload = useCallback(
(consentedDirtyFiles: string[] = []) => {
if (noRepository) return [];
return buildRepositoriesPayload({
useGitHubUrl,
githubUrl,
githubBranch,
githubPrHeadBranch,
repositories,
discoveredRepositories,
workspaceRepositories,
isLocalExecutor,
freshBranch: buildFreshBranchPayload(consentedDirtyFiles),
});
},
// buildFreshBranchPayload is a closure over current scope; lint exception kept narrow.
// eslint-disable-next-line react-hooks/exhaustive-deps
[
noRepository,
useGitHubUrl,
githubUrl,
githubBranch,
githubPrHeadBranch,
repositories,
discoveredRepositories,
workspaceRepositories,
isLocalExecutor,
isFreshBranchActive,
],
);
const handleSessionSubmit = useCallback(async () => {
const description = descriptionInputRef.current?.getValue() ?? "";
const trimmedDescription = description.trim();
const attachments = descriptionInputRef.current?.getAttachments() ?? [];
if (!agentProfileId) return;
if (!trimmedDescription && !isPassthroughProfile) return;
if (onCreateSession) {
onCreateSession({ prompt: trimmedDescription, agentProfileId, executorId });
onOpenChange(false);
return;
}
if (!taskId) return;
setIsCreatingSession(true);
try {
const { request } = buildStartRequest(taskId, agentProfileId, {
executorId,
executorProfileId: executorProfileId || undefined,
prompt: trimmedDescription,
attachments: toMessageAttachments(attachments),
});
await launchSession(request);
onOpenChange(false);
router.push(linkToTask(taskId));
} catch (error) {
toast({
title: "Failed to create session",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
setIsCreatingSession(false);
}
}, [
agentProfileId,
executorId,
executorProfileId,
isPassthroughProfile,
onCreateSession,
onOpenChange,
router,
taskId,
toast,
descriptionInputRef,
setIsCreatingSession,
]);
const performTaskUpdate = useCallback(async () => {
if (!editingTask) return null;
const trimmedTitle = taskName.trim();
if (!trimmedTitle) return null;
const description = descriptionInputRef.current?.getValue() ?? "";
const trimmedDescription = description.trim();
const repositoriesPayload = getRepositoriesPayload();
const updatePayload: Parameters<typeof updateTask>[1] = {
title: trimmedTitle,
description: trimmedDescription,
...(repositoriesPayload.length > 0 && { repositories: repositoriesPayload }),
};
const updatedTask = await updateTask(editingTask.id, updatePayload);
return { updatedTask, trimmedDescription };
}, [editingTask, taskName, descriptionInputRef, getRepositoriesPayload]);
const handleEditSubmit = useCallback(async () => {
setIsCreatingTask(true);
try {
const result = await performTaskUpdate();
if (!result) return;
const { updatedTask, trimmedDescription } = result;
let taskSessionId: string | null = null;
if (agentProfileId) {
try {
const { request } = buildStartRequest(updatedTask.id, agentProfileId, {
executorId,
executorProfileId: executorProfileId || undefined,
prompt: trimmedDescription || "",
});
const response = await launchSession(request);
taskSessionId = response?.session_id ?? null;
} catch (error) {
console.error("[TaskCreateDialog] failed to start agent:", error);
}
}
onSuccess?.(updatedTask, "edit", { taskSessionId });
} catch (error) {
toast({
title: "Failed to update task",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
onOpenChange(false);
setIsCreatingTask(false);
}
}, [
performTaskUpdate,
agentProfileId,
executorId,
executorProfileId,
onSuccess,
onOpenChange,
toast,
setIsCreatingTask,
]);
const handleUpdateWithoutAgent = useCallback(async () => {
setIsCreatingTask(true);
try {
const result = await performTaskUpdate();
if (!result) return;
onSuccess?.(result.updatedTask, "edit");
} catch (error) {
toast({
title: "Failed to update task",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
onOpenChange(false);
setIsCreatingTask(false);
}
}, [performTaskUpdate, onSuccess, onOpenChange, toast, setIsCreatingTask]);
const performCreate = useCallback(
async (opts: {
trimmedTitle: string;
trimmedDescription: string;
consented: string[];
withAgent: boolean;
planMode?: boolean;
attachments?: ReturnType<typeof toMessageAttachments>;
}) => {
if (!workspaceId || !effectiveWorkflowId) return;
const buildPayload = (c: string[]) =>
buildCreateTaskPayload({
workspaceId,
effectiveWorkflowId,
trimmedTitle: opts.trimmedTitle,
trimmedDescription: opts.trimmedDescription,
repositoriesPayload: getRepositoriesPayload(c),
agentProfileId,
executorId,
executorProfileId,
withAgent: opts.withAgent,
planMode: opts.planMode,
attachments: opts.attachments,
parentId: parentTaskId,
// Pass undefined (not "") for an empty trimmed path so the JSON
// payload omits the key entirely — matches the noRepository=false
// case and keeps "no path provided" semantically distinct from
// "empty path string" on the wire.
workspacePath: noRepository ? workspacePath.trim() || undefined : undefined,
});
const taskResponse = await createTaskWithFreshBranchRetry(buildPayload, opts.consented);
if (!taskResponse) return;
const newSessionId = taskResponse.session_id ?? taskResponse.primary_session_id ?? null;
onSuccess?.(taskResponse, "create", { taskSessionId: newSessionId });
clearDraft();
onOpenChange(false);
if (opts.planMode && newSessionId) {
activatePlanMode({
sessionId: newSessionId,
taskId: taskResponse.id,
setActiveDocument,
setPlanMode,
router,
});
} else if (opts.withAgent && isPassthroughProfile) {
router.push(linkToTask(taskResponse.id));
}
},
[
workspaceId,
effectiveWorkflowId,
agentProfileId,
executorId,
executorProfileId,
isPassthroughProfile,
parentTaskId,
noRepository,
workspacePath,
onSuccess,
onOpenChange,
clearDraft,
setActiveDocument,
setPlanMode,
router,
getRepositoriesPayload,
createTaskWithFreshBranchRetry,
],
);
const handleCreatePlanMode = useCallback(
(trimmedTitle: string, consented: string[]) =>
performCreate({
trimmedTitle,
trimmedDescription: "",
consented,
withAgent: false,
planMode: true,
}),
[performCreate],
);
const performEditWithPlanMode = useCallback(async () => {
const result = await performTaskUpdate();
if (!result) return;
const { updatedTask, trimmedDescription } = result;
const { request } = buildStartRequest(updatedTask.id, agentProfileId, {
executorId,
executorProfileId: executorProfileId || undefined,
prompt: trimmedDescription || "",
planMode: true,
});
const response = await launchSession(request);
const newSessionId = response?.session_id ?? null;
onSuccess?.(updatedTask, "edit", { taskSessionId: newSessionId });
onOpenChange(false);
if (newSessionId) {
activatePlanMode({
sessionId: newSessionId,
taskId: updatedTask.id,
setActiveDocument,
setPlanMode,
router,
});
}
}, [
performTaskUpdate,
agentProfileId,
executorId,
executorProfileId,
onSuccess,
onOpenChange,
setActiveDocument,
setPlanMode,
router,
]);
const handleCreateWithPlanMode = useCallback(async () => {
if (isEditMode) {
setIsCreatingTask(true);
try {
await performEditWithPlanMode();
} catch (error) {
toast({
title: "Failed to start task in plan mode",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
setIsCreatingTask(false);
}
return;
}
const trimmedTitle = taskName.trim();
const description = descriptionInputRef.current?.getValue() ?? "";
const trimmedDescription = description.trim();
const attachments = toMessageAttachments(descriptionInputRef.current?.getAttachments() ?? []);
if (!validateForCreate(trimmedTitle)) return;
const consent = await ensureFreshBranchConsent();
if (consent === null) return;
setIsCreatingTask(true);
try {
await performCreate({
trimmedTitle,
trimmedDescription,
consented: consent,
withAgent: true,
planMode: true,
attachments,
});
} catch (error) {
toast({
title: "Failed to start task in plan mode",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
setIsCreatingTask(false);
}
}, [
isEditMode,
performEditWithPlanMode,
taskName,
validateForCreate,
ensureFreshBranchConsent,
performCreate,
toast,
descriptionInputRef,
setIsCreatingTask,
]);
const handleCreateSubmit = useCallback(async () => {
const trimmedTitle = taskName.trim();
const description = descriptionInputRef.current?.getValue() ?? "";
const trimmedDescription = description.trim();
const attachments = toMessageAttachments(descriptionInputRef.current?.getAttachments() ?? []);
if (!validateForCreate(trimmedTitle)) return;
const consent = await ensureFreshBranchConsent();
if (consent === null) return;
setIsCreatingTask(true);
try {
if (trimmedDescription || isPassthroughProfile) {
const finalDescription = transformDescriptionBeforeSubmit
? await transformDescriptionBeforeSubmit(trimmedDescription)
: trimmedDescription;
await performCreate({
trimmedTitle,
trimmedDescription: finalDescription,
consented: consent,
withAgent: true,
attachments,
});
} else {
await handleCreatePlanMode(trimmedTitle, consent);
}
} catch (error) {
toast({
title: "Failed to create task",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
setIsCreatingTask(false);
}
}, [
taskName,
isPassthroughProfile,
validateForCreate,
ensureFreshBranchConsent,
performCreate,
handleCreatePlanMode,
transformDescriptionBeforeSubmit,
toast,
descriptionInputRef,
setIsCreatingTask,
]);
const handleCreateWithoutAgent = useCallback(async () => {
const trimmedTitle = taskName.trim();
const trimmedDescription = (descriptionInputRef.current?.getValue() ?? "").trim();
if (!validateForCreate(trimmedTitle)) return;
if (!trimmedDescription || !effectiveDefaultStepId || !workspaceId || !effectiveWorkflowId)
return;
const consent = await ensureFreshBranchConsent();
if (consent === null) return;
setIsCreatingTask(true);
try {
const buildPayload = (c: string[]) => {
const p = buildCreateTaskPayload({
workspaceId,
effectiveWorkflowId,
trimmedTitle,
trimmedDescription,
repositoriesPayload: getRepositoriesPayload(c),
agentProfileId,
executorId,
executorProfileId,
withAgent: false,
workspacePath: noRepository ? workspacePath.trim() || undefined : undefined,
});
p.workflow_step_id = effectiveDefaultStepId;
return p;
};
const taskResponse = await createTaskWithFreshBranchRetry(buildPayload, consent);
if (!taskResponse) return;
onSuccess?.(taskResponse, "create");
clearDraft();
onOpenChange(false);
} catch (error) {
toast({
title: "Failed to create task",
description: error instanceof Error ? error.message : GENERIC_ERROR_MESSAGE,
variant: "error",
});
} finally {
setIsCreatingTask(false);
}
}, [
taskName,
workspaceId,
effectiveWorkflowId,
agentProfileId,
effectiveDefaultStepId,
executorId,
executorProfileId,
noRepository,
workspacePath,
validateForCreate,
getRepositoriesPayload,
ensureFreshBranchConsent,
createTaskWithFreshBranchRetry,
onSuccess,
onOpenChange,
clearDraft,
toast,
descriptionInputRef,
setIsCreatingTask,
]);
const handleSubmit = useCallback(
async (e: FormEvent) => {
e.preventDefault();
if (isSessionMode) return handleSessionSubmit();
if (isEditMode) return handleEditSubmit();
return handleCreateSubmit();
},
[isSessionMode, isEditMode, handleSessionSubmit, handleEditSubmit, handleCreateSubmit],
);
const handleCancel = useCallback(() => {
resetForm();
onOpenChange(false);
}, [resetForm, onOpenChange]);
return {
resetForm,
handleSubmit,
handleUpdateWithoutAgent,
handleCreateWithoutAgent,
handleCreateWithPlanMode,
handleCancel,
pendingDiscard,
};
}