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
fix(creative-director): stop hiding installed vision models; add CD-wide model defaults
Adam Eivyb9c4ce53467f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 76cbba9c6b..39542d0e59 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Creative Director now has its own Model defaults.** The Creative Director index page gets a **Model defaults** button (deep-linkable at `?models=1`) that pins the provider + model every project uses for Treatment, Production plan, and Scene evaluation — the settings that previously existed only as three rows buried in the global AI Assignments table. Individual projects still override them from their own Models drawer, which now says which default it's inheriting; leaving a stage blank at the Creative Director level falls through to the system default provider, exactly as before. Both surfaces are the same drawer, so the two scopes can't drift.+- **The Brain daily log now saves itself.** Your entry is saved automatically as you type (about a second and a half after you pause, and at least every ten seconds during a long uninterrupted writing run), when you click away from the editor, when you switch tabs or navigate away, and when you background the tab or app — so a closed laptop or a backgrounded phone no longer loses the day. The toolbar shows the current state (`Unsaved…` / `Saving…` / `Saved`) in place of a toast on every autosave; the Save button and ⌘S still work and still confirm with a toast. Autosave never reverts what you're typing mid-save, never writes one day's text into another when you change dates, keeps debouncing instead of retrying per keystroke when the server is unreachable, and deliberately stands down when a dictated voice segment arrives while you have unsaved edits (the toolbar says "Autosave paused — save to keep your edits") — a full-content save would otherwise drop the segment.- [issue-2701] **Cerebras is now available as an AI provider.** Add your API key on the AI Providers page and PortOS can route AI-backed work through Cerebras's OpenAI-compatible endpoint (very high tokens/sec). Ships disabled with no key, so nothing calls it until you opt in; hit "Refresh models" after adding your key to pull the live model list. Existing installs pick the provider up automatically on restart. Cost estimates on /devtools/usage are also now accurate for `gpt-oss-120b` — it was previously billed at OpenAI GPT-5.4's rates, roughly 10x its real price.@@ -16,6 +18,7 @@## Fixed+- **The Scene evaluation model dropdown no longer comes up empty when you have vision models installed.** Picking Ollama for a Creative Director project's Scene evaluation showed an empty model list (and a bare text box) even with vision-capable models pulled, because the browser decided what counts as a vision model from a hard-coded list of model-name patterns that knew `gemma-3` but not `gemma4` — so `gemma4:e4b` and `qwen3.6:35b` were filtered out as if they were text-only. Vision pickers now ask the server, which reads each model's real capabilities from the backend itself (Ollama's `/api/show`, LM Studio's `vlm` tag), and union that with the old name matching — so a newer model family shows up without waiting for the pattern list to catch up, and nothing that used to be offered disappears. The AI Assignments table's vision rows get the same fix. Also, the Scene evaluation stage now explains that it needs an API provider (Ollama / LM Studio) and can't use an agent CLI/TUI provider such as Claude Ollama TUI — pinning one there was silently ignored at run time — and a provider with no vision model installed now says so, with a link to install one, instead of showing an empty dropdown.- The Chief of Staff status panel's Learning card no longer spills its skipped-task count outside the card on mobile. The "(3 skipped)" note used to sit beside the success rate on one line, where it was too wide to fit a narrow card and rendered past the border; it now sits on its own line under the percentage and truncates if it can't fit.- The Brain **Graph** tab is now usable on a phone. The graph canvas sizes itself to the viewport instead of a fixed 500px (which overflowed a landscape phone entirely and left no room to scroll past a canvas that swallows drags), the controls bar stacks into readable rows instead of cramming a breadcrumb, seven type filters, and both buttons into one line, and the type filters wrap with a proper tap target. The legend — ten rows that blanketed a phone-sized graph — now shows automatically only when there's room for it and collapses behind a "Legend" toggle everywhere else, including a landscape phone (which is wide enough to look like a desktop but far too short). The hover tooltip no longer flashes under your finger advertising a double-click that touch can't do (tap the node and use the detail panel's "Explore connections" instead), and it no longer runs off the right edge in a narrow window. "Explore connections" moved out of a cramped side column onto its own full-width row, above the record text so it stays reachable on a long entry.- [issue-2669] The Series Pipeline no longer shows two stacked error toasts when a stage or arc action fails — the custom-catch callers now pass `{ silent: true }` so only their own toast fires, not the shared `request()` helper's default one too. Swept the pipeline stages/canvas area (ArcCanvas, the Audio/ComicPages/ComicScript/Storyboards/Idea stages, and the Pipeline series/issue/manuscript-editor pages, including the `useLockToggle` volume lock and the `useAsyncAction` editorial review) and threaded a backward-compatible `options` arg into the affected API wrappers (arc generate/verify/resolve/derive, volume beats + episodes, season and issue CRUD, stage generate/extract/render/refine, manuscript fetch + completeness, and the audio line/music-library calls).diff --git a/PLAN.md b/PLAN.mdindex 7d26d061ea..6a68aa1d17 100644--- a/PLAN.md+++ b/PLAN.md@@ -158,3 +158,7 @@ by `/do:replan --issues`:### Creative Director agents should not push code (deferred — needs a distinct completion contract)- [ ] **Suppress `/simplify` + `/do:push` + PR in CD agent completions WITHOUT breaking their API output contract.** CD plan/treatment/evaluation agents persist their real output via an HTTP call in the task BODY (e.g. `PATCH http://localhost:5555/api/creative-director/{id}/plan` — see the plan prompt), and use the `.agent-done` sentinel only as a *done-signal* (a short markdown summary that PortOS's 2s poll consumes to finalize the run). They run on `main` (`useWorktree:false`, `configCodingOnMain:true`) and make no repo changes, so the trailing `/simplify` → `/do:push` completion is both pointless and dangerous (a `/do:push` on main could commit stray working-tree files). The fix must remove `/simplify`+`/do:push`+PR from the CD completion while KEEPING (a) the sentinel done-signal handshake and (b) the task-body PATCH as the output channel. **Do NOT reuse `discardWorktree`** — codex review (2026-07-16) correctly flagged that it routes to `buildProgrammaticOutputCompletionSection`, whose wording ("your *only* output channel is the `.agent-done` sentinel; write your result there in the payload format from your instructions") directly contradicts the PATCH and could make the agent write the plan to the sentinel instead of PATCHing → plan never persists → project stalls/re-enqueues. `readOnly:true` is also wrong ("read data and report findings only" contradicts the PATCH, and the CLI read-only path emits no sentinel). The correct fix is a NEW completion contract (e.g. a `apiOutput`/`noRepoOutput` metadata flag) that emits: "This task persists its output via the API/tool calls described above and makes no repo changes — do NOT run `/simplify`, `/do:push`, `/do:pr`, `git commit/push`, or open a PR; when done write a short summary to the sentinel to signal completion." Thread the flag through the completion selection in `server/services/agentPromptBuilder.js` (lines ~1137-1160 light path + the full-context path ~790, and whichever of `buildTuiCompletionSection`/`buildCliCompletionSection` CD actually reaches — confirm via a regenerated CD prompt fixture) and add a test asserting the CD prompt contains the sentinel step but NO `/do:push`/`/do:pr`/`/simplify`. Deferred from this PR because it needs a carefully-designed prompt-contract change + fixture test, not a rushed flag reuse.++### Vision model pickers — `useProviderModels` auto-select ignores a late-arriving capability list++- [ ] **Make `VisionProviderPicker` union the server's authoritative vision-model list into its filter (the `gemma4` gap), which requires `useProviderModels` to re-pick its initial model when `modelFilter` changes.** The Creative Director / AI Assignments vision pickers were fixed to union `useVisionModelIds()` (the server's `/api/local-llm/vision-models`, which reads Ollama `/api/show` capabilities + LM Studio's `vlm` tag) into `visionLocalModelFilter`, because the client id regex in `client/src/utils/providers.js#isVisionModel` knows `gemma-3` but not `gemma4`/`glm-4.6v` and so hides installed VLMs. `client/src/components/universe/VisionProviderPicker.jsx:27` has the identical defect but was **deliberately left unfixed**: it gets its models from `useProviderModels({ modelFilter })`, and passing a `modelFilter` whose identity changes when the fetch resolves (null → Set) breaks two ways. (1) `pickInitialModel` (`client/src/hooks/useProviderModels.js:44-49`) closes over `modelFilter`, and `load` (`:52-68`) depends on `pickInitialModel`, so the `useEffect(() => { load(); }, [load])` at `:70` re-fires a redundant `api.getProviders()`. (2) Worse, `load` guards initial selection behind `hasSetInitialRef` (`:62`), so the model auto-picked during the FIRST load (regex-only, returns `''` when the only VLM is `gemma4`) is never re-picked once the authoritative set lands — leaving `selectedModel === ''` while `availableModels` now contains `gemma4`, which renders the "no vision model" blocker (`VisionProviderPicker.jsx:41` `noVisionModel = hasProviders && !selectedModel`) *next to a populated dropdown*. That half-fixed state is more confusing than the current consistent-but-wrong behavior, so the change was reverted. Doing it properly means teaching `useProviderModels` to re-run its initial pick when `modelFilter`'s identity changes (e.g. re-pick when the current `selectedModel` is no longer in / absent from `availableModels`, without clobbering a deliberate user clear) — that hook is shared by many callers and `VisionProviderPicker` has no test file, so it needs its own PR + tests. Deferred from the Creative-Director vision-picker fix, which is scoped to the `assignment*` helpers and ships fully tested.diff --git a/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx b/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsxindex 7585a633cf..a965d13c74 100644--- a/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx+++ b/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx@@ -3,8 +3,9 @@ import { Link } from 'react-router-dom';import { Bot, Save } from 'lucide-react';import Drawer from '../Drawer.jsx';import toast from '../ui/Toast';-import { getAiAssignments } from '../../services/api';+import { getAiAssignments, updateAiAssignment } from '../../services/api';import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';+import useVisionModelIds from '../../hooks/useVisionModelIds.js';import {providerDisplayName,assignmentProviderOptions,@@ -12,54 +13,66 @@ import {assignmentDefaultModel,} from '../../utils/providers.js';-// Per-project AI model override drawer (per-project CD provider/model pins).-// Lets the user pin the treatment / plan / evaluation stage to a specific-// provider + model ON THIS PROJECT, overriding the global AI Assignment. A-// blank stage inherits the global pin (shown as the "Inherit" hint). The same-// resolution the server does (`resolveStagePin`) is mirrored here only for the-// inherit-hint label — the authoritative resolve happens server-side.--// Each CD cognitive stage maps 1:1 to a global AI Assignment entry keyed-// `settings.creativeDirector.<key>`, so the drawer reads that entry's-// `providerTypes` (which providers are eligible: CLI/TUI for treatment+plan,-// API for evaluation) and its current global provider/model (the inherit hint).+// Creative Director provider/model pins, at either of two scopes:+//+// scope="global" — the CD-wide defaults (`settings.creativeDirector.<stage>`),+// which every project inherits. Saved through the same+// AI Assignments endpoint the global settings table uses.+// scope="project" — this project's `modelOverrides.<stage>`, overriding the+// CD-wide default. A blank stage inherits (shown as a hint).+//+// The server's `resolveStagePin` resolves project override → CD default →+// system default; the inherit hint mirrors that chain for display only.const STAGES = [{ key: 'treatment', label: 'Treatment', help: 'Agent that turns the brief into a treatment + scene plan.' },{ key: 'plan', label: 'Production plan', help: 'Agent that converts a production directive into an executable plan.' },- { key: 'evaluation', label: 'Scene evaluation', help: 'Vision model that judges each rendered scene.' },+ {+ key: 'evaluation',+ label: 'Scene evaluation',+ // Spelled out because the provider list here looks "missing" otherwise: this+ // stage is a direct HTTP vision call (sceneEvaluator's `usableApiProvider`+ // requires `type === 'api'`), so agent CLI/TUI providers are not eligible+ // and pinning one would be silently ignored at run time.+ help: 'Vision model that judges each rendered scene. Runs as a direct vision call, so it needs an API provider (Ollama / LM Studio) — agent CLI/TUI providers such as Claude Ollama TUI can\'t serve it.',+ },];const assignmentIdFor = (key) => `settings.creativeDirector.${key}`;-// The inherit-hint text: what this stage resolves to when left blank.-const inheritLabel = (entry, providers) => {- if (!entry?.providerId) return 'system default';- const name = providerDisplayName(providers, entry.providerId);- return entry.model ? `${name} · ${entry.model}` : name;-};+// Every draft source (blank / project record / assignments payload) is the same+// shape — one `{ providerId, model }` per stage, blank-normalized — so they+// share one builder. Stable key order is what makes the JSON dirty-compare+// below sound.+const draftsFrom = (pinFor) => Object.fromEntries(STAGES.map(({ key }) => {+ const pin = pinFor(key) || {};+ return [key, { providerId: pin.providerId || '', model: pin.model || '' }];+}));-const draftsFromProject = (project) => {- const overrides = project?.modelOverrides || {};- return Object.fromEntries(STAGES.map(({ key }) => {- const o = overrides[key] || {};- return [key, { providerId: o.providerId || '', model: o.model || '' }];- }));+const blankDrafts = () => draftsFrom(() => null);+const draftsFromProject = (project) => draftsFrom((key) => project?.modelOverrides?.[key]);+const draftsFromAssignments = (assignments) => {+ const byId = Object.fromEntries((assignments || []).map((e) => [e.id, e]));+ return draftsFrom((key) => byId[assignmentIdFor(key)]);};-export default function CreativeDirectorModelsDrawer({ open, onClose, project, onSaved }) {+export default function CreativeDirectorModelsDrawer({ open, onClose, project, onSaved, scope = 'project' }) {+ const isGlobal = scope === 'global';const [loading, setLoading] = useState(true);const [providers, setProviders] = useState([]);const [assignments, setAssignments] = useState([]);- const [drafts, setDrafts] = useState(() => draftsFromProject(project));+ const [drafts, setDrafts] = useState(blankDrafts);+ // The persisted values the drafts were seeded from — the dirty check compares+ // against this rather than a live prop, so the detail page's 5s project poll+ // can't flip `dirty` mid-edit, and the global scope (whose baseline arrives+ // async with the assignments fetch) uses the same code path.+ const [baseline, setBaseline] = useState(blankDrafts);const [saving, setSaving] = useState(false);+ // Authoritative vision-capable ids from the backends themselves; `null` until+ // fetched, which `assignmentModelOptions` degrades to its id regex for. Gated+ // on `open` — this drawer stays mounted on a closed page.+ const visionModelIds = useVisionModelIds(open);- // Re-seed drafts from the persisted project only on the open transition or a- // project swap — NOT on `project` object identity, which the parent's 5s poll- // mints fresh every tick and would otherwise wipe in-progress edits.- useEffect(() => {- if (open) setDrafts(draftsFromProject(project));- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, project?.id]);+ const seed = useCallback((next) => { setDrafts(next); setBaseline(next); }, []);const load = useCallback(async () => {setLoading(true);@@ -70,44 +83,96 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, oif (next) {setProviders(next.providers || []);setAssignments(next.assignments || []);+ // Global drafts live in the assignments payload, so they can only be+ // seeded once it lands.+ if (isGlobal) seed(draftsFromAssignments(next.assignments));}setLoading(false);- }, []);+ }, [isGlobal, seed]);useEffect(() => { if (open) load(); }, [open, load]);+ // Project drafts come off the record, so re-seed on the open transition or a+ // project swap — NOT on `project` object identity, which the parent's 5s poll+ // mints fresh every tick and would otherwise wipe in-progress edits.+ useEffect(() => {+ if (open && !isGlobal) seed(draftsFromProject(project));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, isGlobal, project?.id]);+const entryById = useMemo(() => Object.fromEntries((assignments || []).map((e) => [e.id, e])),[assignments],);- // draftsFromProject normalizes every stage to a stable key order, so a plain- // JSON compare against the persisted project is a sound dirty check.+ // Both seeds normalize every stage to a stable key order, so a plain JSON+ // compare is a sound dirty check.const dirty = useMemo(- () => JSON.stringify(drafts) !== JSON.stringify(draftsFromProject(project)),- [drafts, project],+ () => JSON.stringify(drafts) !== JSON.stringify(baseline),+ [drafts, baseline],);const setStage = (key, patch) =>setDrafts((prev) => ({ ...prev, [key]: { ...prev[key], ...patch } }));- const handleSave = async () => {- setSaving(true);+ // The inherit-hint text: what a blank project stage resolves to. Reads the+ // CD-wide default off the assignment entry, falling back to the system default.+ const inheritLabel = (entry) => {+ if (!entry?.providerId) return 'system default';+ const name = providerDisplayName(providers, entry.providerId);+ return entry.model ? `${name} · ${entry.model}` : name;+ };++ const saveGlobal = async () => {+ // Only PUT stages that actually changed — each call re-derives the whole+ // assignments payload server-side.+ let latest = null;+ for (const { key, label } of STAGES) {+ const d = drafts[key];+ if (JSON.stringify(d) === JSON.stringify(baseline[key])) continue;+ const next = await updateAiAssignment(+ assignmentIdFor(key),+ { providerId: d.providerId || null, model: d.model || null },+ { silent: true },+ ).catch((err) => {+ toast.error(`Failed to save ${label}: ${err.message}`);+ return null;+ });+ if (!next) return null;+ latest = next;+ }+ return latest;+ };++ const saveProject = async () => {// Only send stages that name a provider; a blank provider means "inherit".const modelOverrides = {};for (const { key } of STAGES) {const d = drafts[key];if (d?.providerId) modelOverrides[key] = { providerId: d.providerId, ...(d.model ? { model: d.model } : {}) };}- const updated = await updateCreativeDirectorProject(project.id, { modelOverrides }, { silent: true })+ return updateCreativeDirectorProject(project.id, { modelOverrides }, { silent: true }).catch((err) => {toast.error(err.message || 'Failed to save model overrides');return null;});+ };++ const handleSave = async () => {+ setSaving(true);+ const result = isGlobal ? await saveGlobal() : await saveProject();setSaving(false);- if (!updated) return;- onSaved?.(updated.modelOverrides || {});- toast.success('Project model overrides saved');+ if (!result) return;+ if (isGlobal) {+ setAssignments(result.assignments || []);+ setProviders(result.providers || []);+ setBaseline(drafts);+ onSaved?.(drafts);+ toast.success('Creative Director model defaults saved');+ } else {+ onSaved?.(result.modelOverrides || {});+ toast.success('Project model overrides saved');+ }onClose?.();};@@ -115,8 +180,8 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o<Draweropen={open}onClose={onClose}- title="AI models for this project"- subtitle={project?.name}+ title={isGlobal ? 'Creative Director model defaults' : 'AI models for this project'}+ subtitle={isGlobal ? 'Applies to every Creative Director project' : project?.name}size="md">{loading ? (@@ -124,25 +189,41 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o) : (<div className="space-y-5"><p className="text-xs text-gray-400">- Pin the provider + model for each Creative Director stage on this project. Leave a- stage on <span className="text-gray-300">Inherit</span> to use the global{' '}- <Link to="/settings/ai-assignments" className="text-port-accent hover:underline">AI Assignment</Link>.+ {isGlobal ? (+ <>+ Pin the provider + model every Creative Director project uses by default. Leave a+ stage blank to use the <span className="text-gray-300">system default provider</span>.+ An individual project can still override these from its own Models drawer. Also+ editable from{' '}+ <Link to="/settings/ai-assignments" className="text-port-accent hover:underline">AI Assignments</Link>.+ </>+ ) : (+ <>+ Pin the provider + model for each Creative Director stage on this project. Leave a+ stage on <span className="text-gray-300">Inherit</span> to use the{' '}+ <Link to="/creative-director" className="text-port-accent hover:underline">Creative Director default</Link>.+ </>+ )}</p>{STAGES.map((stage) => {const entry = entryById[assignmentIdFor(stage.key)];const draft = drafts[stage.key] || { providerId: '', model: '' };const providerOptions = assignmentProviderOptions(entry, providers);- const modelOptions = assignmentModelOptions(entry, providers, draft.providerId);- const overriding = !!draft.providerId;+ const modelOptions = assignmentModelOptions(entry, providers, draft.providerId, visionModelIds);+ const pinned = !!draft.providerId;+ // A vision stage on a local backend with nothing to offer means no+ // VLM is installed — say so instead of showing a bare text box that+ // reads as a broken dropdown.+ const noVisionModels = pinned && entry?.modelFilter === 'vision' && modelOptions.length === 0;return (<section key={stage.key} className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2"><div className="flex items-center gap-2"><Bot size={15} className="text-port-accent shrink-0" /><h3 className="text-sm font-medium text-white">{stage.label}</h3>- {!overriding && (+ {!pinned && !isGlobal && (<span className="ml-auto text-[11px] px-1.5 py-0.5 rounded bg-port-card border border-port-border text-gray-400">- Inherit: {inheritLabel(entry, providers)}+ Inherit: {inheritLabel(entry)}</span>)}</div>@@ -159,22 +240,22 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o// Vision-filtered stages (scene evaluation) seed the first// eligible VLM when the provider's default is text-only.const nextDefault = providerId- ? assignmentDefaultModel(entry, providers, providerId)+ ? assignmentDefaultModel(entry, providers, providerId, visionModelIds): '';// Seed the provider's default model on switch; clearing the- // provider (Inherit) clears the model too.+ // provider clears the model too.setStage(stage.key, { providerId, model: nextDefault });}}className="bg-port-card border border-port-border rounded px-2 py-2 text-sm text-white">- <option value="">Inherit global</option>+ <option value="">{isGlobal ? 'System default' : 'Inherit default'}</option>{providerOptions.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></label><label className="flex flex-col gap-1"><span className="text-[11px] uppercase tracking-wide text-gray-500">Model</span>- {!overriding ? (+ {!pinned ? (<div className="text-sm text-gray-600 py-2">—</div>) : modelOptions.length > 0 ? (<select@@ -197,6 +278,14 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o)}</label></div>++ {noVisionModels && (+ <p className="text-xs text-port-warning">+ No vision-capable models found on this provider.{' '}+ <Link to="/settings/local-llm" className="underline hover:text-port-warning/80">Install a VLM</Link>+ {' '}(e.g. qwen3-vl, gemma4) or type a model id above.+ </p>+ )}</section>);})}diff --git a/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx b/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsxindex c81aa6c666..7e3f43b979 100644--- a/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx+++ b/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx@@ -2,13 +2,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';-vi.mock('../../services/api', () => ({ getAiAssignments: vi.fn() }));+vi.mock('../../services/api', () => ({ getAiAssignments: vi.fn(), updateAiAssignment: vi.fn() }));vi.mock('../../services/apiCreativeDirector.js', () => ({ updateCreativeDirectorProject: vi.fn() }));+vi.mock('../../services/apiLocalLlm', () => ({ getVisionModels: vi.fn() }));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));import CreativeDirectorModelsDrawer from './CreativeDirectorModelsDrawer.jsx';-import { getAiAssignments } from '../../services/api';+import { getAiAssignments, updateAiAssignment } from '../../services/api';import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';+import { getVisionModels } from '../../services/apiLocalLlm';const ASSIGNMENTS = {providers: [@@ -45,6 +47,9 @@ const renderDrawer = (project, props = {}) => render(beforeEach(() => {vi.clearAllMocks();getAiAssignments.mockResolvedValue(ASSIGNMENTS);+ // Default: the local backends report no vision models, so the id regex alone+ // decides — the pre-`useVisionModelIds` behavior.+ getVisionModels.mockResolvedValue({ models: [] });});describe('CreativeDirectorModelsDrawer', () => {@@ -99,4 +104,125 @@ describe('CreativeDirectorModelsDrawer', () => {// Text-only default is replaced by the first eligible VLM.expect(modelSelect.value).toBe('qwen2.5vl:latest');});++ // The reported bug: the client id regex knows `gemma-3` but not `gemma4`, so a+ // user whose only installed VLMs are gemma4/qwen3.6 saw an EMPTY Scene+ // evaluation model picker. The server already knows better via Ollama's+ // /api/show capabilities, so its verdict is unioned in.+ it('offers vision models the id regex misses but the server reports as vision-capable', async () => {+ getVisionModels.mockResolvedValue({+ models: [+ { providerId: 'ollama', backend: 'ollama', id: 'gemma4:26b', vision: true },+ { providerId: 'ollama', backend: 'ollama', id: 'llama3.2:latest', vision: true },+ ],+ });+ renderDrawer({ id: 'cd-1', name: 'Demo', modelOverrides: {} });+ await waitFor(() => expect(screen.getByLabelText('Scene evaluation provider')).toBeTruthy());+ await waitFor(() => expect(getVisionModels).toHaveBeenCalled());++ fireEvent.change(screen.getByLabelText('Scene evaluation provider'), { target: { value: 'ollama' } });++ const optionValues = Array.from(+ screen.getByLabelText('Scene evaluation model').querySelectorAll('option'),+ ).map((o) => o.value);+ // Server-reported ids the regex would have hidden.+ expect(optionValues).toContain('gemma4:26b');+ expect(optionValues).toContain('llama3.2:latest');+ // Union, not replacement — regex-matched ids the server didn't list survive.+ expect(optionValues).toContain('qwen2.5vl:latest');+ expect(optionValues).toContain('llava:latest');+ });++ it('does not fetch vision models while closed', async () => {+ // The drawer stays mounted on the page; the endpoint asks Ollama for every+ // installed model's capabilities, so a closed drawer must not pay for it.+ render(+ <MemoryRouter>+ <CreativeDirectorModelsDrawer open={false} onClose={vi.fn()} project={{ id: 'cd-1', name: 'Demo' }} />+ </MemoryRouter>,+ );+ await waitFor(() => expect(getAiAssignments).not.toHaveBeenCalled());+ expect(getVisionModels).not.toHaveBeenCalled();+ });++ it('falls back to the id regex when the vision-model fetch fails', async () => {+ getVisionModels.mockRejectedValue(new Error('ollama down'));+ renderDrawer({ id: 'cd-1', name: 'Demo', modelOverrides: {} });+ await waitFor(() => expect(screen.getByLabelText('Scene evaluation provider')).toBeTruthy());++ fireEvent.change(screen.getByLabelText('Scene evaluation provider'), { target: { value: 'ollama' } });++ const optionValues = Array.from(+ screen.getByLabelText('Scene evaluation model').querySelectorAll('option'),+ ).map((o) => o.value);+ expect(optionValues).toContain('qwen2.5vl:latest');+ expect(optionValues).not.toContain('llama3.2:latest');+ });++ it('warns instead of showing a bare text box when a vision provider has no VLM', async () => {+ getAiAssignments.mockResolvedValue({+ ...ASSIGNMENTS,+ providers: [+ ...ASSIGNMENTS.providers.filter((p) => p.id !== 'ollama'),+ // Text-only local backend — nothing survives the vision filter.+ { id: 'ollama', name: 'Ollama', type: 'api', enabled: true, defaultModel: 'llama3.2:latest', models: ['llama3.2:latest'] },+ ],+ });+ renderDrawer({ id: 'cd-1', name: 'Demo', modelOverrides: {} });+ await waitFor(() => expect(screen.getByLabelText('Scene evaluation provider')).toBeTruthy());++ fireEvent.change(screen.getByLabelText('Scene evaluation provider'), { target: { value: 'ollama' } });++ expect(screen.getByText(/No vision-capable models found/i)).toBeTruthy();+ });++ describe('global scope', () => {+ const renderGlobal = (props = {}) => render(+ <MemoryRouter>+ <CreativeDirectorModelsDrawer scope="global" open onClose={vi.fn()} {...props} />+ </MemoryRouter>,+ );++ it('seeds drafts from the CD-wide assignment defaults', async () => {+ getAiAssignments.mockResolvedValue({+ ...ASSIGNMENTS,+ assignments: ASSIGNMENTS.assignments.map((a) => (+ a.id === 'settings.creativeDirector.treatment'+ ? { ...a, providerId: 'agent-a', model: 'a-big' }+ : a+ )),+ });+ renderGlobal();+ await waitFor(() => expect(screen.getByLabelText('Treatment provider')).toBeTruthy());+ expect(screen.getByLabelText('Treatment provider').value).toBe('agent-a');+ expect(screen.getByLabelText('Treatment model').value).toBe('a-big');+ // Global scope pins the system default, so there is no "inherit" hint.+ expect(screen.queryByText(/Inherit:/)).toBeNull();+ });++ it('saves only the changed stage through the AI assignment endpoint', async () => {+ updateAiAssignment.mockResolvedValue(ASSIGNMENTS);+ renderGlobal();+ await waitFor(() => expect(screen.getByLabelText('Treatment provider')).toBeTruthy());++ fireEvent.change(screen.getByLabelText('Treatment provider'), { target: { value: 'agent-a' } });+ fireEvent.click(screen.getByRole('button', { name: /Save/i }));++ await waitFor(() => expect(updateAiAssignment).toHaveBeenCalledTimes(1));+ expect(updateAiAssignment.mock.calls[0][0]).toBe('settings.creativeDirector.treatment');+ expect(updateAiAssignment.mock.calls[0][1]).toEqual({ providerId: 'agent-a', model: 'a-default' });+ // Untouched stages are not PUT.+ expect(updateAiAssignment.mock.calls.map((c) => c[0])).not.toContain('settings.creativeDirector.plan');+ });++ it('does not write the project record', async () => {+ updateAiAssignment.mockResolvedValue(ASSIGNMENTS);+ renderGlobal();+ await waitFor(() => expect(screen.getByLabelText('Production plan provider')).toBeTruthy());+ fireEvent.change(screen.getByLabelText('Production plan provider'), { target: { value: 'agent-a' } });+ fireEvent.click(screen.getByRole('button', { name: /Save/i }));+ await waitFor(() => expect(updateAiAssignment).toHaveBeenCalled());+ expect(updateCreativeDirectorProject).not.toHaveBeenCalled();+ });+ });});diff --git a/client/src/components/settings/AiAssignmentsTab.jsx b/client/src/components/settings/AiAssignmentsTab.jsxindex 1496917c82..444b8fc3c7 100644--- a/client/src/components/settings/AiAssignmentsTab.jsx+++ b/client/src/components/settings/AiAssignmentsTab.jsx@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom';import { ArrowRight, Bot, RefreshCw, Save, Search } from 'lucide-react';import toast from '../ui/Toast';import { getAiAssignments, updateAiAssignment } from '../../services/api';+import useVisionModelIds from '../../hooks/useVisionModelIds.js';import {providerDisplayName,assignmentProviderOptions,@@ -45,6 +46,10 @@ export default function AiAssignmentsTab() {const [fromProvider, setFromProvider] = useState('');const [toProvider, setToProvider] = useState('');const [bulkSaving, setBulkSaving] = useState(false);+ // Authoritative vision-capable ids straight from the local backends, so a+ // vision-filtered row (Scene evaluation) isn't reduced to an empty list by+ // the client's id regex not knowing a newer VLM family.+ const visionModelIds = useVisionModelIds();const load = useCallback(async () => {setLoading(true);@@ -131,7 +136,7 @@ export default function AiAssignmentsTab() {const savedIds = [];for (const entry of targets) {// Vision-filtered rows seed the first eligible VLM, not a text-only default.- const targetDefaultModel = assignmentDefaultModel(entry, data.providers, toProvider);+ const targetDefaultModel = assignmentDefaultModel(entry, data.providers, toProvider, visionModelIds);const nextModel = entry.modelEditable === false ? (drafts[entry.id]?.model || '') : targetDefaultModel;const next = await updateAiAssignment(entry.id, {providerId: toProvider,@@ -252,7 +257,7 @@ export default function AiAssignmentsTab() {{filtered.map((entry) => {const draft = drafts[entry.id] || getDraft(entry);const providerOptions = assignmentProviderOptions(entry, data.providers);- const modelOptions = assignmentModelOptions(entry, data.providers, draft.providerId);+ const modelOptions = assignmentModelOptions(entry, data.providers, draft.providerId, visionModelIds);const dirty = !sameDraft(entry, draft);return (<tr key={entry.id} className="align-top">@@ -274,7 +279,7 @@ export default function AiAssignmentsTab() {const nextProviderId = e.target.value;// Vision-filtered rows (e.g. Scene evaluation) seed the// first eligible VLM when the provider default is text-only.- const nextDefault = assignmentDefaultModel(entry, data.providers, nextProviderId);+ const nextDefault = assignmentDefaultModel(entry, data.providers, nextProviderId, visionModelIds);setDraft(entry.id, { providerId: nextProviderId, model: entry.modelEditable === false ? draft.model : nextDefault });}}aria-label={`Provider for ${entry.label}`}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex a00a99e1fd..d3b4d7a739 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -148,6 +148,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. || `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |+| `useVisionModelIds` | `Set` of model ids the server reports as vision-capable from each backend's own capability metadata (Ollama `/api/show`, LM Studio `type:'vlm'`); `null` until fetched. | Any VISION model picker — pass to `visionLocalModelFilter` / `assignmentModelOptions` so a new multimodal family (`gemma4`) isn't hidden by the stale client id regex. || `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. || `useSingToScore` | Capture a sung melody from the mic and transcribe it into lead-sheet notation. `start()` opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; `stop()` runs the `transcribePitchTrack` pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes `{ phase, beat, result, error, start, stop, reset }`; tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-score panel. || `useSongTraining` | Drives a song training run over one scope (whole song or a sliced section) on top of `useColorMatch`: counts in, walks + grades the scope's score, then folds the finished take into the rolling progress history (`songProgress.recordAttempt`) and surfaces the next aggregate via `onProgress`. Supports looping (auto-restart after a run) and keeps a `lastSummary`. Exposes `{ running, countingIn, noteColors, activeIndex, lastSummary, start, stop }`; cancels pending loop relaunches on stop/unmount. | The Song editor's Training panel. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex fe4cc0e496..67d9489641 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -42,6 +42,7 @@ export { default as useMounted } from './useMounted.js';export { default as usePendingListRows } from './usePendingListRows.js';export { default as usePopoverPosition } from './usePopoverPosition.js';export { default as useLocalModels } from './useLocalModels.js';+export { default as useVisionModelIds } from './useVisionModelIds.js';export { default as usePreviewRoute } from './usePreviewRoute.js';export { default as useProviderModels } from './useProviderModels.js';export { default as useRowDraft } from './useRowDraft.js';diff --git a/client/src/hooks/useVisionModelIds.js b/client/src/hooks/useVisionModelIds.jsnew file mode 100644index 0000000000..ade80f5f5b--- /dev/null+++ b/client/src/hooks/useVisionModelIds.js@@ -0,0 +1,48 @@+import { useEffect, useState } from 'react';+import { getVisionModels } from '../services/apiLocalLlm';++/**+ * The set of model ids the SERVER reports as vision-capable, fetched once.+ *+ * The client's `isVisionModel` regex can only recognize multimodal families it+ * was written against, so it silently goes stale as new ones ship — it knew+ * `gemma-3` but not `gemma4`, which left a user whose only installed VLMs were+ * `gemma4:e4b` and `qwen3.6:35b` staring at an EMPTY Scene Evaluation model+ * picker. The server has the authoritative answer (Ollama's `/api/show`+ * capabilities and LM Studio's `type: 'vlm'` tag), so vision pickers union this+ * set with the regex via `visionLocalModelFilter`.+ *+ * Returns `null` until the fetch resolves (and on failure). Callers union this+ * set with the regex, so it only ever ADDS models the regex didn't recognize —+ * `null` (or an empty set, when no local VLM is installed) simply degrades to+ * today's regex-only behavior rather than blanking a picker. Widening is the+ * safe direction: a stale regex hides a model the user has, whereas this set+ * can't speak for a custom provider pointing at a host the server never+ * enumerated, so neither source is allowed to veto the other.+ *+ * @param {boolean} [enabled] gate the fetch — pass a drawer/modal's `open` when+ * the host stays mounted while closed. The endpoint asks Ollama for each+ * installed model's capabilities, so it is not free enough to fire on every+ * render of a page that merely *contains* a closed picker. Fetches once and+ * keeps the result if `enabled` later goes false.+ * @returns {Set<string>|null}+ */+export default function useVisionModelIds(enabled = true) {+ const [ids, setIds] = useState(null);++ useEffect(() => {+ if (!enabled || ids) return undefined;+ let canceled = false;+ // Secondary control — a failed fetch falls back to the regex rather than+ // toasting over the host page.+ getVisionModels({ silent: true })+ .then((res) => {+ if (canceled) return;+ setIds(new Set((res?.models || []).map((m) => m?.id).filter(Boolean)));+ })+ .catch(() => {});+ return () => { canceled = true; };+ }, [enabled, ids]);++ return ids;+}diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxindex 859c53e37a..8b12e85670 100644--- a/client/src/pages/CreativeDirector.jsx+++ b/client/src/pages/CreativeDirector.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback } from 'react';import { Link, useLocation, useNavigate, useSearchParams } from 'react-router-dom';-import { Plus, Film, Trash2, Play, Pause, FlaskConical, Sparkles, Wand2 } from 'lucide-react';+import { Plus, Film, Trash2, Play, Pause, FlaskConical, Sparkles, Wand2, SlidersHorizontal } from 'lucide-react';import toast from '../components/ui/Toast';import {listCreativeDirectorProjects,@@ -18,6 +18,7 @@ import ModelSelect from '../components/ModelSelect';import PageHeader from '../components/PageHeader';import Drawer from '../components/Drawer';import DirectiveComposer from '../components/creative-director/DirectiveComposer.jsx';+import CreativeDirectorModelsDrawer from '../components/creative-director/CreativeDirectorModelsDrawer.jsx';const ASPECT_RATIOS = ['16:9', '9:16', '1:1'];const QUALITIES = ['draft', 'standard', 'high'];@@ -46,6 +47,7 @@ export default function CreativeDirector() {// that creates a studio production project seeded with a directive. State is// hoisted here (above the Drawer body) per the Drawer state-hoisting rule.const directiveOpen = searchParams.get('new') === 'directive';+ const modelsOpen = searchParams.get('models') === '1';const [directiveName, setDirectiveName] = useState('');const [directiveDraft, setDirectiveDraft] = useState(EMPTY_DIRECTIVE);const [creatingDirective, setCreatingDirective] = useState(false);@@ -158,6 +160,16 @@ export default function CreativeDirector() {setSearchParams((prev) => { const n = new URLSearchParams(prev); n.delete('new'); return n; }, { replace: true });};+ // URL-driven so the CD-wide model defaults are deep-linkable, mirroring the+ // per-project drawer's `?models=1` on the detail page.+ const setModelsOpen = (open) => {+ setSearchParams((prev) => {+ const n = new URLSearchParams(prev);+ if (open) n.set('models', '1'); else n.delete('models');+ return n;+ }, { replace: true });+ };+const handleCreateDirective = async () => {if (!directiveName.trim()) { toast.error('Name is required'); return; }if (!directiveDraft.goal.trim()) { toast.error('Directive goal is required'); return; }@@ -257,6 +269,14 @@ export default function CreativeDirector() {<Wand2 className="w-4 h-4" />New directive</button>+ <button+ onClick={() => setModelsOpen(true)}+ className="flex items-center gap-2 bg-port-card border border-port-border hover:bg-port-card/60 text-port-text px-3 py-2 rounded text-sm"+ title="Pin the provider + model every Creative Director project uses by default"+ >+ <SlidersHorizontal className="w-4 h-4" />+ Model defaults+ </button><buttononClick={() => { setShowForm((s) => !s); clearRemix(); }}className="flex items-center gap-2 bg-port-accent hover:bg-port-accent/80 text-white px-3 py-2 rounded text-sm"@@ -478,6 +498,12 @@ export default function CreativeDirector() {</button></div></Drawer>++ <CreativeDirectorModelsDrawer+ scope="global"+ open={modelsOpen}+ onClose={() => setModelsOpen(false)}+ /></div>);}diff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex be2d288620..13a55ad177 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -197,12 +197,29 @@ export const filterGenerationModels = (models) =>* lists untouched — `isVisionModel` is a local-name heuristic and would wrongly* hide multimodal cloud models whose ids don't encode vision (`gpt-4o`,* `claude-*`). Pass as `useProviderModels({ modelFilter: visionLocalModelFilter })`.+ *+ * `visionModelIds` is the AUTHORITATIVE set the server reports from each+ * backend's own capability metadata (Ollama `/api/show`, LM Studio+ * `type: 'vlm'`) — see `useVisionModelIds`. It is unioned with, not substituted+ * for, the id regex: the regex alone goes stale every time a new multimodal+ * family ships (it knew `gemma-3` but not `gemma4`, so a user with only+ * `gemma4:e4b` + `qwen3.6:35b` installed saw an EMPTY vision picker), while the+ * authoritative set alone can't speak for a custom provider pointing at a+ * remote host the server never enumerated. Pass `null` (the default) when the+ * list hasn't loaded — a `null` set degrades to today's regex-only behavior,+ * whereas an EMPTY set correctly means "fetched: no vision models installed".+ * The union is still intersected with the provider's own `models` list by the+ * callers below, so an id can never leak onto a provider that lacks it.+ ** @param {string} id* @param {{endpoint?:string,name?:string}} [provider]+ * @param {Set<string>|null} [visionModelIds]* @returns {boolean}*/-export const visionLocalModelFilter = (id, provider) =>- localBackendForProvider(provider) ? isVisionModel(id) : true;+export const visionLocalModelFilter = (id, provider, visionModelIds = null) =>+ localBackendForProvider(provider)+ ? visionModelIds?.has(id) === true || isVisionModel(id)+ : true;/*** Classify a provider as a local-LLM backend by its id/endpoint/name, so callers@@ -433,9 +450,11 @@ export const assignmentProviderOptions = (entry, providers) => {* When `entry.modelFilter === 'vision'`, LOCAL backends (Ollama / LM Studio)* are reduced to vision-capable models via `visionLocalModelFilter` so the* Scene Evaluation (and other vision) pickers can't offer text-only ids.- * Cloud/API providers are left intact by that filter.+ * Cloud/API providers are left intact by that filter. Pass `visionModelIds`+ * (from `useVisionModelIds`) so that reduction uses the backend's own+ * capability metadata instead of the id regex alone.*/-export const assignmentModelOptions = (entry, providers, providerId) => {+export const assignmentModelOptions = (entry, providers, providerId, visionModelIds = null) => {const provider = providers.find((p) => p.id === providerId);const raw = Array.isArray(entry?.modelOptions)? entry.modelOptions@@ -446,7 +465,7 @@ export const assignmentModelOptions = (entry, providers, providerId) => {.map((m) => (typeof m === 'string' ? m : m?.id)).filter(Boolean);if (entry?.modelFilter === 'vision') {- return models.filter((id) => visionLocalModelFilter(id, provider));+ return models.filter((id) => visionLocalModelFilter(id, provider, visionModelIds));}return models;};@@ -457,13 +476,13 @@ export const assignmentModelOptions = (entry, providers, providerId) => {* filtered options — a local backend's text-only `defaultModel` must not be* seeded into the Scene Evaluation picker.*/-export const assignmentDefaultModel = (entry, providers, providerId) => {+export const assignmentDefaultModel = (entry, providers, providerId, visionModelIds = null) => {if (!providerId) return '';const provider = providers.find((p) => p.id === providerId);if (!provider) return '';const def = provider.defaultModel || '';if (entry?.modelFilter !== 'vision') return def;- const models = assignmentModelOptions(entry, providers, providerId);+ const models = assignmentModelOptions(entry, providers, providerId, visionModelIds);if (def && models.includes(def)) return def;return models[0] || '';};diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 95629b80a0..d3b2053ace 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -428,6 +428,27 @@ describe('visionLocalModelFilter', () => {expect(visionLocalModelFilter('nomic-embed-text', ollama)).toBe(false);});+ it('accepts a server-reported vision id the stale id regex does not know', () => {+ // The id regex knows `gemma-3` but not `gemma4` — without the authoritative+ // set, a user whose only VLMs are gemma4/qwen3.6 gets an empty picker.+ expect(visionLocalModelFilter('gemma4:e4b', ollama)).toBe(false);+ expect(visionLocalModelFilter('gemma4:e4b', ollama, new Set(['gemma4:e4b']))).toBe(true);+ expect(visionLocalModelFilter('qwen3.6:35b', ollama, new Set(['qwen3.6:35b']))).toBe(true);+ });++ it('unions rather than replaces — the set never vetoes a regex match', () => {+ // Fetched-but-empty (no local VLM reported) still keeps regex matches, and a+ // set that omits a model the regex knows must not hide it.+ expect(visionLocalModelFilter('llava:latest', ollama, new Set())).toBe(true);+ expect(visionLocalModelFilter('llava:latest', ollama, new Set(['gemma4:e4b']))).toBe(true);+ // ...and it still can't smuggle a text-only model past the filter.+ expect(visionLocalModelFilter('qwen2.5-coder:32b', ollama, new Set(['gemma4:e4b']))).toBe(false);+ });++ it('leaves cloud providers untouched regardless of the authoritative set', () => {+ expect(visionLocalModelFilter('gpt-4o', cloud, new Set())).toBe(true);+ });+it('leaves cloud/API providers untouched (multimodal ids that miss the local regex pass)', () => {// gpt-4o / claude are multimodal but their ids do not encode "vision";// a local-name heuristic must NOT hide them on a cloud provider.