All files / features / runs RunsPage.tsx

64.17% Statements 86/134
64.28% Branches 45/70
57.5% Functions 23/40
66.66% Lines 80/120

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347                            39x   39x   570x 570x 570x 570x 550x 542x 542x 420x 420x 420x     2x 2x 2x 2x 2x 2x     570x 570x 570x 570x           570x                                                                                                                                                             39x 12x   39x   570x 570x 570x     62x 62x 62x 62x 62x 62x                         62x 62x 62x 62x 62x 62x 62x 62x         570x                   570x     1x                       570x                             570x                   570x                           570x 570x 570x                       570x 570x 570x 570x                   570x             62x                                                       114x                                                                                   62x 62x                   62x 62x
import { useState, useRef, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { Play } from 'lucide-react'
import { useRuns, useCreateRun } from './runsApi'
import { useProjects } from '@/features/projects/projectsApi'
import { usePipelines } from '@/features/pipelines/pipelinesApi'
import { useFilterState } from '@/shared/hooks/useFilterState'
import { DataTable, type Column } from '@/shared/components/DataTable'
import { ManualTriggerModal } from '@/shared/components/ManualTriggerModal'
import { RunPhaseIcon } from '@/shared/components/RunPhaseIcon'
import { SourceBadge } from '@/shared/components/SourceBadge'
import { DurationDisplay } from '@/shared/components/DurationDisplay'
import { Button } from '@/components/ui/button'
import { toast } from 'sonner'
 
function relativeTime(dateStr: string | undefined): string {
  if (!dateStr) return '\u2014'
  const diff = Date.now() - new Date(dateStr).getTime()
 I const mins = Math.floor(diff / 60000)
  if (mins < 1) return 'now'
  if (mins < 60) return `${mins} min ago`
  const hours = Math.floor(mins / 60)
  if (hours < 24) return `${hours}h ago`
  const days = Math.floor(hours / 24)
  if (days < 7) return `${days}d ago`
  return new Date(dateStr).toLocaleDateString()
}I
 
function toISODate(duration: string): string {
  const match = duration.match(/^(\d+)(h|d)$/)
  if (!match) return ''
 I const amount = parseInt(match[1])
  const unit = match[2]
  const ms = unit === 'h' ? amount * 3600000 : amount * 86400000
  return new Date(Date.now() - ms).toISOString()
}
 
function ActionsMenu({ item }: { item: Record<string, unknown> }) {
  const navigate = useNavigate()
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)
 
  function handleCopyRunId() {
    navigator.clipboard.writeText(item.run_id as string)
    toast.success('Run ID copied')
    setOpen(false)
  }
 
  return (
    <div ref={ref} className="relative">
      <button
        onClick={(e) => { e.stopPropagation(); setOpen(!open) }}
        className="rounded-md px-2 py-1 text-muted-foreground hover:bg-accent"
        aria-label="Actions"
      >
        ⋮
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
          <div className="absolute right-0 z-20 w-40 rounded-md border border-border bg-card shadow-lg">
            <button
              onClick={(e) => { e.stopPropagation(); navigate(`/runs/${item.run_id as string}`); setOpen(false) }}
              className="block w-full px-4 py-2 text-left text-sm hover:bg-accent"
            >
              View Details
            </button>
            <button
              onClick={(e) => { e.stopPropagation(); navigate('/runs'); setOpen(false) }}
              className="block w-full px-4 py-2 text-left text-sm hover:bg-accent"
            >
              Re-run
            </button>
            <button
              onClick={(e) => { e.stopPropagation(); handleCopyRunId() }}
              className="block w-full px-4 py-2 text-left text-sm hover:bg-accent"
            >
              Copy Run ID
            </button>
          </div>
        </>
      )}
    </div>
  )
}
 
function sourceLabel(source: string, metadata: Record<string, unknown> | null | undefined): string {
  if (metadata?.origin === 'jira') return 'jira'
  if (metadata?.origin === 'vikunja') return 'vikunja'
  return source
}
 
