Files
CollabTable/shared/media-webui/src/lib/components/AnalyzerLiveStatus.svelte
T

209 lines
8.3 KiB
Svelte

<script lang="ts">
import { Badge, Button, Card, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { post } from '$lib/api'
type Json = Record<string, unknown>
type StatusTone = 'default' | 'primary' | 'success' | 'warning' | 'danger'
let {
status = {},
stats = {},
loading = false,
description = 'Current analyzer worker state.',
}: { status?: Json; stats?: Json; loading?: boolean; description?: string } = $props()
// discovering/extracting/cleaning all share one backend scan slot (see scanCancel on the Go
// side), so they stop through the same endpoint; generate/analyze/the legacy extract worker
// each have their own. "clearing" (database clear) has no entry - that reset runs synchronously
// on the request that started it, so there's nothing separate left to cancel.
const STOP_ENDPOINTS: Record<string, string> = {
discovering: 'scan/stop',
extracting: 'scan/stop',
cleaning: 'scan/stop',
generating: 'generate/stop',
analyzing: 'analyze/stop',
processing: 'extract/stop',
}
let stopping = $state(false)
function asRecord(value: unknown): Json {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
}
function firstRecord(...values: unknown[]): Json {
for (const value of values) {
const record = asRecord(value)
if (Object.keys(record).length > 0) return record
}
return {}
}
function numeric(source: Json, key: string, fallback = 0) {
const value = Number(source[key] ?? fallback)
return Number.isFinite(value) ? value : fallback
}
function formatTimestamp(value: unknown) {
if (value === null || value === undefined) return '—'
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? '—' : value.toLocaleString()
}
const raw = String(value).trim()
if (!raw) return '—'
const numericValue = Number(raw)
const timestamp =
Number.isFinite(numericValue) && /^-?\d+(?:\.\d+)?$/.test(raw)
? Math.abs(numericValue) < 100_000_000_000
? numericValue * 1000
: numericValue
: Date.parse(raw)
if (!Number.isFinite(timestamp) || timestamp <= 0) return '—'
return new Date(timestamp).toLocaleString()
}
function stateTone(label: string, running: boolean, paused: boolean): StatusTone {
if (running) return paused ? 'warning' : 'primary'
if (label.includes('error') || label.includes('failed')) return 'danger'
if (['idle', 'completed', 'complete', 'done'].includes(label)) return 'success'
return 'default'
}
const extractionProgress = $derived(asRecord(status.extractionProgress))
const queue = $derived(firstRecord(status.queue, extractionProgress, stats, status))
const currentJob = $derived(asRecord(status.current))
const stateLabel = $derived(
String(
status.state ||
status.status ||
(status.running === true ? (status.paused === true ? 'paused' : 'running') : 'idle'),
),
)
const stateKey = $derived(stateLabel.toLowerCase())
const running = $derived(
status.running === true ||
status.extracting === true ||
status.processing === true ||
['running', 'extracting', 'processing', 'discovering', 'generating', 'analyzing', 'cleaning', 'clearing'].includes(
stateKey,
),
)
const paused = $derived(status.paused === true || stateKey.includes('paused'))
// `status.queue` (a raw media_worker_jobs count) is misleading here: those rows go straight to
// "done" on discovery and never actually sit in "queued"/"processing", so that count is always
// 0 regardless of how much metadata/thumbnail/AI-analysis work is really pending. `stats` -
// summed from the same per-stage pipeline breakdown the dashboard/discover pages render below
// this card - is the real number, so it takes priority; the job-table queue is just a fallback
// for callers that only ever pass `status`.
const queued = $derived(numeric(stats, 'queued', numeric(queue, 'queued', numeric(status, 'queued'))))
const processing = $derived(
numeric(stats, 'processing', numeric(queue, 'processing', numeric(status, 'processing'))),
)
const total = $derived(numeric(status, 'total', numeric(extractionProgress, 'total')))
const completed = $derived(
numeric(
status,
'completed',
numeric(queue, 'completed', numeric(queue, 'done', numeric(extractionProgress, 'extracted'))),
),
)
const failed = $derived(numeric(status, 'failed', numeric(queue, 'failed')))
const progressCompleted = $derived(completed + failed)
const progressPercent = $derived(total > 0 ? Math.min(100, (progressCompleted / total) * 100) : 0)
const current = $derived(
typeof status.current === 'string'
? status.current
: String(currentJob.fileName || currentJob.file_name || currentJob.filePath || currentJob.file_path || '—'),
)
const worker = $derived(String(status.worker || status.activeWorker || '—'))
const lastUpdate = $derived(
formatTimestamp(status.updatedAt || status.updated_at || status.timestamp || status.finishedAt),
)
const lastError = $derived(String(status.lastError || status.error || ''))
const tone = $derived(stateTone(stateKey, running, paused))
const stopEndpoint = $derived(STOP_ENDPOINTS[stateKey])
const canStop = $derived(running && !!stopEndpoint)
async function stopAction() {
if (!stopEndpoint) return
stopping = true
try {
await post(`/api/${stopEndpoint}`)
notify.success('Stop requested.')
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to stop the running action.')
} finally {
stopping = false
}
}
</script>
<Card class="space-y-4">
<SectionTitle title="Live status" {description} />
{#if loading}
<p class="text-sm text-muted-fg">Loading status…</p>
{:else}
<div class="space-y-3" aria-live="polite">
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-muted-fg">State</span>
<div class="flex items-center gap-2">
<Badge variant={tone}>{stateLabel}</Badge>
{#if canStop}
<Button variant="danger" size="sm" disabled={stopping} onclick={() => void stopAction()}>
{stopping ? 'Stopping…' : 'Stop'}
</Button>
{/if}
</div>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-muted-fg">Pending</span>
<span class="text-sm text-fg">{queued}</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-muted-fg">Processing</span>
<span class="text-sm text-fg">{processing}</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-muted-fg">Worker</span>
<span class="text-sm text-fg">{worker}</span>
</div>
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-muted-fg">Current item</span>
<span class="max-w-52 truncate text-right text-xs text-muted-fg">{current}</span>
</div>
{#if total > 0}
<div>
<div class="mb-1 flex justify-between text-xs text-muted-fg">
<span>Progress</span>
<span>{progressCompleted} / {total}</span>
</div>
<div class="h-2 overflow-hidden rounded-full bg-surface-hover">
<div class="h-full rounded-full bg-primary transition-[width]" style={`width: ${progressPercent}%`}></div>
</div>
</div>
{:else if running && progressCompleted > 0}
<div>
<div class="mb-1 flex justify-between text-xs text-muted-fg">
<span>Progress</span>
<span>{progressCompleted} processed</span>
</div>
<div class="h-2 overflow-hidden rounded-full bg-surface-hover">
<div class="h-full w-1/3 animate-pulse rounded-full bg-primary"></div>
</div>
</div>
{/if}
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-muted-fg">Last update</span>
<span class="max-w-52 truncate text-right text-xs text-muted-fg">{lastUpdate}</span>
</div>
{#if lastError}
<p class="rounded-md border border-danger/30 bg-danger/10 p-3 text-xs text-danger">{lastError}</p>
{/if}
</div>
{/if}
</Card>