-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.jsx
More file actions
5258 lines (4839 loc) · 304 KB
/
App.jsx
File metadata and controls
5258 lines (4839 loc) · 304 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
import React, { useState, useEffect, useRef, useCallback } from "react";
// ── Local server ──────────────────────────────────────────────────────────────
const API = "http://localhost:3001";
// ── Constants ─────────────────────────────────────────────────────────────────
const AGENT_TYPES = [
{ value: "customer", label: "Customer-facing" },
{ value: "internal", label: "Internal (employees)" },
];
const TONES = ["casual", "formal", "neutral"];
const METRICS = [
{ id: "coherence", label: "Coherence", desc: "Response is easy to understand, no grammatical errors" },
{ id: "completeness", label: "Completeness", desc: "Response includes all essential information" },
{ id: "conciseness", label: "Conciseness", desc: "Response is brief but comprehensive" },
{ id: "latency", label: "Latency", desc: "Latency in ms from request to response" },
{ id: "instruction_following", label: "Instruction Following", desc: "Available in API/CLI only — not in Salesforce Testing Center UI", locked: true },
{ id: "factuality", label: "Factuality", desc: "Available in API/CLI only — not in Salesforce Testing Center UI", locked: true },
];
// ── Salesforce Lightning Design Tokens ───────────────────────────────────────
const C = {
bg: "#010409",
surface: "#0d1117",
surfaceAlt: "#161b22",
border: "#30363d",
borderFocus: "#388bfd",
text: "#e6edf3",
textWeak: "#8b949e",
textWeaker: "#484f58",
brand: "#1f6feb",
brandDark: "#1158c7",
brandLight: "#0d2149",
gold: "#e3b341",
goldBg: "#2d1f00",
success: "#3fb950",
successBg: "#0d2a14",
warning: "#d29922",
warningBg: "#2b2000",
error: "#f85149",
errorBg: "#2d1010",
shadow: "0 2px 8px rgba(0,0,0,0.4)",
shadowMd: "0 4px 16px rgba(0,0,0,0.5)",
radius: "6px",
radiusMd: "10px",
};
// ── AI Prompts ────────────────────────────────────────────────────────────────
// Official reference: https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-reference.html
//
// agentSpec required: agentType, companyName, companyDescription, role, topics
// agentSpec optional: maxNumOfTopics (default 5), agentUser, enrichLogs (default false),
// tone (casual|formal|neutral, default casual),
// promptTemplateName, groundingContext
// agentType valid values: "customer" | "internal" ONLY
// tone valid values: "casual" | "formal" | "neutral" ONLY
//
// testSpec required: name, subjectType (AGENT), subjectName, testCases
// testSpec optional: description, subjectVersion
// testCase required: utterance, expectedTopic, expectedActions, expectedOutcome
// testCase optional: contextVariables, customEvaluations, conversationHistory, metrics
const AGENT_SPEC_PROMPT = `You are an expert Salesforce Agentforce architect. Generate a valid agentSpec.yaml.
Reference: https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-reference.html
EXACT YAML structure (all fields from official reference):
agentType: <"customer" or "internal" ONLY — no other values>
companyName: <company name>
companyDescription: <natural language description of the company>
role: <natural language description of agent role and tasks>
tone: <"casual", "formal", or "neutral" ONLY>
maxNumOfTopics: <EXACT integer provided — no more, no less>
enrichLogs: false
topics:
- name: <PascalCase, no spaces — e.g. OrderTracking, EmployeeScheduling>
description: <specific description, hint at which Salesforce actions to use>
OPTIONAL fields to include if relevant (from official reference):
# agentUser: <username@org.com> — assigns agent to a user in the org
# promptTemplateName: <ApiName> — custom prompt template API name
# groundingContext: <context string> — context added to prompts with custom template
CRITICAL RULES:
- agentType MUST be "customer" or "internal" — never "customer_facing", "sales", "service", etc.
- tone MUST be "casual", "formal", or "neutral" — no other values
- Generate EXACTLY maxNumOfTopics topic blocks — hard constraint
- Topic names: PascalCase, no spaces, descriptive (e.g. OrderTracking not Order_Tracking)
- Topics must be distinct and non-overlapping
- Output ONLY valid YAML, no markdown fences, start with "agentType:"`;
const AGENT_SPEC_REFINE_PROMPT = `You are an expert Salesforce Agentforce architect. Refine an existing agentSpec.yaml.
Reference: https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-reference.html
CRITICAL: agentType must be "customer" or "internal" ONLY. tone must be "casual", "formal", or "neutral" ONLY. Preserve maxNumOfTopics count exactly.
Output ONLY the complete updated YAML. No markdown fences. Start with "agentType:".`;
// Full testSpec structure reference (from official Salesforce docs):
// https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-test-spec.html
// https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-test-customize.html
//
// COMPLETE testCase structure:
// utterance (required) - natural language user input
// expectedTopic (required) - topic API name (GenAiPlugin)
// expectedActions (required) - action API names (GenAiFunction)
// expectedOutcome (required) - natural language expected result
// contextVariables (optional) - Service agent context vars (MessagingSession fields)
// - name: EndUserLanguage
// value: Spanish
// customEvaluations (optional) - test response for specific strings/numbers
// - label: "Check order ID in response"
// JSONPath: "$.actions[?(@.name=='GetOrder')].output.orderId"
// operator: equals # equals | notEquals | greaterThan | greaterThanOrEquals | lessThan | lessThanOrEquals | contains
// expectedValue: "12345"
// conversationHistory (optional) - multi-turn context
// - role: user # user | agent
// message: "Hi I need help with my order"
// - role: agent
// message: "Sure! What's your order number?"
// topic: OrderManagement # required when role is agent
// metrics (optional but recommended) - inside each testCase
// - name: coherence | completeness | conciseness | latency | instruction_following | factuality
const TESTSPEC_FORMAT_RULES = `
CRITICAL FORMAT RULES — Salesforce Agentforce testSpec.yaml
Sources: https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-test-spec.html
https://developer.salesforce.com/docs/ai/agentforce/guide/agent-dx-test-customize.html
═══════════════════════════════════════════════════════════════════════════════════════════════
STANDARD testSpec.yaml structure (used by sf agent generate test-spec):
name: <string>
description: <string>
subjectType: AGENT
subjectName: <agentApiName>
testCases:
- utterance: <string>
expectedTopic: <topicApiName>
expectedActions:
- <actionApiName>
expectedOutcome: <natural language expected outcome>
contextVariables: # optional — for Service agents with context variables
- name: <variableName> # API name from MessagingSession object
value: "<string>" # ALWAYS a string — never boolean/number (e.g. "true" not true)
customEvaluations: # optional — only when explicitly requested
- label: "<descriptive label>"
JSONPath: "<JSONPath to action output field, e.g. $.generatedData.outcome>"
operator: contains # equals | contains | startswith | endswith | greater_than | less_than
expectedValue: "<expected value>"
conversationHistory: # optional — for multi-turn context
- role: user
message: <string>
- role: agent
message: <string>
topic: <topicApiName> # required for agent messages
metrics: # CRITICAL — NO 'name:' key, just the bare metric value
- coherence
- completeness
- conciseness
- output_latency_milliseconds
# ⚠️ DO NOT add instruction_following or factuality unless explicitly in the selected metrics list below
RULES:
1. subjectType MUST always be AGENT
2. contextVariables values are ALWAYS strings — "true" not true, "42" not 42
3. customEvaluations: only include if the user explicitly requested them
4. metrics: include only metrics from the user's selection
5. conversationHistory: agent messages MUST have a topic field
6. Output ONLY valid YAML, start with "name:", no markdown fences
`;
const TEST_FROM_AGENT_PROMPT = `You are an expert Salesforce Agentforce QA engineer generating testSpec.yaml files.
${TESTSPEC_FORMAT_RULES}
The .agent file contains topics, actions, instructions, variables, and config.
Extract: developer_name (→ subjectName), topic names, action names.
Generate ${'{'}testsPerTopic{'}'} test cases per topic:
- 1 happy path: direct utterance, correct topic + action, positive outcome
- 1 edge/error: ambiguous or auth-required, may include conversationHistory
- Additional if testsPerTopic > 2: varied scenarios (off-topic, multi-turn, boundary)
EXAMPLE test case (use EXACTLY this structure):
testCases:
- utterance: "I want to cancel my flight"
expectedTopic: cancellation_management
expectedActions:
- verify_passenger
expectedOutcome: Agent asks for booking reference and email to verify identity
contextVariables: []
customEvaluations: []
conversationHistory: []
metrics:
- coherence
- completeness
- conciseness
- output_latency_milliseconds
❌ NEVER use: - name: coherence (wrong — no 'name:' key)
❌ NEVER add instruction_following or factuality unless they appear in the selected metrics list
✅ ALWAYS use: - coherence (correct — bare value only)
Output ONLY valid YAML starting with "name:".`;
const TEST_APPEND_FROM_AGENT_PROMPT = `You are an expert Salesforce Agentforce QA engineer appending test cases to an existing testSpec.yaml.
${TESTSPEC_FORMAT_RULES}
Return the COMPLETE updated testSpec.yaml with new test cases appended.
Do NOT modify existing test cases.
New test cases must use the correct expectation[] structure (not old flat format).
Output ONLY valid YAML starting with "name:".`;
const TEST_FROM_GHERKIN_PROMPT = `You are an expert Salesforce Agentforce QA engineer converting Gherkin BDD scenarios into testSpec.yaml.
${TESTSPEC_FORMAT_RULES}
Gherkin mapping:
- "Given ..." → conversationHistory (role: user/agent messages)
- "When user says" → inputs.utterance
- "Then agent ..." → expectation[{name: bot_response_rating, expectedValue: ...}]
- "And response contains X" → expectation[{name: string_comparison, parameter: [{name:actual,value:$.response,isReference:true},{name:operator,value:contains},{name:expected,value:X}]}]
- Infer topic and action from the agent file topics list provided.
Output ONLY valid YAML starting with "name:".`;
const TEST_APPEND_FROM_GHERKIN_PROMPT = `You are an expert Salesforce Agentforce QA engineer appending Gherkin-derived test cases to an existing testSpec.yaml.
${TESTSPEC_FORMAT_RULES}
Return the COMPLETE updated testSpec.yaml with new test cases appended.
Do NOT modify existing test cases.
Gherkin mapping: "Given" → conversationHistory, "When" → utterance, "Then/And" → bot_response_rating / string_comparison expectation.
Output ONLY valid YAML starting with "name:".`;
const TEST_FROM_AI_EVAL_PROMPT = `You are an expert Salesforce Agentforce QA engineer converting AiEvaluationDefinition XML into testSpec.yaml.
${TESTSPEC_FORMAT_RULES}
XML → YAML field mapping:
- AiEvaluationDefinition.name → name
- AiEvaluationDefinition.description → description
- subjectType: AGENT (always)
- AiEvaluationDefinition.subjectName → subjectName
- Each AiEvaluationTestCase → testCases entry with inputs + expectation[] structure
- testCase.inputs.utterance → inputs.utterance
- testCase.inputs.contextVariable[] → inputs.contextVariables (variableName/variableValue — values always strings)
- testCase.inputs.conversationHistory[]→ inputs.conversationHistory (role/message/topic)
- testCase.expectation[] → expectation[] keep name/expectedValue/parameter as-is
Output ONLY valid YAML starting with "name:".
`;
// ── Helpers ───────────────────────────────────────────────────────────────────
const parseTopics = yaml => [...(yaml||"").matchAll(/- name:\s*(.+)/g)].map(m => m[1].trim());
// Parse topics from .agent file — supports Salesforce XML format and plain text
const parseAgentTopics = content => {
if (!content) return [];
const results = new Set();
// Primary: YAML custom format "topic booking_information:" (your .agent format)
for (const m of content.matchAll(/^topic\s+([A-Za-z0-9_]+)\s*:/gm)) results.add(m[1].trim());
// Secondary: XML metadata format
if (results.size === 0) {
for (const m of content.matchAll(/<topicApiName>([^<]+)<\/topicApiName>/g)) results.add(m[1].trim());
for (const m of content.matchAll(/<apiName>([^<]+)<\/apiName>/g)) results.add(m[1].trim());
}
// Tertiary: JSON
if (results.size === 0)
for (const m of content.matchAll(/"(?:apiName|topicApiName)":\s*"([A-Za-z0-9_]+)"/g)) results.add(m[1].trim());
// Exclude non-topic keywords (entry points, farewell, etc.)
const EXCLUDE = new Set(["farewell", "greet_and_route", "start_agent"]);
return [...results].filter(t => t.length > 1 && !EXCLUDE.has(t));
};
const parseSubject = yaml => (yaml?.match(/subjectName:\s*(.+)/)||[])[1]?.trim() || "";
const parseAgentDeveloperName = content =>
(content?.match(/developer_name:\s*["']?([^"'\n]+)["']?/)||
content?.match(/config:\s*\n\s+developer_name:\s*["']?([^"'\n]+)["']?/)||[])[1]?.trim() || "";
async function callAI(system, userMsg) {
const res = await fetch(`${API}/ai`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ system, userMsg }),
});
const data = await res.json();
if (!data.ok) throw new Error(data.error || "Server error");
return data.result || "";
}
async function fetchFiles(route, filterFn) {
const r = await fetch(`${API}${route}`);
const text = await r.text();
let d;
try { d = JSON.parse(text); } catch (_) { throw new Error(`Server error on ${route} — is tdad-server.js running?`); }
if (!d.ok) throw new Error(d.error);
return filterFn ? d.files.filter(filterFn) : d.files;
}
async function fetchSpecs(filterFn) { return fetchFiles("/files/specs", filterFn); }
// ── Hooks ─────────────────────────────────────────────────────────────────────
function useServerStatus() {
const [status, setStatus] = useState(null);
const check = useCallback(async () => {
try {
const r = await fetch(`${API}/status`, { signal: AbortSignal.timeout(2000) });
const d = await r.json();
setStatus(d.ok ? d : false);
} catch (_) { setStatus(false); }
}, []);
useEffect(() => { check(); const t = setInterval(check, 8000); return () => clearInterval(t); }, [check]);
return { status, refresh: check };
}
function useIsMobile() {
const [m, setM] = useState(window.innerWidth < 768);
useEffect(() => { const h = () => setM(window.innerWidth < 768); window.addEventListener("resize", h); return () => window.removeEventListener("resize", h); }, []);
return m;
}
// ── Design Components ─────────────────────────────────────────────────────────
function Card({ children, style = {} }) {
return (
<div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: C.radiusMd, boxShadow: C.shadow, ...style }}>
{children}
</div>
);
}
function CardHeader({ title, subtitle, icon, action }) {
return (
<div style={{ padding: "16px 20px", borderBottom: `1px solid ${C.border}`, display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px" }}>
<div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
{icon && <span style={{ fontSize: "18px" }}>{icon}</span>}
<div>
<div style={{ fontWeight: "700", fontSize: "14px", color: C.text }}>{title}</div>
{subtitle && <div style={{ fontSize: "12px", color: C.textWeak, marginTop: "1px" }}>{subtitle}</div>}
</div>
</div>
{action}
</div>
);
}
function Btn({ children, onClick, disabled, variant = "brand", size = "md", style = {} }) {
const variants = {
brand: { bg: C.brand, color: "#fff", border: C.brand, hoverBg: C.brandDark },
outline: { bg: "transparent", color: C.brand, border: C.brand, hoverBg: C.brandLight },
neutral: { bg: C.surface, color: C.text, border: C.border, hoverBg: C.surfaceAlt },
success: { bg: C.success, color: "#fff", border: C.success, hoverBg: "#1d6135" },
danger: { bg: C.error, color: "#fff", border: C.error, hoverBg: "#8e0312" },
};
const sizes = { sm: "6px 12px", md: "8px 16px", lg: "10px 20px" };
const v = variants[variant];
return (
<button onClick={onClick} disabled={disabled}
style={{ background: v.bg, color: v.color, border: `1px solid ${v.border}`, padding: sizes[size],
borderRadius: C.radius, fontSize: size === "sm" ? "12px" : "13px", fontWeight: "600",
cursor: disabled ? "not-allowed" : "pointer", fontFamily: "inherit",
opacity: disabled ? 0.4 : 1, display: "inline-flex", alignItems: "center", gap: "6px",
transition: "all 0.15s", ...style }}>
{children}
</button>
);
}
function Badge({ children, color = "brand" }) {
const colors = {
brand: { bg: C.brandLight, text: C.brandDark },
success: { bg: C.successBg, text: C.success },
warning: { bg: C.warningBg, text: "#b75000" },
error: { bg: C.errorBg, text: C.error },
neutral: { bg: C.surfaceAlt, text: C.textWeak },
};
const c = colors[color] || colors.brand;
return (
<span style={{ background: c.bg, color: c.text, padding: "2px 8px", borderRadius: "999px",
fontSize: "11px", fontWeight: "600", display: "inline-block" }}>
{children}
</span>
);
}
function Alert({ type = "info", children }) {
const map = {
info: { bg: C.brandLight, border: C.brand, color: C.text, icon: "ℹ️" },
success: { bg: C.successBg, border: C.success, color: C.success, icon: "✅" },
warning: { bg: C.warningBg, border: C.warning, color: "#b75000", icon: "⚠️" },
error: { bg: C.errorBg, border: C.error, color: C.error, icon: "❌" },
};
const m = map[type];
return (
<div style={{ background: m.bg, border: `1px solid ${m.border}`, borderRadius: C.radius,
padding: "10px 14px", fontSize: "13px", color: m.color,
display: "flex", gap: "8px", alignItems: "flex-start" }}>
<span>{m.icon}</span><div>{children}</div>
</div>
);
}
const inputStyle = {
width: "100%", background: C.surface, border: `1px solid ${C.border}`, color: C.text,
padding: "8px 12px", borderRadius: C.radius, fontFamily: "inherit", fontSize: "13px",
outline: "none", transition: "border-color 0.15s", boxSizing: "border-box",
};
const labelStyle = {
color: C.textWeak, fontSize: "12px", fontWeight: "600", marginBottom: "5px",
display: "block", textTransform: "uppercase", letterSpacing: "0.5px",
};
function Field({ label, required, children, hint }) {
return (
<div>
<label style={labelStyle}>{label}{required && <span style={{ color: C.error, marginLeft: "3px" }}>*</span>}</label>
{children}
{hint && <div style={{ fontSize: "11px", color: C.textWeak, marginTop: "3px" }}>{hint}</div>}
</div>
);
}
function Spinner({ size = 14 }) {
return <span style={{ width: size, height: size, border: `2px solid ${C.brand}`, borderTopColor: "transparent", borderRadius: "50%", display: "inline-block", animation: "spin 0.6s linear infinite", flexShrink: 0 }} />;
}
// ── YAML tokenizer (shared) ──────────────────────────────────────────────────
// ── AgentScript (.agent) tokenizer ──────────────────────────────────────────
const agentTokenize = line => {
const t = line.trimStart();
if (t.startsWith("#")) return "#6e7681"; // comment — grey
if (/^(config|system|variables|start_agent|topic)/.test(t)) return "#ff7b72"; // block keywords — red
if (/^(topic|start_agent)\s+\w+:/.test(t)) return "#ffa657"; // topic name — orange
if (t.startsWith(" messages:") || t.startsWith(" instructions:") || t.startsWith(" reasoning:") || t.startsWith(" actions:")) return "#7ee787"; // section keys — green
if (t.startsWith(" instructions:") || t.startsWith(" actions:")) return "#7ee787";
if (t.startsWith("description:") || t.startsWith(" description:") || t.startsWith(" description:")) return "#8b949e";
if (/^\s+\w+:\s+@/.test(t)) return "#79c0ff"; // action ref — blue
if (/^\s+@/.test(t)) return "#d2a8ff"; // @ references — purple
if (/^\s+go_\w+:|^\s+\w+_\w+:/.test(t)) return "#79c0ff"; // action names — blue
if (t.startsWith(" developer_name:") || t.startsWith(" agent_type:") || t.startsWith(" agent_description:")) return "#ffa657";
if (t.startsWith(" welcome:") || t.startsWith(" error:")) return "#a5d6ff";
if (/^\s+mutable\s/.test(t) || /^\s+\w+:\s+(string|boolean|int)/.test(t)) return "#d2a8ff"; // type declarations
if (t.startsWith(" - ") || t.startsWith(" - ")) return "#e6edf3";
if (t.includes(":") && !t.startsWith(" ")) return "#ff7b72"; // top-level keys
if (t.includes(": ")) return "#8b949e"; // general key:value
return "#e6edf3";
};
// ── AgentScript (.agent) tokenizer ─────────────────────────────────────────
const yamlTokenize = line => {
const t = line.trimStart();
if (t.startsWith("#")) return "#6e7681";
if (t.startsWith("agentType:") || t.startsWith("subjectType:")) return "#ff7b72";
if (t.startsWith("name:") || t.startsWith("subjectName:")) return "#ffa657";
if (t.startsWith("topics:") || t.startsWith("testCases:") || t.startsWith("metrics:")) return "#7ee787";
if (t.startsWith("- name:")) return "#79c0ff";
if (t.startsWith("utterance:")) return "#d2a8ff";
if (t.startsWith("expectedTopic:")) return "#ffa657";
if (t.startsWith("expectedOutcome:") || t.startsWith("expectedActions:")) return "#7ee787";
if (t.startsWith(" - name: ")) return "#79c0ff";
if (t.match(/^ - [A-Z]/)) return "#79c0ff";
if (t.includes(":")) {
const key = t.split(":")[0].trim();
if (["companyName","companyDescription","role","tone","maxNumOfTopics","enrichLogs",
"description","customEvaluations","conversationHistory"].includes(key)) return "#8b949e";
}
return "#8b949e";
};
// ── YAML Viewer ───────────────────────────────────────────────────────────────
function YamlViewer({ code, maxHeight = "400px" }) {
if (!code) return null;
return (
<div style={{ background: "#0d1117", border: `1px solid ${C.border}`, borderRadius: C.radius,
padding: "14px 16px", overflowY: "auto", maxHeight,
fontFamily: "'JetBrains Mono', 'Fira Code', monospace", fontSize: "12px", lineHeight: "1.8" }}>
{code.split("\n").map((line, i) => (
<div key={i} style={{ color: yamlTokenize(line), whiteSpace: "pre-wrap", wordBreak: "break-word" }}>{line || " "}</div>
))}
</div>
);
}
// ── YAML Editor (syntax-highlighted + editable) ───────────────────────────────
function YamlEditor({ value, onChange, minHeight = "420px" }) {
const textareaRef = useRef(null);
const backdropRef = useRef(null);
// Sync scroll between textarea and backdrop
const syncScroll = () => {
if (backdropRef.current && textareaRef.current) {
backdropRef.current.scrollTop = textareaRef.current.scrollTop;
backdropRef.current.scrollLeft = textareaRef.current.scrollLeft;
}
};
const sharedStyle = {
fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
fontSize: "12px",
lineHeight: "1.8",
whiteSpace: "pre",
overflowWrap: "normal",
wordBreak: "normal",
overflowX: "auto",
padding: "14px 16px",
margin: 0,
border: "none",
outline: "none",
width: "100%",
boxSizing: "border-box",
minHeight,
tabSize: 2,
};
return (
<div style={{ position: "relative", background: "#0d1117", border: `1px solid ${C.gold}`,
borderRadius: C.radius, overflow: "hidden" }}>
{/* Highlighted backdrop */}
<div ref={backdropRef} aria-hidden="true"
style={{ ...sharedStyle, position: "absolute", top: 0, left: 0, height: "100%",
overflowY: "hidden", overflowX: "hidden", pointerEvents: "none", color: "transparent" }}>
{(value + "\n").split("\n").map((line, i) => (
<div key={i} style={{ color: yamlTokenize(line), minHeight: "1.8em" }}>{line || " "}</div>
))}
</div>
{/* Editable textarea on top */}
<textarea
ref={textareaRef}
value={value}
onChange={e => onChange(e.target.value)}
onScroll={syncScroll}
spellCheck={false}
autoCapitalize="off"
autoCorrect="off"
style={{
...sharedStyle,
position: "relative",
background: "transparent",
color: "transparent",
caretColor: "#e6edf3",
resize: "vertical",
overflowY: "auto",
zIndex: 1,
}}
/>
</div>
);
}
// ── Agent Script Editor (syntax-highlighted + editable) ─────────────────────
function AgentEditor({ value, onChange, minHeight = "420px" }) {
const textareaRef = useRef(null);
const backdropRef = useRef(null);
const syncScroll = () => {
if (backdropRef.current && textareaRef.current) {
backdropRef.current.scrollTop = textareaRef.current.scrollTop;
backdropRef.current.scrollLeft = textareaRef.current.scrollLeft;
}
};
const sharedStyle = {
fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
fontSize: "12px", lineHeight: "1.8",
whiteSpace: "pre", overflowWrap: "normal", wordBreak: "normal",
overflowX: "auto", padding: "14px 16px", margin: 0,
border: "none", outline: "none", width: "100%",
boxSizing: "border-box", minHeight, tabSize: 2,
};
return (
<div style={{ position: "relative", background: "#0d1117",
border: `1px solid ${C.gold}`, borderRadius: C.radius, overflow: "hidden" }}>
{/* Highlighted backdrop */}
<div ref={backdropRef} aria-hidden="true"
style={{ ...sharedStyle, position: "absolute", top: 0, left: 0, height: "100%",
overflowY: "hidden", overflowX: "hidden", pointerEvents: "none", color: "transparent" }}>
{(value + "\n").split("\n").map((line, i) => (
<div key={i} style={{ color: agentTokenize(line), minHeight: "1.8em" }}>{line || " "}</div>
))}
</div>
{/* Editable textarea */}
<textarea
ref={textareaRef}
value={value}
onChange={e => onChange(e.target.value)}
onScroll={syncScroll}
spellCheck={false} autoCapitalize="off" autoCorrect="off"
style={{
...sharedStyle,
position: "relative",
background: "transparent",
color: "transparent",
caretColor: "#e6edf3",
resize: "vertical",
overflowY: "auto",
zIndex: 1,
}}
/>
</div>
);
}
// ── Terminal Panel ────────────────────────────────────────────────────────────
function TerminalPanel({ cmd, serverOnline, onSuccess }) {
const [lines, setLines] = useState([]);
const [running, setRunning] = useState(false);
const [open, setOpen] = useState(false);
const [succeeded, setSucceeded] = useState(false);
const bottomRef = useRef(null);
const esRef = useRef(null);
useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }); }, [lines]);
const run = () => {
if (!serverOnline || running) return;
setLines([]); setOpen(true); setRunning(true); setSucceeded(false);
// Detect if this is a multi-line bash script (contains newlines or shell operators)
const isBashScript = cmd.includes("\n") || cmd.includes("SESSION_ID") || cmd.includes("for ") || cmd.includes("PLAN_IDS");
if (isBashScript) {
// Use POST /sf/bash for multi-line scripts
fetch(`${API}/preview/run`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ script: cmd }),
}).then(res => {
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
const pump = () => reader.read().then(({ done, value }) => {
if (done) { setRunning(false); return; }
buf += decoder.decode(value, { stream: true });
const parts = buf.split("\n\n");
buf = parts.pop();
for (const part of parts) {
const line = part.replace(/^data: /, "").trim();
if (!line || line.startsWith(":")) continue; // skip pings
try {
const { type, text } = JSON.parse(line);
setLines(l => [...l, { type, text }]);
if (type === "done" || type === "error") { setRunning(false); if (type === "done") { setSucceeded(true); onSuccess && onSuccess(); } }
} catch (_) {}
}
pump();
}).catch(() => setRunning(false));
pump();
}).catch(() => {
setLines(l => [...l, { type: "error", text: "\n✗ Connection failed" }]);
setRunning(false);
});
} else {
// Use GET /sf/run via EventSource for simple sf commands
const cmdAfterSf = cmd.replace(/^sf\s+/, "").replace(/\\ \n\s*/g, " ").replace(/\\\n\s*/g, " ").trim();
const es = new EventSource(`${API}/sf/run?cmd=${encodeURIComponent(cmdAfterSf)}`);
esRef.current = es;
es.onmessage = e => {
try {
const { type, text } = JSON.parse(e.data);
setLines(l => [...l, { type, text }]);
if (type === "done" || type === "error") { setRunning(false); if (type === "done") { setSucceeded(true); onSuccess && onSuccess(); } es.close(); }
} catch (_) {}
};
es.onerror = () => {
setLines(l => [...l, { type: "error", text: "\n✗ Connection lost" }]);
setRunning(false); es.close();
};
}
};
const typeColor = { stdout: C.text, stderr: "#b75000", info: C.textWeak, done: C.success, error: C.error };
return (
<div style={{ marginTop: "6px" }}>
<div style={{ display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" }}>
<Btn size="sm" variant="success" onClick={run} disabled={!serverOnline || running}>
{running ? <><Spinner size={10} /> Running…</> : "▶ Run"}
</Btn>
{running && <Btn size="sm" variant="danger" onClick={() => { esRef.current?.close(); setRunning(false); }}>■ Stop</Btn>}
{lines.length > 0 && !running && (
<button onClick={() => setOpen(o => !o)} style={{ background: "none", border: "none", color: C.brand, fontSize: "11px", cursor: "pointer", textDecoration: "underline" }}>
{open ? "Hide output" : "Show output"}
</button>
)}
{!serverOnline && <span style={{ fontSize: "11px", color: C.textWeak }}>Server offline</span>}
</div>
{open && lines.length > 0 && (
<div style={{ marginTop: "8px", background: "#1e1e1e", borderRadius: C.radius, padding: "10px 14px",
maxHeight: "200px", overflowY: "auto", fontFamily: "monospace", fontSize: "11px", lineHeight: "1.7" }}>
{lines.map((l, i) => <span key={i} style={{ color: typeColor[l.type]||"#ccc", whiteSpace: "pre-wrap" }}>{l.text}</span>)}
<div ref={bottomRef} />
</div>
)}
</div>
);
}
// ── Step Reference (copy-only, no Run) ───────────────────────────────────────
function StepRef({ label, cmd }) {
const [copied, setCopied] = useState(false);
const copy = () => { navigator.clipboard.writeText(cmd); setCopied(true); setTimeout(() => setCopied(false), 2000); };
return (
<div style={{ border: `1px solid ${C.border}`, borderRadius: C.radius, overflow: "hidden" }}>
<div style={{ padding: "5px 12px", background: C.surfaceAlt, borderBottom: `1px solid ${C.border}`,
display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<span style={{ fontSize: "11px", fontWeight: "600", color: C.textWeak, textTransform: "uppercase", letterSpacing: "0.5px" }}>{label}</span>
<button onClick={copy} style={{ background: "none", border: "none", color: copied ? C.success : C.brand, cursor: "pointer", fontSize: "11px", fontWeight: "600" }}>
{copied ? "✓ Copied" : "Copy"}
</button>
</div>
<div style={{ padding: "10px 14px", fontFamily: "JetBrains Mono, monospace", fontSize: "11px",
color: "#79c0ff", background: "#0d1117", whiteSpace: "pre-wrap", wordBreak: "break-all", lineHeight: "1.6" }}>
{cmd}
</div>
</div>
);
}
// ── CLI Command Block ─────────────────────────────────────────────────────────
function CmdBlock({ label, cmd, note, serverOnline, onSuccess }) {
const [copied, setCopied] = useState(false);
const copy = () => { navigator.clipboard.writeText(cmd.replace(/\\\n\s+/g, " ")); setCopied(true); setTimeout(() => setCopied(false), 2000); };
return (
<div style={{ border: `1px solid ${C.border}`, borderRadius: C.radius, overflow: "hidden", marginBottom: "8px" }}>
<div style={{ padding: "6px 12px", background: C.surfaceAlt, borderBottom: `1px solid ${C.border}`,
display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<span style={{ fontSize: "11px", fontWeight: "600", color: C.textWeak, textTransform: "uppercase", letterSpacing: "0.5px" }}>{label}</span>
<button onClick={copy} style={{ background: "none", border: "none", color: copied ? C.success : C.brand, cursor: "pointer", fontSize: "11px", fontWeight: "600" }}>
{copied ? "✓ Copied" : "Copy"}
</button>
</div>
<div style={{ padding: "10px 14px", fontFamily: "JetBrains Mono, monospace", fontSize: "12px", color: "#79c0ff", background: "#0d1117", lineHeight: "1.7", whiteSpace: "pre-wrap", wordBreak: "break-all", overflowWrap: "break-word", minWidth: 0 }}>
{cmd}
</div>
{note && <div style={{ padding: "4px 12px 8px", fontSize: "11px", color: C.textWeak }}>{note}</div>}
<div style={{ padding: "4px 12px 10px" }}><TerminalPanel cmd={cmd} serverOnline={serverOnline} onSuccess={onSuccess} /></div>
</div>
);
}
// ── Save Button ───────────────────────────────────────────────────────────────
function SaveBtn({ filename, content, serverOnline, route = "/files/save" }) {
const [state, setState] = useState("idle");
const save = async () => {
if (!serverOnline || !content) return;
setState("saving");
try {
const r = await fetch(`${API}${route}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ filename, content }) });
const d = await r.json();
setState(d.ok ? "saved" : "error");
setTimeout(() => setState("idle"), 3000);
} catch (_) { setState("error"); }
};
return (
<Btn size="sm" variant={state === "saved" ? "success" : "outline"} onClick={save} disabled={state === "saving" || !serverOnline || !content}>
{state === "saving" ? <><Spinner size={10} /> Saving…</> : state === "saved" ? "✓ Saved!" : state === "error" ? "✗ Error" : "💾 Save to project"}
</Btn>
);
}
// ── File Picker (picklist) ────────────────────────────────────────────────────
function FilePicker({ label, route = "/files/specs", filterFn, onSelect, selected, emptyMsg, serverOnline }) {
const [files, setFiles] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const load = useCallback(async () => {
if (!serverOnline) return;
setLoading(true); setError("");
try { setFiles(await fetchFiles(route, filterFn)); }
catch (e) { setError(e.message); }
setLoading(false);
}, [serverOnline, route, filterFn]);
useEffect(() => { load(); }, [load]);
if (!serverOnline) return <Alert type="warning">Server offline — start <code>tdad-server.js</code> to browse project files.</Alert>;
const handleChange = e => {
const f = files.find(f => f.name === e.target.value);
if (f) onSelect(f);
};
const selectStyle = {
...inputStyle,
cursor: "pointer",
fontFamily: "monospace",
paddingRight: "32px",
appearance: "none",
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238b949e' d='M6 8L1 3h10z'/%3E%3C/svg%3E")`,
backgroundRepeat: "no-repeat",
backgroundPosition: "right 10px center",
};
return (
<div>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "6px" }}>
<label style={labelStyle}>{label}</label>
<button onClick={load} style={{ background: "none", border: "none", color: C.brand, fontSize: "11px", cursor: "pointer", display: "flex", alignItems: "center", gap: "4px" }}>
{loading ? <Spinner size={9} /> : "↻"} {loading ? "Loading…" : "Refresh"}
</button>
</div>
{error && <Alert type="error">{error}</Alert>}
{!loading && !error && files.length === 0 ? (
<div style={{ padding: "12px 14px", background: C.surfaceAlt, border: `1px solid ${C.border}`, borderRadius: C.radius, color: C.textWeak, fontSize: "13px" }}>
{emptyMsg || "No files found."}
</div>
) : (
<div style={{ position: "relative" }}>
<select value={selected?.name || ""} onChange={handleChange} style={selectStyle} disabled={loading || files.length === 0}>
<option value="" disabled>{loading ? "Loading files…" : `— select a file (${files.length}) —`}</option>
{files.map(f => {
const kb = (f.size / 1024).toFixed(1);
const date = new Date(f.modified).toLocaleDateString("fr-FR", { day: "2-digit", month: "short" });
return <option key={f.name} value={f.name}>{f.name} · {kb} KB · {date}</option>;
})}
</select>
{selected && (
<div style={{ marginTop: "6px", padding: "8px 12px", background: C.brandLight, border: `1px solid ${C.brand}`, borderRadius: C.radius, display: "flex", alignItems: "center", gap: "8px" }}>
<span style={{ color: C.brand, fontSize: "12px" }}>✓</span>
<span style={{ fontFamily: "monospace", fontSize: "12px", color: C.text, fontWeight: "600" }}>{selected.name}</span>
<span style={{ fontSize: "11px", color: C.textWeak, marginLeft: "auto" }}>{(selected.size/1024).toFixed(1)} KB</span>
</div>
)}
</div>
)}
</div>
);
}
// ── Metrics Selector ──────────────────────────────────────────────────────────
function MetricsSelector({ selected, onChange }) {
const toggle = id => onChange(selected.includes(id) ? selected.filter(x => x !== id) : [...selected, id]);
return (
<div style={{ display: "flex", flexWrap: "wrap", gap: "6px", alignItems: "center" }}>
{METRICS.map(m => {
const on = selected.includes(m.id);
if (m.locked) return (
<span key={m.id} title={m.desc}
style={{ padding: "5px 12px", borderRadius: "999px", border: `1px solid ${C.border}`,
background: C.bg, color: C.textWeaker, fontSize: "12px", fontWeight: "600",
cursor: "not-allowed", opacity: 0.45 }}>
{m.label}
</span>
);
return (
<button key={m.id} onClick={() => toggle(m.id)} title={m.desc}
style={{ padding: "5px 12px", borderRadius: "999px", border: `1px solid ${on ? C.brand : C.border}`,
background: on ? C.brandLight : C.surface, color: on ? C.brandDark : C.textWeak,
fontSize: "12px", fontWeight: "600", cursor: "pointer", transition: "all 0.15s" }}>
{m.label}
</button>
);
})}
</div>
);
}
// ── YAML Output Panel ─────────────────────────────────────────────────────────
function OutputPanel({ title, filename, yaml, statsComp, history, onUndo, onCopy, copied,
refineText, setRefineText, onRefine, refining, refinePlaceholder,
onManualEdit, cliContent, footer, serverOnline, saveRoute = "/files/save" }) {
const [tab, setTab] = useState("yaml");
const [editContent, setEditContent] = useState("");
const [editDirty, setEditDirty] = useState(false);
// Sync textarea when switching to edit tab or yaml changes
const handleTabClick = t => {
if (t === "edit") setEditContent(yaml);
setTab(t);
setEditDirty(false);
};
const applyEdit = () => {
if (onManualEdit && editContent.trim()) {
onManualEdit(editContent);
setEditDirty(false);
setTab("yaml");
}
};
if (!yaml) return null;
return (
<Card style={{ animation: "fadeIn 0.25s ease" }}>
<CardHeader
title={title || filename}
subtitle={`${yaml.split("\n").length} lines`}
action={
<div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
<SaveBtn filename={filename} content={yaml} serverOnline={serverOnline} route={saveRoute} />
<Btn size="sm" variant="neutral" onClick={onCopy}>{copied ? "✓ Copied" : "⎘ Copy"}</Btn>
{history?.length > 1 && (
<Btn size="sm" variant="neutral" onClick={onUndo}>↩ Undo</Btn>
)}
</div>
}
/>
{statsComp}
<div style={{ borderBottom: `1px solid ${C.border}`, display: "flex", gap: "0" }}>
{[
{ id: "yaml", label: "YAML" },
{ id: "edit", label: "✏️ Edit manually" },
].map(({ id, label }) => (
<button key={id} onClick={() => handleTabClick(id)}
style={{ padding: "10px 18px", background: "none", border: "none",
borderBottom: `2px solid ${tab === id ? (id === "edit" ? C.gold : C.brand) : "transparent"}`,
color: tab === id ? (id === "edit" ? C.gold : C.brand) : C.textWeak,
fontSize: "13px", fontWeight: "600", cursor: "pointer", transition: "all 0.15s",
display: "flex", alignItems: "center", gap: "5px" }}>
{label}
{id === "edit" && editDirty && (
<span style={{ width: "6px", height: "6px", borderRadius: "50%", background: C.gold, display: "inline-block" }} />
)}
</button>
))}
</div>
<div style={{ padding: "16px" }}>
{tab === "yaml" && (
<>
<YamlViewer code={yaml} />
<div style={{ marginTop: "12px", display: "flex", flexDirection: "column", gap: "6px" }}>
<label style={labelStyle}>🔁 Refine with AI</label>
<div style={{ display: "flex", gap: "8px" }}>
<input value={refineText} onChange={e => setRefineText(e.target.value)}
onKeyDown={e => e.key === "Enter" && !e.shiftKey && onRefine()}
placeholder={refinePlaceholder} style={{ ...inputStyle, flex: 1 }} />
<Btn onClick={onRefine} disabled={refining || !refineText?.trim()}>
{refining ? <><Spinner size={11} /> Refining…</> : "Refine"}
</Btn>
</div>
</div>
</>
)}
{tab === "edit" && (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<span style={{ fontSize: "12px", color: C.textWeak }}>
Edit the YAML directly — click <strong style={{ color: C.gold }}>Apply</strong> to save to history
</span>
<span style={{ fontSize: "11px", color: C.textWeaker }}>
{editContent.split("\n").length} lines
</span>
</div>
<YamlEditor
value={editContent}
onChange={v => { setEditContent(v); setEditDirty(true); }}
minHeight="420px"
/>
<div style={{ display: "flex", gap: "8px", justifyContent: "flex-end" }}>
<Btn size="sm" variant="neutral" onClick={() => { setEditContent(yaml); setEditDirty(false); }}>
↺ Reset
</Btn>
<Btn size="sm" variant="outline"
onClick={applyEdit}
disabled={!editDirty || !editContent.trim()}
style={{ borderColor: C.gold, color: C.gold }}>
✓ Apply changes
</Btn>
</div>
</div>
)}
</div>
{footer && <div style={{ padding: "0 16px 16px" }}>{footer}</div>}
</Card>
);
}
// ═══════════════════════════════════════════════════════════════════════════════
// PAGE 1 — AGENT SPEC
// ═══════════════════════════════════════════════════════════════════════════════
function PageAgentSpec({ serverOnline, targetOrg = "my-dev-org" }) {
const [tab, setTab] = useState("new");
const [subNew, setSubNew] = useState("cli");
const [subEdit, setSubEdit] = useState("paste");
// AI generation state
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [yaml, setYaml] = useState("");
const [copied, setCopied] = useState(false);
const [refineText, setRefineText] = useState("");
const [refining, setRefining] = useState(false);
const [history, setHistory] = useState([]);
const [showAdvanced, setShowAdvanced] = useState(false);
const [form, setForm] = useState({ agentType:"customer", companyName:"", companyDescription:"", role:"", tone:"casual", maxNumOfTopics:5, agentUser:"", promptTemplateName:"", groundingContext:"", enrichLogs:false });
const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
// CLI spec state
const [cliAgentType, setCliAgentType] = useState("customer");
const [cliRole, setCliRole] = useState("");
const [cliCompany, setCliCompany] = useState("");
const [cliCompDesc, setCliCompDesc] = useState("");
const [cliTone, setCliTone] = useState("casual");
const [cliMaxTopics, setCliMaxTopics] = useState(5);