droboticflow-new/src/pages/Operators.tsx
2026-07-13 19:21:12 +08:00

3091 lines
149 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useCallback, useEffect, useRef, useState } from "react";
import {
Cpu,
Plus,
Search,
Code,
Box,
X,
Info,
Layers,
Edit3,
Trash2,
Sparkles,
Loader2,
AlertCircle,
UploadCloud,
Zap,
ChevronDown,
ChevronRight,
FileText,
FolderPlus,
FolderOpen,
Pencil,
RefreshCw,
Save,
Star,
} from "lucide-react";
import { useUser } from "../context/UserContext";
import { getActionErrorMessage } from "../lib/action-errors.js";
import {
getLightweightMovePlan,
hasLightweightPathTraversal,
joinLightweightPath,
lightweightContainerPath,
lightweightParentDir,
normalizeLightweightRelativePath,
resolveLightweightEditorRelativePath,
} from "../lib/lightweight-files.js";
import { buildOperatorPayload, getOperatorPayloadIssue } from "../lib/operators.js";
import { cn } from "../lib/utils";
import { canManagePipelineDesign } from "../lib/user-roles";
import { Operator, PortDefinition, PortTransmission, PortType } from "../types";
import { generateOperatorFromDescription } from "../services/aiService";
import type { GeneratedOperator } from "../services/api/ai";
import {
operatorsApi,
type LightweightOperatorFileItem,
type LightweightOperatorFilesResponse,
} from "../services/api/operators";
import { useAIStatus } from "../hooks/useAIStatus";
function createPortID() {
if (typeof globalThis.crypto?.randomUUID === "function") {
return globalThis.crypto.randomUUID();
}
if (typeof globalThis.crypto?.getRandomValues === "function") {
const bytes = new Uint8Array(16);
globalThis.crypto.getRandomValues(bytes);
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
return `port-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
const portTypes: PortType[] = ["json", "image", "video", "tensor", "file"];
const portTransmissions: PortTransmission[] = ["bus", "oss", "shm", "stream"];
const defaultLightweightCommand: string[] = [];
const defaultLightweightArgs: string[] = [];
const defaultLightweightMountPath = "/opt/droboticflow/lightweight/operator";
const lightweightPathDragMime = "application/x-droboticflow-lightweight-path";
const gpuTypeOptions = [
"NVIDIA A800 80GB",
"NVIDIA A100 80GB",
"NVIDIA L40S 48GB",
"NVIDIA H800 80GB",
"NVIDIA H100 80GB",
"NVIDIA T4 16GB",
"NVIDIA GPU",
];
type GeneratedImplementation = NonNullable<GeneratedOperator["implementation"]>;
function parsePortType(value: string): PortType {
return portTypes.includes(value as PortType) ? (value as PortType) : "json";
}
function parsePortTransmission(value: string): PortTransmission {
return portTransmissions.includes(value as PortTransmission) ? (value as PortTransmission) : "bus";
}
function trimResource(value: unknown) {
return typeof value === "string" ? value.trim() : "";
}
function getGPURequirement(op: Partial<Operator>) {
const gpuLimit = trimResource(op.resources?.gpuLimit);
const gpuType = trimResource(op.resources?.gpuType) || (gpuLimit ? "NVIDIA GPU" : "");
return {
required: /^[1-9]\d*$/.test(gpuLimit),
configured: Boolean(gpuLimit || trimResource(op.resources?.gpuType)),
gpuLimit,
gpuType,
};
}
function getPublicationStatusLabel(status?: string) {
switch (status) {
case "draft":
return "草稿";
case "built":
return "已构建";
case "verified":
return "已验证";
case "published":
return "已发布";
default:
return "已发布";
}
}
function isAIGeneratedOperator(op: Partial<Operator>) {
return op.generationSource === "ai" || Boolean(op.runtimeContract?.generatedRepository);
}
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 === true,
ideEnabled: mount.ideEnabled === true,
};
})
: [];
return {
codeSubPath: typeof raw?.codeSubPath === "string" ? raw.codeSubPath : "",
mountPath: typeof raw?.mountPath === "string" ? raw.mountPath : defaultLightweightMountPath,
codeReadOnly: raw?.codeReadOnly === true,
mounts,
};
}
function formatCommandDraft(items: unknown, fallback: string[] = []) {
return JSON.stringify(Array.isArray(items) && items.length > 0 ? items : fallback, null, 2);
}
function parseCommandDraft(label: string, value: string, options: { allowEmpty?: boolean } = {}) {
let parsed: unknown;
try {
parsed = JSON.parse(value);
} catch {
return { issue: `${label} 必须是 JSON 字符串数组`, items: [] as string[] };
}
if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string" || !item.trim())) {
return { issue: `${label} 必须是非空字符串数组`, items: [] as string[] };
}
if (!options.allowEmpty && parsed.length === 0) {
return { issue: `${label} 必须至少包含一个字符串`, items: [] as string[] };
}
return { issue: "", items: parsed.map((item) => item.trim()) };
}
function formatFileSize(sizeBytes?: number) {
if (!sizeBytes || sizeBytes <= 0) return "0 B";
if (sizeBytes < 1024) return `${sizeBytes} B`;
if (sizeBytes < 1024 * 1024) return `${(sizeBytes / 1024).toFixed(1)} KiB`;
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MiB`;
}
function isLightweightFileItemVisible(item: LightweightOperatorFileItem, expandedDirs: Set<string>) {
if (item.depth === 0) return true;
const parts = item.path.split("/");
let current = "";
for (let index = 0; index < parts.length - 1; index += 1) {
current = current ? `${current}/${parts[index]}` : parts[index];
if (!expandedDirs.has(current)) {
return false;
}
}
return true;
}
function parentDirectoriesForPath(filePath: string) {
const parts = filePath.split("/").filter(Boolean);
const parents: string[] = [];
let current = "";
for (let index = 0; index < parts.length - 1; index += 1) {
current = current ? `${current}/${parts[index]}` : parts[index];
parents.push(current);
}
return parents;
}
function lightweightUploadPathForFile(directory: string, file: File) {
const relativePath = normalizeLightweightRelativePath(
(file as File & { webkitRelativePath?: string }).webkitRelativePath || "",
);
return joinLightweightPath(directory, relativePath || file.name);
}
function hasLightweightPathDrag(event: React.DragEvent) {
return Array.from(event.dataTransfer.types).includes(lightweightPathDragMime);
}
function isFileNotFoundError(error: unknown) {
const message = error instanceof Error ? error.message : String(error || "");
return (
message.includes("File not found") ||
message.includes("Code directory not found") ||
message.includes("Path not found")
);
}
export default function Operators() {
const { role, currentUser } = useUser();
const aiStatus = useAIStatus();
const [operators, setOperators] = useState<Operator[]>([]);
const [searchQuery, setSearchQuery] = useState("");
const [typeFilter, setTypeFilter] = useState("all");
const [gpuFilter, setGpuFilter] = useState("all");
const [publicationFilter, setPublicationFilter] = useState("all");
const [portFilter, setPortFilter] = useState("all");
const [quickFilter, setQuickFilter] = useState("all");
const [favoriteOperatorIds, setFavoriteOperatorIds] = useState<string[]>([]);
const [recentOperatorIds, setRecentOperatorIds] = useState<string[]>([]);
const [loadedOperatorPreferenceKey, setLoadedOperatorPreferenceKey] = useState("");
const [isModalOpen, setIsModalOpen] = useState(false);
const [isAIModalOpen, setIsAIModalOpen] = useState(false);
const [actionError, setActionError] = useState("");
const [aiDescription, setAiDescription] = useState("");
const [isGenerating, setIsGenerating] = useState(false);
const [isSavingOperator, setIsSavingOperator] = useState(false);
const [deletingOperatorId, setDeletingOperatorId] = useState<string | null>(null);
const [aiError, setAiError] = useState<string | null>(null);
const [editingOpId, setEditingOpId] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<"basic" | "ports" | "hyperparams" | "skill" | "implementation">("basic");
const [generatedImplementation, setGeneratedImplementation] = useState<GeneratedImplementation | null>(null);
const [activeImplementationFile, setActiveImplementationFile] = useState("");
const [imageSourceMode, setImageSourceMode] = useState<"reference" | "archive">("reference");
const [archiveFile, setArchiveFile] = useState<File | null>(null);
const [archiveRepository, setArchiveRepository] = useState("");
const [archiveTag, setArchiveTag] = useState("");
const [archiveFormat, setArchiveFormat] = useState<"docker" | "oci">("docker");
const [containerCommandDraft, setContainerCommandDraft] = useState("[]");
const [containerArgsDraft, setContainerArgsDraft] = useState("[]");
const [lightweightFiles, setLightweightFiles] = useState<LightweightOperatorFilesResponse | null>(null);
const [lightweightFilesLoading, setLightweightFilesLoading] = useState(false);
const [lightweightFilesError, setLightweightFilesError] = useState("");
const [expandedLightweightDirs, setExpandedLightweightDirs] = useState<Set<string>>(() => new Set());
const [activeLightweightFilePath, setActiveLightweightFilePath] = useState("");
const [lightweightFileDraft, setLightweightFileDraft] = useState("");
const [lightweightFileSavedContent, setLightweightFileSavedContent] = useState("");
const [lightweightFileLoading, setLightweightFileLoading] = useState(false);
const [lightweightFileSaving, setLightweightFileSaving] = useState(false);
const [lightweightFileError, setLightweightFileError] = useState("");
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("");
const [lightweightDropTargetPath, setLightweightDropTargetPath] = useState<string | null>(null);
const lightweightUploadInputRef = useRef<HTMLInputElement | null>(null);
const [newOp, setNewOp] = useState<Partial<Operator>>({
type: "custom",
category: "CV",
version: "v1",
inputs: [],
outputs: [],
hyperparams: [],
skillDefinition: "",
generationSource: "manual",
publicationStatus: "published",
});
useEffect(() => {
operatorsApi
.list()
.then(setOperators)
.catch((error) => {
console.error("Failed to load operators", error);
setActionError(getActionErrorMessage(error, "加载算子失败"));
});
}, []);
const operatorPreferenceKey = currentUser?.id ? `droboticflow.operator-usage:v1:${currentUser.id}` : "";
useEffect(() => {
if (!operatorPreferenceKey) {
setFavoriteOperatorIds([]);
setRecentOperatorIds([]);
setLoadedOperatorPreferenceKey("");
return;
}
try {
const stored = JSON.parse(window.localStorage.getItem(operatorPreferenceKey) || "{}");
setFavoriteOperatorIds(
Array.isArray(stored.favorites) ? stored.favorites.filter((id: unknown) => typeof id === "string") : [],
);
setRecentOperatorIds(
Array.isArray(stored.recent) ? stored.recent.filter((id: unknown) => typeof id === "string").slice(0, 20) : [],
);
} catch {
setFavoriteOperatorIds([]);
setRecentOperatorIds([]);
}
setLoadedOperatorPreferenceKey(operatorPreferenceKey);
}, [operatorPreferenceKey]);
useEffect(() => {
if (!operatorPreferenceKey || loadedOperatorPreferenceKey !== operatorPreferenceKey) return;
try {
window.localStorage.setItem(
operatorPreferenceKey,
JSON.stringify({ version: 1, favorites: favoriteOperatorIds, recent: recentOperatorIds.slice(0, 20) }),
);
} catch {
// Browser storage may be unavailable; filters remain usable for the current session.
}
}, [favoriteOperatorIds, loadedOperatorPreferenceKey, operatorPreferenceKey, recentOperatorIds]);
const markOperatorRecent = (operatorId: string) => {
setRecentOperatorIds((current) => [operatorId, ...current.filter((id) => id !== operatorId)].slice(0, 20));
};
const toggleOperatorFavorite = (operatorId: string) => {
setFavoriteOperatorIds((current) =>
current.includes(operatorId) ? current.filter((id) => id !== operatorId) : [operatorId, ...current],
);
};
const handleAddHyperParam = () => {
const hp = {
key: `PARAM_${(newOp.hyperparams?.length || 0) + 1}`,
value: "",
description: "",
};
setNewOp({ ...newOp, hyperparams: [...(newOp.hyperparams || []), hp] });
};
const handleAddPort = (type: "inputs" | "outputs") => {
setNewOp((current) => {
const nextIndex = (current[type]?.length ?? 0) + 1;
const port: PortDefinition = {
id: createPortID(),
name: `端口 ${nextIndex}`,
type: "json",
transmission: "bus",
};
return { ...current, [type]: [...(current[type] || []), port] };
});
};
const updatePort = (
type: "inputs" | "outputs",
index: number,
updater: Partial<PortDefinition> | ((current: PortDefinition) => PortDefinition),
) => {
setNewOp((current) => {
const ports = [...(current[type] || [])];
const target = ports[index];
if (!target) {
return current;
}
ports[index] = typeof updater === "function" ? updater(target) : { ...target, ...updater };
return { ...current, [type]: ports };
});
};
const removePort = (type: "inputs" | "outputs", index: number) => {
setNewOp((current) => ({
...current,
[type]: (current[type] || []).filter((_, portIndex) => portIndex !== index),
}));
};
const operatorName = (newOp.name || "").trim();
const operatorDescription = (newOp.description || "").trim();
const currentLightweightConfig = lightweightConfig(newOp);
const canSaveOperator =
operatorName.length > 0 &&
operatorDescription.length > 0 &&
(newOp.type !== "lightweight" ||
((newOp.image || "").trim().length > 0 &&
currentLightweightConfig.codeSubPath.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: Partial<ReturnType<typeof lightweightConfig>>) => {
setNewOp((current) => {
const currentRuntime = current.runtimeContract || {};
const currentLightweight = lightweightConfig(current);
return {
...current,
type: "lightweight",
runtimeContract: {
...currentRuntime,
lightweightOperator: {
enabled: true,
...currentLightweight,
...patch,
},
},
};
});
};
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: false,
ideEnabled: false,
},
],
});
};
const removeLightweightMount = (index: number) => {
updateLightweightConfig({ mounts: lightweightConfig(newOp).mounts.filter((_, itemIndex) => itemIndex !== index) });
};
const updateResources = (patch: NonNullable<Operator["resources"]>) => {
setNewOp((current) => ({
...current,
resources: {
...(current.resources || {}),
...patch,
},
}));
};
const setGPURequired = (required: boolean) => {
setNewOp((current) => {
const resources = { ...(current.resources || {}) };
if (required) {
resources.gpuType = resources.gpuType || "NVIDIA A800 80GB";
resources.gpuLimit = resources.gpuLimit || "1";
} else {
resources.gpuType = "";
resources.gpuLimit = "";
}
return { ...current, resources };
});
};
const resetArchiveUpload = () => {
setImageSourceMode("reference");
setArchiveFile(null);
setArchiveRepository("");
setArchiveTag("");
setArchiveFormat("docker");
};
const resetLightweightEditorState = useCallback(() => {
setLightweightFiles(null);
setLightweightFilesLoading(false);
setLightweightFilesError("");
setExpandedLightweightDirs(new Set());
setActiveLightweightFilePath("");
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileLoading(false);
setLightweightFileSaving(false);
setLightweightFileError("");
setNewLightweightFilePath("operator.py");
setNewLightweightDirectoryPath("src");
setActiveLightweightDirectoryPath("");
setActiveLightweightMountName("code");
setIsLightweightUploading(false);
setIsLightweightDragActive(false);
setDraggedLightweightPath("");
setLightweightDropTargetPath(null);
}, []);
const loadLightweightFileContent = useCallback(
(filePath: string) => {
if (!editingOpId || !filePath) {
return;
}
setActiveLightweightFilePath(filePath);
setLightweightFileLoading(true);
setLightweightFileError("");
operatorsApi
.getLightweightFileContent(
editingOpId,
filePath,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
)
.then((content) => {
setLightweightFileDraft(content.content);
setLightweightFileSavedContent(content.content);
setActiveLightweightDirectoryPath(lightweightParentDir(content.path));
setExpandedLightweightDirs((current) => {
const next = new Set(current);
for (const parent of parentDirectoriesForPath(filePath)) {
next.add(parent);
}
return next;
});
})
.catch((error) => {
console.error("Failed to load lightweight operator file", error);
if (isFileNotFoundError(error)) {
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("");
setActiveLightweightDirectoryPath(lightweightParentDir(filePath));
return;
}
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError(getActionErrorMessage(error, "读取代码文件失败"));
})
.finally(() => {
setLightweightFileLoading(false);
});
},
[activeLightweightMountName, editingOpId],
);
const refreshLightweightFiles = useCallback(
(preferredPath?: string) => {
if (!editingOpId || newOp.type !== "lightweight") {
return;
}
setLightweightFilesLoading(true);
setLightweightFilesError("");
operatorsApi
.listLightweightFiles(
editingOpId,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
)
.then((result) => {
setLightweightFiles(result);
const targetPath =
preferredPath ||
activeLightweightFilePath ||
result.items.find((item) => item.kind === "file" && item.editable)?.path ||
"";
if (targetPath) {
const targetItem = result.items.find((item) => item.path === targetPath);
if (targetItem?.kind === "directory") {
setActiveLightweightFilePath(targetPath);
setActiveLightweightDirectoryPath(targetPath);
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("");
return;
}
loadLightweightFileContent(targetPath);
} else {
setActiveLightweightFilePath("");
setLightweightFileDraft("");
setLightweightFileSavedContent("");
}
})
.catch((error) => {
console.error("Failed to load lightweight operator code directory", error);
setLightweightFiles(null);
setLightweightFilesError(getActionErrorMessage(error, "加载轻量算子代码目录失败"));
})
.finally(() => {
setLightweightFilesLoading(false);
});
},
[activeLightweightFilePath, activeLightweightMountName, editingOpId, loadLightweightFileContent, newOp.type],
);
const openNewLightweightFile = () => {
const targetPath = resolveLightweightEditorRelativePath(
newLightweightFilePath,
activeLightweightDirectoryPath,
lightweightFiles?.mountPath || lightweightConfig(newOp).mountPath,
);
if (!targetPath || hasLightweightPathTraversal(targetPath)) {
setLightweightFileError("请输入容器挂载目录内的文件路径");
return;
}
setActiveLightweightFilePath(targetPath);
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("");
setActiveLightweightDirectoryPath(lightweightParentDir(targetPath));
setExpandedLightweightDirs((current) => {
const next = new Set(current);
for (const parent of parentDirectoriesForPath(targetPath)) {
next.add(parent);
}
return next;
});
};
const createLightweightDirectory = () => {
if (!editingOpId) {
return;
}
const targetPath = resolveLightweightEditorRelativePath(
newLightweightDirectoryPath,
activeLightweightDirectoryPath,
lightweightFiles?.mountPath || lightweightConfig(newOp).mountPath,
);
if (!targetPath || hasLightweightPathTraversal(targetPath)) {
setLightweightFilesError("请输入容器挂载目录内的目录路径");
return;
}
setLightweightFilesLoading(true);
setLightweightFilesError("");
operatorsApi
.createLightweightDirectory(
editingOpId,
targetPath,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
)
.then(() => {
setExpandedLightweightDirs((current) => {
const next = new Set(current);
for (const parent of parentDirectoriesForPath(`${targetPath}/placeholder`)) {
next.add(parent);
}
next.add(targetPath);
return next;
});
setActiveLightweightDirectoryPath(targetPath);
setActiveLightweightFilePath(targetPath);
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("");
refreshLightweightFiles(targetPath);
})
.catch((error) => {
console.error("Failed to create lightweight operator directory", error);
setLightweightFilesError(getActionErrorMessage(error, "创建目录失败"));
})
.finally(() => {
setLightweightFilesLoading(false);
});
};
const uploadLightweightFiles = (files: FileList | File[]) => {
if (!editingOpId || isLightweightUploading) {
return;
}
const selectedFiles = Array.from(files).filter((file) => file.size >= 0);
if (selectedFiles.length === 0) {
return;
}
setIsLightweightUploading(true);
setLightweightFilesError("");
setLightweightFileError("");
const uploadDirectory = activeLightweightDirectoryPath;
Promise.all(
selectedFiles.map((file) =>
operatorsApi.uploadLightweightFile(
editingOpId,
lightweightUploadPathForFile(uploadDirectory, file),
file,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
),
),
)
.then((results) => {
const lastPath = results[results.length - 1]?.path || activeLightweightFilePath;
if (lastPath) {
setActiveLightweightDirectoryPath(lightweightParentDir(lastPath));
}
refreshLightweightFiles(lastPath);
})
.catch((error) => {
console.error("Failed to upload lightweight operator files", error);
setLightweightFilesError(getActionErrorMessage(error, "上传文件失败"));
})
.finally(() => {
setIsLightweightUploading(false);
setIsLightweightDragActive(false);
if (lightweightUploadInputRef.current) {
lightweightUploadInputRef.current.value = "";
}
});
};
const moveActiveLightweightPath = () => {
if (!editingOpId || !activeLightweightFilePath) {
return;
}
const nextPath = window.prompt("移动/重命名为", activeLightweightFilePath);
if (nextPath === null) {
return;
}
const normalized = resolveLightweightEditorRelativePath(
nextPath,
lightweightParentDir(activeLightweightFilePath),
lightweightFiles?.mountPath || lightweightConfig(newOp).mountPath,
);
if (!normalized || hasLightweightPathTraversal(normalized)) {
setLightweightFileError("请输入容器挂载目录内的路径");
return;
}
operatorsApi
.moveLightweightPath(
editingOpId,
activeLightweightFilePath,
normalized,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
)
.then((result) => {
setActiveLightweightFilePath(result.newPath || normalized);
setActiveLightweightDirectoryPath(lightweightParentDir(result.newPath || normalized));
setNewLightweightFilePath(result.newPath || normalized);
refreshLightweightFiles(result.newPath || normalized);
})
.catch((error) => {
console.error("Failed to move lightweight operator path", error);
setLightweightFileError(getActionErrorMessage(error, "移动/重命名失败"));
});
};
const moveLightweightPathToDirectory = (sourcePath: string, targetDirectory: string) => {
if (!editingOpId || !lightweightFiles || lightweightFilesLoading || isLightweightUploading) {
return;
}
const sourceItem = lightweightFiles.items.find((item) => item.path === sourcePath);
if (!sourceItem) {
setLightweightFilesError("移动失败:源路径不存在");
return;
}
const plan = getLightweightMovePlan(
sourceItem.path,
sourceItem.kind,
targetDirectory,
lightweightFiles.items.map((item) => item.path),
);
if (!plan.ok) {
setLightweightFilesError(plan.issue);
return;
}
setLightweightFilesLoading(true);
setLightweightFilesError("");
setLightweightFileError("");
operatorsApi
.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);
setExpandedLightweightDirs((current) => {
const next = new Set(current);
for (const parent of parentDirectoriesForPath(`${movedPath}/placeholder`)) {
next.add(parent);
}
if (sourceItem.kind === "directory") {
next.add(movedPath);
}
return next;
});
setActiveLightweightDirectoryPath(movedDirectory);
refreshLightweightFiles(movedPath);
})
.catch((error) => {
console.error("Failed to drag-move lightweight operator path", error);
setLightweightFilesError(getActionErrorMessage(error, "移动失败"));
})
.finally(() => {
setDraggedLightweightPath("");
setLightweightDropTargetPath(null);
setLightweightFilesLoading(false);
});
};
const deleteActiveLightweightPath = () => {
if (!editingOpId || !activeLightweightFilePath) {
return;
}
const target = activeLightweightFilePath;
if (!window.confirm(`确认删除 ${target}?目录会递归删除。`)) {
return;
}
operatorsApi
.deleteLightweightPath(
editingOpId,
target,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
)
.then(() => {
setActiveLightweightFilePath("");
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("");
setActiveLightweightDirectoryPath(lightweightParentDir(target));
refreshLightweightFiles();
})
.catch((error) => {
console.error("Failed to delete lightweight operator path", error);
setLightweightFileError(getActionErrorMessage(error, "删除失败"));
});
};
const saveLightweightFile = () => {
if (!editingOpId || !activeLightweightFilePath || lightweightFileSaving) {
return;
}
setLightweightFileSaving(true);
setLightweightFileError("");
operatorsApi
.saveLightweightFileContent(
editingOpId,
activeLightweightFilePath,
lightweightFileDraft,
activeLightweightMountName === "code" ? undefined : activeLightweightMountName,
)
.then((content) => {
setLightweightFileDraft(content.content);
setLightweightFileSavedContent(content.content);
refreshLightweightFiles(content.path);
})
.catch((error) => {
console.error("Failed to save lightweight operator file", error);
setLightweightFileError(getActionErrorMessage(error, "保存代码文件失败"));
})
.finally(() => {
setLightweightFileSaving(false);
});
};
useEffect(() => {
if (!isModalOpen || !editingOpId || newOp.type !== "lightweight" || activeTab !== "implementation") {
return;
}
refreshLightweightFiles();
}, [activeTab, editingOpId, isModalOpen, newOp.type, refreshLightweightFiles]);
const openRegisterModal = (type: "custom" | "lightweight") => {
setActionError("");
setEditingOpId(null);
setActiveTab("basic");
setGeneratedImplementation(null);
setActiveImplementationFile("");
setContainerCommandDraft("[]");
setContainerArgsDraft("[]");
resetLightweightEditorState();
resetArchiveUpload();
setNewOp({
type,
category: type === "lightweight" ? "AI" : "CV",
version: "v1",
inputs: [],
outputs: [],
hyperparams: [],
skillDefinition: "",
generationSource: "manual",
publicationStatus: "published",
...(type === "lightweight"
? {
runtimeContract: {
lightweightOperator: {
enabled: true,
codeSubPath: "",
mountPath: defaultLightweightMountPath,
codeReadOnly: false,
},
},
}
: {}),
});
setIsModalOpen(true);
};
const setGeneratedImplementationState = (generated: GeneratedOperator) => {
const implementation = generated.implementation || null;
setGeneratedImplementation(implementation);
setActiveImplementationFile(implementation?.files?.[0]?.path || "");
return {
...(generated.runtimeContract || {}),
...(implementation ? { generatedRepository: implementation } : {}),
generationSource: "ai",
publicationStatus: "draft",
};
};
const handleRegister = () => {
if (isSavingOperator) {
return;
}
const commandOverride: Pick<Operator, "containerCommand" | "containerArgs"> | Record<string, never> =
newOp.type === "lightweight"
? (() => {
const command = parseCommandDraft("启动命令", containerCommandDraft);
if (command.issue) {
setActionError(command.issue);
return {};
}
const args = parseCommandDraft("启动参数", containerArgsDraft, { allowEmpty: true });
if (args.issue) {
setActionError(args.issue);
return {};
}
return {
containerCommand: command.items,
containerArgs: args.items,
};
})()
: {};
if (
newOp.type === "lightweight" &&
(!("containerCommand" in commandOverride) || !("containerArgs" in commandOverride))
) {
return;
}
const payload = buildOperatorPayload(newOp, {
name: operatorName,
description: operatorDescription,
type: newOp.type || "custom",
...commandOverride,
}) as Partial<Operator>;
if (payload.type === "lightweight" && !lightweightConfig(payload).codeSubPath.trim()) {
setActionError("轻量算子必须配置代码目录");
return;
}
if (payload.type === "lightweight" && !String(payload.image || "").trim()) {
setActionError("轻量算子必须配置基础镜像地址");
return;
}
if (payload.type === "lightweight" && !lightweightConfig(payload).mountPath.trim()) {
setActionError("轻量算子必须配置容器挂载目录");
return;
}
const payloadIssue = getOperatorPayloadIssue(payload);
if (payloadIssue) {
setActionError(payloadIssue);
return;
}
const selectedArchiveFile = archiveFile;
if (!editingOpId && imageSourceMode === "archive" && !selectedArchiveFile) {
setActionError("请选择 Docker 镜像归档文件");
return;
}
const resetModal = () => {
setIsModalOpen(false);
setEditingOpId(null);
setActiveTab("basic");
setNewOp({
type: "custom",
category: "CV",
version: "v1",
inputs: [],
outputs: [],
hyperparams: [],
skillDefinition: "",
generationSource: "manual",
publicationStatus: "published",
});
setGeneratedImplementation(null);
setActiveImplementationFile("");
setContainerCommandDraft("[]");
setContainerArgsDraft("[]");
resetLightweightEditorState();
resetArchiveUpload();
};
setActionError("");
setIsSavingOperator(true);
if (editingOpId) {
operatorsApi
.update(editingOpId, payload)
.then((updated) => {
setActionError("");
setOperators((current) => current.map((op) => (op.id === updated.id ? updated : op)));
resetModal();
})
.catch((error) => {
console.error("Failed to update operator", error);
setActionError(getActionErrorMessage(error, "更新算子失败"));
})
.finally(() => setIsSavingOperator(false));
} else if (imageSourceMode === "archive" && selectedArchiveFile) {
operatorsApi
.importImageArchive({
file: selectedArchiveFile,
operator: payload,
repository: archiveRepository.trim(),
tag: archiveTag.trim(),
archiveFormat,
})
.then((result) => {
setActionError("");
setOperators((current) => [result.operator, ...current]);
resetModal();
})
.catch((error) => {
console.error("Failed to import operator image archive", error);
setActionError(getActionErrorMessage(error, "导入镜像归档失败"));
})
.finally(() => setIsSavingOperator(false));
} else {
operatorsApi
.create(payload)
.then((created) => {
setActionError("");
setOperators((current) => [created, ...current]);
resetModal();
})
.catch((error) => {
console.error("Failed to create operator", error);
setActionError(getActionErrorMessage(error, "创建算子失败"));
})
.finally(() => setIsSavingOperator(false));
}
};
const handleEdit = (op: Operator) => {
setActionError("");
resetLightweightEditorState();
setEditingOpId(op.id);
setNewOp({ ...op });
setContainerCommandDraft(formatCommandDraft(op.containerCommand, defaultLightweightCommand));
setContainerArgsDraft(formatCommandDraft(op.containerArgs, defaultLightweightArgs));
setActiveTab("basic");
const implementation = op.runtimeContract?.generatedRepository as GeneratedImplementation | undefined;
setGeneratedImplementation(implementation || null);
setActiveImplementationFile(implementation?.files?.[0]?.path || "");
resetArchiveUpload();
setIsModalOpen(true);
};
const handleAIGenerate = async () => {
if (!aiDescription.trim()) return;
setIsGenerating(true);
setAiError(null);
try {
const generated = await generateOperatorFromDescription(aiDescription);
const runtimeContract = setGeneratedImplementationState(generated);
setNewOp({
...newOp,
name: generated.name,
category: generated.category,
description: generated.description,
version: generated.version || "v1.0.0",
image: generated.image || "",
imageId: generated.imageId || "",
containerCommand: generated.containerCommand || ["python", "/app/src/operator.py"],
containerArgs: generated.containerArgs || [],
runtimeContract,
resources: generated.resources,
inputs: generated.inputs.map((input) => ({ id: createPortID(), ...input })),
outputs: generated.outputs.map((output) => ({ id: createPortID(), ...output })),
hyperparams: generated.hyperparams || [],
skillDefinition: generated.skillDefinition,
generationSource: generated.generationSource || "ai",
publicationStatus: generated.publicationStatus || "draft",
publicationEvidence: generated.publicationEvidence,
});
setIsAIModalOpen(false);
setIsModalOpen(true);
setActiveTab("basic");
} catch (err) {
setAiError(getActionErrorMessage(err, "生成失败,请重试。"));
} finally {
setIsGenerating(false);
}
};
const handleDelete = (id: string) => {
if (deletingOperatorId) {
return;
}
const target = operators.find((op) => op.id === id);
if (!window.confirm(`确认删除算子 ${target?.name || id}?该操作可能影响依赖它的工作流。`)) {
return;
}
setActionError("");
setDeletingOperatorId(id);
operatorsApi
.remove(id)
.then(() => {
setActionError("");
setOperators((current) => current.filter((op) => op.id !== id));
})
.catch((error) => {
console.error("Failed to delete operator", error);
setActionError(getActionErrorMessage(error, "删除算子失败"));
})
.finally(() => {
setDeletingOperatorId(null);
});
};
const canManage = canManagePipelineDesign(role);
const operatorGenerationReady = aiStatus.enabled && (aiStatus.operatorGeneration?.ready ?? true);
const operatorGenerationReason = !aiStatus.enabled
? aiStatus.reason || "当前服务端未配置 AI 服务"
: aiStatus.operatorGeneration?.reason || "算子生成配置不完整,请在设置 - 算子生成相关设置中补齐";
const operatorGenerationMissingFields = aiStatus.operatorGeneration?.missingFields || [];
const normalizedSearch = searchQuery.trim().toLowerCase();
const filteredOperators = operators.filter((op) => {
const matchesSearch =
!normalizedSearch ||
[op.name, op.description, op.category, op.type]
.filter(Boolean)
.some((value) => value.toLowerCase().includes(normalizedSearch));
const gpuRequirement = getGPURequirement(op);
const transmissions = [...(op.inputs || []), ...(op.outputs || [])].map((port) => port.transmission || "bus");
return (
matchesSearch &&
(typeFilter === "all" || op.type === typeFilter) &&
(gpuFilter === "all" || (gpuFilter === "required" ? gpuRequirement.required : !gpuRequirement.required)) &&
(publicationFilter === "all" || (op.publicationStatus || "published") === publicationFilter) &&
(portFilter === "all" || transmissions.includes(portFilter as PortTransmission)) &&
(quickFilter === "all" ||
(quickFilter === "favorites" ? favoriteOperatorIds.includes(op.id) : recentOperatorIds.includes(op.id)))
);
});
const lightweightVisibleFileItems =
lightweightFiles?.items.filter((item) => isLightweightFileItemVisible(item, expandedLightweightDirs)) || [];
const activeLightweightFileItem = lightweightFiles?.items.find((item) => item.path === activeLightweightFilePath);
const lightweightEditorDirty = lightweightFileDraft !== lightweightFileSavedContent;
const activeLightweightFileExists = Boolean(activeLightweightFileItem);
const activeLightweightPathIsDirectory = activeLightweightFileItem?.kind === "directory";
const activeLightweightPathIsEditableFile =
!activeLightweightFileItem || (activeLightweightFileItem.kind === "file" && activeLightweightFileItem.editable);
const lightweightMountPath = lightweightFiles?.mountPath || currentLightweightConfig.mountPath;
const activeLightweightContainerDirectoryPath = lightweightContainerPath(
lightweightMountPath,
activeLightweightDirectoryPath,
);
const activeLightweightContainerFilePath = activeLightweightFilePath
? lightweightContainerPath(lightweightMountPath, activeLightweightFilePath)
: "";
const closeOperatorModal = () => {
if (isSavingOperator) {
return;
}
resetLightweightEditorState();
setIsModalOpen(false);
};
return (
<div className="space-y-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight text-white">算子管理</h1>
<p className="text-gray-500 mt-1">工作流的基础功能模块,运行在 K8s 集群中</p>
</div>
{canManage && (
<div className="flex flex-wrap justify-end gap-3">
<button
onClick={() => {
setAiDescription("");
setAiError(null);
setActionError("");
setIsAIModalOpen(true);
}}
disabled={!operatorGenerationReady}
title={operatorGenerationReady ? `使用 ${aiStatus.model} 辅助生成算子定义` : operatorGenerationReason}
className={cn(
"flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors border border-blue-500/20",
operatorGenerationReady
? "bg-white/5 hover:bg-white/10 text-blue-400"
: "bg-white/5 text-gray-500 cursor-not-allowed opacity-60",
)}
>
<Sparkles className="w-4 h-4" />
AI 辅助注册
</button>
<button
onClick={() => openRegisterModal("custom")}
className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors"
>
<Plus className="w-4 h-4" />
注册算子
</button>
<button
onClick={() => openRegisterModal("lightweight")}
className="flex items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-4 py-2 text-sm font-medium text-emerald-100 transition-colors hover:bg-emerald-500/20"
>
<Code className="w-4 h-4" />
注册轻量算子
</button>
</div>
)}
</div>
{actionError && !isModalOpen && (
<div className="flex items-center gap-3 rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-200">
<AlertCircle className="h-4 w-4 shrink-0" />
<span>{actionError}</span>
</div>
)}
<div className="grid gap-3 bg-[#151619] p-4 rounded-lg border border-[#2a2b2f] lg:grid-cols-[minmax(260px,1fr)_repeat(5,minmax(120px,auto))]">
<div className="relative min-w-0">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
<input
type="text"
placeholder="搜索算子..."
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md pl-10 pr-4 py-2 text-sm focus:outline-none focus:border-blue-500 transition-colors"
/>
</div>
<select
value={typeFilter}
onChange={(event) => setTypeFilter(event.target.value)}
className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-xs focus:border-blue-500 focus:outline-none"
aria-label="按算子类型筛选"
>
<option value="all">全部类型</option>
<option value="builtin">内置</option>
<option value="custom">自定义</option>
<option value="lightweight">轻量</option>
</select>
<select
value={gpuFilter}
onChange={(event) => setGpuFilter(event.target.value)}
className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-xs focus:border-blue-500 focus:outline-none"
aria-label="按 GPU 需求筛选"
>
<option value="all">全部算力</option>
<option value="required">需要 GPU</option>
<option value="cpu">CPU 可运行</option>
</select>
<select
value={publicationFilter}
onChange={(event) => setPublicationFilter(event.target.value)}
className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-xs focus:border-blue-500 focus:outline-none"
aria-label="按发布状态筛选"
>
<option value="all">全部发布状态</option>
<option value="draft">草稿</option>
<option value="built">已构建</option>
<option value="verified">已验证</option>
<option value="published">已发布</option>
</select>
<select
value={portFilter}
onChange={(event) => setPortFilter(event.target.value)}
className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-xs focus:border-blue-500 focus:outline-none"
aria-label="按端口协议筛选"
>
<option value="all">全部端口协议</option>
{portTransmissions.map((transmission) => (
<option key={transmission} value={transmission}>
{transmission.toUpperCase()}
</option>
))}
</select>
<select
value={quickFilter}
onChange={(event) => setQuickFilter(event.target.value)}
className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-xs focus:border-blue-500 focus:outline-none"
aria-label="按收藏或最近使用筛选"
>
<option value="all">全部算子</option>
<option value="favorites">我的收藏</option>
<option value="recent">最近使用</option>
</select>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{filteredOperators.map((op) => {
const gpuRequirement = getGPURequirement(op);
return (
<div
key={op.id}
data-testid="operator-card"
onDoubleClick={() => {
markOperatorRecent(op.id);
if (canManage) handleEdit(op);
}}
className={cn(
"bg-[#151619] border border-[#2a2b2f] rounded-xl p-6 hover:bg-[#1a1b1e] transition-all group relative",
canManage && "cursor-pointer",
)}
>
<div className="flex items-center justify-between mb-4">
<div
className={cn(
"w-12 h-12 rounded-lg flex items-center justify-center",
op.type === "builtin"
? "bg-blue-500/10 text-blue-500"
: op.type === "lightweight"
? "bg-emerald-500/10 text-emerald-400"
: "bg-purple-500/10 text-purple-500",
)}
>
{op.category === "IO" ? <Box className="w-6 h-6" /> : <Code className="w-6 h-6" />}
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => toggleOperatorFavorite(op.id)}
className={cn(
"rounded p-1.5 transition-colors",
favoriteOperatorIds.includes(op.id)
? "bg-amber-500/10 text-amber-300"
: "text-gray-600 hover:bg-white/5 hover:text-amber-300",
)}
title={favoriteOperatorIds.includes(op.id) ? "取消收藏" : "收藏算子"}
aria-label={favoriteOperatorIds.includes(op.id) ? `取消收藏 ${op.name}` : `收藏 ${op.name}`}
>
<Star className={cn("h-3.5 w-3.5", favoriteOperatorIds.includes(op.id) && "fill-current")} />
</button>
{isAIGeneratedOperator(op) && (
<span className="rounded border border-pink-400/30 bg-pink-500/10 px-2 py-0.5 text-[10px] font-semibold text-pink-200">
AI {getPublicationStatusLabel(op.publicationStatus)}
</span>
)}
{!isAIGeneratedOperator(op) && op.publicationStatus && (
<span className="rounded border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-semibold text-emerald-200">
{getPublicationStatusLabel(op.publicationStatus)}
</span>
)}
{canManage && (
<>
{op.type !== "builtin" && (
<button
onClick={() => {
markOperatorRecent(op.id);
handleEdit(op);
}}
disabled={Boolean(deletingOperatorId)}
className="p-1.5 hover:bg-white/5 rounded text-gray-500 hover:text-blue-400 transition-colors disabled:cursor-not-allowed disabled:opacity-50"
>
<Edit3 className="w-3.5 h-3.5" />
</button>
)}
<button
onClick={() => handleDelete(op.id)}
disabled={Boolean(deletingOperatorId)}
className="p-1.5 hover:bg-white/5 rounded text-gray-500 hover:text-red-400 transition-colors disabled:cursor-not-allowed disabled:opacity-50"
>
{deletingOperatorId === op.id ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<Trash2 className="w-3.5 h-3.5" />
)}
</button>
</>
)}
<span
className={cn(
"text-[10px] px-2 py-0.5 rounded-full font-mono uppercase tracking-wider",
op.type === "builtin"
? "bg-blue-500/10 text-blue-500 border border-blue-500/20"
: op.type === "lightweight"
? "bg-emerald-500/10 text-emerald-300 border border-emerald-500/20"
: "bg-purple-500/10 text-purple-500 border border-purple-500/20",
)}
>
{op.type === "builtin" ? "Built-in" : op.type === "lightweight" ? "Lightweight" : "Custom"}
</span>
{op.version && (
<span className="text-[10px] px-2 py-0.5 rounded-full font-mono uppercase tracking-wider bg-amber-500/10 text-amber-400 border border-amber-500/20">
{op.version}
</span>
)}
{op.skillDefinition && (
<span className="text-[10px] px-2 py-0.5 rounded-full font-mono uppercase tracking-wider bg-green-500/10 text-green-500 border border-green-500/20 flex items-center gap-1">
<Layers className="w-2.5 h-2.5" />
Skill
</span>
)}
{gpuRequirement.required && (
<span className="text-[10px] px-2 py-0.5 rounded-full font-mono uppercase tracking-wider bg-cyan-500/10 text-cyan-300 border border-cyan-500/30 flex items-center gap-1">
<Zap className="w-2.5 h-2.5" />
GPU {gpuRequirement.gpuType} x{gpuRequirement.gpuLimit}
</span>
)}
{trimResource(op.resources?.sharedMemorySize) && (
<span className="text-[10px] px-2 py-0.5 rounded-full font-mono uppercase tracking-wider bg-violet-500/10 text-violet-300 border border-violet-500/30">
SHM {trimResource(op.resources?.sharedMemorySize)}
</span>
)}
</div>
</div>
<h3 className="text-lg font-bold text-white mb-1">{op.name}</h3>
<p className="text-sm text-gray-500 mb-6 h-10 line-clamp-2">{op.description}</p>
{/* Contract / Ports Display */}
<div className="space-y-3 mb-6">
<div className="flex items-center gap-2 text-[10px] text-gray-600 uppercase font-mono tracking-widest">
<Layers className="w-3 h-3" />
契约定义 (Ports)
</div>
<div className="flex flex-wrap gap-2">
{op.inputs?.map((port) => (
<span
key={port.id}
className="px-2 py-1 bg-blue-500/5 border border-blue-500/20 rounded text-[10px] text-blue-400"
>
IN: {port.name} ({port.type})
</span>
))}
{op.outputs?.map((port) => (
<span
key={port.id}
className="px-2 py-1 bg-green-500/5 border border-green-500/20 rounded text-[10px] text-green-400"
>
OUT: {port.name} ({port.type})
</span>
))}
{!op.inputs?.length && !op.outputs?.length && (
<span className="text-[10px] text-gray-700 italic">无端口定义</span>
)}
</div>
</div>
{/* Hyperparams Summary */}
{op.hyperparams && op.hyperparams.length > 0 && (
<div className="space-y-3 mb-6">
<div className="flex items-center gap-2 text-[10px] text-gray-600 uppercase font-mono tracking-widest">
<Cpu className="w-3 h-3" />
超参配置 (Hyperparams)
</div>
<div className="flex flex-wrap gap-2">
{op.hyperparams.map((hp) => (
<span
key={hp.key}
className="px-2 py-1 bg-orange-500/5 border border-orange-500/20 rounded text-[10px] text-orange-400 font-mono"
>
{hp.key}={hp.value}
</span>
))}
</div>
</div>
)}
<div className="flex items-center justify-between pt-4 border-t border-[#2a2b2f]">
<span className="text-[10px] text-gray-600 font-mono uppercase tracking-widest">{op.category}</span>
<button
onClick={() => handleEdit(op)}
className="text-xs text-blue-500 hover:underline flex items-center gap-1"
>
{canManage ? "配置详情" : "查看详情"}
<Info className="w-3 h-3" />
</button>
</div>
</div>
);
})}
{filteredOperators.length === 0 && (
<div className="col-span-full bg-[#151619] border border-[#2a2b2f] rounded-xl p-12 text-center text-gray-500">
{operators.length === 0 ? "当前还没有算子,请先注册或同步内置算子。" : "没有匹配的算子,请调整搜索条件。"}
</div>
)}
</div>
{/* Registration/Edit Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
<div className="bg-[#151619] border border-[#2a2b2f] rounded-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col shadow-2xl">
<div className="px-6 py-4 border-b border-[#2a2b2f] flex items-center justify-between">
<h2 className="text-xl font-bold text-white">{editingOpId ? "编辑算子" : "注册新算子"}</h2>
<button
type="button"
onClick={closeOperatorModal}
disabled={isSavingOperator}
className="text-gray-500 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
>
<X className="w-6 h-6" />
</button>
</div>
{/* Tabs */}
<div className="flex px-6 border-b border-[#2a2b2f]">
<button
type="button"
onClick={() => setActiveTab("basic")}
className={cn(
"px-4 py-3 text-xs font-bold uppercase tracking-widest transition-all border-b-2",
activeTab === "basic"
? "text-blue-500 border-blue-500"
: "text-gray-500 border-transparent hover:text-gray-300",
)}
>
基础配置
</button>
<button
type="button"
onClick={() => setActiveTab("ports")}
className={cn(
"px-4 py-3 text-xs font-bold uppercase tracking-widest transition-all border-b-2",
activeTab === "ports"
? "text-blue-500 border-blue-500"
: "text-gray-500 border-transparent hover:text-gray-300",
)}
>
端口定义
</button>
<button
type="button"
onClick={() => setActiveTab("hyperparams")}
className={cn(
"px-4 py-3 text-xs font-bold uppercase tracking-widest transition-all border-b-2",
activeTab === "hyperparams"
? "text-blue-500 border-blue-500"
: "text-gray-500 border-transparent hover:text-gray-300",
)}
>
超参配置
</button>
<button
type="button"
onClick={() => setActiveTab("skill")}
className={cn(
"px-4 py-3 text-xs font-bold uppercase tracking-widest transition-all border-b-2",
activeTab === "skill"
? "text-blue-500 border-blue-500"
: "text-gray-500 border-transparent hover:text-gray-300",
)}
>
AI Skill 描述
</button>
{(generatedImplementation || newOp.type === "lightweight") && (
<button
type="button"
onClick={() => setActiveTab("implementation")}
className={cn(
"px-4 py-3 text-xs font-bold uppercase tracking-widest transition-all border-b-2",
activeTab === "implementation"
? "text-blue-500 border-blue-500"
: "text-gray-500 border-transparent hover:text-gray-300",
)}
>
{newOp.type === "lightweight" ? "代码目录" : "实现文件"}
</button>
)}
</div>
<div className="p-6 overflow-y-auto flex-1 space-y-6">
{actionError && (
<div className="flex items-center gap-3 rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-200">
<AlertCircle className="h-4 w-4 shrink-0" />
<span>{actionError}</span>
</div>
)}
{activeTab === "basic" && (
<div className="space-y-6">
{generatedImplementation && (
<div className="rounded-lg border border-blue-500/20 bg-blue-500/5 p-4 text-xs leading-6 text-blue-100">
<div className="flex items-center gap-2 text-sm font-semibold text-white">
<Sparkles className="h-4 w-4 text-blue-400" />
AI 已生成外部算子工程骨架
</div>
<p className="mt-2 text-gray-400">
已生成 Dockerfile、运行入口、runtime contract 和验收清单。它可以作为真实外部算子的起点,
但提交生产 workflow 前仍需补齐业务处理逻辑、构建镜像、推送 CCR,并把 digest 填入镜像字段。
</p>
<p className="mt-1 font-mono text-blue-300">建议目录:{generatedImplementation.repositoryPath}</p>
</div>
)}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">算子名称</label>
<input
type="text"
placeholder="例如: 图像锐化"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500"
value={newOp.name || ""}
onChange={(e) => setNewOp({ ...newOp, name: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">分类</label>
<select
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500"
value={newOp.category || "CV"}
onChange={(e) => setNewOp({ ...newOp, category: e.target.value })}
>
<option value="CV">计算机视觉 (CV)</option>
<option value="AI">人工智能 (AI)</option>
<option value="IO">输入输出 (IO)</option>
<option value="MATH">数学运算 (MATH)</option>
</select>
</div>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">算子类型</label>
<div className="grid grid-cols-2 gap-2">
<button
type="button"
disabled={Boolean(editingOpId)}
onClick={() => setNewOp((current) => ({ ...current, type: "custom" }))}
className={cn(
"rounded-md border px-3 py-2 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-60",
newOp.type !== "lightweight"
? "border-blue-500 bg-blue-500/10 text-blue-300"
: "border-[#2a2b2f] bg-[#0a0a0a] text-gray-400 hover:text-white",
)}
>
普通算子
</button>
<button
type="button"
disabled={Boolean(editingOpId)}
onClick={() => {
setImageSourceMode("reference");
setContainerCommandDraft(
formatCommandDraft(newOp.containerCommand, defaultLightweightCommand),
);
setContainerArgsDraft(formatCommandDraft(newOp.containerArgs, defaultLightweightArgs));
updateLightweightConfig({});
}}
className={cn(
"rounded-md border px-3 py-2 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-60",
newOp.type === "lightweight"
? "border-emerald-500 bg-emerald-500/10 text-emerald-300"
: "border-[#2a2b2f] bg-[#0a0a0a] text-gray-400 hover:text-white",
)}
>
轻量算子
</button>
</div>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">算子版本</label>
<input
type="text"
placeholder={imageSourceMode === "archive" ? "留空时默认使用镜像 tag" : "v1"}
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500"
value={newOp.version || ""}
onChange={(e) => setNewOp({ ...newOp, version: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">描述</label>
<textarea
placeholder="描述该算子的功能与用途..."
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm h-20 focus:outline-none focus:border-blue-500"
value={newOp.description || ""}
onChange={(e) => setNewOp({ ...newOp, description: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">镜像来源</label>
{!editingOpId && newOp.type !== "lightweight" && (
<div className="grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => {
setImageSourceMode("reference");
setNewOp((current) => ({ ...current, version: current.version || "v1" }));
}}
className={cn(
"flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-xs font-medium transition-colors",
imageSourceMode === "reference"
? "border-blue-500 bg-blue-500/10 text-blue-300"
: "border-[#2a2b2f] bg-[#0a0a0a] text-gray-400 hover:text-white",
)}
>
<Code className="h-3.5 w-3.5" />
镜像地址
</button>
<button
type="button"
onClick={() => {
setImageSourceMode("archive");
setNewOp((current) => ({
...current,
version: current.version === "v1" ? "" : current.version,
}));
}}
className={cn(
"flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-xs font-medium transition-colors",
imageSourceMode === "archive"
? "border-blue-500 bg-blue-500/10 text-blue-300"
: "border-[#2a2b2f] bg-[#0a0a0a] text-gray-400 hover:text-white",
)}
>
<UploadCloud className="h-3.5 w-3.5" />
上传归档
</button>
</div>
)}
</div>
{(editingOpId || imageSourceMode === "reference") && (
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">
{newOp.type === "lightweight" ? "基础镜像地址" : "Docker 镜像地址"}
</label>
<input
type="text"
placeholder="registry.flowai.io/operators/sharpen:v1.0"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500"
value={newOp.image || ""}
onChange={(e) => setNewOp({ ...newOp, image: e.target.value })}
/>
</div>
)}
{newOp.type === "lightweight" && (
<div className="space-y-4 rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-4">
<div>
<div className="flex items-center gap-2 text-sm font-semibold text-white">
<Code className="h-4 w-4 text-emerald-300" />
轻量算子代码目录
</div>
<p className="mt-1 text-xs leading-5 text-gray-400">
基础镜像只提供环境;真实功能代码放在对象存储工作区目录中,运行时会挂载到容器内。
</p>
</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">
Workspace 子目录
</label>
<input
type="text"
placeholder="例如 lightweight-operators/train-demo"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-emerald-500"
value={lightweightConfig(newOp).codeSubPath}
onChange={(event) => updateLightweightConfig({ codeSubPath: event.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
容器挂载目录
</label>
<input
type="text"
placeholder={defaultLightweightMountPath}
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-emerald-500"
value={lightweightConfig(newOp).mountPath}
onChange={(event) => updateLightweightConfig({ mountPath: event.target.value })}
/>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-xs text-gray-500">
启动命令由轻量算子管理;运行时会注入{" "}
<span className="font-mono">LIGHTWEIGHT_OPERATOR_CODE_DIR</span>。
</p>
<label className="inline-flex items-center gap-2 text-xs text-gray-300">
<input
type="checkbox"
checked={lightweightConfig(newOp).codeReadOnly}
onChange={(event) => updateLightweightConfig({ codeReadOnly: event.target.checked })}
/>
代码目录只读挂载(默认可写)
</label>
<button
type="button"
disabled={!lightweightConfig(newOp).codeSubPath.trim()}
onClick={() => {
if (editingOpId) {
setActiveTab("implementation");
return;
}
const prefix = encodeURIComponent(
lightweightConfig(newOp)
.codeSubPath.trim()
.replace(/^\/+|\/+$/g, ""),
);
window.open(`/object-storage?prefix=${prefix}`, "_blank", "noopener,noreferrer");
}}
className="rounded-md border border-emerald-500/30 px-3 py-1.5 text-xs font-medium text-emerald-200 transition-colors hover:bg-emerald-500/10 disabled:cursor-not-allowed disabled:opacity-50"
>
{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">
启动命令 containerCommand
</label>
<textarea
className="h-24 w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 font-mono text-xs focus:outline-none focus:border-emerald-500"
value={containerCommandDraft}
onChange={(event) => setContainerCommandDraft(event.target.value)}
spellCheck={false}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
启动参数 containerArgs
</label>
<textarea
className="h-24 w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 font-mono text-xs focus:outline-none focus:border-emerald-500"
value={containerArgsDraft}
onChange={(event) => setContainerArgsDraft(event.target.value)}
spellCheck={false}
/>
</div>
</div>
</div>
)}
{!editingOpId && imageSourceMode === "archive" && (
<div className="space-y-4 rounded-lg border border-blue-500/20 bg-blue-500/5 p-4">
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">
Docker 镜像归档
</label>
<label className="flex cursor-pointer items-center justify-between gap-3 rounded-md border border-dashed border-[#3a3b40] bg-[#0a0a0a] px-4 py-3 text-sm text-gray-300 hover:border-blue-500/60">
<span className="min-w-0 truncate">
{archiveFile ? archiveFile.name : "选择 .tar / .tar.gz / .tgz 文件"}
</span>
<UploadCloud className="h-4 w-4 shrink-0 text-blue-400" />
<input
type="file"
accept=".tar,.tar.gz,.tgz,application/x-tar,application/gzip"
className="hidden"
onChange={(event) => setArchiveFile(event.target.files?.[0] || null)}
/>
</label>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
目标仓库名
</label>
<input
type="text"
placeholder="默认使用算子名称"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={archiveRepository}
onChange={(e) => setArchiveRepository(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">Tag</label>
<input
type="text"
placeholder="默认自动生成"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={archiveTag}
onChange={(e) => setArchiveTag(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
归档格式
</label>
<select
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={archiveFormat}
onChange={(e) => setArchiveFormat(e.target.value === "oci" ? "oci" : "docker")}
>
<option value="docker">Docker archive</option>
<option value="oci">OCI archive</option>
</select>
</div>
</div>
</div>
)}
<div className="space-y-4 rounded-lg border border-[#2a2b2f] bg-[#0a0a0a]/60 p-4">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm font-semibold text-white">
<Cpu className="h-4 w-4 text-blue-400" />
资源默认值
</div>
<label className="flex cursor-pointer items-center gap-2 text-xs text-gray-300">
<input
type="checkbox"
className="h-4 w-4 accent-blue-500"
checked={getGPURequirement(newOp).configured}
onChange={(event) => setGPURequired(event.target.checked)}
/>
需要 GPU
</label>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-5">
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
CPU Request
</label>
<input
type="text"
placeholder="例如 2"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.cpuRequest || ""}
onChange={(event) => updateResources({ cpuRequest: event.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
CPU Limit
</label>
<input
type="text"
placeholder="例如 16"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.cpuLimit || ""}
onChange={(event) => updateResources({ cpuLimit: event.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
Memory Request
</label>
<input
type="text"
placeholder="例如 16Gi"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.memoryRequest || ""}
onChange={(event) => updateResources({ memoryRequest: event.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
Memory Limit
</label>
<input
type="text"
placeholder="例如 64Gi"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.memoryLimit || ""}
onChange={(event) => updateResources({ memoryLimit: event.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
Shared Memory (/dev/shm)
</label>
<input
type="text"
list="droboticflow-shared-memory-sizes"
placeholder="留空继承平台默认"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.sharedMemorySize || ""}
onChange={(event) => updateResources({ sharedMemorySize: event.target.value })}
/>
<datalist id="droboticflow-shared-memory-sizes">
{["1Gi", "2Gi", "4Gi", "8Gi", "16Gi", "32Gi"].map((size) => (
<option key={size} value={size} />
))}
</datalist>
<p className="text-[10px] leading-snug text-gray-600">
空值继承平台默认;实际使用会占用 Pod/节点内存。
</p>
</div>
</div>
{getGPURequirement(newOp).configured && (
<div className="grid grid-cols-1 gap-3 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
GPU 型号
</label>
<select
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.gpuType || "NVIDIA A800 80GB"}
onChange={(event) => updateResources({ gpuType: event.target.value })}
>
{gpuTypeOptions.map((gpuType) => (
<option key={gpuType} value={gpuType}>
{gpuType}
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-medium uppercase tracking-wider text-gray-500">
GPU 数量
</label>
<input
type="number"
min={1}
step={1}
className="w-full bg-[#151619] border border-[#2a2b2f] rounded-md px-3 py-2 text-xs focus:outline-none focus:border-blue-500"
value={newOp.resources?.gpuLimit || "1"}
onChange={(event) => updateResources({ gpuLimit: event.target.value })}
/>
</div>
</div>
)}
</div>
</div>
)}
{activeTab === "ports" && (
<div className="space-y-6">
<div className="space-y-3 min-w-0">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">
输入端口 (Inputs)
</label>
<button
type="button"
onClick={() => handleAddPort("inputs")}
className="text-blue-500 hover:text-blue-400 text-xs flex items-center gap-1"
>
<Plus className="w-3 h-3" /> 添加
</button>
</div>
<div className="space-y-2">
{newOp.inputs?.map((port, idx) => (
<div
key={port.id}
className="grid grid-cols-[minmax(0,1fr)_5.5rem_5rem_auto] gap-2 items-center"
>
<input
type="text"
placeholder="名称"
className="min-w-0 bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-xs"
value={port.name}
onChange={(e) => updatePort("inputs", idx, { name: e.target.value })}
/>
<select
className="w-full shrink-0 bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-xs"
value={port.type}
onChange={(e) => {
const type = parsePortType(e.target.value);
updatePort("inputs", idx, (current) => ({
...current,
type,
transmission:
type === "video" || type === "file" ? "oss" : type === "tensor" ? "stream" : "bus",
}));
}}
>
<option value="json">JSON</option>
<option value="image">Image</option>
<option value="video">Video</option>
<option value="tensor">Tensor</option>
<option value="file">File</option>
</select>
<select
className="w-full shrink-0 bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-[10px] text-blue-400"
value={port.transmission}
onChange={(e) =>
updatePort("inputs", idx, { transmission: parsePortTransmission(e.target.value) })
}
>
<option value="bus">Bus</option>
<option value="oss">OSS</option>
<option value="shm">SHM</option>
<option value="stream">Stream</option>
</select>
<button
type="button"
onClick={() => removePort("inputs", idx)}
className="shrink-0 p-1.5 text-gray-600 hover:text-red-500"
aria-label={`删除输入端口 ${port.name || idx + 1}`}
>
<Trash2 className="w-3 h-3" />
</button>
</div>
))}
</div>
</div>
<div className="space-y-3 min-w-0">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">
输出端口 (Outputs)
</label>
<button
type="button"
onClick={() => handleAddPort("outputs")}
className="text-green-500 hover:text-green-400 text-xs flex items-center gap-1"
>
<Plus className="w-3 h-3" /> 添加
</button>
</div>
<div className="space-y-2">
{newOp.outputs?.map((port, idx) => (
<div
key={port.id}
className="grid grid-cols-[minmax(0,1fr)_5.5rem_5rem_auto] gap-2 items-center"
>
<input
type="text"
placeholder="名称"
className="min-w-0 bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-xs"
value={port.name}
onChange={(e) => updatePort("outputs", idx, { name: e.target.value })}
/>
<select
className="w-full shrink-0 bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-xs"
value={port.type}
onChange={(e) => {
const type = parsePortType(e.target.value);
updatePort("outputs", idx, (current) => ({
...current,
type,
transmission:
type === "video" || type === "file" ? "oss" : type === "tensor" ? "stream" : "bus",
}));
}}
>
<option value="json">JSON</option>
<option value="image">Image</option>
<option value="video">Video</option>
<option value="tensor">Tensor</option>
<option value="file">File</option>
</select>
<select
className="w-full shrink-0 bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-[10px] text-blue-400"
value={port.transmission}
onChange={(e) =>
updatePort("outputs", idx, { transmission: parsePortTransmission(e.target.value) })
}
>
<option value="bus">Bus</option>
<option value="oss">OSS</option>
<option value="shm">SHM</option>
<option value="stream">Stream</option>
</select>
<button
type="button"
onClick={() => removePort("outputs", idx)}
className="shrink-0 p-1.5 text-gray-600 hover:text-red-500"
aria-label={`删除输出端口 ${port.name || idx + 1}`}
>
<Trash2 className="w-3 h-3" />
</button>
</div>
))}
</div>
</div>
</div>
)}
{activeTab === "hyperparams" && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 text-blue-500">
<Cpu className="w-4 h-4" />
<h3 className="text-sm font-bold uppercase tracking-wider">超参定义 (K8s Env Vars)</h3>
</div>
<button
type="button"
onClick={handleAddHyperParam}
className="text-blue-500 hover:text-blue-400 text-xs flex items-center gap-1"
>
<Plus className="w-3 h-3" /> 添加参数
</button>
</div>
<div className="p-4 bg-orange-500/5 border border-orange-500/20 rounded-lg flex items-start gap-3 mb-4">
<Info className="w-4 h-4 text-orange-500 mt-0.5" />
<p className="text-[10px] text-gray-500 leading-relaxed">
超参将作为环境变量注入到算子的 K8s Job 中。 例如:设置 <code>CONFIDENCE_THRESHOLD</code> 为{" "}
<code>0.5</code>, 算子代码中可以通过 <code>os.environ.get('CONFIDENCE_THRESHOLD')</code> 获取。
</p>
</div>
<div className="space-y-3">
{newOp.hyperparams?.map((hp, idx) => (
<div
key={idx}
className="bg-[#0a0a0a] border border-[#2a2b2f] rounded-lg p-4 space-y-3 relative group"
>
<button
type="button"
onClick={() => {
const hyperparams = newOp.hyperparams?.filter((_, i) => i !== idx);
setNewOp({ ...newOp, hyperparams });
}}
className="absolute top-2 right-2 text-gray-600 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
>
<Trash2 className="w-4 h-4" />
</button>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1">
<label className="text-[10px] text-gray-500 uppercase font-mono">变量名 (Key)</label>
<input
type="text"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded px-3 py-1.5 text-xs focus:outline-none focus:border-blue-500 font-mono"
value={hp.key}
onChange={(e) => {
const hyperparams = [...(newOp.hyperparams || [])];
hyperparams[idx].key = e.target.value.toUpperCase().replace(/\s+/g, "_");
setNewOp({ ...newOp, hyperparams });
}}
/>
</div>
<div className="space-y-1">
<label className="text-[10px] text-gray-500 uppercase font-mono">
默认值 (Default Value)
</label>
<input
type="text"
className="w-full bg-[#151619] border border-[#2a2b2f] rounded px-3 py-1.5 text-xs focus:outline-none focus:border-blue-500"
value={hp.value}
onChange={(e) => {
const hyperparams = [...(newOp.hyperparams || [])];
hyperparams[idx].value = e.target.value;
setNewOp({ ...newOp, hyperparams });
}}
/>
</div>
</div>
<div className="space-y-1">
<label className="text-[10px] text-gray-500 uppercase font-mono">描述 (Description)</label>
<input
type="text"
placeholder="说明该参数的作用..."
className="w-full bg-[#151619] border border-[#2a2b2f] rounded px-3 py-1.5 text-xs focus:outline-none focus:border-blue-500"
value={hp.description}
onChange={(e) => {
const hyperparams = [...(newOp.hyperparams || [])];
hyperparams[idx].description = e.target.value;
setNewOp({ ...newOp, hyperparams });
}}
/>
</div>
</div>
))}
{(!newOp.hyperparams || newOp.hyperparams.length === 0) && (
<div className="text-center py-10 border-2 border-dashed border-[#2a2b2f] rounded-xl text-gray-600 text-xs">
暂无超参配置,点击上方“添加参数”开始
</div>
)}
</div>
</div>
)}
{activeTab === "skill" && (
<div className="space-y-4">
<div className="p-4 bg-blue-500/5 border border-blue-500/20 rounded-lg flex items-start gap-3">
<Info className="w-4 h-4 text-blue-500 mt-0.5" />
<p className="text-[10px] text-gray-500 leading-relaxed">
AI Skill 描述用于向 AI 助手描述该算子的功能、输入输出要求以及使用场景。 良好的描述能帮助 AI
更准确地在自动化工作流生成中使用该算子。
</p>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">
Skill 定义 (Markdown)
</label>
<textarea
placeholder="### 算子名称\n描述算子的核心功能...\n\n#### 使用场景\n在什么情况下应该使用该算子...\n\n#### 限制条件\n输入数据的特殊要求..."
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm h-64 font-mono focus:outline-none focus:border-blue-500"
value={newOp.skillDefinition || ""}
onChange={(e) => setNewOp({ ...newOp, skillDefinition: e.target.value })}
/>
</div>
</div>
)}
{activeTab === "implementation" && newOp.type === "lightweight" && (
<div className="space-y-4">
{!editingOpId ? (
<div className="rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-4 text-xs leading-6 text-emerald-100">
<div className="flex items-center gap-2 text-sm font-semibold text-white">
<FolderOpen className="h-4 w-4 text-emerald-300" />
轻量算子代码目录
</div>
<p className="mt-2 text-gray-400">先保存算子配置后,可以在这里展开并修改该算子的代码目录。</p>
</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>
<div className="mt-1 break-all font-mono text-xs text-gray-200">
{lightweightFiles?.codeSubPath || lightweightConfig(newOp).codeSubPath || "未配置"}
</div>
</div>
<div className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2">
<div className="text-[10px] uppercase tracking-wider text-gray-500">容器挂载目录</div>
<div className="mt-1 break-all font-mono text-xs text-gray-200">
{lightweightFiles?.mountPath ||
lightweightConfig(newOp).mountPath ||
defaultLightweightMountPath}
</div>
</div>
<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>
<div className="mt-1 break-all font-mono text-xs text-gray-200">
{lightweightFiles?.workspacePath || "未加载"}
</div>
</div>
<div className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2">
<div className="text-[10px] uppercase tracking-wider text-gray-500">运行挂载</div>
<div className="mt-1 font-mono text-xs text-gray-200">
{lightweightFiles?.readOnly ? "read-only" : "read-write by default"}
</div>
</div>
</div>
{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"
value={newLightweightFilePath}
onChange={(event) => setNewLightweightFilePath(event.target.value)}
placeholder="src/operator.py"
className="min-w-0 rounded-md border border-[#2a2b2f] bg-[#151619] px-3 py-2 font-mono text-xs focus:border-emerald-500 focus:outline-none"
/>
<button
type="button"
onClick={openNewLightweightFile}
className="inline-flex items-center justify-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs font-medium text-emerald-100 transition-colors hover:bg-emerald-500/15"
>
<Plus className="h-3.5 w-3.5" />
新建/打开文件
</button>
<input
type="text"
value={newLightweightDirectoryPath}
onChange={(event) => setNewLightweightDirectoryPath(event.target.value)}
placeholder="src"
className="min-w-0 rounded-md border border-[#2a2b2f] bg-[#151619] px-3 py-2 font-mono text-xs focus:border-emerald-500 focus:outline-none"
/>
<button
type="button"
onClick={createLightweightDirectory}
className="inline-flex items-center justify-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs font-medium text-emerald-100 transition-colors hover:bg-emerald-500/15"
>
<FolderPlus className="h-3.5 w-3.5" />
创建目录
</button>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0 truncate font-mono text-[10px] text-gray-500">
当前目录: {activeLightweightContainerDirectoryPath}
</div>
<div className="flex flex-wrap items-center gap-2">
<input
ref={lightweightUploadInputRef}
type="file"
multiple
className="hidden"
onChange={(event) => event.target.files && uploadLightweightFiles(event.target.files)}
/>
<button
type="button"
onClick={() => lightweightUploadInputRef.current?.click()}
disabled={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"
>
{isLightweightUploading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<UploadCloud className="h-3.5 w-3.5" />
)}
上传文件
</button>
<button
type="button"
onClick={() => refreshLightweightFiles(activeLightweightFilePath)}
disabled={lightweightFilesLoading}
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"
>
{lightweightFilesLoading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5" />
)}
刷新
</button>
</div>
</div>
</div>
)}
<div
className={cn(
"grid min-h-[32rem] gap-4 rounded-lg border border-transparent p-0.5 transition-colors lg:grid-cols-[18rem_minmax(0,1fr)]",
isLightweightDragActive && "border-emerald-500/40 bg-emerald-500/5",
)}
onDragOver={(event) => {
if (hasLightweightPathDrag(event)) {
event.preventDefault();
return;
}
if (Array.from(event.dataTransfer.types).includes("Files")) {
event.preventDefault();
setIsLightweightDragActive(true);
}
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
setIsLightweightDragActive(false);
}
}}
onDrop={(event) => {
if (hasLightweightPathDrag(event)) {
event.preventDefault();
setDraggedLightweightPath("");
setLightweightDropTargetPath(null);
return;
}
event.preventDefault();
setIsLightweightDragActive(false);
uploadLightweightFiles(event.dataTransfer.files);
}}
>
<div className="min-h-0 overflow-hidden rounded-lg border border-[#2a2b2f] bg-[#0a0a0a]">
<div className="flex items-center justify-between border-b border-[#2a2b2f] px-3 py-2">
<div className="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-gray-500">
<FolderOpen className="h-3.5 w-3.5 text-emerald-300" />
文件树
</div>
{lightweightFiles && (
<span className="font-mono text-[10px] text-gray-600">
{lightweightFiles.fileCount} files
</span>
)}
</div>
<div
className={cn(
"h-[29rem] overflow-auto p-2 scrollbar-thin scrollbar-thumb-gray-800",
lightweightDropTargetPath === "" && "ring-1 ring-inset ring-emerald-400/40",
)}
onDragOver={(event) => {
if (!hasLightweightPathDrag(event)) {
return;
}
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "move";
setLightweightDropTargetPath("");
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
setLightweightDropTargetPath(null);
}
}}
onDrop={(event) => {
if (!hasLightweightPathDrag(event)) {
return;
}
event.preventDefault();
event.stopPropagation();
const sourcePath =
event.dataTransfer.getData(lightweightPathDragMime) || draggedLightweightPath;
moveLightweightPathToDirectory(sourcePath, "");
}}
>
{lightweightFilesError ? (
<div className="rounded border border-red-500/20 bg-red-500/10 px-3 py-2 text-[11px] text-red-200">
{lightweightFilesError}
</div>
) : lightweightFilesLoading && !lightweightFiles ? (
<div className="flex items-center gap-2 px-2 py-3 text-xs text-gray-500">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
正在加载目录
</div>
) : lightweightFiles && !lightweightFiles.exists ? (
<div className="px-2 py-3 text-xs leading-5 text-gray-500">
目录尚未创建,保存新文件后会创建。
</div>
) : lightweightVisibleFileItems.length > 0 ? (
<div className="space-y-0.5">
{lightweightVisibleFileItems.map((item) => {
const isDirectory = item.kind === "directory";
const isActive = activeLightweightFilePath === item.path;
const isExpanded = expandedLightweightDirs.has(item.path);
const isDropTarget = lightweightDropTargetPath === item.path;
const isDragged = draggedLightweightPath === item.path;
return (
<button
key={`${item.kind}:${item.path}`}
type="button"
draggable={Boolean(editingOpId) && (item.kind === "file" || isDirectory)}
title={
isDirectory
? "拖动可移动,放到此处可移入目录"
: "拖动可移动,放到此处可移到同级目录"
}
onDragStart={(event) => {
event.stopPropagation();
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(lightweightPathDragMime, item.path);
event.dataTransfer.setData("text/plain", item.path);
setDraggedLightweightPath(item.path);
setLightweightDropTargetPath(null);
}}
onDragEnd={() => {
setDraggedLightweightPath("");
setLightweightDropTargetPath(null);
}}
onDragOver={(event) => {
if (!hasLightweightPathDrag(event)) {
return;
}
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "move";
setLightweightDropTargetPath(item.path);
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
setLightweightDropTargetPath((current) =>
current === item.path ? null : current,
);
}
}}
onDrop={(event) => {
if (!hasLightweightPathDrag(event)) {
return;
}
event.preventDefault();
event.stopPropagation();
const sourcePath =
event.dataTransfer.getData(lightweightPathDragMime) || draggedLightweightPath;
moveLightweightPathToDirectory(
sourcePath,
isDirectory ? item.path : lightweightParentDir(item.path),
);
}}
onClick={() => {
if (isDirectory) {
setActiveLightweightFilePath(item.path);
setActiveLightweightDirectoryPath(item.path);
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("");
setExpandedLightweightDirs((current) => {
const next = new Set(current);
if (next.has(item.path)) {
next.delete(item.path);
} else {
next.add(item.path);
}
return next;
});
return;
}
if (item.kind === "file" && item.editable) {
setActiveLightweightDirectoryPath(lightweightParentDir(item.path));
loadLightweightFileContent(item.path);
return;
}
setActiveLightweightFilePath(item.path);
setActiveLightweightDirectoryPath(lightweightParentDir(item.path));
setLightweightFileDraft("");
setLightweightFileSavedContent("");
setLightweightFileError("该文件不能在文本编辑器中打开");
}}
className={cn(
"flex w-full items-center gap-1.5 rounded px-2 py-1.5 text-left text-xs transition-colors",
isActive
? "bg-emerald-500/10 text-emerald-100"
: "text-gray-400 hover:bg-white/5 hover:text-white",
isDropTarget && "outline outline-1 outline-emerald-400/70",
isDragged && "opacity-50",
)}
style={{ paddingLeft: `${8 + item.depth * 14}px` }}
>
{isDirectory ? (
isExpanded ? (
<ChevronDown className="h-3 w-3 shrink-0 text-gray-500" />
) : (
<ChevronRight className="h-3 w-3 shrink-0 text-gray-500" />
)
) : (
<span className="w-3 shrink-0" />
)}
{isDirectory ? (
<FolderOpen className="h-3.5 w-3.5 shrink-0 text-emerald-300" />
) : (
<FileText className="h-3.5 w-3.5 shrink-0 text-blue-300" />
)}
<span className="min-w-0 flex-1 truncate font-mono">
{isDirectory ? `${item.name}/` : item.name}
</span>
{!isDirectory && (
<span className="shrink-0 font-mono text-[10px] text-gray-600">
{formatFileSize(item.sizeBytes)}
</span>
)}
</button>
);
})}
{lightweightFiles?.truncated && (
<div className="px-2 py-2 text-[10px] text-amber-300">
文件数量超过 {lightweightFiles.maxItems},当前只展示前一部分。
</div>
)}
</div>
) : (
<div className="px-2 py-3 text-xs text-gray-500">目录下没有文件。</div>
)}
</div>
</div>
<div className="min-w-0 overflow-hidden rounded-lg border border-[#2a2b2f] bg-[#0a0a0a]">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#2a2b2f] px-4 py-3">
<div className="min-w-0">
<div className="truncate font-mono text-sm text-white">
{activeLightweightContainerFilePath || "未选择文件"}
</div>
<div className="mt-1 font-mono text-[10px] text-gray-500">
{activeLightweightFileItem
? `${activeLightweightFileItem.mode || ""} · ${formatFileSize(activeLightweightFileItem.sizeBytes)}`
: activeLightweightFilePath
? "new file"
: "idle"}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={moveActiveLightweightPath}
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" />
重命名/移动
</button>
<button
type="button"
onClick={deleteActiveLightweightPath}
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" />
删除
</button>
<button
type="button"
onClick={saveLightweightFile}
disabled={
!activeLightweightFilePath ||
lightweightFiles?.readOnly ||
!activeLightweightPathIsEditableFile ||
lightweightFileLoading ||
lightweightFileSaving ||
(activeLightweightFileExists && !lightweightEditorDirty)
}
className="inline-flex items-center gap-2 rounded-md bg-emerald-600 px-3 py-2 text-xs font-medium text-white transition-colors hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{lightweightFileSaving ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Save className="h-3.5 w-3.5" />
)}
保存文件
</button>
</div>
</div>
{lightweightFileError && (
<div className="border-b border-red-500/20 bg-red-500/10 px-4 py-2 text-xs text-red-200">
{lightweightFileError}
</div>
)}
{lightweightFileLoading ? (
<div className="flex h-[28rem] items-center justify-center gap-2 text-sm text-gray-500">
<Loader2 className="h-4 w-4 animate-spin" />
正在读取文件
</div>
) : activeLightweightPathIsDirectory ? (
<div className="flex h-[28rem] items-center justify-center px-6 text-center text-sm text-gray-500">
<div>
<FolderOpen className="mx-auto mb-3 h-8 w-8 text-emerald-300" />
<div className="font-mono text-xs text-gray-300">{activeLightweightFilePath}</div>
<div className="mt-2 text-xs text-gray-600">目录已选中,上传文件会写入该目录。</div>
</div>
</div>
) : activeLightweightFilePath && activeLightweightPathIsEditableFile ? (
<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}
/>
) : activeLightweightFilePath ? (
<div className="flex h-[28rem] items-center justify-center px-6 text-center text-sm text-gray-500">
<div>
<FileText className="mx-auto mb-3 h-8 w-8 text-blue-300" />
<div className="font-mono text-xs text-gray-300">{activeLightweightFilePath}</div>
<div className="mt-2 text-xs text-gray-600">该文件不能以内联文本方式编辑。</div>
</div>
</div>
) : (
<div className="flex h-[28rem] items-center justify-center text-sm text-gray-600">
从左侧选择文件
</div>
)}
</div>
</div>
</>
)}
</div>
)}
{activeTab === "implementation" && generatedImplementation && newOp.type !== "lightweight" && (
<div className="space-y-6">
<div className="rounded-lg border border-blue-500/20 bg-blue-500/5 p-4">
<div className="flex items-center gap-2 text-sm font-semibold text-white">
<Code className="h-4 w-4 text-blue-400" />
外部算子实现包
</div>
<p className="mt-2 text-xs leading-6 text-gray-400">
这些文件是 AI 生成的独立算子目录草案。它们不会自动创建线上镜像;需要将文件落地到独立 repo,
补齐真实业务逻辑后构建并推送到 CCR,再用 digest 注册和验收。
</p>
<div className="mt-3 rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 font-mono text-xs text-blue-300">
{generatedImplementation.repositoryPath}
</div>
{(generatedImplementation.repositoryName || generatedImplementation.repositoryURL) && (
<div className="mt-2 grid gap-2 md:grid-cols-2">
{generatedImplementation.repositoryName && (
<div className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2">
<p className="text-[10px] uppercase tracking-wider text-gray-500">Repo</p>
<p className="mt-1 truncate font-mono text-xs text-gray-200">
{generatedImplementation.repositoryName}
</p>
</div>
)}
{generatedImplementation.repositoryURL && (
<div className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2">
<p className="text-[10px] uppercase tracking-wider text-gray-500">Gitea URL</p>
<p className="mt-1 truncate font-mono text-xs text-gray-200">
{generatedImplementation.repositoryURL}
</p>
</div>
)}
</div>
)}
</div>
<div className="grid gap-4 lg:grid-cols-[16rem_minmax(0,1fr)]">
<div className="space-y-2">
<div className="text-[10px] font-bold uppercase tracking-widest text-gray-500">文件列表</div>
<div className="space-y-2">
{generatedImplementation.files.map((file) => (
<button
key={file.path}
type="button"
onClick={() => setActiveImplementationFile(file.path)}
className={cn(
"w-full rounded-md border px-3 py-2 text-left transition-colors",
activeImplementationFile === file.path
? "border-blue-500 bg-blue-500/10 text-blue-200"
: "border-[#2a2b2f] bg-[#0a0a0a] text-gray-400 hover:text-white",
)}
>
<div className="truncate font-mono text-xs">{file.path}</div>
<div className="mt-1 line-clamp-2 text-[10px] leading-4 text-gray-500">
{file.description}
</div>
</button>
))}
</div>
</div>
<div className="min-w-0 space-y-3">
{generatedImplementation.files
.filter((file) => file.path === activeImplementationFile)
.map((file) => (
<div
key={file.path}
className="min-w-0 overflow-hidden rounded-lg border border-[#2a2b2f] bg-[#0a0a0a]"
>
<div className="border-b border-[#2a2b2f] px-4 py-3">
<div className="truncate font-mono text-sm text-white">{file.path}</div>
<div className="mt-1 text-xs text-gray-500">{file.description}</div>
</div>
<pre className="max-h-[28rem] overflow-auto p-4 text-[11px] leading-5 text-gray-300">
<code>{file.content}</code>
</pre>
</div>
))}
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className="rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] p-4">
<div className="text-[10px] font-bold uppercase tracking-widest text-gray-500">
构建与推送命令
</div>
<pre className="mt-3 overflow-auto rounded-md bg-[#151619] p-3 text-[11px] leading-5 text-gray-300">
<code>{generatedImplementation.buildCommands.join("\n")}</code>
</pre>
</div>
<div className="rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] p-4">
<div className="text-[10px] font-bold uppercase tracking-widest text-gray-500">验收检查</div>
<ul className="mt-3 space-y-2 text-xs leading-5 text-gray-400">
{generatedImplementation.acceptanceChecklist.map((item) => (
<li key={item} className="flex gap-2">
<span className="mt-1 h-1.5 w-1.5 shrink-0 rounded-full bg-blue-400" />
<span>{item}</span>
</li>
))}
</ul>
</div>
</div>
</div>
)}
</div>
<div className="p-6 border-t border-[#2a2b2f] flex justify-end gap-3">
<button
type="button"
onClick={closeOperatorModal}
className="px-4 py-2 text-sm font-medium text-gray-400 hover:text-white transition-colors"
disabled={isSavingOperator}
>
取消
</button>
<button
type="button"
onClick={handleRegister}
disabled={!canSaveOperator || isSavingOperator}
className={cn(
"px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium transition-colors flex items-center gap-2",
(!canSaveOperator || isSavingOperator) && "opacity-50 cursor-not-allowed",
)}
>
{isSavingOperator && <Loader2 className="h-4 w-4 animate-spin" />}
{editingOpId ? "保存修改" : imageSourceMode === "archive" ? "导入并注册" : "确认注册"}
</button>
</div>
</div>
</div>
)}
{/* AI Generate Modal */}
{isAIModalOpen && (
<div className="fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
<div className="bg-[#151619] border border-[#2a2b2f] rounded-2xl w-full max-w-lg shadow-2xl overflow-hidden">
<div className="px-6 py-4 border-b border-[#2a2b2f] flex items-center justify-between bg-gradient-to-r from-blue-600/10 to-purple-600/10">
<div className="flex items-center gap-2">
<Sparkles className="w-5 h-5 text-blue-500" />
<h2 className="text-xl font-bold text-white">AI 辅助注册算子</h2>
</div>
<button
onClick={() => setIsAIModalOpen(false)}
className="text-gray-500 hover:text-white transition-colors"
>
<X className="w-6 h-6" />
</button>
</div>
<div className="p-6 space-y-6">
<div className="space-y-3">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider">描述您的算子</label>
<textarea
placeholder="例如:帮我注册一个算子,用于对输入的视频进行锐化处理。它应该接受一个视频输入,输出一个处理后的视频。它属于 CV 类别。"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-xl px-4 py-3 text-sm h-40 focus:outline-none focus:border-blue-500 transition-all resize-none leading-relaxed"
value={aiDescription}
onChange={(e) => setAiDescription(e.target.value)}
disabled={isGenerating}
/>
<p className="text-[10px] text-gray-500 italic">
提示:AI 会自动为您生成算子名称、描述、端口定义(包含传输协议)以及详细的 Skill 自述文件。
</p>
</div>
{aiError && (
<div className="p-3 bg-red-500/10 border border-red-500/20 rounded-lg flex items-center gap-3 text-red-500 text-xs">
<AlertCircle className="w-4 h-4 shrink-0" />
{aiError}
</div>
)}
{!operatorGenerationReady && (
<div className="p-3 bg-yellow-500/10 border border-yellow-500/20 rounded-lg flex items-center gap-3 text-yellow-300 text-xs">
<AlertCircle className="w-4 h-4 shrink-0" />
<span>
{operatorGenerationReason}
{operatorGenerationMissingFields.length > 0 ? (
<span className="mt-1 block text-yellow-100/80">
缺少:{operatorGenerationMissingFields.join("、")}
</span>
) : null}
</span>
</div>
)}
{operatorGenerationReady && (
<div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg flex items-center gap-3 text-blue-200 text-xs">
<Sparkles className="w-4 h-4 shrink-0" />
当前由服务端模型 `{aiStatus.model}` 生成算子定义,API Key 不会暴露到浏览器。
</div>
)}
</div>
<div className="p-6 border-t border-[#2a2b2f] flex justify-end gap-3 bg-[#0a0a0a]/50">
<button
onClick={() => setIsAIModalOpen(false)}
className="px-4 py-2 text-sm font-medium text-gray-400 hover:text-white transition-colors"
disabled={isGenerating}
>
取消
</button>
<button
onClick={handleAIGenerate}
disabled={!operatorGenerationReady || !aiDescription.trim() || isGenerating}
className={cn(
"px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium transition-all flex items-center gap-2",
(!operatorGenerationReady || !aiDescription.trim() || isGenerating) &&
"opacity-50 cursor-not-allowed",
)}
>
{isGenerating ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
正在生成中...
</>
) : (
<>
<Sparkles className="w-4 h-4" />
开始生成
</>
)}
</button>
</div>
</div>
</div>
)}
</div>
);
}