Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(safety): the content gate runs before a character renders and on phone lanes; no checker blacks out a Mac image (#231)

purplef99ba7a74c19
diff --git a/src-tauri/resources/mlx/server.py b/src-tauri/resources/mlx/server.py
index bf947b15..96903d74 100644
--- a/src-tauri/resources/mlx/server.py
+++ b/src-tauri/resources/mlx/server.py
@@ -187,11 +187,26 @@ def _ensure_pipe(
# No attention/VAE slicing here: on torch 2.12 + MPS it corrupts the
# forward pass into all-NaN latents (verified live — plain runs are
# clean, sliced runs decode to black frames).
- _pipe = AutoPipelineForText2Image.from_pretrained(repo, **kwargs).to(device)
+ _pipe = _without_checker(AutoPipelineForText2Image.from_pretrained(repo, **kwargs).to(device))
_pipe_repo = repo
return _pipe
+def _without_checker(pipe):
+ """No image of this app goes through the diffusers safety checker. It
+ blacks out what it reads as nudity, an adult picture included, and says
+ nothing. LU's own gate refuses a prompt that sexualizes minors before any
+ engine starts (lib/render/safety.ts), on every model.
+
+ The catalog's flag skips the checker at load, where a repo bundles one
+ (it also spares its download). On 13.11.2026 no catalog repo shipped
+ checker weights, but the install follows each repo's main branch, so
+ one that adds them later is caught here, for every model alike."""
+ if getattr(pipe, "safety_checker", None) is not None:
+ pipe.safety_checker = None
+ return pipe
+
+
app = FastAPI(title="LU MLX server")
diff --git a/src-tauri/resources/mlx/tests/test_cancel.py b/src-tauri/resources/mlx/tests/test_cancel.py
index 1b64d390..bef1f89d 100644
--- a/src-tauri/resources/mlx/tests/test_cancel.py
+++ b/src-tauri/resources/mlx/tests/test_cancel.py
@@ -244,3 +244,22 @@ class ProgressTest(unittest.TestCase):
server._ensure_pipe = lambda *args, **kwargs: OldPipe(on_step=lambda step: seen.append(asyncio.run(server.progress())))
server.generate(server.GenerateRequest(prompt="a cat", steps=2))
self.assertEqual([(s["phase"], s["step"], s["step_hook"]) for s in seen], [("steps", 0, False)] * 2)
+
+
+class CheckerTest(unittest.TestCase):
+ """The diffusers safety checker never blacks out a picture (13.11.2026)."""
+
+ def setUp(self):
+ self.server = _load_server()
+
+ def test_a_pipeline_that_brought_a_checker_runs_without_it(self):
+ pipe = types.SimpleNamespace(safety_checker=object())
+ self.assertIs(self.server._without_checker(pipe), pipe)
+ self.assertIsNone(pipe.safety_checker)
+
+ def test_a_pipeline_without_one_is_left_as_it_is(self):
+ pipe = types.SimpleNamespace(transformer=object())
+ self.assertIs(self.server._without_checker(pipe), pipe)
+ self.assertFalse(hasattr(pipe, "safety_checker"))
+ empty = types.SimpleNamespace(safety_checker=None)
+ self.assertIsNone(self.server._without_checker(empty).safety_checker)
diff --git a/src/api/mcp/__tests__/agent-gate-before-character.test.ts b/src/api/mcp/__tests__/agent-gate-before-character.test.ts
new file mode 100644
index 00000000..fcc48801
--- /dev/null
+++ b/src/api/mcp/__tests__/agent-gate-before-character.test.ts
@@ -0,0 +1,83 @@
+// #231 follow-up (13.11.2026): the agent's media tools pass the same gate as
+// Create (localRenderBlocked). With a character, video_generate first renders
+// the character's picture and only then reached the gate, so a refused prompt
+// had already gone to the engine once. The gate now runs on what the call asks
+// for before anything else, and every picture the chain renders passes it too.
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const io = vi.hoisted(() => ({ renders: [] as Array<Record<string, unknown>> }))
+
+vi.mock('../../backend', async (orig) => ({
+ ...(await orig<typeof import('../../backend')>()),
+ backendCall: vi.fn(async () => null),
+ isTauri: () => false,
+}))
+vi.mock('../../agents/sub-agent', () => ({
+ DELEGATE_TASK_TOOL_DEF: { name: 'delegate_task', description: '', category: 'system', inputSchema: {} },
+ buildDelegateExecutor: () => async () => 'stub',
+}))
+vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
+vi.mock('../../mlx-image', async (orig) => ({
+ ...(await orig<typeof import('../../mlx-image')>()),
+ isMlxImageHost: () => false,
+}))
+vi.mock('../../../stores/chatStore', () => ({
+ useChatStore: { getState: () => ({ conversations: [], activeConversationId: 'c1' }) },
+}))
+vi.mock('../../../lib/characters', async (orig) => ({
+ ...(await orig<typeof import('../../../lib/characters')>()),
+ listLocalCharacters: async () => [{ id: 'local:char_mira_zimage.safetensors', name: 'mira', triggerWord: 'mira', family: 'zimage' }],
+}))
+vi.mock('../../comfyui', async (orig) => ({
+ ...(await orig<typeof import('../../comfyui')>()),
+ getImageModels: async () => [{ name: 'z_image_bf16.safetensors', type: 'zimage' }],
+}))
+vi.mock('../../vram-handoff', async (orig) => ({
+ ...(await orig<typeof import('../../vram-handoff')>()),
+ vramHandoffGenerate: async (_kind: string, args: Record<string, unknown>) => {
+ io.renders.push(args)
+ return 'Image generated: LU_00001_.png (prompt: "x")\nhttp://127.0.0.1:8188/view?filename=LU_00001_.png&subfolder=&type=output'
+ },
+}))
+
+import { registerBuiltinTools } from '../builtin-tools'
+import { ToolRegistry } from '../tool-registry'
+import type { AgentRunContext } from '../../agent-context'
+
+const registry = new ToolRegistry()
+registerBuiltinTools(registry)
+const run = { token: 't', chatId: null, conversationId: 'c1', workspace: null, artifactMode: false, readOnlyShellTurn: false, mode: null } as unknown as AgentRunContext
+
+beforeEach(() => { io.renders = [] })
+
+describe('the agent gate comes before a character renders anything', () => {
+ it.each([
+ 'nude teen on a beach',
+ 'n4ked sch00lgirl',
+ 'nude 15 year old',
+ 'naked t e e n',
+ 'erotic chіld', // Cyrillic i
+ ])('video_generate with a character and "%s": refused, nothing rendered', async (prompt) => {
+ const out = await registry.execute('video_generate', { prompt, character: 'mira', model: 'wan2.2_ti2v_5B_fp16.safetensors' }, 1, run)
+ expect(String(out)).toMatch(/content sexualizing minors/)
+ expect(io.renders).toEqual([])
+ })
+
+ it('image_generate with a character and a refused prompt: refused, nothing rendered', async () => {
+ const out = await registry.execute('image_generate', { prompt: 'nude teen', character: 'mira' }, 1, run)
+ expect(String(out)).toMatch(/content sexualizing minors/)
+ expect(io.renders).toEqual([])
+ })
+
+ it('an unambiguous term in the negative prompt is refused here too', async () => {
+ const out = await registry.execute('video_generate', { prompt: 'walking', negativePrompt: 'jailbait', character: 'mira' }, 1, run)
+ expect(String(out)).toMatch(/content sexualizing minors/)
+ expect(io.renders).toEqual([])
+ })
+
+ it('COUNTER-CHECK: an adult prompt with "teen" kept out in the negative prompt renders the character', async () => {
+ const out = await registry.execute('image_generate', { prompt: 'portrait, nsfw, lingerie', negativePrompt: 'teen, child', character: 'mira' }, 1, run)
+ expect(String(out)).toMatch(/^Image generated/)
+ expect(io.renders).toHaveLength(1)
+ })
+})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 9abaf207..0413cc8a 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1577,6 +1577,10 @@ async function executeImageGenerate(args: ToolArgs, run?: AgentRunContext, signa
if (stop?.aborted) return 'Image generation cancelled.'
const sizeRej = mediaSizeReject(merged)
if (sizeRej) return sizeRej
+ // The gate first, on what the call asks for: a character renders nothing
+ // before it, and the checks below cover what the character adds.
+ const asked = localRenderBlocked({ ...merged, prompt })
+ if (asked) return asked
// Hard rule: on macOS, local image generation is Apple MLX only — ComfyUI
// never runs there (see isMlxImageHost() / useCreate.ts's MLX image
@@ -1651,6 +1655,10 @@ async function executeVideoGenerate(args: ToolArgs, run?: AgentRunContext, signa
if (stop?.aborted) return 'Video generation cancelled.'
const sizeRej = mediaSizeReject(merged)
if (sizeRej) return sizeRej
+ // The gate first: a character's chain renders its picture before the clip,
+ // and that picture must not start on a prompt the gate refuses.
+ const asked = localRenderBlocked(merged)
+ if (asked) return asked
// Hard rule: on macOS, local video generation is Apple MLX only — ComfyUI
// never runs there. Route around vram-handoff entirely (no VRAM juggling —
@@ -1895,7 +1903,8 @@ async function characterChatDeps(run?: AgentRunContext, signal?: AbortSignal): P
return {
characters: () => listLocalCharacters(),
imageModels: () => comfy.getImageModels(),
- renderImage: (a) => vramHandoffGenerate('image', a, generationOwnerOf(run), { signal }),
+ // Every picture the chain renders passes the gate itself too.
+ renderImage: async (a) => localRenderBlocked(a) ?? vramHandoffGenerate('image', a, generationOwnerOf(run), { signal }),
failed: isMediaFailureResult,
takesStartImage: comfy.isI2VModel,
}
@@ -1914,6 +1923,8 @@ async function macCharacterChatDeps(signal?: AbortSignal): Promise<CharacterChat
characters: () => listLocalCharacters(),
imageModels: async () => (await listMlxImageModels()).filter((m) => m.installed).map((m) => ({ name: m.name, type: mlxModelType(m) })),
renderImage: async (a) => {
+ const blocked = localRenderBlocked(a)
+ if (blocked) return blocked
const out = await executeImageGenerateMlx(String(a.prompt ?? ''), a, signal)
const url = out.split('\n')[1] ?? ''
if (!out.startsWith('Image generated:') || !url.startsWith('file:')) return out
diff --git a/src/lib/__tests__/remote-create-runner.test.ts b/src/lib/__tests__/remote-create-runner.test.ts
index 84d30c87..32b18c33 100644
--- a/src/lib/__tests__/remote-create-runner.test.ts
+++ b/src/lib/__tests__/remote-create-runner.test.ts
@@ -269,3 +269,38 @@ describe('parseMediaResult', () => {
expect(parseMediaResult('')).toBeNull()
})
})
+
+// #231 follow-up (13.11.2026): a lane (edit, music, upscale, cut-out) reaches
+// the engines without image_generate and passed no gate. Every job from the
+// phone passes lib/render/safety.ts now, before anything runs.
+describe('a job from the phone passes the content gate first', () => {
+ it.each([
+ { kind: 'edit' as const, prompt: 'make her nude, she is 14 years old' },
+ { kind: 'edit' as const, prompt: 'n a k e d preteen' },
+ { kind: 'music' as const, prompt: 'pop song', lyrics: 'jailbait' },
+ { kind: 'image' as const, prompt: 'sexy sch00lgirl' },
+ ])('$kind with a refused text: nothing runs, the phone hears why', async (over) => {
+ const r = rig(undefined, undefined, 'mlx')
+ const runner = createRemoteCreateRunner(r.deps)
+ await runner.handle({ action: 'run', job: job(over) })
+ expect(r.lanes).toEqual([])
+ expect(r.generated).toEqual([])
+ expect(r.finished).toHaveLength(1)
+ expect(r.finished[0].ok).toBe(false)
+ expect(r.finished[0].error).toMatch(/content sexualizing minors/)
+ })
+
+ it('an unambiguous term in the negative prompt is refused too', async () => {
+ const r = rig(undefined, undefined, 'mlx')
+ await createRemoteCreateRunner(r.deps).handle({ action: 'run', job: job({ kind: 'edit', prompt: 'a portrait', negative: 'child porn' }) })
+ expect(r.lanes).toEqual([])
+ expect(r.finished[0].error).toMatch(/content sexualizing minors/)
+ })
+
+ it('COUNTER-CHECK: an edit that keeps "teen" out in the negative prompt runs', async () => {
+ const r = rig(undefined, undefined, 'mlx')
+ await createRemoteCreateRunner(r.deps).handle({ action: 'run', job: job({ kind: 'edit', prompt: 'nsfw portrait of a woman', negative: 'teen, kid, baby' }) })
+ expect(r.lanes).toHaveLength(1)
+ expect(r.finished[0].ok).toBe(true)
+ })
+})
diff --git a/src/lib/remote-create-runner.ts b/src/lib/remote-create-runner.ts
index 9d1b7255..93326b13 100644
--- a/src/lib/remote-create-runner.ts
+++ b/src/lib/remote-create-runner.ts
@@ -24,6 +24,7 @@ import { backendCall, isTauri } from '../api/backend'
import { fileUrlToPath } from './local-media-url'
import { isMediaFailureResult } from './media-result'
import { log } from './logger'
+import { blockMessageFor, checkPromptSafety } from './render/safety'
import { FROM_YOUR_PHONE, type GalleryOut, type LaneCaps, type LaneInput, type LaneKind, type LaneWatch } from './remote-create-lanes'
export const REMOTE_CREATE_EVENT = 'remote-create-job'
@@ -210,6 +211,12 @@ export function createRemoteCreateRunner(deps: RemoteCreateDeps): RemoteCreateRu
const outputs: RemoteCreateOutput[] = []
let error: string | null = null
try {
+ // The same gate as Create and the chat (lib/render/safety.ts), before
+ // anything runs: a lane (edit, music, upscale, cut-out) reaches the
+ // engines without image_generate, so it would pass unchecked otherwise.
+ // The negative prompt is read apart (B30).
+ const verdict = checkPromptSafety(`${job.prompt} ${job.lyrics ?? ''} ${job.character ?? ''}`, { negative: job.negative })
+ if (verdict.blocked) throw new Error(blockMessageFor(verdict.reason))
if (!(await deps.progress(job.id, { progress: 0, stepText: 'Starting', index: 0 }))) return
stopWatch = deps.watchEngine?.(report)
if (lane) {
diff --git a/src/lib/render/__tests__/safety-negative-prompt.test.ts b/src/lib/render/__tests__/safety-negative-prompt.test.ts
index f611d142..15ecb934 100644
--- a/src/lib/render/__tests__/safety-negative-prompt.test.ts
+++ b/src/lib/render/__tests__/safety-negative-prompt.test.ts
@@ -76,3 +76,30 @@ describe('what is rendered is checked as strictly as before', () => {
expect(checkPromptSafety('portrait of a woman, nude', { tier: 'cloud', policy: 'off' }).blocked).toBe(false)
})
})
+
+// GitHub #231 "It is still censored" (3.0.0): "nsfw" in the negative prompt and
+// "teen", "kid" or "baby" in the prompt were read as one text and refused.
+describe('#231: words kept out in the negative prompt do not complete the conjunction', () => {
+ it.each(['teen', 'kid', 'baby', 'a teen skateboarder at sunset', 'kids playing football', 'a baby sleeping'])(
+ '"%s" with "nsfw" in the negative prompt renders, locally and on every cloud setting',
+ (prompt) => {
+ expect(checkPromptSafety(prompt, { negative: 'nsfw, nude, lowres' }).blocked).toBe(false)
+ for (const policy of ['off', 'soft', 'strict'] as const) expect(cloud(prompt, 'nsfw, nude', policy).blocked).toBe(false)
+ },
+ )
+
+ it.each([
+ 'nsfw teen', 'teen, nsfw', 'n s f w t e e n', 'nsfw t33n', 'nsfw kіd', // Cyrillic i
+ 'nude 14 yo', 'naked fourteen years old', 'sexy 9 y/o', 'nsfw baby',
+ ])('"%s" in the prompt stays refused, whatever the negative prompt says', (prompt) => {
+ for (const negative of [undefined, 'nsfw', 'adult, 30 year old']) {
+ expect(checkPromptSafety(prompt, { negative }).blocked).toBe(true)
+ }
+ })
+
+ it('the hard terms are refused in the negative prompt, folded as everywhere', () => {
+ for (const negative of ['csam', 'jailbait', 'pedo', 'j4ilb4it', 'p e d o p h i l e', 'chіld pоrn']) {
+ expect(checkPromptSafety('teen', { negative })).toEqual({ blocked: true, reason: 'csam' })
+ }
+ })
+})