✨ Add multi-PVC mounts for lightweight operators

This commit is contained in:
eust-w 2026-07-10 11:27:01 +08:00
parent ea5255db77
commit dcb103d686
11 changed files with 579 additions and 45 deletions

View File

@ -0,0 +1,47 @@
# Lightweight operator PVC mounts
Lightweight operators keep their executable code in the required `codeSubPath` mount and may declare additional PVC mounts in `runtimeContract.lightweightOperator.mounts`.
```json
{
"runtimeContract": {
"lightweightOperator": {
"enabled": true,
"codeSubPath": "lightweight-operators/example",
"mountPath": "/opt/droboticflow/lightweight/operator",
"mounts": [
{
"name": "dataset",
"pvcName": "dataset-pvc",
"subPath": "robotwin",
"mountPath": "/data/robotwin",
"readOnly": true,
"ideEnabled": true
},
{
"name": "outputs",
"pvcName": "droboticflow-workspace",
"subPath": "outputs/example",
"mountPath": "/outputs",
"readOnly": false,
"ideEnabled": true
}
]
}
}
}
```
Every mount requires a unique `name`, `pvcName`, and absolute `mountPath`. `subPath` may be empty to mount the PVC root. Mount paths must not overlap the code mount, another configured mount, or platform run output paths. Invalid configurations fail before a Kubernetes Job is created; the platform does not infer or replace missing values.
Kubernetes volumes are deduplicated by PVC name, so one PVC can expose multiple independent subdirectories. `readOnly` is passed directly to the container volume mount. Code remains read-only at runtime, while platform run output paths retain their dedicated writable mount.
The operator file IDE always manages the code directory and also lists mounts with `ideEnabled=true`. A mount is editable only when `readOnly=false`. The API process can directly manage only PVCs mounted into its file-management service; selecting another PVC returns an explicit validation error instead of reading a different directory or falling back to the workspace PVC.
File API calls select a configured mount with the optional `mount` query parameter:
```text
GET /api/operators/:id/lightweight-files?mount=dataset
GET /api/operators/:id/lightweight-files/content?path=state.json&mount=dataset
PUT /api/operators/:id/lightweight-files/content?mount=outputs
```

View File

