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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
start a substitute text encoder's download when it is picked, not on a second click
[._.]/ Adam Eivyf3a0cd66cb1e
diff --git a/.changelog/next/added-agent-436929f7.md b/.changelog/next/added-agent-436929f7.mdnew file mode 100644index 0000000000..4cbb05f4cb--- /dev/null+++ b/.changelog/next/added-agent-436929f7.md@@ -0,0 +1 @@+- Video Gen: a second swappable text encoder for MiniMax H3 (huihui-ai's abliterated Qwen3-VL-32B), and picking any substitute now starts its download instead of waiting on a separate Download clickdiff --git a/client/src/components/media/ModelDownloadBadge.jsx b/client/src/components/media/ModelDownloadBadge.jsxindex eabd8f1f5d..1a9cc7c546 100644--- a/client/src/components/media/ModelDownloadBadge.jsx+++ b/client/src/components/media/ModelDownloadBadge.jsx@@ -4,13 +4,18 @@// HF pull. Local generation forms block until required weights are present,// keeping downloads explicit and recoverable instead of hiding them in render.//-// Three render states:+// Four render states:// 1. cached → green CheckCircle, "Available · <size>"// 2. unknown → grey, no CTA (model has no `repo` in the registry)// 3. needsDl → "↓ Download (~est)" button; while downloading, a stage// label + percentage replace the button.+// 4. queued → this pull is already committed (a picker chose it via+// `startWhenIdle`) and is waiting for the single download+// lane. REPLACES the button rather than sitting beside it:+// offering Download here would hijack the lane the queued+// pull is politely waiting for.-import { CheckCircle, Download, Loader2 } from 'lucide-react';+import { CheckCircle, Clock, Download, Loader2 } from 'lucide-react';import { formatBytes } from '../../utils/formatters.js';const STAGE_LABELS = {@@ -25,6 +30,7 @@ export default function ModelDownloadBadge({onDownload, // () => voidonCancel, // () => voidestimateLabel, // e.g. "~8 GB" — caller derives from model entry name+ queued = false, // this pull is committed and waiting for the download lanedisabled = false,disabledReason,disabledReasonId,@@ -99,6 +105,17 @@ export default function ModelDownloadBadge({);}+ // Committed but not yet started — the lane belongs to another pull. Say so+ // instead of rendering a button that reads as "your click did nothing".+ if (queued) {+ return (+ <p className="mt-1 flex items-center gap-1.5 text-[11px] text-gray-400">+ <Clock className="w-3.5 h-3.5" />+ <span>Queued{estimateLabel ? ` (${estimateLabel})` : ''} — starts when the current download finishes</span>+ </p>+ );+ }+// Not cached, not in flight — offer the inline trigger.return (<buttondiff --git a/client/src/components/videoGen/TextEncoderPicker.jsx b/client/src/components/videoGen/TextEncoderPicker.jsxindex 79ccbdb276..84197ce2ae 100644--- a/client/src/components/videoGen/TextEncoderPicker.jsx+++ b/client/src/components/videoGen/TextEncoderPicker.jsx@@ -17,6 +17,12 @@* with the select rather than behind the collapsed Advanced panel — the user has* to see the cost at the moment they pick it, and the page gates Generate on the* same status.+ *+ * Selecting an un-downloaded substitute starts that pull (the page wires the+ * select to `startWhenIdle`), so the option's size rides in the option TEXT+ * where it is legible before the click. The badge still renders because it owns+ * every state that follows — queued, in progress, cancel, and the retry after a+ * failed or cancelled pull.*/import { FormField } from '../ui/FormField';import ModelSelect from '../ModelSelect';@@ -24,6 +30,9 @@ import ModelDownloadBadge from '../media/ModelDownloadBadge';import FactLink from './FactLink';import { formatBytes } from '../../utils/formatters.js';+// Shared by the three sub-label lines below so they can't drift apart.+const HINT_CLASS = 'text-[10px] text-gray-500 leading-snug mt-1';+// The option text carries its own download size, so the shared ModelSelect gets// a getLabel rather than the default `m.name` (these entries have `label`).const optionLabel = (option) => (@@ -37,6 +46,7 @@ export default function TextEncoderPicker({status = null,onDownload,onCancel,+ queued = false,disabled = false,}) {if (options.length < 2) return null;@@ -61,15 +71,13 @@ export default function TextEncoderPicker({getLabel={optionLabel}disabled={disabled}/>- {selected.description && (- <p className="text-[10px] text-gray-500 leading-snug mt-1">{selected.description}</p>- )}+ {selected.description && <p className={HINT_CLASS}>{selected.description}</p>}{/* Same provenance affordance a MODEL gets (ModelDisclosure/FactLink): asubstitute is someone else's tens-of-GB checkpoint, so its card andlicense stay one click away instead of being facts only the registryknows. */}{(card || license) && (- <p className="text-[10px] text-gray-500 leading-snug mt-1 flex flex-wrap items-center gap-x-2">+ <p className={`${HINT_CLASS} flex flex-wrap items-center gap-x-2`}>{card && <FactLink href={card}>Model card</FactLink>}{license && <FactLink href={license.url}>{license.name}</FactLink>}</p>@@ -79,6 +87,7 @@ export default function TextEncoderPicker({status={status}onDownload={() => onDownload?.(selected.id)}onCancel={onCancel}+ queued={queued}estimateLabel={selected.sizeBytes ? `~${formatBytes(selected.sizeBytes)}` : undefined}/>)}diff --git a/client/src/components/videoGen/TextEncoderPicker.test.jsx b/client/src/components/videoGen/TextEncoderPicker.test.jsxindex 2989df2a44..460465ea0d 100644--- a/client/src/components/videoGen/TextEncoderPicker.test.jsx+++ b/client/src/components/videoGen/TextEncoderPicker.test.jsx@@ -122,6 +122,36 @@ describe('TextEncoderPicker', () => {.toHaveAttribute('href', HERETIC.disclosure.weightsLicense.url);});+ // Selecting a substitute commits its pull, but the single download lane may+ // already be busy. The badge then says "queued" INSTEAD of offering Download —+ // a button here would hijack the lane the queued pull is waiting for.+ it('replaces the Download button with a queued notice, not a second control', () => {+ const { rerender } = render(+ <TextEncoderPicker+ options={OPTIONS}+ value="heretic-bf16"+ onChange={vi.fn()}+ status={{ id: 'heretic-bf16', repo: 'org/heretic', cached: false, sizeBytes: 0 }}+ queued+ />,+ );+ expect(screen.getByText(/starts when the current download finishes/i)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Download/ })).not.toBeInTheDocument();++ // Once this option's own pull is running, the badge carries the progress —+ // a "queued" line alongside it would contradict it.+ rerender(+ <TextEncoderPicker+ options={OPTIONS}+ value="heretic-bf16"+ onChange={vi.fn()}+ status={{ id: 'heretic-bf16', repo: 'org/heretic', cached: false, sizeBytes: 0, downloading: true }}+ queued+ />,+ );+ expect(screen.queryByText(/starts when the current download finishes/i)).not.toBeInTheDocument();+ });+it('disables the select while a render is in flight', () => {render(<TextEncoderPicker options={OPTIONS} value="stock" onChange={vi.fn()} disabled />);expect(screen.getByLabelText('Text encoder')).toBeDisabled();diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex f51131730d..26bd28ae3a 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -39,7 +39,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. || `useSseJobSlot` | Generic single-slot SSE job: `pending`/`job` state, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, percent, stage, context, start, cancel }`; pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. || `useInstallStream` | BYO-runtime install-log EventSource lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes). Don't re-roll the EventSource teardown/onComplete-ref dance. |-| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. |+| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. `start(id)` commands a pull; `startWhenIdle(id)` requests one — it waits for the cache verdict, skips an already-resident repo, and queues behind whatever owns the single EventSource lane (`queuedModelId` while it waits, falsy id to retract). | Surfacing "Available" vs "Download" badge inline in the gen form; `startWhenIdle` for a picker where choosing an option IS the request for its weights. || `useAgyModels` | Live `agy models` probe (the AGENT models `--model` accepts) with `models`/`error`/`loading`/`refresh`; opt-in via an `enabled` flag so it never spawns for a disabled backend. | Any Agy model picker — the Settings default or the per-render override. Don't hardcode a model list: agy exits non-zero on an id outside this catalog. || `useSpritePendingRenders` | Sprite-workflow in-flight render map: queue rehydrate + 4s poll keyed by a media-job tag field, `'submitting'` double-render guard, 404-only drop, deferred `onChanged` sweeps. | A sprite workflow tracking `queued/running` media jobs by tag (reference renders, walk videos, phase-4 publish) — don't re-roll the rehydrate/poll dance. || `useSpriteRecordCrud` | Rename/delete state machine for one sprite record: `view`/`rename`/`confirm` mode, name draft, busy/inline-error, silent PATCH/DELETE. | A surface that renames or deletes a sprite record (the Library catalog card, the detail header) — share this so both stay in lock-step. |diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.jsindex 2338be31ed..6d0e922501 100644--- a/client/src/hooks/useModelDownloadStatus.js+++ b/client/src/hooks/useModelDownloadStatus.js@@ -67,6 +67,12 @@ export const buildDownloadUrl = (kind, modelId, force = false) => {// opens an EventSource against the download endpoint. When the stream// emits a terminal frame we automatically refetch /models/status so the// badge flips to "Available" without the caller wiring that up.+//+// `startWhenIdle(modelId)` is the same pull expressed as an intent rather than+// a command — for a picker where choosing an option IS the request for its+// weights. It waits for the cache verdict, skips an already-resident repo, and+// queues behind whatever owns the lane; `queuedModelId` is what a badge renders+// while it waits.export function useModelDownloadStatus({ kind = 'image' } = {}) {const [statuses, setStatuses] = useState(null);const [extra, setExtra] = useState({}); // video: { textEncoder: {...} }@@ -245,6 +251,29 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {return findEntry(modelId);}, [findEntry, activeModelId, activeStatus]);+ // "Download this unless it's already here" — the shape a picker needs when+ // choosing an option IS the request to fetch its weights, with no separate+ // Download click. Lives here rather than in the caller because both things it+ // has to wait on are this hook's: the cache verdict (`statuses` may still be+ // loading, and starting on an unknown verdict would re-pull a resident+ // multi-GB repo) and the single EventSource lane (`start` would otherwise+ // hijack a download already in flight).+ //+ // Passing a falsy id clears a queued intent, so a caller whose selection moved+ // on — to an option with no download of its own, or to another id, which+ // replaces the queue — doesn't strand a pull nobody is waiting for any more.+ const [queuedModelId, setQueuedModelId] = useState(null);+ const startWhenIdle = useCallback((modelId) => { setQueuedModelId(modelId || null); }, []);+ useEffect(() => {+ if (!queuedModelId || loading || activeModelId) return;+ const entry = findEntry(queuedModelId);+ // Cleared either way: with the verdict in, the question is answered. A+ // missing entry means the id is in no downloadable collection, so there is+ // nothing to start and nothing to keep waiting for.+ setQueuedModelId(null);+ if (entry?.cached === false) start(queuedModelId);+ }, [queuedModelId, loading, activeModelId, findEntry, start]);+return {statuses,extra,@@ -252,6 +281,8 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {statusError,refresh: fetchStatuses,start,+ startWhenIdle,+ queuedModelId,cancel,verify,verifying,diff --git a/client/src/hooks/useModelDownloadStatus.test.js b/client/src/hooks/useModelDownloadStatus.test.jsindex 356e429d38..2f22f67cc9 100644--- a/client/src/hooks/useModelDownloadStatus.test.js+++ b/client/src/hooks/useModelDownloadStatus.test.js@@ -1,7 +1,35 @@-import { describe, expect, it } from 'vitest';-import {- buildDownloadUrl, TEXT_ENCODER_DOWNLOAD_ID, textEncoderDownloadId,-} from './useModelDownloadStatus.js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, renderHook, waitFor } from '@testing-library/react';++// The hook's own SSE lifecycle is covered by useSseProgress's suite; here it+// only has to be inert and observable, so the tests can assert which download+// owns the lane without opening a real EventSource.+const sseState = vi.hoisted(() => ({ url: null }));+vi.mock('./useSseProgress.js', () => ({+ useSseProgress: (url) => {+ sseState.url = url;+ return { latest: null, closed: false, close: vi.fn() };+ },+}));+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),+}));+vi.mock('../services/apiImageVideo.js', () => ({+ getImageModelStatuses: vi.fn(async () => []),+ getVideoModelStatuses: vi.fn(async () => ({ models: [], textEncoder: null, textEncoderOptions: [], icLoras: [] })),+ verifyImageModels: vi.fn(),+ verifyVideoModels: vi.fn(),+ repairImageModel: vi.fn(),+ repairVideoModel: vi.fn(),+ repairTextEncoder: vi.fn(),+ repairTextEncoderOption: vi.fn(),+ repairIcLora: vi.fn(),+}));++const { getVideoModelStatuses } = await import('../services/apiImageVideo.js');+const {+ buildDownloadUrl, TEXT_ENCODER_DOWNLOAD_ID, textEncoderDownloadId, useModelDownloadStatus,+} = await import('./useModelDownloadStatus.js');describe('buildDownloadUrl', () => {it('builds a plain model download URL', () => {@@ -48,3 +76,84 @@ describe('buildDownloadUrl', () => {);});});++// `startWhenIdle` — the "choosing an option IS the request for its weights"+// entry point. Everything it has to wait on belongs to this hook (the cache+// verdict and the single EventSource lane), which is why the policy lives here+// rather than in each picker that wants auto-download-on-select.+describe('startWhenIdle', () => {+ const ENCODER_ID = textEncoderDownloadId('heretic-bf16');++ const mountHook = async (encoderStatus, { onStatuses } = {}) => {+ getVideoModelStatuses.mockImplementation(async () => {+ onStatuses?.();+ return { models: [], textEncoder: null, textEncoderOptions: [encoderStatus], icLoras: [] };+ });+ const view = renderHook(() => useModelDownloadStatus({ kind: 'video' }));+ await waitFor(() => expect(view.result.current.loading).toBe(false));+ return view;+ };++ beforeEach(() => {+ getVideoModelStatuses.mockReset();+ sseState.url = null;+ });++ it('starts the pull for an id that is not cached', async () => {+ const { result } = await mountHook({ id: 'heretic-bf16', cached: false });+ act(() => { result.current.startWhenIdle(ENCODER_ID); });+ await waitFor(() => expect(result.current.activeModelId).toBe(ENCODER_ID));+ expect(result.current.queuedModelId).toBeNull();+ });++ // The whole point of the "if missing" half: re-pulling a resident multi-GB+ // repo because a picker was clicked is the failure this replaces.+ it('starts nothing for an id that is already cached', async () => {+ const { result } = await mountHook({ id: 'heretic-bf16', cached: true });+ act(() => { result.current.startWhenIdle(ENCODER_ID); });+ await waitFor(() => expect(result.current.queuedModelId).toBeNull());+ expect(result.current.activeModelId).toBeNull();+ });++ // One EventSource lane: starting here would abort the pull already on it.+ it('queues behind a download already in flight and starts when it frees up', async () => {+ const { result } = await mountHook({ id: 'heretic-bf16', cached: false });+ act(() => { result.current.start('some-model'); });+ act(() => { result.current.startWhenIdle(ENCODER_ID); });++ expect(result.current.activeModelId).toBe('some-model');+ expect(result.current.queuedModelId).toBe(ENCODER_ID);++ act(() => { result.current.cancel(); });+ await waitFor(() => expect(result.current.activeModelId).toBe(ENCODER_ID));+ });++ // The verdict usually hasn't landed at click time — the intent has to survive+ // until it does rather than resolve against an empty status list.+ it('holds the intent until the cache verdict lands', async () => {+ let release;+ const gate = new Promise((resolve) => { release = resolve; });+ getVideoModelStatuses.mockImplementation(async () => {+ await gate;+ return { models: [], textEncoder: null, textEncoderOptions: [{ id: 'heretic-bf16', cached: false }], icLoras: [] };+ });+ const { result } = renderHook(() => useModelDownloadStatus({ kind: 'video' }));+ act(() => { result.current.startWhenIdle(ENCODER_ID); });+ expect(result.current.activeModelId).toBeNull();++ await act(async () => { release(); });+ await waitFor(() => expect(result.current.activeModelId).toBe(ENCODER_ID));+ });++ it('clears a queued intent when the caller passes nothing', async () => {+ const { result } = await mountHook({ id: 'heretic-bf16', cached: false });+ act(() => { result.current.start('some-model'); });+ act(() => { result.current.startWhenIdle(ENCODER_ID); });+ expect(result.current.queuedModelId).toBe(ENCODER_ID);++ act(() => { result.current.startWhenIdle(null); });+ expect(result.current.queuedModelId).toBeNull();+ act(() => { result.current.cancel(); });+ await waitFor(() => expect(result.current.activeModelId).toBeNull());+ });+});diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex dbf61ad281..12ca4b1efd 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -446,6 +446,21 @@ export default function VideoGen() {const textEncoderOptionStatus = textEncoderOptionDownloadId? modelDownload.getStatus(textEncoderOptionDownloadId): null;+ // Choosing a substitute IS the request for its weights: it is unusable until+ // resident and Generate is gated on it either way, so `startWhenIdle` turns+ // the pick into the pull (it owns waiting for the cache verdict, skipping an+ // already-downloaded one, and queueing behind an active download).+ //+ // Wired to the PICKER's onChange alone, deliberately — a Remix, a resumed+ // render, and the snap-to-stock on a model change all reach `setTextEncoderId`+ // too, and a multi-GB pull must follow a click the user just made rather than+ // a state restore. Passing null for a built-in option clears any queued pull.+ const { startWhenIdle: startEncoderWhenIdle } = modelDownload;+ const handleTextEncoderChange = useCallback((id) => {+ setTextEncoderId(id);+ const option = textEncoderOptions.find((entry) => entry.id === id);+ startEncoderWhenIdle(option && !option.builtIn ? textEncoderDownloadId(id) : null);+ }, [setTextEncoderId, textEncoderOptions, startEncoderWhenIdle]);const icWeightStatus = icSpec ? modelDownload.getStatus(icSpec.mode) : null;const modelWeightsBlocked = !isGrok&& (statusLoading || !modelId || !currentModel || modelDownload.loading@@ -1062,9 +1077,10 @@ export default function VideoGen() {<TextEncoderPickeroptions={textEncoderOptions}value={textEncoderId}- onChange={setTextEncoderId}+ onChange={handleTextEncoderChange}status={textEncoderOptionStatus}- onDownload={(id) => modelDownload.start(textEncoderDownloadId(id))}+ onDownload={() => modelDownload.start(textEncoderOptionDownloadId)}+ queued={modelDownload.queuedModelId === textEncoderOptionDownloadId}onCancel={modelDownload.cancel}disabled={generating}/>diff --git a/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx b/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsxnew file mode 100644index 0000000000..f4dd6ae2f2--- /dev/null+++ b/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx@@ -0,0 +1,240 @@+/**+ * Picking a substitute prompt conditioner starts its download right there.+ *+ * The conditioner is unusable until it is resident and Generate is gated on it+ * either way, so the separate Download click sat between the choice and the only+ * thing that could follow it. What this file pins down is the boundary: an+ * EXPLICIT selection pulls, and a state restore (a resumed render, a Remix, the+ * snap-to-stock on a model change) never does — those all reach the same+ * setTextEncoderId, and a ~57 GB pull must follow a click, not a restore.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const TERMS_ID = 'minimax-h3-license-v1';+const MODEL = {+ id: 'h3-one',+ name: 'MiniMax h3-one',+ repo: 'example-org/h3-one',+ revision: '1111111111111111111111111111111111111111',+ runtime: 'minimax_h3',+ supportedModes: ['text'],+ defaultFrames: 124,+ frameOptions: [124, 141],+ fpsOptions: [24],+ steps: 8,+ guidance: 0,+ samplerLocked: true,+ supportsNegativePrompt: false,+ supportsTiling: false,+ supportsDisableAudio: false,+ textEncoderOptions: [+ { id: 'stock', label: 'Stock', description: 'Ships with the model.', builtIn: true },+ { id: 'huihui-abliterated', label: 'Huihui abliterated', description: 'Abliterated.', builtIn: false, repo: 'example-org/abliterated', sizeBytes: 56962931632 },+ ],+ termsGate: {+ id: TERMS_ID,+ title: 'Terms for h3-one',+ summary: 'This model is available only in its applicable territory.',+ acknowledgement: `I am eligible and accept ${TERMS_ID}.`,+ licenseUrl: 'https://example.com/license',+ },+};++const state = vi.hoisted(() => ({+ start: vi.fn(),+ startWhenIdle: vi.fn(),+ downloadStatus: { downloading: false, loading: false, cached: false },+ queued: null,+ history: [],+ activeJob: null,+ generateVideo: vi.fn(),+ attach: vi.fn(),+ enqueue: vi.fn(),+ eventSourceRef: { current: null },+}));++vi.mock('../services/apiImageVideo.js', () => ({+ getVideoModelTerms: vi.fn(async () => ({ accepted: [TERMS_ID] })),+ setVideoModelTerms: vi.fn(async () => ({ accepted: [TERMS_ID] })),+}));++vi.mock('../services/api', () => ({+ getVideoGenStatus: vi.fn(async () => ({+ connected: true,+ pythonPath: '/opt/example/python3',+ defaultModel: 'h3-one',+ models: [MODEL],+ byovRuntimes: [],+ systemMemoryGb: 128,+ backendDisclosures: [],+ })),+ generateVideo: (...args) => state.generateVideo(...args),+ cancelVideoGen: vi.fn(async () => ({})),+ listVideoHistory: vi.fn(async () => state.history),+ deleteVideoHistoryItem: vi.fn(async () => ({})),+ setVideoHidden: vi.fn(async () => ({})),+ extractLastFrame: vi.fn(async () => ({})),+ upscaleVideo: vi.fn(async () => ({})),+ listImageGallery: vi.fn(async () => []),+ patchSettingsSlice: vi.fn(async () => ({})),+ getActiveVideoJob: vi.fn(async () => ({ activeJob: state.activeJob })),+ getSettings: vi.fn(async () => ({ imageGen: { grok: { enabled: false } } })),+ getVideoGenRuntimeStatus: vi.fn(async () => ({ installed: true, ready: true, current: true })),+ listLorasFull: vi.fn(async () => []),+ getProviders: vi.fn(async () => ({ providers: [] })),+ getVisionModels: vi.fn(async () => ({ models: [] })),+}));++vi.mock('../hooks/useModelDownloadStatus', () => ({+ TEXT_ENCODER_DOWNLOAD_ID: '__text_encoder__',+ textEncoderDownloadId: (id) => `__text_encoder_option__:${id}`,+ useModelDownloadStatus: () => ({+ extra: {},+ loading: state.downloadStatus.loading,+ statusError: null,+ activeModelId: null,+ progress: null,+ lastError: null,+ downloading: state.downloadStatus.downloading,+ repairing: false,+ getStatus: (id) => (String(id).startsWith('__text_encoder_option__:')+ ? { id: 'huihui-abliterated', repo: 'example-org/abliterated', cached: state.downloadStatus.cached, sizeBytes: 0 }+ : { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 }),+ start: state.start,+ startWhenIdle: state.startWhenIdle,+ queuedModelId: state.queued,+ cancel: vi.fn(),+ repair: vi.fn(),+ refresh: vi.fn(),+ }),+}));++vi.mock('../hooks/useMediaJobSse', () => ({+ useMediaJobSse: () => ({ attach: state.attach, eventSourceRef: state.eventSourceRef }),+}));+vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: vi.fn() }));+vi.mock('../hooks/useMediaAnnotations', () => ({+ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),+}));+vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));+vi.mock('../hooks/useVideoGenQueue.js', () => ({+ useVideoGenQueue: () => ({+ queue: [],+ enqueue: state.enqueue,+ removeFromQueue: vi.fn(),+ clearFinishedQueue: vi.fn(),+ cancelRunning: vi.fn(),+ }),+}));+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),+}));++vi.mock('../components/media/PromptEnhancer', () => ({+ default: ({ disabled }) => (+ <div data-testid="prompt-enhancer" data-disabled={disabled ? '1' : '0'}>Enhance with AI</div>+ ),+}));+vi.mock('../components/media/PromptFromMedia', () => ({+ default: ({ disabled }) => (+ <div data-testid="prompt-from-media" data-disabled={disabled ? '1' : '0'}>Prompt from media</div>+ ),+}));++vi.mock('../components/Drawer', () => ({ default: () => null }));+vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));+vi.mock('../components/settings/LocalSetupPanel', () => ({ default: () => null }));+vi.mock('../components/install/RuntimeInstallModal', () => ({ default: () => null }));+vi.mock('../components/videoGen/FramePanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/KeyframePanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/AudioPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/ExtendPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/IcLoraPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/AdvancedParamsPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => null }));+vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));+vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));+vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));+vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));+vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));++const { default: VideoGen } = await import('./VideoGen.jsx');++const SUBSTITUTE_ID = 'huihui-abliterated';+const DOWNLOAD_ID = `__text_encoder_option__:${SUBSTITUTE_ID}`;++const mountPage = async () => {+ await act(async () => {+ render(<MemoryRouter initialEntries={['/media/video']}><VideoGen /></MemoryRouter>);+ });+ return screen.findByLabelText('Text encoder');+};++describe('VideoGen substitute text-encoder auto-download', () => {+ beforeEach(() => {+ state.start.mockReset();+ state.startWhenIdle.mockReset();+ state.queued = null;+ state.downloadStatus = { downloading: false, loading: false, cached: false };+ state.history = [];+ state.activeJob = null;+ });++ it('requests the pull when a substitute is selected', async () => {+ const select = await mountPage();+ // Arriving on the page with stock selected requests nothing.+ expect(state.startWhenIdle).not.toHaveBeenCalled();++ await act(async () => {+ fireEvent.change(select, { target: { value: SUBSTITUTE_ID } });+ });+ await waitFor(() => expect(state.startWhenIdle).toHaveBeenCalledWith(DOWNLOAD_ID));+ // The commanding `start` is NOT used here — it would hijack the lane and+ // skip the cache check that makes selecting a resident encoder free.+ expect(state.start).not.toHaveBeenCalled();+ });++ // The built-in conditioner ships inside the model's weights, so there is+ // nothing to fetch — and switching to it must retract a pull queued a moment+ // earlier for the substitute the user just moved off.+ it('clears the request when the selection goes back to stock', async () => {+ const select = await mountPage();+ await act(async () => {+ fireEvent.change(select, { target: { value: SUBSTITUTE_ID } });+ });+ await act(async () => {+ fireEvent.change(select, { target: { value: 'stock' } });+ });+ expect(state.startWhenIdle).toHaveBeenLastCalledWith(null);+ });++ it('surfaces the queued state on the selected substitute', async () => {+ state.queued = DOWNLOAD_ID;+ const select = await mountPage();+ await act(async () => {+ fireEvent.change(select, { target: { value: SUBSTITUTE_ID } });+ });+ await waitFor(() => expect(screen.getByText(/starts when the current download finishes/i)).toBeInTheDocument());+ });++ // Reloading onto an in-flight render replays its conditioner into the form.+ // That is a state restore, not a choice — and the weights are demonstrably+ // already resident, since the render is running on them. Remix (applyRemix)+ // and the model-change snap reach setTextEncoderId the same way, which is why+ // only the picker's own onChange requests a pull.+ it('requests nothing when a resumed render restores its conditioner', async () => {+ state.activeJob = {+ jobId: 'job-1',+ status: 'running',+ params: { modelId: MODEL.id, prompt: 'a fox watches the rain', mode: 'text', textEncoderId: SUBSTITUTE_ID },+ };+ await mountPage();+ await waitFor(() => expect(screen.getByLabelText('Text encoder')).toHaveValue(SUBSTITUTE_ID));+ expect(state.startWhenIdle).not.toHaveBeenCalled();+ expect(state.start).not.toHaveBeenCalled();+ });+});diff --git a/docs/features/video-text-encoders.md b/docs/features/video-text-encoders.mdindex a5f0700500..4cef4dcc3a 100644--- a/docs/features/video-text-encoders.md+++ b/docs/features/video-text-encoders.md@@ -27,24 +27,42 @@ schedule, same joint video+audio output.|--------|-----------|----------------|| **Stock** | The conditioner inside `MiniMaxAI/MiniMax-H3`'s `FL2VA/text_encoder/` | none — already downloaded with the model || **Ultra-Heretic uncensored** | `ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot`, bf16 variant — Qwen3-VL-32B-Instruct abliterated with Heretic v1.2.0 (attention-targeted), repackaged for H3 | ~48 GB, one pinned file |+| **Huihui abliterated** | `huihui-ai/Huihui-Qwen3-VL-32B-Instruct-abliterated` — the same base model abliterated by a different lab and a different method, so it reads prompts differently again | ~57 GB, 12 of the repo's 14 pinned shards |-Only the **bf16** file is usable here. The repo's INT8 ConvRot and NVFP4/AWQ-variants use ComfyUI's own quantization (learned row-wise rotation matrices,-group size 256) that the MLX loader cannot dequantize, and the `50_63`+For Ultra-Heretic, only the **bf16** file is usable. The repo's INT8 ConvRot and+NVFP4/AWQ variants use ComfyUI's own quantization (learned row-wise rotation+matrices, group size 256) that the MLX loader cannot dequantize, and the `50_63`generation tails belong to ComfyUI's H3 Prompt Enhancer node — a feature PortOSdoes not implement. That's why the download is scoped to one file rather than arepo snapshot: the full repo is ~130 GB for ~48 GB of usable weights.+Huihui's is an upstream checkpoint rather than a repack, so it arrives as+safetensors shards. Two of the fourteen hold only language layers 50–63 —+parameters the loader never builds — so they aren't pulled: 12 shards, ~57 GB+instead of ~67 GB. Because it's the upstream Hugging Face namespace and it ships+its own final norm, it needs neither the key remap nor the synthesized norm the+repack does.+## Using it1. Pick **MiniMax H3** on `/media/video`. A **Text encoder** select appears underthe model's download badge.-2. Choose a substitute. If it isn't downloaded, a Download button appears and- **Generate stays disabled** until it's resident — the same gate the model- weights and IC-LoRA weights use.+2. Choose a substitute. **Selecting one starts its download** — each option's+ size is in its own line of the select, so the cost is visible before the+ click. **Generate stays disabled** until it's resident, the same gate the+ model weights and IC-LoRA weights use, and the badge below the select carries+ the progress, the cancel and the retry.3. Render. The chosen conditioner is recorded in history, so **Remix** reproducesthe render faithfully; a stock render records nothing and remixes as stock.+Only an explicit pick starts a download. Restoring a conditioner — a Remix, a+resumed render replayed after a reload — never does; those weights are either+already present or one click away on the badge.++If another download already holds the progress stream, the pick queues behind it+(the badge reads "Queued — starts when the current download finishes") rather+than aborting it.+Switching to a model whose runtime can't load your selection snaps the pickerback to Stock rather than leaving it on a value the server would reject.@@ -63,6 +81,11 @@ then loads it with no argument it doesn't already take. The shim lives outsidethe pinned checkout deliberately: anything written inside would read as untrackedin the pin verification.+The loader globs `*.safetensors` in that directory, so a multi-shard substitute+is just several links instead of one — no index file, no loader change. It also+means the shards that weren't pulled are simply absent from the glob, which is+exactly right: their tensors are ones the loader never asks for.+The substitute ships weights only. Its config, tokenizer and processor come fromupstream — correct, because abliteration changes weights, not the vocabulary orthe vision geometry.@@ -90,6 +113,12 @@ Verified against the real pinned runtime: the 902 tensors in the bf16 file plusthe synthesized norm map onto exactly the 903 parameters the loader builds — 552language, 351 vision, zero missing, zero extra, zero skipped.+Neither adapter runs for the Huihui entry: its keys are already the namespace the+loader matches, and its `model.language_model.norm.weight` is real rather than+synthesized. Its 12 pinned shards carry the same 903 parameters (the other 155+tensors in the repo are layers 50–63 and `lm_head`, which the loader skips+exactly as it skips them in the stock checkpoint).+## Adding another conditionerAdd an entry to `TEXT_ENCODERS_BY_RUNTIME` in@@ -104,7 +133,7 @@ integrity scan and the render path all read from that table.description: '…',repo: 'org/repo',revision: '<40-char sha>', // pinned, never a branch- file: 'weights.safetensors', // one file; never a repo snapshot+ files: ['weights.safetensors'], // explicit list; never a repo snapshotkeyPrefixMap: { 'model.': 'model.language_model.', 'visual.': 'model.visual.' },finalNormKey: 'model.norm.weight', // omit if the checkpoint ships its own normsizeBytes: 12345, // exact published size — the UI formats this@@ -116,10 +145,35 @@ These live in code rather than `data/media-models.json` on purpose: a staleregistry file must never be able to name a checkpoint this build's runner has nokey map for.-To confirm a candidate is really a drop-in before downloading tens of GB, read-its safetensors header with an HTTP range request, apply the prefix map, and diff-the result against the parameter set the loader builds. That's how the shipped-entry was validated.+### The candidate has to be Qwen3-VL-32B++The shim reuses **upstream's** `config.json`, tokenizer and processor, so a+substitute has to match them: `hidden_size` 5120, 64 language layers, `head_dim`+128, `vocab_size` 151936, `intermediate_size` 25600, and the same 27-block /+1152-wide vision tower with deepstack indices `[8, 16, 24]`. Abliteration changes+weights, not the vocabulary or the vision geometry, which is exactly why an+abliterated Qwen3-VL-32B drops in.++A *different Qwen generation* does not, however close the conditioning width+looks. Qwen3.5-27B (`model_type: qwen3_5`, e.g.+`Blackfrost-AI/Qwen3.8-27B-ABLITERATED-BF16`) also reports `hidden_size: 5120`,+but 48 of its 64 layers are Gated-DeltaNet `linear_attn` blocks with parameters+(`in_proj_qkv`, `conv1d`, `A_log`, `dt_bias`) that have no counterpart in the+module tree this loader builds, its vocabulary is 248320 tokens against the+stock tokenizer's 151936, and its `head_dim` is 256. No key remap can bridge+that — it needs a different model implementation and a different tokenizer, not+a registry entry.++### Validating one before you pull tens of GB++Fetch the candidate's `model.safetensors.index.json` (or read a single file's+safetensors header with an HTTP range request), apply the prefix map, and diff+the result against the parameter set the loader builds — 903 tensors: embed ++`norm` + language layers 0–49, plus the full vision tower. Diff its+`config.json` against `FL2VA/text_encoder/config.json` at the same time. That's+how both shipped entries were validated; for the Huihui entry the index also+identified which shards carry no needed tensor, which is what the `files` list+leaves out.## Cost note@@ -134,3 +188,4 @@ grows.- `scripts/generate_minimax_h3.py` — the shim builder and key remap- `server/services/videoGen/local.js` — cache resolution and argv- `client/src/components/videoGen/TextEncoderPicker.jsx` — the control+- `client/src/hooks/useModelDownloadStatus.js` — `startWhenIdle`, the select-starts-the-pull mechanism (generic: any gated-weight picker can adopt it)