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
honor the per-app provider/model pin on every CoS task type, not just layered-intelligence (#4783)
[._.]/ Adam Eivyd89e88eeda51
diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex d4f471172d..5af1828235 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -1,8 +1,8 @@import { Plus, Trash2, Brain } from 'lucide-react';import Banner from '../ui/Banner';-import ProviderModelSelector from '../ProviderModelSelector';+import AppProviderPin from '../cos/AppProviderPin';+import { providerPinPatch } from '../cos/constants';import LayeredIntelligenceOutcomes from './LayeredIntelligenceOutcomes';-import { filterSelectableModels } from '../../utils/providers';import { timeAgo } from '../../utils/formatters';import { formatLiReason, liReasonTone } from '../../utils/layeredIntelligenceReasons';import { INPUT_CLASS } from './constants';@@ -201,10 +201,12 @@ export function buildLayeredIntelligenceScheduleUpdate(baseline, current) {update.interval = interval;update.intervalMs = intervalMs;}- const curProvider = current.providerId || null;- if (curProvider !== (baseline.providerId || null)) update.providerId = curProvider;- const curModel = current.model || null;- if (curModel !== (baseline.model || null)) update.model = curModel;+ // Both sides through the shared normalizer so '' and null can't read as a+ // change, and a clear ships the same null every other surface sends (#4783).+ const cur = providerPinPatch(current.providerId, current.model);+ const base = providerPinPatch(baseline.providerId, baseline.model);+ if (cur.providerId !== base.providerId) update.providerId = cur.providerId;+ if (cur.model !== base.model) update.model = cur.model;return Object.keys(update).length > 0 ? update : null;}@@ -244,11 +246,6 @@ export default function LayeredIntelligenceTab({ appId, li, onChange, providers,const setSources = (patch) => onChange({ sources: { ...sources, ...patch } });const setCustom = (next) => setSources({ custom: next });- const currentProvider = providers.find(p => p.id === li.providerId);- const availableModels = currentProvider- ? filterSelectableModels(currentProvider.models || [currentProvider.defaultModel])- : [];-const toggleScope = (id, on) => {const next = on ? [...new Set([...allowedScopes, id])] : allowedScopes.filter(s => s !== id);onChange({ allowedScopes: next });@@ -305,17 +302,12 @@ export default function LayeredIntelligenceTab({ appId, li, onChange, providers,<div><span className="block text-sm text-gray-400 mb-1">AI provider</span>- <ProviderModelSelector+ <AppProviderPinproviders={providers}- selectedProviderId={li.providerId || ''}- selectedModel={li.model || ''}- availableModels={availableModels}- onProviderChange={id => onChange({ providerId: id || null, model: '' })}- onModelChange={model => onChange({ model: model || null })}+ providerId={li.providerId}+ model={li.model}+ onChange={onChange}label="Provider"- emptyProviderOption="Use default provider"- emptyModelOption="Default model"- alwaysShowModel/><p className="text-xs text-gray-500 mt-1">Leave on "Use default provider" to run the loop with the active CoS provider.</p></div>diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsxindex ff0a6ff346..2823303fe5 100644--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx@@ -197,6 +197,15 @@ describe('buildLayeredIntelligenceScheduleUpdate (per-app task override, #2322)'.toEqual({ providerId: 'claude-code', model: 'sonnet' });});+ // Third of the three surfaces that write this field. All three now emit the+ // SAME clear — explicit nulls — so "clear the pin" produces one stored result+ // no matter where the user did it (#4783).+ it('clears a stored pin with explicit nulls, like the Automation and Schedule surfaces', () => {+ const pinned = { ...baseline, providerId: 'claude-code', model: 'sonnet' };+ expect(buildLayeredIntelligenceScheduleUpdate(pinned, { ...pinned, providerId: '', model: '' }))+ .toEqual({ providerId: null, model: null });+ });+it('intervalFieldsFromMs maps standard cadences + falls back to daily', () => {expect(intervalFieldsFromMs(86400000)).toEqual({ interval: 'daily', intervalMs: 86400000 });expect(intervalFieldsFromMs(7 * 86400000)).toEqual({ interval: 'weekly', intervalMs: 7 * 86400000 });diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsxindex ab5a69c9b5..3a55a6db99 100644--- a/client/src/components/apps/tabs/AutomationTab.jsx+++ b/client/src/components/apps/tabs/AutomationTab.jsx@@ -5,11 +5,11 @@ import toast from '../../ui/Toast';import BrailleSpinner from '../../BrailleSpinner';import CronInput from '../../CronInput';import ToggleSwitch from '../../ToggleSwitch';-import ProviderModelSelector from '../../ProviderModelSelector';+import AppProviderPin from '../../cos/AppProviderPin';import * as api from '../../../services/api';-import { AGENT_OPTIONS, toggleAppMetadataOverride, agentOptionButtonClass } from '../../cos/constants';+import { AGENT_OPTIONS, hasProviderPin, toggleAppMetadataOverride, agentOptionButtonClass } from '../../cos/constants';import { isCronExpression, describeCron } from '../../../utils/cronHelpers';-import { PROVIDER_TYPES, filterSelectableModels, providerDisplayName, providerModelLabel } from '../../../utils/providers';+import { PROVIDER_TYPES, providerDisplayName } from '../../../utils/providers';import CustomTasksSection from './CustomTasksSection';const RUNNABLE_PROVIDER_TYPES = Object.values(PROVIDER_TYPES);@@ -136,29 +136,17 @@ export default function AutomationTab({ appId, appName }) {}));};- const handleProviderChange = async (taskType, newProviderId) => {- // Picking a new provider clears any pinned model so a stale model from the- // previous provider can't leak through. Empty → inherit the default.- const providerId = newProviderId || null;- await api.updateAppTaskTypeOverride(appId, taskType, { providerId, model: '' }, { silent: true }).catch(err => {+ // One mutation for the whole pin — AppProviderPin hands back an already+ // normalized { providerId, model }, so the clear rule lives in the control+ // rather than being re-derived here (#4783).+ const handlePinChange = async (taskType, patch) => {+ await api.updateAppTaskTypeOverride(appId, taskType, patch, { silent: true }).catch(err => {toast.error(err.message);return null;});setOverrides(prev => ({...prev,- [taskType]: { ...prev[taskType], providerId, model: '' }- }));- };-- const handleModelChange = async (taskType, newModel) => {- const model = newModel || '';- await api.updateAppTaskTypeOverride(appId, taskType, { model }, { silent: true }).catch(err => {- toast.error(err.message);- return null;- });- setOverrides(prev => ({- ...prev,- [taskType]: { ...prev[taskType], model }+ [taskType]: { ...prev[taskType], ...patch }}));};@@ -250,30 +238,16 @@ export default function AutomationTab({ appId, appName }) {: overrideInterval || (globalConfig.type || 'rotation');const intervalSuffix = !overrideInterval && globalConfig.intervalMs ? ` (${Math.round(globalConfig.intervalMs / 3600000)}h)` : '';const isExpanded = expandedTaskType === taskType;- const overrideProviderId = override.providerId || '';- const overrideModel = override.model || '';- const selectedProvider = providers.find(p => p.id === overrideProviderId);- const availableModels = filterSelectableModels(selectedProvider?.models);- // Keep a pinned model visible even when it's not in the provider's- // fetched list (avoids a blanked select on a stale/custom model).- const modelOptions = overrideModel && !availableModels.includes(overrideModel)- ? [overrideModel, ...availableModels]- : availableModels;const isLayeredIntelligence = taskType === 'layered-intelligence';- // A per-app provider/model pin only reaches the spawn for task types- // whose buildTaskInput hook resolves it (server stamps the flag). For- // every other type the provider comes from the global schedule pin, so- // offering the picker here would silently do nothing — show only a- // clear-it affordance when a stale one is already stored.- const providerOverrideCapable = globalConfig.providerOverrideCapable === true;- const hasProviderOverride = !!(override.providerId || override.model);- // The app pin only counts toward "effective" where it is honored —- // naming an ignored pin as the effective provider is exactly the lie- // this row exists to correct.- const effectiveProviderId = (providerOverrideCapable && override.providerId) || globalConfig.providerId || null;- const effectiveProviderName = effectiveProviderId- ? providerDisplayName(providers, effectiveProviderId)+ // The per-app pin outranks the task's Schedule pin at spawn for EVERY+ // task type (#4783), so it always counts toward "effective".+ const hasProviderOverride = hasProviderPin(override);+ const taskProviderName = globalConfig.providerId+ ? providerDisplayName(providers, globalConfig.providerId): 'default (active provider)';+ const effectiveProviderName = override.providerId+ ? providerDisplayName(providers, override.providerId)+ : taskProviderName;return (<div key={taskType} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">@@ -284,18 +258,16 @@ export default function AutomationTab({ appId, appName }) {<span className="text-white font-mono text-xs">{taskType}</span><div className="text-xs text-gray-500">{effectiveLabel}{intervalSuffix}</div></div>- {(providerOverrideCapable || hasProviderOverride) && (- <button- onClick={() => setExpandedTaskType(prev => prev === taskType ? null : taskType)}- aria-expanded={isExpanded}- aria-label={`${isExpanded ? 'Hide' : 'Show'} provider and model overrides for ${taskType}`}- className="px-2 py-1 bg-port-border/60 text-gray-300 hover:bg-port-border rounded text-xs inline-flex items-center gap-1 shrink-0"- >- {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}- <Settings size={12} />- Configure- </button>- )}+ <button+ onClick={() => setExpandedTaskType(prev => prev === taskType ? null : taskType)}+ aria-expanded={isExpanded}+ aria-label={`${isExpanded ? 'Hide' : 'Show'} provider and model overrides for ${taskType}`}+ className="px-2 py-1 bg-port-border/60 text-gray-300 hover:bg-port-border rounded text-xs inline-flex items-center gap-1 shrink-0"+ >+ {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ <Settings size={12} />+ Configure+ </button><buttononClick={() => handleTrigger(taskType)}disabled={triggering === taskType || !isEnabled}@@ -378,39 +350,19 @@ export default function AutomationTab({ appId, appName }) {{/* Expanded config: per-app provider/model override (+ LI behavior link) */}{isExpanded && (<div className="border-t border-port-border pt-3 space-y-3">- {providerOverrideCapable ? (- <>- <ProviderModelSelector- providers={providers}- selectedProviderId={overrideProviderId}- selectedModel={overrideModel}- availableModels={modelOptions}- onProviderChange={id => handleProviderChange(taskType, id)}- onModelChange={model => handleModelChange(taskType, model)}- label="Provider override"- emptyProviderOption="Use default provider"- emptyModelOption="Default model"- alwaysShowModel- layout="stacked"- />- <p className="text-xs text-gray-500">- Effective provider: <span className="text-gray-300">{effectiveProviderName}</span>- {override.providerId ? ' (app override, wins over the task default)' : globalConfig.providerId ? ' (task default)' : ''}- </p>- </>- ) : (- <p className="text-xs text-gray-500">- {taskType} runs on the provider pinned for the task in CoS → Schedule- (<span className="text-gray-300">{effectiveProviderName}</span>).- {hasProviderOverride && (- <>- {' '}This app stores an unused override- (<span className="text-gray-300">{providerModelLabel(providers, override.providerId, override.model)}</span>).{' '}- <button onClick={() => handleProviderChange(taskType, '')} className="text-port-accent hover:underline">Clear it</button>- </>- )}- </p>- )}+ <AppProviderPin+ providers={providers}+ providerId={override.providerId}+ model={override.model}+ onChange={patch => handlePinChange(taskType, patch)}+ label="Provider override"+ inheritLabel={`Inherit (${taskProviderName})`}+ layout="stacked"+ />+ <p className="text-xs text-gray-500">+ Effective provider: <span className="text-gray-300">{effectiveProviderName}</span>+ {hasProviderOverride ? ' (app override, wins over the task default)' : globalConfig.providerId ? ' (task default)' : ''}+ </p>{isLayeredIntelligence && (<div className="pt-1"><buttondiff --git a/client/src/components/apps/tabs/AutomationTab.test.jsx b/client/src/components/apps/tabs/AutomationTab.test.jsxindex 4850c00100..3dca489005 100644--- a/client/src/components/apps/tabs/AutomationTab.test.jsx+++ b/client/src/components/apps/tabs/AutomationTab.test.jsx@@ -35,10 +35,9 @@ const AutomationTab = (await import('./AutomationTab')).default;const SCHEDULE = {tasks: {- // Only layered-intelligence honors a per-app provider/model override (the- // server stamps providerOverrideCapable from taskTypeHooks) — the other rows- // take their provider from this global pin.- 'layered-intelligence': { type: 'daily', taskMetadata: {}, providerId: 'global-claude', providerOverrideCapable: true },+ // Every row honors a per-app provider/model pin (#4783); the task's own pin+ // is what a row inherits when the app pins nothing.+ 'layered-intelligence': { type: 'daily', taskMetadata: {}, providerId: 'global-claude' },'app-improvement': { type: 'rotation', taskMetadata: {} },security: { type: 'weekly', taskMetadata: { fileIssues: false }, fileIssuesCapable: true, defaultFileIssues: false },},@@ -100,7 +99,7 @@ describe('AutomationTab per-app overrides', () => {expect(api.updateAppTaskTypeOverride).toHaveBeenCalledWith('app-1','layered-intelligence',- { providerId: 'claude-cli', model: '' },+ { providerId: 'claude-cli', model: null },{ silent: true });});@@ -115,7 +114,7 @@ describe('AutomationTab per-app overrides', () => {await waitFor(() => expect(api.updateAppTaskTypeOverride).toHaveBeenCalledWith('app-1','layered-intelligence',- { model: 'sonnet' },+ { providerId: 'claude-cli', model: 'sonnet' },{ silent: true }));});@@ -139,27 +138,25 @@ describe('AutomationTab per-app overrides', () => {expect(mockNavigate).toHaveBeenCalledWith('/apps/app-1?edit=1&appTab=intelligence');});- // A per-app provider/model pin is inert for a task type with no buildTaskInput- // hook — the picker must not be offered there, or the user sets a provider that- // silently never runs.- it('offers no provider override on a task type that does not honor one', async () => {+ // The pin reaches the spawn for EVERY task type now (#4783), so the picker is+ // offered on every row rather than only where a buildTaskInput hook read it.+ it('offers the same provider picker on a task type with no hook', async () => {await renderTab();const row = rowFor('app-improvement');- expect(within(row).queryByRole('button', { name: /show provider and model overrides/i })).toBeNull();+ fireEvent.click(within(row).getByRole('button', { name: /show provider and model overrides/i }));+ expect(within(row).getByLabelText('Provider override')).toBeInTheDocument();});- it('shows a stored-but-inert override with a way to clear it', async () => {+ it('clearing the provider sends explicit nulls, matching the other pin surfaces', async () => {await renderTab({ 'app-improvement': { providerId: 'claude-cli', model: 'opus' } });const row = rowFor('app-improvement');fireEvent.click(within(row).getByRole('button', { name: /show provider and model overrides/i }));- expect(within(row).getByText(/unused override/i)).toBeInTheDocument();- expect(within(row).queryByLabelText('Provider override')).toBeNull();- fireEvent.click(within(row).getByRole('button', { name: /clear it/i }));+ fireEvent.change(within(row).getByLabelText('Provider override'), { target: { value: '' } });await waitFor(() => expect(api.updateAppTaskTypeOverride).toHaveBeenCalledWith('app-1','app-improvement',- { providerId: null, model: '' },+ { providerId: null, model: null },{ silent: true }));});diff --git a/client/src/components/cos/AppProviderPin.jsx b/client/src/components/cos/AppProviderPin.jsxnew file mode 100644index 0000000000..32ae1fcf72--- /dev/null+++ b/client/src/components/cos/AppProviderPin.jsx@@ -0,0 +1,74 @@+import ProviderModelSelector from '../ProviderModelSelector';+import { filterSelectableModels } from '../../utils/providers';+import { providerPinPatch } from './constants';++/**+ * The ONE control for an app's per-app provider/model pin on a scheduled task+ * type (`taskTypeOverrides[<taskType>].providerId` / `.model`).+ *+ * The same field used to be edited from three places with three different+ * clear-normalizations (`model: ''`, `model: null`, `'' → null`) and three+ * different "picking a provider clears the model" rules — or no rule at all.+ * Both rules live here now (#4783), so every surface produces one stored result:+ *+ * - `''` / absent → `null`, the "inherit" sentinel the route deletes the key for.+ * - Choosing a provider CLEARS the pinned model, so a model from the previous+ * provider can't leak into a provider that has never heard of it.+ *+ * Fully controlled: it renders `providerId`/`model` and hands the caller a+ * complete normalized `{ providerId, model }` patch. The caller decides whether+ * that patch is PUT immediately (Automation / Schedule rows) or staged in a form+ * (the Intelligence tab's drawer save).+ *+ * @param {Array} props.providers Selectable providers (already type/enabled filtered).+ * @param {string} [props.providerId] Currently pinned provider id ('' / null = inherit).+ * @param {string} [props.model] Currently pinned model ('' / null = provider default).+ * @param {function} props.onChange Called with `{ providerId, model }`, both normalized.+ * @param {string} props.label Provider-select label (also its aria-label when compact).+ * @param {string} [props.inheritLabel] What a blank pin resolves to, e.g. `Inherit (claude-code)`.+ * @param {boolean} [props.disabled]+ * @param {boolean} [props.compact] Hide labels for inline/table use.+ * @param {'row'|'stacked'} [props.layout]+ */+export default function AppProviderPin({+ providers,+ providerId,+ model,+ onChange,+ label,+ inheritLabel = 'Use default provider',+ disabled = false,+ compact = false,+ layout = 'row'+}) {+ const selectedProviderId = providerId || '';+ const selectedModel = model || '';+ const selectedProvider = providers?.find(p => p.id === selectedProviderId);+ const availableModels = selectedProvider+ ? filterSelectableModels(selectedProvider.models || [selectedProvider.defaultModel])+ : [];+ // Keep a pinned model visible even when it isn't in the provider's fetched list+ // (a stale or hand-typed model must not render as a blanked select).+ const modelOptions = selectedModel && !availableModels.includes(selectedModel)+ ? [selectedModel, ...availableModels]+ : availableModels;++ return (+ <ProviderModelSelector+ providers={providers || []}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={modelOptions}+ // Switching providers drops the model pin — see the header note.+ onProviderChange={id => onChange(providerPinPatch(id, ''))}+ onModelChange={next => onChange(providerPinPatch(selectedProviderId, next))}+ label={label}+ emptyProviderOption={inheritLabel}+ emptyModelOption="Default model"+ alwaysShowModel+ disabled={disabled}+ compact={compact}+ layout={layout}+ />+ );+}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex c2d762bd9c..5f13dd122f 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -458,6 +458,22 @@ export function agentOptionButtonClass(effective, hasOverride) {: 'bg-transparent text-gray-600 border-gray-700/50';}+// Normalize a per-app provider/model pin (`taskTypeOverrides[<taskType>].providerId`+// / `.model`) to the ONE shape every write site sends. '' and null both mean+// "inherit" — the route deletes the key for either — but three surfaces used to+// clear with three different values ('', null, and '' → null), so the same user+// action read as three different intents in the diff. Emitting null from all of+// them is what makes the stored result identical (#4783).+export function providerPinPatch(providerId, model) {+ return { providerId: providerId || null, model: model || null };+}++// Whether an app has pinned anything of its own for a task type (as opposed to+// inheriting the task's Schedule pin).+export function hasProviderPin(override) {+ return !!(override?.providerId || override?.model);+}+// Compute new taskMetadata after toggling a field in a per-app override.// Returns null when all overrides are cleared (inherit everything).// Enforces invariant: openPR implies useWorktree (turning on openPR forcesdiff --git a/client/src/components/cos/constants.test.js b/client/src/components/cos/constants.test.jsindex 22ac1145ff..8174e34f18 100644--- a/client/src/components/cos/constants.test.js+++ b/client/src/components/cos/constants.test.js@@ -16,7 +16,9 @@ import {reviewerLabel,summarizeHealthIssues,healthIssueTone,- fresherHealth+ fresherHealth,+ providerPinPatch,+ hasProviderPin} from './constants';// These mirror the server's domainBudgets/domainAutonomy helpers so the UI's@@ -300,4 +302,33 @@ describe('healthIssueTone', () => {});});+// The per-app provider pin is written from three surfaces (Edit App → Automation,+// CoS → Schedule rows, Edit App → Intelligence). They used to clear it with three+// different values ('', null, and '' → null); one normalizer is what makes the+// stored result identical (#4783).+describe('providerPinPatch', () => {+ it('collapses every "inherit" spelling to explicit nulls', () => {+ expect(providerPinPatch('', '')).toEqual({ providerId: null, model: null });+ expect(providerPinPatch(null, undefined)).toEqual({ providerId: null, model: null });+ expect(providerPinPatch(undefined, null)).toEqual({ providerId: null, model: null });+ });++ it('passes real values through unchanged', () => {+ expect(providerPinPatch('claude-cli', 'opus')).toEqual({ providerId: 'claude-cli', model: 'opus' });+ });++ it('keeps a model pinned with no provider (inherit the provider, pin the model)', () => {+ expect(providerPinPatch('', 'opus')).toEqual({ providerId: null, model: 'opus' });+ });+});++describe('hasProviderPin', () => {+ it('is true for either half of the pin, false for inherit', () => {+ expect(hasProviderPin({ providerId: 'claude-cli' })).toBe(true);+ expect(hasProviderPin({ model: 'opus' })).toBe(true);+ expect(hasProviderPin({ providerId: '', model: null })).toBe(false);+ expect(hasProviderPin(undefined)).toBe(false);+ });+});+// @vitest-environment nodediff --git a/client/src/components/cos/tabs/WorkflowTab.jsx b/client/src/components/cos/tabs/WorkflowTab.jsxindex ffaf1fce70..0b6c85936c 100644--- a/client/src/components/cos/tabs/WorkflowTab.jsx+++ b/client/src/components/cos/tabs/WorkflowTab.jsx@@ -103,7 +103,7 @@ function TrackGrid({ divisions }) {// Reshapes a task node into the `config` shape PerAppOverrideList expects and// renders it. Shared by the pinned TimelineRow and the flexible-queue rows so// the config reconstruction lives in exactly one place.-function AppOverridePanel({ node, apps, onUpdateOverride, onBulkToggleOverride }) {+function AppOverridePanel({ node, apps, providers, onUpdateOverride, onBulkToggleOverride }) {return (<PerAppOverrideListtaskType={node.label}@@ -112,18 +112,18 @@ function AppOverridePanel({ node, apps, onUpdateOverride, onBulkToggleOverride }type: node.schedule?.type,taskMetadata: node.taskMetadata,managedAgentOptions: node.managedAgentOptions,- providerOverrideCapable: node.providerOverrideCapable,providerId: node.providerId,model: node.model}}apps={apps}+ providers={providers}onUpdateOverride={onUpdateOverride}onBulkToggleOverride={onBulkToggleOverride}/>);}-function TimelineRow({ node, occurrences, windows, timeline, hours, timezone, selected, apps, expanded, onSelect, onToggleExpand, onUpdateOverride, onBulkToggleOverride }) {+function TimelineRow({ node, occurrences, windows, timeline, hours, timezone, selected, apps, providers, expanded, onSelect, onToggleExpand, onUpdateOverride, onBulkToggleOverride }) {const palette = trackPalette(node);const Icon = node.kind === 'job' ? Bot : GitBranch;const divisions = hours === 168 ? 7 : 8;@@ -202,7 +202,7 @@ function TimelineRow({ node, occurrences, windows, timeline, hours, timezone, se</div>{canExpand && expanded && (<div className="border-t border-port-border/40 bg-port-bg/20 px-3 py-3">- <AppOverridePanel node={node} apps={apps} onUpdateOverride={onUpdateOverride} onBulkToggleOverride={onBulkToggleOverride} />+ <AppOverridePanel node={node} apps={apps} providers={providers} onUpdateOverride={onUpdateOverride} onBulkToggleOverride={onBulkToggleOverride} /></div>)}</div>@@ -240,7 +240,10 @@ function NextUp({ occurrences, nodeMap, hours, timezone, onSelect }) {);}-export default function WorkflowTab({ apps }) {+// `providers` is the same ChiefOfStaff-owned list ScheduleTab renders — without it+// the per-app rows here degraded to raw provider ids while the Schedule tab showed+// display names for the very same pin (#4783).+export default function WorkflowTab({ apps, providers }) {// Zoom window + selected track live in the URL so the open editor and view// are shareable/bookmarkable and survive reload — the same "URL is the// source of truth for what's open" convention as ScheduleTab's ?task=.@@ -407,6 +410,7 @@ export default function WorkflowTab({ apps }) {timezone={graph.timezone}selected={selectedId === node.id}apps={apps}+ providers={providers}expanded={expandedIds.has(node.id)}onSelect={setSelectedId}onToggleExpand={toggleExpand}@@ -452,7 +456,7 @@ export default function WorkflowTab({ apps }) {{model.flexible.filter(node => expandedIds.has(node.id) && node.kind === 'task' && (node.totalAppCount || 0) > 0).map(node => (<div key={node.id} className="mt-2 rounded border border-port-border/60 bg-port-bg/20 px-3 py-3"><div className="mb-2 text-xs font-medium text-gray-300">{node.label} <span className="text-gray-600">· app overrides</span></div>- <AppOverridePanel node={node} apps={apps} onUpdateOverride={handleUpdateOverride} onBulkToggleOverride={handleBulkToggleOverride} />+ <AppOverridePanel node={node} apps={apps} providers={providers} onUpdateOverride={handleUpdateOverride} onBulkToggleOverride={handleBulkToggleOverride} /></div>))}</section>diff --git a/client/src/components/cos/tabs/WorkflowTab.providers.test.jsx b/client/src/components/cos/tabs/WorkflowTab.providers.test.jsxnew file mode 100644index 0000000000..10f6522b3b--- /dev/null+++ b/client/src/components/cos/tabs/WorkflowTab.providers.test.jsx@@ -0,0 +1,88 @@+/**+ * The Timeline tab's expanded per-app rows resolve provider DISPLAY NAMES (#4783).+ *+ * `WorkflowTab` rendered `PerAppOverrideList` without a `providers` list, so the+ * same pin read as `claude-ollama-tui` here and "Claude (ollama)" on the Schedule+ * tab. The list is owned by ChiefOfStaff and already threaded to ScheduleTab, so+ * the fix is to hand it to this tab too.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, cleanup, act } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const api = {+ getCosWorkflow: vi.fn(),+ updateAppTaskTypeOverride: vi.fn(),+ bulkUpdateAppTaskTypeOverride: vi.fn(),+};+vi.mock('../../../services/api', () => api);++const WorkflowTab = (await import('./WorkflowTab')).default;++const APPS = [{ id: 'app-1', name: 'Acme', icon: 'package' }];+const PROVIDERS = [+ { id: 'opencode-llama-tui', name: 'OpenCode (llama)', models: ['qwen-a'] },+ { id: 'claude-ollama-tui', name: 'Claude (ollama)', models: ['qwen-b'] },+];++const NOW = new Date('2026-08-22T00:00:00Z');+const GRAPH = {+ timezone: 'UTC',+ timeline: {+ startAt: NOW.toISOString(),+ endAt: new Date(NOW.getTime() + 24 * 3600 * 1000).toISOString(),+ occurrences: [{ nodeId: 'task:ux', at: NOW.toISOString() }],+ windows: [],+ },+ nodes: [{+ id: 'task:ux',+ kind: 'task',+ label: 'ux',+ enabled: true,+ schedule: { type: 'daily' },+ totalAppCount: 1,+ enabledAppCount: 1,+ // The task's own Schedule pin, which an app inherits when it pins nothing.+ providerId: 'opencode-llama-tui',+ model: 'qwen-a',+ appOverrides: { 'app-1': { enabled: true, providerId: 'claude-ollama-tui', model: 'qwen-b' } },+ }],+ edges: [],+};++beforeEach(() => {+ vi.clearAllMocks();+ api.getCosWorkflow.mockResolvedValue(GRAPH);+});+afterEach(cleanup);++const renderTab = async (providers) => {+ await act(async () => {+ render(<MemoryRouter><WorkflowTab apps={APPS} providers={providers} /></MemoryRouter>);+ });+ const expand = await screen.findByRole('button', { name: /show app overrides for ux/i });+ fireEvent.click(expand);+};++describe('WorkflowTab per-app override rows', () => {+ it('renders the app pin with the provider display name, not the raw id', async () => {+ await renderTab(PROVIDERS);+ const pin = screen.getByLabelText('Provider for Acme');+ expect(pin).toHaveValue('claude-ollama-tui');+ expect(screen.getByRole('option', { name: 'Claude (ollama)' })).toBeInTheDocument();+ // …and the inherited task pin reads by name too.+ expect(screen.getByRole('option', { name: 'Inherit (OpenCode (llama) / qwen-a)' })).toBeInTheDocument();+ });++ it('writes the pin from the Timeline tab through the shared override mutation', async () => {+ api.updateAppTaskTypeOverride.mockResolvedValue({ success: true });+ await renderTab(PROVIDERS);+ await act(async () => {+ fireEvent.change(screen.getByLabelText('Provider for Acme'), { target: { value: '' } });+ });+ expect(api.updateAppTaskTypeOverride).toHaveBeenCalledWith(+ 'app-1', 'ux', { providerId: null, model: null }, { silent: true }+ );+ });+});diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsxindex 8f60447c95..3820aa5eb5 100644--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx@@ -2,13 +2,13 @@ import { useState, memo } from 'react';import AppIcon from '../../../AppIcon';import CronInput from '../../../CronInput';import { AGENT_OPTIONS, BRANCHES_PER_AGENT_DEFAULT, BRANCHES_PER_AGENT_OPTIONS, BRANCHES_PER_AGENT_TASK_TYPES, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES, PR_COMPLETION_OPTIONS, pinnedPrCompletion, prCompletionOption, SWARM_COUNT_OPTIONS, SWARM_TASK_TYPES, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';+import AppProviderPin from '../../AppProviderPin';import { isCronExpression, describeCron } from '../../../../utils/cronHelpers';import ToggleSwitch from '../../../ToggleSwitch';import useFieldDraft from '../../../../hooks/useFieldDraft';-import { providerModelLabel } from '../../../../utils/providers';-import { badge, INTERVAL_LABELS, setMetadataOverride } from './scheduleConstants';+import { INTERVAL_LABELS, setMetadataOverride } from './scheduleConstants';-const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata, managedAgentOptions, fileIssuesCapable, defaultFileIssues, providerOverrideCapable, inheritedProviderText, providers, override, onUpdate }) {+const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata, managedAgentOptions, fileIssuesCapable, defaultFileIssues, inheritedProviderText, providers, override, onUpdate }) {const [updating, setUpdating] = useState(false);const [cronEditing, setCronEditing] = useState(false);const isEnabled = override?.enabled === true;@@ -18,19 +18,13 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter// wins, else the global config. No PR, nothing to decide about one.const opensPR = (override?.taskMetadata?.openPR ?? globalTaskMetadata?.openPR) === true;- // A per-app provider/model pin OUTRANKS the task's own provider pin at spawn- // (the buildTaskInput hook resolves it and the generator applies it last), so- // an app carrying one runs on a provider the card above never mentions. Show- // it here — where the task provider is chosen — rather than only inside Edit- // App → Automation, and let it be cleared back to inherit in one click.- const hasProviderOverride = !!(override?.providerId || override?.model);- // `providers` is absent on the Timeline tab, which renders these rows without- // fetching the list — providerDisplayName falls back to the raw id there.- const overrideProviderText = providerModelLabel(providers || [], override?.providerId, override?.model);-- const handleClearProviderOverride = async () => {+ // A per-app provider/model pin OUTRANKS the task's own provider pin at spawn,+ // for every task type (#4783) — so an app carrying one runs on a provider the+ // card above never mentions. Edit it here, where the task provider is chosen,+ // through the same control Edit App → Automation uses.+ const handlePinChange = async (patch) => {setUpdating(true);- await onUpdate(app.id, taskType, { providerId: null, model: null }).catch(() => {});+ await onUpdate(app.id, taskType, patch).catch(() => {});setUpdating(false);};@@ -202,28 +196,20 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter})}</div>- {hasProviderOverride ? (- <span- className={`${badge(providerOverrideCapable ? 'warning' : 'gray')} flex items-center gap-1`}- title={providerOverrideCapable- ? `${overrideProviderText} (app override) — wins over the task provider (${inheritedProviderText})`- : `${overrideProviderText} (app override) is ignored: ${taskType} always uses the task provider (${inheritedProviderText})`}- >- <span className="truncate max-w-[200px]">{overrideProviderText}</span>- <button- onClick={handleClearProviderOverride}- disabled={updating}- aria-label={`Clear provider override for ${app.name}`}- className="underline decoration-dotted hover:no-underline disabled:opacity-50"- >- clear- </button>- </span>- ) : providerOverrideCapable && (- <span className="text-xs px-2 py-1.5 text-gray-500 truncate max-w-[200px]" title={`Inherit (${inheritedProviderText})`}>- Inherit ({inheritedProviderText})- </span>- )}+ {/* Bounded so the two selects stay a row item next to the other per-app+ knobs instead of stretching across the wrapped flex line. */}+ <div className="w-full sm:w-auto sm:min-w-[240px] sm:max-w-[360px] sm:flex-1">+ <AppProviderPin+ providers={providers}+ providerId={override?.providerId}+ model={override?.model}+ onChange={handlePinChange}+ disabled={updating}+ label={`Provider for ${app.name}`}+ inheritLabel={`Inherit (${inheritedProviderText})`}+ compact+ />+ </div>{opensPR && (<selectdiff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsxindex d4648157d9..8b7a2104f0 100644--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx@@ -12,7 +12,6 @@ function renderRow({taskType = 'feature-ideas',fileIssuesCapable,defaultFileIssues,- providerOverrideCapable,inheritedProviderText,providers,} = {}) {@@ -25,7 +24,6 @@ function renderRow({managedAgentOptions={[]}fileIssuesCapable={fileIssuesCapable}defaultFileIssues={defaultFileIssues}- providerOverrideCapable={providerOverrideCapable}inheritedProviderText={inheritedProviderText}providers={providers}override={override}@@ -206,69 +204,58 @@ describe('AppOverrideRow — branch-reconcile batch size', () => {});});-// The per-app provider/model pin beats the task's own pin at spawn for the task-// types whose buildTaskInput hook resolves it — so the Schedule page, where that-// task pin is chosen, has to show when an app is running on something else.-describe('AppOverrideRow — per-app provider override', () => {+// The per-app provider/model pin beats the task's own pin at spawn for EVERY task+// type (#4783) — so the Schedule page, where that task pin is chosen, both shows+// what an app is running on and lets it be changed there.+describe('AppOverrideRow — per-app provider pin', () => {const PROVIDERS = [- { id: 'opencode-llama-tui', name: 'OpenCode (llama)' },- { id: 'claude-ollama-tui', name: 'Claude (ollama)' },+ { id: 'opencode-llama-tui', name: 'OpenCode (llama)', models: ['qwen-a'] },+ { id: 'claude-ollama-tui', name: 'Claude (ollama)', models: ['qwen-b'] },];const INHERITED = 'OpenCode (llama) / qwen-a';+ const pinSelect = () => screen.getByLabelText('Provider for Acme');- it('names the app override and the task pin it supersedes', () => {+ it('renders the app pin, on a task type with no buildTaskInput hook', () => {renderRow({- taskType: 'layered-intelligence',- providerOverrideCapable: true,+ taskType: 'feature-ideas',inheritedProviderText: INHERITED,providers: PROVIDERS,override: { enabled: true, providerId: 'claude-ollama-tui', model: 'qwen-b' },});- expect(screen.getByText('Claude (ollama) / qwen-b')).toBeInTheDocument();- expect(screen.getByTitle(`Claude (ollama) / qwen-b (app override) — wins over the task provider (${INHERITED})`)).toBeInTheDocument();+ expect(pinSelect()).toHaveValue('claude-ollama-tui');+ expect(screen.getByLabelText('Model')).toHaveValue('qwen-b');});- it('clearing sends explicit nulls so the app falls back to the task pin', async () => {- const onUpdate = renderRow({+ it('names the task pin on the Inherit option when the app pins nothing', () => {+ renderRow({taskType: 'layered-intelligence',- providerOverrideCapable: true,inheritedProviderText: INHERITED,providers: PROVIDERS,- override: { enabled: true, providerId: 'claude-ollama-tui' },- });- await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'Clear provider override for Acme' }));+ override: { enabled: true },});- expect(onUpdate).toHaveBeenCalledWith('app-1', 'layered-intelligence', { providerId: null, model: null });+ expect(pinSelect()).toHaveValue('');+ expect(screen.getByRole('option', { name: `Inherit (${INHERITED})` })).toBeInTheDocument();});- it('reads as inheriting the task pin when the app pins nothing', () => {- renderRow({+ it('clearing the provider sends explicit nulls so the app falls back to the task pin', async () => {+ const onUpdate = renderRow({taskType: 'layered-intelligence',- providerOverrideCapable: true,inheritedProviderText: INHERITED,providers: PROVIDERS,- override: { enabled: true },+ override: { enabled: true, providerId: 'claude-ollama-tui', model: 'qwen-b' },});- expect(screen.getByText(`Inherit (${INHERITED})`)).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'Clear provider override for Acme' })).toBeNull();- });-- it('says nothing about providers on a task type that ignores the override', () => {- renderRow({ taskType: 'feature-ideas', inheritedProviderText: INHERITED, providers: PROVIDERS, override: { enabled: true } });- expect(screen.queryByText(/Inherit \(OpenCode/)).toBeNull();+ await act(async () => { fireEvent.change(pinSelect(), { target: { value: '' } }); });+ expect(onUpdate).toHaveBeenCalledWith('app-1', 'layered-intelligence', { providerId: null, model: null });});- // A stale pin stored on a non-honoring type (the app Automation tab used to- // offer one for every task type) still has to be visible to be removable.- it('surfaces a stored-but-ignored override so it can be cleared', () => {- renderRow({- taskType: 'feature-ideas',+ it('switching providers drops the model pinned for the previous one', async () => {+ const onUpdate = renderRow({+ taskType: 'ux',inheritedProviderText: INHERITED,providers: PROVIDERS,- override: { enabled: true, providerId: 'claude-ollama-tui' },+ override: { enabled: true, providerId: 'claude-ollama-tui', model: 'qwen-b' },});- expect(screen.getByTitle(/is ignored: feature-ideas always uses the task provider/)).toBeInTheDocument();- expect(screen.getByRole('button', { name: 'Clear provider override for Acme' })).toBeInTheDocument();+ await act(async () => { fireEvent.change(pinSelect(), { target: { value: 'opencode-llama-tui' } }); });+ expect(onUpdate).toHaveBeenCalledWith('app-1', 'ux', { providerId: 'opencode-llama-tui', model: null });});});diff --git a/client/src/components/cos/tabs/schedule/PerAppOverrideList.jsx b/client/src/components/cos/tabs/schedule/PerAppOverrideList.jsxindex 5133224cd2..0a0a6d5632 100644--- a/client/src/components/cos/tabs/schedule/PerAppOverrideList.jsx+++ b/client/src/components/cos/tabs/schedule/PerAppOverrideList.jsx@@ -55,7 +55,6 @@ export default function PerAppOverrideList({ taskType, config, apps, providers,managedAgentOptions={config.managedAgentOptions}fileIssuesCapable={config.fileIssuesCapable}defaultFileIssues={config.defaultFileIssues}- providerOverrideCapable={config.providerOverrideCapable}inheritedProviderText={inheritedProviderText}providers={providers}override={appOverrides[app.id]}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 5c9181d722..be6a3ed5ec 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -1075,7 +1075,7 @@ export default function ChiefOfStaff() {)}{activeTab === 'workflow' && (<div role="tabpanel" id="tabpanel-workflow" aria-labelledby="tab-workflow">- <WorkflowTab apps={apps} />+ <WorkflowTab apps={apps} providers={providers} /></div>)}{activeTab === 'digest' && (diff --git a/server/services/appTaskProviderPin.js b/server/services/appTaskProviderPin.jsnew file mode 100644index 0000000000..feb3577245--- /dev/null+++ b/server/services/appTaskProviderPin.js@@ -0,0 +1,104 @@+/**+ * Which provider/model a scheduled app task actually spawns its agent on.+ *+ * Two pins can name one: the task's global Schedule pin, and the app's own+ * per-app override (`taskTypeOverrides[<taskType>].providerId` / `.model`). The+ * per-app pin is the more specific choice, so it wins — for EVERY task type+ * (#4783), not only the one whose `buildTaskInput` hook happened to read it.+ *+ * The constraint both pins answer to is the HARNESS BOUNDARY: an `api`-type+ * provider (Ollama / LM Studio / kimi over HTTP) returns plain text with no+ * file-writing tool harness, so a CoS agent task pinned to one can never do the+ * work. `agentProviderResolution` already refuses such a task at spawn, but by+ * then the run is a permanent failure the user has to notice and clear — and for+ * layered-intelligence (whose per-app pin migration 184 populated verbatim,+ * ollama entries included) it wedged the task instead. Catching it HERE lets an+ * api-typed per-app pin fall back to the task's Schedule pin, which is the+ * self-heal LI shipped, generalized: every task type spawns an agent that needs a+ * harness, so the constraint was never LI's.+ *+ * The walk, in one place so the generic generator path and LI's hook cannot drift:+ *+ * per-app pin → (api-typed? adopt the Schedule pin instead) → Schedule pin →+ * the install's default coding agent+ */++const NOT_AGENT_CAPABLE = 'provider-not-agent-capable';++/**+ * Resolve the agent provider/model pin for one app + task type.+ *+ * @param {object} args+ * @param {object} [args.appPin] `{ providerId, model }` the app pinned for this task type.+ * @param {function} args.readSchedulePin Async thunk returning the task's global Schedule pin+ * (`{ providerId, model }`). A THUNK, not a value, so a per-app pin that already resolves+ * never pays for the read; it is invoked at most once per call.+ * @param {string} args.taskType Task type, for the harness-fallback log line.+ * @param {string} args.appName App name, for the same log line.+ * @param {function} [args.getProviderType] Injectable `(id) => Promise<type|null>` seam for tests.+ * @returns {Promise<{ providerId: string|null, model: string|null, healedFrom: string|null, skipReason: string|null }>}+ * `skipReason` is `'provider-not-agent-capable'` when NOTHING resolvable has a harness. Callers+ * that can decline to generate (LI) gate on it; the generic path leaves the Schedule pin alone so+ * `agentProviderResolution` reports its actionable permanent error rather than silently rerouting+ * the run onto a provider the user never chose.+ */+export async function resolveAgentProviderPin({ appPin, readSchedulePin, taskType, appName, getProviderType } = {}) {+ const typeOf = getProviderType || (async (id) => {+ const { getProviderById } = await import('./providers.js');+ const provider = await getProviderById(id).catch(() => null);+ return provider?.type ?? null;+ });+ const providerTypeOf = async (id) => (id ? typeOf(id) : null);++ // Read the Schedule pin at most once, and only when a branch below needs it.+ let schedulePinPromise = null;+ const schedulePin = () => {+ if (!schedulePinPromise) schedulePinPromise = Promise.resolve(readSchedulePin()).catch(() => null);+ return schedulePinPromise;+ };++ let providerId = appPin?.providerId || null;+ let model = appPin?.model ?? null;+ let type = await providerTypeOf(providerId);+ let healedFrom = null;++ if (type === 'api') {+ const pin = await schedulePin();+ const pinId = pin?.providerId || null;+ const pinType = await providerTypeOf(pinId);+ // Adopt the Schedule pin only when it RESOLVES to a real non-api provider.+ // `pinType` is null for an unresolvable id (deleted / renamed / typo'd pin) —+ // treating that as "not api" would re-wedge the task on a doomed provider+ // under a misleading "healed" line, so require a positively-known type.+ if (pinId && pinType && pinType !== 'api') {+ healedFrom = providerId;+ providerId = pinId;+ // Adopt the pin's model too — provider+model are a matched pair the user set+ // together, and an api provider's model name may not be valid for a CLI/TUI one.+ model = pin?.model ?? null;+ type = pinType;+ }+ } else if (!providerId) {+ // No per-app provider → the Schedule pin IS the resolved choice; resolving it+ // here (rather than leaving that leg to the caller) keeps this the single+ // source of truth for what the agent runs on. No pin at all leaves+ // `providerId` null, which inherits the install's default coding agent.+ const pin = await schedulePin();+ const pinId = pin?.providerId || null;+ if (pinId) {+ providerId = pinId;+ type = await providerTypeOf(pinId);+ // Keep an explicit per-app model when the user set one (a model pinned+ // without a provider); only fall back to the pin's model when there is none.+ model = appPin?.model ?? pin?.model ?? null;+ }+ }++ if (healedFrom) {+ console.warn(`⚠️ ${taskType}: ${appName} per-app provider '${healedFrom}' is API-only (no coding harness) — using the task provider '${providerId}' instead`);+ }++ return { providerId, model, healedFrom, skipReason: type === 'api' ? NOT_AGENT_CAPABLE : null };+}++export { NOT_AGENT_CAPABLE };diff --git a/server/services/appTaskProviderPin.test.js b/server/services/appTaskProviderPin.test.jsnew file mode 100644index 0000000000..7ccd28c38c--- /dev/null+++ b/server/services/appTaskProviderPin.test.js@@ -0,0 +1,88 @@+import { describe, it, expect, vi } from 'vitest';+import { resolveAgentProviderPin } from './appTaskProviderPin.js';++// Provider registry for the walk: a CLI/TUI harness pair the agent can actually+// run on, and two api-only backends that can only ever return text.+const TYPES = {+ 'claude-cli': 'cli',+ 'opencode-tui': 'tui',+ ollama: 'api',+ lmstudio: 'api'+};+const getProviderType = vi.fn(async (id) => TYPES[id] ?? null);++const resolve = (appPin, schedulePin, readSchedulePin) => resolveAgentProviderPin({+ appPin,+ readSchedulePin: readSchedulePin || (async () => schedulePin),+ taskType: 'ux',+ appName: 'Acme',+ getProviderType+});++describe('resolveAgentProviderPin', () => {+ it('honors a harness-capable per-app pin over the schedule pin', async () => {+ const res = await resolve(+ { providerId: 'claude-cli', model: 'opus' },+ { providerId: 'opencode-tui', model: 'qwen' }+ );+ expect(res).toMatchObject({ providerId: 'claude-cli', model: 'opus', skipReason: null });+ });++ it('falls back to the schedule pin (provider AND model) when the app pin is api-only', async () => {+ const res = await resolve(+ { providerId: 'ollama', model: 'llama-3' },+ { providerId: 'claude-cli', model: 'opus' }+ );+ // The model travels with the provider: an api model name is not necessarily+ // valid for the CLI provider that replaces it.+ expect(res).toMatchObject({ providerId: 'claude-cli', model: 'opus', healedFrom: 'ollama', skipReason: null });+ });++ it('refuses to heal onto an UNRESOLVABLE schedule pin', async () => {+ // A deleted/renamed/typo'd pin has no known type — adopting it would re-wedge+ // the task on a doomed provider under a misleading "healed" line.+ const res = await resolve({ providerId: 'ollama' }, { providerId: 'deleted-provider' });+ expect(res).toMatchObject({ providerId: 'ollama', healedFrom: null, skipReason: 'provider-not-agent-capable' });+ });++ it('reports not-agent-capable when BOTH pins are api-only', async () => {+ const res = await resolve({ providerId: 'ollama' }, { providerId: 'lmstudio' });+ expect(res.skipReason).toBe('provider-not-agent-capable');+ });++ it('resolves the schedule pin when the app pins nothing', async () => {+ const res = await resolve({}, { providerId: 'claude-cli', model: 'opus' });+ expect(res).toMatchObject({ providerId: 'claude-cli', model: 'opus', skipReason: null });+ });++ it('keeps an app model pinned without a provider, over the schedule pin model', async () => {+ const res = await resolve({ model: 'sonnet' }, { providerId: 'claude-cli', model: 'opus' });+ expect(res).toMatchObject({ providerId: 'claude-cli', model: 'sonnet' });+ });++ it('leaves both null when nothing is pinned anywhere (inherit the default agent)', async () => {+ const res = await resolve({}, { providerId: null, model: null });+ expect(res).toMatchObject({ providerId: null, model: null, skipReason: null });+ });++ it('flags an api-only SCHEDULE pin the app did not override', async () => {+ const res = await resolve({}, { providerId: 'ollama' });+ expect(res).toMatchObject({ providerId: 'ollama', skipReason: 'provider-not-agent-capable' });+ });++ // The schedule pin is a THUNK so an already-usable per-app pin never pays for+ // the read — and no branch may read it twice.+ it('reads the schedule pin lazily, and at most once', async () => {+ const readSchedulePin = vi.fn(async () => ({ providerId: 'claude-cli' }));+ await resolve({ providerId: 'claude-cli' }, null, readSchedulePin);+ expect(readSchedulePin).not.toHaveBeenCalled();++ await resolve({ providerId: 'ollama' }, null, readSchedulePin);+ expect(readSchedulePin).toHaveBeenCalledTimes(1);+ });++ it('survives a schedule-pin read that throws', async () => {+ const res = await resolve({ providerId: 'ollama' }, null, async () => { throw new Error('nope'); });+ expect(res.skipReason).toBe('provider-not-agent-capable');+ });+});diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 426a7be11f..390879f06e 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -79,6 +79,7 @@ function outcomesTrackerSupported(filer) {}import { resolveAppWorkTracker } from '../../lib/workTracker.js'import { tryReadFile } from '../../lib/fileUtils.js'+import { resolveAgentProviderPin } from '../appTaskProviderPin.js'import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js'import { join } from 'path'@@ -117,89 +118,37 @@ async function resolveLiContext(app) {/*** Resolve LI's reasoning-AGENT provider/model — the SINGLE source of truth, so the* spawn path's hookOverride carries the fully-resolved choice rather than- * re-deriving the schedule pin in cosTaskGenerator. Walks per-app → schedule pin →- * default and applies the "must be a file-writing CLI/TUI harness" filter.+ * re-deriving the schedule pin in cosTaskGenerator. Delegates the per-app →+ * schedule-pin → default walk (and the api-harness guard) to the shared+ * `resolveAgentProviderPin`, which every task type now runs (#4783).*- * The reasoning agent needs a CLI/TUI harness to emit its `.agent-done` sentinel —- * an HTTP `api` provider (ollama / lmstudio / kimi) has none, so an agent-backed- * run pinned to one fails provider resolution and the task sits pending forever.- * Pre-#2322 LI called the API path directly, so an api provider was valid then;- * migration 184 faithfully carried whatever `layeredIntelligence.providerId` held- * — INCLUDING ollama/lmstudio/kimi — into the per-app override, which now outranks- * everything at spawn (cosTaskGenerator applies the hook's providerId LAST). So any- * install that ran LI on an api provider before #2322 is wedged, and the user's- * natural fix — picking a CLI/TUI provider on the global Schedule page — silently- * misses, because that only sets the schedule pin (the FALLBACK) while the stale- * per-app override still wins.+ * The guard matters most here because of LI's own history: pre-#2322 LI called the+ * API path directly, so an api provider was valid then, and migration 184+ * faithfully carried whatever `layeredIntelligence.providerId` held — INCLUDING+ * ollama/lmstudio/kimi — into the per-app override, which outranks everything at+ * spawn. Any install that ran LI on an api provider before #2322 is wedged, and+ * the user's natural fix (picking a CLI/TUI provider on the global Schedule page)+ * silently misses because that only sets the FALLBACK. The shared resolver's+ * self-heal adopts that pin instead of wedging.*- * SELF-HEAL that residue: when the per-app override is api-only but the schedule- * pin IS a real CLI/TUI provider, adopt the pin (provider + its matched model)- * instead of wedging — this makes the Schedule page's selection finally take- * effect. Only when NO CLI/TUI provider is configured anywhere the user chose- * (per-app api with no usable pin, or an api pin) do we return an actionable- * `skipReason` — guiding them to pick a real CLI/TUI provider beats silently- * substituting one they never chose. A null/absent resolved provider is fine: it- * inherits the default coding agent (a spawn-time api resolution still falls to the- * lifecycle block).- *- * Reads the global schedule pin AT MOST ONCE and mutates nothing — `config` is a- * read-only input (its `providerId`/`model` are the per-app effective override).- * Returns `{ providerId, model, skipReason }`; the caller gates on `skipReason`.+ * `config` is a read-only input (its `providerId`/`model` are the per-app+ * effective override). Returns `{ providerId, model, skipReason }`; the caller+ * gates on `skipReason` — LI is the one caller that CAN decline to generate, and+ * guiding the user to pick a real CLI/TUI provider beats silently substituting one+ * they never chose.*/async function resolveLiAgentProvider(app, config) {- const { getProviderById } = await import('../providers.js')- const providerTypeOf = async (id) => {- if (!id) return null- const provider = await getProviderById(id).catch(() => null)- return provider?.type ?? null- }- // The global schedule pin is LI's provider FALLBACK; read it via the canonical- // getTaskInterval (returns a defaulted { providerId: null, ... } when absent).- const readPin = async () => {- const { getTaskInterval } = await import('../taskSchedule.js')- return getTaskInterval('layered-intelligence')- }-- let providerId = config.providerId || null- let model = config.model ?? null- let type = await providerTypeOf(providerId)-- if (type === 'api') {- const pin = await readPin()- const pinId = pin?.providerId || null- const pinType = await providerTypeOf(pinId)- // Adopt the pin only when it RESOLVES to a real non-api provider. `pinType` is- // null for an unresolvable id (deleted/renamed/typo'd pin) — treating that as- // "not api" and adopting it would re-wedge the task on a doomed provider with a- // misleading "healed" warning, so require a positively-known type.- if (pinId && pinType && pinType !== 'api') {- console.warn(`⚠️ Layered Intelligence: ${app.name} per-app provider '${providerId}' is API-only (no coding harness) — using the schedule provider '${pinId}' instead`)- // Adopt the pin's model too — provider+model are a matched pair the user set- // together on the Schedule page (an api-provider model name may not be valid- // for the CLI/TUI provider).- providerId = pinId- model = pin?.model ?? null- type = pinType- }- } else if (!providerId) {- // No per-app override → resolve the schedule pin here so the returned override- // carries it, rather than delegating that leg to the generator's- // interval.providerId. An api pin still skips; a non-api pin becomes LI's- // provider; no pin inherits the default coding agent.- const pin = await readPin()- const pinId = pin?.providerId || null- type = await providerTypeOf(pinId)- if (type && type !== 'api') {- providerId = pinId- // Keep an explicit per-app model if the user set one (provider absent but- // model present); only fall back to the pin's model when there's no per-app- // model. This matches the pre-refactor net spawn behavior, where the hook's- // returned model (the per-app model) overrode the generator's interval.model.- model = config.model ?? pin?.model ?? null- }- }-- if (type === 'api') return { providerId: null, model: null, skipReason: 'provider-not-agent-capable' }+ const { providerId, model, skipReason } = await resolveAgentProviderPin({+ appPin: { providerId: config.providerId || null, model: config.model ?? null },+ // A thunk: an already-usable per-app provider never pays for the schedule read.+ readSchedulePin: async () => {+ const { getTaskInterval } = await import('../taskSchedule.js')+ return getTaskInterval('layered-intelligence')+ },+ taskType: 'layered-intelligence',+ appName: app.name+ })+ if (skipReason) return { providerId: null, model: null, skipReason }return { providerId, model, skipReason: null }}diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 4b47d6f038..3869890e87 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -34,6 +34,7 @@ import { addTask, updateTask, reviveBlockedTask, getAllTasks, getCosTasks, firstimport { recordDecision, DECISION_TYPES } from './decisionLog.js';import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';+import { resolveAgentProviderPin } from './appTaskProviderPin.js';import { getTaskTypeConfidence } from './taskLearning.js';import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';import { generateProactiveTasks as generateMissionTasks } from './missions.js';@@ -2340,11 +2341,13 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, t/*** Assemble the base improvement-task metadata and layer the sanitized global- * (schedule interval) + per-app taskMetadata overrides on top. Per-app strips+ * (schedule interval) + per-app taskMetadata overrides on top. `appOverride` is+ * this app's stored entry for `taskType` (loaded once by the caller, which also+ * reads its provider/model pin). Per-app strips* managed-agent fields first (see the sibling generateManagedAppTask path for* the rationale). Pure assembly — no gating, no early return.*/-async function buildImprovementTaskMetadata(taskType, app, interval, taskSchedule) {+function buildImprovementTaskMetadata(taskType, app, interval, taskSchedule, appOverride) {const metadata = {app: app.id,appName: app.name,@@ -2361,9 +2364,8 @@ async function buildImprovementTaskMetadata(taskType, app, interval, taskSchedul}// Apply sanitized per-app taskMetadata overrides (merge on top of global).- const appOverrides = await getAppTaskTypeOverrides(app.id);const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(- taskType, appOverrides[taskType]?.taskMetadata+ taskType, appOverride?.taskMetadata);const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);if (sanitizedAppMeta) {@@ -2957,15 +2959,41 @@ async function buildImprovementTaskDescription({ promptTemplate, app, promptTask: '');}+const EMPTY_PROVIDER_PIN = Object.freeze({ providerId: null, model: null });+/**- * Layer the provider/model/effort pins onto `metadata`: the global schedule- * interval first, then a buildTaskInput hook's per-app override (the more- * specific choice wins, so it is applied last). A model is only ever pinned- * when explicitly configured — otherwise it stays unset so selectModelForTask- * resolves the active provider's tier/default model at spawn time (see the- * note in generateSelfImprovementTaskForType).+ * The app's per-app provider/model pin for this task type, as an overlay to apply+ * over the global Schedule pin. Runs the shared harness guard+ * (`resolveAgentProviderPin`) so an api-typed per-app pin — which has no+ * file-writing harness and could only ever fail at spawn — falls back to the+ * Schedule pin rather than reaching the agent.+ *+ * Returns an EMPTY overlay when nothing resolvable is harness-capable: the+ * Schedule pin then stands untouched and agentProviderResolution reports its+ * actionable permanent error, which beats silently rerouting the run onto a+ * provider the user never chose.*/-function applyProviderModelPins(metadata, interval, hookOverride) {+async function resolveAppProviderPin({ app, taskType, appOverride, interval }) {+ if (!appOverride?.providerId && !appOverride?.model) return EMPTY_PROVIDER_PIN;+ const { providerId, model, skipReason } = await resolveAgentProviderPin({+ appPin: { providerId: appOverride.providerId || null, model: appOverride.model ?? null },+ readSchedulePin: () => interval,+ taskType,+ appName: app.name+ });+ return skipReason ? EMPTY_PROVIDER_PIN : { providerId, model };+}++/**+ * Layer the provider/model/effort pins onto `metadata`, least specific first:+ * the global schedule interval, then the app's own per-app pin, then a+ * buildTaskInput hook's fully-resolved choice. A model is only ever pinned when+ * explicitly configured — otherwise it stays unset so selectModelForTask resolves+ * the active provider's tier/default model at spawn time (see the note in+ * generateSelfImprovementTaskForType).+ */+function applyProviderModelPins(metadata, interval, appPin, hookOverride) {+ // Least specific first: the task's global Schedule pin.if (interval.providerId) {metadata.provider = interval.providerId;metadata.providerId = interval.providerId;@@ -2976,6 +3004,11 @@ function applyProviderModelPins(metadata, interval, hookOverride) {if (interval.effort) {metadata.effort = interval.effort;}+ // Then the app's own per-app pin, which is the more specific choice — honored+ // for EVERY task type (#4783), not just the one whose buildTaskInput hook read it.+ if (appPin.providerId) { metadata.provider = appPin.providerId; metadata.providerId = appPin.providerId; }+ if (appPin.model) { metadata.model = appPin.model; }+ // A buildTaskInput hook's fully-resolved choice wins outright.if (hookOverride.providerId) { metadata.provider = hookOverride.providerId; metadata.providerId = hookOverride.providerId; }if (hookOverride.model) { metadata.model = hookOverride.model; }}@@ -3000,9 +3033,15 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// task means rotation advanced; a `return null` short-circuit means it// didn't.- // Get interval settings to determine provider/model and pipeline config- const interval = await taskSchedule.getTaskInterval(taskType);- const metadata = await buildImprovementTaskMetadata(taskType, app, interval, taskSchedule);+ // Get interval settings to determine provider/model and pipeline config.+ // The per-app override entry is loaded ONCE here: it carries both the+ // taskMetadata merged below and the provider/model pin applied further down.+ const [interval, appOverrides] = await Promise.all([+ taskSchedule.getTaskInterval(taskType),+ getAppTaskTypeOverrides(app.id)+ ]);+ const appOverride = appOverrides[taskType] || null;+ const metadata = buildImprovementTaskMetadata(taskType, app, interval, taskSchedule, appOverride);initializePipelineMetadata(metadata);if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;@@ -3136,7 +3175,15 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stmetadata.openPR = false;metadata.simplify = false;}- applyProviderModelPins(metadata, interval, hookOverride);+ // The app's per-app provider/model pin (#4783). Resolved through the shared+ // harness guard, so an api-typed pin falls back to the Schedule pin instead of+ // reaching the spawn as a permanent provider failure. Skipped when a+ // buildTaskInput hook already resolved the provider — its return wins anyway, so+ // re-deriving here would only duplicate the fallback log line.+ const appPin = hookOverride.providerId+ ? EMPTY_PROVIDER_PIN+ : await resolveAppProviderPin({ app, taskType, appOverride, interval });+ applyProviderModelPins(metadata, interval, appPin, hookOverride);const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`, metadata);stampApprovalReason(metadata, approval);diff --git a/server/services/cosTaskGenerator.providerPin.test.js b/server/services/cosTaskGenerator.providerPin.test.jsnew file mode 100644index 0000000000..0da3ce5da5--- /dev/null+++ b/server/services/cosTaskGenerator.providerPin.test.js@@ -0,0 +1,125 @@+/**+ * The per-app provider/model pin reaching the SPAWN, for every task type (#4783).+ *+ * `taskTypeOverrides[<taskType>].providerId` / `.model` used to reach the agent+ * only for `layered-intelligence`, because only its `buildTaskInput` hook read+ * the field and `applyProviderModelPins` applied the hook's return last. Every+ * other type merged `taskMetadata` off the same record and then took its provider+ * from the global Schedule pin, so a pin set on the Automation tab silently never+ * ran. These tests assert the generated task's metadata, not the plumbing.+ *+ * Isolated file so the mocked leaf graph (taskSchedule / taskPromptService /+ * providers) can't leak into the shared cosTaskGenerator suite.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++vi.mock('./taskPromptService.js', () => ({+ getTaskPrompt: vi.fn(async () => 'Improve {appName} at {repoPath}'),+ getStagePrompt: vi.fn(async () => 'Improve {appName} at {repoPath}'),+}));++const getTaskIntervalMock = vi.fn(async () => ({ type: 'weekly', taskMetadata: {} }));+vi.mock('./taskSchedule.js', () => ({+ INTERVAL_TYPES: { PERPETUAL: 'perpetual', WEEKLY: 'weekly' },+ getTaskInterval: vi.fn((...args) => getTaskIntervalMock(...args)),+ stripManagedAgentOptionsFromOverride: vi.fn((_type, meta) => meta),+ recordExecution: vi.fn(async () => {}),+ parkPerpetual: vi.fn(async () => {}),+ getPerpetualDrainState: vi.fn(async () => ({ signature: null, dispatchCount: 0 })),+ recordPerpetualDispatch: vi.fn(async () => 1),+}));++vi.mock('./appActivity.js', async (importActual) => ({+ ...(await importActual()),+ updateAppActivity: vi.fn(async () => {}),+}));++const getAppTaskTypeOverridesMock = vi.fn(async () => ({}));+vi.mock('./apps.js', async (importActual) => ({+ ...(await importActual()),+ getAppTaskTypeOverrides: vi.fn((...args) => getAppTaskTypeOverridesMock(...args)),+}));++// The harness boundary the pin has to answer to: `api` providers return text with+// no file-writing tools, so an agent task can never run on one.+const PROVIDER_TYPES = { 'claude-cli': 'cli', 'opencode-tui': 'tui', ollama: 'api' };+vi.mock('./providers.js', async (importActual) => ({+ ...(await importActual()),+ getProviderById: vi.fn(async (id) => (PROVIDER_TYPES[id] ? { id, type: PROVIDER_TYPES[id] } : null)),+}));++vi.mock('./taskLearning.js', async (importActual) => ({+ ...(await importActual()),+ getTaskTypeConfidence: vi.fn(async () => ({ autoApprove: true, tier: 'high', reason: 'test' })),+}));++vi.mock('../lib/gitRemote.js', async (importActual) => ({+ ...(await importActual()),+ readOriginRemoteUrl: vi.fn(async () => null),+}));++import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js';++const APP = { id: 'app-1', name: 'Example App', repoPath: '/tmp/example-repo' };+const STATE = { config: { confidenceAutoApproval: { enabled: false }, idleReviewPriority: 'MEDIUM' } };++// `ux` has no buildTaskInput hook — exactly the class of task type the pin used to+// be inert for.+const generate = (taskType = 'ux') =>+ generateManagedAppImprovementTaskForType(taskType, APP, STATE, { skipPreconditions: true });++describe('per-app provider/model pin on a task type with no buildTaskInput hook', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', taskMetadata: {} });+ getAppTaskTypeOverridesMock.mockResolvedValue({});+ });++ it('spawns on the app pin, not the global Schedule pin', async () => {+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', taskMetadata: {}, providerId: 'opencode-tui', model: 'qwen' });+ getAppTaskTypeOverridesMock.mockResolvedValue({ ux: { enabled: true, providerId: 'claude-cli', model: 'opus' } });++ const task = await generate();+ expect(task.metadata.provider).toBe('claude-cli');+ expect(task.metadata.providerId).toBe('claude-cli');+ expect(task.metadata.model).toBe('opus');+ });++ it('still takes the Schedule pin when the app pins nothing', async () => {+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', taskMetadata: {}, providerId: 'opencode-tui', model: 'qwen' });++ const task = await generate();+ expect(task.metadata.provider).toBe('opencode-tui');+ expect(task.metadata.model).toBe('qwen');+ });++ it('does not wedge on an api-typed app pin — it falls back to the Schedule pin', async () => {+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', taskMetadata: {}, providerId: 'claude-cli', model: 'opus' });+ getAppTaskTypeOverridesMock.mockResolvedValue({ ux: { enabled: true, providerId: 'ollama', model: 'llama-3' } });++ const task = await generate();+ expect(task.metadata.provider).toBe('claude-cli');+ expect(task.metadata.model).toBe('opus');+ });++ it('leaves an api-only Schedule pin alone when the app pins an api provider too', async () => {+ // Nothing reachable has a harness. Rerouting to some other provider the user+ // never chose would be worse than letting agentProviderResolution report its+ // permanent, actionable error — so the Schedule pin stands.+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', taskMetadata: {}, providerId: 'ollama' });+ getAppTaskTypeOverridesMock.mockResolvedValue({ ux: { enabled: true, providerId: 'ollama' } });++ const task = await generate();+ expect(task.metadata.provider).toBe('ollama');+ });++ it('honors an app model pinned without an app provider', async () => {+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', taskMetadata: {}, providerId: 'claude-cli', model: 'opus' });+ getAppTaskTypeOverridesMock.mockResolvedValue({ ux: { enabled: true, model: 'sonnet' } });++ const task = await generate();+ expect(task.metadata.provider).toBe('claude-cli');+ expect(task.metadata.model).toBe('sonnet');+ });+});diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex ab47ad3dfa..22a18fa8e1 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -230,7 +230,7 @@ describe('isConfiguredApprovalRequired', () => {const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');const appStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');expect(GEN_SRC.slice(selfStart, selfStart + 2500)).toContain('stampApprovalReason(metadata, approval)');- expect(GEN_SRC.slice(appStart, appStart + 9000)).toContain('stampApprovalReason(metadata, approval)');+ expect(GEN_SRC.slice(appStart, appStart + 11000)).toContain('stampApprovalReason(metadata, approval)');});it('resolveConfidenceApproval consults the toggle before safety-kind and confidence', () => {diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 79f39ed2f5..8524a5ebc7 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -49,7 +49,6 @@ import {PREVIOUS_DEFAULT_PROMPTS} from './taskPromptDefaults.js';import { isAuditTaskType, defaultFileIssuesFor } from '../lib/auditCatalog.js';-import { honorsPerAppProviderOverride } from './taskTypeHooks.js';// Re-export the prompt-version constants so existing importers of taskSchedule.js// are unaffected. The prompt GETTERS (getDefaultPrompt / getTaskPrompt /@@ -2058,11 +2057,10 @@ export async function getScheduleStatus() {appOverrides[activeApps[i].id] = {enabled: isEnabledForApp(override),interval: override.interval || null,- // Surface the per-app provider/model pin: for a provider-override- // honoring type it OUTRANKS the global pin at spawn, so omitting it- // here made the Schedule page's provider read as authoritative when- // it wasn't (an app pinned to another provider ran on that one with- // no hint why).+ // Surface the per-app provider/model pin: it OUTRANKS the global pin at+ // spawn for every task type (#4783), so omitting it here made the Schedule+ // page's provider read as authoritative when it wasn't (an app pinned to+ // another provider ran on that one with no hint why)....(override.providerId && { providerId: override.providerId }),...(override.model && { model: override.model }),...(override.taskMetadata && { taskMetadata: override.taskMetadata })@@ -2109,13 +2107,6 @@ export async function getScheduleStatus() {taskStatus.defaultFileIssues = defaultFileIssuesFor(taskType);}- // Whether a per-app provider/model override reaches the spawn for this type- // (and therefore beats the pin above). Lets the UI offer the per-app picker- // exactly where it takes effect, and flag a stored-but-inert one elsewhere.- if (honorsPerAppProviderOverride(taskType)) {- taskStatus.providerOverrideCapable = true;- }-// Perpetual tasks park PER-APP (parkPerpetual is called with the appId), so// the global `status` above (shouldRunTask with no appId) always reads// 'perpetual-drain' for app-scoped tasks like claim-issue/claim-work evendiff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 6ad1561efa..11de57244a 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -1383,18 +1383,12 @@ describe('taskSchedule', () => {expect(status.tasks['claim-issue'].fileIssuesCapable).toBeUndefined()})- // A per-app provider/model pin outranks the task's own pin at spawn, but ONLY- // for a type whose buildTaskInput hook resolves it. The UI needs both facts —- // which types honor it, and what each app pinned — or the Schedule page shows- // a provider the run never used.- it('surfaces providerOverrideCapable only on provider-override honoring types', async () => {- mockSchedule()- const status = await getScheduleStatus()- expect(status.tasks['layered-intelligence'].providerOverrideCapable).toBe(true)- expect(status.tasks['security'].providerOverrideCapable).toBeUndefined()- })-- it('carries each app\'s provider/model pin into appOverrides', async () => {+ // A per-app provider/model pin outranks the task's own pin at spawn for EVERY+ // task type (#4783). The Schedule page needs to show what each app pinned, on+ // every row, or it advertises a provider the run never used. The retired+ // `providerOverrideCapable` stamp must not come back — it existed only while+ // the generic spawn path declined to read the pin.+ it('carries each app\'s provider/model pin into appOverrides, with no capability stamp', async () => {mockSchedule()const apps = await import('./apps.js')apps.getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])@@ -1407,6 +1401,9 @@ describe('taskSchedule', () => {providerId: 'claude-ollama-tui',model: 'qwen-b'})+ // A non-LI type surfaces the SAME pin — the capability flag is gone.+ expect(status.tasks['layered-intelligence']).not.toHaveProperty('providerOverrideCapable')+ expect(status.tasks['security']).not.toHaveProperty('providerOverrideCapable')// An app that pinned nothing carries no provider keys at all — absent must// stay distinguishable from "explicitly pinned".expect(status.tasks['security'].appOverrides['app-1']).not.toHaveProperty('providerId')diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 255bc8c95c..378362bbdb 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -50,20 +50,14 @@ import { isFalsyMeta, isTruthyMeta } from './agentState.js';import { TRACKER_FILING_TASK_TYPES, CONCRETE_WORK_TRACKERS } from '../lib/workTracker.js';import { isAuditTaskType } from '../lib/auditCatalog.js';-// taskType → { load, honorsPerAppProviderOverride? }. `load` is the module import-// thunk; a module may export either or both hooks, and a missing export means "no-// hook of that kind for this type". Capabilities that callers must know WITHOUT-// paying for the import are declared here on the entry, so this stays the single-// registration point (a parallel per-capability list would be free to drift).+// taskType → { load }. `load` is the module import thunk; a module may export+// either or both hooks, and a missing export means "no hook of that kind for this+// type". Entries stay objects rather than bare thunks so a capability a caller+// must know WITHOUT paying for the import can be declared here, keeping this the+// single registration point (a parallel per-capability list would be free to drift).const HOOK_MODULES = {'layered-intelligence': {- load: () => import('./autonomousJobs/layeredIntelligenceHooks.js'),- // Its buildTaskInput hook resolves the app's per-app provider/model override,- // and cosTaskGenerator applies the hook's return LAST (applyProviderModelPins)- // — so for this type the per-app pin OUTRANKS the global Schedule pin. A type- // without this flag reads only `taskMetadata` off the override and takes its- // provider from the pin, making a stored per-app provider inert there.- honorsPerAppProviderOverride: true+ load: () => import('./autonomousJobs/layeredIntelligenceHooks.js')},};const PAYLOAD_OPTIONAL_OUTPUT_HOOKS = new Set();@@ -267,17 +261,6 @@ function isTrackerFilingDispatch(task) {return CONCRETE_WORK_TRACKERS.includes(task?.metadata?.workTracker);}-/**- * Whether a per-app provider/model override actually reaches the spawn for this- * task type (and therefore supersedes the global Schedule pin) — read off the- * type's own registry entry. Synchronous so the schedule-status builder can stamp- * the capability on every task row.- */-export function honorsPerAppProviderOverride(taskType) {- return isProgrammaticIoTaskType(taskType)- && HOOK_MODULES[taskType].honorsPerAppProviderOverride === true;-}-/*** Resolve the pre-agent input hook for a task type, or null if it has none.* `buildTaskInput({ app, taskType })` → `{ prompt?, providerId?, model?, hookMetadata?, skip? }`diff --git a/server/services/taskTypeHooks.test.js b/server/services/taskTypeHooks.test.jsindex 0a741ee976..59ffc9e018 100644--- a/server/services/taskTypeHooks.test.js+++ b/server/services/taskTypeHooks.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { canRunTaskOutputHookWithoutPayload, getTaskInputHook, getTaskOutputHook, honorsPerAppProviderOverride, isProgrammaticIoTaskType } from './taskTypeHooks.js';+import { canRunTaskOutputHookWithoutPayload, getTaskInputHook, getTaskOutputHook, isProgrammaticIoTaskType } from './taskTypeHooks.js';describe('taskTypeHooks registry', () => {it('resolves both hooks for layered-intelligence to callables', async () => {@@ -40,15 +40,3 @@ describe('isProgrammaticIoTaskType (#2700)', () => {expect(isProgrammaticIoTaskType('toString')).toBe(false);});});--describe('honorsPerAppProviderOverride', () => {- it('is true only for the type whose hook resolves the app pin', () => {- expect(honorsPerAppProviderOverride('layered-intelligence')).toBe(true);- // A type with no hook at all can't consume a per-app provider/model, so the- // UI must not offer one for it.- expect(honorsPerAppProviderOverride('security')).toBe(false);- // Same inherited-key hazard isProgrammaticIoTaskType guards — the capability- // read must not resolve through the prototype either.- expect(honorsPerAppProviderOverride('constructor')).toBe(false);- });-});diff --git a/server/services/workflow.js b/server/services/workflow.jsindex 416656e6d8..b531d53d9f 100644--- a/server/services/workflow.js+++ b/server/services/workflow.js@@ -201,11 +201,10 @@ export async function getWorkflowGraph({ horizonHours = 24, from = new Date() }totalAppCount: info.totalAppCount || 0,taskMetadata: info.taskMetadata || null,managedAgentOptions: info.managedAgentOptions || null,- // The task's provider/model pin plus whether a per-app override of it is- // honored — the per-app rows render their "Inherit (…)" label from these.+ // The task's provider/model pin — the per-app rows render their+ // "Inherit (…)" label from it and pin over it.providerId: info.providerId || null,- model: info.model || null,- providerOverrideCapable: info.providerOverrideCapable === true+ model: info.model || null});for (const dep of runAfter) {