Files
kandev/apps/web/components/task-create-dialog-form-body.tsx
T
João Salavisa 54b98ed9eb feat(jira): add Jira integration for ticket browsing, import, and task linking (#705)
* feat(jira): add Jira integration for ticket browsing, import, and task linking

Adds a workspace-scoped Atlassian Cloud integration: per-workspace settings
(site URL, email, API token or session cookie), encrypted secret storage,
and a REST client for tickets, projects, search, and transitions. A
background poller probes credentials on a 90s cadence and the keepalive
runs immediately on save so the UI's connected indicator updates without
delay.

The /jira page provides ticket browsing with filter pills, custom JQL,
saved views (including JQL), and configurable task-launch presets that
prefill TaskCreateDialog. JiraLinkButton on the task top bar links an
existing task to a ticket by prepending its key to the title; the ticket
popover surfaces details, transitions, and re-auth prompts on session
expiry. Topbar shows separate icon buttons for GitHub and Jira when each
is configured.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(jira): address PR review feedback

- Token-based pagination (pageToken/isLast) replaces broken offset/total pagination
- Race-fix in service.clientFor: re-check cache after acquiring write lock
- sync.Mutex guards poller started/cancel state against concurrent Start/Stop
- Channel-based + atomic.Int32 test sync replaces time.Sleep polling in poller_test
- Async auth probe on SetConfig with detached context.Background goroutine
- Distinguish 4xx vs 5xx in httpSetConfig via ErrInvalidConfig sentinel
- Propagate 4xx APIErrors from ListTransitions in GetTicket
- Distinguish "not found" from real errors in jiraSecretAdapter.Exists
- Log secret Exists errors instead of swallowing
- walkADF: handle softBreak (was only hardBreak despite the doc-comment)
- Consolidate JIRA_KEY_RE in jira-ticket-common; remove duplicates
- ticket-row imports formatRelative/statusBadgeClass from common
- isFilterState type guard validates SavedView.filters shape
- task-presets readStorage preserves user's "cleared all" intent (returns [])
- task-presets-section gates draft sync on `loaded` to avoid wiping in-progress edits
- jira-api: caller `init` no longer overrides method/body via spread order
- jira-settings: disable Test button when no saved/typed secret

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(jira): record auth probe failure even when probe ctx expires

- RecordAuthHealth now uses a fresh context.Background-derived ctx with a
  5s timeout for the UpdateAuthHealth DB write, so a probe that consumes
  its full 15s deadline still persists the failure (greptile P1).
- SetConfig goroutine drops its redundant outer timeout — RecordAuthHealth
  manages its own probe timeout, so context.Background is enough.
- Add Service.SetProbeHook so tests can synchronize on probe completion;
  service_test waitForAuthProbe now blocks on the hook channel instead of
  time.Sleep polling.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(jira): address coderabbit review feedback (round 3)

- url.PathEscape ticketKey in GetTicket/ListTransitions/DoTransition paths
  to harden against malicious keys ('../../foo', 'KEY?override=x').
- factoryHit on the test fixture is now sync/atomic.Int32; the async probe
  goroutine spawned by SetConfig races the test thread under -race.
- GetConfig logs Reveal failures (was silently dropped, leaving the UI to
  show "no expiry info" indistinguishably from a freshly-saved cookie).
- DeleteConfig logs secret-delete errors instead of swallowing them.
- clientFor distinguishes a secret-store failure from "not configured" so
  the UI doesn't render the configure-CTA for transient backend errors.
- Unify ErrNotConfigured wire code: HTTP and WebSocket both return
  "JIRA_NOT_CONFIGURED" via a shared constant.
- JiraLinkButton strips a leading "PROJ-123: " before re-prefixing so
  re-linking a task replaces the prefix instead of stacking it.
- jira-settings clears testResult on save/delete so the alert reflects
  only the currently-saved credentials.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(jira): cover Reveal error path in clientFor

Reveal-error case is distinct from "no config row" — the former wraps
the underlying error, the latter returns ErrNotConfigured. Without
this test the changed contract has no regression coverage.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(jira): route secret adapter Set through Exists

Treating every Get error as "not found" turned a transient DB error on
an existing row into a constraint-violation Create that masked the real
cause. Reuse Exists so the "secret not found:" prefix is the only path
that falls through to Create.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(jira): cover jiraSecretAdapter.Set branching

Routing Set through Exists changed the contract: a transient DB error
in Get now propagates instead of cascading into a constraint-violation
Create. Add three tests so a future refactor cannot regress this without
CI catching it.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(jira): split Reveal errors and guard Save for new configs

- resolveCredentials now mirrors the clientFor split: a Reveal error
  surfaces as `read jira secret: %w` with a warn log instead of
  collapsing into "no token stored — paste one to test".
- disableSave gains the same missing-secret guard as disableTest so a
  brand-new config can no longer POST an empty secret and leave the
  workspace stuck with hasSecret=false.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 22:47:45 +01:00

375 lines
12 KiB
TypeScript

"use client";
import { memo, useCallback, useState } from "react";
import Link from "next/link";
import type { AgentProfileOption } from "@/lib/state/slices";
import type { WorkflowSnapshotData } from "@/lib/state/slices/kanban/types";
import { WorkflowSelectorRow } from "@/components/workflow-selector-row";
import { AgentLogo } from "@/components/agent-logo";
import type { DialogFormState } from "@/components/task-create-dialog-types";
import type { useKeyboardShortcutHandler } from "@/hooks/use-keyboard-shortcut";
import { TaskFormInputs } from "@/components/task-create-dialog-selectors";
import type { JiraTicket } from "@/lib/types/jira";
type SelectorOption = {
value: string;
label: string;
renderLabel: () => React.ReactNode;
};
type CreateEditSelectorsProps = {
isTaskStarted: boolean;
hasRepositorySelection: boolean;
branchOptions: SelectorOption[];
branch: string;
onBranchChange: (value: string) => void;
branchesLoading: boolean;
localBranchesLoading: boolean;
agentProfiles: AgentProfileOption[];
agentProfilesLoading: boolean;
agentProfileOptions: SelectorOption[];
agentProfileId: string;
onAgentProfileChange: (value: string) => void;
isCreatingSession: boolean;
executorProfileOptions: Array<{
value: string;
label: string;
renderLabel?: () => React.ReactNode;
}>;
executorProfileId: string;
onExecutorProfileChange: (value: string) => void;
executorsLoading: boolean;
BranchSelectorComponent: React.ComponentType<{
options: SelectorOption[];
value: string;
onValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
searchPlaceholder: string;
emptyMessage: string;
}>;
AgentSelectorComponent: React.ComponentType<{
options: SelectorOption[];
value: string;
onValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
triggerClassName?: string;
}>;
ExecutorProfileSelectorComponent: React.ComponentType<{
options: Array<{ value: string; label: string; renderLabel?: () => React.ReactNode }>;
value: string;
onValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
triggerClassName?: string;
}>;
isLocalExecutor: boolean;
useGitHubUrl: boolean;
workflowAgentLocked: boolean;
};
export const CreateEditSelectors = memo(function CreateEditSelectors({
isTaskStarted,
hasRepositorySelection,
branchOptions,
branch,
onBranchChange,
branchesLoading,
localBranchesLoading,
agentProfiles,
agentProfilesLoading,
agentProfileOptions,
agentProfileId,
onAgentProfileChange,
isCreatingSession,
executorProfileOptions,
executorProfileId,
onExecutorProfileChange,
executorsLoading,
isLocalExecutor,
useGitHubUrl,
workflowAgentLocked,
BranchSelectorComponent,
AgentSelectorComponent,
ExecutorProfileSelectorComponent,
}: CreateEditSelectorsProps) {
if (isTaskStarted) return null;
const agentLockedByWorkflow = workflowAgentLocked;
const isLocalWithoutGitHubUrl = isLocalExecutor && !useGitHubUrl;
const branchPlaceholder = (() => {
if (isLocalWithoutGitHubUrl) return "Uses current branch";
if (!hasRepositorySelection) return "Select repository first";
if (branchesLoading || localBranchesLoading) return "Loading branches...";
return branchOptions.length > 0 ? "Select branch" : "No branches found";
})();
const branchDisabled =
isLocalWithoutGitHubUrl ||
!hasRepositorySelection ||
branchesLoading ||
localBranchesLoading ||
branchOptions.length === 0;
const agentPlaceholder = (() => {
if (agentProfilesLoading) return "Loading agents...";
if (agentProfiles.length === 0) return "No agents available";
return "Select agent";
})();
return (
<div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
<div>
<BranchSelectorComponent
options={branchOptions}
value={branch}
onValueChange={onBranchChange}
placeholder={branchPlaceholder}
searchPlaceholder="Search branches..."
emptyMessage="No branch found."
disabled={branchDisabled}
/>
</div>
<div>
{agentProfiles.length === 0 && !agentProfilesLoading ? (
<div className="flex h-7 items-center justify-center gap-2 rounded-sm border border-input px-3 text-xs text-muted-foreground">
<span>No agents found.</span>
<Link href="/settings/agents" className="text-primary hover:underline">
Add agent
</Link>
</div>
) : (
<>
<AgentSelectorComponent
options={agentProfileOptions}
value={agentProfileId}
onValueChange={onAgentProfileChange}
placeholder={agentPlaceholder}
disabled={agentProfilesLoading || isCreatingSession || agentLockedByWorkflow}
/>
{agentLockedByWorkflow && (
<p className="text-[11px] text-muted-foreground mt-1">Agent set by workflow</p>
)}
</>
)}
</div>
<div>
<ExecutorProfileSelectorComponent
options={executorProfileOptions}
value={executorProfileId}
onValueChange={onExecutorProfileChange}
placeholder={executorsLoading ? "Loading profiles..." : "Select profile"}
disabled={executorsLoading}
/>
</div>
</div>
);
});
type SessionSelectorsProps = {
agentProfileOptions: SelectorOption[];
agentProfileId: string;
onAgentProfileChange: (value: string) => void;
agentProfilesLoading: boolean;
isCreatingSession: boolean;
executorProfileOptions: Array<{
value: string;
label: string;
renderLabel?: () => React.ReactNode;
}>;
executorProfileId: string;
onExecutorProfileChange: (value: string) => void;
executorsLoading: boolean;
AgentSelectorComponent: React.ComponentType<{
options: SelectorOption[];
value: string;
onValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
triggerClassName?: string;
}>;
ExecutorProfileSelectorComponent: React.ComponentType<{
options: Array<{ value: string; label: string; renderLabel?: () => React.ReactNode }>;
value: string;
onValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
triggerClassName?: string;
}>;
};
export const SessionSelectors = memo(function SessionSelectors({
agentProfileOptions,
agentProfileId,
onAgentProfileChange,
agentProfilesLoading,
isCreatingSession,
executorProfileOptions,
executorProfileId,
onExecutorProfileChange,
executorsLoading,
AgentSelectorComponent,
ExecutorProfileSelectorComponent,
}: SessionSelectorsProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<AgentSelectorComponent
options={agentProfileOptions}
value={agentProfileId}
onValueChange={onAgentProfileChange}
placeholder={agentProfilesLoading ? "Loading agent profiles..." : "Select agent profile"}
disabled={agentProfilesLoading || isCreatingSession}
/>
<ExecutorProfileSelectorComponent
options={executorProfileOptions}
value={executorProfileId}
onValueChange={onExecutorProfileChange}
placeholder={executorsLoading ? "Loading profiles..." : "Select profile"}
disabled={executorsLoading || isCreatingSession}
/>
</div>
);
});
type WorkflowSectionProps = {
isCreateMode: boolean;
isTaskStarted: boolean;
workflows: Array<{ id: string; name: string; agent_profile_id?: string; [key: string]: unknown }>;
snapshots: Record<string, WorkflowSnapshotData>;
effectiveWorkflowId: string | null;
onWorkflowChange: (value: string) => void;
agentProfiles: AgentProfileOption[];
};
export const WorkflowSection = memo(function WorkflowSection({
isCreateMode,
isTaskStarted,
workflows,
snapshots,
effectiveWorkflowId,
onWorkflowChange,
agentProfiles,
}: WorkflowSectionProps) {
const [lastUsedWorkflowId, setLastUsedWorkflowId] = useState<string | null>(null);
const handleWorkflowChange = useCallback(
(workflowId: string) => {
setLastUsedWorkflowId(workflowId);
onWorkflowChange(workflowId);
},
[onWorkflowChange],
);
if (!isCreateMode || isTaskStarted) return null;
// Single workflow — show agent override info if any overrides exist
if (workflows.length <= 1) {
const singleWorkflow = workflows[0];
if (!singleWorkflow) return null;
const snapshot = snapshots[singleWorkflow.id];
const workflowProfile = singleWorkflow.agent_profile_id
? agentProfiles.find((p) => p.id === singleWorkflow.agent_profile_id)
: null;
const stepsWithOverrides = (snapshot?.steps ?? [])
.filter((s) => s.agent_profile_id)
.map((s) => ({
name: s.title,
profile: agentProfiles.find((p) => p.id === s.agent_profile_id),
}))
.filter((s) => s.profile);
if (!workflowProfile && stepsWithOverrides.length === 0) return null;
return (
<div
className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"
data-testid="workflow-override-info"
>
{workflowProfile && (
<span className="flex items-center gap-1">
<AgentLogo agentName={workflowProfile.agent_name} size={14} className="shrink-0" />
<span>{workflowProfile.label}</span>
</span>
)}
{stepsWithOverrides.map((s) => (
<span key={s.name} className="flex items-center gap-1">
<span className="text-muted-foreground/50">{s.name}:</span>
<AgentLogo agentName={s.profile!.agent_name} size={14} className="shrink-0" />
<span>{s.profile!.label}</span>
</span>
))}
</div>
);
}
return (
<WorkflowSelectorRow
workflows={workflows}
snapshots={snapshots}
selectedWorkflowId={effectiveWorkflowId ?? null}
onWorkflowChange={handleWorkflowChange}
lastUsedWorkflowId={lastUsedWorkflowId}
agentProfiles={agentProfiles}
/>
);
});
export type DialogPromptSectionProps = {
isSessionMode: boolean;
isTaskStarted: boolean;
isPassthroughProfile: boolean;
initialDescription: string;
hasDescription: boolean;
fs: DialogFormState;
handleKeyDown: ReturnType<typeof useKeyboardShortcutHandler>;
enhance?: { onEnhance: () => void; isLoading: boolean; isConfigured: boolean };
workspaceId?: string | null;
onJiraImport?: (ticket: JiraTicket) => void;
};
export function DialogPromptSection({
isSessionMode,
isTaskStarted,
isPassthroughProfile,
initialDescription,
hasDescription,
fs,
handleKeyDown,
enhance,
workspaceId,
onJiraImport,
}: DialogPromptSectionProps) {
const showJiraImport = !isSessionMode && !isTaskStarted && !!onJiraImport;
return (
<>
<TaskFormInputs
key={fs.openCycle}
isSessionMode={isSessionMode}
autoFocus={!isTaskStarted}
initialDescription={initialDescription}
onDescriptionChange={fs.setHasDescription}
onKeyDown={handleKeyDown}
descriptionValueRef={fs.descriptionInputRef}
disabled={isTaskStarted || isPassthroughProfile}
placeholder={isPassthroughProfile ? "Passthrough mode — prompt not supported" : undefined}
onEnhancePrompt={enhance?.onEnhance}
isEnhancingPrompt={enhance?.isLoading}
isUtilityConfigured={enhance?.isConfigured}
jiraImport={
showJiraImport && onJiraImport
? {
workspaceId: workspaceId ?? null,
disabled: isPassthroughProfile,
onImport: onJiraImport,
}
: undefined
}
/>
{isPassthroughProfile && hasDescription && (
<p className="text-xs text-amber-500">Prompt ignored — passthrough mode active</p>
)}
</>
);
}