All files / features / projects ProjectDetailPage.tsx

52.32% Statements 45/86
59.25% Branches 32/54
31.57% Functions 12/38
55% Lines 44/80

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                                        69x   69x   60x 60x 60x           69x       60x                 60x                           60x                 60x                       60x                         60x 60x                 26x 26x 26x 26x 26x 26x 26x 26x   26x 26x   26x         26x 26x 26x 26x 26x 26x 26x                                                                                                                                                                                                                                                                                                                                                            
import { useState, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { type CrudFormRef as ProjectFormRef } from '@/features/projects/components/ProjectForm'
import { ProjectForm } from '@/features/projects/components/ProjectForm'
import { type CrudFormRef as PipelineFormRef } from '@/features/pipelines/components/PipelineForm'
import { PipelineForm } from '@/features/pipelines/components/PipelineForm'
import { useProject, useDeleteProject } from './projectsApi'
import { usePipelines } from '@/features/pipelines/pipelinesApi'
import { useProjectRunFiltersAndData } from './hooks/useProjectRunFiltersAndData'
import { usePipelineColumns } from '@/features/pipelines/hooks/usePipelineColumns'
import { DataTable } from '@/shared/components/DataTable'
import { CrudModal } from '@/shared/components/CrudModal'
import { CrudReadCard } from '@/shared/components/CrudReadCard'
import { Page } from '@/shared/components/Page'
import { ConfirmDialog } from '@/shared/components/ConfirmDialog'
import { RunPhaseIcon } from '@/shared/components/RunPhaseIcon'
import { SourceBadge } from '@/shared/components/SourceBadge'
import { DurationDisplay } from '@/shared/components/DurationDisplay'
import { formatDateTime, formatRelativeTime } from '@/shared/utils/format'
import type { components } from '@/types/api'
import { Button } from '@/components/ui/button'
 
type Run = components['schemas']['Run']
type Pipeline = components['schemas']['Pipeline']
I
fIunction abbreviatedNumber(n: number | undefined): string {
 E if (n == null) return '\u2014'
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
  return String(n)
}
 
function is404(err: Error): boolean {
  return (err as { response?: { status?: number } })?.response?.status === 404
}
 
const runsColumns = [
  {
    key: 'phase',
    label: 'Phase',
    render: (item: Run) => (
      <RunPhaseIcon phase={item.phase ?? 'pending'} />
    ),
  },
  {
    key: 'pipeline_name',
    label: 'Pipeline',
    render: (item: Run) => (
      <a
        href={`#/pipelines/${item.pipeline_id}`}
        className="text-primary underline-offset-4 hover:underline"
        onClick={(e) => e.stopPropagation()}
      >
        {item.pipeline_name}
      </a>
    ),
  },
  {
    key: 'source_type',
    label: 'Source',
    render: (item: Run) => (
      <SourceBadge source={item.source_type ?? 'manual'} />
    ),
  },
  {
    key: 'created_at',
    label: 'Created',
    render: (item: Run) => (
      <span className="text-sm text-muted-foreground">
        {formatRelativeTime(item.created_at)}
      </span>
    ),
  },
  {
    key: 'tokens',
    label: 'Tokens',
    render: (item: Run) => (
      <span className="text-sm text-muted-foreground">
        {abbreviatedNumber(
          (item.token_input ?? 0) + (item.token_output ?? 0) || undefined,
        )}
      </span>
    ),
  },
  {
    key: 'duration',
    label: 'Duration',
    render: (item: Run) => {
      const ms =
        item.started_at && item.completed_at
          ? new Date(item.completed_at).getTime() -
            new Date(item.started_at).getTime()
          : null
      return <DurationDisplay ms={ms} />
    },
  },
]
 
export function ProjectDetailPage() {
  const { id } = useParams<{ id: string }>()
  const [searchParams, setSearchParams] = useSearchParams()
  const nav = useNavigate()
  const { data, isLoading, error, refetch } = useProject(id ?? '')
  const deleteProject = useDeleteProject()
  const [showDelete, setShowDelete] = useState(false)
 
  const project = data?.project

  // Pipelines
  const pipelineCols = usePipelineColumns()
  const { data: pipelinesData, isLoading: pipelinesLoading } = usePipelines(
    id ?? '',
  )

  // Runs (SSE)
  const {
    data: runsData,
    isLoading: runsLoading,
    sse,
  } = useProjectRunFiltersAndData({ prefix: 'pruns', projectId: id ?? '' })
 
  // Modal state
  const [formDirty, setFormDirty] = useState(false)
  const [formPending, setFormPending] = useState(false)
  const projFormRef = useRef<ProjectFormRef>(null)
  const pipeFormRef = useRef<PipelineFormRef>(null)
 
  const showEditProject = searchParams.get('editProject') === 'true'
  const showCreatePipeline = searchParams.get('create') === 'true'
 
  return (
    <Page>
      <CrudReadCard
        title={project?.name ?? 'Project'}
        breadcrumbs={[
          { label: 'Dashboard', href: '/' },
          { label: 'Projects', href: '/projects' },
          { label: project?.name ?? '...' },
        ]}
        fields={[
          { label: 'Name', value: project?.name, spanFull: true },
          {
            label: 'Description',
            value: project?.description || '\u2014',
            spanFull: true,
          },
          {
            label: 'Created',
            value: formatDateTime(project?.created_at),
          },
          {
            label: 'Updated',
            value: formatDateTime(project?.updated_at),
          },
        ]}
        actions={{
          edit: {
            onClick: () =>
              setSearchParams((prev) => {
                prev.set('editProject', 'true')
                return prev
              }),
          },
          delete: {
            onClick: () => setShowDelete(true),
            entityName: project?.name ?? 'this project',
          },
        }}
        isLoading={isLoading}
        error={error}
        is404={error ? is404(error) : false}
        onRetry={refetch}
        backPath="/projects"
      />
 
      <h2 className="text-lg font-semibold">Pipelines</h2>
      <DataTable<Pipeline>
        prefix="plines"
        columns={pipelineCols}
        data={pipelinesData?.data}
        isLoading={pipelinesLoading}
        entityName="Pipeline"
        add={{
          onAdd: () =>
            setSearchParams((prev) => {
              prev.set('create', 'true')
              return prev
            }),
          label: 'New Pipeline',
        }}
        onRowClick={(item) => nav(`/pipelines/${item.id}`)}
      />
 
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Recent Runs</h2>
        <Button
          variant="outline"
          size="sm"
          onClick={() =>
            nav(
              `/runs?runs_project_id=${id}&runs_sort=created_at&runs_order=desc`,
            )
          }
        >
          View All Runs &rarr;
        </Button>
      </div>
      <DataTable<Run>
        prefix="pruns"
        columns={runsColumns}
        data={runsData}
        isLoading={runsLoading}
        sse={sse}
        onRowClick={(item) => nav(`/runs/${item.run_id}`)}
      />
 
      {/* Project Edit Modal */}
      <CrudModal
        open={showEditProject}
        title="Edit Project"
        isDirty={formDirty}
        isPending={formPending}
        onClose={() =>
          setSearchParams((prev) => {
            prev.delete('editProject')
            return prev
          })
        }
        onSave={() => projFormRef.current?.submit()}
      >
        <ProjectForm
          ref={projFormRef}
          id={id}
          defaults={{
            name: project?.name,
            repo_url: project?.repo_url,
            description: project?.description,
          }}
          onSuccess={() => {
            setSearchParams({})
            refetch()
          }}
          onClose={() =>
            setSearchParams((prev) => {
              prev.delete('editProject')
              return prev
            })
          }
          onDirtyChange={setFormDirty}
          onPendingChange={setFormPending}
        />
      </CrudModal>

      {/* Pipeline Create Modal */}
      <CrudModal
        open={showCreatePipeline}
        title="New Pipeline"
        isDirty={formDirty}
        isPending={formPending}
        saveLabel="Create"
        onClose={() =>
          setSearchParams((prev) => {
            prev.delete('create')
            return prev
          })
        }
        onSave={() => pipeFormRef.current?.submit()}
      >
        <PipelineForm
          ref={pipeFormRef}
          projectId={id ?? ''}
          onSuccess={(result) => {
            nav(`/pipelines/${result.id}`, { replace: true })
          }}
          onClose={() =>
            setSearchParams((prev) => {
              prev.delete('create')
              return prev
            })
          }
          onDirtyChange={setFormDirty}
          onPendingChange={setFormPending}
        />
      </CrudModal>
 
      {/* Delete Confirm */}
      <ConfirmDialog
        open={showDelete}
        title="Delete project"
        message={`Are you sure you want to delete '${project?.name ?? 'this project'}'? This will also delete all associated pipelines.`}
        onConfirm={() =>
          deleteProject.mutate(id ?? '', {
            onSuccess: () => nav('/projects', { replace: true }),
          })
        }
        onCancel={() => setShowDelete(false)}
      />
    </Page>
  )
}