-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathDeploymentAddRevisionModal.tsx
More file actions
1631 lines (1556 loc) · 59.4 KB
/
DeploymentAddRevisionModal.tsx
File metadata and controls
1631 lines (1556 loc) · 59.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
@license
Copyright (c) 2015-2026 Lablup Inc. All rights reserved.
*/
import { DeploymentAddRevisionModalAddMutation } from '../__generated__/DeploymentAddRevisionModalAddMutation.graphql';
import { DeploymentAddRevisionModalImageNameQuery } from '../__generated__/DeploymentAddRevisionModalImageNameQuery.graphql';
import type { DeploymentAddRevisionModalPresetCountQuery } from '../__generated__/DeploymentAddRevisionModalPresetCountQuery.graphql';
import type { DeploymentAddRevisionModalPresetDetailQuery } from '../__generated__/DeploymentAddRevisionModalPresetDetailQuery.graphql';
import type { DeploymentAddRevisionModalQuery } from '../__generated__/DeploymentAddRevisionModalQuery.graphql';
import type {
DeploymentAddRevisionModalSelectedPresetQuery,
DeploymentAddRevisionModalSelectedPresetQuery$data,
} from '../__generated__/DeploymentAddRevisionModalSelectedPresetQuery.graphql';
import { convertToBinaryUnit } from '../helper';
import {
formatShellCommand,
tokenizeShellCommand,
} from '../helper/parseCliCommand';
import {
mergeExtraArgs,
reverseMapExtraArgs,
} from '../helper/runtimeExtraArgsParser';
import { useBAISettingUserState } from '../hooks/useBAISetting';
import { useCurrentProjectValue } from '../hooks/useCurrentProject';
import {
buildArgsSchemaKeySet,
buildDefaultsMap,
flattenPresets,
getAllExtraArgsEnvVarNames,
getExtraArgsEnvVarName,
type RuntimeParameterGroup,
} from '../hooks/useRuntimeParameterSchema';
import DeploymentPresetDetailModal from './DeploymentPresetDetailModal';
import EnvVarFormList, { type EnvVarFormListValue } from './EnvVarFormList';
import ImageEnvironmentSelectFormItems, {
type ImageEnvironmentFormInput,
} from './ImageEnvironmentSelectFormItems';
import RuntimeParameterFormSection, {
type RuntimeParameterValues,
} from './RuntimeParameterFormSection';
import ResourceAllocationFormItems, {
AUTOMATIC_DEFAULT_SHMEM,
RESOURCE_ALLOCATION_INITIAL_FORM_VALUES,
type ResourceAllocationFormValue,
} from './SessionFormItems/ResourceAllocationFormItems';
import VFolderTableFormItem, {
type VFolderTableFormValues,
} from './VFolderTableFormItem';
import { InfoCircleOutlined } from '@ant-design/icons';
import {
Alert,
App,
Button,
Checkbox,
Collapse,
Divider,
Form,
Input,
InputNumber,
Segmented,
Skeleton,
Space,
Tooltip,
Typography,
theme,
} from 'antd';
import type { FormInstance } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import {
BAIAvailablePresetSelect,
BAIFlex,
BAIModal,
BAIModalProps,
BAIRuntimeVariantSelect,
BAIVFolderSelect,
convertToUUID,
safeDecodeUuid,
toLocalId,
useBAILogger,
} from 'backend.ai-ui';
import * as _ from 'lodash-es';
import React, {
Suspense,
useDeferredValue,
useEffect,
useEffectEvent,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
fetchQuery,
graphql,
useLazyLoadQuery,
useMutation,
useRelayEnvironment,
} from 'react-relay';
export type FormValues = ImageEnvironmentFormInput &
ResourceAllocationFormValue &
VFolderTableFormValues & {
runtimeVariantId: string;
modelFolderId: string;
mountDestination: string;
definitionPath: string;
customDefinitionMode?: 'command' | 'file';
startCommand?: string;
commandPort?: number;
commandHealthCheck?: string;
commandModelMount?: string;
commandInitialDelay?: number;
commandMaxRetries?: number;
commandInterval?: number;
commandMaxWaitTime?: number;
environ: EnvVarFormListValue[];
};
export type PresetFormValues = {
revisionPresetId: string;
modelFolderId: string;
};
interface DeploymentAddRevisionModalProps extends BAIModalProps {
onRequestClose: (success?: boolean) => void;
deploymentId: string;
open?: boolean;
}
const SectionHeader: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { token } = theme.useToken();
return (
<Divider titlePlacement="left">
<Typography.Text type="secondary" style={{ fontSize: token.fontSizeSM }}>
{children}
</Typography.Text>
</Divider>
);
};
// Loader for the preset-detail modal in this paginated context. The Preset
// selector here (`BAIAvailablePresetSelect`) paginates independently of the
// modal's main query, so we cannot spread `DeploymentPresetDetailModalFragment`
// on a list edge. Instead, when the user opens the detail view, fire a tiny
// singular query keyed by the selected presetId and hand the fragment ref
// directly to `DeploymentPresetDetailModal`.
const PresetDetailLoader: React.FC<{
presetId: string;
onCancel: () => void;
}> = ({ presetId, onCancel }) => {
'use memo';
const data = useLazyLoadQuery<DeploymentAddRevisionModalPresetDetailQuery>(
graphql`
query DeploymentAddRevisionModalPresetDetailQuery($id: UUID!) {
deploymentRevisionPreset(id: $id) {
...DeploymentPresetDetailModalFragment
}
}
`,
{ id: presetId },
);
return (
<DeploymentPresetDetailModal
open
presetFrgmt={data.deploymentRevisionPreset}
onCancel={onCancel}
/>
);
};
const DeploymentAddRevisionModal: React.FC<DeploymentAddRevisionModalProps> = ({
onRequestClose,
deploymentId,
open,
...restModalProps
}) => {
'use memo';
const { t } = useTranslation();
const { token } = theme.useToken();
const { message } = App.useApp();
const relayEnvironment = useRelayEnvironment();
// The model folder picker scopes to the user's current project so the
// listing matches what the user has access to in the active project
// context, consistent with the rest of the model-deployment UI
// (ServiceLauncherPageContent, ModelCardDeployModal).
const { id: currentProjectId } = useCurrentProjectValue();
const { logger } = useBAILogger();
// Defer `open` so the lazy query only fires once the modal has actually
// committed to opening. `loading={deferredOpen !== open}` then lets the
// modal show its built-in skeleton during the transition instead of an
// inner Suspense fallback (FR-2862 review).
const deferredOpen = useDeferredValue(open);
const [customForm] = Form.useForm<FormValues>();
const [presetForm] = Form.useForm<PresetFormValues>();
// FR-2862 feedback: hoist `autoActivate` from the Custom body into the
// modal so it can be rendered in the modal footer. Both modes forward
// the value via `AddRevisionOptions.autoActivate` on `addModelRevision`.
const [autoActivate, setAutoActivate] = useState(true);
const [mode, setMode] = useBAISettingUserState(
'deploymentRevisionCreationMode',
);
const effectiveMode = mode ?? 'preset';
// One-shot carry-over consumed by the Custom body on mount. Set when the
// user transitions Preset → Custom with a preset selected.
const [presetTransferPrefill, setPresetTransferPrefill] =
useState<Partial<FormValues> | null>(null);
// One-shot carry-over consumed by the Preset body on mount. Set when the
// user transitions Custom → Preset; carries the selected model folder so
// the user does not have to re-pick it after switching modes.
const [customTransferPrefill, setCustomTransferPrefill] =
useState<Partial<PresetFormValues> | null>(null);
// Preset detail modal target — opens DeploymentPresetDetailModal when the
// user clicks the (i) button next to the preset selector. The modal owns
// its own Relay query keyed by this id.
const [presetDetailId, setPresetDetailId] = useState<string | null>(null);
// Map of runtime variant id → name, populated by `BAIRuntimeVariantSelect`
// as it resolves the currently selected value (via its `runtimeVariant(id:)`
// point lookup) and the visible page of the paginated list. Used by the
// form to branch on `variantName === 'custom'` and to look up the human-
// readable name at submit time, without owning the variant list here.
const [runtimeVariantNameMap, setRuntimeVariantNameMap] = useState<
Record<string, string>
>({});
// Runtime parameter refs — kept outside form state so slider/input changes
// don't re-render the modal. Read at submit time via serializeRuntimeParamsToEnviron.
const runtimeParamValuesRef = useRef<RuntimeParameterValues>({});
const runtimeParamTouchedKeysRef = useRef<Set<string>>(new Set());
const runtimeParamGroupsRef = useRef<RuntimeParameterGroup[] | null>(null);
// Initial values fed into `RuntimeParameterFormSection` for non-custom
// variants — split out of `currentRevision.modelRuntimeConfig.environ`
// once at mount time so the runtime-parameter UI can reverse-map ARGS-
// and ENV-typed presets back into their controls. State (not ref) so the
// child re-renders with the right initial data after the body resolves.
const [initialRuntimeExtraArgs, setInitialRuntimeExtraArgs] = useState('');
const [initialRuntimeEnvVars, setInitialRuntimeEnvVars] = useState<
Record<string, string> | undefined
>(undefined);
// Snapshot of prefilled `extraMounts.mountDestination`, keyed by the
// dash-stripped vfolder id. Read at submit time as a fallback when
// `values.mount_id_map` does not have the entry — VFolderTable's
// `onChangeAliasMap` *replaces* (not merges) the alias map and only
// surfaces aliases for rows that are visible in the current filtered
// table view, so any extra mount that lives outside that view (e.g. a
// vfolder owned by another user that the deployment was created with)
// would lose its alias as soon as the user edits *any* visible row's
// alias. The backend requires `mount_destination`, so without this
// fallback the next submit fails with `ExtraVFolderMountInput.__init__()
// missing 1 required keyword-only argument: 'mount_destination'`.
const prefilledMountAliasesRef = useRef<Record<string, string>>({});
const data = useLazyLoadQuery<DeploymentAddRevisionModalQuery>(
graphql`
query DeploymentAddRevisionModalQuery($deploymentId: ID!) {
deployment(id: $deploymentId) {
metadata {
resourceGroupName
}
currentRevision {
clusterConfig {
mode
size
}
resourceConfig {
resourceOpts {
entries {
name
value
}
}
}
resourceSlots {
slotName
quantity
}
extraMounts {
vfolderId
mountDestination
}
modelRuntimeConfig {
runtimeVariantId
runtimeVariant {
name
}
environ {
entries {
name
value
}
}
}
modelMountConfig {
vfolderId
mountDestination
definitionPath
}
modelDefinition {
models {
name
modelPath
service {
startCommand
port
healthCheck {
path
maxRetries
initialDelay
interval
maxWaitTime
}
}
}
}
imageV2 {
id
identity {
canonicalName
}
}
}
}
}
`,
{ deploymentId },
{
// Skip the network round-trip until the modal has actually committed
// to opening (`deferredOpen === open === true`); `store-and-network`
// afterwards so re-opening after a successful `addModelRevision`
// mutation pulls a fresh `currentRevision` instead of the cached one.
fetchPolicy: deferredOpen && open ? 'store-and-network' : 'store-only',
},
);
const deployment = data.deployment;
const currentRevision = deployment?.currentRevision;
// The preset "empty state" probe runs as a side-effect fetchQuery rather
// than part of the main `useLazyLoadQuery`, because reading the count
// from the lazy query throws a Suspense up to the nearest parent
// boundary — which, with no inner boundary, lands in the deployment
// detail page and blanks the whole page while the modal opens.
// `undefined` means "still probing"; we render the form optimistically
// until the answer arrives.
const [hasNoPresets, setHasNoPresets] = useState<boolean | undefined>(
undefined,
);
useEffect(() => {
if (!open) return;
let cancelled = false;
fetchQuery<DeploymentAddRevisionModalPresetCountQuery>(
relayEnvironment,
graphql`
query DeploymentAddRevisionModalPresetCountQuery {
deploymentRevisionPresets(
orderBy: [{ field: RANK, direction: "ASC" }]
first: 1
) {
count
}
}
`,
{},
{ fetchPolicy: 'store-or-network' },
)
.toPromise()
.then((result) => {
if (cancelled) return;
setHasNoPresets((result?.deploymentRevisionPresets?.count ?? 0) === 0);
})
.catch(() => {
if (cancelled) return;
// On error, assume presets exist — the BAIAvailablePresetSelect's
// own paginated query will surface a per-select empty state if it
// also fails.
setHasNoPresets(false);
});
return () => {
cancelled = true;
};
}, [open, relayEnvironment]);
// The parent deployment's vfolder is the default Model Folder. Users can
// override it in this mode (in contrast to the VFolder/ModelStore entry
// point where the folder is locked in by context).
const defaultModelFolderId =
currentRevision?.modelMountConfig?.vfolderId ?? undefined;
// The `BAIAvailablePresetSelect` paginates independently of this modal's
// main query (it can scroll past the first page on demand), so the user
// can select a preset that does not appear in any local list we hold.
// Resolve the selected preset's full data on demand via the singular
// `deploymentRevisionPreset(id:)` query — used by `handleModeChange` to
// prefill the Custom form. A small in-memory cache avoids refetching when
// the same preset is referenced multiple times during a session.
const presetDataCacheRef = useRef<
Map<
string,
NonNullable<
DeploymentAddRevisionModalSelectedPresetQuery$data['deploymentRevisionPreset']
>
>
>(new Map());
const fetchPresetData = async (
presetId: string,
): Promise<NonNullable<
DeploymentAddRevisionModalSelectedPresetQuery$data['deploymentRevisionPreset']
> | null> => {
const cached = presetDataCacheRef.current.get(presetId);
if (cached) return cached;
const result =
await fetchQuery<DeploymentAddRevisionModalSelectedPresetQuery>(
relayEnvironment,
graphql`
query DeploymentAddRevisionModalSelectedPresetQuery($id: UUID!) {
deploymentRevisionPreset(id: $id) {
id
runtimeVariantId
cluster {
clusterMode
clusterSize
}
execution {
imageId
environ {
key
value
}
}
resource {
resourceOpts {
name
value
}
}
resourceSlots {
slotName
quantity
}
}
}
`,
{ id: presetId },
{ fetchPolicy: 'store-or-network' },
).toPromise();
const preset = result?.deploymentRevisionPreset ?? null;
if (preset) {
presetDataCacheRef.current.set(presetId, preset);
}
return preset;
};
// The `revision.deployment` selection (added in BA-6056) lets the mutation
// update the parent deployment record in the Relay store atomically — so
// row tags in the revision history table and the Configuration Section's
// "current / deploying" panels stay consistent without a manual refresh.
// `currentRevisionId` / `deployingRevisionId` aren't in any deployment
// fragment yet (DeploymentRevisionHistoryTab reads them inline), so they
// are selected explicitly here.
const [commitAdd, isAddInFlight] =
useMutation<DeploymentAddRevisionModalAddMutation>(graphql`
mutation DeploymentAddRevisionModalAddMutation(
$input: AddRevisionInput!
) {
addModelRevision(input: $input) {
revision {
id
...DeploymentRevisionDetail_revision
deployment @since(version: "26.4.4") {
id
currentRevisionId
deployingRevisionId
currentRevision @since(version: "26.4.3") {
id
...DeploymentRevisionDetail_revision
}
deployingRevision @since(version: "26.4.3") {
id
...DeploymentRevisionDetail_revision
}
}
}
}
}
`);
// Build a Custom-form prefill object from a preset node read off the
// singular `deploymentRevisionPreset(id:)` query (resolved via
// `fetchPresetData`). `image canonicalName` is fetched async because
// `ImageEnvironmentSelectFormItems` matches the form's `environments.version`
// against canonical names.
const buildPrefillFromPreset = async (
preset: NonNullable<
DeploymentAddRevisionModalSelectedPresetQuery$data['deploymentRevisionPreset']
>,
): Promise<Partial<FormValues>> => {
const slots = preset.resourceSlots ?? [];
const cpuSlot = slots.find((s) => s.slotName === 'cpu');
const memSlot = slots.find((s) => s.slotName === 'mem');
const acceleratorSlot = slots.find(
(s) => s.slotName !== 'cpu' && s.slotName !== 'mem',
);
const shmemEntry = (preset.resource?.resourceOpts ?? []).find(
(e) => e.name === 'shmem',
);
const clusterMode =
preset.cluster?.clusterMode === 'SINGLE_NODE'
? ('single-node' as const)
: ('multi-node' as const);
let imageCanonicalName: string | undefined;
if (preset.execution?.imageId) {
try {
const result =
await fetchQuery<DeploymentAddRevisionModalImageNameQuery>(
relayEnvironment,
graphql`
query DeploymentAddRevisionModalImageNameQuery($id: ID!) {
imageV2(id: $id) {
identity {
canonicalName
}
}
}
`,
{ id: preset.execution.imageId },
{ fetchPolicy: 'store-or-network' },
).toPromise();
imageCanonicalName =
result?.imageV2?.identity?.canonicalName ?? undefined;
} catch {
imageCanonicalName = undefined;
}
}
const environEntries = (preset.execution?.environ ?? []).map((e) => ({
variable: e.key,
value: e.value,
}));
// `setFieldsValue` accepts a deep partial structurally even though
// FormValues' nested `environments` requires `environment` / `image`.
// Build as a loosely-typed record and let antd handle merging.
const prefill: Record<string, unknown> = {
cluster_mode: clusterMode,
cluster_size: preset.cluster?.clusterSize ?? 1,
allocationPreset: 'custom',
resource: {
cpu: cpuSlot ? Number(cpuSlot.quantity) : 0,
mem:
convertToBinaryUnit(String(memSlot?.quantity ?? '0'), 'g', 2)
?.value ?? '0g',
shmem:
convertToBinaryUnit(
shmemEntry?.value ?? AUTOMATIC_DEFAULT_SHMEM,
'g',
2,
)?.value ?? AUTOMATIC_DEFAULT_SHMEM,
...(acceleratorSlot
? {
acceleratorType: acceleratorSlot.slotName,
accelerator:
acceleratorSlot.slotName === 'cuda.shares'
? parseFloat(String(acceleratorSlot.quantity))
: parseInt(String(acceleratorSlot.quantity), 10),
}
: {}),
},
enabledAutomaticShmem: !shmemEntry,
runtimeVariantId: preset.runtimeVariantId ?? undefined,
environ: environEntries,
...(imageCanonicalName
? { environments: { version: imageCanonicalName } }
: {}),
};
return prefill as Partial<FormValues>;
};
const handleModeChange = async (next: 'preset' | 'custom') => {
if (next === effectiveMode) return;
if (effectiveMode === 'preset' && next === 'custom') {
// Carry the currently selected preset (if any) into the Custom form.
// Also carry the model folder the user picked in Preset mode (spec (d)).
//
// Read the preset id from the form (source of truth for the selection,
// since `BAIAvailablePresetSelect` is wrapped in a named `Form.Item`),
// then resolve the preset's full data via the singular
// `deploymentRevisionPreset(id:)` query so this works regardless of
// which page the select scrolled to.
const presetValues = presetForm.getFieldsValue();
const selectedPresetId = presetValues.revisionPresetId;
let prefill: Partial<FormValues> = {};
if (selectedPresetId) {
const preset = await fetchPresetData(selectedPresetId);
if (preset) {
prefill = await buildPrefillFromPreset(preset);
}
}
if (presetValues.modelFolderId) {
prefill.modelFolderId = presetValues.modelFolderId;
}
setPresetTransferPrefill(
Object.keys(prefill).length > 0 ? prefill : null,
);
setMode('custom');
return;
}
// Custom → Preset: discard custom edits (spec line 206), but carry over
// the model folder the user picked in Custom mode so the selection is
// not lost across mode switches (parallel to Preset → Custom carry-over).
const customValues = customForm.getFieldsValue();
const carryOver: Partial<PresetFormValues> = {};
if (customValues.modelFolderId) {
carryOver.modelFolderId = customValues.modelFolderId;
}
customForm.resetFields();
setPresetTransferPrefill(null);
setCustomTransferPrefill(
Object.keys(carryOver).length > 0 ? carryOver : null,
);
setMode('preset');
};
// Build the form values that mirror the deployment's current revision and
// push them into the Custom antd Form. Called from the "Load current
// revision" button on the Alert; the React Compiler handles memoization
// under the `'use memo'` directive so a plain function suffices.
const prefillFromCurrentRevision = () => {
if (!currentRevision) return;
const rev = currentRevision;
const slots = rev.resourceSlots ?? [];
const cpuSlot = slots.find((s) => s.slotName === 'cpu');
const memSlot = slots.find((s) => s.slotName === 'mem');
const acceleratorSlot = slots.find(
(s) => s.slotName !== 'cpu' && s.slotName !== 'mem',
);
const shmemEntry = (rev.resourceConfig?.resourceOpts?.entries ?? []).find(
(e) => e.name === 'shmem',
);
// The query selects `modelRuntimeConfig.runtimeVariant.name`, so the
// prefill path knows the variant name without waiting for
// `BAIRuntimeVariantSelect` to resolve it.
const variantName = rev.modelRuntimeConfig?.runtimeVariant?.name ?? '';
const isCustom = variantName === 'custom';
// Seed `runtimeVariantNameMap` so submit and any other consumers can
// resolve `runtimeVariantId → name` immediately, without waiting for
// `BAIRuntimeVariantSelect`'s point lookup to finish.
const variantId = rev.modelRuntimeConfig?.runtimeVariantId;
if (variantId && variantName) {
setRuntimeVariantNameMap((prev) => ({
...prev,
[variantId]: variantName,
}));
}
const service = rev.modelDefinition?.models?.[0]?.service;
const customModelPath = rev.modelDefinition?.models?.[0]?.modelPath;
// For custom + command mode: the saved revision carries a populated
// `modelDefinition` with a `startCommand` token list. For custom +
// file mode the form serializes to a null `modelDefinition`, so the
// absence of `service.startCommand` indicates file mode.
const hasCustomCommand =
isCustom && !!service && (service.startCommand?.length ?? 0) > 0;
prefilledMountAliasesRef.current = _.fromPairs(
(rev.extraMounts ?? [])
.filter((m) => !!m.mountDestination)
.map((m) => [
m.vfolderId.replace(/-/g, ''),
m.mountDestination as string,
]),
);
// Split `environ` for non-custom variants: the runtime-parameter
// section uses one designated env var (e.g. `BACKEND_VLLM_EXTRA_ARGS`)
// to encode CLI-style ARGS presets, and individual env vars for ENV
// presets. Build both sides and stash them so the child can reverse-map.
const environRecord: Record<string, string> = Object.fromEntries(
(rev.modelRuntimeConfig?.environ?.entries ?? []).map((e) => [
e.name,
e.value,
]),
);
if (!isCustom && variantName) {
const extraArgsKey = getExtraArgsEnvVarName(variantName);
const { [extraArgsKey]: extraArgsValue, ...envVarsWithoutArgs } =
environRecord;
setInitialRuntimeExtraArgs(extraArgsValue ?? '');
setInitialRuntimeEnvVars(
Object.keys(envVarsWithoutArgs).length > 0
? envVarsWithoutArgs
: undefined,
);
}
customForm.setFieldsValue({
cluster_mode:
rev.clusterConfig?.mode === 'SINGLE_NODE'
? 'single-node'
: 'multi-node',
cluster_size: rev.clusterConfig?.size ?? 1,
// Keep `ResourceAllocationFormItems`' auto-preset effect from
// clobbering the prefilled resource values. That effect runs when
// `allocationPreset === 'auto-select'` (the default) and rewrites
// cpu/mem to the first allocatable preset's values, which would
// erase the cpu/mem we set just below.
allocationPreset: 'custom',
resource: {
cpu: cpuSlot ? Number(cpuSlot.quantity) : 0,
mem:
convertToBinaryUnit(String(memSlot?.quantity ?? '0'), 'g', 2)
?.value ?? '0g',
shmem:
convertToBinaryUnit(
shmemEntry?.value ?? AUTOMATIC_DEFAULT_SHMEM,
'g',
2,
)?.value ?? AUTOMATIC_DEFAULT_SHMEM,
...(acceleratorSlot
? {
acceleratorType: acceleratorSlot.slotName,
accelerator:
acceleratorSlot.slotName === 'cuda.shares'
? parseFloat(String(acceleratorSlot.quantity))
: parseInt(String(acceleratorSlot.quantity), 10),
}
: {}),
},
enabledAutomaticShmem: !shmemEntry,
// VFolderTable's `rowKey="id"` uses the 32-char-hex form, so
// selectedRowKeys must match that shape for prefilled rows to
// appear checked.
mount_ids: (rev.extraMounts ?? []).map((m) =>
m.vfolderId.replace(/-/g, ''),
),
mount_id_map: _.fromPairs(
(rev.extraMounts ?? [])
.filter((m) => !!m.mountDestination)
.map((m) => [
m.vfolderId.replace(/-/g, ''),
m.mountDestination as string,
]),
),
runtimeVariantId: rev.modelRuntimeConfig?.runtimeVariantId ?? undefined,
// BAIVFolderSelect with `valuePropName="row_id"` returns the
// canonical dashed UUID, which matches `rev.modelMountConfig.vfolderId`
// directly. `convertToUUID` in the submit is idempotent on already-
// dashed values.
modelFolderId: rev.modelMountConfig?.vfolderId ?? undefined,
mountDestination: rev.modelMountConfig?.mountDestination ?? '/models',
definitionPath: rev.modelMountConfig?.definitionPath ?? undefined,
// `ImageEnvironmentSelectFormItems` matches the form's
// `environments.version` against its image catalog by canonical
// name; setting this is enough to drive the rest of the
// environment selector (registry/namespace/tag) and ultimately
// populate `environments.image.id`.
environments: rev.imageV2?.identity?.canonicalName
? { version: rev.imageV2.identity.canonicalName }
: undefined,
// EnvVarFormList stores entries as { variable, value } — translate
// from the GraphQL `{ name, value }` shape on prefill.
environ: (rev.modelRuntimeConfig?.environ?.entries ?? []).map((e) => ({
variable: e.name,
value: e.value,
})),
...(hasCustomCommand && service
? {
customDefinitionMode: 'command' as const,
startCommand: formatShellCommand(service.startCommand ?? []),
commandPort: service.port,
commandHealthCheck: service.healthCheck?.path ?? undefined,
commandModelMount: customModelPath ?? '/models',
commandInitialDelay: service.healthCheck?.initialDelay ?? undefined,
commandMaxRetries: service.healthCheck?.maxRetries ?? undefined,
commandInterval: service.healthCheck?.interval ?? undefined,
commandMaxWaitTime: service.healthCheck?.maxWaitTime ?? undefined,
}
: isCustom
? { customDefinitionMode: 'file' as const }
: {}),
});
};
// One-shot consumption of preset-transfer prefill when the user transitions
// to Custom mode. The Preset→Custom switch sets `presetTransferPrefill`;
// here we apply it as soon as Custom mode is active, then clear it.
const consumePresetTransferPrefill = useEffectEvent(() => {
if (!presetTransferPrefill) return;
customForm.setFieldsValue(presetTransferPrefill as FormValues);
setPresetTransferPrefill(null);
});
// Mirror image of the above for Custom → Preset transitions. Applied after
// the Preset form mounts, since `setFieldsValue` before the fields are
// registered does not stick.
const consumeCustomTransferPrefill = useEffectEvent(() => {
if (!customTransferPrefill) return;
presetForm.setFieldsValue(customTransferPrefill as PresetFormValues);
setCustomTransferPrefill(null);
});
useEffect(() => {
if (effectiveMode === 'custom') {
consumePresetTransferPrefill();
} else {
consumeCustomTransferPrefill();
}
}, [effectiveMode]);
// Serialize runtime parameter UI values (from RuntimeParameterFormSection)
// into an environ map — mirrors ServiceLauncherPageContent logic.
const serializeRuntimeParamsToEnviron = (
environ: Record<string, string>,
runtimeVariant: string,
) => {
const groups = runtimeParamGroupsRef.current;
if (!groups || Object.keys(runtimeParamValuesRef.current).length === 0)
return;
const extraArgsEnvVar = getExtraArgsEnvVarName(runtimeVariant);
for (const envName of getAllExtraArgsEnvVarNames()) {
if (envName !== extraArgsEnvVar) delete environ[envName];
}
const touchedValues: Record<string, string> = {};
for (const [key, val] of Object.entries(runtimeParamValuesRef.current)) {
if (runtimeParamTouchedKeysRef.current.has(key)) touchedValues[key] = val;
}
const presets = flattenPresets(groups);
const presetMap = new Map(presets.map((p) => [p.key, p]));
const defaults = buildDefaultsMap(groups);
const argsValues: Record<string, string> = {};
const envValues: Record<string, string> = {};
for (const [key, val] of Object.entries(touchedValues)) {
if (val === '' || val === undefined) continue;
const preset = presetMap.get(key);
if (!preset) continue;
if (preset.presetTarget === 'ENV') envValues[key] = val;
else argsValues[key] = val;
}
const argsSchemaKeys = buildArgsSchemaKeySet(groups);
if (environ[extraArgsEnvVar] && argsSchemaKeys.size > 0) {
const { unmappedText } = reverseMapExtraArgs(
environ[extraArgsEnvVar],
argsSchemaKeys,
);
if (unmappedText) environ[extraArgsEnvVar] = unmappedText;
else delete environ[extraArgsEnvVar];
}
for (const preset of presets) {
if (preset.presetTarget === 'ENV') delete environ[preset.key];
}
if (Object.keys(argsValues).length > 0) {
const manualArgs = environ[extraArgsEnvVar] ?? '';
const merged = mergeExtraArgs(argsValues, manualArgs, defaults);
if (merged) environ[extraArgsEnvVar] = merged;
else delete environ[extraArgsEnvVar];
}
for (const [key, val] of Object.entries(envValues)) {
const preset = presetMap.get(key);
if (preset?.defaultValue !== null && preset?.defaultValue === val)
continue;
environ[key] = val;
}
};
const handleCustomFinish = (values: FormValues): void => {
// `setFields` raises an error programmatically — antd's
// `scrollToFirstError` only fires from `onFinishFailed`, so we have
// to nudge the scroll explicitly here.
const flagImageRequired = () => {
customForm.setFields([
{
name: ['environments', 'version'],
errors: [t('modelService.ImageRequired')],
},
]);
customForm.scrollToField(['environments', 'version'], {
behavior: 'smooth',
block: 'center',
});
};
const imageId = values.environments?.image?.id;
if (!imageId) {
flagImageRequired();
return;
}
// `ImageInput.id` is declared as `ID!` but parsed as `UUID!` server-side.
const decodedImageId = safeDecodeUuid(imageId);
if (!decodedImageId) {
flagImageRequired();
return;
}
const slotEntries: { resourceType: string; quantity: string }[] = [
{ resourceType: 'cpu', quantity: String(values.resource.cpu) },
{ resourceType: 'mem', quantity: values.resource.mem },
];
if (
values.resource.acceleratorType &&
values.resource.accelerator &&
values.resource.accelerator > 0
) {
slotEntries.push({
resourceType: values.resource.acceleratorType,
quantity: String(values.resource.accelerator),
});
}
const optsEntries: { name: string; value: string }[] = [];
if (values.resource.shmem) {
optsEntries.push({ name: 'shmem', value: values.resource.shmem });
}
const clusterMode =
values.cluster_mode === 'single-node' ||
(values.cluster_mode === 'multi-node' && values.cluster_size === 1)
? 'SINGLE_NODE'
: 'MULTI_NODE';
const vfoldersNameMap: Record<string, string> =
values.vfoldersNameMap ?? {};
const extraMounts = (values.mount_ids ?? []).map((vfolderId) => {
const mountDestination =
values.mount_id_map?.[vfolderId] ||
prefilledMountAliasesRef.current[vfolderId] ||
(vfoldersNameMap[vfolderId]
? `/home/work/${vfoldersNameMap[vfolderId]}`
: `/home/work/${vfolderId}`);
return {
vfolderId: convertToUUID(vfolderId),
mountDestination,
};
});
const variantName = runtimeVariantNameMap[values.runtimeVariantId] ?? '';
const isCustom = variantName === 'custom';
const isCommandMode = values.customDefinitionMode === 'command';
const environRecord: Record<string, string> = {};
for (const { variable, value } of values.environ ?? []) {
if (variable) environRecord[variable] = value;
}
if (!isCustom) {
serializeRuntimeParamsToEnviron(environRecord, variantName);
}
const environEntries = Object.entries(environRecord).map(
([name, value]) => ({ name, value }),
);
const modelDefinition =
isCustom && isCommandMode && values.startCommand
? {
models: [
{
name: 'model',
modelPath: values.commandModelMount ?? '/models',
service: {
preStartActions: [],
startCommand: tokenizeShellCommand(values.startCommand),
port: values.commandPort ?? 8000,
healthCheck: values.commandHealthCheck
? {
path: values.commandHealthCheck,
interval: values.commandInterval ?? 10,
maxRetries: values.commandMaxRetries ?? 10,
maxWaitTime: values.commandMaxWaitTime ?? 15,
initialDelay: values.commandInitialDelay,
}
: null,
},
},
],
}
: null;
const mountDestination =