Files
kandev/apps/backend/internal/linear/models.go
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

138 lines
6.5 KiB
Go

// Package linear implements the Linear integration: a single install-wide
// configuration, a GraphQL client for issues and workflow states, and the HTTP
// and WebSocket handlers that expose these capabilities to the frontend.
package linear
import "time"
// AuthMethodAPIKey is the only auth method Linear supports today: a Personal
// API Key sent as the `Authorization` header (no Bearer prefix). The constant
// exists so the wire format mirrors the Jira integration's `authMethod` field
// and leaves room for OAuth in the future.
const AuthMethodAPIKey = "api_key"
// LinearConfig is the install-wide configuration for the Linear integration.
// The API key is stored separately in the encrypted secret store under
// SecretKey.
type LinearConfig struct {
AuthMethod string `json:"authMethod" db:"auth_method"`
DefaultTeamKey string `json:"defaultTeamKey" db:"default_team_key"`
HasSecret bool `json:"hasSecret" db:"-"`
// OrgSlug is captured from the most recent successful probe so the UI can
// build canonical issue URLs (linear.app/<slug>/issue/<id>) without an
// extra round-trip. Empty until the first probe succeeds.
OrgSlug string `json:"orgSlug,omitempty" db:"org_slug"`
// LastCheckedAt / LastOk / LastError are written by the background auth
// poller. They let the UI render a "connected/disconnected + checked Xs ago"
// indicator without doing its own probing.
LastCheckedAt *time.Time `json:"lastCheckedAt,omitempty" db:"last_checked_at"`
LastOk bool `json:"lastOk" db:"last_ok"`
LastError string `json:"lastError,omitempty" db:"last_error"`
CreatedAt time.Time `json:"createdAt" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
}
// SetConfigRequest is the payload sent by the UI to create or update the
// Linear configuration. When Secret is empty on update, the existing secret
// is retained; when non-empty it replaces the stored value.
type SetConfigRequest struct {
AuthMethod string `json:"authMethod"`
DefaultTeamKey string `json:"defaultTeamKey"`
Secret string `json:"secret"`
}
// TestConnectionResult reports what the backend learned when pinging Linear
// with the supplied credentials.
type TestConnectionResult struct {
OK bool `json:"ok"`
UserID string `json:"userId,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Email string `json:"email,omitempty"`
OrgSlug string `json:"orgSlug,omitempty"`
OrgName string `json:"orgName,omitempty"`
Error string `json:"error,omitempty"`
}
// LinearIssue is the subset of Linear's issue payload that Kandev consumes.
// Kept small intentionally: the UI needs enough to prefill a task, show the
// current state, and surface a few familiar fields (assignee, priority, team)
// in the popover.
type LinearIssue struct {
ID string `json:"id"`
Identifier string `json:"identifier"` // e.g. "ENG-123"
Title string `json:"title"`
Description string `json:"description"`
// State mirrors Jira's status tuple (id, name, category) so frontend code
// styling status pills can branch on Category without per-integration
// switches. Linear's StateType values map onto: backlog/unstarted → "new",
// started → "indeterminate", completed/canceled → "done".
StateID string `json:"stateId"`
StateName string `json:"stateName"`
StateType string `json:"stateType"` // backlog | unstarted | started | completed | canceled | triage
StateCategory string `json:"stateCategory"`
TeamID string `json:"teamId"`
TeamKey string `json:"teamKey"`
Priority int `json:"priority"` // 0=none, 1=urgent, 2=high, 3=med, 4=low
PriorityLabel string `json:"priorityLabel,omitempty"`
AssigneeName string `json:"assigneeName,omitempty"`
AssigneeEmail string `json:"assigneeEmail,omitempty"`
AssigneeIcon string `json:"assigneeIcon,omitempty"`
CreatorName string `json:"creatorName,omitempty"`
CreatorIcon string `json:"creatorIcon,omitempty"`
Updated string `json:"updated,omitempty"`
URL string `json:"url"`
States []LinearWorkflowState `json:"states"`
}
// LinearWorkflowState is one of the team workflow states an issue can be
// transitioned into. Unlike Jira transitions (which are edges), Linear states
// are nodes — to "transition" we set the issue's stateId to one of the team's
// states. State IDs are stable per team.
type LinearWorkflowState struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"` // backlog | unstarted | started | completed | canceled | triage
Color string `json:"color,omitempty"`
Position int `json:"position"`
}
// LinearTeam is the minimal shape used by the team selector on the settings
// page and by the issue browser to scope searches.
type LinearTeam struct {
ID string `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
}
// SearchFilter is a structured search filter used by SearchIssues. Linear has
// no JQL equivalent, so we expose a small set of structured fields that map
// cleanly to GraphQL filter inputs.
type SearchFilter struct {
Query string `json:"query,omitempty"` // free-text title/description/identifier match
TeamKey string `json:"teamKey,omitempty"` // restrict to one team
StateIDs []string `json:"stateIds,omitempty"` // restrict to specific workflow states
Assigned string `json:"assigned,omitempty"` // "me" | "unassigned" | "" (any)
}
// SearchResult is a page of issues from a search. Linear uses cursor-based
// pagination (endCursor + hasNextPage), which we expose here under the same
// shape as the Jira SearchResult so the frontend pagination component can be
// reused.
type SearchResult struct {
Issues []LinearIssue `json:"issues"`
MaxResults int `json:"maxResults"`
IsLast bool `json:"isLast"`
NextPageToken string `json:"nextPageToken,omitempty"`
}
// SecretKey is the secret-store key used for the install-wide Linear API key.
// Centralised so the service, store and provider migration agree.
const SecretKey = "linear:singleton:token"
// LegacySecretKeyForWorkspace returns the pre-singleton per-workspace secret
// key. Only used by the one-shot startup migration in provider.go to copy an
// existing token over to SecretKey.
func LegacySecretKeyForWorkspace(workspaceID string) string {
return "linear:" + workspaceID + ":token"
}