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
feat: focus AI assignments on persisted mappings
[._.]/ Adam Eivya203f2e663b1
diff --git a/client/src/components/settings/AiAssignmentsTab.jsx b/client/src/components/settings/AiAssignmentsTab.jsxindex 7f367d98f1..54df40da52 100644--- a/client/src/components/settings/AiAssignmentsTab.jsx+++ b/client/src/components/settings/AiAssignmentsTab.jsx@@ -14,17 +14,22 @@ import {assignmentModelOptions,assignmentDefaultModel,assignmentToolUseState,+ effortLevelsForProvider,+ effortAwareModelOptions,+ effortSurvivingModel,withToolUseOptionLabel,} from '../../utils/providers.js';const getDraft = (entry) => ({providerId: entry.providerId || '',model: entry.model || '',+ effort: entry.effort || '',});const sameDraft = (entry, draft) =>(entry.providerId || '') === (draft?.providerId || '') &&- (entry.model || '') === (draft?.model || '');+ (entry.model || '') === (draft?.model || '') &&+ (entry.effort || '') === (draft?.effort || '');// Rebuild the draft map from a server response without discarding edits the// user has in-flight on OTHER rows: reset only the rows we just saved (and seed@@ -40,6 +45,7 @@ const reconcileDrafts = (prev, assignments, savedIds) => {// Provider label with the settings-table's "Default" fallback for an unset id.const providerName = (providers, id) => providerDisplayName(providers, id, 'Default');+const effortOptionsFor = (provider, model) => effortLevelsForProvider(provider, model) || [];// Chip key for rows with no provider pinned. An empty string already means// "no provider chip selected", so unset rows need their own sentinel to be@@ -53,10 +59,13 @@ export default function AiAssignmentsTab() {const [drafts, setDrafts] = useState({});const [query, setQuery] = useState('');const [area, setArea] = useState('all');- const [scope, setScope] = useState('all');+ const [assignmentType, setAssignmentType] = useState('all');const [providerFilter, setProviderFilter] = useState('');const [fromProvider, setFromProvider] = useState('');+ const [fromModel, setFromModel] = useState('');const [toProvider, setToProvider] = useState('');+ const [toModel, setToModel] = useState('');+ const [toEffort, setToEffort] = 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@@ -89,6 +98,38 @@ export default function AiAssignmentsTab() {[data.assignments]);+ const assignmentTypes = useMemo(+ () => ['all', ...Array.from(new Set((data.assignments || []).map((entry) => entry.assignmentType))).filter(Boolean).sort()],+ [data.assignments]+ );++ const sourceProviders = useMemo(() => {+ const assigned = new Set((data.assignments || []).map((entry) => entry.providerId).filter(Boolean));+ const byId = new Map(data.providers.map((provider) => [provider.id, provider]));+ return Array.from(assigned, (id) => byId.get(id) || { id, name: id });+ }, [data.assignments, data.providers]);++ const sourceModels = useMemo(() => Array.from(new Set(+ (data.assignments || [])+ .filter((entry) => entry.providerId === fromProvider && entry.model)+ .map((entry) => entry.model)+ )).sort(), [data.assignments, fromProvider]);++ const targetProvider = data.providers.find((provider) => provider.id === toProvider);+ const targetModels = effortAwareModelOptions(targetProvider, '');++ const bulkTargets = useMemo(() => {+ if (!fromProvider || !toProvider) return [];+ return (data.assignments || []).filter((entry) => (+ entry.editable !== false &&+ entry.providerEditable !== false &&+ entry.providerId === fromProvider &&+ (!fromModel || entry.model === fromModel) &&+ assignmentProviderOptions(entry, data.providers).some((option) => option.id === toProvider) &&+ (!toModel || assignmentModelOptions(entry, data.providers, toProvider, visionIdsByProvider).includes(toModel))+ ));+ }, [data.assignments, data.providers, fromModel, fromProvider, toModel, toProvider, visionIdsByProvider]);+// Everything except the provider chips, so the chip counts describe what the// OTHER filters left behind (faceted-filter behaviour) instead of a global// total that stops matching the table the moment you type in the search box.@@ -96,10 +137,11 @@ export default function AiAssignmentsTab() {const q = query.trim().toLowerCase();return (data.assignments || []).filter((entry) => {if (area !== 'all' && entry.area !== area) return false;- if (scope !== 'all' && entry.scope !== scope) return false;+ if (assignmentType !== 'all' && entry.assignmentType !== assignmentType) return false;if (!q) return true;return [entry.area,+ entry.assignmentType,entry.label,entry.source,entry.providerId,@@ -107,7 +149,7 @@ export default function AiAssignmentsTab() {entry.notes,].some((value) => String(value || '').toLowerCase().includes(q));});- }, [area, data.assignments, query, scope]);+ }, [area, assignmentType, data.assignments, query]);const filtered = useMemo(() => {if (!providerFilter) return preProviderFiltered;@@ -149,6 +191,7 @@ export default function AiAssignmentsTab() {const next = await updateAiAssignment(entry.id, {providerId: draft.providerId || null,model: draft.model || null,+ effort: draft.effort || null,}, { silent: true }).catch((err) => {toast.error(`Save failed: ${err.message}`);return null;@@ -161,27 +204,20 @@ export default function AiAssignmentsTab() {};const runBulkMigration = async () => {- if (!fromProvider || !toProvider || fromProvider === toProvider || bulkSaving) return;- const targets = (data.assignments || []).filter((entry) => (- entry.editable !== false &&- entry.providerEditable !== false &&- (drafts[entry.id]?.providerId || entry.providerId || '') === fromProvider &&- assignmentProviderOptions(entry, data.providers).some((option) => option.id === toProvider)- ));- if (targets.length === 0) {+ if (!fromProvider || !toProvider || bulkSaving) return;+ if (bulkTargets.length === 0) {toast.error('No editable assignments match that provider');return;}setBulkSaving(true);let latest = data;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, visionIdsByProvider);- const nextModel = entry.modelEditable === false ? (drafts[entry.id]?.model || '') : targetDefaultModel;+ for (const entry of bulkTargets) {+ const nextModel = entry.modelEditable === false ? (entry.model || '') : toModel;const next = await updateAiAssignment(entry.id, {providerId: toProvider,model: nextModel || null,+ ...(entry.effortEditable ? { effort: toEffort || null } : {}),}, { silent: true }).catch((err) => {toast.error(`${entry.label}: ${err.message}`);return null;@@ -194,7 +230,7 @@ export default function AiAssignmentsTab() {setData(latest);setDrafts((prev) => reconcileDrafts(prev, latest.assignments, savedIds));setBulkSaving(false);- toast.success(`Migrated ${savedIds.length} assignment${savedIds.length === 1 ? '' : 's'}`);+ toast.success(`Replaced ${savedIds.length} assignment${savedIds.length === 1 ? '' : 's'}`);};if (loading) {@@ -207,7 +243,10 @@ export default function AiAssignmentsTab() {<div className="min-w-0 flex-1"><div className="flex items-center gap-2 text-gray-200"><Bot size={18} className="text-port-accent" />- <h2 className="text-lg font-semibold">AI Assignments</h2>+ <div>+ <h2 className="text-lg font-semibold">AI Assignments</h2>+ <p className="mt-0.5 text-sm text-gray-500">Manage persisted feature, workflow, and scheduled-task assignments.</p>+ </div></div><TabPillstabs={providerTabs}@@ -222,44 +261,87 @@ export default function AiAssignmentsTab() {/></div>- <div className="w-full min-w-0 max-w-full shrink-0 bg-port-card border border-port-border rounded-lg p-3 space-y-2 xl:w-[520px]">- <div className="flex flex-col sm:flex-row gap-2">- <FormField label="Migrate from provider" labelClassName="sr-only" className="min-w-0 flex-1">+ <div className="w-full min-w-0 max-w-full shrink-0 bg-port-card border border-port-border rounded-lg p-3 space-y-2 xl:w-[720px]">+ <div className="text-xs font-medium uppercase tracking-wide text-gray-500">Replace assignments</div>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-[1fr_1fr_auto_1fr_1fr]">+ <FormField label="Replace from provider" labelClassName="sr-only" className="min-w-0 flex-1"><selectvalue={fromProvider}- onChange={(e) => setFromProvider(e.target.value)}- aria-label="Migrate from provider"+ onChange={(e) => { setFromProvider(e.target.value); setFromModel(''); }}+ aria-label="Replace from provider"className="w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white"><option value="">From provider</option>- {data.providers.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}+ {sourceProviders.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}+ </select>+ </FormField>+ <FormField label="Replace from model" labelClassName="sr-only" className="min-w-0">+ <select+ value={fromModel}+ onChange={(e) => setFromModel(e.target.value)}+ aria-label="Replace from model"+ disabled={!fromProvider}+ className="w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white disabled:opacity-50"+ >+ <option value="">Any model</option>+ {sourceModels.map((model) => <option key={model} value={model}>{model}</option>)}</select></FormField>- <div className="hidden sm:flex items-center text-gray-500">+ <div className="hidden sm:flex items-center justify-center text-gray-500"><ArrowRight size={16} /></div>- <FormField label="Migrate to provider" labelClassName="sr-only" className="min-w-0 flex-1">+ <FormField label="Replace with provider" labelClassName="sr-only" className="min-w-0 flex-1"><selectvalue={toProvider}- onChange={(e) => setToProvider(e.target.value)}- aria-label="Migrate to provider"+ onChange={(e) => { setToProvider(e.target.value); setToModel(''); setToEffort(''); }}+ aria-label="Replace with provider"className="w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white"><option value="">To provider</option>- {data.providers.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}+ {data.providers.filter((p) => p.enabled !== false).map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></FormField>+ <FormField label="Replace with model" labelClassName="sr-only" className="min-w-0">+ <select+ value={toModel}+ onChange={(e) => { setToModel(e.target.value); setToEffort(''); }}+ aria-label="Replace with model"+ disabled={!toProvider}+ className="w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white disabled:opacity-50"+ >+ <option value="">Default model</option>+ {targetModels.map((model) => <option key={model} value={model}>{model}</option>)}+ </select>+ </FormField>+ </div>+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end">+ {effortOptionsFor(targetProvider, toModel || targetProvider?.defaultModel).length > 0 && (+ <FormField label="Target effort" labelClassName="sr-only" className="min-w-0 sm:w-48">+ <select+ value={toEffort}+ onChange={(e) => setToEffort(e.target.value)}+ aria-label="Target effort"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white"+ >+ <option value="">Default effort</option>+ {effortOptionsFor(targetProvider, toModel || targetProvider?.defaultModel).map((effort) => (+ <option key={effort} value={effort}>{effort}</option>+ ))}+ </select>+ </FormField>+ )}<buttontype="button"onClick={runBulkMigration}- disabled={!fromProvider || !toProvider || fromProvider === toProvider || bulkSaving}+ disabled={!fromProvider || !toProvider || bulkTargets.length === 0 || bulkSaving}className="shrink-0 px-3 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded text-sm">- {bulkSaving ? 'Migrating...' : 'Migrate'}+ {bulkSaving ? 'Replacing...' : 'Replace all matches'}</button></div><p className="text-xs text-gray-500">- Bulk migration updates editable rows that currently use the source provider and resets their model to the target default.+ {fromProvider && toProvider ? `${bulkTargets.length} compatible match${bulkTargets.length === 1 ? '' : 'es'}. ` : ''}+ Match every persisted assignment on a provider, optionally narrow by model, then point compatible assignments to the new provider and model. Effort applies to scheduled assignments that persist it.</p></div></div>@@ -282,12 +364,9 @@ export default function AiAssignmentsTab() {{areas.map((a) => <option key={a} value={a}>{a === 'all' ? 'All areas' : a}</option>)}</select></FormField>- <FormField label="Filter by scope" labelClassName="sr-only" className="contents">- <select value={scope} onChange={(e) => setScope(e.target.value)} aria-label="Filter by scope" className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white">- <option value="all">All scopes</option>- <option value="global">Global</option>- <option value="record">Record pins</option>- <option value="runtime">Runtime call sites</option>+ <FormField label="Filter by assignment type" labelClassName="sr-only" className="contents">+ <select value={assignmentType} onChange={(e) => setAssignmentType(e.target.value)} aria-label="Filter by assignment type" className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white">+ {assignmentTypes.map((type) => <option key={type} value={type}>{type === 'all' ? 'All assignment types' : type}</option>)}</select></FormField><button type="button" onClick={load} className="flex items-center justify-center gap-1.5 px-3 py-2 bg-port-border hover:bg-port-border/80 text-sm text-white rounded">@@ -304,6 +383,7 @@ export default function AiAssignmentsTab() {<th className="px-3 py-2 font-medium min-w-[220px]">Assignment</th><th className="px-3 py-2 font-medium min-w-[210px]">Provider</th><th className="px-3 py-2 font-medium min-w-[220px]">Model</th>+ <th className="px-3 py-2 font-medium min-w-[130px]">Effort</th><th className="px-3 py-2 font-medium min-w-[160px]">Source</th><th className="px-3 py-2 font-medium w-[90px]"></th></tr>@@ -330,7 +410,7 @@ export default function AiAssignmentsTab() {<tr key={entry.id} className="align-top"><td className="px-3 py-3 text-sm text-gray-300 whitespace-nowrap"><div>{entry.area}</div>- <div className="mt-1 text-xs text-gray-600">{entry.scope}</div>+ <div className="mt-1 text-xs text-gray-600">{entry.assignmentType}</div></td><td className="px-3 py-3"><div className="text-sm text-white">{entry.label}</div>@@ -348,7 +428,7 @@ export default function AiAssignmentsTab() {// 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, visionIdsByProvider);- setDraft(entry.id, { providerId: nextProviderId, model: entry.modelEditable === false ? draft.model : nextDefault });+ setDraft(entry.id, { providerId: nextProviderId, model: entry.modelEditable === false ? draft.model : nextDefault, effort: '' });}}aria-label={`Provider for ${entry.label}`}disabled={visionUnknown}@@ -367,7 +447,10 @@ export default function AiAssignmentsTab() {<FormField label={`Model for ${entry.label}`} labelClassName="sr-only"><selectvalue={draft.model}- onChange={(e) => setDraft(entry.id, { model: e.target.value })}+ onChange={(e) => setDraft(entry.id, {+ model: e.target.value,+ effort: effortSurvivingModel(selectedProvider, e.target.value, draft.effort),+ })}aria-label={`Model for ${entry.label}`}className="w-full bg-port-card border border-port-border rounded px-2 py-2 text-sm text-white">@@ -398,6 +481,25 @@ export default function AiAssignmentsTab() {</ToolUseWarning>)}</td>+ <td className="px-3 py-3">+ {entry.effortEditable && effortOptionsFor(selectedProvider, draft.model || selectedProvider?.defaultModel).length > 0 ? (+ <FormField label={`Effort for ${entry.label}`} labelClassName="sr-only">+ <select+ value={draft.effort}+ onChange={(e) => setDraft(entry.id, { effort: e.target.value })}+ aria-label={`Effort for ${entry.label}`}+ className="w-full bg-port-card border border-port-border rounded px-2 py-2 text-sm text-white"+ >+ <option value="">Default</option>+ {effortOptionsFor(selectedProvider, draft.model || selectedProvider?.defaultModel).map((effort) => (+ <option key={effort} value={effort}>{effort}</option>+ ))}+ </select>+ </FormField>+ ) : (+ <span className="text-sm text-gray-600">—</span>+ )}+ </td><td className="px-3 py-3 text-xs text-gray-500"><div className="break-all">{entry.source}</div>{entry.link && (@@ -424,7 +526,7 @@ export default function AiAssignmentsTab() {})}{filtered.length === 0 && (<tr>- <td colSpan="6" className="px-3 py-8 text-center text-sm text-gray-500">No assignments match the current filters.</td>+ <td colSpan="7" className="px-3 py-8 text-center text-sm text-gray-500">No assignments match the current filters.</td></tr>)}</tbody>diff --git a/client/src/components/settings/AiAssignmentsTab.test.jsx b/client/src/components/settings/AiAssignmentsTab.test.jsxindex 421acabf56..742d1328ae 100644--- a/client/src/components/settings/AiAssignmentsTab.test.jsx+++ b/client/src/components/settings/AiAssignmentsTab.test.jsx@@ -8,7 +8,7 @@ vi.mock('../../services/apiLocalLlm', () => ({ getVisionModels: vi.fn(), getToolvi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));import AiAssignmentsTab from './AiAssignmentsTab.jsx';-import { getAiAssignments } from '../../services/api';+import { getAiAssignments, updateAiAssignment } from '../../services/api';import { getVisionModels, getToolUseModels } from '../../services/apiLocalLlm';import { __resetToolUseModelIdsCache } from '../../hooks/useToolUseModelIds.js';@@ -33,6 +33,7 @@ const entry = (over) => ({label: 'Production planning model',source: 'settings.creativeDirector.plan',scope: 'global',+ assignmentType: 'Creative workflows',editable: true,providerEditable: true,modelEditable: true,@@ -45,6 +46,8 @@ const entry = (over) => ({notes: '',providerId: '',model: '',+ effort: '',+ effortEditable: false,...over,});@@ -211,3 +214,68 @@ describe('AiAssignmentsTab provider chips', () => {expect(screen.getByText('Bravo row')).toBeInTheDocument();});});++describe('AiAssignmentsTab assignment management', () => {+ it('filters persisted assignments by assignment type', async () => {+ getAiAssignments.mockResolvedValue(payload([+ entry({ id: 'creative', label: 'Creative row', assignmentType: 'Creative workflows' }),+ entry({ id: 'scheduled', label: 'Scheduled row', area: 'Chief of Staff', assignmentType: 'Scheduled tasks' }),+ ]));+ renderTab();++ await userEvent.selectOptions(await screen.findByLabelText('Filter by assignment type'), 'Scheduled tasks');+ expect(screen.getByText('Scheduled row')).toBeInTheDocument();+ expect(screen.queryByText('Creative row')).not.toBeInTheDocument();+ });++ it('replaces an exact model mapping within the same provider', async () => {+ const before = entry({ id: 'creative', label: 'Creative row', providerId: 'ollama', model: 'gemma2:9b' });+ const after = { ...before, model: 'qwen3.6:35b' };+ getAiAssignments.mockResolvedValue(payload([before]));+ updateAiAssignment.mockResolvedValue(payload([after]));+ renderTab();++ await userEvent.selectOptions(await screen.findByLabelText('Replace from provider'), 'ollama');+ await userEvent.selectOptions(screen.getByLabelText('Replace from model'), 'gemma2:9b');+ await userEvent.selectOptions(screen.getByLabelText('Replace with provider'), 'ollama');+ await userEvent.selectOptions(screen.getByLabelText('Replace with model'), 'qwen3.6:35b');+ await userEvent.click(screen.getByRole('button', { name: 'Replace all matches' }));++ await waitFor(() => expect(updateAiAssignment).toHaveBeenCalledWith(+ 'creative',+ { providerId: 'ollama', model: 'qwen3.6:35b' },+ { silent: true },+ ));+ });++ it('saves reasoning effort on scheduled assignments that support it', async () => {+ const providers = [+ ...PROVIDERS,+ { id: 'claude-code', name: 'Claude Code', type: 'cli', enabled: true, defaultModel: 'opus', models: ['opus'], ollamaBacked: false },+ ];+ const before = entry({+ id: 'cos.job.audit',+ area: 'Chief of Staff',+ assignmentType: 'Scheduled tasks',+ label: 'Scheduled job: Audit',+ providerId: 'claude-code',+ model: 'opus',+ providerTypes: ['cli', 'tui'],+ needsTools: true,+ effortEditable: true,+ });+ const after = { ...before, effort: 'xhigh' };+ getAiAssignments.mockResolvedValue({ providers, activeProvider: 'claude-code', assignments: [before] });+ updateAiAssignment.mockResolvedValue({ providers, activeProvider: 'claude-code', assignments: [after] });+ renderTab();++ await userEvent.selectOptions(await screen.findByLabelText('Effort for Scheduled job: Audit'), 'xhigh');+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateAiAssignment).toHaveBeenCalledWith(+ 'cos.job.audit',+ { providerId: 'claude-code', model: 'opus', effort: 'xhigh' },+ { silent: true },+ ));+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex a5b5571e3b..b08902528d 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -14,6 +14,7 @@ import { getInstanceFeatures, updateInstanceFeature } from '../services/instanceimport { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';+import { EFFORT_LEVELS } from '../lib/providerModels.js';import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, openWorldSnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -21,6 +22,7 @@ const router = Router();const aiAssignmentUpdateSchema = z.object({providerId: z.string().trim().max(128).nullable().optional(),model: z.string().trim().max(300).nullable().optional(),+ effort: z.enum(EFFORT_LEVELS).nullable().optional(),}).strict();// Server-authoritative bounds the client UI can render directly so the formdiff --git a/server/services/aiAssignments.js b/server/services/aiAssignments.jsindex ffbb86d81f..0c70142489 100644--- a/server/services/aiAssignments.js+++ b/server/services/aiAssignments.js@@ -8,6 +8,7 @@ import * as taskScheduleService from './taskSchedule.js';import * as loopsService from './loops.js';import * as featureAgentsService from './featureAgents.js';import * as agentPersonalitiesService from './agentPersonalities.js';+import * as autonomousJobsService from './autonomousJobs.js';import { getVoiceConfig, updateVoiceConfig } from './voice/config.js';import { isPlainObject } from '../lib/objects.js';import { ServerError } from '../lib/errorHandler.js';@@ -51,10 +52,13 @@ const makeEntry = ({source,providerId = null,model = null,+ effort = null,+ assignmentType = 'Configuration',scope = 'global',editable = true,providerEditable = true,modelEditable = true,+ effortEditable = false,providerTypes = textProviderTypes,providerOptions = null,modelOptions = null,@@ -77,10 +81,13 @@ const makeEntry = ({source,providerId: providerId || null,model: model || null,+ effort: effort || null,+ assignmentType,scope,editable,providerEditable,modelEditable,+ effortEditable,providerTypes,providerOptions,modelOptions,@@ -104,46 +111,6 @@ const patchSettingsPath = async (path, value) => {await updateSettings({ [top]: root });};-const addProviderRegistryEntries = (entries, providersData) => {- const { activeProvider, providers = [] } = providersData;- entries.push(makeEntry({- id: 'provider.active',- area: 'Provider Registry',- label: 'System default provider',- source: 'data/providers.json activeProvider',- providerId: activeProvider,- modelEditable: false,- notes: 'Fallback for tools that do not pin their own provider.',- }));-- for (const provider of providers) {- for (const field of ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel']) {- entries.push(makeEntry({- id: `provider.model.${provider.id}.${field}`,- area: 'Provider Registry',- label: `${provider.name} ${field.replace('Model', '').toLowerCase() || 'default'} model`,- source: `provider ${provider.id}.${field}`,- providerId: provider.id,- model: provider[field] || null,- providerEditable: false,- modelOptions: pickModelOptions(provider),- notes: field === 'defaultModel' ? 'Used when an assignment leaves model blank.' : 'Used by task-tier model selection.',- link: '/ai',- }));- }- entries.push(makeEntry({- id: `provider.fallback.${provider.id}`,- area: 'Provider Registry',- label: `${provider.name} fallback provider`,- source: `provider ${provider.id}.fallbackProvider`,- providerId: provider.fallbackProvider || null,- modelEditable: false,- notes: 'Used when this provider is rate-limited or unavailable.',- link: '/ai',- }));- }-};-const addSettingsEntries = async (entries) => {const settings = await getSettings();const voice = await getVoiceConfig().catch(() => settings.voice || {});@@ -169,6 +136,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: `settings.${key}`,area: 'Automation',+ assignmentType: 'Agents & automation',label,source: `settings.${key}`,providerId: settings[key]?.providerId || null,@@ -182,6 +150,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: 'settings.creativeDirector.treatment',area: 'Creative Director',+ assignmentType: 'Creative workflows',label: 'Treatment generation model',source: 'settings.creativeDirector.treatment',providerId: settings.creativeDirector?.treatment?.providerId || null,@@ -194,6 +163,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: 'settings.creativeDirector.plan',area: 'Creative Director',+ assignmentType: 'Creative workflows',label: 'Production planning model',source: 'settings.creativeDirector.plan',providerId: settings.creativeDirector?.plan?.providerId || null,@@ -206,6 +176,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: 'settings.creativeDirector.evaluation',area: 'Creative Director',+ assignmentType: 'Creative workflows',label: 'Scene evaluation vision model',source: 'settings.creativeDirector.evaluation',providerId: settings.creativeDirector?.evaluation?.providerId || null,@@ -221,6 +192,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: 'settings.voice.llm',area: 'Voice',+ assignmentType: 'Voice & messaging',label: 'Conversational LLM',source: 'settings.voice.llm',providerId: voice.llm?.provider || null,@@ -231,6 +203,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: 'settings.voice.vision',area: 'Voice',+ assignmentType: 'Voice & messaging',label: 'Screen vision model',source: 'settings.voice.llm.visionModel',providerId: voice.llm?.provider || null,@@ -242,6 +215,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: 'settings.voice.codeAgent',area: 'Voice',+ assignmentType: 'Voice & messaging',label: 'Delegated coding agent',source: 'settings.voice.llm.codeAgent',providerId: voice.llm?.codeAgent?.provider || null,@@ -255,6 +229,7 @@ const addSettingsEntries = async (entries) => {entries.push(makeEntry({id: `settings.messages.${action}`,area: 'Messages',+ assignmentType: 'Voice & messaging',label: `${action[0].toUpperCase()}${action.slice(1)} assistant`,source: `settings.messages.${action}`,providerId: cfg.providerId || messages.providerId || null,@@ -289,6 +264,7 @@ const addRecordEntries = async (entries) => {loops,featureAgents,socialAgents,+ autonomousJobs,] = await Promise.all([brainService.loadMeta().catch(() => null),universeService.listUniverses().catch(() => []),@@ -298,6 +274,7 @@ const addRecordEntries = async (entries) => {loopsService.getLoops().catch(() => []),featureAgentsService.getAllFeatureAgents().catch(() => []),agentPersonalitiesService.getAllAgents().catch(() => []),+ autonomousJobsService.getAllJobs().catch(() => []),]);if (brainMeta) {@@ -317,6 +294,7 @@ const addRecordEntries = async (entries) => {entries.push(makeEntry({id: `universe.${universe.id}`,area: 'Universe Builder',+ assignmentType: 'World & story building',label: universe.name,source: `universe ${universe.id}.llm`,providerId: universe.llm?.provider || null,@@ -332,6 +310,7 @@ const addRecordEntries = async (entries) => {entries.push(makeEntry({id: `story.${session.id}`,area: 'Story Builder',+ assignmentType: 'World & story building',label: session.title,source: `story session ${session.id}.llm`,providerId: session.llm?.provider || null,@@ -347,6 +326,7 @@ const addRecordEntries = async (entries) => {entries.push(makeEntry({id: `pipeline.series.${s.id}`,area: 'Pipeline',+ assignmentType: 'World & story building',label: s.name,source: `pipeline series ${s.id}.llm`,providerId: s.llm?.provider || null,@@ -358,28 +338,34 @@ const addRecordEntries = async (entries) => {}for (const [taskType, task] of Object.entries(schedule?.tasks || {})) {- if (task.providerId || task.model) {+ if (task.providerId || task.model || task.effort) {entries.push(makeEntry({id: `cos.task.${taskType}`,area: 'Chief of Staff',+ assignmentType: 'Scheduled tasks',label: `Scheduled task: ${taskType}`,source: `cos task-schedule ${taskType}`,providerId: task.providerId || null,model: task.model || null,+ effort: task.effort || null,+ effortEditable: true,scope: 'record',...agentEntry,link: '/cos/config',}));}for (const [index, stage] of (task.taskMetadata?.pipeline?.stages || []).entries()) {- if (stage?.providerId || stage?.model) {+ if (stage?.providerId || stage?.model || stage?.effort) {entries.push(makeEntry({id: `cos.taskStage.${taskType}.${index}`,area: 'Chief of Staff',+ assignmentType: 'Scheduled tasks',label: `${taskType} stage: ${stage.name || index + 1}`,source: `cos task ${taskType}.taskMetadata.pipeline.stages[${index}]`,providerId: stage.providerId || null,model: stage.model || null,+ effort: stage.effort || null,+ effortEditable: true,scope: 'record',...agentEntry,link: '/cos/config',@@ -393,6 +379,7 @@ const addRecordEntries = async (entries) => {entries.push(makeEntry({id: `loop.${loop.id}`,area: 'Loops',+ assignmentType: 'Agents & automation',label: loop.name || loop.id,source: `loop ${loop.id}.providerId`,providerId: loop.providerId || null,@@ -410,6 +397,7 @@ const addRecordEntries = async (entries) => {entries.push(makeEntry({id: `featureAgent.${agent.id}`,area: 'Feature Agents',+ assignmentType: 'Agents & automation',label: agent.name,source: `feature agent ${agent.id}`,providerId: agent.providerId || null,@@ -431,6 +419,7 @@ const addRecordEntries = async (entries) => {entries.push(makeEntry({id: `socialAgent.${agent.id}.${key}`,area: 'Social Agents',+ assignmentType: 'Agents & automation',label: `${agent.name} ${key}`,source: `agent personality ${agent.id}.aiConfig.${key}`,providerId: cfg.providerId || null,@@ -440,37 +429,22 @@ const addRecordEntries = async (entries) => {}));}}-};-const addRuntimeCallSiteEntries = (entries) => {- const callSites = [- ['Ask', 'Ask conversations', '/ask', 'Per-request provider/model override, otherwise the active provider resolves at run time.'],- ['Brain', 'Capture/retry/digest run buttons', '/brain/inbox', 'Uses Brain defaults unless a caller passes a one-off provider/model override.'],- ['Catalog', 'Catalog AI extraction', '/catalog', 'Accepts a one-off provider override for extraction jobs.'],- ['Digital Twin', 'Tests, enrichment, import, traits, taste summaries', '/digital-twin/overview', 'Most actions require a provider/model in the request and do not persist it as a default.'],- ['Insights', 'Theme and narrative refresh', '/insights/overview', 'Refresh endpoints accept provider/model per run.'],- ['Media', 'Prompt refinement', '/media/image', 'Prompt refine jobs carry their own provider/model in the request.'],- ['Meatspace POST', 'LLM drill generation and scoring', '/post/launcher', 'Drill runs accept provider/model per request and otherwise use active-provider fallback.'],- ['Standardizer', 'PM2 app standardization analysis', '/apps', 'Runs with an explicit provider when supplied, otherwise the active provider.'],- ['Social Agents', 'Generate post/comment actions', '/agents', 'Tool actions use the agent AI config when present, otherwise per-call values or defaults.'],- ['Universe Builder', 'Generate/refine/expand actions', '/universes', 'World actions use the universe pin when present and accept per-run overrides.'],- ['Pipeline', 'Stage generation, verification, canon extraction, editorial analysis', '/pipeline', 'Series pins are listed separately; individual action buttons may override provider/model for a single run.'],- ['Story Builder', 'Conductor steps and refinements', '/story-builder', 'Session pins are listed separately; step actions may override provider/model for a single run.'],- ['Voice', 'Screen description and image generation tools', '/settings/voice', 'Uses Voice LLM settings plus image-generation backend settings; per-tool calls may override image backend.'],- ];-- for (const [area, label, link, notes] of callSites) {+ for (const job of autonomousJobs) {+ if (job.type !== 'agent' || (!job.providerId && !job.model && !job.effort)) continue;entries.push(makeEntry({- id: `runtime.${area.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`,- area,- label,- source: 'runtime call site',- scope: 'runtime',- editable: false,- providerEditable: false,- modelEditable: false,- link,- notes,+ id: `cos.job.${job.id}`,+ area: 'Chief of Staff',+ assignmentType: 'Scheduled tasks',+ label: `Scheduled job: ${job.name}`,+ source: `cos autonomous job ${job.id}`,+ providerId: job.providerId || null,+ model: job.model || null,+ effort: job.effort || null,+ effortEditable: true,+ scope: 'record',+ ...agentEntry,+ link: '/cos/jobs',}));}};@@ -478,10 +452,8 @@ const addRuntimeCallSiteEntries = (entries) => {export async function getAiAssignments() {const providersData = await getAllProviders();const entries = [];- addProviderRegistryEntries(entries, providersData);await addSettingsEntries(entries);await addRecordEntries(entries);- addRuntimeCallSiteEntries(entries);return {providers: providersData.providers.map((p) => ({id: p.id,@@ -503,9 +475,14 @@ export async function getAiAssignments() {};}-export async function updateAiAssignment(id, { providerId, model } = {}) {+export async function updateAiAssignment(id, payload = {}) {+ const { providerId, model, effort } = payload;const nextProviderId = asNullable(providerId);const nextModel = asNullable(model);+ const nextEffort = asNullable(effort);+ // Older clients only send provider/model. Preserve a saved effort unless the+ // caller explicitly supplies the field (null is the intentional clear).+ const effortPatch = Object.hasOwn(payload, 'effort') ? { effort: nextEffort } : {};if (id === 'provider.active') {if (!nextProviderId) throw new ServerError('System default provider is required', { status: 400, code: 'VALIDATION_ERROR' });@@ -609,7 +586,7 @@ export async function updateAiAssignment(id, { providerId, model } = {}) {const task = await taskScheduleService.getTaskInterval(taskType);const stages = [...(task.taskMetadata?.pipeline?.stages || [])];if (!stages[index]) throw new ServerError(`Stage not found: ${id}`, { status: 404, code: 'NOT_FOUND' });- stages[index] = { ...stages[index], providerId: nextProviderId, model: nextModel };+ stages[index] = { ...stages[index], providerId: nextProviderId, model: nextModel, ...effortPatch };await taskScheduleService.updateTaskInterval(taskType, {taskMetadata: { ...(task.taskMetadata || {}), pipeline: { ...(task.taskMetadata?.pipeline || {}), stages } },});@@ -622,7 +599,18 @@ export async function updateAiAssignment(id, { providerId, model } = {}) {// write a junk schedule record — gate on the existing task set first.const status = await taskScheduleService.getScheduleStatus();if (!status?.tasks?.[taskType]) throw new ServerError(`Scheduled task not found: ${taskType}`, { status: 404, code: 'NOT_FOUND' });- await taskScheduleService.updateTaskInterval(taskType, { providerId: nextProviderId, model: nextModel });+ await taskScheduleService.updateTaskInterval(taskType, { providerId: nextProviderId, model: nextModel, ...effortPatch });+ return getAiAssignments();+ }++ if (id.startsWith('cos.job.')) {+ const jobId = id.replace('cos.job.', '');+ const updated = await autonomousJobsService.updateJob(jobId, {+ providerId: nextProviderId,+ model: nextModel,+ ...effortPatch,+ });+ if (!updated) throw new ServerError(`Scheduled job not found: ${jobId}`, { status: 404, code: 'NOT_FOUND' });return getAiAssignments();}diff --git a/server/services/aiAssignments.test.js b/server/services/aiAssignments.test.jsindex f386a91847..5cdd507be8 100644--- a/server/services/aiAssignments.test.js+++ b/server/services/aiAssignments.test.js@@ -37,6 +37,8 @@ const mocks = vi.hoisted(() => ({updateAgent: vi.fn(),getVoiceConfig: vi.fn(),updateVoiceConfig: vi.fn(),+ getAllJobs: vi.fn(),+ updateJob: vi.fn(),}));vi.mock('./settings.js', () => ({ getSettings: mocks.getSettings, updateSettings: mocks.updateSettings }));@@ -67,6 +69,7 @@ vi.mock('./agentPersonalities.js', () => ({updateAgent: mocks.updateAgent,}));vi.mock('./voice/config.js', () => ({ getVoiceConfig: mocks.getVoiceConfig, updateVoiceConfig: mocks.updateVoiceConfig }));+vi.mock('./autonomousJobs.js', () => ({ getAllJobs: mocks.getAllJobs, updateJob: mocks.updateJob }));const { getAiAssignments, updateAiAssignment } = await import('./aiAssignments.js');@@ -95,6 +98,7 @@ beforeEach(() => {mocks.getLoops.mockResolvedValue([]);mocks.getAllFeatureAgents.mockResolvedValue([]);mocks.getAllAgents.mockResolvedValue([]);+ mocks.getAllJobs.mockResolvedValue([]);});describe('getAiAssignments', () => {@@ -112,18 +116,40 @@ describe('getAiAssignments', () => {expect(Object.keys(p).sort()).toEqual(['defaultModel', 'enabled', 'id', 'models', 'name', 'ollamaBacked', 'type']);}const ids = result.assignments.map((a) => a.id);- expect(ids).toContain('provider.active');+ expect(ids).not.toContain('provider.active');+ expect(result.assignments.some((assignment) => assignment.area === 'Provider Registry')).toBe(false);+ expect(result.assignments.some((assignment) => assignment.scope === 'runtime')).toBe(false);expect(ids).toContain('settings.embeddings');expect(ids).toContain('settings.voice.vision');expect(ids).toContain('settings.creativeDirector.treatment');expect(ids).toContain('settings.creativeDirector.plan');expect(ids).toContain('settings.creativeDirector.evaluation');expect(ids).toContain('cos.task.morning-brief');+ expect(result.assignments.find((a) => a.id === 'cos.task.morning-brief').assignmentType).toBe('Scheduled tasks');// Scene evaluation is a vision call — clients filter local model lists to VLMs.const evaluation = result.assignments.find((a) => a.id === 'settings.creativeDirector.evaluation');expect(evaluation.modelFilter).toBe('vision');});+ it('includes explicitly assigned recurring agent jobs with model effort', async () => {+ mocks.getAllJobs.mockResolvedValue([+ { id: 'managed-app', name: 'Managed app audit', type: 'agent', providerId: 'claude', model: 'opus', effort: 'high' },+ { id: 'shell-job', name: 'Shell cleanup', type: 'shell', providerId: 'claude', model: 'opus' },+ { id: 'inherited', name: 'Inherited agent', type: 'agent', providerId: null, model: null, effort: null },+ ]);++ const result = await getAiAssignments();+ expect(result.assignments.find((a) => a.id === 'cos.job.managed-app')).toMatchObject({+ assignmentType: 'Scheduled tasks',+ providerId: 'claude',+ model: 'opus',+ effort: 'high',+ effortEditable: true,+ });+ expect(result.assignments.some((a) => a.id === 'cos.job.shell-job')).toBe(false);+ expect(result.assignments.some((a) => a.id === 'cos.job.inherited')).toBe(false);+ });+it('marks agent-harness assignments needsTools so every editor warns from one flag', async () => {const result = await getAiAssignments();const byId = Object.fromEntries(result.assignments.map((a) => [a.id, a]));@@ -208,10 +234,21 @@ describe('updateAiAssignment routing', () => {});it('cos.task.<existing> updates the schedule interval', async () => {+ await updateAiAssignment('cos.task.morning-brief', { providerId: 'claude', model: 'opus', effort: 'high' });+ expect(mocks.updateTaskInterval).toHaveBeenCalledWith('morning-brief', { providerId: 'claude', model: 'opus', effort: 'high' });+ });++ it('preserves scheduled-task effort when an older client omits the field', async () => {await updateAiAssignment('cos.task.morning-brief', { providerId: 'claude', model: 'opus' });expect(mocks.updateTaskInterval).toHaveBeenCalledWith('morning-brief', { providerId: 'claude', model: 'opus' });});+ it('cos.job.<existing> updates the recurring agent job assignment', async () => {+ mocks.updateJob.mockResolvedValue({ id: 'managed-app' });+ await updateAiAssignment('cos.job.managed-app', { providerId: 'claude', model: 'opus', effort: 'high' });+ expect(mocks.updateJob).toHaveBeenCalledWith('managed-app', { providerId: 'claude', model: 'opus', effort: 'high' });+ });+it('provider.model.<id>.<field> writes the field on the right provider, even when the id contains a dot', async () => {mocks.getProviderById.mockResolvedValue({ id: 'lm.studio', name: 'LM Studio', models: ['mistral'] });await updateAiAssignment('provider.model.lm.studio.heavyModel', { model: 'mistral' });@@ -240,6 +277,11 @@ describe('updateAiAssignment guards', () => {await expect(updateAiAssignment('featureAgent.gone', { providerId: 'x' })).rejects.toMatchObject({ status: 404 });});+ it('surfaces a 404 when a recurring job no longer exists', async () => {+ mocks.updateJob.mockResolvedValue(null);+ await expect(updateAiAssignment('cos.job.gone', { providerId: 'x' })).rejects.toMatchObject({ status: 404 });+ });+it('surfaces a 404 when a provider model target is missing', async () => {mocks.getProviderById.mockResolvedValue(null);await expect(updateAiAssignment('provider.model.ghost.defaultModel', { model: 'x' })).rejects.toMatchObject({ status: 404 });