All files / features / runs RunDetailPage.tsx

84.76% Statements 89/105
69% Branches 69/100
82.85% Functions 29/35
88.17% Lines 82/93

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                      55x   55x 55x 55x   66x 66x 66x 66x 66x 66x 66x 66x 66x 44x 1x     1x     1x         66x 24x   1x       1x 1x   66x                                         32x                               32x           32x 32x                                               32x 32x                 32x                   32x 32x 32x 32x 2x 2x 2x                   30x 30x 30x 30x 30x 30x 30x   32x   32x 32x 2x                 30x   32x   32x 32x 32x 32x   32x                   66x                       66x                                                                                 1x                                     2x              
import { useEffect, useMemo, useState, useRef } from 'react'
import { Outlet, useNavigate, useParams } from 'react-router-dom'
// depcruiser:ignore l3-not-lower — Custom view: live polling for run duration (wireframes/run-detail.md)
import { useEntityDetail } from '@/layers/L1/entityResolver'
import { Page, EntityDetail, Crud } from '@/layers/L2R'
import type { PageConfig, DetailConfig, CrudConfig } from '@/layers/interfaces'
import { Button } from '@/components/ui/button'
import { RunPhaseIcon } from '@/shared/components/RunPhaseIcon'
import { SourceBadge } from '@/shared/components/SourceBadge'
import { formatDateTime } from '@/shared/utils/format'
import { ErrorPanel, OutputPanel, TokenSummaryCards, CopyRunIdButton, type RunError } from './RunDetailPanels'
import { toast } from 'sonner'
 
const LIVE_DURATION_TICK_MS = 1_000
const RUNNING_REFETCH_MS = 5_000
 
