diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index 9a0195aa5..13b395ab5 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -57,7 +57,7 @@ vi.mock('./rate-limit', () => ({ noteRateLimitSpend: noteRateLimitSpendMock })) -import { listWorkItems, _resetOwnerRepoCache } from './client' +import { countWorkItems, listWorkItems, _resetOwnerRepoCache } from './client' describe('listWorkItems', () => { beforeEach(() => { @@ -263,6 +263,135 @@ describe('listWorkItems', () => { ]) }) + it('routes merged queries to PR search only and maps MERGED PR state', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 8, + title: 'Merged work', + state: 'MERGED', + url: 'https://github.com/acme/widgets/pull/8', + labels: [], + updatedAt: '2026-03-31T00:00:00Z', + author: { login: 'octocat' }, + isDraft: false, + headRefName: 'feature/merged', + headRefOid: 'head-8', + baseRefName: 'main' + } + ]) + }) + + const { items } = await listWorkItems('/repo-root', 10, 'is:merged') + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(ghExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'pr', + 'list', + '--limit', + '10', + '--json', + 'number,title,state,url,labels,updatedAt,author,isDraft,headRefName,baseRefName,headRefOid,headRepositoryOwner,reviewRequests', + '--repo', + 'acme/widgets', + '--state', + 'merged' + ], + { cwd: '/repo-root' } + ) + expect(items).toMatchObject([ + { + id: 'pr:8', + type: 'pr', + number: 8, + state: 'merged' + } + ]) + }) + + it('passes state:all through to gh instead of using the default open state', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) + + await listWorkItems('/repo-root', 10, 'is:pr state:all') + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(expect.arrayContaining(['--state', 'all']), { + cwd: '/repo-root' + }) + }) + + it('excludes merged PRs from closed PR searches', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 9, + title: 'Closed without merge', + state: 'CLOSED', + url: 'https://github.com/acme/widgets/pull/9', + labels: [], + updatedAt: '2026-04-01T00:00:00Z', + author: { login: 'octocat' }, + isDraft: false, + headRefName: 'feature/closed', + headRefOid: 'head-9', + baseRefName: 'main' + }, + { + number: 8, + title: 'Merged work', + state: 'MERGED', + url: 'https://github.com/acme/widgets/pull/8', + labels: [], + updatedAt: '2026-03-31T00:00:00Z', + author: { login: 'octocat' }, + isDraft: false, + headRefName: 'feature/merged', + headRefOid: 'head-8', + baseRefName: 'main' + } + ]) + }) + + const { items } = await listWorkItems('/repo-root', 10, 'is:pr is:closed') + + expect(ghExecFileAsyncMock).toHaveBeenCalledWith( + expect.arrayContaining(['--state', 'closed', '--search', '-is:merged']), + { cwd: '/repo-root' } + ) + expect(items).toMatchObject([{ id: 'pr:9', type: 'pr', state: 'closed' }]) + }) + + it('quotes spaced label qualifiers when counting search results', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '12' }) + + const count = await countWorkItems('/repo-root', 'is:pr label:"needs review"') + + const apiPath = ghExecFileAsyncMock.mock.calls[0][0][3] as string + expect(count).toBe(12) + expect(decodeURIComponent(apiPath)).toContain('label:"needs review"') + }) + + it('does not add the merged exclusion to issue-only closed count queries', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '4' }) + + await countWorkItems('/repo-root', 'is:issue is:closed') + + const apiPath = decodeURIComponent(ghExecFileAsyncMock.mock.calls[0][0][3] as string) + expect(apiPath).toContain('is:issue is:closed') + expect(apiPath).not.toContain('-is:merged') + }) + it('passes review-requested as a --search qualifier (gh CLI has no dedicated flag)', async () => { getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 0a4126379..db0ee90da 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -588,13 +588,13 @@ function mapPullRequestWorkItem( number: Number(item.number), title: String(item.title ?? ''), state: - state === 'closed' - ? item.merged_at || item.mergedAt - ? 'merged' - : 'closed' - : item.isDraft || item.draft - ? 'draft' - : 'open', + state === 'merged' || item.merged_at || item.mergedAt + ? 'merged' + : state === 'closed' + ? 'closed' + : item.isDraft || item.draft + ? 'draft' + : 'open', url: String(item.html_url ?? item.url ?? ''), labels: Array.isArray(item.labels) ? item.labels @@ -718,14 +718,13 @@ function buildWorkItemListArgs(args: { out.push('--repo', `${ownerRepo.owner}/${ownerRepo.repo}`) } - const state = query.state - if (state && !(kind === 'issue' && state === 'merged')) { - out.push('--state', state === 'all' ? 'all' : state) - } - - if (kind === 'pr' && query.state === 'merged') { - out.push('--state', 'merged') + if (query.state) { + out.push('--state', query.state) } + // Why: GitHub considers merged PRs as "closed". When the user filters for + // closed-only, exclude merged PRs via the search predicate so the displayed + // and counted results match the user's intent. + const excludeMergedFromClosed = kind === 'pr' && query.state === 'closed' if (query.assignee) { out.push('--assignee', query.assignee) @@ -746,6 +745,9 @@ function buildWorkItemListArgs(args: { } const searchParts: string[] = [] + if (excludeMergedFromClosed) { + searchParts.push('-is:merged') + } // Why: cursor-based pagination. GitHub search supports updated: { const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId)) - const issueScope = query.scope !== 'pr' + const hasPrOnlyFilter = + query.state === 'merged' || + query.draft || + query.reviewRequested !== null || + query.reviewedBy !== null + const issueScope = query.scope !== 'pr' && !hasPrOnlyFilter const prScope = query.scope !== 'issue' // Why: run the issue and PR fetches in parallel but surface the @@ -985,9 +992,13 @@ async function listQueriedWorkItems( }) try { const { stdout } = await ghExecFileAsync(args, ghOptions) - return (JSON.parse(stdout) as Record[]).map((item) => + const mapped = (JSON.parse(stdout) as Record[]).map((item) => mapPullRequestWorkItem(item, prOwnerRepo) ) + if (query.state === 'closed') { + return mapped.filter((item) => item.state !== 'merged') + } + return mapped } catch (err) { console.warn('listQueriedWorkItems PRs partial failure:', err) return [] @@ -1068,7 +1079,12 @@ function buildSearchQueryString( if (query.state === 'open') { parts.push('is:open') } else if (query.state === 'closed') { + // Why: GitHub search treats merged PRs as closed. Exclude merged so the + // "Closed" filter actually means closed-without-merge. parts.push('is:closed') + if (query.scope !== 'issue') { + parts.push('-is:merged') + } } else if (query.state === 'merged') { parts.push('is:merged') } @@ -1076,19 +1092,19 @@ function buildSearchQueryString( parts.push('draft:true') } if (query.assignee) { - parts.push(`assignee:${query.assignee}`) + parts.push(`assignee:${quoteGitHubSearchValue(query.assignee)}`) } if (query.author) { - parts.push(`author:${query.author}`) + parts.push(`author:${quoteGitHubSearchValue(query.author)}`) } if (query.reviewRequested) { - parts.push(`review-requested:${query.reviewRequested}`) + parts.push(`review-requested:${quoteGitHubSearchValue(query.reviewRequested)}`) } if (query.reviewedBy) { - parts.push(`reviewed-by:${query.reviewedBy}`) + parts.push(`reviewed-by:${quoteGitHubSearchValue(query.reviewedBy)}`) } for (const label of query.labels) { - parts.push(`label:${label}`) + parts.push(`label:${quoteGitHubSearchValue(label)}`) } if (query.freeText) { parts.push(query.freeText) @@ -1096,6 +1112,10 @@ function buildSearchQueryString( return parts.join(' ') } +function quoteGitHubSearchValue(value: string): string { + return /\s/.test(value) ? `"${value.replaceAll('"', '\\"')}"` : value +} + async function countWorkItemsForQuery( repoPath: string, ownerRepo: OwnerRepo, diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 3ae3bbf70..669bdec3c 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -302,6 +302,21 @@ min-height: 28px; } +/* Thicker variant for dense data tables where the default 6px-thumb is hard to grab. */ +.scrollbar-sleek-lg { + scrollbar-width: auto; +} + +.scrollbar-sleek-lg::-webkit-scrollbar { + width: 16px; + height: 16px; +} + +.scrollbar-sleek-lg::-webkit-scrollbar-thumb { + border-width: 3px; + min-height: 36px; +} + .scrollbar-sleek::-webkit-scrollbar-thumb:hover { background-color: color-mix(in srgb, var(--muted-foreground, #737373) 48%, transparent); } diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 0e20ac053..fcdc7cdb8 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -362,15 +362,15 @@ function getStateTone(item: GitHubWorkItem): string { } function getPRMergeTooltip(item: GitHubWorkItem): string { - if (item.mergeable === undefined && item.mergeStateStatus === undefined) { - return 'Merge status has not loaded yet' - } if (item.state === 'merged') { return 'This pull request is already merged' } if (item.state === 'closed') { return 'This pull request is closed' } + if (item.mergeable === undefined && item.mergeStateStatus === undefined) { + return 'Merge status is unavailable for this PR' + } if (item.mergeable === 'CONFLICTING') { return 'GitHub reports merge conflicts' } diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index 5285f725e..23dd8e518 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -87,7 +87,8 @@ import { getLinearStateMarkerStyle, getLinearStatePillStyle } from '@/components/linear-state-pill-style' -import { stripRepoQualifiers } from '../../../shared/task-query' +import { parseTaskQuery, stripRepoQualifiers, withQualifier } from '../../../shared/task-query' +import PRFilterDropdowns, { type PRFilterChange } from '@/components/github/PRFilterDropdowns' import { parseGitHubIssueOrPRLink } from '@/lib/github-links' import { useRepoAssigneesBySlug } from '@/hooks/useGitHubSlugMetadata' import GitHubItemDialog, { type ItemDialogTab } from '@/components/GitHubItemDialog' @@ -160,6 +161,21 @@ type TaskQueryPreset = { } type GitHubTaskKind = 'issues' | 'prs' +const ISSUE_TASK_QUERY_PRESETS: TaskQueryPreset[] = [ + { id: 'issues', label: 'Open', query: getTaskPresetQuery('issues') }, + { id: 'my-issues', label: 'Assigned to me', query: getTaskPresetQuery('my-issues') } +] + +const PR_TASK_QUERY_PRESETS: TaskQueryPreset[] = [ + { id: 'prs', label: 'Open', query: getTaskPresetQuery('prs') }, + { id: 'my-prs', label: 'Mine', query: getTaskPresetQuery('my-prs') }, + { id: 'review', label: 'Needs review', query: getTaskPresetQuery('review') } +] + +function getGitHubTaskKindPresets(kind: GitHubTaskKind): TaskQueryPreset[] { + return kind === 'prs' ? PR_TASK_QUERY_PRESETS : ISSUE_TASK_QUERY_PRESETS +} + function getRuntimeTargetForRepoId(repoId: string | null | undefined) { if (!repoId) { return null @@ -205,17 +221,6 @@ const SOURCE_OPTIONS: SourceOption[] = [ } ] -const ISSUE_TASK_QUERY_PRESETS: TaskQueryPreset[] = [ - { id: 'issues', label: 'Open', query: getTaskPresetQuery('issues') }, - { id: 'my-issues', label: 'Assigned to me', query: getTaskPresetQuery('my-issues') } -] - -const PR_TASK_QUERY_PRESETS: TaskQueryPreset[] = [ - { id: 'prs', label: 'Open', query: getTaskPresetQuery('prs') }, - { id: 'my-prs', label: 'Mine', query: getTaskPresetQuery('my-prs') }, - { id: 'review', label: 'Needs review', query: getTaskPresetQuery('review') } -] - type LinearPresetId = 'assigned' | 'created' | 'all' | 'completed' type LinearPreset = { id: LinearPresetId; label: string } @@ -233,18 +238,24 @@ const PR_CHECKS_EAGER_PREFETCH_LIMIT = 20 const GITHUB_TASK_GRID_CLASS = 'min-w-[860px] grid-cols-[72px_minmax(260px,2fr)_minmax(130px,0.8fr)_100px_92px_158px]' const GITHUB_PR_TASK_GRID_CLASS = - 'min-w-[1270px] grid-cols-[72px_minmax(260px,2fr)_minmax(130px,0.8fr)_100px_132px_128px_132px_92px_158px]' + 'min-w-[1170px] grid-cols-[72px_minmax(260px,2fr)_minmax(130px,0.8fr)_132px_128px_132px_92px_158px]' const GITHUB_TASK_ROW_SURFACE_CLASS = '[background:color-mix(in_srgb,var(--muted)_50%,var(--background))]' const GITHUB_TASK_ROW_HOVER_SURFACE_CLASS = 'group-hover/github-task-row:[background:color-mix(in_srgb,var(--muted)_70%,var(--background))]' -const GITHUB_TASK_STICKY_ID_HEADER_CLASS = cn('sticky left-3 z-30', GITHUB_TASK_ROW_SURFACE_CLASS) +// Why: the row's px-3 left padding leaves a 12px gap between the scroll-viewport +// edge and the sticky ID column; without a covering ::before, scrolled cell text +// bleeds through that strip. Same trick as the title column for its 8px gap. +const GITHUB_TASK_STICKY_ID_HEADER_CLASS = cn( + 'sticky left-3 z-30 before:absolute before:-left-3 before:top-0 before:bottom-0 before:w-3 before:bg-inherit', + GITHUB_TASK_ROW_SURFACE_CLASS +) const GITHUB_TASK_STICKY_TITLE_HEADER_CLASS = cn( 'sticky left-[92px] z-30 border-r border-border/50 before:absolute before:-left-2 before:top-0 before:bottom-0 before:w-2 before:bg-inherit', GITHUB_TASK_ROW_SURFACE_CLASS ) const GITHUB_TASK_STICKY_ID_CELL_CLASS = cn( - 'sticky left-3 z-20 flex items-center', + 'sticky left-3 z-20 flex items-center before:absolute before:-left-3 before:top-0 before:bottom-0 before:w-3 before:bg-inherit', GITHUB_TASK_ROW_SURFACE_CLASS, GITHUB_TASK_ROW_HOVER_SURFACE_CLASS ) @@ -266,8 +277,14 @@ function isPRFocusedTaskView(preset: TaskViewPresetId | null, query: string): bo if (preset === 'prs' || preset === 'my-prs' || preset === 'review') { return true } - const normalized = query.toLowerCase() - return /\bis:pr\b/.test(normalized) && !/\bis:issue\b/.test(normalized) + const parsed = parseTaskQuery(query) + return ( + parsed.scope === 'pr' || + parsed.state === 'merged' || + parsed.draft || + parsed.reviewRequested !== null || + parsed.reviewedBy !== null + ) } function normalizeGitHubTaskPreset(preset: TaskViewPresetId | null | undefined): TaskViewPresetId { @@ -284,19 +301,17 @@ function getDefaultPresetForGitHubTaskKind(kind: GitHubTaskKind): TaskViewPreset return kind === 'prs' ? 'prs' : 'issues' } -function getGitHubTaskKindPresets(kind: GitHubTaskKind): TaskQueryPreset[] { - return kind === 'prs' ? PR_TASK_QUERY_PRESETS : ISSUE_TASK_QUERY_PRESETS -} - function scopeGitHubTaskSearch(query: string, kind: GitHubTaskKind): string { const trimmed = query.trim() if (!trimmed) { return getTaskPresetQuery(getDefaultPresetForGitHubTaskKind(kind)) } - if (/\bis:(?:issue|pr)\b/i.test(trimmed)) { + if (/\bis:(?:issue|pr|pull-request)\b/i.test(trimmed)) { return trimmed } - return `${kind === 'prs' ? 'is:pr' : 'is:issue'} ${trimmed}` + const parsed = parseTaskQuery(trimmed) + const inferredKind = parsed.scope === 'pr' ? 'prs' : parsed.scope === 'issue' ? 'issues' : kind + return `${inferredKind === 'prs' ? 'is:pr' : 'is:issue'} ${trimmed}` } // Why: Intl.RelativeTimeFormat allocation is non-trivial, and previously we @@ -326,26 +341,6 @@ function formatRelativeTime(input: string): string { return relativeTimeFormatter.format(diffDays, 'day') } -function getTaskStatusLabel(item: GitHubWorkItem): string { - if (item.type === 'issue') { - return 'Open' - } - if (item.state === 'draft') { - return 'Draft' - } - return 'Ready' -} - -function getTaskStatusTone(item: GitHubWorkItem): string { - if (item.type === 'issue') { - return 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-200' - } - if (item.state === 'draft') { - return 'border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-300' - } - return 'border-cyan-500/30 bg-cyan-500/10 text-cyan-700 dark:text-cyan-200' -} - // Why: Linear encodes priority as an integer (0–4). Map to human-readable // labels so the table column is scannable without memorising the scale. const LINEAR_PRIORITY_LABELS: Record = { @@ -737,13 +732,8 @@ function GHStatusCell({ if (item.type !== 'issue' || !repo) { return ( - - {getTaskStatusLabel(item)} + + Open ) } @@ -899,15 +889,15 @@ function sameOptionalGitHubOwnerRepo( } function getMergeLabel(item: GitHubWorkItem): string { - if (item.mergeable === undefined && item.mergeStateStatus === undefined) { - return 'Merge' - } if (item.state === 'merged') { return 'Merged' } if (item.state === 'closed') { return 'Closed' } + if (item.mergeable === undefined && item.mergeStateStatus === undefined) { + return 'Merge' + } if (item.mergeable === 'CONFLICTING') { return 'Conflicts' } @@ -937,15 +927,15 @@ function getMergeTone(item: GitHubWorkItem): string { } function getMergeTooltip(item: GitHubWorkItem): string { - if (item.mergeable === undefined && item.mergeStateStatus === undefined) { - return 'Merge status has not loaded yet' - } if (item.state === 'merged') { return 'This pull request is already merged' } if (item.state === 'closed') { return 'This pull request is closed' } + if (item.mergeable === undefined && item.mergeStateStatus === undefined) { + return 'Merge status is unavailable for this PR' + } if (item.mergeable === 'CONFLICTING') { return 'GitHub reports merge conflicts' } @@ -1203,8 +1193,11 @@ function PRReviewCell({ if (selectedReviewerLogins.has(reviewer.login.toLowerCase())) { return } + // Close the popover immediately so the UI feels responsive; the GitHub + // request runs in the background and toasts on completion. + setOpen(false) + setReviewerInput('') await handleRequestReview([reviewer.login]) - requestAnimationFrame(() => reviewerInputRef.current?.focus()) } const handleReviewerPickerOpenChange = (nextOpen: boolean): void => { @@ -1910,6 +1903,7 @@ export default function TaskPage(): React.JSX.Element { ) const [tasksLoading, setTasksLoading] = useState(false) const [tasksRefreshing, setTasksRefreshing] = useState(false) + const [tasksFiltering, setTasksFiltering] = useState(false) const [tasksError, setTasksError] = useState(null) // Why: per-repo failure count surfaced through the "N of M" banner. IPC-level // rejections populate tasksError instead — the two are mutually exclusive so @@ -2727,6 +2721,37 @@ export default function TaskPage(): React.JSX.Element { () => applyTypeFilter(currentPageItems), [applyTypeFilter, currentPageItems] ) + const showGitHubTaskSkeletons = tasksFiltering || (tasksLoading && filteredWorkItems.length === 0) + const loadedGitHubAuthorLogins = useMemo(() => { + const seen = new Set() + const logins: string[] = [] + for (const page of pages) { + for (const item of page) { + if ( + !item.author || + (activeGithubTaskKind === 'prs' ? item.type !== 'pr' : item.type !== 'issue') + ) { + continue + } + const key = item.author.toLowerCase() + if (seen.has(key)) { + continue + } + seen.add(key) + logins.push(item.author) + } + } + return logins + }, [activeGithubTaskKind, pages]) + const primaryGithubFilterSlug = useMemo(() => { + for (const state of perRepoSourceState) { + const source = activeGithubTaskKind === 'prs' ? state.sources?.prs : state.sources?.issues + if (source) { + return source + } + } + return null + }, [activeGithubTaskKind, perRepoSourceState]) const showPRManagementColumns = activeGithubTaskKind === 'prs' const githubTaskGridClass = showPRManagementColumns ? GITHUB_PR_TASK_GRID_CLASS @@ -2774,13 +2799,28 @@ export default function TaskPage(): React.JSX.Element { } }, [ensurePRChecksLoaded, filteredWorkItems, githubMode, showPRManagementColumns, taskSource]) - // Why: totalPages is derived from the search API count when available, - // so the pagination bar shows the full range (with ellipsis) upfront. - // Falls back to the loaded page count when the count hasn't returned yet. + // Why: each page is bounded by both the per-repo fetch budget (so a single + // repo can yield at most PER_REPO_FETCH_LIMIT rows per page) and the + // post-merge display cap. Dividing the total by CROSS_REPO_DISPLAY_LIMIT + // alone under-counts pages when the per-repo budget is the tighter bound — + // e.g. one repo with 60 open PRs yielded 36 rows on page 0 and ceil(60/100) + // = 1 total pages, hiding the pager entirely. + const effectivePageSize = Math.max( + 1, + Math.min(PER_REPO_FETCH_LIMIT * Math.max(1, selectedRepos.length), CROSS_REPO_DISPLAY_LIMIT) + ) + // Why: if the search-API count is unavailable (rate-limited, transient + // failure — `countWorkItemsAcrossRepos` swallows errors and returns 0), + // infer there's at least one more page whenever the last loaded page + // filled to the per-page capacity. Otherwise pagination would silently + // hide and trap the user on page 0 with no way to advance. + const lastPageFull = (pages.at(-1)?.length ?? 0) >= effectivePageSize const totalPages = - totalItemCount !== null - ? Math.max(pages.length, Math.ceil(totalItemCount / CROSS_REPO_DISPLAY_LIMIT)) - : pages.length + totalItemCount && totalItemCount > 0 + ? Math.max(pages.length, Math.ceil(totalItemCount / effectivePageSize)) + : lastPageFull + ? pages.length + 1 + : pages.length // Why: loads the next page using the oldest item's updatedAt as a cursor. // When targetPage is provided (from clicking a numbered page beyond loaded @@ -2844,10 +2884,14 @@ export default function TaskPage(): React.JSX.Element { return } const timeout = window.setTimeout(() => { - setAppliedTaskSearch(scopeGitHubTaskSearch(taskSearchInput, activeGithubTaskKind)) + const scoped = scopeGitHubTaskSearch(taskSearchInput, activeGithubTaskKind) + if (scoped !== appliedTaskSearch) { + setTasksFiltering(true) + } + setAppliedTaskSearch(scoped) }, TASK_SEARCH_DEBOUNCE_MS) return () => window.clearTimeout(timeout) - }, [activeGithubTaskKind, taskSearchInput, taskResumeApplied]) + }, [activeGithubTaskKind, appliedTaskSearch, taskSearchInput, taskResumeApplied]) useEffect(() => { if (!taskResumeApplied) { @@ -2881,11 +2925,13 @@ export default function TaskPage(): React.JSX.Element { if (taskSource !== 'github' || githubMode !== 'items') { setRetryingRepoPaths(new Set()) setTasksRefreshing(false) + setTasksFiltering(false) return } if (selectedRepos.length === 0) { setRetryingRepoPaths(new Set()) setTasksRefreshing(false) + setTasksFiltering(false) return } // unreachable — multi-combobox forbids empty @@ -2996,6 +3042,7 @@ export default function TaskPage(): React.JSX.Element { setFailedCount(failed) setTasksLoading(false) setTasksRefreshing(false) + setTasksFiltering(false) }) .catch((err) => { // Why: fetchWorkItemsAcrossRepos swallows per-repo failures, so a @@ -3023,6 +3070,7 @@ export default function TaskPage(): React.JSX.Element { setFailedCount(0) // the per-repo banner would be misleading next to tasksError setTasksLoading(false) setTasksRefreshing(false) + setTasksFiltering(false) }) // Why: fire-and-forget count query in parallel with the items fetch. @@ -3055,12 +3103,66 @@ export default function TaskPage(): React.JSX.Element { taskResumeApplied ]) + const applyPRFilterChange = useCallback( + (change: PRFilterChange): void => { + let next = scopeGitHubTaskSearch(taskSearchInput, activeGithubTaskKind) + // Why: each filter dropdown contributes an independent qualifier patch. + // `withQualifier` round-trips through parseTaskQuery so prior filters and + // free-text are preserved. + if ('author' in change) { + next = withQualifier(next, 'author', change.author ?? null) + } + if ('assignee' in change) { + next = withQualifier(next, 'assignee', change.assignee ?? null) + } + if ('labels' in change) { + next = withQualifier(next, 'labels', change.labels ?? []) + } + if ('state' in change && change.state) { + next = withQualifier(next, 'state', change.state) + if (change.state !== 'open') { + next = withQualifier(next, 'draft', null) + } + } + if ('draft' in change) { + next = withQualifier(next, 'draft', change.draft ? 'true' : 'false') + } + if ('reviewer' in change) { + // Why: the two reviewer qualifiers (review-requested vs reviewed-by) are + // mutually exclusive in the PR-list UX — clear the other axis whenever + // one is set so the chip's visible state matches the actual query. + const reviewer = change.reviewer ?? null + if (reviewer === null) { + next = withQualifier(next, 'reviewRequested', null) + next = withQualifier(next, 'reviewedBy', null) + } else if (reviewer.kind === 'requested') { + next = withQualifier(next, 'reviewedBy', null) + next = withQualifier(next, 'reviewRequested', reviewer.login) + } else { + next = withQualifier(next, 'reviewRequested', null) + next = withQualifier(next, 'reviewedBy', reviewer.login) + } + } + setTaskSearchInput(next) + setAppliedTaskSearch(next) + setActiveTaskPreset(null) + setTaskResumeState({ githubItemsPreset: null, githubItemsQuery: next }) + // Why: filter changes replace the meaning of every row. Showing stale + // rows while the filtered query resolves reads like the filter did + // nothing, so render the same skeleton used for an uncached initial load. + setTasksFiltering(true) + setTaskRefreshNonce((current) => current + 1) + }, + [activeGithubTaskKind, setTaskResumeState, taskSearchInput] + ) + const handleApplyTaskSearch = useCallback((): void => { const scoped = scopeGitHubTaskSearch(taskSearchInput, activeGithubTaskKind) setTaskSearchInput(scoped) setAppliedTaskSearch(scoped) setActiveTaskPreset(null) setTaskResumeState({ githubItemsPreset: null, githubItemsQuery: scoped }) + setTasksFiltering(true) setTaskRefreshNonce((current) => current + 1) }, [activeGithubTaskKind, setTaskResumeState, taskSearchInput]) @@ -3093,6 +3195,7 @@ export default function TaskPage(): React.JSX.Element { githubItemsPreset: preset, githubItemsQuery: query }) + setTasksFiltering(true) setTaskRefreshNonce((current) => current + 1) }, [setTaskResumeState] @@ -3340,7 +3443,7 @@ export default function TaskPage(): React.JSX.Element { setSelectedLinearIssue ]) - const githubTasksBusy = tasksLoading || tasksRefreshing + const githubTasksBusy = tasksLoading || tasksRefreshing || tasksFiltering useEffect(() => { // Why: when a modal is open, let it own Esc dismissal. @@ -3784,7 +3887,7 @@ export default function TaskPage(): React.JSX.Element { inert — hide it to avoid suggesting it does something. */} {githubMode !== 'project' && ( -
+
)} @@ -3810,95 +3913,49 @@ export default function TaskPage(): React.JSX.Element { {taskSource === 'github' && githubMode === 'items' ? (
-
-
-
- {getGitHubTaskKindPresets(activeGithubTaskKind).map((option) => { - const active = activeTaskPreset === option.id - return ( - - ) - })} -
-
- -
- - - - - - New GitHub issue - - - - - - - - {githubTasksBusy ? 'Refreshing GitHub work…' : 'Refresh GitHub work'} - - -
+
+ {getGitHubTaskKindPresets(activeGithubTaskKind).map((option) => { + const active = activeTaskPreset === option.id + return ( + + ) + })}
- -
+
+ applyPRFilterChange(change)} + />
) : null}
+
+ + + + + + New GitHub issue + + + + + + + + {githubTasksBusy ? 'Refreshing GitHub work…' : 'Refresh GitHub work'} + + +
{(() => { @@ -4220,7 +4325,7 @@ export default function TaskPage(): React.JSX.Element { ) : taskSource === 'github' ? (
ID Title / Context Branch - Status {showPRManagementColumns ? ( <> Reviewers Checks Merge - ) : null} + ) : ( + Status + )} Updated
@@ -4305,13 +4411,13 @@ export default function TaskPage(): React.JSX.Element { ) })} - {tasksLoading && filteredWorkItems.length === 0 ? ( - // Why: shimmer skeleton stands in for the first ~3 rows while - // the initial fetch is in flight, so the card is never empty - // or collapsed during load. Only shown when we have no cached - // items — on revalidate we keep the stale list visible. + {showGitHubTaskSkeletons ? ( + // Why: render enough shimmer rows to fill a typical viewport + // so the table doesn't visibly grow when results land. A + // 3-row stub jumps to ~30 real rows; matching the steady- + // state height keeps layout stable across the load.
- {Array.from({ length: 3 }).map((_, i) => ( + {Array.from({ length: 12 }).map((_, i) => (
@@ -4323,9 +4429,6 @@ export default function TaskPage(): React.JSX.Element {
-
-
-
{showPRManagementColumns ? ( <>
@@ -4338,7 +4441,11 @@ export default function TaskPage(): React.JSX.Element {
- ) : null} + ) : ( +
+
+
+ )}
@@ -4356,7 +4463,7 @@ export default function TaskPage(): React.JSX.Element { "No matching GitHub work" next to "Couldn't load issues from X/Y" is contradictory and misleads the user into thinking they typed the wrong query. */} - {!tasksLoading && + {!showGitHubTaskSkeletons && filteredWorkItems.length === 0 && !tasksError && failedCount === 0 && @@ -4370,179 +4477,200 @@ export default function TaskPage(): React.JSX.Element { ) : null}
- {filteredWorkItems.map((item) => { - const itemRepo = repoMap.get(item.repoId) ?? null - return ( - // Why: the row is a clickable container rather than a - // + + + + + e.stopPropagation()}> + window.api.shell.openUrl(item.url)} + > + + Open in browser + + + +
- -
- -
- - {showPRManagementColumns ? ( - <> -
- -
- -
- setDialogWorkItem(item, 'checks')} - onLoadChecks={() => ensurePRChecksLoaded(item)} - /> -
- -
- setTaskRefreshNonce((current) => current + 1)} - /> -
- - ) : null} - - - -
- {formatRelativeTime(item.updatedAt)} -
-
- - {new Date(item.updatedAt).toLocaleString()} - -
- -
- - - - - - e.stopPropagation()}> - window.api.shell.openUrl(item.url)}> - - Open in browser - - - -
-
- ) - })} + ) + })}
+
- {/* Pagination controls — GitHub-style with ellipsis */} - {filteredWorkItems.length > 0 && !tasksLoading && totalPages > 1 ? ( + {/* Why: pagination sits outside the scroll container so it + remains pinned at the bottom of the panel rather than + hiding below the last row inside the scrolling region. */} + {filteredWorkItems.length > 0 && !showGitHubTaskSkeletons && totalPages > 1 ? ( +
- ) : null} -
+
+ ) : null}
) : taskSource === 'gitlab' && gitlabView === 'todos' ? (
@@ -4573,7 +4701,7 @@ export default function TaskPage(): React.JSX.Element { > {gitlabTodosLoading && gitlabTodos.length === 0 ? (
- {Array.from({ length: 3 }).map((_, i) => ( + {Array.from({ length: 12 }).map((_, i) => (
- {Array.from({ length: 3 }).map((_, i) => ( + {Array.from({ length: 12 }).map((_, i) => (
- {Array.from({ length: 6 }).map((_, i) => ( + {Array.from({ length: 12 }).map((_, i) => (
@@ -5245,7 +5375,7 @@ export default function TaskPage(): React.JSX.Element { - Start workspace + Start diff --git a/src/renderer/src/components/github-project/ProjectCell.tsx b/src/renderer/src/components/github-project/ProjectCell.tsx index 2ecae59ac..d38ca6d08 100644 --- a/src/renderer/src/components/github-project/ProjectCell.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.tsx @@ -779,7 +779,7 @@ function AssigneesCell({ 'flex h-full w-full flex-wrap items-center gap-1 cursor-pointer px-1 text-xs text-muted-foreground hover:text-foreground' )} > - {labelContent ?? } + {labelContent ?? } diff --git a/src/renderer/src/components/github-project/ProjectViewWrapper.tsx b/src/renderer/src/components/github-project/ProjectViewWrapper.tsx index d2701f48b..a23fdea3f 100644 --- a/src/renderer/src/components/github-project/ProjectViewWrapper.tsx +++ b/src/renderer/src/components/github-project/ProjectViewWrapper.tsx @@ -5,7 +5,6 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ExternalLink, - Loader, RefreshCw, KanbanSquare, Map as MapIcon, @@ -724,10 +723,7 @@ export default function ProjectViewWrapper(_props: Props = {} as Props): React.J Choose a project to get started.
) : loading && !table ? ( -
- - Loading project view… -
+ ) : error ? ( ) } + +// Why: matches the shape of ProjectViewList's header + rows so the table +// doesn't visibly jump in height when real data lands. A 12-row stub fills +// a typical viewport at the table's min-h-10 row height. +function ProjectTableSkeleton(): React.JSX.Element { + const headerCols = 6 + const bodyCols = 5 + return ( +
+
+
+ {Array.from({ length: headerCols }).map((_, i) => ( +
+ ))} +
+
+
+ {Array.from({ length: 12 }).map((_, i) => ( +
+
+
+
+
+
+
+ ))} +
+
+ ) +} diff --git a/src/renderer/src/components/github/PRFilterDropdowns.tsx b/src/renderer/src/components/github/PRFilterDropdowns.tsx new file mode 100644 index 000000000..49b6f8cae --- /dev/null +++ b/src/renderer/src/components/github/PRFilterDropdowns.tsx @@ -0,0 +1,269 @@ +// Why: GitHub-style PR filter UI. A single "Filters" button opens a popover +// containing Author / Label / Reviewer / Assignee sections, mirroring GitHub's +// own collapsed Filters dropdown so the toolbar stays uncluttered when nothing +// is set. Active filters surface as inline removable pills next to the button. +import React, { useEffect, useMemo, useState } from 'react' +import { ListFilter, X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' +import { cn } from '@/lib/utils' +import { useRepoLabelsBySlug, useRepoAssigneesBySlug } from '@/hooks/useGitHubSlugMetadata' +import { type PickerOption } from '@/components/github/PRFilterPickers' +import { + SectionDetail, + SectionMenu, + type PRFilterChange, + type SectionKey +} from '@/components/github/PRFilterSections' +import type { + GitHubAssignableUser, + GitHubOwnerRepo, + GlobalSettings +} from '../../../../shared/types' +import type { ParsedTaskQuery } from '../../../../shared/task-query' + +type Props = { + parsed: ParsedTaskQuery + kind: 'prs' | 'issues' + authorLogins: string[] + // Why: drive label + assignable-user lookups off the first selected repo. + // Cross-repo filters can't enumerate every repo's labels in one popover — + // GitHub's own PR list scopes the dropdown to a single repo too. + primarySlug: GitHubOwnerRepo | null + settings?: Pick | null + onChange: (change: PRFilterChange) => void +} + +export type { PRFilterChange } from '@/components/github/PRFilterSections' + +function userOptions(users: GitHubAssignableUser[]): PickerOption[] { + return users.map((u) => ({ key: u.login, primary: u.login, secondary: u.name ?? undefined })) +} + +function ActivePill({ + label, + value, + onClear +}: { + label: string + value: string + onClear: () => void +}): React.JSX.Element { + return ( + + {label}: + {value} + + + ) +} + +export default function PRFilterDropdowns({ + parsed, + kind, + authorLogins, + primarySlug, + settings, + onChange +}: Props): React.JSX.Element { + const [openSection, setOpenSection] = useState(null) + const [popoverOpen, setPopoverOpen] = useState(false) + const owner = primarySlug?.owner ?? null + const repo = primarySlug?.repo ?? null + const hasPrimarySlug = popoverOpen && owner !== null && repo !== null + const labelsState = useRepoLabelsBySlug( + popoverOpen ? owner : null, + popoverOpen ? repo : null, + settings + ) + const assigneesState = useRepoAssigneesBySlug( + popoverOpen ? owner : null, + popoverOpen ? repo : null, + undefined, + settings + ) + + // Why: surface @me as a first-class option even though it's not a real + // login — GitHub's search API resolves it server-side to the authenticated + // user, matching the behavior of the built-in "Mine" / "Needs review" presets. + const userOpts = useMemo(() => { + const meOption: PickerOption = { key: '@me', primary: '@me', secondary: 'Current user' } + return [meOption, ...userOptions(hasPrimarySlug ? assigneesState.data : [])] + }, [assigneesState.data, hasPrimarySlug]) + const authorOpts = useMemo(() => { + const options = new Map() + options.set('@me', { key: '@me', primary: '@me', secondary: 'Current user' }) + // Why: the Author filter should reflect actual visible item authors. + // Assignable-user metadata is repo-collaborator scoped and can omit outside + // contributors. + for (const login of authorLogins) { + options.set(login.toLowerCase(), { key: login, primary: login }) + } + if (parsed.author && !options.has(parsed.author.toLowerCase())) { + options.set(parsed.author.toLowerCase(), { key: parsed.author, primary: parsed.author }) + } + return [...options.values()] + }, [authorLogins, parsed.author]) + const labelOpts = useMemo( + () => (hasPrimarySlug ? labelsState.data.map((name) => ({ key: name, primary: name })) : []), + [hasPrimarySlug, labelsState.data] + ) + + const reviewerActive = parsed.reviewRequested ?? parsed.reviewedBy ?? null + const reviewerKind: 'requested' | 'reviewed-by' = parsed.reviewedBy ? 'reviewed-by' : 'requested' + const [reviewerMode, setReviewerMode] = useState<'requested' | 'reviewed-by'>(reviewerKind) + // Why: keep mode in sync if the user types qualifier syntax directly. + useEffect(() => { + setReviewerMode(reviewerKind) + }, [reviewerKind]) + + // Why: treat anything other than the implicit "open" default as an active + // status filter so the user can see (and clear) it via the inline pill. + const statusActive = (parsed.state !== null && parsed.state !== 'open') || parsed.draft + const statusPillValue = ((): string | null => { + const parts: string[] = [] + if (parsed.state === 'closed') { + parts.push('Closed') + } else if (parsed.state === 'merged') { + parts.push('Merged') + } else if (parsed.state === 'all') { + parts.push('Any') + } + if (parsed.draft) { + parts.push('Draft') + } + return parts.length > 0 ? parts.join(' · ') : null + })() + + const activeCount = + (statusActive ? 1 : 0) + + (parsed.author ? 1 : 0) + + (parsed.assignee ? 1 : 0) + + (reviewerActive ? 1 : 0) + + (parsed.labels.length > 0 ? 1 : 0) + + const handleSelect = (change: PRFilterChange): void => { + onChange(change) + setOpenSection(null) + } + + return ( +
+ { + setPopoverOpen(next) + if (!next) { + setOpenSection(null) + } + }} + > + + + + + {openSection === null ? ( + setOpenSection(s)} + onClearAll={ + activeCount > 0 + ? () => { + onChange({ + author: null, + assignee: null, + reviewer: null, + labels: [], + state: 'open', + draft: false + }) + setPopoverOpen(false) + } + : null + } + /> + ) : ( + setOpenSection(null)} + onSelect={handleSelect} + /> + )} + + + {statusPillValue ? ( + onChange({ state: 'open', draft: false })} + /> + ) : null} + {parsed.author ? ( + onChange({ author: null })} + /> + ) : null} + {parsed.labels.length > 0 ? ( + onChange({ labels: [] })} + /> + ) : null} + {reviewerActive ? ( + onChange({ reviewer: null })} + /> + ) : null} + {parsed.assignee ? ( + onChange({ assignee: null })} + /> + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/github/PRFilterPickers.tsx b/src/renderer/src/components/github/PRFilterPickers.tsx new file mode 100644 index 000000000..32aa4042c --- /dev/null +++ b/src/renderer/src/components/github/PRFilterPickers.tsx @@ -0,0 +1,190 @@ +// Why: lower-level pickers used by PRFilterDropdowns. Split out so the parent +// stays under the per-file line cap and so each picker can be tested or reused +// independently of the qualifier-mapping logic. +import React, { useMemo, useState } from 'react' +import { Check } from 'lucide-react' +import { + Command, + CommandEmpty, + CommandInput, + CommandItem, + CommandList +} from '@/components/ui/command' +import { cn } from '@/lib/utils' + +export type PickerOption = { key: string; primary: string; secondary?: string } + +function filterOptions(options: PickerOption[], query: string): PickerOption[] { + const q = query.trim().toLowerCase() + if (!q) { + return options + } + return options.filter( + (o) => o.primary.toLowerCase().includes(q) || (o.secondary ?? '').toLowerCase().includes(q) + ) +} + +export function SingleSelectList({ + options, + activeValue, + loading, + error, + searchPlaceholder, + emptyText, + renderOption, + allowCustomValue, + onSelect +}: { + options: PickerOption[] + activeValue: string | null + loading: boolean + error: string | null + searchPlaceholder: string + emptyText?: string + renderOption?: (opt: PickerOption) => React.ReactNode + // Why: PR authors and reviewers can be external contributors who aren't in + // `listAssignableUsers` (repo collaborators only). Allowing a typed login as + // a fallback lets the user filter by anyone GitHub recognizes. + allowCustomValue?: boolean + onSelect: (value: string | null) => void +}): React.JSX.Element { + const [query, setQuery] = useState('') + const filtered = useMemo(() => filterOptions(options, query), [options, query]) + const trimmed = query.trim() + const showCustom = + allowCustomValue && + trimmed.length > 0 && + !filtered.some((o) => o.key.toLowerCase() === trimmed.toLowerCase()) + const fallback = loading + ? 'Loading…' + : showCustom + ? 'Press Enter to use the typed value.' + : (error ?? emptyText ?? 'No matches') + + return ( + + + + {fallback} + {showCustom ? ( + onSelect(trimmed)} + className="items-center gap-2 px-3 py-1.5 text-xs" + > + Use + {trimmed} + + ) : null} + {activeValue ? ( + onSelect(null)} + className="gap-2 px-3 py-1.5 text-xs text-muted-foreground" + > + Clear + + ) : null} + {filtered.map((opt) => { + const isActive = opt.key === activeValue + return ( + onSelect(isActive ? null : opt.key)} + className="items-center gap-2 px-3 py-1.5 text-xs" + > + + {renderOption ? renderOption(opt) : {opt.primary}} + + ) + })} + + + ) +} + +export function MultiSelectList({ + options, + selected, + loading, + error, + searchPlaceholder, + emptyText, + onChange +}: { + options: PickerOption[] + selected: string[] + loading: boolean + error: string | null + searchPlaceholder: string + emptyText?: string + onChange: (next: string[]) => void +}): React.JSX.Element { + const [query, setQuery] = useState('') + const filtered = useMemo(() => filterOptions(options, query), [options, query]) + const selectedSet = useMemo(() => new Set(selected), [selected]) + const fallback = loading ? 'Loading…' : (error ?? emptyText ?? 'No matches') + + const toggle = (key: string): void => { + const next = new Set(selectedSet) + if (next.has(key)) { + next.delete(key) + } else { + next.add(key) + } + onChange([...next]) + } + + return ( + + + + {fallback} + {selected.length > 0 ? ( + onChange([])} + className="gap-2 px-3 py-1.5 text-xs text-muted-foreground" + > + Clear ({selected.length}) + + ) : null} + {filtered.map((opt) => { + const isActive = selectedSet.has(opt.key) + return ( + toggle(opt.key)} + className="items-center gap-2 px-3 py-1.5 text-xs" + > + + {opt.primary} + + ) + })} + + + ) +} diff --git a/src/renderer/src/components/github/PRFilterSections.tsx b/src/renderer/src/components/github/PRFilterSections.tsx new file mode 100644 index 000000000..890b16791 --- /dev/null +++ b/src/renderer/src/components/github/PRFilterSections.tsx @@ -0,0 +1,327 @@ +import React from 'react' +import { ChevronRight } from 'lucide-react' +import { + MultiSelectList, + SingleSelectList, + type PickerOption +} from '@/components/github/PRFilterPickers' +import { cn } from '@/lib/utils' +import type { ParsedTaskQuery } from '../../../../shared/task-query' + +export type PRFilterChange = { + author?: string | null + assignee?: string | null + reviewer?: { kind: 'requested' | 'reviewed-by'; login: string } | null + labels?: string[] + state?: 'open' | 'closed' | 'merged' | 'all' + draft?: boolean +} + +export type SectionKey = 'status' | 'author' | 'label' | 'reviewer' | 'assignee' + +function statusLabel(parsed: ParsedTaskQuery): string { + const parts: string[] = [] + if (parsed.state === 'open') { + parts.push('Open') + } else if (parsed.state === 'closed') { + parts.push('Closed') + } else if (parsed.state === 'merged') { + parts.push('Merged') + } else if (parsed.state === 'all') { + parts.push('All') + } + if (parsed.draft) { + parts.push('Draft') + } + return parts.join(' · ') +} + +function StatusSection({ + parsed, + kind, + onSelect +}: { + parsed: ParsedTaskQuery + kind: 'prs' | 'issues' + onSelect: (change: PRFilterChange) => void +}): React.JSX.Element { + const states: { key: 'open' | 'closed' | 'merged' | 'all'; label: string }[] = + kind === 'prs' + ? [ + { key: 'open', label: 'Open' }, + { key: 'closed', label: 'Closed' }, + { key: 'merged', label: 'Merged' }, + { key: 'all', label: 'Any state' } + ] + : [ + { key: 'open', label: 'Open' }, + { key: 'closed', label: 'Closed' }, + { key: 'all', label: 'Any state' } + ] + return ( +
+ {states.map((s) => { + const active = parsed.state === s.key + return ( + + ) + })} + {kind !== 'prs' ? null : } +
+ ) +} + +function DraftToggle({ + parsed, + onSelect +}: { + parsed: ParsedTaskQuery + onSelect: (change: PRFilterChange) => void +}): React.JSX.Element { + return ( + <> +
+ + + ) +} + +function UserOptionRow({ option }: { option: PickerOption }): React.JSX.Element { + return ( +
+ {option.primary} + {option.secondary ? ( + {option.secondary} + ) : null} +
+ ) +} + +export function SectionMenu({ + parsed, + kind, + reviewerActive, + reviewerKind, + onPick, + onClearAll +}: { + parsed: ParsedTaskQuery + kind: 'prs' | 'issues' + reviewerActive: string | null + reviewerKind: 'requested' | 'reviewed-by' + onPick: (s: SectionKey) => void + onClearAll: (() => void) | null +}): React.JSX.Element { + const status = statusLabel(parsed) + const rows: { key: SectionKey; label: string; value: string | null }[] = [ + { key: 'status', label: 'Status', value: status || null }, + { key: 'author', label: 'Author', value: parsed.author }, + { + key: 'label', + label: 'Label', + value: + parsed.labels.length === 0 + ? null + : parsed.labels.length === 1 + ? parsed.labels[0] + : `${parsed.labels.length} labels` + }, + ...(kind === 'prs' + ? [ + { + key: 'reviewer' as SectionKey, + label: reviewerKind === 'reviewed-by' ? 'Reviewed by' : 'Review from', + value: reviewerActive + } + ] + : []), + { key: 'assignee', label: 'Assignee', value: parsed.assignee } + ] + const subject = kind === 'prs' ? 'pull requests' : 'issues' + return ( +
+
+ Filter {subject} +
+ {rows.map((row) => ( + + ))} + {onClearAll ? ( + <> +
+ + + ) : null} +
+ ) +} + +export function SectionDetail({ + section, + parsed, + kind, + authorOpts, + userOpts, + labelOpts, + labelsLoading, + labelsError, + usersLoading, + usersError, + reviewerMode, + setReviewerMode, + onBack, + onSelect +}: { + section: SectionKey + parsed: ParsedTaskQuery + kind: 'prs' | 'issues' + authorOpts: PickerOption[] + userOpts: PickerOption[] + labelOpts: PickerOption[] + labelsLoading: boolean + labelsError: string | null + usersLoading: boolean + usersError: string | null + reviewerMode: 'requested' | 'reviewed-by' + setReviewerMode: (mode: 'requested' | 'reviewed-by') => void + onBack: () => void + onSelect: (change: PRFilterChange) => void +}): React.JSX.Element { + return ( +
+ + {section === 'status' ? ( + + ) : null} + {section === 'author' ? ( + } + onSelect={(value) => onSelect({ author: value })} + /> + ) : null} + {section === 'assignee' ? ( + } + onSelect={(value) => onSelect({ assignee: value })} + /> + ) : null} + {section === 'label' ? ( + onSelect({ labels: next })} + /> + ) : null} + {section === 'reviewer' ? ( + <> +
+ + +
+ } + onSelect={(login) => + onSelect({ reviewer: login ? { kind: reviewerMode, login } : null }) + } + /> + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/ui/repo-multi-combobox.tsx b/src/renderer/src/components/ui/repo-multi-combobox.tsx index 8d6823527..20c964d4a 100644 --- a/src/renderer/src/components/ui/repo-multi-combobox.tsx +++ b/src/renderer/src/components/ui/repo-multi-combobox.tsx @@ -120,7 +120,14 @@ export default function RepoMultiCombobox({ - + {/* Why: trigger width can be as narrow as the "All repos" label, but the + popover hosts a search input and repo rows with paths. Use the + trigger as a minimum width and let the content expand to a readable + size so the search field and repo names aren't truncated. */} + { it('splits on whitespace', () => { @@ -18,6 +24,13 @@ describe('tokenizeSearchQuery', () => { expect(tokenizeSearchQuery("'with spaces' bar")).toEqual(['with spaces', 'bar']) }) + it('keeps quoted qualifier values as one token', () => { + expect(tokenizeSearchQuery('label:"needs review" author:alice')).toEqual([ + 'label:needs review', + 'author:alice' + ]) + }) + it('returns an empty list for an empty string', () => { expect(tokenizeSearchQuery('')).toEqual([]) }) @@ -38,11 +51,22 @@ describe('parseTaskQuery', () => { expect(parsed.state).toBe('open') }) + it('parses is:pull-request as a PR scope alias', () => { + const parsed = parseTaskQuery('is:pull-request is:open') + expect(parsed.scope).toBe('pr') + expect(parsed.state).toBe('open') + }) + it('widens scope to all when both is:issue and is:pr are present', () => { const parsed = parseTaskQuery('is:issue is:pr') expect(parsed.scope).toBe('all') }) + it('widens scope to all regardless of issue and PR token order', () => { + const parsed = parseTaskQuery('is:pr is:issue') + expect(parsed.scope).toBe('all') + }) + it('is:draft forces scope to pr and state to open', () => { const parsed = parseTaskQuery('is:draft') expect(parsed.scope).toBe('pr') @@ -50,6 +74,13 @@ describe('parseTaskQuery', () => { expect(parsed.draft).toBe(true) }) + it('keeps draft scoped to open PRs even when a later token says issue', () => { + const parsed = parseTaskQuery('is:draft is:issue') + expect(parsed.scope).toBe('pr') + expect(parsed.state).toBe('open') + expect(parsed.draft).toBe(true) + }) + it('is:pr is:open does not set draft', () => { const parsed = parseTaskQuery('is:pr is:open') expect(parsed.scope).toBe('pr') @@ -69,10 +100,22 @@ describe('parseTaskQuery', () => { expect(parsed.freeText).toBe('free text') }) + it('keeps review qualifiers scoped to PRs even when a later token says issue', () => { + const parsed = parseTaskQuery('review-requested:@me is:issue') + expect(parsed.scope).toBe('pr') + expect(parsed.reviewRequested).toBe('@me') + }) + it('leaves unknown qualifiers and bare words in freeText', () => { const parsed = parseTaskQuery('custom:value hello') expect(parsed.freeText).toBe('custom:value hello') }) + + it('parses state:all for the Any state filter', () => { + const parsed = parseTaskQuery('is:pr state:all') + expect(parsed.scope).toBe('pr') + expect(parsed.state).toBe('all') + }) }) describe('stripRepoQualifiers', () => { @@ -103,3 +146,71 @@ describe('stripRepoQualifiers', () => { expect(stripRepoQualifiers('hello repo:a/b world')).toBe('hello world') }) }) + +describe('serializeTaskQuery', () => { + it('round-trips qualifiers and free text', () => { + const raw = 'is:pr is:open author:alice label:bug review-requested:bob hello world' + const reserialized = serializeTaskQuery(parseTaskQuery(raw)) + expect(parseTaskQuery(reserialized)).toEqual(parseTaskQuery(raw)) + }) + + it('quotes label values containing whitespace', () => { + const parsed = parseTaskQuery('label:"needs review"') + expect(parsed.labels).toEqual(['needs review']) + expect(parsed.freeText).toBe('') + expect(serializeTaskQuery(parsed)).toContain('label:"needs review"') + }) + + it('serializes all state so filter changes do not fall back to the default open state', () => { + const raw = serializeTaskQuery(parseTaskQuery('is:pr state:all')) + expect(raw).toBe('is:pr state:all') + }) +}) + +describe('withQualifier', () => { + it('sets and clears the author qualifier without disturbing free text', () => { + const set = withQualifier('hello', 'author', 'alice') + expect(parseTaskQuery(set).author).toBe('alice') + expect(parseTaskQuery(set).freeText).toBe('hello') + const cleared = withQualifier(set, 'author', null) + expect(parseTaskQuery(cleared).author).toBeNull() + expect(parseTaskQuery(cleared).freeText).toBe('hello') + }) + + it('replaces the labels list', () => { + const result = withQualifier('label:bug label:enh', 'labels', ['triage']) + expect(parseTaskQuery(result).labels).toEqual(['triage']) + }) + + it('clears labels when given an empty array', () => { + const result = withQualifier('label:bug is:pr', 'labels', []) + expect(parseTaskQuery(result).labels).toEqual([]) + expect(parseTaskQuery(result).scope).toBe('pr') + }) + + it('sets the all state filter', () => { + const result = withQualifier('is:pr is:open', 'state', 'all') + expect(parseTaskQuery(result).state).toBe('all') + expect(result).toContain('state:all') + }) + + it('preserves quoted free-text tokens when applying a filter', () => { + const result = withQualifier('"exact phrase" milestone:"next release"', 'author', 'alice') + expect(result).toContain('"exact phrase"') + expect(result).toContain('milestone:"next release"') + expect(parseTaskQuery(result).author).toBe('alice') + }) + + it('keeps PR-only filters scoped to PRs', () => { + expect(parseTaskQuery(withQualifier('', 'draft', 'true')).scope).toBe('pr') + expect(parseTaskQuery(withQualifier('', 'state', 'merged')).scope).toBe('pr') + expect(parseTaskQuery(withQualifier('', 'reviewRequested', '@me')).scope).toBe('pr') + }) + + it('forces draft filters back to open PRs', () => { + const parsed = parseTaskQuery(withQualifier('is:pr is:closed', 'draft', 'true')) + expect(parsed.scope).toBe('pr') + expect(parsed.state).toBe('open') + expect(parsed.draft).toBe(true) + }) +}) diff --git a/src/shared/task-query.ts b/src/shared/task-query.ts index ea0337de6..cd2c921d6 100644 --- a/src/shared/task-query.ts +++ b/src/shared/task-query.ts @@ -10,16 +10,50 @@ export type ParsedTaskQuery = { freeText: string } -export function tokenizeSearchQuery(rawQuery: string): string[] { - const tokens: string[] = [] - const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g - let match: RegExpExecArray | null - while ((match = pattern.exec(rawQuery)) !== null) { - tokens.push(match[1] ?? match[2] ?? match[3] ?? '') +type SearchQueryToken = { + value: string + raw: string +} + +function tokenizeSearchQueryWithRaw(rawQuery: string): SearchQueryToken[] { + const tokens: SearchQueryToken[] = [] + let value = '' + let raw = '' + let quote: '"' | "'" | null = null + + const flush = (): void => { + if (value || raw) { + tokens.push({ value, raw }) + value = '' + raw = '' + } } + + for (let i = 0; i < rawQuery.length; i += 1) { + const char = rawQuery[i] + if (/\s/.test(char) && quote === null) { + flush() + continue + } + raw += char + if ((char === '"' || char === "'") && quote === null) { + quote = char + continue + } + if (char === quote) { + quote = null + continue + } + value += char + } + flush() return tokens } +export function tokenizeSearchQuery(rawQuery: string): string[] { + return tokenizeSearchQueryWithRaw(rawQuery).map((token) => token.value) +} + export function parseTaskQuery(rawQuery: string): ParsedTaskQuery { const query: ParsedTaskQuery = { scope: 'all', @@ -34,17 +68,18 @@ export function parseTaskQuery(rawQuery: string): ParsedTaskQuery { } const freeTextTokens: string[] = [] - for (const token of tokenizeSearchQuery(rawQuery.trim())) { + let sawIssueScope = false + let sawPRScope = false + for (const { value: token, raw } of tokenizeSearchQueryWithRaw(rawQuery.trim())) { const normalized = token.toLowerCase() if (normalized === 'is:issue') { - if (query.scope === 'pr') { - continue - } - query.scope = 'issue' + sawIssueScope = true + query.scope = sawPRScope ? 'all' : 'issue' continue } - if (normalized === 'is:pr') { - query.scope = query.scope === 'issue' ? 'all' : 'pr' + if (normalized === 'is:pr' || normalized === 'is:pull-request') { + sawPRScope = true + query.scope = sawIssueScope ? 'all' : 'pr' continue } if (normalized === 'is:open') { @@ -70,7 +105,7 @@ export function parseTaskQuery(rawQuery: string): ParsedTaskQuery { const value = rest.join(':').trim() const key = rawKey.toLowerCase() if (!value) { - freeTextTokens.push(token) + freeTextTokens.push(raw) continue } @@ -96,14 +131,150 @@ export function parseTaskQuery(rawQuery: string): ParsedTaskQuery { query.labels.push(value) continue } + const normalizedValue = value.toLowerCase() + if ( + key === 'state' && + (normalizedValue === 'open' || + normalizedValue === 'closed' || + normalizedValue === 'merged' || + normalizedValue === 'all') + ) { + query.state = normalizedValue + continue + } - freeTextTokens.push(token) + // Why: unknown qualifiers and exact phrases are passed through to GitHub + // search as-is; reserializing stripped quotes changes search semantics. + freeTextTokens.push(raw) } + if (query.draft) { + query.scope = 'pr' + query.state = 'open' + } else if ( + query.state === 'merged' || + query.reviewRequested !== null || + query.reviewedBy !== null + ) { + query.scope = 'pr' + } query.freeText = freeTextTokens.join(' ').trim() return query } +function quoteIfNeeded(value: string): string { + return /\s/.test(value) ? `"${value.replaceAll('"', '\\"')}"` : value +} + +/** + * Serialize a ParsedTaskQuery back to a raw search string. Round-trips with + * parseTaskQuery for the qualifiers it understands; freeText is appended last. + */ +export function serializeTaskQuery(q: ParsedTaskQuery): string { + const parts: string[] = [] + if (q.scope === 'pr') { + parts.push('is:pr') + } else if (q.scope === 'issue') { + parts.push('is:issue') + } + if (q.state === 'open') { + parts.push('is:open') + } else if (q.state === 'closed') { + parts.push('is:closed') + } else if (q.state === 'merged') { + parts.push('is:merged') + } else if (q.state === 'all') { + parts.push('state:all') + } + if (q.draft) { + parts.push('is:draft') + } + if (q.author) { + parts.push(`author:${quoteIfNeeded(q.author)}`) + } + if (q.assignee) { + parts.push(`assignee:${quoteIfNeeded(q.assignee)}`) + } + if (q.reviewRequested) { + parts.push(`review-requested:${quoteIfNeeded(q.reviewRequested)}`) + } + if (q.reviewedBy) { + parts.push(`reviewed-by:${quoteIfNeeded(q.reviewedBy)}`) + } + for (const label of q.labels) { + parts.push(`label:${quoteIfNeeded(label)}`) + } + if (q.freeText) { + parts.push(q.freeText) + } + return parts.join(' ') +} + +export type TaskQueryFilterKey = + | 'author' + | 'assignee' + | 'reviewRequested' + | 'reviewedBy' + | 'labels' + | 'state' + | 'draft' + +/** + * Apply a filter change to a raw query string and return the updated raw string. + * For single-value keys, pass `null` to clear. For `labels`, pass the full next + * array (caller manages add/remove). + */ +export function withQualifier( + rawQuery: string, + key: TaskQueryFilterKey, + value: string | string[] | null +): string { + const parsed = parseTaskQuery(rawQuery) + switch (key) { + case 'author': + parsed.author = typeof value === 'string' ? value : null + break + case 'assignee': + parsed.assignee = typeof value === 'string' ? value : null + break + case 'reviewRequested': + parsed.reviewRequested = typeof value === 'string' ? value : null + if (parsed.reviewRequested) { + parsed.scope = 'pr' + } + break + case 'reviewedBy': + parsed.reviewedBy = typeof value === 'string' ? value : null + if (parsed.reviewedBy) { + parsed.scope = 'pr' + } + break + case 'labels': + parsed.labels = Array.isArray(value) ? value : [] + break + case 'state': + parsed.state = + value === 'open' || value === 'closed' || value === 'merged' || value === 'all' + ? value + : null + if (parsed.state === 'merged') { + parsed.scope = 'pr' + } + if (parsed.state !== 'open') { + parsed.draft = false + } + break + case 'draft': + parsed.draft = value === 'true' + if (parsed.draft) { + parsed.scope = 'pr' + parsed.state = 'open' + } + break + } + return serializeTaskQuery(parsed) +} + /** * Strip any `repo:owner/name` qualifiers from a raw search string. *