Files
kandev/apps/web/components/linear/linear-settings.tsx
T
João Salavisa bb36cb9e01 refactor: move integrations to top-level settings with install-wide configs (#787)
* refactor: move integrations to top-level settings with install-wide configs

Jira and Linear configurations are now install-wide singletons rather than
per-workspace duplicates, and the GitHub/Jira/Linear settings pages live
under /settings/integrations instead of being nested inside each workspace.
Issue and PR watchers stay per-workspace via a workspace switcher inside
each integration page. Backend ships one-shot migrations that promote the
most-recently-updated row and copy its secret onto the new global key.

* fix: address review feedback on integrations refactor

Fix migration crash on installs whose jira_configs predate the auth-health
columns by selecting only guaranteed-present legacy columns and falling back
to defaults for the rest. Cover the empty-legacy-table and pre-health-columns
upgrade paths with new store tests.

On the frontend, refactor useIntegrationEnabled to take string parameters
instead of an inline options object so getSnapshot stays referentially stable
across renders, and stop dispatching a misleading no-op sync event when
localStorage.setItem fails in private mode.

* fix: hydrate workspace list on integration settings pages

The integration pages wrapped their content in a fresh StateProvider, which
created a nested store scope with an empty initial state and shadowed the
settings layout's hydrated workspace list. WorkspaceScopedSection then saw
zero workspaces and rendered the "Create a workspace to configure this
integration" empty state even when the user had workspaces.

Drop the redundant StateProvider from the jira and linear pages so they share
the layout's store. The github page switches to StateHydrator so it can still
seed the GitHub OAuth status without resetting the rest of the store.

* refactor(integrations): flatten watcher tables, pick workspace in create dialog

Hiding watchers behind a workspace switcher made the list invisible at a
glance — a user with multiple workspaces had to flip between each one to
see what was configured. Replace the switcher with a flat table that lists
every watch across every workspace, with a Workspace column for context, and
move workspace selection into the create dialog so the user picks once when
the watcher is born.

Backend: jira list-issue-watches and github list-review-watches /
list-issue-watches accept the workspace_id query param as optional; when
omitted, the corresponding store ListAll* method returns rows across every
workspace. Per-row mutations still require workspace_id as the IDOR guard.

Frontend: useReviewWatches / useIssueWatches / useJiraIssueWatches gain a
three-state contract — string for one workspace, undefined for all
workspaces, null to skip fetching. Watch tables grow an optional
showWorkspace column. Watch dialogs accept an optional workspaceId prop;
when absent, the dialog renders a workspace dropdown for the create flow
(disabled when editing existing rows so refs aren't orphaned). Github
review-watch-dialog crossed the 600-line lint cap so the prompt editor
moved to review-watch-prompt-field.tsx.

* fix(integrations): make watcher step dropdown reactive across workspace switches

Switching to a workspace whose workflows had to be fetched left the workflow
step dropdown stuck — the user could pick a workflow but the step Select
either showed the previous workflow's steps or appeared inert. The cause was
the per-dialog useWorkflowSteps hook deferring its empty-state reset via
Promise.resolve().then(() => setSteps([])) to dodge a setState-in-effect
lint rule, which let stale steps survive into the next render and gave Radix
nothing to anchor the popover to during the in-flight fetch.

Hoist the hook into a shared useWorkflowSteps that resets via React's
official setState-during-render pattern, exposes a loading flag, and returns
a stepPlaceholder helper so the Select can render "Loading steps…" or "No
steps in this workflow" instead of an empty popover. The Step Select is now
also disabled while loading or when there are no steps, making the state of
the dropdown unambiguous.

* fix: address PR review feedback on integrations refactor

Backend:
- linear migration: add column-presence guard mirroring the Jira fix so
  installs that upgraded from the original Linear schema (without org_slug
  / last_checked_at / last_ok / last_error) don't crash startup with
  "no such column"; add TestStore_MigrateLegacyPerWorkspaceTable_PreHealthColumns
- jira/handlers.go: drop the now-unused errMsgWorkspaceIDRequired constant
  that was failing golangci-lint
- jira/mock_controller_test.go (new): cover setAuthHealth happy-path and
  invalid-JSON-rejection so the singleton-shaped payload is locked in

Frontend:
- useIntegrationAvailable: gate the auth-health probe on loaded && enabled
  so disabled integrations don't poll /config every 90s
- use-workflow-steps: initialize loading to !!workflowId so edit-mode opens
  show "Loading steps…" instead of "No steps in this workflow" before the
  first fetch lands
- use-workflow-steps.test.ts (new): cover the empty/non-empty workflowId,
  workflow switch, fetch error, and stepPlaceholder branches
- use-linear-enabled.test: tighten the legacy-key migration assertion to
  pin the migrated value rather than just verifying key cleanup

---------

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

438 lines
13 KiB
TypeScript

"use client";
import { useCallback, useEffect, useState } from "react";
import { IconHexagon } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Card, CardContent } from "@kandev/ui/card";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { Separator } from "@kandev/ui/separator";
import { Alert, AlertDescription } from "@kandev/ui/alert";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { Switch } from "@kandev/ui/switch";
import { useToast } from "@/components/toast-provider";
import { SettingsSection } from "@/components/settings/settings-section";
import { useLinearEnabled } from "@/hooks/domains/linear/use-linear-enabled";
import {
IntegrationAuthStatusBanner,
type IntegrationAuthHealth,
} from "@/components/integrations/auth-status-banner";
import { INTEGRATION_STATUS_REFRESH_MS } from "@/hooks/domains/integrations/use-integration-availability";
import {
getLinearConfig,
setLinearConfig,
deleteLinearConfig,
testLinearConnection,
listLinearTeams,
} from "@/lib/api/domains/linear-api";
import type { LinearConfig, LinearTeam, TestLinearConnectionResult } from "@/lib/types/linear";
type FormState = {
defaultTeamKey: string;
secret: string;
};
const emptyForm: FormState = { defaultTeamKey: "", secret: "" };
function configToForm(cfg: LinearConfig | null): FormState {
if (!cfg) return emptyForm;
return { defaultTeamKey: cfg.defaultTeamKey, secret: "" };
}
function saveLabel(saving: boolean, hasConfig: boolean): string {
if (saving) return "Saving...";
return hasConfig ? "Update" : "Save";
}
type FieldsRowProps = {
form: FormState;
loading: boolean;
update: <K extends keyof FormState>(key: K, value: FormState[K]) => void;
hasSavedSecret: boolean;
teams: LinearTeam[];
loadingTeams: boolean;
};
function SecretField({
form,
loading,
update,
hasSavedSecret,
}: Omit<FieldsRowProps, "teams" | "loadingTeams">) {
return (
<div className="space-y-1.5">
<Label htmlFor="linear-secret">
API key
{hasSavedSecret && (
<span className="text-xs text-muted-foreground ml-2">
(saved — leave blank to keep the current value)
</span>
)}
</Label>
<Input
id="linear-secret"
data-testid="linear-secret-input"
type="password"
placeholder={hasSavedSecret ? "••••••••" : "lin_api_..."}
value={form.secret}
onChange={(e) => update("secret", e.target.value)}
disabled={loading}
/>
<p className="text-xs text-muted-foreground">
Create a personal API key at{" "}
<a
className="underline cursor-pointer"
href="https://linear.app/settings/account/security"
target="_blank"
rel="noreferrer"
>
linear.app/settings/account/security
</a>
</p>
</div>
);
}
function TeamSelector({ form, loading, update, teams, loadingTeams }: FieldsRowProps) {
return (
<div className="space-y-1.5">
<Label htmlFor="linear-team">Default team (optional)</Label>
<Select
value={form.defaultTeamKey || "__none__"}
onValueChange={(v) => update("defaultTeamKey", v === "__none__" ? "" : v)}
disabled={loading || loadingTeams}
>
<SelectTrigger id="linear-team" className="w-full">
<SelectValue placeholder={loadingTeams ? "Loading teams…" : "Choose a team"} />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">No default</SelectItem>
{teams.map((t) => (
<SelectItem key={t.id} value={t.key}>
{t.name} ({t.key})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
}
function TestResultAlert({ result }: { result: TestLinearConnectionResult | null }) {
if (!result) return null;
return (
<Alert variant={result.ok ? "default" : "destructive"}>
<AlertDescription>
{result.ok
? `Connected as ${result.displayName || result.email || result.userId}${result.orgName ? ` (${result.orgName})` : ""}`
: `Failed: ${result.error}`}
</AlertDescription>
</Alert>
);
}
function configToHealth(config: LinearConfig | null): IntegrationAuthHealth | null {
if (!config?.hasSecret) return null;
if (!config.lastCheckedAt) return { ok: false, error: "", checkedAt: null };
return {
ok: !!config.lastOk,
error: config.lastError ?? "",
checkedAt: new Date(config.lastCheckedAt),
};
}
type ActionBarProps = {
saving: boolean;
testing: boolean;
loading: boolean;
hasConfig: boolean;
disableSave: boolean;
disableTest: boolean;
onTest: () => void;
onSave: () => void;
onDelete: () => void;
};
function ActionBar({
saving,
testing,
loading,
hasConfig,
disableSave,
disableTest,
onTest,
onSave,
onDelete,
}: ActionBarProps) {
return (
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
onClick={onTest}
disabled={testing || loading || disableTest}
className="cursor-pointer"
title={disableTest ? "Paste an API key to test the connection" : undefined}
data-testid="linear-test-button"
>
{testing ? "Testing..." : "Test connection"}
</Button>
<Button
type="button"
onClick={onSave}
disabled={disableSave}
className="cursor-pointer"
data-testid="linear-save-button"
>
{saveLabel(saving, hasConfig)}
</Button>
{hasConfig && (
<Button
type="button"
variant="destructive"
onClick={onDelete}
className="ml-auto cursor-pointer"
data-testid="linear-delete-button"
>
Remove configuration
</Button>
)}
</div>
);
}
type SettingsActionsArgs = {
form: FormState;
setConfig: (cfg: LinearConfig | null) => void;
setForm: (form: FormState) => void;
setTestResult: (r: TestLinearConnectionResult | null) => void;
};
function useSettingsActions({ form, setConfig, setForm, setTestResult }: SettingsActionsArgs) {
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const handleTest = useCallback(async () => {
setTesting(true);
setTestResult(null);
try {
const res = await testLinearConnection({
authMethod: "api_key",
secret: form.secret || undefined,
});
setTestResult(res);
} catch (err) {
setTestResult({ ok: false, error: String(err) });
} finally {
setTesting(false);
}
}, [form, setTestResult]);
const handleSave = useCallback(async () => {
setSaving(true);
try {
const saved = await setLinearConfig({
authMethod: "api_key",
defaultTeamKey: form.defaultTeamKey,
secret: form.secret || undefined,
});
setConfig(saved);
setForm(configToForm(saved));
setTestResult(null);
toast({ description: "Linear configuration saved", variant: "success" });
} catch (err) {
toast({ description: `Save failed: ${String(err)}`, variant: "error" });
} finally {
setSaving(false);
}
}, [form, toast, setConfig, setForm, setTestResult]);
const handleDelete = useCallback(async () => {
if (!confirm("Remove Linear configuration?")) return;
try {
await deleteLinearConfig();
setConfig(null);
setForm(emptyForm);
setTestResult(null);
toast({ description: "Linear configuration removed", variant: "success" });
} catch (err) {
toast({ description: `Delete failed: ${String(err)}`, variant: "error" });
}
}, [toast, setConfig, setForm, setTestResult]);
return { saving, testing, handleTest, handleSave, handleDelete };
}
function useTeamsLoader(hasSecret: boolean | undefined, lastOk: boolean | undefined) {
// `teams === null` means "no fetch attempt yet", so the dropdown can show a
// "Loading…" placeholder without us calling setState synchronously inside
// the effect (which the lint rule forbids). Once a fetch settles we always
// store an array, even if empty.
const [teams, setTeams] = useState<LinearTeam[] | null>(null);
// Fetch teams once a working configuration exists. Skips when there's no
// saved secret (the API call would 503). Stale teams from a previous save
// remain visible after deletion, but the dropdown is gated on hasSecret so
// the user never sees them.
useEffect(() => {
if (!hasSecret) return;
let cancelled = false;
listLinearTeams()
.then((res) => {
if (!cancelled) setTeams(res.teams ?? []);
})
.catch(() => {
if (!cancelled) setTeams([]);
});
return () => {
cancelled = true;
};
}, [hasSecret, lastOk]);
return { teams: teams ?? [], loadingTeams: teams === null && !!hasSecret };
}
function useLinearSettings() {
const { toast } = useToast();
const [config, setConfig] = useState<LinearConfig | null>(null);
const [form, setForm] = useState<FormState>(emptyForm);
const [loading, setLoading] = useState(true);
const [testResult, setTestResult] = useState<TestLinearConnectionResult | null>(null);
const health = configToHealth(config);
const { teams, loadingTeams } = useTeamsLoader(config?.hasSecret, config?.lastOk);
const load = useCallback(async () => {
setLoading(true);
try {
const cfg = await getLinearConfig();
setConfig(cfg);
setForm(configToForm(cfg));
} catch (err) {
toast({ description: `Failed to load Linear config: ${String(err)}`, variant: "error" });
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
}, [load]);
// Background refresh so the auth-health banner picks up new probe results.
useEffect(() => {
const id = setInterval(() => {
getLinearConfig()
.then((cfg) => setConfig(cfg))
.catch(() => {
/* transient failures are fine — next tick retries */
});
}, INTEGRATION_STATUS_REFRESH_MS);
return () => clearInterval(id);
}, []);
const update = useCallback(
<K extends keyof FormState>(key: K, value: FormState[K]) =>
setForm((prev) => ({ ...prev, [key]: value })),
[],
);
const { saving, testing, handleTest, handleSave, handleDelete } = useSettingsActions({
form,
setConfig,
setForm,
setTestResult,
});
return {
config,
form,
loading,
saving,
testing,
testResult,
health,
teams,
loadingTeams,
update,
handleTest,
handleSave,
handleDelete,
};
}
function EnabledPill() {
const { enabled, setEnabled } = useLinearEnabled();
return (
<div className="flex items-center gap-2 rounded-full border bg-muted/30 px-3 py-1">
<Switch
id="linear-enabled"
checked={enabled}
onCheckedChange={setEnabled}
className="cursor-pointer"
/>
<Label htmlFor="linear-enabled" className="text-xs cursor-pointer">
{enabled ? "Enabled" : "Disabled"}
</Label>
</div>
);
}
// LinearConnectionSection holds the install-wide credentials form. Linear has
// no per-workspace state to surface here today, so the page composes only this
// section.
export function LinearConnectionSection() {
const s = useLinearSettings();
const missingSecret = !s.config?.hasSecret && !s.form.secret;
const disableSave = s.saving || missingSecret;
const disableTest = missingSecret;
return (
<SettingsSection
icon={<IconHexagon className="h-5 w-5" />}
title="Linear integration"
description="Connect Kandev to Linear with a personal API key. Credentials are stored encrypted server-side and shared across all workspaces."
action={<EnabledPill />}
>
<Card>
<CardContent className="space-y-4 pt-6">
<IntegrationAuthStatusBanner health={s.health} />
<SecretField
form={s.form}
loading={s.loading}
update={s.update}
hasSavedSecret={!!s.config?.hasSecret}
/>
<TeamSelector
form={s.form}
loading={s.loading}
update={s.update}
hasSavedSecret={!!s.config?.hasSecret}
teams={s.teams}
loadingTeams={s.loadingTeams}
/>
<TestResultAlert result={s.testResult} />
<Separator />
<ActionBar
saving={s.saving}
testing={s.testing}
loading={s.loading}
hasConfig={!!s.config}
disableSave={disableSave}
disableTest={disableTest}
onTest={s.handleTest}
onSave={s.handleSave}
onDelete={s.handleDelete}
/>
</CardContent>
</Card>
</SettingsSection>
);
}
export function LinearIntegrationPage() {
return (
<div className="space-y-8">
<LinearConnectionSection />
</div>
);
}