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

feat: extend Qwen/HiDream hi-res presets, step counter under preview, suppress cosmetic CLIP truncation warning

[._.]/ Adam Eivy86d0f135d044
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9d260934d8..1588ae5006 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,6 +22,11 @@ TBD
## Changed
+- **Image Gen: hi-res presets opened to HiDream + Qwen-Image, plus a Qwen comic-page draft preset.** `client/src/lib/imageGenResolutions.js`'s `compatibilityKey` previously fell through to `flux1` for HIDREAM/QWEN, silently denying their natural `1024×1536` / `1536×1024` / `1536²` hi-res variants. Both runners now return their own keys, the three hi-res entries advertise compatibility for FLUX2 + QWEN + HIDREAM, and the Flux portrait/landscape entries (`832×1216`, `1216×832`) also open to them. Added a Qwen-only `1328×2048 (Qwen comic draft — experimental)` preset for US-comic-trim-aspect draft renders — past Qwen's documented ~1664 long-edge support window but coherent in practice on the 20B MMDiT; pair with a 1.5× upscale for final 1988×3056 output. Partial fix for `[hidream-qwen-client-runner-consumers]`; LoRA-picker side still pending.
+- **Image Gen preview: step counter under the preview.** The live diffusion preview now shows a `step 32/50 · 64%` row below the image while a render is in flight. The progress payload already carried `step`/`totalSteps` from `imageGen/local.js`; just rendered them. Hidden for Codex / external paths that don't emit per-step events.
+- **Qwen-Image stepwise preview decode.** `scripts/z_image_turbo.py` gained a Qwen-aware preview-decoder branch: Qwen-Image (and Img2Img / Edit siblings) packs latents to 3D `(B, num_patches, C*4)` like Flux, then unpacks to a 5-D video-VAE layout and unnormalizes with per-channel `latents_mean`/`latents_std` lists from `vae.config` before decoding. The generic `latents/scaling + shift` path matched neither step. New unpack helper (3D→5D) + Qwen-specific decoder; per-channel norm tensors are built CPU-side once and lazily migrated to (device, dtype) per call so the diffusion loop's ~30–50 fires don't rebuild from a list every step.
+- **Suppress cosmetic CLIP-truncation warning on multi-encoder pipelines.** The "input was truncated because CLIP can only handle N tokens" warning from diffusers was bleeding red into PortOS server logs on long prompts with HiDream, Qwen-Image, FLUX.2, Z-Image, and ERNIE — but on every one of these pipelines CLIP only contributes pooled style vectors derived from the first ~77 tokens while a high-context encoder (T5 / Llama-3.1-8B / Qwen2-VL) reads the full prompt. New `suppress_cosmetic_clip_truncation()` helper in `scripts/_runner_common.py` attaches an idempotent logging filter to the `diffusers` and `transformers` handlers (filter is on handlers, not loggers, because logger-level filters don't apply to propagated child records). Called from `scripts/z_image_turbo.py` after `import diffusers` and from `scripts/flux2_macos.py` after the pipeline-load dispatcher.
+
## Fixed
- **Big-local-models PR review pass.** Multi-agent review of the big-local-models branch surfaced eight cross-file regressions that landed alongside the Memory Management + new-runtime work:
diff --git a/PLAN.md b/PLAN.md
index 4f38c3acae..9bde4cf3d6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -221,7 +221,7 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr
- [ ] [consolidate-client-url-normalize] **Consolidate client-side URL normalization.** Three components prepend `https://` to a bare URL with near-identical logic: `normalizeUrl` in `client/src/components/brain/tabs/LinksTab.jsx`, the inline block in `client/src/components/QuickBrainCapture.jsx` (~line 34, with `URL_PATTERN`/`DOMAIN_PATTERN` regexes), and `client/src/components/brain/tabs/FeedsTab.jsx` (~line 50, no `git@` handling). Extract one `normalizeUrl`/`isUrl` pair to a shared `client/src/utils/` helper and migrate all three. Skipped during the buckets PR /simplify (2026-05-28) because a correct consolidation touches two unrelated components and must preserve each one's subtly different behavior (FeedsTab ignores `git@`; QuickBrainCapture splits detection from normalization).
- [ ] [brain-bucket-chip-reorder] **Drag-to-reorder chips *within* a bucket.** The Brain → Links bucket board (`client/src/components/brain/links/BucketBoard.jsx` + `BucketCard.jsx`) supports dragging a chip *between* buckets and reordering buckets, but not repositioning a chip within its own bucket — `bucketOrder` is only ever appended (max+1) on assign. Add intra-bucket position-aware drop (compute target index from the drop location, renumber `bucketOrder`, persist via `updateBrainLink`). Skipped in the initial buckets PR (2026-05-28) to avoid fragile drop-index math; chips currently sort by `bucketOrder` then insertion order, which is fine for the common case.
-- [ ] [hidream-qwen-client-runner-consumers] **Wire HIDREAM/QWEN through client runnerFamily consumers.** `client/src/lib/runnerFamilies.js` exports the constants and `server/lib/runners.js` mirrors them, but client-side consumers haven't been extended: `client/src/lib/imageGenResolutions.js`'s `compatibilityKey` OR-chain still only checks `FLUX2 | Z_IMAGE | ERNIE` (falls through to `'flux1'` for HiDream/Qwen — silently denies their natural 1536× hi-res variants), and `client/src/pages/Loras.jsx` `RUNNER_LABELS` / `RUNNER_BG_COLORS` / Top-LoRA section list omit them so the LoRA picker shows them as unlabeled / no badge color. Either extend each consumer site or document that HiDream/Qwen intentionally inherit Flux 1 resolution presets. Surfaced by /do:review of PR #516 (2026-05-28).
+- [ ] [hidream-qwen-loras-runner-consumers] **Wire HIDREAM/QWEN through `client/src/pages/Loras.jsx`.** `imageGenResolutions.js` was extended on 2026-05-28 (`compatibilityKey` now returns HIDREAM/QWEN as their own keys; `1024×1536` / `1536×1024` / `1536×1536` plus a new Qwen-only `1328×2048` comic draft preset opened to them). Still pending: `client/src/pages/Loras.jsx` `RUNNER_LABELS` / `RUNNER_BG_COLORS` / Top-LoRA section list omit HIDREAM/QWEN so the LoRA picker shows them as unlabeled / no badge color. Surfaced by /do:review of PR #516 (2026-05-28).
- [ ] [wan22-hunyuan-setup-pin-shas] **Pin Wan22 / HunyuanVideo MLX clones to known-good commit SHAs.** `scripts/setup-image-video.sh` defaults `WAN22_PIN="${WAN22_PIN:-main}"` and `HUNYUAN_PIN="${HUNYUAN_PIN:-main}"`. Floating `main` on two community-maintained ports with unpinned CLIs (the PR description explicitly flags both as experimental — "if upstream renames args, flip the registry entry broken: true") means every new install gets whatever HEAD is on those repos that day. Replace the default with a tested SHA for each; let users override via the env var (same shape as the diffusers pin). Surfaced by /do:review of PR #516 (2026-05-28).
- [ ] [memory-mgmt-new-endpoint-tests] **Add tests for the 5 new memory-management routes.** `/api/local-llm/loaded`, `/api/local-llm/unload`, `/api/voice/whisper`, `/api/voice/tts/status`, `/api/voice/tts/unload` have no test coverage. The PR description claims "8062/8062 tests passing" — true for the existing suite, but no asserts pin the new wire contracts (response shapes, residency precondition, validation rejection). Add focused happy-path + validation-rejection tests so future regressions in the schema-parity fixes (or the `unloadModel` residency check) surface as test failures. Surfaced by /do:review of PR #516 (2026-05-28).
- [ ] [qwen-image-edit-init-image-required] **Qwen-Image-Edit dispatches without its required init image.** `qwen-image-edit` (registry `mediaModels.js:202`) loads `QwenImageEditPipeline` which requires an `image` arg; the entry is exposed in the normal image-gen model picker which permits text-only submission. Today the user picks the model, submits a text prompt, and the runner crashes deep inside the diffusers pipeline after loading the 20B-param model from disk. Options: (a) add an `editOnly: true` flag to the model + validate at `routes/imageGen.js` POST; (b) filter the model from the picker when no source image is uploaded; (c) reroute through a future `/api/image-gen/edit` endpoint. Touches the image route schema + UI gating — defer to a focused PR. Surfaced by codex review of PR #516 (2026-05-28).
diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.js
index f68ddcecf8..b771cccac4 100644
--- a/client/src/lib/imageGenResolutions.js
+++ b/client/src/lib/imageGenResolutions.js
@@ -18,13 +18,16 @@ export const RESOLUTIONS = [
{ label: '512×768', w: 512, h: 768 },
{ label: '768×768', w: 768, h: 768 },
{ label: '1024×1024', w: 1024, h: 1024 },
- { label: '832×1216 (Flux portrait)', w: 832, h: 1216, compatible: ['flux1', RUNNER_FAMILIES.FLUX2, 'external'] },
- { label: '1216×832 (Flux landscape)', w: 1216, h: 832, compatible: ['flux1', RUNNER_FAMILIES.FLUX2, 'external'] },
+ { label: '832×1216 (Flux portrait)', w: 832, h: 1216, compatible: ['flux1', RUNNER_FAMILIES.FLUX2, RUNNER_FAMILIES.QWEN, RUNNER_FAMILIES.HIDREAM, 'external'] },
+ { label: '1216×832 (Flux landscape)', w: 1216, h: 832, compatible: ['flux1', RUNNER_FAMILIES.FLUX2, RUNNER_FAMILIES.QWEN, RUNNER_FAMILIES.HIDREAM, 'external'] },
{ label: '1024×576 (16:9)', w: 1024, h: 576 },
{ label: '576×1024 (9:16)', w: 576, h: 1024 },
- { label: '1536×1536 (hi-res square)', w: 1536, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
- { label: '1024×1536 (hi-res portrait)', w: 1024, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
- { label: '1536×1024 (hi-res landscape)', w: 1536, h: 1024, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
+ { label: '1536×1536 (hi-res square)', w: 1536, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2, RUNNER_FAMILIES.QWEN, RUNNER_FAMILIES.HIDREAM] },
+ { label: '1024×1536 (hi-res portrait)', w: 1024, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2, RUNNER_FAMILIES.QWEN, RUNNER_FAMILIES.HIDREAM] },
+ { label: '1536×1024 (hi-res landscape)', w: 1536, h: 1024, compatible: ['codex', RUNNER_FAMILIES.FLUX2, RUNNER_FAMILIES.QWEN, RUNNER_FAMILIES.HIDREAM] },
+ // Past Qwen's documented ~1664 long-edge support window — renders coherently
+ // in practice but is out-of-distribution; keep flagged "experimental."
+ { label: '1328×2048 (Qwen comic draft — experimental)', w: 1328, h: 2048, compatible: [RUNNER_FAMILIES.QWEN] },
// US comic-book trim presets — 6.625"×10.25" = 1.547:1 aspect, the real
// standard. Distinct from "portrait" because comic pages are squarer than
// 2:3. Codex-only: every dimension here exceeds the implicit local-runner
@@ -44,14 +47,18 @@ export const RESOLUTIONS = [
// Flux 1 (mflux/diffusers, `dev` / `schnell`) has no `runner` field — it's
// the fallback for local mode when nothing more specific matches.
+const NATIVE_RUNNER_KEYS = new Set([
+ RUNNER_FAMILIES.FLUX2,
+ RUNNER_FAMILIES.Z_IMAGE,
+ RUNNER_FAMILIES.ERNIE,
+ RUNNER_FAMILIES.QWEN,
+ RUNNER_FAMILIES.HIDREAM,
+]);
+
export const compatibilityKey = (mode, runner) => {
if (mode === IMAGE_GEN_MODE.CODEX) return 'codex';
if (mode === IMAGE_GEN_MODE.EXTERNAL) return 'external';
- if (runner === RUNNER_FAMILIES.FLUX2
- || runner === RUNNER_FAMILIES.Z_IMAGE
- || runner === RUNNER_FAMILIES.ERNIE) {
- return runner;
- }
+ if (NATIVE_RUNNER_KEYS.has(runner)) return runner;
return 'flux1';
};
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 74c8c1a365..28fcac63f9 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -252,9 +252,9 @@ export default function ImageGen() {
// server/lib/imageClean.js). One pass per mode, then split into the
// parallel cleanC2PA / denoise maps the UI binds to.
const perMode = {
- external: resolveCleanersFromConfig(s?.imageGen?.external),
- local: resolveCleanersFromConfig(s?.imageGen?.local),
- codex: resolveCleanersFromConfig(s?.imageGen?.codex),
+ external: resolveCleanersFromConfig(s?.imageGen?.external, IMAGE_GEN_MODE.EXTERNAL),
+ local: resolveCleanersFromConfig(s?.imageGen?.local, IMAGE_GEN_MODE.LOCAL),
+ codex: resolveCleanersFromConfig(s?.imageGen?.codex, IMAGE_GEN_MODE.CODEX),
};
const c2 = { external: perMode.external.cleanC2PA, local: perMode.local.cleanC2PA, codex: perMode.codex.cleanC2PA };
const dn = { external: perMode.external.denoise, local: perMode.local.denoise, codex: perMode.codex.denoise };
@@ -1291,6 +1291,14 @@ export default function ImageGen() {
)}
</div>
+ {generating && progress?.totalSteps != null && (
+ <div className="flex items-center justify-center gap-2 text-[11px] text-gray-400 tabular-nums">
+ <span>step {progress.step ?? 0}/{progress.totalSteps}</span>
+ {progressPct != null && <span className="text-gray-600">·</span>}
+ {progressPct != null && <span>{progressPct}%</span>}
+ </div>
+ )}
+
{result && !generating && (
<div className="flex flex-wrap items-center gap-2 text-xs text-gray-400">
<span className="truncate flex-1">{result.filename}</span>
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
index d0a9b5b27e..f9408398d2 100644
--- a/scripts/_runner_common.py
+++ b/scripts/_runner_common.py
@@ -19,14 +19,18 @@ walker that turns a buried `GatedRepoError` into a friendly link — belongs her
"""
import json
+import logging
import sys
import threading
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
-import torch
-from PIL import Image
+# Lazy heavy-import note: `torch` and `PIL` are deferred into the functions
+# that actually need them (pick_device, make_generator, make_stepwise_callback).
+# Lightweight helpers — heartbeat, install_hf_error_handler, write_sidecar —
+# stay usable from venvs that haven't pip-installed torch yet (e.g. the
+# Hunyuan venv during a partial bootstrap).
@contextmanager
@@ -58,10 +62,40 @@ def heartbeat(stage: str, interval: float = 20.0):
t.join(timeout=interval + 1)
+class _ClipTruncationFilter(logging.Filter):
+ _MARKER = "input was truncated because CLIP can only handle"
+
+ def filter(self, record: logging.LogRecord) -> bool:
+ return self._MARKER not in record.getMessage()
+
+
+def suppress_cosmetic_clip_truncation() -> None:
+ """Hide the "CLIP can only handle N tokens" warning on multi-encoder
+ pipelines (FLUX.2, HiDream, Qwen-Image, Z-Image, ERNIE).
+
+ Every pipeline in this runner stack runs CLIP alongside a high-context
+ encoder (T5 / Llama-3.1-8B / Qwen2-VL); CLIP only contributes pooled
+ style/color vectors derived from the first ~77 tokens, while the long
+ encoder reads the full prompt. The diffusers warning fires anyway and
+ bleeds red into PortOS server logs as if the prompt were being damaged.
+ Filter just that one message — every other diffusers warning still flows.
+
+ Logger-level filters don't apply to propagated child records, so the
+ filter has to be on the handlers. Idempotent (skips handlers it's
+ already attached to) so callers don't need to track first-run state.
+ """
+ f = _ClipTruncationFilter()
+ for name in ("diffusers", "transformers"):
+ for handler in logging.getLogger(name).handlers:
+ if not any(isinstance(existing, _ClipTruncationFilter) for existing in handler.filters):
+ handler.addFilter(f)
+
+
def pick_device(requested: str) -> str:
"""Resolve `auto`/`mps`/`cuda`/`cpu` against what torch actually has.
Falls back to CPU with a warning when the requested accelerator isn't
available — never silently downgrades without telling the user."""
+ import torch
if requested == "auto":
if torch.backends.mps.is_available():
return "mps"
@@ -77,10 +111,11 @@ def pick_device(requested: str) -> str:
return requested
-def make_generator(device: str, seed: int) -> torch.Generator:
+def make_generator(device: str, seed: int) -> "torch.Generator":
"""Seed a torch Generator on the right device. Accelerator generators
must be initialised with the device string; the CPU fallback uses the
no-arg form."""
+ import torch
if device in ("cuda", "mps"):
return torch.Generator(device).manual_seed(int(seed))
return torch.Generator().manual_seed(int(seed))
@@ -139,6 +174,8 @@ def make_stepwise_callback(
"""
if not stepwise_dir:
return None
+ import torch
+ from PIL import Image
out = Path(stepwise_dir)
out.mkdir(parents=True, exist_ok=True)
vae = pipe.vae
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index 2444b043c0..c19349257b 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -42,6 +42,7 @@ from _runner_common import ( # noqa: E402
make_generator,
make_stepwise_callback,
pick_device,
+ suppress_cosmetic_clip_truncation,
write_sidecar,
)
from lora_utils import apply_loras # noqa: E402
@@ -269,6 +270,7 @@ def main() -> None:
else:
print(f"❌ unknown quantization: {args.quantization}", file=sys.stderr)
sys.exit(64)
+ suppress_cosmetic_clip_truncation()
apply_memory_optimizations(pipe)
apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index 40b42ff5f4..a42ae8bb48 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -32,6 +32,7 @@ from _runner_common import ( # noqa: E402
make_generator,
make_stepwise_callback,
pick_device,
+ suppress_cosmetic_clip_truncation,
write_sidecar,
)
from lora_utils import apply_loras # noqa: E402
@@ -89,6 +90,7 @@ def load_pipeline(
# to AutoPipelineForText2Image so Z-Image-Turbo and any future registered
# model continues to work without a flag.
import diffusers
+ suppress_cosmetic_clip_truncation()
# HiDream needs a 4th text encoder + tokenizer loaded externally and
# passed as kwargs. The text-encoder-repo flag is the trigger; if it's
@@ -213,6 +215,7 @@ def main() -> None:
# mismatch ([32,32,1,1] weight vs 128-ch input). When the loaded pipeline
# exposes both hooks, pass an ERNIE-aware preview decoder.
preview_decoder = None
+ unpack_latents = None
pipe_vae = getattr(pipe, "vae", None)
if hasattr(pipe, "_unpatchify_latents") and pipe_vae is not None and hasattr(pipe_vae, "bn"):
def preview_decoder(p, latents): # noqa: E306 — local closure on purpose
@@ -221,12 +224,50 @@ def main() -> None:
std = torch.sqrt(vae.bn.running_var.view(1, -1, 1, 1) + 1e-5).to(device=latents.device, dtype=latents.dtype)
unpacked = p._unpatchify_latents(latents * std + mean)
return vae.decode(unpacked, return_dict=False)[0]
+ # Qwen-Image (and its Img2Img / Edit siblings) packs latents to 3D
+ # `(B, num_patches, C*4)` like Flux, then unpacks to a 5-D video-VAE
+ # layout `(B, C, 1, H, W)` and unnormalizes with per-channel
+ # latents_mean/latents_std lists from vae.config before decoding. The
+ # generic `latents/scaling + shift` path doesn't match either step, so
+ # we wire both an unpack helper (3D→5D) and a Qwen-specific decoder.
+ elif hasattr(pipe, "_unpack_latents") and getattr(getattr(pipe_vae, "config", None), "latents_mean", None) is not None:
+ vae_scale_factor = getattr(pipe, "vae_scale_factor", 8)
+ z_dim = getattr(pipe_vae.config, "z_dim", len(pipe_vae.config.latents_mean))
+ # Pipeline config holds these as plain Python lists; build the CPU
+ # tensors once here and lazily migrate to (device, dtype) per call —
+ # the diffusion loop fires this closure ~30-50 times per render, and
+ # rebuilding from a list every step is pure waste (mirrors how the
+ # ERNIE branch above pulls vae.bn directly, not from a list).
+ qwen_mean_cpu = torch.tensor(pipe_vae.config.latents_mean).view(1, z_dim, 1, 1, 1)
+ qwen_inv_std_cpu = (1.0 / torch.tensor(pipe_vae.config.latents_std)).view(1, z_dim, 1, 1, 1)
+ qwen_norm_cache = {}
+
+ def unpack_latents(latents, height, width): # noqa: E306
+ return pipe._unpack_latents(latents, height, width, vae_scale_factor)
+
+ def preview_decoder(p, latents): # noqa: E306
+ key = (latents.device, latents.dtype)
+ cached = qwen_norm_cache.get(key)
+ if cached is None:
+ cached = (
+ qwen_mean_cpu.to(device=latents.device, dtype=latents.dtype),
+ qwen_inv_std_cpu.to(device=latents.device, dtype=latents.dtype),
+ )
+ qwen_norm_cache[key] = cached
+ mean, inv_std = cached
+ unnorm = latents * inv_std + mean
+ decoded = p.vae.decode(unnorm, return_dict=False)[0]
+ # Qwen's image VAE returns `(B, C, T, H, W)` with T=1 for stills.
+ # Slice the temporal dim out so the generic post-decode path's
+ # `decoded[0].permute(1, 2, 0)` receives the expected 4-D shape.
+ return decoded[:, :, 0]
callback = make_stepwise_callback(
args.stepwise_image_output_dir,
pipe,
int(args.height),
int(args.width),
+ unpack_latents=unpack_latents,
preview_decoder=preview_decoder,
)