diff --git a/.gitignore b/.gitignore index 5a86d2a8..b4093fa2 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ node_modules/ build/ dist/ coverage/ +tmp/ .DS_Store *.log .env* diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..53bd88af --- /dev/null +++ b/.prettierignore @@ -0,0 +1,7 @@ +build/ +coverage/ +dist/ +node_modules/ +tmp/ +docs/ +backend/operator-runner/ diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..caa6777f --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "printWidth": 120, + "semi": true, + "singleQuote": false, + "trailingComma": "all" +} diff --git a/README.md b/README.md index 709b8fe4..a839ecf3 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ Drobodata is a workflow orchestration platform for embodied AI and vision pipeli ### Useful Scripts - `npm run lint`: type-check frontend and verify Go formatting +- `npm run format`: format frontend source and frontend tests with Prettier +- `npm run format:check`: check frontend formatting without writing files - `npm test`: Go unit and integration tests - `npm run build`: build frontend assets and Go binaries - `npm run verify`: lint, Go tests, Python operator-runner tests, frontend node tests, build, dependency audit, and Kubernetes manifest dry-run validation diff --git a/cmd/api/main.go b/cmd/api/main.go index 68fe2ef1..2a18ad79 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -69,6 +69,10 @@ func main() { }() dataStore := store.NewMongoStore(client.Database(cfg.MongoDB)) + if err := dataStore.EnsureIndexes(ctx); err != nil { + fmt.Printf("[api] failed to ensure mongo indexes: %v\n", err) + os.Exit(1) + } aiService := ai.NewService(cfg.AIAPIBaseURL, cfg.AIAPIKey, cfg.AIModel) handler := spaHandler(api.NewHandler(dataStore, aiService), cfg.DistDir) diff --git a/cmd/worker/main.go b/cmd/worker/main.go index a79b72c0..3d810822 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -44,6 +44,10 @@ func main() { }() dataStore := store.NewMongoStore(client.Database(cfg.MongoDB)) + if err := dataStore.EnsureIndexes(ctx); err != nil { + fmt.Printf("[worker] failed to ensure mongo indexes: %v\n", err) + os.Exit(1) + } runtime, err := worker.NewRuntime( dataStore, cfg.K8sNamespace, diff --git a/docs/operations.md b/docs/operations.md index f45007e7..29247028 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -41,6 +41,8 @@ - `users` - `settings` +API and worker startup both call `EnsureIndexes` on the platform MongoDB. Index creation is idempotent and covers the main lookup and dispatch paths such as run status queues, workflow/project run history, source-state checkpoints, audit queues, and singleton/settings lookups. + ## Run Lifecycle 1. frontend calls `POST /api/workflows/:id/run` @@ -60,7 +62,7 @@ Run the full verification loop: npm run verify ``` -This includes TypeScript/Go linting, Go tests, Python operator-runner tests, frontend node tests, production build, `npm audit --audit-level=moderate`, and Kubernetes manifest dry-run validation. +This includes TypeScript/Go linting, frontend Prettier formatting checks, Go tests, Python operator-runner tests, frontend node tests, production build, `npm audit --audit-level=moderate`, and Kubernetes manifest dry-run validation. ## Runtime Metrics diff --git a/internal/store/mongo_indexes.go b/internal/store/mongo_indexes.go new file mode 100644 index 00000000..f1281224 --- /dev/null +++ b/internal/store/mongo_indexes.go @@ -0,0 +1,97 @@ +package store + +import ( + "context" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +func uniqueIndex(name string, keys bson.D) mongo.IndexModel { + return mongo.IndexModel{ + Keys: keys, + Options: options.Index().SetName(name).SetUnique(true), + } +} + +func index(name string, keys bson.D) mongo.IndexModel { + return mongo.IndexModel{ + Keys: keys, + Options: options.Index().SetName(name), + } +} + +func ensureCollectionIndexes(ctx context.Context, collection *mongo.Collection, models []mongo.IndexModel) error { + if len(models) == 0 { + return nil + } + _, err := collection.Indexes().CreateMany(ctx, models) + return err +} + +func (store *MongoStore) EnsureIndexes(ctx context.Context) error { + indexesByCollection := map[*mongo.Collection][]mongo.IndexModel{ + store.projects: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("status_createdAt", bson.D{{Key: "status", Value: 1}, {Key: "createdAt", Value: -1}}), + }, + store.operators: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("category_name", bson.D{{Key: "category", Value: 1}, {Key: "name", Value: 1}}), + }, + store.builtinOperatorDeletions: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + }, + store.workflows: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("projectId_createdAt", bson.D{{Key: "projectId", Value: 1}, {Key: "createdAt", Value: -1}}), + index("type_status_lastRunAt", bson.D{{Key: "type", Value: 1}, {Key: "status", Value: 1}, {Key: "lastRunAt", Value: -1}}), + }, + store.templates: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("createdAt", bson.D{{Key: "createdAt", Value: -1}}), + }, + store.runs: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("status_availableAt_createdAt", bson.D{{Key: "status", Value: 1}, {Key: "availableAt", Value: 1}, {Key: "createdAt", Value: -1}}), + index("workflowId_createdAt", bson.D{{Key: "workflowId", Value: 1}, {Key: "createdAt", Value: -1}}), + index("projectId_createdAt", bson.D{{Key: "projectId", Value: 1}, {Key: "createdAt", Value: -1}}), + }, + store.sourceStates: { + uniqueIndex("workflow_node_fingerprint_unique", bson.D{{Key: "workflowId", Value: 1}, {Key: "nodeId", Value: 1}, {Key: "sourceFingerprint", Value: 1}}), + index("workflowId_nodeId", bson.D{{Key: "workflowId", Value: 1}, {Key: "nodeId", Value: 1}}), + }, + store.auditTasks: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("status_createdAt", bson.D{{Key: "status", Value: 1}, {Key: "createdAt", Value: -1}}), + index("runId_nodeId", bson.D{{Key: "runId", Value: 1}, {Key: "nodeId", Value: 1}}), + index("workflowId_createdAt", bson.D{{Key: "workflowId", Value: 1}, {Key: "createdAt", Value: -1}}), + }, + store.samplingTasks: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("status_createdAt", bson.D{{Key: "status", Value: 1}, {Key: "createdAt", Value: -1}}), + index("workflowId_createdAt", bson.D{{Key: "workflowId", Value: 1}, {Key: "createdAt", Value: -1}}), + }, + store.users: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + }, + store.storageConnections: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("name", bson.D{{Key: "name", Value: 1}}), + }, + store.mongoConnections: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + index("name", bson.D{{Key: "name", Value: 1}}), + }, + store.settings: { + uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), + }, + } + for collection, models := range indexesByCollection { + if err := ensureCollectionIndexes(ctx, collection, models); err != nil { + return err + } + } + return nil +} diff --git a/package-lock.json b/package-lock.json index b13c21a7..e45cfdd8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "autoprefixer": "^10.4.21", "concurrently": "^10.0.3", "playwright": "^1.59.1", + "prettier": "^3.8.4", "tailwindcss": "^4.1.14", "typescript": "~5.8.2", "vite": "^8.0.16" @@ -2531,6 +2532,22 @@ "dev": true, "license": "MIT" }, + "node_modules/prettier": { + "version": "3.8.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.4.tgz", + "integrity": "sha512-N2MylSdi48+5N/6S5j+maeHbUSIzzZ5uOcX5Hm4QpV8Dkb1HFjfAKTKX6yNPJQD9AhcT3ifHNB66tWTTJDi11Q==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/react": { "version": "19.2.4", "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", diff --git a/package.json b/package.json index 6b2830fe..630ff931 100644 --- a/package.json +++ b/package.json @@ -21,11 +21,13 @@ "lint": "npm run lint:web && npm run lint:go", "lint:web": "tsc --noEmit", "lint:go": "bash -lc 'test -z \"$(gofmt -l cmd internal)\"'", + "format": "prettier --write \"src/**/*.{ts,tsx,css}\" \"tests/frontend/**/*.mjs\"", + "format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"tests/frontend/**/*.mjs\"", "test": "go test ./...", "test:python": "python3 -m pytest backend/operator-runner tests/backend", "test:frontend": "node --test tests/frontend/*.test.mjs", "audit:moderate": "npm audit --audit-level=moderate", - "verify": "npm run lint && npm test && npm run test:python && npm run test:frontend && npm run build && npm run audit:moderate && npm run k8s:validate", + "verify": "npm run lint && npm run format:check && npm test && npm run test:python && npm run test:frontend && npm run build && npm run audit:moderate && npm run k8s:validate", "docker:build:api": "docker build -f Dockerfile.api -t droboticflow-api:local .", "docker:build:worker": "docker build -f Dockerfile.worker -t droboticflow-worker:local .", "docker:build:operator-runner": "docker build -f Dockerfile.operator-runner -t droboticflow-operator-runner:local .", @@ -56,6 +58,7 @@ "autoprefixer": "^10.4.21", "concurrently": "^10.0.3", "playwright": "^1.59.1", + "prettier": "^3.8.4", "tailwindcss": "^4.1.14", "typescript": "~5.8.2", "vite": "^8.0.16" diff --git a/src/App.tsx b/src/App.tsx index 530cbc7b..9b9c89f0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -22,17 +22,11 @@ const Audit = lazy(() => import("./pages/Audit")); const DataAssets = lazy(() => import("./pages/DataAssets")); const DatabaseBrowser = lazy(() => import("./pages/DatabaseBrowser")); const ObjectStorageBrowser = lazy(() => import("./pages/ObjectStorageBrowser")); -const LegacyDataAssetsRedirect = lazy( - () => import("./pages/LegacyDataAssetsRedirect"), -); +const LegacyDataAssetsRedirect = lazy(() => import("./pages/LegacyDataAssetsRedirect")); const Sampling = lazy(() => import("./pages/Sampling")); function RouteFallback() { - return ( -
@@ -100,19 +103,20 @@ export default function AIGenerateModal({ isOpen, onClose, onGenerate }: AIGener
diff --git a/src/components/Logo.tsx b/src/components/Logo.tsx index 1ab4282f..624fdedc 100644 --- a/src/components/Logo.tsx +++ b/src/components/Logo.tsx @@ -16,46 +16,44 @@ export function Logo({ className, size = "md", showText = false }: LogoProps) { return ( - + {/* Stylized "D" + Robot + Flow */} - + {/* The "D" shape / Robot Head */} - - + + {/* Antenna */} - + {/* Robot Eyes */} - + {/* Flow Lines inside D */} - + {/* External Flow Nodes */} - + {/* Subtle Glow Effect */} - + {showText && ( Drobodata - Embodied Data Workflows + + Embodied Data Workflows + )} diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx index 3e23ffe8..ffcb8efe 100644 --- a/src/components/Sidebar.tsx +++ b/src/components/Sidebar.tsx @@ -51,16 +51,7 @@ export function Sidebar({ isCollapsed, onToggle }: SidebarProps) { const [isProfileModalOpen, setIsProfileModalOpen] = useState(false); const [profileDraft, setProfileDraft] = useState(null); const [isSavingProfile, setIsSavingProfile] = useState(false); - const { - currentUser, - users, - role, - name, - email, - selectUser, - updateCurrentUser, - logout, - } = useUser(); + const { currentUser, users, role, name, email, selectUser, updateCurrentUser, logout } = useUser(); useEffect(() => { if (!isProfileModalOpen || !currentUser) { @@ -171,7 +162,10 @@ export function Sidebar({ isCollapsed, onToggle }: SidebarProps) { 当前用户 - setIsProfileModalOpen(false)} className="text-gray-500 hover:text-white transition-colors"> + setIsProfileModalOpen(false)} + className="text-gray-500 hover:text-white transition-colors" + > @@ -211,7 +205,11 @@ export function Sidebar({ isCollapsed, onToggle }: SidebarProps) { type="text" className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500 text-white" value={profileDraft.name} - onChange={(event) => setProfileDraft((previous) => (previous ? { ...previous, name: event.target.value } : previous))} + onChange={(event) => + setProfileDraft((previous) => + previous ? { ...previous, name: event.target.value } : previous, + ) + } />
- 处理工作流中需要人工介入的审核请求。 -
处理工作流中需要人工介入的审核请求。
- {" "} - {formatCompactDateTime(task.createdAt, timeZone)} + {formatCompactDateTime(task.createdAt, timeZone)}
- {selectedTask.data.reason} -
{selectedTask.data.reason}
- 点击左侧列表中的待审核任务,查看详细数据并进行人工确认。 -
点击左侧列表中的待审核任务,查看详细数据并进行人工确认。
- {currentUser ? `欢迎回来,${currentUser.name}。这里是当前平台的真实执行概览。` : "这里是当前平台的真实执行概览。"} + {currentUser + ? `欢迎回来,${currentUser.name}。这里是当前平台的真实执行概览。` + : "这里是当前平台的真实执行概览。"}
用一个入口查看源数据和成品数据,并按项目、工作流、运行记录回溯真实资产链路。
- {JSON.stringify(collectionDetail.collection.meta, null, 2)} -
+ {JSON.stringify(collectionDetail.collection.meta, null, 2)} +
- {JSON.stringify( - packageDetail.package.annotation || {}, - null, - 2, - )} + {JSON.stringify(packageDetail.package.annotation || {}, null, 2)}
- 管理用户自定义的业务 MongoDB 连接,并维护其集合、索引和记录。 -
管理用户自定义的业务 MongoDB 连接,并维护其集合、索引和记录。
- X-API-Key -
X-API-Key
{JSON.stringify(jsonValue ?? {}, null, 2)} @@ -494,9 +450,7 @@ export default function Monitoring() { {loading ? ( - - 正在获取实时数据... - + 正在获取实时数据... ) : ( <> @@ -521,12 +475,8 @@ export default function Monitoring() { > {log.level} - - [{log.operator}] - - - {log.message} - + [{log.operator}] + {log.message} ))} @@ -552,18 +502,9 @@ export default function Monitoring() { color: "text-purple-500", }, ].map((stat) => ( - - - {stat.label} - - - {stat.value} - + + {stat.label} + {stat.value} ))} @@ -572,46 +513,21 @@ export default function Monitoring() { - - - + + + - + - formatClockTime(String(value), timeZone) - } - /> - formatClockTime(String(value), timeZone)} /> + - formatDateTime(String(value), timeZone) - } + labelFormatter={(value) => formatDateTime(String(value), timeZone)} /> - - 文件列表 - + 文件列表 {modalData.data?.map((item) => ( - - {item.name} - + {item.name} {item.size} • {artifactSecondaryLabel(item)} @@ -700,11 +610,7 @@ export default function Monitoring() { { e.stopPropagation(); - window.open( - item.path, - "_blank", - "noopener,noreferrer", - ); + window.open(item.path, "_blank", "noopener,noreferrer"); }} className="p-2 hover:bg-white/5 rounded-lg text-gray-400 hover:text-white transition-colors" title="打开真实资源" @@ -718,52 +624,38 @@ export default function Monitoring() { - - 预览面板 - + 预览面板 {selectedArtifact ? ( {renderArtifactPreview(selectedArtifact)} - - {selectedArtifact.name} - + {selectedArtifact.name} {selectedArtifact.path} - - 类型 - + 类型 {artifactKindLabel(selectedArtifact)} - - 文件大小 - - - {selectedArtifact.size} - + 文件大小 + {selectedArtifact.size} - - MIME - + MIME {selectedArtifact.metadata?.mimeType || "--"} - - SHA256 - + SHA256 {selectedArtifact.metadata?.sha256?.slice(0, 16) || "--"} @@ -771,13 +663,7 @@ export default function Monitoring() { {hasDirectArtifactURL(selectedArtifact) ? ( - window.open( - selectedArtifact.path, - "_blank", - "noopener,noreferrer", - ) - } + onClick={() => window.open(selectedArtifact.path, "_blank", "noopener,noreferrer")} className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-sm font-bold transition-all flex items-center justify-center gap-2" > @@ -785,9 +671,7 @@ export default function Monitoring() { ) : ( - copyToClipboard(selectedArtifact.path) - } + onClick={() => copyToClipboard(selectedArtifact.path)} className="w-full py-3 bg-white/5 hover:bg-white/10 text-white rounded-xl text-sm font-bold transition-all flex items-center justify-center gap-2 border border-[#2a2b2f]" > @@ -801,9 +685,7 @@ export default function Monitoring() { - - 未选择预览内容 - + 未选择预览内容 点击左侧任一产物,即可查看对应的结构化预览、媒体预览或真实元数据。 @@ -830,12 +712,8 @@ export default function Monitoring() { )} - - 执行监控 - - - 实时查看 K8s Job 运行状态与算子执行日志 - + 执行监控 + 实时查看 K8s Job 运行状态与算子执行日志 @@ -863,24 +741,15 @@ export default function Monitoring() { value: formatDuration( runs .filter((run) => typeof run.durationMs === "number") - .reduce( - (sum, run, _, all) => - sum + (run.durationMs || 0) / Math.max(all.length, 1), - 0, - ), + .reduce((sum, run, _, all) => sum + (run.durationMs || 0) / Math.max(all.length, 1), 0), ), icon: Clock, color: "text-purple-500", }, ].map((stat) => ( - + - - {stat.label} - + {stat.label} {stat.value} @@ -918,9 +787,7 @@ export default function Monitoring() { - - 执行历史 ({filteredExecutions.length}) - + 执行历史 ({filteredExecutions.length}) { @@ -954,16 +821,10 @@ export default function Monitoring() { } className="hover:bg-white/5 transition-colors group cursor-pointer" > - - {run.id} - + {run.id} - - {run.workflowName} - - - {run.projectName} - + {run.workflowName} + {run.projectName} {(run.status === "running" || run.status === "stopping") && ( @@ -987,14 +848,9 @@ export default function Monitoring() { - {formatCompactDateTime( - run.startedAt || run.createdAt, - timeZone, - )} - - - {formatDuration(run.durationMs)} + {formatCompactDateTime(run.startedAt || run.createdAt, timeZone)} + {formatDuration(run.durationMs)} )} - {(run.status === "running" || run.status === "stopping" || run.status === "waiting_for_audit") && ( + {(run.status === "running" || + run.status === "stopping" || + run.status === "waiting_for_audit") && ( - + 没有找到匹配的执行记录 diff --git a/src/pages/ObjectStorageBrowser.tsx b/src/pages/ObjectStorageBrowser.tsx index ed3720d4..52846585 100644 --- a/src/pages/ObjectStorageBrowser.tsx +++ b/src/pages/ObjectStorageBrowser.tsx @@ -20,19 +20,12 @@ import { } from "lucide-react"; import { useTimeZone } from "../context/TimeZoneContext"; import { formatCompactDateTime } from "../lib/datetime"; -import { - isObjectStorageEditorLocked, - shouldSyncObjectStoragePreviewToEditor, -} from "../lib/object-storage-preview.js"; +import { isObjectStorageEditorLocked, shouldSyncObjectStoragePreviewToEditor } from "../lib/object-storage-preview.js"; import { buildBrowserPlayableVideoURL } from "../lib/video-preview.js"; import { cn } from "../lib/utils"; import { objectStorageApi } from "../services/api/object-storage"; import { storageConnectionsApi } from "../services/api/storage-connections"; -import type { - ObjectStorageObjectSummary, - ObjectStorageOverview, - StorageConnection, -} from "../types"; +import type { ObjectStorageObjectSummary, ObjectStorageOverview, StorageConnection } from "../types"; const formatBytes = (value?: number) => { if (!value) return "-"; @@ -201,9 +194,7 @@ export default function ObjectStorageBrowser() { : ""; const playablePreviewURL = - previewKind(selectedItem) === "video" - ? buildBrowserPlayableVideoURL(previewURL) - : previewURL; + previewKind(selectedItem) === "video" ? buildBrowserPlayableVideoURL(previewURL) : previewURL; const filteredItems = useMemo(() => { const keyword = objectSearch.trim().toLowerCase(); @@ -212,9 +203,7 @@ export default function ObjectStorageBrowser() { return sorted; } return sorted.filter((item) => { - const haystack = [item.name, item.key, item.contentType || "", item.kind] - .join(" ") - .toLowerCase(); + const haystack = [item.name, item.key, item.contentType || "", item.kind].join(" ").toLowerCase(); return haystack.includes(keyword); }); }, [items, objectSearch]); @@ -238,10 +227,7 @@ export default function ObjectStorageBrowser() { const items = await storageConnectionsApi.list(); setConnections(items); setSelectedConnectionId((current) => { - if ( - preferredConnectionId && - items.some((item) => item.id === preferredConnectionId) - ) { + if (preferredConnectionId && items.some((item) => item.id === preferredConnectionId)) { return preferredConnectionId; } if (current && items.some((item) => item.id === current)) { @@ -253,9 +239,7 @@ export default function ObjectStorageBrowser() { console.error("Failed to load storage connections", error); setConnections([]); setSelectedConnectionId(""); - setConnectionsError( - error instanceof Error ? error.message : "加载对象存储连接失败", - ); + setConnectionsError(error instanceof Error ? error.message : "加载对象存储连接失败"); } finally { setConnectionsLoading(false); } @@ -285,8 +269,7 @@ export default function ObjectStorageBrowser() { setOverview(result); setSelectedBucket((current) => { const resolvedBucket = result.bucket || result.buckets[0]?.name || ""; - const nextPreferred = - preferredBucket && preferredBucket === resolvedBucket ? preferredBucket : ""; + const nextPreferred = preferredBucket && preferredBucket === resolvedBucket ? preferredBucket : ""; if (nextPreferred) return nextPreferred; if (current && current === resolvedBucket) { return current; @@ -301,9 +284,7 @@ export default function ObjectStorageBrowser() { console.error("Failed to load object storage overview", error); setOverview(null); setSelectedBucket(""); - setOverviewError( - error instanceof Error ? error.message : "加载对象存储概览失败", - ); + setOverviewError(error instanceof Error ? error.message : "加载对象存储概览失败"); return null; } finally { if (overviewRequestIdRef.current === requestId) { @@ -363,9 +344,7 @@ export default function ObjectStorageBrowser() { console.error("Failed to load object storage items", error); setItems([]); setSelectedItem(null); - setObjectsError( - error instanceof Error ? error.message : "加载对象列表失败", - ); + setObjectsError(error instanceof Error ? error.message : "加载对象列表失败"); return null; } finally { if (objectsRequestIdRef.current === requestId) { @@ -426,9 +405,7 @@ export default function ObjectStorageBrowser() { setPreviewReturnedSizeBytes(undefined); if (!isNewObjectMode) { setObjectDraftKey(selectedItem.key); - setObjectContentType( - selectedItem.contentType || guessContentType(selectedItem.key), - ); + setObjectContentType(selectedItem.contentType || guessContentType(selectedItem.key)); } return; } @@ -445,9 +422,7 @@ export default function ObjectStorageBrowser() { if (cancelled) return; setPreviewText(result.content); setPreviewTruncated(result.truncated); - setPreviewOriginalSizeBytes( - result.originalSizeBytes || selectedItem.sizeBytes, - ); + setPreviewOriginalSizeBytes(result.originalSizeBytes || selectedItem.sizeBytes); setPreviewReturnedSizeBytes(result.returnedSizeBytes); if ( !isNewObjectMode && @@ -458,24 +433,18 @@ export default function ObjectStorageBrowser() { ) { setObjectDraftKey(selectedItem.key); setObjectEditorText(result.content); - setObjectContentType( - selectedItem.contentType || guessContentType(selectedItem.key), - ); + setObjectContentType(selectedItem.contentType || guessContentType(selectedItem.key)); } else if (!isNewObjectMode) { setObjectDraftKey(selectedItem.key); setObjectEditorText(""); - setObjectContentType( - selectedItem.contentType || guessContentType(selectedItem.key), - ); + setObjectContentType(selectedItem.contentType || guessContentType(selectedItem.key)); } }) .catch((error) => { if (cancelled) return; console.error("Failed to read object content", error); setPreviewText(""); - setPreviewError( - error instanceof Error ? error.message : "读取对象内容失败", - ); + setPreviewError(error instanceof Error ? error.message : "读取对象内容失败"); setPreviewTruncated(false); setPreviewOriginalSizeBytes(undefined); setPreviewReturnedSizeBytes(undefined); @@ -510,14 +479,14 @@ export default function ObjectStorageBrowser() { return; } setConnectionFormMode("edit"); - setConnectionDraft({ - name: selectedConnection.name || "", - description: selectedConnection.description || "", - endpoint: selectedConnection.endpoint || "", - bucket: selectedConnection.bucket || "", - accessKeyId: "", - secretAccessKey: "", - }); + setConnectionDraft({ + name: selectedConnection.name || "", + description: selectedConnection.description || "", + endpoint: selectedConnection.endpoint || "", + bucket: selectedConnection.bucket || "", + accessKeyId: "", + secretAccessKey: "", + }); setConnectionActionMessage(""); setConnectionActionError(""); setIsConnectionFormOpen(true); @@ -563,14 +532,10 @@ export default function ObjectStorageBrowser() { } setIsConnectionFormOpen(false); setConnectionDraft(EMPTY_CONNECTION_DRAFT); - setConnectionActionMessage( - connectionFormMode === "create" ? "连接已创建。" : "连接已更新。", - ); + setConnectionActionMessage(connectionFormMode === "create" ? "连接已创建。" : "连接已更新。"); } catch (error) { console.error("Failed to save storage connection", error); - setConnectionActionError( - error instanceof Error ? error.message : "保存对象存储连接失败", - ); + setConnectionActionError(error instanceof Error ? error.message : "保存对象存储连接失败"); } finally { setConnectionActionLoading(false); } @@ -598,9 +563,7 @@ export default function ObjectStorageBrowser() { setConnectionActionMessage("连接已删除。"); } catch (error) { console.error("Failed to delete storage connection", error); - setConnectionActionError( - error instanceof Error ? error.message : "删除对象存储连接失败", - ); + setConnectionActionError(error instanceof Error ? error.message : "删除对象存储连接失败"); } finally { setConnectionActionLoading(false); } @@ -648,9 +611,7 @@ export default function ObjectStorageBrowser() { setSelectedItem(result.object); } catch (error) { console.error("Failed to save object", error); - setObjectActionError( - error instanceof Error ? error.message : "保存对象失败", - ); + setObjectActionError(error instanceof Error ? error.message : "保存对象失败"); } finally { setObjectActionLoading(false); } @@ -681,9 +642,7 @@ export default function ObjectStorageBrowser() { setSelectedItem(result.object); } catch (error) { console.error("Failed to rename object", error); - setObjectActionError( - error instanceof Error ? error.message : "重命名对象失败", - ); + setObjectActionError(error instanceof Error ? error.message : "重命名对象失败"); } finally { setObjectActionLoading(false); } @@ -716,9 +675,7 @@ export default function ObjectStorageBrowser() { await reloadObjects(); } catch (error) { console.error("Failed to delete object", error); - setObjectActionError( - error instanceof Error ? error.message : isDirectory ? "删除目录失败" : "删除对象失败", - ); + setObjectActionError(error instanceof Error ? error.message : isDirectory ? "删除目录失败" : "删除对象失败"); } finally { setObjectActionLoading(false); } @@ -753,9 +710,7 @@ export default function ObjectStorageBrowser() { setSelectedItem(result.object); } catch (error) { console.error("Failed to upload object", error); - setObjectActionError( - error instanceof Error ? error.message : "上传对象失败", - ); + setObjectActionError(error instanceof Error ? error.message : "上传对象失败"); } finally { setObjectActionLoading(false); } @@ -781,9 +736,7 @@ export default function ObjectStorageBrowser() { return ( 当前选中目录 ` {selectedItem.key} ` - - 双击或点击列表中的目录即可进入下一级前缀。 - + 双击或点击列表中的目录即可进入下一级前缀。 ); } @@ -791,11 +744,7 @@ export default function ObjectStorageBrowser() { if (kind === "image" && previewURL) { return ( - + ); } @@ -877,9 +826,7 @@ export default function ObjectStorageBrowser() { 对象存储 - - 管理真实 OSS/BOS 连接、绑定 bucket、对象目录,并直接在页面内预览与操作。 - + 管理真实 OSS/BOS 连接、绑定 bucket、对象目录,并直接在页面内预览与操作。 @@ -965,9 +912,7 @@ export default function ObjectStorageBrowser() { 连接名称 - setConnectionDraft((previous) => ({ ...previous, name: event.target.value })) - } + onChange={(event) => setConnectionDraft((previous) => ({ ...previous, name: event.target.value }))} className="w-full rounded-xl border border-[#2a2b2f] bg-[#0b0c10] px-4 py-3 text-sm text-white focus:border-blue-500 focus:outline-none" placeholder="例如:BOS 测试环境" /> @@ -976,9 +921,7 @@ export default function ObjectStorageBrowser() { Endpoint - setConnectionDraft((previous) => ({ ...previous, endpoint: event.target.value })) - } + onChange={(event) => setConnectionDraft((previous) => ({ ...previous, endpoint: event.target.value }))} className="w-full rounded-xl border border-[#2a2b2f] bg-[#0b0c10] px-4 py-3 text-sm text-white focus:border-blue-500 focus:outline-none" placeholder="留空则使用 BOS 默认 endpoint" /> @@ -988,9 +931,7 @@ export default function ObjectStorageBrowser() { - setConnectionDraft((previous) => ({ ...previous, bucket: event.target.value })) - } + onChange={(event) => setConnectionDraft((previous) => ({ ...previous, bucket: event.target.value }))} className="w-full rounded-xl border border-[#2a2b2f] bg-[#0b0c10] px-4 py-3 text-sm text-white focus:border-blue-500 focus:outline-none" placeholder="例如:datastorage" /> @@ -1063,11 +1004,7 @@ export default function ObjectStorageBrowser() { disabled={connectionActionLoading} className="inline-flex items-center gap-2 rounded-xl bg-blue-600 px-4 py-3 text-sm font-medium text-white hover:bg-blue-500 disabled:opacity-60" > - {connectionActionLoading ? ( - - ) : ( - - )} + {connectionActionLoading ? : } {connectionFormMode === "create" ? "创建连接" : "保存连接"} @@ -1115,10 +1052,7 @@ export default function ObjectStorageBrowser() { 绑定 Bucket - + {selectedBucket || selectedConnection.bucket || "未绑定 bucket"} @@ -1264,9 +1198,7 @@ export default function ObjectStorageBrowser() { {formatBytes(item.sizeBytes)} - {item.lastModified && ( - {formatCompactDateTime(item.lastModified, timeZone)} - )} + {item.lastModified && {formatCompactDateTime(item.lastModified, timeZone)}} {item.contentType && {item.contentType}} @@ -1346,9 +1278,9 @@ export default function ObjectStorageBrowser() { 对象 key - setObjectDraftKey(event.target.value)} className="w-full rounded-xl border border-[#2a2b2f] bg-[#0b0c10] px-4 py-3 text-sm text-white focus:border-blue-500 focus:outline-none" placeholder="例如:demo/output.json" @@ -1356,9 +1288,9 @@ export default function ObjectStorageBrowser() { Content-Type - setObjectContentType(event.target.value)} className="w-full rounded-xl border border-[#2a2b2f] bg-[#0b0c10] px-4 py-3 text-sm text-white focus:border-blue-500 focus:outline-none" /> @@ -1391,11 +1323,7 @@ export default function ObjectStorageBrowser() { disabled={objectActionLoading || objectEditorLocked} className="inline-flex items-center gap-2 rounded-xl bg-blue-600 px-4 py-3 text-sm font-medium text-white hover:bg-blue-500 disabled:opacity-60" > - {objectActionLoading ? ( - - ) : ( - - )} + {objectActionLoading ? : } 保存对象 diff --git a/src/pages/Operators.tsx b/src/pages/Operators.tsx index c6f6ad6e..077810f9 100644 --- a/src/pages/Operators.tsx +++ b/src/pages/Operators.tsx @@ -1,5 +1,19 @@ import React, { useEffect, useState } from "react"; -import { Cpu, Plus, Search, Code, Box, X, Info, Layers, Edit3, Trash2, Sparkles, Loader2, AlertCircle } from "lucide-react"; +import { + Cpu, + Plus, + Search, + Code, + Box, + X, + Info, + Layers, + Edit3, + Trash2, + Sparkles, + Loader2, + AlertCircle, +} from "lucide-react"; import { useUser } from "../context/UserContext"; import { cn } from "../lib/utils"; import { Operator, PortDefinition } from "../types"; @@ -37,39 +51,42 @@ export default function Operators() { inputs: [], outputs: [], hyperparams: [], - skillDefinition: "" + skillDefinition: "", }); useEffect(() => { - operatorsApi.list().then(setOperators).catch((error) => { - console.error("Failed to load operators", error); - }); + operatorsApi + .list() + .then(setOperators) + .catch((error) => { + console.error("Failed to load operators", error); + }); }, []); const handleAddHyperParam = () => { const hp = { key: `PARAM_${(newOp.hyperparams?.length || 0) + 1}`, value: "", - description: "" + description: "", }; setNewOp({ ...newOp, hyperparams: [...(newOp.hyperparams || []), hp] }); }; - const handleAddPort = (type: 'inputs' | 'outputs') => { + 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" + transmission: "bus", }; return { ...current, [type]: [...(current[type] || []), port] }; }); }; const updatePort = ( - type: 'inputs' | 'outputs', + type: "inputs" | "outputs", index: number, updater: Partial | ((current: PortDefinition) => PortDefinition), ) => { @@ -84,7 +101,7 @@ export default function Operators() { }); }; - const removePort = (type: 'inputs' | 'outputs', index: number) => { + const removePort = (type: "inputs" | "outputs", index: number) => { setNewOp((current) => ({ ...current, [type]: (current[type] || []).filter((_, portIndex) => portIndex !== index), @@ -96,9 +113,7 @@ export default function Operators() { if (editingOpId) { operatorsApi .update(editingOpId, newOp) - .then((updated) => - setOperators(operators.map((op) => (op.id === editingOpId ? updated : op))), - ) + .then((updated) => setOperators(operators.map((op) => (op.id === editingOpId ? updated : op)))) .catch((error) => console.error("Failed to update operator", error)); } else { operatorsApi @@ -141,10 +156,10 @@ export default function Operators() { name: generated.name, category: generated.category as any, description: generated.description, - inputs: generated.inputs.map(i => ({ id: createPortID(), ...i })) as any, - outputs: generated.outputs.map(o => ({ id: createPortID(), ...o })) as any, + inputs: generated.inputs.map((i) => ({ id: createPortID(), ...i })) as any, + outputs: generated.outputs.map((o) => ({ id: createPortID(), ...o })) as any, hyperparams: generated.hyperparams || [], - skillDefinition: generated.skillDefinition + skillDefinition: generated.skillDefinition, }); setIsAIModalOpen(false); setIsModalOpen(true); @@ -183,14 +198,18 @@ export default function Operators() { {canManage && ( - { setAiDescription(""); setAiError(null); setIsAIModalOpen(true); }} disabled={!aiStatus.enabled} - title={aiStatus.enabled ? `使用 ${aiStatus.model || "glm-5"} 辅助生成算子定义` : (aiStatus.reason || "当前服务端未配置 AI 服务")} + title={ + aiStatus.enabled + ? `使用 ${aiStatus.model || "glm-5"} 辅助生成算子定义` + : aiStatus.reason || "当前服务端未配置 AI 服务" + } className={cn( "flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors border border-blue-500/20", aiStatus.enabled @@ -201,7 +220,7 @@ export default function Operators() { AI 辅助注册 - { setEditingOpId(null); setNewOp({ type: "custom", category: "CV", inputs: [], outputs: [], skillDefinition: "" }); @@ -219,9 +238,9 @@ export default function Operators() { - 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" @@ -231,39 +250,51 @@ export default function Operators() { {filteredOperators.map((op) => ( - canManage && handleEdit(op)} className={cn( "bg-[#151619] border border-[#2a2b2f] rounded-xl p-6 hover:bg-[#1a1b1e] transition-all group relative", - canManage && "cursor-pointer" + canManage && "cursor-pointer", )} > - + {op.category === "IO" ? : } {canManage && ( <> {op.type === "custom" && ( - handleEdit(op)} className="p-1.5 hover:bg-white/5 rounded text-gray-500 hover:text-blue-400 transition-colors"> + handleEdit(op)} + className="p-1.5 hover:bg-white/5 rounded text-gray-500 hover:text-blue-400 transition-colors" + > )} - handleDelete(op.id)} className="p-1.5 hover:bg-white/5 rounded text-gray-500 hover:text-red-400 transition-colors"> + handleDelete(op.id)} + className="p-1.5 hover:bg-white/5 rounded text-gray-500 hover:text-red-400 transition-colors" + > > )} - + {op.type === "builtin" ? "Built-in" : "Custom"} {op.skillDefinition && ( @@ -274,10 +305,10 @@ export default function Operators() { )} - + {op.name} {op.description} - + {/* Contract / Ports Display */} @@ -285,17 +316,25 @@ export default function Operators() { 契约定义 (Ports) - {op.inputs?.map(port => ( - + {op.inputs?.map((port) => ( + IN: {port.name} ({port.type}) ))} - {op.outputs?.map(port => ( - + {op.outputs?.map((port) => ( + OUT: {port.name} ({port.type}) ))} - {(!op.inputs?.length && !op.outputs?.length) && 无端口定义} + {!op.inputs?.length && !op.outputs?.length && ( + 无端口定义 + )} @@ -307,8 +346,11 @@ export default function Operators() { 超参配置 (Hyperparams) - {op.hyperparams.map(hp => ( - + {op.hyperparams.map((hp) => ( + {hp.key}={hp.value} ))} @@ -318,7 +360,7 @@ export default function Operators() { {op.category} - handleEdit(op)} className="text-xs text-blue-500 hover:underline flex items-center gap-1" > @@ -353,7 +395,9 @@ export default function Operators() { 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" + activeTab === "basic" + ? "text-blue-500 border-blue-500" + : "text-gray-500 border-transparent hover:text-gray-300", )} > 基础配置 @@ -363,7 +407,9 @@ export default function Operators() { 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" + activeTab === "ports" + ? "text-blue-500 border-blue-500" + : "text-gray-500 border-transparent hover:text-gray-300", )} > 端口定义 @@ -373,7 +419,9 @@ export default function Operators() { 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" + activeTab === "hyperparams" + ? "text-blue-500 border-blue-500" + : "text-gray-500 border-transparent hover:text-gray-300", )} > 超参配置 @@ -383,33 +431,35 @@ export default function Operators() { 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" + activeTab === "skill" + ? "text-blue-500 border-blue-500" + : "text-gray-500 border-transparent hover:text-gray-300", )} > AI Skill 描述 - + {activeTab === "basic" && ( 算子名称 - setNewOp({...newOp, name: e.target.value})} + onChange={(e) => setNewOp({ ...newOp, name: e.target.value })} /> 分类 - setNewOp({...newOp, category: e.target.value})} + onChange={(e) => setNewOp({ ...newOp, category: e.target.value })} > 计算机视觉 (CV) 人工智能 (AI) @@ -421,22 +471,24 @@ export default function Operators() { 描述 - setNewOp({...newOp, description: e.target.value})} + onChange={(e) => setNewOp({ ...newOp, description: e.target.value })} /> - Docker 镜像地址 - + Docker 镜像地址 + + setNewOp({...newOp, image: e.target.value})} + onChange={(e) => setNewOp({ ...newOp, image: e.target.value })} /> @@ -446,35 +498,40 @@ export default function Operators() { - 输入端口 (Inputs) - handleAddPort('inputs')} className="text-blue-500 hover:text-blue-400 text-xs flex items-center gap-1"> + + 输入端口 (Inputs) + + handleAddPort("inputs")} + className="text-blue-500 hover:text-blue-400 text-xs flex items-center gap-1" + > 添加 {newOp.inputs?.map((port, idx) => ( - - + updatePort('inputs', idx, { name: e.target.value })} + onChange={(e) => updatePort("inputs", idx, { name: e.target.value })} /> - { + onChange={(e) => { const type = e.target.value as any; - updatePort('inputs', idx, (current) => ({ + updatePort("inputs", idx, (current) => ({ ...current, type, transmission: - type === "video" || type === "file" - ? "oss" - : type === "tensor" - ? "stream" - : "bus", + type === "video" || type === "file" ? "oss" : type === "tensor" ? "stream" : "bus", })); }} > @@ -484,19 +541,19 @@ export default function Operators() { Tensor File - updatePort('inputs', idx, { transmission: e.target.value as any })} + onChange={(e) => updatePort("inputs", idx, { transmission: e.target.value as any })} > Bus OSS SHM Stream - removePort('inputs', idx)} + onClick={() => removePort("inputs", idx)} className="shrink-0 p-1.5 text-gray-600 hover:text-red-500" aria-label={`删除输入端口 ${port.name || idx + 1}`} > @@ -509,35 +566,40 @@ export default function Operators() { - 输出端口 (Outputs) - handleAddPort('outputs')} className="text-green-500 hover:text-green-400 text-xs flex items-center gap-1"> + + 输出端口 (Outputs) + + handleAddPort("outputs")} + className="text-green-500 hover:text-green-400 text-xs flex items-center gap-1" + > 添加 {newOp.outputs?.map((port, idx) => ( - - + updatePort('outputs', idx, { name: e.target.value })} + onChange={(e) => updatePort("outputs", idx, { name: e.target.value })} /> - { + onChange={(e) => { const type = e.target.value as any; - updatePort('outputs', idx, (current) => ({ + updatePort("outputs", idx, (current) => ({ ...current, type, transmission: - type === "video" || type === "file" - ? "oss" - : type === "tensor" - ? "stream" - : "bus", + type === "video" || type === "file" ? "oss" : type === "tensor" ? "stream" : "bus", })); }} > @@ -547,19 +609,19 @@ export default function Operators() { Tensor File - updatePort('outputs', idx, { transmission: e.target.value as any })} + onChange={(e) => updatePort("outputs", idx, { transmission: e.target.value as any })} > Bus OSS SHM Stream - removePort('outputs', idx)} + onClick={() => removePort("outputs", idx)} className="shrink-0 p-1.5 text-gray-600 hover:text-red-500" aria-label={`删除输出端口 ${port.name || idx + 1}`} > @@ -587,69 +649,73 @@ export default function Operators() { 添加参数 - + - 超参将作为环境变量注入到算子的 K8s Job 中。 - 例如:设置 CONFIDENCE_THRESHOLD 为 0.5, - 算子代码中可以通过 os.environ.get('CONFIDENCE_THRESHOLD') 获取。 + 超参将作为环境变量注入到算子的 K8s Job 中。 例如:设置 CONFIDENCE_THRESHOLD 为{" "} + 0.5, 算子代码中可以通过 os.environ.get('CONFIDENCE_THRESHOLD') 获取。 {newOp.hyperparams?.map((hp, idx) => ( - + { const hyperparams = newOp.hyperparams?.filter((_, i) => i !== idx); - setNewOp({...newOp, hyperparams}); + setNewOp({ ...newOp, hyperparams }); }} className="absolute top-2 right-2 text-gray-600 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity" > - + 变量名 (Key) - { + onChange={(e) => { const hyperparams = [...(newOp.hyperparams || [])]; - hyperparams[idx].key = e.target.value.toUpperCase().replace(/\s+/g, '_'); - setNewOp({...newOp, hyperparams}); + hyperparams[idx].key = e.target.value.toUpperCase().replace(/\s+/g, "_"); + setNewOp({ ...newOp, hyperparams }); }} /> - 默认值 (Default Value) - + 默认值 (Default Value) + + { + onChange={(e) => { const hyperparams = [...(newOp.hyperparams || [])]; hyperparams[idx].value = e.target.value; - setNewOp({...newOp, hyperparams}); + setNewOp({ ...newOp, hyperparams }); }} /> 描述 (Description) - { + onChange={(e) => { const hyperparams = [...(newOp.hyperparams || [])]; hyperparams[idx].description = e.target.value; - setNewOp({...newOp, hyperparams}); + setNewOp({ ...newOp, hyperparams }); }} /> @@ -669,17 +735,19 @@ export default function Operators() { - AI Skill 描述用于向 AI 助手描述该算子的功能、输入输出要求以及使用场景。 - 良好的描述能帮助 AI 更准确地在自动化工作流生成中使用该算子。 + AI Skill 描述用于向 AI 助手描述该算子的功能、输入输出要求以及使用场景。 良好的描述能帮助 AI + 更准确地在自动化工作流生成中使用该算子。 - Skill 定义 (Markdown) - + Skill 定义 (Markdown) + + setNewOp({...newOp, skillDefinition: e.target.value})} + onChange={(e) => setNewOp({ ...newOp, skillDefinition: e.target.value })} /> @@ -715,7 +783,10 @@ export default function Operators() { AI 辅助注册算子 - setIsAIModalOpen(false)} className="text-gray-500 hover:text-white transition-colors"> + setIsAIModalOpen(false)} + className="text-gray-500 hover:text-white transition-colors" + > @@ -723,11 +794,11 @@ export default function Operators() { 描述您的算子 - setAiDescription(e.target.value)} + onChange={(e) => setAiDescription(e.target.value)} disabled={isGenerating} /> @@ -758,19 +829,19 @@ export default function Operators() { - setIsAIModalOpen(false)} className="px-4 py-2 text-sm font-medium text-gray-400 hover:text-white transition-colors" disabled={isGenerating} > 取消 - {isGenerating ? ( diff --git a/src/pages/Packages.tsx b/src/pages/Packages.tsx index b6fa6cc2..ac81e72a 100644 --- a/src/pages/Packages.tsx +++ b/src/pages/Packages.tsx @@ -15,22 +15,28 @@ export default function Packages() { const [search, setSearch] = useState(""); useEffect(() => { - dataPlatformApi.listPackages().then((loaded) => { - setItems(loaded); - if (loaded[0]) setSelected(loaded[0]); - }).catch((error) => { - console.error("Failed to load packages", error); - }); + dataPlatformApi + .listPackages() + .then((loaded) => { + setItems(loaded); + if (loaded[0]) setSelected(loaded[0]); + }) + .catch((error) => { + console.error("Failed to load packages", error); + }); }, []); useEffect(() => { if (!selected) return; - dataPlatformApi.getPackage(selected.runId, selected.packageName).then((loaded) => { - setDetail(loaded); - setSelectedArtifact(loaded.package.previewArtifact || loaded.files[0] || null); - }).catch((error) => { - console.error("Failed to load package detail", error); - }); + dataPlatformApi + .getPackage(selected.runId, selected.packageName) + .then((loaded) => { + setDetail(loaded); + setSelectedArtifact(loaded.package.previewArtifact || loaded.files[0] || null); + }) + .catch((error) => { + console.error("Failed to load package detail", error); + }); }, [selected]); const filtered = useMemo(() => { @@ -47,7 +53,9 @@ export default function Packages() { 成品数据 - 直接基于真实 package run artifacts 聚合,保留来源 workflow 与 run 可追溯性。 + + 直接基于真实 package run artifacts 聚合,保留来源 workflow 与 run 可追溯性。 + @@ -81,14 +89,19 @@ export default function Packages() { {item.pipelineTags.map((tag) => ( - + {tag} ))} - {item.projectName} / {item.workflowName} + + {item.projectName} / {item.workflowName} + {formatCompactDateTime(item.createdAt, timeZone)} @@ -126,7 +139,9 @@ export default function Packages() { > {file.path} - {file.size} · {file.metadata?.mimeType || file.type} + + {file.size} · {file.metadata?.mimeType || file.type} + @@ -139,11 +154,15 @@ export default function Packages() { 质检结果 - {JSON.stringify(detail.package.quality || {}, null, 2)} + + {JSON.stringify(detail.package.quality || {}, null, 2)} + 标注结果 - {JSON.stringify(detail.package.annotation || {}, null, 2)} + + {JSON.stringify(detail.package.annotation || {}, null, 2)} + diff --git a/src/pages/ProjectDetail.tsx b/src/pages/ProjectDetail.tsx index ce7c80d9..4f6ee0ac 100644 --- a/src/pages/ProjectDetail.tsx +++ b/src/pages/ProjectDetail.tsx @@ -27,10 +27,7 @@ import { import { cn } from "../lib/utils"; import { buildDataAssetsPath, DATA_ASSET_PACKAGES_TAB } from "../lib/data-assets.js"; import { formatCompactDateTime } from "../lib/datetime"; -import { - buildTemplatePayload, - buildWorkflowCopyPayload, -} from "../lib/templates.js"; +import { buildTemplatePayload, buildWorkflowCopyPayload } from "../lib/templates.js"; import { buildWorkflowEditorPath } from "../lib/scan-workflows.js"; import { countWorkflowOperators } from "../lib/workflow"; import { Project, Workflow as WorkflowRecord } from "../types"; @@ -55,9 +52,7 @@ export default function ProjectDetail() { const [isAIModalOpen, setIsAIModalOpen] = useState(false); const [isEditModalOpen, setIsEditModalOpen] = useState(false); const [isSaveTemplateModalOpen, setIsSaveTemplateModalOpen] = useState(false); - const [editingWorkflow, setEditingWorkflow] = useState( - null, - ); + const [editingWorkflow, setEditingWorkflow] = useState(null); const [workflows, setWorkflows] = useState([]); const [newWfData, setNewWfData] = useState({ name: "", @@ -81,9 +76,7 @@ export default function ProjectDetail() { console.error("Failed to load project detail", error); setProject(null); setWorkflows([]); - setLoadError( - error instanceof Error ? error.message : "加载项目详情失败", - ); + setLoadError(error instanceof Error ? error.message : "加载项目详情失败"); }) .finally(() => { setLoading(false); @@ -127,11 +120,7 @@ export default function ProjectDetail() { return status !== "running" && status !== "completed"; }; - const handleAIGenerate = ( - workflow: GeneratedWorkflow, - name: string, - description: string, - ) => { + const handleAIGenerate = (workflow: GeneratedWorkflow, name: string, description: string) => { if (!id) return; projectsApi .createWorkflow(id, { @@ -172,9 +161,7 @@ export default function ProjectDetail() { const handleDeleteWorkflow = (wfId: string) => { workflowsApi .remove(wfId) - .then(() => - setWorkflows(workflows.filter((workflow) => workflow.id !== wfId)), - ) + .then(() => setWorkflows(workflows.filter((workflow) => workflow.id !== wfId))) .catch((error) => console.error("Failed to delete workflow", error)); }; @@ -201,11 +188,7 @@ export default function ProjectDetail() { workflowsApi .update(editingWorkflow.id, editingWorkflow) .then((updated) => { - setWorkflows( - workflows.map((workflow) => - workflow.id === updated.id ? updated : workflow, - ), - ); + setWorkflows(workflows.map((workflow) => (workflow.id === updated.id ? updated : workflow))); setIsEditModalOpen(false); setEditingWorkflow(null); }) @@ -221,8 +204,7 @@ export default function ProjectDetail() { setTemplateDraft({ workflowId: defaultWorkflow.id, name: `${defaultWorkflow.name} 模板`, - description: - defaultWorkflow.description || `${project.name} 导出的工作流模板`, + description: defaultWorkflow.description || `${project.name} 导出的工作流模板`, }); setIsSaveTemplateModalOpen(true); }; @@ -237,9 +219,7 @@ export default function ProjectDetail() { }; const handleSaveTemplate = () => { - const sourceWorkflow = workflows.find( - (workflow) => workflow.id === templateDraft.workflowId, - ); + const sourceWorkflow = workflows.find((workflow) => workflow.id === templateDraft.workflowId); if (!sourceWorkflow || !templateDraft.name.trim()) { return; } @@ -254,9 +234,7 @@ export default function ProjectDetail() { setIsSaveTemplateModalOpen(false); navigate(`/workflow/${created.id}?type=template`); }) - .catch((error) => - console.error("Failed to save workflow as template", error), - ); + .catch((error) => console.error("Failed to save workflow as template", error)); }; return ( @@ -270,9 +248,7 @@ export default function ProjectDetail() { - - {project.name} - + {project.name} {project.description} @@ -340,183 +316,177 @@ export default function ProjectDetail() { onClick={() => navigate( (() => { - const params = new URLSearchParams({ - projectId: project.id, - readOnly: String(!isEditable(wf.status)), - }); - if (wf.status === "running" && wf.lastRunId) { - params.set("runId", wf.lastRunId); - } - return `/workflow/${wf.id}?${params.toString()}`; + const params = new URLSearchParams({ + projectId: project.id, + readOnly: String(!isEditable(wf.status)), + }); + if (wf.status === "running" && wf.lastRunId) { + params.set("runId", wf.lastRunId); + } + return `/workflow/${wf.id}?${params.toString()}`; })(), ) } className="group bg-[#151619] border border-[#2a2b2f] rounded-xl p-5 hover:border-blue-500/50 transition-all cursor-pointer flex items-center gap-6" > - - {wf.status === "completed" ? ( - - ) : wf.status === "running" ? ( - wf.type === "streaming" ? ( - - ) : ( - - ) - ) : wf.status === "failed" ? ( - - ) : ( - - )} - - - - - - {wf.name} - - - - {wf.status} - - - {wf.type === "streaming" ? "周期执行" : "手动执行"} - - - - {wf.description} - - - - - - 算子数 - - - - {operatorCount} - - - - - 最后运行 - - - - {wf.lastRunAt - ? formatCompactDateTime(wf.lastRunAt, timeZone) - : wf.lastRun || "未运行"} - - - - - - {isEditable(wf.status) && canManage ? ( - <> - - 编辑 - > - ) : ( - <> - - 查看 - > - )} - - {canManage && ( - <> - { - e.stopPropagation(); - navigate( - buildDataAssetsPath({ - tab: DATA_ASSET_PACKAGES_TAB, - projectId: project.id, - projectName: project.name, - workflowId: wf.id, - workflowName: wf.name, - runId: wf.lastRunId || "", - }), - ); - }} - title="查看相关数据资产" - > - - - { - e.stopPropagation(); - handleEditInfo(wf); - }} - title="编辑基本信息" - > - - - { - e.stopPropagation(); - handleCopyWorkflow(wf); - }} - title="复制工作流" - > - - - { - e.stopPropagation(); - handleDeleteWorkflow(wf.id); - }} - title="删除工作流" - > - - - > + - + > + {wf.status === "completed" ? ( + + ) : wf.status === "running" ? ( + wf.type === "streaming" ? ( + + ) : ( + + ) + ) : wf.status === "failed" ? ( + + ) : ( + + )} + + + + + + {wf.name} + + + + {wf.status} + + + {wf.type === "streaming" ? "周期执行" : "手动执行"} + + + + {wf.description} + + + + + 算子数 + + + {operatorCount} + + + + 最后运行 + + + {wf.lastRunAt ? formatCompactDateTime(wf.lastRunAt, timeZone) : wf.lastRun || "未运行"} + + + + + + {isEditable(wf.status) && canManage ? ( + <> + + 编辑 + > + ) : ( + <> + + 查看 + > + )} + + {canManage && ( + <> + { + e.stopPropagation(); + navigate( + buildDataAssetsPath({ + tab: DATA_ASSET_PACKAGES_TAB, + projectId: project.id, + projectName: project.name, + workflowId: wf.id, + workflowName: wf.name, + runId: wf.lastRunId || "", + }), + ); + }} + title="查看相关数据资产" + > + + + { + e.stopPropagation(); + handleEditInfo(wf); + }} + title="编辑基本信息" + > + + + { + e.stopPropagation(); + handleCopyWorkflow(wf); + }} + title="复制工作流" + > + + + { + e.stopPropagation(); + handleDeleteWorkflow(wf.id); + }} + title="删除工作流" + > + + + > + )} + + + - ); })} {workflows.length === 0 && ( @@ -531,13 +501,8 @@ export default function ProjectDetail() { - - 创建新工作流 - - setIsNewWorkflowModalOpen(false)} - className="text-gray-500 hover:text-white" - > + 创建新工作流 + setIsNewWorkflowModalOpen(false)} className="text-gray-500 hover:text-white"> @@ -556,19 +521,15 @@ export default function ProjectDetail() { 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={newWfData.name} - onChange={(e) => - setNewWfData({ ...newWfData, name: e.target.value }) - } + onChange={(e) => setNewWfData({ ...newWfData, name: e.target.value })} /> - - 默认先创建普通工作流 - + 默认先创建普通工作流 - 创建后请在“工作流配置”里设置触发方式。如果流程需要源数据扫描, - 直接把“BOS 增量扫描”算子拖到画布;FULL/INCREMENTAL、连接信息和扫描路径都在该节点中配置。 + 创建后请在“工作流配置”里设置触发方式。如果流程需要源数据扫描, 直接把“BOS + 增量扫描”算子拖到画布;FULL/INCREMENTAL、连接信息和扫描路径都在该节点中配置。 @@ -594,11 +555,7 @@ export default function ProjectDetail() { )} - setIsAIModalOpen(false)} - onGenerate={handleAIGenerate} - /> + setIsAIModalOpen(false)} onGenerate={handleAIGenerate} /> {isSaveTemplateModalOpen && ( @@ -617,14 +574,10 @@ export default function ProjectDetail() { - - 来源工作流 - + 来源工作流 - handleTemplateWorkflowChange(event.target.value) - } + onChange={(event) => handleTemplateWorkflowChange(event.target.value)} className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500 text-white" > {workflows.map((workflow) => ( @@ -635,9 +588,7 @@ export default function ProjectDetail() { - - 模板名称 - + 模板名称 - - 模板描述 - + 模板描述 保存模板 @@ -698,18 +644,13 @@ export default function ProjectDetail() { 编辑工作流信息 - setIsEditModalOpen(false)} - className="text-gray-500 hover:text-white" - > + setIsEditModalOpen(false)} className="text-gray-500 hover:text-white"> - - 工作流名称 - + 工作流名称 - - 描述 - + 描述 ([]); const [searchQuery, setSearchQuery] = useState(""); - const [statusFilter, setStatusFilter] = useState< - "all" | "active" | "archived" - >("all"); + const [statusFilter, setStatusFilter] = useState<"all" | "active" | "archived">("all"); const [isModalOpen, setIsModalOpen] = useState(false); const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [modalMode, setModalMode] = useState<"create" | "edit">("create"); @@ -103,8 +101,7 @@ export default function Projects() { .filter(Boolean) .some((value) => value.toLowerCase().includes(normalizedSearch)); const projectStatus = project.status || "active"; - const matchesStatus = - statusFilter === "all" || projectStatus === statusFilter; + const matchesStatus = statusFilter === "all" || projectStatus === statusFilter; return matchesSearch && matchesStatus; }); @@ -122,13 +119,7 @@ export default function Projects() { } else { projectsApi .update(currentProject.id as string, currentProject) - .then((updated) => - setProjects( - projects.map((project) => - project.id === updated.id ? updated : project, - ), - ), - ) + .then((updated) => setProjects(projects.map((project) => (project.id === updated.id ? updated : project)))) .catch((error) => console.error("Failed to update project", error)); } setIsModalOpen(false); @@ -138,12 +129,8 @@ export default function Projects() { - - 项目管理 - - - 在 Drobodata 中管理您的具身智能数据处理项目 - + 项目管理 + 在 Drobodata 中管理您的具身智能数据处理项目 {canManage && ( - setStatusFilter(event.target.value as typeof statusFilter) - } + onChange={(event) => setStatusFilter(event.target.value as typeof statusFilter)} className="bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500" > 所有状态 @@ -197,9 +182,7 @@ export default function Projects() { className="text-gray-500 hover:text-white p-1 rounded-md hover:bg-white/5 transition-colors" onClick={(e) => { e.stopPropagation(); - setOpenMenuId( - openMenuId === project.id ? null : project.id, - ); + setOpenMenuId(openMenuId === project.id ? null : project.id); }} > @@ -243,12 +226,8 @@ export default function Projects() { )} - - {project.name} - - - {project.description} - + {project.name} + {project.description} @@ -270,9 +249,7 @@ export default function Projects() { ))} {filteredProjects.length === 0 && ( - {projects.length === 0 - ? "当前还没有项目,请先创建真实项目。" - : "没有匹配的项目,请调整筛选条件。"} + {projects.length === 0 ? "当前还没有项目,请先创建真实项目。" : "没有匹配的项目,请调整筛选条件。"} )} @@ -299,9 +276,7 @@ export default function Projects() { - - 项目名称 - + 项目名称 - - 项目描述 - + 项目描述 确认删除项目? - - 此操作不可撤销。该项目及其关联的所有工作流都将被永久删除。 - + 此操作不可撤销。该项目及其关联的所有工作流都将被永久删除。 diff --git a/src/pages/Sampling.tsx b/src/pages/Sampling.tsx index 508f0b95..ea8ed84f 100644 --- a/src/pages/Sampling.tsx +++ b/src/pages/Sampling.tsx @@ -23,15 +23,18 @@ export default function Sampling() { const [review, setReview] = useState(emptyReview); const loadTasks = () => { - dataPlatformApi.listSamplingTasks().then((loaded) => { - setTasks(loaded); - if (loaded[0]) { - setSelectedTask(loaded[0]); - setSelectedItem(loaded[0].items.find((item) => item.status === "pending") || loaded[0].items[0] || null); - } - }).catch((error) => { - console.error("Failed to load sampling tasks", error); - }); + dataPlatformApi + .listSamplingTasks() + .then((loaded) => { + setTasks(loaded); + if (loaded[0]) { + setSelectedTask(loaded[0]); + setSelectedItem(loaded[0].items.find((item) => item.status === "pending") || loaded[0].items[0] || null); + } + }) + .catch((error) => { + console.error("Failed to load sampling tasks", error); + }); }; useEffect(() => { @@ -40,10 +43,11 @@ export default function Sampling() { useEffect(() => { if (!selectedTask) return; - const nextItem = selectedTask.items.find((item) => item.id === selectedItem?.id) - || selectedTask.items.find((item) => item.status === "pending") - || selectedTask.items[0] - || null; + const nextItem = + selectedTask.items.find((item) => item.id === selectedItem?.id) || + selectedTask.items.find((item) => item.status === "pending") || + selectedTask.items[0] || + null; setSelectedItem(nextItem); }, [selectedTask]); @@ -63,7 +67,11 @@ export default function Sampling() { const updated = await dataPlatformApi.reviewSamplingItem(selectedItem.id, review); setTasks((current) => current.map((task) => (task.id === updated.id ? updated : task))); setSelectedTask(updated); - setSelectedItem(updated.items.find((item) => item.status === "pending") || updated.items.find((item) => item.id === selectedItem.id) || null); + setSelectedItem( + updated.items.find((item) => item.status === "pending") || + updated.items.find((item) => item.id === selectedItem.id) || + null, + ); setReview(emptyReview); } catch (error) { console.error("Failed to review sampling item", error); @@ -74,7 +82,9 @@ export default function Sampling() { 抽检任务 - 基于真实 `audit-samples.json` 自动生成的人工抽检任务,评审结果会持久化保存。 + + 基于真实 `audit-samples.json` 自动生成的人工抽检任务,评审结果会持久化保存。 + @@ -100,14 +110,20 @@ export default function Sampling() { {task.name} - {task.projectName} / {task.workflowName} + + {task.projectName} / {task.workflowName} + - + {task.status === "completed" ? "已完成" : "待处理"} - {task.items.filter((item) => item.status === "completed").length}/{task.items.length} 已评审 + + {task.items.filter((item) => item.status === "completed").length}/{task.items.length} 已评审 + {formatCompactDateTime(task.createdAt, timeZone)} @@ -126,9 +142,13 @@ export default function Sampling() { {item.packageName} - {item.sourceVideo} · 规则 {item.sampleRuleId || "-"} + + {item.sourceVideo} · 规则 {item.sampleRuleId || "-"} + - + {item.status === "completed" ? "已评审" : "待评审"} @@ -158,43 +178,76 @@ export default function Sampling() { 质检 - {JSON.stringify(selectedItem.quality || {}, null, 2)} + + {JSON.stringify(selectedItem.quality || {}, null, 2)} + 标注 - {JSON.stringify(selectedItem.annotation || {}, null, 2)} + + {JSON.stringify(selectedItem.annotation || {}, null, 2)} + {selectedItem.status === "completed" && selectedItem.review ? ( - 已评审:{selectedItem.review.overallGrade} · {selectedItem.review.videoQuality} / {selectedItem.review.annotationAccuracy} / {selectedItem.review.annotationCompleteness} + 已评审:{selectedItem.review.overallGrade} · {selectedItem.review.videoQuality} /{" "} + {selectedItem.review.annotationAccuracy} / {selectedItem.review.annotationCompleteness} ) : ( 视频质量 - setReview((current) => ({ ...current, videoQuality: event.target.value }))} className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white"> - {["合格", "不合格"].map((option) => {option})} + setReview((current) => ({ ...current, videoQuality: event.target.value }))} + className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white" + > + {["合格", "不合格"].map((option) => ( + {option} + ))} 标注准确性 - setReview((current) => ({ ...current, annotationAccuracy: event.target.value }))} className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white"> - {["正确", "不正确"].map((option) => {option})} + + setReview((current) => ({ ...current, annotationAccuracy: event.target.value })) + } + className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white" + > + {["正确", "不正确"].map((option) => ( + {option} + ))} 标注完整性 - setReview((current) => ({ ...current, annotationCompleteness: event.target.value }))} className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white"> - {["完整", "不完整"].map((option) => {option})} + + setReview((current) => ({ ...current, annotationCompleteness: event.target.value })) + } + className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white" + > + {["完整", "不完整"].map((option) => ( + {option} + ))} 总体评价 - setReview((current) => ({ ...current, overallGrade: event.target.value }))} className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white"> - {["A", "B", "C", "D"].map((option) => {option})} + setReview((current) => ({ ...current, overallGrade: event.target.value }))} + className="w-full rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-white" + > + {["A", "B", "C", "D"].map((option) => ( + {option} + ))} @@ -208,7 +261,10 @@ export default function Sampling() { /> - + 提交抽检结果 diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index 9db0ca51..4be1f0e4 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,21 +1,7 @@ import React, { useEffect, useState } from "react"; -import { - AlertCircle, - Bot, - CheckCircle2, - Clock3, - Cpu, - Loader2, - Save, - Server, -} from "lucide-react"; +import { AlertCircle, Bot, CheckCircle2, Clock3, Cpu, Loader2, Save, Server } from "lucide-react"; import { useTimeZone } from "../context/TimeZoneContext"; -import { - COMMON_TIME_ZONES, - formatCompactDateTime, - formatDateTime, - resolveTimeZone, -} from "../lib/datetime"; +import { COMMON_TIME_ZONES, formatCompactDateTime, formatDateTime, resolveTimeZone } from "../lib/datetime"; import { buildSettingsUpdatePayload } from "../lib/settings.js"; import { settingsApi } from "../services/api/settings"; import type { SystemConfig } from "../types"; @@ -41,9 +27,7 @@ export default function Settings() { }) .catch((error) => { console.error("Failed to load settings", error); - setErrorMessage( - error instanceof Error ? error.message : "加载系统配置失败", - ); + setErrorMessage(error instanceof Error ? error.message : "加载系统配置失败"); }); }, []); @@ -66,9 +50,7 @@ export default function Settings() { } catch (error) { console.error("Failed to save settings", error); setSaveState("error"); - setErrorMessage( - error instanceof Error ? error.message : "保存系统配置失败", - ); + setErrorMessage(error instanceof Error ? error.message : "保存系统配置失败"); } }; @@ -76,12 +58,8 @@ export default function Settings() { return ( - - 系统配置 - - - 配置 Kubernetes 集群、Worker 调度、显示时区、AI 生成服务及默认资源限制 - + 系统配置 + 配置 Kubernetes 集群、Worker 调度、显示时区、AI 生成服务及默认资源限制 @@ -97,24 +75,17 @@ export default function Settings() { ); } - const savedAIKeyExists = - Boolean(config.ai.hasAPIKey) && - !(config.ai.apiKey && config.ai.apiKey.trim().length > 0); + const savedAIKeyExists = Boolean(config.ai.hasAPIKey) && !(config.ai.apiKey && config.ai.apiKey.trim().length > 0); const savedKubeconfigExists = - Boolean(config.k8s.hasKubeconfig) && - !(config.k8s.kubeconfig && config.k8s.kubeconfig.trim().length > 0); + Boolean(config.k8s.hasKubeconfig) && !(config.k8s.kubeconfig && config.k8s.kubeconfig.trim().length > 0); const savedAIKeyPreview = config.ai.apiKeyPreview?.trim() || ""; const savedKubeconfigPreview = config.k8s.kubeconfigPreview?.trim() || ""; return ( - - 系统配置 - - - 配置 Kubernetes 集群、Worker 调度、显示时区、AI 生成服务及默认资源限制 - + 系统配置 + 配置 Kubernetes 集群、Worker 调度、显示时区、AI 生成服务及默认资源限制 {errorMessage && ( @@ -142,9 +113,7 @@ export default function Settings() { - - 集群 Endpoint - + 集群 Endpoint - - 默认命名空间 - + 默认命名空间 - - 默认 GPU 数量 - + 默认 GPU 数量 - - 共享 PVC 名称 - + 共享 PVC 名称 - - 共享挂载路径 - + 共享挂载路径 {savedKubeconfigPreview ? ( - - 仅回显前后缀 - - - {savedKubeconfigPreview} - + 仅回显前后缀 + {savedKubeconfigPreview} ) : null} @@ -292,9 +249,7 @@ export default function Settings() { k8s: { ...current.k8s, kubeconfig: event.target.value, - hasKubeconfig: - current.k8s.hasKubeconfig || - event.target.value.trim().length > 0, + hasKubeconfig: current.k8s.hasKubeconfig || event.target.value.trim().length > 0, }, } : current, @@ -324,9 +279,7 @@ export default function Settings() { - - 轮询间隔 (ms) - + 轮询间隔 (ms) - - 默认最大并发数 - + 默认最大并发数 - - IANA 时区 - + IANA 时区 - setConfig((current) => - current - ? { ...current, timezone: event.target.value } - : current, - ) + setConfig((current) => (current ? { ...current, timezone: event.target.value } : current)) } placeholder="例如 Asia/Shanghai" className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-amber-400" @@ -517,9 +458,7 @@ export default function Settings() { - - Provider - + Provider - - 模型 - + 模型 - - OpenAI 兼容 Base URL - + OpenAI 兼容 Base URL {savedAIKeyPreview ? ( - - 仅回显前后缀 - - - {savedAIKeyPreview} - + 仅回显前后缀 + {savedAIKeyPreview} ) : null} @@ -597,11 +528,7 @@ export default function Settings() { setConfig((current) => current @@ -610,9 +537,7 @@ export default function Settings() { ai: { ...current.ai, apiKey: event.target.value, - hasAPIKey: - current.ai.hasAPIKey || - event.target.value.trim().length > 0, + hasAPIKey: current.ai.hasAPIKey || event.target.value.trim().length > 0, }, } : current, @@ -632,23 +557,14 @@ export default function Settings() { - 最近更新时间:{" "} - {formatCompactDateTime( - config.updatedAt, - config.timezone, - "尚未保存", - )} + 最近更新时间: {formatCompactDateTime(config.updatedAt, config.timezone, "尚未保存")} - {saveState === "saving" ? ( - - ) : ( - - )} + {saveState === "saving" ? : } {saveState === "saving" ? "正在保存..." : "保存配置"} diff --git a/src/pages/SourceData.tsx b/src/pages/SourceData.tsx index 9dfe7642..954e83d9 100644 --- a/src/pages/SourceData.tsx +++ b/src/pages/SourceData.tsx @@ -1,12 +1,5 @@ import React, { useEffect, useMemo, useState } from "react"; -import { - ChevronRight, - FileJson, - FileVideo, - Folder, - HardDrive, - Search, -} from "lucide-react"; +import { ChevronRight, FileJson, FileVideo, Folder, HardDrive, Search } from "lucide-react"; import { useTimeZone } from "../context/TimeZoneContext"; import { formatCompactDateTime } from "../lib/datetime"; import type { ExecutionData, SourceCollection, SourceCollectionDetail, SourceCollectionEntry } from "../types"; @@ -25,12 +18,11 @@ const formatBytes = (value?: number) => { return `${current.toFixed(current >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`; }; -const collectionLabel = (item: Pick) => ( - item.meta?.project_id - || item.collectionName - || item.relativePath.split("/").filter(Boolean).at(-1) - || item.collectionId -); +const collectionLabel = (item: Pick) => + item.meta?.project_id || + item.collectionName || + item.relativePath.split("/").filter(Boolean).at(-1) || + item.collectionId; export default function SourceData() { const { timeZone } = useTimeZone(); @@ -43,25 +35,31 @@ export default function SourceData() { const [placeFilter, setPlaceFilter] = useState("all"); useEffect(() => { - dataPlatformApi.listSourceCollections().then((items) => { - setCollections(items); - if (items[0]) { - setSelectedCollection(items[0]); - } - }).catch((error) => { - console.error("Failed to load source collections", error); - }); + dataPlatformApi + .listSourceCollections() + .then((items) => { + setCollections(items); + if (items[0]) { + setSelectedCollection(items[0]); + } + }) + .catch((error) => { + console.error("Failed to load source collections", error); + }); }, []); useEffect(() => { if (!selectedCollection) return; - dataPlatformApi.getSourceCollection(selectedCollection.runId, selectedCollection.collectionId).then((loaded) => { - setDetail(loaded); - const firstFile = loaded.entries.find((entry) => entry.kind !== "directory" && entry.artifact); - setSelectedArtifact(firstFile?.artifact || null); - }).catch((error) => { - console.error("Failed to load source collection detail", error); - }); + dataPlatformApi + .getSourceCollection(selectedCollection.runId, selectedCollection.collectionId) + .then((loaded) => { + setDetail(loaded); + const firstFile = loaded.entries.find((entry) => entry.kind !== "directory" && entry.artifact); + setSelectedArtifact(firstFile?.artifact || null); + }) + .catch((error) => { + console.error("Failed to load source collection detail", error); + }); }, [selectedCollection]); const typeOptions = useMemo( @@ -78,7 +76,14 @@ export default function SourceData() { return collections.filter((item) => { const matchesSearch = !query || - [item.collectionId, item.collectionName, item.relativePath, item.meta?.place, item.meta?.type, item.meta?.project_id] + [ + item.collectionId, + item.collectionName, + item.relativePath, + item.meta?.place, + item.meta?.type, + item.meta?.project_id, + ] .filter(Boolean) .some((value) => String(value).toLowerCase().includes(query)); const matchesType = typeFilter === "all" || item.meta?.type === typeFilter; @@ -89,13 +94,16 @@ export default function SourceData() { const openPrefix = (prefix: string) => { if (!selectedCollection) return; - dataPlatformApi.getSourceCollectionEntries(selectedCollection.runId, selectedCollection.collectionId, prefix).then((loaded) => { - setDetail(loaded); - const firstFile = loaded.entries.find((entry) => entry.kind !== "directory" && entry.artifact); - setSelectedArtifact(firstFile?.artifact || null); - }).catch((error) => { - console.error("Failed to browse source entries", error); - }); + dataPlatformApi + .getSourceCollectionEntries(selectedCollection.runId, selectedCollection.collectionId, prefix) + .then((loaded) => { + setDetail(loaded); + const firstFile = loaded.entries.find((entry) => entry.kind !== "directory" && entry.artifact); + setSelectedArtifact(firstFile?.artifact || null); + }) + .catch((error) => { + console.error("Failed to browse source entries", error); + }); }; const breadcrumbParts = (detail?.prefix || "").split("/").filter(Boolean); @@ -123,7 +131,9 @@ export default function SourceData() { className="rounded-md border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none" > {typeOptions.map((item) => ( - {item === "all" ? "全部场景" : item} + + {item === "all" ? "全部场景" : item} + ))} {placeOptions.map((item) => ( - {item === "all" ? "全部地点" : item} + + {item === "all" ? "全部地点" : item} + ))} @@ -148,9 +160,13 @@ export default function SourceData() { {collectionLabel(item)} - {item.meta?.place || "未知地点"} · {item.meta?.type || "未知场景"} + + {item.meta?.place || "未知地点"} · {item.meta?.type || "未知场景"} + - + {item.valid ? "有效" : "缺文件"} @@ -221,14 +237,26 @@ export default function SourceData() { className="flex w-full items-start gap-3 border-b border-[#202227] px-4 py-3 text-left hover:bg-white/5" > - {entry.kind === "directory" ? : entry.kind === "video" ? : } + {entry.kind === "directory" ? ( + + ) : entry.kind === "video" ? ( + + ) : ( + + )} {entry.name} {entry.kind === "directory" ? "文件夹" - : [entry.codec, entry.resolution, entry.frameRate ? `${entry.frameRate}fps` : "", entry.duration ? `${entry.duration}s` : "", formatBytes(entry.sizeBytes)] + : [ + entry.codec, + entry.resolution, + entry.frameRate ? `${entry.frameRate}fps` : "", + entry.duration ? `${entry.duration}s` : "", + formatBytes(entry.sizeBytes), + ] .filter(Boolean) .join(" · ")} @@ -269,7 +297,9 @@ export default function SourceData() { ) : ( - 请选择左侧采集目录 + + 请选择左侧采集目录 + )} diff --git a/src/pages/Templates.tsx b/src/pages/Templates.tsx index 5996d099..8e21a394 100644 --- a/src/pages/Templates.tsx +++ b/src/pages/Templates.tsx @@ -17,10 +17,7 @@ import { useNavigate } from "react-router-dom"; import { useTimeZone } from "../context/TimeZoneContext"; import { useUser } from "../context/UserContext"; import { formatCompactDateTime } from "../lib/datetime"; -import { - buildTemplatePayload, - buildWorkflowFromTemplate, -} from "../lib/templates.js"; +import { buildTemplatePayload, buildWorkflowFromTemplate } from "../lib/templates.js"; import { countWorkflowOperators } from "../lib/workflow"; import { cn } from "../lib/utils"; import AIGenerateModal from "../components/AIGenerateModal"; @@ -41,9 +38,7 @@ export default function Templates() { const [isAIModalOpen, setIsAIModalOpen] = useState(false); const [isProjectSelectOpen, setIsProjectSelectOpen] = useState(false); const [selectedTemplate, setSelectedTemplate] = useState(null); - const [selectedProjectId, setSelectedProjectId] = useState( - null, - ); + const [selectedProjectId, setSelectedProjectId] = useState(null); const [searchQuery, setSearchQuery] = useState(""); const [newTpl, setNewTpl] = useState({ name: "", description: "" }); @@ -78,11 +73,7 @@ export default function Templates() { } }; - const handleAIGenerate = ( - workflow: GeneratedWorkflow, - name: string, - description: string, - ) => { + const handleAIGenerate = (workflow: GeneratedWorkflow, name: string, description: string) => { templatesApi .create( buildTemplatePayload( @@ -117,9 +108,7 @@ export default function Templates() { const handleDelete = (id: string) => { templatesApi .remove(id) - .then(() => - setTemplates(templates.filter((template) => template.id !== id)), - ) + .then(() => setTemplates(templates.filter((template) => template.id !== id))) .catch((error) => console.error("Failed to delete template", error)); }; @@ -147,18 +136,13 @@ export default function Templates() { const confirmUseTemplate = () => { if (selectedTemplate && selectedProjectId) { projectsApi - .createWorkflow( - selectedProjectId, - buildWorkflowFromTemplate(selectedTemplate), - ) + .createWorkflow(selectedProjectId, buildWorkflowFromTemplate(selectedTemplate)) .then((created) => { setIsProjectSelectOpen(false); setSelectedProjectId(null); navigate(`/workflow/${created.id}?projectId=${selectedProjectId}`); }) - .catch((error) => - console.error("Failed to instantiate template workflow", error), - ); + .catch((error) => console.error("Failed to instantiate template workflow", error)); } }; @@ -166,12 +150,8 @@ export default function Templates() { - - 工作流模板 - - - 复用经过验证的数据处理流程,加速开发效率 - + 工作流模板 + 复用经过验证的数据处理流程,加速开发效率 {canManage && ( @@ -266,9 +246,7 @@ export default function Templates() { {tpl.name} - - {tpl.description} - + {tpl.description} @@ -320,37 +298,26 @@ export default function Templates() { 创建新模板 - setIsModalOpen(false)} - className="text-gray-500 hover:text-white" - > + setIsModalOpen(false)} className="text-gray-500 hover:text-white"> - - 模板名称 - + 模板名称 - setNewTpl({ ...newTpl, name: e.target.value }) - } + onChange={(e) => setNewTpl({ ...newTpl, name: e.target.value })} /> - - 描述 - + 描述 - setNewTpl({ ...newTpl, description: e.target.value }) - } + onChange={(e) => setNewTpl({ ...newTpl, description: e.target.value })} /> @@ -372,11 +339,7 @@ export default function Templates() { )} - setIsAIModalOpen(false)} - onGenerate={handleAIGenerate} - /> + setIsAIModalOpen(false)} onGenerate={handleAIGenerate} /> {/* Project Selection Modal */} {isProjectSelectOpen && ( @@ -395,9 +358,7 @@ export default function Templates() { - - 请选择要将此模板应用到的项目: - + 请选择要将此模板应用到的项目: {projects.length === 0 ? ( @@ -419,9 +380,7 @@ export default function Templates() { {project.name} - {selectedProjectId === project.id && ( - - )} + {selectedProjectId === project.id && } )) )} diff --git a/src/pages/Users.tsx b/src/pages/Users.tsx index 28e64ca9..8a4ea1fd 100644 --- a/src/pages/Users.tsx +++ b/src/pages/Users.tsx @@ -13,9 +13,11 @@ export default function Users() { const [modalMode, setModalMode] = useState<"create" | "edit">("edit"); useEffect(() => { - refreshUsers({ silent: true }).then(setUsers).catch((error) => { - console.error("Failed to load users", error); - }); + refreshUsers({ silent: true }) + .then(setUsers) + .catch((error) => { + console.error("Failed to load users", error); + }); }, [refreshUsers]); const handleEdit = (user: UserData) => { @@ -98,18 +100,22 @@ export default function Users() { {u.name} {u.email} - + {u.role} - handleEdit(u)} className="text-xs text-blue-500 hover:text-blue-400 font-medium transition-colors" > @@ -139,7 +145,10 @@ export default function Users() { {modalMode === "create" ? "创建用户" : "编辑用户信息"} - setIsModalOpen(false)} className="text-gray-500 hover:text-white transition-colors"> + setIsModalOpen(false)} + className="text-gray-500 hover:text-white transition-colors" + > @@ -148,32 +157,32 @@ export default function Users() { 用户名 - setEditingUser({...editingUser, name: e.target.value})} + onChange={(e) => setEditingUser({ ...editingUser, name: e.target.value })} /> 邮箱地址 - setEditingUser({...editingUser, email: e.target.value})} + onChange={(e) => setEditingUser({ ...editingUser, email: e.target.value })} /> 角色权限 - setEditingUser({...editingUser, role: e.target.value as UserData["role"]})} + onChange={(e) => setEditingUser({ ...editingUser, role: e.target.value as UserData["role"] })} > Admin Auditor @@ -182,13 +191,13 @@ export default function Users() { - setIsModalOpen(false)} className="px-4 py-2 text-sm font-medium text-gray-400 hover:text-white transition-colors" > 取消 - diff --git a/src/pages/WorkflowEditor.tsx b/src/pages/WorkflowEditor.tsx index 5f5ba465..5c6c6c94 100644 --- a/src/pages/WorkflowEditor.tsx +++ b/src/pages/WorkflowEditor.tsx @@ -1,11 +1,4 @@ -import React, { - useState, - useCallback, - memo, - useEffect, - useMemo, - useRef, -} from "react"; +import React, { useState, useCallback, memo, useEffect, useMemo, useRef } from "react"; import { Logo } from "../components/Logo"; import ReactFlow, { addEdge, @@ -58,21 +51,12 @@ import { Star, Users, } from "lucide-react"; -import { - useNavigate, - useSearchParams, - useParams, - useLocation, -} from "react-router-dom"; +import { useNavigate, useSearchParams, useParams, useLocation } from "react-router-dom"; import { useTimeZone } from "../context/TimeZoneContext"; import { useUser } from "../context/UserContext"; import { cn } from "../lib/utils"; import { formatClockTime, formatCompactDateTime } from "../lib/datetime"; -import { - buildDataAssetsPath, - DATA_ASSET_PACKAGES_TAB, - DATA_ASSET_SOURCE_TAB, -} from "../lib/data-assets.js"; +import { buildDataAssetsPath, DATA_ASSET_PACKAGES_TAB, DATA_ASSET_SOURCE_TAB } from "../lib/data-assets.js"; import { decorateWorkflowEdges, decorateWorkflowNodes, @@ -151,25 +135,25 @@ const OperatorNode = memo(({ data, selected }: any) => { ? "border-blue-400 shadow-[0_0_24px_rgba(59,130,246,0.28)] animate-node-flash z-10" : executionState === "cancelled" ? "border-slate-400 shadow-[0_0_14px_rgba(148,163,184,0.16)]" - : executionState === "waiting_for_audit" - ? "border-amber-400 shadow-[0_0_18px_rgba(245,158,11,0.2)] z-10" - : executionState === "completed" - ? "border-emerald-400 shadow-[0_0_18px_rgba(52,211,153,0.16)]" - : executionState === "failed" - ? "border-red-400 shadow-[0_0_18px_rgba(248,113,113,0.18)]" - : ""; + : executionState === "waiting_for_audit" + ? "border-amber-400 shadow-[0_0_18px_rgba(245,158,11,0.2)] z-10" + : executionState === "completed" + ? "border-emerald-400 shadow-[0_0_18px_rgba(52,211,153,0.16)]" + : executionState === "failed" + ? "border-red-400 shadow-[0_0_18px_rgba(248,113,113,0.18)]" + : ""; const statusLabel = executionState === "running" ? "运行中" : executionState === "cancelled" ? "已取消" - : executionState === "waiting_for_audit" - ? "待审核" - : executionState === "completed" - ? "已完成" - : executionState === "failed" - ? "失败" - : ""; + : executionState === "waiting_for_audit" + ? "待审核" + : executionState === "completed" + ? "已完成" + : executionState === "failed" + ? "失败" + : ""; const getPortColor = (type: string) => { switch (type) { @@ -198,16 +182,11 @@ const OperatorNode = memo(({ data, selected }: any) => { {executionState === "running" ? ( @@ -228,20 +207,13 @@ const OperatorNode = memo(({ data, selected }: any) => { {(() => { - if (data.label.includes("导出")) - return ; - if (data.label.includes("合并")) - return ; - if (data.label.includes("交集")) - return ; - if (data.label.includes("分配")) - return ; - if (data.label.includes("分割")) - return ; - if (data.label.includes("标注")) - return ; - if (data.label.includes("扫描")) - return ; + if (data.label.includes("导出")) return ; + if (data.label.includes("合并")) return ; + if (data.label.includes("交集")) return ; + if (data.label.includes("分配")) return ; + if (data.label.includes("分割")) return ; + if (data.label.includes("标注")) return ; + if (data.label.includes("扫描")) return ; switch (data.category) { case "IO": return ; @@ -258,58 +230,39 @@ const OperatorNode = memo(({ data, selected }: any) => { } })()} - - {data.category} - + {data.category} {statusLabel && ( {statusLabel} )} - - {data.label} - + {data.label} {/* Input Ports Section */} {(data.inputs || []).map((port: any, i: number) => ( - + - - {port.name} - - - {port.type} - + {port.name} + {port.type} ))} @@ -318,26 +271,16 @@ const OperatorNode = memo(({ data, selected }: any) => { {/* Output Ports Section */} {(data.outputs || []).map((port: any, i: number) => ( - + - - {port.name} - - - {port.type} - + {port.name} + {port.type} ))} @@ -397,20 +340,22 @@ function isOssNode(node: Node | null | undefined) { function isMongoWriteNode(node: Node | null | undefined) { return Boolean( node?.data?.label?.includes("MongoDB") || - String(node?.data?.label || "").toLowerCase().includes("mongo"), + String(node?.data?.label || "") + .toLowerCase() + .includes("mongo"), ); } function getNodeHyperparamValue(node: Node | null | undefined, key: string) { - const hyperparams = Array.isArray(node?.data?.hyperparams) - ? node.data.hyperparams - : []; + const hyperparams = Array.isArray(node?.data?.hyperparams) ? node.data.hyperparams : []; const match = hyperparams.find((item: any) => item?.key === key); return typeof match?.value === "string" ? match.value.trim() : ""; } function normalizeStoragePrefix(value: string) { - return String(value || "").trim().replace(/^\/+|\/+$/g, ""); + return String(value || "") + .trim() + .replace(/^\/+|\/+$/g, ""); } function buildBosSourcePath(bucket: string, prefix: string) { @@ -419,16 +364,10 @@ function buildBosSourcePath(bucket: string, prefix: string) { return ""; } const normalizedPrefix = normalizeStoragePrefix(prefix); - return normalizedPrefix - ? `bos://${normalizedBucket}/${normalizedPrefix}` - : `bos://${normalizedBucket}`; + return normalizedPrefix ? `bos://${normalizedBucket}/${normalizedPrefix}` : `bos://${normalizedBucket}`; } -function findNodePort( - node: Node | null | undefined, - direction: "inputs" | "outputs", - handleId: string, -) { +function findNodePort(node: Node | null | undefined, direction: "inputs" | "outputs", handleId: string) { const ports = Array.isArray(node?.data?.[direction]) ? node.data[direction] : []; return ( ports.find((port: any) => String(port?.id || "").trim() === handleId) || @@ -441,9 +380,7 @@ function upsertNodeHyperparams( hyperparams: Array<{ key?: string; value?: string; [key: string]: any }> | undefined, updates: Record, ) { - const next = Array.isArray(hyperparams) - ? hyperparams.map((item) => ({ ...item })) - : []; + const next = Array.isArray(hyperparams) ? hyperparams.map((item) => ({ ...item })) : []; const indexByKey = new Map(); next.forEach((item, index) => { if (typeof item?.key === "string" && item.key.trim()) { @@ -470,7 +407,9 @@ function upsertNodeHyperparams( } function normalizeWorkflowEnvKey(value: string | undefined) { - return String(value || "").trim().toUpperCase(); + return String(value || "") + .trim() + .toUpperCase(); } function duplicateWorkflowEnvKeys( @@ -518,8 +457,7 @@ export default function WorkflowEditor() { const isTemplate = searchParams.get("type") === "template"; const requestedRunId = searchParams.get("runId")?.trim() || ""; const requestedFocusNodeId = searchParams.get("focusNodeId")?.trim() || ""; - const requestedOpenConfigPanel = - searchParams.get("openConfigPanel") === "true"; + const requestedOpenConfigPanel = searchParams.get("openConfigPanel") === "true"; const canManage = role === "admin" || role === "operator"; @@ -528,9 +466,7 @@ export default function WorkflowEditor() { const [nodes, setNodes, onNodesChange] = useNodesState(initialNodesData); const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdgesData); - const [entity, setEntity] = useState( - null, - ); + const [entity, setEntity] = useState(null); const [operators, setOperators] = useState([]); const [operatorSearchQuery, setOperatorSearchQuery] = useState(""); const [selectedNode, setSelectedNode] = useState(null); @@ -581,56 +517,35 @@ export default function WorkflowEditor() { const [sourceStateError, setSourceStateError] = useState(""); const [isResettingSourceState, setIsResettingSourceState] = useState(false); const [sourceStateRefreshKey, setSourceStateRefreshKey] = useState(0); - const workflowEntity = - !isTemplate && entity && "projectId" in entity ? (entity as Workflow) : null; - const workflowProjectId = - workflowEntity?.projectId || searchParams.get("projectId") || ""; + const workflowEntity = !isTemplate && entity && "projectId" in entity ? (entity as Workflow) : null; + const workflowProjectId = workflowEntity?.projectId || searchParams.get("projectId") || ""; const workflowConfigEntity = entity as Workflow | WorkflowTemplate | null; - const hasScanSourceNode = useMemo( - () => nodes.some((node) => isScanSourceNode(node)), - [nodes], - ); + const hasScanSourceNode = useMemo(() => nodes.some((node) => isScanSourceNode(node)), [nodes]); const isScanWorkflow = Boolean( - workflowConfigEntity?.kind === "scan" || - workflowConfigEntity?.scanConfig || - hasScanSourceNode, + workflowConfigEntity?.kind === "scan" || workflowConfigEntity?.scanConfig || hasScanSourceNode, ); const workflowAssetsPath = workflowEntity && !isTemplate ? buildDataAssetsPath({ - tab: isScanWorkflow - ? DATA_ASSET_SOURCE_TAB - : DATA_ASSET_PACKAGES_TAB, - projectId: - workflowProjectId, + tab: isScanWorkflow ? DATA_ASSET_SOURCE_TAB : DATA_ASSET_PACKAGES_TAB, + projectId: workflowProjectId, workflowId: workflowEntity.id, workflowName: workflowEntity.name, runId: requestedRunId || workflowEntity.lastRunId || "", }) : ""; const isStreaming = workflowConfigEntity?.type === "streaming"; - const workflowSchedule = normalizeWorkflowSchedule( - workflowConfigEntity?.schedule || {}, - ); - const workflowScheduleMode = - effectiveWorkflowScheduleMode(workflowConfigEntity?.schedule) || - "interval_seconds"; + const workflowSchedule = normalizeWorkflowSchedule(workflowConfigEntity?.schedule || {}); + const workflowScheduleMode = effectiveWorkflowScheduleMode(workflowConfigEntity?.schedule) || "interval_seconds"; const standardTriggerMode = - isStreaming && isWorkflowScheduleEnabled(workflowConfigEntity?.schedule) - ? "scheduled" - : "manual"; + isStreaming && isWorkflowScheduleEnabled(workflowConfigEntity?.schedule) ? "scheduled" : "manual"; const scanTriggerMode = - workflowConfigEntity?.scanConfig?.enabled && - isWorkflowScheduleEnabled(workflowConfigEntity?.schedule) + workflowConfigEntity?.scanConfig?.enabled && isWorkflowScheduleEnabled(workflowConfigEntity?.schedule) ? "scheduled" : "manual"; - const scheduledHistoryEnabled = - Boolean(workflowEntity) && isWorkflowScheduleEnabled(workflowConfigEntity?.schedule); + const scheduledHistoryEnabled = Boolean(workflowEntity) && isWorkflowScheduleEnabled(workflowConfigEntity?.schedule); const workflowLevelHyperparams = useMemo( - () => - Array.isArray(workflowConfigEntity?.hyperparams) - ? workflowConfigEntity.hyperparams - : [], + () => (Array.isArray(workflowConfigEntity?.hyperparams) ? workflowConfigEntity.hyperparams : []), [workflowConfigEntity?.hyperparams], ); const workflowLevelEnvDuplicates = useMemo( @@ -639,21 +554,17 @@ export default function WorkflowEditor() { ); const activeRunStatus = useMemo(() => getRunDisplayStatus(activeRun), [activeRun]); const activeRunInFlight = isRunInFlight(activeRun); - const hydrateLoadedEntity = useCallback( - (loaded: Workflow | WorkflowTemplate) => { - if (!loaded.nodes?.some((node) => isScanSourceNode(node)) || loaded.scanConfig) { - return loaded; - } - return (applyScanConfigPatchToWorkflow(loaded, { - enabled: - Boolean(loaded.scanConfig?.enabled) || - (loaded.type === "streaming" && - isWorkflowScheduleEnabled(loaded.schedule)), - ...normalizeWorkflowSchedule(loaded.schedule || {}), - }) ?? loaded) as Workflow | WorkflowTemplate; - }, - [], - ); + const hydrateLoadedEntity = useCallback((loaded: Workflow | WorkflowTemplate) => { + if (!loaded.nodes?.some((node) => isScanSourceNode(node)) || loaded.scanConfig) { + return loaded; + } + return (applyScanConfigPatchToWorkflow(loaded, { + enabled: + Boolean(loaded.scanConfig?.enabled) || + (loaded.type === "streaming" && isWorkflowScheduleEnabled(loaded.schedule)), + ...normalizeWorkflowSchedule(loaded.schedule || {}), + }) ?? loaded) as Workflow | WorkflowTemplate; + }, []); useEffect(() => { if (!activeRunInFlight) { setRunStopPending(""); @@ -664,10 +575,7 @@ export default function WorkflowEditor() { workflowStatus: workflowEntity?.status, activeRunStatus, }); - const inputConnectionConflicts = useMemo( - () => findInputConnectionConflicts(edges), - [edges], - ); + const inputConnectionConflicts = useMemo(() => findInputConnectionConflicts(edges), [edges]); const hasInputConnectionConflicts = inputConnectionConflicts.length > 0; const prepareEntityForPersistence = useCallback( (draft: Workflow | WorkflowTemplate | null) => { @@ -686,8 +594,7 @@ export default function WorkflowEditor() { return applyScanConfigPatchToWorkflow(next, { enabled: Boolean(draft.scanConfig?.enabled) || - (draft.type === "streaming" && - isWorkflowScheduleEnabled(draft.schedule)), + (draft.type === "streaming" && isWorkflowScheduleEnabled(draft.schedule)), ...normalizeWorkflowSchedule(draft.schedule || {}), }) as Workflow | WorkflowTemplate; }, @@ -714,21 +621,19 @@ export default function WorkflowEditor() { reason: "invalidConnections", } : !baseRunAction.disabled && !scanWorkflowConfigReady - ? { - disabled: true, - label: "请先配置扫描源", - reason: "scanConfig", - } - : baseRunAction; + ? { + disabled: true, + label: "请先配置扫描源", + reason: "scanConfig", + } + : baseRunAction; useEffect(() => { if (!id) return; const loader = isTemplate ? templatesApi.get(id) : workflowsApi.get(id); loader .then((loaded) => { - const hydrated = hydrateLoadedEntity( - loaded as Workflow | WorkflowTemplate, - ); + const hydrated = hydrateLoadedEntity(loaded as Workflow | WorkflowTemplate); setEntity(hydrated); if (hydrated.nodes?.length) { setNodes(hydrated.nodes as any); @@ -763,10 +668,7 @@ export default function WorkflowEditor() { firstField.select(); return; } - if ( - firstField instanceof HTMLSelectElement || - firstField instanceof HTMLTextAreaElement - ) { + if (firstField instanceof HTMLSelectElement || firstField instanceof HTMLTextAreaElement) { firstField.focus(); return; } @@ -779,11 +681,7 @@ export default function WorkflowEditor() { }, []); useEffect(() => { - if ( - autoFocusHandledRef.current || - !requestedFocusNodeId || - nodes.length === 0 - ) { + if (autoFocusHandledRef.current || !requestedFocusNodeId || nodes.length === 0) { return; } const targetNode = nodes.find((node) => node.id === requestedFocusNodeId); @@ -801,14 +699,7 @@ export default function WorkflowEditor() { nextParams.delete("focusNodeId"); nextParams.delete("openConfigPanel"); setSearchParams(nextParams, { replace: true }); - }, [ - focusNodeConfigInput, - nodes, - requestedFocusNodeId, - requestedOpenConfigPanel, - searchParams, - setSearchParams, - ]); + }, [focusNodeConfigInput, nodes, requestedFocusNodeId, requestedOpenConfigPanel, searchParams, setSearchParams]); useEffect(() => { if (!selectedEdgeId) { @@ -831,9 +722,7 @@ export default function WorkflowEditor() { .catch((error) => { console.error("Failed to load storage connections", error); setStorageConnections([]); - setStorageConnectionsError( - error instanceof Error ? error.message : "加载存储连接失败", - ); + setStorageConnectionsError(error instanceof Error ? error.message : "加载存储连接失败"); }) .finally(() => { setIsStorageConnectionsLoading(false); @@ -855,9 +744,7 @@ export default function WorkflowEditor() { .catch((error) => { console.error("Failed to load mongo connections", error); setMongoConnections([]); - setMongoConnectionsError( - error instanceof Error ? error.message : "加载 MongoDB 连接失败", - ); + setMongoConnectionsError(error instanceof Error ? error.message : "加载 MongoDB 连接失败"); }) .finally(() => { setIsMongoConnectionsLoading(false); @@ -873,51 +760,35 @@ export default function WorkflowEditor() { if (!normalizedOperatorSearch) { return true; } - return [ - operator.name, - operator.description, - operator.category, - operator.type, - ] + return [operator.name, operator.description, operator.category, operator.type] .filter(Boolean) .some((value) => value.toLowerCase().includes(normalizedOperatorSearch)); }); - const operatorLibrarySections = useMemo( - () => getOperatorLibrarySections(filteredOperators), - [filteredOperators], - ); + const operatorLibrarySections = useMemo(() => getOperatorLibrarySections(filteredOperators), [filteredOperators]); - const displayNodes = useMemo( - () => decorateWorkflowNodes(nodes, activeRun), - [nodes, activeRun], - ); - const displayEdges = useMemo( - () => { - const nodeLabelById = new Map( - nodes.map((node) => [node.id, node.data?.label || node.id]), - ); - return decorateWorkflowEdges(edges, nodes, activeRun).map((edge) => { - const sourceLabel = nodeLabelById.get(edge.source) || edge.source; - const targetLabel = nodeLabelById.get(edge.target) || edge.target; - const baseEdge = { - ...edge, - ariaLabel: `${sourceLabel} 到 ${targetLabel} 连线`, - }; - if (edge.id !== selectedEdgeId) { - return baseEdge; - } - return { - ...baseEdge, - style: { - ...edge.style, - strokeWidth: Math.max(Number(edge.style?.strokeWidth || 1.5), 3.5), - filter: "drop-shadow(0 0 8px rgba(96,165,250,0.45))", - }, - }; - }); - }, - [activeRun, edges, nodes, selectedEdgeId], - ); + const displayNodes = useMemo(() => decorateWorkflowNodes(nodes, activeRun), [nodes, activeRun]); + const displayEdges = useMemo(() => { + const nodeLabelById = new Map(nodes.map((node) => [node.id, node.data?.label || node.id])); + return decorateWorkflowEdges(edges, nodes, activeRun).map((edge) => { + const sourceLabel = nodeLabelById.get(edge.source) || edge.source; + const targetLabel = nodeLabelById.get(edge.target) || edge.target; + const baseEdge = { + ...edge, + ariaLabel: `${sourceLabel} 到 ${targetLabel} 连线`, + }; + if (edge.id !== selectedEdgeId) { + return baseEdge; + } + return { + ...baseEdge, + style: { + ...edge.style, + strokeWidth: Math.max(Number(edge.style?.strokeWidth || 1.5), 3.5), + filter: "drop-shadow(0 0 8px rgba(96,165,250,0.45))", + }, + }; + }); + }, [activeRun, edges, nodes, selectedEdgeId]); const selectedEdge = useMemo( () => displayEdges.find((edge) => edge.id === selectedEdgeId) || @@ -944,8 +815,7 @@ export default function WorkflowEditor() { () => getEdgeOutputArtifacts(selectedEdge, activeRun, nodes), [activeRun, nodes, selectedEdge], ); - const selectedEdgeExecutionState = - String(selectedEdge?.data?.executionState || "").trim() || "idle"; + const selectedEdgeExecutionState = String(selectedEdge?.data?.executionState || "").trim() || "idle"; const selectedEdgeArtifact = useMemo( () => selectedEdgeArtifacts.find((artifact) => artifact.id === selectedEdgeArtifactId) || @@ -958,21 +828,15 @@ export default function WorkflowEditor() { setSelectedEdgeArtifactId(""); return; } - if ( - selectedEdgeArtifactId && - selectedEdgeArtifacts.some((artifact) => artifact.id === selectedEdgeArtifactId) - ) { + if (selectedEdgeArtifactId && selectedEdgeArtifacts.some((artifact) => artifact.id === selectedEdgeArtifactId)) { return; } setSelectedEdgeArtifactId(selectedEdgeArtifacts[0].id); }, [selectedEdge, selectedEdgeArtifactId, selectedEdgeArtifacts]); - const selectedEdgeSourceLabel = - selectedEdgeSourceNode?.data?.label || selectedEdge?.source || "上游节点"; - const selectedEdgeTargetLabel = - selectedEdgeTargetNode?.data?.label || selectedEdge?.target || "下游节点"; + const selectedEdgeSourceLabel = selectedEdgeSourceNode?.data?.label || selectedEdge?.source || "上游节点"; + const selectedEdgeTargetLabel = selectedEdgeTargetNode?.data?.label || selectedEdge?.target || "下游节点"; const selectedEdgePortLabel = - String(selectedEdgeOutputPort?.name || selectedEdge?.sourceHandle || "").trim() || - "默认输出"; + String(selectedEdgeOutputPort?.name || selectedEdge?.sourceHandle || "").trim() || "默认输出"; const selectedEdgeEmptyStateMessage = useMemo(() => { if (!selectedEdge) { return ""; @@ -995,21 +859,12 @@ export default function WorkflowEditor() { return "当前运行还没有经过这条连线,待上游节点执行并产出数据后,这里会显示该线的输出文件。"; }, [activeRun?.id, selectedEdge, selectedEdgeExecutionState]); const selectedNodeExecution = useMemo( - () => - activeRun?.nodeExecutions?.find( - (execution) => execution.nodeId === selectedNode?.id, - ) || null, + () => activeRun?.nodeExecutions?.find((execution) => execution.nodeId === selectedNode?.id) || null, [activeRun?.nodeExecutions, selectedNode?.id], ); - const selectedNodeExecutionState = getNodeExecutionState( - activeRun, - selectedNode?.id, - ); + const selectedNodeExecutionState = getNodeExecutionState(activeRun, selectedNode?.id); const isSelectedScanSourceNode = - Boolean(workflowEntity) && - !isTemplate && - isScanWorkflow && - isScanSourceNode(selectedNode); + Boolean(workflowEntity) && !isTemplate && isScanWorkflow && isScanSourceNode(selectedNode); const refreshSourceState = useCallback(() => { setSourceStateRefreshKey((current) => current + 1); }, []); @@ -1018,16 +873,10 @@ export default function WorkflowEditor() { if (!connectionId) { return null; } - return ( - storageConnections.find((item) => item.id === connectionId) || null - ); + return storageConnections.find((item) => item.id === connectionId) || null; }, [storageConnections, workflowConfigEntity?.scanConfig?.connectionId]); const selectedNodeStorageScope = - isScanWorkflow && isScanSourceNode(selectedNode) - ? "scan" - : isOssNode(selectedNode) - ? "node" - : null; + isScanWorkflow && isScanSourceNode(selectedNode) ? "scan" : isOssNode(selectedNode) ? "node" : null; const nodeStorageConnection = useMemo(() => { const connectionId = String(selectedNode?.data?.connectionId || "").trim(); if (!connectionId) { @@ -1035,18 +884,12 @@ export default function WorkflowEditor() { } return storageConnections.find((item) => item.id === connectionId) || null; }, [selectedNode?.data?.connectionId, storageConnections]); - const selectedNodeMongoConnectionId = getNodeHyperparamValue( - selectedNode, - "MONGO_CONNECTION_ID", - ); + const selectedNodeMongoConnectionId = getNodeHyperparamValue(selectedNode, "MONGO_CONNECTION_ID"); const selectedNodeMongoConnection = useMemo(() => { if (!selectedNodeMongoConnectionId) { return null; } - return ( - mongoConnections.find((item) => item.id === selectedNodeMongoConnectionId) || - null - ); + return mongoConnections.find((item) => item.id === selectedNodeMongoConnectionId) || null; }, [mongoConnections, selectedNodeMongoConnectionId]); const shouldIncludeScheduledRunTimestamps = useMemo(() => { if (activeRun?.id) { @@ -1056,13 +899,13 @@ export default function WorkflowEditor() { }, [activeRun?.id, activeRun?.trigger, scheduledHistoryEnabled]); const selectedNodeEnvRows = useMemo(() => { const systemRows = - selectedNode?.type === "operator" && shouldIncludeScheduledRunTimestamps - ? buildWorkflowSystemEnvVarsPreview({ - workflowLastRunAt: workflowEntity?.lastRunAt || "", - run: activeRun, - includePrevious: true, - includeCurrent: true, - }) + selectedNode?.type === "operator" && shouldIncludeScheduledRunTimestamps + ? buildWorkflowSystemEnvVarsPreview({ + workflowLastRunAt: workflowEntity?.lastRunAt || "", + run: activeRun, + includePrevious: true, + includeCurrent: true, + }) : []; return buildSelectedNodeEnvRows({ nodeHyperparams: selectedNode?.data?.hyperparams, @@ -1072,25 +915,15 @@ export default function WorkflowEditor() { }, [ activeRun, selectedNode?.data?.hyperparams, - selectedNode?.type, - shouldIncludeScheduledRunTimestamps, - workflowLevelHyperparams, - workflowEntity?.lastRunAt, - ]); - const selectedNodeIds = useMemo( - () => nodes.filter((node) => node.selected).map((node) => node.id), - [nodes], - ); - const selectedEdgeIds = useMemo( - () => edges.filter((edge) => edge.selected).map((edge) => edge.id), - [edges], - ); - const hasCanvasSelection = - selectedNodeIds.length > 0 || selectedEdgeIds.length > 0; - const activeRunCurrentNodeLabel = useMemo( - () => getCurrentNodeLabel(activeRun, nodes), - [activeRun, nodes], - ); + selectedNode?.type, + shouldIncludeScheduledRunTimestamps, + workflowLevelHyperparams, + workflowEntity?.lastRunAt, + ]); + const selectedNodeIds = useMemo(() => nodes.filter((node) => node.selected).map((node) => node.id), [nodes]); + const selectedEdgeIds = useMemo(() => edges.filter((edge) => edge.selected).map((edge) => edge.id), [edges]); + const hasCanvasSelection = selectedNodeIds.length > 0 || selectedEdgeIds.length > 0; + const activeRunCurrentNodeLabel = useMemo(() => getCurrentNodeLabel(activeRun, nodes), [activeRun, nodes]); useEffect(() => { if (!id || isTemplate || !workflowEntity?.id || !selectedNode?.id || !isSelectedScanSourceNode) { @@ -1116,9 +949,7 @@ export default function WorkflowEditor() { } console.error("Failed to load source state", error); setSourceState(null); - setSourceStateError( - error instanceof Error ? error.message : "加载扫描状态失败", - ); + setSourceStateError(error instanceof Error ? error.message : "加载扫描状态失败"); }) .finally(() => { if (!cancelled) { @@ -1142,20 +973,10 @@ export default function WorkflowEditor() { if (!isSelectedScanSourceNode || !activeRun?.id) { return; } - if ( - activeRunStatus === "completed" || - activeRunStatus === "failed" || - activeRunStatus === "cancelled" - ) { + if (activeRunStatus === "completed" || activeRunStatus === "failed" || activeRunStatus === "cancelled") { refreshSourceState(); } - }, [ - activeRun?.endedAt, - activeRun?.id, - activeRunStatus, - isSelectedScanSourceNode, - refreshSourceState, - ]); + }, [activeRun?.endedAt, activeRun?.id, activeRunStatus, isSelectedScanSourceNode, refreshSourceState]); useEffect(() => { setActiveRun(null); @@ -1179,10 +1000,7 @@ export default function WorkflowEditor() { const handlePointerDown = (event: MouseEvent) => { const target = event.target as HTMLElement | null; - if ( - workflowSettingsPanelRef.current?.contains(target) || - workflowSettingsTriggerRef.current?.contains(target) - ) { + if (workflowSettingsPanelRef.current?.contains(target) || workflowSettingsTriggerRef.current?.contains(target)) { return; } setIsWorkflowSettingsOpen(false); @@ -1220,9 +1038,7 @@ export default function WorkflowEditor() { return; } console.error("Failed to restore workflow run context", error); - setActiveRunError( - error instanceof Error ? error.message : "无法恢复当前工作流运行状态", - ); + setActiveRunError(error instanceof Error ? error.message : "无法恢复当前工作流运行状态"); }); return () => { @@ -1256,9 +1072,7 @@ export default function WorkflowEditor() { setWorkflowRuns(items); } catch (error) { console.error("Failed to load workflow runs", error); - setWorkflowRunsError( - error instanceof Error ? error.message : "无法加载周期运行记录", - ); + setWorkflowRunsError(error instanceof Error ? error.message : "无法加载周期运行记录"); } finally { setIsWorkflowRunsLoading(false); } @@ -1279,9 +1093,7 @@ export default function WorkflowEditor() { updateRunSearchParam(run.id); } catch (error) { console.error("Failed to load workflow run", error); - setActiveRunError( - error instanceof Error ? error.message : "无法加载该次运行详情", - ); + setActiveRunError(error instanceof Error ? error.message : "无法加载该次运行详情"); } }, [id, updateRunSearchParam], @@ -1303,12 +1115,7 @@ export default function WorkflowEditor() { let timer = 0; let failureCount = 0; - const baseDelay = - activeRunStatus === "waiting_for_audit" - ? 12000 - : activeRunStatus === "running" - ? 8000 - : 10000; + const baseDelay = activeRunStatus === "waiting_for_audit" ? 12000 : activeRunStatus === "running" ? 8000 : 10000; const refreshRun = async () => { try { @@ -1324,16 +1131,11 @@ export default function WorkflowEditor() { return; } console.error("Failed to refresh workflow run status", error); - setActiveRunError( - error instanceof Error ? error.message : "无法刷新当前工作流运行状态", - ); + setActiveRunError(error instanceof Error ? error.message : "无法刷新当前工作流运行状态"); failureCount += 1; } finally { if (!cancelled) { - const nextDelay = Math.min( - baseDelay * Math.max(1, 2 ** failureCount), - 30000, - ); + const nextDelay = Math.min(baseDelay * Math.max(1, 2 ** failureCount), 30000); timer = window.setTimeout(refreshRun, nextDelay); } } @@ -1379,9 +1181,7 @@ export default function WorkflowEditor() { } } catch (error) { console.error("Failed to enqueue workflow run", error); - setActiveRunError( - error instanceof Error ? error.message : "工作流启动失败,请稍后重试", - ); + setActiveRunError(error instanceof Error ? error.message : "工作流启动失败,请稍后重试"); } finally { setIsExecuting(false); } @@ -1408,9 +1208,7 @@ export default function WorkflowEditor() { setActiveRun(stopped); } catch (error) { console.error("Failed to request graceful stop", error); - setActiveRunError( - error instanceof Error ? error.message : "停止工作流失败,请稍后重试", - ); + setActiveRunError(error instanceof Error ? error.message : "停止工作流失败,请稍后重试"); setRunStopPending(""); } }, [activeRun?.id, runStopPending]); @@ -1426,9 +1224,7 @@ export default function WorkflowEditor() { setActiveRun(stopped); } catch (error) { console.error("Failed to force stop run", error); - setActiveRunError( - error instanceof Error ? error.message : "强制停止工作流失败,请稍后重试", - ); + setActiveRunError(error instanceof Error ? error.message : "强制停止工作流失败,请稍后重试"); setRunStopPending(""); } }, [activeRun?.id, runStopPending]); @@ -1450,20 +1246,11 @@ export default function WorkflowEditor() { } } catch (error) { console.error("Failed to rerun subtree", error); - setActiveRunError( - error instanceof Error ? error.message : "创建子链路重跑失败,请稍后重试", - ); + setActiveRunError(error instanceof Error ? error.message : "创建子链路重跑失败,请稍后重试"); } finally { setRerunSubtreePendingNodeId(""); } - }, [ - activeRun?.id, - activeRun?.status, - loadWorkflowRuns, - scheduledHistoryEnabled, - selectedNode, - updateRunSearchParam, - ]); + }, [activeRun?.id, activeRun?.status, loadWorkflowRuns, scheduledHistoryEnabled, selectedNode, updateRunSearchParam]); const updateWorkflowSchedule = useCallback( (patch: Partial) => { @@ -1518,9 +1305,7 @@ export default function WorkflowEditor() { if (!previous) { return previous; } - const current = Array.isArray(previous.hyperparams) - ? previous.hyperparams.map((item) => ({ ...item })) - : []; + const current = Array.isArray(previous.hyperparams) ? previous.hyperparams.map((item) => ({ ...item })) : []; return { ...previous, hyperparams: updater(current), @@ -1531,10 +1316,7 @@ export default function WorkflowEditor() { ); const appendWorkflowHyperparam = useCallback(() => { - updateWorkflowHyperparams((current) => [ - ...current, - { key: "", value: "", description: "" }, - ]); + updateWorkflowHyperparams((current) => [...current, { key: "", value: "", description: "" }]); }, [updateWorkflowHyperparams]); const updateWorkflowHyperparamField = useCallback( @@ -1555,9 +1337,7 @@ export default function WorkflowEditor() { const removeWorkflowHyperparam = useCallback( (index: number) => { - updateWorkflowHyperparams((current) => - current.filter((_, itemIndex) => itemIndex !== index), - ); + updateWorkflowHyperparams((current) => current.filter((_, itemIndex) => itemIndex !== index)); }, [updateWorkflowHyperparams], ); @@ -1591,8 +1371,7 @@ export default function WorkflowEditor() { } return patched as Workflow | WorkflowTemplate; } - const nextType: WorkflowType = - mode === "scheduled" ? "streaming" : "batch"; + const nextType: WorkflowType = mode === "scheduled" ? "streaming" : "batch"; return { ...previous, type: nextType, @@ -1640,33 +1419,16 @@ export default function WorkflowEditor() { if (isReadOnly || !selectedNode || !isOssNode(selectedNode)) { return; } - const nextBucket = String( - patch.bucket ?? selectedNode.data.bucket ?? "", - ).trim(); - const nextPrefix = normalizeStoragePrefix( - String(patch.prefix ?? selectedNode.data.prefix ?? ""), - ); - const nextConnectionID = String( - patch.connectionId ?? selectedNode.data.connectionId ?? "", - ).trim(); - const matchedConnection = storageConnections.find( - (item) => item.id === nextConnectionID, - ); + const nextBucket = String(patch.bucket ?? selectedNode.data.bucket ?? "").trim(); + const nextPrefix = normalizeStoragePrefix(String(patch.prefix ?? selectedNode.data.prefix ?? "")); + const nextConnectionID = String(patch.connectionId ?? selectedNode.data.connectionId ?? "").trim(); + const matchedConnection = storageConnections.find((item) => item.id === nextConnectionID); const currentSourcePath = getNodeHyperparamValue(selectedNode, "SOURCE_PATH"); const derivedSourcePath = buildBosSourcePath(nextBucket, nextPrefix); - const currentDataSource = - getNodeHyperparamValue(selectedNode, "DATA_SOURCE") || "BOS"; - const existingEndpoint = - getNodeHyperparamValue(selectedNode, "BOS_ENDPOINT") || - DEFAULT_BOS_ENDPOINT; - const existingAccessKeyID = getNodeHyperparamValue( - selectedNode, - "BOS_ACCESS_KEY_ID", - ); - const existingSecretAccessKey = getNodeHyperparamValue( - selectedNode, - "BOS_SECRET_ACCESS_KEY", - ); + const currentDataSource = getNodeHyperparamValue(selectedNode, "DATA_SOURCE") || "BOS"; + const existingEndpoint = getNodeHyperparamValue(selectedNode, "BOS_ENDPOINT") || DEFAULT_BOS_ENDPOINT; + const existingAccessKeyID = getNodeHyperparamValue(selectedNode, "BOS_ACCESS_KEY_ID"); + const existingSecretAccessKey = getNodeHyperparamValue(selectedNode, "BOS_SECRET_ACCESS_KEY"); const nextData = { ...selectedNode.data, ...patch, @@ -1674,30 +1436,16 @@ export default function WorkflowEditor() { prefix: nextPrefix, connectionId: nextConnectionID, hyperparams: upsertNodeHyperparams(selectedNode.data.hyperparams, { - DATA_SOURCE: - nextConnectionID || nextBucket || nextPrefix - ? "BOS" - : currentDataSource, + DATA_SOURCE: nextConnectionID || nextBucket || nextPrefix ? "BOS" : currentDataSource, SOURCE_PATH: derivedSourcePath || currentSourcePath, - BOS_ENDPOINT: - (nextConnectionID - ? matchedConnection?.endpoint - : patch.endpoint) || existingEndpoint, + BOS_ENDPOINT: (nextConnectionID ? matchedConnection?.endpoint : patch.endpoint) || existingEndpoint, BOS_ACCESS_KEY_ID: nextConnectionID ? "" : existingAccessKeyID, - BOS_SECRET_ACCESS_KEY: nextConnectionID - ? "" - : existingSecretAccessKey, + BOS_SECRET_ACCESS_KEY: nextConnectionID ? "" : existingSecretAccessKey, }), }; - setNodes((nds) => - nds.map((node) => - node.id === selectedNode.id ? { ...node, data: nextData } : node, - ), - ); + setNodes((nds) => nds.map((node) => (node.id === selectedNode.id ? { ...node, data: nextData } : node))); setSelectedNode((previous) => - previous && previous.id === selectedNode.id - ? { ...previous, data: nextData } - : previous, + previous && previous.id === selectedNode.id ? { ...previous, data: nextData } : previous, ); }, [isReadOnly, selectedNode, setNodes, storageConnections], @@ -1713,10 +1461,7 @@ export default function WorkflowEditor() { const matched = storageConnections.find((item) => item.id === connectionId); updateScanWorkflowConfig({ connectionId, - endpoint: - connectionId - ? matched?.endpoint || DEFAULT_BOS_ENDPOINT - : DEFAULT_BOS_ENDPOINT, + endpoint: connectionId ? matched?.endpoint || DEFAULT_BOS_ENDPOINT : DEFAULT_BOS_ENDPOINT, accessKeyId: "", secretAccessKey: "", }); @@ -1759,17 +1504,13 @@ export default function WorkflowEditor() { setStorageConnections((previous) => [created, ...previous.filter((item) => item.id !== created.id)]); handleStorageConnectionSelect( created.id, - isOssNode(selectedNode) && !(isScanWorkflow && isScanSourceNode(selectedNode)) - ? "node" - : "scan", + isOssNode(selectedNode) && !(isScanWorkflow && isScanSourceNode(selectedNode)) ? "node" : "scan", ); setIsStorageConnectionFormOpen(false); resetStorageConnectionDraft(); } catch (error) { console.error("Failed to create storage connection", error); - setStorageConnectionsError( - error instanceof Error ? error.message : "创建存储连接失败", - ); + setStorageConnectionsError(error instanceof Error ? error.message : "创建存储连接失败"); } finally { setIsSavingStorageConnection(false); } @@ -1795,15 +1536,9 @@ export default function WorkflowEditor() { MONGO_CONNECTION_ID: connectionId, }), }; - setNodes((nds) => - nds.map((node) => - node.id === selectedNode.id ? { ...node, data: nextData } : node, - ), - ); + setNodes((nds) => nds.map((node) => (node.id === selectedNode.id ? { ...node, data: nextData } : node))); setSelectedNode((previous) => - previous && previous.id === selectedNode.id - ? { ...previous, data: nextData } - : previous, + previous && previous.id === selectedNode.id ? { ...previous, data: nextData } : previous, ); }, [isReadOnly, selectedNode, setNodes], @@ -1885,20 +1620,22 @@ export default function WorkflowEditor() { category: op.category, description: op.description, inputs: op.inputs, - outputs: op.outputs, - image: op.image, - hyperparams: op.hyperparams || [], - cpu: op.resources?.cpuLimit || "", - memory: op.resources?.memoryLimit || "", - gpu: op.resources?.gpuLimit || "", - }, + outputs: op.outputs, + image: op.image, + hyperparams: op.hyperparams || [], + cpu: op.resources?.cpuLimit || "", + memory: op.resources?.memoryLimit || "", + gpu: op.resources?.gpuLimit || "", + }, }; setNodes((currentNodes) => - currentNodes.map((node) => ({ ...node, selected: false })).concat({ - ...newNode, - selected: true, - }), + currentNodes + .map((node) => ({ ...node, selected: false })) + .concat({ + ...newNode, + selected: true, + }), ); if (String(op?.name || "").trim() === "BOS 增量扫描") { setEntity((previous) => @@ -1951,20 +1688,17 @@ export default function WorkflowEditor() { [canManage, isCanvasDragActive, isReadOnly], ); - const handleCanvasDragLeave = useCallback( - (event: React.DragEvent) => { - if (!reactFlowWrapperRef.current) { - setIsCanvasDragActive(false); - return; - } - const nextTarget = event.relatedTarget as globalThis.Node | null; - if (nextTarget && reactFlowWrapperRef.current.contains(nextTarget)) { - return; - } + const handleCanvasDragLeave = useCallback((event: React.DragEvent) => { + if (!reactFlowWrapperRef.current) { setIsCanvasDragActive(false); - }, - [], - ); + return; + } + const nextTarget = event.relatedTarget as globalThis.Node | null; + if (nextTarget && reactFlowWrapperRef.current.contains(nextTarget)) { + return; + } + setIsCanvasDragActive(false); + }, []); const handleCanvasDrop = useCallback( (event: React.DragEvent) => { @@ -1976,9 +1710,7 @@ export default function WorkflowEditor() { try { const payload = event.dataTransfer.getData(OPERATOR_DRAG_MIME); - const operator = payload - ? JSON.parse(payload) - : draggedOperatorRef.current; + const operator = payload ? JSON.parse(payload) : draggedOperatorRef.current; if (!operator) { return; } @@ -2001,46 +1733,30 @@ export default function WorkflowEditor() { const [favoriteStoragePaths, setFavoriteStoragePaths] = useState< Array<{ bucket: string; prefix: string; label: string }> >([]); - const [projectFavoriteStoragePathRecords, setProjectFavoriteStoragePathRecords] = - useState>([]); + const [projectFavoriteStoragePathRecords, setProjectFavoriteStoragePathRecords] = useState< + Array<{ scopeKey: string; bucket: string; prefix?: string; label?: string }> + >([]); const favoriteStorageMutationVersionRef = useRef(0); const projectFavoriteStorageMutationVersionRef = useRef(0); const [recentStoragePaths, setRecentStoragePaths] = useState< Array<{ bucket: string; prefix: string; label: string }> >([]); - const selectedNodeSourcePath = getNodeHyperparamValue( - selectedNode, - "SOURCE_PATH", - ); + const selectedNodeSourcePath = getNodeHyperparamValue(selectedNode, "SOURCE_PATH"); const selectedNodeConnectionId = selectedNodeStorageScope === "scan" ? workflowConfigEntity?.scanConfig?.connectionId?.trim() || "" : String(selectedNode?.data?.connectionId || "").trim(); - const selectedStorageConnection = - selectedNodeStorageScope === "scan" - ? scanStorageConnection - : nodeStorageConnection; - const canBrowseSelectedStorage = Boolean( - selectedNodeConnectionId || selectedNodeSourcePath, - ); + const selectedStorageConnection = selectedNodeStorageScope === "scan" ? scanStorageConnection : nodeStorageConnection; + const canBrowseSelectedStorage = Boolean(selectedNodeConnectionId || selectedNodeSourcePath); const selectedNodeBucket = - (selectedNodeStorageScope === "scan" - ? workflowConfigEntity?.scanConfig?.bucket - : selectedNode?.data?.bucket) || ""; + (selectedNodeStorageScope === "scan" ? workflowConfigEntity?.scanConfig?.bucket : selectedNode?.data?.bucket) || ""; const selectedNodePrefix = - (selectedNodeStorageScope === "scan" - ? workflowConfigEntity?.scanConfig?.prefix - : selectedNode?.data?.prefix) || ""; + (selectedNodeStorageScope === "scan" ? workflowConfigEntity?.scanConfig?.prefix : selectedNode?.data?.prefix) || ""; const selectedStoragePathKey = selectedNodeBucket ? `${selectedNodeBucket}/${normalizeStoragePrefix(selectedNodePrefix)}` : ""; const favoriteStoragePathKeys = useMemo( - () => - new Set( - favoriteStoragePaths.map( - (item) => `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`, - ), - ), + () => new Set(favoriteStoragePaths.map((item) => `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`)), [favoriteStoragePaths], ); const selectedStorageScopeKey = useMemo( @@ -2059,42 +1775,27 @@ export default function WorkflowEditor() { .map((item) => ({ bucket: item.bucket, prefix: item.prefix || "", - label: - item.label || - (item.prefix ? `${item.bucket}/${item.prefix}` : item.bucket), + label: item.label || (item.prefix ? `${item.bucket}/${item.prefix}` : item.bucket), })), [projectFavoriteStoragePathRecords, selectedStorageScopeKey], ); const projectFavoriteStoragePathKeys = useMemo( - () => - new Set( - projectFavoriteStoragePaths.map( - (item) => `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`, - ), - ), + () => new Set(projectFavoriteStoragePaths.map((item) => `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`)), [projectFavoriteStoragePaths], ); const visibleUserFavoriteStoragePaths = useMemo( - () => - filterRecentPathsAgainstFavorites( - favoriteStoragePaths, - projectFavoriteStoragePaths, - ), + () => filterRecentPathsAgainstFavorites(favoriteStoragePaths, projectFavoriteStoragePaths), [favoriteStoragePaths, projectFavoriteStoragePaths], ); const isCurrentStoragePathFavorite = Boolean( selectedStoragePathKey && favoriteStoragePathKeys.has(selectedStoragePathKey), ); const isCurrentProjectStoragePathFavorite = Boolean( - selectedStoragePathKey && - projectFavoriteStoragePathKeys.has(selectedStoragePathKey), + selectedStoragePathKey && projectFavoriteStoragePathKeys.has(selectedStoragePathKey), ); const visibleRecentStoragePaths = useMemo( () => - filterRecentPathsAgainstFavorites( - recentStoragePaths, - [...projectFavoriteStoragePaths, ...favoriteStoragePaths], - ), + filterRecentPathsAgainstFavorites(recentStoragePaths, [...projectFavoriteStoragePaths, ...favoriteStoragePaths]), [favoriteStoragePaths, projectFavoriteStoragePaths, recentStoragePaths], ); const selectedBrowseRootLabel = selectedNodeConnectionId @@ -2102,9 +1803,9 @@ export default function WorkflowEditor() { : selectedNodeSourcePath || buildBosSourcePath(selectedNodeBucket, selectedNodePrefix); const canBrowseStorageNode = Boolean( isOssNode(selectedNode) || - (isScanWorkflow && - isScanSourceNode(selectedNode) && - (workflowConfigEntity?.scanConfig?.dataSource || "BOS") === "BOS"), + (isScanWorkflow && + isScanSourceNode(selectedNode) && + (workflowConfigEntity?.scanConfig?.dataSource || "BOS") === "BOS"), ); const refreshRecentStoragePaths = useCallback(() => { setRecentStoragePaths( @@ -2164,37 +1865,24 @@ export default function WorkflowEditor() { usersApi .listStoragePathFavorites(currentUser.id) .then((remoteRecords) => { - if ( - cancelled || - loadVersion !== favoriteStorageMutationVersionRef.current - ) { + if (cancelled || loadVersion !== favoriteStorageMutationVersionRef.current) { return; } const currentLocalRecords = listFavoriteStoragePathRecords(); - const mergedRecords = mergeFavoriteStoragePathRecords( - remoteRecords, - currentLocalRecords, - ); + const mergedRecords = mergeFavoriteStoragePathRecords(remoteRecords, currentLocalRecords); const normalizedRemote = normalizeFavoriteStoragePathRecords(remoteRecords); const normalizedMerged = replaceFavoriteStoragePathRecords(mergedRecords); refreshFavoriteStoragePathsRef.current(); - if ( - loadVersion !== favoriteStorageMutationVersionRef.current - ) { + if (loadVersion !== favoriteStorageMutationVersionRef.current) { return; } - if ( - JSON.stringify(normalizedMerged) === JSON.stringify(normalizedRemote) - ) { + if (JSON.stringify(normalizedMerged) === JSON.stringify(normalizedRemote)) { return; } usersApi .updateStoragePathFavorites(currentUser.id, normalizedMerged) .then((response) => { - if ( - cancelled || - loadVersion !== favoriteStorageMutationVersionRef.current - ) { + if (cancelled || loadVersion !== favoriteStorageMutationVersionRef.current) { return; } replaceFavoriteStoragePathRecords(response.items); @@ -2231,15 +1919,10 @@ export default function WorkflowEditor() { projectsApi .listStoragePathFavorites(workflowProjectId) .then((items) => { - if ( - cancelled || - loadVersion !== projectFavoriteStorageMutationVersionRef.current - ) { + if (cancelled || loadVersion !== projectFavoriteStorageMutationVersionRef.current) { return; } - setProjectFavoriteStoragePathRecords( - normalizeFavoriteStoragePathRecords(items), - ); + setProjectFavoriteStoragePathRecords(normalizeFavoriteStoragePathRecords(items)); }) .catch((error) => { if (cancelled) { @@ -2284,12 +1967,7 @@ export default function WorkflowEditor() { } rememberRecentStoragePath(bucket, prefix); }, - [ - rememberRecentStoragePath, - selectedNodeStorageScope, - updateOssNodeConfig, - updateScanWorkflowConfig, - ], + [rememberRecentStoragePath, selectedNodeStorageScope, updateOssNodeConfig, updateScanWorkflowConfig], ); const applyFavoriteStoragePath = useCallback( @@ -2301,12 +1979,7 @@ export default function WorkflowEditor() { } rememberRecentStoragePath(bucket, prefix); }, - [ - rememberRecentStoragePath, - selectedNodeStorageScope, - updateOssNodeConfig, - updateScanWorkflowConfig, - ], + [rememberRecentStoragePath, selectedNodeStorageScope, updateOssNodeConfig, updateScanWorkflowConfig], ); const toggleCurrentStoragePathFavorite = useCallback(async () => { @@ -2316,23 +1989,17 @@ export default function WorkflowEditor() { sourcePath: selectedNodeSourcePath, }; const previousRecords = listFavoriteStoragePathRecords(); - const nextScopeItems = toggleFavoriteStoragePath( - target, - { - bucket: selectedNodeBucket, - prefix: selectedNodePrefix, - }, - ); + const nextScopeItems = toggleFavoriteStoragePath(target, { + bucket: selectedNodeBucket, + prefix: selectedNodePrefix, + }); setFavoriteStoragePaths(nextScopeItems); if (!currentUser?.id) { return; } try { const nextRecords = listFavoriteStoragePathRecords(); - const response = await usersApi.updateStoragePathFavorites( - currentUser.id, - nextRecords, - ); + const response = await usersApi.updateStoragePathFavorites(currentUser.id, nextRecords); replaceFavoriteStoragePathRecords(response.items); refreshFavoriteStoragePaths(); } catch (error) { @@ -2359,10 +2026,9 @@ export default function WorkflowEditor() { scopeKey: selectedStorageScopeKey, bucket: selectedNodeBucket, prefix: normalizeStoragePrefix(selectedNodePrefix), - label: - normalizeStoragePrefix(selectedNodePrefix) - ? `${selectedNodeBucket}/${normalizeStoragePrefix(selectedNodePrefix)}` - : selectedNodeBucket, + label: normalizeStoragePrefix(selectedNodePrefix) + ? `${selectedNodeBucket}/${normalizeStoragePrefix(selectedNodePrefix)}` + : selectedNodeBucket, }; const previousRecords = projectFavoriteStoragePathRecords; const nextRecords = isCurrentProjectStoragePathFavorite @@ -2377,13 +2043,8 @@ export default function WorkflowEditor() { : normalizeFavoriteStoragePathRecords([record, ...previousRecords]); setProjectFavoriteStoragePathRecords(nextRecords); try { - const response = await projectsApi.updateStoragePathFavorites( - workflowProjectId, - nextRecords, - ); - setProjectFavoriteStoragePathRecords( - normalizeFavoriteStoragePathRecords(response.items), - ); + const response = await projectsApi.updateStoragePathFavorites(workflowProjectId, nextRecords); + setProjectFavoriteStoragePathRecords(normalizeFavoriteStoragePathRecords(response.items)); } catch (error) { console.error("Failed to save project storage favorites", error); setProjectFavoriteStoragePathRecords(previousRecords); @@ -2428,11 +2089,7 @@ export default function WorkflowEditor() { } console.error("Failed to load OSS buckets", error); setBuckets([]); - setOssBrowseError( - error instanceof Error - ? error.message - : "无法读取当前节点的 OSS 根目录", - ); + setOssBrowseError(error instanceof Error ? error.message : "无法读取当前节点的 OSS 根目录"); }); return () => { cancelled = true; @@ -2488,11 +2145,7 @@ export default function WorkflowEditor() { } console.error("Failed to load OSS objects", error); setOssObjects([]); - setOssBrowseError( - error instanceof Error - ? error.message - : "无法读取当前节点的 OSS 路径", - ); + setOssBrowseError(error instanceof Error ? error.message : "无法读取当前节点的 OSS 路径"); }) .finally(() => { if (!cancelled) { @@ -2531,15 +2184,9 @@ export default function WorkflowEditor() { } return stripScanWorkflowShell(previous) as Workflow | WorkflowTemplate; }); - setSelectedNode((previous) => - previous && result.removedNodeIds.includes(previous.id) ? null : previous, - ); - setSelectedEdgeId((previous) => - previous && result.removedEdgeIds.includes(previous) ? "" : previous, - ); - setCanvasNotice( - `已删除 ${result.removedNodeIds.length} 个节点和 ${result.removedEdgeIds.length} 条连线`, - ); + setSelectedNode((previous) => (previous && result.removedNodeIds.includes(previous.id) ? null : previous)); + setSelectedEdgeId((previous) => (previous && result.removedEdgeIds.includes(previous) ? "" : previous)); + setCanvasNotice(`已删除 ${result.removedNodeIds.length} 个节点和 ${result.removedEdgeIds.length} 条连线`); }, [edges, nodes, setEdges, setNodes]); useEffect(() => { @@ -2603,27 +2250,24 @@ export default function WorkflowEditor() { setSelectedEdgeId(""); }, []); - const onNodeDoubleClick = useCallback((_: any, node: Node) => { - setSelectedNode(node); - setSelectedEdgeId(""); - setIsConfigOpen(true); - focusNodeConfigInput(); - }, [focusNodeConfigInput]); + const onNodeDoubleClick = useCallback( + (_: any, node: Node) => { + setSelectedNode(node); + setSelectedEdgeId(""); + setIsConfigOpen(true); + focusNodeConfigInput(); + }, + [focusNodeConfigInput], + ); const updateNodeData = useCallback( (newData: any) => { if (isReadOnly || !selectedNode) return; setNodes((nds) => - nds.map((node) => - node.id === selectedNode.id - ? { ...node, data: { ...node.data, ...newData } } - : node, - ), - ); - setSelectedNode((prev) => - prev ? { ...prev, data: { ...prev.data, ...newData } } : null, + nds.map((node) => (node.id === selectedNode.id ? { ...node, data: { ...node.data, ...newData } } : node)), ); + setSelectedNode((prev) => (prev ? { ...prev, data: { ...prev.data, ...newData } } : null)); }, [isReadOnly, selectedNode, setNodes], ); @@ -2647,9 +2291,7 @@ export default function WorkflowEditor() { setCanvasNotice("已重置当前扫描源的增量状态"); } catch (error) { console.error("Failed to reset source state", error); - setSourceStateError( - error instanceof Error ? error.message : "重置扫描状态失败", - ); + setSourceStateError(error instanceof Error ? error.message : "重置扫描状态失败"); } finally { setIsResettingSourceState(false); } @@ -2675,13 +2317,8 @@ export default function WorkflowEditor() { } try { if (isTemplate) { - const payload = prepareEntityForPersistence( - entity as WorkflowTemplate, - ); - const updated = await templatesApi.update( - id, - payload as Partial, - ); + const payload = prepareEntityForPersistence(entity as WorkflowTemplate); + const updated = await templatesApi.update(id, payload as Partial); setEntity(updated); } else { const updated = await workflowsApi.update(id, { @@ -2692,7 +2329,16 @@ export default function WorkflowEditor() { } catch (error) { console.error("Failed to save workflow", error); } - }, [canManage, entity, hasInputConnectionConflicts, id, isReadOnly, isTemplate, prepareEntityForPersistence, workflowLevelEnvDuplicates]); + }, [ + canManage, + entity, + hasInputConnectionConflicts, + id, + isReadOnly, + isTemplate, + prepareEntityForPersistence, + workflowLevelEnvDuplicates, + ]); const openExportTemplateModal = useCallback(() => { if (hasInputConnectionConflicts) { @@ -2705,9 +2351,7 @@ export default function WorkflowEditor() { } setTemplateDraft({ name: `${entity?.name || "工作流"} 模板`, - description: - ("description" in (entity || {}) && entity?.description) || - "从工作流导出的模板", + description: ("description" in (entity || {}) && entity?.description) || "从工作流导出的模板", }); setIsExportTemplateOpen(true); }, [entity, hasInputConnectionConflicts, workflowLevelEnvDuplicates]); @@ -2723,9 +2367,7 @@ export default function WorkflowEditor() { try { const created = await templatesApi.create( buildTemplatePayload( - prepareEntityForPersistence( - entity as Workflow | WorkflowTemplate, - ) || { + prepareEntityForPersistence(entity as Workflow | WorkflowTemplate) || { ...(entity || {}), nodes, edges, @@ -2769,9 +2411,7 @@ export default function WorkflowEditor() { {entity?.name || "数据工作流"} {isReadOnly && } - - Drobodata 工作流编辑器 - + Drobodata 工作流编辑器 @@ -2798,9 +2438,7 @@ export default function WorkflowEditor() { > - - 工作流配置 - + 工作流配置 工作流级设置统一放在这里,避免和节点参数混在一起。 @@ -2826,16 +2464,12 @@ export default function WorkflowEditor() { - - 触发方式 - + 触发方式 { - const scanSourceNode = nodes.find((node) => - isScanSourceNode(node), - ); + const scanSourceNode = nodes.find((node) => isScanSourceNode(node)); if (!scanSourceNode) { return; } @@ -2850,10 +2484,8 @@ export default function WorkflowEditor() { - - 触发方式 - - + 触发方式 + @@ -2871,9 +2503,7 @@ export default function WorkflowEditor() { )} > 手动执行 - - 只在点击运行时生成一次 run。 - + 只在点击运行时生成一次 run。 周期执行 - - 按间隔反复触发新的 run。 - + 按间隔反复触发新的 run。 {scanTriggerMode === "scheduled" && ( - - 调度方式 - + 调度方式 @@ -2928,9 +2554,7 @@ export default function WorkflowEditor() { {workflowScheduleMode === "interval_seconds" && ( - - 调度间隔 (秒) - + 调度间隔 (秒) - - 每 N 小时 - + 每 N 小时 - - 每 N 天 - + 每 N 天 - - 执行时间 - + 执行时间 )} - 如果流程使用扫描源算子,bucket、prefix、连接信息以及 FULL/INCREMENTAL 都在扫描源节点里配置;这里只控制触发方式和调度策略。 + 如果流程使用扫描源算子,bucket、prefix、连接信息以及 FULL/INCREMENTAL + 都在扫描源节点里配置;这里只控制触发方式和调度策略。 )} @@ -3017,9 +2636,7 @@ export default function WorkflowEditor() { - - 触发方式 - + 触发方式 @@ -3035,9 +2652,7 @@ export default function WorkflowEditor() { )} > 手动执行 - - 只在点击运行时生成一次 run。 - + 只在点击运行时生成一次 run。 周期执行 - - 按固定间隔重复创建新的 run。 - + 按固定间隔重复创建新的 run。 {standardTriggerMode === "scheduled" && ( - - 调度方式 - + 调度方式 @@ -3101,9 +2712,7 @@ export default function WorkflowEditor() { )} {workflowScheduleMode === "every_hours" && ( - - 每 N 小时 - + 每 N 小时 - - 每 N 天 - + 每 N 天 - - 执行时间 - + 执行时间 - - 全局环境变量 - + 全局环境变量 - 这里配置的 env 会注入到全部算子节点。模板中的配置会被实例化继承;如果某个节点配置了同名 env,则以节点级配置为准。 + 这里配置的 env 会注入到全部算子节点。模板中的配置会被实例化继承;如果某个节点配置了同名 + env,则以节点级配置为准。 {workflowLevelEnvDuplicates.size > 0 && ( - 存在重复环境变量 key:{Array.from(workflowLevelEnvDuplicates).join("、")}。请先去重后再保存、运行或导出模板。 + 存在重复环境变量 key:{Array.from(workflowLevelEnvDuplicates).join("、")} + 。请先去重后再保存、运行或导出模板。 )} @@ -3197,17 +2802,13 @@ export default function WorkflowEditor() { )} {workflowLevelHyperparams.map((item, index) => { - const isDuplicate = workflowLevelEnvDuplicates.has( - normalizeWorkflowEnvKey(item?.key), - ); + const isDuplicate = workflowLevelEnvDuplicates.has(normalizeWorkflowEnvKey(item?.key)); return ( @@ -3224,19 +2825,11 @@ export default function WorkflowEditor() { - - Key - + Key - updateWorkflowHyperparamField( - index, - "key", - e.target.value, - ) - } + onChange={(e) => updateWorkflowHyperparamField(index, "key", e.target.value)} disabled={workflowSettingsReadOnly} className={cn( "w-full rounded border bg-[#0a0a0a] px-2 py-1 text-xs font-mono focus:outline-none disabled:opacity-50", @@ -3248,19 +2841,11 @@ export default function WorkflowEditor() { /> - - Value - + Value - updateWorkflowHyperparamField( - index, - "value", - e.target.value, - ) - } + onChange={(e) => updateWorkflowHyperparamField(index, "value", e.target.value)} disabled={workflowSettingsReadOnly} className="w-full rounded border border-[#2a2b2f] bg-[#0a0a0a] px-2 py-1 text-xs font-mono focus:outline-none focus:border-sky-500 disabled:opacity-50" placeholder="shared-value" @@ -3275,31 +2860,25 @@ export default function WorkflowEditor() { - - 运行并发设置 - + 运行并发设置 - - 工作流最大并发数 - + 工作流最大并发数 updateWorkflowSettings({ - maxConcurrentRuns: Math.max( - 0, - Number(e.target.value) || 0, - ), + maxConcurrentRuns: Math.max(0, Number(e.target.value) || 0), }) } disabled={workflowSettingsReadOnly} className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-xs focus:outline-none focus:border-blue-500 disabled:opacity-50" /> - 设为 `0` 表示继承系统默认并发数;会影响当前工作流的排队调度,以及单次执行里可同时运行的分支节点数。 + 设为 `0` + 表示继承系统默认并发数;会影响当前工作流的排队调度,以及单次执行里可同时运行的分支节点数。 @@ -3307,25 +2886,18 @@ export default function WorkflowEditor() { - - 执行保障 - + 执行保障 - - 单节点超时 (秒) - + 单节点超时 (秒) updateWorkflowSettings({ - nodeTimeoutSeconds: Math.max( - 0, - Number(e.target.value) || 0, - ), + nodeTimeoutSeconds: Math.max(0, Number(e.target.value) || 0), }) } disabled={workflowSettingsReadOnly} @@ -3337,19 +2909,14 @@ export default function WorkflowEditor() { - - 运行超时 (秒) - + 运行超时 (秒) updateWorkflowSettings({ - runTimeoutSeconds: Math.max( - 0, - Number(e.target.value) || 0, - ), + runTimeoutSeconds: Math.max(0, Number(e.target.value) || 0), }) } disabled={workflowSettingsReadOnly} @@ -3361,9 +2928,7 @@ export default function WorkflowEditor() { - - 失败自动重试次数 - + 失败自动重试次数 updateWorkflowSettings({ - maxRetryAttempts: Math.max( - 0, - Number(e.target.value) || 0, - ), + maxRetryAttempts: Math.max(0, Number(e.target.value) || 0), }) } disabled={workflowSettingsReadOnly} @@ -3388,19 +2950,14 @@ export default function WorkflowEditor() { - - 失败重试间隔 (秒) - + 失败重试间隔 (秒) updateWorkflowSettings({ - retryBackoffSeconds: Math.max( - 0, - Number(e.target.value) || 0, - ), + retryBackoffSeconds: Math.max(0, Number(e.target.value) || 0), }) } disabled={workflowSettingsReadOnly} @@ -3418,8 +2975,8 @@ export default function WorkflowEditor() { )} - {canManage && ( - !isTemplate && workflowEntity ? ( + {canManage && + (!isTemplate && workflowEntity ? ( navigate(workflowAssetsPath)} className="flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-md transition-colors text-gray-400 hover:text-white hover:bg-white/5" @@ -3427,17 +2984,12 @@ export default function WorkflowEditor() { 相关数据资产 - ) : null - )} + ) : null)} {canManage && ( 0 && !hasInputConnectionConflicts @@ -3453,11 +3005,7 @@ export default function WorkflowEditor() { - {runStopPending === "force" ? ( - - ) : ( - - )} + {runStopPending === "force" ? : } 强制停止 )} @@ -3591,37 +3135,25 @@ export default function WorkflowEditor() { "border-slate-500/40 bg-slate-500/10 text-slate-200", )} > - {runStatusLabels[activeRunStatus || activeRun.status] || - activeRunStatus || - activeRun.status} - - - Run {activeRun.id} + {runStatusLabels[activeRunStatus || activeRun.status] || activeRunStatus || activeRun.status} + Run {activeRun.id} {runTriggerLabels[activeRun.trigger] || activeRun.trigger} {activeRun.restartFromNodeId && ( - 重跑起点:{" "} - - {activeRun.restartFromNodeId} - + 重跑起点: {activeRun.restartFromNodeId} )} {activeRunCurrentNodeLabel && ( - 当前节点:{" "} - - {activeRunCurrentNodeLabel} - + 当前节点: {activeRunCurrentNodeLabel} )} )} - {activeRunError && ( - {activeRunError} - )} + {activeRunError && {activeRunError}} {activeRun && ( 运行会停留在当前画布,节点高亮和连线动画会实时反映真实执行进度。 @@ -3632,11 +3164,7 @@ export default function WorkflowEditor() { {activeRun && ( - navigate( - `/monitoring?runId=${encodeURIComponent(activeRun.id)}`, - ) - } + onClick={() => navigate(`/monitoring?runId=${encodeURIComponent(activeRun.id)}`)} className="rounded-md border border-[#2a2b2f] px-3 py-1.5 text-[11px] font-medium text-gray-300 hover:border-blue-500/40 hover:text-white hover:bg-blue-500/10 transition-colors" > 查看执行监控 @@ -3670,9 +3198,7 @@ export default function WorkflowEditor() { - - 周期运行记录 - + 周期运行记录 查看该周期工作流的实际运行历史,并在失败 run 上从任意节点重新执行下游子链路。 @@ -3727,8 +3253,7 @@ export default function WorkflowEditor() { {runStatusLabels[run.status] || run.status} @@ -3742,15 +3267,9 @@ export default function WorkflowEditor() { 创建于 {formatCompactDateTime(run.createdAt, timeZone, "--")} 状态节点 {run.currentNodeId || "--"} 尝试次数 {run.attempt || 1} - {run.parentRunId && ( - 父运行 {run.parentRunId} - )} - {run.restartFromNodeId && ( - 重跑起点 {run.restartFromNodeId} - )} - {run.error && ( - {run.error} - )} + {run.parentRunId && 父运行 {run.parentRunId}} + {run.restartFromNodeId && 重跑起点 {run.restartFromNodeId}} + {run.error && {run.error}} ); @@ -3774,7 +3293,7 @@ export default function WorkflowEditor() { )} - + {/* Left Sidebar: Operator Library */} setIsLibOpen(!isLibOpen)} className="absolute -right-3 top-1/2 -translate-y-1/2 z-50 w-6 h-12 bg-[#2a2b2f] border border-[#3a3b3f] rounded-full flex items-center justify-center text-gray-400 hover:text-white transition-colors shadow-xl" > - {isLibOpen ? ( - - ) : ( - - )} + {isLibOpen ? : } {isLibOpen ? ( <> - - 算子库 - - + 算子库 + {filteredOperators.length} / {operators.length} 个算子 @@ -3816,9 +3326,7 @@ export default function WorkflowEditor() { type="text" placeholder="搜索算子..." value={operatorSearchQuery} - onChange={(event) => - setOperatorSearchQuery(event.target.value) - } + onChange={(event) => setOperatorSearchQuery(event.target.value)} className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded px-7 py-1.5 text-[10px] focus:outline-none focus:border-blue-500" /> @@ -3828,12 +3336,8 @@ export default function WorkflowEditor() { return ( - - {category} - - - {categoryOperators.length} - + {category} + {categoryOperators.length} {categoryOperators.map((op) => ( @@ -3846,9 +3350,7 @@ export default function WorkflowEditor() { onDragEnd={handleOperatorDragEnd} className={cn( "group p-2 bg-[#0a0a0a] border border-[#2a2b2f] rounded-lg hover:border-blue-500/50 transition-all", - !isReadOnly && canManage - ? "cursor-grab active:cursor-grabbing" - : "cursor-default", + !isReadOnly && canManage ? "cursor-grab active:cursor-grabbing" : "cursor-default", )} > @@ -3878,9 +3380,7 @@ export default function WorkflowEditor() { - - {op.description} - + {op.description} {!isReadOnly && canManage && ( 拖到画布添加 @@ -3985,9 +3485,7 @@ export default function WorkflowEditor() { > {isConfigOpen ? ( <> - - 配置面板 - + 配置面板 > ) : ( @@ -4014,19 +3512,16 @@ export default function WorkflowEditor() { "flex items-center gap-2 px-3 py-2 rounded-md", selectedNodeExecutionState === "running" && "bg-blue-500/10 border border-blue-500/20 animate-pulse", - selectedNodeExecutionState === - "waiting_for_audit" && + selectedNodeExecutionState === "waiting_for_audit" && "bg-amber-500/10 border border-amber-500/20", selectedNodeExecutionState === "completed" && "bg-emerald-500/10 border border-emerald-500/20", - selectedNodeExecutionState === "failed" && - "bg-red-500/10 border border-red-500/20", + selectedNodeExecutionState === "failed" && "bg-red-500/10 border border-red-500/20", )} > {selectedNodeExecutionState === "running" ? ( - ) : selectedNodeExecutionState === - "waiting_for_audit" ? ( + ) : selectedNodeExecutionState === "waiting_for_audit" ? ( ) : selectedNodeExecutionState === "completed" ? ( @@ -4036,14 +3531,10 @@ export default function WorkflowEditor() { {executionStateLabels[selectedNodeExecutionState]} @@ -4076,47 +3567,30 @@ export default function WorkflowEditor() { - - 节点参数: {selectedNode.data.label} - + 节点参数: {selectedNode.data.label} {!isReadOnly && canManage && ( { setNodes((currentNodes) => - currentNodes.filter( - (node) => node.id !== selectedNode.id, - ), + currentNodes.filter((node) => node.id !== selectedNode.id), ); setEdges((currentEdges) => currentEdges.filter( - (edge) => - edge.source !== selectedNode.id && - edge.target !== selectedNode.id, + (edge) => edge.source !== selectedNode.id && edge.target !== selectedNode.id, ), ); setEntity((previous) => { if (!previous) { return previous; } - const nextNodes = nodes.filter( - (node) => node.id !== selectedNode.id, - ); - if ( - nextNodes.some((node) => - isDedicatedScanSourceNode(node), - ) - ) { + const nextNodes = nodes.filter((node) => node.id !== selectedNode.id); + if (nextNodes.some((node) => isDedicatedScanSourceNode(node))) { return previous; } - if ( - previous.kind !== "scan" && - !previous.scanConfig - ) { + if (previous.kind !== "scan" && !previous.scanConfig) { return previous; } - return stripScanWorkflowShell( - previous, - ) as Workflow | WorkflowTemplate; + return stripScanWorkflowShell(previous) as Workflow | WorkflowTemplate; }); setSelectedNode(null); setCanvasNotice("已删除 1 个节点和相关连线"); @@ -4141,19 +3615,14 @@ export default function WorkflowEditor() { - - 算子名称 - + 算子名称 n.id === selectedNode.id) - ?.data.label || selectedNode.data.label - } - onChange={(e) => - updateNodeData({ label: e.target.value }) + nodes.find((n) => n.id === selectedNode.id)?.data.label || selectedNode.data.label } + onChange={(e) => updateNodeData({ label: e.target.value })} readOnly={isReadOnly} disabled={isReadOnly} /> @@ -4162,40 +3631,33 @@ export default function WorkflowEditor() { {/* Execution Logs Section */} - - 运行日志 - + 运行日志 {selectedNodeExecution?.logs?.length ? ( - selectedNodeExecution.logs.map( - (log: any, i: number) => ( - - - [{formatClockTime(log.timestamp, timeZone)}] - - - {log.level} - - {log.message} - - ), - ) - ) : nodes.find((n) => n.id === selectedNode.id) - ?.data.logs?.length > 0 ? ( + selectedNodeExecution.logs.map((log: any, i: number) => ( + + + [{formatClockTime(log.timestamp, timeZone)}] + + {log.level} + {log.message} + + )) + ) : nodes.find((n) => n.id === selectedNode.id)?.data.logs?.length > 0 ? ( nodes .find((n) => n.id === selectedNode.id) ?.data.logs.map((log: any, i: number) => ( @@ -4210,9 +3672,7 @@ export default function WorkflowEditor() { : "text-gray-400", )} > - - [{log.time}] - + [{log.time}] {log.message} )) @@ -4228,15 +3688,11 @@ export default function WorkflowEditor() { - - 扫描源配置 - + 扫描源配置 - - 数据源类型 - + 数据源类型 - {(workflowConfigEntity?.scanConfig?.dataSource || "BOS") === - "BOS" ? ( + {(workflowConfigEntity?.scanConfig?.dataSource || "BOS") === "BOS" ? ( <> - - Bucket - + Bucket {scanStorageConnection ? ( - - Prefix - + Prefix - {isCurrentStoragePathFavorite - ? "取消收藏当前路径" - : "收藏当前路径"} + {isCurrentStoragePathFavorite ? "取消收藏当前路径" : "收藏当前路径"} {workflowProjectId && ( - void toggleCurrentProjectStoragePathFavorite() - } + onClick={() => void toggleCurrentProjectStoragePathFavorite()} className={cn( "inline-flex items-center gap-1 rounded border px-2 py-1 text-[10px] transition-colors disabled:opacity-50", isCurrentProjectStoragePathFavorite @@ -4386,9 +3829,7 @@ export default function WorkflowEditor() { disabled={isReadOnly} > - {isCurrentProjectStoragePathFavorite - ? "移出项目常用" - : "加入项目常用"} + {isCurrentProjectStoragePathFavorite ? "移出项目常用" : "加入项目常用"} )} @@ -4405,12 +3846,7 @@ export default function WorkflowEditor() { - applyFavoriteStoragePath( - item.bucket, - item.prefix, - ) - } + onClick={() => applyFavoriteStoragePath(item.bucket, item.prefix)} className="rounded-full border border-cyan-500/20 bg-cyan-500/10 px-2 py-1 text-[10px] text-cyan-100 hover:bg-cyan-500/15 disabled:opacity-50" disabled={isReadOnly} title={item.label} @@ -4433,12 +3869,7 @@ export default function WorkflowEditor() { - applyFavoriteStoragePath( - item.bucket, - item.prefix, - ) - } + onClick={() => applyFavoriteStoragePath(item.bucket, item.prefix)} className="rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-1 text-[10px] text-amber-100 hover:bg-amber-500/15 disabled:opacity-50" disabled={isReadOnly} title={item.label} @@ -4461,12 +3892,7 @@ export default function WorkflowEditor() { - applyRecentStoragePath( - item.bucket, - item.prefix, - ) - } + onClick={() => applyRecentStoragePath(item.bucket, item.prefix)} className="rounded-full border border-cyan-500/20 bg-cyan-500/10 px-2 py-1 text-[10px] text-cyan-100 hover:bg-cyan-500/15 disabled:opacity-50" disabled={isReadOnly} title={item.label} @@ -4481,9 +3907,7 @@ export default function WorkflowEditor() { - - BOS 连接 - + BOS 连接 连接保存 endpoint 和密钥,工作流只引用连接 ID。 @@ -4499,9 +3923,7 @@ export default function WorkflowEditor() { - setIsStorageConnectionFormOpen((current) => !current) - } + onClick={() => setIsStorageConnectionFormOpen((current) => !current)} className="rounded border border-cyan-500/30 bg-cyan-500/10 px-2 py-1 text-[10px] text-cyan-200 hover:bg-cyan-500/15 disabled:opacity-50" disabled={isReadOnly} > @@ -4511,15 +3933,11 @@ export default function WorkflowEditor() { - - 已选连接 - + 已选连接 - handleStorageConnectionSelect(e.target.value, "scan") - } + onChange={(e) => handleStorageConnectionSelect(e.target.value, "scan")} disabled={isReadOnly || isStorageConnectionsLoading} > 直接在当前工作流填写 BOS 凭据 @@ -4540,9 +3958,7 @@ export default function WorkflowEditor() { {scanStorageConnection && ( - - Endpoint - + Endpoint {scanStorageConnection.endpoint || DEFAULT_BOS_ENDPOINT} @@ -4587,9 +4003,7 @@ export default function WorkflowEditor() { /> - - 描述 - + 描述 updateScanWorkflowConfig({ endpoint: e.target.value, @@ -4743,9 +4154,7 @@ export default function WorkflowEditor() { > ) : ( - - 扫描路径 - + 扫描路径 - - 扫描模式 - + 扫描模式 updateScanWorkflowConfig({ scanMode: e.target.value, @@ -4783,14 +4188,10 @@ export default function WorkflowEditor() { - - 增量单位 - + 增量单位 updateScanWorkflowConfig({ incrementalUnit: e.target.value, @@ -4798,8 +4199,7 @@ export default function WorkflowEditor() { } disabled={ isReadOnly || - (workflowConfigEntity?.scanConfig?.scanMode || "INCREMENTAL") === - "FULL" + (workflowConfigEntity?.scanConfig?.scanMode || "INCREMENTAL") === "FULL" } > OBJECT @@ -4807,9 +4207,7 @@ export default function WorkflowEditor() { - - 目录层级 - + 目录层级 updateScanWorkflowConfig({ - directoryDepth: Math.max( - 1, - Number.parseInt(e.target.value || "1", 10) || 1, - ), + directoryDepth: Math.max(1, Number.parseInt(e.target.value || "1", 10) || 1), }) } readOnly={ isReadOnly || - (workflowConfigEntity?.scanConfig?.scanMode || "INCREMENTAL") === - "FULL" + (workflowConfigEntity?.scanConfig?.scanMode || "INCREMENTAL") === "FULL" } disabled={ isReadOnly || - (workflowConfigEntity?.scanConfig?.scanMode || "INCREMENTAL") === - "FULL" + (workflowConfigEntity?.scanConfig?.scanMode || "INCREMENTAL") === "FULL" } /> @@ -4866,9 +4259,7 @@ export default function WorkflowEditor() { - - 增量状态 - + 增量状态 - {isResettingSourceState - ? "重置中..." - : "重置当前状态"} + {isResettingSourceState ? "重置中..." : "重置当前状态"} - 这里只显示服务端已保存的扫描源状态。修改 - `bucket/prefix/scanMode` 后请先保存;状态只会在整条工作流成功后提交。 + 这里只显示服务端已保存的扫描源状态。修改 `bucket/prefix/scanMode` + 后请先保存;状态只会在整条工作流成功后提交。 {isSourceStateLoading ? ( @@ -4914,39 +4303,28 @@ export default function WorkflowEditor() { - - 已记住对象 - + 已记住对象 {sourceState.current.seenFingerprints?.length || 0} - - 上次列出 - + 上次列出 {sourceState.current.lastListedCount ?? 0} - - 上次新增 - + 上次新增 {sourceState.current.lastNewCount ?? 0} - - 上次完成 - + 上次完成 {sourceState.current.lastScanCompletedAt - ? formatCompactDateTime( - sourceState.current.lastScanCompletedAt, - timeZone, - ) + ? formatCompactDateTime(sourceState.current.lastScanCompletedAt, timeZone) : "--"} @@ -4999,8 +4377,7 @@ export default function WorkflowEditor() { - Run {item.lastRunId || "--"} · listed{" "} - {item.lastListedCount ?? 0} · new{" "} + Run {item.lastRunId || "--"} · listed {item.lastListedCount ?? 0} · new{" "} {item.lastNewCount ?? 0} @@ -5027,7 +4404,8 @@ export default function WorkflowEditor() { 业务 MongoDB 连接 - 平台库不会作为写入目标。请选择一个用户创建的业务 MongoDB 连接,或显式填写 URI/DB 超参。 + 平台库不会作为写入目标。请选择一个用户创建的业务 MongoDB 连接,或显式填写 URI/DB + 超参。 @@ -5050,15 +4428,11 @@ export default function WorkflowEditor() { - - 已选连接 - + 已选连接 - handleMongoConnectionSelect(event.target.value) - } + onChange={(event) => handleMongoConnectionSelect(event.target.value)} disabled={isReadOnly || isMongoConnectionsLoading} > 使用节点超参里的 MONGO_URI / MONGO_DB @@ -5079,25 +4453,19 @@ export default function WorkflowEditor() { {selectedNodeMongoConnection ? ( - - 连接名称 - + 连接名称 {selectedNodeMongoConnection.name} - - 数据库 - + 数据库 {selectedNodeMongoConnection.database || "--"} - - Mongo URI - + Mongo URI {selectedNodeMongoConnection.uriPreview || "已保存"} @@ -5106,9 +4474,7 @@ export default function WorkflowEditor() { ) : ( 当前没有绑定业务 MongoDB 连接。若不选择连接,节点将只使用超参里的 - - MONGO_URI / MONGO_DB - + MONGO_URI / MONGO_DB 显式配置。 )} @@ -5120,17 +4486,13 @@ export default function WorkflowEditor() { - - OSS 数据源配置 - + OSS 数据源配置 - - BOS 连接 - + BOS 连接 节点优先引用存储连接;浏览器会直接列出该连接下的真实 bucket 和前缀。 @@ -5146,9 +4508,7 @@ export default function WorkflowEditor() { - setIsStorageConnectionFormOpen((current) => !current) - } + onClick={() => setIsStorageConnectionFormOpen((current) => !current)} className="rounded border border-blue-500/30 bg-blue-500/10 px-2 py-1 text-[10px] text-blue-200 hover:bg-blue-500/15 disabled:opacity-50" disabled={isReadOnly} > @@ -5158,15 +4518,11 @@ export default function WorkflowEditor() { - - 已选连接 - + 已选连接 - handleStorageConnectionSelect(e.target.value, "node") - } + onChange={(e) => handleStorageConnectionSelect(e.target.value, "node")} disabled={isReadOnly || isStorageConnectionsLoading} > 继续使用节点超参里的 BOS 凭据 @@ -5187,25 +4543,19 @@ export default function WorkflowEditor() { {nodeStorageConnection && ( - - Endpoint - + Endpoint {nodeStorageConnection.endpoint || DEFAULT_BOS_ENDPOINT} - - Access Key - + Access Key {nodeStorageConnection.accessKeyPreview || "已保存"} - - Secret Key - + Secret Key {nodeStorageConnection.secretAccessKeyPreview || "已保存"} @@ -5216,9 +4566,7 @@ export default function WorkflowEditor() { {isStorageConnectionFormOpen && ( - - 连接名称 - + 连接名称 - - 描述 - + 描述 - - Endpoint - + Endpoint - - SOURCE_PATH - + SOURCE_PATH - 优先使用节点绑定的 BOS 连接浏览真实 bucket/prefix;未绑定连接时,回退读取节点超参里的 - `SOURCE_PATH`。 + 优先使用节点绑定的 BOS 连接浏览真实 + bucket/prefix;未绑定连接时,回退读取节点超参里的 `SOURCE_PATH`。 @@ -5355,22 +4697,14 @@ export default function WorkflowEditor() { > - {isCurrentStoragePathFavorite - ? "取消收藏当前路径" - : "收藏当前路径"} + {isCurrentStoragePathFavorite ? "取消收藏当前路径" : "收藏当前路径"} {workflowProjectId && ( - void toggleCurrentProjectStoragePathFavorite() - } + onClick={() => void toggleCurrentProjectStoragePathFavorite()} className={cn( "inline-flex items-center gap-1 rounded border px-2 py-1 text-[10px] transition-colors disabled:opacity-50", isCurrentProjectStoragePathFavorite @@ -5380,9 +4714,7 @@ export default function WorkflowEditor() { disabled={isReadOnly} > - {isCurrentProjectStoragePathFavorite - ? "移出项目常用" - : "加入项目常用"} + {isCurrentProjectStoragePathFavorite ? "移出项目常用" : "加入项目常用"} )} @@ -5398,12 +4730,7 @@ export default function WorkflowEditor() { - applyFavoriteStoragePath( - item.bucket, - item.prefix, - ) - } + onClick={() => applyFavoriteStoragePath(item.bucket, item.prefix)} className="rounded-full border border-cyan-500/20 bg-cyan-500/10 px-2 py-1 text-[10px] text-cyan-100 hover:bg-cyan-500/15 disabled:opacity-50" disabled={isReadOnly} title={item.label} @@ -5425,12 +4752,7 @@ export default function WorkflowEditor() { - applyFavoriteStoragePath( - item.bucket, - item.prefix, - ) - } + onClick={() => applyFavoriteStoragePath(item.bucket, item.prefix)} className="rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-1 text-[10px] text-amber-100 hover:bg-amber-500/15 disabled:opacity-50" disabled={isReadOnly} title={item.label} @@ -5452,12 +4774,7 @@ export default function WorkflowEditor() { - applyRecentStoragePath( - item.bucket, - item.prefix, - ) - } + onClick={() => applyRecentStoragePath(item.bucket, item.prefix)} className="rounded-full border border-blue-500/20 bg-blue-500/10 px-2 py-1 text-[10px] text-blue-100 hover:bg-blue-500/15 disabled:opacity-50" disabled={isReadOnly} title={item.label} @@ -5474,17 +4791,12 @@ export default function WorkflowEditor() { onChange={(e) => { const nextBucket = e.target.value; updateOssNodeConfig({ bucket: nextBucket }); - rememberRecentStoragePath( - nextBucket, - selectedNode.data.prefix || "", - ); + rememberRecentStoragePath(nextBucket, selectedNode.data.prefix || ""); }} disabled={isReadOnly || !canBrowseSelectedStorage} > - {canBrowseSelectedStorage - ? "选择存储桶..." - : "请先选择连接或配置 SOURCE_PATH"} + {canBrowseSelectedStorage ? "选择存储桶..." : "请先选择连接或配置 SOURCE_PATH"} {buckets.map((b) => ( @@ -5515,10 +4827,7 @@ export default function WorkflowEditor() { }) } onBlur={(e) => - rememberRecentStoragePath( - selectedNode.data.bucket || "", - e.target.value, - ) + rememberRecentStoragePath(selectedNode.data.bucket || "", e.target.value) } readOnly={isReadOnly} disabled={isReadOnly} @@ -5529,11 +4838,11 @@ export default function WorkflowEditor() { className="absolute right-1 top-1/2 -translate-y-1/2 p-1 hover:bg-white/5 rounded text-blue-500" disabled={ isReadOnly || - ((!selectedNode.data.bucket && + (!selectedNode.data.bucket && visibleRecentStoragePaths.length === 0 && favoriteStoragePaths.length === 0 && projectFavoriteStoragePaths.length === 0) || - !canBrowseSelectedStorage) + !canBrowseSelectedStorage } > @@ -5545,12 +4854,12 @@ export default function WorkflowEditor() { 文件过滤 (Pattern) - + updateOssNodeConfig({ pattern: e.target.value, }) @@ -5561,9 +4870,7 @@ export default function WorkflowEditor() { {ossBrowseError && !isOssBrowsing && ( - - {ossBrowseError} - + {ossBrowseError} )} )} @@ -5573,9 +4880,7 @@ export default function WorkflowEditor() { - - 任务分配配置 - + 任务分配配置 @@ -5585,9 +4890,7 @@ export default function WorkflowEditor() { updateNodeData({ shuffle: e.target.checked, @@ -5598,14 +4901,10 @@ export default function WorkflowEditor() { - - 分配模式 - + 分配模式 updateNodeData({ distMode: e.target.value, @@ -5613,142 +4912,108 @@ export default function WorkflowEditor() { } disabled={isReadOnly} > - - 按比例分配 (%) - - - 按数量分配 (Count) - + 按比例分配 (%) + 按数量分配 (Count) - - 出口权重设置 - - {(selectedNode.data.outputs || []).map( - (port: any, idx: number) => ( - - - {port.name} - - { - const newWeights = { - ...(selectedNode.data.weights || - {}), - [port.id]: e.target.value, - }; - updateNodeData({ - weights: newWeights, - }); - }} - disabled={isReadOnly} - /> - - {selectedNode.data.distMode === - "ratio" - ? "%" - : "pcs"} - - - ), - )} + 出口权重设置 + {(selectedNode.data.outputs || []).map((port: any, idx: number) => ( + + {port.name} + { + const newWeights = { + ...(selectedNode.data.weights || {}), + [port.id]: e.target.value, + }; + updateNodeData({ + weights: newWeights, + }); + }} + disabled={isReadOnly} + /> + + {selectedNode.data.distMode === "ratio" ? "%" : "pcs"} + + + ))} )} {/* Hyperparameters Config (K8s Env Vars) */} - {selectedNode?.type === "operator" && - selectedNodeEnvRows.length > 0 && ( - - - - - 超参配置 (K8s Job Env) - - - - 节点自定义 env 可编辑;继承自工作流和系统注入项为只读。 - 系统时间戳只会在周期执行时出现,值与实际运行时完全一致。 - 已加载 run 时显示真实值;未加载 run 时显示“如果现在按当前调度执行”的预览值。 - 时间格式固定为 Asia/Shanghai。 - - - - {selectedNodeEnvRows.map((hp: any) => { - const isSystemEnv = hp.source === "system"; - const isWorkflowEnv = hp.source === "workflow"; - return ( - - - - {hp.key} - - {isSystemEnv && ( - - 系统注入 - - )} - {isWorkflowEnv && ( - - 继承自工作流 - - )} - - {hp.description && ( - - {hp.description} - - )} - { - const newHyperparams = [ - ...selectedNode.data.hyperparams, - ]; - newHyperparams[hp.index] = { - ...newHyperparams[hp.index], - value: e.target.value, - }; - updateNodeData({ - hyperparams: newHyperparams, - }); - } - } - readOnly={isReadOnly || isSystemEnv || isWorkflowEnv} - disabled={isReadOnly || isSystemEnv || isWorkflowEnv} - /> - - ); - })} - + {selectedNode?.type === "operator" && selectedNodeEnvRows.length > 0 && ( + + + + + 超参配置 (K8s Job Env) + - )} + + 节点自定义 env 可编辑;继承自工作流和系统注入项为只读。 + 系统时间戳只会在周期执行时出现,值与实际运行时完全一致。 已加载 run + 时显示真实值;未加载 run 时显示“如果现在按当前调度执行”的预览值。 时间格式固定为{" "} + Asia/Shanghai。 + + + + {selectedNodeEnvRows.map((hp: any) => { + const isSystemEnv = hp.source === "system"; + const isWorkflowEnv = hp.source === "workflow"; + return ( + + + + {hp.key} + + {isSystemEnv && ( + + 系统注入 + + )} + {isWorkflowEnv && ( + + 继承自工作流 + + )} + + {hp.description && ( + {hp.description} + )} + { + const newHyperparams = [...selectedNode.data.hyperparams]; + newHyperparams[hp.index] = { + ...newHyperparams[hp.index], + value: e.target.value, + }; + updateNodeData({ + hyperparams: newHyperparams, + }); + } + } + readOnly={isReadOnly || isSystemEnv || isWorkflowEnv} + disabled={isReadOnly || isSystemEnv || isWorkflowEnv} + /> + + ); + })} + + + )} @@ -5758,9 +5023,7 @@ export default function WorkflowEditor() { type="text" className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded px-2 py-1 text-xs focus:outline-none focus:border-blue-500 disabled:opacity-50" value={selectedNode.data.image || ""} - onChange={(e) => - updateNodeData({ image: e.target.value }) - } + onChange={(e) => updateNodeData({ image: e.target.value })} readOnly={isReadOnly} disabled={isReadOnly} /> @@ -5768,52 +5031,40 @@ export default function WorkflowEditor() { - - 资源限制 (CPU) - + 资源限制 (CPU) - updateNodeData({ cpu: e.target.value }) - } + onChange={(e) => updateNodeData({ cpu: e.target.value })} readOnly={isReadOnly} disabled={isReadOnly} /> - - - 资源限制 (MEM) - + + 资源限制 (MEM) - updateNodeData({ memory: e.target.value }) - } + onChange={(e) => updateNodeData({ memory: e.target.value })} readOnly={isReadOnly} - disabled={isReadOnly} - /> - - - - GPU 数量 - - - updateNodeData({ gpu: e.target.value }) - } - readOnly={isReadOnly} - disabled={isReadOnly} - /> - - + disabled={isReadOnly} + /> + + + GPU 数量 + updateNodeData({ gpu: e.target.value })} + readOnly={isReadOnly} + disabled={isReadOnly} + /> + + @@ -5840,69 +5091,61 @@ export default function WorkflowEditor() { )} - {(selectedNode.data.inputs || []).map( - (port: any, idx: number) => ( - ( + + { + const newInputs = [...selectedNode.data.inputs]; + newInputs[idx] = { + ...port, + name: e.target.value, + }; + updateNodeData({ inputs: newInputs }); + }} + readOnly={isReadOnly} + /> + { + const newInputs = [...selectedNode.data.inputs]; + newInputs[idx] = { + ...port, + type: e.target.value, + }; + updateNodeData({ inputs: newInputs }); + }} + disabled={isReadOnly} > - { - const newInputs = [ - ...selectedNode.data.inputs, - ]; - newInputs[idx] = { - ...port, - name: e.target.value, - }; - updateNodeData({ inputs: newInputs }); + JSON + Video + Image + Tensor + File + + {!isReadOnly && ( + { + const newInputs = selectedNode.data.inputs.filter( + (_: any, i: number) => i !== idx, + ); + updateNodeData({ + inputs: newInputs, + }); }} - readOnly={isReadOnly} - /> - { - const newInputs = [ - ...selectedNode.data.inputs, - ]; - newInputs[idx] = { - ...port, - type: e.target.value, - }; - updateNodeData({ inputs: newInputs }); - }} - disabled={isReadOnly} + className="text-gray-600 hover:text-red-500" > - JSON - Video - Image - Tensor - File - - {!isReadOnly && ( - { - const newInputs = - selectedNode.data.inputs.filter( - (_: any, i: number) => - i !== idx, - ); - updateNodeData({ - inputs: newInputs, - }); - }} - className="text-gray-600 hover:text-red-500" - > - - - )} - - ), - )} + + + )} + + ))} @@ -5931,80 +5174,70 @@ export default function WorkflowEditor() { )} - {(selectedNode.data.outputs || []).map( - (port: any, idx: number) => ( - ( + + { + const newOutputs = [...selectedNode.data.outputs]; + newOutputs[idx] = { + ...port, + name: e.target.value, + }; + updateNodeData({ + outputs: newOutputs, + }); + }} + readOnly={isReadOnly} + /> + { + const newOutputs = [...selectedNode.data.outputs]; + newOutputs[idx] = { + ...port, + type: e.target.value, + }; + updateNodeData({ + outputs: newOutputs, + }); + }} + disabled={isReadOnly} > - { - const newOutputs = [ - ...selectedNode.data.outputs, - ]; - newOutputs[idx] = { - ...port, - name: e.target.value, - }; + JSON + Video + Image + Tensor + File + + {!isReadOnly && ( + { + const newOutputs = selectedNode.data.outputs.filter( + (_: any, i: number) => i !== idx, + ); updateNodeData({ outputs: newOutputs, }); }} - readOnly={isReadOnly} - /> - { - const newOutputs = [ - ...selectedNode.data.outputs, - ]; - newOutputs[idx] = { - ...port, - type: e.target.value, - }; - updateNodeData({ - outputs: newOutputs, - }); - }} - disabled={isReadOnly} + className="text-gray-600 hover:text-red-500" > - JSON - Video - Image - Tensor - File - - {!isReadOnly && ( - { - const newOutputs = - selectedNode.data.outputs.filter( - (_: any, i: number) => - i !== idx, - ); - updateNodeData({ - outputs: newOutputs, - }); - }} - className="text-gray-600 hover:text-red-500" - > - - - )} - - ), - )} + + + )} + + ))} - - 算子描述 - + 算子描述 {selectedEdgeExecutionState === "running" ? ( @@ -6050,35 +5281,25 @@ export default function WorkflowEditor() { - {executionStateLabels[selectedEdgeExecutionState] || - selectedEdgeExecutionState} + {executionStateLabels[selectedEdgeExecutionState] || selectedEdgeExecutionState} - - 连线输出 - + 连线输出 {!isReadOnly && canManage && ( { setEdges((currentEdges) => - currentEdges.filter( - (edge) => edge.id !== selectedEdge.id, - ), + currentEdges.filter((edge) => edge.id !== selectedEdge.id), ); setSelectedEdgeId(""); setCanvasNotice("已删除 1 条连线"); @@ -6094,9 +5315,7 @@ export default function WorkflowEditor() { - - 数据流向 - + 数据流向 {selectedEdgeSourceLabel} → @@ -6104,44 +5323,32 @@ export default function WorkflowEditor() { - - 输出端口 - - - {selectedEdgePortLabel} - + 输出端口 + {selectedEdgePortLabel} 当前 Run - - {activeRun?.id || "未加载"} - + {activeRun?.id || "未加载"} 输出文件数 - - {selectedEdgeArtifacts.length} - + {selectedEdgeArtifacts.length} {selectedEdgeArtifacts.length > 0 ? ( - - 该连线输出文件 - + 该连线输出文件 {selectedEdgeArtifacts.map((artifact) => ( - setSelectedEdgeArtifactId(artifact.id) - } + onClick={() => setSelectedEdgeArtifactId(artifact.id)} className={cn( "w-full rounded-lg border px-3 py-2 text-left transition-colors", selectedEdgeArtifact?.id === artifact.id @@ -6159,9 +5366,7 @@ export default function WorkflowEditor() { {artifact.type.toUpperCase()} - - {artifact.size} - + {artifact.size} ))} @@ -6169,9 +5374,7 @@ export default function WorkflowEditor() { - - 输出预览 - + 输出预览 @@ -6185,12 +5388,8 @@ export default function WorkflowEditor() { ) : ( - - 选择算子或连线查看配置与输出 - - - 工作流级配置请使用顶部的“工作流配置”入口。 - + 选择算子或连线查看配置与输出 + 工作流级配置请使用顶部的“工作流配置”入口。 )} @@ -6224,9 +5423,7 @@ export default function WorkflowEditor() { className="relative w-full max-w-md bg-[#151619] border border-[#2a2b2f] rounded-2xl shadow-2xl overflow-hidden" > - - 导出为模板 - + 导出为模板 setIsExportTemplateOpen(false)} className="p-2 hover:bg-white/5 rounded-full text-gray-500 hover:text-white transition-colors" @@ -6236,9 +5433,7 @@ export default function WorkflowEditor() { - - 模板名称 - + 模板名称 - - 模板描述 - + 模板描述 创建模板 @@ -6311,13 +5503,10 @@ export default function WorkflowEditor() { - - OSS 资源浏览器 - + OSS 资源浏览器 - {selectedBrowseRootLabel || "未配置连接或 SOURCE_PATH"} /{" "} - {selectedNodeBucket || "未选择存储桶"} /{" "} - {selectedNodePrefix || ""} + {selectedBrowseRootLabel || "未配置连接或 SOURCE_PATH"} / {selectedNodeBucket || "未选择存储桶"}{" "} + / {selectedNodePrefix || ""} @@ -6338,20 +5527,16 @@ export default function WorkflowEditor() { {projectFavoriteStoragePaths.map((item) => { - const itemKey = `${item.bucket}/${normalizeStoragePrefix( - item.prefix, - )}`; + const itemKey = `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`; const isCurrent = itemKey === selectedStoragePathKey; return ( - applyFavoriteStoragePath(item.bucket, item.prefix) - } - className={cn( - "rounded-full border px-2.5 py-1 text-[10px] transition-colors", - isCurrent + onClick={() => applyFavoriteStoragePath(item.bucket, item.prefix)} + className={cn( + "rounded-full border px-2.5 py-1 text-[10px] transition-colors", + isCurrent ? "border-cyan-400/40 bg-cyan-500/15 text-cyan-100" : "border-[#2a2b2f] bg-[#0a0a0a] text-gray-300 hover:border-cyan-500/40 hover:text-cyan-200", )} @@ -6375,17 +5560,13 @@ export default function WorkflowEditor() { {visibleUserFavoriteStoragePaths.map((item) => { - const itemKey = `${item.bucket}/${normalizeStoragePrefix( - item.prefix, - )}`; + const itemKey = `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`; const isCurrent = itemKey === selectedStoragePathKey; return ( - applyFavoriteStoragePath(item.bucket, item.prefix) - } + onClick={() => applyFavoriteStoragePath(item.bucket, item.prefix)} className={cn( "rounded-full border px-2.5 py-1 text-[10px] transition-colors", isCurrent @@ -6399,9 +5580,7 @@ export default function WorkflowEditor() { ); })} - - 仅当前用户可见的常用 bucket/prefix。 - + 仅当前用户可见的常用 bucket/prefix。 )} {visibleRecentStoragePaths.length > 0 && ( @@ -6412,17 +5591,13 @@ export default function WorkflowEditor() { {visibleRecentStoragePaths.map((item) => { - const itemKey = `${item.bucket}/${normalizeStoragePrefix( - item.prefix, - )}`; + const itemKey = `${item.bucket}/${normalizeStoragePrefix(item.prefix)}`; const isCurrent = itemKey === selectedStoragePathKey; return ( - applyRecentStoragePath(item.bucket, item.prefix) - } + onClick={() => applyRecentStoragePath(item.bucket, item.prefix)} className={cn( "rounded-full border px-2.5 py-1 text-[10px] transition-colors", isCurrent @@ -6444,9 +5619,7 @@ export default function WorkflowEditor() { {!canBrowseSelectedStorage ? ( - - 请先绑定 BOS 连接,或在当前节点超参里配置 SOURCE_PATH - + 请先绑定 BOS 连接,或在当前节点超参里配置 SOURCE_PATH ) : !selectedNodeBucket ? ( @@ -6458,23 +5631,17 @@ export default function WorkflowEditor() { ) : isOssLoading ? ( - - 正在扫描 OSS 目录... - + 正在扫描 OSS 目录... ) : ossBrowseError ? ( - - {ossBrowseError} - + {ossBrowseError} ) : ossObjects.length === 0 ? ( - - 当前路径下没有可选对象 - + 当前路径下没有可选对象 ) : ( @@ -6496,9 +5663,7 @@ export default function WorkflowEditor() { ) : ( )} - - {obj} - + {obj} diff --git a/src/services/aiService.ts b/src/services/aiService.ts index 4b5dbb61..01194ec2 100644 --- a/src/services/aiService.ts +++ b/src/services/aiService.ts @@ -1,9 +1,4 @@ -import { - aiApi, - type AIStatus, - type GeneratedOperator, - type GeneratedWorkflow, -} from "./api/ai"; +import { aiApi, type AIStatus, type GeneratedOperator, type GeneratedWorkflow } from "./api/ai"; export type { AIStatus, GeneratedOperator, GeneratedWorkflow }; diff --git a/src/services/api/ai.ts b/src/services/api/ai.ts index 7cd242cc..9356b687 100644 --- a/src/services/api/ai.ts +++ b/src/services/api/ai.ts @@ -35,14 +35,16 @@ async function loadStatus(force = false) { if (!force && statusPromise) { return statusPromise; } - statusPromise = apiRequest("/api/ai/status").then((status) => { - statusCache = status; - statusPromise = null; - return status; - }).catch((error) => { - statusPromise = null; - throw error; - }); + statusPromise = apiRequest("/api/ai/status") + .then((status) => { + statusCache = status; + statusPromise = null; + return status; + }) + .catch((error) => { + statusPromise = null; + throw error; + }); return statusPromise; } diff --git a/src/services/api/data-platform.ts b/src/services/api/data-platform.ts index 69f207e0..af90eabe 100644 --- a/src/services/api/data-platform.ts +++ b/src/services/api/data-platform.ts @@ -1,43 +1,24 @@ -import type { - PackageDetail, - PackageRecord, - SamplingTask, - SourceCollection, - SourceCollectionDetail, -} from "../../types"; +import type { PackageDetail, PackageRecord, SamplingTask, SourceCollection, SourceCollectionDetail } from "../../types"; import { apiRequest } from "./client"; export const dataPlatformApi = { listSourceCollections: async () => - ( - await apiRequest<{ items: SourceCollection[] }>( - "/api/source-data/collections", - ) - ).items, + (await apiRequest<{ items: SourceCollection[] }>("/api/source-data/collections")).items, getSourceCollection: (runId: string, collectionId: string) => apiRequest( `/api/source-data/collections/${encodeURIComponent(runId)}/${encodeURIComponent(collectionId)}`, ), - getSourceCollectionEntries: ( - runId: string, - collectionId: string, - prefix = "", - ) => + getSourceCollectionEntries: (runId: string, collectionId: string, prefix = "") => apiRequest( `/api/source-data/collections/${encodeURIComponent(runId)}/${encodeURIComponent(collectionId)}/entries?prefix=${encodeURIComponent(prefix)}`, ), - listPackages: async () => - (await apiRequest<{ items: PackageRecord[] }>("/api/packages")).items, + listPackages: async () => (await apiRequest<{ items: PackageRecord[] }>("/api/packages")).items, getPackage: (runId: string, packageName: string) => - apiRequest( - `/api/packages/${encodeURIComponent(runId)}/${encodeURIComponent(packageName)}`, - ), + apiRequest(`/api/packages/${encodeURIComponent(runId)}/${encodeURIComponent(packageName)}`), - listSamplingTasks: async () => - (await apiRequest<{ items: SamplingTask[] }>("/api/sampling-tasks")).items, - getSamplingTask: (id: string) => - apiRequest(`/api/sampling-tasks/${id}`), + listSamplingTasks: async () => (await apiRequest<{ items: SamplingTask[] }>("/api/sampling-tasks")).items, + getSamplingTask: (id: string) => apiRequest(`/api/sampling-tasks/${id}`), reviewSamplingItem: ( id: string, payload: { @@ -47,10 +28,5 @@ export const dataPlatformApi = { overallGrade: string; notes?: string; }, - ) => - apiRequest( - `/api/sampling-items/${id}/review`, - { method: "POST" }, - payload, - ), + ) => apiRequest(`/api/sampling-items/${id}/review`, { method: "POST" }, payload), }; diff --git a/src/services/api/database.ts b/src/services/api/database.ts index 8d87feb3..57c6d7e0 100644 --- a/src/services/api/database.ts +++ b/src/services/api/database.ts @@ -11,7 +11,13 @@ import type { } from "../../types"; import { apiRequest } from "./client"; -function buildDatabaseParams(options?: { target?: "platform" | "business"; connectionId?: string; filter?: string; limit?: number; skip?: number }) { +function buildDatabaseParams(options?: { + target?: "platform" | "business"; + connectionId?: string; + filter?: string; + limit?: number; + skip?: number; +}) { const params = new URLSearchParams(); if (options?.target) { params.set("target", options.target); @@ -38,7 +44,13 @@ export const databaseApi = { }, queryCollection: ( collection: string, - options?: { target?: "platform" | "business"; connectionId?: string; filter?: string; limit?: number; skip?: number }, + options?: { + target?: "platform" | "business"; + connectionId?: string; + filter?: string; + limit?: number; + skip?: number; + }, ) => { return apiRequest( `/api/database/collections/${encodeURIComponent(collection)}/documents${buildDatabaseParams(options)}`, diff --git a/src/services/api/external-business-db.ts b/src/services/api/external-business-db.ts index ebc29b0d..44440024 100644 --- a/src/services/api/external-business-db.ts +++ b/src/services/api/external-business-db.ts @@ -49,9 +49,6 @@ export const externalBusinessWriteApi = { }), }; -export function scopeForConnection( - token: ExternalBusinessWriteToken | null | undefined, - connectionId: string, -) { +export function scopeForConnection(token: ExternalBusinessWriteToken | null | undefined, connectionId: string) { return token?.scopes?.find((scope) => scope.connectionId === connectionId) || null; } diff --git a/src/services/api/mongo-connections.ts b/src/services/api/mongo-connections.ts index 1cc6d9d5..98eca92b 100644 --- a/src/services/api/mongo-connections.ts +++ b/src/services/api/mongo-connections.ts @@ -9,16 +9,13 @@ type MongoConnectionPayload = { }; export const mongoConnectionsApi = { - list: async () => - (await apiRequest<{ items: MongoConnection[] }>("/api/mongo/connections")) - .items, + list: async () => (await apiRequest<{ items: MongoConnection[] }>("/api/mongo/connections")).items, get: (id: string) => apiRequest(`/api/mongo/connections/${id}`), create: (payload: MongoConnectionPayload) => apiRequest("/api/mongo/connections", { method: "POST" }, payload), update: (id: string, payload: Partial) => apiRequest(`/api/mongo/connections/${id}`, { method: "PUT" }, payload), - remove: (id: string) => - apiRequest(`/api/mongo/connections/${id}`, { method: "DELETE" }), + remove: (id: string) => apiRequest(`/api/mongo/connections/${id}`, { method: "DELETE" }), test: (payload: { id?: string; uri?: string; database?: string }) => apiRequest("/api/mongo/connections/test", { method: "POST" }, payload), }; diff --git a/src/services/api/monitoring.ts b/src/services/api/monitoring.ts index 792ca163..aa2a2d04 100644 --- a/src/services/api/monitoring.ts +++ b/src/services/api/monitoring.ts @@ -1,10 +1,4 @@ -import type { - ExecutionData, - ExecutionRun, - ExecutionRunSummary, - LogEntry, - ResourceUsage, -} from "../../types"; +import type { ExecutionData, ExecutionRun, ExecutionRunSummary, LogEntry, ResourceUsage } from "../../types"; import { apiRequest } from "./client"; export { type ExecutionData, type LogEntry, type ResourceUsage }; @@ -15,29 +9,18 @@ type StorageBrowseTarget = { }; export const monitoringApi = { - listRuns: async () => - (await apiRequest<{ items: ExecutionRunSummary[] }>("/api/runs")).items, + listRuns: async () => (await apiRequest<{ items: ExecutionRunSummary[] }>("/api/runs")).items, getRun: (runId: string) => apiRequest(`/api/runs/${runId}`), rerunSubtree: (runId: string, nodeId: string) => apiRequest(`/api/runs/${runId}/rerun-subtree`, { method: "POST" }, { nodeId }), - stopRun: (runId: string) => - apiRequest(`/api/runs/${runId}/stop`, { method: "POST" }), - forceStopRun: (runId: string) => - apiRequest(`/api/runs/${runId}/force-stop`, { method: "POST" }), + stopRun: (runId: string) => apiRequest(`/api/runs/${runId}/stop`, { method: "POST" }), + forceStopRun: (runId: string) => apiRequest(`/api/runs/${runId}/force-stop`, { method: "POST" }), getLogs: async (runId: string): Promise => (await apiRequest<{ items: LogEntry[] }>(`/api/runs/${runId}/logs`)).items, getResourceUsage: async (runId: string): Promise => - ( - await apiRequest<{ items: ResourceUsage[] }>( - `/api/runs/${runId}/resources`, - ) - ).items, + (await apiRequest<{ items: ResourceUsage[] }>(`/api/runs/${runId}/resources`)).items, getExecutionData: async (runId: string): Promise => - ( - await apiRequest<{ items: ExecutionData[] }>( - `/api/runs/${runId}/artifacts`, - ) - ).items, + (await apiRequest<{ items: ExecutionData[] }>(`/api/runs/${runId}/artifacts`)).items, listOssBuckets: async ({ sourcePath = "", connectionId = "" }: StorageBrowseTarget): Promise => { const query = new URLSearchParams(); if (connectionId.trim()) { @@ -46,11 +29,7 @@ export const monitoringApi = { if (sourcePath.trim()) { query.set("sourcePath", sourcePath.trim()); } - return ( - await apiRequest<{ items: string[] }>( - `/api/storage/buckets?${query.toString()}`, - ) - ).items; + return (await apiRequest<{ items: string[] }>(`/api/storage/buckets?${query.toString()}`)).items; }, listOssObjects: async ( { sourcePath = "", connectionId = "" }: StorageBrowseTarget, @@ -66,10 +45,6 @@ export const monitoringApi = { } query.set("bucket", bucket); query.set("prefix", prefix); - return ( - await apiRequest<{ items: string[] }>( - `/api/storage/objects?${query.toString()}`, - ) - ).items; + return (await apiRequest<{ items: string[] }>(`/api/storage/objects?${query.toString()}`)).items; }, }; diff --git a/src/services/api/object-storage.ts b/src/services/api/object-storage.ts index 456688ee..82172e08 100644 --- a/src/services/api/object-storage.ts +++ b/src/services/api/object-storage.ts @@ -52,10 +52,8 @@ function buildObjectStorageParams(options?: { } const OBJECT_STORAGE_PREVIEW_TRUNCATED_HEADER = "X-Drobodata-Preview-Truncated"; -const OBJECT_STORAGE_PREVIEW_ORIGINAL_SIZE_HEADER = - "X-Drobodata-Preview-Original-Bytes"; -const OBJECT_STORAGE_PREVIEW_RETURNED_SIZE_HEADER = - "X-Drobodata-Preview-Returned-Bytes"; +const OBJECT_STORAGE_PREVIEW_ORIGINAL_SIZE_HEADER = "X-Drobodata-Preview-Original-Bytes"; +const OBJECT_STORAGE_PREVIEW_RETURNED_SIZE_HEADER = "X-Drobodata-Preview-Returned-Bytes"; export interface ObjectStorageTextPreviewResult { content: string; @@ -78,13 +76,9 @@ async function uploadWithFormData(path: string, formData: FormData) { export const objectStorageApi = { getOverview: (options?: { connectionId?: string }) => - apiRequest( - `/api/object-storage${buildObjectStorageParams(options)}`, - ), + apiRequest(`/api/object-storage${buildObjectStorageParams(options)}`), listObjects: (options: { connectionId: string; bucket?: string; prefix?: string }) => - apiRequest( - `/api/object-storage/objects${buildObjectStorageParams(options)}`, - ), + apiRequest(`/api/object-storage/objects${buildObjectStorageParams(options)}`), putObject: ( payload: { bucket?: string; key: string; content: string; contentType?: string }, options: { connectionId: string }, @@ -105,28 +99,18 @@ export const objectStorageApi = { formData, ); }, - renameObject: ( - payload: { bucket?: string; key: string; newKey: string }, - options: { connectionId: string }, - ) => + renameObject: (payload: { bucket?: string; key: string; newKey: string }, options: { connectionId: string }) => apiRequest( `/api/object-storage/objects${buildObjectStorageParams(options)}`, { method: "PATCH" }, payload, ), - deleteObject: ( - options: { connectionId: string; bucket?: string; key: string; recursive?: boolean }, - ) => - apiRequest( - `/api/object-storage/objects${buildObjectStorageParams(options)}`, - { method: "DELETE" }, - ), - buildContentURL: (options: { - connectionId: string; - bucket?: string; - key: string; - transcode?: string; - }) => `/api/object-storage/content${buildObjectStorageParams(options)}`, + deleteObject: (options: { connectionId: string; bucket?: string; key: string; recursive?: boolean }) => + apiRequest(`/api/object-storage/objects${buildObjectStorageParams(options)}`, { + method: "DELETE", + }), + buildContentURL: (options: { connectionId: string; bucket?: string; key: string; transcode?: string }) => + `/api/object-storage/content${buildObjectStorageParams(options)}`, readObjectTextPreview: async (options: { connectionId: string; bucket?: string; @@ -153,14 +137,9 @@ export const objectStorageApi = { }; return { content, - truncated: - response.headers.get(OBJECT_STORAGE_PREVIEW_TRUNCATED_HEADER) === "true", - originalSizeBytes: parseBytesHeader( - OBJECT_STORAGE_PREVIEW_ORIGINAL_SIZE_HEADER, - ), - returnedSizeBytes: parseBytesHeader( - OBJECT_STORAGE_PREVIEW_RETURNED_SIZE_HEADER, - ), + truncated: response.headers.get(OBJECT_STORAGE_PREVIEW_TRUNCATED_HEADER) === "true", + originalSizeBytes: parseBytesHeader(OBJECT_STORAGE_PREVIEW_ORIGINAL_SIZE_HEADER), + returnedSizeBytes: parseBytesHeader(OBJECT_STORAGE_PREVIEW_RETURNED_SIZE_HEADER), }; }, }; diff --git a/src/services/api/operators.ts b/src/services/api/operators.ts index b80f8158..fa807752 100644 --- a/src/services/api/operators.ts +++ b/src/services/api/operators.ts @@ -3,8 +3,7 @@ import { apiRequest } from "./client"; export const operatorsApi = { list: async () => (await apiRequest<{ items: Operator[] }>("/api/operators")).items, - create: (payload: Partial) => - apiRequest("/api/operators", { method: "POST" }, payload), + create: (payload: Partial) => apiRequest("/api/operators", { method: "POST" }, payload), update: (id: string, payload: Partial) => apiRequest(`/api/operators/${id}`, { method: "PUT" }, payload), remove: (id: string) => apiRequest(`/api/operators/${id}`, { method: "DELETE" }), diff --git a/src/services/api/projects.ts b/src/services/api/projects.ts index 052aae4c..c64a66e2 100644 --- a/src/services/api/projects.ts +++ b/src/services/api/projects.ts @@ -9,11 +9,7 @@ export const projectsApi = { update: (id: string, payload: Partial) => apiRequest(`/api/projects/${id}`, { method: "PUT" }, payload), listStoragePathFavorites: async (id: string) => - ( - await apiRequest<{ items: StoragePathFavorite[] }>( - `/api/projects/${id}/storage-path-favorites`, - ) - ).items, + (await apiRequest<{ items: StoragePathFavorite[] }>(`/api/projects/${id}/storage-path-favorites`)).items, updateStoragePathFavorites: (id: string, items: StoragePathFavorite[]) => apiRequest<{ items: StoragePathFavorite[] }>( `/api/projects/${id}/storage-path-favorites`, diff --git a/src/services/api/settings.ts b/src/services/api/settings.ts index 23c41926..61a74164 100644 --- a/src/services/api/settings.ts +++ b/src/services/api/settings.ts @@ -3,6 +3,5 @@ import { apiRequest } from "./client"; export const settingsApi = { get: () => apiRequest("/api/settings"), - update: (payload: Partial) => - apiRequest("/api/settings", { method: "PUT" }, payload), + update: (payload: Partial) => apiRequest("/api/settings", { method: "PUT" }, payload), }; diff --git a/src/services/api/storage-connections.ts b/src/services/api/storage-connections.ts index daae1bf0..3aaa1e2e 100644 --- a/src/services/api/storage-connections.ts +++ b/src/services/api/storage-connections.ts @@ -12,23 +12,11 @@ type StorageConnectionPayload = { }; export const storageConnectionsApi = { - list: async () => - (await apiRequest<{ items: StorageConnection[] }>("/api/storage/connections")) - .items, - get: (id: string) => - apiRequest(`/api/storage/connections/${id}`), + list: async () => (await apiRequest<{ items: StorageConnection[] }>("/api/storage/connections")).items, + get: (id: string) => apiRequest(`/api/storage/connections/${id}`), create: (payload: StorageConnectionPayload) => - apiRequest( - "/api/storage/connections", - { method: "POST" }, - payload, - ), + apiRequest("/api/storage/connections", { method: "POST" }, payload), update: (id: string, payload: Partial) => - apiRequest( - `/api/storage/connections/${id}`, - { method: "PUT" }, - payload, - ), - remove: (id: string) => - apiRequest(`/api/storage/connections/${id}`, { method: "DELETE" }), + apiRequest(`/api/storage/connections/${id}`, { method: "PUT" }, payload), + remove: (id: string) => apiRequest(`/api/storage/connections/${id}`, { method: "DELETE" }), }; diff --git a/src/services/api/users.ts b/src/services/api/users.ts index 636eea37..784020a3 100644 --- a/src/services/api/users.ts +++ b/src/services/api/users.ts @@ -5,14 +5,9 @@ export const usersApi = { list: async () => (await apiRequest<{ items: User[] }>("/api/users")).items, create: (payload: Pick) => apiRequest("/api/users", { method: "POST" }, payload), - update: (id: string, payload: Partial) => - apiRequest(`/api/users/${id}`, { method: "PUT" }, payload), + update: (id: string, payload: Partial) => apiRequest(`/api/users/${id}`, { method: "PUT" }, payload), listStoragePathFavorites: async (id: string) => - ( - await apiRequest<{ items: StoragePathFavorite[] }>( - `/api/users/${id}/storage-path-favorites`, - ) - ).items, + (await apiRequest<{ items: StoragePathFavorite[] }>(`/api/users/${id}/storage-path-favorites`)).items, updateStoragePathFavorites: (id: string, items: StoragePathFavorite[]) => apiRequest<{ items: StoragePathFavorite[] }>( `/api/users/${id}/storage-path-favorites`, diff --git a/src/services/api/workflows.ts b/src/services/api/workflows.ts index 657792c5..6f9429e0 100644 --- a/src/services/api/workflows.ts +++ b/src/services/api/workflows.ts @@ -1,9 +1,4 @@ -import type { - ExecutionRun, - ExecutionRunSummary, - Workflow, - WorkflowNodeSourceState, -} from "../../types"; +import type { ExecutionRun, ExecutionRunSummary, Workflow, WorkflowNodeSourceState } from "../../types"; import { apiRequest } from "./client"; export const workflowsApi = { diff --git a/src/types.ts b/src/types.ts index 20c52d39..f820a56c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -608,13 +608,7 @@ export interface SamplingTask { updatedAt: string; } -export type NodeExecutionStatus = - | "queued" - | "running" - | "cancelled" - | "waiting_for_audit" - | "completed" - | "failed"; +export type NodeExecutionStatus = "queued" | "running" | "cancelled" | "waiting_for_audit" | "completed" | "failed"; export interface NodeExecution { nodeId: string; @@ -639,14 +633,7 @@ export interface ExecutionRun { parentRunId?: string; restartFromNodeId?: string; availableAt?: string; - status: - | "queued" - | "running" - | "stopping" - | "waiting_for_audit" - | "completed" - | "failed" - | "cancelled"; + status: "queued" | "running" | "stopping" | "waiting_for_audit" | "completed" | "failed" | "cancelled"; stopMode?: "graceful" | "force"; stopRequestedAt?: string; previousRunAt?: string; @@ -675,14 +662,7 @@ export interface ExecutionRunSummary { parentRunId?: string; restartFromNodeId?: string; availableAt?: string; - status: - | "queued" - | "running" - | "stopping" - | "waiting_for_audit" - | "completed" - | "failed" - | "cancelled"; + status: "queued" | "running" | "stopping" | "waiting_for_audit" | "completed" | "failed" | "cancelled"; stopMode?: "graceful" | "force"; stopRequestedAt?: string; startedAt?: string; diff --git a/tests/frontend/data-assets.test.mjs b/tests/frontend/data-assets.test.mjs index 9db46d82..58d9e817 100644 --- a/tests/frontend/data-assets.test.mjs +++ b/tests/frontend/data-assets.test.mjs @@ -45,10 +45,7 @@ test("data asset scope matching supports project workflow and run filtering", () assert.equal(matchesDataAssetScope(item, { projectId: "project-1" }), true); assert.equal(matchesDataAssetScope(item, { workflowId: "workflow-1" }), true); assert.equal(matchesDataAssetScope(item, { runId: "run-1" }), true); - assert.equal( - matchesDataAssetScope(item, { projectId: "project-1", workflowId: "workflow-1" }), - true, - ); + assert.equal(matchesDataAssetScope(item, { projectId: "project-1", workflowId: "workflow-1" }), true); assert.equal(matchesDataAssetScope(item, { projectId: "project-2" }), false); assert.equal(matchesDataAssetScope(item, { workflowId: "workflow-2" }), false); assert.equal(matchesDataAssetScope(item, { runId: "run-2" }), false); diff --git a/tests/frontend/scan-workflows.test.mjs b/tests/frontend/scan-workflows.test.mjs index a37c2a0c..00bf7e4d 100644 --- a/tests/frontend/scan-workflows.test.mjs +++ b/tests/frontend/scan-workflows.test.mjs @@ -130,18 +130,9 @@ test("scan workflow config payload falls back to incremental source node when wo }); test("workflow schedule helpers support hourly and daily modes", () => { - assert.equal( - effectiveWorkflowScheduleMode({ mode: "every_hours", intervalHours: 4 }), - "every_hours", - ); - assert.equal( - effectiveWorkflowScheduleMode({ dayInterval: 2, timeOfDay: "18:30" }), - "every_days_at_time", - ); - assert.equal( - isWorkflowScheduleEnabled({ mode: "every_hours", intervalHours: 4 }), - true, - ); + assert.equal(effectiveWorkflowScheduleMode({ mode: "every_hours", intervalHours: 4 }), "every_hours"); + assert.equal(effectiveWorkflowScheduleMode({ dayInterval: 2, timeOfDay: "18:30" }), "every_days_at_time"); + assert.equal(isWorkflowScheduleEnabled({ mode: "every_hours", intervalHours: 4 }), true); assert.equal( isWorkflowScheduleEnabled({ mode: "every_days_at_time", @@ -245,22 +236,13 @@ test("scan config patch keeps workflow config, schedule, type, and source node d assert.equal(updated.nodes[0].data.bucket, "datastorage"); assert.equal(updated.nodes[0].data.prefix, "algo/X-platform-test"); assert.equal(updated.nodes[0].data.label, "BOS 增量扫描"); - assert.equal( - updated.nodes[0].data.hyperparams.find((item) => item.key === "DATA_SOURCE")?.value, - "BOS", - ); + assert.equal(updated.nodes[0].data.hyperparams.find((item) => item.key === "DATA_SOURCE")?.value, "BOS"); assert.equal( updated.nodes[0].data.hyperparams.find((item) => item.key === "SOURCE_PATH")?.value, "bos://datastorage/algo/X-platform-test", ); - assert.equal( - updated.nodes[0].data.hyperparams.find((item) => item.key === "SCAN_MODE")?.value, - "FULL", - ); - assert.equal( - updated.nodes[0].data.hyperparams.find((item) => item.key === "INCREMENTAL_UNIT")?.value, - "DIRECTORY", - ); + assert.equal(updated.nodes[0].data.hyperparams.find((item) => item.key === "SCAN_MODE")?.value, "FULL"); + assert.equal(updated.nodes[0].data.hyperparams.find((item) => item.key === "INCREMENTAL_UNIT")?.value, "DIRECTORY"); assert.equal( updated.nodes[0].data.hyperparams.find((item) => item.key === "INCREMENTAL_DIRECTORY_DEPTH")?.value, "2", diff --git a/tests/frontend/storage-path-history.test.mjs b/tests/frontend/storage-path-history.test.mjs index d8bf55eb..c66c119e 100644 --- a/tests/frontend/storage-path-history.test.mjs +++ b/tests/frontend/storage-path-history.test.mjs @@ -51,11 +51,7 @@ test("rememberStoragePath deduplicates and keeps newest entries first", () => { rememberStoragePath(target, { bucket: "datastorage", prefix: "algo/a" }, storage); rememberStoragePath(target, { bucket: "datastorage", prefix: "algo/b" }, storage); - const items = rememberStoragePath( - target, - { bucket: "datastorage", prefix: "algo/a" }, - storage, - ); + const items = rememberStoragePath(target, { bucket: "datastorage", prefix: "algo/a" }, storage); assert.deepEqual(items, [ { @@ -77,11 +73,7 @@ test("listRecentStoragePaths isolates scopes and caps the history length", () => const targetB = { connectionId: "conn-b" }; for (let index = 0; index < MAX_RECENT_STORAGE_PATHS + 2; index += 1) { - rememberStoragePath( - targetA, - { bucket: "datastorage", prefix: `algo/run-${index}` }, - storage, - ); + rememberStoragePath(targetA, { bucket: "datastorage", prefix: `algo/run-${index}` }, storage); } rememberStoragePath(targetB, { bucket: "other", prefix: "root" }, storage); @@ -114,11 +106,7 @@ test("toggleFavoriteStoragePath pins and unpins scoped favorites", () => { const storage = createMemoryStorage(); const target = { connectionId: "conn-1" }; - let items = toggleFavoriteStoragePath( - target, - { bucket: "datastorage", prefix: "algo/a" }, - storage, - ); + let items = toggleFavoriteStoragePath(target, { bucket: "datastorage", prefix: "algo/a" }, storage); assert.deepEqual(items, [ { bucket: "datastorage", @@ -127,11 +115,7 @@ test("toggleFavoriteStoragePath pins and unpins scoped favorites", () => { }, ]); - items = toggleFavoriteStoragePath( - target, - { bucket: "datastorage", prefix: "algo/a" }, - storage, - ); + items = toggleFavoriteStoragePath(target, { bucket: "datastorage", prefix: "algo/a" }, storage); assert.deepEqual(items, []); }); @@ -141,17 +125,9 @@ test("favorite storage paths are isolated by scope and capped independently", () const targetB = { sourcePath: "bos://other/root" }; for (let index = 0; index < MAX_FAVORITE_STORAGE_PATHS + 3; index += 1) { - toggleFavoriteStoragePath( - targetA, - { bucket: "datastorage", prefix: `algo/favorite-${index}` }, - storage, - ); + toggleFavoriteStoragePath(targetA, { bucket: "datastorage", prefix: `algo/favorite-${index}` }, storage); } - toggleFavoriteStoragePath( - targetB, - { bucket: "other", prefix: "root" }, - storage, - ); + toggleFavoriteStoragePath(targetB, { bucket: "other", prefix: "root" }, storage); const itemsA = listFavoriteStoragePaths(targetA, storage); const itemsB = listFavoriteStoragePaths(targetB, storage); @@ -175,16 +151,8 @@ test("favorites and recents are stored independently", () => { const storage = createMemoryStorage(); const target = { connectionId: "conn-1" }; - rememberStoragePath( - target, - { bucket: "datastorage", prefix: "algo/recent-only" }, - storage, - ); - toggleFavoriteStoragePath( - target, - { bucket: "datastorage", prefix: "algo/favorite-only" }, - storage, - ); + rememberStoragePath(target, { bucket: "datastorage", prefix: "algo/recent-only" }, storage); + toggleFavoriteStoragePath(target, { bucket: "datastorage", prefix: "algo/favorite-only" }, storage); assert.deepEqual(listRecentStoragePaths(target, storage), [ { diff --git a/tests/frontend/template-settings.test.mjs b/tests/frontend/template-settings.test.mjs index 0ef84526..f85a8072 100644 --- a/tests/frontend/template-settings.test.mjs +++ b/tests/frontend/template-settings.test.mjs @@ -1,10 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { - buildTemplatePayload, - buildWorkflowFromTemplate, -} from "../../src/lib/templates.js"; +import { buildTemplatePayload, buildWorkflowFromTemplate } from "../../src/lib/templates.js"; test("buildWorkflowFromTemplate preserves workflow-level execution config", () => { const payload = buildWorkflowFromTemplate({ diff --git a/tests/frontend/templates.test.mjs b/tests/frontend/templates.test.mjs index a7fcee74..0f0563f5 100644 --- a/tests/frontend/templates.test.mjs +++ b/tests/frontend/templates.test.mjs @@ -1,11 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { - buildTemplatePayload, - buildWorkflowCopyPayload, - buildWorkflowFromTemplate, -} from "../../src/lib/templates.js"; +import { buildTemplatePayload, buildWorkflowCopyPayload, buildWorkflowFromTemplate } from "../../src/lib/templates.js"; test("buildTemplatePayload keeps scan config and execution settings", () => { const workflow = { @@ -92,7 +88,9 @@ test("buildWorkflowCopyPayload keeps all workflow-level fields", () => { maxRetryAttempts: 4, retryBackoffSeconds: 30, schedule: { interval: 600, sourcePath: "bos://wjzh-data-migration/wjzh-0330-Data-migration" }, - nodes: [{ id: "n1", data: { label: "BOS 增量扫描", hyperparams: [{ key: "BOS_SECRET_ACCESS_KEY", value: "secret" }] } }], + nodes: [ + { id: "n1", data: { label: "BOS 增量扫描", hyperparams: [{ key: "BOS_SECRET_ACCESS_KEY", value: "secret" }] } }, + ], edges: [{ id: "e1", source: "n1", target: "n2" }], }; diff --git a/tests/frontend/video-preview.test.mjs b/tests/frontend/video-preview.test.mjs index 69f75f06..1d97ca1c 100644 --- a/tests/frontend/video-preview.test.mjs +++ b/tests/frontend/video-preview.test.mjs @@ -71,8 +71,5 @@ test("does not duplicate browser transcode flag", () => { }); test("leaves non source data urls untouched", () => { - assert.equal( - buildBrowserPlayableVideoURL("https://example.com/preview.mp4"), - "https://example.com/preview.mp4", - ); + assert.equal(buildBrowserPlayableVideoURL("https://example.com/preview.mp4"), "https://example.com/preview.mp4"); }); diff --git a/tests/frontend/workflow-canvas.test.mjs b/tests/frontend/workflow-canvas.test.mjs index 23f08a3b..a4656534 100644 --- a/tests/frontend/workflow-canvas.test.mjs +++ b/tests/frontend/workflow-canvas.test.mjs @@ -120,7 +120,5 @@ test("removing selected edges leaves nodes intact", () => { assert.deepEqual(result.removedEdgeIds, ["edge-a"]); assert.equal(result.nodes.length, 2); - assert.deepEqual(result.edges, [ - { id: "edge-b", source: "node-b", target: "node-a", selected: false }, - ]); + assert.deepEqual(result.edges, [{ id: "edge-b", source: "node-b", target: "node-a", selected: false }]); }); diff --git a/tests/frontend/workflow-run.test.mjs b/tests/frontend/workflow-run.test.mjs index 1de3ab3c..9b6192cd 100644 --- a/tests/frontend/workflow-run.test.mjs +++ b/tests/frontend/workflow-run.test.mjs @@ -173,14 +173,9 @@ test("resolves edge output artifacts by source handle and source port definition }, ]; - assert.deepEqual( - getEdgeOutputArtifacts( - { id: "edge-1", source: "source", sourceHandle: "out-1" }, - run, - graphNodes, - ), - [run.nodeExecutions[0].artifacts[0]], - ); + assert.deepEqual(getEdgeOutputArtifacts({ id: "edge-1", source: "source", sourceHandle: "out-1" }, run, graphNodes), [ + run.nodeExecutions[0].artifacts[0], + ]); }); test("resolves edge output artifacts by port name when the run payload lacks port ids", () => { @@ -212,11 +207,7 @@ test("resolves edge output artifacts by port name when the run payload lacks por ]; assert.deepEqual( - getEdgeOutputArtifacts( - { id: "edge-1", source: "source", sourceHandle: "approved" }, - run, - graphNodes, - ), + getEdgeOutputArtifacts({ id: "edge-1", source: "source", sourceHandle: "approved" }, run, graphNodes), [run.nodeExecutions[0].artifacts[0]], ); }); diff --git a/tests/frontend/workflow-system-env.test.mjs b/tests/frontend/workflow-system-env.test.mjs index b1c73712..f7963b6b 100644 --- a/tests/frontend/workflow-system-env.test.mjs +++ b/tests/frontend/workflow-system-env.test.mjs @@ -1,16 +1,10 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { - buildWorkflowSystemEnvVarsPreview, - toWorkflowEnvDateTime, -} from "../../src/lib/workflow-system-env.js"; +import { buildWorkflowSystemEnvVarsPreview, toWorkflowEnvDateTime } from "../../src/lib/workflow-system-env.js"; test("converts ISO timestamps to Asia/Shanghai datetime strings", () => { - assert.equal( - toWorkflowEnvDateTime("2026-04-21T10:00:00Z"), - "2026-04-21T18:00:00+08:00", - ); + assert.equal(toWorkflowEnvDateTime("2026-04-21T10:00:00Z"), "2026-04-21T18:00:00+08:00"); assert.equal(toWorkflowEnvDateTime(""), ""); assert.equal(toWorkflowEnvDateTime("not-a-date"), ""); }); diff --git a/tmp/business-mongo-validation.mjs b/tmp/business-mongo-validation.mjs deleted file mode 100644 index 5f2043ae..00000000 --- a/tmp/business-mongo-validation.mjs +++ /dev/null @@ -1,124 +0,0 @@ -const base = "http://114.111.24.223:30080"; -const stamp = Date.now(); -const projectName = `Business Mongo Validation ${stamp}`; -const workflowName = `Business Mongo Write ${stamp}`; -const doc = { - runLabel: `business-mongo-${stamp}`, - source: "workflow", - value: 1, - createdAt: new Date().toISOString(), -}; - -async function api(path, init = {}) { - const response = await fetch(`${base}${path}`, { - ...init, - headers: { - "Content-Type": "application/json", - ...(init.headers || {}), - }, - }); - const text = await response.text(); - if (!response.ok) { - throw new Error(`${response.status} ${text}`); - } - return text ? JSON.parse(text) : null; -} - -async function main() { - const project = await api("/api/projects", { - method: "POST", - body: JSON.stringify({ - name: projectName, - description: "Validate business Mongo write operator", - }), - }); - - const workflow = await api(`/api/projects/${project.id}/workflows`, { - method: "POST", - body: JSON.stringify({ - name: workflowName, - description: "Writes workflow output into business MongoDB", - nodes: [ - { - id: "node-source", - type: "operator", - position: { x: 120, y: 180 }, - data: { - label: "真实数据源", - category: "IO", - description: "source", - inputs: [], - outputs: [{ id: "out-json", name: "output", type: "json" }], - hyperparams: [{ key: "SOURCE_JSON", value: JSON.stringify([doc]) }], - }, - }, - { - id: "node-mongo", - type: "operator", - position: { x: 420, y: 180 }, - data: { - label: "MongoDB 写入", - category: "DATA", - description: "write business data", - inputs: [{ id: "input", name: "input", type: "json" }], - outputs: [{ id: "result", name: "result", type: "json" }], - hyperparams: [ - { key: "MONGO_COLLECTION", value: "businessWriteValidation" }, - { key: "MONGO_MODE", value: "insert_many" }, - { key: "MONGO_TARGET", value: "business" }, - ], - }, - }, - ], - edges: [ - { - id: "edge-source-mongo", - source: "node-source", - sourceHandle: "out-json", - target: "node-mongo", - targetHandle: "input", - }, - ], - }), - }); - - const run = await api(`/api/workflows/${workflow.id}/run`, { - method: "POST", - body: JSON.stringify({ trigger: "manual" }), - }); - - let latest = null; - for (let attempt = 0; attempt < 90; attempt += 1) { - latest = await api(`/api/runs/${run.id}`); - if (latest.status === "completed" || latest.status === "failed") { - break; - } - await new Promise((resolve) => setTimeout(resolve, 2000)); - } - - if (!latest || latest.status !== "completed") { - console.log(JSON.stringify({ project, workflow, run: latest }, null, 2)); - process.exit(1); - } - - const filter = encodeURIComponent(JSON.stringify({ runLabel: doc.runLabel })); - const query = await api(`/api/database/collections/businessWriteValidation/documents?filter=${filter}&limit=10`); - console.log( - JSON.stringify( - { - projectId: project.id, - workflowId: workflow.id, - runId: run.id, - runStatus: latest.status, - query, - }, - null, - 2, - ), - ); -} - -main().catch((error) => { - console.error(error); - process.exit(1); -}); diff --git a/tmp/business-mongo-validation.sh b/tmp/business-mongo-validation.sh deleted file mode 100644 index b14b89e3..00000000 --- a/tmp/business-mongo-validation.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -base='http://114.111.24.223:30080' -stamp="$(date +%s)" -connection_payload="$(jq -nc --arg name "Business Mongo ${stamp}" --arg description 'Validation business mongo connection' --arg uri 'mongodb://business-mongodb.droboticflow.svc.cluster.local:27017' --arg database 'business_data' '{name:$name,description:$description,uri:$uri,database:$database}')" -connection="$(curl -fsS -X POST "$base/api/mongo/connections" -H 'Content-Type: application/json' --data-binary "$connection_payload")" -connection_id="$(printf '%s' "$connection" | jq -r '.id')" -draft_test="$(curl -fsS -X POST "$base/api/mongo/connections/test" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg uri 'mongodb://business-mongodb.droboticflow.svc.cluster.local:27017' --arg database 'business_data' '{uri:$uri,database:$database}')")" -stored_test="$(curl -fsS -X POST "$base/api/mongo/connections/test" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg id "$connection_id" '{id:$id}')")" - -project_payload="$(jq -nc --arg name "Business Mongo Validation ${stamp}" --arg description 'Validate business Mongo write operator' '{name:$name,description:$description}')" -project="$(curl -fsS -X POST "$base/api/projects" -H 'Content-Type: application/json' --data-binary "$project_payload")" -project_id="$(printf '%s' "$project" | jq -r '.id')" - -doc="$(jq -nc --arg runLabel "business-mongo-${stamp}" --arg createdAt "$(date -u +%FT%TZ)" '{runLabel:$runLabel,source:"workflow",value:1,createdAt:$createdAt}')" -source_json="$(jq -nc --argjson doc "$doc" '[ $doc ]')" -workflow_payload="$(jq -nc \ - --arg name "Business Mongo Write ${stamp}" \ - --arg description 'Writes workflow output into business MongoDB' \ - --arg source_json "$source_json" \ - --arg connection_id "$connection_id" \ - '{name:$name,description:$description,nodes:[{id:"node-source",type:"operator",position:{x:120,y:180},data:{label:"真实数据源",category:"IO",description:"source",inputs:[],outputs:[{id:"out-json",name:"output",type:"json"}],hyperparams:[{key:"SOURCE_JSON",value:$source_json}]}},{id:"node-mongo",type:"operator",position:{x:420,y:180},data:{label:"MongoDB 写入",category:"DATA",description:"write business data",inputs:[{id:"input",name:"input",type:"json"}],outputs:[{id:"result",name:"result",type:"json"}],hyperparams:[{key:"MONGO_COLLECTION",value:"businessWriteValidation"},{key:"MONGO_MODE",value:"insert_many"},{key:"MONGO_CONNECTION_ID",value:$connection_id},{key:"MONGO_TARGET",value:"business"}]}}],edges:[{id:"edge-source-mongo",source:"node-source",sourceHandle:"out-json",target:"node-mongo",targetHandle:"input"}] }')" - -workflow="$(curl -fsS -X POST "$base/api/projects/$project_id/workflows" -H 'Content-Type: application/json' --data-binary "$workflow_payload")" -workflow_id="$(printf '%s' "$workflow" | jq -r '.id')" -run="$(curl -fsS -X POST "$base/api/workflows/$workflow_id/run" -H 'Content-Type: application/json' --data-binary '{"trigger":"manual"}')" -run_id="$(printf '%s' "$run" | jq -r '.id')" - -run_state='' -run_detail='' -for _ in $(seq 1 90); do - run_detail="$(curl -fsS "$base/api/runs/$run_id")" - run_state="$(printf '%s' "$run_detail" | jq -r '.status')" - if [[ "$run_state" == 'completed' || "$run_state" == 'failed' ]]; then - break - fi - sleep 2 -done - -if [[ "$run_state" != 'completed' ]]; then - printf '%s\n' "$run_detail" - exit 1 -fi - -filter="$(python3 -c 'import json, urllib.parse, sys; print(urllib.parse.quote(json.dumps({"runLabel": sys.argv[1]})))' "business-mongo-${stamp}")" -query="$(curl -fsS "$base/api/database/collections/businessWriteValidation/documents?connectionId=${connection_id}&filter=${filter}&limit=10")" -crud_collection="crudValidation_${stamp}" -crud_collection_renamed="crudValidationRenamed_${stamp}" - -create_collection="$(curl -fsS -X POST "$base/api/database/collections?connectionId=${connection_id}" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg name "$crud_collection" '{name:$name}')")" -create_document="$(curl -fsS -X POST "$base/api/database/collections/${crud_collection}/documents?connectionId=${connection_id}" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg recordKey "crud-${stamp}" '{document:{recordKey:$recordKey,status:"draft",amount:1}}')")" -crud_document_id="$(printf '%s' "$create_document" | jq -r '.document._id."$oid" // .document._id')" -crud_query_filter="$(python3 -c 'import json, urllib.parse, sys; print(urllib.parse.quote(json.dumps({"recordKey": sys.argv[1]})))' "crud-${stamp}")" -crud_query_before="$(curl -fsS "$base/api/database/collections/${crud_collection}/documents?connectionId=${connection_id}&filter=${crud_query_filter}&limit=10")" -update_document="$(curl -fsS -X PUT "$base/api/database/collections/${crud_collection}/documents/${crud_document_id}?connectionId=${connection_id}" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg recordKey "crud-${stamp}" '{document:{recordKey:$recordKey,status:"done",amount:2}}')")" -rename_collection="$(curl -fsS -X PATCH "$base/api/database/collections/${crud_collection}?connectionId=${connection_id}" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg newName "$crud_collection_renamed" '{newName:$newName}')")" -create_index="$(curl -fsS -X POST "$base/api/database/collections/${crud_collection_renamed}/indexes?connectionId=${connection_id}" -H 'Content-Type: application/json' --data-binary "$(jq -nc --arg name "idx_record_key_${stamp}" '{name:$name,keys:{recordKey:1},unique:true}')")" -list_indexes="$(curl -fsS "$base/api/database/collections/${crud_collection_renamed}/indexes?connectionId=${connection_id}")" -delete_index="$(curl -fsS -X DELETE "$base/api/database/collections/${crud_collection_renamed}/indexes/idx_record_key_${stamp}?connectionId=${connection_id}")" -delete_document="$(curl -fsS -X DELETE "$base/api/database/collections/${crud_collection_renamed}/documents/${crud_document_id}?connectionId=${connection_id}")" -delete_collection="$(curl -fsS -X DELETE "$base/api/database/collections/${crud_collection_renamed}?connectionId=${connection_id}")" -crud_overview="$(curl -fsS "$base/api/database?connectionId=${connection_id}")" - -jq -nc \ - --arg connectionId "$connection_id" \ - --arg projectId "$project_id" \ - --arg workflowId "$workflow_id" \ - --arg runId "$run_id" \ - --arg runStatus "$run_state" \ - --argjson draftTest "$draft_test" \ - --argjson storedTest "$stored_test" \ - --argjson query "$query" \ - --argjson createCollection "$create_collection" \ - --argjson createDocument "$create_document" \ - --argjson crudQueryBefore "$crud_query_before" \ - --argjson updateDocument "$update_document" \ - --argjson renameCollection "$rename_collection" \ - --argjson createIndex "$create_index" \ - --argjson listIndexes "$list_indexes" \ - --argjson deleteIndex "$delete_index" \ - --argjson deleteDocument "$delete_document" \ - --argjson deleteCollection "$delete_collection" \ - --argjson crudOverview "$crud_overview" \ - '{connectionId:$connectionId,projectId:$projectId,workflowId:$workflowId,runId:$runId,runStatus:$runStatus,tests:{draftConnection:$draftTest,storedConnection:$storedTest},query:$query,crud:{createCollection:$createCollection,createDocument:$createDocument,queryBefore:$crudQueryBefore,updateDocument:$updateDocument,renameCollection:$renameCollection,createIndex:$createIndex,listIndexes:$listIndexes,deleteIndex:$deleteIndex,deleteDocument:$deleteDocument,deleteCollection:$deleteCollection,overview:$crudOverview}}' diff --git a/tmp/live-real-data-acceptance.mjs b/tmp/live-real-data-acceptance.mjs deleted file mode 100644 index 79873fd1..00000000 --- a/tmp/live-real-data-acceptance.mjs +++ /dev/null @@ -1,320 +0,0 @@ -const BASE = "http://114.111.24.223:30080"; -const SOURCE_PATH = - "bos://datastorage/algo/X-platform-test/raw/BJ_001_0001_OsmoNano_2026-03-19_14-51-43"; -const CONNECTION_ID = "storage-d69ba0e9824a9abd216eced490f0aed3"; -const BUCKET = "datastorage"; -const PREFIX = "algo/X-platform-test/raw/BJ_001_0001_OsmoNano_2026-03-19_14-51-43"; - -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -async function request(method, path, payload, expected = [200, 201, 202, 204]) { - let lastError; - for (let attempt = 1; attempt <= 6; attempt += 1) { - try { - const response = await fetch(`${BASE}${path}`, { - method, - headers: { "Content-Type": "application/json" }, - body: payload === undefined ? undefined : JSON.stringify(payload), - }); - const text = await response.text(); - if (!expected.includes(response.status)) { - throw new Error(`${method} ${path} failed ${response.status}: ${text}`); - } - return text ? JSON.parse(text) : null; - } catch (error) { - lastError = error; - if (attempt === 6) { - throw error; - } - await sleep(Math.min(attempt, 3) * 1000); - } - } - throw lastError; -} - -function buildNode(operator, nodeId, x, y, overrides = {}, extra = {}) { - const hyper = (operator.hyperparams || []).map((item) => ({ ...item })); - const seen = new Set(); - for (const item of hyper) { - if (Object.prototype.hasOwnProperty.call(overrides, item.key)) { - item.value = overrides[item.key]; - seen.add(item.key); - } - } - for (const [key, value] of Object.entries(overrides)) { - if (seen.has(key)) { - continue; - } - hyper.push({ key, value }); - } - return { - id: nodeId, - type: "operator", - data: { - label: operator.name, - category: operator.category, - description: operator.description, - inputs: operator.inputs || [], - outputs: operator.outputs || [], - image: operator.image || "", - skillDefinition: operator.skillDefinition || "", - hyperparams: hyper, - ...extra, - }, - position: { x, y }, - }; -} - -const interestingArtifactNames = new Set([ - "source-manifest.json", - "dataset-index.json", - "dataset-validation.json", - "quality-report.json", - "filtered-videos.json", - "clips-manifest.json", - "annotations-manifest.json", - "packages-manifest.json", - "audit-samples.json", - "uploaded-results.json", -]); - -async function cleanupAll() { - const scanWorkflows = (await request("GET", "/api/scan-configs")).items; - for (const workflow of scanWorkflows) { - await request("DELETE", `/api/scan-configs/${encodeURIComponent(workflow.id)}`); - } - const projects = (await request("GET", "/api/projects")).items; - for (const project of projects) { - const workflows = ( - await request("GET", `/api/projects/${encodeURIComponent(project.id)}/workflows`) - ).items; - for (const workflow of workflows) { - await request("DELETE", `/api/workflows/${encodeURIComponent(workflow.id)}`); - } - await request("DELETE", `/api/projects/${encodeURIComponent(project.id)}`); - } - const templates = (await request("GET", "/api/templates")).items; - for (const template of templates) { - await request("DELETE", `/api/templates/${encodeURIComponent(template.id)}`); - } -} - -async function main() { - await cleanupAll(); - - const operators = (await request("GET", "/api/operators")).items; - const byName = Object.fromEntries(operators.map((item) => [item.name, item])); - const needed = [ - "BOS 增量扫描", - "X 平台数据集索引", - "采集目录校验", - "视频质检", - "数据过滤", - "视频切片", - "视频标注", - "成品打包", - "抽检采样", - "结果上传", - ]; - for (const name of needed) { - if (!byName[name]) { - throw new Error(`missing operator: ${name}`); - } - } - - const ts = new Date().toISOString().replace(/[-:TZ.]/g, "").slice(0, 14); - const outputPrefix = `factory/output/xplatform-real-data/${ts}`; - const outputPath = `bos://${BUCKET}/${outputPrefix}`; - const project = await request("POST", "/api/projects", { - name: `XPlatform Real Data ${ts}`, - description: "真实 BOS 数据验收项目", - }); - - const nodes = [ - buildNode( - byName["BOS 增量扫描"], - "source", - 0, - 0, - { - DATA_SOURCE: "BOS", - SOURCE_PATH: SOURCE_PATH, - SCAN_MODE: "FULL", - }, - { connectionId: CONNECTION_ID, bucket: BUCKET, prefix: PREFIX }, - ), - buildNode(byName["X 平台数据集索引"], "index", 260, 0), - buildNode(byName["采集目录校验"], "validate", 520, 0, { - REQUIRE_INTRINSICS: "false", - }), - buildNode(byName["视频质检"], "quality", 780, 0, { - MIN_CLARITY: "0.8", - MAX_SHAKE: "0.2", - MAX_HAND_OCCLUSION: "0.2", - CLARITY_SCALE: "35", - }), - buildNode(byName["数据过滤"], "filter", 1040, 0, { - DATE_START: "2026-02-01", - DATE_END: "2026-04-05", - PLACE: "蓟门里小区", - TYPE: "家庭", - MIN_CLARITY: "0.8", - MAX_SHAKE: "0.2", - MAX_HAND_OCCLUSION: "0.2", - }), - buildNode(byName["视频切片"], "slice", 1300, 0, { - SEGMENT_DURATION_SECONDS: "300", - }), - buildNode(byName["视频标注"], "annotate", 1560, 0, { - FRAME_INTERVAL_SECONDS: "1.0", - }), - buildNode(byName["成品打包"], "package", 1820, 0), - buildNode(byName["抽检采样"], "sample", 2080, -100, { - RULES_JSON: JSON.stringify([ - { - id: "clarity-check", - field: "quality.clarity", - operator: "lt", - value: 1.0, - samplePercent: 100, - }, - ]), - }), - buildNode( - byName["结果上传"], - "upload", - 2080, - 120, - { - DATA_SOURCE: "BOS", - OUTPUT_PATH: outputPath, - SOURCE_PATH: outputPath, - }, - { connectionId: CONNECTION_ID, bucket: BUCKET, prefix: outputPrefix }, - ), - ]; - - const edges = [ - { - id: "source-index", - source: "source", - sourceHandle: "out-1", - target: "index", - targetHandle: "in-1", - }, - { - id: "index-validate", - source: "index", - sourceHandle: "out-1", - target: "validate", - targetHandle: "in-1", - }, - { - id: "validate-quality", - source: "validate", - sourceHandle: "out-1", - target: "quality", - targetHandle: "in-1", - }, - { - id: "quality-filter", - source: "quality", - sourceHandle: "out-1", - target: "filter", - targetHandle: "in-1", - }, - { - id: "filter-slice", - source: "filter", - sourceHandle: "out-1", - target: "slice", - targetHandle: "in-1", - }, - { - id: "slice-annotate", - source: "slice", - sourceHandle: "out-1", - target: "annotate", - targetHandle: "in-1", - }, - { - id: "annotate-package", - source: "annotate", - sourceHandle: "out-1", - target: "package", - targetHandle: "in-1", - }, - { - id: "package-sample", - source: "package", - sourceHandle: "out-1", - target: "sample", - targetHandle: "in-1", - }, - { - id: "package-upload", - source: "package", - sourceHandle: "out-1", - target: "upload", - targetHandle: "in-1", - }, - ]; - - const workflow = await request( - "POST", - `/api/projects/${encodeURIComponent(project.id)}/workflows`, - { - name: `XPlatform Real Pipeline ${ts}`, - description: "基于真实 BOS 数据的 X 平台处理流程", - type: "batch", - nodes, - edges, - }, - ); - const run = await request("POST", `/api/workflows/${encodeURIComponent(workflow.id)}/run`, { - trigger: "manual", - }); - - let terminal = null; - for (let index = 0; index < 900; index += 1) { - const current = await request("GET", `/api/runs/${encodeURIComponent(run.id)}`); - if (["completed", "failed", "cancelled", "waiting_for_audit"].includes(current.status)) { - terminal = current; - break; - } - await sleep(2000); - } - if (!terminal) { - throw new Error(`timeout waiting for run ${run.id}`); - } - - const artifacts = (await request("GET", `/api/runs/${encodeURIComponent(run.id)}/artifacts`)) - .items; - const logs = (await request("GET", `/api/runs/${encodeURIComponent(run.id)}/logs`)).items; - const interesting = {}; - for (const item of artifacts) { - if (interestingArtifactNames.has(item.name)) { - interesting[item.name] = item.data; - } - } - - const summary = { - projectId: project.id, - projectName: project.name, - workflowId: workflow.id, - workflowName: workflow.name, - runId: run.id, - status: terminal.status, - nodeStatuses: Object.fromEntries( - (terminal.nodeExecutions || []).map((item) => [item.nodeId, item.status]), - ), - interestingArtifacts: interesting, - lastLogs: logs.slice(-20), - }; - console.log(JSON.stringify(summary, null, 2)); - if (terminal.status !== "completed") { - process.exit(1); - } -} - -await main(); diff --git a/tmp/object-storage-debug.mjs b/tmp/object-storage-debug.mjs deleted file mode 100644 index 0a325b21..00000000 --- a/tmp/object-storage-debug.mjs +++ /dev/null @@ -1,65 +0,0 @@ -import { chromium } from "playwright"; - -const base = "http://114.111.24.223:30080"; -const conn = "storage-d69ba0e9824a9abd216eced490f0aed3"; -const bucket = "droboticflow-debug-preview"; -const key = "preview.json"; - -async function requestJSON(url, init) { - const response = await fetch(url, init); - const text = await response.text(); - if (!response.ok) { - throw new Error(text || `Request failed: ${response.status}`); - } - return text ? JSON.parse(text) : null; -} - -try { - try { - await requestJSON(`${base}/api/object-storage/buckets?connectionId=${conn}`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ name: bucket }), - }); - } catch {} - - await requestJSON(`${base}/api/object-storage/objects?connectionId=${conn}`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - bucket, - key, - content: JSON.stringify({ hello: "world" }, null, 2), - contentType: "application/json", - }), - }); - - const browser = await chromium.launch({ headless: true }); - const page = await browser.newPage(); - await page.goto(`${base}/object-storage`, { waitUntil: "networkidle" }); - await page.selectOption('[data-testid="object-storage-connection-select"]', conn); - await page.waitForSelector(`[data-bucket-name="${bucket}"]`); - await page.click(`[data-bucket-name="${bucket}"]`); - await page.waitForSelector(`[data-object-key="${key}"]`); - await page.click(`[data-object-key="${key}"]`); - await page.waitForTimeout(4000); - - const preTexts = await page.locator("pre").allTextContents(); - const bodyText = await page.locator("body").innerText(); - console.log(JSON.stringify({ preTexts, bodyHasWorld: bodyText.includes("world") }, null, 2)); - await page.screenshot({ path: "/tmp/object-storage-debug.png", fullPage: true }); - await browser.close(); -} finally { - try { - await fetch( - `${base}/api/object-storage/objects?connectionId=${conn}&bucket=${bucket}&key=${encodeURIComponent(key)}`, - { method: "DELETE" }, - ); - } catch {} - try { - await fetch( - `${base}/api/object-storage/buckets/${bucket}?connectionId=${conn}`, - { method: "DELETE" }, - ); - } catch {} -} diff --git a/tmp/operators-live-summary.txt b/tmp/operators-live-summary.txt deleted file mode 100644 index 56a1a31c..00000000 --- a/tmp/operators-live-summary.txt +++ /dev/null @@ -1,52 +0,0 @@ -=== MongoDB 写入 -{"category": "DATA", "description": "将上游 JSON 数据写入用户配置的业务 MongoDB,支持批量插入和按键 upsert,并允许显式覆盖连接。", "inputs": [{"id": "input", "name": "input", "type": "json", "description": "待写入的 JSON 文档或 items 列表"}], "outputs": [{"id": "result", "name": "result", "type": "json", "description": "写入结果摘要"}], "hyperparams": [{"key": "MONGO_COLLECTION", "value": "", "description": "目标集合名称(禁止写系统保留集合)", "type": "string"}, {"key": "MONGO_MODE", "value": "insert_many", "description": "写入模式:insert_many 或 upsert", "type": "string"}, {"key": "MONGO_CONNECTION_ID", "value": "", "description": "业务 MongoDB 连接 ID;推荐优先配置", "type": "string"}, {"key": "MONGO_TARGET", "value": "business", "description": "兼容字段;默认 business。若显式传入 URI/DB,会优先使用显式连接", "type": "string"}, {"key": "UPSERT_KEY", "value": "_id", "description": "upsert 模式使用的唯一键", "type": "string"}, {"key": "DOCUMENT_PATH", "value": "", "description": "从输入 payload 中提取待写入文档的字段路径", "type": "string"}, {"key": "MONGO_DB", "value": "", "description": "可选数据库名;显式填写后会覆盖 business/platform 默认连接", "type": "string"}, {"key": "MONGO_URI", "value": "", "description": "可选 Mongo URI;显式填写后会覆盖 business/platform 默认连接", "type": "string"}]} -=== BOS 增量扫描 -{"category": "IO", "description": "按 bucket/prefix 增量扫描 BOS,仅输出本次新增对象并提交 checkpoint 给 runtime。", "inputs": [], "outputs": [{"id": "out-1", "name": "manifest", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "DATA_SOURCE", "value": "BOS", "description": "固定为 BOS"}, {"key": "SOURCE_PATH", "value": "", "description": "完整 bos://bucket/prefix 路径"}, {"key": "BOS_ENDPOINT", "value": "https://bj.bcebos.com", "description": "BOS Endpoint"}, {"key": "BOS_ACCESS_KEY_ID", "value": "", "description": "BOS Access Key ID"}, {"key": "BOS_SECRET_ACCESS_KEY", "value": "", "description": "BOS Secret Access Key"}, {"key": "SCAN_MODE", "value": "INCREMENTAL", "description": "固定为 INCREMENTAL"}]} -=== 抽检采样 -{"category": "QA", "description": "按质检和标注规则对成品数据执行真实抽检采样。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "samples", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "RULES_JSON", "value": "[]", "description": "抽检规则数组,包含 field/operator/value/samplePercent"}]} -=== 成品打包 -{"category": "VIDEO", "description": "将切片视频、质检结果、标注结果和配置文件组装成成品数据包。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "packages", "type": "json", "transmission": "bus"}], "hyperparams": null} -=== 视频标注 -{"category": "VIDEO", "description": "基于真实视频片段生成阶段划分、动作标签和对象提示。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "annotations", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "FRAME_INTERVAL_SECONDS", "value": "1.0", "description": "采样帧间隔秒数"}]} -=== 视频切片 -{"category": "VIDEO", "description": "将真实视频按固定时长切分为多个 mp4 片段。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "clips", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SEGMENT_DURATION_SECONDS", "value": "300", "description": "每个切片的秒数"}]} -=== 数据过滤 -{"category": "VIDEO", "description": "按日期、地点、场景和质检阈值过滤有效视频。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "filtered", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "DATE_START", "value": "", "description": "开始日期,支持 YYYY-MM-DD / YYYYMMDD"}, {"key": "DATE_END", "value": "", "description": "结束日期,支持 YYYY-MM-DD / YYYYMMDD"}, {"key": "PLACE", "value": "", "description": "采集地点"}, {"key": "TYPE", "value": "", "description": "采集场景类型"}, {"key": "MIN_CLARITY", "value": "0.8", "description": "清晰度最低阈值"}, {"key": "MAX_SHAKE", "value": "0.1", "description": "抖动度最高阈值"}, {"key": "MAX_HAND_OCCLUSION", "value": "0.1", "description": "无手率最高阈值"}]} -=== 视频质检 -{"category": "VIDEO", "description": "基于真实视频帧计算清晰度、抖动度和无手率估计。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "quality", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "MIN_CLARITY", "value": "0.8", "description": "清晰度最低阈值"}, {"key": "MAX_SHAKE", "value": "0.1", "description": "抖动度最高阈值"}, {"key": "MAX_HAND_OCCLUSION", "value": "0.1", "description": "无手率最高阈值"}, {"key": "CLARITY_SCALE", "value": "35", "description": "清晰度归一化尺度"}]} -=== 采集目录校验 -{"category": "DATASET", "description": "校验采集目录是否包含 meta.json、video_meta.json,以及可选 intrinsics.json。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "validated", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "REQUIRE_INTRINSICS", "value": "false", "description": "是否要求 intrinsics.json 必须存在"}]} -=== X 平台数据集索引 -{"category": "DATASET", "description": "扫描 X-platform 采集目录,解析 meta.json、video_meta.json 和视频文件索引。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "dataset", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SOURCE_PATH", "value": "", "description": "X-platform 根目录或单个采集目录"}]} -=== Shell 命令执行 -{"category": "UTIL", "description": "在 operator-runner 容器中真实执行 shell 命令并收集输出文件。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "result", "type": "file", "transmission": "bus"}], "hyperparams": [{"key": "COMMAND", "value": "", "description": "容器内执行的命令"}, {"key": "SCRIPT", "value": "", "description": "可执行脚本内容"}]} -=== ROSBag 数据概览 -{"category": "ROBOTICS", "description": "读取真实 rosbag1 / rosbag2 / mcap / db3 数据并输出概览。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "summary", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SOURCE_PATH", "value": "", "description": "bag/db3/mcap 文件或 rosbag2 目录"}]} -=== LeRobot 数据集概览 -{"category": "ROBOTICS", "description": "读取真实 LeRobot 数据集目录,输出 meta/tasks/parquet/videos 概览。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "summary", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SOURCE_PATH", "value": "", "description": "LeRobot 数据集根目录"}]} -=== 条件分流 -{"category": "LOGIC", "description": "按字段条件将输入拆分到 matched / unmatched 两个真实输出端口。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "matched", "name": "matched", "type": "json", "transmission": "bus"}, {"id": "unmatched", "name": "unmatched", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "FIELD_PATH", "value": "", "description": "待判断字段路径"}, {"key": "OPERATOR", "value": "eq", "description": "eq/ne/contains/gt/gte/lt/lte/exists/missing"}, {"key": "EXPECTED", "value": "", "description": "字符串比较值"}, {"key": "EXPECTED_JSON", "value": "", "description": "JSON 格式比较值,优先于 EXPECTED"}]} -=== 文本模板渲染 -{"category": "UTIL", "description": "使用上游 JSON 上下文渲染真实文本模板文件。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "rendered", "type": "file", "transmission": "bus"}], "hyperparams": [{"key": "TEMPLATE_TEXT", "value": "", "description": "模板文本"}, {"key": "OUTPUT_NAME", "value": "rendered.txt", "description": "输出文件名"}]} -=== JSON 映射重命名 -{"category": "DATA", "description": "按映射表批量重命名 JSON 字段。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "mapped", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "FIELD_MAP_JSON", "value": "{}", "description": "JSON 字段映射,例如 {\"old\":\"new\"}"}]} -=== JSON 过滤 -{"category": "DATA", "description": "按字段条件过滤 JSON 列表。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "filtered", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "FIELD_PATH", "value": "", "description": "待判断字段路径"}, {"key": "OPERATOR", "value": "eq", "description": "eq/ne/contains/gt/gte/lt/lte/exists/missing"}, {"key": "EXPECTED", "value": "", "description": "字符串比较值"}, {"key": "EXPECTED_JSON", "value": "", "description": "JSON 格式比较值,优先于 EXPECTED"}]} -=== JSON 字段提取 -{"category": "DATA", "description": "按字段路径从 JSON 输入中提取指定值。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "extracted", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "FIELD_PATH", "value": "", "description": "点分字段路径,例如 metrics.score"}]} -=== JSON 转 CSV -{"category": "DATA", "description": "将 JSON 行数据导出为真实 CSV 文件。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "csv", "type": "file", "transmission": "bus"}], "hyperparams": null} -=== CSV 转 JSON -{"category": "DATA", "description": "将真实 CSV/TSV 文件转换成结构化 JSON 行列表。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "table", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SOURCE_PATH", "value": "", "description": "csv/tsv 文件路径"}]} -=== 目录扫描 -{"category": "IO", "description": "对真实目录做文件统计、扩展名分布和样例文件扫描。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "summary", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SOURCE_PATH", "value": "", "description": "待扫描目录"}]} -=== 人工审核 -{"category": "HUMAN", "description": "将真实输入送入人工审核并等待审核动作恢复流程。", "inputs": [{"id": "in-1", "name": "candidate", "type": "json", "transmission": "bus"}], "outputs": [{"id": "approved", "name": "approved", "type": "json", "transmission": "bus"}, {"id": "rejected", "name": "rejected", "type": "json", "transmission": "bus"}], "hyperparams": null} -=== 结果上传 -{"category": "IO", "description": "收集上游真实输出并生成上传结果清单。", "inputs": [{"id": "in-1", "name": "result", "type": "json", "transmission": "bus"}], "outputs": [], "hyperparams": null} -=== 数据合并 -{"category": "MATH", "description": "将多个 JSON 输入合并成统一结果。", "inputs": [{"id": "in-1", "name": "left", "type": "json", "transmission": "bus"}, {"id": "in-2", "name": "right", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "merged", "type": "json", "transmission": "bus"}], "hyperparams": null} -=== 模型推理 -{"category": "AI", "description": "执行真实节点输入汇总、命令调用或模型镜像推理。", "inputs": [{"id": "in-1", "name": "input", "type": "json", "transmission": "bus"}], "outputs": [{"id": "out-1", "name": "result", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "COMMAND", "value": "", "description": "容器内执行的命令"}, {"key": "SCRIPT", "value": "", "description": "可执行脚本内容"}]} -=== 真实数据源 -{"category": "IO", "description": "从 SOURCE_TEXT、SOURCE_JSON、SOURCE_PATH 或上游输入生成真实源数据清单。", "inputs": [], "outputs": [{"id": "out-1", "name": "manifest", "type": "json", "transmission": "bus"}], "hyperparams": [{"key": "SOURCE_TEXT", "value": "", "description": "直接注入文本内容"}, {"key": "SOURCE_JSON", "value": "", "description": "直接注入 JSON 内容"}, {"key": "SOURCE_PATH", "value": "", "description": "从本地路径读取真实数据"}]} diff --git a/tmp/project-operator-count.png b/tmp/project-operator-count.png deleted file mode 100644 index 10ed6b8c..00000000 Binary files a/tmp/project-operator-count.png and /dev/null differ diff --git a/tmp/template-dblclick-edit.png b/tmp/template-dblclick-edit.png deleted file mode 100644 index 940637af..00000000 Binary files a/tmp/template-dblclick-edit.png and /dev/null differ diff --git a/tmp/templates-operator-count.png b/tmp/templates-operator-count.png deleted file mode 100644 index 03a730aa..00000000 Binary files a/tmp/templates-operator-count.png and /dev/null differ
- 正在获取实时数据... -
正在获取实时数据...
点击左侧任一产物,即可查看对应的结构化预览、媒体预览或真实元数据。
- 实时查看 K8s Job 运行状态与算子执行日志 -
实时查看 K8s Job 运行状态与算子执行日志
- 管理真实 OSS/BOS 连接、绑定 bucket、对象目录,并直接在页面内预览与操作。 -
管理真实 OSS/BOS 连接、绑定 bucket、对象目录,并直接在页面内预览与操作。
{op.description}
- 超参将作为环境变量注入到算子的 K8s Job 中。 - 例如:设置 CONFIDENCE_THRESHOLD 为 0.5, - 算子代码中可以通过 os.environ.get('CONFIDENCE_THRESHOLD') 获取。 + 超参将作为环境变量注入到算子的 K8s Job 中。 例如:设置 CONFIDENCE_THRESHOLD 为{" "} + 0.5, 算子代码中可以通过 os.environ.get('CONFIDENCE_THRESHOLD') 获取。
CONFIDENCE_THRESHOLD
0.5
os.environ.get('CONFIDENCE_THRESHOLD')
- AI Skill 描述用于向 AI 助手描述该算子的功能、输入输出要求以及使用场景。 - 良好的描述能帮助 AI 更准确地在自动化工作流生成中使用该算子。 + AI Skill 描述用于向 AI 助手描述该算子的功能、输入输出要求以及使用场景。 良好的描述能帮助 AI + 更准确地在自动化工作流生成中使用该算子。
@@ -758,19 +829,19 @@ export default function Operators() {
直接基于真实 package run artifacts 聚合,保留来源 workflow 与 run 可追溯性。
+ 直接基于真实 package run artifacts 聚合,保留来源 workflow 与 run 可追溯性。 +
{JSON.stringify(detail.package.quality || {}, null, 2)}
+ {JSON.stringify(detail.package.quality || {}, null, 2)} +
{JSON.stringify(detail.package.annotation || {}, null, 2)}
+ {JSON.stringify(detail.package.annotation || {}, null, 2)} +
{project.description}
{wf.description}
- 在 Drobodata 中管理您的具身智能数据处理项目 -
在 Drobodata 中管理您的具身智能数据处理项目
- {project.description} -
- 此操作不可撤销。该项目及其关联的所有工作流都将被永久删除。 -
此操作不可撤销。该项目及其关联的所有工作流都将被永久删除。
基于真实 `audit-samples.json` 自动生成的人工抽检任务,评审结果会持久化保存。
+ 基于真实 `audit-samples.json` 自动生成的人工抽检任务,评审结果会持久化保存。 +
{JSON.stringify(selectedItem.quality || {}, null, 2)}
+ {JSON.stringify(selectedItem.quality || {}, null, 2)} +
{JSON.stringify(selectedItem.annotation || {}, null, 2)}
+ {JSON.stringify(selectedItem.annotation || {}, null, 2)} +
- 配置 Kubernetes 集群、Worker 调度、显示时区、AI 生成服务及默认资源限制 -
配置 Kubernetes 集群、Worker 调度、显示时区、AI 生成服务及默认资源限制
- 仅回显前后缀 -
- {savedKubeconfigPreview} -
仅回显前后缀
{savedKubeconfigPreview}
@@ -292,9 +249,7 @@ export default function Settings() { k8s: { ...current.k8s, kubeconfig: event.target.value, - hasKubeconfig: - current.k8s.hasKubeconfig || - event.target.value.trim().length > 0, + hasKubeconfig: current.k8s.hasKubeconfig || event.target.value.trim().length > 0, }, } : current, @@ -324,9 +279,7 @@ export default function Settings() {
- {savedAIKeyPreview} -
{savedAIKeyPreview}
@@ -597,11 +528,7 @@ export default function Settings() { setConfig((current) => current @@ -610,9 +537,7 @@ export default function Settings() { ai: { ...current.ai, apiKey: event.target.value, - hasAPIKey: - current.ai.hasAPIKey || - event.target.value.trim().length > 0, + hasAPIKey: current.ai.hasAPIKey || event.target.value.trim().length > 0, }, } : current, @@ -632,23 +557,14 @@ export default function Settings() {
- 最近更新时间:{" "} - {formatCompactDateTime( - config.updatedAt, - config.timezone, - "尚未保存", - )} + 最近更新时间: {formatCompactDateTime(config.updatedAt, config.timezone, "尚未保存")}
- 复用经过验证的数据处理流程,加速开发效率 -
复用经过验证的数据处理流程,加速开发效率
- {tpl.description} -
{tpl.description}
- 请选择要将此模板应用到的项目: -
请选择要将此模板应用到的项目:
- Drobodata 工作流编辑器 -
Drobodata 工作流编辑器
工作流级设置统一放在这里,避免和节点参数混在一起。
- 如果流程使用扫描源算子,bucket、prefix、连接信息以及 FULL/INCREMENTAL 都在扫描源节点里配置;这里只控制触发方式和调度策略。 + 如果流程使用扫描源算子,bucket、prefix、连接信息以及 FULL/INCREMENTAL + 都在扫描源节点里配置;这里只控制触发方式和调度策略。
- 这里配置的 env 会注入到全部算子节点。模板中的配置会被实例化继承;如果某个节点配置了同名 env,则以节点级配置为准。 + 这里配置的 env 会注入到全部算子节点。模板中的配置会被实例化继承;如果某个节点配置了同名 + env,则以节点级配置为准。
- 设为 `0` 表示继承系统默认并发数;会影响当前工作流的排队调度,以及单次执行里可同时运行的分支节点数。 + 设为 `0` + 表示继承系统默认并发数;会影响当前工作流的排队调度,以及单次执行里可同时运行的分支节点数。
- {op.description} -
- 这里只显示服务端已保存的扫描源状态。修改 - `bucket/prefix/scanMode` 后请先保存;状态只会在整条工作流成功后提交。 + 这里只显示服务端已保存的扫描源状态。修改 `bucket/prefix/scanMode` + 后请先保存;状态只会在整条工作流成功后提交。
- 优先使用节点绑定的 BOS 连接浏览真实 bucket/prefix;未绑定连接时,回退读取节点超参里的 - `SOURCE_PATH`。 + 优先使用节点绑定的 BOS 连接浏览真实 + bucket/prefix;未绑定连接时,回退读取节点超参里的 `SOURCE_PATH`。
- {ossBrowseError} -
{ossBrowseError}
- 节点自定义 env 可编辑;继承自工作流和系统注入项为只读。 - 系统时间戳只会在周期执行时出现,值与实际运行时完全一致。 - 已加载 run 时显示真实值;未加载 run 时显示“如果现在按当前调度执行”的预览值。 - 时间格式固定为 Asia/Shanghai。 -
Asia/Shanghai
- {hp.description} -
+ 节点自定义 env 可编辑;继承自工作流和系统注入项为只读。 + 系统时间戳只会在周期执行时出现,值与实际运行时完全一致。 已加载 run + 时显示真实值;未加载 run 时显示“如果现在按当前调度执行”的预览值。 时间格式固定为{" "} + Asia/Shanghai。 +
{hp.description}
- 选择算子或连线查看配置与输出 -
- 工作流级配置请使用顶部的“工作流配置”入口。 -
选择算子或连线查看配置与输出
工作流级配置请使用顶部的“工作流配置”入口。
- {selectedBrowseRootLabel || "未配置连接或 SOURCE_PATH"} /{" "} - {selectedNodeBucket || "未选择存储桶"} /{" "} - {selectedNodePrefix || ""} + {selectedBrowseRootLabel || "未配置连接或 SOURCE_PATH"} / {selectedNodeBucket || "未选择存储桶"}{" "} + / {selectedNodePrefix || ""}
- 仅当前用户可见的常用 bucket/prefix。 -
仅当前用户可见的常用 bucket/prefix。
- 请先绑定 BOS 连接,或在当前节点超参里配置 SOURCE_PATH -
请先绑定 BOS 连接,或在当前节点超参里配置 SOURCE_PATH
- 正在扫描 OSS 目录... -
正在扫描 OSS 目录...
- 当前路径下没有可选对象 -
当前路径下没有可选对象