-
Notifications
You must be signed in to change notification settings - Fork 936
Expand file tree
/
Copy pathindex.tsx
More file actions
1101 lines (987 loc) · 36 KB
/
index.tsx
File metadata and controls
1101 lines (987 loc) · 36 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 { BorderOutlined, SendOutlined } from '@ant-design/icons';
import './index.less';
import { DownOutlined } from '@ant-design/icons';
import type { z } from '@midscene/core';
import { Button, Dropdown, Form, Input, Radio, Tooltip } from 'antd';
import type { MenuProps } from 'antd';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import type { HistoryItem } from '../../store/history';
import { useHistoryStore } from '../../store/history';
import type { DeviceType, RunType } from '../../types';
import type { ServiceModeType } from '../../types';
import {
type FormParams,
type ZodObjectSchema,
type ZodRuntimeAccess,
type ZodType,
extractDefaultValue,
isLocateField,
isZodObjectSchema,
unwrapZodType,
} from '../../types';
import { apiMetadata, defaultMainButtons } from '../../utils/constants';
import { hasDeviceSpecificConfig } from '../../utils/device-capabilities';
import {
actionNameForType,
isRunButtonEnabled as calculateIsRunButtonEnabled,
getPlaceholderForType,
} from '../../utils/playground-utils';
import { ConfigSelector } from '../config-selector';
import {
BooleanField,
EnumField,
LocateField,
NumberField,
TextField,
} from '../form-field';
import { HistorySelector } from '../history-selector';
import './index.less';
import type { DeviceAction } from '@midscene/core';
const { TextArea } = Input;
interface PromptInputProps {
runButtonEnabled: boolean;
form: any; // Ant Design FormInstance - keeping as any since it's external library type
serviceMode: ServiceModeType;
selectedType: RunType;
dryMode: boolean;
stoppable: boolean;
loading: boolean;
onRun: () => void;
onStop: () => void;
clearPromptAfterRun?: boolean;
hideDomAndScreenshotOptions?: boolean; // Hide domIncluded and screenshotIncluded options
actionSpace: DeviceAction<any>[]; // Required actionSpace for dynamic parameter detection
deviceType?: DeviceType;
}
export const PromptInput: React.FC<PromptInputProps> = ({
runButtonEnabled,
form,
serviceMode,
selectedType,
dryMode,
stoppable,
loading,
onRun,
onStop,
clearPromptAfterRun = true,
actionSpace,
hideDomAndScreenshotOptions = false,
deviceType,
}) => {
const [hoveringSettings, setHoveringSettings] = useState(false);
const [promptValue, setPromptValue] = useState('');
const placeholder = getPlaceholderForType(selectedType);
const textAreaRef = useRef<any>(null); // Ant Design TextArea ref with internal structure
const modeRadioGroupRef = useRef<HTMLDivElement>(null); // Ref for the mode-radio-group container
const params = Form.useWatch('params', form);
const lastHistoryRef = useRef<HistoryItem | null>(null);
// Get history from store
const history = useHistoryStore((state) => state.history);
const lastSelectedType = useHistoryStore((state) => state.lastSelectedType);
const addHistory = useHistoryStore((state) => state.addHistory);
const setLastSelectedType = useHistoryStore(
(state) => state.setLastSelectedType,
);
const historyForSelectedType = useMemo(
() => history[selectedType] || [],
[history, selectedType],
);
const actionMap = useMemo(() => {
const map = new Map<string, DeviceAction<any>>();
if (actionSpace) {
for (const action of actionSpace) {
if (action.name) map.set(action.name, action);
if (action.interfaceAlias) map.set(action.interfaceAlias, action);
}
}
return map;
}, [actionSpace]);
// Check if current method needs structured parameters (dynamic based on actionSpace)
const needsStructuredParams = useMemo(() => {
if (actionSpace) {
// Use actionSpace to determine if method needs structured params
const action = actionMap.get(selectedType);
if (!action?.paramSchema) return false;
// Check if paramSchema actually has fields
if (isZodObjectSchema(action.paramSchema)) {
const schema = action.paramSchema as ZodObjectSchema;
const shape: Record<string, ZodType> = schema.shape || {};
const shapeKeys = Object.keys(shape);
return shapeKeys.length > 0; // Only need structured params if there are actual fields
}
// If paramSchema exists but not in expected format, assume it needs params
return true;
}
return false;
}, [selectedType, actionMap, actionSpace]);
// Check if current method needs any input (either prompt or parameters)
const needsAnyInput = useMemo(() => {
if (actionSpace && actionSpace.length > 0) {
// Use actionSpace to determine if method needs any input
const action = actionMap.get(selectedType);
// If action exists in actionSpace, check if it has required parameters
if (action) {
// Check if the paramSchema has any required fields
if (action.paramSchema && isZodObjectSchema(action.paramSchema)) {
const schema = action.paramSchema as ZodObjectSchema;
const shape: Record<string, ZodType> = schema.shape || {};
// Check if any field is required (not optional)
const hasRequiredFields = Object.keys(shape).some((key) => {
const field = shape[key];
const { isOptional } = unwrapZodType(field);
return !isOptional;
});
return hasRequiredFields;
}
// If has paramSchema but not a ZodObject, assume it needs input
return !!action.paramSchema;
}
// If not found in actionSpace, assume most methods need input
return true;
}
// Fallback when actionSpace is not loaded yet - assume most methods need input
return true;
}, [selectedType, actionSpace]);
// Check if current method supports data extraction options
const showDataExtractionOptions = useMemo(() => {
const dataExtractionMethods = [
'aiQuery',
'aiBoolean',
'aiNumber',
'aiString',
'aiAsk',
'aiAssert',
];
return dataExtractionMethods.includes(selectedType);
}, [selectedType]);
// Check if current method supports deep locate option (dynamic based on actionSpace)
const showDeepLocateOption = useMemo(() => {
if (selectedType === 'aiAct' || selectedType === 'aiLocate') {
return true;
}
if (actionSpace) {
// Use actionSpace to determine if method supports deep locate
const action = actionMap.get(selectedType);
if (action?.paramSchema && isZodObjectSchema(action.paramSchema)) {
const schema = action.paramSchema as ZodObjectSchema;
const shape: Record<string, ZodType> = schema.shape || {};
// Check if any parameter is a locate field
const hasLocateField = Object.keys(shape).some((key) => {
const field = shape[key];
const { actualField } = unwrapZodType(field);
return isLocateField(actualField);
});
return hasLocateField;
}
return false;
}
return false;
}, [selectedType, actionSpace]);
// Check if current method supports deep think option (for aiAct planning)
const showDeepThinkOption = useMemo(() => {
return selectedType === 'aiAct';
}, [selectedType]);
// Check if ConfigSelector will actually have options to show
const hasConfigOptions = useMemo(() => {
const hasTracking = serviceMode === 'In-Browser-Extension';
const hasDeepLocate = showDeepLocateOption;
const hasDeepThink = showDeepThinkOption;
const hasDataExtraction =
showDataExtractionOptions && !hideDomAndScreenshotOptions;
const hasDeviceOptions = hasDeviceSpecificConfig(deviceType);
return (
hasTracking ||
hasDeepLocate ||
hasDeepThink ||
hasDataExtraction ||
hasDeviceOptions
);
}, [
serviceMode,
showDeepLocateOption,
showDeepThinkOption,
showDataExtractionOptions,
hideDomAndScreenshotOptions,
deviceType,
]);
// Get available methods for dropdown (filtered by actionSpace)
const availableDropdownMethods = useMemo(() => {
const metadataMethods = Object.keys(apiMetadata);
if (!actionSpace || actionSpace.length === 0) {
// Fallback to metadata methods if actionSpace is not available
return metadataMethods;
}
// Extract available methods from actionSpace
const availableMethods = actionSpace.map(
(action) => action.interfaceAlias || action.name,
);
// Combine methods from two sources:
// 1. Methods from apiMetadata (filtered by rules)
// 2. Methods from actionSpace (even if not in apiMetadata)
const finalMethods = new Set<string>();
// Add filtered apiMetadata methods
metadataMethods.forEach((method) => {
const methodInfo = apiMetadata[method as keyof typeof apiMetadata];
// Always include extraction and validation methods
if (
methodInfo?.group === 'extraction' ||
methodInfo?.group === 'validation'
) {
finalMethods.add(method);
} else {
// For interaction methods, check if they're available in actionSpace
if (availableMethods.includes(method)) {
finalMethods.add(method);
}
}
});
// Add all methods from actionSpace (including Android-specific ones)
availableMethods.forEach((method) => {
finalMethods.add(method);
});
return Array.from(finalMethods);
}, [actionSpace]);
// Get default values for fields with defaults
const getDefaultParams = useCallback((): FormParams => {
if (!needsStructuredParams || !actionSpace) {
return {};
}
const action = actionMap.get(selectedType);
if (action?.paramSchema && isZodObjectSchema(action.paramSchema)) {
const defaultParams: FormParams = {};
const schema = action.paramSchema as ZodObjectSchema;
const shape: Record<string, ZodType> = schema.shape || {};
Object.keys(shape).forEach((key) => {
const field = shape[key];
const defaultValue = extractDefaultValue(field);
if (defaultValue !== undefined) {
defaultParams[key] = defaultValue as
| string
| number
| boolean
| null
| undefined;
}
});
return defaultParams;
}
return {};
}, [selectedType, needsStructuredParams, actionSpace]);
// Initialize form with last selected type when component mounts
useEffect(() => {
if (!form.getFieldValue('type') && lastSelectedType) {
form.setFieldValue('type', lastSelectedType);
}
}, [form, lastSelectedType]);
// Save selected type when it changes
useEffect(() => {
if (selectedType && selectedType !== lastSelectedType) {
setLastSelectedType(selectedType);
}
}, [selectedType, lastSelectedType, setLastSelectedType]);
// Scroll to selected item in mode-radio-group
const scrollToSelectedItem = useCallback(() => {
const container = modeRadioGroupRef.current;
if (!container) return;
let targetElement: HTMLElement | null = null;
// Find the selected radio button
const selectedRadioButton = container.querySelector(
'.ant-radio-button-wrapper-checked',
) as HTMLElement;
// Find the dropdown button if it's selected (showing a non-default item)
const dropdownButton = container.querySelector(
'.more-apis-button.selected-from-dropdown',
) as HTMLElement;
// Determine which element to scroll to
if (selectedRadioButton) {
targetElement = selectedRadioButton;
} else if (dropdownButton) {
targetElement = dropdownButton;
}
if (targetElement) {
const containerRect = container.getBoundingClientRect();
const targetRect = targetElement.getBoundingClientRect();
// Calculate the relative position of the target within the container
const targetLeft =
targetRect.left - containerRect.left + container.scrollLeft;
const targetWidth = targetRect.width;
const containerWidth = containerRect.width;
// Calculate the optimal scroll position to center the target
const optimalScrollLeft = targetLeft - (containerWidth - targetWidth) / 2;
// Smooth scroll to the target
container.scrollTo({
left: Math.max(0, optimalScrollLeft),
behavior: 'smooth',
});
}
}, []);
// When the selectedType changes, populate the form with the last item from that type's history.
useEffect(() => {
const lastHistory = historyForSelectedType[0];
// Skip auto-filling if this is the same history item we just added
if (
lastHistory &&
lastHistoryRef.current &&
lastHistory.timestamp === lastHistoryRef.current.timestamp
) {
return;
}
if (lastHistory) {
form.setFieldsValue({
type: lastHistory.type,
prompt: lastHistory.prompt || '',
params: lastHistory.params,
});
setPromptValue(lastHistory.prompt || '');
lastHistoryRef.current = lastHistory;
} else {
// If there's no history for this type, fill with default values
const defaultParams = getDefaultParams();
form.setFieldsValue({
prompt: '',
params: defaultParams,
});
setPromptValue('');
lastHistoryRef.current = null;
}
}, [selectedType, historyForSelectedType, form, getDefaultParams]);
// Scroll to selected item when selectedType changes
useEffect(() => {
// Use a timeout to ensure the DOM has been updated with the new selection
const timeoutId = setTimeout(() => {
scrollToSelectedItem();
}, 100);
return () => clearTimeout(timeoutId);
}, [selectedType, scrollToSelectedItem]);
// Watch form prompt value changes
const formPromptValue = Form.useWatch('prompt', form);
// Sync promptValue with form field value when form changes
useEffect(() => {
if (formPromptValue !== promptValue) {
setPromptValue(formPromptValue || '');
}
}, [formPromptValue, promptValue]);
// Handle history selection internally
const handleSelectHistory = useCallback(
(historyItem: HistoryItem) => {
form.setFieldsValue({
prompt: historyItem.prompt,
type: historyItem.type,
params: historyItem.params,
});
setPromptValue(historyItem.prompt);
},
[form],
);
// Handle prompt input change
const handlePromptChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
setPromptValue(value);
},
[],
);
const hasSingleStructuredParam = useMemo(() => {
if (!needsStructuredParams || !actionSpace) {
return false;
}
const action = actionMap.get(selectedType);
if (action?.paramSchema && isZodObjectSchema(action.paramSchema)) {
const schema = action.paramSchema as ZodObjectSchema;
const shape: Record<string, ZodType> = schema.shape || {};
return Object.keys(shape).length === 1;
}
return false;
}, [selectedType, needsStructuredParams, actionMap, actionSpace]);
// Calculate if run button should be enabled
const isRunButtonEnabled = useMemo(
(): boolean =>
calculateIsRunButtonEnabled(
runButtonEnabled,
!!needsStructuredParams,
params,
actionMap,
selectedType,
promptValue,
),
[
runButtonEnabled,
needsStructuredParams,
selectedType,
actionMap,
promptValue,
params,
],
);
// Handle run with history addition
const handleRunWithHistory = useCallback(() => {
const values = form.getFieldsValue() as {
type: string;
prompt?: string;
params?: Record<string, unknown>;
};
// For structured params, create a display string for history - dynamically
let historyPrompt = '';
if (needsStructuredParams && values.params && actionSpace) {
const action = actionMap.get(selectedType);
if (action?.paramSchema && isZodObjectSchema(action.paramSchema)) {
// Separate locate field from other fields for legacy format compatibility
let locateValue = '';
const otherValues: string[] = [];
const schema = action.paramSchema as ZodObjectSchema;
const shape: Record<string, ZodType> = schema.shape || {};
Object.keys(shape).forEach((key) => {
const paramValue = values.params?.[key];
if (
paramValue !== undefined &&
paramValue !== null &&
paramValue !== ''
) {
const field = shape[key];
const { actualField } = unwrapZodType(field);
if (isLocateField(actualField)) {
locateValue = String(paramValue);
} else {
// Format based on field type
if (key === 'distance') {
otherValues.push(`${paramValue}`);
} else {
otherValues.push(String(paramValue));
}
}
}
});
// Create legacy-compatible format for history
const mainPart = otherValues.join(' ');
historyPrompt = locateValue ? `${locateValue} - ${mainPart}` : mainPart;
} else {
historyPrompt = values.prompt || '';
}
} else {
historyPrompt = values.prompt || '';
}
const newHistoryItem = {
type: values.type,
prompt: historyPrompt,
params: values.params,
timestamp: Date.now(),
};
addHistory(newHistoryItem);
onRun();
if (clearPromptAfterRun) {
// Remember the history item we just added to avoid auto-filling with it
lastHistoryRef.current = newHistoryItem;
setPromptValue('');
if (needsStructuredParams) {
const defaultParams = getDefaultParams();
form.setFieldValue('params', defaultParams);
} else {
form.setFieldValue('prompt', '');
}
}
}, [
form,
addHistory,
onRun,
needsStructuredParams,
selectedType,
clearPromptAfterRun,
actionSpace,
getDefaultParams,
]);
// Handle key events
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && e.metaKey && isRunButtonEnabled) {
handleRunWithHistory();
e.preventDefault();
e.stopPropagation();
} else if (e.key === 'Enter') {
setTimeout(() => {
if (textAreaRef.current) {
// Access the internal textarea element (Ant Design specific structure)
const textarea = (textAreaRef.current as any).resizableTextArea
?.textArea;
if (textarea) {
const selectionStart = textarea.selectionStart;
const value = textarea.value;
// check if cursor is at the end of the text
const lastNewlineIndex = value.lastIndexOf('\n');
const isAtLastLine =
lastNewlineIndex === -1 || selectionStart > lastNewlineIndex;
// only scroll to bottom when cursor is at the end of the text
if (isAtLastLine) {
textarea.scrollTop = textarea.scrollHeight;
}
}
}
}, 0);
}
},
[handleRunWithHistory, isRunButtonEnabled],
);
// Handle key events for structured params
const handleStructuredKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && e.metaKey && isRunButtonEnabled) {
handleRunWithHistory();
e.preventDefault();
e.stopPropagation();
}
},
[handleRunWithHistory, isRunButtonEnabled],
);
// Render structured parameter inputs dynamically based on paramSchema
const renderStructuredParams = useCallback(() => {
if (!needsStructuredParams) return null;
// Try to get action from actionSpace first
if (actionSpace) {
const action = actionMap.get(selectedType);
if (action?.paramSchema && isZodObjectSchema(action.paramSchema)) {
const schema = action.paramSchema as ZodObjectSchema;
// Handle both runtime and serialized schemas
const shape: Record<string, ZodType> = schema.shape || {};
const schemaKeys = Object.keys(shape);
// If only one field, use traditional single input style without labels
if (schemaKeys.length === 1) {
const key = schemaKeys[0];
const field = shape[key];
const { actualField } = unwrapZodType(field);
// Check if it's a locate field
const isLocateFieldFlag = isLocateField(actualField);
// Extract placeholder from fieldSchema if available, otherwise use defaults
const placeholderText = (() => {
const fieldWithRuntime = actualField as ZodRuntimeAccess;
// Try to get description from the field schema
if (fieldWithRuntime._def?.description) {
return fieldWithRuntime._def.description;
}
if (fieldWithRuntime.description) {
return fieldWithRuntime.description;
}
// Try to get from action's paramSchema directly
if (actionSpace) {
const action = actionMap.get(selectedType);
if (
action?.paramSchema &&
typeof action.paramSchema === 'object' &&
'shape' in action.paramSchema
) {
const shape: Record<string, ZodType> =
(action.paramSchema as unknown as ZodObjectSchema).shape ||
{};
const fieldDef = shape[key];
if (fieldDef?._def?.description) {
return fieldDef._def.description;
}
if (fieldDef?.description) {
return fieldDef.description;
}
}
}
// Fallback to default placeholders
if (isLocateFieldFlag) {
return 'Describe the element you want to interact with';
} else {
if (key === 'keyName') return 'Enter key name or text to type';
if (key === 'value') return 'Enter text to input';
return `Enter ${key}`;
}
})();
return (
<Form.Item name={['params', key]} style={{ margin: 0 }}>
<Input.TextArea
className="main-side-console-input-textarea"
rows={3}
placeholder={placeholderText}
autoFocus
onKeyDown={handleStructuredKeyDown}
/>
</Form.Item>
);
}
// Multiple fields - use structured layout with labels
const fields: React.ReactNode[] = [];
// Sort fields: required fields first, then optional fields
const sortedKeys = schemaKeys.sort((keyA, keyB) => {
const fieldSchemaA = shape[keyA];
const fieldSchemaB = shape[keyB];
const { isOptional: isOptionalA } = unwrapZodType(fieldSchemaA);
const { isOptional: isOptionalB } = unwrapZodType(fieldSchemaB);
// Required fields (isOptional = false) come first
if (!isOptionalA && isOptionalB) return -1;
if (isOptionalA && !isOptionalB) return 1;
return 0;
});
// Dynamically render form fields based on paramSchema
sortedKeys.forEach((key, index) => {
const fieldSchema = shape[key];
const { actualField, isOptional } = unwrapZodType(fieldSchema);
const isLocateFieldFlag = isLocateField(actualField);
const label = key.charAt(0).toUpperCase() + key.slice(1);
const isRequired = !isOptional;
const marginBottom = index === sortedKeys.length - 1 ? 0 : 12;
// Extract placeholder from fieldSchema if available
const placeholder = (() => {
// Try to get placeholder from field description or other metadata
const fieldWithRuntime = actualField as ZodRuntimeAccess;
if (fieldWithRuntime._def?.description) {
return fieldWithRuntime._def.description;
}
// Try to get from field metadata/annotations
if (fieldWithRuntime.description) {
return fieldWithRuntime.description;
}
// Try to get from action's paramSchema directly
if (actionSpace) {
const action = actionMap.get(selectedType);
if (
action?.paramSchema &&
typeof action.paramSchema === 'object' &&
'shape' in action.paramSchema
) {
const shape: Record<string, ZodType> =
(action.paramSchema as { shape?: Record<string, ZodType> })
.shape || {};
const fieldDef = shape[key];
if (fieldDef?._def?.description) {
return fieldDef._def.description;
}
if (fieldDef?.description) {
return fieldDef.description;
}
}
}
// For locate fields, provide a default placeholder
if (isLocateFieldFlag) {
return 'Describe the element you want to interact with';
}
return undefined;
})();
const fieldProps = {
name: key,
label,
fieldSchema: actualField as z.ZodTypeAny,
isRequired,
marginBottom,
placeholder,
};
if (isLocateFieldFlag) {
fields.push(<LocateField key={key} {...fieldProps} />);
} else if (
(actualField as ZodRuntimeAccess)._def?.typeName === 'ZodEnum'
) {
fields.push(<EnumField key={key} {...fieldProps} />);
} else if (
(actualField as ZodRuntimeAccess)._def?.typeName === 'ZodNumber'
) {
fields.push(<NumberField key={key} {...fieldProps} />);
} else if (
(actualField as ZodRuntimeAccess)._def?.typeName === 'ZodBoolean'
) {
fields.push(<BooleanField key={key} {...fieldProps} />);
} else {
fields.push(<TextField key={key} {...fieldProps} />);
}
});
// Special layout handling for scroll action with direction and distance
if (selectedType === 'aiScroll') {
const directionField = fields.find(
(field) =>
React.isValidElement(field) && field.props.name === 'direction',
);
const distanceField = fields.find(
(field) =>
React.isValidElement(field) && field.props.name === 'distance',
);
const otherFields = fields.filter(
(field) =>
React.isValidElement(field) &&
field.props.name !== 'direction' &&
field.props.name !== 'distance',
);
if (directionField && distanceField) {
return (
<div className="structured-params">
<div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
{directionField}
{distanceField}
</div>
{otherFields}
</div>
);
}
}
return <div className="structured-params">{fields}</div>;
}
}
// Fallback - should not be reached if actionSpace is properly loaded
return null;
}, [
selectedType,
needsStructuredParams,
actionSpace,
handleStructuredKeyDown,
]);
// Handle settings hover state
const handleMouseEnter = useCallback(() => {
setHoveringSettings(true);
}, []);
const handleMouseLeave = useCallback(() => {
setHoveringSettings(false);
}, []);
// Render action button based on current state
const renderActionButton = useCallback(() => {
const runButton = (text: string) => (
<Button
type="primary"
icon={<SendOutlined />}
style={{ borderRadius: 20, zIndex: 999 }}
onClick={handleRunWithHistory}
disabled={!isRunButtonEnabled}
loading={loading}
>
{text}
</Button>
);
if (dryMode) {
return selectedType === 'aiAct' ? (
<Tooltip title="Start executing until some interaction actions need to be performed. You can see the process of planning and locating.">
{runButton('Dry Run')}
</Tooltip>
) : (
runButton('Run')
);
}
if (stoppable) {
return (
<Button
icon={<BorderOutlined />}
onClick={onStop}
style={{ borderRadius: 20, zIndex: 999 }}
>
Stop
</Button>
);
}
return runButton('Run');
}, [
dryMode,
loading,
handleRunWithHistory,
onStop,
isRunButtonEnabled,
selectedType,
stoppable,
]);
return (
<div className="prompt-input-wrapper">
{/* top operation button area */}
<div className="mode-radio-group-wrapper">
<div className="mode-radio-group" ref={modeRadioGroupRef}>
<Form.Item name="type" style={{ margin: 0 }}>
<Radio.Group buttonStyle="solid" disabled={!runButtonEnabled}>
{defaultMainButtons.map((apiType) => (
<Tooltip
key={apiType}
title={
apiMetadata[apiType as keyof typeof apiMetadata]?.title ||
''
}
>
<Radio.Button value={apiType}>
{actionNameForType(apiType)}
</Radio.Button>
</Tooltip>
))}
</Radio.Group>
</Form.Item>
<Dropdown
menu={(() => {
// Get all APIs not currently shown in main buttons, filtered by actionSpace
const hiddenAPIs = availableDropdownMethods.filter(
(api) => !defaultMainButtons.includes(api),
);
// Group hidden APIs by category
const groupedItems: any[] = [];
const interactionAPIs = hiddenAPIs.filter(
(api) =>
apiMetadata[api as keyof typeof apiMetadata]?.group ===
'interaction',
);
if (interactionAPIs.length > 0) {
groupedItems.push({
key: 'interaction-group',
type: 'group',
label: 'Interaction APIs',
children: interactionAPIs.map((api) => ({
key: api,
label: actionNameForType(api),
title:
apiMetadata[api as keyof typeof apiMetadata]?.title || '',
onClick: () => {
form.setFieldValue('type', api);
},
})),
});
}
const extractionAPIs = hiddenAPIs.filter(
(api) =>
apiMetadata[api as keyof typeof apiMetadata]?.group ===
'extraction',
);
if (extractionAPIs.length > 0) {
groupedItems.push({
key: 'extraction-group',
type: 'group',
label: 'Data Extraction APIs',
children: extractionAPIs.map((api) => ({
key: api,
label: actionNameForType(api),
title:
apiMetadata[api as keyof typeof apiMetadata]?.title || '',
onClick: () => {
form.setFieldValue('type', api);
},
})),
});
}
const validationAPIs = hiddenAPIs.filter(
(api) =>
apiMetadata[api as keyof typeof apiMetadata]?.group ===
'validation',
);
if (validationAPIs.length > 0) {
groupedItems.push({
key: 'validation-group',
type: 'group',
label: 'Validation APIs',
children: validationAPIs.map((api) => ({
key: api,
label: actionNameForType(api),
title:
apiMetadata[api as keyof typeof apiMetadata]?.title || '',
onClick: () => {
form.setFieldValue('type', api);
},
})),
});
}
// Add device-specific APIs (those not in apiMetadata)
const deviceSpecificAPIs = hiddenAPIs.filter(
(api) => !apiMetadata[api as keyof typeof apiMetadata],
);
if (deviceSpecificAPIs.length > 0) {
groupedItems.push({
key: 'device-specific-group',
type: 'group',
label: 'Device-Specific APIs',
children: deviceSpecificAPIs.map((api) => ({
key: api,
label: actionNameForType(api),
title: '',
onClick: () => {
form.setFieldValue('type', api);