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
resolve a deck's render model from the install pin, not the Pipeline form's sticky state
[._.]/ Adam Eivy9c654b112985
diff --git a/client/src/components/decks/DeckRenderControls.jsx b/client/src/components/decks/DeckRenderControls.jsxindex d436e90d6f..c9627fa48d 100644--- a/client/src/components/decks/DeckRenderControls.jsx+++ b/client/src/components/decks/DeckRenderControls.jsx@@ -1,13 +1,22 @@import { useId } from 'react';-import { Loader2, Play, RefreshCw, Sparkles, WandSparkles } from 'lucide-react';+import { Loader2, Play, RefreshCw, Sliders, Sparkles, WandSparkles } from 'lucide-react';import RecordRenderPinRow from '../imageGen/RecordRenderPinRow';+import CollapsibleSection from '../ui/CollapsibleSection';+import FormField from '../ui/FormField';import DeckLlmPinPicker from './DeckLlmPinPicker';+import useFieldDraft from '../../hooks/useFieldDraft';import useImageRenderSettings from '../../hooks/useImageRenderSettings';+import {+ DECK_CARD_SIZE, DECK_CARD_SIZE_BY_KIND, DECK_CARD_SIZE_MAX, DECK_CARD_SIZE_MIN,+} from '../../lib/decks';import { RENDER_TARGET, modeLabel } from '../../lib/imageGenBackends';+import { clampImageEdge } from '../../lib/imageGenResolutions';import { pluralize } from '../../lib/textUtils';const PRIMARY_BTN = 'inline-flex min-h-[38px] items-center gap-1.5 rounded bg-port-accent px-3 py-2 text-sm text-white hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed';const SECONDARY_BTN = 'inline-flex min-h-[38px] items-center gap-1.5 rounded border border-port-border px-3 py-2 text-sm text-gray-200 hover:bg-white/5 disabled:opacity-40 disabled:cursor-not-allowed';+const NUM_FIELD = 'w-24 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent';+const SIZE_BOUNDS = { min: DECK_CARD_SIZE_MIN, max: DECK_CARD_SIZE_MAX, step: 8 };/*** The action bar above the card grid: which image backend this deck renders on@@ -33,11 +42,30 @@ export default function DeckRenderControls({const unprompted = Math.max(0, total - prompted);const busy = generating || rendering;const promptsAreTheNextStep = unprompted > 0;+ const size = deck.cardSize || DECK_CARD_SIZE;+ // What this deck will actually render on, in the order a sentence wants it.+ // Formatted once: the collapsed header and the expanded note say the same+ // three facts, and a fourth would otherwise have to be added to both.+ const model = imageCfg.cloudModel || imageCfg.modelId;+ const renderFacts = backends.length+ ? [modeLabel(imageCfg.mode), model, `${size.width}×${size.height}`].filter(Boolean)+ : [];return (<div className="bg-port-card border border-port-border rounded-md p-3 space-y-3"><div className="grid grid-cols-1 gap-3 lg:grid-cols-2 lg:items-start">- <div className="space-y-1">+ {/* The collapsed summary is the whole render config in one line, so the+ common case — glance, confirm, render — costs no click, and the+ uncommon one (change the model, resize the card) is one. */}+ <CollapsibleSection+ size="md"+ icon={Sliders}+ id="deck-render-options"+ label="Render options"+ summary={renderFacts.join(' · ')}+ buttonClassName="min-h-[38px]"+ bodyClassName="space-y-3 pt-2"+ ><RecordRenderPinRowidPrefix="deck-render"label="Image backend"@@ -47,14 +75,15 @@ export default function DeckRenderControls({options={backends.length ? backends.map((b) => ({ id: b.id, label: b.label })) : null}autoLabel="Auto (Settings default)"/>- {backends.length ? (+ <CardSize kind={deck.kind} size={size} onPatch={onPatch} />+ {/* What an "Auto" pin and a blank model actually resolve to — the+ controls above name the PIN, this names the outcome. */}+ {renderFacts.length ? (<p className="text-[11px] text-gray-500">- Renders on <span className="text-gray-300">{modeLabel(imageCfg.mode)}</span>- {imageCfg.cloudModel || imageCfg.modelId ? <> · <span className="text-gray-300">{imageCfg.cloudModel || imageCfg.modelId}</span></> : null}- {' '}at {deck.cardSize?.width}×{deck.cardSize?.height}+ Renders on <span className="text-gray-300">{renderFacts.join(' · ')}</span></p>) : null}- </div>+ </CollapsibleSection><DeckLlmPinPickerlabel="Prompt model"pin={deck.promptLlm}@@ -120,6 +149,48 @@ export default function DeckRenderControls({);}+// Card render size. Persisted on the deck (`cardSize`), so it is a deck+// property rather than a per-render one — every card of a deck has to share a+// trim or the set stops reading as one physical object. Commits on blur so a+// three-keystroke width doesn't fire three PATCHes, and snaps through+// `clampImageEdge` to the bounds the deck schema itself is built from, rather+// than letting an out-of-range entry come back as a 400.+function CardSize({ kind, size, onPatch }) {+ const kindDefault = DECK_CARD_SIZE_BY_KIND[kind] || DECK_CARD_SIZE;+ const commit = (axis) => (raw) => {+ const clamped = clampImageEdge(raw, SIZE_BOUNDS);+ if (clamped !== size[axis]) onPatch({ cardSize: { ...size, [axis]: clamped } });+ };+ const width = useFieldDraft(size.width, commit('width'));+ const height = useFieldDraft(size.height, commit('height'));+ const isKindDefault = size.width === kindDefault.width && size.height === kindDefault.height;+ return (+ <div className="flex flex-wrap items-end gap-2">+ <FormField label="Card width" compact>+ <input+ type="number" min={SIZE_BOUNDS.min} max={SIZE_BOUNDS.max} step={SIZE_BOUNDS.step}+ className={NUM_FIELD} value={width.value} onChange={width.onChange} onBlur={width.onBlur}+ />+ </FormField>+ <span className="pb-2 text-xs text-gray-500" aria-hidden="true">×</span>+ <FormField label="Card height" compact>+ <input+ type="number" min={SIZE_BOUNDS.min} max={SIZE_BOUNDS.max} step={SIZE_BOUNDS.step}+ className={NUM_FIELD} value={height.value} onChange={height.onChange} onBlur={height.onBlur}+ />+ </FormField>+ <button+ type="button"+ onClick={() => onPatch({ cardSize: { ...kindDefault } })}+ disabled={isKindDefault}+ className="min-h-[38px] rounded border border-port-border px-2 py-2 text-[11px] text-gray-400 hover:bg-white/5 disabled:opacity-40 disabled:cursor-not-allowed"+ >+ Reset to {kindDefault.width}×{kindDefault.height}+ </button>+ </div>+ );+}+// What step 1's buttons will do, or why they can't.const promptNote = ({ generating, unprompted, total }) => {if (generating) return 'Writing prompts…';diff --git a/client/src/components/decks/DeckRenderControls.test.jsx b/client/src/components/decks/DeckRenderControls.test.jsxindex 1a814701e3..e86e2a3a73 100644--- a/client/src/components/decks/DeckRenderControls.test.jsx+++ b/client/src/components/decks/DeckRenderControls.test.jsx@@ -1,18 +1,37 @@import { describe, it, expect, vi } from 'vitest';-import { render, screen } from '@testing-library/react';+import { act, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import DeckRenderControls from './DeckRenderControls';// The backend row and the LLM pin both fetch provider/settings state; this-// suite is about the batch actions and the notes that explain them.+// suite is about the render-options panel, the batch actions, and the notes+// that explain them.vi.mock('../../hooks/useImageRenderSettings', () => ({- default: () => ({ imageCfg: { mode: 'local', modelId: 'qwen-image' }, backends: [{ id: 'local', label: 'Local' }] }),+ default: () => ({+ imageCfg: { mode: 'local', modelId: 'flux2-klein-9b' },+ backends: [{ id: 'local', label: 'Local' }],+ }),}));vi.mock('./DeckLlmPinPicker', () => ({ default: () => <div /> }));+// The pin row probes the local catalog + the install's model pin itself, so the+// deck page threads neither through.+vi.mock('../../services/api', () => ({+ listImageModels: vi.fn().mockResolvedValue([+ { id: 'flux2-klein-9b', name: 'FLUX.2 Klein 9B' },+ { id: 'qwen-image', name: 'Qwen-Image' },+ ]),+ getSettings: vi.fn().mockResolvedValue({ imageGen: { local: { modelId: 'flux2-klein-9b' } } }),+}));-const deck = { id: 'd1', imageMode: null, imageModelId: null, promptLlm: null, cardSize: { width: 1024, height: 1536 } };+const deck = {+ id: 'd1', kind: 'playing', imageMode: 'local', imageModelId: null, promptLlm: null,+ cardSize: { width: 1096, height: 1536 },+};const completion = (over) => ({ total: 79, prompted: 0, rendered: 0, inFlight: 0, failed: 0, percent: 0, ...over });-const renderControls = (over = {}) => {+// Async so the mount's own settings fetch settles here rather than surfacing as+// an act() warning in whichever case happens to run first.+const renderControls = async (over = {}) => {const props = {deck,completion: completion(),@@ -22,14 +41,61 @@ const renderControls = (over = {}) => {onRenderAll: vi.fn(),...over,};- return { ...props, ...render(<DeckRenderControls {...props} />) };+ const utils = render(<DeckRenderControls {...props} />);+ await act(async () => {});+ return { ...props, ...utils };};const btn = (name) => screen.getByRole('button', { name });+// The pin row mounts with the section, so its catalog probe settles here.+const openOptions = async () => {+ await userEvent.click(btn(/Render options/));+ await act(async () => {});+};++describe('DeckRenderControls render options', () => {+ it('summarises the resolved backend, model and card size without a click', async () => {+ await renderControls();+ expect(btn(/Render options/)).toHaveTextContent('Local · flux2-klein-9b · 1096×1536');+ });++ it('offers this install\'s local model catalog, with the install pin as the blank option', async () => {+ const { onPatch } = await renderControls();+ await openOptions();+ const select = screen.getByRole('combobox', { name: 'Image backend model' });+ expect(screen.getByRole('option', { name: 'Default (FLUX.2 Klein 9B)' })).toBeInTheDocument();++ await userEvent.selectOptions(select, 'qwen-image');+ expect(onPatch).toHaveBeenCalledWith({ imageMode: 'local', imageModelId: 'qwen-image' });+ });++ it('persists a card size on blur, clamped to the sizes the server accepts', async () => {+ const { onPatch } = await renderControls();+ await openOptions();+ const width = screen.getByRole('spinbutton', { name: 'Card width' });+ await userEvent.clear(width);+ await userEvent.type(width, '99999');+ await userEvent.tab();+ expect(onPatch).toHaveBeenCalledWith({ cardSize: { width: 4096, height: 1536 } });+ });++ it('resets to the deck kind\'s own trim, and says which that is', async () => {+ const { onPatch } = await renderControls({ deck: { ...deck, cardSize: { width: 512, height: 512 } } });+ await openOptions();+ await userEvent.click(btn(/Reset to 1096×1536/));+ expect(onPatch).toHaveBeenCalledWith({ cardSize: { width: 1096, height: 1536 } });+ });++ it('disables the reset once the deck is already at its kind default', async () => {+ await renderControls();+ await openOptions();+ expect(btn(/Reset to 1096×1536/)).toBeDisabled();+ });+});describe('DeckRenderControls', () => {- it('says in the page why generating prompts is unavailable on a fully prompted deck', () => {- renderControls({ completion: completion({ prompted: 79, inFlight: 1 }) });+ it('says in the page why generating prompts is unavailable on a fully prompted deck', async () => {+ await renderControls({ completion: completion({ prompted: 79, inFlight: 1 }) });expect(btn(/^Generate prompts$/)).toBeDisabled();// The reason is rendered text, not a title — a disabled button has no// hover on touch and no focus anywhere.@@ -40,27 +106,27 @@ describe('DeckRenderControls', () => {expect(btn(/^Generate prompts$/)).toHaveAttribute('aria-describedby', note.id);});- it('says why rendering is unavailable before any prompt exists', () => {- renderControls();+ it('says why rendering is unavailable before any prompt exists', async () => {+ await renderControls();expect(btn(/^Render missing \(79\)$/)).toBeDisabled();expect(btn(/^Render all$/)).toBeDisabled();expect(screen.getByText('A card renders from its prompt. Write prompts first.')).toBeInTheDocument();expect(screen.getByText('79 of 79 cards still need a prompt.')).toBeInTheDocument();});- it('counts in-flight cards out of the render-missing total and names them', () => {- renderControls({ completion: completion({ prompted: 79, rendered: 0, inFlight: 1 }) });+ it('counts in-flight cards out of the render-missing total and names them', async () => {+ await renderControls({ completion: completion({ prompted: 79, rendered: 0, inFlight: 1 }) });expect(btn(/^Render missing \(78\)$/)).toBeEnabled();expect(screen.getByText('78 prompted cards not rendered yet · 1 card rendering now.')).toBeInTheDocument();});- it('moves the accent button from step 1 to step 2 as the deck becomes fully prompted', () => {- const { unmount } = renderControls({ completion: completion({ prompted: 10 }) });+ it('moves the accent button from step 1 to step 2 as the deck becomes fully prompted', async () => {+ const { unmount } = await renderControls({ completion: completion({ prompted: 10 }) });expect(btn(/^Generate prompts \(69\)$/).className).toContain('bg-port-accent');expect(btn(/^Render missing \(79\)$/).className).not.toContain('bg-port-accent');unmount();- renderControls({ completion: completion({ prompted: 79 }) });+ await renderControls({ completion: completion({ prompted: 79 }) });expect(btn(/^Generate prompts$/).className).not.toContain('bg-port-accent');expect(btn(/^Render missing \(79\)$/).className).toContain('bg-port-accent');});diff --git a/client/src/components/imageGen/RecordRenderPinRow.jsx b/client/src/components/imageGen/RecordRenderPinRow.jsxindex f6bdda9cc1..49d9e963e2 100644--- a/client/src/components/imageGen/RecordRenderPinRow.jsx+++ b/client/src/components/imageGen/RecordRenderPinRow.jsx@@ -1,15 +1,29 @@-import { IMAGE_GEN_MODE, RENDER_TARGET_BACKEND_AUTO, modeLabel, supportsCloudModelOverride } from '../../lib/imageGenBackends';+import ModelSelect from '../ModelSelect';+import {+ IMAGE_GEN_MODE, RENDER_TARGET_BACKEND_AUTO, localModelSelectOptions, modeLabel,+ supportsCloudModelOverride,+} from '../../lib/imageGenBackends';import useFieldDraft from '../../hooks/useFieldDraft';+import useLocalImageModels from '../../hooks/useLocalImageModels';const DEFAULT_MODES = [IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY];+const FIELD = 'w-full max-w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent';// Per-record render pin editor (#3231 Phase 3) — one row pinning a record's-// default image backend + (for model-override-capable cloud CLIs) a model.-// Mirrors the Settings → Image Gen "Render defaults" row: the model input only-// appears when the pinned backend accepts one, and ANY backend change clears+// default image backend and the model that backend renders on. Mirrors the+// Settings → Image Gen "Render defaults" row, and ANY backend change clears// the pinned model — model ids are namespaced per provider, and the server's// leak guard can't catch a mode+model pinned together (see ImageGenTab).//+// Which model control appears follows the pinned backend. An override-capable+// cloud CLI takes a free-text id, because its catalog is the provider's rather+// than ours. A LOCAL pin takes a select over this install's own image-model+// catalog, probed here (`useLocalImageModels`, which also reports what a blank+// pin resolves to) rather than passed down, so every surface hosting this row+// gets the same picker without threading two props through — a text box would+// only invite a typo the render 400s on. Nothing is fetched until a local pin+// is actually selected. Grok, which accepts no model override, gets neither.+//// `onChange` always receives BOTH keys (`{ imageMode, imageModelId }`), with// null for "no pin" — key-present-with-null is the intentional clear per the// absent-vs-empty convention, so callers can PATCH the payload verbatim.@@ -29,6 +43,8 @@ export default function RecordRenderPinRow({}) {const pinnedMode = imageMode && imageMode !== RENDER_TARGET_BACKEND_AUTO ? imageMode : '';const optionList = options || modes.map((m) => ({ id: m, label: modeLabel(m) }));+ const isLocal = pinnedMode === IMAGE_GEN_MODE.LOCAL;+ const { models, installDefault } = useLocalImageModels(isLocal);const modelDraft = useFieldDraft(imageModelId, (v) => {onChange({ imageMode: pinnedMode || null, imageModelId: v.trim() || null });});@@ -39,12 +55,21 @@ export default function RecordRenderPinRow({id={`${idPrefix}-mode`}value={pinnedMode}onChange={(e) => onChange({ imageMode: e.target.value || null, imageModelId: null })}- className="w-full max-w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-auto sm:min-w-[11rem]"+ className={`${FIELD} sm:w-auto sm:min-w-[11rem]`}>{showAuto ? <option value="">{autoLabel}</option> : (!pinnedMode && <option value="" disabled>Pick a backend</option>)}{optionList.map((o) => <option key={o.id} value={o.id}>{o.label || o.id}</option>)}</select>- {supportsCloudModelOverride(pinnedMode) ? (+ {isLocal ? (+ <LocalModelPin+ id={`${idPrefix}-model`}+ ariaLabel={`${label} model`}+ models={models}+ installDefault={installDefault}+ value={imageModelId}+ onChange={(modelId) => onChange({ imageMode: pinnedMode, imageModelId: modelId })}+ />+ ) : supportsCloudModelOverride(pinnedMode) ? (<inputid={`${idPrefix}-model`}type="text"@@ -53,9 +78,27 @@ export default function RecordRenderPinRow({onBlur={modelDraft.onBlur}placeholder="Model (optional)"aria-label={`${label} model`}- className="w-full max-w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-52"+ className={`${FIELD} sm:w-52`}/>) : <span className="hidden sm:block" />}</div>);}++function LocalModelPin({ id, ariaLabel, models, installDefault, value, onChange }) {+ const loading = models === null || installDefault === null;+ const { options, fallbackLabel } = localModelSelectOptions(models, value, installDefault ?? undefined);+ return (+ <ModelSelect+ id={id}+ ariaLabel={ariaLabel}+ models={options}+ value={value || ''}+ loading={loading}+ onChange={(e) => onChange(e.target.value || null)}+ getLabel={(m) => m.name || m.id}+ emptyOption={`Default (${fallbackLabel})`}+ className={`${FIELD} sm:w-52 disabled:opacity-50`}+ />+ );+}diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 814343484e..b749af76fc 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -21,14 +21,15 @@ import { isLoopbackHost } from '../../lib/loopbackHost.js';import { PORTS } from '../../lib/ports.js';import {getSettings, updateSettings, getImageGenStatus, generateImage,- registerTool, updateTool, getToolsList, listImageModels,+ registerTool, updateTool, getToolsList,saveHfToken, clearHfToken,} from '../../services/api';-import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, LOCAL_IMAGEGEN_DEFAULT_MODEL, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';+import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, localModelSelectOptions, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';import { resolveCleanersFromConfig } from '../../lib/imageCleaners';import { useMediaJobSse } from '../../hooks/useMediaJobSse';import { useAgyModels } from '../../hooks/useAgyModels';import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';+import useLocalImageModels from '../../hooks/useLocalImageModels';import { effortLevelsForProvider } from '../../utils/providers';const SDAPI_TOOL_ID = 'sdapi';@@ -130,10 +131,12 @@ export function ImageGenTab() {// hand-editing settings.json. Client-side defaults in lib/pipelineImageDefaults// and lib/wrImageDefaults still hardcode their own model and do not consult it.const [localModelId, setLocalModelId] = useState('');- // Catalog for the picker, probed once the Local tab is mounted. `null` until- // the fetch resolves (vs `[]` for "fetched and genuinely empty") so the- // select can say "loading" rather than silently offering nothing.- const [localModels, setLocalModels] = useState(null);+ // Catalog for the picker, probed once the Local tab is mounted — the same+ // "don't probe a tab nobody looked at" rule as the Agy list below.+ // Hardware-incompatible entries are filtered out by the hook's fetch: a+ // default this machine's runner refuses is a render error waiting to happen,+ // and `checkLocalConnection` already reports it as unavailable.+ const { models: localModels } = useLocalImageModels(localMounted);const [exposeA1111, setExposeA1111] = useState(false);// Codex CLI provider config — gated by `codexEnabled` so users without// a paid Codex plan that includes image_gen can hide the option entirely.@@ -359,30 +362,14 @@ export function ImageGenTab() {.finally(() => setLoading(false));}, []);- // Local model catalog — fetched once the Local tab has been opened, on the- // same "don't probe a tab nobody looked at" rule as the Agy list below.- // Hardware-incompatible entries are filtered out by `listImageModels`: a- // default that this machine's runner refuses is a render error waiting to- // happen, and `checkLocalConnection` already reports it as unavailable.- useEffect(() => {- if (!localMounted) return;- let alive = true;- listImageModels()- .then((list) => { if (alive) setLocalModels(Array.isArray(list) ? list : []); })- .catch(() => { if (alive) setLocalModels([]); });- return () => { alive = false; };- }, [localMounted]);-- // A pin the live catalog no longer lists (model rotated out, or this machine- // stopped being compatible) still has to render as the selected option —- // otherwise the select paints blank, reads as "install default", and a save- // would silently drop a pin the server is still honouring.- const pinIsOrphaned = localModelId && localModels !== null && !localModels.some((m) => m.id === localModelId);- const localModelOptions = pinIsOrphaned- ? [{ id: localModelId, name: `${localModelId} (unavailable on this machine)` }, ...localModels]- : localModels ?? [];- const localDefaultLabel = localModels?.find((m) => m.id === LOCAL_IMAGEGEN_DEFAULT_MODEL)?.name- || LOCAL_IMAGEGEN_DEFAULT_MODEL;+ // Shared with the per-record local-model picker (RecordRenderPinRow), which+ // needs the same orphaned-pin handling: a pin the live catalog no longer+ // lists still has to render as the selected option, or the select paints+ // blank, reads as "install default", and a save silently drops a pin the+ // server is still honouring.+ const { options: localModelOptions, fallbackLabel: localDefaultLabel } = localModelSelectOptions(+ localModels, localModelId,+ );// Probe only while the Agy tab is actually open — the list spawns `agy models`// server-side, so an unopened tab must not pay for a child process.diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 129a40da3e..a0606d2077 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -178,6 +178,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. || `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. || `useReviewerModelOptions` | Selectable model ids and concrete provider defaults per model-taking reviewer for `ReviewerPicker`'s Model column — local-LLM ids from `/api/local-llm/status`, codex/claude/antigravity tiers from `/api/providers` (claude's list also spans installed Ollama ids for an Ollama-backed CLI; agy's list collapses to base ids since the row has its own Effort cell). Returns `{ optionsByReviewer, defaultModels, freeText, unavailable, loaded, reviewers }`. | Every surface that renders `ReviewerPicker` (Code Review Defaults, TaskAddForm, ScheduleTab, SlashDoRunDrawer) — the picker never fetches; pass this as its `modelOptions`. |+| `useLocalImageModels` | This install's local image-model catalog plus the model a blank pin resolves to (`settings.imageGen.local.modelId` → the shipped default), `enabled`-gated so nothing is probed until a local render is in play. `models` is `null` until fetched, `[]` when genuinely empty. | Any local image-model picker — the Settings Local default, and the per-record pin row on decks/universes/series/sprites/music video. || `useLocalModels` | Live installed Ollama/LM Studio model ids per backend, runtime capability badges, the server's editorial recommendation, and `installed` per backend (`null` until fetched) — the app-level verdict that counts a macOS bundle with no CLI shim. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`), or explain a selected model's live capabilities. Fold in via `mergeModelLists` + `localBackendForProvider`. || `useVisionModelIds` | `{ idsByProvider, loaded }` — vision-capable model ids the server reports (Ollama `/api/show` + LM Studio `type:'vlm'`), keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. Drops `backend:'cli'` rows (a blanket per-provider claim, not a per-model fact) and never vouches for a provider the server didn't enumerate. | Any VISION model picker — pass `idsByProvider` to `visionLocalModelFilter` / `assignmentModelOptions` so a new multimodal family (`gemma4`) isn't hidden by the stale client id regex, and so an installed VLM shows even when the provider's stored `models` snapshot is stale; gate any "none installed" messaging on `loaded` and on the provider being a local backend. || `useToolUseModelIds` | `{ idsByProvider, loaded }` — TOOL-USE (function-calling) capable model ids the server reports (Ollama `/api/show` `tools` capability + LM Studio catalog capabilities) via `/api/local-llm/tool-use-models`, keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. One module-shared fetch across every mounted caller, retried on a later mount if it failed. | Any AGENT model picker — pass `idsByProvider` to `localToolUseHint` / `withToolUseOptionLabel` so a tool-capable family the client id regex predates (`phi4-mini`) isn't mislabelled "⚠ no known tool use", and gate the annotation on `loaded` so the warning isn't asserted mid-fetch. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 4e8a23814d..698eaef3bd 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -66,6 +66,7 @@ export { default as usePopoverPosition } from './usePopoverPosition.js';export { default as useAgyModels } from './useAgyModels.js';export * from './useAgyModels.js';export { default as useLocalLlmStatus } from './useLocalLlmStatus.js';+export { default as useLocalImageModels } from './useLocalImageModels.js';export { default as useLocalModels } from './useLocalModels.js';export { default as useVisionModelIds } from './useVisionModelIds.js';export { default as useToolUseModelIds } from './useToolUseModelIds.js';diff --git a/client/src/hooks/useImageRenderSettings.js b/client/src/hooks/useImageRenderSettings.jsindex feb265b262..5cd34f180b 100644--- a/client/src/hooks/useImageRenderSettings.js+++ b/client/src/hooks/useImageRenderSettings.js@@ -1,25 +1,44 @@import { useState, useEffect, useMemo } from 'react';import { getSettings } from '../services/api';-import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';+import { IMAGE_RENDER_KNOB_DEFAULTS } from '../lib/pipelineImageDefaults';import {- applyRecordRenderPin, deriveAvailableBackends, renderTargetPin,+ deriveAvailableBackends, IMAGE_GEN_MODE, installLocalModelId, LOCAL_IMAGEGEN_DEFAULT_MODEL,+ pickUsableMode, renderPinLadder, renderTargetPin, supportsCloudModelOverride,} from '../lib/imageGenBackends';+// What the hook reports before the settings blob lands, and after a failed+// fetch: the shipped knobs on the backend that is always usable. Frozen and+// module-level so an unresolved hook hands every consumer the same identity+// rather than a fresh object per render.+const UNRESOLVED = Object.freeze({+ ...IMAGE_RENDER_KNOB_DEFAULTS,+ mode: IMAGE_GEN_MODE.LOCAL,+ modelId: LOCAL_IMAGEGEN_DEFAULT_MODEL,+ cloudModel: null,+});+/**- * Load the pipeline image-gen render config once on mount and expose it as a- * ready-to-use `imageCfg`. Collapses the `getSettings → readPipelineImageSettings`- * fetch every single-image-render call site re-implements (Story Builder's- * characters step, the universe base-style probe). Fails open to- * `PIPELINE_IMAGE_DEFAULTS` — a transient settings fetch failure shouldn't block- * rendering, and the defaults are a valid render config on their own.+ * Resolve "what will this record's next render actually run on" — the client+ * mirror of the server's own ladder — and expose it as a ready-to-use+ * `imageCfg`. Collapses the `getSettings` + resolve every single-image-render+ * call site re-implements (Story Builder's characters step, the universe+ * base-style probe, the Decks render bar).+ *+ * The backend walks `renderPinLadder` (the record's own `imageMode`, then the+ * target's `renderDefaults` pin, both gated on backends this install actually+ * has) and falls through to the install-wide `imageGen.mode` via the shared+ * `pickUsableMode`. The model then follows the backend it belongs to: local+ * takes the pin, else `imageGen.local.modelId`, else the shipped default;+ * an override-capable cloud CLI takes the pin as `cloudModel` and nothing+ * else. Neither ever comes from `settings.pipeline.imageGen` — that slice is+ * the Pipeline visual FORM's sticky state, and reading it here is what made a+ * deck advertise the model a comic page was last rendered with while the+ * server rendered on the install pin.** Components that already load the full settings blob for other reasons (e.g.* the Universe Builder reads loras + models from the same fetch) should keep* deriving `imageCfg` from that shared fetch rather than double-fetching here.*- * Pass `record` + `target` to resolve the render-pin ladder over the install- * default — see `renderPinLadder` for why the client has to do this at all.- ** @param {object} [opts]* @param {object|null} [opts.record] - Record whose `imageMode`/`imageModelId` pin wins.* @param {string|null} [opts.target] - RENDER_TARGET id whose `renderDefaults` pin is next.@@ -30,11 +49,8 @@ import {export default function useImageRenderSettings({ record = null, target = null } = {}) {// `null` = not fetched yet (or the fetch failed), which is NOT the same as a// settings blob with no backends enabled. Holding the raw blob (rather than a- // derived cfg seeded with `PIPELINE_IMAGE_DEFAULTS` and an `[]` backend list)- // keeps the two apart: `[]` reads as "loaded, nothing enabled" and would- // suppress every pin. Until the blob lands there is no install default and no- // backend list to gate against, so the hook fails open to the bare defaults —- // no pin — exactly as it did before the ladder existed.+ // derived cfg seeded with the defaults and an `[]` backend list) keeps the two+ // apart: `[]` reads as "loaded, nothing enabled" and would suppress every pin.const [settings, setSettings] = useState(null);useEffect(() => {@@ -45,15 +61,23 @@ export default function useImageRenderSettings({ record = null, target = null }// a freshly-fetched draft object on every save, and re-deriving an identical// cfg would churn the render opts for every consumer downstream.return useMemo(() => {- if (!settings) return { imageCfg: PIPELINE_IMAGE_DEFAULTS, backends: [] };+ if (!settings) return { imageCfg: UNRESOLVED, backends: [] };const backends = deriveAvailableBackends(settings, { excludeExternal: true });+ const pin = renderPinLadder([record, renderTargetPin(settings, target)], backends);+ const mode = pin.mode || pickUsableMode(settings, [settings.imageGen?.mode]);+ const isLocal = mode === IMAGE_GEN_MODE.LOCAL;return {- imageCfg: applyRecordRenderPin(- readPipelineImageSettings(settings),- [record, renderTargetPin(settings, target)],- backends,- ),backends,+ imageCfg: {+ ...IMAGE_RENDER_KNOB_DEFAULTS,+ mode,+ // Only one of these is ever set: a local render reads `modelId`, an+ // override-capable cloud CLI reads `cloudModel`. Carrying the local+ // model alongside a cloud mode is how "Renders on Codex · <local+ // model>" would get advertised.+ modelId: isLocal ? (pin.modelId || installLocalModelId(settings)) : null,+ cloudModel: !isLocal && supportsCloudModelOverride(mode) ? pin.modelId : null,+ },};}, [settings, target, record?.imageMode, record?.imageModelId]);}diff --git a/client/src/hooks/useImageRenderSettings.test.jsx b/client/src/hooks/useImageRenderSettings.test.jsxindex 2bbca9cd4d..27bef85faa 100644--- a/client/src/hooks/useImageRenderSettings.test.jsx+++ b/client/src/hooks/useImageRenderSettings.test.jsx@@ -7,40 +7,84 @@ vi.mock('../services/api', () => ({}));import useImageRenderSettings from './useImageRenderSettings.js';-import { PIPELINE_IMAGE_DEFAULTS } from '../lib/pipelineImageDefaults.js';+import { IMAGE_RENDER_KNOB_DEFAULTS } from '../lib/pipelineImageDefaults.js';+import { LOCAL_IMAGEGEN_DEFAULT_MODEL } from '../lib/imageGenModes.js';++// What the hook reports with no settings blob to resolve against.+const UNRESOLVED = {+ ...IMAGE_RENDER_KNOB_DEFAULTS,+ mode: 'local',+ modelId: LOCAL_IMAGEGEN_DEFAULT_MODEL,+ cloudModel: null,+};beforeEach(() => {getSettings.mockReset();});describe('useImageRenderSettings', () => {- it('starts at the pipeline defaults before settings resolve', () => {+ it('starts on the always-usable backend before settings resolve', () => {getSettings.mockReturnValue(new Promise(() => {})); // never resolvesconst { result } = renderHook(() => useImageRenderSettings());- expect(result.current.imageCfg).toEqual(PIPELINE_IMAGE_DEFAULTS);+ expect(result.current.imageCfg).toEqual(UNRESOLVED);});- it('reads the stored pipeline image config and fetches silently', async () => {- getSettings.mockResolvedValue({ pipeline: { imageGen: { modelId: 'custom-model', width: 768 } } });- const { result } = renderHook(() => useImageRenderSettings());- await waitFor(() => expect(result.current.imageCfg.modelId).toBe('custom-model'));- expect(result.current.imageCfg.width).toBe(768);- expect(getSettings).toHaveBeenCalledWith({ silent: true });- });-- it('fails open to the defaults when the settings fetch rejects', async () => {+ it('fails open to the same defaults when the settings fetch rejects', async () => {getSettings.mockRejectedValue(new Error('offline'));const { result } = renderHook(() => useImageRenderSettings());// No throw; cfg stays at the defaults.await waitFor(() => expect(getSettings).toHaveBeenCalled());- expect(result.current.imageCfg).toEqual(PIPELINE_IMAGE_DEFAULTS);+ expect(result.current.imageCfg).toEqual(UNRESOLVED);+ expect(getSettings).toHaveBeenCalledWith({ silent: true });+ });++ // The bug this hook shipped with: `settings.pipeline.imageGen` is the+ // Pipeline visual FORM's sticky state, so a backend, model, seed or negative+ // prompt set once on a comic page became every deck's and every universe's —+ // while the server resolved those from the install ladder the whole time.+ describe('never inherits the Pipeline form state', () => {+ const PIPELINE_FORM = {+ pipeline: {+ imageGen: {+ mode: 'codex', modelId: 'qwen-image', width: 768, seed: '42', negativePrompt: 'no hands',+ },+ },+ };++ it('takes the local model from the install pin, not the pipeline form', async () => {+ getSettings.mockResolvedValue({ ...PIPELINE_FORM, imageGen: { local: { modelId: 'flux2-klein-9b' } } });+ const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));+ await waitFor(() => expect(result.current.imageCfg.modelId).toBe('flux2-klein-9b'));+ });++ it('falls back to the shipped local default when the install pins no model', async () => {+ getSettings.mockResolvedValue(PIPELINE_FORM);+ const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));+ await waitFor(() => expect(result.current.imageCfg.modelId).toBe(LOCAL_IMAGEGEN_DEFAULT_MODEL));+ });++ it('takes the backend from the install-wide mode, not the pipeline form', async () => {+ getSettings.mockResolvedValue({+ ...PIPELINE_FORM,+ imageGen: { mode: 'agy', agy: { enabled: true }, codex: { enabled: true } },+ });+ const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));+ await waitFor(() => expect(result.current.imageCfg.mode).toBe('agy'));+ });++ it('leaves the geometry and prompt knobs at the shipped defaults', async () => {+ getSettings.mockResolvedValue(PIPELINE_FORM);+ const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));+ await waitFor(() => expect(result.current.imageCfg.width).toBe(IMAGE_RENDER_KNOB_DEFAULTS.width));+ expect(result.current.imageCfg.seed).toBe('');+ expect(result.current.imageCfg.negativePrompt).toBe('');+ });});// Wiring only — the ladder's own matrix is covered by `renderPinLadder`'s- // unit tests. Codex + agy both enabled means `readPipelineImageSettings`- // picks codex, so an agy result can only have come from a pin.+ // unit tests.describe('render pin ladder', () => {- const CLOUD_ON = { codex: { enabled: true }, agy: { enabled: true } };+ const CLOUD_ON = { mode: 'codex', codex: { enabled: true }, agy: { enabled: true } };it('resolves the record pin, then the target pin, then the install default', async () => {getSettings.mockResolvedValue({ imageGen: CLOUD_ON });@@ -60,14 +104,34 @@ describe('useImageRenderSettings', () => {expect(result.current.imageCfg.mode).toBe('codex');});- it('fails open to the bare defaults when the settings fetch fails', async () => {- // No settings blob means no install default and no backend list to gate a- // pin against, so the ladder is skipped entirely rather than applied over- // a guessed cfg — the pre-ladder fail-open behavior, unchanged.- getSettings.mockRejectedValue(new Error('offline'));- const { result } = renderHook(() => useImageRenderSettings({ record: { imageMode: 'agy' } }));- await waitFor(() => expect(getSettings).toHaveBeenCalled());- expect(result.current.imageCfg).toEqual(PIPELINE_IMAGE_DEFAULTS);+ // The two model knobs are mutually exclusive: whichever one the resolved+ // backend does NOT read is null, so a UI that shows "the model" can't+ // advertise a local model beside a cloud backend.+ it('routes a cloud pin to cloudModel and leaves the local model unset', async () => {+ getSettings.mockResolvedValue({+ imageGen: { ...CLOUD_ON, local: { modelId: 'flux2-klein-9b' } },+ });+ const { result } = renderHook(() => useImageRenderSettings({+ record: { imageMode: 'agy', imageModelId: 'gemini-3.8-flash' }, target: 'deck',+ }));+ await waitFor(() => expect(result.current.imageCfg.cloudModel).toBe('gemini-3.8-flash'));+ expect(result.current.imageCfg.modelId).toBeNull();+ });++ it('leaves both model knobs unset when an unpinned install defaults to a cloud backend', async () => {+ getSettings.mockResolvedValue({ imageGen: { ...CLOUD_ON, local: { modelId: 'flux2-klein-9b' } } });+ const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));+ await waitFor(() => expect(result.current.imageCfg.mode).toBe('codex'));+ expect(result.current.imageCfg.modelId).toBeNull();+ expect(result.current.imageCfg.cloudModel).toBeNull();+ });++ it('drops a record pin naming a backend this install does not have enabled', async () => {+ getSettings.mockResolvedValue({ imageGen: CLOUD_ON });+ const { result } = renderHook(() => useImageRenderSettings({+ record: { imageMode: 'grok' }, target: 'deck',+ }));+ await waitFor(() => expect(result.current.imageCfg.mode).toBe('codex'));});});});diff --git a/client/src/hooks/useLocalImageModels.js b/client/src/hooks/useLocalImageModels.jsnew file mode 100644index 0000000000..3213693590--- /dev/null+++ b/client/src/hooks/useLocalImageModels.js@@ -0,0 +1,43 @@+// This install's local image-model catalog, plus the model a blank pin+// resolves to — everything a local-model picker needs.+//+// `enabled`-gated in the same shape as `useAgyModels`: the catalog probe reads+// the model registry and the install's hardware compatibility server-side, and+// a surface that is rendering on a cloud CLI has no use for it, so nothing is+// fetched until a local render is actually in play. That gate is also what+// keeps a collapsed panel free: the probe only runs once the picker mounts.+//+// The install default is read here rather than passed in so every caller gets+// the same answer without threading a prop — `RecordRenderPinRow` is rendered+// by six unrelated surfaces, and a picker whose blank option names the wrong+// model is the exact class of lie this hook was added to end.++import { useEffect, useState } from 'react';+import { getSettings, listImageModels } from '../services/api';+import { installLocalModelId } from '../lib/imageGenBackends';++/**+ * @param {boolean} enabled - only probe while a local render is in play.+ * @returns {{ models: Array<{id:string,name?:string}>|null, installDefault: string|null }} —+ * `models` is `null` until the probe resolves (vs `[]` for "probed and+ * genuinely empty", which a picker must render as "no compatible models"+ * rather than as "still loading"); `installDefault` is `null` alongside it.+ */+export default function useLocalImageModels(enabled) {+ const [models, setModels] = useState(null);+ const [installDefault, setInstallDefault] = useState(null);++ useEffect(() => {+ if (!enabled) return undefined;+ let alive = true;+ listImageModels({ silent: true })+ .then((list) => { if (alive) setModels(Array.isArray(list) ? list : []); })+ .catch(() => { if (alive) setModels([]); });+ getSettings({ silent: true })+ .then((s) => { if (alive) setInstallDefault(installLocalModelId(s)); })+ .catch(() => { if (alive) setInstallDefault(installLocalModelId(null)); });+ return () => { alive = false; };+ }, [enabled]);++ return { models, installDefault };+}diff --git a/client/src/lib/decks.js b/client/src/lib/decks.jsindex c158eea7db..9f1b898a19 100644--- a/client/src/lib/decks.js+++ b/client/src/lib/decks.js@@ -5,6 +5,9 @@ export {CARD_STATUS,DECK_BACK_KEY,DECK_CARD_SIZE,+ DECK_CARD_SIZE_BY_KIND,+ DECK_CARD_SIZE_MAX,+ DECK_CARD_SIZE_MIN,DECK_KIND,DECK_KINDS,DECK_KIND_LABELS,diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex 7ba1113b2e..dd6e623ad1 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -172,6 +172,44 @@ export const renderTargetPin = (settings, target) => ({imageModelId: settings?.renderDefaults?.[target]?.imageModel ?? null,});+/**+ * The local model a render resolves to when nothing else names one — the+ * client mirror of the tail of the server's `selectLocalImageModel`+ * (`settings.imageGen.local.modelId`, then `LOCAL_IMAGEGEN_DEFAULT_MODEL`).+ *+ * Every surface that is not the Pipeline visual form has to read THIS rather+ * than `settings.pipeline.imageGen.modelId`: that key is the Pipeline form's+ * own sticky state, so a model picked once on a comic page followed the Decks+ * "Renders on Local · …" summary around and named a model a deck render would+ * never actually use — the server has always read the install pin here.+ */+export const installLocalModelId = (settings) => (+ normalizeRenderPinValue(settings?.imageGen?.local?.modelId) || LOCAL_IMAGEGEN_DEFAULT_MODEL+);++/**+ * The option list + blank-option label a local-image-model `<select>` needs.+ *+ * A pin the live catalog no longer lists (model rotated out, or this machine+ * stopped being compatible) still has to render as the selected option —+ * otherwise the select paints blank, reads as "use the default", and the next+ * save silently drops a pin the server is still honouring.+ *+ * @param {Array<{id:string,name?:string}>|null} models - Catalog; `null` while it loads.+ * @param {string|null} pinned - Currently selected id ('' / null = no pin).+ * @param {string} [fallbackId] - What a blank pin resolves to on this surface.+ * @returns {{options: Array<{id:string,name?:string}>, fallbackLabel: string}}+ */+export function localModelSelectOptions(models, pinned, fallbackId = LOCAL_IMAGEGEN_DEFAULT_MODEL) {+ const orphaned = pinned && models !== null && !models.some((m) => m.id === pinned);+ return {+ options: orphaned+ ? [{ id: pinned, name: `${pinned} (unavailable on this machine)` }, ...models]+ : models ?? [],+ fallbackLabel: models?.find((m) => m.id === fallbackId)?.name || fallbackId,+ };+}+/*** Resolve the effective render pin from an ordered ladder of pin sources — the* client-side counterpart of the server's `resolveRenderTargetConfig` (#3231), minus thediff --git a/client/src/lib/pipelineImageDefaults.js b/client/src/lib/pipelineImageDefaults.jsindex c63f3943f4..2eba20d639 100644--- a/client/src/lib/pipelineImageDefaults.js+++ b/client/src/lib/pipelineImageDefaults.js@@ -7,12 +7,16 @@import { isCloudCliMode, IMAGE_GEN_MODE } from './imageGenBackends';+// The geometry + prompt knobs of a render config, with no backend or model —+// the half that is NOT install-wide state. `settings.pipeline.imageGen` is the+// Pipeline visual form's own sticky buffer, so a surface that is not that form+// starts from these shipped values instead of inheriting whatever a comic page+// was last rendered with (see `useImageRenderSettings`).+//// 1024×1536 = 2:3 portrait, the closest preset to a real comic-book trim// (~0.65 ratio). The "hi-res portrait" entry in imageGenResolutions is// gated to codex + FLUX2, which lines up with our codex-first default.-export const PIPELINE_IMAGE_DEFAULTS = Object.freeze({- mode: IMAGE_GEN_MODE.LOCAL,- modelId: 'flux2-klein-4b',+export const IMAGE_RENDER_KNOB_DEFAULTS = Object.freeze({width: 1024,height: 1536,steps: '',@@ -22,6 +26,12 @@ export const PIPELINE_IMAGE_DEFAULTS = Object.freeze({extraStyle: '',});+export const PIPELINE_IMAGE_DEFAULTS = Object.freeze({+ mode: IMAGE_GEN_MODE.LOCAL,+ modelId: 'flux2-klein-4b',+ ...IMAGE_RENDER_KNOB_DEFAULTS,+});+// Resolve the per-render config. Codex-enabled systems default to codex// mode unless the user explicitly stored a different mode on// `settings.pipeline.imageGen` — that override always wins so the formdiff --git a/server/lib/deckTemplates.js b/server/lib/deckTemplates.jsindex 5d3f5011b2..a8633c7e40 100644--- a/server/lib/deckTemplates.js+++ b/server/lib/deckTemplates.js@@ -28,6 +28,13 @@ export const DECK_KIND_LABELS = Object.freeze({// Real decks use `DECK_CARD_SIZE_BY_KIND` below instead.export const DECK_CARD_SIZE = Object.freeze({ width: 1024, height: 1536 });+// Per-edge bounds for a deck's card size. `deckValidation.js` builds its zod+// `cardSizeSchema` from these and the client's size inputs clamp to them, so+// the form can't submit a value the PATCH would 400 on and neither side holds+// its own copy of the numbers.+export const DECK_CARD_SIZE_MIN = 256;+export const DECK_CARD_SIZE_MAX = 4096;+// Per-kind default card size, at each kind's true physical trim ratio rather// than the generic 2:3 fallback above — poker cards are 2.5"×3.5" (5:7),// tarot cards are 2.75"×4.75" (11:19). Both hold the same 1536 long edge asdiff --git a/server/lib/deckValidation.js b/server/lib/deckValidation.jsindex 0ef6813ff6..e5ae915ab0 100644--- a/server/lib/deckValidation.js+++ b/server/lib/deckValidation.js@@ -5,7 +5,7 @@*/import { z } from 'zod';-import { DECK_KINDS } from './deckTemplates.js';+import { DECK_CARD_SIZE_MAX, DECK_CARD_SIZE_MIN, DECK_KINDS } from './deckTemplates.js';import { llmRoutePinSchema } from './llmRoutePin.js';import { INFLUENCE_ENTRY_MAX, INFLUENCES_PER_LIST_MAX, STYLE_NOTES_MAX } from './universeBibleLimits.js';@@ -32,10 +32,8 @@ const influencesSchema = z.object({avoid: z.array(influenceEntry).max(INFLUENCES_PER_LIST_MAX).optional().default([]),}).strict();-const cardSizeSchema = z.object({- width: z.number().int().min(256).max(4096),- height: z.number().int().min(256).max(4096),-}).strict();+const cardEdge = z.number().int().min(DECK_CARD_SIZE_MIN).max(DECK_CARD_SIZE_MAX);+const cardSizeSchema = z.object({ width: cardEdge, height: cardEdge }).strict();export const deckCreateSchema = z.object({name: z.string().trim().min(1).max(DECK_NAME_MAX),