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

fix: recover and cancel LoRA caption batches after reload (#9973)

[._.]/ Adam Eivy32a41ba5fd58
diff --git a/client/src/components/loraTraining/DatasetImageGrid.jsx b/client/src/components/loraTraining/DatasetImageGrid.jsx
index 5a39c13be6..d7449d478a 100644
--- a/client/src/components/loraTraining/DatasetImageGrid.jsx
+++ b/client/src/components/loraTraining/DatasetImageGrid.jsx
@@ -7,7 +7,6 @@ import { useState, useEffect, useCallback } from 'react';
import {
Loader2, RefreshCw, AlertTriangle, ChevronLeft, ChevronRight, X, Eye, EyeOff,
} from 'lucide-react';
-import toast from '../ui/Toast';
import Modal from '../ui/Modal';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import AutoSizeTextarea from '../ui/AutoSizeTextarea';
@@ -15,7 +14,6 @@ import Pill from '../ui/Pill';
import {
updateLoraDatasetImageCaption,
deleteLoraDatasetImage,
- startLoraCaptionRun,
} from '../../services/api';
// Lightweight full-size preview for a dataset image. Kept page-local (the
@@ -97,7 +95,7 @@ const SOURCE_BADGE = {
};
export default function DatasetImageGrid({
- dataset, onImagesChange, onCaptionRunStarted, captionModel = null, draftResetToken = 0,
+ dataset, onImagesChange, onRecaption, recaptioningId = null, captionBusy = false, draftResetToken = 0,
}) {
const [drafts, setDrafts] = useState({});
// A bulk caption rewrite in the parent (e.g. strip-shared-fragments) replaces
@@ -107,7 +105,6 @@ export default function DatasetImageGrid({
const [savingId, setSavingId] = useState(null);
const [confirmingId, setConfirmingId] = useState(null);
const [deletingId, setDeletingId] = useState(null);
- const [recaptioningId, setRecaptioningId] = useState(null);
const [showCaptions, setShowCaptions] = useState(true);
// Index into the ready-image subset that the lightbox is previewing (null = closed).
const [previewIndex, setPreviewIndex] = useState(null);
@@ -143,22 +140,6 @@ export default function DatasetImageGrid({
}
};
- const recaption = async (img) => {
- setRecaptioningId(img.id);
- try {
- const run = await startLoraCaptionRun(dataset.id, {
- imageIds: [img.id],
- overwrite: true,
- ...(captionModel?.providerId ? { providerId: captionModel.providerId } : {}),
- ...(captionModel?.model ? { model: captionModel.model } : {}),
- });
- onCaptionRunStarted?.(run);
- toast.success('Re-captioning image…');
- } finally {
- setRecaptioningId(null);
- }
- };
-
if (!dataset.images.length) {
return (
<div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400 text-sm">
@@ -245,8 +226,8 @@ export default function DatasetImageGrid({
<div className="flex items-center justify-between text-xs">
<button
type="button"
- onClick={() => recaption(img)}
- disabled={img.status !== 'ready' || recaptioningId === img.id}
+ onClick={() => onRecaption?.(img)}
+ disabled={img.status !== 'ready' || captionBusy || recaptioningId === img.id}
className="text-gray-400 hover:text-white flex items-center gap-1 disabled:opacity-50"
title="Re-caption with the vision model"
>
diff --git a/client/src/hooks/useSseJobSlot.js b/client/src/hooks/useSseJobSlot.js
index 58761f05c2..f0827f1028 100644
--- a/client/src/hooks/useSseJobSlot.js
+++ b/client/src/hooks/useSseJobSlot.js
@@ -161,6 +161,9 @@ export default function useSseJobSlot({
jobId: job?.jobId ?? null,
percent: progress.percent,
stage: progress.stage,
+ // Most recent frame for THIS job (null until one arrives) — for features
+ // that render counts the percent projection can't carry.
+ latest: job?.jobId ? latest : null,
context: job?.context ?? null,
start,
attach,
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index fe68842bbd..ba2d18ec43 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -12,17 +12,17 @@ import { listSheetPointers } from '../lib/sheetPointers.js';
* single source of truth; rendering images poll-refresh until they land.
*/
-import { useState, useEffect, useMemo, useCallback } from 'react';
+import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { useParams, Link } from 'react-router';
import {
- ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images, Replace, Lightbulb, Eraser,
+ ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images, Replace, Lightbulb, Eraser, XCircle,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
import { IMAGE_ACCEPT } from '../utils/fileUpload';
import Modal from '../components/ui/Modal';
import { useSocketResource } from '../hooks/useSocketResource.js';
-import { useSseProgress } from '../hooks/useSseProgress';
+import useSseJobSlot from '../hooks/useSseJobSlot';
import DatasetImageGrid from '../components/loraTraining/DatasetImageGrid';
import GenerateBatchDialog from '../components/loraTraining/GenerateBatchDialog';
import TrainingPanel from '../components/loraTraining/TrainingPanel';
@@ -44,6 +44,7 @@ import {
uploadLoraDatasetImages,
sliceLoraDatasetRefSheet,
startLoraCaptionRun,
+ cancelLoraCaptionRun,
stripLoraDatasetSharedCaptionFragments,
getUniverse,
} from '../services/api';
@@ -217,8 +218,6 @@ export default function LoraDatasetDetail({ recordId }) {
const [showSlice, setShowSlice] = useState(false);
const [showImport, setShowImport] = useState(false);
const [showReassign, setShowReassign] = useState(false);
- const [captionRun, setCaptionRun] = useState(null);
- const [captionStarting, setCaptionStarting] = useState(false);
// Chosen caption model { providerId, model } — null fields mean "let the
// server auto-pick a vision model". Lifted from CaptionModelPicker so caption
// runs pass the explicit selection.
@@ -297,43 +296,54 @@ export default function LoraDatasetDetail({ recordId }) {
const renderingCount = readiness.rendering;
- // Caption-run SSE — refetch on terminal so captions land in the grid, and
- // surface failures the run reported. The server emits per-image `error`
- // progress frames and a terminal frame carrying the failure tally
- // (`complete` with `failed`, or `error` when every image failed); without
- // this the run just stops spinning and the user never learns an image was
- // refused / returned an empty description.
- const captionSseUrl = captionRun ? `/api/lora-datasets/${datasetId}/caption-runs/${captionRun.runId}/events` : null;
- const captionSse = useSseProgress(captionSseUrl, { enabled: !!captionRun });
- useEffect(() => {
- if (!captionRun || !captionSse.closed) return;
- const last = captionSse.latest;
- // The per-image `progress` frames carry the specific failure reason (refusal
- // vs. a reasoning model that exhausted its token budget). The terminal frame
- // only has a tally, so pull the most recent per-image error to surface the
- // actionable detail — invaluable when a single-image run fails.
- const lastImageError = [...(captionSse.frames || [])]
- .reverse().find((f) => f?.type === 'progress' && f.error)?.error;
- if (last?.type === 'error') {
- // Every image failed — the server's terminal `error` frame carries only a
- // generic "check the vision provider" tally, but the per-image `progress`
- // frames already reported the specific reason (refusal vs. a reasoning
- // model that exhausted its token budget). Prefer that detail; it's the
- // whole point for the common single-image failure, which lands here (not
- // in the `complete` branch) because done===0.
- toast.error(lastImageError || last.message || 'Captioning failed');
- } else if (last?.type === 'complete' && last.failed > 0) {
- const noun = last.failed === 1 ? 'image' : 'images';
- const detail = lastImageError ? ` ${lastImageError}` : '';
- toast.error(last.done > 0
- ? `Captioned ${last.done}/${last.total} — ${last.failed} ${noun} failed.${detail || ' Re-caption individually or pick another vision model.'}`
- : `All ${last.failed} ${noun} failed to caption.${detail || ' The vision model refused or returned nothing — try another vision model.'}`);
- } else if (last?.type === 'complete' && last.done > 0) {
- toast.success(`Captioned ${last.done} image${last.done === 1 ? '' : 's'}`);
+ // Caption run — one slot, driven by the SERVER's run (not the kickoff reply):
+ // the dataset GET reports the in-flight run (`dataset.captionRun`), so a reload,
+ // a second tab or a lost kickoff acknowledgement re-attaches to the same batch
+ // instead of showing idle controls. The server emits per-image `error` progress
+ // and a terminal frame carrying the failure tally + the last per-image reason
+ // (refusal vs. an exhausted reasoning budget); surface it so a failure isn't silent.
+ const toastCaptionFailure = (frame) => {
+ const detail = frame.lastError ? ` ${frame.lastError}` : '';
+ if (frame.type === 'error') {
+ toast.error(frame.lastError || frame.message || frame.error || 'Captioning failed');
+ return;
}
- setCaptionRun(null);
- refresh();
- }, [captionRun, captionSse.closed, captionSse.latest, captionSse.frames, refresh]);
+ const noun = frame.failed === 1 ? 'image' : 'images';
+ toast.error(frame.done > 0
+ ? `Captioned ${frame.done}/${frame.total} — ${frame.failed} ${noun} failed.${detail || ' Re-caption individually or pick another vision model.'}`
+ : `All ${frame.failed} ${noun} failed to caption.${detail || ' The vision model refused or returned nothing — try another vision model.'}`);
+ };
+ // Run ids already adopted from a dataset snapshot — a snapshot read before the
+ // terminal refetch lands must not re-attach to the run that just settled.
+ const adoptedCaptionRuns = useRef(new Set());
+ const captionSlot = useSseJobSlot({
+ startRequest: async (options) => {
+ const run = await startLoraCaptionRun(datasetId, options);
+ if (run.conflict) toast.info('A different caption run is already active on this dataset — showing its progress');
+ return { jobId: run.runId };
+ },
+ eventsUrl: (runId) => `/api/lora-datasets/${datasetId}/caption-runs/${runId}/events`,
+ cancelRequest: (runId, opts) => cancelLoraCaptionRun(datasetId, runId, opts),
+ onKickoffSuccess: (runId) => adoptedCaptionRuns.current.add(runId),
+ onSettled: () => refresh(),
+ onComplete: (frame) => {
+ if (frame.failed > 0) toastCaptionFailure(frame);
+ else if (frame.done > 0) toast.success(`Captioned ${frame.done} image${frame.done === 1 ? '' : 's'}`);
+ },
+ onErrorFrame: (frame) => { toastCaptionFailure(frame); return true; },
+ canceledMessage: 'Captioning canceled — captions already written are kept',
+ lostConnectionMessage: 'Lost connection to the caption run — reload to re-attach',
+ startErrorFallback: 'Failed to start captioning',
+ });
+ const activeCaptionRun = dataset?.captionRun;
+ useEffect(() => {
+ const runId = activeCaptionRun?.runId;
+ if (!runId || adoptedCaptionRuns.current.has(runId)) return;
+ if (captionSlot.attach(runId, null)) adoptedCaptionRuns.current.add(runId);
+ }, [activeCaptionRun?.runId, captionSlot.active]);
+ const captionBusy = captionSlot.active;
+ const captionProgress = captionSlot.latest ?? activeCaptionRun;
+ const canceling = captionProgress?.status === 'canceling';
const onImagesChange = (mutate) => setDataset((prev) => (prev ? { ...prev, images: mutate(prev.images) } : prev));
@@ -382,15 +392,8 @@ export default function LoraDatasetDetail({ recordId }) {
// Caption only images that have no caption yet (overwrite: false). Re-caption
// all overwrites every ready image's caption with the picked model — the way
// to re-run the whole dataset through a newer/better VLM.
- const startCaption = async (overwrite) => {
- setCaptionStarting(true);
- try {
- const run = await startLoraCaptionRun(datasetId, captionOptions({ overwrite }));
- setCaptionRun(run);
- } finally {
- setCaptionStarting(false);
- }
- };
+ const startCaption = (overwrite) => captionSlot.start(captionOptions({ overwrite }));
+ const recaptionImage = (img) => captionSlot.start(captionOptions({ imageIds: [img.id], overwrite: true }));
const captionAll = () => startCaption(false);
const recaptionAll = () => startCaption(true);
@@ -519,18 +522,18 @@ export default function LoraDatasetDetail({ recordId }) {
<button
type="button"
onClick={captionAll}
- disabled={captionStarting || !!captionRun || !readiness.ready}
+ disabled={captionBusy || !readiness.ready}
className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50"
>
- {captionStarting || captionRun ? <Loader2 className="w-4 h-4 animate-spin" /> : <Tags className="w-4 h-4" />}
- {captionRun
- ? `Captioning ${captionSse.latest?.done ?? 0}/${captionSse.latest?.total ?? '…'}`
+ {captionBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Tags className="w-4 h-4" />}
+ {captionBusy
+ ? `Captioning ${captionProgress?.done ?? 0}/${captionProgress?.total ?? '…'}`
: 'Caption all'}
</button>
<button
type="button"
onClick={recaptionAll}
- disabled={captionStarting || !!captionRun || !readiness.ready}
+ disabled={captionBusy || !readiness.ready}
title="Re-caption every ready image with the selected model — overwrites all existing captions, including manual edits"
className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50"
>
@@ -539,6 +542,33 @@ export default function LoraDatasetDetail({ recordId }) {
<CaptionModelPicker onChange={onCaptionModelChange} />
</div>
+ {captionBusy && (
+ <div
+ role="status"
+ className="bg-port-card border border-port-border rounded-lg p-3 flex flex-wrap items-center gap-3 text-sm"
+ >
+ <Loader2 className="w-4 h-4 animate-spin text-port-accent shrink-0" />
+ <div className="min-w-0 flex-1">
+ <div className="text-white">
+ {canceling
+ ? 'Canceling… finishing the vision call already in flight (its result is discarded)'
+ : `Captioning ${captionProgress?.done ?? 0}/${captionProgress?.total ?? '…'}${captionProgress?.failed ? ` · ${captionProgress.failed} failed` : ''}`}
+ </div>
+ {activeCaptionRun?.model && (
+ <div className="text-xs text-gray-400 truncate">{activeCaptionRun.provider} · {activeCaptionRun.model}</div>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={captionSlot.cancel}
+ disabled={!captionSlot.jobId || canceling}
+ className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50 min-h-[40px]"
+ >
+ <XCircle className="w-4 h-4" /> Cancel
+ </button>
+ </div>
+ )}
+
{captionInvariants.sharedFragments.length > 0 && (
<div className="bg-port-warning/10 border border-port-warning/40 rounded-lg p-3 text-sm">
<div className="flex items-start gap-2">
@@ -569,7 +599,7 @@ export default function LoraDatasetDetail({ recordId }) {
<button
type="button"
onClick={stripSharedFragments}
- disabled={strippingFragments || !!captionRun}
+ disabled={strippingFragments || captionBusy}
className="px-3 py-1.5 text-xs rounded bg-port-warning/20 text-port-warning hover:bg-port-warning/30 flex items-center gap-2 disabled:opacity-50"
title="Remove these shared fragments from every caption, keeping the trigger word and per-shot detail"
>
@@ -621,8 +651,9 @@ export default function LoraDatasetDetail({ recordId }) {
<DatasetImageGrid
dataset={dataset}
onImagesChange={onImagesChange}
- onCaptionRunStarted={setCaptionRun}
- captionModel={captionModel}
+ onRecaption={recaptionImage}
+ recaptioningId={captionSlot.context?.imageIds?.length === 1 ? captionSlot.context.imageIds[0] : null}
+ captionBusy={captionBusy}
draftResetToken={captionDraftResetToken}
/>
<TrainingPanel
diff --git a/client/src/pages/LoraDatasetDetail.test.jsx b/client/src/pages/LoraDatasetDetail.test.jsx
index 54dae28dd6..486aaf1d78 100644
--- a/client/src/pages/LoraDatasetDetail.test.jsx
+++ b/client/src/pages/LoraDatasetDetail.test.jsx
@@ -1,11 +1,16 @@
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { afterEach, expect, it, vi } from 'vitest';
import LoraDatasetDetail from './LoraDatasetDetail';
-import { getLoraDataset } from '../services/api';
+import { cancelLoraCaptionRun, getLoraDataset, startLoraCaptionRun } from '../services/api';
import socket from '../services/socket';
-vi.mock('../services/api', () => ({ getLoraDataset: vi.fn(), getUniverse: vi.fn() }));
+vi.mock('../services/api', () => ({
+ getLoraDataset: vi.fn(), getUniverse: vi.fn(), startLoraCaptionRun: vi.fn(), cancelLoraCaptionRun: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), info: vi.fn() }),
+}));
vi.mock('../services/socket', () => {
const handlers = new Map();
return { default: {
@@ -14,7 +19,30 @@ vi.mock('../services/socket', () => {
emit: (event, payload) => handlers.get(event)?.forEach(handler => handler(payload)),
} };
});
-vi.mock('../hooks/useSseProgress', () => ({ useSseProgress: () => ({}) }));
+// Controllable SSE stream: the test pushes frames; the page reads them through
+// the real useSseJobSlot, so adoption/cancel/settlement are exercised end to end.
+const sse = vi.hoisted(() => {
+ const listeners = new Set();
+ let value = { latest: null, closed: false, isOpen: true, frames: [] };
+ return {
+ urls: [],
+ get: () => value,
+ push: (frame) => { value = { latest: frame, closed: true, isOpen: false, frames: [frame] }; listeners.forEach(fn => fn()); },
+ reset: () => { value = { latest: null, closed: false, isOpen: true, frames: [] }; sse.urls.length = 0; },
+ subscribe: (fn) => { listeners.add(fn); return () => listeners.delete(fn); },
+ };
+});
+vi.mock('../hooks/useSseProgress', async () => {
+ const { useSyncExternalStore } = await import('react');
+ return {
+ isTerminalSseFrame: frame => ['complete', 'error', 'canceled'].includes(frame?.type),
+ useSseProgress: (url) => {
+ const value = useSyncExternalStore(sse.subscribe, sse.get);
+ if (url) sse.urls.push(url);
+ return url ? { ...value, latestUrl: url } : { latest: null, closed: false, isOpen: false, frames: [] };
+ },
+ };
+});
vi.mock('../components/loraTraining/TrainingPanel', () => ({ default: () => null }));
vi.mock('../components/loraTraining/CaptionModelPicker', () => ({ default: () => null }));
vi.mock('../components/loraTraining/DatasetImageGrid', () => ({
@@ -24,7 +52,7 @@ const dataset = (id, status = 'rendering') => ({
id, character: { name: id, entryKind: 'characters' }, triggerWord: 'example',
images: [{ id: 'image-1', status, file: 'example.png', caption: '' }], training: {},
});
-afterEach(() => { cleanup(); vi.useRealTimers(); vi.clearAllMocks(); });
+afterEach(() => { cleanup(); vi.useRealTimers(); vi.clearAllMocks(); sse.reset(); });
it('updates on scoped persistence events, reconnect and tab show without polling', async () => {
vi.useFakeTimers();
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
@@ -70,3 +98,46 @@ it('reads a changed route and ignores the previous response and events', async (
await act(async () => { socket.emit('training:dataset:changed', { datasetId: 'example-a' }); });
expect(getLoraDataset).toHaveBeenCalledTimes(2);
});
+
+const readyDataset = (captionRun = null) => ({
+ ...dataset('example-a', 'ready'),
+ images: [{ id: 'image-1', status: 'ready', file: 'example.png', caption: '' }],
+ readiness: {}, captionRun,
+});
+const activeRun = { runId: 'run-1', datasetId: 'example-a', status: 'running', provider: 'p', model: 'm', total: 3, done: 1, failed: 0 };
+
+it('re-attaches to the server caption run after a remount and cancels it from there', async () => {
+ getLoraDataset.mockResolvedValue(readyDataset(activeRun));
+ cancelLoraCaptionRun.mockResolvedValue({ canceled: true });
+ const first = render(<MemoryRouter><LoraDatasetDetail recordId="example-a" /></MemoryRouter>);
+ await act(async () => {});
+ expect(screen.getByRole('button', { name: /Cancel/ })).toBeTruthy();
+ first.unmount();
+ // Reload / second tab: a fresh mount adopts the same run from the dataset read.
+ render(<MemoryRouter><LoraDatasetDetail recordId="example-a" /></MemoryRouter>);
+ await act(async () => {});
+ expect(screen.getAllByText(/Captioning 1\/3/).length).toBeGreaterThan(0);
+ expect(sse.urls.at(-1)).toBe('/api/lora-datasets/example-a/caption-runs/run-1/events');
+ expect(screen.getByRole('button', { name: /^Captioning 1\/3/ }).disabled).toBe(true);
+ expect(startLoraCaptionRun).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Cancel/ }));
+ expect(cancelLoraCaptionRun).toHaveBeenCalledWith('example-a', 'run-1', { silent: true });
+ // The server's terminal canceled frame settles the UI and refetches the dataset.
+ getLoraDataset.mockResolvedValue(readyDataset(null));
+ await act(async () => { sse.push({ type: 'canceled', runId: 'run-1', done: 1, total: 3 }); });
+ expect(screen.queryByRole('button', { name: /^Cancel/ })).toBeNull();
+ expect(screen.getByRole('button', { name: /Caption all/ }).disabled).toBe(false);
+ expect(getLoraDataset).toHaveBeenCalledTimes(3);
+ expect(startLoraCaptionRun).not.toHaveBeenCalled();
+});
+
+it('attaches to the holder when a start reports a conflicting active run', async () => {
+ getLoraDataset.mockResolvedValue(readyDataset(null));
+ startLoraCaptionRun.mockResolvedValue({ runId: 'run-9', alreadyRunning: true, conflict: true, total: 3 });
+ render(<MemoryRouter><LoraDatasetDetail recordId="example-a" /></MemoryRouter>);
+ await act(async () => {});
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Caption all/ })); });
+ expect(sse.urls.at(-1)).toBe('/api/lora-datasets/example-a/caption-runs/run-9/events');
+ expect(screen.getByRole('button', { name: /^Cancel/ })).toBeTruthy();
+});
diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.js
index 9195b0372b..401f13f3d6 100644
--- a/client/src/services/apiLoraTraining.js
+++ b/client/src/services/apiLoraTraining.js
@@ -73,6 +73,11 @@ export const sliceLoraDatasetRefSheet = (id, { variant, cols, rows, useVision }
export const startLoraCaptionRun = (id, options = {}) =>
request(`/lora-datasets/${id}/caption`, { method: 'POST', body: JSON.stringify(options) });
+// Run-scoped cancel: the server rejects (404) a run id that is not the dataset's
+// current caption run. The terminal `canceled` frame follows over SSE.
+export const cancelLoraCaptionRun = (id, runId, options = {}) =>
+ request(`/lora-datasets/${id}/caption-runs/${runId}/cancel`, { method: 'POST', silent: options.silent });
+
export const updateLoraDatasetImageCaption = (id, imageId, caption) =>
request(`/lora-datasets/${id}/images/${imageId}`, {
method: 'PATCH', body: JSON.stringify({ caption }),
diff --git a/server/routes/loraDatasets.caption.test.js b/server/routes/loraDatasets.caption.test.js
new file mode 100644
index 0000000000..e4fa1d9b01
--- /dev/null
+++ b/server/routes/loraDatasets.caption.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+vi.mock('../services/loraDatasets.js', () => ({
+ addUploadedImage: vi.fn(),
+ createDataset: vi.fn(),
+ deleteDataset: vi.fn(),
+ deleteImage: vi.fn(),
+ getDataset: vi.fn(),
+ importGalleryImages: vi.fn(),
+ listDatasets: vi.fn(),
+ patchDataset: vi.fn(),
+ reconcileRenderingImages: vi.fn(async (id) => ({ id, images: [] })),
+ stripSharedCaptionFragments: vi.fn(),
+ updateImageCaption: vi.fn(),
+}));
+vi.mock('../services/loraDatasetGenerate.js', () => ({
+ generateDatasetImages: vi.fn(),
+ getDatasetVariationAxes: vi.fn(),
+ sliceReferenceSheet: vi.fn(),
+}));
+vi.mock('../services/loraDatasetCaption.js', () => ({
+ attachCaptionSseClient: vi.fn(),
+ cancelCaptionRun: vi.fn(),
+ getActiveCaptionRun: vi.fn(),
+ startCaptionRun: vi.fn(),
+}));
+vi.mock('../lib/multipart.js', () => ({ uploadFields: () => (_req, _res, next) => next() }));
+
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { attachCaptionSseClient, cancelCaptionRun, getActiveCaptionRun } from '../services/loraDatasetCaption.js';
+import loraDatasetRoutes from './loraDatasets.js';
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/lora-datasets', loraDatasetRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('LoRA dataset caption-run routes', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('dataset GET carries the dataset-scoped active caption run (or null)', async () => {
+ const run = { runId: 'run-1', datasetId: 'ds-1', status: 'running', total: 3, done: 1, failed: 0 };
+ getActiveCaptionRun.mockReturnValueOnce(run);
+ const active = await request(makeApp()).get('/api/lora-datasets/ds-1');
+ expect(active.body.captionRun).toEqual(run);
+ expect(getActiveCaptionRun).toHaveBeenCalledWith('ds-1');
+ getActiveCaptionRun.mockReturnValueOnce(null);
+ const idle = await request(makeApp()).get('/api/lora-datasets/ds-1');
+ expect(idle.body.captionRun).toBeNull();
+ });
+
+ it('cancel is scoped to dataset + run id and surfaces a mismatch as 404', async () => {
+ cancelCaptionRun.mockReturnValueOnce({ canceled: true, run: { runId: 'run-1', status: 'canceling' } });
+ const ok = await request(makeApp()).post('/api/lora-datasets/ds-1/caption-runs/run-1/cancel');
+ expect(ok.status).toBe(202);
+ expect(cancelCaptionRun).toHaveBeenCalledWith('ds-1', 'run-1');
+ cancelCaptionRun.mockImplementationOnce(() => {
+ throw new ServerError('Caption run not found: stale', { status: 404, code: 'NOT_FOUND' });
+ });
+ const stale = await request(makeApp()).post('/api/lora-datasets/ds-1/caption-runs/stale/cancel');
+ expect(stale.status).toBe(404);
+ });
+
+ it('SSE attach passes the dataset id so a foreign run id is a 404', async () => {
+ attachCaptionSseClient.mockReturnValueOnce(false);
+ const res = await request(makeApp()).get('/api/lora-datasets/ds-2/caption-runs/run-1/events');
+ expect(attachCaptionSseClient).toHaveBeenCalledWith('ds-2', 'run-1', expect.anything());
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.js
index 01a0055117..4513739205 100644
--- a/server/routes/loraDatasets.js
+++ b/server/routes/loraDatasets.js
@@ -27,7 +27,9 @@ import {
updateImageCaption,
} from '../services/loraDatasets.js';
import { generateDatasetImages, getDatasetVariationAxes, sliceReferenceSheet } from '../services/loraDatasetGenerate.js';
-import { attachCaptionSseClient, startCaptionRun } from '../services/loraDatasetCaption.js';
+import {
+ attachCaptionSseClient, cancelCaptionRun, getActiveCaptionRun, startCaptionRun,
+} from '../services/loraDatasetCaption.js';
import { LORA_DATASET_ENTRY_KINDS, computeDatasetReadiness } from '../lib/loraDataset.js';
const router = Router();
@@ -65,7 +67,9 @@ router.get('/:id', asyncHandler(async (req, res) => {
// Heal any images stuck in 'rendering' (server restart dropped the live
// completion hook) before returning — the grid then shows truth.
const dataset = await reconcileRenderingImages(req.params.id);
- res.json({ ...dataset, readiness: computeDatasetReadiness(dataset) });
+ // `captionRun` is the in-flight caption batch (or null) — how a reloaded page
+ // or a second tab discovers, observes and cancels work the server is still doing.
+ res.json({ ...dataset, readiness: computeDatasetReadiness(dataset), captionRun: getActiveCaptionRun(req.params.id) });
}));
// Live variation axes (expressions/outfits for characters; lighting/settings
@@ -171,11 +175,18 @@ router.post('/:id/caption', asyncHandler(async (req, res) => {
}));
router.get('/:id/caption-runs/:runId/events', asyncHandler(async (req, res) => {
- if (!attachCaptionSseClient(req.params.runId, res)) {
+ if (!attachCaptionSseClient(req.params.id, req.params.runId, res)) {
throw new ServerError(`Caption run not found: ${req.params.runId}`, { status: 404, code: 'NOT_FOUND' });
}
}));
+// Run-scoped cancel: the id must match the dataset's CURRENT run, so a stale tab
+// can't stop a newer batch. Returns the (now `canceling`) run projection; the
+// terminal `canceled` frame follows over SSE once the run settles.
+router.post('/:id/caption-runs/:runId/cancel', asyncHandler(async (req, res) => {
+ res.status(202).json(cancelCaptionRun(req.params.id, req.params.runId));
+}));
+
// Bulk caption lint — strip the identity fragments shared across most captions
// so the trigger token (not the caption phrases) learns the character. The
// server recomputes the shared set itself; no request body.
diff --git a/server/routes/loraDatasets.pagination.test.js b/server/routes/loraDatasets.pagination.test.js
index 5e404b5bc9..308b3e3d92 100644
--- a/server/routes/loraDatasets.pagination.test.js
+++ b/server/routes/loraDatasets.pagination.test.js
@@ -26,6 +26,8 @@ vi.mock('../services/loraDatasetGenerate.js', () => ({
vi.mock('../services/loraDatasetCaption.js', () => ({
attachCaptionSseClient: vi.fn(),
+ cancelCaptionRun: vi.fn(),
+ getActiveCaptionRun: vi.fn(),
startCaptionRun: vi.fn(),
}));
diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.js
index 8dcc794d4d..4e1073db68 100644
--- a/server/services/loraDatasetCaption.js
+++ b/server/services/loraDatasetCaption.js
@@ -24,9 +24,8 @@
import { readFile } from 'fs/promises';
import { ServerError } from '../lib/errorHandler.js';
import { shortId } from '../lib/fileUtils.js';
-import { v4 as uuidv4 } from '../lib/uuid.js';
import { prefixCaption } from '../lib/loraDataset.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
+import { createSseRunner } from '../lib/sseUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import { describeImageDataUrlDetailed } from './visionTest.js';
import { getSettings } from './settings.js';
@@ -101,11 +100,83 @@ const CAPTION_MAX_TOKENS = 600;
// FIFO-starve an interactive describe.
export const withCaptionVisionLock = createMutex();
-// runId → { clients: [], lastPayload } — same shape the imageGen/videoGen
-// SSE helpers operate on.
-const captionRuns = new Map();
+// One caption run per dataset: the runner keys its map by datasetId, so a second
+// kickoff for the same dataset adopts the in-flight run (identical work) or is
+// reported as a conflict (different work) instead of spawning another detached
+// loop against the same images. The run's identity is therefore discoverable
+// from the dataset alone — a reloaded page / second tab re-attaches to it.
+const captionRunner = createSseRunner({ logLabel: 'lora caption run' });
-export const attachCaptionSseClient = (runId, res) => attachSse(captionRuns, runId, res);
+/** Live run record for `datasetId` only when it is still the `runId` asked for. */
+const recordFor = (datasetId, runId) => {
+ const record = captionRunner.runs.get(datasetId);
+ return record && record.runId === runId ? record : null;
+};
+
+/**
+ * Attach an SSE client to a run. The run must belong to THIS dataset and carry
+ * this id — a stale id for an older run (or another dataset's id) never binds
+ * onto whatever run currently holds the dataset's slot.
+ */
+export const attachCaptionSseClient = (datasetId, runId, res) => (
+ recordFor(datasetId, runId) ? captionRunner.attachClient(datasetId, res) : false
+);
+
+const projectRun = (record) => ({
+ runId: record.runId,
+ datasetId: record.meta.datasetId,
+ status: record.cancelRequested ? 'canceling' : 'running',
+ provider: record.meta.provider,
+ model: record.meta.model,
+ total: record.meta.total,
+ done: record.meta.done,
+ failed: record.meta.failed,
+ startedAt: record.startedAt,
+});
+
+/**
+ * Bounded projection of the dataset's in-flight caption run, or null. Carries
+ * no clients, controller or image content. `status: 'canceling'` means a cancel
+ * was requested but the run has not yet emitted its terminal frame (it is still
+ * settling an already-issued vision call).
+ */
+export const getActiveCaptionRun = (datasetId) => {
+ const record = captionRunner.runs.get(datasetId);
+ return record && !record.finished ? projectRun(record) : null;
+};
+
+/**
+ * Cancel the dataset's caption run, requiring the run id to match. Throws 404
+ * for an unknown/superseded run. A run that already finished (still inside its
+ * terminal-replay window) reports `canceled: false` rather than erroring so a
+ * late Cancel click is harmless.
+ */
+export function cancelCaptionRun(datasetId, runId) {
+ const record = recordFor(datasetId, runId);
+ if (!record) {
+ throw new ServerError(`Caption run not found: ${runId}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ if (record.finished) return { canceled: false, run: null };
+ captionRunner.cancel(datasetId);
+ return { canceled: true, run: projectRun(record) };
+}
+
+const CANCELED = Symbol('caption-canceled');
+
+// Settle with CANCELED as soon as `signal` aborts, without waiting on `promise`.
+// The vision adapter takes no AbortSignal, so an already-issued call cannot be
+// terminated — the run stops waiting for it and its late result is discarded.
+// The original promise keeps its own rejection handler so a late failure is not
+// an unhandled rejection.
+function raceCancel(promise, signal) {
+ promise.catch(() => {});
+ if (signal.aborted) return Promise.resolve(CANCELED);
+ return new Promise((resolve, reject) => {
+ const onAbort = () => resolve(CANCELED);
+ signal.addEventListener('abort', onAbort, { once: true });
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
+ });
+}
/**
* Resolve which provider+model the run captions with, requiring a
@@ -220,16 +291,17 @@ export function buildCaption(triggerWord, text, model = 'vision model', meta = n
return prefixCaption(triggerWord, text);
}
-const emit = (runId, payload) => {
- const run = captionRuns.get(runId);
- if (run) broadcastSse(run, payload);
-};
-
/**
- * Start a caption run. Returns `{ runId, total }` immediately; the loop
+ * Start (or adopt) the dataset's caption run. Returns
+ * `{ runId, total, provider, alreadyRunning, conflict? }` immediately; the loop
* runs detached. `imageIds` limits the run to specific images (single
* re-caption = one-element array); `overwrite: false` skips images that
- * already have a caption.
+ * already have a caption — so starting again after an interrupted run retries
+ * only the images that never got one.
+ *
+ * Identical work (same targets, overwrite mode, provider and model) adopts the
+ * in-flight run; different work returns the holder's id with `conflict: true`
+ * so the caller can attach to it instead of silently double-booking the images.
*/
export async function startCaptionRun(datasetId, {
imageIds = null, providerId = null, model = null, overwrite = false,
@@ -269,58 +341,105 @@ export async function startCaptionRun(datasetId, {
}
const captionPrompt = buildCaptionPrompt(signaturePhrases);
- const runId = uuidv4();
- captionRuns.set(runId, { clients: [], lastPayload: null });
- console.log(`🏷️ Caption run ${shortId(runId)} — dataset=${shortId(datasetId)} images=${targets.length} provider=${resolvedProvider} model=${resolvedModel}`);
+ const targetIds = targets.map((img) => img.id);
+ const sig = JSON.stringify({
+ ids: [...targetIds].sort(), overwrite: !!overwrite, provider: resolvedProvider, model: resolvedModel,
+ });
+ const meta = {
+ datasetId, provider: resolvedProvider, model: resolvedModel, total: targets.length, done: 0, failed: 0, lastError: null,
+ };
+
+ // `start` is synchronous (no await between its in-flight check and the map
+ // write), so concurrent kickoffs that got past the awaits above cannot both
+ // become coordinators.
+ const started = captionRunner.start(datasetId, ({ runId, signal, record, broadcast }) => runCaptionLoop({
+ runId, signal, meta: record.meta, broadcast, dataset, targets, captionPrompt,
+ }), { sig, meta });
+
+ if (started.alreadyRunning) {
+ const holder = captionRunner.runs.get(datasetId);
+ console.log(`🏷️ Caption run ${shortId(started.runId)} already active for dataset=${shortId(datasetId)} — ${started.conflict ? 'conflicting request attached to it' : 'identical request adopted it'}`);
+ return {
+ runId: started.runId,
+ total: holder.meta.total,
+ provider: holder.meta.provider,
+ alreadyRunning: true,
+ ...(started.conflict ? { conflict: true } : {}),
+ };
+ }
+ console.log(`🏷️ Caption run ${shortId(started.runId)} — dataset=${shortId(datasetId)} images=${targets.length} provider=${resolvedProvider} model=${resolvedModel}`);
+ return { runId: started.runId, total: targets.length, provider: resolvedProvider, alreadyRunning: false };
+}
- // Detached loop — runs outside the request lifecycle, so each iteration
- // wraps its fallible work in try/catch (the async-boundary exception to
- // the no-try/catch rule) and failures route into the SSE error frames.
- (async () => {
- let done = 0;
- let failed = 0;
- for (const img of targets) {
- let caption = null;
- try {
- const bytes = await readFile(datasetImagePath(datasetId, img.file));
- const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
- const result = await withCaptionVisionLock(() => describeImageDataUrlDetailed({
+/**
+ * The detached per-run loop. Runs inside `createSseRunner`'s coordinator, which
+ * owns the generic `error` frame and the terminal-replay cleanup; per-image
+ * failures are caught here (a boundary outside the request lifecycle) and routed
+ * into `progress` frames. Cancellation is checked before and after acquiring the
+ * vision mutex, after inference returns, and before each caption is committed.
+ */
+async function runCaptionLoop({ runId, signal, meta, broadcast, dataset, targets, captionPrompt }) {
+ const datasetId = dataset.id;
+ const total = targets.length;
+ let settling = false;
+ const canceled = () => {
+ broadcast({ type: 'canceled', runId, done: meta.done, failed: meta.failed, total, settling });
+ console.log(`🏷️ Caption run ${shortId(runId)} canceled — ${meta.done}/${total} captioned${settling ? ' (a vision call was still settling; its result is discarded)' : ''}`);
+ };
+
+ for (const img of targets) {
+ if (signal.aborted) return canceled();
+ let caption = null;
+ try {
+ const bytes = await readFile(datasetImagePath(datasetId, img.file));
+ if (signal.aborted) return canceled();
+ const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
+ // A run canceled while queued behind another dataset's vision call
+ // returns here when the mutex frees WITHOUT calling the provider.
+ const call = withCaptionVisionLock(() => {
+ if (signal.aborted) return CANCELED;
+ settling = true;
+ return describeImageDataUrlDetailed({
dataUrl,
prompt: captionPrompt,
- providerId: resolvedProvider,
- model: resolvedModel,
+ providerId: meta.provider,
+ model: meta.model,
maxTokens: CAPTION_MAX_TOKENS,
- }));
- caption = buildCaption(dataset.triggerWord, result.text, `vision model "${resolvedModel}"`, result);
- } catch (err) {
- failed += 1;
- console.error(`❌ Caption failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);
- emit(runId, { type: 'progress', done, total: targets.length, imageId: img.id, error: String(err?.message || err) });
- continue;
- }
- try {
- await updateDataset(datasetId, (current) => ({
- ...current,
- images: current.images.map((i) => (i.id === img.id
- ? { ...i, caption, captionSource: 'vision', captionedAt: new Date().toISOString() }
- : i)),
- }));
- } catch (err) {
- failed += 1;
- console.error(`❌ Caption persist failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);
- emit(runId, { type: 'progress', done, total: targets.length, imageId: img.id, error: String(err?.message || err) });
- continue;
- }
- done += 1;
- emit(runId, { type: 'progress', done, total: targets.length, imageId: img.id, caption });
+ }).finally(() => { settling = false; });
+ });
+ const result = await raceCancel(call, signal);
+ if (result === CANCELED || signal.aborted) return canceled();
+ caption = buildCaption(dataset.triggerWord, result.text, `vision model "${meta.model}"`, result);
+ } catch (err) {
+ meta.failed += 1;
+ meta.lastError = String(err?.message || err);
+ console.error(`❌ Caption failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);
+ broadcast({ type: 'progress', runId, done: meta.done, total, imageId: img.id, error: String(err?.message || err) });
+ continue;
}
- const terminal = failed && !done
- ? { type: 'error', message: `All ${failed} caption(s) failed — check the vision provider (${resolvedProvider})` }
- : { type: 'complete', done, failed, total: targets.length };
- emit(runId, terminal);
- console.log(`🏷️ Caption run ${shortId(runId)} finished — ${done}/${targets.length} captioned, ${failed} failed`);
- closeJobAfterDelay(captionRuns, runId);
- })();
-
- return { runId, total: targets.length, provider: resolvedProvider };
+ try {
+ await updateDataset(datasetId, (current) => ({
+ ...current,
+ images: current.images.map((i) => (i.id === img.id
+ ? { ...i, caption, captionSource: 'vision', captionedAt: new Date().toISOString() }
+ : i)),
+ }));
+ } catch (err) {
+ meta.failed += 1;
+ meta.lastError = String(err?.message || err);
+ console.error(`❌ Caption persist failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);
+ broadcast({ type: 'progress', runId, done: meta.done, total, imageId: img.id, error: String(err?.message || err) });
+ continue;
+ }
+ meta.done += 1;
+ broadcast({ type: 'progress', runId, done: meta.done, total, imageId: img.id, caption });
+ }
+ // Terminal frames carry the most recent per-image failure reason: a tab that
+ // attached after the `progress` frames were sent only replays this last frame,
+ // so the actionable detail (refusal vs. exhausted reasoning budget) must ride it.
+ const { done, failed, lastError } = meta;
+ broadcast(failed && !done
+ ? { type: 'error', runId, message: `All ${failed} caption(s) failed — check the vision provider (${meta.provider})`, lastError }
+ : { type: 'complete', runId, done, failed, total, lastError });
+ console.log(`🏷️ Caption run ${shortId(runId)} finished — ${done}/${total} captioned, ${failed} failed`);
}
diff --git a/server/services/loraDatasetCaption.runs.test.js b/server/services/loraDatasetCaption.runs.test.js
new file mode 100644
index 0000000000..2a07a75128
--- /dev/null
+++ b/server/services/loraDatasetCaption.runs.test.js
@@ -0,0 +1,170 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Run-lifecycle contract for caption batches: one run per dataset, discoverable
+// by dataset id, cancellable by run id, and never double-booking an image.
+// Dependencies are doubled at the module edge so the REAL createSseRunner-backed
+// service drives the lifecycle (no provider, disk or settings access).
+
+const state = vi.hoisted(() => ({ dataset: null, vision: [] }));
+
+vi.mock('./loraDatasets.js', () => ({
+ getDataset: vi.fn(async () => structuredClone(state.dataset)),
+ datasetImagePath: (id, file) => `/nonexistent/${id}/${file}`,
+ updateDataset: vi.fn(async (_id, mutate) => {
+ state.dataset = mutate(state.dataset);
+ return state.dataset;
+ }),
+}));
+vi.mock('fs/promises', () => ({ readFile: vi.fn(async () => Buffer.from('png')) }));
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+vi.mock('./localLlm.js', () => ({ listVisionModels: vi.fn(async () => []) }));
+vi.mock('./loraDatasetSubject.js', () => ({
+ loadDatasetSubject: vi.fn(async () => { throw new Error('no subject'); }),
+ extractSubjectSignaturePhrases: vi.fn(() => []),
+}));
+// Each vision call is a deferred the test resolves by hand.
+vi.mock('./visionTest.js', () => ({
+ describeImageDataUrlDetailed: vi.fn(() => new Promise((resolve, reject) => {
+ state.vision.push({ resolve, reject });
+ })),
+}));
+
+const { startCaptionRun, cancelCaptionRun, getActiveCaptionRun, attachCaptionSseClient, withCaptionVisionLock } = await import('./loraDatasetCaption.js');
+const { describeImageDataUrlDetailed } = await import('./visionTest.js');
+
+const REPLY = { text: 'standing, full body', finishReason: 'stop', usage: null, reasoning: '' };
+const MODEL = { providerId: 'lmstudio', model: 'qwen2.5-vl-7b' };
+const flush = () => new Promise((r) => setImmediate(r));
+const settle = async (n = 5) => { for (let i = 0; i < n; i += 1) await flush(); };
+
+const makeDataset = (n = 3) => ({
+ id: 'ds-1',
+ triggerWord: 'example_trigger',
+ images: Array.from({ length: n }, (_, i) => ({ id: `img-${i}`, status: 'ready', file: `${i}.png`, caption: '' })),
+});
+
+// Minimal SSE response double: records frames written to it.
+const fakeRes = () => {
+ const frames = [];
+ return {
+ frames,
+ writeHead: vi.fn(),
+ write: (msg) => frames.push(JSON.parse(msg.replace(/^data: /, ''))),
+ end: vi.fn(),
+ req: { on: vi.fn() },
+ };
+};
+
+describe('caption run lifecycle', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ state.dataset = makeDataset();
+ state.vision = [];
+ vi.clearAllMocks();
+ });
+ afterEach(async () => {
+ // Drain any run left active by a failing assertion so cases stay isolated.
+ const live = getActiveCaptionRun('ds-1');
+ if (live) {
+ cancelCaptionRun('ds-1', live.runId);
+ state.vision.forEach((v) => v.resolve(REPLY));
+ await settle();
+ }
+ await vi.runAllTimersAsync();
+ vi.useRealTimers();
+ });
+
+ it('exposes the active run by dataset id and adopts an identical second start', async () => {
+ const first = await startCaptionRun('ds-1', MODEL);
+ const second = await startCaptionRun('ds-1', MODEL);
+ expect(second).toMatchObject({ runId: first.runId, alreadyRunning: true });
+ expect(second.conflict).toBeUndefined();
+ await settle();
+ expect(getActiveCaptionRun('ds-1')).toMatchObject({
+ runId: first.runId, datasetId: 'ds-1', status: 'running', total: 3, done: 0, model: MODEL.model,
+ });
+ // One coordinator → one in-flight vision call for the first target only.
+ expect(describeImageDataUrlDetailed).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports different work as a conflict carrying the holder id, without a second run', async () => {
+ const first = await startCaptionRun('ds-1', MODEL);
+ const single = await startCaptionRun('ds-1', { ...MODEL, imageIds: ['img-1'], overwrite: true });
+ expect(single).toMatchObject({ runId: first.runId, alreadyRunning: true, conflict: true, total: 3 });
+ await settle();
+ expect(describeImageDataUrlDetailed).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps run identity out of reach of a different run id (attach and cancel)', async () => {
+ const run = await startCaptionRun('ds-1', MODEL);
+ expect(attachCaptionSseClient('ds-1', 'stale-run-id', fakeRes())).toBe(false);
+ expect(attachCaptionSseClient('other-dataset', run.runId, fakeRes())).toBe(false);
+ expect(() => cancelCaptionRun('ds-1', 'stale-run-id')).toThrow(/not found/i);
+ expect(() => cancelCaptionRun('other-dataset', run.runId)).toThrow(/not found/i);
+ expect(getActiveCaptionRun('ds-1').status).toBe('running');
+ expect(attachCaptionSseClient('ds-1', run.runId, fakeRes())).toBe(true);
+ });
+
+ it('cancel during an active call discards its late result and launches no next image', async () => {
+ const run = await startCaptionRun('ds-1', MODEL);
+ await settle();
+ const res = fakeRes();
+ attachCaptionSseClient('ds-1', run.runId, res);
+ expect(cancelCaptionRun('ds-1', run.runId)).toMatchObject({ canceled: true, run: { status: 'canceling' } });
+ await settle();
+ // Terminal canceled frame is emitted without waiting for the in-flight call…
+ expect(res.frames.at(-1)).toMatchObject({ type: 'canceled', done: 0, total: 3, settling: true });
+ // …and the late result is discarded: nothing persisted, no next image.
+ state.vision[0].resolve(REPLY);
+ await settle();
+ expect(state.dataset.images.every((i) => !i.caption)).toBe(true);
+ expect(describeImageDataUrlDetailed).toHaveBeenCalledTimes(1);
+ expect(getActiveCaptionRun('ds-1')).toBeNull();
+ });
+
+ it('cancel while queued behind another run never invokes the provider', async () => {
+ // Another dataset's vision call holds the shared mutex.
+ let releaseOther;
+ const other = withCaptionVisionLock(() => new Promise((r) => { releaseOther = r; }));
+ const run = await startCaptionRun('ds-1', MODEL);
+ await settle();
+ expect(describeImageDataUrlDetailed).not.toHaveBeenCalled();
+ const res = fakeRes();
+ attachCaptionSseClient('ds-1', run.runId, res);
+ cancelCaptionRun('ds-1', run.runId);
+ await settle();
+ expect(res.frames.at(-1)).toMatchObject({ type: 'canceled', settling: false });
+ releaseOther();
+ await other;
+ await settle();
+ expect(describeImageDataUrlDetailed).not.toHaveBeenCalled();
+ });
+
+ it('completes, keeps finished captions, and a later start retries only unfinished images', async () => {
+ const run = await startCaptionRun('ds-1', MODEL);
+ await settle();
+ state.vision[0].resolve(REPLY); // img-0 captioned
+ await settle();
+ cancelCaptionRun('ds-1', run.runId);
+ await settle();
+ expect(state.dataset.images[0].caption).toMatch(/standing, full body/);
+ expect(state.dataset.images.slice(1).every((i) => !i.caption)).toBe(true);
+ // Settled → an immediate restart is a NEW run over just the two unfinished images.
+ const retry = await startCaptionRun('ds-1', MODEL);
+ expect(retry.alreadyRunning).toBe(false);
+ expect(retry.runId).not.toBe(run.runId);
+ expect(retry.total).toBe(2);
+ });
+
+ it('replays the terminal frame to a late attach and reports per-image errors', async () => {
+ state.dataset = makeDataset(1);
+ const run = await startCaptionRun('ds-1', MODEL);
+ await settle();
+ state.vision[0].reject(new Error('refused'));
+ await settle();
+ const res = fakeRes();
+ expect(attachCaptionSseClient('ds-1', run.runId, res)).toBe(true);
+ expect(res.frames).toEqual([expect.objectContaining({ type: 'error', runId: run.runId })]);
+ expect(getActiveCaptionRun('ds-1')).toBeNull();
+ });
+});