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 <andres.vanreepingen@datacamp.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
This commit is contained in:
Andres Van Reepingen
2026-07-10 12:57:09 -07:00
committed by GitHub
co-authored by Devin Andres Van Reepingen Jinjing
parent c9919e57b3
commit 143c36e566
15 changed files with 887 additions and 182 deletions
+11
View File
@@ -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))
}
)
}
+96
View File
@@ -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: []
})
})
})
})
+82
View File
@@ -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<JiraProjectStatusOrder> {
// 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<JiraPagedResponse<JiraRecord>>(
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<unknown>(
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<string>()
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()
}
}
+8
View File
@@ -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<typeof getJiraProjectStatusOrder> {
return getJiraProjectStatusOrder(projectKey, siteId)
}
// ── Browser automation ──
private readonly browserCommands = new RuntimeBrowserCommands({
+8 -1
View File
@@ -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')
})
})
+11
View File
@@ -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)
})
]
+5
View File
@@ -121,6 +121,7 @@ import type {
JiraIssue,
JiraIssueFilter,
JiraIssueType,
JiraProjectStatusOrder,
JiraIssueUpdate,
JiraPriority,
JiraProject,
@@ -1931,6 +1932,10 @@ export type PreloadApi = {
siteId?: string
}) => Promise<JiraUser[]>
listTransitions: (args: { key: string; siteId?: string }) => Promise<JiraTransition[]>
getProjectStatusOrder: (args: {
projectKey: string
siteId?: string
}) => Promise<JiraProjectStatusOrder>
}
starNag: {
onShow: (
+6 -1
View File
@@ -25,6 +25,7 @@ import type {
GitHubAssignableUser,
GitHubCommentResult,
GitHubWorkItem,
JiraProjectStatusOrder,
GitPushTarget,
GitStagingArea,
GitForkSyncExpectedUpstream,
@@ -1665,7 +1666,11 @@ const api = {
}): Promise<unknown[]> => ipcRenderer.invoke('jira:listAssignableUsers', args),
listTransitions: (args: { key: string; siteId?: string }): Promise<unknown[]> =>
ipcRenderer.invoke('jira:listTransitions', args)
ipcRenderer.invoke('jira:listTransitions', args),
getProjectStatusOrder: (args: {
projectKey: string
siteId?: string
}): Promise<JiraProjectStatusOrder> => ipcRenderer.invoke('jira:getProjectStatusOrder', args)
},
starNag: {
+57 -180
View File
@@ -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<TaskSourceHostAvailability[]>(() => {
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<JiraPresetId>('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 {
</div>
) : null}
<div className="divide-y divide-border/50">
{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 (
<div
key={`${issue.siteId ?? 'site'}:${issue.key}`}
role="button"
tabIndex={0}
aria-current={selected ? 'true' : undefined}
data-current={selected ? 'true' : undefined}
onClick={() => 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'
)}
>
<span className="block truncate font-mono text-[12px] text-muted-foreground max-md:!hidden">
{issue.key}
</span>
<div className="min-w-0">
<div className="flex min-w-0 items-center gap-2">
<span className="shrink-0 font-mono text-[11px] text-muted-foreground md:hidden">
{issue.key}
</span>
<h3 className="min-w-0 truncate text-[13px] font-medium text-foreground">
{issue.title}
</h3>
</div>
<div className="mt-1 flex min-w-0 items-center gap-1.5 md:!hidden">
<span
className={cn(
'inline-flex min-w-0 items-center rounded-full border px-1.5 py-0.5 text-[11px] font-medium',
getJiraStatusTone(issue.status.categoryKey)
)}
>
<span className="truncate">{issue.status.name}</span>
</span>
<span className="shrink-0 text-[11px] text-muted-foreground">
{issue.priority?.name ??
translate('auto.components.TaskPage.713179dfdc', 'No priority')}
</span>
<span className="min-w-0 truncate text-[11px] text-muted-foreground">
{issue.assignee?.displayName ??
translate('auto.components.TaskPage.42a9160321', 'Unassigned')}
</span>
</div>
<div className="mt-1 flex min-w-0 items-center gap-1 max-lg:!hidden">
<span className="max-w-[160px] truncate text-[10px] text-muted-foreground xl:!hidden">
{contextLabel}
</span>
{labels.map((label) => (
<span
key={label}
className="max-w-[140px] truncate rounded-full border border-border/50 bg-muted/35 px-1.5 py-0.5 text-[10px] text-muted-foreground"
>
{label}
</span>
))}
{issue.labels.length > labels.length ? (
<span className="text-[10px] text-muted-foreground">
+{issue.labels.length - labels.length}
</span>
) : null}
</div>
</div>
<div className="flex min-w-0 max-md:!hidden">
<span
className={cn(
'inline-flex max-w-full items-center rounded-full border px-2 py-0.5 text-[11px] font-medium',
getJiraStatusTone(issue.status.categoryKey)
)}
>
<span className="truncate">{issue.status.name}</span>
</span>
</div>
<span className="block truncate text-[12px] text-muted-foreground max-md:!hidden">
{issue.priority?.name ??
translate('auto.components.TaskPage.713179dfdc', 'No priority')}
</span>
<div className="flex min-w-0 items-center gap-2 text-[12px] text-muted-foreground max-lg:!hidden">
{issue.assignee?.avatarUrl ? (
<img
src={issue.assignee.avatarUrl}
alt={issue.assignee.displayName}
className="size-5 shrink-0 rounded-full"
/>
) : (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border/50 bg-muted/40 text-[10px]">
{issue.assignee?.displayName?.slice(0, 1) ?? '-'}
</span>
)}
<span className="truncate">
{issue.assignee?.displayName ??
translate('auto.components.TaskPage.42a9160321', 'Unassigned')}
</span>
</div>
<Tooltip>
<TooltipTrigger asChild>
<div className="block min-w-0 truncate text-[12px] text-muted-foreground max-md:!hidden">
{formatRelativeTime(issue.updatedAt)}
</div>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{new Date(issue.updatedAt).toLocaleString()}
</TooltipContent>
</Tooltip>
<div className="flex shrink-0 items-center justify-end gap-1 md:opacity-0 md:transition-opacity md:group-hover/row:opacity-100 md:group-focus-within/row:opacity-100">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={(event) => {
event.stopPropagation()
handleUseJiraItem(issue)
}}
aria-label={translate(
'auto.components.TaskPage.ff90d0abc7',
'Start workspace from {{value0}}',
{ value0: issue.key }
)}
>
<ArrowRight className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{translate(
'auto.components.TaskPage.9497f2787c',
'Start workspace'
)}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={(event) => {
event.stopPropagation()
window.api.shell.openUrl(issue.url)
}}
aria-label={translate(
'auto.components.TaskPage.4ac8ff2275',
'Open {{value0}} in Jira',
{ value0: issue.key }
)}
>
<ExternalLink className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{translate('auto.components.TaskPage.eee68073b2', 'Open in Jira')}
</TooltipContent>
</Tooltip>
</div>
</div>
)
})}
</div>
<TaskPageJiraIssueList
formatUpdatedAt={formatRelativeTime}
getStatusTone={getJiraStatusTone}
issues={displayedJiraIssues}
onOpenIssue={openJiraDetailPage}
onStartWorkspace={handleUseJiraItem}
selectedIssue={selectedJiraIssue}
showSiteContext={selectedJiraSiteId === 'all'}
statusOrder={displayedJiraStatusOrder}
/>
</div>
<JiraIssueWorkspace
issue={selectedJiraIssue}
@@ -0,0 +1,171 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { TooltipProvider } from '@/components/ui/tooltip'
import { groupJiraIssuesByStatus, TaskPageJiraIssueList } from './task-page-jira-issue-list'
import {
getSingleJiraProjectScope,
loadTaskPageJiraProjectStatusOrder
} from './task-page-jira-status-order'
import type { JiraIssue, JiraProjectStatusOrder } from '../../../shared/types'
const { jiraGetProjectStatusOrderMock } = vi.hoisted(() => ({
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()
})
})
@@ -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<string, number> {
const ranks = new Map<string, number>()
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<string, number>
): 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<string, TaskPageJiraIssueSection>()
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.
<div
role="button"
tabIndex={0}
aria-current={selected ? 'true' : undefined}
data-current={selected ? 'true' : undefined}
onClick={() => 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'
)}
>
<span className="block truncate font-mono text-[12px] text-muted-foreground max-md:!hidden">
{issue.key}
</span>
<div className="min-w-0">
<div className="flex min-w-0 items-center gap-2">
<span className="shrink-0 font-mono text-[11px] text-muted-foreground md:hidden">
{issue.key}
</span>
<h3 className="min-w-0 truncate text-[13px] font-medium text-foreground">
{issue.title}
</h3>
</div>
<div className="mt-1 flex min-w-0 items-center gap-1.5 md:!hidden">
<span
className={cn(
'inline-flex min-w-0 items-center rounded-full border px-1.5 py-0.5 text-[11px] font-medium',
getStatusTone(issue.status.categoryKey)
)}
>
<span className="truncate">{issue.status.name}</span>
</span>
<span className="shrink-0 text-[11px] text-muted-foreground">
{issue.priority?.name ??
translate('auto.components.TaskPage.713179dfdc', 'No priority')}
</span>
<span className="min-w-0 truncate text-[11px] text-muted-foreground">
{issue.assignee?.displayName ??
translate('auto.components.TaskPage.42a9160321', 'Unassigned')}
</span>
</div>
<div className="mt-1 flex min-w-0 items-center gap-1 max-lg:!hidden">
<span className="max-w-[160px] truncate text-[10px] text-muted-foreground xl:!hidden">
{contextLabel}
</span>
{labels.map((label) => (
<span
key={label}
className="max-w-[140px] truncate rounded-full border border-border/50 bg-muted/35 px-1.5 py-0.5 text-[10px] text-muted-foreground"
>
{label}
</span>
))}
{issue.labels.length > labels.length ? (
<span className="text-[10px] text-muted-foreground">
+{issue.labels.length - labels.length}
</span>
) : null}
</div>
</div>
<div className="flex min-w-0 max-md:!hidden">
<span
className={cn(
'inline-flex max-w-full items-center rounded-full border px-2 py-0.5 text-[11px] font-medium',
getStatusTone(issue.status.categoryKey)
)}
>
<span className="truncate">{issue.status.name}</span>
</span>
</div>
<span className="block truncate text-[12px] text-muted-foreground max-md:!hidden">
{issue.priority?.name ?? translate('auto.components.TaskPage.713179dfdc', 'No priority')}
</span>
<div className="flex min-w-0 items-center gap-2 text-[12px] text-muted-foreground max-lg:!hidden">
{issue.assignee?.avatarUrl ? (
<img
src={issue.assignee.avatarUrl}
alt={issue.assignee.displayName}
className="size-5 shrink-0 rounded-full"
/>
) : (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border/50 bg-muted/40 text-[10px]">
{issue.assignee?.displayName?.slice(0, 1) ?? '-'}
</span>
)}
<span className="truncate">
{issue.assignee?.displayName ??
translate('auto.components.TaskPage.42a9160321', 'Unassigned')}
</span>
</div>
<Tooltip>
<TooltipTrigger asChild>
<div className="block min-w-0 truncate text-[12px] text-muted-foreground max-md:!hidden">
{formatUpdatedAt(issue.updatedAt)}
</div>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{new Date(issue.updatedAt).toLocaleString()}
</TooltipContent>
</Tooltip>
<div className="flex shrink-0 items-center justify-end gap-1 md:opacity-0 md:transition-opacity md:group-hover/row:opacity-100 md:group-focus-within/row:opacity-100">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={(event) => {
event.stopPropagation()
onStartWorkspace(issue)
}}
aria-label={translate(
'auto.components.TaskPage.ff90d0abc7',
'Start workspace from {{value0}}',
{ value0: issue.key }
)}
>
<ArrowRight className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{translate('auto.components.TaskPage.9497f2787c', 'Start workspace')}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={(event) => {
event.stopPropagation()
window.api.shell.openUrl(issue.url)
}}
aria-label={translate(
'auto.components.TaskPage.4ac8ff2275',
'Open {{value0}} in Jira',
{ value0: issue.key }
)}
>
<ExternalLink className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{translate('auto.components.TaskPage.eee68073b2', 'Open in Jira')}
</TooltipContent>
</Tooltip>
</div>
</div>
)
}
export function TaskPageJiraIssueList({
formatUpdatedAt,
getStatusTone,
issues,
onOpenIssue,
onStartWorkspace,
selectedIssue,
showSiteContext,
statusOrder
}: TaskPageJiraIssueListProps): React.JSX.Element {
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(() => new Set())
const sections = useMemo(
() => groupJiraIssuesByStatus(issues, statusOrder),
[issues, statusOrder]
)
return (
<div className="divide-y divide-border/50">
{sections.map((section) => {
const open = !collapsedGroups.has(section.key)
return (
<Collapsible
key={section.key}
open={open}
onOpenChange={(nextOpen) => {
setCollapsedGroups((current) => {
const next = new Set(current)
if (nextOpen) {
next.delete(section.key)
} else {
next.add(section.key)
}
return next
})
}}
>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="ghost"
className="h-9 w-full justify-start rounded-none bg-muted/35 px-3 text-left font-normal transition-colors hover:bg-accent focus-visible:bg-accent focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
>
{open ? (
<ChevronDown className="size-3 shrink-0 text-muted-foreground" />
) : (
<ChevronRight className="size-3 shrink-0 text-muted-foreground" />
)}
<span className="min-w-0 truncate text-[13px] font-medium text-foreground">
{section.label}
</span>
<span className="shrink-0 text-[11px] text-muted-foreground">
{section.issues.length}
</span>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="divide-y divide-border/50 border-t border-border/50">
{section.issues.map((issue) => (
<JiraIssueRow
key={`${issue.siteId ?? 'site'}:${issue.id || issue.key}`}
formatUpdatedAt={formatUpdatedAt}
getStatusTone={getStatusTone}
issue={issue}
onOpenIssue={onOpenIssue}
onStartWorkspace={onStartWorkspace}
selected={isSelectedIssue(issue, selectedIssue)}
showSiteContext={showSiteContext}
/>
))}
</CollapsibleContent>
</Collapsible>
)
})}
</div>
)
}
@@ -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<JiraProjectStatusOrder>()
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<JiraProjectStatusOrder> {
// 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: [] }
})
}
@@ -12,6 +12,7 @@ import type {
JiraMutationResult,
JiraPriority,
JiraProject,
JiraProjectStatusOrder,
JiraSiteSelection,
JiraTransition,
JiraUser,
@@ -280,3 +281,17 @@ export async function jiraListTransitions(
? callRuntimeRpc<JiraTransition[]>(target, 'jira.listTransitions', args, { timeoutMs: 30_000 })
: window.api.jira.listTransitions(args)
}
export async function jiraGetProjectStatusOrder(
settings: RuntimeJiraSettings,
projectKey: string,
siteId?: string | null
): Promise<JiraProjectStatusOrder> {
const target = getJiraRuntimeTarget(settings)
const args = { projectKey, siteId: siteId ?? undefined }
return target.kind === 'environment'
? callRuntimeRpc<JiraProjectStatusOrder>(target, 'jira.getProjectStatusOrder', args, {
timeoutMs: 30_000
})
: window.api.jira.getProjectStatusOrder(args)
}
+4
View File
@@ -81,6 +81,10 @@ export type JiraStatus = {
colorName?: string
}
export type JiraProjectStatusOrder = {
statusIdsByColumn: string[][]
}
export type JiraTransition = {
id: string
name: string
+1
View File
@@ -1844,6 +1844,7 @@ export type {
JiraMutationResult,
JiraPriority,
JiraProject,
JiraProjectStatusOrder,
JiraSite,
JiraSiteSelection,
JiraStatus,