From 143c36e566483006fe54fa2716b019ec00599752 Mon Sep 17 00:00:00 2001 From: Andres Van Reepingen Date: Fri, 10 Jul 2026 21:57:09 +0200 Subject: [PATCH] feat(jira): group Jira issues by status (#7958) * fix(jira): group Jira issues by status in task page Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(jira): order grouped statuses by agile board columns configuration * test(jira): add comprehensive tests for Jira issue grouping functionality Add test coverage for the new Jira issue grouping features including: - Grouping issues by status name - Sorting sections by agile board column configuration - Falling back to alphabetical sorting when no board config exists - Collapsed groups state management - Filtering issues based on collapsed state - Backend tests for getProjectStatuses API with various scenarios Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(jira): add backend tests for getProjectStatuses and RPC routing Add test coverage for the new getProjectStatuses backend functionality: - Returns empty array when no clients are available - Returns statuses from project statuses API when no board configuration exists - Orders statuses by agile board column configuration when available - Handles missing status IDs gracefully by falling back to unordered list - Clears token on auth errors - Returns empty array on operational errors - RPC routing for jira.getProjectStatuses method Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(jira): harden status grouping --------- Co-authored-by: Andres Van Reepingen Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> --- src/main/ipc/jira.ts | 11 + src/main/jira/issues.test.ts | 96 +++++ src/main/jira/issues.ts | 82 ++++ src/main/runtime/orca-runtime.ts | 8 + src/main/runtime/rpc/methods/jira.test.ts | 9 +- src/main/runtime/rpc/methods/jira.ts | 11 + src/preload/api-types.ts | 5 + src/preload/index.ts | 7 +- src/renderer/src/components/TaskPage.tsx | 237 +++--------- .../task-page-jira-grouping.test.ts | 171 +++++++++ .../components/task-page-jira-issue-list.tsx | 349 ++++++++++++++++++ .../components/task-page-jira-status-order.ts | 63 ++++ .../src/runtime/runtime-jira-client.ts | 15 + src/shared/jira-types.ts | 4 + src/shared/types.ts | 1 + 15 files changed, 887 insertions(+), 182 deletions(-) create mode 100644 src/renderer/src/components/task-page-jira-grouping.test.ts create mode 100644 src/renderer/src/components/task-page-jira-issue-list.tsx create mode 100644 src/renderer/src/components/task-page-jira-status-order.ts diff --git a/src/main/ipc/jira.ts b/src/main/ipc/jira.ts index e8ed17f9b..e4a0e7ff8 100644 --- a/src/main/ipc/jira.ts +++ b/src/main/ipc/jira.ts @@ -6,6 +6,7 @@ import { createIssue, getIssue, getIssueComments, + getProjectStatusOrder, listAssignableUsers, listCreateFields, listIssueTypes, @@ -259,4 +260,14 @@ export function registerJiraHandlers(): void { } return listTransitions(args.key.trim(), normalizeSiteId(args.siteId)) }) + + ipcMain.handle( + 'jira:getProjectStatusOrder', + async (_event, args: { projectKey: string; siteId?: string }) => { + if (typeof args?.projectKey !== 'string' || !args.projectKey.trim()) { + return { statusIdsByColumn: [] } + } + return getProjectStatusOrder(args.projectKey.trim(), normalizeSiteId(args.siteId)) + } + ) } diff --git a/src/main/jira/issues.test.ts b/src/main/jira/issues.test.ts index 49a49a460..1cf9ab312 100644 --- a/src/main/jira/issues.test.ts +++ b/src/main/jira/issues.test.ts @@ -398,4 +398,100 @@ describe('Jira issue operations', () => { } ]) }) + + describe('getProjectStatusOrder', () => { + it('returns an empty order when no clients are available', async () => { + getClientsMock.mockReturnValue([]) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + }) + + it('returns an empty order when an omitted site resolves to multiple clients', async () => { + getClientsMock.mockReturnValue([makeEntry('site-1'), makeEntry('site-2')]) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP')).resolves.toEqual({ statusIdsByColumn: [] }) + expect(jiraRequestMock).not.toHaveBeenCalled() + }) + + it('returns an empty order when the project has no accessible board', async () => { + jiraRequestMock.mockResolvedValueOnce({ values: [] }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP & OPS', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(String(jiraRequestMock.mock.calls[0][1])).toContain( + '/rest/agile/1.0/board?projectKeyOrId=ALP+%26+OPS&maxResults=2' + ) + }) + + it('keeps alphabetical fallback when a project has multiple boards', async () => { + jiraRequestMock.mockResolvedValueOnce({ + total: 2, + values: [{ id: 42 }, { id: 43 }] + }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(jiraRequestMock).toHaveBeenCalledTimes(1) + }) + + it('keeps alphabetical fallback when Jira reports another board page', async () => { + jiraRequestMock.mockResolvedValueOnce({ + isLast: false, + values: [{ id: 42 }] + }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(jiraRequestMock).toHaveBeenCalledTimes(1) + }) + + it('returns status IDs grouped by Jira board column order', async () => { + jiraRequestMock + .mockResolvedValueOnce({ total: 1, values: [{ id: 42 }] }) + .mockResolvedValueOnce({ + columnConfig: { + columns: [ + { statuses: [{ id: '1' }, { id: '2' }] }, + { statuses: [{ id: '3' }, { id: '2' }] }, + { statuses: [] } + ] + } + }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [['1', '2'], ['3']] + }) + expect(jiraRequestMock.mock.calls[1]?.[1]).toBe('/rest/agile/1.0/board/42/configuration') + }) + + it('clears the token and surfaces credential failures', async () => { + const authError = new Error('Unauthorized') + isAuthErrorMock.mockReturnValue(true) + jiraRequestMock.mockRejectedValueOnce(authError) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).rejects.toThrow('Unauthorized') + expect(clearTokenMock).toHaveBeenCalledWith('site-1') + }) + + it('falls back to an empty order on operational errors', async () => { + jiraRequestMock.mockRejectedValueOnce(new Error('Service Unavailable')) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + }) + }) }) diff --git a/src/main/jira/issues.ts b/src/main/jira/issues.ts index 3bf823734..5a19b9897 100644 --- a/src/main/jira/issues.ts +++ b/src/main/jira/issues.ts @@ -14,6 +14,7 @@ import type { JiraMutationResult, JiraPriority, JiraProject, + JiraProjectStatusOrder, JiraSite, JiraSiteSelection, JiraStatus, @@ -110,6 +111,13 @@ function asString(value: unknown, fallback = ''): string { return typeof value === 'string' ? value : fallback } +function asIdentifier(value: unknown): string { + if (typeof value === 'string') { + return value + } + return typeof value === 'number' && Number.isFinite(value) ? String(value) : '' +} + function asStringArray(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') @@ -810,3 +818,77 @@ export async function listTransitions( release() } } + +export async function getProjectStatusOrder( + projectKey: string, + siteId?: string | null +): Promise { + // Why: an omitted site can resolve to the persisted "all" selection; board + // metadata is only truthful when exactly one Jira connection owns the project. + const entries = getClients(siteId) + const entry = entries.length === 1 ? entries[0] : undefined + if (!entry) { + return { statusIdsByColumn: [] } + } + await acquire() + try { + // Why: without an explicit board picker there is no truthful way to choose + // among multiple project boards, so ambiguous projects keep alphabetical order. + const params = new URLSearchParams({ projectKeyOrId: projectKey, maxResults: '2' }) + const boardsResponse = await jiraRequest>( + entry, + `/rest/agile/1.0/board?${params.toString()}` + ) + const boards = boardsResponse.values ?? [] + const boardCount = asFiniteNumber(boardsResponse.total) + const singleBoardIsProven = + boards.length === 1 && + boardsResponse.isLast !== false && + (boardCount === 1 || (boardCount === null && boardsResponse.isLast === true)) + const boardId = singleBoardIsProven ? asIdentifier(asRecord(boards[0]).id) : '' + if (!boardId) { + return { statusIdsByColumn: [] } + } + + const configResponse = await jiraRequest( + entry, + `/rest/agile/1.0/board/${encodeURIComponent(boardId)}/configuration` + ) + const columns = asRecord(asRecord(configResponse).columnConfig).columns + if (!Array.isArray(columns)) { + return { statusIdsByColumn: [] } + } + + // Why: issues already carry status names and IDs, so returning board IDs + // avoids a second metadata request and keeps duplicate names unambiguous. + const seenStatusIds = new Set() + const statusIdsByColumn: string[][] = [] + for (const column of columns) { + const statuses = asRecord(column).statuses + if (!Array.isArray(statuses)) { + continue + } + const columnStatusIds: string[] = [] + for (const status of statuses) { + const statusId = asIdentifier(asRecord(status).id) + if (statusId && !seenStatusIds.has(statusId)) { + seenStatusIds.add(statusId) + columnStatusIds.push(statusId) + } + } + if (columnStatusIds.length > 0) { + statusIdsByColumn.push(columnStatusIds) + } + } + return { statusIdsByColumn } + } catch (error) { + if (isAuthError(error)) { + clearToken(entry.site.id) + throw error + } + console.warn('[jira] getProjectStatusOrder failed:', error) + return { statusIdsByColumn: [] } + } finally { + release() + } +} diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9625b5e0c..825caa0dc 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -534,6 +534,7 @@ import { createIssue as createJiraIssue, getIssue as getJiraIssue, getIssueComments as getJiraIssueComments, + getProjectStatusOrder as getJiraProjectStatusOrder, listAssignableUsers as listJiraAssignableUsers, listCreateFields as listJiraCreateFields, listIssueTypes as listJiraIssueTypes, @@ -22751,6 +22752,13 @@ export class OrcaRuntimeService { return listJiraTransitions(key, siteId) } + jiraGetProjectStatusOrder( + projectKey: string, + siteId?: string + ): ReturnType { + return getJiraProjectStatusOrder(projectKey, siteId) + } + // ── Browser automation ── private readonly browserCommands = new RuntimeBrowserCommands({ diff --git a/src/main/runtime/rpc/methods/jira.test.ts b/src/main/runtime/rpc/methods/jira.test.ts index 8df96326c..8bf82eab5 100644 --- a/src/main/runtime/rpc/methods/jira.test.ts +++ b/src/main/runtime/rpc/methods/jira.test.ts @@ -125,7 +125,10 @@ describe('jira RPC methods', () => { jiraListCreateFields: vi.fn().mockResolvedValue([{ key: 'customfield_10010' }]), jiraListPriorities: vi.fn().mockResolvedValue([{ id: 'priority-1' }]), jiraListAssignableUsers: vi.fn().mockResolvedValue([{ accountId: 'user-1' }]), - jiraListTransitions: vi.fn().mockResolvedValue([{ id: 'transition-1' }]) + jiraListTransitions: vi.fn().mockResolvedValue([{ id: 'transition-1' }]), + jiraGetProjectStatusOrder: vi.fn().mockResolvedValue({ + statusIdsByColumn: [['status-1']] + }) } as unknown as OrcaRuntimeService const dispatcher = new RpcDispatcher({ runtime, methods: JIRA_METHODS }) @@ -151,6 +154,9 @@ describe('jira RPC methods', () => { await dispatcher.dispatch( makeRequest('jira.listTransitions', { key: 'ABC-3', siteId: 'site-1' }) ) + await dispatcher.dispatch( + makeRequest('jira.getProjectStatusOrder', { projectKey: 'ALP', siteId: 'site-1' }) + ) expect(runtime.jiraListProjects).toHaveBeenCalledWith('all') expect(runtime.jiraListIssueTypes).toHaveBeenCalledWith('project-1', 'site-1') @@ -158,5 +164,6 @@ describe('jira RPC methods', () => { expect(runtime.jiraListPriorities).toHaveBeenCalledWith('site-1') expect(runtime.jiraListAssignableUsers).toHaveBeenCalledWith('ABC-3', 'Ada', 'site-1') expect(runtime.jiraListTransitions).toHaveBeenCalledWith('ABC-3', 'site-1') + expect(runtime.jiraGetProjectStatusOrder).toHaveBeenCalledWith('ALP', 'site-1') }) }) diff --git a/src/main/runtime/rpc/methods/jira.ts b/src/main/runtime/rpc/methods/jira.ts index 9a4c614d9..35d1d067c 100644 --- a/src/main/runtime/rpc/methods/jira.ts +++ b/src/main/runtime/rpc/methods/jira.ts @@ -88,6 +88,11 @@ const AssignableUsers = z.object({ siteId: OptionalString }) +const ProjectStatusOrder = z.object({ + projectKey: requiredString('Project key is required'), + siteId: OptionalString +}) + export const JIRA_METHODS: RpcMethod[] = [ defineMethod({ name: 'jira.connect', @@ -204,5 +209,11 @@ export const JIRA_METHODS: RpcMethod[] = [ params: IssueKey, handler: async (params, { runtime }) => runtime.jiraListTransitions(params.key.trim(), params.siteId) + }), + defineMethod({ + name: 'jira.getProjectStatusOrder', + params: ProjectStatusOrder, + handler: async (params, { runtime }) => + runtime.jiraGetProjectStatusOrder(params.projectKey.trim(), params.siteId) }) ] diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 7604538ab..100b89b97 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -121,6 +121,7 @@ import type { JiraIssue, JiraIssueFilter, JiraIssueType, + JiraProjectStatusOrder, JiraIssueUpdate, JiraPriority, JiraProject, @@ -1931,6 +1932,10 @@ export type PreloadApi = { siteId?: string }) => Promise listTransitions: (args: { key: string; siteId?: string }) => Promise + getProjectStatusOrder: (args: { + projectKey: string + siteId?: string + }) => Promise } starNag: { onShow: ( diff --git a/src/preload/index.ts b/src/preload/index.ts index 8bbe17f7c..9f63a71d9 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -25,6 +25,7 @@ import type { GitHubAssignableUser, GitHubCommentResult, GitHubWorkItem, + JiraProjectStatusOrder, GitPushTarget, GitStagingArea, GitForkSyncExpectedUpstream, @@ -1665,7 +1666,11 @@ const api = { }): Promise => ipcRenderer.invoke('jira:listAssignableUsers', args), listTransitions: (args: { key: string; siteId?: string }): Promise => - ipcRenderer.invoke('jira:listTransitions', args) + ipcRenderer.invoke('jira:listTransitions', args), + getProjectStatusOrder: (args: { + projectKey: string + siteId?: string + }): Promise => ipcRenderer.invoke('jira:getProjectStatusOrder', args) }, starNag: { diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index 810063e39..5e74b874b 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -159,6 +159,12 @@ import { LinearProjectTable } from '@/components/linear-project-view-surfaces' import JiraIssueWorkspace from '@/components/JiraIssueWorkspace' +import { TaskPageJiraIssueList } from '@/components/task-page-jira-issue-list' +import { + getSingleJiraProjectScope, + getTaskPageJiraStatusOrderScopeKey, + loadTaskPageJiraProjectStatusOrder +} from '@/components/task-page-jira-status-order' import { JiraIcon } from '@/components/icons/JiraIcon' import { cn } from '@/lib/utils' import { @@ -277,6 +283,7 @@ import type { JiraIssue, JiraIssueType, JiraProject, + JiraProjectStatusOrder, LinearIssue, LinearProjectDetail, LinearProjectSummary, @@ -3501,6 +3508,9 @@ export default function TaskPage(): React.JSX.Element { selectedJiraSiteId ] ) + const jiraTaskSourceScopeKey = jiraTaskSourceContext + ? getTaskSourceCacheScope(jiraTaskSourceContext) + : providerRuntimeContextKey const accountBackedTaskSourceHostAvailability = useMemo(() => { if (taskSource !== 'linear' && taskSource !== 'jira') { return [] @@ -4575,6 +4585,10 @@ export default function TaskPage(): React.JSX.Element { const [appliedJiraSearch, setAppliedJiraSearch] = useState('') const [activeJiraPreset, setActiveJiraPreset] = useState('assigned') const [jiraRefreshNonce, setJiraRefreshNonce] = useState(0) + const [jiraProjectStatusOrder, setJiraProjectStatusOrder] = useState<{ + order: JiraProjectStatusOrder + scopeKey: string + } | null>(null) useEffect(() => { if (taskResumeAppliedRef.current || !persistedUIReady || !settings) { @@ -5595,6 +5609,17 @@ export default function TaskPage(): React.JSX.Element { ), [jiraIssues, jiraCacheSnapshot.issueCache, jiraCacheSnapshot.searchCache, jiraTaskSourceContext] ) + const displayedJiraProjectScope = useMemo( + () => getSingleJiraProjectScope(displayedJiraIssues), + [displayedJiraIssues] + ) + const displayedJiraStatusOrderScopeKey = displayedJiraProjectScope + ? getTaskPageJiraStatusOrderScopeKey(jiraTaskSourceScopeKey, displayedJiraProjectScope) + : null + const displayedJiraStatusOrder = + jiraProjectStatusOrder && displayedJiraStatusOrderScopeKey === jiraProjectStatusOrder.scopeKey + ? jiraProjectStatusOrder.order + : null // New Linear project dialog state const [newLinearProjectOpen, setNewLinearProjectOpen] = useState(false) @@ -7792,6 +7817,26 @@ export default function TaskPage(): React.JSX.Element { } setJiraIssues(issues) setJiraLoading(false) + const projectScope = getSingleJiraProjectScope(issues) + if (!projectScope) { + return + } + const statusOrderScopeKey = getTaskPageJiraStatusOrderScopeKey( + jiraTaskSourceScopeKey, + projectScope + ) + void loadTaskPageJiraProjectStatusOrder( + jiraTaskSourceContext ?? settings, + jiraTaskSourceScopeKey, + projectScope + ).then((order) => { + if (!cancelled) { + setJiraProjectStatusOrder({ + order, + scopeKey: statusOrderScopeKey + }) + } + }) }) .catch((err) => { if (cancelled) { @@ -7815,7 +7860,8 @@ export default function TaskPage(): React.JSX.Element { activeJiraPreset, jiraRefreshNonce, taskResumeApplied, - jiraTaskSourceContext + jiraTaskSourceContext, + jiraTaskSourceScopeKey ]) useEffect(() => { @@ -10026,185 +10072,16 @@ export default function TaskPage(): React.JSX.Element { ) : null} -
- {displayedJiraIssues.map((issue) => { - const selected = issue.key === selectedJiraIssueKey - const labels = issue.labels.slice(0, 3) - const contextLabel = - selectedJiraSiteId === 'all' && issue.siteName - ? `${issue.siteName} / ${issue.project.key}` - : issue.project.key - return ( -
openJiraDetailPage(issue)} - onKeyDown={(e) => { - if (e.target !== e.currentTarget) { - return - } - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault() - openJiraDetailPage(issue) - } - }} - className={cn( - 'group/row grid min-h-12 cursor-pointer grid-cols-[minmax(0,1fr)_auto] items-center gap-3 px-3 py-2 text-left transition hover:bg-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring md:grid-cols-[90px_minmax(0,1fr)_128px_92px_80px] lg:grid-cols-[96px_minmax(0,1.25fr)_132px_120px_136px_96px_64px] xl:grid-cols-[104px_minmax(0,1.45fr)_144px_132px_160px_128px_72px]', - selected && 'bg-accent' - )} - > - - {issue.key} - - -
-
- - {issue.key} - -

- {issue.title} -

-
-
- - {issue.status.name} - - - {issue.priority?.name ?? - translate('auto.components.TaskPage.713179dfdc', 'No priority')} - - - {issue.assignee?.displayName ?? - translate('auto.components.TaskPage.42a9160321', 'Unassigned')} - -
-
- - {contextLabel} - - {labels.map((label) => ( - - {label} - - ))} - {issue.labels.length > labels.length ? ( - - +{issue.labels.length - labels.length} - - ) : null} -
-
- -
- - {issue.status.name} - -
- - - {issue.priority?.name ?? - translate('auto.components.TaskPage.713179dfdc', 'No priority')} - - -
- {issue.assignee?.avatarUrl ? ( - {issue.assignee.displayName} - ) : ( - - {issue.assignee?.displayName?.slice(0, 1) ?? '-'} - - )} - - {issue.assignee?.displayName ?? - translate('auto.components.TaskPage.42a9160321', 'Unassigned')} - -
- - - -
- {formatRelativeTime(issue.updatedAt)} -
-
- - {new Date(issue.updatedAt).toLocaleString()} - -
- -
- - - - - - {translate( - 'auto.components.TaskPage.9497f2787c', - 'Start workspace' - )} - - - - - - - - {translate('auto.components.TaskPage.eee68073b2', 'Open in Jira')} - - -
-
- ) - })} -
+ ({ + jiraGetProjectStatusOrderMock: vi.fn() +})) + +vi.mock('@/runtime/runtime-jira-client', () => ({ + jiraGetProjectStatusOrder: (...args: unknown[]) => jiraGetProjectStatusOrderMock(...args) +})) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + jiraGetProjectStatusOrderMock.mockReset() +}) + +function jiraIssue( + key: string, + title: string, + statusId: string, + statusName: string, + options: { projectKey?: string; siteId?: string } = {} +): JiraIssue { + const siteId = options.siteId ?? 'site-1' + const projectKey = options.projectKey ?? 'ALP' + return { + id: `${siteId}:${key}`, + key, + title, + url: `https://example.atlassian.net/browse/${key}`, + siteId, + siteName: 'Example Jira', + project: { id: projectKey, key: projectKey, name: projectKey, siteId }, + issueType: { id: '10001', name: 'Bug' }, + status: { id: statusId, name: statusName, categoryKey: 'new', categoryName: statusName }, + labels: [], + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z' + } +} + +function statusOrder(statusIdsByColumn: string[][]): JiraProjectStatusOrder { + return { statusIdsByColumn } +} + +describe('Jira issue status grouping', () => { + it('groups issues through the production implementation and preserves row order', () => { + const first = jiraIssue('ALP-1', 'First', '1', 'To Do') + const second = jiraIssue('ALP-2', 'Second', '2', 'In Progress') + const third = jiraIssue('ALP-3', 'Third', '1', 'To Do') + + const sections = groupJiraIssuesByStatus([first, second, third], null) + + expect(sections.map((section) => section.label)).toEqual(['In Progress', 'To Do']) + expect(sections[1]?.issues).toEqual([first, third]) + }) + + it('uses Jira column order while sorting statuses in the same column alphabetically', () => { + const sections = groupJiraIssuesByStatus( + [ + jiraIssue('ALP-1', 'Done issue', '3', 'Done'), + jiraIssue('ALP-2', 'To do issue', '1', 'To Do'), + jiraIssue('ALP-3', 'Progress issue', '2', 'In Progress') + ], + statusOrder([['1', '2'], ['3']]) + ) + + expect(sections.map((section) => section.label)).toEqual(['In Progress', 'To Do', 'Done']) + }) + + it('places statuses missing from board configuration last in alphabetical order', () => { + const sections = groupJiraIssuesByStatus( + [ + jiraIssue('ALP-1', 'Done issue', '3', 'Done'), + jiraIssue('ALP-2', 'To do issue', '1', 'To Do'), + jiraIssue('ALP-3', 'Progress issue', '2', 'In Progress') + ], + statusOrder([['2']]) + ) + + expect(sections.map((section) => section.label)).toEqual(['In Progress', 'Done', 'To Do']) + }) + + it('only selects a board-order scope for one Jira site and project', () => { + const singleScope = getSingleJiraProjectScope([ + jiraIssue('ALP-1', 'First', '1', 'To Do'), + jiraIssue('ALP-2', 'Second', '2', 'In Progress') + ]) + const multipleSites = getSingleJiraProjectScope([ + jiraIssue('ALP-1', 'First', '1', 'To Do', { siteId: 'site-1' }), + jiraIssue('ALP-2', 'Second', '2', 'In Progress', { siteId: 'site-2' }) + ]) + const multipleProjects = getSingleJiraProjectScope([ + jiraIssue('ALP-1', 'First', '1', 'To Do', { projectKey: 'ALP' }), + jiraIssue('BRV-1', 'Second', '2', 'In Progress', { projectKey: 'BRV' }) + ]) + const missingSite = jiraIssue('ALP-3', 'Third', '3', 'Done') + delete missingSite.siteId + delete missingSite.project.siteId + + expect(singleScope).toMatchObject({ projectKey: 'ALP', siteId: 'site-1' }) + expect(multipleSites).toBeNull() + expect(multipleProjects).toBeNull() + expect(getSingleJiraProjectScope([missingSite])).toBeNull() + }) + + it('uses alphabetical fallback when status-order metadata is unavailable', async () => { + const error = new Error('Unknown RPC method') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + jiraGetProjectStatusOrderMock.mockRejectedValueOnce(error) + const scope = getSingleJiraProjectScope([jiraIssue('ALP-1', 'First', '1', 'To Do')]) + if (!scope) { + throw new Error('Expected one Jira project scope') + } + + await expect(loadTaskPageJiraProjectStatusOrder(null, 'runtime:old', scope)).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(warn).toHaveBeenCalledWith('[jira] Failed to load project status order:', error) + }) + + it('collapses and expands a status group through its accessible trigger', async () => { + const user = userEvent.setup() + render( + React.createElement( + TooltipProvider, + null, + React.createElement(TaskPageJiraIssueList, { + formatUpdatedAt: () => 'today', + getStatusTone: () => 'border-border', + issues: [ + jiraIssue('ALP-1', 'First issue', '1', 'To Do'), + jiraIssue('ALP-2', 'Second issue', '1', 'To Do') + ], + onOpenIssue: vi.fn(), + onStartWorkspace: vi.fn(), + selectedIssue: null, + showSiteContext: false, + statusOrder: null + }) + ) + ) + + const trigger = screen.getByRole('button', { name: 'To Do 2' }) + expect(trigger).toHaveAttribute('data-variant', 'ghost') + expect(trigger).toHaveAttribute('aria-expanded', 'true') + expect(screen.getByText('First issue')).toBeInTheDocument() + + await user.click(trigger) + expect(trigger).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByText('First issue')).not.toBeInTheDocument() + + await user.click(trigger) + expect(screen.getByText('First issue')).toBeInTheDocument() + }) +}) diff --git a/src/renderer/src/components/task-page-jira-issue-list.tsx b/src/renderer/src/components/task-page-jira-issue-list.tsx new file mode 100644 index 000000000..f8b67d1c2 --- /dev/null +++ b/src/renderer/src/components/task-page-jira-issue-list.tsx @@ -0,0 +1,349 @@ +import React, { useMemo, useState } from 'react' +import { ArrowRight, ChevronDown, ChevronRight, ExternalLink } from 'lucide-react' + +import { Button } from '@/components/ui/button' +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { translate } from '@/i18n/i18n' +import { cn } from '@/lib/utils' +import type { JiraIssue, JiraProjectStatusOrder } from '../../../shared/types' + +export type TaskPageJiraIssueSection = { + key: string + label: string + issues: JiraIssue[] +} + +type TaskPageJiraIssueListProps = { + formatUpdatedAt: (updatedAt: string) => string + getStatusTone: (categoryKey: string) => string + issues: JiraIssue[] + onOpenIssue: (issue: JiraIssue) => void + onStartWorkspace: (issue: JiraIssue) => void + selectedIssue: JiraIssue | null + showSiteContext: boolean + statusOrder: JiraProjectStatusOrder | null +} + +function statusColumnRanks(order: JiraProjectStatusOrder | null): Map { + const ranks = new Map() + for (const [columnIndex, statusIds] of (order?.statusIdsByColumn ?? []).entries()) { + for (const statusId of statusIds) { + if (!ranks.has(statusId)) { + ranks.set(statusId, columnIndex) + } + } + } + return ranks +} + +function sectionColumnRank( + section: TaskPageJiraIssueSection, + ranks: ReadonlyMap +): number { + let rank = Number.POSITIVE_INFINITY + for (const issue of section.issues) { + rank = Math.min(rank, ranks.get(issue.status.id) ?? Number.POSITIVE_INFINITY) + } + return rank +} + +export function groupJiraIssuesByStatus( + issues: readonly JiraIssue[], + statusOrder: JiraProjectStatusOrder | null +): TaskPageJiraIssueSection[] { + const sections = new Map() + for (const issue of issues) { + const key = `status:${issue.status.name}` + const section = sections.get(key) + if (section) { + section.issues.push(issue) + } else { + sections.set(key, { key, label: issue.status.name, issues: [issue] }) + } + } + + const ranks = statusColumnRanks(statusOrder) + const sectionRanks = new Map( + [...sections.values()].map((section) => [section.key, sectionColumnRank(section, ranks)]) + ) + return [...sections.values()].sort((a, b) => { + const rankA = sectionRanks.get(a.key) ?? Number.POSITIVE_INFINITY + const rankB = sectionRanks.get(b.key) ?? Number.POSITIVE_INFINITY + return rankA === rankB ? a.label.localeCompare(b.label) : rankA - rankB + }) +} + +function isSelectedIssue(issue: JiraIssue, selectedIssue: JiraIssue | null): boolean { + if (!selectedIssue || issue.key !== selectedIssue.key) { + return false + } + return !selectedIssue.siteId || !issue.siteId || selectedIssue.siteId === issue.siteId +} + +function JiraIssueRow({ + formatUpdatedAt, + getStatusTone, + issue, + onOpenIssue, + onStartWorkspace, + selected, + showSiteContext +}: { + formatUpdatedAt: (updatedAt: string) => string + getStatusTone: (categoryKey: string) => string + issue: JiraIssue + onOpenIssue: (issue: JiraIssue) => void + onStartWorkspace: (issue: JiraIssue) => void + selected: boolean + showSiteContext: boolean +}): React.JSX.Element { + const labels = issue.labels.slice(0, 3) + const contextLabel = + showSiteContext && issue.siteName + ? `${issue.siteName} / ${issue.project.key}` + : issue.project.key + + return ( + // Why: the row contains action buttons, so a native button wrapper would + // create invalid nested buttons; role + keyboard handling preserves access. +
onOpenIssue(issue)} + onKeyDown={(event) => { + if (event.target !== event.currentTarget) { + return + } + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + onOpenIssue(issue) + } + }} + className={cn( + 'group/row grid min-h-12 cursor-pointer grid-cols-[minmax(0,1fr)_auto] items-center gap-3 px-3 py-2 text-left transition hover:bg-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring md:grid-cols-[90px_minmax(0,1fr)_128px_92px_80px] lg:grid-cols-[96px_minmax(0,1.25fr)_132px_120px_136px_96px_64px] xl:grid-cols-[104px_minmax(0,1.45fr)_144px_132px_160px_128px_72px]', + selected && 'bg-accent' + )} + > + + {issue.key} + + +
+
+ + {issue.key} + +