@ -4187,6 +4187,7 @@ func validateLightweightOperatorMetadata(image string, contract map[string]any,
Args: containerArgs,
ArgsConfigured: config.ContainerArgsConfigured,
WorkspaceRoot: workspaceMountPath,
Mounts: config.Mounts,
}); err != nil {
issues = append(issues, validationIssue{Field: "runtimeContract.lightweightOperator", Message: err.Error()})
}
@ -4535,6 +4536,7 @@ const (
var errLightweightOperatorFileListLimit = errors.New("lightweight operator file list limit reached")
type lightweightOperatorCodeRoot struct {
Name string
CodeSubPath string
MountPath string
WorkspacePath string
@ -4542,6 +4544,7 @@ type lightweightOperatorCodeRoot struct {
RootRealPath string
WorkspaceReal string
Exists bool
ReadOnly bool
}
type lightweightOperatorFileItem struct {
@ -4631,7 +4634,7 @@ func (server *server) loadLightweightOperatorForFileRequest(writer http.Response
return item, true
}
func (server *server) resolveLightweightOperatorCodeRoot(item domain.OperatorRecord) (lightweightOperatorCodeRoot, *validationIssue, error) {
func (server *server) resolveLightweightOperatorCodeRoot(item domain.OperatorRecord, mountName string) (lightweightOperatorCodeRoot, *validationIssue, error) {
config := lightweight.ConfigFromContract(item.RuntimeContract)
if err := lightweight.ValidateRuntimeConfig(lightweight.RuntimeConfig{
NodeID: item.ID,
@ -4643,6 +4646,7 @@ func (server *server) resolveLightweightOperatorCodeRoot(item domain.OperatorRec
Args: item.ContainerArgs,
ArgsConfigured: config.ContainerArgsConfigured,
WorkspaceRoot: server.workspaceMountPath,
Mounts: config.Mounts,
}); err != nil {
return lightweightOperatorCodeRoot{}, &validationIssue{Field: "runtimeContract.lightweightOperator", Message: err.Error()}, nil
}
@ -4658,16 +4662,46 @@ func (server *server) resolveLightweightOperatorCodeRoot(item domain.OperatorRec
if err != nil {
return lightweightOperatorCodeRoot{}, nil, fmt.Errorf("workspace root is not readable: %w", err)
}
rootPath := filepath.Clean(filepath.Join(workspaceRoot, filepath.FromSlash(config.CodeSubPath)))
selectedName := strings.TrimSpace(mountName)
selectedSubPath := config.CodeSubPath
selectedMountPath := config.MountPath
selectedReadOnly := false
if selectedName != "" && selectedName != "code" {
found := false
for _, mount := range config.Mounts {
if mount.Name != selectedName {
continue
}
found = true
if !mount.IDEEnabled {
return lightweightOperatorCodeRoot{}, &validationIssue{Field: "mount", Message: "file IDE is disabled for this mount"}, nil
}
if mount.PVCName != strings.TrimSpace(server.workspacePVCName) {
return lightweightOperatorCodeRoot{}, &validationIssue{Field: "mount", Message: "PVC is not mounted into the file management service"}, nil
}
selectedSubPath = mount.SubPath
selectedMountPath = mount.MountPath
selectedReadOnly = mount.ReadOnly
break
}
if !found {
return lightweightOperatorCodeRoot{}, &validationIssue{Field: "mount", Message: "configured mount was not found"}, nil
}
} else {
selectedName = "code"
}
rootPath := filepath.Clean(filepath.Join(workspaceRoot, filepath.FromSlash(selectedSubPath)))
if !localPathInside(rootPath, workspaceRoot) {
return lightweightOperatorCodeRoot{}, &validationIssue{Field: "runtimeContract.lightweightOperator.codeSubPath", Message: "codeSubPath must stay within the workspace PVC"}, nil
}
root := lightweightOperatorCodeRoot{
CodeSubPath: config.CodeSubPath,
MountPath: config.MountPath,
Name: selectedName,
CodeSubPath: selectedSubPath,
MountPath: selectedMountPath,
WorkspacePath: filepath.ToSlash(rootPath),
RootPath: rootPath,
WorkspaceReal: workspaceReal,
ReadOnly: selectedReadOnly,
}
info, err := os.Lstat(rootPath)
if err != nil {
@ -4694,15 +4728,18 @@ func (server *server) resolveLightweightOperatorCodeRoot(item domain.OperatorRec
return root, nil, nil
}
func (server *server) ensureLightweightOperatorCodeRoot(item domain.OperatorRecord) (lightweightOperatorCodeRoot, *validationIssue, error) {
root, issue, err := server.resolveLightweightOperatorCodeRoot(item)
func (server *server) ensureLightweightOperatorCodeRoot(item domain.OperatorRecord, mountName string) (lightweightOperatorCodeRoot, *validationIssue, error) {
root, issue, err := server.resolveLightweightOperatorCodeRoot(item, mountName)
if err != nil || issue != nil || root.Exists {
return root, issue, err
}
if root.ReadOnly {
return lightweightOperatorCodeRoot{}, &validationIssue{Field: "mount", Message: "read-only mount cannot be created or modified"}, nil
}
if err := os.MkdirAll(root.RootPath, 0o755); err != nil {
return lightweightOperatorCodeRoot{}, nil, fmt.Errorf("code directory cannot be created: %w", err)
}
return server.resolveLightweightOperatorCodeRoot(item)
return server.resolveLightweightOperatorCodeRoot(item, mountName)
}
func cleanLightweightOperatorFilePath(value string) (string, error) {
@ -4769,7 +4806,7 @@ func (server *server) handleOperatorLightweightFilesList(writer http.ResponseWri
if !ok {
return
}
root, issue, err := server.resolveLightweightOperatorCodeRoot(*item)
root, issue, err := server.resolveLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -4784,7 +4821,7 @@ func (server *server) handleOperatorLightweightFilesList(writer http.ResponseWri
MountPath: root.MountPath,
WorkspacePath: root.WorkspacePath,
Exists: root.Exists,
ReadOnly: true,
ReadOnly: root.ReadOnly,
MaxItems: lightweightOperatorFileListLimit,
Items: []lightweightOperatorFileItem{},
}
@ -4874,7 +4911,7 @@ func (server *server) handleOperatorLightweightFileContentGet(writer http.Respon
if !ok {
return
}
root, issue, err := server.resolveLightweightOperatorCodeRoot(*item)
root, issue, err := server.resolveLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -4954,7 +4991,7 @@ func (server *server) handleOperatorLightweightDirectoryCreate(writer http.Respo
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})
return
}
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item)
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -4963,6 +5000,10 @@ func (server *server) handleOperatorLightweightDirectoryCreate(writer http.Respo
renderValidationError(writer, *issue)
return
}
if root.ReadOnly {
renderValidationError(writer, validationIssue{Field: "mount", Message: "mount is read-only"})
return
}
target, err := resolveLightweightOperatorTargetPath(root, rel)
if err != nil {
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})
@ -5015,7 +5056,7 @@ func (server *server) handleOperatorLightweightFileContentPut(writer http.Respon
renderValidationError(writer, validationIssue{Field: "content", Message: "file content is too large for inline editing"})
return
}
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item)
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -5024,6 +5065,10 @@ func (server *server) handleOperatorLightweightFileContentPut(writer http.Respon
renderValidationError(writer, *issue)
return
}
if root.ReadOnly {
renderValidationError(writer, validationIssue{Field: "mount", Message: "mount is read-only"})
return
}
target, err := resolveLightweightOperatorTargetPath(root, rel)
if err != nil {
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})
@ -5081,7 +5126,7 @@ func (server *server) handleOperatorLightweightFileUpload(writer http.ResponseWr
return
}
defer file.Close()
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item)
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -5090,6 +5135,10 @@ func (server *server) handleOperatorLightweightFileUpload(writer http.ResponseWr
renderValidationError(writer, *issue)
return
}
if root.ReadOnly {
renderValidationError(writer, validationIssue{Field: "mount", Message: "mount is read-only"})
return
}
target, err := resolveLightweightOperatorTargetPath(root, rel)
if err != nil {
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})
@ -5170,7 +5219,7 @@ func (server *server) handleOperatorLightweightFileMove(writer http.ResponseWrit
renderValidationError(writer, validationIssue{Field: "newPath", Message: "newPath must be different from path"})
return
}
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item)
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -5179,6 +5228,10 @@ func (server *server) handleOperatorLightweightFileMove(writer http.ResponseWrit
renderValidationError(writer, *issue)
return
}
if root.ReadOnly {
renderValidationError(writer, validationIssue{Field: "mount", Message: "mount is read-only"})
return
}
source, err := resolveLightweightOperatorTargetPath(root, rel)
if err != nil {
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})
@ -5243,7 +5296,7 @@ func (server *server) handleOperatorLightweightFileDelete(writer http.ResponseWr
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})
return
}
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item)
root, issue, err := server.ensureLightweightOperatorCodeRoot(*item, request.URL.Query().Get("mount"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
@ -5252,6 +5305,10 @@ func (server *server) handleOperatorLightweightFileDelete(writer http.ResponseWr
renderValidationError(writer, *issue)
return
}
if root.ReadOnly {
renderValidationError(writer, validationIssue{Field: "mount", Message: "mount is read-only"})
return
}
target, err := resolveLightweightOperatorTargetPath(root, rel)
if err != nil {
renderValidationError(writer, validationIssue{Field: "path", Message: err.Error()})

View File

@ -6564,6 +6564,66 @@ func TestLightweightOperatorFileEditorCreatesMissingCodeDirectoryAndRejectsTrave
}
}
func TestLightweightOperatorFileEditorSelectsWorkspacePVCMountAndEnforcesReadOnly(t *testing.T) {
workspaceRoot := t.TempDir()
if err := os.MkdirAll(filepath.Join(workspaceRoot, "lightweight-operators", "editor"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(workspaceRoot, "datasets", "robotwin"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspaceRoot, "lightweight-operators", "editor", "operator.py"), []byte("print('ok')\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspaceRoot, "datasets", "robotwin", "state.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
handler := NewHandlerWithConfig(store.NewMemoryStore(), nil, config.AppConfig{WorkspaceMountPath: workspaceRoot, WorkspacePVCName: "workspace-pvc"})
payload := []byte(`{
"name":"Multi Mount Editor","type":"lightweight","category":"AI","description":"Edit mounted PVC directories",
"image":"python:3.11-slim","containerCommand":["python","/opt/operator/operator.py"],"containerArgs":[],
"runtimeContract":{"lightweightOperator":{"codeSubPath":"lightweight-operators/editor","mountPath":"/opt/operator","mounts":[
{"name":"dataset","pvcName":"workspace-pvc","subPath":"datasets/robotwin","mountPath":"/data","readOnly":true,"ideEnabled":true},
{"name":"models","pvcName":"model-pvc","subPath":"models","mountPath":"/models","readOnly":true,"ideEnabled":true}
]}},"inputs":[],"outputs":[]
}`)
createRecorder := httptest.NewRecorder()
handler.ServeHTTP(createRecorder, httptest.NewRequest(http.MethodPost, "/api/operators", bytes.NewReader(payload)))
if createRecorder.Code != http.StatusCreated {
t.Fatalf("create status=%d body=%s", createRecorder.Code, createRecorder.Body.String())
}
var created domain.OperatorRecord
if err := json.Unmarshal(createRecorder.Body.Bytes(), &created); err != nil {
t.Fatal(err)
}
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, httptest.NewRequest(http.MethodGet, "/api/operators/"+created.ID+"/lightweight-files?mount=dataset", nil))
if listRecorder.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
var listed lightweightOperatorFilesResponse
if err := json.Unmarshal(listRecorder.Body.Bytes(), &listed); err != nil {
t.Fatal(err)
}
if !listed.ReadOnly || listed.CodeSubPath != "datasets/robotwin" || len(listed.Items) != 1 || listed.Items[0].Path != "state.json" {
t.Fatalf("unexpected mounted file tree: %#v", listed)
}
writeRecorder := httptest.NewRecorder()
handler.ServeHTTP(writeRecorder, httptest.NewRequest(http.MethodPut, "/api/operators/"+created.ID+"/lightweight-files/content?mount=dataset", bytes.NewReader([]byte(`{"path":"new.txt","content":"blocked"}`))))
if writeRecorder.Code != http.StatusBadRequest || !strings.Contains(writeRecorder.Body.String(), "read-only") {
t.Fatalf("expected read-only failure, status=%d body=%s", writeRecorder.Code, writeRecorder.Body.String())
}
externalRecorder := httptest.NewRecorder()
handler.ServeHTTP(externalRecorder, httptest.NewRequest(http.MethodGet, "/api/operators/"+created.ID+"/lightweight-files?mount=models", nil))
if externalRecorder.Code != http.StatusBadRequest || !strings.Contains(externalRecorder.Body.String(), "not mounted into the file management service") {
t.Fatalf("expected explicit external PVC boundary, status=%d body=%s", externalRecorder.Code, externalRecorder.Body.String())
}
}
func TestLightweightOperatorFileEditorManagesDirectoriesUploadsMovesAndDeletes(t *testing.T) {
workspaceRoot := t.TempDir()
codeDir := filepath.Join(workspaceRoot, "lightweight-operators", "manager")

View File

@ -61,6 +61,7 @@ type LaunchInput struct {
LongRunning bool
CodeSubPath string
CodeMountPath string
PVCMounts []PVCMount
// OperatorRunnerImage is the image the platform resolves builtin operators to.
// When the resolved Image equals it, the pod runs operator-runner's main.py,
// which already self-reports resourceSeries via its ResourceSampler — so the
@ -70,6 +71,14 @@ type LaunchInput struct {
OperatorRunnerImage string
}
type PVCMount struct {
Name string
PVCName string
SubPath string
MountPath string
ReadOnly bool
}
type JobReference struct {
JobName string
Namespace string
@ -531,6 +540,23 @@ func CreateJobManifest(namespace string, imagePullSecretName string, workspacePV
return nil, err
}
}
cleanPVCMounts := make([]PVCMount, 0, len(input.PVCMounts))
for _, item := range input.PVCMounts {
item.Name = strings.TrimSpace(item.Name)
item.PVCName = strings.TrimSpace(item.PVCName)
item.SubPath, err = cleanVolumeSubPath(item.SubPath)
if err != nil {
return nil, fmt.Errorf("PVC mount %s: %w", item.Name, err)
}
item.MountPath, err = cleanMountPath(item.MountPath)
if err != nil {
return nil, fmt.Errorf("PVC mount %s: %w", item.Name, err)
}
if item.Name == "" || item.PVCName == "" {
return nil, fmt.Errorf("PVC mount name and pvcName are required")
}
cleanPVCMounts = append(cleanPVCMounts, item)
}
jobName := launchJobName(input)
envVars := []corev1.EnvVar{
{Name: "RUN_ID", Value: input.RunID},
@ -656,6 +682,21 @@ func CreateJobManifest(namespace string, imagePullSecretName string, workspacePV
})
}
}
volumeNames := map[string]string{workspacePVCName: "workspace"}
for index, item := range cleanPVCMounts {
volumeName, exists := volumeNames[item.PVCName]
if !exists {
volumeName = fmt.Sprintf("lightweight-pvc-%d", index)
volumeNames[item.PVCName] = volumeName
job.Spec.Template.Spec.Volumes = append(job.Spec.Template.Spec.Volumes, corev1.Volume{
Name: volumeName,
VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: item.PVCName}},
})
}
job.Spec.Template.Spec.Containers[0].VolumeMounts = append(job.Spec.Template.Spec.Containers[0].VolumeMounts, corev1.VolumeMount{
Name: volumeName, MountPath: item.MountPath, SubPath: item.SubPath, ReadOnly: item.ReadOnly,
})
}
if input.RegistryAuth && imagePullSecretName != "" {
job.Spec.Template.Spec.Volumes = append(job.Spec.Template.Spec.Volumes, corev1.Volume{
Name: "registry-auth",

View File

@ -192,6 +192,36 @@ func TestCreateJobManifestRejectsUnsafeLightweightOperatorCodeSubPath(t *testing
}
}
func TestCreateJobManifestMountsMultiplePVCsWithAccessModes(t *testing.T) {
manifest, err := CreateJobManifest("droboticflow", "", "workspace-pvc", "/workspace", LaunchInput{
Image: "python:3.11-slim", RunID: "run-multi", NodeID: "node-multi",
PVCMounts: []PVCMount{
{Name: "dataset", PVCName: "dataset-pvc", SubPath: "robotwin", MountPath: "/data", ReadOnly: true},
{Name: "outputs", PVCName: "workspace-pvc", SubPath: "outputs", MountPath: "/outputs", ReadOnly: false},
{Name: "models", PVCName: "model-pvc", MountPath: "/models", ReadOnly: true},
},
})
if err != nil {
t.Fatalf("CreateJobManifest returned error: %v", err)
}
if len(manifest.Spec.Template.Spec.Volumes) != 3 {
t.Fatalf("expected three deduplicated PVC volumes, got %#v", manifest.Spec.Template.Spec.Volumes)
}
mounts := manifest.Spec.Template.Spec.Containers[0].VolumeMounts
if len(mounts) != 4 {
t.Fatalf("expected workspace plus three configured mounts, got %#v", mounts)
}
if mounts[1].MountPath != "/data" || !mounts[1].ReadOnly || mounts[1].SubPath != "robotwin" {
t.Fatalf("unexpected dataset mount: %#v", mounts[1])
}
if mounts[2].Name != "workspace" || mounts[2].ReadOnly || mounts[2].MountPath != "/outputs" {
t.Fatalf("unexpected output mount: %#v", mounts[2])
}
if mounts[3].MountPath != "/models" || !mounts[3].ReadOnly {
t.Fatalf("unexpected model mount: %#v", mounts[3])
}
}
func TestCreateJobManifestSkipsGPUSchedulingWithoutGPURequest(t *testing.T) {
manifest, err := CreateJobManifest("droboticflow", "", "droboticflow-workspace", "/workspace", LaunchInput{
Image: "runner:latest",

View File

@ -8,6 +8,7 @@ import (
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
@ -15,6 +16,8 @@ import (
"droboticflow/internal/domain"
)
var pvcNamePattern = regexp.MustCompile(`^[a-z0-9](?:[-a-z0-9.]*[a-z0-9])?$`)
const (
DefaultMountPath = "/opt/droboticflow/lightweight/operator"
ContainerArgsConfiguredKey = "containerArgsConfigured"
@ -27,6 +30,16 @@ type Config struct {
MountPath string
ContainerArgsConfigured bool
ContainerCommandConfigured bool
Mounts []Mount
}
type Mount struct {
Name string `json:"name" bson:"name"`
PVCName string `json:"pvcName" bson:"pvcName"`
SubPath string `json:"subPath,omitempty" bson:"subPath,omitempty"`
MountPath string `json:"mountPath" bson:"mountPath"`
ReadOnly bool `json:"readOnly" bson:"readOnly"`
IDEEnabled bool `json:"ideEnabled" bson:"ideEnabled"`
}
type RuntimeConfig struct {
@ -39,6 +52,7 @@ type RuntimeConfig struct {
Args []string
ArgsConfigured bool
WorkspaceRoot string
Mounts []Mount
}
func NormalizeContract(contract map[string]any, commandConfigured bool, argsConfigured bool) map[string]any {
@ -64,6 +78,7 @@ func NormalizeContract(contract map[string]any, commandConfigured bool, argsConf
if mountPath := strings.TrimSpace(stringMapValue(lightweight, "mountPath")); mountPath != "" {
lightweight["mountPath"] = mountPath
}
lightweight["mounts"] = normalizeMounts(lightweight["mounts"])
next["lightweightOperator"] = lightweight
return next
}
@ -84,6 +99,7 @@ func ConfigFromContract(contract map[string]any) Config {
MountPath: mountPath,
ContainerArgsConfigured: argsConfigured,
ContainerCommandConfigured: commandConfigured,
Mounts: normalizeMounts(raw["mounts"]),
}
}
@ -118,9 +134,93 @@ func ValidateRuntimeConfig(config RuntimeConfig) error {
if len(config.Args) == 0 && !config.ArgsConfigured {
return lightweightConfigError(config, "containerArgs must be explicitly configured; use [] when no args are needed")
}
if err := ValidateMounts(config.Mounts, mountPath, workspaceRoot); err != nil {
return lightweightConfigError(config, err.Error())
}
return nil
}
func ValidateMounts(mounts []Mount, codeMountPath string, workspaceRoot string) error {
names := map[string]struct{}{}
paths := []string{strings.TrimSpace(codeMountPath)}
for index, item := range mounts {
name := strings.TrimSpace(item.Name)
if name == "" {
return fmt.Errorf("mounts[%d].name is required", index)
}
if name == "code" {
return fmt.Errorf("mounts[%d].name is reserved: code", index)
}
if _, exists := names[name]; exists {
return fmt.Errorf("mounts[%d].name must be unique: %s", index, name)
}
names[name] = struct{}{}
pvcName := strings.TrimSpace(item.PVCName)
if pvcName == "" {
return fmt.Errorf("mounts[%d].pvcName is required", index)
}
if len(pvcName) > 253 || !pvcNamePattern.MatchString(pvcName) {
return fmt.Errorf("mounts[%d].pvcName must be a valid Kubernetes PVC name", index)
}
if item.SubPath != "" {
if err := validateVolumeSubPath(item.SubPath); err != nil {
return fmt.Errorf("mounts[%d].subPath is invalid: %w", index, err)
}
}
mountPath := strings.TrimSpace(item.MountPath)
if mountPath == "" || !strings.HasPrefix(mountPath, "/") {
return fmt.Errorf("mounts[%d].mountPath must be an absolute path", index)
}
if pathHasPrefix(mountPath, filepath.ToSlash(filepath.Join(workspaceRoot, "system", "runs"))) {
return fmt.Errorf("mounts[%d].mountPath must not overlap platform run output paths", index)
}
for _, existing := range paths {
if existing != "" && (pathHasPrefix(mountPath, existing) || pathHasPrefix(existing, mountPath)) {
return fmt.Errorf("mounts[%d].mountPath overlaps another mount: %s", index, mountPath)
}
}
paths = append(paths, mountPath)
}
return nil
}
func normalizeMounts(value any) []Mount {
items, ok := value.([]any)
if !ok {
if typed, typedOK := value.([]Mount); typedOK {
items = make([]any, len(typed))
for index := range typed {
items[index] = typed[index]
}
} else {
return []Mount{}
}
}
result := make([]Mount, 0, len(items))
for _, item := range items {
var mount Mount
switch typed := item.(type) {
case Mount:
mount = typed
case map[string]any:
mount.Name = strings.TrimSpace(stringMapValue(typed, "name"))
mount.PVCName = strings.TrimSpace(stringMapValue(typed, "pvcName"))
mount.SubPath = NormalizeCodeSubPath(stringMapValue(typed, "subPath"))
mount.MountPath = strings.TrimSpace(stringMapValue(typed, "mountPath"))
mount.ReadOnly, _ = typed["readOnly"].(bool)
mount.IDEEnabled, _ = typed["ideEnabled"].(bool)
default:
continue
}
mount.Name = strings.TrimSpace(mount.Name)
mount.PVCName = strings.TrimSpace(mount.PVCName)
mount.SubPath = NormalizeCodeSubPath(mount.SubPath)
mount.MountPath = strings.TrimSpace(mount.MountPath)
result = append(result, mount)
}
return result
}
func GenerateWorkflowCodeManifests(workspaceRoot string, workflow domain.WorkflowRecord) (map[string]domain.LightweightOperatorCodeManifest, error) {
workspaceRoot = cleanAbsPath(workspaceRoot, "/workspace")
items := map[string]domain.LightweightOperatorCodeManifest{}

View File

@ -0,0 +1,45 @@
package lightweight
import (
"strings"
"testing"
)
func TestConfigFromContractNormalizesMultiplePVCMounts(t *testing.T) {
config := ConfigFromContract(map[string]any{"lightweightOperator": map[string]any{
"codeSubPath": " lightweight-operators/demo ",
"mountPath": "/opt/operator",
"mounts": []any{
map[string]any{"name": " data ", "pvcName": "dataset-pvc", "subPath": "/robotwin/", "mountPath": " /data ", "readOnly": true, "ideEnabled": true},
},
}})
if len(config.Mounts) != 1 {
t.Fatalf("expected one mount, got %#v", config.Mounts)
}
mount := config.Mounts[0]
if mount.Name != "data" || mount.PVCName != "dataset-pvc" || mount.SubPath != "robotwin" || mount.MountPath != "/data" || !mount.ReadOnly || !mount.IDEEnabled {
t.Fatalf("unexpected normalized mount: %#v", mount)
}
}
func TestValidateMountsRejectsConflicts(t *testing.T) {
tests := []struct {
name string
mounts []Mount
issue string
}{
{name: "duplicate name", mounts: []Mount{{Name: "data", PVCName: "a", MountPath: "/data"}, {Name: "data", PVCName: "b", MountPath: "/models"}}, issue: "name must be unique"},
{name: "unsafe subpath", mounts: []Mount{{Name: "data", PVCName: "a", SubPath: "../data", MountPath: "/data"}}, issue: "subPath is invalid"},
{name: "overlapping path", mounts: []Mount{{Name: "data", PVCName: "a", MountPath: "/opt/operator/data"}}, issue: "overlaps another mount"},
{name: "reserved name", mounts: []Mount{{Name: "code", PVCName: "a", MountPath: "/data"}}, issue: "name is reserved"},
{name: "invalid pvc", mounts: []Mount{{Name: "data", PVCName: "INVALID_PVC", MountPath: "/data"}}, issue: "valid Kubernetes PVC name"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := ValidateMounts(test.mounts, "/opt/operator", "/workspace")
if err == nil || !strings.Contains(err.Error(), test.issue) {
t.Fatalf("expected %q, got %v", test.issue, err)
}
})
}
}

View File

@ -607,6 +607,7 @@ func (runtime *Runtime) executeNode(ctx context.Context, run *domain.RunRecord,
Args: node.Data.ContainerArgs,
ArgsConfigured: lightweightConfig.ContainerArgsConfigured,
WorkspaceRoot: runtime.workspaceRoot,
Mounts: lightweightConfig.Mounts,
}); err != nil {
return executionResult{}, nil, err
}
@ -620,6 +621,10 @@ func (runtime *Runtime) executeNode(ctx context.Context, run *domain.RunRecord,
env["LIGHTWEIGHT_OPERATOR_CODE_SUBPATH"] = codeSubPath
env["LIGHTWEIGHT_OPERATOR_CODE_DIR"] = codeMountPath
}
pvcMounts := make([]k8s.PVCMount, 0, len(lightweightConfig.Mounts))
for _, item := range lightweightConfig.Mounts {
pvcMounts = append(pvcMounts, k8s.PVCMount{Name: item.Name, PVCName: item.PVCName, SubPath: item.SubPath, MountPath: item.MountPath, ReadOnly: item.ReadOnly})
}
nodeTimeoutSeconds := 0
if workflow != nil {
nodeTimeoutSeconds = workflow.NodeTimeoutSeconds
@ -643,6 +648,7 @@ func (runtime *Runtime) executeNode(ctx context.Context, run *domain.RunRecord,
LongRunning: runtimeContractLongRunning(node.Data.RuntimeContract),
CodeSubPath: codeSubPath,
CodeMountPath: codeMountPath,
PVCMounts: pvcMounts,
OperatorRunnerImage: runtime.operatorRunnerImage,
})
if err != nil {

View File

@ -1572,6 +1572,7 @@ func TestRuntimePassesLightweightOperatorMountToLauncher(t *testing.T) {
"enabled": true,
"codeSubPath": "lightweight-operators/demo",
"mountPath": "/app/operator",
"mounts": []any{map[string]any{"name": "data", "pvcName": "dataset-pvc", "subPath": "robotwin", "mountPath": "/data", "readOnly": true}},
},
},
},
@ -1613,6 +1614,9 @@ func TestRuntimePassesLightweightOperatorMountToLauncher(t *testing.T) {
if captured.Env["LIGHTWEIGHT_OPERATOR_CODE_DIR"] != "/app/operator" {
t.Fatalf("LIGHTWEIGHT_OPERATOR_CODE_DIR = %q", captured.Env["LIGHTWEIGHT_OPERATOR_CODE_DIR"])
}
if len(captured.PVCMounts) != 1 || captured.PVCMounts[0].PVCName != "dataset-pvc" || captured.PVCMounts[0].MountPath != "/data" || !captured.PVCMounts[0].ReadOnly {
t.Fatalf("unexpected additional PVC mounts: %#v", captured.PVCMounts)
}
}
func TestRuntimeRejectsLightweightOperatorWithoutExplicitContainerArgs(t *testing.T) {

View File

@ -122,9 +122,23 @@ function isAIGeneratedOperator(op: Partial<Operator>) {
function lightweightConfig(op: Partial<Operator>) {
const raw = op.runtimeContract?.lightweightOperator as Record<string, unknown> | undefined;
const mounts = Array.isArray(raw?.mounts)
? raw.mounts.map((item) => {
const mount = item && typeof item === "object" ? (item as Record<string, unknown>) : {};
return {
name: typeof mount.name === "string" ? mount.name : "",
pvcName: typeof mount.pvcName === "string" ? mount.pvcName : "",
subPath: typeof mount.subPath === "string" ? mount.subPath : "",
mountPath: typeof mount.mountPath === "string" ? mount.mountPath : "",
readOnly: mount.readOnly !== false,
ideEnabled: mount.ideEnabled === true,
};
})
: [];
return {
codeSubPath: typeof raw?.codeSubPath === "string" ? raw.codeSubPath : "",
mountPath: typeof raw?.mountPath === "string" ? raw.mountPath : defaultLightweightMountPath,
mounts,
};
}
@ -236,6 +250,7 @@ export default function Operators() {
const [newLightweightFilePath, setNewLightweightFilePath] = useState("operator.py");
const [newLightweightDirectoryPath, setNewLightweightDirectoryPath] = useState("src");
const [activeLightweightDirectoryPath, setActiveLightweightDirectoryPath] = useState("");
const [activeLightweightMountName, setActiveLightweightMountName] = useState("code");
const [isLightweightUploading, setIsLightweightUploading] = useState(false);
const [isLightweightDragActive, setIsLightweightDragActive] = useState(false);
const [draggedLightweightPath, setDraggedLightweightPath] = useState("");
@ -317,10 +332,15 @@ export default function Operators() {
(newOp.type !== "lightweight" ||
((newOp.image || "").trim().length > 0 &&
currentLightweightConfig.codeSubPath.trim().length > 0 &&
currentLightweightConfig.mountPath.trim().length > 0)) &&
currentLightweightConfig.mountPath.trim().length > 0 &&
currentLightweightConfig.mounts.every(
(mount) => mount.name.trim() && mount.pvcName.trim() && mount.mountPath.trim(),
))) &&
(Boolean(editingOpId) || imageSourceMode !== "archive" || Boolean(archiveFile));
const updateLightweightConfig = (patch: { codeSubPath?: string; mountPath?: string }) => {
const updateLightweightConfig = (
patch: Partial<ReturnType<typeof lightweightConfig>>,
) => {
setNewOp((current) => {
const currentRuntime = current.runtimeContract || {};
const currentLightweight = lightweightConfig(current);
@ -339,6 +359,30 @@ export default function Operators() {
});
};
const updateLightweightMount = (
index: number,
patch: Partial<ReturnType<typeof lightweightConfig>["mounts"][number]>,
) => {
const mounts = lightweightConfig(newOp).mounts.map((item, itemIndex) =>
itemIndex === index ? { ...item, ...patch } : item,
);
updateLightweightConfig({ mounts });
};
const addLightweightMount = () => {
const mounts = lightweightConfig(newOp).mounts;
updateLightweightConfig({
mounts: [
...mounts,
{ name: `mount-${mounts.length + 1}`, pvcName: "", subPath: "", mountPath: "", readOnly: true, ideEnabled: false },
],
});
};
const removeLightweightMount = (index: number) => {
updateLightweightConfig({ mounts: lightweightConfig(newOp).mounts.filter((_, itemIndex) => itemIndex !== index) });
};
const updateResources = (patch: NonNullable<Operator["resources"]>) => {
setNewOp((current) => ({
...current,
@ -385,6 +429,7 @@ export default function Operators() {
setNewLightweightFilePath("operator.py");
setNewLightweightDirectoryPath("src");
setActiveLightweightDirectoryPath("");
setActiveLightweightMountName("code");
setIsLightweightUploading(false);
setIsLightweightDragActive(false);
setDraggedLightweightPath("");
@ -400,7 +445,7 @@ export default function Operators() {
setLightweightFileLoading(true);
setLightweightFileError("");
operatorsApi
.getLightweightFileContent(editingOpId, filePath)
.getLightweightFileContent(editingOpId, filePath, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then((content) => {
setLightweightFileDraft(content.content);
setLightweightFileSavedContent(content.content);
@ -430,7 +475,7 @@ export default function Operators() {
setLightweightFileLoading(false);
});
},
[editingOpId],
[activeLightweightMountName, editingOpId],
);
const refreshLightweightFiles = useCallback(
@ -441,7 +486,7 @@ export default function Operators() {
setLightweightFilesLoading(true);
setLightweightFilesError("");
operatorsApi
.listLightweightFiles(editingOpId)
.listLightweightFiles(editingOpId, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then((result) => {
setLightweightFiles(result);
const targetPath =
@ -475,7 +520,7 @@ export default function Operators() {
setLightweightFilesLoading(false);
});
},
[activeLightweightFilePath, editingOpId, loadLightweightFileContent, newOp.type],
[activeLightweightFilePath, activeLightweightMountName, editingOpId, loadLightweightFileContent, newOp.type],
);
const openNewLightweightFile = () => {
@ -518,7 +563,7 @@ export default function Operators() {
setLightweightFilesLoading(true);
setLightweightFilesError("");
operatorsApi
.createLightweightDirectory(editingOpId, targetPath)
.createLightweightDirectory(editingOpId, targetPath, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then(() => {
setExpandedLightweightDirs((current) => {
const next = new Set(current);
@ -558,7 +603,7 @@ export default function Operators() {
const uploadDirectory = activeLightweightDirectoryPath;
Promise.all(
selectedFiles.map((file) =>
operatorsApi.uploadLightweightFile(editingOpId, lightweightUploadPathForFile(uploadDirectory, file), file),
operatorsApi.uploadLightweightFile(editingOpId, lightweightUploadPathForFile(uploadDirectory, file), file, activeLightweightMountName === "code" ? undefined : activeLightweightMountName),
),
)
.then((results) => {
@ -599,7 +644,7 @@ export default function Operators() {
return;
}
operatorsApi
.moveLightweightPath(editingOpId, activeLightweightFilePath, normalized)
.moveLightweightPath(editingOpId, activeLightweightFilePath, normalized, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then((result) => {
setActiveLightweightFilePath(result.newPath || normalized);
setActiveLightweightDirectoryPath(lightweightParentDir(result.newPath || normalized));
@ -636,7 +681,7 @@ export default function Operators() {
setLightweightFilesError("");
setLightweightFileError("");
operatorsApi
.moveLightweightPath(editingOpId, sourceItem.path, plan.newPath)
.moveLightweightPath(editingOpId, sourceItem.path, plan.newPath, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then((result) => {
const movedPath = result.newPath || plan.newPath;
const movedDirectory = sourceItem.kind === "directory" ? movedPath : lightweightParentDir(movedPath);
@ -673,7 +718,7 @@ export default function Operators() {
return;
}
operatorsApi
.deleteLightweightPath(editingOpId, target)
.deleteLightweightPath(editingOpId, target, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then(() => {
setActiveLightweightFilePath("");
setLightweightFileDraft("");
@ -695,7 +740,7 @@ export default function Operators() {
setLightweightFileSaving(true);
setLightweightFileError("");
operatorsApi
.saveLightweightFileContent(editingOpId, activeLightweightFilePath, lightweightFileDraft)
.saveLightweightFileContent(editingOpId, activeLightweightFilePath, lightweightFileDraft, activeLightweightMountName === "code" ? undefined : activeLightweightMountName)
.then((content) => {
setLightweightFileDraft(content.content);
setLightweightFileSavedContent(content.content);
@ -1552,6 +1597,63 @@ export default function Operators() {
{editingOpId ? "编辑代码目录" : "打开代码目录"}
</button>
</div>
<div className="space-y-3 border-t border-emerald-500/15 pt-4">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-xs font-semibold text-gray-200">附加 PVC 挂载</div>
<div className="mt-1 text-[11px] text-gray-500">每个挂载独立指定目录和访问权限;配置错误会直接阻止运行。</div>
</div>
<button
type="button"
onClick={addLightweightMount}
className="inline-flex items-center gap-2 rounded-md border border-emerald-500/30 px-3 py-1.5 text-xs text-emerald-200 hover:bg-emerald-500/10"
>
<Plus className="h-3.5 w-3.5" />
添加挂载
</button>
</div>
{lightweightConfig(newOp).mounts.map((mount, index) => (
<div key={`${mount.name}-${index}`} className="space-y-3 rounded-md border border-[#2a2b2f] bg-[#0a0a0a] p-3">
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
<label className="space-y-1 text-[10px] uppercase text-gray-500">
挂载名称
<input className="w-full rounded border border-[#2a2b2f] bg-[#151619] px-2 py-2 text-xs normal-case text-gray-200" value={mount.name} onChange={(event) => updateLightweightMount(index, { name: event.target.value })} />
</label>
<label className="space-y-1 text-[10px] uppercase text-gray-500">
PVC 名称
<input className="w-full rounded border border-[#2a2b2f] bg-[#151619] px-2 py-2 text-xs normal-case text-gray-200" value={mount.pvcName} onChange={(event) => updateLightweightMount(index, { pvcName: event.target.value })} />
</label>
<label className="space-y-1 text-[10px] uppercase text-gray-500">
PVC 子目录
<input className="w-full rounded border border-[#2a2b2f] bg-[#151619] px-2 py-2 text-xs normal-case text-gray-200" placeholder="datasets/robotwin" value={mount.subPath} onChange={(event) => updateLightweightMount(index, { subPath: event.target.value })} />
</label>
<label className="space-y-1 text-[10px] uppercase text-gray-500">
容器挂载目录
<input className="w-full rounded border border-[#2a2b2f] bg-[#151619] px-2 py-2 text-xs normal-case text-gray-200" placeholder="/data/robotwin" value={mount.mountPath} onChange={(event) => updateLightweightMount(index, { mountPath: event.target.value })} />
</label>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-5 text-xs text-gray-300">
<label className="inline-flex items-center gap-2">
<input type="checkbox" checked={mount.readOnly} onChange={(event) => updateLightweightMount(index, { readOnly: event.target.checked })} />
只读挂载
</label>
<label className="inline-flex items-center gap-2">
<input type="checkbox" checked={mount.ideEnabled} onChange={(event) => updateLightweightMount(index, { ideEnabled: event.target.checked })} />
文件 IDE
</label>
</div>
<button type="button" onClick={() => removeLightweightMount(index)} className="inline-flex items-center gap-2 rounded border border-red-500/30 px-2.5 py-1.5 text-xs text-red-300 hover:bg-red-500/10">
<Trash2 className="h-3.5 w-3.5" />
删除挂载
</button>
</div>
</div>
))}
{lightweightConfig(newOp).mounts.length === 0 && (
<div className="rounded border border-dashed border-[#2a2b2f] px-3 py-4 text-center text-xs text-gray-600">未配置附加 PVC 挂载</div>
)}
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
@ -2018,6 +2120,36 @@ export default function Operators() {
</div>
) : (
<>
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] p-2">
{[
{ name: "code", label: "代码目录", readOnly: false },
...lightweightConfig(newOp).mounts
.filter((mount) => mount.ideEnabled)
.map((mount) => ({ name: mount.name, label: mount.name || "未命名挂载", readOnly: mount.readOnly })),
].map((mount) => (
<button
key={mount.name}
type="button"
onClick={() => {
setActiveLightweightMountName(mount.name);
setActiveLightweightFilePath("");
setActiveLightweightDirectoryPath("");
setLightweightFileDraft("");
setLightweightFileSavedContent("");
}}
className={cn(
"inline-flex items-center gap-2 rounded-md border px-3 py-2 text-xs",
activeLightweightMountName === mount.name
? "border-emerald-500/40 bg-emerald-500/10 text-emerald-100"
: "border-[#2a2b2f] text-gray-400 hover:text-white",
)}
>
<FolderOpen className="h-3.5 w-3.5" />
{mount.label}
<span className="font-mono text-[9px] text-gray-500">{mount.readOnly ? "RO" : "RW"}</span>
</button>
))}
</div>
<div className="grid gap-3 lg:grid-cols-4">
<div className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2">
<div className="text-[10px] uppercase tracking-wider text-gray-500">Workspace 子目录</div>
@ -2047,7 +2179,13 @@ export default function Operators() {
</div>
</div>
<div className="space-y-3 rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] p-3">
{lightweightFiles?.readOnly && (
<div className="rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2 text-xs text-amber-200">
当前挂载为只读,只允许查看和下载;创建、上传、保存、移动和删除操作已禁用。
</div>
)}
{!lightweightFiles?.readOnly && <div className="space-y-3 rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] p-3">
<div className="grid gap-2 lg:grid-cols-[minmax(0,1fr)_auto_minmax(0,0.8fr)_auto]">
<input
type="text"
@ -2120,7 +2258,7 @@ export default function Operators() {
</button>
</div>
</div>
</div>
</div>}
<div
className={cn(
@ -2362,7 +2500,7 @@ export default function Operators() {
<button
type="button"
onClick={moveActiveLightweightPath}
disabled={!activeLightweightFilePath || lightweightFileSaving || isLightweightUploading}
disabled={lightweightFiles?.readOnly || !activeLightweightFilePath || lightweightFileSaving || isLightweightUploading}
className="inline-flex items-center gap-2 rounded-md border border-[#2a2b2f] px-3 py-2 text-xs font-medium text-gray-300 transition-colors hover:bg-white/5 disabled:cursor-not-allowed disabled:opacity-50"
>
<Pencil className="h-3.5 w-3.5" />
@ -2371,7 +2509,7 @@ export default function Operators() {
<button
type="button"
onClick={deleteActiveLightweightPath}
disabled={!activeLightweightFilePath || lightweightFileSaving || isLightweightUploading}
disabled={lightweightFiles?.readOnly || !activeLightweightFilePath || lightweightFileSaving || isLightweightUploading}
className="inline-flex items-center gap-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-xs font-medium text-red-100 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-50"
>
<Trash2 className="h-3.5 w-3.5" />
@ -2382,6 +2520,7 @@ export default function Operators() {
onClick={saveLightweightFile}
disabled={
!activeLightweightFilePath ||
lightweightFiles?.readOnly ||
!activeLightweightPathIsEditableFile ||
lightweightFileLoading ||
lightweightFileSaving ||
@ -2422,6 +2561,7 @@ export default function Operators() {
<textarea
className="h-[28rem] w-full resize-none bg-[#050505] p-4 font-mono text-xs leading-5 text-gray-200 outline-none scrollbar-thin scrollbar-thumb-gray-800"
value={lightweightFileDraft}
readOnly={lightweightFiles?.readOnly}
onChange={(event) => setLightweightFileDraft(event.target.value)}
spellCheck={false}
/>

View File

@ -45,6 +45,10 @@ export interface LightweightOperatorFilesResponse {
items: LightweightOperatorFileItem[];
}
function lightweightMountQuery(mount?: string) {
return mount ? `?mount=${encodeURIComponent(mount)}` : "";
}
export interface LightweightOperatorFileContent {
operatorId: string;
path: string;
@ -84,40 +88,40 @@ export const operatorsApi = {
update: (id: string, payload: Partial<Operator>) =>
apiRequest<Operator>(`/api/operators/${id}`, { method: "PUT" }, payload),
remove: (id: string) => apiRequest<void>(`/api/operators/${id}`, { method: "DELETE" }),
listLightweightFiles: (id: string) =>
apiRequest<LightweightOperatorFilesResponse>(`/api/operators/${id}/lightweight-files`),
getLightweightFileContent: (id: string, path: string) =>
listLightweightFiles: (id: string, mount?: string) =>
apiRequest<LightweightOperatorFilesResponse>(`/api/operators/${id}/lightweight-files${lightweightMountQuery(mount)}`),
getLightweightFileContent: (id: string, path: string, mount?: string) =>
apiRequest<LightweightOperatorFileContent>(
`/api/operators/${id}/lightweight-files/content?path=${encodeURIComponent(path)}`,
`/api/operators/${id}/lightweight-files/content?path=${encodeURIComponent(path)}${mount ? `&mount=${encodeURIComponent(mount)}` : ""}`,
),
saveLightweightFileContent: (id: string, path: string, content: string) =>
saveLightweightFileContent: (id: string, path: string, content: string, mount?: string) =>
apiRequest<LightweightOperatorFileContent>(
`/api/operators/${id}/lightweight-files/content`,
`/api/operators/${id}/lightweight-files/content${lightweightMountQuery(mount)}`,
{ method: "PUT" },
{ path, content },
),
createLightweightDirectory: (id: string, path: string) =>
createLightweightDirectory: (id: string, path: string, mount?: string) =>
apiRequest<LightweightOperatorMutationResult>(
`/api/operators/${id}/lightweight-files/directories`,
`/api/operators/${id}/lightweight-files/directories${lightweightMountQuery(mount)}`,
{ method: "POST" },
{ path },
),
moveLightweightPath: (id: string, path: string, newPath: string) =>
moveLightweightPath: (id: string, path: string, newPath: string, mount?: string) =>
apiRequest<LightweightOperatorMutationResult>(
`/api/operators/${id}/lightweight-files`,
`/api/operators/${id}/lightweight-files${lightweightMountQuery(mount)}`,
{ method: "PATCH" },
{ path, newPath },
),
deleteLightweightPath: (id: string, path: string) =>
deleteLightweightPath: (id: string, path: string, mount?: string) =>
apiRequest<LightweightOperatorMutationResult>(
`/api/operators/${id}/lightweight-files?path=${encodeURIComponent(path)}`,
`/api/operators/${id}/lightweight-files?path=${encodeURIComponent(path)}${mount ? `&mount=${encodeURIComponent(mount)}` : ""}`,
{ method: "DELETE" },
),
uploadLightweightFile: async (id: string, path: string, file: File) => {
uploadLightweightFile: async (id: string, path: string, file: File, mount?: string) => {
const form = new FormData();
form.append("path", path);
form.append("file", file);
const response = await apiFetch(`/api/operators/${id}/lightweight-files/upload`, {
const response = await apiFetch(`/api/operators/${id}/lightweight-files/upload${lightweightMountQuery(mount)}`, {
method: "POST",
body: form,
});