Files
kandev/apps/web/lib/sidebar/apply-view.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

232 lines
7.5 KiB
TypeScript

import { classifyTask, type TaskBucket } from "@/components/task/task-classify";
import type { TaskSwitcherItem } from "@/components/task/task-switcher";
import { getExecutorLabel } from "@/lib/executor-icons";
import type {
FilterClause,
FilterDimension,
FilterOp,
FilterValue,
GroupKey,
SidebarView,
SortKey,
SortSpec,
} from "@/lib/state/slices/ui/sidebar-view-types";
export type SidebarGroup = {
key: string;
label: string;
tasks: TaskSwitcherItem[];
};
export type GroupedSidebarList = {
groups: SidebarGroup[];
subTasksByParentId: Map<string, TaskSwitcherItem[]>;
};
type DimensionExtractor = (task: TaskSwitcherItem) => FilterValue | undefined;
const STATE_BUCKET_ORDER: Record<TaskBucket, number> = {
review: 0,
in_progress: 1,
backlog: 2,
};
function getStateBucket(task: TaskSwitcherItem): TaskBucket {
return classifyTask(task.sessionState, task.state);
}
const dimensionExtractors: Record<FilterDimension, DimensionExtractor> = {
archived: (t) => t.isArchived === true,
state: (t) => getStateBucket(t),
workflow: (t) => t.workflowId,
workflowStep: (t) => t.workflowStepId,
executorType: (t) => t.remoteExecutorType,
repository: (t) => (t.repositories && t.repositories.length > 1 ? "__multi__" : t.repositoryPath),
hasDiff: (t) => {
const ds = t.diffStats;
return !!ds && (ds.additions > 0 || ds.deletions > 0);
},
isPRReview: (t) => t.isPRReview === true,
isIssueWatch: (t) => t.isIssueWatch === true,
titleMatch: (t) => t.title ?? "",
};
function toStringArray(v: FilterValue): string[] {
if (Array.isArray(v)) return v.map(String);
return [String(v)];
}
function evaluateClause(task: TaskSwitcherItem, clause: FilterClause): boolean {
const extract = dimensionExtractors[clause.dimension];
const actual = extract(task);
switch (clause.op) {
case "is":
return String(actual) === String(clause.value);
case "is_not":
return String(actual) !== String(clause.value);
case "in":
return toStringArray(clause.value).includes(String(actual));
case "not_in":
return !toStringArray(clause.value).includes(String(actual));
case "matches": {
const hay = String(actual ?? "").toLowerCase();
const needle = String(clause.value).toLowerCase();
return needle === "" || hay.includes(needle);
}
case "not_matches": {
const hay = String(actual ?? "").toLowerCase();
const needle = String(clause.value).toLowerCase();
return needle !== "" && !hay.includes(needle);
}
default:
return true;
}
}
export function applyFilters(
tasks: TaskSwitcherItem[],
clauses: FilterClause[],
): TaskSwitcherItem[] {
if (clauses.length === 0) return tasks;
return tasks.filter((task) => clauses.every((clause) => evaluateClause(task, clause)));
}
const SORT_COMPARATORS: Record<SortKey, (a: TaskSwitcherItem, b: TaskSwitcherItem) => number> = {
state: (a, b) => {
const bucket = STATE_BUCKET_ORDER[getStateBucket(a)] - STATE_BUCKET_ORDER[getStateBucket(b)];
if (bucket !== 0) return bucket;
// Tiebreak: newest createdAt first (preserves historical sidebar ordering)
return (b.createdAt ?? "").localeCompare(a.createdAt ?? "");
},
updatedAt: (a, b) => (a.updatedAt ?? "").localeCompare(b.updatedAt ?? ""),
createdAt: (a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""),
title: (a, b) => (a.title ?? "").localeCompare(b.title ?? ""),
};
export function applySort(tasks: TaskSwitcherItem[], spec: SortSpec): TaskSwitcherItem[] {
const cmp = SORT_COMPARATORS[spec.key];
const sign = spec.direction === "desc" ? -1 : 1;
const withIndex = tasks.map((t, i) => ({ t, i }));
withIndex.sort((a, b) => {
const primary = cmp(a.t, b.t) * sign;
if (primary !== 0) return primary;
return a.i - b.i;
});
return withIndex.map((x) => x.t);
}
const UNASSIGNED_LABEL = "Unassigned";
const MULTI_REPO_LABEL = "Multi-repo";
type GroupExtractor = (task: TaskSwitcherItem) => { key: string; label: string };
const groupExtractors: Record<Exclude<GroupKey, "none">, GroupExtractor> = {
repository: (t) => {
if (t.repositories && t.repositories.length > 1) {
return { key: "__multi__", label: MULTI_REPO_LABEL };
}
if (t.repositoryPath) return { key: t.repositoryPath, label: t.repositoryPath };
return { key: "__unassigned__", label: UNASSIGNED_LABEL };
},
workflow: (t) => {
if (t.workflowId) return { key: t.workflowId, label: t.workflowName ?? t.workflowId };
return { key: "__unassigned__", label: UNASSIGNED_LABEL };
},
workflowStep: (t) => {
if (t.workflowStepId) {
return { key: t.workflowStepId, label: t.workflowStepTitle ?? t.workflowStepId };
}
return { key: "__unassigned__", label: UNASSIGNED_LABEL };
},
executorType: (t) => {
if (t.remoteExecutorType) {
return { key: t.remoteExecutorType, label: getExecutorLabel(t.remoteExecutorType) };
}
return { key: "__unassigned__", label: UNASSIGNED_LABEL };
},
state: (t) => {
const bucket = getStateBucket(t);
return { key: bucket, label: bucket };
},
};
function separateSubtasks(tasks: TaskSwitcherItem[]): {
rootTasks: TaskSwitcherItem[];
subTasksByParentId: Map<string, TaskSwitcherItem[]>;
} {
const allIds = new Set(tasks.map((t) => t.id));
const subMap = new Map<string, TaskSwitcherItem[]>();
const rootTasks: TaskSwitcherItem[] = [];
for (const t of tasks) {
if (t.parentTaskId && allIds.has(t.parentTaskId)) {
const arr = subMap.get(t.parentTaskId) ?? [];
arr.push(t);
subMap.set(t.parentTaskId, arr);
} else {
rootTasks.push(t);
}
}
return { rootTasks, subTasksByParentId: subMap };
}
export function applyGroup(tasks: TaskSwitcherItem[], groupKey: GroupKey): GroupedSidebarList {
const { rootTasks, subTasksByParentId } = separateSubtasks(tasks);
if (groupKey === "none") {
return {
groups: [{ key: "__all__", label: "All", tasks: rootTasks }],
subTasksByParentId,
};
}
const extract = groupExtractors[groupKey];
const buckets = new Map<string, SidebarGroup>();
for (const task of rootTasks) {
const { key, label } = extract(task);
let group = buckets.get(key);
if (!group) {
group = { key, label, tasks: [] };
buckets.set(key, group);
}
group.tasks.push(task);
}
const groups = [...buckets.values()];
if (groupKey === "repository") {
mergeSingleRepoUnassigned(groups);
sortRepoGroups(groups);
}
return { groups, subTasksByParentId };
}
function mergeSingleRepoUnassigned(groups: SidebarGroup[]): void {
const repoGroups = groups.filter((g) => g.key !== "__multi__" && g.key !== "__unassigned__");
if (repoGroups.length !== 1) return;
const unassignedIdx = groups.findIndex((g) => g.key === "__unassigned__");
if (unassignedIdx === -1) return;
const unassigned = groups[unassignedIdx];
repoGroups[0].tasks.push(...unassigned.tasks);
groups.splice(unassignedIdx, 1);
}
function sortRepoGroups(groups: SidebarGroup[]): void {
groups.sort((a, b) => {
if (a.key === "__multi__") return -1;
if (b.key === "__multi__") return 1;
if (a.key === "__unassigned__") return 1;
if (b.key === "__unassigned__") return -1;
return a.label.localeCompare(b.label);
});
}
export function applyView(tasks: TaskSwitcherItem[], view: SidebarView): GroupedSidebarList {
const filtered = applyFilters(tasks, view.filters);
const sorted = applySort(filtered, view.sort);
return applyGroup(sorted, view.group);
}
export function opIsNegative(op: FilterOp): boolean {
return op === "is_not" || op === "not_in" || op === "not_matches";
}