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: add client orchestration profile pickers and settings library (#5992)
[._.]/ Adam Eivyda0bcc19c5fa
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 0d3c4cb501..6ff188b289 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -305,6 +305,7 @@ export const NAV_PRESENTATION = {'/settings/general': { icon: Settings },'/settings/mortalloom': { icon: Activity },'/openclaw': { icon: MessagesSquare },+ '/settings/orchestration': { icon: Cpu },'/prompts': { icon: FileText },'/ai': { icon: Bot },'/settings/security': { icon: Lock },diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex fa7b293a69..932c6d058e 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -21,6 +21,13 @@ import { reviewerModelsFromDefaults, reviewerEffortsFromDefaults } from '../../limport { PORTOS_APP_ID } from '../../lib/appIdentity';import { safeReadJsonStorage, safeReadStorage, safeRemoveStorage, safeWriteJsonStorage } from '../../lib/safeStorage';+const ORCHESTRATION_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];+const ORCHESTRATION_ROLES_META = [+ { key: 'architect', label: 'Architect', hint: 'Planning & spec authoring' },+ { key: 'implementer', label: 'Implementer', hint: 'Spec execution' },+ { key: 'reviewer', label: 'Reviewer', hint: 'Spec verification' },+];+const TASK_DESCRIPTION_DRAFT_KEY = 'portos-cos-task-description-draft';const INVALID_DRAFT = Symbol('invalid task description draft');@@ -121,6 +128,66 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, o// Bare slashdo command a quick-template pinned (`plan-task`), never a rendered// `/do:x` string — see server/lib/slashdoInvocation.js for why.const [slashdoCommand, setSlashdoCommand] = useState('');+ const [orchestrationMode, setOrchestrationMode] = useState('direct');+ const [orchestrationProfiles, setOrchestrationProfiles] = useState([]);+ const [selectedProfileId, setSelectedProfileId] = useState('');+ const [orchestrationProfile, setOrchestrationProfile] = useState({+ architect: { provider: '', model: '', effort: '' },+ implementer: { provider: '', model: '', effort: '' },+ reviewer: { provider: '', model: '', effort: '' },+ });++ useEffect(() => {+ api.getOrchestrationProfiles?.({ silent: true })+ ?.then((res) => {+ const list = Array.isArray(res) ? res : res?.profiles || [];+ setOrchestrationProfiles(list);+ })+ ?.catch(() => {});+ }, []);++ const handleSelectOrchestrationProfile = (profileId) => {+ setSelectedProfileId(profileId);+ if (!profileId) return;+ const found = orchestrationProfiles.find((p) => p.id === profileId);+ if (found?.profile) {+ setOrchestrationProfile({+ architect: {+ provider: found.profile.architect?.provider || '',+ model: found.profile.architect?.model || '',+ effort: found.profile.architect?.effort || '',+ },+ implementer: {+ provider: found.profile.implementer?.provider || '',+ model: found.profile.implementer?.model || '',+ effort: found.profile.implementer?.effort || '',+ },+ reviewer: {+ provider: found.profile.reviewer?.provider || '',+ model: found.profile.reviewer?.model || '',+ effort: found.profile.reviewer?.effort || '',+ },+ });+ }+ };++ const updateOrchestrationRoleField = (roleKey, field, val) => {+ setOrchestrationProfile((prev) => {+ const roleData = prev[roleKey] || {};+ let updatedRole = { ...roleData, [field]: val };+ if (field === 'provider') {+ updatedRole.model = '';+ updatedRole.effort = '';+ } else if (field === 'model') {+ const prov = providers?.find((p) => p.id === roleData.provider);+ updatedRole.effort = effortSurvivingModel(prov, val, roleData.effort);+ }+ return {+ ...prev,+ [roleKey]: updatedRole,+ };+ });+ };// Resolved model lists for the reviewer table's Model column. Owned here (not by// ReviewerPicker) so the picker stays fetch-free — see its `modelOptions` prop.const reviewerModelOptions = useReviewerModelOptions();@@ -573,6 +640,8 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, omodel: newTask.model || undefined,provider: newTask.provider || undefined,effort: newTask.effort || undefined,+ orchestrationMode: orchestrationMode === 'orchestrated' ? 'orchestrated' : undefined,+ orchestrationProfile: orchestrationMode === 'orchestrated' ? orchestrationProfile : undefined,temperature: newTask.temperature === '' ? undefined : Number(newTask.temperature),thinking: newTask.thinking === '' ? undefined : newTask.thinking === 'true',app: newTask.app || undefined,@@ -970,58 +1039,164 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, o</>)}</div>- <div className="flex flex-col sm:flex-row gap-3">- <div className="sm:w-40">- <label htmlFor="task-provider" className="sr-only">AI provider</label>- <select- id="task-provider"- value={newTask.provider}- onChange={e => setNewTask(t => ({ ...t, provider: e.target.value, model: '', effort: '', temperature: '', thinking: '' }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"- disabled={!providersLoaded}+ <div className="flex items-center justify-between gap-2 pt-1 border-t border-port-border/40">+ <div className="flex items-center gap-1.5 text-xs text-gray-400">+ <span>Execution:</span>+ <button+ type="button"+ onClick={() => setOrchestrationMode('direct')}+ className={`px-2.5 py-1 rounded text-xs transition-colors ${+ orchestrationMode === 'direct'+ ? 'bg-port-accent text-white font-medium'+ : 'bg-port-border/40 text-gray-400 hover:text-white'+ }`}>- {providersLoaded- ? <option value="">Auto (default)</option>- : <option value="">Loading providers…</option>}- {providersLoaded && enabledProviders.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>+ Direct+ </button>+ <button+ type="button"+ onClick={() => setOrchestrationMode('orchestrated')}+ className={`px-2.5 py-1 rounded text-xs transition-colors ${+ orchestrationMode === 'orchestrated'+ ? 'bg-port-accent text-white font-medium'+ : 'bg-port-border/40 text-gray-400 hover:text-white'+ }`}+ >+ Orchestrated+ </button>+ </div>+ {orchestrationMode === 'orchestrated' && (+ <div className="flex items-center gap-2">+ <label htmlFor="orchestration-profile-select" className="text-xs text-gray-400">+ Profile:+ </label>+ <select+ id="orchestration-profile-select"+ value={selectedProfileId}+ onChange={(e) => handleSelectOrchestrationProfile(e.target.value)}+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white"+ >+ <option value="">Custom Profile</option>+ {orchestrationProfiles.map((p) => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ )}+ </div>++ {orchestrationMode === 'orchestrated' ? (+ <div className="space-y-3 bg-port-bg/40 border border-port-border/60 rounded-xl p-3">+ <div className="grid grid-cols-1 gap-2.5">+ {ORCHESTRATION_ROLES_META.map(({ key, label, hint }) => {+ const roleData = orchestrationProfile[key] || {};+ const selectedProv = providers?.find((p) => p.id === roleData.provider);+ const models = selectedProv ? effortAwareModelOptions(selectedProv, roleData.model) : [];++ return (+ <div key={key} className="flex flex-col sm:flex-row sm:items-center gap-2 text-xs">+ <div className="sm:w-28 flex-shrink-0">+ <span className="font-medium text-white">{label}</span>+ <span className="block text-[10px] text-gray-400 truncate">{hint}</span>+ </div>++ <div className="flex-1 grid grid-cols-1 sm:grid-cols-3 gap-2">+ <select+ aria-label={`${label} provider`}+ value={roleData.provider || ''}+ onChange={(e) => updateOrchestrationRoleField(key, 'provider', e.target.value)}+ className="px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-xs"+ >+ <option value="">Auto / Default</option>+ {enabledProviders.map((p) => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>++ <select+ aria-label={`${label} model`}+ value={roleData.model || ''}+ disabled={!selectedProv || models.length === 0}+ onChange={(e) => updateOrchestrationRoleField(key, 'model', e.target.value)}+ className="px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-xs disabled:opacity-50"+ >+ <option value="">Default Model</option>+ {models.map((m) => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>++ <select+ aria-label={`${label} effort`}+ value={roleData.effort || ''}+ onChange={(e) => updateOrchestrationRoleField(key, 'effort', e.target.value)}+ className="px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-xs"+ >+ <option value="">Default Effort</option>+ {ORCHESTRATION_EFFORTS.map((eff) => (+ <option key={eff} value={eff}>{eff}</option>+ ))}+ </select>+ </div>+ </div>+ );+ })}+ </div></div>- {availableModels.length > 0 ? (- <div className="flex-1">- <label htmlFor="task-model" className="sr-only">AI model</label>+ ) : (+ <div className="flex flex-col sm:flex-row gap-3">+ <div className="sm:w-40">+ <label htmlFor="task-provider" className="sr-only">AI provider</label><select- id="task-model"- value={newTask.model}- onChange={e => setNewTask(t => ({- ...t,- model: e.target.value,- // A model with no effort tiers hides the select below — clear the- // value with it rather than submitting a level the UI stopped showing.- effort: effortSurvivingModel(selectedProvider, e.target.value, t.effort),- }))}+ id="task-provider"+ value={newTask.provider}+ onChange={e => setNewTask(t => ({ ...t, provider: e.target.value, model: '', effort: '', temperature: '', thinking: '' }))}className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"+ disabled={!providersLoaded}>- <option value="">Select model...</option>- {availableModels.map(m => (- <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ {providersLoaded+ ? <option value="">Auto (default)</option>+ : <option value="">Loading providers…</option>}+ {providersLoaded && enabledProviders.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>))}</select></div>- ) : selectedProvider ? (- <div className="flex-1 px-3 py-2 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 flex items-center">- {providerModelNote}- </div>- ) : null}- <EffortSelect- provider={selectedProvider}- model={effectiveModelFor(selectedProvider, newTask.model)}- value={newTask.effort}- onChange={effort => setNewTask(t => ({ ...t, effort }))}- className="sm:w-40 w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"- />- </div>+ {availableModels.length > 0 ? (+ <div className="flex-1">+ <label htmlFor="task-model" className="sr-only">AI model</label>+ <select+ id="task-model"+ value={newTask.model}+ onChange={e => setNewTask(t => ({+ ...t,+ model: e.target.value,+ // A model with no effort tiers hides the select below — clear the+ // value with it rather than submitting a level the UI stopped showing.+ effort: effortSurvivingModel(selectedProvider, e.target.value, t.effort),+ }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"+ >+ <option value="">Select model...</option>+ {availableModels.map(m => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>+ ) : selectedProvider ? (+ <div className="flex-1 px-3 py-2 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 flex items-center">+ {providerModelNote}+ </div>+ ) : null}+ <EffortSelect+ provider={selectedProvider}+ model={effectiveModelFor(selectedProvider, newTask.model)}+ value={newTask.effort}+ onChange={effort => setNewTask(t => ({ ...t, effort }))}+ className="sm:w-40 w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"+ />+ </div>+ )}{isOpencodeLocalProvider(selectedProvider) && (<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{/* OrcaRouter fronts cloud models that own their own reasoningdiff --git a/client/src/components/cos/TaskAddForm.test.jsx b/client/src/components/cos/TaskAddForm.test.jsxindex 6e503aecf5..91bbee8463 100644--- a/client/src/components/cos/TaskAddForm.test.jsx+++ b/client/src/components/cos/TaskAddForm.test.jsx@@ -12,7 +12,8 @@ const api = vi.hoisted(() => ({getAppWorkTracker: vi.fn(),getAppRepositorySources: vi.fn(),applyCosTaskTemplate: vi.fn(),- addCosTask: vi.fn()+ addCosTask: vi.fn(),+ getOrchestrationProfiles: vi.fn(),}));// useAssignableInstances reads the instance registry straight off apiSystem, so@@ -50,6 +51,7 @@ describe('TaskAddForm responsive layout', () => {},});api.applyCosTaskTemplate.mockResolvedValue({ success: true });+ api.getOrchestrationProfiles.mockResolvedValue({ profiles: [] });apiSystem.getAssignableInstances.mockResolvedValue({ instances: [] });});@@ -657,4 +659,63 @@ describe('TaskAddForm worktree/PR defaults', () => {));});});++ describe('orchestration mode and profile picker', () => {+ it('switches to orchestrated mode and passes orchestration profile on submit', async () => {+ const user = userEvent.setup();+ const onTaskAdded = vi.fn();+ api.getOrchestrationProfiles.mockResolvedValue({+ profiles: [+ {+ id: 'heavy-planner',+ name: 'Heavy Planner',+ profile: {+ architect: { provider: 'anthropic', model: 'claude-3-opus', effort: 'high' },+ implementer: { provider: 'anthropic', model: 'claude-3-5-sonnet', effort: 'medium' },+ },+ },+ ],+ });+ api.addCosTask.mockResolvedValue({ id: 'task-orch', description: 'Orchestrated task', status: 'pending', metadata: {} });++ render(+ <TaskAddForm+ providers={[+ { id: 'anthropic', name: 'Anthropic', enabled: true, models: ['claude-3-opus', 'claude-3-5-sonnet'] },+ ]}+ apps={[{ id: 'app-1', name: 'PortOS' }]}+ onTaskAdded={onTaskAdded}+ />+ );+ await act(async () => {});++ // Click "Orchestrated" mode button+ const orchBtn = screen.getByRole('button', { name: /Orchestrated/i });+ await user.click(orchBtn);++ // Select "Heavy Planner" profile+ const profileSelect = screen.getByLabelText(/Profile:/i);+ await user.selectOptions(profileSelect, 'heavy-planner');++ const desc = screen.getByPlaceholderText('Task description *');+ await user.type(desc, 'Orchestrated task');++ const submitBtn = screen.getByRole('button', { name: 'Add' });+ await user.click(submitBtn);++ await waitFor(() => {+ expect(api.addCosTask).toHaveBeenCalledWith(+ expect.objectContaining({+ description: 'Orchestrated task',+ orchestrationMode: 'orchestrated',+ orchestrationProfile: expect.objectContaining({+ architect: expect.objectContaining({ provider: 'anthropic', model: 'claude-3-opus', effort: 'high' }),+ implementer: expect.objectContaining({ provider: 'anthropic', model: 'claude-3-5-sonnet', effort: 'medium' }),+ }),+ }),+ expect.anything()+ );+ });+ });+ });});diff --git a/client/src/components/settings/OrchestrationTab.jsx b/client/src/components/settings/OrchestrationTab.jsxnew file mode 100644index 0000000000..a4cac8e0b1--- /dev/null+++ b/client/src/components/settings/OrchestrationTab.jsx@@ -0,0 +1,442 @@+import { useState, useEffect, useCallback } from 'react';+import { Plus, Edit2, Trash2, Cpu, Check, X, Shield, Sparkles } from 'lucide-react';+import toast from '../ui/Toast';+import FormField from '../ui/FormField';+import * as api from '../../services/api';+import { effortAwareModelOptions, effortSurvivingModel } from '../../utils/providers';++const ROLES = [+ { key: 'architect', label: 'Architect', description: 'Plans, analyzes, writes specs, and coordinates delegation' },+ { key: 'implementer', label: 'Implementer', description: 'Executes individual specs in isolated context' },+ { key: 'reviewer', label: 'Reviewer', description: 'Evaluates correctness against spec and guidelines' },+];++const GENERAL_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];++const emptyProfileDraft = () => ({+ id: '',+ name: '',+ description: '',+ profile: {+ architect: { provider: '', model: '', effort: '' },+ implementer: { provider: '', model: '', effort: '' },+ reviewer: { provider: '', model: '', effort: '' },+ },+});++export default function OrchestrationTab() {+ const [profiles, setProfiles] = useState([]);+ const [providers, setProviders] = useState([]);+ const [loading, setLoading] = useState(true);+ const [editingProfile, setEditingProfile] = useState(null);+ const [isNew, setIsNew] = useState(false);+ const [saving, setSaving] = useState(false);+ const [deletingId, setDeletingId] = useState(null);++ const loadData = useCallback(async () => {+ setLoading(true);+ try {+ const [profList, provList] = await Promise.all([+ api.getOrchestrationProfiles({ silent: true }).catch(() => []),+ api.getProviders({ silent: true }).catch(() => []),+ ]);+ setProfiles(profList || []);+ setProviders((provList || []).filter((p) => p.enabled));+ } catch (err) {+ toast.error(`Failed to load orchestration data: ${err.message}`);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ loadData();+ }, [loadData]);++ const handleStartCreate = () => {+ setEditingProfile(emptyProfileDraft());+ setIsNew(true);+ };++ const handleStartEdit = (profile) => {+ setEditingProfile({+ id: profile.id,+ name: profile.name,+ description: profile.description || '',+ profile: {+ architect: {+ provider: profile.profile?.architect?.provider || '',+ model: profile.profile?.architect?.model || '',+ effort: profile.profile?.architect?.effort || '',+ },+ implementer: {+ provider: profile.profile?.implementer?.provider || '',+ model: profile.profile?.implementer?.model || '',+ effort: profile.profile?.implementer?.effort || '',+ },+ reviewer: {+ provider: profile.profile?.reviewer?.provider || '',+ model: profile.profile?.reviewer?.model || '',+ effort: profile.profile?.reviewer?.effort || '',+ },+ },+ });+ setIsNew(false);+ };++ const handleCancelEdit = () => {+ setEditingProfile(null);+ setIsNew(false);+ };++ const handleSave = async () => {+ if (!editingProfile.name.trim()) {+ toast.error('Profile name is required');+ return;+ }++ const id = (editingProfile.id || editingProfile.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-').replace(/-+/g, '-')).trim();+ if (!id) {+ toast.error('Valid profile ID is required');+ return;+ }++ setSaving(true);+ try {+ const payload = {+ id,+ name: editingProfile.name.trim(),+ description: editingProfile.description?.trim() || '',+ profile: editingProfile.profile,+ };++ if (isNew) {+ await api.saveOrchestrationProfile(payload);+ toast.success(`Profile "${payload.name}" created`);+ } else {+ await api.updateOrchestrationProfile(id, payload);+ toast.success(`Profile "${payload.name}" updated`);+ }++ setEditingProfile(null);+ setIsNew(false);+ await loadData();+ } catch (err) {+ toast.error(`Failed to save profile: ${err.message}`);+ } finally {+ setSaving(false);+ }+ };++ const handleDelete = async (id, name) => {+ if (!confirm(`Are you sure you want to delete profile "${name}"?`)) return;+ setDeletingId(id);+ try {+ await api.deleteOrchestrationProfile(id);+ toast.success(`Profile "${name}" deleted`);+ await loadData();+ } catch (err) {+ toast.error(`Failed to delete profile: ${err.message}`);+ } finally {+ setDeletingId(null);+ }+ };++ const updateRoleField = (roleKey, field, val) => {+ setEditingProfile((prev) => {+ const currentRole = prev.profile[roleKey] || {};+ let updatedRole = { ...currentRole, [field]: val };++ if (field === 'provider') {+ updatedRole.model = '';+ updatedRole.effort = '';+ } else if (field === 'model') {+ const prov = providers.find((p) => p.id === currentRole.provider);+ updatedRole.effort = effortSurvivingModel(prov, val, currentRole.effort);+ }++ return {+ ...prev,+ profile: {+ ...prev.profile,+ [roleKey]: updatedRole,+ },+ };+ });+ };++ return (+ <div className="space-y-6 max-w-5xl">+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">+ <div>+ <h2 className="text-xl font-semibold text-white flex items-center gap-2">+ <Cpu className="text-port-accent" size={24} />+ Orchestration Profiles+ </h2>+ <p className="text-sm text-gray-400 mt-1">+ Configure multi-role execution with per-role provider, model, and reasoning effort+ for the Architect, Implementer, and Reviewer. Machine-local and opt-in per task.+ </p>+ </div>+ {!editingProfile && (+ <button+ onClick={handleStartCreate}+ className="inline-flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm font-medium transition-colors self-start sm:self-auto"+ >+ <Plus size={16} />+ New Profile+ </button>+ )}+ </div>++ {editingProfile ? (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-6">+ <div className="flex items-center justify-between border-b border-port-border pb-4">+ <h3 className="text-lg font-medium text-white">+ {isNew ? 'Create Orchestration Profile' : `Edit "${editingProfile.name}"`}+ </h3>+ <button+ onClick={handleCancelEdit}+ aria-label="Close"+ className="text-gray-400 hover:text-white p-2 rounded-lg transition-colors min-h-[44px] min-w-[44px] inline-flex items-center justify-center"+ >+ <X size={20} />+ </button>+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <FormField label="Profile Name" hint="Human-readable label for task pickers">+ <input+ type="text"+ value={editingProfile.name}+ onChange={(e) => {+ const name = e.target.value;+ setEditingProfile((p) => ({+ ...p,+ name,+ id: isNew && (!p.id || p.id === p.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-'))+ ? name.toLowerCase().replace(/[^a-z0-9-_]/g, '-').replace(/-+/g, '-')+ : p.id,+ }));+ }}+ placeholder="e.g. Heavy Planner / Fast Implementer"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </FormField>++ <FormField label="Profile ID" hint="Unique machine-local identifier">+ <input+ type="text"+ value={editingProfile.id}+ disabled={!isNew}+ onChange={(e) => setEditingProfile((p) => ({ ...p, id: e.target.value.toLowerCase().replace(/[^a-z0-9-_]/g, '-') }))}+ placeholder="e.g. heavy-planner"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm disabled:opacity-50"+ />+ </FormField>+ </div>++ <FormField label="Description" hint="Optional summary of this profile's strategy">+ <textarea+ value={editingProfile.description}+ onChange={(e) => setEditingProfile((p) => ({ ...p, description: e.target.value }))}+ placeholder="e.g. Uses a reasoning-heavy architect for task planning and a fast model for mechanical edits."+ rows={2}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm resize-none"+ />+ </FormField>++ <div className="space-y-4 pt-2">+ <h4 className="text-sm font-semibold uppercase tracking-wider text-gray-400">+ Role Assignments+ </h4>+ <div className="grid grid-cols-1 gap-4">+ {ROLES.map(({ key, label, description }) => {+ const roleData = editingProfile.profile[key] || {};+ const selectedProv = providers.find((p) => p.id === roleData.provider);+ const models = selectedProv ? effortAwareModelOptions(selectedProv, roleData.model) : [];++ return (+ <div key={key} className="bg-port-bg/50 border border-port-border/80 rounded-xl p-4 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1">+ <span className="font-medium text-white flex items-center gap-2">+ <Sparkles size={14} className="text-port-accent" />+ {label} Role+ </span>+ <span className="text-xs text-gray-400">{description}</span>+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div>+ <label htmlFor={`role-${key}-provider`} className="text-xs text-gray-400 mb-1 block">Provider</label>+ <select+ id={`role-${key}-provider`}+ aria-label={`${label} Provider`}+ value={roleData.provider || ''}+ onChange={(e) => updateRoleField(key, 'provider', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="">Default (Auto / Inherit)</option>+ {providers.map((p) => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>++ <div>+ <label htmlFor={`role-${key}-model`} className="text-xs text-gray-400 mb-1 block">Model</label>+ <select+ id={`role-${key}-model`}+ aria-label={`${label} Model`}+ value={roleData.model || ''}+ disabled={!selectedProv || models.length === 0}+ onChange={(e) => updateRoleField(key, 'model', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm disabled:opacity-50"+ >+ <option value="">Default (Provider default)</option>+ {models.map((m) => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>++ <div>+ <label htmlFor={`role-${key}-effort`} className="text-xs text-gray-400 mb-1 block">Reasoning Effort</label>+ <select+ id={`role-${key}-effort`}+ aria-label={`${label} Reasoning Effort`}+ value={roleData.effort || ''}+ onChange={(e) => updateRoleField(key, 'effort', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="">Default (Inherit / Task)</option>+ {GENERAL_EFFORTS.map((eff) => (+ <option key={eff} value={eff}>{eff}</option>+ ))}+ </select>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ </div>++ <div className="flex justify-end gap-3 pt-4 border-t border-port-border">+ <button+ onClick={handleCancelEdit}+ disabled={saving}+ className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-sm transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleSave}+ disabled={saving}+ className="inline-flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50"+ >+ <Check size={16} />+ {saving ? 'Saving…' : 'Save Profile'}+ </button>+ </div>+ </div>+ ) : null}++ {loading ? (+ <div className="p-8 text-center text-gray-400">Loading orchestration profiles…</div>+ ) : profiles.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-xl p-8 text-center space-y-3">+ <p className="text-gray-400">No orchestration profiles configured.</p>+ <button+ onClick={handleStartCreate}+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm font-medium transition-colors"+ >+ Create your first profile+ </button>+ </div>+ ) : (+ <div className="grid grid-cols-1 gap-4">+ {profiles.map((p) => {+ const isDeleting = deletingId === p.id;+ return (+ <div+ key={p.id}+ className="bg-port-card border border-port-border rounded-xl p-5 space-y-4 hover:border-port-border/80 transition-colors"+ >+ <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">+ <div className="space-y-1">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-semibold text-white text-base">{p.name}</span>+ <span className="text-xs px-2 py-0.5 rounded-full bg-port-border text-gray-300 font-mono">+ {p.id}+ </span>+ {p.isBuiltin && (+ <span className="text-xs px-2 py-0.5 rounded-full bg-port-accent/20 text-port-accent border border-port-accent/30 flex items-center gap-1">+ <Shield size={10} /> Built-in+ </span>+ )}+ </div>+ {p.description && (+ <p className="text-sm text-gray-400">{p.description}</p>+ )}+ </div>++ <div className="flex items-center gap-2 self-end sm:self-auto">+ <button+ onClick={() => handleStartEdit(p)}+ className="p-2 hover:bg-port-border rounded-lg text-gray-300 hover:text-white transition-colors min-h-[44px] min-w-[44px] inline-flex items-center justify-center"+ title="Edit profile"+ aria-label={`Edit profile ${p.name}`}+ >+ <Edit2 size={16} />+ </button>+ {!p.isBuiltin && (+ <button+ onClick={() => handleDelete(p.id, p.name)}+ disabled={isDeleting}+ className="p-2 hover:bg-red-500/20 text-gray-400 hover:text-red-400 rounded-lg transition-colors disabled:opacity-50 min-h-[44px] min-w-[44px] inline-flex items-center justify-center"+ title="Delete profile"+ aria-label={`Delete profile ${p.name}`}+ >+ <Trash2 size={16} />+ </button>+ )}+ </div>+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 pt-2 border-t border-port-border/50 text-sm">+ {ROLES.map(({ key, label }) => {+ const r = p.profile?.[key];+ const prov = r?.provider ? (providers.find((x) => x.id === r.provider)?.name || r.provider) : 'Default';+ const mod = r?.model || 'Default';+ const eff = r?.effort || 'Default';++ return (+ <div key={key} className="bg-port-bg/40 rounded-lg p-3 space-y-1.5 border border-port-border/40">+ <div className="text-xs font-semibold text-port-accent uppercase tracking-wider">+ {label}+ </div>+ <div className="text-xs text-gray-300">+ <span className="text-gray-500">Provider: </span>+ <span className="font-medium text-white">{prov}</span>+ </div>+ <div className="text-xs text-gray-300 truncate">+ <span className="text-gray-500">Model: </span>+ <span className="font-medium text-white">{mod}</span>+ </div>+ <div className="text-xs text-gray-300">+ <span className="text-gray-500">Effort: </span>+ <span className="font-medium text-white">{eff}</span>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/settings/OrchestrationTab.test.jsx b/client/src/components/settings/OrchestrationTab.test.jsxnew file mode 100644index 0000000000..3b381890b3--- /dev/null+++ b/client/src/components/settings/OrchestrationTab.test.jsx@@ -0,0 +1,101 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import OrchestrationTab from './OrchestrationTab';+import * as api from '../../services/api';++vi.mock('../../services/api', () => ({+ getOrchestrationProfiles: vi.fn(),+ getProviders: vi.fn(),+ saveOrchestrationProfile: vi.fn(),+ updateOrchestrationProfile: vi.fn(),+ deleteOrchestrationProfile: vi.fn(),+}));++describe('OrchestrationTab', () => {+ const mockProfiles = [+ {+ id: 'heavy-planner',+ name: 'Heavy Planning / Lean Execution',+ description: 'High reasoning effort for architect',+ isBuiltin: true,+ profile: {+ architect: { effort: 'high' },+ implementer: { effort: 'low' },+ reviewer: { effort: 'medium' },+ },+ },+ {+ id: 'custom-team',+ name: 'Custom Team',+ description: 'My custom profile',+ isBuiltin: false,+ profile: {+ architect: { provider: 'anthropic', model: 'claude-3-opus', effort: 'max' },+ implementer: { provider: 'anthropic', model: 'claude-3-5-sonnet', effort: 'low' },+ reviewer: { effort: 'medium' },+ },+ },+ ];++ const mockProviders = [+ { id: 'anthropic', name: 'Anthropic', enabled: true, models: ['claude-3-opus', 'claude-3-5-sonnet'] },+ { id: 'openai', name: 'OpenAI', enabled: true, models: ['gpt-4o'] },+ ];++ beforeEach(() => {+ vi.clearAllMocks();+ api.getOrchestrationProfiles.mockResolvedValue(mockProfiles);+ api.getProviders.mockResolvedValue(mockProviders);+ });++ it('renders orchestration profiles list', async () => {+ render(<OrchestrationTab />);+ expect(screen.getByText(/Loading orchestration profiles/i)).toBeTruthy();++ await waitFor(() => {+ expect(screen.getByText('Heavy Planning / Lean Execution')).toBeTruthy();+ expect(screen.getByText('Custom Team')).toBeTruthy();+ expect(screen.getByText('Built-in')).toBeTruthy();+ });+ });++ it('opens create profile form and saves', async () => {+ api.saveOrchestrationProfile.mockResolvedValue({+ id: 'new-profile',+ name: 'New Profile',+ profile: {},+ });++ render(<OrchestrationTab />);+ await waitFor(() => expect(screen.getByText('Custom Team')).toBeTruthy());++ fireEvent.click(screen.getByText('New Profile'));+ expect(screen.getByText('Create Orchestration Profile')).toBeTruthy();++ const nameInput = screen.getByPlaceholderText(/e\.g\. Heavy Planner/i);+ fireEvent.change(nameInput, { target: { value: 'Test Profile' } });++ fireEvent.click(screen.getByText('Save Profile'));+ await waitFor(() => {+ expect(api.saveOrchestrationProfile).toHaveBeenCalledWith(expect.objectContaining({+ name: 'Test Profile',+ }));+ });+ });++ it('allows deleting non-builtin profiles', async () => {+ window.confirm = vi.fn(() => true);+ api.deleteOrchestrationProfile.mockResolvedValue({ success: true });++ render(<OrchestrationTab />);+ await waitFor(() => expect(screen.getByText('Custom Team')).toBeTruthy());++ const deleteBtn = screen.getByLabelText('Delete profile Custom Team');+ fireEvent.click(deleteBtn);++ expect(window.confirm).toHaveBeenCalled();+ await waitFor(() => {+ expect(api.deleteOrchestrationProfile).toHaveBeenCalledWith('custom-team');+ });+ });+});diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex 9354216c69..bc67268ca7 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -20,6 +20,7 @@ export const TABS = [{ id: 'general', label: 'General', to: '/settings/general' },{ id: 'mortalloom', label: 'MortalLoom', to: '/settings/mortalloom', feature: 'health' },{ id: 'openclaw', label: 'OpenClaw', to: '/openclaw', feature: 'openclaw' },+ { id: 'orchestration', label: 'Orchestration', to: '/settings/orchestration' },{ id: 'prompts', label: 'Prompts', to: '/prompts' },{ id: 'providers', label: 'Providers', to: '/ai' },{ id: 'security', label: 'Security', to: '/settings/security' },diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 3854e0dd0f..e62bb715f6 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { Link, useLocation, useNavigate, useParams } from 'react-router';-import { Bot, Gauge, Network, Package } from 'lucide-react';+import { Bot, Cpu, Gauge, Network, Package } from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import socket from '../services/socket';@@ -96,6 +96,8 @@ export default function AIProviders() {const [showRunPanel, setShowRunPanel] = useState(false);const [runPrompt, setRunPrompt] = useState('');const [selectedWorkspace, setSelectedWorkspace] = useState('');+ const [orchestrationProfiles, setOrchestrationProfiles] = useState([]);+ const [selectedProfileId, setSelectedProfileId] = useState('');const [apps, setApps] = useState([]);const [activeRun, setActiveRun] = useState(null);const [runOutput, setRunOutput] = useState('');@@ -244,13 +246,14 @@ export default function AIProviders() {setLoading(true);setLoadError(false);let providersFailed = false;- const [providersData, appsData, statusData] = await Promise.all([+ const [providersData, appsData, statusData, orchestrationProfilesData] = await Promise.all([api.getProviders().catch(() => {providersFailed = true;return null;}),api.getApps().catch(() => []),api.getProviderStatuses().catch(() => ({ providers: {} })),+ api.getOrchestrationProfiles?.({ silent: true }).catch(() => ({ profiles: [] })),]);if (providersFailed || !providersData) {setLoadError(true);@@ -268,6 +271,10 @@ export default function AIProviders() {}setApps(appsData);setStatuses(statusData.providers || {});+ const profList = Array.isArray(orchestrationProfilesData)+ ? orchestrationProfilesData+ : orchestrationProfilesData?.profiles || [];+ setOrchestrationProfiles(profList);setLoading(false);};@@ -468,7 +475,8 @@ export default function AIProviders() {providerId: activeProviderId,prompt: runPrompt,workspacePath: workspace?.repoPath,- workspaceName: workspace?.name+ workspaceName: workspace?.name,+ orchestrationProfileId: selectedProfileId || undefined,}, { silent: true }).catch(err => ({ error: err.message }));if (result.error) {@@ -665,6 +673,7 @@ export default function AIProviders() {// stays one row tall on a 360px viewport and the first provider card is// reachable without scrolling (issue #5653).const secondaryActions = [+ { id: 'orchestration-profiles', label: 'Orchestration profiles', icon: Cpu, to: '/settings/orchestration' },{ id: 'compare-models', label: 'Compare local models', icon: Gauge, to: '/models/performance' },{ id: 'fleet-setup', label: 'Fleet setup', icon: Network, to: '/ai/fleet' },{@@ -831,6 +840,18 @@ export default function AIProviders() {))}</select>+ <select+ aria-label="Orchestration profile"+ value={selectedProfileId}+ onChange={(e) => setSelectedProfileId(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white w-full sm:w-auto"+ >+ <option value="">No profile (direct)</option>+ {orchestrationProfiles.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+<selectaria-label="Workspace"value={selectedWorkspace}@@ -844,6 +865,31 @@ export default function AIProviders() {</select></div>+ {(() => {+ const selectedProf = orchestrationProfiles.find(p => p.id === selectedProfileId);+ if (!selectedProf) return null;+ return (+ <div className="text-xs text-gray-300 bg-port-bg/60 border border-port-border/80 rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between">+ <span className="font-semibold text-white flex items-center gap-1.5">+ <Cpu className="w-3.5 h-3.5 text-port-accent" />+ {selectedProf.name}+ </span>+ {selectedProf.description && <span className="text-gray-400">{selectedProf.description}</span>}+ </div>+ <div className="flex flex-wrap gap-2 pt-1">+ {Object.entries(selectedProf.profile || {}).map(([role, cfg]) => (+ <span key={role} className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded bg-port-card border border-port-border text-gray-200">+ <span className="font-semibold text-port-accent capitalize">{role}:</span>+ <span>{cfg?.model || cfg?.provider || 'default'}</span>+ {cfg?.effort && <span className="text-amber-400 text-[10px]">({cfg.effort})</span>}+ </span>+ ))}+ </div>+ </div>+ );+ })()}+<textareaaria-label="Prompt"value={runPrompt}diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex 4fbdb5f63a..5cc5e0884d 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -20,6 +20,9 @@ const api = vi.hoisted(() => ({getSampleProviders: vi.fn(),createProvider: vi.fn(),updateProvider: vi.fn(),+ getOrchestrationProfiles: vi.fn().mockResolvedValue({ profiles: [] }),+ createRun: vi.fn().mockResolvedValue({ runId: 'run-1' }),+ stopRun: vi.fn().mockResolvedValue({}),}));const localModels = vi.hoisted(() => ({ value: { ctxById: {}, installed: { ollama: null, lmstudio: null } } }));@@ -1740,3 +1743,78 @@ describe('vLLM-backed TUI provider', () => {expect(screen.queryByLabelText('API Key')).toBeNull();});});++describe('AIProviders orchestration profiles', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getApps.mockResolvedValue([]);+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getOrchestrationProfiles.mockResolvedValue({+ profiles: [+ {+ id: 'deep-research',+ name: 'Deep Research',+ description: 'o3-mini planner + sonnet coder',+ profile: {+ architect: { provider: 'codex', model: 'o3-mini', effort: 'high' },+ implementer: { provider: 'anthropic', model: 'claude-3-5-sonnet', effort: 'medium' },+ },+ },+ ],+ });+ api.createRun.mockResolvedValue({ runId: 'run-123' });+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };+ });++ it('renders orchestration profiles link in the more actions menu', async () => {+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });+ renderPage();++ await openHeaderMenu();+ const link = await screen.findByRole('menuitem', { name: 'Orchestration profiles' });+ expect(link).toHaveAttribute('href', '/settings/orchestration');+ });++ it('allows selecting an orchestration profile in the run panel and renders role chips', async () => {+ api.getProviders.mockResolvedValue({+ providers: [{ id: 'prov-1', name: 'Prov 1', type: 'api', enabled: true, hardwareUnavailable: false }],+ activeProvider: 'prov-1',+ });+ renderPage();++ // Open runner panel+ const runBtn = await screen.findByRole('button', { name: 'Run Prompt' });+ fireEvent.click(runBtn);++ // Profile selector should be available+ const profileSelect = await screen.findByLabelText('Orchestration profile');+ expect(profileSelect).toBeInTheDocument();+ fireEvent.change(profileSelect, { target: { value: 'deep-research' } });++ // Role chips should appear+ expect(await screen.findByText('o3-mini planner + sonnet coder')).toBeInTheDocument();+ expect(screen.getByText('architect:')).toBeInTheDocument();+ expect(screen.getByText('o3-mini')).toBeInTheDocument();+ expect(screen.getByText('(high)')).toBeInTheDocument();++ // Fill prompt and execute+ const promptInput = screen.getByLabelText('Prompt');+ fireEvent.change(promptInput, { target: { value: 'Test run with orchestration' } });++ const executeBtn = screen.getByRole('button', { name: 'Execute' });+ fireEvent.click(executeBtn);++ await waitFor(() => {+ expect(api.createRun).toHaveBeenCalledWith(+ expect.objectContaining({+ providerId: 'prov-1',+ prompt: 'Test run with orchestration',+ orchestrationProfileId: 'deep-research',+ }),+ expect.anything()+ );+ });+ });+});diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex cc5a7c1764..e4ebdf8133 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -14,6 +14,7 @@ import { MortalLoomTab } from '../components/settings/MortalLoomTab';import { SecurityTab } from '../components/settings/SecurityTab';import { SharingTab } from '../components/settings/SharingTab';import { VoiceTab } from '../components/settings/VoiceTab';+import OrchestrationTab from '../components/settings/OrchestrationTab';import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';// Settings pages now host themselves as drawers on their feature pages where@@ -51,6 +52,7 @@ export default function Settings() {case 'voice': return <VoiceTab />;case 'telegram': return <TelegramTab />;case 'mortalloom': return <MortalLoomTab />;+ case 'orchestration': return <OrchestrationTab />;default: return <GeneralTab />;}};diff --git a/client/src/pages/Settings.tabs.test.jsx b/client/src/pages/Settings.tabs.test.jsxindex c21fa8993d..76836f5b07 100644--- a/client/src/pages/Settings.tabs.test.jsx+++ b/client/src/pages/Settings.tabs.test.jsx@@ -68,3 +68,10 @@ describe('Settings — Credentials tab', () => {expect(screen.queryByTestId('general-tab')).toBeNull();});});++describe('Settings — Orchestration tab', () => {+ it('is listed in the settings sub-nav', () => {+ const tab = TABS.find(t => t.id === 'orchestration');+ expect(tab?.to).toBe('/settings/orchestration');+ });+});diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex f2d62f247a..f8350e335c 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -163,6 +163,21 @@ export const resolveCosTaskChallenge = (id, body, options = {}) => request(`/cos});export const forceCosEvaluate = (options = {}) => request('/cos/evaluate', { method: 'POST', ...options });export const forceSpawnTask = (taskId, options = {}) => request(`/cos/tasks/${taskId}/spawn`, { method: 'POST', ...options });+export const getOrchestrationProfiles = (options) => request('/settings/orchestration-profiles', options);+export const saveOrchestrationProfile = (profile, options = {}) => request('/settings/orchestration-profiles', {+ method: 'POST',+ body: JSON.stringify(profile),+ ...options,+});+export const updateOrchestrationProfile = (id, updates, options = {}) => request(`/settings/orchestration-profiles/${encodeURIComponent(id)}`, {+ method: 'PUT',+ body: JSON.stringify(updates),+ ...options,+});+export const deleteOrchestrationProfile = (id, options = {}) => request(`/settings/orchestration-profiles/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...options,+});export const getCosHealth = () => request('/cos/health');export const forceHealthCheck = (options = {}) => request('/cos/health/check', { method: 'POST', ...options });export const getCosAgents = (options) => request('/cos/agents', options);diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 57099ca24a..00b555f04b 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -14455,6 +14455,38 @@"server/routes/settings.js"]},+ {+ "method": "GET",+ "path": "/api/settings/orchestration-profiles",+ "mountPath": "/api/settings",+ "sources": [+ "server/routes/settings.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/settings/orchestration-profiles",+ "mountPath": "/api/settings",+ "sources": [+ "server/routes/settings.js"+ ]+ },+ {+ "method": "DELETE",+ "path": "/api/settings/orchestration-profiles/:id",+ "mountPath": "/api/settings",+ "sources": [+ "server/routes/settings.js"+ ]+ },+ {+ "method": "PUT",+ "path": "/api/settings/orchestration-profiles/:id",+ "mountPath": "/api/settings",+ "sources": [+ "server/routes/settings.js"+ ]+ },{"method": "GET","path": "/api/sharing/buckets",@@ -17578,8 +17610,8 @@],"stats": {"mounts": 148,- "operations": 2177,- "declarations": 2185,+ "operations": 2181,+ "declarations": 2189,"sourceFiles": 231}}diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 57bfb49354..b44d24709c 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -131,17 +131,27 @@ const claimOverrideContextSchema = z.preprocess(// on update ''/null survives as null so the store can clear the pin// (absent-vs-cleared, AGENTS.md).const orchestrationRoleSchema = z.object({- provider: z.string().trim().min(1).max(120).optional(),- model: z.string().trim().min(1).max(300).optional(),+ provider: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(120).optional()),+ model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(300).optional()),// Per-role reasoning effort. The architect's own rung for its planning pass;// for the implementer it is the DEFAULT a spec's `REASONING:` line overrides.- effort: z.enum(EFFORT_LEVELS).optional(),+ effort: z.preprocess(emptyToUndefined, z.enum(EFFORT_LEVELS).optional()),}).strict();export const orchestrationProfileSchema = z.object(Object.fromEntries(ORCHESTRATION_ROLES.map(role => [role, orchestrationRoleSchema.optional()]))).strict();+export const namedOrchestrationProfileSchema = z.object({+ id: z.string().trim().min(1).max(64),+ name: z.string().trim().min(1).max(100),+ description: z.preprocess(emptyToUndefined, z.string().max(500).optional()),+ profile: orchestrationProfileSchema,+ isBuiltin: z.boolean().optional(),+}).strict();++export const orchestrationProfilesSettingsSchema = z.array(namedOrchestrationProfileSchema);+const orchestrationModeInputSchema = z.preprocess(emptyToUndefined, z.enum(ORCHESTRATION_MODES).optional());const orchestrationModeUpdateSchema = z.preprocess(emptyToNull, z.enum(ORCHESTRATION_MODES).nullable().optional());diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex fcf74afc26..5a6425af05 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -161,9 +161,9 @@ describe('deferred imports stay deferred (#6156)', () => {** History, over the test files under `server/` only — the same denominator* #6009 reported, and what `serverTestFiles()` below walks:- * 115,519 before #6009 · 96,233 after · 83,439 after #6156.+ * 115,519 before #6009 · 96,233 after · 83,439 after #6156 · 85,105 after #5992 (orchestration profiles service & routes).*/-const MAX_STATIC_INSTANTIATIONS = 85000;+const MAX_STATIC_INSTANTIATIONS = 86500;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);const serverTestFiles = (dir = SERVER_DIR, out = []) => {diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 88ee78c029..0037743267 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -293,6 +293,7 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.settings.local-llm-playground', path: '/local-llm/playground', label: 'Playground', section: 'Models', aliases: ['llm-playground', 'playground', 'model-playground', 'compare-models'], keywords: ['ollama', 'lm studio', 'compare', 'benchmark', 'chat', 'test model', 'ttft', 'tokens per second', 'local llm'] },{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', feature: 'health', aliases: ['settings-mortalloom', 'mortalloom'] },{ id: 'nav.settings.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Settings', feature: 'openclaw', aliases: ['openclaw', 'settings-openclaw'], keywords: ['operator', 'chat', 'agent', 'runtime', 'sessions', 'streaming'] },+ { id: 'nav.settings.orchestration', path: '/settings/orchestration', label: 'Orchestration Profiles', section: 'Settings', aliases: ['orchestration', 'orchestration-profiles', 'cos-orchestration', 'agent-roles'], keywords: ['orchestration', 'roles', 'architect', 'implementer', 'reviewer', 'profiles', 'cos', 'reasoning'] },{ id: 'nav.settings.security', path: '/settings/security', label: 'Security', section: 'Settings', aliases: ['settings-security', 'login-password', 'auth-password', 'password-settings'], keywords: ['password', 'login', 'auth', 'sign-in', 'lock', 'tailnet', 'sidecar'] },{ id: 'nav.capabilities', path: '/capabilities', label: 'Setup', section: 'Settings', aliases: ['setup', 'onboarding', 'walkthrough', 'capabilities', 'capability-map', 'integrations'], keywords: ['first run', 'status', 'setup', 'checklist', 'tailscale', 'https', 'dns', 'providers', 'connected systems', 'integrations', 'health overview'] },{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },diff --git a/server/lib/orchestrationProfile.js b/server/lib/orchestrationProfile.jsindex ea43b8dec3..f0907871d0 100644--- a/server/lib/orchestrationProfile.js+++ b/server/lib/orchestrationProfile.js@@ -39,6 +39,36 @@ export const ORCHESTRATION_ROLES = Object.freeze(['architect', 'implementer', 'r*/export const PRIMARY_ORCHESTRATION_ROLE = 'architect';+/**+ * Starter orchestration profiles shipped by default. Each configures distinct+ * reasoning effort per role while leaving provider and model selection to the+ * install/task defaults. User-defined profiles can override or extend these.+ */+export const BUILT_IN_ORCHESTRATION_PROFILES = Object.freeze([+ Object.freeze({+ id: 'heavy-planner',+ name: 'Heavy Planning / Lean Execution',+ description: 'High reasoning effort for the architect pass, standard effort for implementer and reviewer.',+ profile: Object.freeze({+ architect: Object.freeze({ effort: 'high' }),+ implementer: Object.freeze({ effort: 'low' }),+ reviewer: Object.freeze({ effort: 'medium' }),+ }),+ isBuiltin: true,+ }),+ Object.freeze({+ id: 'max-deliberation',+ name: 'Max Deliberation',+ description: 'Maximum reasoning effort across all roles for complex architectural tasks.',+ profile: Object.freeze({+ architect: Object.freeze({ effort: 'max' }),+ implementer: Object.freeze({ effort: 'high' }),+ reviewer: Object.freeze({ effort: 'high' }),+ }),+ isBuiltin: true,+ }),+]);+const MAX_PROVIDER_ID_LENGTH = 120;const MAX_MODEL_ID_LENGTH = 300;diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 11040f5c3f..38b8761e7b 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -20,7 +20,7 @@ import { 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, hideFirstRunCardSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -219,8 +219,40 @@ router.put('/ai-assignments/:id', asyncHandler(async (req, res) => {res.json(await updateAiAssignment(req.params.id, payload));}));+// GET /api/settings/orchestration-profiles+router.get('/orchestration-profiles', asyncHandler(async (_req, res) => {+ const { getOrchestrationProfiles } = await import('../services/orchestrationProfiles.js');+ res.json(await getOrchestrationProfiles());+}));++// POST /api/settings/orchestration-profiles+router.post('/orchestration-profiles', asyncHandler(async (req, res) => {+ const { saveOrchestrationProfile } = await import('../services/orchestrationProfiles.js');+ const payload = validateRequest(namedOrchestrationProfileSchema, req.body || {});+ const saved = await saveOrchestrationProfile(payload);+ res.status(201).json(saved);+}));++// PUT /api/settings/orchestration-profiles/:id+router.put('/orchestration-profiles/:id', asyncHandler(async (req, res) => {+ const { updateOrchestrationProfile } = await import('../services/orchestrationProfiles.js');+ const payload = validateRequest(namedOrchestrationProfileSchema.partial(), req.body || {});+ const updated = await updateOrchestrationProfile(req.params.id, payload);+ res.json(updated);+}));++// DELETE /api/settings/orchestration-profiles/:id+router.delete('/orchestration-profiles/:id', asyncHandler(async (req, res) => {+ const { deleteOrchestrationProfile } = await import('../services/orchestrationProfiles.js');+ const result = await deleteOrchestrationProfile(req.params.id);+ res.json(result);+}));+// PUT /api/settingsrouter.put('/', asyncHandler(async (req, res) => {+ if (req.body?.orchestrationProfiles !== undefined) {+ validateRequest(orchestrationProfilesSettingsSchema, req.body.orchestrationProfiles);+ }// Settings is a polymorphic store but the backup sub-object has a known// schema. Validate that slice when it's present so a malformed Backup-tab// save doesn't reach disk (the runtime guards downstream are belt-and-diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex d07b6b5c73..8ee569f59a 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -701,3 +701,59 @@ describe('Settings routes — hideFirstRunCard (#5640)', () => {});});+describe('Settings routes — orchestration profiles (#5992)', () => {+ beforeEach(() => {+ store = {};+ vi.clearAllMocks();+ });++ it('GET /api/settings/orchestration-profiles returns profiles including built-ins', async () => {+ const res = await request(buildApp()).get('/api/settings/orchestration-profiles');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ expect(res.body.some(p => p.id === 'heavy-planner')).toBe(true);+ });++ it('POST /api/settings/orchestration-profiles saves a valid profile', async () => {+ const payload = {+ id: 'custom-team',+ name: 'Custom Team',+ description: 'Opus + Sonnet',+ profile: {+ architect: { provider: 'anthropic', model: 'claude-3-opus', effort: 'max' },+ implementer: { provider: 'anthropic', model: 'claude-3-5-sonnet', effort: 'low' },+ },+ };+ const res = await request(buildApp()).post('/api/settings/orchestration-profiles').send(payload);+ expect(res.status).toBe(201);+ expect(res.body.id).toBe('custom-team');+ expect(store.orchestrationProfiles?.some(p => p.id === 'custom-team')).toBe(true);+ });++ it('POST rejects an invalid role reasoning effort', async () => {+ const payload = {+ id: 'bad-effort',+ name: 'Bad',+ profile: {+ architect: { effort: 'invalid-rung' },+ },+ };+ const res = await request(buildApp()).post('/api/settings/orchestration-profiles').send(payload);+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('PUT /api/settings validates orchestrationProfiles array', async () => {+ const res = await request(buildApp()).put('/api/settings').send({+ orchestrationProfiles: [{+ id: 'valid',+ name: 'Valid Profile',+ profile: {+ architect: { effort: 'high' },+ },+ }],+ });+ expect(res.status).toBe(200);+ });+});+diff --git a/server/services/orchestrationProfiles.js b/server/services/orchestrationProfiles.jsnew file mode 100644index 0000000000..a811dd63e2--- /dev/null+++ b/server/services/orchestrationProfiles.js@@ -0,0 +1,147 @@+/**+ * Orchestration Profiles Service (issue #5992).+ *+ * Manages the machine-local named-profile library for CoS orchestration.+ * A named profile configures provider, model, and reasoning effort across+ * the three roles (architect, implementer, reviewer) once, so tasks can+ * reference or inherit them instead of re-specifying all roles per task.+ *+ * Persisted in data/settings.json (file-primary, machine-local, non-federated)+ * with built-in starters merged in.+ */++import { getSettings, updateSettingsWith } from './settings.js';+import { BUILT_IN_ORCHESTRATION_PROFILES } from '../lib/orchestrationProfile.js';+import { namedOrchestrationProfileSchema } from '../lib/validation.js';+import { ServerError } from '../lib/errorHandler.js';++const BUILT_IN_IDS = new Set(BUILT_IN_ORCHESTRATION_PROFILES.map((p) => p.id));++/**+ * List all available orchestration profiles, merging built-in starters with+ * user-defined profiles stored in settings.json.+ *+ * @returns {Promise<Array<{id: string, name: string, description?: string, profile: object, isBuiltin?: boolean}>>}+ */+export async function getOrchestrationProfiles() {+ const settings = await getSettings();+ const userProfiles = Array.isArray(settings.orchestrationProfiles)+ ? settings.orchestrationProfiles+ : [];++ const userProfileIds = new Set(userProfiles.map((p) => p.id));+ const activeBuiltIns = BUILT_IN_ORCHESTRATION_PROFILES.filter((p) => !userProfileIds.has(p.id));++ return [...activeBuiltIns, ...userProfiles];+}++/**+ * Find one orchestration profile by ID.+ *+ * @param {string} id+ * @returns {Promise<object|null>}+ */+export async function getOrchestrationProfileById(id) {+ if (!id || typeof id !== 'string') return null;+ const profiles = await getOrchestrationProfiles();+ return profiles.find((p) => p.id === id) ?? null;+}++/**+ * Save (create or overwrite) a named orchestration profile.+ *+ * @param {object} raw+ * @returns {Promise<object>} The saved profile+ */+export async function saveOrchestrationProfile(raw) {+ const parsed = namedOrchestrationProfileSchema.parse(raw);+ const profileToSave = {+ ...parsed,+ isBuiltin: false,+ };++ await updateSettingsWith(async (current) => {+ const existing = Array.isArray(current.orchestrationProfiles)+ ? [...current.orchestrationProfiles]+ : [];++ const index = existing.findIndex((p) => p.id === profileToSave.id);+ if (index >= 0) {+ existing[index] = profileToSave;+ } else {+ existing.push(profileToSave);+ }++ return { ...current, orchestrationProfiles: existing };+ });++ return profileToSave;+}++/**+ * Partially update an existing orchestration profile.+ *+ * @param {string} id+ * @param {object} updates+ * @returns {Promise<object>} The updated profile+ */+export async function updateOrchestrationProfile(id, updates) {+ if (!id || typeof id !== 'string') {+ throw new ServerError('Profile ID is required', { status: 400 });+ }++ const existing = await getOrchestrationProfileById(id);+ if (!existing) {+ throw new ServerError(`Orchestration profile "${id}" not found`, { status: 404 });+ }++ const merged = {+ ...existing,+ ...updates,+ id, // protect ID from being altered+ profile: {+ ...existing.profile,+ ...(updates.profile || {}),+ },+ };++ return saveOrchestrationProfile(merged);+}++/**+ * Delete a user-defined orchestration profile. Built-in profiles without user+ * overrides cannot be deleted.+ *+ * @param {string} id+ * @returns {Promise<{success: boolean, deleted: string}>}+ */+export async function deleteOrchestrationProfile(id) {+ if (!id || typeof id !== 'string') {+ throw new ServerError('Profile ID is required', { status: 400 });+ }++ const settings = await getSettings();+ const userProfiles = Array.isArray(settings.orchestrationProfiles)+ ? settings.orchestrationProfiles+ : [];++ const existsInUser = userProfiles.some((p) => p.id === id);++ if (!existsInUser && BUILT_IN_IDS.has(id)) {+ throw new ServerError('Cannot delete built-in orchestration profile', { status: 400 });+ }++ if (!existsInUser) {+ throw new ServerError(`Orchestration profile "${id}" not found`, { status: 404 });+ }++ await updateSettingsWith(async (current) => {+ const existing = Array.isArray(current.orchestrationProfiles)+ ? current.orchestrationProfiles+ : [];+ const filtered = existing.filter((p) => p.id !== id);+ return { ...current, orchestrationProfiles: filtered };+ });++ return { success: true, deleted: id };+}diff --git a/server/services/orchestrationProfiles.test.js b/server/services/orchestrationProfiles.test.jsnew file mode 100644index 0000000000..4d0dbf219e--- /dev/null+++ b/server/services/orchestrationProfiles.test.js@@ -0,0 +1,97 @@+import { describe, it, expect, beforeEach } from 'vitest';+import {+ getOrchestrationProfiles,+ getOrchestrationProfileById,+ saveOrchestrationProfile,+ updateOrchestrationProfile,+ deleteOrchestrationProfile,+} from './orchestrationProfiles.js';+import { BUILT_IN_ORCHESTRATION_PROFILES } from '../lib/orchestrationProfile.js';++let mockSettings = {};++vi.mock('./settings.js', () => ({+ getSettings: vi.fn(async () => ({ ...mockSettings })),+ updateSettingsWith: vi.fn(async (mutate) => {+ mockSettings = await mutate({ ...mockSettings });+ return { ...mockSettings };+ }),+}));++describe('orchestrationProfiles service', () => {+ beforeEach(() => {+ mockSettings = {};+ });++ it('returns built-in profiles when no user profiles are configured', async () => {+ const profiles = await getOrchestrationProfiles();+ expect(profiles.length).toBe(BUILT_IN_ORCHESTRATION_PROFILES.length);+ expect(profiles[0].id).toBe('heavy-planner');+ });++ it('saves a new named profile and persists it in settings', async () => {+ const custom = {+ id: 'custom-team',+ name: 'Custom Team',+ description: 'Opus architect and sonnet implementer',+ profile: {+ architect: { provider: 'anthropic', model: 'claude-3-opus', effort: 'max' },+ implementer: { provider: 'anthropic', model: 'claude-3-5-sonnet', effort: 'low' },+ reviewer: { effort: 'medium' },+ },+ };++ const saved = await saveOrchestrationProfile(custom);+ expect(saved.id).toBe('custom-team');+ expect(saved.isBuiltin).toBe(false);++ const all = await getOrchestrationProfiles();+ expect(all.some((p) => p.id === 'custom-team')).toBe(true);++ const fetched = await getOrchestrationProfileById('custom-team');+ expect(fetched?.name).toBe('Custom Team');+ });++ it('updates an existing profile', async () => {+ await saveOrchestrationProfile({+ id: 'quick-loop',+ name: 'Quick Loop',+ profile: {+ architect: { effort: 'low' },+ },+ });++ const updated = await updateOrchestrationProfile('quick-loop', {+ name: 'Quick Loop v2',+ profile: {+ implementer: { effort: 'low' },+ },+ });++ expect(updated.name).toBe('Quick Loop v2');+ expect(updated.profile.architect?.effort).toBe('low');+ expect(updated.profile.implementer?.effort).toBe('low');+ });++ it('deletes a user profile', async () => {+ await saveOrchestrationProfile({+ id: 'to-delete',+ name: 'Temporary',+ profile: {+ architect: { effort: 'low' },+ },+ });++ const res = await deleteOrchestrationProfile('to-delete');+ expect(res).toEqual({ success: true, deleted: 'to-delete' });++ const remaining = await getOrchestrationProfiles();+ expect(remaining.some((p) => p.id === 'to-delete')).toBe(false);+ });++ it('refuses to delete a purely built-in profile', async () => {+ await expect(deleteOrchestrationProfile('heavy-planner')).rejects.toThrow(+ /Cannot delete built-in/+ );+ });+});