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

address review (codex): share the weave with the comic pipeline, widen the word boundary, judge the hint on the styled prompt

[._.]/ Adam Eivye7b7888b901a
diff --git a/client/src/lib/loraTriggers.js b/client/src/lib/loraTriggers.js
index ba31b0a05c..8d6a0d7d5f 100644
--- a/client/src/lib/loraTriggers.js
+++ b/client/src/lib/loraTriggers.js
@@ -19,7 +19,12 @@ export const firstTriggerWord = (words) => {
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-const WORD_CHAR = /[A-Za-z0-9_]/;
+// What counts as "inside a word" for the boundary assertions below. Unicode
+// letters/digits, not just ASCII, so a non-ASCII trigger or an accented prompt
+// gets the same treatment — `\b` and a bare `[A-Za-z0-9_]` class would both
+// read `aria` as present inside `ariaé` and silently skip the activation token.
+const WORD_CLASS = '\\p{L}\\p{N}_';
+const WORD_CHAR = new RegExp(`[${WORD_CLASS}]`, 'u');
// Whole-token, case-insensitive presence test, applied anywhere in the prompt
// (Civitai triggers are commonly woven mid-sentence). Boundaries are asserted
@@ -29,7 +34,7 @@ export const promptHasTriggerWord = (prompt, word) => {
const text = typeof prompt === 'string' ? prompt : '';
const token = typeof word === 'string' ? word.trim() : '';
if (!text || !token) return false;
- const lead = WORD_CHAR.test(token[0]) ? '(?<![A-Za-z0-9_])' : '';
- const tail = WORD_CHAR.test(token[token.length - 1]) ? '(?![A-Za-z0-9_])' : '';
- return new RegExp(`${lead}${escapeRegExp(token)}${tail}`, 'i').test(text);
+ const lead = WORD_CHAR.test(token[0]) ? `(?<![${WORD_CLASS}])` : '';
+ const tail = WORD_CHAR.test(token[token.length - 1]) ? `(?![${WORD_CLASS}])` : '';
+ return new RegExp(`${lead}${escapeRegExp(token)}${tail}`, 'iu').test(text);
};
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index a348080431..38aa9ee9e9 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -1311,7 +1311,10 @@ export default function ImageGen() {
currentRunnerFamily={currentRunnerFamily}
currentCompatKey={currentCompatKey}
onAppendTrigger={(words) => setPrompt((p) => appendTriggerWords(p, words))}
- prompt={prompt}
+ // The STYLED prompt, not the raw one — that's what submit sends and
+ // therefore what the server weaves against, so a trigger already
+ // present in the style preset must not raise a 'will be added' hint.
+ prompt={composeStyledPrompt(prompt, negativePrompt, stylePreset).prompt}
disabled={statusLoading}
/>
)}
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index e8601354cc..841e4a2fc3 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -38,6 +38,7 @@
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { isMiniMaxH3Runtime, isLtx2FamilyRuntime } from '../lib/runnerFamilies';
+import { composeStyledPrompt } from '../lib/composeStyledPrompt';
import Drawer from '../components/Drawer';
import { ImageGenTab } from '../components/settings/ImageGenTab';
import LocalSetupPanel from '../components/settings/LocalSetupPanel';
@@ -1193,7 +1194,10 @@ export default function VideoGen() {
const add = triggers.join(', ');
return p && p.trim() ? `${p}, ${add}` : add;
})}
- prompt={prompt}
+ // The STYLED prompt, not the raw one — buildGeneratePayload's
+ // envelope prefixes the style preset, so that is what the server
+ // weaves against and what the hint must be judged on.
+ prompt={composeStyledPrompt(prompt, negativePrompt, stylePreset).prompt}
disabled={generating}
/>
</div>
diff --git a/server/lib/README.md b/server/lib/README.md
index e95af0c426..a2a811a89d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -316,7 +316,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes: `TUNING_SPECS` (per runtime — llama.cpp's `-b`/`-ub`/`-t`/`--flash-attn`/`--cache-type-k|v`/`--draft-max`, Ollama's `num_ctx`, plus the record-only knobs for LM Studio / MTPLX / vLLM), each declaring `applies: 'launch' \| 'request' \| 'record'` so the UI can never claim PortOS set something it cannot. `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, `requestBody` (request knobs under their wire names), and `compareTunings` (which tuning won per model, with a `deltaPercent` against the winner). Pure. |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
-| `loraTriggers.js` | Pure trigger-word weaving for renders that load a LoRA (#4665): `weaveLoraTriggers(prompt, triggerWordLists)` → `{ prompt, added }` appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. `promptHasTriggerWord` is the whole-token, case-insensitive presence test (`aria_tok` does not match inside `aria_token`); `firstTriggerWord` picks the canonical token out of a Civitai `trainedWords` list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by `services/imageGen/local.js` and `services/videoGen/prepareParams.js`; the comic pipeline opts out because it weaves character triggers itself. |
+| `loraTriggers.js` | Pure trigger-word weaving for renders that load a LoRA (#4665): `weaveLoraTriggers(prompt, triggerWordLists)` → `{ prompt, added }` appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. `promptHasTriggerWord` is the whole-token, case-insensitive presence test (`aria_tok` does not match inside `aria_token`); `firstTriggerWord` picks the canonical token out of a Civitai `trainedWords` list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by `services/imageGen/local.js` and `services/videoGen/local.js` (paired with `services/loras.js#readTriggerWordsByFilename` for the sidecar reads). The comic pipeline shares it rather than opting out — its own "<Name> (<trigger>)" clause uses the same token, so the weave adds nothing there except for the characters that clause drops. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |
| `learningVerdict.js` | The three-way success-criteria verdict a completed agent run carries on `result.validationPassed` (#4107). `true`/`false` = a declared criterion was met/missed; `null` = none declared (record the run, fall back to the exit code); `SKIP_LEARNING_VERDICT` = nothing ever evaluated the run, so task-learning must not record it at all (a programmatic-I/O output hook that bailed on `no-app`/`app-not-found`). `isSkipLearningVerdict(v)` gates the skip; `toValidationVerdict(v)` narrows anything non-boolean — including the sentinel — back to `null` for downstream telemetry. JSON-safe string (not a Symbol) because the verdict is persisted and read back by the learning backfill, and older readers already narrow on `typeof v === 'boolean'`. Pure. |
diff --git a/server/lib/loraTriggers.js b/server/lib/loraTriggers.js
index 48d86b78ee..343762bb08 100644
--- a/server/lib/loraTriggers.js
+++ b/server/lib/loraTriggers.js
@@ -11,7 +11,7 @@
* This module is the pure half of the fix: given the user's prompt and the
* trigger words of the LoRAs selected for THIS render, decide which activation
* tokens are missing and append them. The render call sites (imageGen/local.js,
- * videoGen/prepareParams.js) own the sidecar reads and the provenance stamping.
+ * videoGen/local.js) own the sidecar reads and the provenance stamping.
*/
// Only the FIRST trigger word of each LoRA is woven. Civitai's `trainedWords`
@@ -27,7 +27,12 @@ export const firstTriggerWord = (words) => {
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-const WORD_CHAR = /[A-Za-z0-9_]/;
+// What counts as "inside a word" for the boundary assertions below. Unicode
+// letters/digits, not just ASCII, so a non-ASCII trigger or an accented prompt
+// gets the same treatment — `\b` and a bare `[A-Za-z0-9_]` class would both
+// read `aria` as present inside `ariaé` and silently skip the activation token.
+const WORD_CLASS = '\\p{L}\\p{N}_';
+const WORD_CHAR = new RegExp(`[${WORD_CLASS}]`, 'u');
/**
* Whole-token presence test. `\b`-style boundaries are applied only where the
@@ -45,9 +50,9 @@ export const promptHasTriggerWord = (prompt, word) => {
const text = typeof prompt === 'string' ? prompt : '';
const token = typeof word === 'string' ? word.trim() : '';
if (!text || !token) return false;
- const lead = WORD_CHAR.test(token[0]) ? '(?<![A-Za-z0-9_])' : '';
- const tail = WORD_CHAR.test(token[token.length - 1]) ? '(?![A-Za-z0-9_])' : '';
- return new RegExp(`${lead}${escapeRegExp(token)}${tail}`, 'i').test(text);
+ const lead = WORD_CHAR.test(token[0]) ? `(?<![${WORD_CLASS}])` : '';
+ const tail = WORD_CHAR.test(token[token.length - 1]) ? `(?![${WORD_CLASS}])` : '';
+ return new RegExp(`${lead}${escapeRegExp(token)}${tail}`, 'iu').test(text);
};
/**
diff --git a/server/lib/loraTriggers.parity.test.js b/server/lib/loraTriggers.parity.test.js
index a2ed8ab443..dc1b088cf7 100644
--- a/server/lib/loraTriggers.parity.test.js
+++ b/server/lib/loraTriggers.parity.test.js
@@ -32,6 +32,9 @@ const PRESENCE_CASES = [
['an audio reactive visualizer', 'audio reactive'],
['style: c.a.t art', 'c.a.t'],
['style: cXaYt art', 'c.a.t'],
+ ['a portrait of ariaé', 'aria'],
+ ['a portrait of éclairs', 'éclair'],
+ ['a portrait of éclair', 'éclair'],
['aria_tok, rooftop', 'aria_tok'],
['rooftop', 'aria_tok'],
['', 'aria_tok'],
@@ -74,6 +77,7 @@ describe('LoRA trigger words — server↔client parity', () => {
for (const has of [serverPromptHasTriggerWord, clientPromptHasTriggerWord]) {
expect(has('a portrait of aria_token', 'aria_tok')).toBe(false);
expect(has('a portrait of aria_tok', 'aria_tok')).toBe(true);
+ expect(has('a portrait of ariaé', 'aria')).toBe(false);
}
for (const first of [serverFirstTriggerWord, clientFirstTriggerWord]) {
expect(first(['rstgrm', 'film grain'])).toBe('rstgrm');
diff --git a/server/lib/loraTriggers.test.js b/server/lib/loraTriggers.test.js
index 8ca6f21f02..aa45e0ed6d 100644
--- a/server/lib/loraTriggers.test.js
+++ b/server/lib/loraTriggers.test.js
@@ -34,6 +34,15 @@ describe('promptHasTriggerWord', () => {
expect(promptHasTriggerWord('an audio reactive visualizer', 'audio reactive')).toBe(true);
});
+ it('applies the word boundary to non-ASCII letters too', () => {
+ // An ASCII-only word class would read 'aria' as present inside 'ariaé'
+ // (the trailing char is not in [A-Za-z0-9_]), silently skipping the
+ // activation token — the failure mode is a LoRA that stays inert.
+ expect(promptHasTriggerWord('a portrait of ariaé', 'aria')).toBe(false);
+ expect(promptHasTriggerWord('a portrait of éclairs', 'éclair')).toBe(false);
+ expect(promptHasTriggerWord('a portrait of éclair', 'éclair')).toBe(true);
+ });
+
it('treats regex metacharacters in the trigger literally', () => {
expect(promptHasTriggerWord('style: c.a.t art', 'c.a.t')).toBe(true);
expect(promptHasTriggerWord('style: cXaYt art', 'c.a.t')).toBe(false);
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 8ef436eba8..e0ddacfbfb 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -328,11 +328,6 @@ export function buildSidecarMeta({
// passes the map so this stays pure. Keyed rather than positional because the
// valid-LoRA order is only known after the prefix-check below.
loraTriggerWords = null,
- // Opt-out for callers that already wove the activation tokens into `prompt`
- // themselves — the comic/visual pipeline builds a trigger clause from
- // `applyCharacterLorasToRender` before enqueueing, and appending again would
- // double-weight the token.
- weaveTriggerWords = true,
initImagePath = null,
initImageStrength = null,
referenceImagePaths = [],
@@ -446,9 +441,10 @@ export function buildSidecarMeta({
// render-time text and what was added are recorded alongside it, and only when
// something was actually appended — an un-woven render's sidecar stays
// byte-identical to every sidecar written before this feature.
- const { prompt: wovenPrompt, added: addedTriggerWords } = weaveTriggerWords
- ? weaveLoraTriggers(prompt, validLoraFilenames.map((f) => loraTriggerWords?.[f]))
- : { prompt, added: [] };
+ const { prompt: wovenPrompt, added: addedTriggerWords } = weaveLoraTriggers(
+ prompt,
+ validLoraFilenames.map((f) => loraTriggerWords?.[f]),
+ );
const renderPrompt = addedTriggerWords.length ? wovenPrompt : prompt;
if (addedTriggerWords.length) {
meta.renderPrompt = renderPrompt;
@@ -491,7 +487,7 @@ export function resolveOutputPlacement(outputTarget) {
return { outputDir, skipSidecar, isGallery };
}
-export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', weaveTriggerWords = true, modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
+export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
// Empty prompt is allowed: img2img / edit / unconditional renders are driven
// by the init image (or run unconditionally), so text isn't required. The
// mflux/diffusers runners accept an empty `--prompt` — the regen pass (#912)
@@ -539,12 +535,9 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// Trigger words for the selected LoRAs (#4665). Read against the RAW request
// (a superset of what survives the prefix-check inside buildSidecarMeta) so
// the map is available before validation runs; an absent or legacy sidecar
- // simply contributes nothing and the render is unchanged. Skipped entirely
- // when the caller opted out or selected no LoRAs, so the default no-LoRA
- // render does zero extra I/O.
- const loraTriggerWords = weaveTriggerWords
- ? await readTriggerWordsByFilename([...loraFilenames, ...loraPaths])
- : null;
+ // simply contributes nothing and the render is unchanged. A no-LoRA render
+ // short-circuits inside the helper, so the common case does zero extra I/O.
+ const loraTriggerWords = await readTriggerWordsByFilename([...loraFilenames, ...loraPaths]);
const {
meta,
renderPrompt,
@@ -578,7 +571,6 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
referenceImageStrengths,
regenOf,
loraTriggerWords,
- weaveTriggerWords,
resolveInputPath: resolveImageInputPath,
loraExists: existsSync,
});
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 551cb5a63b..5eb0debcf8 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -847,14 +847,20 @@ describe('imageGen local.buildSidecarMeta', () => {
expect(addedTriggerWords).toEqual([]);
});
- it('honors weaveTriggerWords:false so the comic pipeline does not double-weight its own clause', () => {
+ it('adds nothing to a pipeline prompt that already carries the trigger in its own clause', () => {
+ // The comic/visual pipeline weaves its own "<Name> (<trigger>): <desc>" /
+ // "Featuring <Name> (<trigger>)" clause before enqueueing, using the SAME
+ // first-trigger-word token. Idempotence is what lets those renders share
+ // this weave instead of opting out — and opting out is what would have
+ // left a description-less character's LoRA inert, since comicPages drops
+ // any character with no description from its clause.
const { meta, renderPrompt, addedTriggerWords } = buildSidecarMeta({
...baseMetaInput,
+ prompt: 'Aria (aria_tok): a tall figure in a red coat. A rooftop at dusk.',
loraFilenames: ['aria.safetensors'],
loraTriggerWords: { 'aria.safetensors': ['aria_tok'] },
- weaveTriggerWords: false,
});
- expect(renderPrompt).toBe('a red cube');
+ expect(renderPrompt).toBe('Aria (aria_tok): a tall figure in a red coat. A rooftop at dusk.');
expect(addedTriggerWords).toEqual([]);
expect(meta.renderPrompt).toBeUndefined();
});
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index 16cee4cb9e..318bd99daa 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -127,18 +127,18 @@ async function applyCharacterLorasToRender({ matchedCharacters, mode, options, s
return { loras, triggerByKey };
}
-// `weaveTriggerWords: false` opts these renders out of the server-side trigger
-// weave in imageGen/local.js (#4665). Both pipeline callers already build their
-// own trigger clause from `applyCharacterLorasToRender` — comicPages composes
-// per-character triggers into the page prompt, and the visual stage appends a
-// "Featuring <name> (<trigger>)" sentence — so a second append would double the
-// token's weight.
+// These renders do NOT opt out of the server-side trigger weave (#4665). Both
+// pipeline callers build their own trigger clause from
+// `applyCharacterLorasToRender` — comicPages parenthesizes each character's
+// trigger after its name, the visual stage appends a "Featuring <name>
+// (<trigger>)" sentence — and the weave is idempotent against exactly those
+// tokens (`characterLoraResolver` picks `triggerWords[0]`, the same word the
+// weave would append), so it adds nothing where the clause already landed. That
+// leaves it as a safety net for the characters the clause drops: comicPages
+// filters out any character with no description, so a dialogue-only character's
+// LoRA used to load with its activation token nowhere in the prompt.
const loraRenderOptions = (loras) => (loras.length
- ? {
- loraFilenames: loras.map((l) => l.filename),
- loraScales: loras.map((l) => l.scale),
- weaveTriggerWords: false,
- }
+ ? { loraFilenames: loras.map((l) => l.filename), loraScales: loras.map((l) => l.scale) }
: {});
// Defensive fallback — an unrecognized value must never land in the final
@@ -267,14 +267,7 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
// Character LoRAs resolved by applyCharacterLorasToRender — only the
// local runner honors these (codex has no LoRA support; the resolver is
// skipped there so the spread stays empty).
- ...(options.loraFilenames?.length
- ? {
- loraFilenames: options.loraFilenames,
- loraScales: options.loraScales,
- // Carries loraRenderOptions' opt-out through to generateImage (#4665).
- ...(options.weaveTriggerWords === false ? { weaveTriggerWords: false } : {}),
- }
- : {}),
+ ...(options.loraFilenames?.length ? { loraFilenames: options.loraFilenames, loraScales: options.loraScales } : {}),
};
// The queue dispatches directly to imageGen/{codex,local}.generateImage,
// bypassing imageGen/index.js's dispatcher that resolves cleaners for