export function RunDetailPage() {
  const nav = useNavigate()
  const { id } = useParams<{ id: string }>()
  const { data: run, refetch } = useEntityDetail('runs', id ?? '')
  const [menuOpen, setMenuOpen] = useState(false)
  const menuRef = useRef<HTMLDivElement>(null)
 
  const phase = (run?.phase as string | undefined) ?? 'pending'
  const isRunning = phase === 'running'
 
  useEffect(() => {
    if (!isRunning) return
    const liveTick = setInterval(() => {
      // local re-render driver for live-duration; no remote fetch
    }, LIVE_DURATION_TICK_MS)
    const refetchTick = setInterval(() => {
      void refetch()
    }, RUNNING_REFETCH_MS)
    return () => {
      clearInterval(liveTick)
      clearInterval(refetchTick)
    }
  }, [isRunning, refetch])
 
  useEffect(() => {
   I if (!menuOpen) return
    function handleClick(e: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [menuOpen])
 
  const detailConfig: DetailConfig = useMemo(() => ({
    entityPath: 'runs',
    title: 'Run',
    readGrouping: [
      {
        label: 'Details',
        fields: [
          'run_id',
          'phase',
          'source_type',
          'source_metadata',
          'project_name',
          'pipeline_name',
          'duration',
          'started_at',
          'completed_at',
          'created_at',
          'tokens',
          'exit_code',
        ],
      },
    ],
    fieldFormatters: {
      run_id: (value: unknown) => (
        <span className="inline-flex items-center gap-2 font-mono">
          <span>{String(value ?? '')}</span>
          <CopyRunIdButton runId={String(value ?? '')} />
        </span>
      ),
      phase: (value: unknown) => (
        <RunPhaseIcon phase={((value ?? 'pending') as 'pending' | 'running' | 'succeeded' | 'failed')} />
      ),
      source_type: (value: unknown, entity: Record<string, unknown>) => {
        const meta = entity.source_metadata as { issue_key?: string } | undefined
        return (
          <span className="inline-flex items-center gap-1">
            <SourceBadge source={((value ?? 'manual') as 'manual' | 'webhook' | 'api' | 'schedule')} />
            {meta?.issue_key && (
              <span className="text-xs text-muted-foreground">({meta.issue_key})</span>
            )}
          </span>
        )
      },
      source_metadata: () => null,
      project_name: (value: unknown, entity: Record<string, unknown>) => (
        <a href={`#/projects/${entity.project_id}`} className="text-primary hover:underline">
          {String(value ?? '')}
        </a>
      ),
      pipeline_name: (value: unknown, entity: Record<string, unknown>) => (
        <a href={`#/pipelines/${entity.pipeline_id}`} className="text-primary hover:underline">
          {String(value ?? '')}
        </a>
      ),
      duration: (_value: unknown, entity: Record<string, unknown>) => {
        const started = entity.started_at as string | undefined
        const completed = entity.completed_at as string | undefined
        const entityPhase = entity.phase as string | undefined
        if (entityPhase === 'running') {
          const startedMs = started ? new Date(started).getTime() : null
          const liveMs = startedMs ? Date.now() - startedMs : null
          return (
            <span className="text-blue-500" data-testid="duration-running">
              {liveMs == null ? 'running' : `${Math.floor(liveMs / 1000)}s`}
            </span>
          )
        }
        const ms =
          started && completed
            ? new Date(completed).getTime() - new Date(started).getTime()
            : null
        if (ms == null) return '\u2014'
        const totalSec = Math.floor(ms / 1000)
        if (totalSec < 60) return `${totalSec}s`
        const m = Math.floor(totalSec / 60)
        const s = totalSec % 60
        return s > 0 ? `${m}m ${s}s` : `${m}m`
      },
      started_at: (value: unknown) => formatDateTime(value as string | null | undefined),
      completed_at: (value: unknown, entity: Record<string, unknown>) => {
        const entityPhase = entity.phase as string | undefined
        if (entityPhase === 'running') {
          return <span className="text-blue-500">Running...</span>
        }
        return formatDateTime(value as string | null | undefined)
      },
      created_at: (value: unknown) => formatDateTime(value as string | null | undefined),
      tokens: (_value: unknown, entity: Record<string, unknown>) => {
        const input = entity.token_input as number | undefined
        const output = entity.token_output as number | undefined
        if (input == null && output == null) return '\u2014'
        return `${(input ?? 0).toLocaleString()} in / ${(output ?? 0).toLocaleString()} out`
      },
      exit_code: (value: unknown) =>
        value == null ? (
          '\u2014'
        ) : (
          <span className="font-mono">{String(value)}</span>
        ),
    },
  }), [])

  coInst crudConfig: CrudConfig = {
    entityPath: 'runs',
    IfieldSet: [
      { field: 'pipeline_id', title: 'Pipeline' },
      { field: 'source_type', title: 'Source Type' },
    ],
    successTarget: '/runs/:id',
    cancelTarget: `/runs/${id}`,
  }
 
  const pageConfig: PageConfig = {
    title: run ? `run #${String(run.run_number ?? '')}` : 'Run',
    breadcrumbs: [
      { label: 'Dashboard', href: '/' },
      { label: 'Projects', href: '/projects' },
      ...(run?.project_name
        ? [{ label: String(run.project_name), href: `/projects/${run.project_id}` }]
        : []),
      ...(run?.pipeline_name
        ? [{ label: String(run.pipeline_name), href: `/pipelines/${run.pipeline_id}` }]
        : []),
      { label: run ? `run #${String(run.run_number ?? '')}` : id?.split('-')[0] ?? '' },
    ],
    actions: (
      <div className="flex items-center gap-2" data-testid="run-detail-actions">
        <Button
    I      variant="outline"
          size="sm"
          type="button"
          onClick={() => nav('/runs')}
          data-testid="back-to-runs"
        >
          Back to Runs
        </Button>
        <Button
          variant="default"
          size="sm"
          type="button"
          onClick={() => nav(`/runs/${id}/re-run`)}
          data-testid="re-run-button"
        >
          Re-run
        </Button>
        {run && (
          <div className="relative" ref={menuRef}>
            <Button
              variant="ghost"
              size="icon"
              type="button"
              aria-label="More actions"
              aria-haspopup="true"
              aria-expanded={menuOpen}
              data-testid="run-more-menu"
              onClick={() => setMenuOpen((v) => !v)}
            >
              <span aria-hidden>⋮</span>
            </Button>
            {menuOpen && (
              <div
                role="menu"
                className="absolute right-0 top-full z-20 mt-1 w-48 rounded-md border border-border bg-card shadow-lg"
                data-testid="run-more-menu-panel"
              >
                <button
                  type="button"
                  role="menuitem"
                  className="block w-full px-4 py-2 text-left text-sm hover:bg-accent"
                  data-testid="menu-copy-run-id"
                  onClick={() => {
                    void navigator.clipboard.writeText(String(run.run_id ?? '')).then(() => {
                      toast.success('Run ID copied')
                    })
                    setMenuOpen(false)
                  }}
                >
                  Copy Run ID
                </button>
                <button
                  type="button"
                  role="menuitem"
                  className="block w-full px-4 py-2 text-left text-sm hover:bg-accent"
                  data-testid="menu-view-project"
                  onClick={() => {
                    nav(`/projects/${run.project_id}`)
                    setMenuOpen(false)
                  }}
                >
                  View Project
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    ),
  }
 
  const error: RunError | null = useMemo(() => {
    if (!run || run.error == null) return null
    return run.error as RunError
  }, [run])
 
  const output: string | null = useMemo(() => {
    if (!run || run.output == null) return null
    return String(run.output)
  }, [run])
 
  return (
    <Page config={pageConfig}>
      <EntityDetail config={detailConfig} />
      {error && <ErrorPanel error={error} />}
      {output && <OutputPanel output={output} />}
      <TokenSummaryCards tokenInput={run?.token_input as number | undefined} tokenOutput={run?.token_output as number | undefined} />
      <Crud config={crudConfig} />
      <Outlet />
    </Page>
  )
}