Files
shared/media-webui/src/lib/features/ToolsWorkspace.svelte
T
Gabriel20xxandClaude Sonnet 5 acde180086 Fold MediaEngine (media-backend, media-webui) into this repo
Per owner decision: MediaEngine (the Media product family's Go backend
and SvelteKit frontend, previously its own repo referenced by 7 thin
service repos via git submodule) is folded directly into shared/ as
media-backend/ and media-webui/, rather than staying separate.

media-backend/go.mod's replace directive now points at ../backend (a
true sibling within this repo) instead of a vendored ../shared/backend
copy, since there's no more nested vendoring - it's the real thing.

Also moved MediaEngine's own CI (media-backend-lint.yml,
media-backend-tests.yml) and dev tooling scripts (scripts/media/*,
audit/lint/enforce scripts for the media-backend+media-webui content),
fixing their path assumptions for the new layout, and dropped
scripts/media/sync-shared.mjs (confirmed dead code, and now doubly
obsolete since there's no more vendored shared/ subfolder for it to
check). Added media:* script aliases to package.json for the moved
tooling, namespaced to avoid colliding with this repo's own scripts.

Also fixed sync-consumers.ps1's workspace-root resolution to walk up
until it finds a directory containing both Original/ and Forks/,
instead of assuming shared/ is always a direct child of the workspace
root - it broke when shared/ moved from Web/shared to Web/Central/shared
earlier in this same restructuring. Removed the now-obsolete
Original/MediaEngine entry from its consumer list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:06:29 +02:00

473 lines
19 KiB
Svelte

<script lang="ts">
import { Activity, ArrowRight, CheckCircle2, CloudDownload, Film, Upload, WandSparkles, X } from '@lucide/svelte'
import { onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
type Json = Record<string, unknown>
interface Job {
id?: string
tool?: string
status?: string
createdAt?: string
startedAt?: string
finishedAt?: string
error?: string
}
interface Schedule {
id?: string
name?: string
tool?: string
intervalMinutes?: number
enabled?: boolean
nextRunAt?: string
lastStatus?: string
}
interface ConverterFormat {
id: string
label: string
extension?: string
}
let { panel = 'generator' }: { panel?: string } = $props()
let jobs = $state<Job[]>([])
let schedules = $state<Schedule[]>([])
let queue: Job[] = $state([])
let loading = $state(true)
let error = $state('')
let starting = $state(false)
let prompt = $state('')
let sourceUrl = $state('')
let sourcePath = $state('')
let sourceFile = $state<File | null>(null)
let sourceFileInput = $state<HTMLInputElement | null>(null)
let sourceFileDragging = $state(false)
let uploadingSource = $state(false)
let workflowNames = $state<string[]>([])
let workflowName = $state('')
let workflowGraph = $state<Json>({})
let converterFormats = $state<ConverterFormat[]>([])
let targetFormat = $state('mp4')
let encodingProfile = $state('balanced')
const workflowTitle = $derived(
panel === 'schedules'
? 'Automation schedules'
: panel === 'library'
? 'Workflow library'
: panel[0]?.toUpperCase() + panel.slice(1),
)
function asRecord(value: unknown): Json {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
}
async function loadJobs() {
try {
const toolQuery = ['generator', 'downloader', 'converter'].includes(panel)
? `?tool=${encodeURIComponent(panel)}`
: ''
const [jobResponse, scheduleResponse, queueResponse] = await Promise.all([
get<{ jobs?: Job[] }>(`/api/jobs${toolQuery}`).catch(() => ({ jobs: [] })),
get<{ schedules?: Schedule[] }>('/api/schedules').catch(() => ({ schedules: [] })),
get<{ queue?: Job[] }>(`/api/queue${toolQuery}`).catch(() => ({ queue: [] })),
])
jobs = Array.isArray(jobResponse.jobs) ? jobResponse.jobs : []
schedules = Array.isArray(scheduleResponse.schedules) ? scheduleResponse.schedules : []
queue = Array.isArray(queueResponse.queue) ? queueResponse.queue : []
} catch (reason) {
error = reason instanceof Error ? reason.message : 'Unable to load workflow state.'
} finally {
loading = false
}
}
async function loadGeneratorOptions() {
try {
const response = await get<{ builtIn?: string[]; mine?: string[]; data?: string[] }>('/api/workflows/list')
const names = [...(response.builtIn || []), ...(response.mine || []), ...(response.data || [])].filter(
(name, index, values) => typeof name === 'string' && name.trim() && values.indexOf(name) === index,
)
workflowNames = names
if (!workflowName || !names.includes(workflowName)) workflowName = names[0] || ''
if (workflowName) await loadWorkflowGraph(workflowName)
} catch (reason) {
error = reason instanceof Error ? reason.message : 'Unable to load generator workflows.'
}
}
async function loadWorkflowGraph(name: string) {
if (!name) {
workflowGraph = {}
return
}
try {
const response = await get<{ graph?: Json }>(`/api/generator/workflows/meta?name=${encodeURIComponent(name)}`)
workflowGraph = asRecord(response.graph)
} catch (reason) {
workflowGraph = {}
error = reason instanceof Error ? reason.message : 'Unable to load the selected generator workflow.'
}
}
async function loadConverterOptions() {
try {
const response = await get<{ formats?: ConverterFormat[] }>('/api/converter/formats')
converterFormats = Array.isArray(response.formats) ? response.formats : []
if (converterFormats.length > 0 && !converterFormats.some((format) => format.id === targetFormat)) {
targetFormat = converterFormats[0].id
}
} catch (reason) {
error = reason instanceof Error ? reason.message : 'Unable to load converter formats.'
}
}
function formatFileSize(size: number) {
if (size < 1024) return size + ' B'
if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB'
return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
}
async function uploadSourceFile(file: File) {
sourceFile = file
sourcePath = ''
uploadingSource = true
try {
const form = new FormData()
form.append('file', file)
const response = await post<{
filename?: string
file?: { path?: string; filename?: string }
}>('/api/upload', form)
sourcePath = response.file?.path || response.filename || ''
if (!sourcePath) throw new Error('Upload completed without a usable file path.')
notify.success(file.name + ' uploaded and ready to convert.')
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to upload the converter input.')
} finally {
uploadingSource = false
sourceFileDragging = false
}
}
function handleSourceFileChange(event: Event) {
const input = event.currentTarget as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (file) void uploadSourceFile(file)
}
function handleSourceFileDragOver(event: DragEvent) {
event.preventDefault()
sourceFileDragging = true
}
function handleSourceFileDragLeave(event: DragEvent) {
const dropZone = event.currentTarget as HTMLElement
const nextTarget = event.relatedTarget as Node | null
if (!nextTarget || !dropZone.contains(nextTarget)) sourceFileDragging = false
}
function handleSourceFileDrop(event: DragEvent) {
event.preventDefault()
sourceFileDragging = false
const file = event.dataTransfer?.files?.[0]
if (file) void uploadSourceFile(file)
}
function clearSourceFile() {
sourceFile = null
sourcePath = ''
sourceFileInput?.focus()
}
async function startWorkflow() {
starting = true
try {
if (panel === 'generator') {
if (!workflowName || Object.keys(workflowGraph).length === 0) {
throw new Error('Select a valid generator workflow before starting.')
}
await post('/api/jobs/generator/start', {
workflow: workflowGraph,
workflowName,
...(prompt.trim() ? { promptText: prompt.trim() } : {}),
})
notify.success('Generator workflow queued.')
} else if (panel === 'downloader') {
if (!sourceUrl.trim()) throw new Error('Enter a source URL before starting a download.')
await post('/api/downloader/single', { url: sourceUrl.trim() })
notify.success('Downloader workflow queued.')
} else {
if (uploadingSource) throw new Error('Wait for the input upload to finish before starting a conversion.')
if (!sourcePath.trim()) throw new Error('Upload an input file before starting a conversion.')
await post('/api/converter/start', {
input: sourcePath.trim(),
targetFormat,
encoding: encodingProfile,
})
notify.success('Converter workflow queued.')
}
prompt = ''
sourceUrl = ''
sourcePath = ''
sourceFile = null
await loadJobs()
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to start workflow.')
} finally {
starting = false
}
}
async function runSchedule(id: string) {
try {
await post(`/api/schedules/${encodeURIComponent(id)}/run`)
notify.success('Schedule queued.')
await loadJobs()
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to run schedule.')
}
}
onMount(() => {
const timer = window.setInterval(() => void loadJobs(), 10_000)
return () => window.clearInterval(timer)
})
$effect(() => {
const currentPanel = panel
void loadJobs()
if (currentPanel === 'generator') void loadGeneratorOptions()
if (currentPanel === 'converter') void loadConverterOptions()
})
</script>
<div class="space-y-4">
<div class="grid gap-4 sm:grid-cols-3">
<Metric
label="Active queue"
value={queue.length}
detail="Waiting or running"
tone={queue.length ? 'warning' : 'default'}
/><Metric label="Recent jobs" value={jobs.length} detail="Retained workflow history" /><Metric
label="Schedules"
value={schedules.length}
detail="Recurring automations"
/>
</div>
{#if error}<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
{error}
</div>{/if}
{#if panel === 'schedules'}
<Card class="space-y-5"
><SectionTitle
title="Schedules"
description="Keep recurring downloader and converter jobs visible and controllable."
/>
{#if schedules.length === 0}<EmptyState
title="No schedules configured"
message="Create schedules from the service API or use the builder in the next iteration."
/>{:else}<div class="divide-y divide-border">
{#each schedules as schedule (schedule.id)}<div
class="flex flex-col gap-3 py-3 sm:flex-row sm:items-center sm:justify-between"
>
<div>
<div class="flex items-center gap-2">
<p class="text-sm font-medium text-fg">{schedule.name || schedule.tool || 'Workflow schedule'}</p>
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
>
</div>
<p class="mt-1 text-xs text-muted-fg">
{schedule.tool || 'tool'} · every {schedule.intervalMinutes || '—'} minutes · {schedule.lastStatus ||
'never run'}
</p>
</div>
{#if schedule.id}<Button
variant="secondary"
size="sm"
onclick={() => void runSchedule(String(schedule.id))}>Run now <ArrowRight class="size-4" /></Button
>{/if}
</div>{/each}
</div>{/if}
</Card>
{:else if panel === 'library'}
<Card class="space-y-5"
><SectionTitle
title="Generated media"
description="Browse the output produced by generator and converter workflows."
/><EmptyState
title="Library view"
message="The unified library API remains available at /library/unified; use it to inspect generated outputs once a workflow has completed."
/></Card
>
{:else}
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card class="space-y-5"
><div class="flex items-start gap-3">
<div class="flex size-10 items-center justify-center rounded-lg bg-primary/15 text-primary">
{#if panel === 'downloader'}<CloudDownload class="size-5" />{:else if panel === 'converter'}<Film
class="size-5"
/>{:else}<WandSparkles class="size-5" />{/if}
</div>
<SectionTitle
title={`${workflowTitle} workspace`}
description={panel === 'generator'
? 'Choose a ComfyUI workflow and optionally provide a text prompt.'
: panel === 'downloader'
? 'Queue a download from a public media URL.'
: 'Choose an input file, output format, and encoding profile.'}
/>
</div>
{#if panel === 'generator'}
<label class="block text-xs font-medium text-muted-fg"
>Workflow<select
bind:value={workflowName}
onchange={(event) => void loadWorkflowGraph((event.currentTarget as HTMLSelectElement).value)}
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{#if workflowNames.length === 0}
<option value="">No workflows available</option>
{:else}
{#each workflowNames as name (name)}<option value={name}>{name}</option>{/each}
{/if}
</select></label
><label class="block text-xs font-medium text-muted-fg"
>Prompt (optional)<textarea
bind:value={prompt}
rows="5"
placeholder="Text prompt to apply to the selected workflow"
class="mt-1 w-full resize-y rounded-md border border-border bg-bg px-3 py-2 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
></textarea></label
>
{:else if panel === 'downloader'}
<label class="block text-xs font-medium text-muted-fg"
>Source URL<input
bind:value={sourceUrl}
type="url"
placeholder="https://example.com/media"
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/></label
>
{:else}
<div class="grid gap-4 sm:grid-cols-2">
<div class="space-y-2">
<span class="block text-xs font-medium text-muted-fg">Input file</span>
<label
for="converter-source-file"
class={sourceFileDragging
? 'group flex min-h-36 cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-primary bg-primary/10 px-4 py-6 text-center transition-colors'
: 'group flex min-h-36 cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-border bg-bg px-4 py-6 text-center transition-colors hover:border-primary/60 hover:bg-surface-hover'}
ondragover={handleSourceFileDragOver}
ondragleave={handleSourceFileDragLeave}
ondrop={handleSourceFileDrop}
>
<input
id="converter-source-file"
bind:this={sourceFileInput}
type="file"
accept="audio/*,video/*"
class="sr-only"
onchange={handleSourceFileChange}
disabled={uploadingSource}
/>
{#if uploadingSource}
<Activity class="mb-2 size-6 animate-spin text-primary" />
<span class="text-sm font-medium text-fg">Uploading {sourceFile?.name || 'file'}…</span>
<span class="mt-1 text-xs text-muted-fg">Keep this page open while the upload finishes.</span>
{:else if sourceFile && sourcePath}
<CheckCircle2 class="mb-2 size-6 text-success" />
<span class="max-w-full truncate text-sm font-medium text-fg">{sourceFile.name}</span>
<span class="mt-1 text-xs text-muted-fg">{formatFileSize(sourceFile.size)} · Ready to convert</span>
<span class="mt-2 text-xs text-primary">Drop another file or click to replace</span>
{:else if sourceFile}
<Upload class="mb-2 size-6 text-danger" />
<span class="max-w-full truncate text-sm font-medium text-fg">{sourceFile.name}</span>
<span class="mt-1 text-xs text-danger">Upload failed. Drop another file or click to retry.</span>
{:else}
<Upload class="mb-2 size-6 text-primary" />
<span class="text-sm font-medium text-fg">Drop a media file here</span>
<span class="mt-1 text-xs text-muted-fg">or click to browse · audio and video files</span>
{/if}
</label>
{#if sourceFile && !uploadingSource}
<button
type="button"
class="inline-flex items-center gap-1 text-xs text-muted-fg hover:text-fg"
onclick={clearSourceFile}
>
<X class="size-3.5" /> Clear selected file
</button>
{/if}
</div>
<label class="block text-xs font-medium text-muted-fg"
>Target format<select
bind:value={targetFormat}
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{#if converterFormats.length === 0}
<option value="mp4">MP4</option>
{:else}
{#each converterFormats as format (format.id)}<option value={format.id}>{format.label}</option>{/each}
{/if}
</select></label
>
</div>
<label class="block text-xs font-medium text-muted-fg"
>Encoding profile<select
bind:value={encodingProfile}
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<option value="fast">Fast</option>
<option value="balanced">Balanced</option>
<option value="quality">High quality</option>
</select></label
>
{/if}
<div class="flex items-center justify-between gap-3 border-t border-border pt-4">
<p class="text-xs text-muted-fg">Jobs keep running in the service queue after you leave this page.</p>
<Button disabled={starting || uploadingSource} onclick={() => void startWorkflow()}
><Activity class="size-4" />{starting ? 'Queueing…' : `Start ${panel}`}</Button
>
</div>
</Card>
<Card class="space-y-4"
><SectionTitle title="Queue activity" description="Recent jobs update automatically." />{#if loading}<p
class="text-sm text-muted-fg"
>
Loading queue…
</p>{:else if jobs.length === 0}<EmptyState
title="Queue is quiet"
message="Start a workflow to see progress here."
/>{:else}<div class="space-y-2">
{#each jobs.slice(0, 8) as job (job.id)}<div class="rounded-md border border-border bg-bg p-3">
<div class="flex items-center justify-between gap-2">
<p class="truncate text-sm font-medium text-fg">{job.tool || 'workflow'}</p>
<Badge
tone={job.status === 'completed' || job.status === 'complete'
? 'success'
: job.status === 'error'
? 'danger'
: 'primary'}>{job.status || 'queued'}</Badge
>
</div>
<p class="mt-1 truncate text-xs text-muted-fg">{job.id || 'job id unavailable'}</p>
</div>{/each}
</div>{/if}</Card
>
</div>
{/if}
</div>