e740417885
* 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.
305 lines
10 KiB
Go
305 lines
10 KiB
Go
package linear
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func newMockServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {
|
|
t.Helper()
|
|
s := httptest.NewServer(handler)
|
|
t.Cleanup(s.Close)
|
|
return s
|
|
}
|
|
|
|
// pointTo overrides the GraphQL endpoint on a freshly-built client so tests
|
|
// hit the test server without needing a mockable URL on the production
|
|
// constructor.
|
|
func pointTo(c *GraphQLClient, url string) *GraphQLClient {
|
|
c.endpoint = url
|
|
return c
|
|
}
|
|
|
|
// readReq drains a request body into a generic JSON map so tests can assert on
|
|
// the GraphQL query+variables payload.
|
|
func readReq(t *testing.T, r *http.Request) map[string]interface{} {
|
|
t.Helper()
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
t.Fatalf("read body: %v", err)
|
|
}
|
|
var m map[string]interface{}
|
|
if err := json.Unmarshal(body, &m); err != nil {
|
|
t.Fatalf("unmarshal request: %v", err)
|
|
}
|
|
return m
|
|
}
|
|
|
|
func TestGraphQLClient_AuthHeader(t *testing.T) {
|
|
var gotAuth string
|
|
ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
gotAuth = r.Header.Get("Authorization")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":{"viewer":{"id":"u","name":"Alice","displayName":"Alice","email":"a@x"},"organization":{"urlKey":"acme","name":"Acme"}}}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "lin_api_xyz"), ts.URL)
|
|
res, err := c.TestAuth(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("test auth: %v", err)
|
|
}
|
|
if !res.OK {
|
|
t.Fatalf("expected OK=true, got %+v", res)
|
|
}
|
|
if gotAuth != "lin_api_xyz" {
|
|
t.Errorf("auth header = %q, want bare API key", gotAuth)
|
|
}
|
|
if res.OrgSlug != "acme" {
|
|
t.Errorf("expected orgSlug=acme, got %q", res.OrgSlug)
|
|
}
|
|
if res.DisplayName != "Alice" {
|
|
t.Errorf("expected displayName=Alice, got %q", res.DisplayName)
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_TestAuth_BadCreds_ReportsErrorInResult(t *testing.T) {
|
|
ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_, _ = w.Write([]byte(`{"error":"invalid api key"}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "bad"), ts.URL)
|
|
res, err := c.TestAuth(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("test auth should not error on 401, got %v", err)
|
|
}
|
|
if res.OK {
|
|
t.Errorf("expected OK=false, got %+v", res)
|
|
}
|
|
if !strings.Contains(res.Error, "401") {
|
|
t.Errorf("expected 401 in error, got %q", res.Error)
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_TestAuth_GraphQLErrors(t *testing.T) {
|
|
ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"errors":[{"message":"Authentication required","extensions":{"type":"AUTHENTICATION_ERROR"}}]}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), ts.URL)
|
|
res, err := c.TestAuth(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("unexpected err: %v", err)
|
|
}
|
|
if res.OK {
|
|
t.Errorf("expected OK=false on GraphQL error")
|
|
}
|
|
if !strings.Contains(res.Error, "Authentication required") {
|
|
t.Errorf("expected GraphQL error message preserved, got %q", res.Error)
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_ListTeams(t *testing.T) {
|
|
ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
body := readReq(t, r)
|
|
if !strings.Contains(body["query"].(string), "teams(") {
|
|
t.Errorf("expected teams query, got %q", body["query"])
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":{"teams":{"nodes":[{"id":"t1","key":"ENG","name":"Engineering"}]}}}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), ts.URL)
|
|
teams, err := c.ListTeams(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("list: %v", err)
|
|
}
|
|
if len(teams) != 1 || teams[0].Key != "ENG" {
|
|
t.Errorf("teams = %+v", teams)
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_ListStates_RequiresTeamKey(t *testing.T) {
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), "http://nope")
|
|
if _, err := c.ListStates(context.Background(), ""); err == nil {
|
|
t.Error("expected error for empty team key")
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_GetIssue_AttachesStates(t *testing.T) {
|
|
calls := 0
|
|
ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
body := readReq(t, r)
|
|
q, _ := body["query"].(string)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
switch {
|
|
case strings.Contains(q, "issue(id:"):
|
|
calls++
|
|
_, _ = w.Write([]byte(`{"data":{"issue":{"id":"i1","identifier":"ENG-1","title":"Hi","description":"body","url":"https://linear.app/acme/issue/ENG-1","priority":2,"priorityLabel":"High","state":{"id":"s1","name":"In Progress","type":"started","color":"#fff"},"team":{"id":"t1","key":"ENG"},"assignee":null,"creator":null}}}`))
|
|
case strings.Contains(q, "workflowStates"):
|
|
calls++
|
|
_, _ = w.Write([]byte(`{"data":{"workflowStates":{"nodes":[{"id":"s1","name":"In Progress","type":"started","color":"#fff","position":2}]}}}`))
|
|
default:
|
|
t.Errorf("unexpected query: %q", q)
|
|
}
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), ts.URL)
|
|
issue, err := c.GetIssue(context.Background(), "ENG-1")
|
|
if err != nil {
|
|
t.Fatalf("get issue: %v", err)
|
|
}
|
|
if issue.Identifier != "ENG-1" || issue.StateName != "In Progress" {
|
|
t.Errorf("issue mismatch: %+v", issue)
|
|
}
|
|
if issue.StateCategory != "indeterminate" {
|
|
t.Errorf("expected category=indeterminate for started, got %q", issue.StateCategory)
|
|
}
|
|
if len(issue.States) != 1 {
|
|
t.Errorf("expected 1 state attached, got %d", len(issue.States))
|
|
}
|
|
if calls != 2 {
|
|
t.Errorf("expected 2 GraphQL calls (issue + states), got %d", calls)
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_SearchIssues_PaginationCursor(t *testing.T) {
|
|
ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
body := readReq(t, r)
|
|
vars, _ := body["variables"].(map[string]interface{})
|
|
if got, _ := vars["after"].(string); got != "cursor-1" {
|
|
t.Errorf("expected after=cursor-1, got %v", vars["after"])
|
|
}
|
|
if got, _ := vars["first"].(float64); got != 25 {
|
|
t.Errorf("expected first=25, got %v", vars["first"])
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":{"issues":{"nodes":[{"id":"i1","identifier":"ENG-1","title":"a","description":"","url":"u","priority":0,"priorityLabel":"None","state":{"id":"s","name":"S","type":"backlog","color":""},"team":{"id":"t","key":"ENG"}}],"pageInfo":{"hasNextPage":true,"endCursor":"cursor-2"}}}}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), ts.URL)
|
|
res, err := c.SearchIssues(context.Background(), SearchFilter{Query: "auth"}, "cursor-1", 0)
|
|
if err != nil {
|
|
t.Fatalf("search: %v", err)
|
|
}
|
|
if res.IsLast {
|
|
t.Error("expected IsLast=false when hasNextPage=true")
|
|
}
|
|
if res.NextPageToken != "cursor-2" {
|
|
t.Errorf("expected next cursor, got %q", res.NextPageToken)
|
|
}
|
|
if len(res.Issues) != 1 {
|
|
t.Errorf("expected 1 issue, got %d", len(res.Issues))
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_SetIssueState(t *testing.T) {
|
|
var seenVars map[string]interface{}
|
|
ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
body := readReq(t, r)
|
|
seenVars, _ = body["variables"].(map[string]interface{})
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":{"issueUpdate":{"success":true}}}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), ts.URL)
|
|
if err := c.SetIssueState(context.Background(), "ENG-1", "state-id"); err != nil {
|
|
t.Fatalf("set state: %v", err)
|
|
}
|
|
if seenVars["id"] != "ENG-1" || seenVars["stateId"] != "state-id" {
|
|
t.Errorf("vars = %+v", seenVars)
|
|
}
|
|
}
|
|
|
|
func TestGraphQLClient_SetIssueState_FailureFlag(t *testing.T) {
|
|
ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":{"issueUpdate":{"success":false}}}`))
|
|
})
|
|
c := pointTo(NewGraphQLClient(&LinearConfig{}, "x"), ts.URL)
|
|
err := c.SetIssueState(context.Background(), "ENG-1", "state-id")
|
|
if err == nil {
|
|
t.Error("expected error when success=false")
|
|
}
|
|
}
|
|
|
|
func TestStateCategoryMapping(t *testing.T) {
|
|
cases := map[string]string{
|
|
"backlog": "new",
|
|
"unstarted": "new",
|
|
"triage": "new",
|
|
"started": "indeterminate",
|
|
"completed": "done",
|
|
"canceled": "done",
|
|
"weird": "new",
|
|
}
|
|
for input, want := range cases {
|
|
if got := stateCategory(input); got != want {
|
|
t.Errorf("stateCategory(%q)=%q, want %q", input, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestBuildIssueFilter_DropsEmpty(t *testing.T) {
|
|
if got := buildIssueFilter(SearchFilter{}); got != nil {
|
|
t.Errorf("expected nil filter for empty input, got %+v", got)
|
|
}
|
|
got := buildIssueFilter(SearchFilter{Query: "auth", TeamKey: "ENG", Assigned: "me"})
|
|
if _, ok := got["searchableContent"]; !ok {
|
|
t.Error("expected searchableContent filter")
|
|
}
|
|
if _, ok := got["team"]; !ok {
|
|
t.Error("expected team filter")
|
|
}
|
|
if _, ok := got["assignee"]; !ok {
|
|
t.Error("expected assignee filter")
|
|
}
|
|
}
|
|
|
|
func TestBuildIssueFilter_RichFilters(t *testing.T) {
|
|
min := 1.0
|
|
max := 5.0
|
|
got := buildIssueFilter(SearchFilter{
|
|
Priorities: []int{1, 2},
|
|
LabelIDs: []string{"l1", "l2"},
|
|
CreatorID: "u1",
|
|
EstimateMin: &min,
|
|
EstimateMax: &max,
|
|
})
|
|
prioBlock, ok := got["priority"].(map[string]interface{})
|
|
if !ok {
|
|
t.Fatalf("missing priority filter: %+v", got)
|
|
}
|
|
prioIn, _ := prioBlock["in"].([]int)
|
|
if len(prioIn) != 2 || prioIn[0] != 1 || prioIn[1] != 2 {
|
|
t.Errorf("priority filter mismatch: %+v", prioBlock)
|
|
}
|
|
labelBlock, ok := got["labels"].(map[string]interface{})
|
|
if !ok {
|
|
t.Fatalf("missing labels filter: %+v", got)
|
|
}
|
|
some, _ := labelBlock["some"].(map[string]interface{})
|
|
idBlock, _ := some["id"].(map[string]interface{})
|
|
in, _ := idBlock["in"].([]string)
|
|
if len(in) != 2 || in[0] != "l1" {
|
|
t.Errorf("label ids mismatch: %+v", labelBlock)
|
|
}
|
|
creator, _ := got["creator"].(map[string]interface{})
|
|
idEq, _ := creator["id"].(map[string]interface{})
|
|
if idEq["eq"] != "u1" {
|
|
t.Errorf("creator filter mismatch: %+v", got["creator"])
|
|
}
|
|
est, ok := got["estimate"].(map[string]interface{})
|
|
if !ok || est["gte"] != 1.0 || est["lte"] != 5.0 {
|
|
t.Errorf("estimate filter mismatch: %+v", got["estimate"])
|
|
}
|
|
}
|
|
|
|
func TestBuildIssueFilter_PriorityZero(t *testing.T) {
|
|
got := buildIssueFilter(SearchFilter{Priorities: []int{0}})
|
|
prio, _ := got["priority"].(map[string]interface{})
|
|
in, _ := prio["in"].([]int)
|
|
if len(in) != 1 || in[0] != 0 {
|
|
t.Errorf("priorities=[0] should map to in:[0] (No priority), got %+v", prio)
|
|
}
|
|
}
|