-
Notifications
You must be signed in to change notification settings - Fork 590
Expand file tree
/
Copy pathPlaygroundConfigSection.tsx
More file actions
1619 lines (1484 loc) · 67 KB
/
Copy pathPlaygroundConfigSection.tsx
File metadata and controls
1619 lines (1484 loc) · 67 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
/**
* PlaygroundConfigSection
*
* Schema-driven configuration renderer for playground entities.
* Uses workflowMolecule as the default data source.
*
* Data wiring:
* - Reads from workflowMolecule (configuration, query, parametersSchema) by default
* - Writes via workflowMolecule.actions.updateConfiguration by default
* - Supports custom moleculeAdapter for specialized behavior
* - Schema drives control selection via getSchemaAtPath
* - Model config popover injected via fieldHeader slot
*/
import {memo, useMemo, useCallback, useEffect, useRef, useState} from "react"
import {
type EntitySchema,
type EntitySchemaProperty,
getSchemaAtPath as getSchemaAtPathUtil,
} from "@agenta/entities/shared"
import {workflowMolecule} from "@agenta/entities/workflow"
import type {DataPath} from "@agenta/shared/utils"
import {getOptionsFromSchema, getValueAtPath, setValueAtPath} from "@agenta/shared/utils"
import {HeightCollapse} from "@agenta/ui"
import type {
FieldActionsSlotProps,
FieldContentSlotProps,
FieldHeaderSlotProps,
MoleculeDrillInAdapter,
} from "@agenta/ui/drill-in"
import {useDrillInUI} from "@agenta/ui/drill-in"
import {formatLabel} from "@agenta/ui/drill-in"
import {SharedEditor} from "@agenta/ui/shared-editor"
import {ArrowLeft, CaretDown, CaretRight, MagicWand} from "@phosphor-icons/react"
import {Button, Popover, Tabs, Tooltip, Typography} from "antd"
import clsx from "clsx"
import type {Atom, WritableAtom} from "jotai"
import {atom} from "jotai"
import {useAtom, useAtomValue, useSetAtom} from "jotai"
import yaml from "js-yaml"
import {getModelSchema, getLLMConfigValue, getLLMConfigProperties} from "../SchemaControls"
import {feedbackConfigModeAtomFamily} from "../SchemaControls/FeedbackConfigurationControl"
import {
validateConfigAgainstSchema,
type SchemaValidationError,
} from "../SchemaControls/schemaValidator"
import {MoleculeDrillInView} from "./MoleculeDrillInView"
import {FallbackConfigTab} from "./PlaygroundConfigSection/FallbackConfigTab"
import {ModelConfigEditor} from "./PlaygroundConfigSection/ModelConfigEditor"
import {RetryConfigTab} from "./PlaygroundConfigSection/RetryConfigTab"
// ============================================================================
// TYPES
// ============================================================================
interface SchemaQueryResult {
isPending: boolean
isError: boolean
error: Error | null
data: {agConfigSchema?: PathSchema | null} | null
}
type PathSchema = EntitySchema | EntitySchemaProperty
type ConfigureTabKey = "model" | "fallback" | "retry"
interface FallbackDetailState {
mode: "new" | "edit"
index: number | null
draft: Record<string, unknown>
}
function isEntitySchema(value: unknown): value is PathSchema {
if (!value || typeof value !== "object") return false
const schemaType = (value as Record<string, unknown>).type
return typeof schemaType === "string"
}
/**
* Adapter interface for the data source that PlaygroundConfigSection reads from.
* Defaults to workflowMolecule when not provided.
*/
export interface ConfigSectionMoleculeAdapter {
atoms: {
/** Entity data with `.parameters` — used for hasParameters checks and popover data */
data: (id: string) => Atom<{parameters?: Record<string, unknown>} | null>
/** Base data (pre-draft) with `.parameters` */
serverData: (id: string) => Atom<{parameters?: Record<string, unknown>} | null>
/** Draft data */
draft: (id: string) => Atom<unknown>
/** Whether entity has local changes */
isDirty: (id: string) => Atom<boolean>
/** Schema query state */
schemaQuery: (id: string) => Atom<SchemaQueryResult>
/** ag_config schema */
agConfigSchema: (id: string) => Atom<PathSchema | null>
}
reducers: {
update: WritableAtom<unknown, [id: string, changes: Record<string, unknown>], void>
discard: WritableAtom<unknown, [id: string], void>
}
drillIn: {
getRootData?: (data: unknown) => unknown
getChangesFromRoot?: (data: unknown, rootData: unknown, path: DataPath) => unknown
getValueAtPath?: (data: unknown, path: DataPath) => unknown
getRootItems?: (data: unknown) => unknown[]
getChangesFromPath?: (data: unknown, path: DataPath, value: unknown) => unknown
valueMode?: "native" | "structured"
}
selectors: {
schemaAtPath: (params: {id: string; path: (string | number)[]}) => Atom<unknown>
}
/** @deprecated Use useSetAtom(mol.reducers.update) instead */
set?: {
update: (id: string, changes: Record<string, unknown>) => void
}
}
function hasParameters(data: {parameters?: Record<string, unknown>} | null | undefined): boolean {
return Boolean(data?.parameters && Object.keys(data.parameters).length > 0)
}
const FALLBACK_POLICY_OPTIONS = ["off", "availability", "capacity", "access", "context", "any"].map(
(value) => ({label: value, value}),
)
const RETRY_POLICY_OPTIONS = ["off", "availability", "capacity", "transient", "any"].map(
(value) => ({label: value, value}),
)
const DEFAULT_RETRY_CONFIG = {
max_retries: null as number | null,
base_delay: null as number | null,
}
const PROMPT_EXTENSION_KEYS = [
"fallback_configs",
"fallback_policy",
"retry_config",
"retry_policy",
]
const createFallbackConfigKey = () => {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID()
}
return `${Date.now()}-${Math.random()}`
}
const updateConfigKey = (
base: Record<string, unknown> | undefined,
key: string,
value: unknown,
) => {
const next = {...(base ?? {})}
if (value === null || value === undefined) {
delete next[key]
} else {
next[key] = value
}
return next
}
const getResettableLLMConfigKeys = (llmConfigProps: Record<string, unknown>) =>
Object.keys(llmConfigProps).filter(
(key) => key !== "model" && !PROMPT_EXTENSION_KEYS.includes(key),
)
const resetLLMParameterFields = ({
base,
resetBase,
resetKeys,
}: {
base: Record<string, unknown> | undefined
resetBase: Record<string, unknown> | undefined
resetKeys: string[]
}) => {
const next = {...(base ?? {})}
const keysToReset = ["model", ...resetKeys]
keysToReset.forEach((key) => {
if (resetBase && Object.prototype.hasOwnProperty.call(resetBase, key)) {
next[key] = resetBase[key]
} else {
delete next[key]
}
})
return next
}
// ============================================================================
// AGENTA_METADATA HELPERS
// ============================================================================
/**
* Recursively strip `agenta_metadata` from tool objects in the parameters tree.
* Returns a new object safe for display in JSON/YAML view and a map of stripped
* metadata keyed by stable path so it can be re-attached after editing.
*/
type MetadataMap = Map<string, unknown>
function stripAgentaMetadata(params: Record<string, unknown>): Record<string, unknown> {
return stripRecursive(params) as Record<string, unknown>
}
function stripRecursive(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((item) => stripRecursive(item))
}
if (value && typeof value === "object") {
const obj = value as Record<string, unknown>
const result: Record<string, unknown> = {}
for (const [k, v] of Object.entries(obj)) {
if (k === "agenta_metadata") continue
result[k] = stripRecursive(v)
}
return result
}
return value
}
/**
* Collect all agenta_metadata values from the original parameters,
* keyed by their JSON path (e.g. "prompt.llm_config.tools.0").
*/
function collectAgentaMetadata(
value: unknown,
path = "",
map: MetadataMap = new Map(),
): MetadataMap {
if (Array.isArray(value)) {
value.forEach((item, i) => collectAgentaMetadata(item, path ? `${path}.${i}` : `${i}`, map))
} else if (value && typeof value === "object") {
const obj = value as Record<string, unknown>
if ("agenta_metadata" in obj) {
map.set(path, obj.agenta_metadata)
}
for (const [k, v] of Object.entries(obj)) {
if (k === "agenta_metadata") continue
collectAgentaMetadata(v, path ? `${path}.${k}` : k, map)
}
}
return map
}
/**
* Re-inject agenta_metadata values into a parsed parameters object
* using the metadata map collected from the original.
*/
function reattachAgentaMetadata(value: unknown, metadataMap: MetadataMap, path = ""): unknown {
if (Array.isArray(value)) {
return value.map((item, i) =>
reattachAgentaMetadata(item, metadataMap, path ? `${path}.${i}` : `${i}`),
)
}
if (value && typeof value === "object") {
const obj = value as Record<string, unknown>
const result: Record<string, unknown> = {}
for (const [k, v] of Object.entries(obj)) {
result[k] = reattachAgentaMetadata(v, metadataMap, path ? `${path}.${k}` : k)
}
const meta = metadataMap.get(path)
if (meta !== undefined) {
result.agenta_metadata = meta
}
return result
}
return value
}
// ============================================================================
// ATOM MEMOIZATION HELPER
// ============================================================================
/** Memoize atom factories to return the same atom instance for the same key */
function memoAtom<T>(factory: (id: string) => Atom<T>): (id: string) => Atom<T> {
const cache = new Map<string, Atom<T>>()
return (id: string) => {
let v = cache.get(id)
if (!v) {
v = factory(id)
cache.set(id, v)
}
return v
}
}
// ============================================================================
// DEFAULT ADAPTER (workflowMolecule — direct molecule access)
// ============================================================================
/**
* Build adapter backed by workflowMolecule.
*
* Data mapping:
* - workflowMolecule.selectors.configuration(id) → adapter's `parameters` (for UI display)
* - workflowMolecule.actions.updateConfiguration → adapter's reducers.update
* - workflowMolecule.selectors.parametersSchema(id) → adapter's agConfigSchema
*/
function buildWorkflowMoleculeAdapter(): ConfigSectionMoleculeAdapter {
return {
atoms: {
data: memoAtom((id: string) =>
atom((get) => {
const config = get(workflowMolecule.selectors.configuration(id))
if (!config) return null
return {parameters: config as Record<string, unknown>}
}),
),
serverData: memoAtom((id: string) =>
atom((get) => {
const config = get(workflowMolecule.selectors.serverConfiguration(id))
if (!config) return null
return {parameters: config as Record<string, unknown>}
}),
),
draft: (id: string) => workflowMolecule.atoms.draft(id),
isDirty: (id: string) => workflowMolecule.selectors.isDirty(id),
schemaQuery: memoAtom((id: string) =>
atom((get) => {
const q = get(workflowMolecule.selectors.query(id))
const rawSchema = get(workflowMolecule.selectors.parametersSchema(id))
const schema = isEntitySchema(rawSchema) ? rawSchema : null
return {
isPending: q.isPending,
isError: q.isError,
error: q.error as Error | null,
data: {agConfigSchema: schema},
}
}),
),
agConfigSchema: memoAtom((id: string) =>
atom((get) => {
const schema = get(workflowMolecule.selectors.parametersSchema(id))
return isEntitySchema(schema) ? schema : null
}),
),
},
reducers: {
update: workflowMolecule.actions.updateConfiguration as WritableAtom<
unknown,
[id: string, changes: Record<string, unknown>],
void
>,
discard: workflowMolecule.actions.discard,
},
drillIn: {
getRootData: (data: unknown) => {
const d = data as {parameters?: Record<string, unknown>} | null
const rootData =
d?.parameters && Object.keys(d.parameters).length > 0 ? d.parameters : d
return rootData
},
getRootItems: (data: unknown) => {
const d = data as {parameters?: Record<string, unknown>} | null
const params = d?.parameters
if (!params || typeof params !== "object") return []
return Object.entries(params).map(([key, value]) => ({
key,
name: key,
value,
}))
},
getValueAtPath: (data: unknown, path: DataPath) => {
const d = data as {parameters?: Record<string, unknown>} | null
if (!d?.parameters) return undefined
return getValueAtPath(d.parameters, path)
},
getChangesFromPath: (data: unknown, path: DataPath, value: unknown) => {
const d = data as {parameters?: Record<string, unknown>} | null
const params = {...(d?.parameters ?? {})}
setValueAtPath(params, path, value)
return params
},
getChangesFromRoot: (_entity: unknown, rootData: unknown, _path: DataPath) => {
// rootData is the updated parameters object
return rootData as Record<string, unknown>
},
},
selectors: {
schemaAtPath: memoAtom((key: string) => {
// key is serialized "{id}:{path}" — parse it
// But the interface takes {id, path}, so we use a wrapper below
return atom(() => null)
}) as unknown as ConfigSectionMoleculeAdapter["selectors"]["schemaAtPath"],
},
}
}
/** Wrap schemaAtPath to work with the adapter's (id, path) → atom interface */
const moleculeSchemaAtPathCache = new Map<string, Atom<unknown>>()
function moleculeSchemaAtPath(params: {id: string; path: (string | number)[]}): Atom<unknown> {
const key = `${params.id}:${params.path.join(".")}`
let cached = moleculeSchemaAtPathCache.get(key)
if (!cached) {
cached = atom((get) => {
const schema = get(workflowMolecule.selectors.parametersSchema(params.id))
if (!isEntitySchema(schema)) return null
const resolved = getSchemaAtPathUtil(schema, params.path) ?? null
if (params.path.length === 0) {
console.debug("[PlaygroundConfigSection] root schema", params.id.slice(0, 8), {
schemaType: schema?.type,
schemaHasProperties: !!schema?.properties,
schemaPropertyKeys: schema?.properties
? Object.keys(schema.properties as Record<string, unknown>)
: null,
resolvedType: resolved?.type,
resolvedPropertyKeys: resolved?.properties
? Object.keys(resolved.properties as Record<string, unknown>)
: null,
})
}
return resolved
})
moleculeSchemaAtPathCache.set(key, cached)
}
return cached
}
function buildDefaultAdapter(): ConfigSectionMoleculeAdapter {
const base = buildWorkflowMoleculeAdapter()
return {
...base,
selectors: {
schemaAtPath: moleculeSchemaAtPath,
},
}
}
const defaultAdapter = buildDefaultAdapter()
// ============================================================================
// COMPONENT
// ============================================================================
/** Evaluator preset definition */
export interface EvaluatorPresetConfig {
key: string
name: string
values: Record<string, unknown>
}
export type ConfigViewMode = "form" | "json" | "yaml"
export interface PlaygroundConfigSectionProps {
revisionId: string
disabled?: boolean
useServerData?: boolean
className?: string
/** Optional molecule adapter — defaults to workflowMolecule */
moleculeAdapter?: ConfigSectionMoleculeAdapter
/** Called when the user clicks "Refine prompt with AI" on a prompt section header */
onRefinePrompt?: (promptKey: string) => void
/** View mode controlled from parent (form/json/yaml) */
viewMode?: ConfigViewMode
/**
* Top offset (px) for the sticky section headers. Defaults to 48 to clear
* the sticky `PlaygroundVariantConfigHeader` (h-[48px], `sticky top-0`) that
* sits above the config in the full playground. In the embedded drawer that
* header is rendered non-sticky (`grow`), so there is nothing to clear —
* pass 0 there to keep the section headers flush with the scroll top instead
* of floating 48px down into the editor content.
*/
stickyHeaderTop?: number
}
function PlaygroundConfigSection({
revisionId,
disabled = false,
useServerData = false,
className,
moleculeAdapter,
onRefinePrompt,
viewMode: externalViewMode,
stickyHeaderTop = 48,
}: PlaygroundConfigSectionProps) {
const {llmProviderConfig} = useDrillInUI()
// Feedback config mode (shared with FeedbackConfigurationControl via atom)
const feedbackModeAtom = useMemo(() => feedbackConfigModeAtomFamily(revisionId), [revisionId])
const [feedbackMode, setFeedbackMode] = useAtom(feedbackModeAtom)
const mol = moleculeAdapter ?? defaultAdapter
const dispatchUpdate = useSetAtom(mol.reducers.update)
// ========== DATA ==========
const dataAtom = useMemo(() => mol.atoms.data(revisionId), [mol, revisionId])
const data = useAtomValue(dataAtom)
const serverDataAtom = useMemo(() => mol.atoms.serverData(revisionId), [mol, revisionId])
const serverData = useAtomValue(serverDataAtom)
// Schema query for loading state
const schemaQuery = useAtomValue(
useMemo(() => mol.atoms.schemaQuery(revisionId), [mol, revisionId]),
)
// Schema for model config popover
const schemaAtom = useMemo(() => mol.atoms.agConfigSchema(revisionId), [mol, revisionId])
const schema = useAtomValue(schemaAtom)
// Choose the best available data for loading checks
const activeData = useMemo(() => {
if (useServerData) return serverData
if (hasParameters(data)) return data
if (hasParameters(serverData)) return serverData
return data ?? serverData
}, [useServerData, data, serverData])
const parameters = (activeData?.parameters ?? {}) as Record<string, unknown>
// ========== ADAPTER ==========
// Build adapter with schema support, swapping data source for useServerData
const drillInAdapter = useMemo(
() =>
({
atoms: {
data: useServerData ? mol.atoms.serverData : mol.atoms.data,
draft: mol.atoms.draft,
isDirty: mol.atoms.isDirty,
},
reducers: {
update: mol.reducers.update,
discard: mol.reducers.discard,
},
drillIn: {
...mol.drillIn,
getSchemaAtPath: (path: DataPath) =>
mol.selectors.schemaAtPath({id: revisionId, path}),
},
}) as MoleculeDrillInAdapter<
{parameters?: Record<string, unknown>},
Record<string, unknown>
>,
[mol, revisionId, useServerData],
)
// ========== VIEW MODE (Form / JSON / YAML) ==========
const [internalViewMode] = useState<ConfigViewMode>("form")
const viewMode = externalViewMode ?? internalViewMode
const [rawEditorValue, setRawEditorValue] = useState("")
const [validationErrors, setValidationErrors] = useState<SchemaValidationError[]>([])
// Write raw edits directly to the draft, bypassing evaluator flatten transform.
const dispatchRawUpdate = useSetAtom(workflowMolecule.actions.update)
// Track draft state so we can detect discard (draft goes from truthy → null)
const draftAtom = useMemo(() => mol.atoms.draft(revisionId), [mol, revisionId])
const draft = useAtomValue(draftAtom)
// Strip agenta_metadata from tools before serializing for JSON/YAML view.
// This metadata is internal and should not be exposed to the user.
// Also collect metadata so it can be re-attached when the user saves edits.
// Stabilize via serialized key to prevent infinite re-render loops when the
// parameters object reference changes but content is identical (e.g., during
// entity loading in URL-driven drawer initialization).
const parametersKey = JSON.stringify(parameters)
const {displayParameters, metadataMap} = useMemo(() => {
return {
displayParameters: stripAgentaMetadata(parameters),
metadataMap: collectAgentaMetadata(parameters),
}
}, [parametersKey])
// Derive a stable flag so the effect fires when draft is discarded (becomes null)
const isDraftEmpty = draft === null || draft === undefined
// Track discard events to force re-mount of Form/YAML editors whose internal
// state (Lexical editor, local control state) may not fully reset via prop
// changes alone. Computed during render to avoid useEffect/setState loops.
const discardVersionRef = useRef(0)
const prevIsDraftEmptyRef = useRef(isDraftEmpty)
if (isDraftEmpty && !prevIsDraftEmptyRef.current) {
discardVersionRef.current += 1
}
prevIsDraftEmptyRef.current = isDraftEmpty
// Eagerly sync rawEditorValue during render when entering a raw mode.
// Without this, switching Form → YAML/JSON after a revision change renders
// the SharedEditor with stale/empty content for one frame until the useEffect
// fires. The code editor may not properly re-hydrate from that empty initial state.
const prevViewModeRef = useRef(viewMode)
if (viewMode !== "form" && prevViewModeRef.current !== viewMode) {
const next =
viewMode === "yaml"
? (() => {
try {
return yaml.dump(displayParameters, {indent: 2, lineWidth: -1})
} catch {
return JSON.stringify(displayParameters, null, 2)
}
})()
: JSON.stringify(displayParameters, null, 2)
// Only update if the content is actually different to avoid unnecessary re-renders
if (next !== rawEditorValue) {
setRawEditorValue(next)
}
}
prevViewModeRef.current = viewMode
// Track whether the latest displayParameters change was caused by the user
// editing in this raw editor. When true, the sync effect skips re-serializing
// to avoid overwriting the editor content (which kills focus/cursor).
const isLocalEditRef = useRef(false)
// Keep editor value in sync when parameters change from an external source
// (e.g., form edits in another mode, draft discard, revision switch) while
// already in a raw mode. Skips when the change originated from the user's
// own typing in this editor to avoid a re-serialize → focus-loss loop.
useEffect(() => {
if (isLocalEditRef.current) {
isLocalEditRef.current = false
return
}
if (viewMode === "json") {
setRawEditorValue(JSON.stringify(displayParameters, null, 2))
} else if (viewMode === "yaml") {
try {
setRawEditorValue(yaml.dump(displayParameters, {indent: 2, lineWidth: -1}))
} catch {
setRawEditorValue(JSON.stringify(displayParameters, null, 2))
}
}
setValidationErrors([])
}, [viewMode, isDraftEmpty, displayParameters])
const handleRawEditorChange = useCallback(
(newValue: string) => {
setRawEditorValue(newValue)
try {
const parsed =
viewMode === "yaml"
? (yaml.load(newValue) as Record<string, unknown>)
: JSON.parse(newValue)
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
// Re-attach agenta_metadata that was stripped for display
const withMetadata = reattachAgentaMetadata(parsed, metadataMap) as Record<
string,
unknown
>
// Mark that the next displayParameters change is from our own edit
isLocalEditRef.current = true
dispatchRawUpdate(revisionId, {data: {parameters: withMetadata}})
// Validate against parameters schema
const result = validateConfigAgainstSchema(
parsed as Record<string, unknown>,
schema as Record<string, unknown> | null,
)
setValidationErrors(result.errors)
}
} catch {
// Invalid syntax — don't emit
}
},
[dispatchRawUpdate, revisionId, viewMode, schema, metadataMap],
)
// ========== COLLAPSE STATE ==========
const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({
advanced_settings: true,
})
const toggleSection = useCallback((key: string) => {
setCollapsedSections((prev) => ({...prev, [key]: !prev[key]}))
}, [])
// ========== COMBINED MODEL / FALLBACK / RETRY CONFIG POPOVER ==========
const [isModelConfigOpen, setIsModelConfigOpen] = useState(false)
const [activeConfigureTab, setActiveConfigureTab] = useState<ConfigureTabKey>("model")
const [fallbackDetail, setFallbackDetail] = useState<FallbackDetailState | null>(null)
// Extract model + LLM config info from prompt section.
//
// Supports two schema shapes:
// - Legacy: parameters.prompt.{messages, llm_config.{model, temperature, ...}}
// - Canonical (llm catalog): parameters.{messages, llms[{model, temperature, ...}]}
//
// For the canonical shape, the root parameters object IS the prompt equivalent.
const promptModelInfo = useMemo(() => {
const hasNestedPrompt = !!parameters.prompt
const hasRootMessages = Array.isArray(parameters.messages)
const promptValue = hasNestedPrompt
? (parameters.prompt as Record<string, unknown>)
: hasRootMessages
? parameters
: null
if (!promptValue) return null
const promptSchema = schema?.properties
? hasNestedPrompt
? ((schema.properties as Record<string, EntitySchemaProperty>).prompt ?? null)
: hasRootMessages
? schema
: null
: null
const modelSchema = getModelSchema(promptSchema as EntitySchemaProperty | null)
const optionsResult = getOptionsFromSchema(modelSchema)
const modelOptions = optionsResult?.options ?? []
const llmConfigValue = getLLMConfigValue(promptValue)
const currentModel = llmConfigValue?.model as string | undefined
// Extract LLM config property schemas for sliders
const llmConfigProps = getLLMConfigProperties(promptSchema as EntitySchemaProperty | null)
const promptSchemaProps = ((promptSchema as EntitySchemaProperty | null)?.properties ??
{}) as Record<string, EntitySchemaProperty>
return {
modelSchema,
modelOptions,
currentModel,
promptValue,
promptSchemaProps,
llmConfigValue,
llmConfigProps,
isRootLevel: !hasNestedPrompt && hasRootMessages,
}
}, [parameters, schema])
// Helper to update a key inside the LLM config.
// Supports three structures:
// - Legacy nested: parameters.prompt.llm_config.{key}
// - Legacy flat: parameters.prompt.{key}
// - Canonical: parameters.llms[0].{key}
const updatePromptLLMConfigKey = useCallback(
(key: string, newValue: unknown) => {
if (disabled || !activeData) return
// Canonical: llms array at root level
if (Array.isArray(parameters.llms)) {
const currentLlms = parameters.llms as Record<string, unknown>[]
const updatedFirst = updateConfigKey(currentLlms[0], key, newValue)
dispatchUpdate(revisionId, {
...parameters,
llms: [updatedFirst, ...currentLlms.slice(1)],
})
return
}
// Canonical/root-level prompt without an llms array.
if (promptModelInfo?.isRootLevel) {
const nextParameters = updateConfigKey(parameters, key, newValue)
dispatchUpdate(revisionId, nextParameters)
return
}
// Legacy: prompt.llm_config or prompt.{key}
const currentPrompt = (parameters.prompt as Record<string, unknown>) || {}
const hasNestedLLMConfig = currentPrompt.llm_config || currentPrompt.llmConfig
let updatedPrompt
if (hasNestedLLMConfig) {
const llmConfigKey = currentPrompt.llm_config ? "llm_config" : "llmConfig"
updatedPrompt = {
...currentPrompt,
[llmConfigKey]: updateConfigKey(
currentPrompt[llmConfigKey] as Record<string, unknown> | undefined,
key,
newValue,
),
}
} else {
updatedPrompt = updateConfigKey(currentPrompt, key, newValue)
}
dispatchUpdate(revisionId, {
...parameters,
prompt: updatedPrompt,
})
},
[disabled, activeData, parameters, revisionId, dispatchUpdate, promptModelInfo],
)
const updatePromptRootFields = useCallback(
(changes: Record<string, unknown>) => {
if (disabled || !activeData || !promptModelInfo) return
const applyChanges = (base: Record<string, unknown>) => {
const next = {...base}
for (const [key, value] of Object.entries(changes)) {
if (value === null || value === undefined) {
delete next[key]
} else {
next[key] = value
}
}
return next
}
if (promptModelInfo.isRootLevel) {
dispatchUpdate(revisionId, applyChanges(parameters))
return
}
const currentPrompt = (parameters.prompt as Record<string, unknown>) || {}
dispatchUpdate(revisionId, {
...parameters,
prompt: applyChanges(currentPrompt),
})
},
[disabled, activeData, promptModelInfo, dispatchUpdate, revisionId, parameters],
)
const updatePromptRootField = useCallback(
(key: string, nextValue: unknown) => {
updatePromptRootFields({[key]: nextValue})
},
[updatePromptRootFields],
)
const fallbackConfigs = useMemo(() => {
const raw = promptModelInfo?.promptValue.fallback_configs
return Array.isArray(raw) ? (raw as Record<string, unknown>[]) : []
}, [promptModelInfo])
const [fallbackConfigKeys, setFallbackConfigKeys] = useState<string[]>([])
useEffect(() => {
setFallbackConfigKeys((currentKeys) => {
if (currentKeys.length === fallbackConfigs.length) return currentKeys
if (currentKeys.length > fallbackConfigs.length) {
return currentKeys.slice(0, fallbackConfigs.length)
}
return [
...currentKeys,
...Array.from(
{length: fallbackConfigs.length - currentKeys.length},
createFallbackConfigKey,
),
]
})
}, [fallbackConfigs.length])
const retryConfig = useMemo(() => {
const raw = promptModelInfo?.promptValue.retry_config
return raw && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: {}
}, [promptModelInfo])
const effectiveRetryConfig = useMemo(
() => ({
max_retries:
typeof retryConfig.max_retries === "number"
? retryConfig.max_retries
: DEFAULT_RETRY_CONFIG.max_retries,
base_delay:
typeof retryConfig.base_delay === "number"
? retryConfig.base_delay
: DEFAULT_RETRY_CONFIG.base_delay,
}),
[retryConfig],
)
const hasPromptExtensionFields = useMemo(() => {
if (!promptModelInfo) return false
return PROMPT_EXTENSION_KEYS.some(
(key) => key in promptModelInfo.promptSchemaProps || key in promptModelInfo.promptValue,
)
}, [promptModelInfo])
useEffect(() => {
if (!hasPromptExtensionFields && activeConfigureTab !== "model") {
setActiveConfigureTab("model")
setFallbackDetail(null)
}
}, [activeConfigureTab, hasPromptExtensionFields])
const fallbackPolicyOptions = useMemo(() => {
const schema = promptModelInfo?.promptSchemaProps.fallback_policy as
| {enum?: unknown[]; "x-ag-metadata"?: Record<string, {description?: string}>}
| undefined
const metadata = schema?.["x-ag-metadata"] ?? {}
const enumValues = schema?.enum
const values =
Array.isArray(enumValues) && enumValues.length > 0
? enumValues.map((v) => String(v))
: FALLBACK_POLICY_OPTIONS.map((o) => o.value)
return values.map((value) => ({
label: formatLabel(value),
value,
description: metadata[value]?.description,
}))
}, [promptModelInfo])
const retryPolicyOptions = useMemo(() => {
const schema = promptModelInfo?.promptSchemaProps.retry_policy as
| {enum?: unknown[]; "x-ag-metadata"?: Record<string, {description?: string}>}
| undefined
const metadata = schema?.["x-ag-metadata"] ?? {}
const enumValues = schema?.enum
const values =
Array.isArray(enumValues) && enumValues.length > 0
? enumValues.map((v) => String(v))
: RETRY_POLICY_OPTIONS.map((o) => o.value)
return values.map((value) => ({
label: formatLabel(value),
value,
description: metadata[value]?.description,
}))
}, [promptModelInfo])
const fallbackModelOptions = useMemo(
() => [
...(llmProviderConfig?.extraOptionGroups ?? []),
...(promptModelInfo?.modelOptions ?? []),
],
[llmProviderConfig?.extraOptionGroups, promptModelInfo?.modelOptions],
)
const handleRetryConfigFieldChange = useCallback(
(key: "max_retries" | "base_delay", nextValue: number | null) => {
const nextMaxRetries =
key === "max_retries"
? nextValue
: typeof retryConfig.max_retries === "number"
? retryConfig.max_retries
: DEFAULT_RETRY_CONFIG.max_retries
if (typeof nextMaxRetries !== "number" || nextMaxRetries <= 0) {
updatePromptRootFields({
retry_config: null,
retry_policy: null,
})
return
}
const nextBaseDelay =
key === "base_delay"
? nextValue
: typeof retryConfig.base_delay === "number"
? retryConfig.base_delay
: DEFAULT_RETRY_CONFIG.base_delay
const nextRetryConfig: Record<string, unknown> = {
max_retries: nextMaxRetries,
}
if (typeof nextBaseDelay === "number") {
nextRetryConfig.base_delay = nextBaseDelay
}
updatePromptRootField("retry_config", nextRetryConfig)
},
[retryConfig, updatePromptRootField, updatePromptRootFields],
)
const handleAddFallbackModel = useCallback(() => {
const primaryModel =
typeof promptModelInfo?.llmConfigValue?.model === "string"
? promptModelInfo.llmConfigValue.model
: ""
setFallbackDetail({
mode: "new",
index: null,
draft: {model: primaryModel || "gpt-4o-mini"},
})
}, [promptModelInfo])
const handleEditFallbackModel = useCallback(
(index: number) => {
setFallbackDetail({
mode: "edit",
index,
draft: {...(fallbackConfigs[index] ?? {})},
})
},
[fallbackConfigs],
)
const handleFallbackDetailChange = useCallback((key: string, nextValue: unknown) => {
setFallbackDetail((current) => {
if (!current) return current
const nextDraft = {...current.draft}
if (nextValue === null || nextValue === undefined) {
delete nextDraft[key]
} else {
nextDraft[key] = nextValue
}
return {...current, draft: nextDraft}
})
}, [])
const handleCommitFallbackDetail = useCallback(() => {
if (!fallbackDetail) return
const nextConfigs =
fallbackDetail.mode === "edit" && fallbackDetail.index !== null
? fallbackConfigs.map((config, configIndex) =>
configIndex === fallbackDetail.index ? fallbackDetail.draft : config,
)
: [...fallbackConfigs, fallbackDetail.draft]
updatePromptRootField("fallback_configs", nextConfigs.length > 0 ? nextConfigs : null)
setFallbackDetail(null)
}, [fallbackConfigs, fallbackDetail, updatePromptRootField])
const handleRemoveFallbackModel = useCallback(
(index: number) => {
const nextConfigs = fallbackConfigs.filter((_, configIndex) => configIndex !== index)
setFallbackConfigKeys((currentKeys) =>
currentKeys.filter((_, configIndex) => configIndex !== index),
)
if (nextConfigs.length === 0) {
updatePromptRootFields({