export function RunsPage() {
  const navigate = useNavigate()
  const pageSize = 25
  const { data: projectsData } = useProjects()
  const createRun = useCreateRun()
 
  const { filters, sortKey, sortOrder, setFilter, setSort, clearFilters } = useFilterState({
    keys: ['phase', 'project_id', 'source_type', 'created_after', 'offset'],
    defaults: { sort: 'created_at', order: 'desc' },
  })
 
  const page = parseInt(filters.offset ?? '0')
  const setPage = (p: number) => setFilter('offset', p > 0 ? String(p) : undefined)
 
  const [modalOpen, setModalOpen] = useState(false)
  const [selectedProjectId, setSelectedProjectId] = useState('')
  const { data: pipelinesData } = usePipelines(selectedProjectId)
 
  const projects = projectsData?.data ?? []
  const pipelines = pipelinesData?.data ?? []
 
  const columns: Column[] = [
    {
      key: 'phase',
      label: 'Phase',
      sortable: true,
      render: (item) => (
        <RunPhaseIcon phase={item.phase as 'pending' | 'running' | 'succeeded' | 'failed'} />
      ),
    },
    {
      key: 'project_name',
      label: 'Project',
      sortable: true,
      render: (item) => (
        <a
          href={`#/projects/${item.project_id as string}`}
          className="text-primary hover:underline"
          onClick={(e) => e.stopPropagation()}
 I       >
 I         {item.project_name as string}
        </a>
      ),
    },
    {
      key: 'pipeline_name',
      label: 'Pipeline',
      sortable: true,
      render: (item) => (
        <a
            href={`#/pipelines/${item.pipeline_id as string}`}
          className="text-primary hover:underline"
          onClick={(e) => e.stopPropagation()}
        >
          {item.pipeline_name as string}
        </a>
      ),
    },
    {
      key: 'source_type',
      label: 'Source',
      sortable: true,
      render: (item) => (
        <SourceBadge source={sourceLabel(item.source_type as string, item.source_metadata as Record<string, unknown> | null | undefined) as 'manual' | 'webhook' | 'schedule' | 'cli'} />
      ),
    },
    {
      key: 'created_at',
      label: 'Created',
      sortable: true,
      render: (item) => (
        <span className="text-sm text-muted-foreground">{relativeTime(item.created_at as string)}</span>
      ),
    },
    {
      key: 'tokens',
      label: 'Tokens',
      sortable: true,
      render: (item) => {
        const input = item.token_input as number
        const output = item.token_output as number
        return <span>{(input + output).toLocaleString()}</span>
      },
    },
    {
      key: 'duration',
      label: 'Duration',
      sortable: true,
      render: (item) => {
        const started = item.started_at as string | null
        const completed = item.completed_at as string | null
        const ms =
          started && completed
            ? new Date(completed).getTime() - new Date(started).getTime()
            : null
        return <DurationDisplay ms={ms} />
      },
    },
    {
      key: 'actions',
      label: 'Actions',
      render: (item) => <ActionsMenu item={item} />,
    },
  ]
 
  const filterDefs = [
    {
      key: 'phase',
      label: 'Phase',
      type: 'multi-select' as const,
      options: [
        { value: 'pending', label: 'Pending' },
        { value: 'running', label: 'Running' },
        { value: 'succeeded', label: 'Succeeded' },
        { value: 'failed', label: 'Failed' },
      ],
    },
    {
      key: 'project_id',
      label: 'Project',
      type: 'multi-select' as const,
      options: projects.map((p) => ({ value: p.id, label: p.name })),
    },
    {
      key: 'source_type',
      label: 'Source',
      type: 'multi-select' as const,
      options: [
        { value: 'manual', label: 'Manual' },
        { value: 'webhook', label: 'Webhook' },
        { value: 'schedule', label: 'Schedule' },
        { value: 'cli', label: 'CLI' },
        { value: 'jira', label: 'Jira' },
        { value: 'vikunja', label: 'Vikunja' },
      ],
    },
    {
      key: 'created_after',
      label: 'Date Range',
      type: 'date-range' as const,
    },
  ]
 
  const createdAfter = useMemo(
    () => filters.created_after ? toISODate(filters.created_after) : undefined,
    [filters.created_after],
  )
 
  const { data, isLoading, error, refetch } = useRuns({
    limit: pageSize,
    offset: page * pageSize,
    phase: filters.phase,
    project_id: filters.project_id,
    source_type: filters.source_type,
    created_after: createdAfter,
    sort: sortKey,
    order: sortOrder,
  })
 
  const runs = data?.data ?? []
  const hasMore = data?.meta?.has_more ?? false
  const totalEstimate = data?.meta?.total_estimate
    ?? (hasMore ? null : page * pageSize + (data?.meta?.returned ?? 0))
 
  function handleTriggerRun(pipelineId: string, issueKey?: string, additionalData?: string) {
    let sourceMetadata: Record<string, unknown> | null = null
    if (issueKey || additionalData) {
      sourceMetadata = {}
      if (issueKey) sourceMetadata.issue_key = issueKey
      if (additionalData) {
        try {
          const parsed = JSON.parse(additionalData)
          Object.assign(sourceMetadata, parsed)
        } catch {
          sourceMetadata.additional_data = additionalData
        }
      }
    }
    createRun.mutate(
      { pipeline_id: pipelineId, source_type: 'manual', source_metadata: sourceMetadata as never },
      {
        onSuccess: (run) => {
          setModalOpen(false)
          setSelectedProjectId('')
          navigate(`/runs/${run.run_id}`)
        },
      },
    )
  }
 
  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Runs</h1>
        <Button onClick={() => setModalOpen(true)}>
          <Play className="mr-2 h-4 w-4" />
          New Run
        </Button>
      </div>
 
      <DataTable
        columns={columns}
        data={runs as unknown as Record<string, unknown>[]}
        isLoading={isLoading}
        error={error ?? null}
        onRetry={() => refetch()}
        emptyMessage="No runs yet"
        sortKey={sortKey}
        sortOrder={sortOrder}
        onSort={(key) => setSort(key)}
        onRowClick={(item) => navigate(`/runs/${item.run_id as string}`)}
        filters={filterDefs}
        filterValues={filters}
        onFilterChange={setFilter}
        onFiltersClear={clearFilters}
      />
 
      {runs.length > 0 && (
        <div className="flex flex-col items-center gap-2">
          <div className="flex items-center justify-center gap-2">
            <Button
              variant="outline"
              disabled={page === 0}
              onClick={() => setPage(page - 1)}
            >
              Previous
            </Button>
            <span className="text-sm text-muted-foreground">Page {page + 1}</span>
            <Button
              variant="outline"
              disabled={!hasMore}
              onClick={() => setPage(page + 1)}
            >
              Next
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">
            Showing {page * pageSize + 1} - {Math.min((page + 1) * pageSize, page * pageSize + runs.length)} of{' '}
            {totalEstimate != null ? `${totalEstimate} runs` : `${page * pageSize + runs.length}+ runs`}
          </p>
        </div>
      )}
 
      <ManualTriggerModal
        open={modalOpen}
        projects={projects}
        pipelines={pipelines}
        onProjectChange={(pid) => setSelectedProjectId(pid)}
        onSubmit={handleTriggerRun}
        onCancel={() => { setModalOpen(false); setSelectedProjectId('') }}
      />
    </div>
  )
}