Spaces:
Paused
Paused
File size: 35,608 Bytes
fb867c3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 | /**
* Felix Framework - Interactive Parameter Controls
*
* Type-safe parameter controls for Felix Framework configuration with
* real-time validation, constraint enforcement, and mobile-optimized
* input handling for helix geometry, agent configuration, and system settings.
*
* Features:
* - Type-safe parameter validation
* - Real-time constraint checking
* - Dependency resolution between parameters
* - Mobile-optimized input controls
* - Undo/redo functionality
* - Parameter presets and templates
* - Export/import configurations
* - Performance impact prediction
*
* @version 1.0.0
* @author Felix Framework Team
*/
import {
GradioSlider,
GradioTextbox,
GradioCheckboxGroup,
GradioDropdown,
GradioCheckbox,
ValidationResult,
ValidationError,
ValidationWarning
} from '../types/gradio-interface';
import {
HelixGeometry,
AgentConfig,
AgentType,
TaskRequirements,
PerformanceMetrics,
Radius,
Turns,
Height,
HelixParameter
} from '../types/felix-core';
// =============================================================================
// Parameter Control Types
// =============================================================================
/** Parameter control configuration */
export interface ParameterControlConfig {
readonly id: string;
readonly label: string;
readonly description?: string;
readonly type: ParameterType;
readonly constraints: ParameterConstraints;
readonly defaultValue: unknown;
readonly dependencies?: readonly string[];
readonly mobileOptimized?: boolean;
readonly performanceImpact?: PerformanceImpact;
}
/** Parameter types */
export enum ParameterType {
Number = 'number',
Integer = 'integer',
Float = 'float',
Boolean = 'boolean',
String = 'string',
Enum = 'enum',
Range = 'range',
MultiSelect = 'multi_select'
}
/** Parameter constraints */
export interface ParameterConstraints {
readonly min?: number;
readonly max?: number;
readonly step?: number;
readonly precision?: number;
readonly options?: readonly string[];
readonly pattern?: RegExp;
readonly required?: boolean;
readonly customValidator?: (value: unknown) => ValidationResult;
}
/** Performance impact levels */
export enum PerformanceImpact {
None = 'none',
Low = 'low',
Medium = 'medium',
High = 'high',
Critical = 'critical'
}
// =============================================================================
// Helix Geometry Parameter Controls
// =============================================================================
/** Helix geometry parameter configuration */
export interface HelixGeometryParams {
readonly topRadius: number;
readonly bottomRadius: number;
readonly height: number;
readonly turns: number;
readonly resolution: number;
readonly mathematicalPrecision: number;
}
/** Helix parameter control definitions */
export const HELIX_PARAMETER_CONTROLS: Record<keyof HelixGeometryParams, ParameterControlConfig> = {
topRadius: {
id: 'helix_top_radius',
label: 'Top Radius',
description: 'Radius at the top of the helix (broad exploration phase)',
type: ParameterType.Float,
constraints: {
min: 0.1,
max: 100.0,
step: 0.1,
precision: 3,
required: true,
customValidator: (value) => validateRadius(value as number, 'top')
},
defaultValue: 33.0,
dependencies: ['bottomRadius'],
performanceImpact: PerformanceImpact.Medium
},
bottomRadius: {
id: 'helix_bottom_radius',
label: 'Bottom Radius',
description: 'Radius at the bottom of the helix (focused synthesis phase)',
type: ParameterType.Float,
constraints: {
min: 0.001,
max: 10.0,
step: 0.001,
precision: 6,
required: true,
customValidator: (value) => validateRadius(value as number, 'bottom')
},
defaultValue: 0.001,
dependencies: ['topRadius'],
performanceImpact: PerformanceImpact.Low
},
height: {
id: 'helix_height',
label: 'Helix Height',
description: 'Total height of the helix structure',
type: ParameterType.Float,
constraints: {
min: 10.0,
max: 1000.0,
step: 1.0,
precision: 1,
required: true
},
defaultValue: 100.0,
performanceImpact: PerformanceImpact.Low
},
turns: {
id: 'helix_turns',
label: 'Number of Turns',
description: 'Complete rotations in the helix (affects agent path complexity)',
type: ParameterType.Integer,
constraints: {
min: 1,
max: 100,
step: 1,
required: true,
customValidator: validateTurns
},
defaultValue: 33,
dependencies: ['resolution'],
performanceImpact: PerformanceImpact.High
},
resolution: {
id: 'helix_resolution',
label: 'Visualization Resolution',
description: 'Number of points used for helix visualization (affects rendering performance)',
type: ParameterType.Integer,
constraints: {
min: 50,
max: 2000,
step: 50,
required: true
},
defaultValue: 500,
mobileOptimized: true,
performanceImpact: PerformanceImpact.Critical
},
mathematicalPrecision: {
id: 'helix_precision',
label: 'Mathematical Precision',
description: 'Precision threshold for mathematical calculations (scientific notation)',
type: ParameterType.Float,
constraints: {
min: 1e-15,
max: 1e-6,
step: 1e-15,
precision: 15
},
defaultValue: 1e-12,
performanceImpact: PerformanceImpact.None
}
};
// =============================================================================
// Agent Configuration Parameter Controls
// =============================================================================
/** Agent configuration parameters */
export interface AgentConfigParams {
readonly maxAgents: number;
readonly spawnInterval: number;
readonly agentTypes: readonly AgentType[];
readonly temperatureSettings: Record<AgentType, number>;
readonly lifetimeSettings: Record<AgentType, number>;
readonly enableAdaptiveSpawning: boolean;
readonly enableLoadBalancing: boolean;
}
/** Agent parameter control definitions */
export const AGENT_PARAMETER_CONTROLS: Record<string, ParameterControlConfig> = {
maxAgents: {
id: 'agent_max_count',
label: 'Maximum Agents',
description: 'Maximum number of concurrent agents (affects memory usage)',
type: ParameterType.Integer,
constraints: {
min: 1,
max: 100,
step: 1,
required: true,
customValidator: validateMaxAgents
},
defaultValue: 20,
performanceImpact: PerformanceImpact.Critical
},
spawnInterval: {
id: 'agent_spawn_interval',
label: 'Spawn Interval (ms)',
description: 'Time between agent spawns in milliseconds',
type: ParameterType.Integer,
constraints: {
min: 100,
max: 10000,
step: 100,
required: true
},
defaultValue: 1000,
performanceImpact: PerformanceImpact.Medium
},
agentTypes: {
id: 'agent_types_enabled',
label: 'Enabled Agent Types',
description: 'Select which agent types are available for spawning',
type: ParameterType.MultiSelect,
constraints: {
options: Object.values(AgentType),
required: true,
customValidator: validateAgentTypes
},
defaultValue: [AgentType.Research, AgentType.Analysis, AgentType.Synthesis],
performanceImpact: PerformanceImpact.Medium
},
enableAdaptiveSpawning: {
id: 'agent_adaptive_spawning',
label: 'Adaptive Spawning',
description: 'Automatically adjust agent spawning based on task complexity',
type: ParameterType.Boolean,
constraints: {
required: false
},
defaultValue: true,
performanceImpact: PerformanceImpact.Low
},
enableLoadBalancing: {
id: 'agent_load_balancing',
label: 'Load Balancing',
description: 'Distribute tasks evenly across available agents',
type: ParameterType.Boolean,
constraints: {
required: false
},
defaultValue: true,
performanceImpact: PerformanceImpact.Low
}
};
// =============================================================================
// System Performance Parameter Controls
// =============================================================================
/** System performance parameters */
export interface SystemPerformanceParams {
readonly updateInterval: number;
readonly renderingMode: RenderingMode;
readonly memoryLimit: number;
readonly enableGPU: boolean;
readonly compressionLevel: number;
readonly cacheSize: number;
readonly logLevel: LogLevel;
}
/** Rendering modes */
export enum RenderingMode {
Quality = 'quality',
Balanced = 'balanced',
Performance = 'performance',
Mobile = 'mobile'
}
/** Log levels */
export enum LogLevel {
Debug = 'debug',
Info = 'info',
Warning = 'warning',
Error = 'error'
}
/** System parameter control definitions */
export const SYSTEM_PARAMETER_CONTROLS: Record<string, ParameterControlConfig> = {
updateInterval: {
id: 'system_update_interval',
label: 'Update Interval (ms)',
description: 'How often the system updates visualization and metrics',
type: ParameterType.Integer,
constraints: {
min: 16,
max: 5000,
step: 16,
required: true
},
defaultValue: 500,
mobileOptimized: true,
performanceImpact: PerformanceImpact.High
},
renderingMode: {
id: 'system_rendering_mode',
label: 'Rendering Mode',
description: 'Balance between visual quality and performance',
type: ParameterType.Enum,
constraints: {
options: Object.values(RenderingMode),
required: true
},
defaultValue: RenderingMode.Balanced,
mobileOptimized: true,
performanceImpact: PerformanceImpact.Critical
},
memoryLimit: {
id: 'system_memory_limit',
label: 'Memory Limit (MB)',
description: 'Maximum memory usage for the application',
type: ParameterType.Integer,
constraints: {
min: 100,
max: 8000,
step: 100,
required: true
},
defaultValue: 1000,
performanceImpact: PerformanceImpact.High
},
enableGPU: {
id: 'system_enable_gpu',
label: 'GPU Acceleration',
description: 'Use GPU for compute-intensive operations when available',
type: ParameterType.Boolean,
constraints: {
required: false,
customValidator: validateGPUAvailability
},
defaultValue: true,
performanceImpact: PerformanceImpact.Critical
},
compressionLevel: {
id: 'system_compression_level',
label: 'Data Compression',
description: 'Level of compression for data transfer (0=none, 9=maximum)',
type: ParameterType.Integer,
constraints: {
min: 0,
max: 9,
step: 1,
required: true
},
defaultValue: 3,
performanceImpact: PerformanceImpact.Medium
},
cacheSize: {
id: 'system_cache_size',
label: 'Cache Size (MB)',
description: 'Size of rendering and data cache',
type: ParameterType.Integer,
constraints: {
min: 10,
max: 500,
step: 10,
required: true
},
defaultValue: 100,
performanceImpact: PerformanceImpact.Medium
},
logLevel: {
id: 'system_log_level',
label: 'Log Level',
description: 'Minimum level for system logging',
type: ParameterType.Enum,
constraints: {
options: Object.values(LogLevel),
required: true
},
defaultValue: LogLevel.Info,
performanceImpact: PerformanceImpact.Low
}
};
// =============================================================================
// Parameter Control Manager
// =============================================================================
export class ParameterControlManager {
private currentValues: Map<string, unknown> = new Map();
private parameterHistory: ParameterHistoryEntry[] = [];
private validationResults: Map<string, ValidationResult> = new Map();
private dependencyGraph: Map<string, Set<string>> = new Map();
private changeListeners: Map<string, Set<ParameterChangeListener>> = new Map();
constructor(private readonly isMobile: boolean = false) {
this.initializeParameters();
this.buildDependencyGraph();
}
// =============================================================================
// Parameter Management
// =============================================================================
/**
* Initialize parameters with default values
*/
private initializeParameters(): void {
const allControls = {
...HELIX_PARAMETER_CONTROLS,
...AGENT_PARAMETER_CONTROLS,
...SYSTEM_PARAMETER_CONTROLS
};
Object.values(allControls).forEach(control => {
let defaultValue = control.defaultValue;
// Apply mobile optimizations
if (this.isMobile && control.mobileOptimized) {
defaultValue = this.getMobileOptimizedValue(control);
}
this.currentValues.set(control.id, defaultValue);
});
}
/**
* Get mobile-optimized parameter values
*/
private getMobileOptimizedValue(control: ParameterControlConfig): unknown {
switch (control.id) {
case 'helix_resolution':
return Math.min(control.defaultValue as number, 200);
case 'system_update_interval':
return Math.max(control.defaultValue as number, 1000);
case 'system_rendering_mode':
return RenderingMode.Mobile;
default:
return control.defaultValue;
}
}
/**
* Build dependency graph for parameter relationships
*/
private buildDependencyGraph(): void {
const allControls = {
...HELIX_PARAMETER_CONTROLS,
...AGENT_PARAMETER_CONTROLS,
...SYSTEM_PARAMETER_CONTROLS
};
Object.values(allControls).forEach(control => {
if (control.dependencies) {
control.dependencies.forEach(depId => {
if (!this.dependencyGraph.has(depId)) {
this.dependencyGraph.set(depId, new Set());
}
this.dependencyGraph.get(depId)!.add(control.id);
});
}
});
}
/**
* Set parameter value with validation and dependency checking
*/
public setParameter(parameterId: string, value: unknown): ValidationResult {
const control = this.getParameterControl(parameterId);
if (!control) {
return {
valid: false,
errors: [{ field: parameterId, message: 'Parameter not found', code: 'NOT_FOUND' }],
warnings: []
};
}
// Validate the value
const validationResult = this.validateParameter(control, value);
if (!validationResult.valid) {
this.validationResults.set(parameterId, validationResult);
return validationResult;
}
// Store previous value for history
const previousValue = this.currentValues.get(parameterId);
// Update value
this.currentValues.set(parameterId, value);
this.validationResults.set(parameterId, validationResult);
// Add to history
this.addToHistory(parameterId, previousValue, value);
// Validate dependent parameters
this.validateDependencies(parameterId);
// Notify listeners
this.notifyChangeListeners(parameterId, value, previousValue);
return validationResult;
}
/**
* Get parameter value
*/
public getParameter<T>(parameterId: string): T | undefined {
return this.currentValues.get(parameterId) as T;
}
/**
* Get all parameter values
*/
public getAllParameters(): Record<string, unknown> {
const result: Record<string, unknown> = {};
this.currentValues.forEach((value, key) => {
result[key] = value;
});
return result;
}
/**
* Reset parameters to defaults
*/
public resetToDefaults(): void {
this.currentValues.clear();
this.validationResults.clear();
this.parameterHistory.length = 0;
this.initializeParameters();
}
// =============================================================================
// Validation
// =============================================================================
/**
* Validate a parameter value
*/
private validateParameter(control: ParameterControlConfig, value: unknown): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
// Type validation
if (!this.validateType(control.type, value)) {
errors.push({
field: control.id,
message: `Invalid type. Expected ${control.type}`,
code: 'INVALID_TYPE'
});
return { valid: false, errors, warnings };
}
// Constraint validation
const constraintResult = this.validateConstraints(control.constraints, value);
errors.push(...constraintResult.errors);
warnings.push(...constraintResult.warnings);
// Custom validation
if (control.constraints.customValidator) {
const customResult = control.constraints.customValidator(value);
errors.push(...customResult.errors);
warnings.push(...customResult.warnings);
}
// Performance impact warning
if (control.performanceImpact === PerformanceImpact.Critical) {
warnings.push({
field: control.id,
message: 'This parameter has critical performance impact',
suggestion: 'Consider the effect on system performance'
});
}
return {
valid: errors.length === 0,
errors,
warnings
};
}
/**
* Validate parameter type
*/
private validateType(expectedType: ParameterType, value: unknown): boolean {
switch (expectedType) {
case ParameterType.Number:
case ParameterType.Float:
case ParameterType.Integer:
return typeof value === 'number' && !isNaN(value);
case ParameterType.Boolean:
return typeof value === 'boolean';
case ParameterType.String:
return typeof value === 'string';
case ParameterType.Enum:
return typeof value === 'string';
case ParameterType.MultiSelect:
return Array.isArray(value);
case ParameterType.Range:
return Array.isArray(value) && value.length === 2 &&
typeof value[0] === 'number' && typeof value[1] === 'number';
default:
return false;
}
}
/**
* Validate parameter constraints
*/
private validateConstraints(constraints: ParameterConstraints, value: unknown): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
// Required validation
if (constraints.required && (value === null || value === undefined || value === '')) {
errors.push({
field: 'value',
message: 'This parameter is required',
code: 'REQUIRED'
});
}
// Numeric constraints
if (typeof value === 'number') {
if (constraints.min !== undefined && value < constraints.min) {
errors.push({
field: 'value',
message: `Value must be at least ${constraints.min}`,
code: 'MIN_VALUE'
});
}
if (constraints.max !== undefined && value > constraints.max) {
errors.push({
field: 'value',
message: `Value must be at most ${constraints.max}`,
code: 'MAX_VALUE'
});
}
if (constraints.step !== undefined) {
const remainder = (value - (constraints.min || 0)) % constraints.step;
if (Math.abs(remainder) > 1e-10) {
errors.push({
field: 'value',
message: `Value must be a multiple of ${constraints.step}`,
code: 'STEP_VALUE'
});
}
}
}
// Options validation
if (constraints.options && typeof value === 'string') {
if (!constraints.options.includes(value)) {
errors.push({
field: 'value',
message: `Value must be one of: ${constraints.options.join(', ')}`,
code: 'INVALID_OPTION'
});
}
}
// Pattern validation
if (constraints.pattern && typeof value === 'string') {
if (!constraints.pattern.test(value)) {
errors.push({
field: 'value',
message: 'Value does not match required pattern',
code: 'PATTERN_MISMATCH'
});
}
}
return { valid: errors.length === 0, errors, warnings };
}
/**
* Validate dependent parameters when a parameter changes
*/
private validateDependencies(changedParameterId: string): void {
const dependents = this.dependencyGraph.get(changedParameterId);
if (!dependents) return;
dependents.forEach(dependentId => {
const control = this.getParameterControl(dependentId);
const value = this.currentValues.get(dependentId);
if (control && value !== undefined) {
const result = this.validateParameter(control, value);
this.validationResults.set(dependentId, result);
}
});
}
// =============================================================================
// Gradio Integration
// =============================================================================
/**
* Create Gradio slider component
*/
public createGradioSlider(parameterId: string): GradioSlider {
const control = this.getParameterControl(parameterId);
if (!control) throw new Error(`Parameter ${parameterId} not found`);
const value = this.getParameter<number>(parameterId) || 0;
const validation = this.validationResults.get(parameterId);
return {
value,
label: control.label,
info: control.description,
visible: true,
interactive: true,
minimum: control.constraints.min || 0,
maximum: control.constraints.max || 100,
step: control.constraints.step || 1,
// Additional Gradio-specific properties would be added here
};
}
/**
* Create Gradio textbox component
*/
public createGradioTextbox(parameterId: string): GradioTextbox {
const control = this.getParameterControl(parameterId);
if (!control) throw new Error(`Parameter ${parameterId} not found`);
const value = this.getParameter<string>(parameterId) || '';
return {
value,
label: control.label,
info: control.description,
visible: true,
interactive: true,
placeholder: `Enter ${control.label.toLowerCase()}...`,
type: control.type === ParameterType.String ? 'text' : 'text'
};
}
/**
* Create Gradio checkbox group component
*/
public createGradioCheckboxGroup(parameterId: string): GradioCheckboxGroup {
const control = this.getParameterControl(parameterId);
if (!control) throw new Error(`Parameter ${parameterId} not found`);
const value = this.getParameter<readonly string[]>(parameterId) || [];
return {
value,
label: control.label,
info: control.description,
visible: true,
interactive: true,
choices: control.constraints.options || []
};
}
/**
* Create Gradio dropdown component
*/
public createGradioDropdown(parameterId: string): GradioDropdown {
const control = this.getParameterControl(parameterId);
if (!control) throw new Error(`Parameter ${parameterId} not found`);
const value = this.getParameter<string>(parameterId) || '';
return {
value,
label: control.label,
info: control.description,
visible: true,
interactive: true,
choices: control.constraints.options || []
};
}
// =============================================================================
// Presets and Templates
// =============================================================================
/**
* Create parameter preset
*/
public createPreset(name: string, description: string): ParameterPreset {
return {
id: `preset_${Date.now()}`,
name,
description,
parameters: this.getAllParameters(),
createdAt: Date.now(),
version: '1.0.0'
};
}
/**
* Apply parameter preset
*/
public applyPreset(preset: ParameterPreset): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
Object.entries(preset.parameters).forEach(([parameterId, value]) => {
const result = this.setParameter(parameterId, value);
errors.push(...result.errors);
warnings.push(...result.warnings);
});
return { valid: errors.length === 0, errors, warnings };
}
/**
* Get built-in presets
*/
public getBuiltInPresets(): ParameterPreset[] {
return [
{
id: 'performance_optimized',
name: 'Performance Optimized',
description: 'Settings optimized for maximum performance',
parameters: {
'helix_resolution': 200,
'system_rendering_mode': RenderingMode.Performance,
'system_update_interval': 1000,
'agent_max_count': 10
},
createdAt: Date.now(),
version: '1.0.0'
},
{
id: 'quality_focused',
name: 'Quality Focused',
description: 'Settings optimized for visual quality',
parameters: {
'helix_resolution': 1000,
'system_rendering_mode': RenderingMode.Quality,
'system_update_interval': 250,
'agent_max_count': 20
},
createdAt: Date.now(),
version: '1.0.0'
},
{
id: 'mobile_optimized',
name: 'Mobile Optimized',
description: 'Settings optimized for mobile devices',
parameters: {
'helix_resolution': 150,
'system_rendering_mode': RenderingMode.Mobile,
'system_update_interval': 2000,
'agent_max_count': 5,
'system_compression_level': 6
},
createdAt: Date.now(),
version: '1.0.0'
}
];
}
// =============================================================================
// History and Undo/Redo
// =============================================================================
/**
* Add parameter change to history
*/
private addToHistory(parameterId: string, oldValue: unknown, newValue: unknown): void {
this.parameterHistory.push({
parameterId,
oldValue,
newValue,
timestamp: Date.now()
});
// Limit history size
if (this.parameterHistory.length > 100) {
this.parameterHistory.shift();
}
}
/**
* Undo last parameter change
*/
public undo(): boolean {
if (this.parameterHistory.length === 0) return false;
const lastChange = this.parameterHistory.pop()!;
this.currentValues.set(lastChange.parameterId, lastChange.oldValue);
// Re-validate
const control = this.getParameterControl(lastChange.parameterId);
if (control) {
const result = this.validateParameter(control, lastChange.oldValue);
this.validationResults.set(lastChange.parameterId, result);
}
return true;
}
/**
* Get parameter change history
*/
public getHistory(): readonly ParameterHistoryEntry[] {
return [...this.parameterHistory];
}
// =============================================================================
// Event Handling
// =============================================================================
/**
* Add parameter change listener
*/
public addChangeListener(parameterId: string, listener: ParameterChangeListener): void {
if (!this.changeListeners.has(parameterId)) {
this.changeListeners.set(parameterId, new Set());
}
this.changeListeners.get(parameterId)!.add(listener);
}
/**
* Remove parameter change listener
*/
public removeChangeListener(parameterId: string, listener: ParameterChangeListener): boolean {
const listeners = this.changeListeners.get(parameterId);
return listeners ? listeners.delete(listener) : false;
}
/**
* Notify change listeners
*/
private notifyChangeListeners(parameterId: string, newValue: unknown, oldValue: unknown): void {
const listeners = this.changeListeners.get(parameterId);
if (!listeners) return;
listeners.forEach(listener => {
try {
listener(parameterId, newValue, oldValue);
} catch (error) {
console.error('Error in parameter change listener:', error);
}
});
}
// =============================================================================
// Utility Methods
// =============================================================================
/**
* Get parameter control configuration
*/
private getParameterControl(parameterId: string): ParameterControlConfig | undefined {
const allControls = {
...HELIX_PARAMETER_CONTROLS,
...AGENT_PARAMETER_CONTROLS,
...SYSTEM_PARAMETER_CONTROLS
};
return Object.values(allControls).find(control => control.id === parameterId);
}
/**
* Get validation result for parameter
*/
public getValidationResult(parameterId: string): ValidationResult | undefined {
return this.validationResults.get(parameterId);
}
/**
* Check if all parameters are valid
*/
public isAllValid(): boolean {
return Array.from(this.validationResults.values()).every(result => result.valid);
}
/**
* Get performance impact summary
*/
public getPerformanceImpact(): PerformanceImpactSummary {
const impacts = Array.from(this.currentValues.keys())
.map(id => this.getParameterControl(id))
.filter(control => control?.performanceImpact)
.map(control => control!.performanceImpact!);
return {
overall: this.calculateOverallImpact(impacts),
breakdown: this.groupImpactsByLevel(impacts),
recommendations: this.getPerformanceRecommendations()
};
}
private calculateOverallImpact(impacts: PerformanceImpact[]): PerformanceImpact {
if (impacts.includes(PerformanceImpact.Critical)) return PerformanceImpact.Critical;
if (impacts.includes(PerformanceImpact.High)) return PerformanceImpact.High;
if (impacts.includes(PerformanceImpact.Medium)) return PerformanceImpact.Medium;
if (impacts.includes(PerformanceImpact.Low)) return PerformanceImpact.Low;
return PerformanceImpact.None;
}
private groupImpactsByLevel(impacts: PerformanceImpact[]): Record<PerformanceImpact, number> {
const breakdown = {
[PerformanceImpact.None]: 0,
[PerformanceImpact.Low]: 0,
[PerformanceImpact.Medium]: 0,
[PerformanceImpact.High]: 0,
[PerformanceImpact.Critical]: 0
};
impacts.forEach(impact => {
breakdown[impact]++;
});
return breakdown;
}
private getPerformanceRecommendations(): string[] {
const recommendations: string[] = [];
if (this.isMobile) {
recommendations.push('Consider using the Mobile Optimized preset for better performance');
}
const resolution = this.getParameter<number>('helix_resolution');
if (resolution && resolution > 1000) {
recommendations.push('High resolution may impact rendering performance');
}
const maxAgents = this.getParameter<number>('agent_max_count');
if (maxAgents && maxAgents > 20) {
recommendations.push('High agent count may impact system performance');
}
return recommendations;
}
}
// =============================================================================
// Supporting Types and Interfaces
// =============================================================================
/** Parameter preset configuration */
export interface ParameterPreset {
readonly id: string;
readonly name: string;
readonly description: string;
readonly parameters: Record<string, unknown>;
readonly createdAt: number;
readonly version: string;
}
/** Parameter change history entry */
export interface ParameterHistoryEntry {
readonly parameterId: string;
readonly oldValue: unknown;
readonly newValue: unknown;
readonly timestamp: number;
}
/** Parameter change listener function */
export type ParameterChangeListener = (
parameterId: string,
newValue: unknown,
oldValue: unknown
) => void;
/** Performance impact summary */
export interface PerformanceImpactSummary {
readonly overall: PerformanceImpact;
readonly breakdown: Record<PerformanceImpact, number>;
readonly recommendations: readonly string[];
}
// =============================================================================
// Validation Functions
// =============================================================================
/** Validate radius parameters */
function validateRadius(value: number, type: 'top' | 'bottom'): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
if (type === 'top' && value < 1.0) {
warnings.push({
field: 'topRadius',
message: 'Very small top radius may reduce exploration effectiveness',
suggestion: 'Consider using a radius of at least 1.0'
});
}
if (type === 'bottom' && value > 1.0) {
warnings.push({
field: 'bottomRadius',
message: 'Large bottom radius may reduce focus effectiveness',
suggestion: 'Consider using a radius less than 1.0 for better convergence'
});
}
return { valid: errors.length === 0, errors, warnings };
}
/** Validate number of turns */
function validateTurns(value: unknown): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
const turns = value as number;
if (turns > 50) {
warnings.push({
field: 'turns',
message: 'High number of turns may impact visualization performance',
suggestion: 'Consider reducing turns for better performance'
});
}
if (turns < 5) {
warnings.push({
field: 'turns',
message: 'Low number of turns may reduce helix effectiveness',
suggestion: 'Consider using at least 5 turns for proper helix geometry'
});
}
return { valid: errors.length === 0, errors, warnings };
}
/** Validate maximum agents */
function validateMaxAgents(value: unknown): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
const maxAgents = value as number;
if (maxAgents > 50) {
warnings.push({
field: 'maxAgents',
message: 'High agent count may cause memory issues',
suggestion: 'Consider reducing max agents for better stability'
});
}
return { valid: errors.length === 0, errors, warnings };
}
/** Validate agent types selection */
function validateAgentTypes(value: unknown): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
const types = value as AgentType[];
if (types.length === 0) {
errors.push({
field: 'agentTypes',
message: 'At least one agent type must be selected',
code: 'NO_AGENTS'
});
}
if (!types.includes(AgentType.Synthesis)) {
warnings.push({
field: 'agentTypes',
message: 'Synthesis agents are recommended for task completion',
suggestion: 'Consider including synthesis agents'
});
}
return { valid: errors.length === 0, errors, warnings };
}
/** Validate GPU availability */
function validateGPUAvailability(value: unknown): ValidationResult {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
if (value === true && !window.navigator.gpu) {
warnings.push({
field: 'enableGPU',
message: 'GPU not available on this device',
suggestion: 'GPU acceleration will be disabled automatically'
});
}
return { valid: errors.length === 0, errors, warnings };
}
// Export for use in Gradio interface
export default ParameterControlManager; |