This repository was archived by the owner on Sep 22, 2025. It is now read-only.
forked from Guowei-Yan/Iterative-Contextual-Refinements
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
4087 lines (3601 loc) · 224 KB
/
index.tsx
File metadata and controls
4087 lines (3601 loc) · 224 KB
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
/**
* @license
* SPDX-License-Identifier: Apache-2.0
*/
import * as Diff from 'diff';
import JSZip from 'jszip';
import { GoogleGenAI, GenerateContentResponse, Part } from "@google/genai";
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import hljs from 'highlight.js';
import {
defaultCustomPromptsWebsite,
defaultCustomPromptsCreative,
createDefaultCustomPromptsMath,
createDefaultCustomPromptsAgent,
defaultCustomPromptsReact, // Added for React mode
systemInstructionHtmlOutputOnly, // Though not directly used in index.tsx, it's good to be aware it's here if needed
systemInstructionJsonOutputOnly, // Same as above
systemInstructionTextOutputOnly // Same as above
} from './prompts.js';
// Constants for retry logic
const MAX_RETRIES = 3; // Max number of retries for API errors
const INITIAL_DELAY_MS = 2000; // Initial delay in milliseconds
const BACKOFF_FACTOR = 2; // Factor by which delay increases
/**
* Custom error class to signify that pipeline processing was intentionally
* stopped by a user request.
*/
class PipelineStopRequestedError extends Error {
constructor(message: string) {
super(message);
this.name = "PipelineStopRequestedError";
}
}
type ApplicationMode = 'website' | 'creative' | 'math' | 'agent' | 'react';
interface AgentGeneratedPrompts {
iteration_type_description: string;
expected_output_content_type: string; // e.g., "python", "text", "markdown"
placeholders_guide: Record<string, string>;
initial_generation: { system_instruction: string; user_prompt_template: string; };
feature_implementation: { system_instruction: string; user_prompt_template: string; };
refinement_and_suggestion: { system_instruction: string; user_prompt_template: string; }; // Expected to output JSON: { refined_content: string, suggestions: string[] }
final_polish: { system_instruction: string; user_prompt_template: string; };
}
interface IterationData {
iterationNumber: number;
title: string;
// Website Mode Specific
requestPromptHtml_InitialGenerate?: string;
requestPromptHtml_FeatureImplement?: string;
requestPromptHtml_BugFix?: string;
requestPromptFeatures_Suggest?: string;
generatedHtml?: string;
suggestedFeatures?: string[]; // Used by Website for general suggestions
// Creative Writing Mode Specific
requestPromptText_GenerateDraft?: string;
requestPromptText_Critique?: string;
requestPromptText_Revise?: string;
requestPromptText_Polish?: string;
generatedOrRevisedText?: string;
critiqueSuggestions?: string[];
// Agent Mode Specific
agentJudgeLLM_InitialRequest?: string; // Prompt to Judge LLM
agentGeneratedPrompts?: AgentGeneratedPrompts; // Output from Judge LLM (stored in iter 0)
requestPrompt_SysInstruction?: string; // Dynamically set system instruction for the current step
requestPrompt_UserTemplate?: string; // Dynamically set user prompt template
requestPrompt_Rendered?: string; // Actual rendered prompt sent to API
generatedMainContent?: string; // Main output of an agent step (text, code, etc.)
// For agent loop iterations that have two sub-steps (implement, then refine/suggest)
requestPrompt_SubStep_SysInstruction?: string;
requestPrompt_SubStep_UserTemplate?: string;
requestPrompt_SubStep_Rendered?: string;
generatedSubStep_Content?: string;
generatedSuggestions?: string[]; // For Agent mode's refine/suggest step output
status: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
error?: string;
isDetailsOpen?: boolean;
retryAttempt?: number;
}
interface PipelineState {
id: number;
originalTemperatureIndex: number;
temperature: number;
modelName: string;
iterations: IterationData[];
status: 'idle' | 'running' | 'stopping' | 'stopped' | 'completed' | 'failed';
tabButtonElement?: HTMLButtonElement;
contentElement?: HTMLElement;
stopButtonElement?: HTMLButtonElement;
isStopRequested?: boolean;
}
// Math Mode Specific Interfaces
interface MathSubStrategyData {
id: string; // e.g., "main1-sub1"
subStrategyText: string;
requestPromptSolutionAttempt?: string;
solutionAttempt?: string;
// New fields for self-improvement and refinement
requestPromptSelfImprovement?: string;
refinedSolution?: string;
selfImprovementStatus?: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
selfImprovementError?: string;
selfImprovementRetryAttempt?: number;
status: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
error?: string;
isDetailsOpen?: boolean;
retryAttempt?: number;
}
// New interfaces for Hypothesis Explorer
interface MathHypothesisData {
id: string; // e.g., "hyp1", "hyp2", "hyp3"
hypothesisText: string;
// Prover agent data
proverRequestPrompt?: string;
proverAttempt?: string;
proverStatus: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
proverError?: string;
proverRetryAttempt?: number;
// Disprover agent data
disproverRequestPrompt?: string;
disproverAttempt?: string;
disproverStatus: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
disproverError?: string;
disproverRetryAttempt?: number;
// Final status determination
finalStatus: 'pending' | 'proven' | 'refuted' | 'unresolved' | 'contradiction';
isDetailsOpen?: boolean;
}
interface MathMainStrategyData {
id: string; // e.g., "main1"
strategyText: string;
requestPromptSubStrategyGen?: string;
subStrategies: MathSubStrategyData[];
status: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled'; // for sub-strategy generation
error?: string; // error during sub-strategy generation for this main strategy
isDetailsOpen?: boolean;
retryAttempt?: number; // for sub-strategy generation step
// New fields for judging sub-strategies
judgedBestSubStrategyId?: string;
judgedBestSolution?: string; // The full text of the best solution with reasoning.
judgingRequestPrompt?: string;
judgingResponseText?: string; // The raw response from the judge
judgingStatus?: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
judgingError?: string;
judgingRetryAttempt?: number;
}
interface MathPipelineState {
id: string; // unique ID for this math problem instance
problemText: string;
problemImageBase64?: string | null; // Base64 encoded image
problemImageMimeType?: string;
requestPromptInitialStrategyGen?: string;
initialStrategies: MathMainStrategyData[];
status: 'idle' | 'processing' | 'retrying' | 'completed' | 'error' | 'stopping' | 'stopped' | 'cancelled'; // Overall status
error?: string; // Overall error for the whole process
isStopRequested?: boolean;
activeTabId?: string; // e.g., "problem-details", "strategic-solver", "hypothesis-explorer", "final-result"
retryAttempt?: number; // for initial strategy generation step
// New fields for Hypothesis Explorer (Track B)
requestPromptHypothesisGen?: string;
hypotheses: MathHypothesisData[];
hypothesisGenStatus?: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
hypothesisGenError?: string;
hypothesisGenRetryAttempt?: number;
// Knowledge packet synthesized from hypothesis exploration
knowledgePacket?: string;
// Synchronization flags
strategicSolverComplete?: boolean; // Track A completion
hypothesisExplorerComplete?: boolean; // Track B completion
// New fields for final judging
finalJudgedBestStrategyId?: string;
finalJudgedBestSolution?: string;
finalJudgingRequestPrompt?: string;
finalJudgingResponseText?: string;
finalJudgingStatus?: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
finalJudgingError?: string;
finalJudgingRetryAttempt?: number;
}
export interface CustomizablePromptsWebsite { // Export for prompts.ts
sys_initialGen: string;
user_initialGen: string;
sys_initialBugFix: string;
user_initialBugFix: string;
sys_initialFeatureSuggest: string;
user_initialFeatureSuggest: string;
sys_refineStabilizeImplement: string;
user_refineStabilizeImplement: string;
sys_refineBugFix: string;
user_refineBugFix: string;
sys_refineFeatureSuggest: string;
user_refineFeatureSuggest: string;
sys_finalPolish: string;
user_finalPolish: string;
}
export interface CustomizablePromptsCreative { // Export for prompts.ts
sys_creative_initialDraft: string;
user_creative_initialDraft: string; // {{initialPremise}}
sys_creative_initialCritique: string;
user_creative_initialCritique: string; // {{currentDraft}}
sys_creative_refine_revise: string;
user_creative_refine_revise: string; // {{currentDraft}}, {{critiqueToImplementStr}}
sys_creative_refine_critique: string;
user_creative_refine_critique: string; // {{currentDraft}}
sys_creative_final_polish: string;
user_creative_final_polish: string; // {{currentDraft}}
}
export interface CustomizablePromptsMath { // Export for prompts.ts
sys_math_initialStrategy: string;
user_math_initialStrategy: string; // {{originalProblemText}} (+ image if provided)
sys_math_subStrategy: string;
user_math_subStrategy: string; // {{originalProblemText}}, {{currentMainStrategy}}, {{otherMainStrategiesStr}} (+ image)
sys_math_solutionAttempt: string;
user_math_solutionAttempt: string; // {{originalProblemText}}, {{currentSubStrategy}}, {{knowledgePacket}} (+ image)
// New prompts for self-improvement and refinement
sys_math_selfImprovement: string;
user_math_selfImprovement: string; // {{originalProblemText}}, {{currentSubStrategy}}, {{solutionAttempt}}, {{knowledgePacket}} (+ image)
// New prompts for hypothesis exploration
sys_math_hypothesisGeneration: string;
user_math_hypothesisGeneration: string; // {{originalProblemText}} (+ image)
sys_math_prover: string;
user_math_prover: string; // {{originalProblemText}}, {{hypothesis}} (+ image)
sys_math_disprover: string;
user_math_disprover: string; // {{originalProblemText}}, {{hypothesis}} (+ image)
}
export interface CustomizablePromptsAgent { // Export for prompts.ts
sys_agent_judge_llm: string; // System instruction for the Judge LLM
user_agent_judge_llm: string; // User prompt template for Judge LLM (e.g., "{{initialRequest}}", "{{NUM_AGENT_MAIN_REFINEMENT_LOOPS}}")
}
interface ExportedConfig {
currentMode: ApplicationMode;
initialIdea: string; // Also used for math problem text / agent request
problemImageBase64?: string | null; // For math mode
problemImageMimeType?: string; // For math mode
selectedModel: string;
selectedOriginalTemperatureIndices: number[]; // For website/creative/agent
pipelinesState: PipelineState[]; // For website/creative/agent
activeMathPipeline: MathPipelineState | null; // For math
activeReactPipeline: ReactPipelineState | null; // Added for React mode
activePipelineId: number | null; // For website/creative/agent
activeMathProblemTabId?: string; // For math UI
globalStatusText: string;
globalStatusClass: string;
customPromptsWebsite: CustomizablePromptsWebsite;
customPromptsCreative: CustomizablePromptsCreative;
customPromptsMath: CustomizablePromptsMath;
customPromptsAgent: CustomizablePromptsAgent;
customPromptsReact: CustomizablePromptsReact; // Added for React mode
isCustomPromptsOpen?: boolean;
}
// React Mode Specific Interfaces
export interface ReactModeStage { // Exporting for potential use elsewhere, though primarily internal
id: number; // 0-4 for the 5 worker agents
title: string; // e.g., "Agent 1: UI Components" - defined by Orchestrator
systemInstruction?: string; // Generated by Orchestrator for this worker agent
userPrompt?: string; // Generated by Orchestrator for this worker agent (can be a template)
renderedUserPrompt?: string; // If the userPrompt is a template
generatedContent?: string; // Code output from this worker agent
status: 'pending' | 'processing' | 'retrying' | 'completed' | 'error' | 'cancelled';
error?: string;
isDetailsOpen?: boolean;
retryAttempt?: number;
}
export interface ReactPipelineState { // Exporting for potential use elsewhere
id: string; // Unique ID for this React mode process run
userRequest: string;
orchestratorSystemInstruction: string; // The system prompt used for the orchestrator
orchestratorPlan?: string; // plan.txt generated by Orchestrator
orchestratorRawOutput?: string; // Full raw output from orchestrator (for debugging/inspection)
stages: ReactModeStage[]; // Array of 5 worker agent stages
finalAppendedCode?: string; // Combined code from all worker agents
status: 'idle' | 'orchestrating' | 'processing_workers' | 'completed' | 'error' | 'stopping' | 'stopped' | 'cancelled' | 'orchestrating_retrying' | 'failed';
error?: string;
isStopRequested?: boolean;
activeTabId?: string; // To track which of the 5 worker agent tabs is active in UI, e.g., "worker-0", "worker-1"
orchestratorRetryAttempt?: number;
}
export interface CustomizablePromptsReact { // Export for prompts.ts
sys_orchestrator: string; // System instruction for the Orchestrator Agent
user_orchestrator: string; // User prompt template for Orchestrator Agent {{user_request}}
}
const NUM_WEBSITE_REFINEMENT_ITERATIONS = 5;
const NUM_CREATIVE_REFINEMENT_ITERATIONS = 3;
export const NUM_AGENT_MAIN_REFINEMENT_LOOPS = 3;
const TOTAL_STEPS_WEBSITE = 1 + NUM_WEBSITE_REFINEMENT_ITERATIONS + 1;
const TOTAL_STEPS_CREATIVE = 1 + NUM_CREATIVE_REFINEMENT_ITERATIONS + 1;
// Agent steps: 1 (Judge) + 1 (Initial Gen) + 1 (Initial Refine/Suggest) + N (Loops) + 1 (Final Polish)
const TOTAL_STEPS_AGENT = 1 + 1 + 1 + NUM_AGENT_MAIN_REFINEMENT_LOOPS + 1;
export const NUM_INITIAL_STRATEGIES_MATH = 3;
export const NUM_SUB_STRATEGIES_PER_MAIN_MATH = 3;
const MATH_MODEL_NAME = "gemini-2.5-pro";
const MATH_FIXED_TEMPERATURE = 1.0;
const temperatures = [0, 0.7, 1.0, 1.5, 2.0];
let pipelinesState: PipelineState[] = [];
let activeMathPipeline: MathPipelineState | null = null;
let activeReactPipeline: ReactPipelineState | null = null; // Added for React mode
let ai: GoogleGenAI | null = null;
let activePipelineId: number | null = null;
let isGenerating = false;
let currentMode: ApplicationMode = 'website';
let currentProblemImageBase64: string | null = null;
let currentProblemImageMimeType: string | null = null;
// This variable is no longer used for the modal state but can be kept for config export/import
let isCustomPromptsOpen = false;
let customPromptsWebsiteState: CustomizablePromptsWebsite = JSON.parse(JSON.stringify(defaultCustomPromptsWebsite));
let customPromptsCreativeState: CustomizablePromptsCreative = JSON.parse(JSON.stringify(defaultCustomPromptsCreative));
let customPromptsMathState: CustomizablePromptsMath = createDefaultCustomPromptsMath(NUM_INITIAL_STRATEGIES_MATH, NUM_SUB_STRATEGIES_PER_MAIN_MATH);
let customPromptsAgentState: CustomizablePromptsAgent = createDefaultCustomPromptsAgent(NUM_AGENT_MAIN_REFINEMENT_LOOPS);
let customPromptsReactState: CustomizablePromptsReact = JSON.parse(JSON.stringify(defaultCustomPromptsReact)); // Added for React mode
const apiKeyStatusElement = document.getElementById('api-key-status') as HTMLParagraphElement;
const apiKeyFormContainer = document.getElementById('api-key-form-container') as HTMLElement;
const apiKeyInput = document.getElementById('api-key-input') as HTMLInputElement;
const saveApiKeyButton = document.getElementById('save-api-key-button') as HTMLButtonElement;
const clearApiKeyButton = document.getElementById('clear-api-key-button') as HTMLButtonElement;
const initialIdeaInput = document.getElementById('initial-idea') as HTMLTextAreaElement;
const initialIdeaLabel = document.getElementById('initial-idea-label') as HTMLLabelElement;
const mathProblemImageInputContainer = document.getElementById('math-problem-image-input-container') as HTMLElement;
const mathProblemImageInput = document.getElementById('math-problem-image-input') as HTMLInputElement;
const mathProblemImagePreview = document.getElementById('math-problem-image-preview') as HTMLImageElement;
const modelSelectionContainer = document.getElementById('model-selection-container') as HTMLElement;
const modelSelectElement = document.getElementById('model-select') as HTMLSelectElement;
const temperatureSelectionContainer = document.getElementById('temperature-selection-container') as HTMLElement;
const generateButton = document.getElementById('generate-button') as HTMLButtonElement;
const tabsNavContainer = document.getElementById('tabs-nav-container') as HTMLElement;
const pipelinesContentContainer = document.getElementById('pipelines-content-container') as HTMLElement;
const globalStatusDiv = document.getElementById('global-status') as HTMLElement;
const pipelineSelectorsContainer = document.getElementById('pipeline-selectors-container') as HTMLElement;
const appModeSelector = document.getElementById('app-mode-selector') as HTMLElement;
// Prompts containers (now inside the modal)
const websitePromptsContainer = document.getElementById('website-prompts-container') as HTMLElement;
const creativePromptsContainer = document.getElementById('creative-prompts-container') as HTMLElement;
const mathPromptsContainer = document.getElementById('math-prompts-container') as HTMLElement;
const agentPromptsContainer = document.getElementById('agent-prompts-container') as HTMLElement;
const reactPromptsContainer = document.getElementById('react-prompts-container') as HTMLElement; // Added for React mode
// Custom Prompts Modal Elements
const promptsModalOverlay = document.getElementById('prompts-modal-overlay') as HTMLElement;
const promptsModalCloseButton = document.getElementById('prompts-modal-close-button') as HTMLButtonElement;
const customizePromptsTrigger = document.getElementById('customize-prompts-trigger') as HTMLElement;
// Diff Modal Elements
const diffModalOverlay = document.getElementById('diff-modal-overlay') as HTMLElement;
const diffModalCloseButton = document.getElementById('diff-modal-close-button') as HTMLButtonElement;
const diffSourceLabel = document.getElementById('diff-source-label') as HTMLParagraphElement;
const diffTargetTreeContainer = document.getElementById('diff-target-tree') as HTMLElement;
const diffViewerPanel = document.getElementById('diff-viewer-panel') as HTMLElement;
const exportConfigButton = document.getElementById('export-config-button') as HTMLButtonElement;
const importConfigInput = document.getElementById('import-config-input') as HTMLInputElement;
const importConfigLabel = document.getElementById('import-config-label') as HTMLLabelElement;
const customPromptTextareasWebsite: { [K in keyof CustomizablePromptsWebsite]: HTMLTextAreaElement | null } = {
sys_initialGen: document.getElementById('sys-initial-gen') as HTMLTextAreaElement,
user_initialGen: document.getElementById('user-initial-gen') as HTMLTextAreaElement,
sys_initialBugFix: document.getElementById('sys-initial-bugfix') as HTMLTextAreaElement,
user_initialBugFix: document.getElementById('user-initial-bugfix') as HTMLTextAreaElement,
sys_initialFeatureSuggest: document.getElementById('sys-initial-features') as HTMLTextAreaElement,
user_initialFeatureSuggest: document.getElementById('user-initial-features') as HTMLTextAreaElement,
sys_refineStabilizeImplement: document.getElementById('sys-refine-implement') as HTMLTextAreaElement,
user_refineStabilizeImplement: document.getElementById('user-refine-implement') as HTMLTextAreaElement,
sys_refineBugFix: document.getElementById('sys-refine-bugfix') as HTMLTextAreaElement,
user_refineBugFix: document.getElementById('user-refine-bugfix') as HTMLTextAreaElement,
sys_refineFeatureSuggest: document.getElementById('sys-refine-features') as HTMLTextAreaElement,
user_refineFeatureSuggest: document.getElementById('user-refine-features') as HTMLTextAreaElement,
sys_finalPolish: document.getElementById('sys-final-polish') as HTMLTextAreaElement,
user_finalPolish: document.getElementById('user-final-polish') as HTMLTextAreaElement,
};
const customPromptTextareasCreative: { [K in keyof CustomizablePromptsCreative]: HTMLTextAreaElement | null } = {
sys_creative_initialDraft: document.getElementById('sys-creative-initial-draft') as HTMLTextAreaElement,
user_creative_initialDraft: document.getElementById('user-creative-initial-draft') as HTMLTextAreaElement,
sys_creative_initialCritique: document.getElementById('sys-creative-initial-critique') as HTMLTextAreaElement,
user_creative_initialCritique: document.getElementById('user-creative-initial-critique') as HTMLTextAreaElement,
sys_creative_refine_revise: document.getElementById('sys-creative-refine-revise') as HTMLTextAreaElement,
user_creative_refine_revise: document.getElementById('user-creative-refine-revise') as HTMLTextAreaElement,
sys_creative_refine_critique: document.getElementById('sys-creative-refine-critique') as HTMLTextAreaElement,
user_creative_refine_critique: document.getElementById('user-creative-refine-critique') as HTMLTextAreaElement,
sys_creative_final_polish: document.getElementById('sys-creative-final-polish') as HTMLTextAreaElement,
user_creative_final_polish: document.getElementById('user-creative-final-polish') as HTMLTextAreaElement,
};
const customPromptTextareasMath: { [K in keyof CustomizablePromptsMath]: HTMLTextAreaElement | null } = {
sys_math_initialStrategy: document.getElementById('sys-math-initial-strategy') as HTMLTextAreaElement,
user_math_initialStrategy: document.getElementById('user-math-initial-strategy') as HTMLTextAreaElement,
sys_math_subStrategy: document.getElementById('sys-math-sub-strategy') as HTMLTextAreaElement,
user_math_subStrategy: document.getElementById('user-math-sub-strategy') as HTMLTextAreaElement,
sys_math_solutionAttempt: document.getElementById('sys-math-solution-attempt') as HTMLTextAreaElement,
user_math_solutionAttempt: document.getElementById('user-math-solution-attempt') as HTMLTextAreaElement,
sys_math_selfImprovement: document.getElementById('sys-math-self-improvement') as HTMLTextAreaElement,
user_math_selfImprovement: document.getElementById('user-math-self-improvement') as HTMLTextAreaElement,
sys_math_hypothesisGeneration: document.getElementById('sys-math-hypothesis-generation') as HTMLTextAreaElement,
user_math_hypothesisGeneration: document.getElementById('user-math-hypothesis-generation') as HTMLTextAreaElement,
sys_math_prover: document.getElementById('sys-math-prover') as HTMLTextAreaElement,
user_math_prover: document.getElementById('user-math-prover') as HTMLTextAreaElement,
sys_math_disprover: document.getElementById('sys-math-disprover') as HTMLTextAreaElement,
user_math_disprover: document.getElementById('user-math-disprover') as HTMLTextAreaElement,
};
const customPromptTextareasAgent: { [K in keyof CustomizablePromptsAgent]: HTMLTextAreaElement | null } = {
sys_agent_judge_llm: document.getElementById('sys-agent-judge-llm') as HTMLTextAreaElement,
user_agent_judge_llm: document.getElementById('user-agent-judge-llm') as HTMLTextAreaElement,
};
const customPromptTextareasReact: { [K in keyof CustomizablePromptsReact]: HTMLTextAreaElement | null } = { // Added for React mode
sys_orchestrator: document.getElementById('sys-react-orchestrator') as HTMLTextAreaElement,
user_orchestrator: document.getElementById('user-react-orchestrator') as HTMLTextAreaElement,
};
function initializeApiKey() {
let statusMessage = "";
let isKeyAvailable = false;
let currentApiKey: string | null = null;
// Hide form elements by default
apiKeyFormContainer.style.display = 'none';
saveApiKeyButton.style.display = 'none';
clearApiKeyButton.style.display = 'none';
apiKeyInput.style.display = 'none';
const envKey = process.env.API_KEY;
if (envKey) {
statusMessage = "API Key loaded from environment.";
isKeyAvailable = true;
currentApiKey = envKey;
apiKeyStatusElement.className = 'api-key-status-message status-badge status-ok';
} else {
apiKeyFormContainer.style.display = 'flex'; // Show the container for input/buttons
const storedKey = localStorage.getItem('gemini-api-key');
if (storedKey) {
statusMessage = "Using API Key from local storage.";
isKeyAvailable = true;
currentApiKey = storedKey;
apiKeyStatusElement.className = 'api-key-status-message status-badge status-ok';
clearApiKeyButton.style.display = 'inline-flex'; // Show clear button
} else {
statusMessage = "API Key not found. Please provide one.";
isKeyAvailable = false;
apiKeyStatusElement.className = 'api-key-status-message status-badge status-error';
apiKeyInput.style.display = 'block'; // Show input field
saveApiKeyButton.style.display = 'inline-flex'; // Show save button
}
}
if (apiKeyStatusElement) {
apiKeyStatusElement.textContent = statusMessage;
}
if (isKeyAvailable && currentApiKey) {
try {
ai = new GoogleGenAI({ apiKey: currentApiKey });
if (generateButton) generateButton.disabled = isGenerating;
return true;
} catch (e: any) {
console.error("Failed to initialize GoogleGenAI:", e);
if (apiKeyStatusElement) {
apiKeyStatusElement.textContent = `API Init Error`;
apiKeyStatusElement.className = 'api-key-status-message status-badge status-error';
apiKeyStatusElement.title = `Error: ${e.message}`;
}
if (generateButton) generateButton.disabled = true;
ai = null;
return false;
}
} else {
if (generateButton) generateButton.disabled = true;
ai = null;
return false;
}
}
function initializeCustomPromptTextareas() {
// Website Prompts
for (const key in customPromptTextareasWebsite) {
const k = key as keyof CustomizablePromptsWebsite;
const textarea = customPromptTextareasWebsite[k];
if (textarea) {
textarea.value = customPromptsWebsiteState[k];
textarea.addEventListener('input', (e) => {
customPromptsWebsiteState[k] = (e.target as HTMLTextAreaElement).value;
});
}
}
// Creative Prompts
for (const key in customPromptTextareasCreative) {
const k = key as keyof CustomizablePromptsCreative;
const textarea = customPromptTextareasCreative[k];
if (textarea) {
textarea.value = customPromptsCreativeState[k];
textarea.addEventListener('input', (e) => {
customPromptsCreativeState[k] = (e.target as HTMLTextAreaElement).value;
});
}
}
// Math Prompts
for (const key in customPromptTextareasMath) {
const k = key as keyof CustomizablePromptsMath;
const textarea = customPromptTextareasMath[k];
if (textarea) {
textarea.value = customPromptsMathState[k];
textarea.addEventListener('input', (e) => {
customPromptsMathState[k] = (e.target as HTMLTextAreaElement).value;
});
}
}
// Agent Prompts (for Judge LLM)
for (const key in customPromptTextareasAgent) {
const k = key as keyof CustomizablePromptsAgent;
const textarea = customPromptTextareasAgent[k];
if (textarea) {
textarea.value = customPromptsAgentState[k];
textarea.addEventListener('input', (e) => {
customPromptsAgentState[k] = (e.target as HTMLTextAreaElement).value;
});
}
}
// React Prompts (for Orchestrator)
for (const key in customPromptTextareasReact) {
const k = key as keyof CustomizablePromptsReact;
const textarea = customPromptTextareasReact[k];
if (textarea) {
textarea.value = customPromptsReactState[k];
textarea.addEventListener('input', (e) => {
customPromptsReactState[k] = (e.target as HTMLTextAreaElement).value;
});
}
}
}
function updateCustomPromptTextareasFromState() {
for (const key in customPromptTextareasWebsite) {
const k = key as keyof CustomizablePromptsWebsite;
const textarea = customPromptTextareasWebsite[k];
if (textarea) textarea.value = customPromptsWebsiteState[k];
}
for (const key in customPromptTextareasCreative) {
const k = key as keyof CustomizablePromptsCreative;
const textarea = customPromptTextareasCreative[k];
if (textarea) textarea.value = customPromptsCreativeState[k];
}
for (const key in customPromptTextareasMath) {
const k = key as keyof CustomizablePromptsMath;
const textarea = customPromptTextareasMath[k];
if (textarea) textarea.value = customPromptsMathState[k];
}
for (const key in customPromptTextareasAgent) {
const k = key as keyof CustomizablePromptsAgent;
const textarea = customPromptTextareasAgent[k];
if (textarea) textarea.value = customPromptsAgentState[k];
}
for (const key in customPromptTextareasReact) { // Added for React mode
const k = key as keyof CustomizablePromptsReact;
const textarea = customPromptTextareasReact[k];
if (textarea) textarea.value = customPromptsReactState[k];
}
}
const promptNavStructure = {
website: [
{ groupTitle: "1. Initial Generation & Analysis", prompts: ["initial-gen", "initial-bugfix", "initial-features"] },
{ groupTitle: "2. Refinement Cycle", prompts: ["refine-implement", "refine-bugfix", "refine-features"] },
{ groupTitle: "3. Final Polish", prompts: ["final-polish"] }
],
creative: [
{ groupTitle: "1. Drafting & Critique", prompts: ["creative-initial-draft", "creative-initial-critique"] },
{ groupTitle: "2. Revision Cycle", prompts: ["creative-refine-revise", "creative-refine-critique"] },
{ groupTitle: "3. Final Polish", prompts: ["creative-final-polish"] }
],
math: [
{ groupTitle: "1. Strategic Solver", prompts: ["math-initial-strategy", "math-sub-strategy", "math-solution-attempt", "math-self-improvement"] },
{ groupTitle: "2. Hypothesis Explorer", prompts: ["math-hypothesis-generation", "math-prover", "math-disprover"] }
],
agent: [
{ groupTitle: "Agent Configuration", prompts: ["agent-judge-llm"] }
],
react: [
{ groupTitle: "Orchestrator Agent", prompts: ["react-orchestrator"] }
]
};
function initializePromptsModal() {
const navContainer = document.getElementById('prompts-modal-nav');
const contentContainer = document.getElementById('prompts-modal-content');
if (!navContainer || !contentContainer) return;
// Clear previous state
navContainer.innerHTML = '';
contentContainer.querySelectorAll('.prompts-mode-container').forEach(el => el.classList.remove('active'));
contentContainer.querySelectorAll('.prompt-content-pane').forEach(el => el.classList.remove('active'));
const activeModeContainer = document.getElementById(`${currentMode}-prompts-container`);
if (!activeModeContainer) return;
activeModeContainer.classList.add('active');
// Display current mode at the top of nav
const modeTitle = document.createElement('h4');
modeTitle.className = 'prompts-nav-mode-title';
modeTitle.textContent = `${currentMode.charAt(0).toUpperCase() + currentMode.slice(1)} Mode Prompts`;
navContainer.appendChild(modeTitle);
const navStructure = promptNavStructure[currentMode as keyof typeof promptNavStructure];
if (!navStructure) return;
let firstNavItem: HTMLElement | null = null;
navStructure.forEach(group => {
const groupTitleEl = document.createElement('h5');
groupTitleEl.className = 'prompts-nav-group-title';
groupTitleEl.textContent = group.groupTitle;
navContainer.appendChild(groupTitleEl);
group.prompts.forEach(promptKey => {
const pane = activeModeContainer.querySelector<HTMLElement>(`.prompt-content-pane[data-prompt-key="${promptKey}"]`);
if (!pane) return;
const titleElement = pane.querySelector<HTMLHeadingElement>('.prompt-pane-title');
const title = titleElement ? titleElement.textContent : 'Unnamed Section';
const navItem = document.createElement('div');
navItem.className = 'prompts-nav-item';
navItem.textContent = title;
navItem.dataset.targetPane = promptKey;
navContainer.appendChild(navItem);
if (!firstNavItem) {
firstNavItem = navItem;
}
navItem.addEventListener('click', () => {
// Deactivate all nav items and panes first
navContainer.querySelectorAll('.prompts-nav-item').forEach(item => item.classList.remove('active'));
activeModeContainer.querySelectorAll('.prompt-content-pane').forEach(p => p.classList.remove('active'));
// Activate the clicked one
navItem.classList.add('active');
pane.classList.add('active');
});
});
});
// Activate the first one by default
if (firstNavItem) {
firstNavItem.click();
}
}
function setPromptsModalVisible(visible: boolean) {
if (promptsModalOverlay) {
if (visible) {
initializePromptsModal(); // Re-initialize on open to reflect current mode
promptsModalOverlay.style.display = 'flex';
setTimeout(() => {
promptsModalOverlay.classList.add('is-visible');
}, 10);
} else {
promptsModalOverlay.classList.remove('is-visible');
promptsModalOverlay.addEventListener('transitionend', () => {
if (!promptsModalOverlay.classList.contains('is-visible')) {
promptsModalOverlay.style.display = 'none';
}
}, { once: true });
}
}
}
function updateUIAfterModeChange() {
// Visibility of prompt containers is now handled by CSS classes and initializePromptsModal
const allPromptContainers = document.querySelectorAll('.prompts-mode-container');
allPromptContainers.forEach(container => container.classList.remove('active'));
const activeContainer = document.getElementById(`${currentMode}-prompts-container`);
if (activeContainer) activeContainer.classList.add('active');
// Default UI states
if (mathProblemImageInputContainer) mathProblemImageInputContainer.style.display = 'none';
if (modelSelectionContainer) modelSelectionContainer.style.display = 'flex';
if (temperatureSelectionContainer) temperatureSelectionContainer.style.display = 'block';
const generateButtonText = generateButton?.querySelector('.button-text');
if (currentMode === 'website') {
if (initialIdeaLabel) initialIdeaLabel.textContent = 'HTML Idea:';
if (initialIdeaInput) initialIdeaInput.placeholder = 'E.g., a personal blog about cooking, a portfolio...';
if (generateButtonText) generateButtonText.textContent = 'Generate HTML';
} else if (currentMode === 'creative') {
if (initialIdeaLabel) initialIdeaLabel.textContent = 'Writing Premise:';
if (initialIdeaInput) initialIdeaInput.placeholder = 'E.g., a short story about a time traveler, a poem...';
if (generateButtonText) generateButtonText.textContent = 'Refine Writing';
} else if (currentMode === 'math') {
if (initialIdeaLabel) initialIdeaLabel.textContent = 'Math Problem:';
if (initialIdeaInput) initialIdeaInput.placeholder = 'E.g., "Solve for x: 2x + 5 = 11" or describe...';
if (generateButtonText) generateButtonText.textContent = 'Solve Problem';
if (mathProblemImageInputContainer) mathProblemImageInputContainer.style.display = 'flex';
if (modelSelectionContainer) modelSelectionContainer.style.display = 'none';
if (temperatureSelectionContainer) temperatureSelectionContainer.style.display = 'none';
} else if (currentMode === 'agent') {
if (initialIdeaLabel) initialIdeaLabel.textContent = 'Your Request:';
if (initialIdeaInput) initialIdeaInput.placeholder = 'E.g., "Python snake game", "Analyze iPhone sales data"...';
if (generateButtonText) generateButtonText.textContent = 'Start Agent Process';
} else if (currentMode === 'react') { // Added for React mode
if (initialIdeaLabel) initialIdeaLabel.textContent = 'React App Request:';
if (initialIdeaInput) initialIdeaInput.placeholder = 'E.g., "A simple to-do list app with local storage persistence", "A weather dashboard using OpenWeatherMap API"...';
if (generateButtonText) generateButtonText.textContent = 'Generate React App';
// React mode uses standard model and temperature selection like website/creative/agent
if (modelSelectionContainer) modelSelectionContainer.style.display = 'flex';
if (temperatureSelectionContainer) temperatureSelectionContainer.style.display = 'block';
if (mathProblemImageInputContainer) mathProblemImageInputContainer.style.display = 'none';
}
if (!isGenerating) {
pipelinesState = [];
activeMathPipeline = null;
activeReactPipeline = null;
renderPipelines();
renderActiveMathPipeline();
renderReactModePipeline();
}
updateControlsState();
}
function renderPrompt(template: string, data: Record<string, string>): string {
let rendered = template;
for (const key in data) {
rendered = rendered.replace(new RegExp(`{{${key}}}`, 'g'), data[key] || '');
}
return rendered;
}
function renderPipelineSelectors() {
if (!pipelineSelectorsContainer) return;
pipelineSelectorsContainer.innerHTML = ''; // Clear existing
temperatures.forEach((temp, index) => {
const itemDiv = document.createElement('div');
itemDiv.className = 'pipeline-selector-item';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = `pipeline-selector-${index}`;
checkbox.value = temp.toString();
checkbox.checked = true; // Default to checked
checkbox.dataset.temperatureIndex = index.toString();
const label = document.createElement('label');
label.htmlFor = checkbox.id;
label.textContent = `Variant (T: ${temp.toFixed(1)})`; // Changed label for more generic usage
itemDiv.appendChild(checkbox);
itemDiv.appendChild(label);
pipelineSelectorsContainer.appendChild(itemDiv);
checkbox.addEventListener('change', () => {
updateControlsState();
});
});
updateControlsState(); // Initial state
}
function getSelectedTemperatures(): { temp: number, originalIndex: number }[] {
const selected: { temp: number, originalIndex: number }[] = [];
if (pipelineSelectorsContainer) {
const checkboxes = pipelineSelectorsContainer.querySelectorAll<HTMLInputElement>('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => {
const tempValue = parseFloat(checkbox.value);
const originalIndex = parseInt(checkbox.dataset.temperatureIndex || "-1", 10);
if (!isNaN(tempValue) && originalIndex !== -1) {
selected.push({ temp: tempValue, originalIndex });
}
});
}
return selected;
}
function updateControlsState() {
const anyPipelineRunningOrStopping = pipelinesState.some(p => p.status === 'running' || p.status === 'stopping');
const mathPipelineRunningOrStopping = activeMathPipeline?.status === 'processing' || activeMathPipeline?.status === 'stopping';
const reactPipelineRunningOrStopping = activeReactPipeline?.status === 'orchestrating' || activeReactPipeline?.status === 'processing_workers' || activeReactPipeline?.status === 'stopping'; // Added for React
isGenerating = anyPipelineRunningOrStopping || mathPipelineRunningOrStopping || reactPipelineRunningOrStopping; // Added reactPipeline
const isApiKeyReady = !!ai;
if (generateButton) {
let disabled = isGenerating || !isApiKeyReady;
if (!disabled) {
if (currentMode === 'math') {
// Enabled if not generating
} else if (currentMode === 'react') {
// Enabled if not generating
} else { // website, creative, agent
const selectedTemps = getSelectedTemperatures();
disabled = selectedTemps.length === 0;
}
}
generateButton.disabled = disabled;
}
if (exportConfigButton) exportConfigButton.disabled = isGenerating;
if (importConfigInput) importConfigInput.disabled = isGenerating;
if (importConfigLabel) importConfigLabel.classList.toggle('disabled', isGenerating);
if (initialIdeaInput) initialIdeaInput.disabled = isGenerating;
if (mathProblemImageInput) mathProblemImageInput.disabled = isGenerating;
if (modelSelectElement) modelSelectElement.disabled = isGenerating || currentMode === 'math';
if (pipelineSelectorsContainer) {
const disableSelectors = isGenerating || currentMode === 'math' || currentMode === 'react';
pipelineSelectorsContainer.querySelectorAll('input[type="checkbox"]').forEach(cb => (cb as HTMLInputElement).disabled = disableSelectors);
const pipelineSelectHeading = document.getElementById('pipeline-select-heading');
if (pipelineSelectHeading) {
const parentSection = pipelineSelectHeading.closest('.sidebar-section-content');
parentSection?.classList.toggle('disabled', disableSelectors);
}
}
if (currentMode === 'math' && modelSelectElement) {
modelSelectElement.value = MATH_MODEL_NAME;
}
if (appModeSelector) {
appModeSelector.querySelectorAll('input[type="radio"]').forEach(rb => (rb as HTMLInputElement).disabled = isGenerating);
}
if (customizePromptsTrigger) {
const parentSection = customizePromptsTrigger.closest('.sidebar-section');
parentSection?.classList.toggle('disabled', isGenerating);
customizePromptsTrigger.style.pointerEvents = isGenerating ? 'none' : 'auto';
}
}
function initPipelines() {
const selectedModel = modelSelectElement.value;
const selectedTempsWithOriginalIndices = getSelectedTemperatures();
let totalSteps: number;
let numRefinementIterations: number;
switch (currentMode) {
case 'website':
totalSteps = TOTAL_STEPS_WEBSITE;
numRefinementIterations = NUM_WEBSITE_REFINEMENT_ITERATIONS;
break;
case 'creative':
totalSteps = TOTAL_STEPS_CREATIVE;
numRefinementIterations = NUM_CREATIVE_REFINEMENT_ITERATIONS;
break;
case 'agent':
totalSteps = TOTAL_STEPS_AGENT;
numRefinementIterations = NUM_AGENT_MAIN_REFINEMENT_LOOPS;
break;
default:
return;
}
pipelinesState = selectedTempsWithOriginalIndices.map(({ temp, originalIndex }, pipelineIndex) => {
const iterations: IterationData[] = [];
for (let i = 0; i < totalSteps; i++) {
let title = '';
if (currentMode === 'website') {
if (i === 0) title = 'Initial Gen, Fix & Suggest';
else if (i <= numRefinementIterations) title = `Refine ${i}: Stabilize, Implement, Fix & Suggest`;
else title = 'Final Polish & Fix';
} else if (currentMode === 'creative') {
if (i === 0) title = 'Initial Draft & Critique';
else if (i <= numRefinementIterations) title = `Refine ${i}: Revise & Critique`;
else title = 'Final Polish';
} else if (currentMode === 'agent') {
if (i === 0) title = `Setup: Agent Prompt Design`;
else if (i === 1) title = `Step ${i}: Initial Generation`; // Step is i (1-based for users)
else if (i === 2) title = `Step ${i}: Initial Refinement & Suggestion`;
else if (i < totalSteps - 1) { // Iterations from 3 up to (but not including) the last one are loops
const loopNumber = i - 2; // Loop numbers are 1-based (i=3 is Loop 1)
title = `Step ${i}: Refinement Loop ${loopNumber} (Implement & Refine/Suggest)`;
}
else title = `Step ${i}: Final Polish`; // Last step is i
}
iterations.push({
iterationNumber: i,
title: title,
status: 'pending',
isDetailsOpen: true, // Always open with new design
});
}
return {
id: pipelineIndex,
originalTemperatureIndex: originalIndex,
temperature: temp,
modelName: selectedModel,
iterations: iterations,
status: 'idle',
isStopRequested: false,
};
});
renderPipelines();
if (pipelinesState.length > 0) {
activateTab(pipelinesState[0].id);
} else {
tabsNavContainer.innerHTML = '<p class="no-pipelines-message">No variants selected to run.</p>';
pipelinesContentContainer.innerHTML = '';
}
updateControlsState();
}
function activateTab(idToActivate: number | string) {
if (currentMode === 'math' && activeMathPipeline) {
activeMathPipeline.activeTabId = idToActivate as string;
// Deactivate all math tabs and panes
document.querySelectorAll('#tabs-nav-container .tab-button.math-mode-tab').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('#pipelines-content-container > .pipeline-content').forEach(pane => pane.classList.remove('active'));
// Activate the correct one
const tabButton = document.getElementById(`math-tab-${idToActivate}`);
const contentPane = document.getElementById(`pipeline-content-${idToActivate}`);
if (tabButton) tabButton.classList.add('active');
if (contentPane) contentPane.classList.add('active');
} else if (currentMode === 'react' && activeReactPipeline) {
activeReactPipeline.activeTabId = idToActivate as string;
document.querySelectorAll('#tabs-nav-container .tab-button.react-mode-tab').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('#pipelines-content-container > .pipeline-content').forEach(pane => pane.classList.remove('active'));
const tabButton = document.getElementById(`react-tab-${idToActivate}`);
const contentPane = document.getElementById(`pipeline-content-${idToActivate}`);
if (tabButton) tabButton.classList.add('active');
if (contentPane) contentPane.classList.add('active');
} else if (currentMode !== 'math' && currentMode !== 'react') {
activePipelineId = idToActivate as number;
document.querySelectorAll('#tabs-nav-container .tab-button').forEach(btn => {
btn.classList.toggle('active', btn.id === `pipeline-tab-${activePipelineId}`);
btn.setAttribute('aria-selected', (btn.id === `pipeline-tab-${activePipelineId}`).toString());
});
document.querySelectorAll('#pipelines-content-container > .pipeline-content').forEach(pane => {
pane.classList.toggle('active', pane.id === `pipeline-content-${activePipelineId}`);
});
}
}
function renderPipelines() {
if (currentMode === 'math' || currentMode === 'react') { // React mode also has its own renderer
tabsNavContainer.innerHTML = '';
pipelinesContentContainer.innerHTML = '';
return;
}
tabsNavContainer.innerHTML = '';
pipelinesContentContainer.innerHTML = '';
if (pipelinesState.length === 0) {
tabsNavContainer.innerHTML = '<p class="no-pipelines-message">No variants selected. Please choose at least one variant or import a configuration.</p>';
pipelinesContentContainer.innerHTML = '';