Files
kandev/apps/backend/internal/linear/service.go
T
Nicolas Lenepveu e740417885 feat(linear): enrich issue watch filters with priority, labels, creator, estimate (#974)
* feat(linear): enrich issue watch filters with priority, labels, creator, estimate

Adds priority, labels (multi-select), creator (team member select), and
estimate range filters to Linear issue watchers — closing the gap with
Linear's GraphQL filter surface so users can scope auto-run watchers
nearly as tightly as they would in Linear itself.

- Backend: extend SearchFilter, map new fields to IssueFilter, add
  ListLabels / ListUsers on the Client interface, expose them over HTTP
  (GET /api/v1/linear/labels, /users) and via SearchIssues query params.
- Frontend: extend LinearSearchFilter, fetch labels + users per team,
  render new filter controls in the watcher dialog, and split helpers
  into linear-issue-watch-form.ts + linear-issue-watch-fields.tsx so
  the dialog stays under file/function size limits.

* fix(linear): address reviewer feedback on enriched filter PR

- Reject invalid priority / malformed estimate query params with 400 instead
  of silently dropping them; reject estimateMin > estimateMax. Mirror the
  bounds check in the issue-watch validator so JSON-encoded watches go
  through the same gate.
- A11y: render label/state toggle Badges inside <button aria-pressed> so
  keyboard users can navigate and screen readers can announce state.
- Recover from per-team fetch failures so a transient network blip doesn't
  permanently mark a team as "fetched-empty" — clear the in-flight marker
  when any of states/labels/users fail, allowing remount to retry.
- Tighten priority typing: LinearSearchFilter.priority is 0|1|2|3|4, and
  LinearPriority is the source of truth on the form-state side. Promote
  FormState from a type alias to an interface per repo convention.

* fix(linear): align update error message and clear fetchedTeams on cancel

- UpdateIssueWatch's filter-empty error still listed only the original
  four fields; bring it in line with the create path so the message
  matches what filterIsEmpty actually accepts.
- linear-issue-watch-fields: clear the fetchedTeams marker on effect
  cancellation as well as failure, so a remount after a fast teamKey
  switch can retry instead of being stuck with whatever partial cache
  the prior effect produced.

* fix(linear): address PR #974 reviewer findings

- linear-issue-watch-fields: delete the fetchedTeams marker on effect
  cleanup so rapid team switches (A → B → A) refetch on return instead
  of being stranded mid-load. Capture the Set in a local so the cleanup
  closure references the exact instance the effect body added to.
- graphql_client: raise the labels/users page cap from 100 to Linear's
  max of 250 via a shared linearMaxPageSize constant and a $first
  variable. Documented that a workspace exceeding that would need
  cursor-pagination here AND lazy-load in the UI.
- service_issue_watch.validateFilterBounds + handlers parseSearchNumeric
  Filters: reject negative estimate values — Linear story points are
  non-negative, so a -1 would silently match nothing.

* fix(linear): collapse duplicate hint text on States/Labels rows

When no team was selected the row showed two stacked muted lines —
the field description and the multi-select's "Pick a team…" prose —
saying overlapping things. Swap the row description based on team
selection and let the multi-select render nothing when disabled, so
exactly one line is shown in either state.

Also tightens the new fields' descriptions to match the brevity of
the existing ones (Labels, Estimate min/max).

* fix(linear): reject NaN/Inf estimates and preserve team cache after success

CodeRabbit + cubic flagged two real issues in the previous round:

- strconv.ParseFloat accepts "NaN" / "+Inf" / "-Inf" without erroring,
  and "f < 0" passes through for NaN. Without an explicit math.IsNaN /
  math.IsInf guard those values would propagate into the GraphQL
  request and the eventual json.Marshal would 500 instead of 400.
  Add the guard for both estimate_min and estimate_max, with a
  regression test covering NaN, ±Inf, negative, and inverted range.

- useTeamsAndStates was deleting the per-team cache marker on every
  cleanup, so a normal team switch evicted a healthy cache and the
  next visit re-fetched all three datasets. Track a "loaded" flag and
  only evict on cleanup when the fetch didn't complete successfully.

Also extracts the duplicated "team_key" / "team_key required" wire
strings into package-level constants per the repo's
"3+ occurrences → constant" convention.

* test(linear): add handler tests for /labels and /users endpoints

Mirrors the existing TestHTTPListStates_* pair — required team_key
returns 400, and a happy path that asserts the team_key reaches the
client and the response is 200. Closes the coverage gap CodeRabbit
flagged on the two new endpoints introduced in this PR.

* feat(linear): make priority filter multi-select

Status and label filters are already multi-select; priority being a
single Select broke the symmetry and forced single-value thinking.
Linear's own filter UI is multi-select per priority, and the GraphQL
filter takes priority: { in: [...] } natively, so the wire change is
clean.

Backend
- SearchFilter.Priority *int → Priorities []int
- buildIssueFilter emits priority: { in: priorities } when non-empty
- validateFilterBounds checks each element ∈ [0,4]
- normalizeFilter de-dupes (preserves caller order)
- HTTP query param priority → priorities, parsed as CSV
- Tests updated, including priority=0 still expressible as
  Priorities=[0] (matches "No priority" issues only)

Frontend
- LinearSearchFilter.priority → priorities: LinearPriority[]
- FormState.priority → priorities
- PRIORITY_OPTIONS dropped the (any) sentinel; "No priority" sits at
  the end of the chip row
- PriorityMultiSelect added next to State/Label multi-selects
- Priority moved to its own full-width row matching States/Labels;
  Creator promoted to a stand-alone CreatorRow

Refactor
- searchLinearIssues query-param building extracted to a flat
  table-driven helper to keep cyclomatic complexity ≤ 15

* refactor(linear): regroup watcher dialog fields and add section separators

UX pass on the watcher dialog:

- Pulled Team out into its own full-width row and paired Assignee +
  Creator in a 2-col row so the people filters sit together — the old
  Team+Assignee pairing forced a context switch between scope and
  people filters mid-form.
- Added hairlines between the four conceptual blocks (Destination /
  Filter / Automation / Prompt / Settings). Each block answers a
  different question, so a consistent rhythm helps users scan the form
  by section instead of reading one long stack.

No behaviour change; pure layout.

* refactor(linear): use shared Separator for watcher dialog section breaks

Initially extracted a local SectionDivider, but @kandev/ui/separator
(Radix-based, shadcn) already exists and is used in 14 places across
the codebase — including the sibling Jira settings page. Use that
instead so the styling tracks the rest of the app.

* refactor(linear): split parseSearchNumericFilters to satisfy cyclop

Extract priority and estimate-bound parsing into helpers so the entry
point drops below the project's max cyclomatic complexity (15).

* fix(linear): reject non-finite/negative estimates and align fmt

- validateFilterBounds rejects NaN/+-Inf in addition to negatives, so a
  watch config can't be persisted with values that would later crash
  json.Marshal. Adds focused unit tests.
- parseEstimate on the frontend treats negatives as unset so the UI
  cannot submit estimateMin/Max < 0.
- gofmt-only alignment tweak in handlers_test.go test table.
2026-05-22 10:42:42 +01:00

349 lines
10 KiB
Go

package linear
import (
"context"
"errors"
"fmt"
"sync"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/events/bus"
)
// SecretStore is the subset of the secrets store the service needs.
type SecretStore interface {
Reveal(ctx context.Context, id string) (string, error)
Set(ctx context.Context, id, name, value string) error
Delete(ctx context.Context, id string) error
Exists(ctx context.Context, id string) (bool, error)
}
// Service orchestrates Linear config storage, the cached client, and the
// fetch/transition operations used by the WebSocket + HTTP handlers.
type Service struct {
store *Store
secrets SecretStore
log *logger.Logger
mu sync.Mutex
clientFn ClientFactory
client Client // singleton, cleared on config change.
probeHook func()
eventBus bus.EventBus
// mockClient is non-nil only when Provide built the service with a MockClient
// (KANDEV_MOCK_LINEAR=true). Exposed via MockClient() so the e2e control
// routes can drive the same instance the clientFn returns.
mockClient *MockClient
}
// MockClient returns the shared mock client when the service was built in mock
// mode, or nil for production builds.
func (s *Service) MockClient() *MockClient {
return s.mockClient
}
// ClientFactory builds a Client for the given config + secret. Overridable so
// tests can inject fakes without touching HTTP.
type ClientFactory func(cfg *LinearConfig, secret string) Client
// DefaultClientFactory returns a real GraphQLClient.
func DefaultClientFactory(cfg *LinearConfig, secret string) Client {
return NewGraphQLClient(cfg, secret)
}
// NewService wires the service. Pass nil for clientFn to use the default.
func NewService(store *Store, secrets SecretStore, clientFn ClientFactory, log *logger.Logger) *Service {
if clientFn == nil {
clientFn = DefaultClientFactory
}
return &Service{
store: store,
secrets: secrets,
log: log,
clientFn: clientFn,
}
}
// GetConfig returns the singleton config enriched with a HasSecret flag.
func (s *Service) GetConfig(ctx context.Context) (*LinearConfig, error) {
cfg, err := s.store.GetConfig(ctx)
if err != nil || cfg == nil {
return cfg, err
}
if s.secrets == nil {
return cfg, nil
}
exists, existsErr := s.secrets.Exists(ctx, SecretKey)
if existsErr != nil {
s.log.Warn("linear: secret exists check failed", zap.Error(existsErr))
}
cfg.HasSecret = exists
return cfg, nil
}
// ErrInvalidConfig is returned by SetConfig when the request fails validation.
var ErrInvalidConfig = errors.New("linear: invalid configuration")
// SetConfig is upsert. An empty Secret on update keeps the existing token.
func (s *Service) SetConfig(ctx context.Context, req *SetConfigRequest) (*LinearConfig, error) {
if err := validateConfigRequest(req); err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidConfig, err.Error())
}
cfg := &LinearConfig{
AuthMethod: req.AuthMethod,
DefaultTeamKey: req.DefaultTeamKey,
}
if err := s.store.UpsertConfig(ctx, cfg); err != nil {
return nil, fmt.Errorf("upsert linear config: %w", err)
}
if req.Secret != "" && s.secrets != nil {
if err := s.secrets.Set(ctx, SecretKey, "Linear API key", req.Secret); err != nil {
return nil, fmt.Errorf("store linear secret: %w", err)
}
}
s.invalidateClient()
// Probe asynchronously so a slow Linear doesn't stall the save response.
go func() {
s.RecordAuthHealth(context.Background())
}()
return s.GetConfig(ctx)
}
// DeleteConfig removes both the config row and the stored secret.
func (s *Service) DeleteConfig(ctx context.Context) error {
if err := s.store.DeleteConfig(ctx); err != nil {
return err
}
if s.secrets != nil {
if err := s.secrets.Delete(ctx, SecretKey); err != nil {
s.log.Warn("linear: secret delete failed", zap.Error(err))
}
}
s.invalidateClient()
return nil
}
// TestConnection validates credentials either from a fresh SetConfigRequest
// (before persisting) or from the stored config (after saving).
func (s *Service) TestConnection(ctx context.Context, req *SetConfigRequest) (*TestConnectionResult, error) {
cfg, secret, err := s.resolveCredentials(ctx, req)
if err != nil {
return &TestConnectionResult{OK: false, Error: err.Error()}, nil
}
client := s.clientFn(cfg, secret)
return client.TestAuth(ctx)
}
// ProbeAuth validates the stored credentials.
func (s *Service) ProbeAuth(ctx context.Context) (*TestConnectionResult, error) {
client, err := s.clientFor(ctx)
if err != nil {
return &TestConnectionResult{OK: false, Error: err.Error()}, nil
}
return client.TestAuth(ctx)
}
// Store exposes the underlying store so background workers can persist state.
func (s *Service) Store() *Store {
return s.store
}
// authProbeTimeout caps a single auth-health probe.
const authProbeTimeout = 15 * time.Second
// authHealthWriteTimeout bounds the DB write that persists the probe outcome.
const authHealthWriteTimeout = 5 * time.Second
// SetProbeHook installs a callback fired at the end of each RecordAuthHealth
// call. Production code never sets this; tests use it to synchronise on probe
// completion without sleep-polling.
func (s *Service) SetProbeHook(fn func()) {
s.mu.Lock()
defer s.mu.Unlock()
s.probeHook = fn
}
// RecordAuthHealth probes credentials and writes the outcome onto the row.
func (s *Service) RecordAuthHealth(ctx context.Context) {
probeCtx, cancel := context.WithTimeout(ctx, authProbeTimeout)
defer cancel()
res, err := s.ProbeAuth(probeCtx)
ok := err == nil && res != nil && res.OK
errMsg := ""
switch {
case err != nil:
errMsg = err.Error()
case res != nil && !res.OK:
errMsg = res.Error
}
orgSlug := ""
if res != nil && ok {
orgSlug = res.OrgSlug
}
// Detach the DB write from ctx so a probe that exhausted its deadline can
// still record the failure.
writeCtx, writeCancel := context.WithTimeout(context.Background(), authHealthWriteTimeout)
defer writeCancel()
if updateErr := s.store.UpdateAuthHealth(writeCtx, ok, errMsg, orgSlug, time.Now().UTC()); updateErr != nil {
s.log.Warn("linear: update auth health failed", zap.Error(updateErr))
}
s.mu.Lock()
hook := s.probeHook
s.mu.Unlock()
if hook != nil {
hook()
}
}
// GetIssue loads a Linear issue by identifier (e.g. "ENG-123").
func (s *Service) GetIssue(ctx context.Context, identifier string) (*LinearIssue, error) {
client, err := s.clientFor(ctx)
if err != nil {
return nil, err
}
return client.GetIssue(ctx, identifier)
}
// SetIssueState moves an issue into the requested workflow state.
func (s *Service) SetIssueState(ctx context.Context, issueID, stateID string) error {
client, err := s.clientFor(ctx)
if err != nil {
return err
}
return client.SetIssueState(ctx, issueID, stateID)
}
// ListTeams populates the team selector on the settings page.
func (s *Service) ListTeams(ctx context.Context) ([]LinearTeam, error) {
client, err := s.clientFor(ctx)
if err != nil {
return nil, err
}
return client.ListTeams(ctx)
}
// ListStates returns the workflow states for a team identified by its key.
func (s *Service) ListStates(ctx context.Context, teamKey string) ([]LinearWorkflowState, error) {
client, err := s.clientFor(ctx)
if err != nil {
return nil, err
}
return client.ListStates(ctx, teamKey)
}
// ListLabels returns the issue labels for a team identified by its key.
func (s *Service) ListLabels(ctx context.Context, teamKey string) ([]LinearLabel, error) {
client, err := s.clientFor(ctx)
if err != nil {
return nil, err
}
return client.ListLabels(ctx, teamKey)
}
// ListUsers returns the members of a team identified by its key. Used to
// populate creator / assignee selectors on the watcher filter UI.
func (s *Service) ListUsers(ctx context.Context, teamKey string) ([]LinearUser, error) {
client, err := s.clientFor(ctx)
if err != nil {
return nil, err
}
return client.ListUsers(ctx, teamKey)
}
// SearchIssues runs a filtered search.
func (s *Service) SearchIssues(ctx context.Context, filter SearchFilter, pageToken string, maxResults int) (*SearchResult, error) {
client, err := s.clientFor(ctx)
if err != nil {
return nil, err
}
return client.SearchIssues(ctx, filter, pageToken, maxResults)
}
// clientFor returns the cached client, creating it if needed.
func (s *Service) clientFor(ctx context.Context) (Client, error) {
s.mu.Lock()
if s.client != nil {
c := s.client
s.mu.Unlock()
return c, nil
}
s.mu.Unlock()
cfg, err := s.store.GetConfig(ctx)
if err != nil {
return nil, err
}
if cfg == nil {
return nil, ErrNotConfigured
}
secret := ""
if s.secrets != nil {
secret, err = s.secrets.Reveal(ctx, SecretKey)
if err != nil {
return nil, fmt.Errorf("read linear secret: %w", err)
}
if secret == "" {
return nil, ErrNotConfigured
}
}
client := s.clientFn(cfg, secret)
s.mu.Lock()
defer s.mu.Unlock()
if s.client != nil {
return s.client, nil
}
s.client = client
return client, nil
}
// invalidateClient drops the cached client so the next request rebuilds it.
func (s *Service) invalidateClient() {
s.mu.Lock()
s.client = nil
s.mu.Unlock()
}
// resolveCredentials picks credentials for a test: inline if the request
// carries a secret, otherwise the stored secret.
func (s *Service) resolveCredentials(ctx context.Context, req *SetConfigRequest) (*LinearConfig, string, error) {
cfg := &LinearConfig{
AuthMethod: req.AuthMethod,
}
if req.Secret != "" {
return cfg, req.Secret, nil
}
if s.secrets == nil {
return nil, "", errors.New("no secret store configured")
}
secret, err := s.secrets.Reveal(ctx, SecretKey)
if err != nil {
s.log.Warn("linear: secret reveal failed", zap.Error(err))
return nil, "", fmt.Errorf("read linear secret: %w", err)
}
if secret == "" {
return nil, "", errors.New("no api key stored — paste one to test")
}
stored, storeErr := s.store.GetConfig(ctx)
if storeErr != nil {
// Soft-fail: a transient DB error here only loses the saved-config
// fallback values; the inline credentials still work for the test.
s.log.Warn("linear: load stored config for credential resolution failed", zap.Error(storeErr))
}
if stored != nil && cfg.AuthMethod == "" {
cfg.AuthMethod = stored.AuthMethod
}
return cfg, secret, nil
}
func validateConfigRequest(req *SetConfigRequest) error {
if req.AuthMethod == "" {
req.AuthMethod = AuthMethodAPIKey
}
if req.AuthMethod != AuthMethodAPIKey {
return fmt.Errorf("unknown auth method: %q", req.AuthMethod)
}
return nil
}