Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(media): clear-queued button + provider model display + Copilot fixes

Adam Eivy004e9c344949
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 4b226c2cd8..19e4060b21 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -1,7 +1,7 @@
import { useEffect, useState, useCallback } from 'react';
-import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight } from 'lucide-react';
+import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight, Trash2 } from 'lucide-react';
import toast from '../ui/Toast';
-import { listMediaJobs, cancelMediaJob } from '../../services/apiMediaJobs.js';
+import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs } from '../../services/apiMediaJobs.js';
const STATUS_BADGE = {
queued: 'bg-port-border text-port-text-muted',
@@ -54,8 +54,21 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }
const live = jobs.filter((j) => j.status === 'queued' || j.status === 'running');
const recent = jobs.filter((j) => j.status !== 'queued' && j.status !== 'running').slice(0, recentLimit);
+ const queuedCount = live.filter((j) => j.status === 'queued').length;
const headerLabel = kind ? `${kind === 'image' ? 'Image' : 'Video'} Render Queue` : 'Render Queue';
+ const handleClearQueued = () => {
+ if (!queuedCount) return;
+ cancelQueuedMediaJobs(kind ? { kind } : {})
+ .then(({ canceled }) => {
+ // Optimistic flip: queued → canceled (running jobs stay untouched).
+ // The next 3s poll will reconcile if anything raced through.
+ setJobs((prev) => prev.map((j) => (j.status === 'queued' ? { ...j, status: 'canceled' } : j)));
+ toast.success(`Cleared ${canceled} queued job${canceled === 1 ? '' : 's'}`);
+ })
+ .catch((err) => toast.error(err?.message || 'Clear failed'));
+ };
+
return (
<div className={`bg-port-card border border-port-border rounded-xl p-4 space-y-2 ${className}`}>
<div className="flex items-center justify-between gap-2">
@@ -66,13 +79,25 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }
{live.length} active{recent.length > 0 ? ` • ${recent.length} recent` : ''}
</span>
</div>
- <button
- onClick={fetchJobs}
- className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
- title="Refresh"
- >
- <RefreshCw className="w-3.5 h-3.5" />
- </button>
+ <div className="flex items-center gap-1 shrink-0">
+ {queuedCount > 0 && (
+ <button
+ onClick={handleClearQueued}
+ className="flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-port-error hover:bg-port-error/10 border border-port-border hover:border-port-error/40"
+ title={`Cancel all ${queuedCount} queued job${queuedCount === 1 ? '' : 's'} (running jobs are not affected)`}
+ >
+ <Trash2 className="w-3 h-3" />
+ <span>Clear queued ({queuedCount})</span>
+ </button>
+ )}
+ <button
+ onClick={fetchJobs}
+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
+ title="Refresh"
+ >
+ <RefreshCw className="w-3.5 h-3.5" />
+ </button>
+ </div>
</div>
{loading ? (
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index 60e912605d..4dc8359813 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -23,6 +23,13 @@ export function normalizeImage(i) {
? i.loraPaths.map((p) => (typeof p === 'string' ? p.split(/[\\/]/).pop() : ''))
: [];
const loraNames = (fromFilenames.length ? fromFilenames : fromPaths).filter(Boolean);
+ // modelId display falls back through several sidecar shapes:
+ // 1. modelId — local-runner sidecars (mflux/flux2/z-image/ernie)
+ // 2. model — codex sidecars (older path), and future Gemini etc.
+ // 3. mode — pre-model-field codex sidecars saved before the default
+ // was added; surface the provider tag so the card still
+ // shows where the image came from.
+ const modelId = i.modelId || i.model || (i.mode && i.mode !== 'local' ? i.mode : null);
return {
kind: 'image',
key: `image:${i.filename}`,
@@ -31,7 +38,7 @@ export function normalizeImage(i) {
downloadUrl: i.path || `/data/images/${i.filename}`,
prompt: i.prompt || i.metadata?.prompt || '(no prompt)',
negativePrompt: i.negativePrompt || i.negative_prompt || null,
- modelId: i.modelId || i.model || null,
+ modelId,
width: i.width,
height: i.height,
steps: i.steps,
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 23884fbac7..8b46ebe0cf 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -40,16 +40,20 @@ import { safeParseJSON } from '../lib/genUtils';
const DEFAULT_NEGATIVE = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';
// Append LoRA trigger words to a prompt comma-separated, skipping any
-// already present (case-insensitive substring match — Civitai triggers are
-// often phrases, so we don't tokenize). Returns the updated prompt or the
-// original if every trigger is already in.
+// already present. Compares against comma-separated prompt segments rather
+// than raw substrings so a short trigger like "cat" doesn't false-match
+// inside "concatenate". Civitai triggers are often phrases that themselves
+// contain spaces, so the match is whole-segment, case-insensitive.
const appendTriggerWords = (prompt, words) => {
const list = (Array.isArray(words) ? words : [])
.filter((w) => typeof w === 'string' && w.trim())
.map((w) => w.trim());
if (!list.length) return prompt;
- const haystack = String(prompt || '').toLowerCase();
- const fresh = list.filter((w) => !haystack.includes(w.toLowerCase()));
+ const segments = String(prompt || '')
+ .split(',')
+ .map((s) => s.trim().toLowerCase())
+ .filter(Boolean);
+ const fresh = list.filter((w) => !segments.includes(w.toLowerCase()));
if (!fresh.length) return prompt;
const trimmed = String(prompt || '').trim();
const sep = !trimmed ? '' : trimmed.endsWith(',') ? ' ' : ', ';
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index b985c69447..9ba25e3306 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -441,6 +441,15 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry
const [saving, setSaving] = useState(false);
const [clearing, setClearing] = useState(false);
+ // a11y: close on Escape so keyboard-only users can dismiss without
+ // tabbing to the X. Listen at document level (capture phase not
+ // required — modal is the only open dialog).
+ useEffect(() => {
+ const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [onClose]);
+
const handleSave = async (e) => {
e?.preventDefault?.();
if (!apiKey.trim() || saving) return;
@@ -475,13 +484,16 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry
return (
<div className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4" onClick={onClose}>
<div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="civitai-auth-title"
className="bg-port-card border border-port-border rounded-lg p-5 w-full max-w-md space-y-4"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-2">
<KeyRound size={18} className="text-port-accent" />
- <h2 className="text-base font-semibold text-white">Civitai API key</h2>
+ <h2 id="civitai-auth-title" className="text-base font-semibold text-white">Civitai API key</h2>
</div>
<button onClick={onClose} className="text-gray-400 hover:text-gray-200" aria-label="Close">
<X size={16} />
diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.js
index 3940ccc6fa..09f2a2ceef 100644
--- a/client/src/services/apiMediaJobs.js
+++ b/client/src/services/apiMediaJobs.js
@@ -10,3 +10,8 @@ export const listMediaJobs = (filters = {}) => {
export const getMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}`);
export const cancelMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' });
+
+// Bulk-cancel every queued (not running) job, optionally scoped to a kind.
+// Returns { canceled: <count> }. Running jobs need per-id cancelMediaJob.
+export const cancelQueuedMediaJobs = ({ kind } = {}) =>
+ request(`/media-jobs/cancel-queued${kind ? `?kind=${encodeURIComponent(kind)}` : ''}`, { method: 'POST' });
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index db307f9d13..e5367dcdf8 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -9,7 +9,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { listJobs, getJob, cancelJob, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { listJobs, getJob, cancelJob, cancelQueuedJobs, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
const router = Router();
@@ -85,4 +85,13 @@ router.post('/:id/cancel', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Bulk-cancel every queued job (running jobs are left alone — they need a
+// per-id POST to trigger the SIGTERM path). Optional ?kind=image|video filter.
+const cancelQueuedSchema = z.object({ kind: z.enum(JOB_KINDS).optional() });
+router.post('/cancel-queued', asyncHandler(async (req, res) => {
+ const { kind } = validateRequest(cancelQueuedSchema, req.query);
+ const result = await cancelQueuedJobs({ kind });
+ res.json(result);
+}));
+
export default router;
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 3e902fae73..0b6ca95e7c 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -121,7 +121,7 @@ export async function generateImage({ codexPath, model, prompt, width, height, n
const meta = {
id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
width: width ? Number(width) : null, height: height ? Number(height) : null,
- filename, mode: 'codex', model: model || null,
+ filename, mode: 'codex', model: model || 'codex',
createdAt: new Date().toISOString(),
};
const job = { ...meta, clients: [], status: 'running' };
diff --git a/server/services/loras.js b/server/services/loras.js
index 136607552e..0de413e766 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -11,8 +11,10 @@
* thing is one POST; progress is reported through the existing image-gen
* SSE channel (TBD — for v1 the client polls).
*
- * No try/catch — errors bubble. Network errors during download leave a
- * partial file on disk; the cleanup happens via a finalizer below.
+ * No try/catch — errors bubble. Stream-failure cleanup is handled inline by
+ * downloadToFile's pipeline().catch (the .partial gets unlinked on network
+ * drops, disk full, etc.); only a process crash or power loss can leave a
+ * .partial behind, and listLoras() filters those out by extension.
*/
import { existsSync } from 'fs';
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 5eca571015..d299675674 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -615,6 +615,26 @@ export function enqueueJob({ kind, params, owner = null }) {
return { jobId: id, position: job.position, status: 'queued' };
}
+// Bulk-cancel every queued job (optionally filtered by kind: 'image' | 'video').
+// Running jobs are left alone — they have to be canceled individually with
+// cancelJob(id) so the SIGTERM path runs. Returns the count of jobs that were
+// dropped from the queue.
+export async function cancelQueuedJobs({ kind } = {}) {
+ // Snapshot the IDs before cancel — cancelJob mutates the queue array, and
+ // we don't want our iteration to skip entries when prior splices shift
+ // indexes. The cancelJob path already handles upload cleanup, archive
+ // push, position recompute, and SSE broadcast, so reuse it.
+ const ids = queue
+ .filter((j) => !kind || j.kind === kind)
+ .map((j) => j.id);
+ let canceled = 0;
+ for (const id of ids) {
+ const r = await cancelJob(id);
+ if (r?.ok) canceled += 1;
+ }
+ return { canceled };
+}
+
// Cancel: drops a queued job, or sends SIGTERM to a running gen process.
export async function cancelJob(jobId) {
const queueIdx = queue.findIndex((j) => j.id === jobId);
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 6e2383b3cc..e3723978ec 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -118,6 +118,53 @@ describe('mediaJobQueue', () => {
expect(mediaJobQueue.listJobs({ status: 'running' })).toHaveLength(1);
});
+ it('cancelQueuedJobs drops every queued job, leaves running ones alone', async () => {
+ // Block the worker so subsequent enqueues stay queued.
+ let resolveBlocker;
+ stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));
+ const blocker = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const a = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const b = mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
+ const c = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+
+ await flush();
+
+ // No filter: every queued job (a, b, c) cancels; running blocker is untouched.
+ const r = await mediaJobQueue.cancelQueuedJobs();
+ expect(r.canceled).toBe(3);
+ expect(mediaJobQueue.getJob(a.jobId).status).toBe('canceled');
+ expect(mediaJobQueue.getJob(b.jobId).status).toBe('canceled');
+ expect(mediaJobQueue.getJob(c.jobId).status).toBe('canceled');
+ expect(mediaJobQueue.getJob(blocker.jobId).status).toBe('running');
+
+ videoGenEvents.emit('failed', { generationId: blocker.jobId, error: 'cleanup' });
+ if (resolveBlocker) resolveBlocker();
+ await flush();
+ });
+
+ it('cancelQueuedJobs respects a kind filter', async () => {
+ let resolveBlocker;
+ stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));
+ const blocker = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const v = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const i = mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
+
+ await flush();
+
+ const r = await mediaJobQueue.cancelQueuedJobs({ kind: 'video' });
+ expect(r.canceled).toBe(1);
+ expect(mediaJobQueue.getJob(v.jobId).status).toBe('canceled');
+ // Image queued job is left in the queue (still 'queued', not canceled).
+ expect(mediaJobQueue.getJob(i.jobId).status).toBe('queued');
+ expect(mediaJobQueue.getJob(blocker.jobId).status).toBe('running');
+
+ // Cleanup the leftover queued image + the running blocker.
+ await mediaJobQueue.cancelJob(i.jobId);
+ videoGenEvents.emit('failed', { generationId: blocker.jobId, error: 'cleanup' });
+ if (resolveBlocker) resolveBlocker();
+ await flush();
+ });
+
it('cancelJob drops a queued job before it starts', async () => {
// Block the worker by making the first job hang — generateVideo never
// resolves, so subsequent enqueues stay queued for cancellation.