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

weave installed LoRA trigger words into render prompts so a selected LoRA actually activates (#4665)

[._.]/ Adam Eivy10160cf6c08e
diff --git a/client/src/components/imageGen/LoraPicker.jsx b/client/src/components/imageGen/LoraPicker.jsx
index 248a84e1db..913c87ae60 100644
--- a/client/src/components/imageGen/LoraPicker.jsx
+++ b/client/src/components/imageGen/LoraPicker.jsx
@@ -10,8 +10,14 @@
// gets a `+ trigger` button — typically wired to append the trigger tokens to
// the caller's prompt. Omit it (or pass `null`) where there's no prompt to
// append into (batch render with per-variation prompts).
+//
+// Pass `prompt` (the caller's current prompt text) to surface the #4665 hint on
+// any selected LoRA whose activation token is missing from it. Purely
+// informational — the server weaves the token in at render time either way; the
+// hint just stops that from being a surprise.
import { Link } from 'react-router';
+import { firstTriggerWord, promptHasTriggerWord } from '../../lib/loraTriggers.js';
// Matches /api/image-gen/generate and /api/universe-builder/:id/render's
// .max(8) on the LoRA list. Hard cap stops the user from queuing a render
@@ -33,6 +39,7 @@ export default function LoraPicker({
// load. Falls back to `currentRunnerFamily` for older callers.
currentCompatKey = null,
onAppendTrigger = null,
+ prompt = null,
disabled = false,
}) {
if (!availableLoras.length) return null;
@@ -86,53 +93,69 @@ export default function LoraPicker({
const sel = selected.find((s) => s.filename === lora.filename);
const recommended = typeof lora.recommendedScale === 'number' ? lora.recommendedScale : 1.0;
const triggers = lora.triggerWords || [];
+ // The exact token the server will weave in at render time (#4665) —
+ // only flagged while this LoRA is selected and the word isn't
+ // already in the prompt, so the hint disappears the moment the user
+ // types it (or hits "+ trigger").
+ const activation = firstTriggerWord(triggers);
+ // `prompt === null` means the host didn't opt in (it has no single prompt to
+ // weave into, or its renders opt out of the server weave) — stay silent
+ // rather than claiming an append that may never happen.
+ const willAddTrigger = Boolean(typeof prompt === 'string' && sel && activation && !promptHasTriggerWord(prompt, activation));
return (
- <div key={lora.filename} className="flex items-center gap-2">
- <label className={`flex items-center gap-2 flex-1 min-w-0 ${atCap && !sel ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}>
- <input
- type="checkbox"
- checked={!!sel}
- disabled={disabled || (atCap && !sel)}
- onChange={(e) => toggle(lora, e.target.checked)}
- className="rounded"
- title={atCap && !sel ? `Maximum ${MAX_SELECTED_LORAS} LoRAs per render — uncheck one to swap` : undefined}
- />
- <span className="text-xs text-gray-300 truncate flex-1" title={triggers.length ? `Trigger words: ${triggers.join(', ')}` : lora.name}>
- {lora.name}
- {/* baseModel suffix disambiguates multiple installed
- versions of the same model (e.g. ZImageBase vs
- ZImageTurbo, both mapping to 'z-image' family). */}
- {lora.civitai?.baseModel && (
- <span className="ml-1.5 text-[10px] text-gray-600 font-mono">[{lora.civitai.baseModel}]</span>
- )}
- {triggers.length > 0 && (
- <span className="ml-2 text-[10px] text-gray-500 font-mono">{triggers.slice(0, 2).join(', ')}{triggers.length > 2 ? '…' : ''}</span>
- )}
- </span>
- </label>
- {sel && (
- <div className="flex items-center gap-2">
- {triggers.length > 0 && onAppendTrigger && (
- <button
- type="button"
- onClick={() => onAppendTrigger(triggers)}
- disabled={disabled}
- title={`Append to prompt: ${triggers.join(', ')}`}
- className="text-[11px] px-2 py-1 rounded bg-port-accent/10 text-port-accent border border-port-accent/30 hover:bg-port-accent/20 disabled:opacity-50 whitespace-nowrap"
- >
- + trigger
- </button>
- )}
- <span className="text-xs text-gray-500" title={`Recommended: ${recommended.toFixed(2)}`}>Scale</span>
+ <div key={lora.filename}>
+ <div className="flex items-center gap-2">
+ <label className={`flex items-center gap-2 flex-1 min-w-0 ${atCap && !sel ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}>
<input
- type="number" min={0} max={2} step={0.1}
- aria-label={`Scale for ${lora.filename}`}
- value={sel.scale}
- disabled={disabled}
- onChange={(e) => setScale(lora.filename, parseFloat(e.target.value) || 0)}
- className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"
+ type="checkbox"
+ checked={!!sel}
+ disabled={disabled || (atCap && !sel)}
+ onChange={(e) => toggle(lora, e.target.checked)}
+ className="rounded"
+ title={atCap && !sel ? `Maximum ${MAX_SELECTED_LORAS} LoRAs per render — uncheck one to swap` : undefined}
/>
- </div>
+ <span className="text-xs text-gray-300 truncate flex-1" title={triggers.length ? `Trigger words: ${triggers.join(', ')}` : lora.name}>
+ {lora.name}
+ {/* baseModel suffix disambiguates multiple installed
+ versions of the same model (e.g. ZImageBase vs
+ ZImageTurbo, both mapping to 'z-image' family). */}
+ {lora.civitai?.baseModel && (
+ <span className="ml-1.5 text-[10px] text-gray-600 font-mono">[{lora.civitai.baseModel}]</span>
+ )}
+ {triggers.length > 0 && (
+ <span className="ml-2 text-[10px] text-gray-500 font-mono">{triggers.slice(0, 2).join(', ')}{triggers.length > 2 ? '…' : ''}</span>
+ )}
+ </span>
+ </label>
+ {sel && (
+ <div className="flex items-center gap-2">
+ {triggers.length > 0 && onAppendTrigger && (
+ <button
+ type="button"
+ onClick={() => onAppendTrigger(triggers)}
+ disabled={disabled}
+ title={`Append to prompt: ${triggers.join(', ')}`}
+ className="text-[11px] px-2 py-1 rounded bg-port-accent/10 text-port-accent border border-port-accent/30 hover:bg-port-accent/20 disabled:opacity-50 whitespace-nowrap"
+ >
+ + trigger
+ </button>
+ )}
+ <span className="text-xs text-gray-500" title={`Recommended: ${recommended.toFixed(2)}`}>Scale</span>
+ <input
+ type="number" min={0} max={2} step={0.1}
+ aria-label={`Scale for ${lora.filename}`}
+ value={sel.scale}
+ disabled={disabled}
+ onChange={(e) => setScale(lora.filename, parseFloat(e.target.value) || 0)}
+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"
+ />
+ </div>
+ )}
+ </div>
+ {willAddTrigger && (
+ <p className="text-[10px] text-amber-400/90 pl-6 mt-0.5">
+ Trigger word <span className="font-mono">{activation}</span> is missing — it will be added to your prompt at render time.
+ </p>
)}
</div>
);
diff --git a/client/src/components/imageGen/LoraPicker.test.jsx b/client/src/components/imageGen/LoraPicker.test.jsx
index 5e749c9e0d..13f34c7fac 100644
--- a/client/src/components/imageGen/LoraPicker.test.jsx
+++ b/client/src/components/imageGen/LoraPicker.test.jsx
@@ -45,3 +45,45 @@ describe('LoraPicker compat filtering', () => {
expect(screen.getByText('Legacy LoRA')).toBeTruthy();
});
});
+
+describe('LoraPicker trigger-word hint (#4665)', () => {
+ const TRIGGERED = [{
+ filename: 't.safetensors',
+ name: 'Aria LoRA',
+ loraCompatKey: 'flux2-4b',
+ runnerFamily: 'flux2',
+ triggerWords: ['aria_tok', 'portrait'],
+ }];
+ const base = { availableLoras: TRIGGERED, currentCompatKey: 'flux2-4b', currentRunnerFamily: 'flux2' };
+ const SELECTED = [{ filename: 't.safetensors', name: 'Aria LoRA', scale: 1.0 }];
+ const hint = () => screen.queryByText(/will be added to your prompt/i);
+
+ it('warns that the server will append the missing activation token', () => {
+ renderPicker({ ...base, selected: SELECTED, prompt: 'a rooftop at dusk' });
+ expect(hint()).toBeTruthy();
+ // Names the FIRST trigger word — the only one the server weaves in.
+ expect(screen.getByText('aria_tok')).toBeTruthy();
+ });
+
+ it('stays silent once the prompt already carries the token', () => {
+ renderPicker({ ...base, selected: SELECTED, prompt: 'aria_tok on a rooftop' });
+ expect(hint()).toBeNull();
+ });
+
+ it('is not fooled by the token appearing inside a longer word', () => {
+ renderPicker({ ...base, selected: SELECTED, prompt: 'a portrait of aria_token' });
+ expect(hint()).toBeTruthy();
+ });
+
+ it('stays silent for an unselected LoRA', () => {
+ renderPicker({ ...base, selected: [], prompt: 'a rooftop at dusk' });
+ expect(hint()).toBeNull();
+ });
+
+ it('stays silent when the host did not opt in by passing a prompt', () => {
+ // e.g. the pipeline drawers, whose renders weave their own trigger clause
+ // and opt out server-side — a hint there would be a lie.
+ renderPicker({ ...base, selected: SELECTED });
+ expect(hint()).toBeNull();
+ });
+});
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 3e72ed18eb..3c903d687d 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -813,6 +813,7 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {
onChange={setSelectedLoras}
currentRunnerFamily={loraFamily}
currentCompatKey={loraFamily}
+ prompt={prompt}
/>
)}
{!isGrok && (
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 84fc6c11bc..c2e6a4b3f1 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -50,6 +50,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/cosValidation.js`. |
| `reviewerPins.js` | Client mirrors of 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 the server's own ladders, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. |
+| `loraTriggers.js` | Mirror of the trigger-word predicates in `server/lib/loraTriggers.js` (#4665): `firstTriggerWord` (the canonical activation token of a Civitai `trainedWords` list) and `promptHasTriggerWord` (whole-token, case-insensitive presence — `aria_tok` does not match inside `aria_token`). Lets the LoRA picker warn that the server is about to append a token, and keeps ImageGen's "+ trigger" dedupe using the same rule the server weave uses. |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |
| `slashdoCatalog.js` | Mirror of `server/lib/slashdoCatalog.js` — the launchable slashdo workflows (`SLASHDO_WORKFLOWS`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`) driving the app-overview Agent Operations buttons. Adds only the per-button Tailwind classes; pinned by `server/lib/slashdoCatalog.test.js`. |
| `issueLength.js` | Mirror of `server/lib/issueLength.js`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 375dd56b0b..4e3024209f 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -47,6 +47,7 @@ export * from './pipelineImageDefaults.js';
export * from './reverseOutlineGrid.js';
export * from './reviewerModels.js';
export * from './reviewerPins.js';
+export * from './loraTriggers.js';
export * from './runnerFamilies.js';
export * from './slashdoCatalog.js';
export * from './videoFinish.js';
diff --git a/client/src/lib/loraTriggers.js b/client/src/lib/loraTriggers.js
new file mode 100644
index 0000000000..ba31b0a05c
--- /dev/null
+++ b/client/src/lib/loraTriggers.js
@@ -0,0 +1,35 @@
+/**
+ * Client mirror of the trigger-word predicates in `server/lib/loraTriggers.js`
+ * (issue #4665).
+ *
+ * The server is the enforcement point — it weaves each selected LoRA's first
+ * activation token into the prompt at render time. These two helpers exist so
+ * the UI can say the same thing the server will do: which token is missing, and
+ * whether a word is already doing its job in the prompt. Keep the matching rules
+ * identical to the server module or the picker's hint will contradict the render.
+ */
+
+// Only the FIRST trigger word of a LoRA activates it, per the server weave —
+// Civitai `trainedWords` routinely lists a dozen loosely-related tags.
+export const firstTriggerWord = (words) => {
+ if (!Array.isArray(words)) return null;
+ const first = words.find((w) => typeof w === 'string' && w.trim());
+ return first ? first.trim() : null;
+};
+
+const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+const WORD_CHAR = /[A-Za-z0-9_]/;
+
+// Whole-token, case-insensitive presence test, applied anywhere in the prompt
+// (Civitai triggers are commonly woven mid-sentence). Boundaries are asserted
+// only where the trigger's own edge is a word character, so `aria_tok` does not
+// match inside `aria_token` while a punctuation-edged trigger still matches.
+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);
+};
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 4bbb4b5939..a348080431 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -21,6 +21,7 @@ import PromptFromMedia from '../components/media/PromptFromMedia';
import BackendChipStrip from '../components/media/BackendChipStrip';
import { normalizeImage } from '../components/media/normalize';
import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';
+import { promptHasTriggerWord } from '../lib/loraTriggers';
import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';
import HfTokenBanner from '../components/imageGen/HfTokenBanner';
import ImageGenControls from '../components/imageGen/ImageGenControls';
@@ -71,21 +72,24 @@ const revokeIfBlob = (url) => {
if (url?.startsWith('blob:')) URL.revokeObjectURL(url);
};
-// Append LoRA trigger words to a prompt comma-separated, skipping any
-// 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.
+// Append LoRA trigger words to a prompt comma-separated, skipping any already
+// present. Presence uses the SHARED `promptHasTriggerWord` predicate (#4665) so
+// the button, the picker's "will be added" hint, and the server-side weave all
+// agree on what counts as present: a whole-token, case-insensitive match
+// anywhere in the prompt. That matters because a trigger is commonly woven
+// mid-sentence ("a portrait of aria_tok on a rooftop"), which the old
+// comma-segment comparison read as absent and re-appended — while still not
+// false-matching a short trigger like "cat" inside "concatenate".
+//
+// Unlike the server weave, this appends ALL of the LoRA's trigger words: the
+// user clicked "+ trigger" with the full list in the tooltip, so honoring it is
+// the point. The server only ever adds the first, and never duplicates.
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 segments = String(prompt || '')
- .split(',')
- .map((s) => s.trim().toLowerCase())
- .filter(Boolean);
- const fresh = list.filter((w) => !segments.includes(w.toLowerCase()));
+ const fresh = list.filter((w) => !promptHasTriggerWord(prompt, w));
if (!fresh.length) return prompt;
const trimmed = String(prompt || '').trim();
const sep = !trimmed ? '' : trimmed.endsWith(',') ? ' ' : ', ';
@@ -1307,6 +1311,7 @@ export default function ImageGen() {
currentRunnerFamily={currentRunnerFamily}
currentCompatKey={currentCompatKey}
onAppendTrigger={(words) => setPrompt((p) => appendTriggerWords(p, words))}
+ prompt={prompt}
disabled={statusLoading}
/>
)}
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 16eec0451d..e8601354cc 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -1193,6 +1193,7 @@ export default function VideoGen() {
const add = triggers.join(', ');
return p && p.trim() ? `${p}, ${add}` : add;
})}
+ prompt={prompt}
disabled={generating}
/>
</div>
diff --git a/server/lib/README.md b/server/lib/README.md
index c6918d62c4..e95af0c426 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -316,6 +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. |
| `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/index.js b/server/lib/index.js
index c28d34db7b..a3725b2e1a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -295,6 +295,7 @@ export * from './localModelAssessment.js';
export * from './localModelTuning.js';
export * from './ollamaContext.js';
export * from './loraDataset.js';
+export * from './loraTriggers.js';
export * from './issueLength.js';
export * from './musicDuration.js';
export * from './investigationTasks.js';
diff --git a/server/lib/loraTriggers.js b/server/lib/loraTriggers.js
new file mode 100644
index 0000000000..48d86b78ee
--- /dev/null
+++ b/server/lib/loraTriggers.js
@@ -0,0 +1,90 @@
+/**
+ * LoRA trigger-word weaving (issue #4665).
+ *
+ * PortOS records each installed LoRA's activation vocabulary at install time
+ * (`civitai.js#buildSidecar` → `triggerWords`, `huggingfaceLora.js` → the HF
+ * instance prompt, `loraTraining/sidecar.js` → the dataset's trained token),
+ * but the manual render paths only ever *displayed* it. A user who ticks a
+ * LoRA in the picker and hits Generate got a render that loaded the adapter
+ * without ever activating it — the LoRA looked broken.
+ *
+ * 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.
+ */
+
+// Only the FIRST trigger word of each LoRA is woven. Civitai's `trainedWords`
+// routinely lists a dozen loosely-related tags (style hints, sample-prompt
+// fragments); appending all of them would rewrite the render rather than
+// activate the adapter. First-word-only matches what `characterLoraResolver.js`
+// already treats as the canonical activation token for character LoRAs.
+export const firstTriggerWord = (words) => {
+ if (!Array.isArray(words)) return null;
+ const first = words.find((w) => typeof w === 'string' && w.trim());
+ return first ? first.trim() : null;
+};
+
+const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+const WORD_CHAR = /[A-Za-z0-9_]/;
+
+/**
+ * Whole-token presence test. `\b`-style boundaries are applied only where the
+ * trigger word's own edge is a word character, so a token like `aria_tok` does
+ * NOT match inside `aria_token` (underscore counts as a word char, which is
+ * exactly what LoRA trigger tokens rely on), while a punctuation-edged trigger
+ * (`3d-render.`) still matches literally instead of never matching at all.
+ *
+ * Substring matching is deliberately allowed *within* the prompt rather than
+ * restricted to comma-separated segments: Civitai triggers are frequently woven
+ * mid-sentence ("a portrait of aria_tok on a rooftop"), and re-appending a word
+ * that is already doing its job would double-weight it.
+ */
+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);
+};
+
+/**
+ * Weave the missing activation tokens of the selected LoRAs into `prompt`.
+ *
+ * @param {string} prompt - the user's own text; never reordered or rewritten.
+ * @param {Array<string[]|string|null>} triggerWordLists - one entry per selected
+ * LoRA, in selection order. Each entry is that LoRA's `triggerWords` array (a
+ * bare string is accepted for convenience); only its first usable word is
+ * considered. Entries with no trigger words contribute nothing.
+ * @returns {{ prompt: string, added: string[] }} - the prompt to actually render
+ * with, plus the tokens that were appended (empty when nothing was missing).
+ *
+ * Missing words are appended as a trailing comma-joined clause in selection
+ * order, so the user's own phrasing keeps its position — and, for weighted
+ * samplers, its emphasis. An already-present word is never duplicated, which
+ * makes the weave idempotent: re-rendering a prompt that already carries its
+ * triggers is a no-op.
+ */
+export const weaveLoraTriggers = (prompt, triggerWordLists) => {
+ const original = typeof prompt === 'string' ? prompt : '';
+ const lists = Array.isArray(triggerWordLists) ? triggerWordLists : [];
+ const added = [];
+ const seen = new Set();
+ for (const list of lists) {
+ const word = firstTriggerWord(typeof list === 'string' ? [list] : list);
+ if (!word) continue;
+ const key = word.toLowerCase();
+ // Dedupe across LoRAs too — two adapters trained on the same token (a
+ // character LoRA and its style companion, say) must not stack it twice.
+ if (seen.has(key)) continue;
+ seen.add(key);
+ if (promptHasTriggerWord(original, word)) continue;
+ added.push(word);
+ }
+ if (!added.length) return { prompt: original, added: [] };
+ const trimmed = original.trim();
+ const sep = !trimmed ? '' : trimmed.endsWith(',') ? ' ' : ', ';
+ return { prompt: `${trimmed}${sep}${added.join(', ')}`, added };
+};
diff --git a/server/lib/loraTriggers.parity.test.js b/server/lib/loraTriggers.parity.test.js
new file mode 100644
index 0000000000..a2ed8ab443
--- /dev/null
+++ b/server/lib/loraTriggers.parity.test.js
@@ -0,0 +1,82 @@
+/**
+ * Cross-package parity for the LoRA trigger-word predicates (#4665).
+ *
+ * `server/lib/loraTriggers.js` is the source of truth — it decides what the
+ * runner actually renders. `client/src/lib/loraTriggers.js` mirrors the two
+ * predicates the UI needs so the LoRA picker's "this token will be added" hint
+ * and ImageGen's "+ trigger" dedupe agree with what the server will do. If the
+ * two disagree, the picker tells the user one thing and the render does
+ * another — this suite fails CI instead of letting that ship.
+ *
+ * It lives server-side because the server module is the authority; both copies
+ * are pure and load fine under the node runner.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ firstTriggerWord as serverFirstTriggerWord,
+ promptHasTriggerWord as serverPromptHasTriggerWord,
+} from './loraTriggers.js';
+import {
+ firstTriggerWord as clientFirstTriggerWord,
+ promptHasTriggerWord as clientPromptHasTriggerWord,
+} from '../../client/src/lib/loraTriggers.js';
+
+// Every shape the two implementations must agree on: the whole-token boundary
+// (`aria_tok` vs `aria_token`), multi-word Civitai phrases, regex
+// metacharacters, case-insensitivity, and the empty/absent inputs.
+const PRESENCE_CASES = [
+ ['a portrait of Aria_Tok on a rooftop', 'aria_tok'],
+ ['a portrait of aria_token', 'aria_tok'],
+ ['concatenate the frames', 'cat'],
+ ['an audio reactive visualizer', 'audio reactive'],
+ ['style: c.a.t art', 'c.a.t'],
+ ['style: cXaYt art', 'c.a.t'],
+ ['aria_tok, rooftop', 'aria_tok'],
+ ['rooftop', 'aria_tok'],
+ ['', 'aria_tok'],
+ ['a prompt', ''],
+ [null, 'aria_tok'],
+ ['a prompt', null],
+];
+
+const FIRST_WORD_CASES = [
+ [' aria_tok ', 'portrait'],
+ ['', ' ', 'rstgrm'],
+ [],
+ null,
+ 'aria_tok',
+ [null, 42],
+];
+
+describe('LoRA trigger words — server↔client parity', () => {
+ it('agrees on whether a word is already present in a prompt', () => {
+ for (const [prompt, word] of PRESENCE_CASES) {
+ expect(
+ clientPromptHasTriggerWord(prompt, word),
+ `promptHasTriggerWord drifted for prompt=${JSON.stringify(prompt)} word=${JSON.stringify(word)}`,
+ ).toBe(serverPromptHasTriggerWord(prompt, word));
+ }
+ });
+
+ it('agrees on which word activates a LoRA', () => {
+ for (const words of FIRST_WORD_CASES) {
+ expect(
+ clientFirstTriggerWord(words),
+ `firstTriggerWord drifted for ${JSON.stringify(words)}`,
+ ).toEqual(serverFirstTriggerWord(words));
+ }
+ });
+
+ it('pins the boundary rule both copies encode (not just that they match)', () => {
+ // A mutual regression — both copies losing the boundary together — would
+ // slip past the equality assertions above, so pin the behavior itself.
+ 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);
+ }
+ 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
new file mode 100644
index 0000000000..8ca6f21f02
--- /dev/null
+++ b/server/lib/loraTriggers.test.js
@@ -0,0 +1,130 @@
+import { describe, it, expect } from 'vitest';
+import { weaveLoraTriggers, promptHasTriggerWord, firstTriggerWord } from './loraTriggers.js';
+
+describe('firstTriggerWord', () => {
+ it('picks the first usable token and trims it', () => {
+ expect(firstTriggerWord([' aria_tok ', 'portrait'])).toBe('aria_tok');
+ });
+
+ it('skips blank leading entries rather than returning an empty token', () => {
+ expect(firstTriggerWord(['', ' ', 'rstgrm'])).toBe('rstgrm');
+ });
+
+ it('returns null for a missing / empty / non-array list', () => {
+ expect(firstTriggerWord([])).toBeNull();
+ expect(firstTriggerWord(null)).toBeNull();
+ expect(firstTriggerWord('aria_tok')).toBeNull();
+ expect(firstTriggerWord([null, 42])).toBeNull();
+ });
+});
+
+describe('promptHasTriggerWord', () => {
+ it('matches whole tokens case-insensitively, anywhere in the prompt', () => {
+ expect(promptHasTriggerWord('a portrait of Aria_Tok on a rooftop', 'aria_tok')).toBe(true);
+ });
+
+ it('does NOT match inside a longer token', () => {
+ // The exact regression the issue names: underscore is a word character,
+ // so `aria_tok` must not be considered present in `aria_token`.
+ expect(promptHasTriggerWord('a portrait of aria_token', 'aria_tok')).toBe(false);
+ expect(promptHasTriggerWord('concatenate the frames', 'cat')).toBe(false);
+ });
+
+ it('matches a multi-word Civitai trigger phrase', () => {
+ expect(promptHasTriggerWord('an audio reactive visualizer', 'audio reactive')).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);
+ });
+
+ it('is false for empty inputs', () => {
+ expect(promptHasTriggerWord('', 'aria_tok')).toBe(false);
+ expect(promptHasTriggerWord('a prompt', '')).toBe(false);
+ expect(promptHasTriggerWord(null, 'aria_tok')).toBe(false);
+ });
+});
+
+describe('weaveLoraTriggers', () => {
+ it('appends a missing trigger word as a trailing clause', () => {
+ const { prompt, added } = weaveLoraTriggers('a rooftop at dusk', [['aria_tok']]);
+ expect(prompt).toBe('a rooftop at dusk, aria_tok');
+ expect(added).toEqual(['aria_tok']);
+ });
+
+ it('uses only the FIRST trigger word of each LoRA', () => {
+ // Civitai `trainedWords` routinely carries a dozen loosely-related tags;
+ // appending all of them would rewrite the render.
+ const { prompt, added } = weaveLoraTriggers('a rooftop', [
+ ['rstgrm', 'film grain', 'analog', 'vintage'],
+ ]);
+ expect(prompt).toBe('a rooftop, rstgrm');
+ expect(added).toEqual(['rstgrm']);
+ });
+
+ it('preserves the user prompt position and weight (append, never prepend)', () => {
+ const { prompt } = weaveLoraTriggers('(masterpiece:1.4), a rooftop', [['aria_tok']]);
+ expect(prompt.startsWith('(masterpiece:1.4), a rooftop')).toBe(true);
+ });
+
+ it('never duplicates a word already present in the prompt', () => {
+ const { prompt, added } = weaveLoraTriggers('aria_tok on a rooftop', [['aria_tok']]);
+ expect(prompt).toBe('aria_tok on a rooftop');
+ expect(added).toEqual([]);
+ });
+
+ it('is idempotent — weaving the result again adds nothing', () => {
+ const once = weaveLoraTriggers('a rooftop', [['aria_tok'], ['rstgrm']]);
+ const twice = weaveLoraTriggers(once.prompt, [['aria_tok'], ['rstgrm']]);
+ expect(twice.prompt).toBe(once.prompt);
+ expect(twice.added).toEqual([]);
+ });
+
+ it('appends multiple LoRAs in selection order', () => {
+ const { prompt, added } = weaveLoraTriggers('a rooftop', [['aria_tok'], ['rstgrm']]);
+ expect(prompt).toBe('a rooftop, aria_tok, rstgrm');
+ expect(added).toEqual(['aria_tok', 'rstgrm']);
+ });
+
+ it('dedupes a token shared by two selected LoRAs', () => {
+ const { prompt, added } = weaveLoraTriggers('a rooftop', [['aria_tok'], ['ARIA_TOK']]);
+ expect(prompt).toBe('a rooftop, aria_tok');
+ expect(added).toEqual(['aria_tok']);
+ });
+
+ it('skips LoRAs with no trigger words', () => {
+ const { prompt, added } = weaveLoraTriggers('a rooftop', [[], null, ['aria_tok'], undefined]);
+ expect(prompt).toBe('a rooftop, aria_tok');
+ expect(added).toEqual(['aria_tok']);
+ });
+
+ it('is a no-op when no LoRAs are selected', () => {
+ expect(weaveLoraTriggers('a rooftop', [])).toEqual({ prompt: 'a rooftop', added: [] });
+ expect(weaveLoraTriggers('a rooftop', null)).toEqual({ prompt: 'a rooftop', added: [] });
+ });
+
+ it('renders triggers alone when the prompt is empty (img2img / unconditional)', () => {
+ expect(weaveLoraTriggers('', [['aria_tok']])).toEqual({ prompt: 'aria_tok', added: ['aria_tok'] });
+ expect(weaveLoraTriggers(' ', [['aria_tok']])).toEqual({ prompt: 'aria_tok', added: ['aria_tok'] });
+ });
+
+ it('leaves an empty prompt untouched when there is nothing to add', () => {
+ // Whitespace is only trimmed when something is actually appended, so an
+ // empty-prompt render with no LoRAs keeps its exact original value.
+ expect(weaveLoraTriggers(' ', [])).toEqual({ prompt: ' ', added: [] });
+ });
+
+ it('does not double the separator after a trailing comma', () => {
+ expect(weaveLoraTriggers('a rooftop,', [['aria_tok']]).prompt).toBe('a rooftop, aria_tok');
+ });
+
+ it('coerces a non-string prompt to empty rather than stringifying it', () => {
+ expect(weaveLoraTriggers(null, [['aria_tok']])).toEqual({ prompt: 'aria_tok', added: ['aria_tok'] });
+ expect(weaveLoraTriggers(undefined, [])).toEqual({ prompt: '', added: [] });
+ });
+
+ it('accepts a bare string entry as a single-word list', () => {
+ expect(weaveLoraTriggers('a rooftop', ['aria_tok']).added).toEqual(['aria_tok']);
+ });
+});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 634f7a10cb..8ef436eba8 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -41,6 +41,8 @@ const IS_WIN = process.platform === 'win32';
import { getImageModels, isFlux2, isErnie, isHiDream, isQwen } from '../../lib/mediaModels.js';
import { usesDiffusersRunner, flux2Bf16BaseRepo } from '../../lib/runners.js';
+import { weaveLoraTriggers } from '../../lib/loraTriggers.js';
+import { readTriggerWordsByFilename } from '../loras.js';
// Read the registry lazily — callers below hit getImageModels() at request
// time. A prior `IMAGE_MODELS = Object.fromEntries(getImageModels()...)`
@@ -298,6 +300,9 @@ const clampStrength01 = (raw, fallback) => {
* (production passes `resolveImageInputPath`).
* - `loraExists(absPath)` — whether a prefix-checked LoRA path exists on disk
* (production passes `existsSync`).
+ * - `loraTriggerWords` — `{ [loraBasename]: string[] }` read from the LoRA
+ * sidecars by `generateImage`, so the trigger-word weave (#4665) needs no I/O
+ * of its own.
*
* `meta` is the exact object `generateImage` persists as the `<jobId>.metadata.json`
* sidecar AND spreads into the in-memory job + activeJob snapshots, so the
@@ -318,6 +323,16 @@ export function buildSidecarMeta({
loraFilenames = [],
loraPaths = [],
loraScales = [],
+ // LoRA trigger-word weaving (#4665). `loraTriggerWords` maps a LoRA basename
+ // to its sidecar `triggerWords` array; `generateImage` reads the sidecars and
+ // 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 = [],
@@ -424,8 +439,25 @@ export function buildSidecarMeta({
meta.regenSteps = actualSteps;
meta.regenModelId = modelId;
}
+ // Weave each selected LoRA's activation token into the prompt that actually
+ // reaches the runner (#4665). Provenance stays honest: `meta.prompt` remains
+ // the user's own text, so a Remix re-derives triggers from whatever LoRAs are
+ // selected at THAT time instead of compounding this render's clause. The
+ // 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 renderPrompt = addedTriggerWords.length ? wovenPrompt : prompt;
+ if (addedTriggerWords.length) {
+ meta.renderPrompt = renderPrompt;
+ meta.addedTriggerWords = addedTriggerWords;
+ }
return {
meta,
+ renderPrompt,
+ addedTriggerWords,
actualSeed,
actualSteps,
actualGuidance,
@@ -459,7 +491,7 @@ export function resolveOutputPlacement(outputTarget) {
return { outputDir, skipSidecar, isGallery };
}
-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 }) {
+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 }) {
// 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)
@@ -504,8 +536,19 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// non-gallery render has no static mount, so the queue reads the finished
// bytes off `outputPath` directly (surfaced as `outputPath` in the result).
const publicPath = outputDir === PATHS.images ? `/data/images/${filename}` : null;
+ // 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;
const {
meta,
+ renderPrompt,
+ addedTriggerWords,
actualSeed,
actualSteps,
actualGuidance,
@@ -534,9 +577,14 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
referenceImagePaths,
referenceImageStrengths,
regenOf,
+ loraTriggerWords,
+ weaveTriggerWords,
resolveInputPath: resolveImageInputPath,
loraExists: existsSync,
});
+ if (addedTriggerWords.length) {
+ console.log(`🔤 LoRA trigger words woven [${jobId.slice(0, 8)}]: ${addedTriggerWords.join(', ')}`);
+ }
const job = { ...meta, clients: [], status: 'running' };
jobs.set(jobId, job);
@@ -544,7 +592,9 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// per inference step here; we watch and stream the latest as `currentImage`.
const stepwiseDir = await mkdtemp(join(tmpdir(), 'portos-stepwise-'));
- const { bin, args } = buildArgs({ pythonPath, model, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength, referenceImagePaths: validReferenceImagePaths, referenceImageStrengths: validReferenceImageStrengths });
+ // `renderPrompt` — the user's prompt plus any LoRA activation tokens it was
+ // missing (#4665). Identical to `prompt` when nothing was woven.
+ const { bin, args } = buildArgs({ pythonPath, model, prompt: renderPrompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength, referenceImagePaths: validReferenceImagePaths, referenceImageStrengths: validReferenceImageStrengths });
const heavyClaim = await claimHeavyLocalJob({ kind: 'local image generation', id: jobId });
if (!heavyClaim.ok) {
jobs.delete(jobId);
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index fdc56e908c..551cb5a63b 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -771,6 +771,94 @@ describe('imageGen local.buildSidecarMeta', () => {
expect(meta.seed).toBeGreaterThanOrEqual(0);
expect(meta.seed).toBeLessThan(2147483647);
});
+
+ // --- LoRA trigger-word weaving (#4665) ---------------------------------
+ // `loraTriggerWords` is the sidecar map generateImage reads before calling
+ // in; the LoRA candidates go through the same prefix-check as every other
+ // test here (LORAS_ROOT + injected `loraExists`).
+
+ it('weaves a selected LoRA trigger word into the render prompt, keeping meta.prompt the user text', () => {
+ const { meta, renderPrompt, addedTriggerWords } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraFilenames: ['aria.safetensors'],
+ loraTriggerWords: { 'aria.safetensors': ['aria_tok', 'portrait'] },
+ });
+ // What the runner renders.
+ expect(renderPrompt).toBe('a red cube, aria_tok');
+ expect(addedTriggerWords).toEqual(['aria_tok']);
+ // Provenance: the user's own text is what a Remix reads back.
+ expect(meta.prompt).toBe('a red cube');
+ expect(meta.renderPrompt).toBe('a red cube, aria_tok');
+ expect(meta.addedTriggerWords).toEqual(['aria_tok']);
+ });
+
+ it('uses only the FIRST trigger word of each LoRA, in selection order', () => {
+ const { renderPrompt } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraFilenames: ['aria.safetensors', 'grain.safetensors'],
+ loraTriggerWords: {
+ 'aria.safetensors': ['aria_tok', 'portrait', 'closeup'],
+ 'grain.safetensors': ['rstgrm', 'film grain'],
+ },
+ });
+ expect(renderPrompt).toBe('a red cube, aria_tok, rstgrm');
+ });
+
+ it('does not weave a word the prompt already contains', () => {
+ const { meta, renderPrompt, addedTriggerWords } = buildSidecarMeta({
+ ...baseMetaInput,
+ prompt: 'aria_tok holding a red cube',
+ loraFilenames: ['aria.safetensors'],
+ loraTriggerWords: { 'aria.safetensors': ['aria_tok'] },
+ });
+ expect(renderPrompt).toBe('aria_tok holding a red cube');
+ expect(addedTriggerWords).toEqual([]);
+ // No provenance fields when nothing was woven — the sidecar stays
+ // byte-identical to every one written before this feature.
+ expect(meta.renderPrompt).toBeUndefined();
+ expect(meta.addedTriggerWords).toBeUndefined();
+ });
+
+ it('is a no-op when the render selected no LoRAs', () => {
+ const { meta, renderPrompt, addedTriggerWords } = buildSidecarMeta({ ...baseMetaInput });
+ expect(renderPrompt).toBe('a red cube');
+ expect(addedTriggerWords).toEqual([]);
+ expect(meta.renderPrompt).toBeUndefined();
+ });
+
+ it('skips a LoRA whose sidecar carries no trigger words (legacy / pre-Civitai)', () => {
+ const { renderPrompt, addedTriggerWords } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraFilenames: ['legacy.safetensors', 'aria.safetensors'],
+ loraTriggerWords: { 'legacy.safetensors': [], 'aria.safetensors': ['aria_tok'] },
+ });
+ expect(renderPrompt).toBe('a red cube, aria_tok');
+ expect(addedTriggerWords).toEqual(['aria_tok']);
+ });
+
+ it('never weaves a trigger for a LoRA that failed the prefix/existence check', () => {
+ const { renderPrompt, addedTriggerWords } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraFilenames: ['aria.safetensors'],
+ loraTriggerWords: { 'aria.safetensors': ['aria_tok'] },
+ loraExists: () => false,
+ });
+ expect(renderPrompt).toBe('a red cube');
+ expect(addedTriggerWords).toEqual([]);
+ });
+
+ it('honors weaveTriggerWords:false so the comic pipeline does not double-weight its own clause', () => {
+ const { meta, renderPrompt, addedTriggerWords } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraFilenames: ['aria.safetensors'],
+ loraTriggerWords: { 'aria.safetensors': ['aria_tok'] },
+ weaveTriggerWords: false,
+ });
+ expect(renderPrompt).toBe('a red cube');
+ expect(addedTriggerWords).toEqual([]);
+ expect(meta.renderPrompt).toBeUndefined();
+ });
+
});
describe('imageGen local.resolveOutputPlacement (issue #2264 non-gallery render seam)', () => {
diff --git a/server/services/loras.js b/server/services/loras.js
index e6cd3d1aff..c74c538513 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -88,6 +88,25 @@ export const readSidecar = async (filename) => {
return isPlainObject(parsed) ? parsed : null;
};
+// Read the `triggerWords` of several LoRAs at once, keyed by basename — the
+// input to the render-time trigger weave (`lib/loraTriggers.js`, #4665).
+// `filenames` may mix bare basenames (the current client surface) and absolute
+// paths (legacy sidecar replays); both collapse to the basename key. A LoRA
+// with no sidecar, or a legacy sidecar predating `triggerWords`, simply gets no
+// entry, so the weave is a no-op for it rather than an error.
+export const readTriggerWordsByFilename = async (filenames) => {
+ const names = [...new Set(
+ (Array.isArray(filenames) ? filenames : [])
+ .filter((f) => typeof f === 'string' && f)
+ .map((f) => basename(f)),
+ )];
+ if (!names.length) return {};
+ const sidecars = await Promise.all(names.map((n) => readSidecar(n)));
+ return Object.fromEntries(
+ names.map((n, i) => [n, sidecars[i]?.triggerWords]).filter(([, words]) => Array.isArray(words)),
+ );
+};
+
// Validate a basename so it can't escape PATHS.loras. Delegates to the
// shared `assertSafeFilename` helper in fileUtils.js (which also handles
// gallery .png assertions). Substring `..` is allowed because
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index 11e5227096..96615b9ac0 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -795,3 +795,57 @@ describe('LoRA key layout — stored value validation', () => {
expect(list.find((l) => l.filename === 'lora-bogus.safetensors').keyLayout).toBe('comfyui');
});
});
+
+describe('readTriggerWordsByFilename (#4665)', () => {
+ const writeSidecar = async (filename, body) => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, filename), 'fake-weights');
+ await fs.writeFile(join(tmpLoras, `${filename}.metadata.json`), JSON.stringify(body));
+ };
+
+ it('keys each LoRA basename to its sidecar trigger words', async () => {
+ await writeSidecar('aria.safetensors', { triggerWords: ['aria_tok', 'portrait'] });
+ await writeSidecar('grain.safetensors', { triggerWords: ['rstgrm'] });
+ expect(await lorasService.readTriggerWordsByFilename(['aria.safetensors', 'grain.safetensors'])).toEqual({
+ 'aria.safetensors': ['aria_tok', 'portrait'],
+ 'grain.safetensors': ['rstgrm'],
+ });
+ });
+
+ it('collapses an absolute path to its basename key (legacy sidecar replay)', async () => {
+ await writeSidecar('aria.safetensors', { triggerWords: ['aria_tok'] });
+ expect(await lorasService.readTriggerWordsByFilename([join(tmpLoras, 'aria.safetensors')]))
+ .toEqual({ 'aria.safetensors': ['aria_tok'] });
+ });
+
+ it('reads each LoRA once even when a basename and its path are both listed', async () => {
+ await writeSidecar('aria.safetensors', { triggerWords: ['aria_tok'] });
+ const out = await lorasService.readTriggerWordsByFilename([
+ 'aria.safetensors',
+ join(tmpLoras, 'aria.safetensors'),
+ ]);
+ expect(Object.keys(out)).toEqual(['aria.safetensors']);
+ });
+
+ it('omits a LoRA with no sidecar, and one whose sidecar predates triggerWords', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'orphan.safetensors'), 'fake-weights');
+ await writeSidecar('legacy.safetensors', { name: 'Legacy' });
+ // Absent, not `[]` — the weave then skips it entirely rather than treating
+ // it as "read and found none".
+ expect(await lorasService.readTriggerWordsByFilename(['orphan.safetensors', 'legacy.safetensors'])).toEqual({});
+ });
+
+ it('keeps an explicitly-empty triggerWords array (Civitai reported none)', async () => {
+ await writeSidecar('none.safetensors', { triggerWords: [] });
+ expect(await lorasService.readTriggerWordsByFilename(['none.safetensors'])).toEqual({ 'none.safetensors': [] });
+ });
+
+ it('returns {} for an empty / non-array / junk-entry input without touching disk', async () => {
+ expect(await lorasService.readTriggerWordsByFilename([])).toEqual({});
+ expect(await lorasService.readTriggerWordsByFilename(null)).toEqual({});
+ expect(await lorasService.readTriggerWordsByFilename([null, '', 42])).toEqual({});
+ });
+});
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index 87b718b5fc..16cee4cb9e 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -127,8 +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.
const loraRenderOptions = (loras) => (loras.length
- ? { loraFilenames: loras.map((l) => l.filename), loraScales: loras.map((l) => l.scale) }
+ ? {
+ loraFilenames: loras.map((l) => l.filename),
+ loraScales: loras.map((l) => l.scale),
+ weaveTriggerWords: false,
+ }
: {});
// Defensive fallback — an unrecognized value must never land in the final
@@ -257,7 +267,14 @@ 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 } : {}),
+ ...(options.loraFilenames?.length
+ ? {
+ loraFilenames: options.loraFilenames,
+ loraScales: options.loraScales,
+ // Carries loraRenderOptions' opt-out through to generateImage (#4665).
+ ...(options.weaveTriggerWords === false ? { weaveTriggerWords: false } : {}),
+ }
+ : {}),
};
// The queue dispatches directly to imageGen/{codex,local}.generateImage,
// bypassing imageGen/index.js's dispatcher that resolves cleaners for
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index d5901c1907..fcd97c3c53 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -44,7 +44,8 @@ import { hfChildEnv } from '../../lib/hfToken.js';
import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
import { safeChildProcessEnv, safeChildProcessOptions } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, planPromptEncodingRetry, bufferChildExit, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
-import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';
+import { assertSafeLoraFilename, getLoraKeyLayout, readTriggerWordsByFilename } from '../loras.js';
+import { weaveLoraTriggers } from '../../lib/loraTriggers.js';
import { videoLoraFamily, isLtx2FamilyRuntime } from '../../lib/runners.js';
import {
publicVideoTextEncoderOptions, resolveVideoTextEncoder,
@@ -1261,6 +1262,22 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// jobId may be supplied by the queue so SSE clients (which attached against
// the queue's id) reach the same generation events.
const jobId = providedJobId || randomUUID();
+
+ // Weave each selected LoRA's activation token into the prompt the runner
+ // actually receives (#4665) — a video LoRA whose trigger word never reaches
+ // the model is loaded but inert, which reads to the user as "the LoRA didn't
+ // work". Only the FIRST trigger word per LoRA is used, and one already in the
+ // prompt is never duplicated. Done here rather than in the route so the chain
+ // orchestrator's per-chunk beats (`chunkPrompts`) get the tokens too — each
+ // chunk re-enters through this function with its own prompt.
+ const triggerWordsByLora = await readTriggerWordsByFilename(resolvedLoras.map((l) => l.filename));
+ const { prompt: renderPrompt, added: addedTriggerWords } = weaveLoraTriggers(
+ prompt,
+ resolvedLoras.map((l) => triggerWordsByLora[l.filename]),
+ );
+ if (addedTriggerWords.length) {
+ console.log(`🔤 Video LoRA trigger words woven [${jobId.slice(0, 8)}]: ${addedTriggerWords.join(', ')}`);
+ }
const filename = `${jobId}.mp4`;
const outputPath = join(PATHS.videos, filename);
// Most local runners use PortOS's shared 64px grid. H3's released canvas
@@ -1554,6 +1571,12 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
loraFilenames: resolvedLoras.map((l) => l.filename),
loraScales: resolvedLoras.map((l) => l.strength),
} : {}),
+ // Provenance for the trigger weave (#4665). `prompt` above stays the user's
+ // own text, so Remix re-derives triggers from whatever LoRAs are selected
+ // then instead of compounding this render's clause; these two record what
+ // was actually rendered. Present only when something was woven, so every
+ // other history row stays byte-identical to pre-feature renders.
+ ...(addedTriggerWords.length ? { renderPrompt, addedTriggerWords } : {}),
...(hidden ? { hidden: true } : {}),
};
const job = { ...meta, clients: [], status: 'running' };
@@ -1567,7 +1590,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt: renderPrompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 3b75a2201a..38f42431df 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -289,9 +289,18 @@ vi.mock('./runtimes.js', async (importOriginal) => ({
// the permissive default so the pre-existing LoRA-threading tests below still
// reach the spawn path; the gate's own tests set a layout explicitly.
const loraLayoutState = vi.hoisted(() => ({ layout: null }));
+const loraSidecarState = vi.hoisted(() => ({ byFilename: {} }));
vi.mock('../loras.js', () => ({
assertSafeLoraFilename: vi.fn(),
getLoraKeyLayout: vi.fn(async () => loraLayoutState.layout),
+ // Trigger-word weaving (#4665) reads each selected LoRA's sidecar. Default to
+ // "no trigger words" so every pre-existing LoRA test renders its prompt
+ // unchanged; the weave tests populate `loraSidecarState.byFilename`.
+ readTriggerWordsByFilename: vi.fn(async (names) => Object.fromEntries(
+ (names || [])
+ .map((n) => [n, loraSidecarState.byFilename[n]?.triggerWords])
+ .filter(([, words]) => Array.isArray(words)),
+ )),
}));
vi.mock('fs/promises', () => ({
@@ -2466,6 +2475,92 @@ describe('generateVideo — LoRA history-record contract (Remix round-trip)', ()
});
});
+describe('generateVideo — LoRA trigger-word weaving (#4665)', () => {
+ const promptFrom = (spawnMock, jobId) => {
+ const call = spawnMock.mock.calls.find(([, args]) =>
+ Array.isArray(args) && args.some((a) => typeof a === 'string' && a.includes(jobId)));
+ if (!call) return null;
+ const i = call[1].indexOf('--prompt');
+ return i === -1 ? null : call[1][i + 1];
+ };
+
+ const renderWithLoras = async ({ jobId, prompt, loras }) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ let startedMeta = null;
+ const onStarted = (e) => { if (e.generationId === jobId) startedMeta = e; };
+ videoGenEvents.on('started', onStarted);
+ await generateVideo({
+ jobId,
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt,
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ loras,
+ });
+ videoGenEvents.off('started', onStarted);
+ return { renderedPrompt: promptFrom(spawnMock, jobId), startedMeta };
+ };
+
+ beforeEach(() => { loraSidecarState.byFilename = {}; });
+ afterEach(() => { loraSidecarState.byFilename = {}; });
+
+ it('appends the selected LoRA trigger word to the prompt the runner receives', async () => {
+ loraSidecarState.byFilename = { 'fox.safetensors': { triggerWords: ['fox_tok', 'animal'] } };
+ const { renderedPrompt, startedMeta } = await renderWithLoras({
+ jobId: 'weave-basic',
+ prompt: 'a clip in the rain',
+ loras: [{ filename: 'fox.safetensors', scale: 0.8 }],
+ });
+ // Only the FIRST trigger word — 'animal' is a loose Civitai tag, not an
+ // activation token.
+ expect(renderedPrompt).toBe('a clip in the rain, fox_tok');
+ // Provenance: history keeps the user's prompt so Remix re-derives triggers
+ // from whatever LoRAs are selected then rather than compounding this clause.
+ expect(startedMeta.prompt).toBe('a clip in the rain');
+ expect(startedMeta.renderPrompt).toBe('a clip in the rain, fox_tok');
+ expect(startedMeta.addedTriggerWords).toEqual(['fox_tok']);
+ });
+
+ it('does not duplicate a trigger word the prompt already carries', async () => {
+ loraSidecarState.byFilename = { 'fox.safetensors': { triggerWords: ['fox_tok'] } };
+ const { renderedPrompt, startedMeta } = await renderWithLoras({
+ jobId: 'weave-present',
+ prompt: 'fox_tok running through the rain',
+ loras: [{ filename: 'fox.safetensors', scale: 0.8 }],
+ });
+ expect(renderedPrompt).toBe('fox_tok running through the rain');
+ // No provenance fields — this history row stays byte-identical to a
+ // pre-feature one.
+ expect(startedMeta.renderPrompt).toBeUndefined();
+ expect(startedMeta.addedTriggerWords).toBeUndefined();
+ });
+
+ it('leaves the prompt untouched when the LoRA sidecar has no trigger words', async () => {
+ loraSidecarState.byFilename = { 'legacy.safetensors': { triggerWords: [] } };
+ const { renderedPrompt, startedMeta } = await renderWithLoras({
+ jobId: 'weave-legacy',
+ prompt: 'a clip in the rain',
+ loras: [{ filename: 'legacy.safetensors', scale: 1.0 }],
+ });
+ expect(renderedPrompt).toBe('a clip in the rain');
+ expect(startedMeta.renderPrompt).toBeUndefined();
+ });
+
+ it('is a no-op for a render with no LoRAs', async () => {
+ loraSidecarState.byFilename = { 'fox.safetensors': { triggerWords: ['fox_tok'] } };
+ const { renderedPrompt, startedMeta } = await renderWithLoras({
+ jobId: 'weave-no-loras',
+ prompt: 'a clip in the rain',
+ loras: undefined,
+ });
+ expect(renderedPrompt).toBe('a clip in the rain');
+ expect(startedMeta.renderPrompt).toBeUndefined();
+ });
+});
+
describe('generateVideo — heavy claim setup cleanup (#4364)', () => {
it('releases the claim when local setup fails before spawn', async () => {
mockPrepareLocalMemory.mockRejectedValueOnce(new Error('memory setup failed'));