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

Show a loading Model picker on Video Gen and cache the status payload

[._.]/ Adam Eivy9e4db5d6ccd9
diff --git a/client/src/components/ModelSelect.jsx b/client/src/components/ModelSelect.jsx
index 2948f7d510..a88aa48e90 100644
--- a/client/src/components/ModelSelect.jsx
+++ b/client/src/components/ModelSelect.jsx
@@ -9,6 +9,12 @@
// it for "optional model / fall back to the server default" pickers (mirrors
// ProviderModelSelector's `emptyModelOption`). `ariaLabel` / `title` let an
// inline picker with no visible <label> stay accessible.
+//
+// `loading` renders the picker as a disabled placeholder ("Loading models…")
+// instead of an empty select. Model lists come from a probe that can take a
+// second or two, and a caller that hides the whole field until it lands makes
+// the form jump when it does — so hold the field's place and say why it's
+// empty. `loadingLabel` customizes the placeholder text.
const defaultGetLabel = (m) => m.name;
export default function ModelSelect({
models,
@@ -21,7 +27,25 @@ export default function ModelSelect({
emptyOption,
ariaLabel,
title,
+ loading = false,
+ loadingLabel = 'Loading models…',
}) {
+ if (loading) {
+ return (
+ <select
+ id={id}
+ value=""
+ disabled
+ aria-busy="true"
+ aria-label={ariaLabel}
+ title={title}
+ className={className}
+ onChange={onChange}
+ >
+ <option value="">{loadingLabel}</option>
+ </select>
+ );
+ }
const active = models.filter((m) => !m.deprecated);
const legacy = models.filter((m) => m.deprecated);
return (
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 471a99dbb1..6f41f39360 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -80,6 +80,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. `isDeliveryVideoModel(model, models)` is the other end of the same graph — true when some entry names `model` as its `finishModelId`, which is what makes a delivery render always decode on the full decoder (#5423). Mirrors `finishTargetForModel` / `isDeliveryVideoModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |
| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `selectVideoMemoryProfile(model, systemMemoryGb)` + `VIDEO_MEMORY_RESERVE_GB` (#5420 — which declared weight-placement profile this machine can actually hold, out of the `memoryProfiles` the server decorates onto the entry; the floors ride on the model so only the reserve is mirrored, and an unmeasured `systemMemoryGb` returns a `null` usable figure rather than reading as a box that is too small), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v uses the shared audio-runtime capability; IC remix remains LTX-only). Speed profiles (#4875) mirror the conditioner shape: `DEFAULT_SPEED_PROFILE_ID` (must equal `SPEED_PROFILE_DEFAULT_ID` in `server/lib/videoSpeedProfiles.js` — absence and `'quality'` are the same request), `isDefaultSpeedProfileId()` mirrors the server's absence-is-the-default rule, `speedProfilesForModel()` reads the server-decorated `speedProfiles` off the entry, `speedProfilesForMode(model, mode)` applies the SAME mode gate the server's `speedProfileDeclineReason` does (so a profile the server would decline is never offered, nor allowed to lock the dials), `normalizeSpeedProfileForModel()` snaps a selection onto what a just-switched model declares (mode-independent, so switching to fflf hides the picker without rewriting the choice), `speedProfileIdFromRecord()` reads one back out of a history entry / resumed job, `selectedSpeedProfile(id, model, mode)` resolves the profile actually driving the render — what the picker shows and what disables Steps+CFG — and `videoChainChunkModes({ model, mode, chaining, contextFrames, hasSourceImage })` derives the modes a CHAINED request’s chunks will run in (chunk 0 the request’s, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), mirroring `generateChainedVideo`’s dispatch and `resolveContinuityStrategy`; `resolveContextFramesForDisplay()` is the absent/invalid→`DEFAULT_CONTEXT_FRAMES` half of `resolveContextFrames` that gate depends on. All pinned by `server/lib/videoSpeedProfiles.parity.test.js`. Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |
| `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |
+| `videoGenStatusCache.js` | Session-scoped cache of the `GET /api/video-gen/status` payload (`readCachedVideoGenStatus` / `writeCachedVideoGenStatus` / `VIDEO_GEN_STATUS_CACHE_KEY`). The probe shells out to python and rebuilds the hardware-aware model list on every call, so the Video Gen Model picker would otherwise have nothing to render for a second or two on each page load. The read comes back marked `stale: true` and is trusted only for the model list and the model-shaping numbers (`defaultModel`, `systemMemoryGb`, pixel budget) — connectivity claims stay keyed on the live probe, so a python interpreter the user just fixed or broke is never reported from a stored answer. |
| `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. |
| `videoReferenceModes.js` | Mirror of `server/lib/videoReferenceModes.js` (parity enforced by `server/lib/videoReferenceModes.mirror.test.js`) — the i2v reference-mode contract: `I2V_REFERENCE_MODES`, `I2V_REFERENCE_MODE_OPTIONS` (label + the promise sentence `AdvancedParamsPanel` and the source-frame note print), `runtimeSupportsI2vReferenceMode` (gates which options the picker offers), `resolveI2vReferenceStrength` (the effective strength the panel displays), and `i2vReferenceModeViolation` for pre-submit feedback. |
| `videoStagePreview.js` | VideoGen main-stage preview resolver (#4588). `resolveVideoStagePreview({ generating, width, height, result, extendSource, sourceImageFile/Url, lastImageFile/Url, keyframes })` → `{ kind: 'loop'|'still'|'result'|'empty', src, poster, label, aspectRatio }` — conditioning media while a render runs and the finished clip once it lands; transient runner frames are intentionally excluded. Plus `videoStageAspectRatio()` (a NUMBER for an inline `aspect-ratio` style — a computed Tailwind `aspect-[w/h]` class never reaches the JIT build; `null` means unknown geometry, not 16:9) and `videoStageSignature()` for the hold/return guard in `components/videoGen/LiveVideoStage.jsx`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 5b174c7b4f..a0a62b903e 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -60,6 +60,7 @@ export * from './slashdoCatalog.js';
export * from './videoFinish.js';
export * from './videoGenParams.js';
export * from './videoGenResolutions.js';
+export * from './videoGenStatusCache.js';
export * from './videoGenSubmission.js';
export * from './videoReferenceModes.js';
export * from './videoStagePreview.js';
diff --git a/client/src/lib/videoGenStatusCache.js b/client/src/lib/videoGenStatusCache.js
new file mode 100644
index 0000000000..70e0828b6e
--- /dev/null
+++ b/client/src/lib/videoGenStatusCache.js
@@ -0,0 +1,42 @@
+/**
+ * Session-scoped cache of the `GET /api/video-gen/status` payload.
+ *
+ * That probe shells out to python and rebuilds the hardware-aware model list on
+ * every call, so a cold Video Gen page load leaves the Model picker with nothing
+ * to render for a second or two. Caching the last payload lets the picker paint
+ * from the previous answer while the live probe revalidates behind it.
+ *
+ * The cached copy comes back marked `stale: true`, and callers must honour that:
+ * it is trusted only for the model list and the model-shaping numbers
+ * (`defaultModel`, `systemMemoryGb`, the pixel budget). Connectivity claims —
+ * `connected`, `missingPackages`, the "install missing packages" banner — stay
+ * keyed on the live probe, because a python interpreter the user just fixed (or
+ * just broke) must never be reported from a stored answer.
+ *
+ * Session, not local: the model registry and the python environment both move
+ * with an upgrade or an install, and a payload kept for weeks would outlive
+ * both.
+ */
+import { safeReadJsonSession, safeWriteJsonSession } from './safeStorage.js';
+
+// Bump the suffix when the shape the page reads out of this changes, so an
+// older tab's entry is ignored rather than half-read.
+export const VIDEO_GEN_STATUS_CACHE_KEY = 'portos.videoGenStatus.v1';
+
+// Returns the cached payload with `stale: true`, or null when nothing usable is
+// stored. A payload with no `models` array is worthless here — the whole point
+// is painting the picker — so it reads as absent.
+export const readCachedVideoGenStatus = () => {
+ const cached = safeReadJsonSession(VIDEO_GEN_STATUS_CACHE_KEY);
+ if (!cached || typeof cached !== 'object' || !Array.isArray(cached.models)) return null;
+ return { ...cached, stale: true };
+};
+
+// Store a freshly fetched payload. Never persists the `stale` marker: what is
+// written here is by definition the live answer, and it is read back as stale.
+export const writeCachedVideoGenStatus = (status) => {
+ if (!status || typeof status !== 'object' || !Array.isArray(status.models)) return;
+ // `stale: undefined` is dropped by JSON.stringify, so a payload that somehow
+ // round-tripped through the reader can't be stored as if it were fresh.
+ safeWriteJsonSession(VIDEO_GEN_STATUS_CACHE_KEY, { ...status, stale: undefined });
+};
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index d5b07ad26a..2a2f23c802 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -99,6 +99,7 @@ import ResolutionField from '../components/media/ResolutionField';
import { VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, IC_LORA_MODES } from '../lib/videoGenParams.js';
import { finishTargetForRecord, isDeliveryVideoModel } from '../lib/videoFinish.js';
import { peerModelRequiresInput } from '../lib/federatedMediaReadiness.js';
+import { readCachedVideoGenStatus, writeCachedVideoGenStatus } from '../lib/videoGenStatusCache.js';
const MODES = [
{ id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },
{ id: 'image', label: 'Image', icon: ImageIcon, desc: 'Image-to-video (start frame)' },
@@ -121,7 +122,12 @@ export default function VideoGen() {
refreshGrokEnabled();
};
- const [status, setStatus] = useState(null);
+ // Paint from the previous /status answer while the live probe runs (it shells
+ // out to python and rebuilds the hardware-aware model list on every call).
+ // The cached copy carries `stale: true` and feeds ONLY the model list and the
+ // model-shaping numbers — every connectivity claim below gates on
+ // `statusFresh`, so a stale payload can never report python health.
+ const [status, setStatus] = useState(readCachedVideoGenStatus);
const [statusLoading, setStatusLoading] = useState(true);
// Grok Build CLI video backend (#2859 phase 2) — surfaced only when the
// user enabled Grok in Settings → Image Gen (one toggle covers image +
@@ -130,7 +136,7 @@ export default function VideoGen() {
// The jobId of the render this tab's Generate button currently owns —
// threaded into cancelVideoGen so cancellation is job-scoped.
const activeJobIdRef = useRef(null);
- const [models, setModels] = useState([]);
+ const [models, setModels] = useState(() => status?.models || []);
const refreshGrokEnabled = useCallback(() => {
getSettings({ silent: true })
.then((sv) => setGrokEnabled(sv?.imageGen?.grok?.enabled === true))
@@ -401,6 +407,7 @@ export default function VideoGen() {
.then((s) => {
setStatus(s);
setModels(s.models || []);
+ writeCachedVideoGenStatus(s);
})
.catch(() => setStatus({ connected: false, reason: 'Status check failed' }))
.finally(() => setStatusLoading(false));
@@ -800,7 +807,11 @@ export default function VideoGen() {
// `byovRuntimeMissing` for those models. Without this, a user who installed
// ONLY a BYOV runtime via the modal would stay stuck behind a "not
// configured" error from the unrelated legacy probe.
- const notConnected = !!status && status.connected === false && !needsByovProbe;
+ // A cached payload says nothing trustworthy about python health, so every
+ // connectivity read below waits for the live probe rather than reporting the
+ // interpreter state of whenever the last visit happened.
+ const statusFresh = !!status && !status.stale;
+ const notConnected = statusFresh && status.connected === false && !needsByovProbe;
// A federated render answers to the PEER’s readiness, not to this machine’s
// runtime gates — none of the local probes below describe the hardware it
@@ -814,7 +825,7 @@ export default function VideoGen() {
return (
<div className="space-y-3">
<div className="flex items-center justify-between gap-2 text-xs">
- {status ? (
+ {statusFresh ? (
<span
className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full border ${
status.connected
@@ -870,7 +881,7 @@ export default function VideoGen() {
<RuntimeFingerprint runtime={status?.runtime} />
- {status && status.connected === false && (() => {
+ {statusFresh && status.connected === false && (() => {
const missingCount = status.missingPackages?.length || 0;
const hasPath = !!status.pythonPath;
return (
@@ -1240,12 +1251,16 @@ export default function VideoGen() {
{/* The peer advertises its own models; the local list would name
none of them, and a stale selection here must not read as the
model that rendered the clip. */}
- {models.length > 0 && !remoteTarget.isRemote && (
+ {/* The list arrives with /status, which probes python — keep the
+ field (and its label) in place with a loading placeholder rather
+ than letting it pop into the form a second or two later. */}
+ {(models.length > 0 || statusLoading) && !remoteTarget.isRemote && (
<FormField className="col-span-2 sm:col-span-3" label="Model" labelClassName="block text-xs font-medium text-gray-400 mb-1">
<ModelSelect
models={visibleModels}
value={modelId}
onChange={(e) => handleModelChange(e.target.value)}
+ loading={models.length === 0}
/>
{remixModelFallback && (
<p className="mt-1 text-[11px] text-port-accent leading-snug" role="status">
diff --git a/client/src/pages/VideoGen.modelLoading.test.jsx b/client/src/pages/VideoGen.modelLoading.test.jsx
new file mode 100644
index 0000000000..c8cc055d38
--- /dev/null
+++ b/client/src/pages/VideoGen.modelLoading.test.jsx
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+/**
+ * The Model picker paints before /status lands.
+ *
+ * /status shells out to python and rebuilds the hardware-aware model list on
+ * every call, so the field used to be absent for a second or two and then pop
+ * into the middle of the form. It now holds its place with a loading
+ * placeholder, and a session-cached payload paints the real list immediately —
+ * while every connectivity claim keeps waiting for the live probe.
+ */
+const model = (id) => ({
+ id,
+ name: `Example ${id}`,
+ repo: `example-org/${id}`,
+ 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,
+});
+const MODEL_ONE = model('example-one');
+const MODEL_TWO = model('example-two');
+const statusPayload = (overrides = {}) => ({
+ connected: true,
+ pythonPath: '/opt/example/python3',
+ defaultModel: MODEL_ONE.id,
+ models: [MODEL_ONE, MODEL_TWO],
+ byovRuntimes: [],
+ systemMemoryGb: 128,
+ backendDisclosures: [],
+ ...overrides,
+});
+const state = vi.hoisted(() => ({
+ modelStatuses: {},
+ generateVideo: vi.fn(),
+ startDownload: vi.fn(),
+ repairModel: vi.fn(),
+ attach: vi.fn(),
+ eventSourceRef: { current: null },
+ getVideoGenStatus: vi.fn(),
+ runtimeInstallComplete: null,
+}));
+
+vi.mock('../services/api', () => ({
+ // The page offers a federated render target (#4348); with no peer opted in
+ // as a media provider the picker renders nothing and every local path below
+ // is unchanged.
+ getInstances: vi.fn(async () => ({ peers: [] })),
+ getVideoGenStatus: (...args) => state.getVideoGenStatus(...args),
+ generateVideo: (...args) => state.generateVideo(...args),
+ cancelVideoGen: vi.fn(async () => ({})),
+ listVideoHistory: vi.fn(async () => []),
+ 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: null })),
+ getSettings: vi.fn(async () => ({ imageGen: { grok: { enabled: false } } })),
+ getVideoGenRuntimeStatus: vi.fn(async () => ({ installed: true, ready: true, current: true })),
+ listLorasFull: vi.fn(async () => []),
+ // The prompt-enhancement controls mount useProviderModels, which fetches the
+ // provider list from a mount effect. Unmocked it throws out of a passive
+ // effect — the tests still pass, but the unhandled rejection fails the run.
+ getProviders: vi.fn(async () => ({ providers: [] })),
+ getVisionModels: vi.fn(async () => ({ models: [] })),
+}));
+
+vi.mock('../components/media/PromptFromMedia', () => ({ default: () => null }));
+
+vi.mock('../hooks/useModelDownloadStatus', () => ({
+ TEXT_ENCODER_DOWNLOAD_ID: '__text_encoder__',
+ useModelDownloadStatus: () => ({
+ extra: {},
+ loading: false,
+ statusError: null,
+ activeModelId: null,
+ progress: null,
+ lastError: null,
+ downloading: false,
+ repairing: false,
+ getStatus: (id) => state.modelStatuses[id] || null,
+ start: state.startDownload,
+ cancel: vi.fn(),
+ repair: state.repairModel,
+ 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('../components/ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
+}));
+
+// Keep the policy-bearing controls real; replace unrelated, heavyweight page
+// surfaces so this is a focused orchestration test rather than a gallery/SSE
+// integration suite.
+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: ({ onComplete }) => {
+ state.runtimeInstallComplete = onComplete;
+ return 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/UniverseStylePicker', () => ({ 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 { VIDEO_GEN_STATUS_CACHE_KEY } = await import('../lib/videoGenStatusCache.js');
+
+const renderPage = async () => {
+ let view;
+ await act(async () => {
+ view = render(
+ <MemoryRouter initialEntries={['/media/video']}>
+ <VideoGen />
+ </MemoryRouter>,
+ );
+ });
+ return view;
+};
+
+// A /status call the test settles by hand, so the page can be asserted mid-probe.
+const deferredStatus = () => {
+ let settle;
+ state.getVideoGenStatus.mockReturnValue(new Promise((resolve) => { settle = resolve; }));
+ return async (payload) => { await act(async () => { settle(payload); }); };
+};
+
+describe('VideoGen model picker while /status is in flight', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ state.modelStatuses = {};
+ state.generateVideo.mockReset().mockResolvedValue({ jobId: 'job-1' });
+ state.startDownload.mockReset();
+ state.repairModel.mockReset().mockResolvedValue({ ok: true });
+ state.getVideoGenStatus.mockReset().mockResolvedValue(statusPayload());
+ state.eventSourceRef.current = null;
+ state.attach.mockReset().mockResolvedValue({ filename: 'example.mp4' });
+ });
+
+ it('keeps the Model field with a loading placeholder until the model list lands', async () => {
+ const resolveStatus = deferredStatus();
+ await renderPage();
+
+ const field = screen.getByLabelText('Model');
+ expect(field).toBeDisabled();
+ expect(field).toHaveTextContent('Loading models…');
+
+ await resolveStatus(statusPayload());
+
+ await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(MODEL_ONE.id));
+ expect(screen.getByLabelText('Model')).toBeEnabled();
+ });
+
+ it('paints the cached model list on the next load instead of waiting for the probe', async () => {
+ const first = await renderPage();
+ await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(MODEL_ONE.id));
+ expect(JSON.parse(sessionStorage.getItem(VIDEO_GEN_STATUS_CACHE_KEY)).models).toHaveLength(2);
+ first.unmount();
+
+ const resolveStatus = deferredStatus();
+ await renderPage();
+
+ // Second visit, probe still in flight: the picker is already populated.
+ const field = screen.getByLabelText('Model');
+ expect(field).toBeEnabled();
+ expect(field).toHaveValue(MODEL_ONE.id);
+ await resolveStatus(statusPayload());
+ });
+
+ it('never reports python health from the cached payload', async () => {
+ // A stored payload whose probe FAILED. The model list may come from it; the
+ // diagnosis may not — the interpreter can have been fixed since.
+ sessionStorage.setItem(VIDEO_GEN_STATUS_CACHE_KEY, JSON.stringify(statusPayload({
+ connected: false,
+ reason: 'Python probe failed',
+ missingPackages: ['torch'],
+ })));
+ const resolveStatus = deferredStatus();
+ await renderPage();
+
+ expect(screen.getByLabelText('Model')).toHaveValue(MODEL_ONE.id);
+ expect(screen.getByText('Checking…')).toBeInTheDocument();
+ expect(screen.queryByText(/Install missing Python packages/)).toBeNull();
+ expect(screen.queryByText(/Python probe failed/)).toBeNull();
+
+ await resolveStatus(statusPayload({ connected: true, pythonVersion: '3.12.1' }));
+ await waitFor(() => expect(screen.getByText('Python 3.12.1')).toBeInTheDocument());
+ });
+});