Files
kandev/apps/web/lib/sidebar/apply-view.test.ts
T
João Salavisa c11a6bbfd2 feat(github): add issue watcher with task creation and auto-cleanup (#672)
* feat(github): add issue watcher with task creation and auto-cleanup

Add a GitHub Issue Watcher feature that polls for new issues matching
configurable filters and automatically creates tasks for them. This
complements the existing PR Review Watcher with the same patterns.

Backend:
- Issue watch CRUD (models, store, service, controller, WS handlers)
- Poller integration with configurable intervals
- Event-driven task creation via orchestrator
- Repository resolution and worktree support for issue tasks
- Auto-cleanup of tasks for closed issues (CleanupClosedIssueTasks)
- GetIssueState client method across all implementations
- Default branch auto-detection from cloned repo HEAD

Frontend:
- Issue watch settings UI (table, dialog, placeholders)
- Issue link icon on task cards (green circle-dot)
- API client, store slice, and hook for issue watches
- SSR and WS hydration of issue metadata

* fix: resolve golangci-lint errors (goconst, nestif, dupl) and prettier formatting

* fix(github): fix issue watch update shape, trigger key, and label quoting

- httpUpdateIssueWatch now returns the full IssueWatch object instead of
  {updated:true} so the frontend store correctly refreshes after edits
- httpTriggerIssueWatch returns new_issues_found to match TriggerIssueResponse
  type; was returning new_issues so the toast count was always 0
- buildIssueFilter uses conditional quoting instead of fmt.Sprintf %q to
  avoid Go escape sequences in GitHub search qualifiers

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

* fix: resolve eslint warnings (max-lines-per-function, no-nested-ternary)

* test(github): add issue watcher tests and fix review feedback

- Add TestInterpolateIssuePrompt (4 cases: empty/all/none/partial)
- Add TestCreateIssueTask (3 cases: skip/reserve+assign/release on fail)
- Add TestShouldDeleteIssueTask (4 cases: open/closed+sessions/closed/error)
- Fix WS response key new_issues -> new_issues_found
- Fix fmt.Printf -> fmt.Fprintf(os.Stderr) in store.go
- Add CleanupClosedIssueTasks call in WS trigger handler

* fix: address PR review feedback and CI failures

- Split test files to fix revive file-length-limit (service_test.go,
  event_handlers_github_test.go)
- Add session checker guard in CleanupClosedIssueTasks
- Normalize poll intervals on UpdateIssueWatch
- Add cleanup call in TriggerAllIssueChecks loop
- Log cleanup errors in controller and WS handler
- Prefer refs/remotes/origin/HEAD in detectGitDefaultBranch
- Add aria-label to issue task icon
- Fix TypeScript type errors: add linkedIssues to GitHubSlice,
  fix hook exports, remove invalid imports

* fix: split test files exceeding revive limit and clean up minor issues

- Split service_test.go (883→779 lines): move TestTriggerPRSync_* to
  service_pr_sync_test.go
- Split event_handlers_github_test.go (806→677 lines): move
  TestCreateReviewTask_* and helpers to event_handlers_github_review_test.go
- Remove redundant s.taskSessionChecker nil-check inside shouldDeleteIssueTask
  (early guard at CleanupClosedIssueTasks already ensures it is non-nil)
- Remove unreachable dead guard in detectAndPersistDefaultBranch
  (repo.DefaultBranch is always "" at that call site)
- Fix bogus #0 issue badge in task-session-sidebar.tsx when issueNumber is absent

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

* fix: address Claude review — poll clamp and prompt injection

- Handle v <= 0 in UpdateIssueWatch poll interval (fall back to default)
- Remove {{issue.body}} from default template to prevent prompt injection
- Update test expected output for new default template

* fix: remove {{issue.body}} from frontend DEFAULT_ISSUE_WATCH_PROMPT

Mirrors the backend fix — the UI pre-fills the prompt so the backend
fallback was never reached. The placeholder stays in
ISSUE_WATCH_PLACEHOLDERS for explicit opt-in.

* feat(github): add isIssueWatch sidebar filter dimension

Add isIssueWatch boolean to KanbanState, TaskSwitcherItem, and sidebar
filter registry — mirroring the isPRReview pattern. Issue-watch tasks
(created from issue_watch_id in metadata) can now be explicitly filtered
in the sidebar, just like PR review tasks.

Files changed:
- sidebar-view-types: add isIssueWatch dimension
- filter-dimension-registry: add Issue watch filter meta
- apply-view: add isIssueWatch extractor
- kanban types: add isIssueWatch field
- TaskSwitcherItem: add isIssueWatch field
- use-all-workflow-snapshots: derive isIssueWatch from metadata
- ssr/mapper: derive isIssueWatch from metadata
- task-session-sidebar: pass isIssueWatch, extract helpers to fix complexity

* fix: correct deleteIssueWatch response type to match backend

Backend httpDeleteIssueWatch returns {"deleted": true}; the frontend
type was { success: boolean } — a mismatch with no functional impact
(return value is ignored) but wrong per TypeScript contract.

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

* refactor: extract metadata helpers to shared lib/metadata-utils.ts

- Move isPRReviewFromMetadata, isIssueWatchFromMetadata, and
  issueFieldsFromMetadata to a shared module to eliminate duplicate
  definitions (sonarjs/no-identical-functions).
- Fix deleteIssueWatch response type: { success: boolean } -> { deleted: boolean }
  to match the actual backend response.

* style: fix prettier formatting

* test(web): add tests for isIssueWatch filter dimension and metadata-utils

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: fix prettier formatting in test files

* fix(github): cascade-delete issue watch tasks on watch deletion and add isPRReview to SSR mapper

- DeleteIssueWatch now wraps in a transaction and deletes related
  github_issue_watch_tasks rows before removing the watch; prevents
  orphaned dedup rows accumulating after a watch is deleted
- snapshotToState in mapper.ts now also sets isPRReview from metadata,
  matching the mapping already done in use-all-workflow-snapshots.ts

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

* style: extract duplicate string constant in metadata-utils test

* style: extract repeated WS error strings into constants in handlers.go

goconst min-occurrences: 3 — 'invalid payload' (6x) and 'id required' (4x)
both exceed the threshold. Extract to package-level constants.

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

* style: extract repeated issue key strings into constants in event_handlers_github.go

goconst min-occurrences: 3 — 'issue_number' (9x) and 'issue_watch_id' (5x)
both newly introduced in this PR exceed the threshold.

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

* style: fix prettier formatting in metadata-utils test

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 17:32:46 +01:00

321 lines
12 KiB
TypeScript

import { describe, it, expect } from "vitest";
import type { TaskSwitcherItem } from "@/components/task/task-switcher";
import { applyFilters, applyGroup, applySort, applyView } from "./apply-view";
import type { FilterClause, SidebarView } from "@/lib/state/slices/ui/sidebar-view-types";
import { DEFAULT_VIEW } from "@/lib/state/slices/ui/sidebar-view-builtins";
function task(overrides: Partial<TaskSwitcherItem>): TaskSwitcherItem {
return {
id: overrides.id ?? "t",
title: overrides.title ?? "Task",
...overrides,
};
}
const C = (c: Omit<FilterClause, "id">): FilterClause => ({ id: "c1", ...c });
describe("applyFilters — basics", () => {
it("returns all when no clauses", () => {
const tasks = [task({ id: "a" }), task({ id: "b" })];
expect(applyFilters(tasks, [])).toHaveLength(2);
});
});
describe("applyFilters — per-dimension", () => {
it("filters by isPRReview is true (watcher-created task)", () => {
const tasks = [task({ id: "a", isPRReview: true }), task({ id: "b" })];
const out = applyFilters(tasks, [C({ dimension: "isPRReview", op: "is", value: true })]);
expect(out.map((t) => t.id)).toEqual(["a"]);
});
it("filters by isPRReview is false (regular task, even with linked PR)", () => {
const tasks = [
task({ id: "a", isPRReview: true }),
task({ id: "b", prInfo: { number: 1, state: "Open" } }),
];
const out = applyFilters(tasks, [C({ dimension: "isPRReview", op: "is", value: false })]);
expect(out.map((t) => t.id)).toEqual(["b"]);
});
it("supports is_not negation on isPRReview", () => {
const tasks = [task({ id: "a", isPRReview: true }), task({ id: "b" })];
const out = applyFilters(tasks, [C({ dimension: "isPRReview", op: "is_not", value: true })]);
expect(out.map((t) => t.id)).toEqual(["b"]);
});
it("filters by isIssueWatch is true (issue-watcher-created task)", () => {
const tasks = [task({ id: "a", isIssueWatch: true }), task({ id: "b" })];
const out = applyFilters(tasks, [C({ dimension: "isIssueWatch", op: "is", value: true })]);
expect(out.map((t) => t.id)).toEqual(["a"]);
});
it("filters by isIssueWatch is false (regular task)", () => {
const tasks = [task({ id: "a", isIssueWatch: true }), task({ id: "b" })];
const out = applyFilters(tasks, [C({ dimension: "isIssueWatch", op: "is", value: false })]);
expect(out.map((t) => t.id)).toEqual(["b"]);
});
it("supports is_not negation on isIssueWatch", () => {
const tasks = [task({ id: "a", isIssueWatch: true }), task({ id: "b" })];
const out = applyFilters(tasks, [C({ dimension: "isIssueWatch", op: "is_not", value: true })]);
expect(out.map((t) => t.id)).toEqual(["b"]);
});
it("filters by archived boolean", () => {
const tasks = [task({ id: "a", isArchived: true }), task({ id: "b" })];
const only = applyFilters(tasks, [C({ dimension: "archived", op: "is", value: true })]);
expect(only.map((t) => t.id)).toEqual(["a"]);
const not = applyFilters(tasks, [C({ dimension: "archived", op: "is", value: false })]);
expect(not.map((t) => t.id)).toEqual(["b"]);
});
it("filters by state bucket with in / not_in", () => {
const tasks = [
task({ id: "a", state: "REVIEW" }),
task({ id: "b", sessionState: "RUNNING" }),
task({ id: "c" }),
];
const review = applyFilters(tasks, [C({ dimension: "state", op: "in", value: ["review"] })]);
expect(review.map((t) => t.id)).toEqual(["a"]);
const notBacklog = applyFilters(tasks, [
C({ dimension: "state", op: "not_in", value: ["backlog"] }),
]);
expect(notBacklog.map((t) => t.id).sort()).toEqual(["a", "b"]);
});
it("filters by repository", () => {
const tasks = [
task({ id: "a", repositoryPath: "org/repo1" }),
task({ id: "b", repositoryPath: "org/repo2" }),
];
const out = applyFilters(tasks, [C({ dimension: "repository", op: "is", value: "org/repo1" })]);
expect(out.map((t) => t.id)).toEqual(["a"]);
});
it("filters by executorType", () => {
const tasks = [
task({ id: "a", remoteExecutorType: "sprites" }),
task({ id: "b", remoteExecutorType: "local_docker" }),
];
const out = applyFilters(tasks, [C({ dimension: "executorType", op: "is", value: "sprites" })]);
expect(out.map((t) => t.id)).toEqual(["a"]);
});
it("filters by workflow + workflowStep", () => {
const tasks = [
task({ id: "a", workflowId: "wf1", workflowStepId: "s1" }),
task({ id: "b", workflowId: "wf2", workflowStepId: "s1" }),
task({ id: "c", workflowId: "wf1", workflowStepId: "s2" }),
];
const out = applyFilters(tasks, [
{ id: "c1", dimension: "workflow", op: "is", value: "wf1" },
{ id: "c2", dimension: "workflowStep", op: "is", value: "s1" },
]);
expect(out.map((t) => t.id)).toEqual(["a"]);
});
it("filters by hasDiff", () => {
const tasks = [
task({ id: "a", diffStats: { additions: 10, deletions: 0 } }),
task({ id: "b", diffStats: { additions: 0, deletions: 0 } }),
task({ id: "c" }),
];
const withDiff = applyFilters(tasks, [C({ dimension: "hasDiff", op: "is", value: true })]);
expect(withDiff.map((t) => t.id)).toEqual(["a"]);
const noDiff = applyFilters(tasks, [C({ dimension: "hasDiff", op: "is", value: false })]);
expect(noDiff.map((t) => t.id).sort()).toEqual(["b", "c"]);
});
});
describe("applyFilters — titleMatch + combos", () => {
it("filters by titleMatch matches (case-insensitive substring)", () => {
const tasks = [
task({ id: "a", title: "Fix auth bug" }),
task({ id: "b", title: "Update deps" }),
task({ id: "c", title: "AUTHenticate users" }),
];
const out = applyFilters(tasks, [C({ dimension: "titleMatch", op: "matches", value: "auth" })]);
expect(out.map((t) => t.id).sort()).toEqual(["a", "c"]);
});
it("filters by titleMatch not_matches", () => {
const tasks = [
task({ id: "a", title: "Fix auth bug" }),
task({ id: "b", title: "Update deps" }),
];
const out = applyFilters(tasks, [
C({ dimension: "titleMatch", op: "not_matches", value: "auth" }),
]);
expect(out.map((t) => t.id)).toEqual(["b"]);
});
it("AND combines multiple clauses", () => {
const tasks = [
task({ id: "a", sessionState: "RUNNING", isPRReview: true }),
task({ id: "b", sessionState: "RUNNING" }),
task({ id: "c", isPRReview: true }),
];
const out = applyFilters(tasks, [
C({ dimension: "state", op: "is", value: "in_progress" }),
{ id: "c2", dimension: "isPRReview", op: "is", value: true },
]);
expect(out.map((t) => t.id)).toEqual(["a"]);
});
});
describe("applySort", () => {
const a = task({ id: "a", state: "REVIEW", updatedAt: "2026-04-01", title: "Zeta" });
const b = task({ id: "b", sessionState: "RUNNING", updatedAt: "2026-04-05", title: "Alpha" });
const c = task({ id: "c", updatedAt: "2026-04-03", title: "Mu" });
it("sorts by state bucket asc (review, in_progress, backlog)", () => {
const out = applySort([c, b, a], { key: "state", direction: "asc" });
expect(out.map((t) => t.id)).toEqual(["a", "b", "c"]);
});
it("sorts by state bucket desc", () => {
const out = applySort([a, b, c], { key: "state", direction: "desc" });
expect(out.map((t) => t.id)).toEqual(["c", "b", "a"]);
});
it("sorts by updatedAt desc", () => {
const out = applySort([a, b, c], { key: "updatedAt", direction: "desc" });
expect(out.map((t) => t.id)).toEqual(["b", "c", "a"]);
});
it("sorts by title asc", () => {
const out = applySort([a, b, c], { key: "title", direction: "asc" });
expect(out.map((t) => t.id)).toEqual(["b", "c", "a"]);
});
it("is stable for equal keys", () => {
const x = task({ id: "x", state: "REVIEW" });
const y = task({ id: "y", state: "REVIEW" });
const z = task({ id: "z", state: "REVIEW" });
const out = applySort([x, y, z], { key: "state", direction: "asc" });
expect(out.map((t) => t.id)).toEqual(["x", "y", "z"]);
});
});
describe("applyGroup", () => {
it("wraps all tasks in single pseudo-group when group=none", () => {
const tasks = [task({ id: "a" }), task({ id: "b" })];
const out = applyGroup(tasks, "none");
expect(out.groups).toHaveLength(1);
expect(out.groups[0].tasks).toHaveLength(2);
});
it("groups by repository with multi-repo + per-repo buckets", () => {
const tasks = [
task({ id: "a", repositories: ["org/r1", "org/r2"] }),
task({ id: "b", repositoryPath: "org/r1" }),
task({ id: "c", repositoryPath: "org/r2" }),
task({ id: "d" }),
];
const out = applyGroup(tasks, "repository");
const labels = out.groups.map((g) => g.label);
expect(labels).toContain("Multi-repo");
expect(labels).toContain("org/r1");
expect(labels).toContain("org/r2");
expect(labels).toContain("Unassigned");
expect(out.groups[0].label).toBe("Multi-repo");
});
it("merges unassigned into single repo group", () => {
const tasks = [task({ id: "a", repositoryPath: "org/only" }), task({ id: "b" })];
const out = applyGroup(tasks, "repository");
expect(out.groups).toHaveLength(1);
expect(out.groups[0].label).toBe("org/only");
expect(out.groups[0].tasks).toHaveLength(2);
});
it("separates subtasks from root tasks", () => {
const tasks = [
task({ id: "parent", repositoryPath: "r" }),
task({ id: "child", repositoryPath: "r", parentTaskId: "parent" }),
task({ id: "orphan", repositoryPath: "r", parentTaskId: "ghost" }),
];
const out = applyGroup(tasks, "repository");
expect(out.groups[0].tasks.map((t) => t.id).sort()).toEqual(["orphan", "parent"]);
expect(out.subTasksByParentId.get("parent")?.map((t) => t.id)).toEqual(["child"]);
});
it("groups by workflow / workflowStep / executorType / state", () => {
const tasks = [
task({ id: "a", workflowId: "wf1", workflowStepId: "s1", remoteExecutorType: "sprites" }),
task({ id: "b", workflowId: "wf2", workflowStepId: "s2", remoteExecutorType: "local_pc" }),
];
expect(applyGroup(tasks, "workflow").groups).toHaveLength(2);
expect(applyGroup(tasks, "workflowStep").groups).toHaveLength(2);
expect(applyGroup(tasks, "executorType").groups).toHaveLength(2);
});
it("buckets missing group-key value into Unassigned", () => {
const tasks = [task({ id: "a", workflowId: "wf1" }), task({ id: "b" })];
const out = applyGroup(tasks, "workflow");
const labels = out.groups.map((g) => g.label);
expect(labels).toContain("Unassigned");
});
it("labels workflow groups with workflowName when available", () => {
const tasks = [
task({ id: "a", workflowId: "wf1", workflowName: "Kanban" }),
task({ id: "b", workflowId: "wf2", workflowName: "PR Reviews" }),
];
const labels = applyGroup(tasks, "workflow")
.groups.map((g) => g.label)
.sort();
expect(labels).toEqual(["Kanban", "PR Reviews"]);
});
it("labels workflowStep groups with workflowStepTitle when available", () => {
const tasks = [
task({ id: "a", workflowStepId: "s1", workflowStepTitle: "Backlog" }),
task({ id: "b", workflowStepId: "s2", workflowStepTitle: "In Progress" }),
];
const labels = applyGroup(tasks, "workflowStep")
.groups.map((g) => g.label)
.sort();
expect(labels).toEqual(["Backlog", "In Progress"]);
});
});
describe("applyView (integration)", () => {
it("applies filter + sort + group in sequence", () => {
const view: SidebarView = {
id: "v",
name: "v",
filters: [{ id: "f1", dimension: "isPRReview", op: "is", value: false }],
sort: { key: "updatedAt", direction: "desc" },
group: "none",
collapsedGroups: [],
};
const tasks = [
task({ id: "a", isPRReview: true, updatedAt: "2026-04-05" }),
task({ id: "b", updatedAt: "2026-04-01" }),
task({ id: "c", updatedAt: "2026-04-10" }),
];
const out = applyView(tasks, view);
expect(out.groups).toHaveLength(1);
expect(out.groups[0].tasks.map((t) => t.id)).toEqual(["c", "b"]);
});
});
describe("default view semantics", () => {
it("default view shows everything, grouped by repository", () => {
const tasks = [
task({
id: "pr-open",
prInfo: { number: 1, state: "Open" },
state: "REVIEW",
repositoryPath: "org/r",
}),
task({ id: "plain", state: "IN_PROGRESS", repositoryPath: "org/r" }),
task({ id: "archived", isArchived: true, repositoryPath: "org/r" }),
];
const out = applyView(tasks, DEFAULT_VIEW);
const ids = out.groups.flatMap((g) => g.tasks.map((t) => t.id));
expect(ids.sort()).toEqual(["archived", "plain", "pr-open"]);
});
});