+ {issue.title} +

+
+
+ + {issue.status.name} + + + {issue.priority?.name ?? + translate('auto.components.TaskPage.713179dfdc', 'No priority')} + + + {issue.assignee?.displayName ?? + translate('auto.components.TaskPage.42a9160321', 'Unassigned')} + +
+
+ + {contextLabel} + + {labels.map((label) => ( + + {label} + + ))} + {issue.labels.length > labels.length ? ( + + +{issue.labels.length - labels.length} + + ) : null} +
+
+ +
+ + {issue.status.name} + +
+ + + {issue.priority?.name ?? translate('auto.components.TaskPage.713179dfdc', 'No priority')} + + +
+ {issue.assignee?.avatarUrl ? ( + {issue.assignee.displayName} + ) : ( + + {issue.assignee?.displayName?.slice(0, 1) ?? '-'} + + )} + + {issue.assignee?.displayName ?? + translate('auto.components.TaskPage.42a9160321', 'Unassigned')} + +
+ + + +
+ {formatUpdatedAt(issue.updatedAt)} +
+
+ + {new Date(issue.updatedAt).toLocaleString()} + +
+ +
+ + + + + + {translate('auto.components.TaskPage.9497f2787c', 'Start workspace')} + + + + + + + + {translate('auto.components.TaskPage.eee68073b2', 'Open in Jira')} + + +
+
+ ) +} + +export function TaskPageJiraIssueList({ + formatUpdatedAt, + getStatusTone, + issues, + onOpenIssue, + onStartWorkspace, + selectedIssue, + showSiteContext, + statusOrder +}: TaskPageJiraIssueListProps): React.JSX.Element { + const [collapsedGroups, setCollapsedGroups] = useState>(() => new Set()) + const sections = useMemo( + () => groupJiraIssuesByStatus(issues, statusOrder), + [issues, statusOrder] + ) + + return ( +
+ {sections.map((section) => { + const open = !collapsedGroups.has(section.key) + return ( + { + setCollapsedGroups((current) => { + const next = new Set(current) + if (nextOpen) { + next.delete(section.key) + } else { + next.add(section.key) + } + return next + }) + }} + > + + + + + {section.issues.map((issue) => ( + + ))} + + + ) + })} +
+ ) +} diff --git a/src/renderer/src/components/task-page-jira-status-order.ts b/src/renderer/src/components/task-page-jira-status-order.ts new file mode 100644 index 000000000..8cb6ed39c --- /dev/null +++ b/src/renderer/src/components/task-page-jira-status-order.ts @@ -0,0 +1,63 @@ +import type { JiraIssue, JiraProjectStatusOrder } from '../../../shared/types' +import { jiraGetProjectStatusOrder, type RuntimeJiraSettings } from '@/runtime/runtime-jira-client' +import { createMetadataRequestStore, loadMetadata } from '@/hooks/metadata-request-cache' + +export type TaskPageJiraProjectScope = { + key: string + projectKey: string + siteId: string +} + +const jiraProjectStatusOrderStore = createMetadataRequestStore() + +export function getTaskPageJiraStatusOrderScopeKey( + runtimeScopeKey: string, + projectScope: TaskPageJiraProjectScope +): string { + return `${encodeURIComponent(runtimeScopeKey)}:${projectScope.key}` +} + +function issueProjectScope(issue: JiraIssue): TaskPageJiraProjectScope | null { + const projectKey = issue.project.key.trim() + const siteId = issue.siteId?.trim() || issue.project.siteId?.trim() + if (!projectKey || !siteId) { + return null + } + return { + key: `${encodeURIComponent(siteId)}:${encodeURIComponent(projectKey)}`, + projectKey, + siteId + } +} + +export function getSingleJiraProjectScope( + issues: readonly JiraIssue[] +): TaskPageJiraProjectScope | null { + let onlyScope: TaskPageJiraProjectScope | null = null + for (const issue of issues) { + const scope = issueProjectScope(issue) + if (!scope || (onlyScope && onlyScope.key !== scope.key)) { + return null + } + onlyScope = scope + } + return onlyScope +} + +export function loadTaskPageJiraProjectStatusOrder( + settings: RuntimeJiraSettings, + runtimeScopeKey: string, + projectScope: TaskPageJiraProjectScope +): Promise { + // Why: a project key can exist on multiple Jira sites and runtimes; all three + // identities must participate in caching to preserve SSH and multi-site parity. + const cacheKey = getTaskPageJiraStatusOrderScopeKey(runtimeScopeKey, projectScope) + return loadMetadata(jiraProjectStatusOrderStore, cacheKey, () => + jiraGetProjectStatusOrder(settings, projectScope.projectKey, projectScope.siteId) + ).catch((error: unknown) => { + // Why: older remote runtimes do not expose this optional metadata method; + // an empty order preserves the deterministic alphabetical fallback. + console.warn('[jira] Failed to load project status order:', error) + return { statusIdsByColumn: [] } + }) +} diff --git a/src/renderer/src/runtime/runtime-jira-client.ts b/src/renderer/src/runtime/runtime-jira-client.ts index c4d5ca666..812e28b82 100644 --- a/src/renderer/src/runtime/runtime-jira-client.ts +++ b/src/renderer/src/runtime/runtime-jira-client.ts @@ -12,6 +12,7 @@ import type { JiraMutationResult, JiraPriority, JiraProject, + JiraProjectStatusOrder, JiraSiteSelection, JiraTransition, JiraUser, @@ -280,3 +281,17 @@ export async function jiraListTransitions( ? callRuntimeRpc(target, 'jira.listTransitions', args, { timeoutMs: 30_000 }) : window.api.jira.listTransitions(args) } + +export async function jiraGetProjectStatusOrder( + settings: RuntimeJiraSettings, + projectKey: string, + siteId?: string | null +): Promise { + const target = getJiraRuntimeTarget(settings) + const args = { projectKey, siteId: siteId ?? undefined } + return target.kind === 'environment' + ? callRuntimeRpc(target, 'jira.getProjectStatusOrder', args, { + timeoutMs: 30_000 + }) + : window.api.jira.getProjectStatusOrder(args) +} diff --git a/src/shared/jira-types.ts b/src/shared/jira-types.ts index 8ce07fde4..7831bd184 100644 --- a/src/shared/jira-types.ts +++ b/src/shared/jira-types.ts @@ -81,6 +81,10 @@ export type JiraStatus = { colorName?: string } +export type JiraProjectStatusOrder = { + statusIdsByColumn: string[][] +} + export type JiraTransition = { id: string name: string diff --git a/src/shared/types.ts b/src/shared/types.ts index 3af1e7fdd..d6e04ef85 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1844,6 +1844,7 @@ export type { JiraMutationResult, JiraPriority, JiraProject, + JiraProjectStatusOrder, JiraSite, JiraSiteSelection, JiraStatus,