Files
kandev/apps/web/components/github/my-github/quick-task-launcher.tsx
T
João Salavisa 85aa3ac0aa feat(github): add /github page for PRs and issues (#687)
* feat(github): add /github page for PRs and issues

Dedicated page under /github lists pull requests and issues across the
authenticated user's repos with preset filters, custom GitHub search
queries, per-repo narrowing, saved queries, and one-click task launching
for any PR or issue.

Performance:
- Cache user PR/issue search responses for 30s with singleflight to
  coalesce concurrent misses, so preset switching and pagination avoid
  upstream round trips.
- Replace the per-row PR status fetch (N+1) with a batch endpoint
  POST /api/v1/github/prs/statuses that fans out concurrently on the
  backend with a semaphore and caches per-PR.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: apply Prettier formatting

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address review feedback on PR cache + status batching

- Harden searchCacheKey against separator collisions from
  user-controllable customQuery (length-prefix encoding).
- Drop repositories.loaded hydration when inner workspace fetch fails
  so the client refetches instead of trusting a partial snapshot.
- Guard useGitHubSearch with a monotonic request counter to drop
  stale responses when filter+page changes overlap.
- Fix usePRStatuses teardown: depend only on composed key so a new
  array identity per render doesn't cancel the in-flight batch.
- Correct godocs (duplicate, outdated state:open claim).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address additional review feedback

- Restore state:open for issue watcher: buildIssueSearchQuery no
  longer injects it as a default, so existing watches were starting
  to surface closed issues. Inject state:open in buildIssueFilter so
  only the watcher path is affected; the /github page presets already
  set their own state qualifiers.
- countCheckResults now excludes in-progress checks from the denominator
  so a `1/3` badge reflects pass rate on completed checks, not a mix of
  running and failed. The pending state is still carried via ChecksState.
- usePRStatuses retries after a transient fetch error (only mark the
  key as completed once the fetch resolves). This also fixes missing
  badges under React Strict Mode's intentional double-mount, since the
  first effect's cleanup fires before the response lands and the guard
  stays unset for the second mount to retry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(github): add tests for my-github hooks

Covers use-committed-query, buildParams from use-github-search,
use-saved-presets readStorage validation, use-known-repos recordForKey
accumulator semantics, and use-pr-statuses batch fetch lifecycle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address review feedback on search cache and repo accumulator

- Clamp perPage before composing the search cache key so identical
  pages (e.g. perPage=150 and =100) share a cache entry instead of
  creating duplicates keyed on the raw value.
- Add resetKnownReposStore and call it on /github unmount so the
  module-level repo accumulator doesn't carry across navigations.
- Rename use-pr-statuses test to match its assertion (it verifies
  stale statuses are cleared when the key changes and fetch fails).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: apply Prettier formatting

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web): distinguish blocked from dirty in PR mergeable badge

GitHub's blocked state (required reviews/checks/branch protection)
is not a merge conflict, so don't label it "Conflicts". Surface it
as "Blocked" with the pending tone; keep "Conflicts" for dirty.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: address remaining /github code review comments

- Route PR status + batch through handleSearchError so ErrNoClient
  surfaces as 503 instead of 500 (matches the search endpoints).
- Sort workflow steps by position in the quick-task-launcher default
  pick, matching the convention in issue-watch-dialog.
- Make PresetItem keyboard-accessible: role=button, tabIndex, and
  Enter/Space handling on the wrapping div (it contains a nested
  delete button, so it can't itself be a button).
- Extract useRepoOptions out of useGitHubPageState to bring the hook
  back under the 100-line complexity limit.
- Honor ctx.Done() when acquiring the PR-status batch semaphore so a
  cancelled HTTP request releases queued goroutines instead of
  running each upstream fetch to completion.
- Clarify parsePaginationQuery doc: the upper bound (100) is enforced
  by clampSearchPage in the client layer, not here.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): address /github review follow-ups

- Merge duplicate @/lib/utils imports in pr-list.
- Use rel="noopener noreferrer" on external PR/issue links (codebase
  convention) and add cursor-pointer per the UI guidelines.
- Rewrite onOpenSaveDialog as an explicit if-block so the callback
  returns void rather than boolean | void.
- Use PaginationEllipsis in its own PaginationItem so the ellipsis
  and the adjacent page link are separate list items instead of
  visually fused into a single cell.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(web): derive QuickTaskLauncher dialog state from props

Replaces the useEffect+setState anti-pattern with useMemo-derived state
driven directly by the payload prop. Drops the eslint suppression that
was needed for react-hooks/set-state-in-effect.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 10:38:49 +01:00

203 lines
5.5 KiB
TypeScript

