83e01477df
* refactor: extract shared shapes between jira and linear integrations Factors out the duplicated logic between internal/jira + internal/linear (backend) and components/jira + components/linear (frontend) into reusable shared shapes. Follow-up to PR #736. Backend: - New internal/integrations/secretadapter wraps secrets.SecretStore with the upsert API both jira.SecretStore and linear.SecretStore expect; drops both adapter copies from cmd/kandev/services.go. - New internal/integrations/healthpoll owns the 90s auth-health loop via a Prober interface; linear/poller.go is a thin wrapper, jira/poller.go keeps only its (jira-specific) issue-watch loop. - provideServices split into initGitHubService / initJiraService / initLinearService — now 75 lines (was ~125, exceeded the 80-line limit). Frontend: - New hooks/domains/integrations/use-integration-availability.ts and use-integration-enabled.ts; jira/linear hooks reduce to one-line delegates and move from components/<x>/ to hooks/domains/<x>/ per the project convention Greptile flagged on PR #736. - New components/integrations/{auth-status-banner,auth-error-message, validated-popover}.tsx; the four link/import-bar wrappers drop from ~110 lines to ~35 each, and JiraLinkButton picks up the clear-error-on-close behaviour LinearLinkButton already had. Docs: - New 'Adding a new third-party integration' section in CLAUDE.md/AGENTS.md documenting the shared shapes and intentional Jira/Linear divergence (transition vs state, JQL vs filter object, eventBus only on jira). * fix: address PR #759 review feedback - validated-popover: outline-with-label trigger now sets type="button" and honours triggerDisabled, matching ghost-icon (Greptile, Claude, CodeRabbit). - jira-link-button / linear-link-button: move updateTask() into the awaited fetch path so a failed title update surfaces as the popover's inline error instead of an unhandled rejection (CodeRabbit). - use-integration-availability: monotonic requestId race guard prevents a slow earlier probe from overwriting a newer auth result (CodeRabbit). - use-integration-enabled: drop unnecessary async on synchronous init (Claude). - jira/linear poller smoke tests: wrap in testing/synctest instead of time.After(2s) per backend testing convention (CodeRabbit nitpick). Skipped with reasoning on the threads: - secretadapter Set TOCTOU — single-process SQLite + single-writer per workspace; constraint violation on conflict surfaces as an error to the caller, not silent corruption. - healthpoll SetInterval validation — the function isn't called from production code today; a panic on misuse would be a footgun and silent ignore would just hide bugs differently. * fix: address PR #759 round-2 review feedback - jira-settings / linear-settings: drop the local STATUS_REFRESH_MS = 90_000 copies and import the shared INTEGRATION_STATUS_REFRESH_MS so changing the cadence only touches one file (Claude). - healthpoll: rename Poller.ProbeAll → probeAll. The only callers are the loop and the in-package tests, so widening the public API wasn't buying anything (Claude). * fix: invalidate ValidatedPopover in-flight submits on close If the user clicked Submit and dismissed the popover before the request settled, the next time they re-opened it would inherit `loading=true` (the disabled-while-loading submit button was stuck) and a late rejection from the previous session could repopulate `error` in the new one. Track the submit via a `useRef` token, bump it on close, and ignore any result/rejection whose token no longer matches. Also reset `loading` and `error` on close so the next open starts clean. Adds a regression test covering both the late-resolution and late-rejection paths. Addresses CodeRabbit review on PR #759. * ci: trigger workflow re-run GitHub Actions did not dispatch the pull_request workflows on the previous two pushes (1d869f0e,0ab6c034); only pull_request_target and CodeQL fired. Empty commit to nudge synchronize event. * fix: address PR #759 round-3 review feedback - jira.Poller.Stop: add nil-receiver guard so callers using the defer-Stop-after-NewPoller pattern don't panic when initJiraService returned nil (Greptile + Claude). Matches linear.Poller's guard. - healthpoll TestStart_RunsImmediateProbe + TestStart_IsIdempotent: rewrap in testing/synctest with synctest.Wait() instead of time.After(2s) wall-clock waits. Drops the now-unused probedAll signal channel from fakeProber (Claude). --------- Co-authored-by: Kandev Agent <agent@kandev.dev>
195 lines
6.4 KiB
TypeScript
195 lines
6.4 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useRef, useState, type ReactNode } from "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";
|
|
|
|
// ValidatedPopover is the shared trigger+popover+input+submit skeleton both
|
|
// integrations need for "paste a key/URL → fetch the entity → do something
|
|
// with it" flows (link a task, import a ticket/issue). It owns:
|
|
// - open/close + state reset on close
|
|
// - the keyed Input with autofocus + Enter-to-submit
|
|
// - validation against an integration-supplied regex
|
|
// - loading + error display
|
|
// - the disabled-while-empty / disabled-while-loading submit Button
|
|
//
|
|
// Each integration provides {icon, label, tooltip, placeholder, regex,
|
|
// fetch, onSuccess, validationHint, headline, submitLabel, submittingLabel}.
|
|
//
|
|
// Designing this as one shared skeleton both fixes the existing bug that
|
|
// JiraLinkButton was missing the clear-error-on-close behaviour LinearLinkButton
|
|
// had, and prevents future drift between the four near-identical popovers.
|
|
|
|
export type ValidatedPopoverTriggerStyle = "outline-with-label" | "ghost-icon";
|
|
|
|
export type ValidatedPopoverProps<T> = {
|
|
// Trigger button content + tooltip.
|
|
triggerStyle: ValidatedPopoverTriggerStyle;
|
|
triggerIcon: ReactNode;
|
|
triggerLabel?: string; // Required for "outline-with-label", ignored for "ghost-icon".
|
|
triggerAriaLabel?: string; // Used for "ghost-icon" since there's no visible label.
|
|
triggerDisabled?: boolean;
|
|
tooltip: string;
|
|
// PopoverContent layout.
|
|
align?: "start" | "end";
|
|
headline: string;
|
|
placeholder: string;
|
|
// Validation: extract a key from the user's input. Returning null shows the
|
|
// hint as an error. The hint typically reads "Paste a Jira ticket URL or
|
|
// key (PROJ-123)" or similar — integration-specific copy.
|
|
extractKey: (rawValue: string) => string | null;
|
|
validationHint: string;
|
|
// Async work to run after the user submits a valid key. The result is
|
|
// handed to onSuccess; throwing surfaces .message as the error string.
|
|
fetch: (key: string) => Promise<T>;
|
|
onSuccess: (key: string, result: T) => void;
|
|
// Submit button labels.
|
|
submitLabel: string; // e.g. "Link", "Import"
|
|
submittingLabel: string; // e.g. "Linking...", "Loading..."
|
|
};
|
|
|
|
function TriggerButton({
|
|
triggerStyle,
|
|
triggerIcon,
|
|
triggerLabel,
|
|
triggerAriaLabel,
|
|
triggerDisabled,
|
|
}: Pick<
|
|
ValidatedPopoverProps<unknown>,
|
|
"triggerStyle" | "triggerIcon" | "triggerLabel" | "triggerAriaLabel" | "triggerDisabled"
|
|
>) {
|
|
if (triggerStyle === "outline-with-label") {
|
|
return (
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={triggerDisabled}
|
|
className="cursor-pointer px-2 gap-1"
|
|
>
|
|
{triggerIcon}
|
|
<span className="text-xs font-medium">{triggerLabel}</span>
|
|
</Button>
|
|
);
|
|
}
|
|
return (
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
disabled={triggerDisabled}
|
|
aria-label={triggerAriaLabel}
|
|
className="h-7 w-7 cursor-pointer hover:bg-muted/40 text-slate-400"
|
|
>
|
|
{triggerIcon}
|
|
</Button>
|
|
);
|
|
}
|
|
|
|
export function ValidatedPopover<T>(props: ValidatedPopoverProps<T>) {
|
|
const {
|
|
tooltip,
|
|
align,
|
|
headline,
|
|
placeholder,
|
|
extractKey,
|
|
validationHint,
|
|
fetch,
|
|
onSuccess,
|
|
submitLabel,
|
|
submittingLabel,
|
|
} = props;
|
|
const [open, setOpen] = useState(false);
|
|
const [value, setValue] = useState("");
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
// Submission token: bumped on every submit and on close, so an in-flight
|
|
// request whose promise resolves after the popover was closed (or
|
|
// re-opened) cannot leak loading/error state into the next session.
|
|
const submissionRef = useRef(0);
|
|
|
|
const submit = useCallback(async () => {
|
|
const key = extractKey(value.trim());
|
|
if (!key) {
|
|
setError(validationHint);
|
|
return;
|
|
}
|
|
const submission = ++submissionRef.current;
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
const result = await fetch(key);
|
|
if (submission !== submissionRef.current) return;
|
|
onSuccess(key, result);
|
|
setOpen(false);
|
|
setValue("");
|
|
} catch (err) {
|
|
if (submission !== submissionRef.current) return;
|
|
setError(err instanceof Error ? err.message : String(err));
|
|
} finally {
|
|
if (submission === submissionRef.current) setLoading(false);
|
|
}
|
|
}, [value, extractKey, validationHint, fetch, onSuccess]);
|
|
|
|
// Closing invalidates any in-flight submit (so a late rejection can't
|
|
// re-populate `error` after the user dismissed the popover) and clears
|
|
// local submit state so the next open starts clean.
|
|
const handleOpenChange = (next: boolean) => {
|
|
setOpen(next);
|
|
if (!next) {
|
|
submissionRef.current += 1;
|
|
setLoading(false);
|
|
setError(null);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Popover open={open} onOpenChange={handleOpenChange}>
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<PopoverTrigger asChild>
|
|
<TriggerButton {...props} />
|
|
</PopoverTrigger>
|
|
</TooltipTrigger>
|
|
<TooltipContent>{tooltip}</TooltipContent>
|
|
</Tooltip>
|
|
<PopoverContent align={align ?? "end"} className="w-80 p-3">
|
|
<div className="space-y-2">
|
|
<div className="text-xs font-medium">{headline}</div>
|
|
<Input
|
|
autoFocus
|
|
value={value}
|
|
onChange={(e) => setValue(e.target.value)}
|
|
placeholder={placeholder}
|
|
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 ? submittingLabel : submitLabel}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</PopoverContent>
|
|
</Popover>
|
|
);
|
|
}
|