Files
CollabTable/shared/webui/src/lib/features/AnalyzerWorkspace.svelte
T

620 lines
26 KiB
Svelte
Raw Normal View History

2026-09-01 08:43:25 +02:00
<script lang="ts">
import { AlertTriangle, Play, Plus, RefreshCw, Trash2 } from '@lucide/svelte'
import { onMount } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
2026-09-03 00:16:55 +02:00
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
2026-09-01 08:43:25 +02:00
import { del, get, post } from '$lib/api'
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
import AnalyzerLiveStatus from '$lib/components/AnalyzerLiveStatus.svelte'
import AnalyzerPipelineBreakdown from '$lib/components/AnalyzerPipelineBreakdown.svelte'
import { cn } from '$lib/utils/cn'
type Json = Record<string, unknown>
let { panel = 'dashboard' }: { panel?: string } = $props()
let stats = $state<Json>({})
let status = $state<Json>({})
let schedules = $state<Json[]>([])
let loading = $state(true)
let error = $state('')
const DISCOVER_TYPES: { key: 'image' | 'video' | 'audio' | 'funscript'; label: string; statsKey: string }[] = [
{ key: 'image', label: 'Images', statsKey: 'images' },
{ key: 'video', label: 'Videos', statsKey: 'videos' },
{ key: 'audio', label: 'Audios', statsKey: 'audio' },
{ key: 'funscript', label: 'Funscripts', statsKey: 'funscripts' },
]
const selectedDiscoverTypes = new SvelteSet<string>(DISCOVER_TYPES.map((type) => type.key))
const allDiscoverTypesSelected = $derived(DISCOVER_TYPES.every((type) => selectedDiscoverTypes.has(type.key)))
function toggleDiscoverType(key: string) {
if (selectedDiscoverTypes.has(key)) selectedDiscoverTypes.delete(key)
else selectedDiscoverTypes.add(key)
}
function selectAllDiscoverTypes() {
for (const type of DISCOVER_TYPES) selectedDiscoverTypes.add(type.key)
}
// Pipeline controls (dashboard panel): an independent media-type selection from the discover
// panel's own one above, since they're two separate controls that happen to share a type list.
const selectedPipelineTypes = new SvelteSet<string>(DISCOVER_TYPES.map((type) => type.key))
const allPipelineTypesSelected = $derived(DISCOVER_TYPES.every((type) => selectedPipelineTypes.has(type.key)))
function togglePipelineType(key: string) {
if (selectedPipelineTypes.has(key)) selectedPipelineTypes.delete(key)
else selectedPipelineTypes.add(key)
}
function selectAllPipelineTypes() {
for (const type of DISCOVER_TYPES) selectedPipelineTypes.add(type.key)
}
// Mirrors the pipeline stages modeled everywhere else (AnalyzerPipelineBreakdown, the per-type
// Images/Videos/Audios/Funscripts tabs): discover, extract metadata, generate thumbnails, and
// run AI analysis. Each maps to its own backend action, scoped by the selected media types.
const PIPELINE_ACTIONS: { key: 'discover' | 'metadata' | 'thumbnails' | 'analyze'; label: string; endpoint: string }[] = [
{ key: 'discover', label: 'Discovery', endpoint: 'extract/discover' },
{ key: 'metadata', label: 'Metadata', endpoint: 'metadata/start' },
{ key: 'thumbnails', label: 'Thumbnails', endpoint: 'generate/start' },
{ key: 'analyze', label: 'AI analysis', endpoint: 'analyze/start' },
]
const selectedPipelineActions = new SvelteSet<string>(PIPELINE_ACTIONS.map((action) => action.key))
const allPipelineActionsSelected = $derived(PIPELINE_ACTIONS.every((action) => selectedPipelineActions.has(action.key)))
function togglePipelineAction(key: string) {
if (selectedPipelineActions.has(key)) selectedPipelineActions.delete(key)
else selectedPipelineActions.add(key)
}
function selectAllPipelineActions() {
for (const action of PIPELINE_ACTIONS) selectedPipelineActions.add(action.key)
}
// Schedules: recurring runs of the same five pipeline actions, on the backend's own poll-based
// scheduler (see runAnalyzerScheduler on the Go side) rather than anything client-driven. Cleanup
// always sweeps the whole library, so it's the one action here with no media-type scoping.
const SCHEDULE_TOOLS: { key: 'discover' | 'metadata' | 'thumbnails' | 'analyze' | 'cleanup'; label: string; usesTypes: boolean }[] =
[
{ key: 'discover', label: 'Discovery', usesTypes: true },
{ key: 'metadata', label: 'Metadata', usesTypes: true },
{ key: 'thumbnails', label: 'Thumbnails', usesTypes: true },
{ key: 'analyze', label: 'AI analysis', usesTypes: true },
{ key: 'cleanup', label: 'Cleanup', usesTypes: false },
]
let scheduleName = $state('')
let scheduleTool = $state<(typeof SCHEDULE_TOOLS)[number]['key']>('discover')
const scheduleTypes = new SvelteSet<string>(DISCOVER_TYPES.map((type) => type.key))
let scheduleIntervalMinutes = $state(60)
let scheduleEnabled = $state(true)
let creatingSchedule = $state(false)
const selectedScheduleTool = $derived(SCHEDULE_TOOLS.find((tool) => tool.key === scheduleTool)!)
const allScheduleTypesSelected = $derived(DISCOVER_TYPES.every((type) => scheduleTypes.has(type.key)))
function toggleScheduleType(key: string) {
if (scheduleTypes.has(key)) scheduleTypes.delete(key)
else scheduleTypes.add(key)
}
function selectAllScheduleTypes() {
for (const type of DISCOVER_TYPES) scheduleTypes.add(type.key)
}
async function createSchedule() {
if (selectedScheduleTool.usesTypes && scheduleTypes.size === 0) return
creatingSchedule = true
try {
await post('/api/automation-schedules', {
tool: scheduleTool,
name: scheduleName.trim() || `${selectedScheduleTool.label} schedule`,
intervalMinutes: scheduleIntervalMinutes,
enabled: scheduleEnabled,
settings: selectedScheduleTool.usesTypes ? { types: Array.from(scheduleTypes) } : {},
})
notify.success('Schedule created.')
scheduleName = ''
await load({ background: true })
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to create schedule.')
} finally {
creatingSchedule = false
}
}
async function runScheduleNow(id: string) {
try {
await post(`/api/automation-schedules/${id}/run`)
notify.success('Schedule run started.')
await load({ background: true })
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to run that schedule.')
}
}
async function deleteSchedule(id: string) {
try {
await del(`/api/automation-schedules/${id}`)
notify.success('Schedule deleted.')
await load({ background: true })
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to delete that schedule.')
}
}
function numeric(key: string, fallback = 0) {
const value = Number(stats[key] ?? status[key])
return Number.isFinite(value) ? value : fallback
}
function asRecord(value: unknown): Json {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
}
let loadGeneration = 0
// Tracks the last analyzer-reported failure we've already toasted, so a lingering lastError
// (it persists in status until the next run starts or clears it) doesn't re-notify on every
// background poll - only a new/changed error should interrupt the user.
let lastNotifiedError = ''
async function load({ background = false } = {}) {
if (!background) loading = true
error = ''
const generation = ++loadGeneration
try {
const responses = await Promise.all([
get<Json>('/api/stats').catch(() => ({})),
get<Json>('/api/status').catch(() => ({})),
get<Json>('/api/automation-schedules').catch(() => ({})),
])
// A newer load() may have been triggered (e.g. by a start-action) and already resolved while
// this one was still in flight - applying this stale response would clobber the fresher state.
if (generation !== loadGeneration) return
const statsResponse = responses[0] as Json
const nestedStats = statsResponse.stats
stats =
nestedStats && typeof nestedStats === 'object' && !Array.isArray(nestedStats)
? (nestedStats as Json)
: statsResponse
const statusResponse = responses[1] as Json
const nestedStatus = statusResponse.status
status =
nestedStatus && typeof nestedStatus === 'object' && !Array.isArray(nestedStatus)
? (nestedStatus as Json)
: statusResponse
const lastError = typeof status.lastError === 'string' ? status.lastError : ''
if (lastError && lastError !== lastNotifiedError) notify.error(lastError)
lastNotifiedError = lastError
const schedulesResponse = responses[2] as Json
const rawSchedules = schedulesResponse.schedules || schedulesResponse.items
schedules = Array.isArray(rawSchedules) ? (rawSchedules as Json[]) : []
} catch (reason) {
if (generation !== loadGeneration) return
error = reason instanceof Error ? reason.message : 'Unable to load analyzer state.'
} finally {
if (!background) loading = false
}
}
// The backend sets its Running flag synchronously before responding to a start request, so this
// is normally redundant - but the very next status poll still has to round-trip over the
// network, and a small/near-empty library can finish a run in well under that time. Patching
// `status` immediately gives instant feedback that the click was received, and the next real
// poll (below) overwrites it with the authoritative value moments later either way.
const OPTIMISTIC_STATUS: Record<string, Json> = {
'extract/discover': { running: true, state: 'discovering', worker: 'Discovery' },
'metadata/start': { running: true, state: 'extracting', worker: 'Metadata extraction' },
'generate/start': { running: true, state: 'generating', worker: 'Thumbnail generation' },
'analyze/start': { running: true, state: 'analyzing', worker: 'AI analysis' },
'cleanup/start': { running: true, state: 'cleaning', worker: 'Cleanup' },
'pipeline/clear': { running: true, state: 'clearing', worker: 'Database cleanup', total: 1, completed: 0 },
}
function applyOptimisticStatus(action: string) {
const patch = OPTIMISTIC_STATUS[action]
if (patch) status = { ...status, ...patch }
}
function clearProgressTotal(types: string[], stages: string[]) {
let total = 0
for (const type of types) {
if (stages.includes('discover')) {
total += 1
} else if (type === 'funscript') {
total += stages.includes('metadata') ? 1 : 0
} else {
total += stages.filter((stage) => stage === 'metadata' || stage === 'thumbnails' || stage === 'analyze').length
}
}
return total
}
async function runAction(action: string, label = action) {
try {
await post(`/api/${action}`)
applyOptimisticStatus(action)
notify.success(`${label} started.`)
await load({ background: true })
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : `Unable to start ${label.toLowerCase()}.`)
}
}
let pipelineRunning = $state(false)
async function runSelectedPipeline() {
if (selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0) return
pipelineRunning = true
try {
const types = Array.from(selectedPipelineTypes)
// Discovery and the standalone metadata refresh share one worker slot on the backend (both
// walk/probe files synchronously) and can't run at once - discovery already re-probes
// metadata for the exact same files as a side effect, so when both are picked, discovery
// wins and the separate metadata call is skipped rather than failing with a conflict.
const runDiscover = selectedPipelineActions.has('discover')
const stages = PIPELINE_ACTIONS.filter(
(action) => selectedPipelineActions.has(action.key) && !(action.key === 'metadata' && runDiscover),
)
const started: string[] = []
const failed: string[] = []
for (const stage of stages) {
try {
await post(`/api/${stage.endpoint}`, { types })
applyOptimisticStatus(stage.endpoint)
started.push(stage.label)
} catch (reason) {
failed.push(`${stage.label} (${reason instanceof Error ? reason.message : 'failed to start'})`)
}
}
if (started.length > 0) notify.success(`${started.join(', ')} started.`)
if (failed.length > 0) notify.error(`Unable to start: ${failed.join(', ')}.`)
await load({ background: true })
} finally {
pipelineRunning = false
}
}
let clearingDatabase = $state(false)
async function clearSelectedPipeline() {
if (selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0) return
const types = Array.from(selectedPipelineTypes)
const stages = PIPELINE_ACTIONS.filter((action) => selectedPipelineActions.has(action.key))
if (
!window.confirm(
`Clear ${stages.map((stage) => stage.label.toLowerCase()).join(', ')} data for ${types.join(', ')}? This can't be undone, though everything will be regenerated on the next run.`,
)
) {
return
}
clearingDatabase = true
const clearRequest = post<Json>('/api/pipeline/clear', { types, stages: stages.map((stage) => stage.key) })
status = {
...status,
...OPTIMISTIC_STATUS['pipeline/clear'],
total: clearProgressTotal(types, stages.map((stage) => stage.key)),
}
// Fetch the authoritative progress immediately as well as through the normal polling loop;
// a large thumbnail cleanup can outlive the next scheduled poll interval.
void load({ background: true })
try {
const response = await clearRequest
notify.success('Selected pipeline data cleared.')
const progress = asRecord(response.progress)
await load({ background: true })
if (Object.keys(progress).length > 0) {
status = {
...status,
running: false,
state: 'completed',
worker: 'Database cleanup',
total: Number(progress.total) || 0,
completed: Number(progress.completed) || 0,
failed: Number(progress.failed) || 0,
}
}
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to clear the selected pipeline data.')
} finally {
clearingDatabase = false
}
}
async function startDiscover() {
if (selectedDiscoverTypes.size === 0) return
try {
await post('/api/extract/discover', { types: Array.from(selectedDiscoverTypes) })
applyOptimisticStatus('extract/discover')
notify.success('Discovery started.')
await load({ background: true })
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to start discovery.')
}
}
onMount(() => {
let timer: number
let cancelled = false
const tick = async () => {
await load({ background: true })
if (!cancelled) timer = window.setTimeout(() => void tick(), status.running === true ? 3_000 : 10_000)
}
void load().then(() => {
if (!cancelled) timer = window.setTimeout(() => void tick(), status.running === true ? 3_000 : 10_000)
})
return () => {
cancelled = true
window.clearTimeout(timer)
}
})
</script>
{#snippet chipGroup(
items: { key: string; label: string }[],
isSelected: (key: string) => boolean,
onToggle: (key: string) => void,
allSelected: boolean,
onSelectAll: () => void,
)}
<div class="flex flex-wrap gap-2">
{#each items as item (item.key)}
<button
type="button"
class={cn(
'rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
isSelected(item.key)
? 'border-primary bg-primary text-primary-fg'
: 'border-border bg-surface text-fg hover:bg-surface-hover',
)}
aria-pressed={isSelected(item.key)}
onclick={() => onToggle(item.key)}
>
{item.label}
</button>
{/each}
<button
type="button"
class={cn(
'rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
allSelected
? 'border-primary bg-primary text-primary-fg'
: 'border-border bg-surface text-fg hover:bg-surface-hover',
)}
aria-pressed={allSelected}
onclick={onSelectAll}
>
All
</button>
</div>
{/snippet}
<div class="space-y-4">
{#if error}<div
class="flex items-center gap-2 rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger"
>
<AlertTriangle class="size-4" />{error}
</div>{/if}
{#if panel === 'dashboard'}
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Metric
label="Pending"
value={numeric('queued', numeric('queueLength'))}
detail="Waiting for a worker"
2026-09-03 00:16:55 +02:00
variant="warning"
2026-09-01 08:43:25 +02:00
/><Metric
label="Processing"
value={numeric('processing', numeric('activeJobs'))}
detail="Active jobs"
2026-09-03 00:16:55 +02:00
variant="primary"
2026-09-01 08:43:25 +02:00
/><Metric
label="Completed"
value={numeric('completed', numeric('processed'))}
detail="Current history window"
2026-09-03 00:16:55 +02:00
variant="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" variant="danger" />
2026-09-01 08:43:25 +02:00
</div>
<AnalyzerPipelineBreakdown pipeline={asRecord(stats.pipeline)} />
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
<Card class="space-y-5"
><SectionTitle
title="Pipeline controls"
description="Pick media types and pipeline stages, then run just that combination. Each type's own Images/Videos/Audios/Funscripts tab still holds the detailed thumbnails/metadata/AI model settings."
/>
<div class="space-y-2">
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Media types</p>
{@render chipGroup(
DISCOVER_TYPES,
(key: string) => selectedPipelineTypes.has(key),
togglePipelineType,
allPipelineTypesSelected,
selectAllPipelineTypes,
)}
</div>
<div class="space-y-2">
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Stages</p>
{@render chipGroup(
PIPELINE_ACTIONS,
(key: string) => selectedPipelineActions.has(key),
togglePipelineAction,
allPipelineActionsSelected,
selectAllPipelineActions,
)}
</div>
<div class="flex flex-wrap items-center gap-3">
<Button
disabled={
pipelineRunning || clearingDatabase || selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0
}
onclick={() => void runSelectedPipeline()}
><Play class="size-4" />{pipelineRunning ? 'Starting…' : 'Run selected'}</Button
><Button variant="outline" disabled={clearingDatabase} onclick={() => void runAction('cleanup/start', 'Cleanup')}
><RefreshCw class="size-4" />Clean stale entries</Button
><Button
variant="danger"
disabled={clearingDatabase || pipelineRunning || selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0}
onclick={() => void clearSelectedPipeline()}
><Trash2 class="size-4" />{clearingDatabase ? 'Clearing…' : 'Clear database'}</Button
>
</div>
</Card>
<AnalyzerLiveStatus {status} {stats} {loading} description="Last response from the analyzer service." />
</div>
<AnalyzerHistory
title="Recent processing history"
description="Every discovered, extracted, and analyzed element is recorded here."
/>
{:else if panel === 'schedules'}
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Metric
label="Pending"
value={numeric('queued', numeric('queueLength'))}
detail="Waiting for a worker"
2026-09-03 00:16:55 +02:00
variant="warning"
2026-09-01 08:43:25 +02:00
/><Metric
label="Processing"
value={numeric('processing', numeric('activeJobs'))}
detail="Active jobs"
2026-09-03 00:16:55 +02:00
variant="primary"
2026-09-01 08:43:25 +02:00
/><Metric
label="Completed"
value={numeric('completed', numeric('processed'))}
detail="Current history window"
2026-09-03 00:16:55 +02:00
variant="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" variant="danger" />
2026-09-01 08:43:25 +02:00
</div>
<AnalyzerLiveStatus {status} {stats} {loading} description="Current analyzer schedule and worker state." />
<Card class="space-y-5"
><SectionTitle
title="New schedule"
description="Run a pipeline action automatically on a recurring interval."
/>
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<label class="space-y-1 text-sm"
><span class="text-muted-fg">Name</span><input
class="field h-9"
type="text"
placeholder={`${selectedScheduleTool.label} schedule`}
bind:value={scheduleName}
/></label
>
<label class="space-y-1 text-sm"
><span class="text-muted-fg">Action</span><select class="field h-9" bind:value={scheduleTool}>
{#each SCHEDULE_TOOLS as tool (tool.key)}
<option value={tool.key}>{tool.label}</option>
{/each}
</select></label
>
<label class="space-y-1 text-sm"
><span class="text-muted-fg">Every (minutes)</span><input
class="field h-9"
type="number"
min="5"
step="5"
bind:value={scheduleIntervalMinutes}
/></label
>
<label class="flex items-end gap-2 pb-2 text-sm"
><input type="checkbox" bind:checked={scheduleEnabled} /><span class="text-muted-fg">Enabled</span></label
>
</div>
{#if selectedScheduleTool.usesTypes}
<div class="space-y-2">
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Media types</p>
{@render chipGroup(
DISCOVER_TYPES,
(key: string) => scheduleTypes.has(key),
toggleScheduleType,
allScheduleTypesSelected,
selectAllScheduleTypes,
)}
</div>
{/if}
<Button
disabled={creatingSchedule || (selectedScheduleTool.usesTypes && scheduleTypes.size === 0)}
onclick={() => void createSchedule()}
><Plus class="size-4" />{creatingSchedule ? 'Creating…' : 'Create schedule'}</Button
></Card
>
<Card class="space-y-5"
><SectionTitle
title="Schedules"
description="Recurring analyzer jobs and their current state."
/>{#if schedules.length === 0}<EmptyState
title="No automation schedules"
message="Create one above; it will appear here with its next run."
/>{:else}<div class="divide-y divide-border">
{#each schedules as schedule, index (String(schedule.id || index))}<div
class="flex items-center justify-between gap-3 py-3"
>
<div class="min-w-0">
<p class="truncate text-sm font-medium text-fg">
{String(schedule.name || schedule.tool || 'Analyzer schedule')}
</p>
<p class="mt-1 text-xs text-muted-fg">
{String(schedule.tool || '—')} · every {String(schedule.intervalMinutes ?? '?')}m · Next run: {String(
schedule.nextRunAt || schedule.next_run_at || '—',
)}
</p>
{#if schedule.lastStatus}<p class="mt-1 text-xs text-muted-fg">
Last run: {String(schedule.lastStatus)}
</p>{/if}
</div>
<div class="flex shrink-0 items-center gap-2">
2026-09-03 00:16:55 +02:00
<Badge variant={schedule.enabled === false ? 'default' : 'success'}
2026-09-01 08:43:25 +02:00
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
><Button variant="outline" size="sm" onclick={() => void runScheduleNow(String(schedule.id))}
>Run now</Button
><Button variant="danger" size="sm" onclick={() => void deleteSchedule(String(schedule.id))}
><Trash2 class="size-4" /></Button
>
</div>
</div>{/each}
</div>{/if}</Card
>
<AnalyzerHistory
title="Processing history"
description="Elements processed while scheduled analyzer work runs."
/>
{:else}
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{#each DISCOVER_TYPES as type (type.key)}
<Metric label={type.label} value={numeric(type.statsKey)} detail="Discovered" />
{/each}
</div>
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
<Card class="space-y-5"
><SectionTitle
title="Discovery controls"
description="Choose which media types to walk the configured media roots for, then watch the unified run history below."
/>
{@render chipGroup(
DISCOVER_TYPES,
(key: string) => selectedDiscoverTypes.has(key),
toggleDiscoverType,
allDiscoverTypesSelected,
selectAllDiscoverTypes,
)}
<div class="flex flex-wrap gap-3">
<Button disabled={selectedDiscoverTypes.size === 0} onclick={() => void startDiscover()}
><Play class="size-4" />Start discover</Button
><Button variant="secondary" onclick={() => void runAction('cleanup/start', 'Cleanup')}
><RefreshCw class="size-4" />Cleanup</Button
>
</div>
<div class="rounded-md border border-border bg-bg p-4">
<p class="text-sm font-medium text-fg">Stage guidance</p>
<p class="mt-1 text-sm text-muted-fg">
Discovered files are indexed immediately. Visit each media type's own tab (Images, Videos, Audios,
Funscripts) to configure thumbnails, metadata extraction, and AI analysis for what discovery finds.
</p>
</div></Card
>
<AnalyzerLiveStatus {status} {stats} {loading} description="Current discovery run, including the file it's on." />
</div>
<AnalyzerHistory
title="Discovery history"
description="Discovered elements, statuses, and results."
/>
{/if}
</div>