"use client";
import { useMemo } from "react";
import { useRouter } from "next/navigation";
import {
IconEye,
IconMessageDots,
IconTool,
IconCode,
IconSearch,
IconBug,
} from "@tabler/icons-react";
import type { Icon } from "@tabler/icons-react";
import { TaskCreateDialog } from "@/components/task-create-dialog";
import type { Repository, Task, Workflow, WorkflowStep } from "@/lib/types/http";
import type { GitHubPR, GitHubIssue } from "@/lib/types/github";
export type TaskPreset = {
id: string;
label: string;
hint: string;
icon: Icon;
prompt: (opts: { url: string; title: string }) => string;
};
export type LaunchPayload =
| { kind: "pr"; pr: GitHubPR; preset: TaskPreset }
| { kind: "issue"; issue: GitHubIssue; preset: TaskPreset };
export const PR_TASK_PRESETS: TaskPreset[] = [
{
id: "review",
label: "Review",
hint: "Read the diff, flag issues",
icon: IconEye,
prompt: ({ url }) =>
`Review the pull request at ${url}. Provide feedback on code quality, correctness, and suggest improvements.`,
},
{
id: "address_feedback",
label: "Address feedback",
hint: "Apply review comments",
icon: IconMessageDots,
prompt: ({ url }) =>
`Address the review feedback on the pull request at ${url}. Make the requested changes and push them.`,
},
{
id: "fix_ci",
label: "Fix CI",
hint: "Diagnose failing checks",
icon: IconTool,
prompt: ({ url }) =>
`Investigate and fix the CI failures on the pull request at ${url}. Run the failing checks locally, diagnose, and push fixes.`,
},
];
export const ISSUE_TASK_PRESETS: TaskPreset[] = [
{
id: "implement",
label: "Implement",
hint: "Build and open a PR",
icon: IconCode,
prompt: ({ url, title }) =>
`Implement the changes described in the GitHub issue at ${url} (title: "${title}"). Open a pull request when complete.`,
},
{
id: "investigate",
label: "Investigate",
hint: "Find the root cause",
icon: IconSearch,
prompt: ({ url, title }) =>
`Investigate the GitHub issue at ${url} (title: "${title}"). Identify root cause and summarize findings.`,
},
{
id: "reproduce",
label: "Reproduce",
hint: "Document repro steps",
icon: IconBug,
prompt: ({ url, title }) =>
`Reproduce the bug described in the GitHub issue at ${url} (title: "${title}"). Document the reproduction steps.`,
},
];
type DialogState = {
title: string;
description: string;
repositoryId?: string;
branch?: string;
githubUrl?: string;
};
function matchRepo(repos: Repository[], owner: string, name: string): Repository | undefined {
return repos.find(
(r) =>
(r.provider_owner || "").toLowerCase() === owner.toLowerCase() &&
(r.provider_name || "").toLowerCase() === name.toLowerCase(),
);
}
function extractPayload(payload: LaunchPayload) {
if (payload.kind === "pr") {
return {
url: payload.pr.html_url,
title: payload.pr.title,
owner: payload.pr.repo_owner,
name: payload.pr.repo_name,
branch: payload.pr.head_branch,
};
}
return {
url: payload.issue.html_url,
title: payload.issue.title,
owner: payload.issue.repo_owner,
name: payload.issue.repo_name,
branch: undefined as string | undefined,
};
}
function buildDialogState(payload: LaunchPayload, repositories: Repository[]): DialogState {
const data = extractPayload(payload);
const repo = matchRepo(repositories, data.owner, data.name);
const description = payload.preset.prompt({ url: data.url, title: data.title });
const title = `${payload.preset.label}: ${data.title}`;
if (repo) {
return { title, description, repositoryId: repo.id, branch: data.branch };
}
return {
title,
description,
githubUrl: `github.com/${data.owner}/${data.name}`,
branch: data.branch,
};
}
type QuickTaskLauncherProps = {
workspaceId: string | null;
workflows: Workflow[];
steps: WorkflowStep[];
repositories: Repository[];
payload: LaunchPayload | null;
onClose: () => void;
};
export function QuickTaskLauncher({
workspaceId,
workflows,
steps,
repositories,
payload,
onClose,
}: QuickTaskLauncherProps) {
const router = useRouter();
const defaultWorkflow = workflows[0];
const sortedStepsForWorkflow = useMemo(
() =>
steps
.filter((s) => s.workflow_id === defaultWorkflow?.id)
.sort((a, b) => a.position - b.position),
[steps, defaultWorkflow],
);
const defaultStep = sortedStepsForWorkflow[0];
const stepsForWorkflow = useMemo(
() => sortedStepsForWorkflow.map((s) => ({ id: s.id, title: s.name, events: s.events })),
[sortedStepsForWorkflow],
);
const dialog = useMemo(
() => (payload ? buildDialogState(payload, repositories) : null),
[payload, repositories],
);
const handleOpenChange = (open: boolean) => {
if (!open) onClose();
};
const handleSuccess = (task: Task) => {
onClose();
router.push(`/t/${task.id}`);
};
if (!workspaceId || !defaultWorkflow || !defaultStep || !dialog) return null;
return (
<TaskCreateDialog
open={true}
onOpenChange={handleOpenChange}
mode="create"
workspaceId={workspaceId}
workflowId={defaultWorkflow.id}
defaultStepId={defaultStep.id}
steps={stepsForWorkflow}
initialValues={{
title: dialog.title,
description: dialog.description,
repositoryId: dialog.repositoryId,
branch: dialog.branch,
githubUrl: dialog.githubUrl,
}}
onSuccess={handleSuccess}
/>
);
}