Files
kandev/apps/web/components/linear/linear-link-button.tsx
T
João Salavisa 7b5b3f329d feat: add Linear integration (#736)
* feat: add Linear integration

Mirrors the existing Jira integration so a workspace can connect to Linear
with a personal API key, browse and search issues, and start a Kandev task
from any issue. Backend uses Linear's GraphQL API with a workspace-scoped
config + secret store and a 90s auth-health poller; the frontend adds a
settings page, an issue dialog with state transitions, link/import buttons
in the task UI, and a paginated /linear browse page with a Start task flow.

* fix(linear): address PR review feedback

- Route httpListStates through Service.ListStates instead of clientFor
- Extract repeated workspace_id required string into a constant
- Log GetConfig errors during credential resolution instead of dropping them
- Clear popover error state on close in import + link buttons
- Pick the first workflow with steps in the quick task launcher (don't hard-pin to workflows[0])
- Reset useLinearEnabled state on workspace change via tag-based pattern
- Add cursor-pointer to anchor + Link elements per project convention
- Add tests: handlers_test.go, linear-api.test.ts, use-linear-enabled.test.ts, linear-issue-common.test.tsx
- Document internal/jira and internal/linear in CLAUDE.md/AGENTS.md

* fix(linear): address second-round PR review feedback

- Round Linear's fractional state position instead of truncating it via
  int(math.Round(s.Position)) so adjacent fractional positions don't collapse
- Force LinearSettings to remount on workspace change with key={id} so the
  previous workspace's config / form / testResult / teams cannot bleed into
  the next workspace before the new fetches settle
- Broaden the legacy-value useLinearEnabled test to cover "true", "1", "yes",
  and "legacy" so a regression to strict value === "true" would fail

* fix(linear): address third-round PR review feedback

- Propagate context.Canceled / context.DeadlineExceeded from ListStates in
  GetIssue instead of swallowing them — a caller cancellation must not return
  a partial-success response
- Drop the one-off contains() test helper in handlers_test.go and use
  strings.Contains directly so the assertion is self-documenting
- Add getLinearIssue URL-shape test that locks identifier-as-path-segment
  vs workspaceId-as-query-param so accidentally swapping them would fail

* test(linear): extract repeated literals in linear-api.test.ts

Pulls "ws-1", the API base URL, and the auth-method literal into module-
level constants so the assertions read as the route shape they care about
and the duplicate-strings ESLint rule (currently warn, threshold 4)
stays quiet as the file grows.

---------

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

118 lines
4.1 KiB
TypeScript

"use client";
import { useCallback, useState } from "react";
import { IconLink } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { toast } from "sonner";
import { getLinearIssue } from "@/lib/api/domains/linear-api";
import { updateTask } from "@/lib/api/domains/kanban-api";
import { LINEAR_KEY_RE } from "./linear-issue-common";
import { useLinearAvailable } from "./use-linear-availability";
type LinearLinkButtonProps = {
taskId: string | null | undefined;
workspaceId: string | null | undefined;
taskTitle: string | undefined | null;
};
// LinearLinkButton lets the user attach a Linear issue to an existing task by
// prepending the issue identifier to its title ("ENG-123: ..."). The
// LinearIssueButton picks up the identifier automatically once the title is
// updated.
export function LinearLinkButton({ taskId, workspaceId, taskTitle }: LinearLinkButtonProps) {
const available = useLinearAvailable(workspaceId);
const [open, setOpen] = useState(false);
const [value, setValue] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = useCallback(async () => {
if (!taskId || !workspaceId) return;
const match = value.toUpperCase().match(LINEAR_KEY_RE);
if (!match) {
setError("Paste a Linear issue URL or identifier (ENG-123)");
return;
}
const key = match[0];
setLoading(true);
setError(null);
try {
await getLinearIssue(workspaceId, key);
// Strip any existing leading "ENG-123: " so re-linking replaces the
// prefix instead of stacking it.
const stripped = (taskTitle ?? "").trim().replace(/^[A-Z][A-Z0-9]*-\d+:\s*/, "");
const newTitle = stripped ? `${key}: ${stripped}` : key;
await updateTask(taskId, { title: newTitle });
toast.success(`Linked to ${key}`);
setOpen(false);
setValue("");
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}, [taskId, workspaceId, value, taskTitle]);
if (!available || !taskId || !workspaceId) return null;
// Closing the popover discards any stale validation/error so reopening
// starts clean.
const handleOpenChange = (next: boolean) => {
setOpen(next);
if (!next) setError(null);
};
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<Tooltip>
<TooltipTrigger asChild>
<PopoverTrigger asChild>
<Button size="sm" variant="outline" className="cursor-pointer px-2 gap-1">
<IconLink className="h-4 w-4" />
<span className="text-xs font-medium">Link Linear</span>
</Button>
</PopoverTrigger>
</TooltipTrigger>
<TooltipContent>Link this task to a Linear issue</TooltipContent>
</Tooltip>
<PopoverContent align="end" className="w-80 p-3">
<div className="space-y-2">
<div className="text-xs font-medium">Link to Linear issue</div>
<Input
autoFocus
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="ENG-123 or paste issue URL"
className="h-8 text-xs"
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void submit();
}
}}
/>
{error && (
<p className="text-[11px] text-destructive" role="alert">
{error}
</p>
)}
<div className="flex justify-end">
<Button
type="button"
size="sm"
onClick={() => void submit()}
disabled={loading || !value.trim()}
className="h-7 cursor-pointer"
>
{loading ? "Linking..." : "Link"}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
);
}