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: stop LoRA dataset page from mirroring training readiness logic (#8297)

[._.]/ Adam Eivy5113f1cf06a4
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 00b17bf634..a20c352b98 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -71,6 +71,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
| `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/reviewerConfig.js`. Also preserves configured-provider model and effort pins in the additive `providerModels` / `providerEfforts` maps, keyed by `provider:<id>`; empty maps clear overrides without changing builtin scalars. |
| `reviewerPins.js` | Client mirror of the whole reviewer vocabulary — the roster (`REVIEWER_VALUES`), `REVIEWER_ALIASES`, `DEFAULT_REVIEWER(S)`, `normalizeReviewers`, the review-username pattern/cap (`MAX_REVIEW_USERNAMES` / `cleanReviewUsername` / `normalizeReviewUsernames`), `MAX_REVIEWER_MAX_ROUNDS`, `REVIEW_STOP_MODES` / `DEFAULT_REVIEW_STOP_MODE`, plus the per-reviewer pin vocabularies (`MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput`) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against `server/lib/reviewerConfig.js`, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. `isProviderReviewer` recognizes the shared `provider:<id>` identity alongside legacy harness slugs. |
+| `loraDatasetReadiness.js` | Re-export of `server/lib/loraDataset.js` (#8297) — `MIN_TRAINING_IMAGES` / `RECOMMENDED_TRAINING_IMAGES` / `TRAINING_IMAGE_SWEET_SPOT_MAX`, `captionHasTriggerWord`, `datasetQualityTier`, `computeDatasetReadiness`, `analyzeCaptionInvariants` (+ its `INVARIANT_SHARE_THRESHOLD` / `MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS`). `LoraDatasetDetail.jsx`'s live advisory (readiness summary, Train gate, shared-caption-fragment warning) calls these directly instead of a page-local mirror, so it cannot drift from the server's authoritative training gate. |
| `loraEffect.js` | How the LoRA manager card renders an adapter-effect measurement (#4872). `LORA_EFFECT_STATUSES` is re-exported from `server/lib/loraEffect.js`; `LORA_EFFECT_BADGES` + `loraEffectBadge(status)` (only `zero` is styled as an error, because only `zero` refuses a render server-side) and `loraEffectDetail(report)` are client-only — the detail line returns `null` when the badge already says everything, where the server's `formatLoraEffect` always returns a sentence for its log. |
| `loraTriggers.js` | The picker's `+ trigger` append (#4665). `firstTriggerWord` / `promptHasTriggerWord` / `separatorFor` are re-exported from `server/lib/loraTriggers.js`, so the hint reads the rule the render enforces. `appendTriggerWords(prompt, words, effectivePrompt?)` is client-only: it adds ALL of a LoRA's words (the server only ever weaves the first) and judges presence against the composed prompt the page will actually submit. |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`, including the shared LTX + MiniMax H3 Ref2VA audio-to-video runtime predicate. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index af98645a05..a2ffa1d7b2 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -9,6 +9,7 @@ export * from './canonPrompt.js';
export * from './cleanPlatePrompt.js';
export * from './composeStyledPrompt.js';
export * from './decks.js';
+export * from './loraDatasetReadiness.js';
export * from './personaTraitBlend.js';
export * from './scenePrompt.js';
export * from './seasonStructure.js';
diff --git a/client/src/lib/loraDatasetReadiness.js b/client/src/lib/loraDatasetReadiness.js
new file mode 100644
index 0000000000..93c73224fc
--- /dev/null
+++ b/client/src/lib/loraDatasetReadiness.js
@@ -0,0 +1,26 @@
+/**
+ * LoRA dataset training-readiness thresholds, trigger-word matching, and
+ * caption-invariant analysis.
+ *
+ * Re-export of `server/lib/loraDataset.js` — the one definition of these
+ * rules, imported rather than copied so the page-local advisory (which
+ * updates the instant a caption is edited or an image deleted, without a
+ * server round-trip — see `client/src/pages/LoraDatasetDetail.jsx`) cannot
+ * drift from `computeDatasetReadiness` / `validateDatasetReady`, the
+ * authoritative gate the server applies at train time (#8297). The server
+ * module is dependency-free (`isPlainObject`, `escapeRegExp` — no Node
+ * builtins), so it is safe to bundle into the browser build; see
+ * `scripts/client-server-import-purity.test.js`.
+ */
+export {
+ MIN_TRAINING_IMAGES,
+ RECOMMENDED_TRAINING_IMAGES,
+ TRAINING_IMAGE_SWEET_SPOT_MAX,
+ INVARIANT_SHARE_THRESHOLD,
+ MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS,
+ isValidTriggerWord,
+ captionHasTriggerWord,
+ datasetQualityTier,
+ computeDatasetReadiness,
+ analyzeCaptionInvariants,
+} from '../../../server/lib/loraDataset.js';
diff --git a/client/src/lib/loraDatasetReadiness.test.js b/client/src/lib/loraDatasetReadiness.test.js
new file mode 100644
index 0000000000..78c7a931a4
--- /dev/null
+++ b/client/src/lib/loraDatasetReadiness.test.js
@@ -0,0 +1,107 @@
+// @vitest-environment node
+import { describe, it, expect } from 'vitest';
+import * as clientReadiness from './loraDatasetReadiness.js';
+import * as serverReadiness from '../../../server/lib/loraDataset.js';
+
+// Cross-runtime contract (#8297): `LoraDatasetDetail.jsx`'s live training
+// advisory (readiness summary, Train gate, shared-caption-fragment warning)
+// calls these helpers directly instead of a page-local mirror, so a page
+// caption/trigger-word edit can never show "Ready to train" while the
+// server's `validateDatasetReady` gate (which calls the same
+// `computeDatasetReadiness`/`analyzeCaptionInvariants`) would reject the run.
+// Two layers of protection:
+// 1. Reference identity — the client module is a straight re-export, so a
+// future edit that quietly swaps it for a duplicated implementation
+// (reintroducing the drift issue #8297 fixed) fails here immediately.
+// 2. Behavior on the shared fixture matrix (valid / boundary / non-
+// trainable), so the contract is pinned even if the re-export shape
+// changes later.
+const EXPORT_NAMES = [
+ 'MIN_TRAINING_IMAGES',
+ 'RECOMMENDED_TRAINING_IMAGES',
+ 'TRAINING_IMAGE_SWEET_SPOT_MAX',
+ 'INVARIANT_SHARE_THRESHOLD',
+ 'MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS',
+ 'isValidTriggerWord',
+ 'captionHasTriggerWord',
+ 'datasetQualityTier',
+ 'computeDatasetReadiness',
+ 'analyzeCaptionInvariants',
+];
+
+const readyImage = (caption) => ({ status: 'ready', caption });
+const renderingImage = () => ({ status: 'rendering', caption: '' });
+
+// 10 ready, captioned images naming the trigger — exactly MIN_TRAINING_IMAGES.
+const boundaryImages = Array.from(
+ { length: 10 },
+ (_, i) => readyImage(`subj_x, pose ${i}, studio lighting`),
+);
+
+// Same images as boundaryImages, plus a few more so 4 of the captions repeat
+// an identical descriptive fragment ("white hair") — enough signal for
+// analyzeCaptionInvariants to flag it as a shared identity fragment.
+const invariantImages = [
+ readyImage('subj_x, white hair, pose a'),
+ readyImage('subj_x, white hair, pose b'),
+ readyImage('subj_x, white hair, pose c'),
+ readyImage('subj_x, white hair, pose d'),
+ readyImage('subj_x, pose e'),
+];
+
+describe('loraDatasetReadiness (client re-export of server/lib/loraDataset.js)', () => {
+ it('re-exports the exact same functions/constants the server owns — no page-local copy', () => {
+ for (const name of EXPORT_NAMES) {
+ expect(clientReadiness[name]).toBe(serverReadiness[name]);
+ }
+ });
+
+ it('agrees with the server on a trainable dataset at the sweet spot (valid)', () => {
+ const dataset = {
+ triggerWord: 'subj_x',
+ images: Array.from({ length: 22 }, (_, i) => readyImage(`subj_x, pose ${i}`)),
+ };
+ const clientResult = clientReadiness.computeDatasetReadiness(dataset);
+ const serverResult = serverReadiness.computeDatasetReadiness(dataset);
+ expect(clientResult).toEqual(serverResult);
+ expect(clientResult).toMatchObject({ trainable: true, quality: 'good', captioned: 22 });
+ });
+
+ it('agrees with the server exactly at the MIN_TRAINING_IMAGES boundary', () => {
+ const dataset = { triggerWord: 'subj_x', images: boundaryImages };
+ const clientResult = clientReadiness.computeDatasetReadiness(dataset);
+ const serverResult = serverReadiness.computeDatasetReadiness(dataset);
+ expect(clientResult).toEqual(serverResult);
+ expect(clientResult).toMatchObject({
+ trainable: true,
+ quality: 'minimum',
+ captioned: clientReadiness.MIN_TRAINING_IMAGES,
+ });
+ });
+
+ it('agrees with the server on a non-trainable dataset (missing trigger word)', () => {
+ const dataset = { triggerWord: '', images: [...boundaryImages, renderingImage()] };
+ const clientResult = clientReadiness.computeDatasetReadiness(dataset);
+ const serverResult = serverReadiness.computeDatasetReadiness(dataset);
+ expect(clientResult).toEqual(serverResult);
+ // No trigger word configured: never trainable, quality never reports
+ // 'good'/'minimum' even though 10 images are otherwise ready+captioned.
+ expect(clientResult).toMatchObject({ trainable: false, quality: 'insufficient', rendering: 1 });
+ });
+
+ it('agrees with the server on caption-invariant fragment detection', () => {
+ const clientResult = clientReadiness.analyzeCaptionInvariants(invariantImages, 'subj_x');
+ const serverResult = serverReadiness.analyzeCaptionInvariants(invariantImages, 'subj_x');
+ expect(clientResult).toEqual(serverResult);
+ expect(clientResult.analyzable).toBe(true);
+ expect(clientResult.sharedFragments.map((f) => f.normalized)).toContain('white hair');
+ });
+
+ it('agrees with the server on trigger-word token-boundary matching', () => {
+ // "train" contains "ai" as a substring but not as a bounded token.
+ expect(clientReadiness.captionHasTriggerWord('a subject in training gear', 'ai'))
+ .toBe(serverReadiness.captionHasTriggerWord('a subject in training gear', 'ai'));
+ expect(clientReadiness.captionHasTriggerWord('subj_x, wearing ai badge', 'ai'))
+ .toBe(serverReadiness.captionHasTriggerWord('subj_x, wearing ai badge', 'ai'));
+ });
+});
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index 9a719fcdbf..4a558df55c 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -28,7 +28,14 @@ import TrainingPanel from '../components/loraTraining/TrainingPanel';
import CaptionModelPicker from '../components/loraTraining/CaptionModelPicker';
import ImportGalleryDialog from '../components/loraTraining/ImportGalleryDialog';
import UniverseCharacterPicker from '../components/loraTraining/UniverseCharacterPicker';
-import { escapeRegExp } from '../lib/textUtils.js';
+import {
+ MIN_TRAINING_IMAGES,
+ RECOMMENDED_TRAINING_IMAGES,
+ TRAINING_IMAGE_SWEET_SPOT_MAX,
+ isValidTriggerWord,
+ computeDatasetReadiness,
+ analyzeCaptionInvariants,
+} from '../lib/loraDatasetReadiness.js';
import {
getLoraDataset,
getLoraDatasetVariationAxes,
@@ -40,94 +47,8 @@ import {
getUniverse,
} from '../services/api';
-const TRIGGER_RE = /^[a-z0-9_]{2,64}$/;
const SUBJECT_TYPE_LABEL = { characters: 'Character', objects: 'Object', places: 'Place' };
const subjectKind = (dataset) => dataset?.character?.entryKind || 'characters';
-// Mirror of server/lib/loraDataset.js MIN_TRAINING_IMAGES + the token-boundary
-// caption match. Kept page-local (UX-advisory only — the server re-validates
-// authoritatively via validateDatasetReady at train time) so the readiness
-// summary + Train gate update the instant a caption is edited or an image
-// deleted, instead of waiting on a server round-trip. Port logic changes here
-// when the server helper changes.
-const MIN_TRAINING_IMAGES = 10;
-const RECOMMENDED_TRAINING_IMAGES = 20;
-const TRAINING_IMAGE_SWEET_SPOT_MAX = 30;
-const qualityTier = (captioned) => {
- if (captioned < MIN_TRAINING_IMAGES) return 'insufficient';
- if (captioned < RECOMMENDED_TRAINING_IMAGES) return 'minimum';
- return 'good';
-};
-const captionHasTriggerWord = (caption, triggerWord) => {
- const word = (triggerWord || '').trim();
- const text = (caption || '').trim();
- if (!text) return false;
- if (!word) return true;
- const escaped = escapeRegExp(word);
- return new RegExp(`(?:^|[^a-z0-9_])${escaped}(?:[^a-z0-9_]|$)`, 'i').test(text);
-};
-// Mirror of server/lib/loraDataset.js analyzeCaptionInvariants — flags the
-// identity fragments repeated across most captions (which bind the character to
-// the caption phrases instead of the trigger token, issue #1320). Page-local so
-// the advisory updates the instant a caption is edited, without a refetch; the
-// authoritative strip recomputes server-side. Port logic changes here when the
-// server helper changes.
-const INVARIANT_SHARE_THRESHOLD = 0.8;
-const MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS = 4;
-const captionBody = (caption, triggerWord) => {
- const word = (triggerWord || '').trim();
- let body = (caption || '').trim();
- if (word) {
- const escaped = escapeRegExp(word);
- body = body.replace(new RegExp(`^${escaped}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');
- }
- return body;
-};
-const splitCaptionFragments = (caption, triggerWord) => captionBody(caption, triggerWord)
- .split(',').map((f) => f.trim()).filter(Boolean);
-const normalizeFragment = (f) => (f || '').trim().toLowerCase().replace(/\s+/g, ' ');
-const analyzeCaptionInvariants = (images, triggerWord) => {
- const list = Array.isArray(images) ? images : [];
- const word = (triggerWord || '').trim();
- const captioned = list.filter((img) => img?.status === 'ready' && captionHasTriggerWord(img.caption, word));
- const total = captioned.length;
- if (total < MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS) return { analyzable: false, total, sharedFragments: [] };
- const counts = new Map();
- for (const img of captioned) {
- const seen = new Set();
- for (const frag of splitCaptionFragments(img.caption, word)) {
- const norm = normalizeFragment(frag);
- if (!norm || seen.has(norm)) continue;
- seen.add(norm);
- const cur = counts.get(norm) || { fragment: frag, count: 0 };
- cur.count += 1;
- counts.set(norm, cur);
- }
- }
- const sharedFragments = [...counts.entries()]
- .filter(([, v]) => v.count >= 2 && v.count / total >= INVARIANT_SHARE_THRESHOLD)
- .map(([normalized, v]) => ({ fragment: v.fragment, normalized, count: v.count, ratio: v.count / total }))
- .sort((a, b) => b.count - a.count || a.fragment.localeCompare(b.fragment));
- return { analyzable: true, total, sharedFragments };
-};
-const deriveReadiness = (images, triggerWord) => {
- const list = Array.isArray(images) ? images : [];
- const word = (triggerWord || '').trim();
- const ready = list.filter((img) => img.status === 'ready');
- const captioned = ready.filter((img) => captionHasTriggerWord(img.caption, word));
- const trainable = !!word && captioned.length >= MIN_TRAINING_IMAGES;
- return {
- total: list.length,
- ready: ready.length,
- captioned: captioned.length,
- rendering: list.filter((img) => img.status === 'rendering').length,
- required: MIN_TRAINING_IMAGES,
- recommended: RECOMMENDED_TRAINING_IMAGES,
- trainable,
- // Mirror of computeDatasetReadiness: gate the tier on trainability so a
- // record with enough images but no trigger word never shows green.
- quality: trainable ? qualityTier(captioned.length) : 'insufficient',
- };
-};
function SliceDialog({ dataset, onClose, onSliced }) {
const [cols, setCols] = useState(3);
@@ -346,7 +267,7 @@ export default function LoraDatasetDetail({ recordId }) {
// on `dataset.readiness`) so manual caption edits / deletes reflect in the
// counts + Train gate immediately, without a refetch per keystroke.
const readiness = useMemo(
- () => deriveReadiness(dataset?.images, dataset?.triggerWord),
+ () => computeDatasetReadiness(dataset),
[dataset?.images, dataset?.triggerWord],
);
@@ -420,7 +341,7 @@ export default function LoraDatasetDetail({ recordId }) {
const saveTriggerWord = async () => {
if (triggerDraft === null || triggerDraft === dataset.triggerWord) { setTriggerDraft(null); return; }
- if (!TRIGGER_RE.test(triggerDraft)) {
+ if (!isValidTriggerWord(triggerDraft)) {
toast.error('Trigger word must be 2-64 chars of a-z, 0-9, _');
return;
}