Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat: app deploy (#35670)
Stephen Zhou48452aefbc4d
diff --git a/.agents/skills/component-refactoring/SKILL.md b/.agents/skills/component-refactoring/SKILL.mddeleted file mode 100644index a7cae67e8f9..00000000000--- a/.agents/skills/component-refactoring/SKILL.md+++ /dev/null@@ -1,440 +0,0 @@-----name: component-refactoring-description: Refactor high-complexity React components in Dify frontend. Use when `pnpm analyze-component --json` shows complexity > 50 or lineCount > 300, when the user asks for code splitting, hook extraction, or complexity reduction, or when `pnpm analyze-component` warns to refactor before testing; avoid for simple/well-structured components, third-party wrappers, or when the user explicitly wants testing without refactoring.------# Dify Component Refactoring Skill--Refactor high-complexity React components in the Dify frontend codebase with the patterns and workflow below.--> **Complexity Threshold**: Components with complexity > 50 (measured by `pnpm analyze-component`) should be refactored before testing.--## Quick Reference--### Commands (run from `web/`)--Use paths relative to `web/` (e.g., `app/components/...`).-Use `refactor-component` for refactoring prompts and `analyze-component` for testing prompts and metrics.--```bash-cd web--# Generate refactoring prompt-pnpm refactor-component <path>--# Output refactoring analysis as JSON-pnpm refactor-component <path> --json--# Generate testing prompt (after refactoring)-pnpm analyze-component <path>--# Output testing analysis as JSON-pnpm analyze-component <path> --json-```--### Complexity Analysis--```bash-# Analyze component complexity-pnpm analyze-component <path> --json--# Key metrics to check:-# - complexity: normalized score 0-100 (target < 50)-# - maxComplexity: highest single function complexity-# - lineCount: total lines (target < 300)-```--### Complexity Score Interpretation--| Score | Level | Action |-|-------|-------|--------|-| 0-25 | 🟢 Simple | Ready for testing |-| 26-50 | 🟡 Medium | Consider minor refactoring |-| 51-75 | 🟠 Complex | **Refactor before testing** |-| 76-100 | 🔴 Very Complex | **Must refactor** |--## Core Refactoring Patterns--### Pattern 1: Extract Custom Hooks--**When**: Component has complex state management, multiple `useState`/`useEffect`, or business logic mixed with UI.--**Dify Convention**: Place hooks in a `hooks/` subdirectory or alongside the component as `use-<feature>.ts`.--```typescript-// ❌ Before: Complex state logic in component-function Configuration() {- const [modelConfig, setModelConfig] = useState<ModelConfig>(...)- const [datasetConfigs, setDatasetConfigs] = useState<DatasetConfigs>(...)- const [completionParams, setCompletionParams] = useState<FormValue>({})-- // 50+ lines of state management logic...-- return <div>...</div>-}--// ✅ After: Extract to custom hook-// hooks/use-model-config.ts-export const useModelConfig = (appId: string) => {- const [modelConfig, setModelConfig] = useState<ModelConfig>(...)- const [completionParams, setCompletionParams] = useState<FormValue>({})-- // Related state management logic here-- return { modelConfig, setModelConfig, completionParams, setCompletionParams }-}--// Component becomes cleaner-function Configuration() {- const { modelConfig, setModelConfig } = useModelConfig(appId)- return <div>...</div>-}-```--**Dify Examples**:-- `web/app/components/app/configuration/hooks/use-advanced-prompt-config.ts`-- `web/app/components/app/configuration/debug/hooks.tsx`-- `web/app/components/workflow/hooks/use-workflow.ts`--### Pattern 2: Extract Sub-Components--**When**: Single component has multiple UI sections, conditional rendering blocks, or repeated patterns.--**Dify Convention**: Place sub-components in subdirectories or as separate files in the same directory.--```typescript-// ❌ Before: Monolithic JSX with multiple sections-const AppInfo = () => {- return (- <div>- {/* 100 lines of header UI */}- {/* 100 lines of operations UI */}- {/* 100 lines of modals */}- </div>- )-}--// ✅ After: Split into focused components-// app-info/-// ├── index.tsx (orchestration only)-// ├── app-header.tsx (header UI)-// ├── app-operations.tsx (operations UI)-// └── app-modals.tsx (modal management)--const AppInfo = () => {- const { showModal, setShowModal } = useAppInfoModals()-- return (- <div>- <AppHeader appDetail={appDetail} />- <AppOperations onAction={handleAction} />- <AppModals show={showModal} onClose={() => setShowModal(null)} />- </div>- )-}-```--**Dify Examples**:-- `web/app/components/app/configuration/` directory structure-- `web/app/components/workflow/nodes/` per-node organization--### Pattern 3: Simplify Conditional Logic--**When**: Deep nesting (> 3 levels), complex ternaries, or multiple `if/else` chains.--```typescript-// ❌ Before: Deeply nested conditionals-const Template = useMemo(() => {- if (appDetail?.mode === AppModeEnum.CHAT) {- switch (locale) {- case LanguagesSupported[1]:- return <TemplateChatZh />- case LanguagesSupported[7]:- return <TemplateChatJa />- default:- return <TemplateChatEn />- }- }- if (appDetail?.mode === AppModeEnum.ADVANCED_CHAT) {- // Another 15 lines...- }- // More conditions...-}, [appDetail, locale])--// ✅ After: Use lookup tables + early returns-const TEMPLATE_MAP = {- [AppModeEnum.CHAT]: {- [LanguagesSupported[1]]: TemplateChatZh,- [LanguagesSupported[7]]: TemplateChatJa,- default: TemplateChatEn,- },- [AppModeEnum.ADVANCED_CHAT]: {- [LanguagesSupported[1]]: TemplateAdvancedChatZh,- // ...- },-}--const Template = useMemo(() => {- const modeTemplates = TEMPLATE_MAP[appDetail?.mode]- if (!modeTemplates) return null-- const TemplateComponent = modeTemplates[locale] || modeTemplates.default- return <TemplateComponent appDetail={appDetail} />-}, [appDetail, locale])-```--### Pattern 4: Extract API/Data Logic--**When**: Component directly handles API calls, data transformation, or complex async operations.--**Dify Convention**:-- This skill is for component decomposition, not query/mutation design.-- Do not introduce deprecated `useInvalid` / `useReset`.-- Do not add thin passthrough `useQuery` wrappers during refactoring; only extract a custom hook when it truly orchestrates multiple queries/mutations or shared derived state.--**Dify Examples**:-- `web/service/use-workflow.ts`-- `web/service/use-common.ts`-- `web/service/knowledge/use-dataset.ts`-- `web/service/knowledge/use-document.ts`--### Pattern 5: Extract Modal/Dialog Management--**When**: Component manages multiple modals with complex open/close states.--**Dify Convention**: Modals should be extracted with their state management.--```typescript-// ❌ Before: Multiple modal states in component-const AppInfo = () => {- const [showEditModal, setShowEditModal] = useState(false)- const [showDuplicateModal, setShowDuplicateModal] = useState(false)- const [showConfirmDelete, setShowConfirmDelete] = useState(false)- const [showSwitchModal, setShowSwitchModal] = useState(false)- const [showImportDSLModal, setShowImportDSLModal] = useState(false)- // 5+ more modal states...-}--// ✅ After: Extract to modal management hook-type ModalType = 'edit' | 'duplicate' | 'delete' | 'switch' | 'import' | null--const useAppInfoModals = () => {- const [activeModal, setActiveModal] = useState<ModalType>(null)-- const openModal = useCallback((type: ModalType) => setActiveModal(type), [])- const closeModal = useCallback(() => setActiveModal(null), [])-- return {- activeModal,- openModal,- closeModal,- isOpen: (type: ModalType) => activeModal === type,- }-}-```--### Pattern 6: Extract Form Logic--**When**: Complex form validation, submission handling, or field transformation.--**Dify Convention**: Use `@tanstack/react-form` patterns from `web/app/components/base/form/`.--```typescript-// ✅ Use existing form infrastructure-import { useAppForm } from '@/app/components/base/form'--const ConfigForm = () => {- const form = useAppForm({- defaultValues: { name: '', description: '' },- onSubmit: handleSubmit,- })-- return <form.Provider>...</form.Provider>-}-```--## Dify-Specific Refactoring Guidelines--### 1. Context Provider Extraction--**When**: Component provides complex context values with multiple states.--```typescript-// ❌ Before: Large context value object-const value = {- appId, isAPIKeySet, isTrailFinished, mode, modelModeType,- promptMode, isAdvancedMode, isAgent, isOpenAI, isFunctionCall,- // 50+ more properties...-}-return <ConfigContext.Provider value={value}>...</ConfigContext.Provider>--// ✅ After: Split into domain-specific contexts-<ModelConfigProvider value={modelConfigValue}>- <DatasetConfigProvider value={datasetConfigValue}>- <UIConfigProvider value={uiConfigValue}>- {children}- </UIConfigProvider>- </DatasetConfigProvider>-</ModelConfigProvider>-```--**Dify Reference**: `web/context/` directory structure--### 2. Workflow Node Components--**When**: Refactoring workflow node components (`web/app/components/workflow/nodes/`).--**Conventions**:-- Keep node logic in `use-interactions.ts`-- Extract panel UI to separate files-- Use `_base` components for common patterns--```-nodes/<node-type>/- ├── index.tsx # Node registration- ├── node.tsx # Node visual component- ├── panel.tsx # Configuration panel- ├── use-interactions.ts # Node-specific hooks- └── types.ts # Type definitions-```--### 3. Configuration Components--**When**: Refactoring app configuration components.--**Conventions**:-- Separate config sections into subdirectories-- Use existing patterns from `web/app/components/app/configuration/`-- Keep feature toggles in dedicated components--### 4. Tool/Plugin Components--**When**: Refactoring tool-related components (`web/app/components/tools/`).--**Conventions**:-- Follow existing modal patterns-- Use service hooks from `web/service/use-tools.ts`-- Keep provider-specific logic isolated--## Refactoring Workflow--### Step 1: Generate Refactoring Prompt--```bash-pnpm refactor-component <path>-```--This command will:-- Analyze component complexity and features-- Identify specific refactoring actions needed-- Generate a prompt for AI assistant (auto-copied to clipboard on macOS)-- Provide detailed requirements based on detected patterns--### Step 2: Analyze Details--```bash-pnpm analyze-component <path> --json-```--Identify:-- Total complexity score-- Max function complexity-- Line count-- Features detected (state, effects, API, etc.)--### Step 3: Plan--Create a refactoring plan based on detected features:--| Detected Feature | Refactoring Action |-|------------------|-------------------|-| `hasState: true` + `hasEffects: true` | Extract custom hook |-| `hasAPI: true` | Extract data/service hook |-| `hasEvents: true` (many) | Extract event handlers |-| `lineCount > 300` | Split into sub-components |-| `maxComplexity > 50` | Simplify conditional logic |--### Step 4: Execute Incrementally--1. **Extract one piece at a time**-2. **Run lint, type-check, and tests after each extraction**-3. **Verify functionality before next step**--```-For each extraction:- ┌────────────────────────────────────────┐- │ 1. Extract code │- │ 2. Run: pnpm lint:fix │- │ 3. Run: pnpm type-check │- │ 4. Run: pnpm test │- │ 5. Test functionality manually │- │ 6. PASS? → Next extraction │- │ FAIL? → Fix before continuing │- └────────────────────────────────────────┘-```--### Step 5: Verify--After refactoring:--```bash-# Re-run refactor command to verify improvements-pnpm refactor-component <path>--# If complexity < 25 and lines < 200, you'll see:-# ✅ COMPONENT IS WELL-STRUCTURED--# For detailed metrics:-pnpm analyze-component <path> --json--# Target metrics:-# - complexity < 50-# - lineCount < 300-# - maxComplexity < 30-```--## Common Mistakes to Avoid--### ❌ Over-Engineering--```typescript-// ❌ Too many tiny hooks-const useButtonText = () => useState('Click')-const useButtonDisabled = () => useState(false)-const useButtonLoading = () => useState(false)--// ✅ Cohesive hook with related state-const useButtonState = () => {- const [text, setText] = useState('Click')- const [disabled, setDisabled] = useState(false)- const [loading, setLoading] = useState(false)- return { text, setText, disabled, setDisabled, loading, setLoading }-}-```--### ❌ Breaking Existing Patterns--- Follow existing directory structures-- Maintain naming conventions-- Preserve export patterns for compatibility--### ❌ Premature Abstraction--- Only extract when there's clear complexity benefit-- Don't create abstractions for single-use code-- Keep refactored code in the same domain area--## References--### Dify Codebase Examples--- **Hook extraction**: `web/app/components/app/configuration/hooks/`-- **Component splitting**: `web/app/components/app/configuration/`-- **Service hooks**: `web/service/use-*.ts`-- **Workflow patterns**: `web/app/components/workflow/hooks/`-- **Form patterns**: `web/app/components/base/form/`--### Related Skills--- `frontend-testing` - For testing refactored components-- `web/docs/test.md` - Testing specificationdiff --git a/.agents/skills/component-refactoring/references/complexity-patterns.md b/.agents/skills/component-refactoring/references/complexity-patterns.mddeleted file mode 100644index 2873630d4ba..00000000000--- a/.agents/skills/component-refactoring/references/complexity-patterns.md+++ /dev/null@@ -1,495 +0,0 @@-# Complexity Reduction Patterns--This document provides patterns for reducing cognitive complexity in Dify React components.--## Understanding Complexity--### SonarJS Cognitive Complexity--The `pnpm analyze-component` tool uses SonarJS cognitive complexity metrics:--- **Total Complexity**: Sum of all functions' complexity in the file-- **Max Complexity**: Highest single function complexity--### What Increases Complexity--| Pattern | Complexity Impact |-|---------|-------------------|-| `if/else` | +1 per branch |-| Nested conditions | +1 per nesting level |-| `switch/case` | +1 per case |-| `for/while/do` | +1 per loop |-| `&&`/`||` chains | +1 per operator |-| Nested callbacks | +1 per nesting level |-| `try/catch` | +1 per catch |-| Ternary expressions | +1 per nesting |--## Pattern 1: Replace Conditionals with Lookup Tables--**Before** (complexity: ~15):--```typescript-const Template = useMemo(() => {- if (appDetail?.mode === AppModeEnum.CHAT) {- switch (locale) {- case LanguagesSupported[1]:- return <TemplateChatZh appDetail={appDetail} />- case LanguagesSupported[7]:- return <TemplateChatJa appDetail={appDetail} />- default:- return <TemplateChatEn appDetail={appDetail} />- }- }- if (appDetail?.mode === AppModeEnum.ADVANCED_CHAT) {- switch (locale) {- case LanguagesSupported[1]:- return <TemplateAdvancedChatZh appDetail={appDetail} />- case LanguagesSupported[7]:- return <TemplateAdvancedChatJa appDetail={appDetail} />- default:- return <TemplateAdvancedChatEn appDetail={appDetail} />- }- }- if (appDetail?.mode === AppModeEnum.WORKFLOW) {- // Similar pattern...- }- return null-}, [appDetail, locale])-```--**After** (complexity: ~3):--```typescript-import type { ComponentType } from 'react'--// Define lookup table outside component-const TEMPLATE_MAP: Record<AppModeEnum, Record<string, ComponentType<TemplateProps>>> = {- [AppModeEnum.CHAT]: {- [LanguagesSupported[1]]: TemplateChatZh,- [LanguagesSupported[7]]: TemplateChatJa,- default: TemplateChatEn,- },- [AppModeEnum.ADVANCED_CHAT]: {- [LanguagesSupported[1]]: TemplateAdvancedChatZh,- [LanguagesSupported[7]]: TemplateAdvancedChatJa,- default: TemplateAdvancedChatEn,- },- [AppModeEnum.WORKFLOW]: {- [LanguagesSupported[1]]: TemplateWorkflowZh,- [LanguagesSupported[7]]: TemplateWorkflowJa,- default: TemplateWorkflowEn,- },- // ...-}--// Clean component logic-const Template = useMemo(() => {- if (!appDetail?.mode) return null-- const templates = TEMPLATE_MAP[appDetail.mode]- if (!templates) return null-- const TemplateComponent = templates[locale] ?? templates.default- return <TemplateComponent appDetail={appDetail} />-}, [appDetail, locale])-```--## Pattern 2: Use Early Returns--**Before** (complexity: ~10):--```typescript-const handleSubmit = () => {- if (isValid) {- if (hasChanges) {- if (isConnected) {- submitData()- } else {- showConnectionError()- }- } else {- showNoChangesMessage()- }- } else {- showValidationError()- }-}-```--**After** (complexity: ~4):--```typescript-const handleSubmit = () => {- if (!isValid) {- showValidationError()- return- }-- if (!hasChanges) {- showNoChangesMessage()- return- }-- if (!isConnected) {- showConnectionError()- return- }-- submitData()-}-```--## Pattern 3: Extract Complex Conditions--**Before** (complexity: high):--```typescript-const canPublish = (() => {- if (mode !== AppModeEnum.COMPLETION) {- if (!isAdvancedMode)- return true-- if (modelModeType === ModelModeType.completion) {- if (!hasSetBlockStatus.history || !hasSetBlockStatus.query)- return false- return true- }- return true- }- return !promptEmpty-})()-```--**After** (complexity: lower):--```typescript-// Extract to named functions-const canPublishInCompletionMode = () => !promptEmpty--const canPublishInChatMode = () => {- if (!isAdvancedMode) return true- if (modelModeType !== ModelModeType.completion) return true- return hasSetBlockStatus.history && hasSetBlockStatus.query-}--// Clean main logic-const canPublish = mode === AppModeEnum.COMPLETION- ? canPublishInCompletionMode()- : canPublishInChatMode()-```--## Pattern 4: Replace Chained Ternaries--**Before** (complexity: ~5):--```typescript-const statusText = serverActivated- ? t('status.running')- : serverPublished- ? t('status.inactive')- : appUnpublished- ? t('status.unpublished')- : t('status.notConfigured')-```--**After** (complexity: ~2):--```typescript-const getStatusText = () => {- if (serverActivated) return t('status.running')- if (serverPublished) return t('status.inactive')- if (appUnpublished) return t('status.unpublished')- return t('status.notConfigured')-}--const statusText = getStatusText()-```--Or use lookup:--```typescript-const STATUS_TEXT_MAP = {- running: 'status.running',- inactive: 'status.inactive',- unpublished: 'status.unpublished',- notConfigured: 'status.notConfigured',-} as const--const getStatusKey = (): keyof typeof STATUS_TEXT_MAP => {- if (serverActivated) return 'running'- if (serverPublished) return 'inactive'- if (appUnpublished) return 'unpublished'- return 'notConfigured'-}--const statusText = t(STATUS_TEXT_MAP[getStatusKey()])-```--## Pattern 5: Flatten Nested Loops--**Before** (complexity: high):--```typescript-const processData = (items: Item[]) => {- const results: ProcessedItem[] = []-- for (const item of items) {- if (item.isValid) {- for (const child of item.children) {- if (child.isActive) {- for (const prop of child.properties) {- if (prop.value !== null) {- results.push({- itemId: item.id,- childId: child.id,- propValue: prop.value,- })- }- }- }- }- }- }-- return results-}-```--**After** (complexity: lower):--```typescript-// Use functional approach-const processData = (items: Item[]) => {- return items- .filter(item => item.isValid)- .flatMap(item =>- item.children- .filter(child => child.isActive)- .flatMap(child =>- child.properties- .filter(prop => prop.value !== null)- .map(prop => ({- itemId: item.id,- childId: child.id,- propValue: prop.value,- }))- )- )-}-```--## Pattern 6: Extract Event Handler Logic--**Before** (complexity: high in component):--```typescript-const Component = () => {- const handleSelect = (data: DataSet[]) => {- if (isEqual(data.map(item => item.id), dataSets.map(item => item.id))) {- hideSelectDataSet()- return- }-- formattingChangedDispatcher()- let newDatasets = data- if (data.find(item => !item.name)) {- const newSelected = produce(data, (draft) => {- data.forEach((item, index) => {- if (!item.name) {- const newItem = dataSets.find(i => i.id === item.id)- if (newItem)- draft[index] = newItem- }- })- })- setDataSets(newSelected)- newDatasets = newSelected- }- else {- setDataSets(data)- }- hideSelectDataSet()-- // 40 more lines of logic...- }-- return <div>...</div>-}-```--**After** (complexity: lower):--```typescript-// Extract to hook or utility-const useDatasetSelection = (dataSets: DataSet[], setDataSets: SetState<DataSet[]>) => {- const normalizeSelection = (data: DataSet[]) => {- const hasUnloadedItem = data.some(item => !item.name)- if (!hasUnloadedItem) return data-- return produce(data, (draft) => {- data.forEach((item, index) => {- if (!item.name) {- const existing = dataSets.find(i => i.id === item.id)- if (existing) draft[index] = existing- }- })- })- }-- const hasSelectionChanged = (newData: DataSet[]) => {- return !isEqual(- newData.map(item => item.id),- dataSets.map(item => item.id)- )- }-- return { normalizeSelection, hasSelectionChanged }-}--// Component becomes cleaner-const Component = () => {- const { normalizeSelection, hasSelectionChanged } = useDatasetSelection(dataSets, setDataSets)-- const handleSelect = (data: DataSet[]) => {- if (!hasSelectionChanged(data)) {- hideSelectDataSet()- return- }-- formattingChangedDispatcher()- const normalized = normalizeSelection(data)- setDataSets(normalized)- hideSelectDataSet()- }-- return <div>...</div>-}-```--## Pattern 7: Reduce Boolean Logic Complexity--**Before** (complexity: ~8):--```typescript-const toggleDisabled = hasInsufficientPermissions- || appUnpublished- || missingStartNode- || triggerModeDisabled- || (isAdvancedApp && !currentWorkflow?.graph)- || (isBasicApp && !basicAppConfig.updated_at)-```--**After** (complexity: ~3):--```typescript-// Extract meaningful boolean functions-const isAppReady = () => {- if (isAdvancedApp) return !!currentWorkflow?.graph- return !!basicAppConfig.updated_at-}--const hasRequiredPermissions = () => {- return isCurrentWorkspaceEditor && !hasInsufficientPermissions-}--const canToggle = () => {- if (!hasRequiredPermissions()) return false- if (!isAppReady()) return false- if (missingStartNode) return false- if (triggerModeDisabled) return false- return true-}--const toggleDisabled = !canToggle()-```--## Pattern 8: Simplify useMemo/useCallback Dependencies--**Before** (complexity: multiple recalculations):--```typescript-const payload = useMemo(() => {- let parameters: Parameter[] = []- let outputParameters: OutputParameter[] = []-- if (!published) {- parameters = (inputs || []).map((item) => ({- name: item.variable,- description: '',- form: 'llm',- required: item.required,- type: item.type,- }))- outputParameters = (outputs || []).map((item) => ({- name: item.variable,- description: '',- type: item.value_type,- }))- }- else if (detail && detail.tool) {- parameters = (inputs || []).map((item) => ({- // Complex transformation...- }))- outputParameters = (outputs || []).map((item) => ({- // Complex transformation...- }))- }-- return {- icon: detail?.icon || icon,- label: detail?.label || name,- // ...more fields- }-}, [detail, published, workflowAppId, icon, name, description, inputs, outputs])-```--**After** (complexity: separated concerns):--```typescript-// Separate transformations-const useParameterTransform = (inputs: InputVar[], detail?: ToolDetail, published?: boolean) => {- return useMemo(() => {- if (!published) {- return inputs.map(item => ({- name: item.variable,- description: '',- form: 'llm',- required: item.required,- type: item.type,- }))- }-- if (!detail?.tool) return []-- return inputs.map(item => ({- name: item.variable,- required: item.required,- type: item.type === 'paragraph' ? 'string' : item.type,- description: detail.tool.parameters.find(p => p.name === item.variable)?.llm_description || '',- form: detail.tool.parameters.find(p => p.name === item.variable)?.form || 'llm',- }))- }, [inputs, detail, published])-}--// Component uses hook-const parameters = useParameterTransform(inputs, detail, published)-const outputParameters = useOutputTransform(outputs, detail, published)--const payload = useMemo(() => ({- icon: detail?.icon || icon,- label: detail?.label || name,- parameters,- outputParameters,- // ...-}), [detail, icon, name, parameters, outputParameters])-```--## Target Metrics After Refactoring--| Metric | Target |-|--------|--------|-| Total Complexity | < 50 |-| Max Function Complexity | < 30 |-| Function Length | < 30 lines |-| Nesting Depth | ≤ 3 levels |-| Conditional Chains | ≤ 3 conditions |diff --git a/.agents/skills/component-refactoring/references/component-splitting.md b/.agents/skills/component-refactoring/references/component-splitting.mddeleted file mode 100644index 81c007e0050..00000000000--- a/.agents/skills/component-refactoring/references/component-splitting.md+++ /dev/null@@ -1,477 +0,0 @@-# Component Splitting Patterns--This document provides detailed guidance on splitting large components into smaller, focused components in Dify.--## When to Split Components--Split a component when you identify:--1. **Multiple UI sections** - Distinct visual areas with minimal coupling that can be composed independently-1. **Conditional rendering blocks** - Large `{condition && <JSX />}` blocks-1. **Repeated patterns** - Similar UI structures used multiple times-1. **300+ lines** - Component exceeds manageable size-1. **Modal clusters** - Multiple modals rendered in one component--## Splitting Strategies--### Strategy 1: Section-Based Splitting--Identify visual sections and extract each as a component.--```typescript-// ❌ Before: Monolithic component (500+ lines)-const ConfigurationPage = () => {- return (- <div>- {/* Header Section - 50 lines */}- <div className="header">- <h1>{t('configuration.title')}</h1>- <div className="actions">- {isAdvancedMode && <Badge>Advanced</Badge>}- <ModelParameterModal ... />- <AppPublisher ... />- </div>- </div>-- {/* Config Section - 200 lines */}- <div className="config">- <Config />- </div>-- {/* Debug Section - 150 lines */}- <div className="debug">- <Debug ... />- </div>-- {/* Modals Section - 100 lines */}- {showSelectDataSet && <SelectDataSet ... />}- {showHistoryModal && <EditHistoryModal ... />}- {showUseGPT4Confirm && <Confirm ... />}- </div>- )-}--// ✅ After: Split into focused components-// configuration/-// ├── index.tsx (orchestration)-// ├── configuration-header.tsx-// ├── configuration-content.tsx-// ├── configuration-debug.tsx-// └── configuration-modals.tsx--// configuration-header.tsx-interface ConfigurationHeaderProps {- isAdvancedMode: boolean- onPublish: () => void-}--function ConfigurationHeader({- isAdvancedMode,- onPublish,-}: ConfigurationHeaderProps) {- const { t } = useTranslation()-- return (- <div className="header">- <h1>{t('configuration.title')}</h1>- <div className="actions">- {isAdvancedMode && <Badge>Advanced</Badge>}- <ModelParameterModal ... />- <AppPublisher onPublish={onPublish} />- </div>- </div>- )-}--// index.tsx (orchestration only)-const ConfigurationPage = () => {- const { modelConfig, setModelConfig } = useModelConfig()- const { activeModal, openModal, closeModal } = useModalState()-- return (- <div>- <ConfigurationHeader- isAdvancedMode={isAdvancedMode}- onPublish={handlePublish}- />- <ConfigurationContent- modelConfig={modelConfig}- onConfigChange={setModelConfig}- />- {!isMobile && (- <ConfigurationDebug- inputs={inputs}- onSetting={handleSetting}- />- )}- <ConfigurationModals- activeModal={activeModal}- onClose={closeModal}- />- </div>- )-}-```--### Strategy 2: Conditional Block Extraction--Extract large conditional rendering blocks.--```typescript-// ❌ Before: Large conditional blocks-const AppInfo = () => {- return (- <div>- {expand ? (- <div className="expanded">- {/* 100 lines of expanded view */}- </div>- ) : (- <div className="collapsed">- {/* 50 lines of collapsed view */}- </div>- )}- </div>- )-}--// ✅ After: Separate view components-function AppInfoExpanded({ appDetail, onAction }: AppInfoViewProps) {- return (- <div className="expanded">- {/* Clean, focused expanded view */}- </div>- )-}--function AppInfoCollapsed({ appDetail, onAction }: AppInfoViewProps) {- return (- <div className="collapsed">- {/* Clean, focused collapsed view */}- </div>- )-}--const AppInfo = () => {- return (- <div>- {expand- ? <AppInfoExpanded appDetail={appDetail} onAction={handleAction} />- : <AppInfoCollapsed appDetail={appDetail} onAction={handleAction} />- }- </div>- )-}-```--### Strategy 3: Modal Extraction--Extract modals with their trigger logic.--```typescript-// ❌ Before: Multiple modals in one component-const AppInfo = () => {- const [showEdit, setShowEdit] = useState(false)- const [showDuplicate, setShowDuplicate] = useState(false)- const [showDelete, setShowDelete] = useState(false)- const [showSwitch, setShowSwitch] = useState(false)-- const onEdit = async (data) => { /* 20 lines */ }- const onDuplicate = async (data) => { /* 20 lines */ }- const onDelete = async () => { /* 15 lines */ }-- return (- <div>- {/* Main content */}-- {showEdit && <EditModal onConfirm={onEdit} onClose={() => setShowEdit(false)} />}- {showDuplicate && <DuplicateModal onConfirm={onDuplicate} onClose={() => setShowDuplicate(false)} />}- {showDelete && <DeleteConfirm onConfirm={onDelete} onClose={() => setShowDelete(false)} />}- {showSwitch && <SwitchModal ... />}- </div>- )-}--// ✅ After: Modal manager component-// app-info-modals.tsx-type ModalType = 'edit' | 'duplicate' | 'delete' | 'switch' | null--interface AppInfoModalsProps {- appDetail: AppDetail- activeModal: ModalType- onClose: () => void- onSuccess: () => void-}--function AppInfoModals({- appDetail,- activeModal,- onClose,- onSuccess,-}: AppInfoModalsProps) {- const handleEdit = async (data) => { /* logic */ }- const handleDuplicate = async (data) => { /* logic */ }- const handleDelete = async () => { /* logic */ }-- return (- <>- {activeModal === 'edit' && (- <EditModal- appDetail={appDetail}- onConfirm={handleEdit}- onClose={onClose}- />- )}- {activeModal === 'duplicate' && (- <DuplicateModal- appDetail={appDetail}- onConfirm={handleDuplicate}- onClose={onClose}- />- )}- {activeModal === 'delete' && (- <DeleteConfirm- onConfirm={handleDelete}- onClose={onClose}- />- )}- {activeModal === 'switch' && (- <SwitchModal- appDetail={appDetail}- onClose={onClose}- />- )}- </>- )-}--// Parent component-const AppInfo = () => {- const { activeModal, openModal, closeModal } = useModalState()-- return (- <div>- {/* Main content with openModal triggers */}- <Button onClick={() => openModal('edit')}>Edit</Button>-- <AppInfoModals- appDetail={appDetail}- activeModal={activeModal}- onClose={closeModal}- onSuccess={handleSuccess}- />- </div>- )-}-```--### Strategy 4: List Item Extraction--Extract repeated item rendering.--```typescript-// ❌ Before: Inline item rendering-const OperationsList = () => {- return (- <div>- {operations.map(op => (- <div key={op.id} className="operation-item">- <span className="icon">{op.icon}</span>- <span className="title">{op.title}</span>- <span className="description">{op.description}</span>- <button onClick={() => op.onClick()}>- {op.actionLabel}- </button>- {op.badge && <Badge>{op.badge}</Badge>}- {/* More complex rendering... */}- </div>- ))}- </div>- )-}--// ✅ After: Extracted item component-interface OperationItemProps {- operation: Operation- onAction: (id: string) => void-}--function OperationItem({ operation, onAction }: OperationItemProps) {- return (- <div className="operation-item">- <span className="icon">{operation.icon}</span>- <span className="title">{operation.title}</span>- <span className="description">{operation.description}</span>- <button onClick={() => onAction(operation.id)}>- {operation.actionLabel}- </button>- {operation.badge && <Badge>{operation.badge}</Badge>}- </div>- )-}--const OperationsList = () => {- const handleAction = useCallback((id: string) => {- const op = operations.find(o => o.id === id)- op?.onClick()- }, [operations])-- return (- <div>- {operations.map(op => (- <OperationItem- key={op.id}- operation={op}- onAction={handleAction}- />- ))}- </div>- )-}-```--## Directory Structure Patterns--### Pattern A: Flat Structure (Simple Components)--For components with 2-3 sub-components:--```-component-name/- ├── index.tsx # Main component- ├── sub-component-a.tsx- ├── sub-component-b.tsx- └── types.ts # Shared types-```--### Pattern B: Nested Structure (Complex Components)--For components with many sub-components:--```-component-name/- ├── index.tsx # Main orchestration- ├── types.ts # Shared types- ├── hooks/- │ ├── use-feature-a.ts- │ └── use-feature-b.ts- ├── components/- │ ├── header/- │ │ └── index.tsx- │ ├── content/- │ │ └── index.tsx- │ └── modals/- │ └── index.tsx- └── utils/- └── helpers.ts-```--### Pattern C: Feature-Based Structure (Dify Standard)--Following Dify's existing patterns:--```-configuration/- ├── index.tsx # Main page component- ├── base/ # Base/shared components- │ ├── feature-panel/- │ ├── group-name/- │ └── operation-btn/- ├── config/ # Config section- │ ├── index.tsx- │ ├── agent/- │ └── automatic/- ├── dataset-config/ # Dataset section- │ ├── index.tsx- │ ├── card-item/- │ └── params-config/- ├── debug/ # Debug section- │ ├── index.tsx- │ └── hooks.tsx- └── hooks/ # Shared hooks- └── use-advanced-prompt-config.ts-```--## Props Design--### Minimal Props Principle--Pass only what's needed:--```typescript-// ❌ Bad: Passing entire objects when only some fields needed-<ConfigHeader appDetail={appDetail} modelConfig={modelConfig} />--// ✅ Good: Destructure to minimum required-<ConfigHeader- appName={appDetail.name}- isAdvancedMode={modelConfig.isAdvanced}- onPublish={handlePublish}-/>-```--### Callback Props Pattern--Use callbacks for child-to-parent communication:--```typescript-// Parent-const Parent = () => {- const [value, setValue] = useState('')-- return (- <Child- value={value}- onChange={setValue}- onSubmit={handleSubmit}- />- )-}--// Child-interface ChildProps {- value: string- onChange: (value: string) => void- onSubmit: () => void-}--function Child({ value, onChange, onSubmit }: ChildProps) {- return (- <div>- <input value={value} onChange={e => onChange(e.target.value)} />- <button onClick={onSubmit}>Submit</button>- </div>- )-}-```--### Render Props for Flexibility--When sub-components need parent context:--```typescript-interface ListProps<T> {- items: T[]- renderItem: (item: T, index: number) => React.ReactNode- renderEmpty?: () => React.ReactNode-}--function List<T>({ items, renderItem, renderEmpty }: ListProps<T>) {- if (items.length === 0 && renderEmpty) {- return <>{renderEmpty()}</>- }-- return (- <div>- {items.map((item, index) => renderItem(item, index))}- </div>- )-}--// Usage-<List- items={operations}- renderItem={(op, i) => <OperationItem key={i} operation={op} />}- renderEmpty={() => <EmptyState message="No operations" />}-/>-```diff --git a/.agents/skills/component-refactoring/references/hook-extraction.md b/.agents/skills/component-refactoring/references/hook-extraction.mddeleted file mode 100644index 6fad2c8885e..00000000000--- a/.agents/skills/component-refactoring/references/hook-extraction.md+++ /dev/null@@ -1,281 +0,0 @@-# Hook Extraction Patterns--This document provides detailed guidance on extracting custom hooks from complex components in Dify.--## When to Extract Hooks--Extract a custom hook when you identify:--1. **Coupled state groups** - Multiple `useState` hooks that are always used together-1. **Complex effects** - `useEffect` with multiple dependencies or cleanup logic-1. **Business logic** - Data transformations, validations, or calculations-1. **Reusable patterns** - Logic that appears in multiple components--## Extraction Process--### Step 1: Identify State Groups--Look for state variables that are logically related:--```typescript-// ❌ These belong together - extract to hook-const [modelConfig, setModelConfig] = useState<ModelConfig>(...)-const [completionParams, setCompletionParams] = useState<FormValue>({})-const [modelModeType, setModelModeType] = useState<ModelModeType>(...)--// These are model-related state that should be in useModelConfig()-```--### Step 2: Identify Related Effects--Find effects that modify the grouped state:--```typescript-// ❌ These effects belong with the state above-useEffect(() => {- if (hasFetchedDetail && !modelModeType) {- const mode = currModel?.model_properties.mode- if (mode) {- const newModelConfig = produce(modelConfig, (draft) => {- draft.mode = mode- })- setModelConfig(newModelConfig)- }- }-}, [textGenerationModelList, hasFetchedDetail, modelModeType, currModel])-```--### Step 3: Create the Hook--```typescript-// hooks/use-model-config.ts-import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'-import type { ModelConfig } from '@/models/debug'-import { produce } from 'immer'-import { useEffect, useState } from 'react'-import { ModelModeType } from '@/types/app'--interface UseModelConfigParams {- initialConfig?: Partial<ModelConfig>- currModel?: { model_properties?: { mode?: ModelModeType } }- hasFetchedDetail: boolean-}--interface UseModelConfigReturn {- modelConfig: ModelConfig- setModelConfig: (config: ModelConfig) => void- completionParams: FormValue- setCompletionParams: (params: FormValue) => void- modelModeType: ModelModeType-}--export const useModelConfig = ({- initialConfig,- currModel,- hasFetchedDetail,-}: UseModelConfigParams): UseModelConfigReturn => {- const [modelConfig, setModelConfig] = useState<ModelConfig>({- provider: 'langgenius/openai/openai',- model_id: 'gpt-3.5-turbo',- mode: ModelModeType.unset,- // ... default values- ...initialConfig,- })-- const [completionParams, setCompletionParams] = useState<FormValue>({})-- const modelModeType = modelConfig.mode-- // Fill old app data missing model mode- useEffect(() => {- if (hasFetchedDetail && !modelModeType) {- const mode = currModel?.model_properties?.mode- if (mode) {- setModelConfig(produce(modelConfig, (draft) => {- draft.mode = mode- }))- }- }- }, [hasFetchedDetail, modelModeType, currModel])-- return {- modelConfig,- setModelConfig,- completionParams,- setCompletionParams,- modelModeType,- }-}-```--### Step 4: Update Component--```typescript-// Before: 50+ lines of state management-function Configuration() {- const [modelConfig, setModelConfig] = useState<ModelConfig>(...)- // ... lots of related state and effects-}--// After: Clean component-function Configuration() {- const {- modelConfig,- setModelConfig,- completionParams,- setCompletionParams,- modelModeType,- } = useModelConfig({- currModel,- hasFetchedDetail,- })-- // Component now focuses on UI-}-```--## Naming Conventions--### Hook Names--- Use `use` prefix: `useModelConfig`, `useDatasetConfig`-- Be specific: `useAdvancedPromptConfig` not `usePrompt`-- Include domain: `useWorkflowVariables`, `useMCPServer`--### File Names--- Kebab-case: `use-model-config.ts`-- Place in `hooks/` subdirectory when multiple hooks exist-- Place alongside component for single-use hooks--### Return Type Names--- Suffix with `Return`: `UseModelConfigReturn`-- Suffix params with `Params`: `UseModelConfigParams`--## Common Hook Patterns in Dify--### 1. Data Fetching / Mutation Hooks--When hook extraction touches query or mutation code, do not use this reference as the source of truth for data-layer patterns.--- Do not introduce deprecated `useInvalid` / `useReset`.-- Do not extract thin passthrough `useQuery` hooks; only extract orchestration hooks.--### 2. Form State Hook--```typescript-// Pattern: Form state + validation + submission-export const useConfigForm = (initialValues: ConfigFormValues) => {- const [values, setValues] = useState(initialValues)- const [errors, setErrors] = useState<Record<string, string>>({})- const [isSubmitting, setIsSubmitting] = useState(false)-- const validate = useCallback(() => {- const newErrors: Record<string, string> = {}- if (!values.name) newErrors.name = 'Name is required'- setErrors(newErrors)- return Object.keys(newErrors).length === 0- }, [values])-- const handleChange = useCallback((field: string, value: any) => {- setValues(prev => ({ ...prev, [field]: value }))- }, [])-- const handleSubmit = useCallback(async (onSubmit: (values: ConfigFormValues) => Promise<void>) => {- if (!validate()) return- setIsSubmitting(true)- try {- await onSubmit(values)- } finally {- setIsSubmitting(false)- }- }, [values, validate])-- return { values, errors, isSubmitting, handleChange, handleSubmit }-}-```--### 3. Modal State Hook--```typescript-// Pattern: Multiple modal management-type ModalType = 'edit' | 'delete' | 'duplicate' | null--export const useModalState = () => {- const [activeModal, setActiveModal] = useState<ModalType>(null)- const [modalData, setModalData] = useState<any>(null)-- const openModal = useCallback((type: ModalType, data?: any) => {- setActiveModal(type)- setModalData(data)- }, [])-- const closeModal = useCallback(() => {- setActiveModal(null)- setModalData(null)- }, [])-- return {- activeModal,- modalData,- openModal,- closeModal,- isOpen: useCallback((type: ModalType) => activeModal === type, [activeModal]),- }-}-```--### 4. Toggle/Boolean Hook--```typescript-// Pattern: Boolean state with convenience methods-export const useToggle = (initialValue = false) => {- const [value, setValue] = useState(initialValue)-- const toggle = useCallback(() => setValue(v => !v), [])- const setTrue = useCallback(() => setValue(true), [])- const setFalse = useCallback(() => setValue(false), [])-- return [value, { toggle, setTrue, setFalse, set: setValue }] as const-}--// Usage-const [isExpanded, { toggle, setTrue: expand, setFalse: collapse }] = useToggle()-```--## Testing Extracted Hooks--After extraction, test hooks in isolation:--```typescript-// use-model-config.spec.ts-import { renderHook, act } from '@testing-library/react'-import { useModelConfig } from './use-model-config'--describe('useModelConfig', () => {- it('should initialize with default values', () => {- const { result } = renderHook(() => useModelConfig({- hasFetchedDetail: false,- }))-- expect(result.current.modelConfig.provider).toBe('langgenius/openai/openai')- expect(result.current.modelModeType).toBe(ModelModeType.unset)- })-- it('should update model config', () => {- const { result } = renderHook(() => useModelConfig({- hasFetchedDetail: true,- }))-- act(() => {- result.current.setModelConfig({- ...result.current.modelConfig,- model_id: 'gpt-4',- })- })-- expect(result.current.modelConfig.model_id).toBe('gpt-4')- })-})-```diff --git a/.agents/skills/how-to-write-component/SKILL.md b/.agents/skills/how-to-write-component/SKILL.mdindex 55ad08941c4..738ec9de95a 100644--- a/.agents/skills/how-to-write-component/SKILL.md+++ b/.agents/skills/how-to-write-component/SKILL.md@@ -1,6 +1,6 @@---name: how-to-write-component-description: React/TypeScript component style guide. Use when writing, refactoring, or reviewing React components, especially around props typing, state boundaries, shared local state with Jotai atoms, API types, query/mutation contracts, navigation, memoization, wrappers, and empty-state handling.+description: React/TypeScript component style guide. Use when writing, refactoring, or reviewing React components, especially around abstraction choices, props typing, state boundaries, shared local state with Jotai atoms, API types, query/mutation contracts, navigation, memoization, wrappers, and empty-state handling.---# How To Write A Component@@ -12,26 +12,79 @@ Use this as the decision guide for React/TypeScript component structure. Existin- Search before adding UI, hooks, helpers, or styling patterns. Reuse existing base components, feature components, hooks, utilities, and design styles when they fit.- Group code by feature workflow, route, or ownership area: components, hooks, local types, query helpers, atoms, constants, and small utilities should live near the code that changes with them.- Promote code to shared only when multiple verticals need the same stable primitive. Otherwise keep it local and compose shared primitives inside the owning feature.+- Prefer local code and purpose-named helpers over catch-all utility modules; do not group workflow-specific defaults, validation, payload shaping, or metadata merging in a generic utils file just because they share a DTO.+- Keep source/default selection, validation, and payload shaping close to the workflow that owns the behavior. Do not extract a shared helper just because two flows read the same DTO when their priority order, fallback behavior, or submit semantics differ.+- Prefer direct, readable conditionals at the use site for small branch-specific decisions, especially form source selection and request payload assembly. Extract only when the helper name captures a stable domain rule and removes repeated complexity without hiding flow-specific behavior.+- When fixing an invalid pattern, scan the touched feature or branch for equivalent patterns and fix them together.- Follow Dify's CSS-first Tailwind v4 contract from `packages/dify-ui/README.md` and `packages/dify-ui/AGENTS.md`. Prefer design-system tokens, utilities, and radius mappings over generic Tailwind guidance.+## Feature Workflow Layout++- State-heavy wizards, drawers, modals, and secondary workflows work best as a small feature surface with route/entry files, a single feature-local state file, and feature-local UI.+- Keep `ui/` shallow with owner files that map to the workflow's real composition boundaries and major visual regions.+- Owner files contain the section components, field components, skeletons, and one-off helper components that belong to their visual region.+- Folders represent groups of related files with a shared owner and a stable reason to change together.+- The entry file handles route integration, provider wiring, close behavior, and feature surface mounting. The composition owner handles high-level workflow branching, and the closest visual owner handles section branching.+## Ownership- Put local state, queries, mutations, handlers, and derived UI data in the lowest component that uses them. Extract a purpose-built owner component only when the logic has no natural home.- Repeated TanStack query calls in sibling components are acceptable when each component independently consumes the data. Do not hoist a query only because it is duplicated; TanStack Query handles deduplication and cache sharing.- Hoist state, queries, or callbacks to a parent only when the parent consumes the data, coordinates shared loading/error/empty UI, needs one consistent snapshot, or owns a workflow spanning children.+- Pass stable domain identity across boundaries; avoid forwarding derived presentation state when the receiver can derive it from its own data source. A component that owns a visual surface should also own the data access, loading, empty, and error states for content rendered inside it unless a parent truly coordinates that state.+- Loading states for visual surfaces should use skeleton placeholders scoped to the content that is actually loading, with shape, density, and dimensions close to the final UI. Avoid generic loading text or centered spinners for page sections, cards, lists, tables, forms, and drawers; reserve spinners for small inline busy indicators such as an in-progress status icon.- Avoid prop drilling. One pass-through layer is acceptable; repeated forwarding means ownership should move down or into feature-scoped Jotai UI state. Keep server/cache state in query and API data flow.+- Do not replace prop drilling with one top-level hook that returns a large view model and then thread that object through section props. Move each hook, query, derived value, and handler to the concrete section that consumes it, or use feature-scoped Jotai atoms for simple shared form/UI state when siblings need the same source of truth.+- When using feature-scoped Jotai state for a form, drawer, or other secondary surface, scope the store to that surface instance when stale cross-instance state is possible. Initialize stable config at the owning boundary, then let descendants read only the atoms or purpose-named hooks they actually need.- Keep callbacks in a parent only for workflow coordination such as form submission, shared selection, batch behavior, or navigation. Otherwise let the child or row own its action.- Prefer uncontrolled DOM state and CSS variables before adding controlled props.+## Feature-Scoped Jotai State++- A module's feature-local state lives in one state file for Jotai-backed features: primitive atoms, query atoms, derived atoms, write-only action atoms, mutation atoms, submission orchestration, provider exports, and optional scope configuration.+- Atom order in the state file follows the dependency graph: types/constants, editable primitives, query atoms, query-data derived atoms, readiness/business derived atoms, write actions, mutation atoms, submission orchestration, provider exports.+- Derived atom names read as business facts. Write atom names read as user or workflow commands.+- UI components read and write the exact atom they use with `useAtomValue` or `useSetAtom`. Repeated workflow semantics live in named derived atoms or write atoms.+- Non-query derived atoms return a narrow value with a clear domain name. Query atoms expose the TanStack Query result object so loading, error, fetch, and pagination state stay attached to the query contract.+- Write-only atoms own state transitions that update multiple primitives, reset dependent state, guard stale async work, or advance the workflow.+- `jotai-tanstack-query` atoms use the same QueryClient as the React Query provider. Query atoms belong in feature state when atoms are the feature's local state surface.+- Jotai scope is an optional instance-isolation tool for secondary surfaces with independent local state. Query atoms keep shared cache behavior through the shared QueryClient.+## Components, Props, And Types- Type component signatures directly; do not use `FC` or `React.FC`.- Prefer `function` for top-level components and module helpers. Use arrow functions for local callbacks, handlers, and lambda-style APIs.- Prefer named exports. Use default exports only where the framework requires them, such as Next.js route files.- Type simple one-off props inline. Use a named `Props` type only when reused, exported, complex, or clearer.-- Use API-generated or API-returned types at component boundaries. Keep small UI conversion helpers beside the component that needs them.-- Name values by their domain role and backend API contract, and keep that name stable across the call chain, especially IDs like `appInstanceId`. Normalize framework or route params at the boundary.-- Keep fallback and invariant checks at the lowest component that already handles that state; callers should pass raw values through instead of duplicating checks.+- Use API-generated or API-returned types at component boundaries. Keep small UI conversion helpers and one-off UI extensions beside the component that needs them.+- Do not create type aliases that only rename another type. Use an alias only when it encodes a real UI concept, refinement, or reusable local contract.+- Name values by their domain role and backend API contract, and keep that name stable across the call chain, especially persistent IDs and route params. Normalize framework or route params at the boundary.+- Keep fallback and invariant checks at the lowest component that already handles that state; avoid defensive fallbacks that mask impossible states.+- Do not extract fallback helpers whose only behavior is hiding missing display data. The component that renders the surface owns the empty, disabled, hidden, or placeholder state.++## Generated API Contracts++- Treat generated contracts as authoritative at API, query, mutation, cache, and service boundaries. For enterprise APIs, use `packages/contracts/generated/enterprise/*`.+- Do not hand-write local request/response/reply/page/cache-data types that mirror generated DTOs. Import or infer the generated type.+- Do not widen generated fields or enums for compatibility. Normalize legacy input at the boundary, then return the generated field type.+- Do not repair generated or API-returned contract fields in components unless the API contract or product requirement says they need normalization. Treat enums, statuses, and presence flags as exact contract values.+- Use generated enum objects and union types directly in props, comparisons, status logic, and i18n keys. Do not add local enum constants or parallel frontend enum/status layers unless they model real product state not represented by the API. Presentation-only tone maps should be keyed by the generated enum.+- Normalize or coerce only at a real boundary, such as user-entered forms, search, URL/query params, file names, DOM IDs, or legacy adapters. Preserve user-entered values when whitespace or formatting can be meaningful.+- Do not coerce nullable or optional API strings to `''` in query, derived model, or payload-building code. Keep `undefined` or `null` until the final boundary that requires a string.+- Local UI models are fine for presentation, form state, select options, or guarded required-field refinements. Name them as UI concepts, not generated DTO mirrors.+- Required-value refinements are allowed only after same-branch filtering or early return. Prefer nullable-tolerant props for render-only data.+- When a component needs a stricter shape than a generated DTO, refine once at the API/query-to-UI boundary into a purpose-named UI type instead of hiding missing fields with generic fallback or coercion helpers.++## Nullable API Data++- Prefer nullable-tolerant call boundaries. Pass API-returned types through for render-only rows, and let the component render fallback, disabled state, or nothing.+- Narrow only where a real value is required, such as mutation params, route hrefs, select values, or query input. Build that target model with `flatMap`, a local loop, or an early return so the required value is captured in the same branch.+- If design says a field is the display value, use that field. Only the final component should decide whether a nullable display value renders a placeholder, hides content, or disables an action.+- Do not wrap required arrays or fields in null-fallback helpers. Use empty collection fallbacks only for not-yet-loaded query data or genuinely nullable collections at the owning render boundary.+- Do not drop rows only to satisfy props or React keys; use a stable fallback key when possible.+- Use conditional spreads or explicit pushes for conditional array items instead of `undefined` placeholders followed by a narrowing filter.+- Avoid truthiness type guards, `filter(Boolean)`, `filter(item => item.id)`, and `!` after those filters.+- Use type guards only for meaningful domain or runtime validation, such as enum membership, object shape, or a reusable business invariant.## Queries And Mutations@@ -39,7 +92,8 @@ Use this as the decision guide for React/TypeScript component structure. Existin- Consume queries directly with `useQuery(consoleQuery.xxx.queryOptions(...))` or `useQuery(marketplaceQuery.xxx.queryOptions(...))`.- Avoid pass-through hooks and thin `web/service/use-*` wrappers that only rename `queryOptions()` or `mutationOptions()`. Extract a small `queryOptions` helper only when repeated call-site options justify it.- Keep feature hooks for real orchestration, workflow state, or shared domain behavior.-- For missing required query input, use `input: skipToken`; use `enabled` only for extra business gating after the input is valid.+- For TanStack cache data, use generated or query-derived types; do not create local wrappers for `getQueryData` or `getQueriesData`.+- For generated oRPC `queryOptions()` / `infiniteOptions()`, do not pass `skipToken` as `input`; keep a valid placeholder input shape and use `enabled` to gate missing required params because the OpenAPI codec encodes input eagerly.- Consume mutations directly with `useMutation(consoleQuery.xxx.mutationOptions(...))` or `useMutation(marketplaceQuery.xxx.mutationOptions(...))`; use oRPC clients as `mutationFn` only for custom flows.- Put shared cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`; components may add UI feedback callbacks, but should not own shared invalidation rules.- Do not use deprecated `useInvalid` or `useReset`.@@ -48,12 +102,13 @@ Use this as the decision guide for React/TypeScript component structure. Existin## Component Boundaries- Use the first level below a page or tab to organize independent page sections when it adds real structure. This layer is layout/semantic first, not automatically the data owner.+- Treat component names, semantic roles, and user- or design-marked visual regions as boundary constraints. Do not expand a child component's responsibility just because its data is useful nearby; keep adjacent UI as a sibling owner or introduce a correctly named broader owner.- Split deeper components by the data and state each layer actually needs. Each component should access only necessary data, and ownership should stay at the lowest consumer.- Keep cohesive forms, menu bodies, and one-off helpers local unless they need their own state, reuse, or semantic boundary.- Separate hidden secondary surfaces from the trigger's main flow. For dialogs, dropdowns, popovers, and similar branches, extract a small local component that owns the trigger, open state, and hidden content when it would obscure the parent flow.- Preserve composability by separating behavior ownership from layout ownership. A dropdown action may own its trigger, open state, and menu content; the caller owns placement such as slots, offsets, and alignment.- Avoid unnecessary DOM hierarchy. Do not add wrapper elements unless they provide layout, semantics, accessibility, state ownership, or integration with a library API; prefer fragments or styling an existing element when possible.-- Avoid shallow wrappers and prop renaming unless the wrapper adds validation, orchestration, error handling, state ownership, or a real semantic boundary.+- Avoid shallow wrappers, hook-to-props adapter components, layout-only render-prop wrappers, and prop renaming unless the wrapper adds validation, orchestration, error handling, state ownership, or a real semantic boundary. If a component only calls a hook and forwards every returned field to one child, move the hook into that child or make the wrapper own a real surface.## You Might Not Need An Effect@@ -68,4 +123,6 @@ Use this as the decision guide for React/TypeScript component structure. Existin## Navigation And Performance- Prefer `Link` for normal navigation. Use router APIs only for command-flow side effects such as mutation success, guarded redirects, or form submission.+- Before reaching for `memo`, first try moving changing state down to the smallest component that actually uses it so unrelated sibling trees stay untouched.+- If changing state must wrap other content, lift the unchanged content up and pass it as `children` so the stateful wrapper can update without React visiting that subtree.- Avoid `memo`, `useMemo`, and `useCallback` unless there is a clear performance reason.diff --git a/api/controllers/inner_api/__init__.py b/api/controllers/inner_api/__init__.pyindex c0e079eeb2c..20fd651b759 100644--- a/api/controllers/inner_api/__init__.py+++ b/api/controllers/inner_api/__init__.py@@ -16,6 +16,7 @@ api = ExternalApi(inner_api_ns = Namespace("inner_api", description="Internal API operations", path="/")from . import mail as _mail+from . import runtime_credentials as _runtime_credentialsfrom .app import dsl as _app_dslfrom .knowledge import retrieval as _knowledge_retrievalfrom .plugin import agent_drive as _agent_drive@@ -30,6 +31,7 @@ __all__ = ["_knowledge_retrieval","_mail","_plugin",+ "_runtime_credentials","_workspace","api","bp",diff --git a/api/controllers/inner_api/runtime_credentials.py b/api/controllers/inner_api/runtime_credentials.pynew file mode 100644index 00000000000..bea65230d73--- /dev/null+++ b/api/controllers/inner_api/runtime_credentials.py@@ -0,0 +1,205 @@+"""Inner API endpoints for runtime credential resolution.++Called by Enterprise while resolving AppRunner runtime artifacts. The endpoint+returns decrypted model and tool credentials for in-memory runtime use only.+"""++import json+import logging+from json import JSONDecodeError+from typing import Any++from flask_restx import Resource+from pydantic import BaseModel, ConfigDict, Field+from sqlalchemy import select+from sqlalchemy.orm import Session++from controllers.common.schema import register_schema_model+from controllers.console.wraps import setup_required+from controllers.inner_api import inner_api_ns+from controllers.inner_api.wraps import enterprise_inner_api_only+from core.helper import encrypter+from core.helper.provider_cache import ToolProviderCredentialsCache+from core.helper.provider_encryption import create_provider_encrypter+from core.plugin.impl.model_runtime_factory import create_plugin_provider_manager+from core.tools.tool_manager import ToolManager+from extensions.ext_database import db+from models.provider import ProviderCredential+from models.tools import BuiltinToolProvider++logger = logging.getLogger(__name__)++_KIND_MODEL = "model"+_KIND_TOOL = "tool"++# (body, status) pair returned by a resolver helper when resolution fails.+ResolveError = tuple[dict[str, str], int]+++class InnerRuntimeCredentialResolveItem(BaseModel):+ model_config = ConfigDict(extra="forbid")++ credential_id: str = Field(description="Credential id")+ provider: str = Field(description="Runtime provider identifier, for example langgenius/openai/openai")+ kind: str = Field(description="Credential kind, either 'model' or 'tool'")+++class InnerRuntimeCredentialsResolvePayload(BaseModel):+ model_config = ConfigDict(extra="forbid")++ tenant_id: str = Field(description="Workspace id")+ credentials: list[InnerRuntimeCredentialResolveItem] = Field(default_factory=list)+++register_schema_model(inner_api_ns, InnerRuntimeCredentialsResolvePayload)+++@inner_api_ns.route("/enterprise/credentials/resolve")+class EnterpriseRuntimeCredentialsResolve(Resource):+ @setup_required+ @enterprise_inner_api_only+ @inner_api_ns.doc(+ "enterprise_runtime_credentials_resolve",+ responses={+ 200: "Credentials resolved",+ 400: "Invalid request or credential config",+ 404: "Provider or credential not found",+ },+ )+ @inner_api_ns.expect(inner_api_ns.models[InnerRuntimeCredentialsResolvePayload.__name__])+ def post(self):+ args = InnerRuntimeCredentialsResolvePayload.model_validate(inner_api_ns.payload or {})+ if not args.credentials:+ return {"credentials": []}, 200++ # Model resolution shares one provider configuration set; build it lazily+ # so a tool-only request never pays for the plugin daemon round trip.+ model_configurations = None++ resolved: list[dict[str, Any]] = []+ for item in args.credentials:+ if item.kind == _KIND_MODEL:+ if model_configurations is None:+ provider_manager = create_plugin_provider_manager(tenant_id=args.tenant_id)+ model_configurations = provider_manager.get_configurations(args.tenant_id)+ values, error = _resolve_model(args.tenant_id, model_configurations, item)+ elif item.kind == _KIND_TOOL:+ values, error = _resolve_tool(args.tenant_id, item)+ else:+ return {"message": f"unsupported credential kind '{item.kind}'"}, 400++ if error is not None:+ return error+ resolved.append(+ {+ "credential_id": item.credential_id,+ "kind": item.kind,+ "provider": item.provider,+ "values": values,+ }+ )++ return {"credentials": resolved}, 200+++def _resolve_model(+ tenant_id: str, provider_configurations: Any, item: InnerRuntimeCredentialResolveItem+) -> tuple[dict[str, Any] | None, ResolveError | None]:+ provider_configuration = provider_configurations.get(item.provider)+ if provider_configuration is None:+ return None, ({"message": f"provider '{item.provider}' not found"}, 404)++ provider_schema = provider_configuration.provider.provider_credential_schema+ secret_variables = provider_configuration.extract_secret_variables(+ provider_schema.credential_form_schemas if provider_schema else []+ )++ with Session(db.engine) as session:+ stmt = select(ProviderCredential).where(+ ProviderCredential.id == item.credential_id,+ ProviderCredential.tenant_id == tenant_id,+ ProviderCredential.provider_name.in_(provider_configuration._get_provider_names()),+ )+ credential = session.execute(stmt).scalar_one_or_none()++ if credential is None or not credential.encrypted_config:+ return None, ({"message": f"credential '{item.credential_id}' not found"}, 404)++ try:+ values = json.loads(credential.encrypted_config)+ except JSONDecodeError:+ return None, ({"message": f"credential '{item.credential_id}' has invalid config"}, 400)+ if not isinstance(values, dict):+ return None, ({"message": f"credential '{item.credential_id}' has invalid config"}, 400)++ for key in secret_variables:+ value = values.get(key)+ if value is None:+ continue+ try:+ values[key] = encrypter.decrypt_token(tenant_id=tenant_id, token=value)+ except Exception as exc:+ logger.warning(+ "failed to resolve runtime model credential",+ extra={+ "credential_id": item.credential_id,+ "provider": item.provider,+ "tenant_id": tenant_id,+ "error": type(exc).__name__,+ },+ )+ return None, ({"message": f"credential '{item.credential_id}' decrypt failed"}, 400)++ return values, None+++def _resolve_tool(+ tenant_id: str, item: InnerRuntimeCredentialResolveItem+) -> tuple[dict[str, Any] | None, ResolveError | None]:+ try:+ provider_controller = ToolManager.get_builtin_provider(item.provider, tenant_id)+ except Exception as exc:+ logger.warning(+ "failed to load runtime tool provider",+ extra={"provider": item.provider, "tenant_id": tenant_id, "error": type(exc).__name__},+ )+ return None, ({"message": f"tool provider '{item.provider}' not found"}, 404)++ with Session(db.engine) as session:+ stmt = select(BuiltinToolProvider).where(+ BuiltinToolProvider.id == item.credential_id,+ BuiltinToolProvider.provider == item.provider,+ BuiltinToolProvider.tenant_id == tenant_id,+ )+ builtin_provider = session.execute(stmt).scalar_one_or_none()++ if builtin_provider is None:+ return None, ({"message": f"credential '{item.credential_id}' not found"}, 404)++ try:+ # Tool credentials are stored as a single encrypted dict; the secret+ # fields are decided by the schema bound to this credential type.+ provider_encrypter, _ = create_provider_encrypter(+ tenant_id=tenant_id,+ config=[+ schema.to_basic_provider_config()+ for schema in provider_controller.get_credentials_schema_by_type(builtin_provider.credential_type)+ ],+ cache=ToolProviderCredentialsCache(+ tenant_id=tenant_id, provider=item.provider, credential_id=builtin_provider.id+ ),+ )+ values = dict(provider_encrypter.decrypt(builtin_provider.credentials))+ except Exception as exc:+ logger.warning(+ "failed to resolve runtime tool credential",+ extra={+ "credential_id": item.credential_id,+ "provider": item.provider,+ "tenant_id": tenant_id,+ "error": type(exc).__name__,+ },+ )+ return None, ({"message": f"credential '{item.credential_id}' decrypt failed"}, 400)++ return values, Nonediff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex 3e21ed4fe06..b5dd329c80c 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -18454,6 +18454,7 @@ Model class for provider system configuration response.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || branding | [BrandingModel](#brandingmodel) | | Yes |+| enable_app_deploy | boolean | | Yes || enable_change_email | boolean, <br>**Default:** true | | Yes || enable_collaboration_mode | boolean, <br>**Default:** true | | Yes || enable_creators_platform | boolean | | Yes |diff --git a/api/openapi/markdown/web-openapi.md b/api/openapi/markdown/web-openapi.mdindex 302c2a55e43..ddbb6f51c79 100644--- a/api/openapi/markdown/web-openapi.md+++ b/api/openapi/markdown/web-openapi.md@@ -1597,6 +1597,7 @@ Default configuration for form inputs.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || branding | [BrandingModel](#brandingmodel) | | Yes |+| enable_app_deploy | boolean | | Yes || enable_change_email | boolean, <br>**Default:** true | | Yes || enable_collaboration_mode | boolean, <br>**Default:** true | | Yes || enable_creators_platform | boolean | | Yes |diff --git a/api/services/feature_service.py b/api/services/feature_service.pyindex 4d460c288ac..10a15a0492b 100644--- a/api/services/feature_service.py+++ b/api/services/feature_service.py@@ -160,6 +160,7 @@ class PluginManagerModel(FeatureResponseModel):class SystemFeatureModel(FeatureResponseModel):+ enable_app_deploy: bool = Falsesso_enforced_for_signin: bool = Falsesso_enforced_for_signin_protocol: str = ""enable_marketplace: bool = False@@ -419,6 +420,9 @@ class FeatureService:if "IsAllowCreateWorkspace" in enterprise_info:features.is_allow_create_workspace = enterprise_info["IsAllowCreateWorkspace"]+ if "EnableAppDeploy" in enterprise_info:+ features.enable_app_deploy = enterprise_info["EnableAppDeploy"]+if "Branding" in enterprise_info:features.branding.application_title = enterprise_info["Branding"].get("applicationTitle", "")features.branding.login_page_logo = enterprise_info["Branding"].get("loginPageLogo", "")diff --git a/api/tests/test_containers_integration_tests/services/test_feature_service.py b/api/tests/test_containers_integration_tests/services/test_feature_service.pyindex a678e37b41d..4e5bfc6ac1d 100644--- a/api/tests/test_containers_integration_tests/services/test_feature_service.py+++ b/api/tests/test_containers_integration_tests/services/test_feature_service.py@@ -61,6 +61,7 @@ class TestFeatureService:},"WebAppAuth": {"allowSso": True, "allowEmailCodeLogin": True, "allowEmailPasswordLogin": False},"SSOEnforcedForWebProtocol": "oidc",+ "EnableAppDeploy": True,"License": {"status": "active","expiredAt": "2025-12-31",@@ -291,6 +292,7 @@ class TestFeatureService:assert isinstance(result, SystemFeatureModel)# Verify enterprise features+ assert result.enable_app_deploy is Trueassert result.branding.enabled is Trueassert result.webapp_auth.enabled is Trueassert result.enable_change_email is False@@ -377,6 +379,7 @@ class TestFeatureService:# Ensure that data required for frontend rendering remains accessible.# Branding should match the mock data+ assert result.enable_app_deploy is Trueassert result.branding.enabled is Trueassert result.branding.application_title == "Test Enterprise"assert result.branding.login_page_logo == "https://example.com/logo.png"@@ -424,6 +427,7 @@ class TestFeatureService:assert isinstance(result, SystemFeatureModel)# Verify basic configuration+ assert result.enable_app_deploy is Falseassert result.branding.enabled is Falseassert result.webapp_auth.enabled is Falseassert result.enable_change_email is True@@ -625,6 +629,7 @@ class TestFeatureService:assert isinstance(result, SystemFeatureModel)# Verify enterprise features are disabled+ assert result.enable_app_deploy is Falseassert result.branding.enabled is Falseassert result.webapp_auth.enabled is Falseassert result.enable_change_email is Truediff --git a/api/tests/unit_tests/controllers/inner_api/test_runtime_credentials.py b/api/tests/unit_tests/controllers/inner_api/test_runtime_credentials.pynew file mode 100644index 00000000000..87511a32b8c--- /dev/null+++ b/api/tests/unit_tests/controllers/inner_api/test_runtime_credentials.py@@ -0,0 +1,208 @@+"""Unit tests for runtime credential inner API."""++import inspect+from unittest.mock import MagicMock, patch++from flask import Flask++from controllers.inner_api.runtime_credentials import (+ EnterpriseRuntimeCredentialsResolve,+ InnerRuntimeCredentialsResolvePayload,+)+++def test_runtime_credentials_payload_accepts_items():+ payload = InnerRuntimeCredentialsResolvePayload.model_validate(+ {+ "tenant_id": "tenant-1",+ "credentials": [+ {+ "credential_id": "credential-1",+ "provider": "langgenius/openai/openai",+ "kind": "model",+ }+ ],+ }+ )++ assert payload.tenant_id == "tenant-1"+ assert payload.credentials[0].provider == "langgenius/openai/openai"+ assert payload.credentials[0].kind == "model"+++@patch("controllers.inner_api.runtime_credentials.encrypter.decrypt_token")+@patch("controllers.inner_api.runtime_credentials.db")+@patch("controllers.inner_api.runtime_credentials.Session")+@patch("controllers.inner_api.runtime_credentials.create_plugin_provider_manager")+def test_runtime_model_credentials_resolve_returns_decrypted_values(+ mock_provider_manager_factory,+ mock_session_cls,+ mock_db,+ mock_decrypt_token,+ app: Flask,+):+ provider_configuration = MagicMock()+ provider_configuration.provider.provider_credential_schema.credential_form_schemas = []+ provider_configuration.extract_secret_variables.return_value = ["openai_api_key"]+ provider_configuration._get_provider_names.return_value = ["langgenius/openai/openai", "openai"]++ provider_configurations = MagicMock()+ provider_configurations.get.return_value = provider_configuration+ provider_manager = MagicMock()+ provider_manager.get_configurations.return_value = provider_configurations+ mock_provider_manager_factory.return_value = provider_manager++ credential = MagicMock()+ credential.encrypted_config = '{"openai_api_key":"encrypted","api_base":"https://api.openai.com/v1"}'+ session = MagicMock()+ session.__enter__.return_value = session+ session.__exit__.return_value = False+ session.execute.return_value.scalar_one_or_none.return_value = credential+ mock_session_cls.return_value = session+ mock_db.engine = MagicMock()+ mock_decrypt_token.return_value = "sk-test"++ handler = EnterpriseRuntimeCredentialsResolve()+ unwrapped = inspect.unwrap(handler.post)+ with app.test_request_context():+ with patch("controllers.inner_api.runtime_credentials.inner_api_ns") as mock_ns:+ mock_ns.payload = {+ "tenant_id": "tenant-1",+ "credentials": [+ {+ "credential_id": "credential-1",+ "provider": "langgenius/openai/openai",+ "kind": "model",+ }+ ],+ }+ body, status_code = unwrapped(handler)++ assert status_code == 200+ assert body["credentials"][0]["kind"] == "model"+ assert body["credentials"][0]["values"]["openai_api_key"] == "sk-test"+ assert body["credentials"][0]["values"]["api_base"] == "https://api.openai.com/v1"+ mock_decrypt_token.assert_called_once_with(tenant_id="tenant-1", token="encrypted")+++@patch("controllers.inner_api.runtime_credentials.create_plugin_provider_manager")+def test_runtime_model_credentials_resolve_rejects_unknown_provider(mock_provider_manager_factory, app: Flask):+ provider_configurations = MagicMock()+ provider_configurations.get.return_value = None+ provider_manager = MagicMock()+ provider_manager.get_configurations.return_value = provider_configurations+ mock_provider_manager_factory.return_value = provider_manager++ handler = EnterpriseRuntimeCredentialsResolve()+ unwrapped = inspect.unwrap(handler.post)+ with app.test_request_context():+ with patch("controllers.inner_api.runtime_credentials.inner_api_ns") as mock_ns:+ mock_ns.payload = {+ "tenant_id": "tenant-1",+ "credentials": [{"credential_id": "credential-1", "provider": "missing", "kind": "model"}],+ }+ body, status_code = unwrapped(handler)++ assert status_code == 404+ assert "provider" in body["message"]+++@patch("controllers.inner_api.runtime_credentials.create_provider_encrypter")+@patch("controllers.inner_api.runtime_credentials.ToolProviderCredentialsCache")+@patch("controllers.inner_api.runtime_credentials.db")+@patch("controllers.inner_api.runtime_credentials.Session")+@patch("controllers.inner_api.runtime_credentials.ToolManager")+def test_runtime_tool_credentials_resolve_returns_decrypted_values(+ mock_tool_manager,+ mock_session_cls,+ mock_db,+ mock_cache_cls,+ mock_create_encrypter,+ app: Flask,+):+ provider_controller = MagicMock()+ provider_controller.get_credentials_schema_by_type.return_value = []+ mock_tool_manager.get_builtin_provider.return_value = provider_controller++ builtin_provider = MagicMock()+ builtin_provider.id = "credential-1"+ session = MagicMock()+ session.__enter__.return_value = session+ session.__exit__.return_value = False+ session.execute.return_value.scalar_one_or_none.return_value = builtin_provider+ mock_session_cls.return_value = session+ mock_db.engine = MagicMock()++ provider_encrypter = MagicMock()+ provider_encrypter.decrypt.return_value = {"tavily_api_key": "tvly-secret"}+ mock_create_encrypter.return_value = (provider_encrypter, MagicMock())++ handler = EnterpriseRuntimeCredentialsResolve()+ unwrapped = inspect.unwrap(handler.post)+ with app.test_request_context():+ with patch("controllers.inner_api.runtime_credentials.inner_api_ns") as mock_ns:+ mock_ns.payload = {+ "tenant_id": "tenant-1",+ "credentials": [+ {+ "credential_id": "credential-1",+ "provider": "langgenius/tavily/tavily",+ "kind": "tool",+ }+ ],+ }+ body, status_code = unwrapped(handler)++ assert status_code == 200+ assert body["credentials"][0]["kind"] == "tool"+ assert body["credentials"][0]["provider"] == "langgenius/tavily/tavily"+ assert body["credentials"][0]["values"]["tavily_api_key"] == "tvly-secret"+ compiled = str(session.execute.call_args.args[0].compile(compile_kwargs={"literal_binds": True}))+ assert "tool_builtin_providers.provider = 'langgenius/tavily/tavily'" in compiled+++@patch("controllers.inner_api.runtime_credentials.db")+@patch("controllers.inner_api.runtime_credentials.Session")+@patch("controllers.inner_api.runtime_credentials.ToolManager")+def test_runtime_tool_credentials_resolve_rejects_unknown_credential(+ mock_tool_manager,+ mock_session_cls,+ mock_db,+ app: Flask,+):+ mock_tool_manager.get_builtin_provider.return_value = MagicMock()++ session = MagicMock()+ session.__enter__.return_value = session+ session.__exit__.return_value = False+ session.execute.return_value.scalar_one_or_none.return_value = None+ mock_session_cls.return_value = session+ mock_db.engine = MagicMock()++ handler = EnterpriseRuntimeCredentialsResolve()+ unwrapped = inspect.unwrap(handler.post)+ with app.test_request_context():+ with patch("controllers.inner_api.runtime_credentials.inner_api_ns") as mock_ns:+ mock_ns.payload = {+ "tenant_id": "tenant-1",+ "credentials": [{"credential_id": "missing", "provider": "langgenius/tavily/tavily", "kind": "tool"}],+ }+ body, status_code = unwrapped(handler)++ assert status_code == 404+ assert "credential" in body["message"]+++def test_runtime_credentials_resolve_rejects_unknown_kind(app: Flask):+ handler = EnterpriseRuntimeCredentialsResolve()+ unwrapped = inspect.unwrap(handler.post)+ with app.test_request_context():+ with patch("controllers.inner_api.runtime_credentials.inner_api_ns") as mock_ns:+ mock_ns.payload = {+ "tenant_id": "tenant-1",+ "credentials": [{"credential_id": "credential-1", "provider": "x", "kind": "secret"}],+ }+ body, status_code = unwrapped(handler)++ assert status_code == 400+ assert "kind" in body["message"]diff --git a/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py b/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.pynew file mode 100644index 00000000000..1c3b4fdbc1f--- /dev/null+++ b/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py@@ -0,0 +1,37 @@+import pytest++from services import feature_service as feature_service_module+from services.feature_service import FeatureService, SystemFeatureModel+++ ("enterprise_info", "initial", "expected"),+ [+ # Enterprise reports the feature on -> mirrored through.+ ({"EnableAppDeploy": True}, False, True),+ # Enterprise may turn it off; the read runs after the hardcoded default+ # and overrides it (forward-compat with a future entitlement gate).+ ({"EnableAppDeploy": False}, True, False),+ # Old enterprise without the key -> the existing value is left untouched.+ ({}, True, True),+ ],+ ids=["enabled", "override_off", "missing_keeps_default"],+)+def test_fulfill_params_from_enterprise_enable_app_deploy(+ monkeypatch: pytest.MonkeyPatch,+ enterprise_info: dict,+ initial: bool,+ expected: bool,+):+ monkeypatch.setattr(+ feature_service_module.EnterpriseService,+ "get_info",+ staticmethod(lambda: enterprise_info),+ )++ features = SystemFeatureModel()+ features.enable_app_deploy = initial++ FeatureService._fulfill_params_from_enterprise(features)++ assert features.enable_app_deploy is expecteddiff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex 87230e947ef..8a75a82a9da 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -487,14 +487,6 @@"count": 1}},- "web/app/components/app/app-access-control/access-control-item.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },"web/app/components/app/app-publisher/sections.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -7649,11 +7641,6 @@"count": 1}},- "web/models/access-control.ts": {- "erasable-syntax-only/enums": {- "count": 2- }- },"web/models/app.ts": {"erasable-syntax-only/enums": {"count": 2@@ -8051,11 +8038,6 @@"count": 17}},- "web/utils/clipboard.ts": {- "ts/no-explicit-any": {- "count": 1- }- },"web/utils/completion-params.spec.ts": {"ts/no-explicit-any": {"count": 3diff --git a/packages/contracts/generated/api/console/system-features/types.gen.ts b/packages/contracts/generated/api/console/system-features/types.gen.tsindex 4f2ef2fa94e..01c77ed076d 100644--- a/packages/contracts/generated/api/console/system-features/types.gen.ts+++ b/packages/contracts/generated/api/console/system-features/types.gen.ts@@ -6,6 +6,7 @@ export type ClientOptions = {export type SystemFeatureModel = {branding: BrandingModel+ enable_app_deploy: booleanenable_change_email: booleanenable_collaboration_mode: booleanenable_creators_platform: booleandiff --git a/packages/contracts/generated/api/console/system-features/zod.gen.ts b/packages/contracts/generated/api/console/system-features/zod.gen.tsindex 7464057a391..a7a8946ad50 100644--- a/packages/contracts/generated/api/console/system-features/zod.gen.ts+++ b/packages/contracts/generated/api/console/system-features/zod.gen.ts@@ -98,6 +98,7 @@ export const zSystemFeatureModel = z.object({login_page_logo: '',workspace_logo: '',}),+ enable_app_deploy: z.boolean().default(false),enable_change_email: z.boolean().default(true),enable_collaboration_mode: z.boolean().default(true),enable_creators_platform: z.boolean().default(false),diff --git a/packages/contracts/generated/api/web/types.gen.ts b/packages/contracts/generated/api/web/types.gen.tsindex 9d16cb99524..47eaed612cf 100644--- a/packages/contracts/generated/api/web/types.gen.ts+++ b/packages/contracts/generated/api/web/types.gen.ts@@ -540,6 +540,7 @@ export type SuggestedQuestionsResponse = {export type SystemFeatureModel = {branding: BrandingModel+ enable_app_deploy: booleanenable_change_email: booleanenable_collaboration_mode: booleanenable_creators_platform: booleandiff --git a/packages/contracts/generated/api/web/zod.gen.ts b/packages/contracts/generated/api/web/zod.gen.tsindex cb731344ab6..aa96e4b3231 100644--- a/packages/contracts/generated/api/web/zod.gen.ts+++ b/packages/contracts/generated/api/web/zod.gen.ts@@ -824,6 +824,7 @@ export const zSystemFeatureModel = z.object({login_page_logo: '',workspace_logo: '',}),+ enable_app_deploy: z.boolean().default(false),enable_change_email: z.boolean().default(true),enable_collaboration_mode: z.boolean().default(true),enable_creators_platform: z.boolean().default(false),diff --git a/packages/contracts/generated/enterprise/orpc.gen.ts b/packages/contracts/generated/enterprise/orpc.gen.tsindex 6b9b76470aa..61503a7f742 100644--- a/packages/contracts/generated/enterprise/orpc.gen.ts+++ b/packages/contracts/generated/enterprise/orpc.gen.ts@@ -4,9 +4,97 @@ import { oc } from '@orpc/contract'import * as z from 'zod'import {+ zAccessServiceCreateApiKeyBody,+ zAccessServiceCreateApiKeyPath,+ zAccessServiceCreateApiKeyResponse,+ zAccessServiceDeleteApiKeyPath,+ zAccessServiceDeleteApiKeyResponse,+ zAccessServiceGetAccessChannelsPath,+ zAccessServiceGetAccessChannelsResponse,+ zAccessServiceGetAccessPolicyPath,+ zAccessServiceGetAccessPolicyResponse,+ zAccessServiceGetAccessSettingsPath,+ zAccessServiceGetAccessSettingsResponse,+ zAccessServiceGetDeveloperApiSettingsPath,+ zAccessServiceGetDeveloperApiSettingsResponse,+ zAccessServiceListApiKeysPath,+ zAccessServiceListApiKeysResponse,+ zAccessServiceUpdateAccessChannelsBody,+ zAccessServiceUpdateAccessChannelsPath,+ zAccessServiceUpdateAccessChannelsResponse,+ zAccessServiceUpdateAccessPolicyBody,+ zAccessServiceUpdateAccessPolicyPath,+ zAccessServiceUpdateAccessPolicyResponse,+ zAccessSubjectServiceListAccessSubjectsQuery,+ zAccessSubjectServiceListAccessSubjectsResponse,+ zAppInstanceServiceCreateAppInstanceBody,+ zAppInstanceServiceCreateAppInstanceResponse,+ zAppInstanceServiceDeleteAppInstancePath,+ zAppInstanceServiceDeleteAppInstanceResponse,+ zAppInstanceServiceGetAppInstanceOverviewPath,+ zAppInstanceServiceGetAppInstanceOverviewResponse,+ zAppInstanceServiceGetAppInstancePath,+ zAppInstanceServiceGetAppInstanceResponse,+ zAppInstanceServiceListAppInstancesQuery,+ zAppInstanceServiceListAppInstancesResponse,+ zAppInstanceServiceListAppInstanceSummariesQuery,+ zAppInstanceServiceListAppInstanceSummariesResponse,+ zAppInstanceServiceUpdateAppInstanceBody,+ zAppInstanceServiceUpdateAppInstancePath,+ zAppInstanceServiceUpdateAppInstanceResponse,zConsoleSsoOAuth2LoginResponse,zConsoleSsoOidcLoginResponse,zConsoleSsoSamlLoginResponse,+ zDeploymentServiceCancelDeploymentBody,+ zDeploymentServiceCancelDeploymentPath,+ zDeploymentServiceCancelDeploymentResponse,+ zDeploymentServiceDeployBody,+ zDeploymentServiceDeployResponse,+ zDeploymentServiceListDeploymentsPath,+ zDeploymentServiceListDeploymentsQuery,+ zDeploymentServiceListDeploymentsResponse,+ zDeploymentServiceListEnvironmentDeploymentsPath,+ zDeploymentServiceListEnvironmentDeploymentsResponse,+ zDeploymentServiceListRollbackTargetsPath,+ zDeploymentServiceListRollbackTargetsQuery,+ zDeploymentServiceListRollbackTargetsResponse,+ zDeploymentServicePromoteBody,+ zDeploymentServicePromotePath,+ zDeploymentServicePromoteResponse,+ zDeploymentServiceRollbackBody,+ zDeploymentServiceRollbackPath,+ zDeploymentServiceRollbackResponse,+ zDeploymentServiceUndeployBody,+ zDeploymentServiceUndeployPath,+ zDeploymentServiceUndeployResponse,+ zEnvironmentServiceListEnvironmentsQuery,+ zEnvironmentServiceListEnvironmentsResponse,+ zReleaseServiceComputeDeploymentOptionsBody,+ zReleaseServiceComputeDeploymentOptionsResponse,+ zReleaseServiceComputeReleaseDeploymentViewPath,+ zReleaseServiceComputeReleaseDeploymentViewQuery,+ zReleaseServiceComputeReleaseDeploymentViewResponse,+ zReleaseServiceCreateReleaseBody,+ zReleaseServiceCreateReleaseResponse,+ zReleaseServiceDeleteReleasePath,+ zReleaseServiceDeleteReleaseResponse,+ zReleaseServiceExportReleaseDslPath,+ zReleaseServiceExportReleaseDslResponse,+ zReleaseServiceGetReleasePath,+ zReleaseServiceGetReleaseResponse,+ zReleaseServiceListReleaseCredentialCandidatesPath,+ zReleaseServiceListReleaseCredentialCandidatesResponse,+ zReleaseServiceListReleasesPath,+ zReleaseServiceListReleasesQuery,+ zReleaseServiceListReleasesResponse,+ zReleaseServiceListReleaseSummariesPath,+ zReleaseServiceListReleaseSummariesQuery,+ zReleaseServiceListReleaseSummariesResponse,+ zReleaseServicePrecheckReleaseBody,+ zReleaseServicePrecheckReleaseResponse,+ zReleaseServiceUpdateReleaseBody,+ zReleaseServiceUpdateReleasePath,+ zReleaseServiceUpdateReleaseResponse,zWebAppAuthGetGroupSubjectsQuery,zWebAppAuthGetGroupSubjectsResponse,zWebAppAuthGetWebAppAccessModeQuery,@@ -21,6 +109,524 @@ import {zWebAppAuthUpdateWebAppWhitelistSubjectsResponse,} from './zod.gen'+export const listAccessSubjects = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AccessSubjectService_ListAccessSubjects',+ path: '/enterprise/access-subjects',+ tags: ['AccessSubjectService'],+ })+ .input(z.object({ query: zAccessSubjectServiceListAccessSubjectsQuery.optional() }))+ .output(zAccessSubjectServiceListAccessSubjectsResponse)++export const accessSubjectService = {+ listAccessSubjects,+}++export const listAppInstanceSummaries = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AppInstanceService_ListAppInstanceSummaries',+ path: '/enterprise/app-deploy/appInstanceSummaries',+ tags: ['AppInstanceService'],+ })+ .input(z.object({ query: zAppInstanceServiceListAppInstanceSummariesQuery.optional() }))+ .output(zAppInstanceServiceListAppInstanceSummariesResponse)++export const listAppInstances = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AppInstanceService_ListAppInstances',+ path: '/enterprise/app-deploy/appInstances',+ tags: ['AppInstanceService'],+ })+ .input(z.object({ query: zAppInstanceServiceListAppInstancesQuery.optional() }))+ .output(zAppInstanceServiceListAppInstancesResponse)++export const createAppInstance = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'AppInstanceService_CreateAppInstance',+ path: '/enterprise/app-deploy/appInstances',+ tags: ['AppInstanceService'],+ })+ .input(z.object({ body: zAppInstanceServiceCreateAppInstanceBody }))+ .output(zAppInstanceServiceCreateAppInstanceResponse)++export const deleteAppInstance = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId: 'AppInstanceService_DeleteAppInstance',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}',+ tags: ['AppInstanceService'],+ })+ .input(z.object({ params: zAppInstanceServiceDeleteAppInstancePath }))+ .output(zAppInstanceServiceDeleteAppInstanceResponse)++export const getAppInstance = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AppInstanceService_GetAppInstance',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}',+ tags: ['AppInstanceService'],+ })+ .input(z.object({ params: zAppInstanceServiceGetAppInstancePath }))+ .output(zAppInstanceServiceGetAppInstanceResponse)++export const updateAppInstance = oc+ .route({+ inputStructure: 'detailed',+ method: 'PATCH',+ operationId: 'AppInstanceService_UpdateAppInstance',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}',+ tags: ['AppInstanceService'],+ })+ .input(+ z.object({+ body: zAppInstanceServiceUpdateAppInstanceBody,+ params: zAppInstanceServiceUpdateAppInstancePath,+ }),+ )+ .output(zAppInstanceServiceUpdateAppInstanceResponse)++export const getAppInstanceOverview = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AppInstanceService_GetAppInstanceOverview',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}:getOverview',+ tags: ['AppInstanceService'],+ })+ .input(z.object({ params: zAppInstanceServiceGetAppInstanceOverviewPath }))+ .output(zAppInstanceServiceGetAppInstanceOverviewResponse)++export const appInstanceService = {+ listAppInstanceSummaries,+ listAppInstances,+ createAppInstance,+ deleteAppInstance,+ getAppInstance,+ updateAppInstance,+ getAppInstanceOverview,+}++export const getAccessChannels = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AccessService_GetAccessChannels',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/accessChannels',+ tags: ['AccessService'],+ })+ .input(z.object({ params: zAccessServiceGetAccessChannelsPath }))+ .output(zAccessServiceGetAccessChannelsResponse)++export const updateAccessChannels = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'AccessService_UpdateAccessChannels',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/accessChannels',+ tags: ['AccessService'],+ })+ .input(+ z.object({+ body: zAccessServiceUpdateAccessChannelsBody,+ params: zAccessServiceUpdateAccessChannelsPath,+ }),+ )+ .output(zAccessServiceUpdateAccessChannelsResponse)++export const getAccessSettings = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AccessService_GetAccessSettings',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/accessSettings',+ tags: ['AccessService'],+ })+ .input(z.object({ params: zAccessServiceGetAccessSettingsPath }))+ .output(zAccessServiceGetAccessSettingsResponse)++export const getDeveloperApiSettings = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AccessService_GetDeveloperApiSettings',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/developerApiSettings',+ tags: ['AccessService'],+ })+ .input(z.object({ params: zAccessServiceGetDeveloperApiSettingsPath }))+ .output(zAccessServiceGetDeveloperApiSettingsResponse)++export const getAccessPolicy = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AccessService_GetAccessPolicy',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/accessPolicy',+ tags: ['AccessService'],+ })+ .input(z.object({ params: zAccessServiceGetAccessPolicyPath }))+ .output(zAccessServiceGetAccessPolicyResponse)++export const updateAccessPolicy = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'AccessService_UpdateAccessPolicy',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/accessPolicy',+ tags: ['AccessService'],+ })+ .input(+ z.object({+ body: zAccessServiceUpdateAccessPolicyBody,+ params: zAccessServiceUpdateAccessPolicyPath,+ }),+ )+ .output(zAccessServiceUpdateAccessPolicyResponse)++export const listApiKeys = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'AccessService_ListApiKeys',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/apiKeys',+ tags: ['AccessService'],+ })+ .input(z.object({ params: zAccessServiceListApiKeysPath }))+ .output(zAccessServiceListApiKeysResponse)++export const createApiKey = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'AccessService_CreateApiKey',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/apiKeys',+ tags: ['AccessService'],+ })+ .input(z.object({ body: zAccessServiceCreateApiKeyBody, params: zAccessServiceCreateApiKeyPath }))+ .output(zAccessServiceCreateApiKeyResponse)++export const deleteApiKey = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId: 'AccessService_DeleteApiKey',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/apiKeys/{apiKeyId}',+ tags: ['AccessService'],+ })+ .input(z.object({ params: zAccessServiceDeleteApiKeyPath }))+ .output(zAccessServiceDeleteApiKeyResponse)++export const accessService = {+ getAccessChannels,+ updateAccessChannels,+ getAccessSettings,+ getDeveloperApiSettings,+ getAccessPolicy,+ updateAccessPolicy,+ listApiKeys,+ createApiKey,+ deleteApiKey,+}++export const listDeployments = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'DeploymentService_ListDeployments',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/deployments',+ tags: ['DeploymentService'],+ })+ .input(+ z.object({+ params: zDeploymentServiceListDeploymentsPath,+ query: zDeploymentServiceListDeploymentsQuery.optional(),+ }),+ )+ .output(zDeploymentServiceListDeploymentsResponse)++export const listEnvironmentDeployments = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'DeploymentService_ListEnvironmentDeployments',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environmentDeployments',+ tags: ['DeploymentService'],+ })+ .input(z.object({ params: zDeploymentServiceListEnvironmentDeploymentsPath }))+ .output(zDeploymentServiceListEnvironmentDeploymentsResponse)++export const listRollbackTargets = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'DeploymentService_ListRollbackTargets',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/rollbackTargets',+ tags: ['DeploymentService'],+ })+ .input(+ z.object({+ params: zDeploymentServiceListRollbackTargetsPath,+ query: zDeploymentServiceListRollbackTargetsQuery.optional(),+ }),+ )+ .output(zDeploymentServiceListRollbackTargetsResponse)++/**+ * CancelDeployment cancels the in-flight deployment on the environment.+ */+export const cancelDeployment = oc+ .route({+ description: 'CancelDeployment cancels the in-flight deployment on the environment.',+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'DeploymentService_CancelDeployment',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:cancelDeployment',+ tags: ['DeploymentService'],+ })+ .input(+ z.object({+ body: zDeploymentServiceCancelDeploymentBody,+ params: zDeploymentServiceCancelDeploymentPath,+ }),+ )+ .output(zDeploymentServiceCancelDeploymentResponse)++export const promote = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'DeploymentService_Promote',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:promote',+ tags: ['DeploymentService'],+ })+ .input(z.object({ body: zDeploymentServicePromoteBody, params: zDeploymentServicePromotePath }))+ .output(zDeploymentServicePromoteResponse)++export const rollback = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'DeploymentService_Rollback',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:rollback',+ tags: ['DeploymentService'],+ })+ .input(z.object({ body: zDeploymentServiceRollbackBody, params: zDeploymentServiceRollbackPath }))+ .output(zDeploymentServiceRollbackResponse)++export const undeploy = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'DeploymentService_Undeploy',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:undeploy',+ tags: ['DeploymentService'],+ })+ .input(z.object({ body: zDeploymentServiceUndeployBody, params: zDeploymentServiceUndeployPath }))+ .output(zDeploymentServiceUndeployResponse)++export const deploy = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'DeploymentService_Deploy',+ path: '/enterprise/app-deploy/appInstances:deploy',+ tags: ['DeploymentService'],+ })+ .input(z.object({ body: zDeploymentServiceDeployBody }))+ .output(zDeploymentServiceDeployResponse)++export const deploymentService = {+ listDeployments,+ listEnvironmentDeployments,+ listRollbackTargets,+ cancelDeployment,+ promote,+ rollback,+ undeploy,+ deploy,+}++export const listReleaseSummaries = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'ReleaseService_ListReleaseSummaries',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/releaseSummaries',+ tags: ['ReleaseService'],+ })+ .input(+ z.object({+ params: zReleaseServiceListReleaseSummariesPath,+ query: zReleaseServiceListReleaseSummariesQuery.optional(),+ }),+ )+ .output(zReleaseServiceListReleaseSummariesResponse)++export const listReleases = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'ReleaseService_ListReleases',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}/releases',+ tags: ['ReleaseService'],+ })+ .input(+ z.object({+ params: zReleaseServiceListReleasesPath,+ query: zReleaseServiceListReleasesQuery.optional(),+ }),+ )+ .output(zReleaseServiceListReleasesResponse)++export const computeReleaseDeploymentView = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'ReleaseService_ComputeReleaseDeploymentView',+ path: '/enterprise/app-deploy/appInstances/{appInstanceId}:computeReleaseDeploymentView',+ tags: ['ReleaseService'],+ })+ .input(+ z.object({+ params: zReleaseServiceComputeReleaseDeploymentViewPath,+ query: zReleaseServiceComputeReleaseDeploymentViewQuery.optional(),+ }),+ )+ .output(zReleaseServiceComputeReleaseDeploymentViewResponse)++export const createRelease = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'ReleaseService_CreateRelease',+ path: '/enterprise/app-deploy/releases',+ tags: ['ReleaseService'],+ })+ .input(z.object({ body: zReleaseServiceCreateReleaseBody }))+ .output(zReleaseServiceCreateReleaseResponse)++export const deleteRelease = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId: 'ReleaseService_DeleteRelease',+ path: '/enterprise/app-deploy/releases/{releaseId}',+ tags: ['ReleaseService'],+ })+ .input(z.object({ params: zReleaseServiceDeleteReleasePath }))+ .output(zReleaseServiceDeleteReleaseResponse)++export const getRelease = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'ReleaseService_GetRelease',+ path: '/enterprise/app-deploy/releases/{releaseId}',+ tags: ['ReleaseService'],+ })+ .input(z.object({ params: zReleaseServiceGetReleasePath }))+ .output(zReleaseServiceGetReleaseResponse)++export const updateRelease = oc+ .route({+ inputStructure: 'detailed',+ method: 'PATCH',+ operationId: 'ReleaseService_UpdateRelease',+ path: '/enterprise/app-deploy/releases/{releaseId}',+ tags: ['ReleaseService'],+ })+ .input(+ z.object({ body: zReleaseServiceUpdateReleaseBody, params: zReleaseServiceUpdateReleasePath }),+ )+ .output(zReleaseServiceUpdateReleaseResponse)++export const exportReleaseDsl = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'ReleaseService_ExportReleaseDSL',+ path: '/enterprise/app-deploy/releases/{releaseId}:exportDsl',+ tags: ['ReleaseService'],+ })+ .input(z.object({ params: zReleaseServiceExportReleaseDslPath }))+ .output(zReleaseServiceExportReleaseDslResponse)++export const listReleaseCredentialCandidates = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'ReleaseService_ListReleaseCredentialCandidates',+ path: '/enterprise/app-deploy/releases/{releaseId}:listCredentialCandidates',+ tags: ['ReleaseService'],+ })+ .input(z.object({ params: zReleaseServiceListReleaseCredentialCandidatesPath }))+ .output(zReleaseServiceListReleaseCredentialCandidatesResponse)++export const computeDeploymentOptions = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'ReleaseService_ComputeDeploymentOptions',+ path: '/enterprise/app-deploy/releases:computeDeploymentOptions',+ tags: ['ReleaseService'],+ })+ .input(z.object({ body: zReleaseServiceComputeDeploymentOptionsBody }))+ .output(zReleaseServiceComputeDeploymentOptionsResponse)++export const precheckRelease = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'ReleaseService_PrecheckRelease',+ path: '/enterprise/app-deploy/releases:precheck',+ tags: ['ReleaseService'],+ })+ .input(z.object({ body: zReleaseServicePrecheckReleaseBody }))+ .output(zReleaseServicePrecheckReleaseResponse)++export const releaseService = {+ listReleaseSummaries,+ listReleases,+ computeReleaseDeploymentView,+ createRelease,+ deleteRelease,+ getRelease,+ updateRelease,+ exportReleaseDsl,+ listReleaseCredentialCandidates,+ computeDeploymentOptions,+ precheckRelease,+}++/**+ * ListEnvironments returns only the environments the current user can+ * deploy to.+ */+export const listEnvironments = oc+ .route({+ description: 'ListEnvironments returns only the environments the current user can\n deploy to.',+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'EnvironmentService_ListEnvironments',+ path: '/enterprise/app-deploy/environments',+ tags: ['EnvironmentService'],+ })+ .input(z.object({ query: zEnvironmentServiceListEnvironmentsQuery.optional() }))+ .output(zEnvironmentServiceListEnvironmentsResponse)++export const environmentService = {+ listEnvironments,+}+export const oAuth2Login = oc.route({inputStructure: 'detailed',@@ -133,6 +739,12 @@ export const webAppAuth = {}export const contract = {+ accessSubjectService,+ appInstanceService,+ accessService,+ deploymentService,+ releaseService,+ environmentService,consoleSso,webAppAuth,}diff --git a/packages/contracts/generated/enterprise/types.gen.ts b/packages/contracts/generated/enterprise/types.gen.tsindex b747c4baa89..0c990967a3c 100644--- a/packages/contracts/generated/enterprise/types.gen.ts+++ b/packages/contracts/generated/enterprise/types.gen.ts@@ -4,6 +4,1051 @@ export type ClientOptions = {baseUrl: `${string}://${string}` | (string & {})}+export const AccessMode = {+ ACCESS_MODE_UNSPECIFIED: 'ACCESS_MODE_UNSPECIFIED',+ ACCESS_MODE_PUBLIC: 'ACCESS_MODE_PUBLIC',+ ACCESS_MODE_PRIVATE: 'ACCESS_MODE_PRIVATE',+ ACCESS_MODE_PRIVATE_ALL: 'ACCESS_MODE_PRIVATE_ALL',+} as const++export type AccessMode = (typeof AccessMode)[keyof typeof AccessMode]++export const SubjectType = {+ SUBJECT_TYPE_UNSPECIFIED: 'SUBJECT_TYPE_UNSPECIFIED',+ SUBJECT_TYPE_ACCOUNT: 'SUBJECT_TYPE_ACCOUNT',+ SUBJECT_TYPE_GROUP: 'SUBJECT_TYPE_GROUP',+} as const++export type SubjectType = (typeof SubjectType)[keyof typeof SubjectType]++export const AppRunnerLogStatus = {+ APP_RUNNER_LOG_STATUS_UNSPECIFIED: 'APP_RUNNER_LOG_STATUS_UNSPECIFIED',+ APP_RUNNER_LOG_STATUS_RUNNING: 'APP_RUNNER_LOG_STATUS_RUNNING',+ APP_RUNNER_LOG_STATUS_SUCCEEDED: 'APP_RUNNER_LOG_STATUS_SUCCEEDED',+ APP_RUNNER_LOG_STATUS_FAILED: 'APP_RUNNER_LOG_STATUS_FAILED',+ APP_RUNNER_LOG_STATUS_PARTIAL_SUCCEEDED: 'APP_RUNNER_LOG_STATUS_PARTIAL_SUCCEEDED',+} as const++export type AppRunnerLogStatus = (typeof AppRunnerLogStatus)[keyof typeof AppRunnerLogStatus]++export const AssignmentOperation = {+ ASSIGNMENT_OPERATION_UNSPECIFIED: 'ASSIGNMENT_OPERATION_UNSPECIFIED',+ ASSIGNMENT_OPERATION_LOAD: 'ASSIGNMENT_OPERATION_LOAD',+ ASSIGNMENT_OPERATION_UNLOAD: 'ASSIGNMENT_OPERATION_UNLOAD',+} as const++export type AssignmentOperation = (typeof AssignmentOperation)[keyof typeof AssignmentOperation]++export const EnvironmentMode = {+ ENVIRONMENT_MODE_UNSPECIFIED: 'ENVIRONMENT_MODE_UNSPECIFIED',+ ENVIRONMENT_MODE_SHARED: 'ENVIRONMENT_MODE_SHARED',+ ENVIRONMENT_MODE_ISOLATED: 'ENVIRONMENT_MODE_ISOLATED',+} as const++export type EnvironmentMode = (typeof EnvironmentMode)[keyof typeof EnvironmentMode]++export const RuntimeBackend = {+ RUNTIME_BACKEND_UNSPECIFIED: 'RUNTIME_BACKEND_UNSPECIFIED',+ RUNTIME_BACKEND_K8S: 'RUNTIME_BACKEND_K8S',+ RUNTIME_BACKEND_EXTERNAL: 'RUNTIME_BACKEND_EXTERNAL',+} as const++export type RuntimeBackend = (typeof RuntimeBackend)[keyof typeof RuntimeBackend]++export const PluginCategory = {+ PLUGIN_CATEGORY_UNSPECIFIED: 'PLUGIN_CATEGORY_UNSPECIFIED',+ PLUGIN_CATEGORY_MODEL: 'PLUGIN_CATEGORY_MODEL',+ PLUGIN_CATEGORY_TOOL: 'PLUGIN_CATEGORY_TOOL',+} as const++export type PluginCategory = (typeof PluginCategory)[keyof typeof PluginCategory]++export const DeploymentStatus = {+ DEPLOYMENT_STATUS_UNSPECIFIED: 'DEPLOYMENT_STATUS_UNSPECIFIED',+ DEPLOYMENT_STATUS_DEPLOYING: 'DEPLOYMENT_STATUS_DEPLOYING',+ DEPLOYMENT_STATUS_READY: 'DEPLOYMENT_STATUS_READY',+ DEPLOYMENT_STATUS_FAILED: 'DEPLOYMENT_STATUS_FAILED',+ DEPLOYMENT_STATUS_CANCELLED: 'DEPLOYMENT_STATUS_CANCELLED',+} as const++export type DeploymentStatus = (typeof DeploymentStatus)[keyof typeof DeploymentStatus]++export const DeploymentAction = {+ DEPLOYMENT_ACTION_UNSPECIFIED: 'DEPLOYMENT_ACTION_UNSPECIFIED',+ DEPLOYMENT_ACTION_DEPLOY: 'DEPLOYMENT_ACTION_DEPLOY',+ DEPLOYMENT_ACTION_PROMOTE: 'DEPLOYMENT_ACTION_PROMOTE',+ DEPLOYMENT_ACTION_ROLLBACK: 'DEPLOYMENT_ACTION_ROLLBACK',+ DEPLOYMENT_ACTION_UNDEPLOY: 'DEPLOYMENT_ACTION_UNDEPLOY',+} as const++export type DeploymentAction = (typeof DeploymentAction)[keyof typeof DeploymentAction]++export const DeveloperApiUrlStatus = {+ DEVELOPER_API_URL_STATUS_UNSPECIFIED: 'DEVELOPER_API_URL_STATUS_UNSPECIFIED',+ DEVELOPER_API_URL_STATUS_CONFIGURED: 'DEVELOPER_API_URL_STATUS_CONFIGURED',+ DEVELOPER_API_URL_STATUS_NOT_CONFIGURED: 'DEVELOPER_API_URL_STATUS_NOT_CONFIGURED',+} as const++export type DeveloperApiUrlStatus+ = (typeof DeveloperApiUrlStatus)[keyof typeof DeveloperApiUrlStatus]++export const EnvVarValueSource = {+ ENV_VAR_VALUE_SOURCE_UNSPECIFIED: 'ENV_VAR_VALUE_SOURCE_UNSPECIFIED',+ ENV_VAR_VALUE_SOURCE_LITERAL: 'ENV_VAR_VALUE_SOURCE_LITERAL',+ ENV_VAR_VALUE_SOURCE_DSL_DEFAULT: 'ENV_VAR_VALUE_SOURCE_DSL_DEFAULT',+ ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT: 'ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT',+} as const++export type EnvVarValueSource = (typeof EnvVarValueSource)[keyof typeof EnvVarValueSource]++export const EnvVarValueType = {+ ENV_VAR_VALUE_TYPE_UNSPECIFIED: 'ENV_VAR_VALUE_TYPE_UNSPECIFIED',+ ENV_VAR_VALUE_TYPE_STRING: 'ENV_VAR_VALUE_TYPE_STRING',+ ENV_VAR_VALUE_TYPE_NUMBER: 'ENV_VAR_VALUE_TYPE_NUMBER',+ ENV_VAR_VALUE_TYPE_SECRET: 'ENV_VAR_VALUE_TYPE_SECRET',+} as const++export type EnvVarValueType = (typeof EnvVarValueType)[keyof typeof EnvVarValueType]++export const EnvironmentStatus = {+ ENVIRONMENT_STATUS_UNSPECIFIED: 'ENVIRONMENT_STATUS_UNSPECIFIED',+ ENVIRONMENT_STATUS_ADMISSION: 'ENVIRONMENT_STATUS_ADMISSION',+ ENVIRONMENT_STATUS_BOOTSTRAPPING: 'ENVIRONMENT_STATUS_BOOTSTRAPPING',+ ENVIRONMENT_STATUS_READY: 'ENVIRONMENT_STATUS_READY',+ ENVIRONMENT_STATUS_FAILED: 'ENVIRONMENT_STATUS_FAILED',+ ENVIRONMENT_STATUS_DELETING: 'ENVIRONMENT_STATUS_DELETING',+} as const++export type EnvironmentStatus = (typeof EnvironmentStatus)[keyof typeof EnvironmentStatus]++export const RuntimeInstanceStatus = {+ RUNTIME_INSTANCE_STATUS_UNSPECIFIED: 'RUNTIME_INSTANCE_STATUS_UNSPECIFIED',+ RUNTIME_INSTANCE_STATUS_UNDEPLOYED: 'RUNTIME_INSTANCE_STATUS_UNDEPLOYED',+ RUNTIME_INSTANCE_STATUS_DEPLOYING: 'RUNTIME_INSTANCE_STATUS_DEPLOYING',+ RUNTIME_INSTANCE_STATUS_READY: 'RUNTIME_INSTANCE_STATUS_READY',+ RUNTIME_INSTANCE_STATUS_FAILED: 'RUNTIME_INSTANCE_STATUS_FAILED',+ RUNTIME_INSTANCE_STATUS_DRIFTED: 'RUNTIME_INSTANCE_STATUS_DRIFTED',+ RUNTIME_INSTANCE_STATUS_INVALID: 'RUNTIME_INSTANCE_STATUS_INVALID',+ RUNTIME_INSTANCE_STATUS_UNDEPLOYING: 'RUNTIME_INSTANCE_STATUS_UNDEPLOYING',+} as const++export type RuntimeInstanceStatus+ = (typeof RuntimeInstanceStatus)[keyof typeof RuntimeInstanceStatus]++export const AppRunnerLaunchProfileMode = {+ APP_RUNNER_LAUNCH_PROFILE_MODE_UNSPECIFIED: 'APP_RUNNER_LAUNCH_PROFILE_MODE_UNSPECIFIED',+ APP_RUNNER_LAUNCH_PROFILE_MODE_DEBUG: 'APP_RUNNER_LAUNCH_PROFILE_MODE_DEBUG',+} as const++export type AppRunnerLaunchProfileMode+ = (typeof AppRunnerLaunchProfileMode)[keyof typeof AppRunnerLaunchProfileMode]++export const OperatorType = {+ OPERATOR_TYPE_UNSPECIFIED: 'OPERATOR_TYPE_UNSPECIFIED',+ OPERATOR_TYPE_END_USER: 'OPERATOR_TYPE_END_USER',+ OPERATOR_TYPE_ACCOUNT: 'OPERATOR_TYPE_ACCOUNT',+ OPERATOR_TYPE_SERVICE_ACCOUNT: 'OPERATOR_TYPE_SERVICE_ACCOUNT',+ OPERATOR_TYPE_SYSTEM: 'OPERATOR_TYPE_SYSTEM',+} as const++export type OperatorType = (typeof OperatorType)[keyof typeof OperatorType]++export const ReleaseSource = {+ RELEASE_SOURCE_UNSPECIFIED: 'RELEASE_SOURCE_UNSPECIFIED',+ RELEASE_SOURCE_SOURCE_APP: 'RELEASE_SOURCE_SOURCE_APP',+ RELEASE_SOURCE_UPLOAD: 'RELEASE_SOURCE_UPLOAD',+} as const++export type ReleaseSource = (typeof ReleaseSource)[keyof typeof ReleaseSource]++export const ReleaseEnvironmentActionKind = {+ RELEASE_ENVIRONMENT_ACTION_KIND_UNSPECIFIED: 'RELEASE_ENVIRONMENT_ACTION_KIND_UNSPECIFIED',+ RELEASE_ENVIRONMENT_ACTION_KIND_PROMOTE: 'RELEASE_ENVIRONMENT_ACTION_KIND_PROMOTE',+ RELEASE_ENVIRONMENT_ACTION_KIND_ROLLBACK: 'RELEASE_ENVIRONMENT_ACTION_KIND_ROLLBACK',+ RELEASE_ENVIRONMENT_ACTION_KIND_CURRENT: 'RELEASE_ENVIRONMENT_ACTION_KIND_CURRENT',+ RELEASE_ENVIRONMENT_ACTION_KIND_DEPLOYING: 'RELEASE_ENVIRONMENT_ACTION_KIND_DEPLOYING',+ RELEASE_ENVIRONMENT_ACTION_KIND_BLOCKED: 'RELEASE_ENVIRONMENT_ACTION_KIND_BLOCKED',+} as const++export type ReleaseEnvironmentActionKind+ = (typeof ReleaseEnvironmentActionKind)[keyof typeof ReleaseEnvironmentActionKind]++export const AckStatus = {+ ACK_STATUS_UNSPECIFIED: 'ACK_STATUS_UNSPECIFIED',+ ACK_STATUS_READY: 'ACK_STATUS_READY',+ ACK_STATUS_FAILED: 'ACK_STATUS_FAILED',+} as const++export type AckStatus = (typeof AckStatus)[keyof typeof AckStatus]++export const SlotType = {+ SLOT_TYPE_UNSPECIFIED: 'SLOT_TYPE_UNSPECIFIED',+ SLOT_TYPE_PLUGIN_CREDENTIAL: 'SLOT_TYPE_PLUGIN_CREDENTIAL',+ SLOT_TYPE_ENV_VAR: 'SLOT_TYPE_ENV_VAR',+} as const++export type SlotType = (typeof SlotType)[keyof typeof SlotType]++export const RouteTargetKind = {+ ROUTE_TARGET_KIND_UNSPECIFIED: 'ROUTE_TARGET_KIND_UNSPECIFIED',+ ROUTE_TARGET_KIND_K8S_SERVICE: 'ROUTE_TARGET_KIND_K8S_SERVICE',+ ROUTE_TARGET_KIND_DIRECT_UPSTREAM: 'ROUTE_TARGET_KIND_DIRECT_UPSTREAM',+} as const++export type RouteTargetKind = (typeof RouteTargetKind)[keyof typeof RouteTargetKind]++export const PasswordChangeReason = {+ PASSWORD_CHANGE_REASON_UNSPECIFIED: 'PASSWORD_CHANGE_REASON_UNSPECIFIED',+ PASSWORD_CHANGE_REASON_TEMP: 'PASSWORD_CHANGE_REASON_TEMP',+ PASSWORD_CHANGE_REASON_EXPIRED: 'PASSWORD_CHANGE_REASON_EXPIRED',+ PASSWORD_CHANGE_REASON_POLICY: 'PASSWORD_CHANGE_REASON_POLICY',+} as const++export type PasswordChangeReason = (typeof PasswordChangeReason)[keyof typeof PasswordChangeReason]++export const OtelEndpointMode = {+ OTEL_ENDPOINT_MODE_UNIFIED: 'OTEL_ENDPOINT_MODE_UNIFIED',+ OTEL_ENDPOINT_MODE_DEDICATED: 'OTEL_ENDPOINT_MODE_DEDICATED',+} as const++export type OtelEndpointMode = (typeof OtelEndpointMode)[keyof typeof OtelEndpointMode]++export const AppStatus = {+ APP_STATUS_UNSPECIFIED: 'APP_STATUS_UNSPECIFIED',+ APP_STATUS_PUBLISHED: 'APP_STATUS_PUBLISHED',+ APP_STATUS_UNPUBLISHED: 'APP_STATUS_UNPUBLISHED',+ APP_STATUS_DELETED: 'APP_STATUS_DELETED',+} as const++export type AppStatus = (typeof AppStatus)[keyof typeof AppStatus]++export const LimitType = {+ LIMIT_TYPE_UNSPECIFIED: 'LIMIT_TYPE_UNSPECIFIED',+ LIMIT_TYPE_RPM: 'LIMIT_TYPE_RPM',+ LIMIT_TYPE_CONCURRENCY: 'LIMIT_TYPE_CONCURRENCY',+ LIMIT_TYPE_TOKEN: 'LIMIT_TYPE_TOKEN',+} as const++export type LimitType = (typeof LimitType)[keyof typeof LimitType]++export const LimitAction = {+ LIMIT_ACTION_UNSPECIFIED: 'LIMIT_ACTION_UNSPECIFIED',+ LIMIT_ACTION_BLOCK: 'LIMIT_ACTION_BLOCK',+ LIMIT_ACTION_TRACK: 'LIMIT_ACTION_TRACK',+} as const++export type LimitAction = (typeof LimitAction)[keyof typeof LimitAction]++export const PasswordStrengthLevel = {+ PASSWORD_STRENGTH_LEVEL_UNSPECIFIED: 'PASSWORD_STRENGTH_LEVEL_UNSPECIFIED',+ PASSWORD_STRENGTH_LEVEL_WEAK: 'PASSWORD_STRENGTH_LEVEL_WEAK',+ PASSWORD_STRENGTH_LEVEL_MEDIUM: 'PASSWORD_STRENGTH_LEVEL_MEDIUM',+ PASSWORD_STRENGTH_LEVEL_STRONG: 'PASSWORD_STRENGTH_LEVEL_STRONG',+} as const++export type PasswordStrengthLevel+ = (typeof PasswordStrengthLevel)[keyof typeof PasswordStrengthLevel]++export const PluginInstallationScope = {+ PLUGIN_INSTALLATION_SCOPE_ALL: 'PLUGIN_INSTALLATION_SCOPE_ALL',+ PLUGIN_INSTALLATION_SCOPE_OFFICIAL_ONLY: 'PLUGIN_INSTALLATION_SCOPE_OFFICIAL_ONLY',+ PLUGIN_INSTALLATION_SCOPE_OFFICIAL_AND_SPECIFIC_PARTNERS:+ 'PLUGIN_INSTALLATION_SCOPE_OFFICIAL_AND_SPECIFIC_PARTNERS',+ PLUGIN_INSTALLATION_SCOPE_NONE: 'PLUGIN_INSTALLATION_SCOPE_NONE',+} as const++export type PluginInstallationScope+ = (typeof PluginInstallationScope)[keyof typeof PluginInstallationScope]++export const LimitStatus = {+ LIMIT_STATUS_UNSPECIFIED: 'LIMIT_STATUS_UNSPECIFIED',+ LIMIT_STATUS_NA: 'LIMIT_STATUS_NA',+ LIMIT_STATUS_NORMAL: 'LIMIT_STATUS_NORMAL',+ LIMIT_STATUS_THROTTLED: 'LIMIT_STATUS_THROTTLED',+} as const++export type LimitStatus = (typeof LimitStatus)[keyof typeof LimitStatus]++export type AccessChannels = {+ id: string+ appInstanceId: string+ webAppEnabled: boolean+ developerApiEnabled: boolean+ updatedBy: Actor+ createdAt: string+ updatedAt: string+}++export type AccessEndpoint = {+ environment?: Environment+ endpointUrl: string+}++export type AccessPolicy = {+ id: string+ appInstanceId: string+ environmentId: string+ mode: AccessMode+ subjects: Array<AccessSubject>+ createdAt: string+ updatedAt: string+}++export type AccessSubject = {+ subjectType: SubjectType+ subjectId: string+}++export type Actor = {+ id: string+ displayName: string+}++export type ApiKey = {+ id: string+ appInstanceId: string+ environmentId: string+ displayName: string+ maskedToken: string+ createdBy: Actor+ createdAt: string+ lastUsedAt?: string+}++export type ApiKeySummary = {+ apiKeyCount: number+ environmentCount: number+ developerApiEnabled: boolean+ developerApiUrl: DeveloperApiUrl+}++export type AppInstance = {+ id: string+ tenantId: string+ displayName: string+ description: string+ createdBy: Actor+ updatedBy: Actor+ createdAt: string+ updatedAt: string+}++export type AppInstanceSummary = {+ appInstance: AppInstance+ environmentDeployments: Array<EnvironmentDeployment>+ latestRelease?: Release+ accessChannels: AccessChannels+ apiKeySummary: ApiKeySummary+}++export type AppRunnerLog = {+ id: string+ timestamp: string+ workflowRunId: string+ status: AppRunnerLogStatus+ durationSeconds: number+ totalTokens: string+ workspace: NamedRef+ environment: NamedRef+ appInstance: NamedRef+ operator: Operator+ invokeFrom: string+ traceId: string+ difyTraceId: string+ gateCommitId: string+ body?: string+ attributesJson?: string+ resourceAttributesJson?: string+}++export type BatchResolveRuntimeArtifactsRequest = {+ requests?: Array<RuntimeArtifactRequest>+}++export type BatchResolveRuntimeArtifactsResponse = {+ results?: Array<RuntimeArtifactResult>+}++export type BootstrapAssignment = {+ appId?: string+ environmentId?: string+ workflowId?: string+ runtimeInstanceId?: string+ workspaceId?: string+ runtimeInstanceVersion?: string+ bindingSnapshotVersion?: string+ executionTokenVersion?: string+ executionToken?: string+ releaseId?: string+ operation?: AssignmentOperation+ deploymentId?: string+ requiresStatusReport?: boolean+}++export type BootstrapRunnerRequest = {+ runner?: RunnerInfo+}++export type BootstrapRunnerResponse = {+ runnerId?: string+ assignmentRevision?: string+ assignments?: Array<BootstrapAssignment>+}++export type CancelDeploymentRequest = {+ appInstanceId?: string+ environmentId?: string+}++export type CancelDeploymentResponse = {+ deployment: Deployment+}++export type ComputeDeploymentOptionsRequest = {+ environmentId?: string+ appInstanceId?: string+ dsl?: string+ sourceAppId?: string+ releaseId?: string+}++export type ComputeDeploymentOptionsResponse = {+ options: DeploymentOptions+}++export type ComputeReleaseDeploymentViewResponse = {+ releases: Array<Release>+ environmentDeployments: Array<EnvironmentDeployment>+ environmentActions: Array<ReleaseEnvironmentAction>+ options?: DeploymentOptions+}++export type CreateApiKeyRequest = {+ appInstanceId?: string+ environmentId?: string+ displayName: string+}++export type CreateApiKeyResponse = {+ apiKey: ApiKey+ token: string+}++export type CreateAppInstanceRequest = {+ displayName: string+ description?: string+}++export type CreateAppInstanceResponse = {+ appInstance: AppInstance+}++export type CreateEnvironmentRequest = {+ displayName: string+ description?: string+ mode?: EnvironmentMode+ backend?: RuntimeBackend+ k8s?: K8sEnvironmentConfig+ external?: ExternalAppRunnerConfig+ cpuCount?: number+ idempotencyKey: string+}++export type CreateEnvironmentResponse = {+ environment?: Environment+}++export type CreateReleaseRequest = {+ createAppInstance?: boolean+ appInstanceId?: string+ displayName?: string+ description?: string+ dsl?: string+ sourceAppId?: string+}++export type CreateReleaseResponse = {+ release: Release+ appInstance: AppInstance+}++export type CredentialCandidate = {+ credentialId: string+ providerId: string+ category: PluginCategory+ displayName: string+ fromEnterprise: boolean+}++export type CredentialSelectionInput = {+ providerId: string+ category?: PluginCategory+ credentialId: string+}++export type CredentialSlot = {+ providerId: string+ category: PluginCategory+ candidates: Array<CredentialCandidate>+ lastCredentialId: string+}++export type DashboardListAppInstancesResponse = {+ appInstances: Array<AppInstance>+ pagination: Pagination+}++export type DashboardListEnvironmentDeploymentsResponse = {+ deployments?: Array<EnvironmentDeploymentHistoryItem>+ pagination?: Pagination+}++export type DeleteApiKeyResponse = {+ [key: string]: unknown+}++export type DeleteAppInstanceResponse = {+ [key: string]: unknown+}++export type DeleteEnvironmentResponse = {+ [key: string]: unknown+}++export type DeleteReleaseResponse = {+ [key: string]: unknown+}++export type DeployRequest = {+ dsl?: string+ sourceAppId?: string+ newAppInstance?: NewAppInstance+ environmentId: string+ releaseName?: string+ releaseDescription?: string+ credentials?: Array<CredentialSelectionInput>+ envVars?: Array<EnvVarInput>+ idempotencyKey: string+ expectedDslDigest?: string+}++export type DeployResponse = {+ appInstance: AppInstance+ release: Release+ deployment: Deployment+}++export type Deployment = {+ id: string+ appInstanceId: string+ status: DeploymentStatus+ action: DeploymentAction+ environment: Environment+ release: Release+ error?: Error+ createdBy: Actor+ createdAt: string+ finalizedAt?: string+}++export type DeploymentOptions = {+ dslDigest: string+ appInstanceDefaults: DeploymentOptionsAppInstanceDefaults+ releaseDefaults: DeploymentOptionsReleaseDefaults+ credentialSlots: Array<CredentialSlot>+ envVarSlots: Array<EnvVarSlot>+}++export type DeploymentOptionsAppInstanceDefaults = {+ displayName: string+ description: string+}++export type DeploymentOptionsReleaseDefaults = {+ displayName: string+ description: string+}++export type DeveloperApiUrl = {+ apiUrl: string+ status: DeveloperApiUrlStatus+ error?: Error+}++export type EnvVarInput = {+ key: string+ value?: string+ valueSource?: EnvVarValueSource+}++export type EnvVarSlot = {+ key: string+ valueType: EnvVarValueType+ description: string+ defaultValue?: string+ lastValue?: string+}++export type Environment = {+ id: string+ displayName: string+ description: string+ mode: EnvironmentMode+ backend: RuntimeBackend+ status: EnvironmentStatus+ statusMessage: string+ lastError?: Error+ apiServer?: string+ namespace?: string+ managedBy?: string+ runtimeEndpoint?: string+ cpuCount: number+ createdAt: string+ updatedAt: string+}++export type EnvironmentAccessPolicy = {+ environment: Environment+ policy?: AccessPolicy+ resolvedSubjects: Array<Subject>+}++export type EnvironmentAppInstance = {+ appInstance?: AppInstance+ currentRelease?: Release+ status?: RuntimeInstanceStatus+ lastError?: Error+ workspaceId?: string+ workspaceName?: string+}++export type EnvironmentDeployment = {+ appInstanceId: string+ environment: Environment+ status: RuntimeInstanceStatus+ currentRelease?: Release+ desiredRelease?: Release+ currentDeployment?: EnvironmentDeploymentRecord+ error?: Error+ updatedAt: string+ releasesBehind?: number+}++export type EnvironmentDeploymentHistoryItem = {+ deployment?: Deployment+ appInstanceId?: string+ appInstanceName?: string+ workspaceId?: string+ workspaceName?: string+}++export type EnvironmentDeploymentRecord = {+ id: string+ status: DeploymentStatus+ createdAt: string+ finalizedAt?: string+}++export type Error = {+ code?: string+ message?: string+ phase?: string+ occurredAt?: string+}++export type ExchangeControlTokenRequest = {+ joinToken?: string+}++export type ExchangeControlTokenResponse = {+ accessToken?: string+ expiresAt?: string+}++export type ExportReleaseDslResponse = {+ dsl: string+}++export type ExternalAppRunnerConfig = {+ runtimeEndpoint?: string+}++export type GenerateAppRunnerLaunchProfileRequest = {+ environmentId?: string+ mode?: AppRunnerLaunchProfileMode+ controlEndpoint: string+ pluginDaemonBaseUrl: string+ runtimeListenAddr: string+ debugListenAddr?: string+}++export type GenerateAppRunnerLaunchProfileResponse = {+ environmentId?: string+ joinToken?: string+ configYaml?: string+ runtimeEndpoint?: string+ sourceCommands?: Array<string>+ dockerCommands?: Array<string>+}++export type GetAccessChannelsResponse = {+ accessChannels: AccessChannels+}++export type GetAccessPolicyResponse = {+ policy: AccessPolicy+}++export type GetAccessSettingsResponse = {+ accessChannels: AccessChannels+ environmentPolicies: Array<EnvironmentAccessPolicy>+ webAppEndpoints?: Array<AccessEndpoint>+ cliEndpoint?: AccessEndpoint+}++export type GetAppInstanceOverviewResponse = {+ appInstance: AppInstance+ environmentDeployments: Array<EnvironmentDeployment>+ recentReleases: Array<Release>+ accessChannels: AccessChannels+ apiKeySummary: ApiKeySummary+ totalReleaseCount: number+}++export type GetAppInstanceResponse = {+ appInstance: AppInstance+}++export type GetAppRunnerLogResponse = {+ appRunnerLog: AppRunnerLog+ lastArchived?: string+}++export type GetDeveloperApiSettingsResponse = {+ accessChannels: AccessChannels+ environments: Array<Environment>+ apiKeys: Array<ApiKey>+ developerApiUrl: DeveloperApiUrl+}++export type GetEnvironmentResponse = {+ environment?: Environment+}++export type GetReleaseResponse = {+ release: Release+}++export type K8sEnvironmentConfig = {+ namespace?: string+ apiServer?: string+ caBundle?: string+ bearerToken?: string+}++export type ListApiKeysResponse = {+ apiKeys: Array<ApiKey>+ apiUrl: string+}++export type ListAppInstanceSummariesResponse = {+ appInstanceSummaries: Array<AppInstanceSummary>+ pagination: Pagination+}++export type ListAppInstancesResponse = {+ appInstances: Array<AppInstance>+ pagination: Pagination+}++export type ListAppRunnerLogsResponse = {+ appRunnerLogs: Array<AppRunnerLog>+ pagination: CursorPagination+ lastArchived?: string+}++export type ListDeploymentsResponse = {+ deployments: Array<Deployment>+ pagination: Pagination+}++export type ListEnvironmentAppInstancesResponse = {+ appInstances?: Array<EnvironmentAppInstance>+ pagination?: Pagination+}++export type ListEnvironmentDeploymentsResponse = {+ environmentDeployments: Array<EnvironmentDeployment>+}++export type ListEnvironmentsResponse = {+ environments: Array<Environment>+ pagination: Pagination+}++export type ListReleaseCredentialCandidatesResponse = {+ slots: Array<CredentialSlot>+}++export type ListReleaseSummariesResponse = {+ releaseSummaries: Array<ReleaseSummary>+ pagination: Pagination+}++export type ListReleasesResponse = {+ releases: Array<Release>+ pagination: Pagination+}++export type ListRollbackTargetsResponse = {+ rollbackTargets: Array<RollbackTarget>+ pagination: Pagination+}++export type NamedRef = {+ id: string+ displayName: string+}++export type NewAppInstance = {+ displayName?: string+ description?: string+}++export type Operator = {+ type: OperatorType+ id: string+ displayName: string+}++export type PrecheckReleaseRequest = {+ appInstanceId?: string+ dsl?: string+ sourceAppId?: string+}++export type PrecheckReleaseResponse = {+ gateCommitId: string+ canCreate: boolean+ matchedRelease?: ReleaseContentMatch+ unsupportedNodes: Array<UnsupportedDslNode>+}++export type PromoteRequest = {+ appInstanceId?: string+ releaseId: string+ environmentId?: string+ credentials?: Array<CredentialSelectionInput>+ envVars?: Array<EnvVarInput>+ idempotencyKey: string+}++export type PromoteResponse = {+ deployment: Deployment+}++export type Release = {+ id: string+ appInstanceId: string+ displayName: string+ description: string+ source: ReleaseSource+ sourceAppId?: string+ gateCommitId: string+ requiredSlots: Array<RequiredSlot>+ createdBy: Actor+ createdAt: string+}++export type ReleaseContentMatch = {+ releaseId: string+ displayName: string+ createdAt: string+}++export type ReleaseEnvironmentAction = {+ environment: Environment+ kind: ReleaseEnvironmentActionKind+ disabledReason?: string+ requiresRuntimeInputs: boolean+ currentReleaseId: string+}++export type ReleaseEnvironmentDeployment = {+ environment: Environment+ status: RuntimeInstanceStatus+}++export type ReleaseSummary = {+ release: Release+ deployedEnvironments: Array<ReleaseEnvironmentDeployment>+ environmentActions: Array<ReleaseEnvironmentAction>+ activeEnvironmentCount: number+}++export type ReportRuntimeAssignmentStatusRequest = {+ deploymentId?: string+ runtimeInstanceId?: string+ releaseId?: string+ status?: AckStatus+ lastError?: Error+ runnerId?: string+ assignmentRevision?: string+}++export type ReportRuntimeAssignmentStatusResponse = {+ accepted?: boolean+ stale?: boolean+}++export type RequiredSlot = {+ type: SlotType+ providerId: string+ category: PluginCategory+ key: string+}++export type ResolveApiTokenRouteRequest = {+ token?: string+}++export type ResolveApiTokenRouteResponse = {+ environmentId?: string+ namespace?: string+ serviceName?: string+ servicePort?: number+ environmentStatus?: EnvironmentStatus+ appId?: string+ tenantId?: string+ runtimeInstanceId?: string+ observedReleaseId?: string+ runtimeInstanceStatus?: RuntimeInstanceStatus+ revoked?: boolean+ unavailableReason?: string+ targetKind?: RouteTargetKind+ directUpstream?: string+}++export type RollbackRequest = {+ appInstanceId?: string+ environmentId?: string+ targetReleaseId: string+ idempotencyKey: string+}++export type RollbackResponse = {+ deployment: Deployment+}++export type RollbackTarget = {+ release: Release+ resolvedDeploymentId: string+ deployedAt: string+ isCurrent: boolean+}++export type RunnerInfo = {+ hostname?: string+}++export type RuntimeArtifact = {+ dslYaml?: string+ bindingSnapshotVersion?: string+ bindingSnapshot?: {+ [key: string]: unknown+ }+}++export type RuntimeArtifactRequest = {+ runtimeInstanceId?: string+ releaseId?: string+ deploymentId?: string+ bindingSnapshotVersion?: string+}++export type RuntimeArtifactResult = {+ runtimeInstanceId?: string+ releaseId?: string+ artifact?: RuntimeArtifact+ error?: Error+ deploymentId?: string+}++export type TestConnectionRequest = {+ environmentId?: string+}++export type TestConnectionResponse = {+ reachable?: boolean+ message?: string+}++export type UndeployRequest = {+ appInstanceId?: string+ environmentId?: string+ idempotencyKey: string+}++export type UndeployResponse = {+ deployment: Deployment+}++export type UnsupportedDslNode = {+ id: string+ type: string+}++export type UpdateAccessChannelsRequest = {+ appInstanceId?: string+ webAppEnabled?: boolean+ developerApiEnabled?: boolean+}++export type UpdateAccessChannelsResponse = {+ accessChannels: AccessChannels+}++export type UpdateAccessPolicyRequest = {+ appInstanceId?: string+ environmentId?: string+ mode: AccessMode+ subjects?: Array<AccessSubject>+}++export type UpdateAccessPolicyResponse = {+ policy: AccessPolicy+}++export type UpdateAppInstanceRequest = {+ appInstanceId?: string+ displayName: string+ description?: string+}++export type UpdateAppInstanceResponse = {+ appInstance: AppInstance+}++export type UpdateEnvironmentRequest = {+ environmentId?: string+ displayName: string+ description?: string+}++export type UpdateEnvironmentResponse = {+ environment?: Environment+}++export type UpdateReleaseRequest = {+ releaseId?: string+ displayName: string+ description?: string+}++export type UpdateReleaseResponse = {+ release: Release+}+export type Account = {id?: stringemail?: string@@ -68,7 +1113,7 @@ export type BrandingInfo = {export type CheckPasswordStatusReply = {requirePasswordChange?: boolean- changeReason?: number+ changeReason?: PasswordChangeReasondaysToExpire?: numbermessage?: string}@@ -185,7 +1230,7 @@ export type DeleteWorkspaceReply = {}export type EndpointReply = {- mode?: number+ mode?: OtelEndpointModemetricsEndpoint?: OtelExporterEndpointtracesEndpoint?: OtelExporterEndpoint}@@ -196,6 +1241,14 @@ export type EnterpriseSystemUserSettingReply = {enableEmailPasswordLogin?: boolean}+export type ExternallyAccessibleApp = {+ appId?: string+ tenantId?: string+ mode?: string+ name?: string+ updatedAt?: string+}+export type GetBearerTokenResponse = {maskedToken?: string}@@ -280,7 +1333,7 @@ export type GroupAppItem = {app_name?: stringworkspace_id?: stringworkspace_name?: string- app_status?: number+ app_status?: AppStatustoken_usage?: stringrpm?: stringconcurrency?: string@@ -304,6 +1357,7 @@ export type InfoConfigReply = {Branding?: BrandingInfoWebAppAuth?: WebAppAuthInfoPluginInstallationPermission?: PluginInstallationPermissionInfo+ EnableAppDeploy?: boolean}export type InnerAdmission = {@@ -355,6 +1409,19 @@ export type InnerIsUserAllowedToAccessWebAppRes = {result?: boolean}+export type InnerListExternallyAccessibleAppsReq = {+ page?: number+ limit?: number+ mode?: string+ name?: string+}++export type InnerListExternallyAccessibleAppsRes = {+ data?: Array<ExternallyAccessibleApp>+ total?: number+ hasMore?: boolean+}+export type InnerReleaseAdmissionRequest = {admission?: InnerAdmission}@@ -411,15 +1478,21 @@ export type LicenseStatus = {}export type LimitConfig = {- type?: number+ type?: LimitTypethreshold?: string- action?: number+ action?: LimitActionreached?: boolean}export type LimitFields = {workspaceMembers?: numberworkspaces?: ResourceQuota+ appRunnerEnvCpus?: ResourceQuota+}++export type ListAccessSubjectsReply = {+ subjects?: Array<Subject>+ pagination?: Pagination}export type ListGroupAppsResponse = {@@ -442,6 +1515,11 @@ export type ListSecretKeysReply = {pagination?: Pagination}+export type ListTraceProvidersReply = {+ providers?: Array<TraceProvider>+ catalog?: Array<TraceProviderDescriptor>+}+export type ListUsersReply = {data?: Array<AccountDetail>pagination?: Pagination@@ -531,7 +1609,7 @@ export type OidcReply = {export type OtelExporterEndpoint = {endpoint?: stringcompression?: string- protocol?: number+ protocol?: 'HTTP_PROTOBUF' | 'HTTP_JSON' | 'GRPC'timeout?: stringheaders?: {[key: string]: string@@ -549,7 +1627,7 @@ export type OtelExporterStatusReply = {bytesPushed?: stringitemsInQueue?: stringlogs?: string- status?: number+ status?: 'RUNNING' | 'ERROR' | 'STOPPED'}export type PasswordPolicyConfig = {@@ -565,7 +1643,7 @@ export type PasswordPolicyConfig = {}export type PasswordStrengthReply = {- level?: number+ level?: PasswordStrengthLevel}export type PasswordStrengthReq = {@@ -578,7 +1656,7 @@ export type PluginInstallationPermissionInfo = {}export type PluginInstallationSettingsReply = {- pluginInstallationScope?: number+ pluginInstallationScope?: PluginInstallationScoperestrictToMarketplaceOnly?: boolean}@@ -616,11 +1694,11 @@ export type ResourceGroupDetail = {description?: stringenabled?: booleanrpm_limit?: number- rpm_action?: number+ rpm_action?: LimitActionconcurrency_limit?: number- concurrency_action?: number+ concurrency_action?: LimitActiontoken_quota?: string- token_action?: number+ token_action?: LimitActioncreated_at?: stringupdated_at?: string}@@ -635,8 +1713,8 @@ export type ResourceGroupItem = {token_quota?: stringtoken_usage?: stringapp_count?: string- rpm_status?: number- conc_status?: number+ rpm_status?: LimitStatus+ conc_status?: LimitStatuscreated_at?: stringupdated_at?: string}@@ -684,7 +1762,7 @@ export type SearchAppItem = {app_name?: stringworkspace_id?: stringworkspace_name?: string- app_status?: number+ app_status?: AppStatusicon?: stringicon_type?: stringicon_background?: string@@ -720,7 +1798,7 @@ export type SetDefaultWorkspaceReq = {export type Subject = {subjectId?: string- subjectType?: string+ subjectType?: SubjectTypeaccountData?: SubjectAccountDatagroupData?: SubjectGroupData}@@ -753,21 +1831,61 @@ export type TestConnectionReply = {error?: string}-export type ToggleEndpointRequest = {- enabled?: boolean+export type TestTraceProviderRequest = {+ provider?: TraceProvider}-export type UpdateAccessModeReq = {- appId?: string- accessMode?: string+export type ToggleEndpointRequest = {+ enabled?: boolean}-export type UpdateAccessModeRes = {- message?: string+export type ToggleTraceProviderRequest = {+ id?: string+ enabled?: boolean}-export type UpdateBrandingInfoReq = {- enabled?: boolean+export type TraceProvider = {+ id?: string+ name?: string+ provider?: string+ endpoint?: string+ protocol?: string+ credentials?: {+ [key: string]: string+ }+ settings?: {+ [key: string]: string+ }+ enabled?: boolean+}++export type TraceProviderDescriptor = {+ provider?: string+ displayName?: string+ credentialFields?: Array<TraceProviderField>+ settingFields?: Array<TraceProviderField>+ defaultProtocol?: string+ supportedProtocols?: Array<string>+}++export type TraceProviderField = {+ key?: string+ displayName?: string+ required?: boolean+ secret?: boolean+}++export type UpdateAccessModeReq = {+ appId?: string+ accessMode?: string+}++export type UpdateAccessModeRes = {+ message?: string+}++export type UpdateBrandingInfoReq = {+ enabled?: booleanapplicationTitle?: stringloginPageLogo?: stringworkspaceLogo?: string@@ -850,7 +1968,7 @@ export type UpdateOfflineLicenseReq = {}export type UpdatePluginInstallationSettingsRequest = {- pluginInstallationScope?: number+ pluginInstallationScope?: PluginInstallationScoperestrictToMarketplaceOnly?: boolean}@@ -860,11 +1978,11 @@ export type UpdateResourceGroupRequest = {description?: stringenabled?: booleanrpm_limit?: number- rpm_action?: number+ rpm_action?: LimitActionconcurrency_limit?: number- concurrency_action?: number+ concurrency_action?: LimitActiontoken_quota?: string- token_action?: number+ token_action?: LimitAction}export type UpdateUserReply = {@@ -919,6 +2037,14 @@ export type UpdateWorkspaceReq = {status?: string}+export type UpsertTraceProviderReply = {+ provider?: TraceProvider+}++export type UpsertTraceProviderRequest = {+ provider?: TraceProvider+}+export type WebAppAuthInfo = {allowSso?: booleanallowEmailCodeLogin?: boolean@@ -956,6 +2082,15 @@ export type WorkspacePermission = {allowOwnerTransfer?: boolean}+export type CursorPagination = {+ pageSize?: number+ nextCursor?: string+ prevCursor?: string+ hasNextPage?: boolean+ hasPrevPage?: boolean+ totalCount?: string+}+export type Pagination = {totalCount?: numberperPage?: number@@ -963,6 +2098,633 @@ export type Pagination = {totalPages?: number}+export type AccessSubjectServiceListAccessSubjectsData = {+ body?: never+ path?: never+ query?: {+ keyword?: string+ groupId?: string+ pageNumber?: number+ resultsPerPage?: number+ }+ url: '/enterprise/access-subjects'+}++export type AccessSubjectServiceListAccessSubjectsResponses = {+ 200: ListAccessSubjectsReply+}++export type AccessSubjectServiceListAccessSubjectsResponse+ = AccessSubjectServiceListAccessSubjectsResponses[keyof AccessSubjectServiceListAccessSubjectsResponses]++export type AppInstanceServiceListAppInstanceSummariesData = {+ body?: never+ path?: never+ query?: {+ pageNumber?: number+ resultsPerPage?: number+ displayName?: string+ environmentId?: string+ }+ url: '/enterprise/app-deploy/appInstanceSummaries'+}++export type AppInstanceServiceListAppInstanceSummariesResponses = {+ 200: ListAppInstanceSummariesResponse+}++export type AppInstanceServiceListAppInstanceSummariesResponse+ = AppInstanceServiceListAppInstanceSummariesResponses[keyof AppInstanceServiceListAppInstanceSummariesResponses]++export type AppInstanceServiceListAppInstancesData = {+ body?: never+ path?: never+ query?: {+ pageNumber?: number+ resultsPerPage?: number+ displayName?: string+ environmentId?: string+ }+ url: '/enterprise/app-deploy/appInstances'+}++export type AppInstanceServiceListAppInstancesResponses = {+ 200: ListAppInstancesResponse+}++export type AppInstanceServiceListAppInstancesResponse+ = AppInstanceServiceListAppInstancesResponses[keyof AppInstanceServiceListAppInstancesResponses]++export type AppInstanceServiceCreateAppInstanceData = {+ body: CreateAppInstanceRequest+ path?: never+ query?: never+ url: '/enterprise/app-deploy/appInstances'+}++export type AppInstanceServiceCreateAppInstanceResponses = {+ 200: CreateAppInstanceResponse+}++export type AppInstanceServiceCreateAppInstanceResponse+ = AppInstanceServiceCreateAppInstanceResponses[keyof AppInstanceServiceCreateAppInstanceResponses]++export type AppInstanceServiceDeleteAppInstanceData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}'+}++export type AppInstanceServiceDeleteAppInstanceResponses = {+ 200: DeleteAppInstanceResponse+}++export type AppInstanceServiceDeleteAppInstanceResponse+ = AppInstanceServiceDeleteAppInstanceResponses[keyof AppInstanceServiceDeleteAppInstanceResponses]++export type AppInstanceServiceGetAppInstanceData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}'+}++export type AppInstanceServiceGetAppInstanceResponses = {+ 200: GetAppInstanceResponse+}++export type AppInstanceServiceGetAppInstanceResponse+ = AppInstanceServiceGetAppInstanceResponses[keyof AppInstanceServiceGetAppInstanceResponses]++export type AppInstanceServiceUpdateAppInstanceData = {+ body: UpdateAppInstanceRequest+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}'+}++export type AppInstanceServiceUpdateAppInstanceResponses = {+ 200: UpdateAppInstanceResponse+}++export type AppInstanceServiceUpdateAppInstanceResponse+ = AppInstanceServiceUpdateAppInstanceResponses[keyof AppInstanceServiceUpdateAppInstanceResponses]++export type AccessServiceGetAccessChannelsData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/accessChannels'+}++export type AccessServiceGetAccessChannelsResponses = {+ 200: GetAccessChannelsResponse+}++export type AccessServiceGetAccessChannelsResponse+ = AccessServiceGetAccessChannelsResponses[keyof AccessServiceGetAccessChannelsResponses]++export type AccessServiceUpdateAccessChannelsData = {+ body: UpdateAccessChannelsRequest+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/accessChannels'+}++export type AccessServiceUpdateAccessChannelsResponses = {+ 200: UpdateAccessChannelsResponse+}++export type AccessServiceUpdateAccessChannelsResponse+ = AccessServiceUpdateAccessChannelsResponses[keyof AccessServiceUpdateAccessChannelsResponses]++export type AccessServiceGetAccessSettingsData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/accessSettings'+}++export type AccessServiceGetAccessSettingsResponses = {+ 200: GetAccessSettingsResponse+}++export type AccessServiceGetAccessSettingsResponse+ = AccessServiceGetAccessSettingsResponses[keyof AccessServiceGetAccessSettingsResponses]++export type DeploymentServiceListDeploymentsData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: {+ pageNumber?: number+ resultsPerPage?: number+ environmentId?: string+ }+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/deployments'+}++export type DeploymentServiceListDeploymentsResponses = {+ 200: ListDeploymentsResponse+}++export type DeploymentServiceListDeploymentsResponse+ = DeploymentServiceListDeploymentsResponses[keyof DeploymentServiceListDeploymentsResponses]++export type AccessServiceGetDeveloperApiSettingsData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/developerApiSettings'+}++export type AccessServiceGetDeveloperApiSettingsResponses = {+ 200: GetDeveloperApiSettingsResponse+}++export type AccessServiceGetDeveloperApiSettingsResponse+ = AccessServiceGetDeveloperApiSettingsResponses[keyof AccessServiceGetDeveloperApiSettingsResponses]++export type DeploymentServiceListEnvironmentDeploymentsData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environmentDeployments'+}++export type DeploymentServiceListEnvironmentDeploymentsResponses = {+ 200: ListEnvironmentDeploymentsResponse+}++export type DeploymentServiceListEnvironmentDeploymentsResponse+ = DeploymentServiceListEnvironmentDeploymentsResponses[keyof DeploymentServiceListEnvironmentDeploymentsResponses]++export type AccessServiceGetAccessPolicyData = {+ body?: never+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/accessPolicy'+}++export type AccessServiceGetAccessPolicyResponses = {+ 200: GetAccessPolicyResponse+}++export type AccessServiceGetAccessPolicyResponse+ = AccessServiceGetAccessPolicyResponses[keyof AccessServiceGetAccessPolicyResponses]++export type AccessServiceUpdateAccessPolicyData = {+ body: UpdateAccessPolicyRequest+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/accessPolicy'+}++export type AccessServiceUpdateAccessPolicyResponses = {+ 200: UpdateAccessPolicyResponse+}++export type AccessServiceUpdateAccessPolicyResponse+ = AccessServiceUpdateAccessPolicyResponses[keyof AccessServiceUpdateAccessPolicyResponses]++export type AccessServiceListApiKeysData = {+ body?: never+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/apiKeys'+}++export type AccessServiceListApiKeysResponses = {+ 200: ListApiKeysResponse+}++export type AccessServiceListApiKeysResponse+ = AccessServiceListApiKeysResponses[keyof AccessServiceListApiKeysResponses]++export type AccessServiceCreateApiKeyData = {+ body: CreateApiKeyRequest+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/apiKeys'+}++export type AccessServiceCreateApiKeyResponses = {+ 200: CreateApiKeyResponse+}++export type AccessServiceCreateApiKeyResponse+ = AccessServiceCreateApiKeyResponses[keyof AccessServiceCreateApiKeyResponses]++export type AccessServiceDeleteApiKeyData = {+ body?: never+ path: {+ appInstanceId: string+ environmentId: string+ apiKeyId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/apiKeys/{apiKeyId}'+}++export type AccessServiceDeleteApiKeyResponses = {+ 200: DeleteApiKeyResponse+}++export type AccessServiceDeleteApiKeyResponse+ = AccessServiceDeleteApiKeyResponses[keyof AccessServiceDeleteApiKeyResponses]++export type DeploymentServiceListRollbackTargetsData = {+ body?: never+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: {+ pageNumber?: number+ resultsPerPage?: number+ }+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}/rollbackTargets'+}++export type DeploymentServiceListRollbackTargetsResponses = {+ 200: ListRollbackTargetsResponse+}++export type DeploymentServiceListRollbackTargetsResponse+ = DeploymentServiceListRollbackTargetsResponses[keyof DeploymentServiceListRollbackTargetsResponses]++export type DeploymentServiceCancelDeploymentData = {+ body: CancelDeploymentRequest+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:cancelDeployment'+}++export type DeploymentServiceCancelDeploymentResponses = {+ 200: CancelDeploymentResponse+}++export type DeploymentServiceCancelDeploymentResponse+ = DeploymentServiceCancelDeploymentResponses[keyof DeploymentServiceCancelDeploymentResponses]++export type DeploymentServicePromoteData = {+ body: PromoteRequest+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:promote'+}++export type DeploymentServicePromoteResponses = {+ 200: PromoteResponse+}++export type DeploymentServicePromoteResponse+ = DeploymentServicePromoteResponses[keyof DeploymentServicePromoteResponses]++export type DeploymentServiceRollbackData = {+ body: RollbackRequest+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:rollback'+}++export type DeploymentServiceRollbackResponses = {+ 200: RollbackResponse+}++export type DeploymentServiceRollbackResponse+ = DeploymentServiceRollbackResponses[keyof DeploymentServiceRollbackResponses]++export type DeploymentServiceUndeployData = {+ body: UndeployRequest+ path: {+ appInstanceId: string+ environmentId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/environments/{environmentId}:undeploy'+}++export type DeploymentServiceUndeployResponses = {+ 200: UndeployResponse+}++export type DeploymentServiceUndeployResponse+ = DeploymentServiceUndeployResponses[keyof DeploymentServiceUndeployResponses]++export type ReleaseServiceListReleaseSummariesData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: {+ releaseId?: string+ displayName?: string+ pageNumber?: number+ resultsPerPage?: number+ environmentId?: string+ }+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/releaseSummaries'+}++export type ReleaseServiceListReleaseSummariesResponses = {+ 200: ListReleaseSummariesResponse+}++export type ReleaseServiceListReleaseSummariesResponse+ = ReleaseServiceListReleaseSummariesResponses[keyof ReleaseServiceListReleaseSummariesResponses]++export type ReleaseServiceListReleasesData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: {+ releaseId?: string+ displayName?: string+ pageNumber?: number+ resultsPerPage?: number+ environmentId?: string+ }+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}/releases'+}++export type ReleaseServiceListReleasesResponses = {+ 200: ListReleasesResponse+}++export type ReleaseServiceListReleasesResponse+ = ReleaseServiceListReleasesResponses[keyof ReleaseServiceListReleasesResponses]++export type ReleaseServiceComputeReleaseDeploymentViewData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: {+ releaseId?: string+ environmentId?: string+ }+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}:computeReleaseDeploymentView'+}++export type ReleaseServiceComputeReleaseDeploymentViewResponses = {+ 200: ComputeReleaseDeploymentViewResponse+}++export type ReleaseServiceComputeReleaseDeploymentViewResponse+ = ReleaseServiceComputeReleaseDeploymentViewResponses[keyof ReleaseServiceComputeReleaseDeploymentViewResponses]++export type AppInstanceServiceGetAppInstanceOverviewData = {+ body?: never+ path: {+ appInstanceId: string+ }+ query?: never+ url: '/enterprise/app-deploy/appInstances/{appInstanceId}:getOverview'+}++export type AppInstanceServiceGetAppInstanceOverviewResponses = {+ 200: GetAppInstanceOverviewResponse+}++export type AppInstanceServiceGetAppInstanceOverviewResponse+ = AppInstanceServiceGetAppInstanceOverviewResponses[keyof AppInstanceServiceGetAppInstanceOverviewResponses]++export type DeploymentServiceDeployData = {+ body: DeployRequest+ path?: never+ query?: never+ url: '/enterprise/app-deploy/appInstances:deploy'+}++export type DeploymentServiceDeployResponses = {+ 200: DeployResponse+}++export type DeploymentServiceDeployResponse+ = DeploymentServiceDeployResponses[keyof DeploymentServiceDeployResponses]++export type EnvironmentServiceListEnvironmentsData = {+ body?: never+ path?: never+ query?: {+ environmentId?: string+ displayName?: string+ pageNumber?: number+ resultsPerPage?: number+ }+ url: '/enterprise/app-deploy/environments'+}++export type EnvironmentServiceListEnvironmentsResponses = {+ 200: ListEnvironmentsResponse+}++export type EnvironmentServiceListEnvironmentsResponse+ = EnvironmentServiceListEnvironmentsResponses[keyof EnvironmentServiceListEnvironmentsResponses]++export type ReleaseServiceCreateReleaseData = {+ body: CreateReleaseRequest+ path?: never+ query?: never+ url: '/enterprise/app-deploy/releases'+}++export type ReleaseServiceCreateReleaseResponses = {+ 200: CreateReleaseResponse+}++export type ReleaseServiceCreateReleaseResponse+ = ReleaseServiceCreateReleaseResponses[keyof ReleaseServiceCreateReleaseResponses]++export type ReleaseServiceDeleteReleaseData = {+ body?: never+ path: {+ releaseId: string+ }+ query?: never+ url: '/enterprise/app-deploy/releases/{releaseId}'+}++export type ReleaseServiceDeleteReleaseResponses = {+ 200: DeleteReleaseResponse+}++export type ReleaseServiceDeleteReleaseResponse+ = ReleaseServiceDeleteReleaseResponses[keyof ReleaseServiceDeleteReleaseResponses]++export type ReleaseServiceGetReleaseData = {+ body?: never+ path: {+ releaseId: string+ }+ query?: never+ url: '/enterprise/app-deploy/releases/{releaseId}'+}++export type ReleaseServiceGetReleaseResponses = {+ 200: GetReleaseResponse+}++export type ReleaseServiceGetReleaseResponse+ = ReleaseServiceGetReleaseResponses[keyof ReleaseServiceGetReleaseResponses]++export type ReleaseServiceUpdateReleaseData = {+ body: UpdateReleaseRequest+ path: {+ releaseId: string+ }+ query?: never+ url: '/enterprise/app-deploy/releases/{releaseId}'+}++export type ReleaseServiceUpdateReleaseResponses = {+ 200: UpdateReleaseResponse+}++export type ReleaseServiceUpdateReleaseResponse+ = ReleaseServiceUpdateReleaseResponses[keyof ReleaseServiceUpdateReleaseResponses]++export type ReleaseServiceExportReleaseDslData = {+ body?: never+ path: {+ releaseId: string+ }+ query?: never+ url: '/enterprise/app-deploy/releases/{releaseId}:exportDsl'+}++export type ReleaseServiceExportReleaseDslResponses = {+ 200: ExportReleaseDslResponse+}++export type ReleaseServiceExportReleaseDslResponse+ = ReleaseServiceExportReleaseDslResponses[keyof ReleaseServiceExportReleaseDslResponses]++export type ReleaseServiceListReleaseCredentialCandidatesData = {+ body?: never+ path: {+ releaseId: string+ }+ query?: never+ url: '/enterprise/app-deploy/releases/{releaseId}:listCredentialCandidates'+}++export type ReleaseServiceListReleaseCredentialCandidatesResponses = {+ 200: ListReleaseCredentialCandidatesResponse+}++export type ReleaseServiceListReleaseCredentialCandidatesResponse+ = ReleaseServiceListReleaseCredentialCandidatesResponses[keyof ReleaseServiceListReleaseCredentialCandidatesResponses]++export type ReleaseServiceComputeDeploymentOptionsData = {+ body: ComputeDeploymentOptionsRequest+ path?: never+ query?: never+ url: '/enterprise/app-deploy/releases:computeDeploymentOptions'+}++export type ReleaseServiceComputeDeploymentOptionsResponses = {+ 200: ComputeDeploymentOptionsResponse+}++export type ReleaseServiceComputeDeploymentOptionsResponse+ = ReleaseServiceComputeDeploymentOptionsResponses[keyof ReleaseServiceComputeDeploymentOptionsResponses]++export type ReleaseServicePrecheckReleaseData = {+ body: PrecheckReleaseRequest+ path?: never+ query?: never+ url: '/enterprise/app-deploy/releases:precheck'+}++export type ReleaseServicePrecheckReleaseResponses = {+ 200: PrecheckReleaseResponse+}++export type ReleaseServicePrecheckReleaseResponse+ = ReleaseServicePrecheckReleaseResponses[keyof ReleaseServicePrecheckReleaseResponses]+export type ConsoleSsoOAuth2LoginData = {body?: neverpath?: neverdiff --git a/packages/contracts/generated/enterprise/zod.gen.ts b/packages/contracts/generated/enterprise/zod.gen.tsindex cef500a9064..8e4251b2095 100644--- a/packages/contracts/generated/enterprise/zod.gen.ts+++ b/packages/contracts/generated/enterprise/zod.gen.ts@@ -2,6 +2,975 @@import * as z from 'zod'+export const zAccessMode = z.enum([+ 'ACCESS_MODE_UNSPECIFIED',+ 'ACCESS_MODE_PUBLIC',+ 'ACCESS_MODE_PRIVATE',+ 'ACCESS_MODE_PRIVATE_ALL',+])++export const zSubjectType = z.enum([+ 'SUBJECT_TYPE_UNSPECIFIED',+ 'SUBJECT_TYPE_ACCOUNT',+ 'SUBJECT_TYPE_GROUP',+])++export const zAppRunnerLogStatus = z.enum([+ 'APP_RUNNER_LOG_STATUS_UNSPECIFIED',+ 'APP_RUNNER_LOG_STATUS_RUNNING',+ 'APP_RUNNER_LOG_STATUS_SUCCEEDED',+ 'APP_RUNNER_LOG_STATUS_FAILED',+ 'APP_RUNNER_LOG_STATUS_PARTIAL_SUCCEEDED',+])++export const zAssignmentOperation = z.enum([+ 'ASSIGNMENT_OPERATION_UNSPECIFIED',+ 'ASSIGNMENT_OPERATION_LOAD',+ 'ASSIGNMENT_OPERATION_UNLOAD',+])++export const zEnvironmentMode = z.enum([+ 'ENVIRONMENT_MODE_UNSPECIFIED',+ 'ENVIRONMENT_MODE_SHARED',+ 'ENVIRONMENT_MODE_ISOLATED',+])++export const zRuntimeBackend = z.enum([+ 'RUNTIME_BACKEND_UNSPECIFIED',+ 'RUNTIME_BACKEND_K8S',+ 'RUNTIME_BACKEND_EXTERNAL',+])++export const zPluginCategory = z.enum([+ 'PLUGIN_CATEGORY_UNSPECIFIED',+ 'PLUGIN_CATEGORY_MODEL',+ 'PLUGIN_CATEGORY_TOOL',+])++export const zDeploymentStatus = z.enum([+ 'DEPLOYMENT_STATUS_UNSPECIFIED',+ 'DEPLOYMENT_STATUS_DEPLOYING',+ 'DEPLOYMENT_STATUS_READY',+ 'DEPLOYMENT_STATUS_FAILED',+ 'DEPLOYMENT_STATUS_CANCELLED',+])++export const zDeploymentAction = z.enum([+ 'DEPLOYMENT_ACTION_UNSPECIFIED',+ 'DEPLOYMENT_ACTION_DEPLOY',+ 'DEPLOYMENT_ACTION_PROMOTE',+ 'DEPLOYMENT_ACTION_ROLLBACK',+ 'DEPLOYMENT_ACTION_UNDEPLOY',+])++export const zDeveloperApiUrlStatus = z.enum([+ 'DEVELOPER_API_URL_STATUS_UNSPECIFIED',+ 'DEVELOPER_API_URL_STATUS_CONFIGURED',+ 'DEVELOPER_API_URL_STATUS_NOT_CONFIGURED',+])++export const zEnvVarValueSource = z.enum([+ 'ENV_VAR_VALUE_SOURCE_UNSPECIFIED',+ 'ENV_VAR_VALUE_SOURCE_LITERAL',+ 'ENV_VAR_VALUE_SOURCE_DSL_DEFAULT',+ 'ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT',+])++export const zEnvVarValueType = z.enum([+ 'ENV_VAR_VALUE_TYPE_UNSPECIFIED',+ 'ENV_VAR_VALUE_TYPE_STRING',+ 'ENV_VAR_VALUE_TYPE_NUMBER',+ 'ENV_VAR_VALUE_TYPE_SECRET',+])++export const zEnvironmentStatus = z.enum([+ 'ENVIRONMENT_STATUS_UNSPECIFIED',+ 'ENVIRONMENT_STATUS_ADMISSION',+ 'ENVIRONMENT_STATUS_BOOTSTRAPPING',+ 'ENVIRONMENT_STATUS_READY',+ 'ENVIRONMENT_STATUS_FAILED',+ 'ENVIRONMENT_STATUS_DELETING',+])++export const zRuntimeInstanceStatus = z.enum([+ 'RUNTIME_INSTANCE_STATUS_UNSPECIFIED',+ 'RUNTIME_INSTANCE_STATUS_UNDEPLOYED',+ 'RUNTIME_INSTANCE_STATUS_DEPLOYING',+ 'RUNTIME_INSTANCE_STATUS_READY',+ 'RUNTIME_INSTANCE_STATUS_FAILED',+ 'RUNTIME_INSTANCE_STATUS_DRIFTED',+ 'RUNTIME_INSTANCE_STATUS_INVALID',+ 'RUNTIME_INSTANCE_STATUS_UNDEPLOYING',+])++export const zAppRunnerLaunchProfileMode = z.enum([+ 'APP_RUNNER_LAUNCH_PROFILE_MODE_UNSPECIFIED',+ 'APP_RUNNER_LAUNCH_PROFILE_MODE_DEBUG',+])++export const zOperatorType = z.enum([+ 'OPERATOR_TYPE_UNSPECIFIED',+ 'OPERATOR_TYPE_END_USER',+ 'OPERATOR_TYPE_ACCOUNT',+ 'OPERATOR_TYPE_SERVICE_ACCOUNT',+ 'OPERATOR_TYPE_SYSTEM',+])++export const zReleaseSource = z.enum([+ 'RELEASE_SOURCE_UNSPECIFIED',+ 'RELEASE_SOURCE_SOURCE_APP',+ 'RELEASE_SOURCE_UPLOAD',+])++export const zReleaseEnvironmentActionKind = z.enum([+ 'RELEASE_ENVIRONMENT_ACTION_KIND_UNSPECIFIED',+ 'RELEASE_ENVIRONMENT_ACTION_KIND_PROMOTE',+ 'RELEASE_ENVIRONMENT_ACTION_KIND_ROLLBACK',+ 'RELEASE_ENVIRONMENT_ACTION_KIND_CURRENT',+ 'RELEASE_ENVIRONMENT_ACTION_KIND_DEPLOYING',+ 'RELEASE_ENVIRONMENT_ACTION_KIND_BLOCKED',+])++export const zAckStatus = z.enum([+ 'ACK_STATUS_UNSPECIFIED',+ 'ACK_STATUS_READY',+ 'ACK_STATUS_FAILED',+])++export const zSlotType = z.enum([+ 'SLOT_TYPE_UNSPECIFIED',+ 'SLOT_TYPE_PLUGIN_CREDENTIAL',+ 'SLOT_TYPE_ENV_VAR',+])++export const zRouteTargetKind = z.enum([+ 'ROUTE_TARGET_KIND_UNSPECIFIED',+ 'ROUTE_TARGET_KIND_K8S_SERVICE',+ 'ROUTE_TARGET_KIND_DIRECT_UPSTREAM',+])++export const zPasswordChangeReason = z.enum([+ 'PASSWORD_CHANGE_REASON_UNSPECIFIED',+ 'PASSWORD_CHANGE_REASON_TEMP',+ 'PASSWORD_CHANGE_REASON_EXPIRED',+ 'PASSWORD_CHANGE_REASON_POLICY',+])++export const zOtelEndpointMode = z.enum([+ 'OTEL_ENDPOINT_MODE_UNIFIED',+ 'OTEL_ENDPOINT_MODE_DEDICATED',+])++export const zAppStatus = z.enum([+ 'APP_STATUS_UNSPECIFIED',+ 'APP_STATUS_PUBLISHED',+ 'APP_STATUS_UNPUBLISHED',+ 'APP_STATUS_DELETED',+])++export const zLimitType = z.enum([+ 'LIMIT_TYPE_UNSPECIFIED',+ 'LIMIT_TYPE_RPM',+ 'LIMIT_TYPE_CONCURRENCY',+ 'LIMIT_TYPE_TOKEN',+])++export const zLimitAction = z.enum([+ 'LIMIT_ACTION_UNSPECIFIED',+ 'LIMIT_ACTION_BLOCK',+ 'LIMIT_ACTION_TRACK',+])++export const zPasswordStrengthLevel = z.enum([+ 'PASSWORD_STRENGTH_LEVEL_UNSPECIFIED',+ 'PASSWORD_STRENGTH_LEVEL_WEAK',+ 'PASSWORD_STRENGTH_LEVEL_MEDIUM',+ 'PASSWORD_STRENGTH_LEVEL_STRONG',+])++export const zPluginInstallationScope = z.enum([+ 'PLUGIN_INSTALLATION_SCOPE_ALL',+ 'PLUGIN_INSTALLATION_SCOPE_OFFICIAL_ONLY',+ 'PLUGIN_INSTALLATION_SCOPE_OFFICIAL_AND_SPECIFIC_PARTNERS',+ 'PLUGIN_INSTALLATION_SCOPE_NONE',+])++export const zLimitStatus = z.enum([+ 'LIMIT_STATUS_UNSPECIFIED',+ 'LIMIT_STATUS_NA',+ 'LIMIT_STATUS_NORMAL',+ 'LIMIT_STATUS_THROTTLED',+])++export const zAccessSubject = z.object({+ subjectType: zSubjectType,+ subjectId: z.string(),+})++export const zAccessPolicy = z.object({+ id: z.string(),+ appInstanceId: z.string(),+ environmentId: z.string(),+ mode: zAccessMode,+ subjects: z.array(zAccessSubject),+ createdAt: z.iso.datetime(),+ updatedAt: z.iso.datetime(),+})++export const zActor = z.object({+ id: z.string(),+ displayName: z.string(),+})++export const zAccessChannels = z.object({+ id: z.string(),+ appInstanceId: z.string(),+ webAppEnabled: z.boolean(),+ developerApiEnabled: z.boolean(),+ updatedBy: zActor,+ createdAt: z.iso.datetime(),+ updatedAt: z.iso.datetime(),+})++export const zApiKey = z.object({+ id: z.string(),+ appInstanceId: z.string(),+ environmentId: z.string(),+ displayName: z.string(),+ maskedToken: z.string(),+ createdBy: zActor,+ createdAt: z.iso.datetime(),+ lastUsedAt: z.iso.datetime().optional(),+})++export const zAppInstance = z.object({+ id: z.string(),+ tenantId: z.string(),+ displayName: z.string(),+ description: z.string(),+ createdBy: zActor,+ updatedBy: zActor,+ createdAt: z.iso.datetime(),+ updatedAt: z.iso.datetime(),+})++/**+ * BootstrapAssignment is one runtime_instance assignment in a runner's startup+ * baseline.+ */+export const zBootstrapAssignment = z.object({+ appId: z.string().optional(),+ environmentId: z.string().optional(),+ workflowId: z.string().optional(),+ runtimeInstanceId: z.string().optional(),+ workspaceId: z.string().optional(),+ runtimeInstanceVersion: z.string().optional(),+ bindingSnapshotVersion: z.string().optional(),+ executionTokenVersion: z.string().optional(),+ executionToken: z.string().optional(),+ releaseId: z.string().optional(),+ operation: zAssignmentOperation.optional(),+ deploymentId: z.string().optional(),+ requiresStatusReport: z.boolean().optional(),+})++export const zBootstrapRunnerResponse = z.object({+ runnerId: z.string().optional(),+ assignmentRevision: z.string().optional(),+ assignments: z.array(zBootstrapAssignment).optional(),+})++export const zCancelDeploymentRequest = z.object({+ appInstanceId: z.string().optional(),+ environmentId: z.string().optional(),+})++export const zComputeDeploymentOptionsRequest = z.object({+ environmentId: z.string().optional(),+ appInstanceId: z.string().optional(),+ dsl: z.string().optional(),+ sourceAppId: z.string().optional(),+ releaseId: z.string().optional(),+})++export const zCreateApiKeyRequest = z.object({+ appInstanceId: z.string().optional(),+ environmentId: z.string().optional(),+ displayName: z.string(),+})++export const zCreateApiKeyResponse = z.object({+ apiKey: zApiKey,+ token: z.string(),+})++export const zCreateAppInstanceRequest = z.object({+ displayName: z.string(),+ description: z.string().optional(),+})++export const zCreateAppInstanceResponse = z.object({+ appInstance: zAppInstance,+})++export const zCreateReleaseRequest = z.object({+ createAppInstance: z.boolean().optional(),+ appInstanceId: z.string().optional(),+ displayName: z.string().optional(),+ description: z.string().optional(),+ dsl: z.string().optional(),+ sourceAppId: z.string().optional(),+})++/**+ * CredentialCandidate is one tenant-visible credential a frontend may+ * pick for a credential slot. It carries no secret.+ */+export const zCredentialCandidate = z.object({+ credentialId: z.string(),+ providerId: z.string(),+ category: zPluginCategory,+ displayName: z.string(),+ fromEnterprise: z.boolean(),+})++/**+ * CredentialSelectionInput is one deploy-time plugin-credential+ * selection: a shared credential id chosen for a required DSL slot.+ */+export const zCredentialSelectionInput = z.object({+ providerId: z.string(),+ category: zPluginCategory.optional(),+ credentialId: z.string(),+})++/**+ * CredentialSlot is one model/tool plugin-credential requirement a+ * Release's DSL declares, paired with the candidates selectable for it.+ */+export const zCredentialSlot = z.object({+ providerId: z.string(),+ category: zPluginCategory,+ candidates: z.array(zCredentialCandidate),+ lastCredentialId: z.string(),+})++export const zDeleteApiKeyResponse = z.record(z.string(), z.unknown())++export const zDeleteAppInstanceResponse = z.record(z.string(), z.unknown())++export const zDeleteEnvironmentResponse = z.record(z.string(), z.unknown())++export const zDeleteReleaseResponse = z.record(z.string(), z.unknown())++export const zDeploymentOptionsAppInstanceDefaults = z.object({+ displayName: z.string(),+ description: z.string(),+})++export const zDeploymentOptionsReleaseDefaults = z.object({+ displayName: z.string(),+ description: z.string(),+})++export const zEnvVarInput = z.object({+ key: z.string(),+ value: z.string().optional(),+ valueSource: zEnvVarValueSource.optional(),+})++export const zEnvVarSlot = z.object({+ key: z.string(),+ valueType: zEnvVarValueType,+ description: z.string(),+ defaultValue: z.string().optional(),+ lastValue: z.string().optional(),+})++export const zDeploymentOptions = z.object({+ dslDigest: z.string(),+ appInstanceDefaults: zDeploymentOptionsAppInstanceDefaults,+ releaseDefaults: zDeploymentOptionsReleaseDefaults,+ credentialSlots: z.array(zCredentialSlot),+ envVarSlots: z.array(zEnvVarSlot),+})++export const zComputeDeploymentOptionsResponse = z.object({+ options: zDeploymentOptions,+})++export const zEnvironmentDeploymentRecord = z.object({+ id: z.string(),+ status: zDeploymentStatus,+ createdAt: z.iso.datetime(),+ finalizedAt: z.iso.datetime().optional(),+})++/**+ * Error is the package-wide failure shape, carried wherever an operation or+ * resource reports an error.+ */+export const zError = z.object({+ code: z.string().optional(),+ message: z.string().optional(),+ phase: z.string().optional(),+ occurredAt: z.iso.datetime().optional(),+})++export const zDeveloperApiUrl = z.object({+ apiUrl: z.string(),+ status: zDeveloperApiUrlStatus,+ error: zError.optional(),+})++export const zApiKeySummary = z.object({+ apiKeyCount: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+ environmentCount: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+ developerApiEnabled: z.boolean(),+ developerApiUrl: zDeveloperApiUrl,+})++export const zEnvironment = z.object({+ id: z.string(),+ displayName: z.string(),+ description: z.string(),+ mode: zEnvironmentMode,+ backend: zRuntimeBackend,+ status: zEnvironmentStatus,+ statusMessage: z.string(),+ lastError: zError.optional(),+ apiServer: z.string().optional(),+ namespace: z.string().optional(),+ managedBy: z.string().optional(),+ runtimeEndpoint: z.string().optional(),+ cpuCount: z.number(),+ createdAt: z.iso.datetime(),+ updatedAt: z.iso.datetime(),+})++export const zAccessEndpoint = z.object({+ environment: zEnvironment.optional(),+ endpointUrl: z.string(),+})++export const zCreateEnvironmentResponse = z.object({+ environment: zEnvironment.optional(),+})++export const zExchangeControlTokenRequest = z.object({+ joinToken: z.string().optional(),+})++export const zExchangeControlTokenResponse = z.object({+ accessToken: z.string().optional(),+ expiresAt: z.iso.datetime().optional(),+})++export const zExportReleaseDslResponse = z.object({+ dsl: z.string(),+})++export const zExternalAppRunnerConfig = z.object({+ runtimeEndpoint: z.string().optional(),+})++export const zGenerateAppRunnerLaunchProfileRequest = z.object({+ environmentId: z.string().optional(),+ mode: zAppRunnerLaunchProfileMode.optional(),+ controlEndpoint: z.string(),+ pluginDaemonBaseUrl: z.string(),+ runtimeListenAddr: z.string(),+ debugListenAddr: z.string().optional(),+})++export const zGenerateAppRunnerLaunchProfileResponse = z.object({+ environmentId: z.string().optional(),+ joinToken: z.string().optional(),+ configYaml: z.string().optional(),+ runtimeEndpoint: z.string().optional(),+ sourceCommands: z.array(z.string()).optional(),+ dockerCommands: z.array(z.string()).optional(),+})++export const zGetAccessChannelsResponse = z.object({+ accessChannels: zAccessChannels,+})++export const zGetAccessPolicyResponse = z.object({+ policy: zAccessPolicy,+})++export const zGetAppInstanceResponse = z.object({+ appInstance: zAppInstance,+})++export const zGetDeveloperApiSettingsResponse = z.object({+ accessChannels: zAccessChannels,+ environments: z.array(zEnvironment),+ apiKeys: z.array(zApiKey),+ developerApiUrl: zDeveloperApiUrl,+})++export const zGetEnvironmentResponse = z.object({+ environment: zEnvironment.optional(),+})++export const zK8sEnvironmentConfig = z.object({+ namespace: z.string().optional(),+ apiServer: z.string().optional(),+ caBundle: z.string().optional(),+ bearerToken: z.string().optional(),+})++export const zCreateEnvironmentRequest = z.object({+ displayName: z.string(),+ description: z.string().optional(),+ mode: zEnvironmentMode.optional(),+ backend: zRuntimeBackend.optional(),+ k8s: zK8sEnvironmentConfig.optional(),+ external: zExternalAppRunnerConfig.optional(),+ cpuCount: z.number().optional(),+ idempotencyKey: z.string(),+})++export const zListApiKeysResponse = z.object({+ apiKeys: z.array(zApiKey),+ apiUrl: z.string(),+})++export const zListReleaseCredentialCandidatesResponse = z.object({+ slots: z.array(zCredentialSlot),+})++export const zNamedRef = z.object({+ id: z.string(),+ displayName: z.string(),+})++export const zNewAppInstance = z.object({+ displayName: z.string().optional(),+ description: z.string().optional(),+})++export const zDeployRequest = z.object({+ dsl: z.string().optional(),+ sourceAppId: z.string().optional(),+ newAppInstance: zNewAppInstance.optional(),+ environmentId: z.string(),+ releaseName: z.string().optional(),+ releaseDescription: z.string().optional(),+ credentials: z.array(zCredentialSelectionInput).optional(),+ envVars: z.array(zEnvVarInput).optional(),+ idempotencyKey: z.string(),+ expectedDslDigest: z.string().optional(),+})++/**+ * Operator is who triggered the run (the "END USER OR ACCOUNT" column).+ */+export const zOperator = z.object({+ type: zOperatorType,+ id: z.string(),+ displayName: z.string(),+})++export const zAppRunnerLog = z.object({+ id: z.string(),+ timestamp: z.iso.datetime(),+ workflowRunId: z.string(),+ status: zAppRunnerLogStatus,+ durationSeconds: z.number(),+ totalTokens: z.string(),+ workspace: zNamedRef,+ environment: zNamedRef,+ appInstance: zNamedRef,+ operator: zOperator,+ invokeFrom: z.string(),+ traceId: z.string(),+ difyTraceId: z.string(),+ gateCommitId: z.string(),+ body: z.string().optional(),+ attributesJson: z.string().optional(),+ resourceAttributesJson: z.string().optional(),+})++export const zGetAppRunnerLogResponse = z.object({+ appRunnerLog: zAppRunnerLog,+ lastArchived: z.iso.datetime().optional(),+})++export const zPrecheckReleaseRequest = z.object({+ appInstanceId: z.string().optional(),+ dsl: z.string().optional(),+ sourceAppId: z.string().optional(),+})++export const zPromoteRequest = z.object({+ appInstanceId: z.string().optional(),+ releaseId: z.string(),+ environmentId: z.string().optional(),+ credentials: z.array(zCredentialSelectionInput).optional(),+ envVars: z.array(zEnvVarInput).optional(),+ idempotencyKey: z.string(),+})++/**+ * ReleaseContentMatch identifies an existing release whose DSL content is+ * identical to the checked content.+ */+export const zReleaseContentMatch = z.object({+ releaseId: z.string(),+ displayName: z.string(),+ createdAt: z.iso.datetime(),+})++export const zReleaseEnvironmentAction = z.object({+ environment: zEnvironment,+ kind: zReleaseEnvironmentActionKind,+ disabledReason: z.string().optional(),+ requiresRuntimeInputs: z.boolean(),+ currentReleaseId: z.string(),+})++/**+ * ReleaseEnvironmentDeployment is an environment where the release is the+ * active deployment, paired with that environment's runtime status so the+ * version history can show running vs failed vs deploying.+ */+export const zReleaseEnvironmentDeployment = z.object({+ environment: zEnvironment,+ status: zRuntimeInstanceStatus,+})++export const zReportRuntimeAssignmentStatusRequest = z.object({+ deploymentId: z.string().optional(),+ runtimeInstanceId: z.string().optional(),+ releaseId: z.string().optional(),+ status: zAckStatus.optional(),+ lastError: zError.optional(),+ runnerId: z.string().optional(),+ assignmentRevision: z.string().optional(),+})++export const zReportRuntimeAssignmentStatusResponse = z.object({+ accepted: z.boolean().optional(),+ stale: z.boolean().optional(),+})++/**+ * RequiredSlot is an input requirement extracted from a Release's+ * DSL.+ */+export const zRequiredSlot = z.object({+ type: zSlotType,+ providerId: z.string(),+ category: zPluginCategory,+ key: z.string(),+})++export const zRelease = z.object({+ id: z.string(),+ appInstanceId: z.string(),+ displayName: z.string(),+ description: z.string(),+ source: zReleaseSource,+ sourceAppId: z.string().optional(),+ gateCommitId: z.string(),+ requiredSlots: z.array(zRequiredSlot),+ createdBy: zActor,+ createdAt: z.iso.datetime(),+})++export const zCreateReleaseResponse = z.object({+ release: zRelease,+ appInstance: zAppInstance,+})++export const zDeployment = z.object({+ id: z.string(),+ appInstanceId: z.string(),+ status: zDeploymentStatus,+ action: zDeploymentAction,+ environment: zEnvironment,+ release: zRelease,+ error: zError.optional(),+ createdBy: zActor,+ createdAt: z.iso.datetime(),+ finalizedAt: z.iso.datetime().optional(),+})++export const zCancelDeploymentResponse = z.object({+ deployment: zDeployment,+})++export const zDeployResponse = z.object({+ appInstance: zAppInstance,+ release: zRelease,+ deployment: zDeployment,+})++/**+ * EnvironmentAppInstance is one app instance as seen from a single environment:+ * its current release, runtime status, and derived last error in THIS env.+ */+export const zEnvironmentAppInstance = z.object({+ appInstance: zAppInstance.optional(),+ currentRelease: zRelease.optional(),+ status: zRuntimeInstanceStatus.optional(),+ lastError: zError.optional(),+ workspaceId: z.string().optional(),+ workspaceName: z.string().optional(),+})++export const zEnvironmentDeployment = z.object({+ appInstanceId: z.string(),+ environment: zEnvironment,+ status: zRuntimeInstanceStatus,+ currentRelease: zRelease.optional(),+ desiredRelease: zRelease.optional(),+ currentDeployment: zEnvironmentDeploymentRecord.optional(),+ error: zError.optional(),+ updatedAt: z.iso.datetime(),+ releasesBehind: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+})++export const zAppInstanceSummary = z.object({+ appInstance: zAppInstance,+ environmentDeployments: z.array(zEnvironmentDeployment),+ latestRelease: zRelease.optional(),+ accessChannels: zAccessChannels,+ apiKeySummary: zApiKeySummary,+})++export const zComputeReleaseDeploymentViewResponse = z.object({+ releases: z.array(zRelease),+ environmentDeployments: z.array(zEnvironmentDeployment),+ environmentActions: z.array(zReleaseEnvironmentAction),+ options: zDeploymentOptions.optional(),+})++/**+ * EnvironmentDeploymentHistoryItem is one deployment row in an environment's+ * history, with a thin reference to the owning app instance.+ */+export const zEnvironmentDeploymentHistoryItem = z.object({+ deployment: zDeployment.optional(),+ appInstanceId: z.string().optional(),+ appInstanceName: z.string().optional(),+ workspaceId: z.string().optional(),+ workspaceName: z.string().optional(),+})++export const zGetAppInstanceOverviewResponse = z.object({+ appInstance: zAppInstance,+ environmentDeployments: z.array(zEnvironmentDeployment),+ recentReleases: z.array(zRelease),+ accessChannels: zAccessChannels,+ apiKeySummary: zApiKeySummary,+ totalReleaseCount: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+})++export const zGetReleaseResponse = z.object({+ release: zRelease,+})++export const zListEnvironmentDeploymentsResponse = z.object({+ environmentDeployments: z.array(zEnvironmentDeployment),+})++export const zPromoteResponse = z.object({+ deployment: zDeployment,+})++export const zReleaseSummary = z.object({+ release: zRelease,+ deployedEnvironments: z.array(zReleaseEnvironmentDeployment),+ environmentActions: z.array(zReleaseEnvironmentAction),+ activeEnvironmentCount: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+})++export const zResolveApiTokenRouteRequest = z.object({+ token: z.string().optional(),+})++export const zResolveApiTokenRouteResponse = z.object({+ environmentId: z.string().optional(),+ namespace: z.string().optional(),+ serviceName: z.string().optional(),+ servicePort: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ environmentStatus: zEnvironmentStatus.optional(),+ appId: z.string().optional(),+ tenantId: z.string().optional(),+ runtimeInstanceId: z.string().optional(),+ observedReleaseId: z.string().optional(),+ runtimeInstanceStatus: zRuntimeInstanceStatus.optional(),+ revoked: z.boolean().optional(),+ unavailableReason: z.string().optional(),+ targetKind: zRouteTargetKind.optional(),+ directUpstream: z.string().optional(),+})++export const zRollbackRequest = z.object({+ appInstanceId: z.string().optional(),+ environmentId: z.string().optional(),+ targetReleaseId: z.string(),+ idempotencyKey: z.string(),+})++export const zRollbackResponse = z.object({+ deployment: zDeployment,+})++export const zRollbackTarget = z.object({+ release: zRelease,+ resolvedDeploymentId: z.string(),+ deployedAt: z.iso.datetime(),+ isCurrent: z.boolean(),+})++export const zRunnerInfo = z.object({+ hostname: z.string().optional(),+})++export const zBootstrapRunnerRequest = z.object({+ runner: zRunnerInfo.optional(),+})++export const zRuntimeArtifact = z.object({+ dslYaml: z.string().optional(),+ bindingSnapshotVersion: z.string().optional(),+ bindingSnapshot: z.record(z.string(), z.unknown()).optional(),+})++export const zRuntimeArtifactRequest = z.object({+ runtimeInstanceId: z.string().optional(),+ releaseId: z.string().optional(),+ deploymentId: z.string().optional(),+ bindingSnapshotVersion: z.string().optional(),+})++export const zBatchResolveRuntimeArtifactsRequest = z.object({+ requests: z.array(zRuntimeArtifactRequest).optional(),+})++export const zRuntimeArtifactResult = z.object({+ runtimeInstanceId: z.string().optional(),+ releaseId: z.string().optional(),+ artifact: zRuntimeArtifact.optional(),+ error: zError.optional(),+ deploymentId: z.string().optional(),+})++export const zBatchResolveRuntimeArtifactsResponse = z.object({+ results: z.array(zRuntimeArtifactResult).optional(),+})++export const zTestConnectionRequest = z.object({+ environmentId: z.string().optional(),+})++export const zTestConnectionResponse = z.object({+ reachable: z.boolean().optional(),+ message: z.string().optional(),+})++export const zUndeployRequest = z.object({+ appInstanceId: z.string().optional(),+ environmentId: z.string().optional(),+ idempotencyKey: z.string(),+})++export const zUndeployResponse = z.object({+ deployment: zDeployment,+})++/**+ * UnsupportedDslNode identifies a workflow node whose type the app runner+ * cannot execute.+ */+export const zUnsupportedDslNode = z.object({+ id: z.string(),+ type: z.string(),+})++export const zPrecheckReleaseResponse = z.object({+ gateCommitId: z.string(),+ canCreate: z.boolean(),+ matchedRelease: zReleaseContentMatch.optional(),+ unsupportedNodes: z.array(zUnsupportedDslNode),+})++export const zUpdateAccessChannelsRequest = z.object({+ appInstanceId: z.string().optional(),+ webAppEnabled: z.boolean().optional(),+ developerApiEnabled: z.boolean().optional(),+})++export const zUpdateAccessChannelsResponse = z.object({+ accessChannels: zAccessChannels,+})++export const zUpdateAccessPolicyRequest = z.object({+ appInstanceId: z.string().optional(),+ environmentId: z.string().optional(),+ mode: zAccessMode,+ subjects: z.array(zAccessSubject).optional(),+})++export const zUpdateAccessPolicyResponse = z.object({+ policy: zAccessPolicy,+})++export const zUpdateAppInstanceRequest = z.object({+ appInstanceId: z.string().optional(),+ displayName: z.string(),+ description: z.string().optional(),+})++export const zUpdateAppInstanceResponse = z.object({+ appInstance: zAppInstance,+})++export const zUpdateEnvironmentRequest = z.object({+ environmentId: z.string().optional(),+ displayName: z.string(),+ description: z.string().optional(),+})++export const zUpdateEnvironmentResponse = z.object({+ environment: zEnvironment.optional(),+})++export const zUpdateReleaseRequest = z.object({+ releaseId: z.string().optional(),+ displayName: z.string(),+ description: z.string().optional(),+})++export const zUpdateReleaseResponse = z.object({+ release: zRelease,+})+/*** Account represents a basic user account*/@@ -52,7 +1021,7 @@ export const zBrandingInfo = z.object({export const zCheckPasswordStatusReply = z.object({requirePasswordChange: z.boolean().optional(),- changeReason: z.int().optional(),+ changeReason: zPasswordChangeReason.optional(),daysToExpire: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })@@ -178,6 +1147,14 @@ export const zEnterpriseSystemUserSettingReply = z.object({enableEmailPasswordLogin: z.boolean().optional(),})+export const zExternallyAccessibleApp = z.object({+ appId: z.string().optional(),+ tenantId: z.string().optional(),+ mode: z.string().optional(),+ name: z.string().optional(),+ updatedAt: z.string().optional(),+})+export const zGetBearerTokenResponse = z.object({maskedToken: z.string().optional(),})@@ -228,7 +1205,7 @@ export const zGroupAppItem = z.object({app_name: z.string().optional(),workspace_id: z.string().optional(),workspace_name: z.string().optional(),- app_status: z.int().optional(),+ app_status: zAppStatus.optional(),token_usage: z.string().optional(),rpm: z.string().optional(),concurrency: z.string().optional(),@@ -277,7 +1254,32 @@ export const zInnerIsUserAllowedToAccessWebAppRes = z.object({result: z.boolean().optional(),})-export const zInnerReleaseAdmissionRequest = z.object({+export const zInnerListExternallyAccessibleAppsReq = z.object({+ page: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ limit: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ mode: z.string().optional(),+ name: z.string().optional(),+})++export const zInnerListExternallyAccessibleAppsRes = z.object({+ data: z.array(zExternallyAccessibleApp).optional(),+ total: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ hasMore: z.boolean().optional(),+})++export const zInnerReleaseAdmissionRequest = z.object({admission: zInnerAdmission.optional(),})@@ -314,9 +1316,9 @@ export const zJoinWorkspaceReq = z.object({})export const zLimitConfig = z.object({- type: z.int().optional(),+ type: zLimitType.optional(),threshold: z.string().optional(),- action: z.int().optional(),+ action: zLimitAction.optional(),reached: z.boolean().optional(),})@@ -424,7 +1426,7 @@ export const zOidcReply = z.object({export const zOtelExporterEndpoint = z.object({endpoint: z.string().optional(),compression: z.string().optional(),- protocol: z.int().optional(),+ protocol: z.enum(['HTTP_PROTOBUF', 'HTTP_JSON', 'GRPC']).optional(),timeout: z.string().regex(/^-?(?:0|[1-9]\d{0,11})(?:\.\d{1,9})?s$/)@@ -439,7 +1441,7 @@ export const zOtelExporterEndpoint = z.object({})export const zEndpointReply = z.object({- mode: z.int().optional(),+ mode: zOtelEndpointMode.optional(),metricsEndpoint: zOtelExporterEndpoint.optional(),tracesEndpoint: zOtelExporterEndpoint.optional(),})@@ -449,7 +1451,7 @@ export const zOtelExporterStatusReply = z.object({bytesPushed: z.string().optional(),itemsInQueue: z.string().optional(),logs: z.string().optional(),- status: z.int().optional(),+ status: z.enum(['RUNNING', 'ERROR', 'STOPPED']).optional(),})export const zPasswordPolicyConfig = z.object({@@ -473,7 +1475,7 @@ export const zPasswordPolicyConfig = z.object({})export const zPasswordStrengthReply = z.object({- level: z.int().optional(),+ level: zPasswordStrengthLevel.optional(),})export const zPasswordStrengthReq = z.object({@@ -486,7 +1488,7 @@ export const zPluginInstallationPermissionInfo = z.object({})export const zPluginInstallationSettingsReply = z.object({- pluginInstallationScope: z.int().optional(),+ pluginInstallationScope: zPluginInstallationScope.optional(),restrictToMarketplaceOnly: z.boolean().optional(),})@@ -534,15 +1536,15 @@ export const zResourceGroupDetail = z.object({.min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),- rpm_action: z.int().optional(),+ rpm_action: zLimitAction.optional(),concurrency_limit: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),- concurrency_action: z.int().optional(),+ concurrency_action: zLimitAction.optional(),token_quota: z.string().optional(),- token_action: z.int().optional(),+ token_action: zLimitAction.optional(),created_at: z.string().optional(),updated_at: z.string().optional(),})@@ -565,8 +1567,8 @@ export const zResourceGroupItem = z.object({token_quota: z.string().optional(),token_usage: z.string().optional(),app_count: z.string().optional(),- rpm_status: z.int().optional(),- conc_status: z.int().optional(),+ rpm_status: zLimitStatus.optional(),+ conc_status: zLimitStatus.optional(),created_at: z.string().optional(),updated_at: z.string().optional(),})@@ -606,6 +1608,7 @@ export const zLimitFields = z.object({.max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),workspaces: zResourceQuota.optional(),+ appRunnerEnvCpus: zResourceQuota.optional(),})/**@@ -693,7 +1696,7 @@ export const zSearchAppItem = z.object({app_name: z.string().optional(),workspace_id: z.string().optional(),workspace_name: z.string().optional(),- app_status: z.int().optional(),+ app_status: zAppStatus.optional(),icon: z.string().optional(),icon_type: z.string().optional(),icon_background: z.string().optional(),@@ -760,11 +1763,24 @@ export const zGetWebAppWhitelistSubjectsRes = z.object({*/export const zSubject = z.object({subjectId: z.string().optional(),- subjectType: z.string().optional(),+ subjectType: zSubjectType.optional(),accountData: zSubjectAccountData.optional(),groupData: zSubjectGroupData.optional(),})+export const zEnvironmentAccessPolicy = z.object({+ environment: zEnvironment,+ policy: zAccessPolicy.optional(),+ resolvedSubjects: z.array(zSubject),+})++export const zGetAccessSettingsResponse = z.object({+ accessChannels: zAccessChannels,+ environmentPolicies: z.array(zEnvironmentAccessPolicy),+ webAppEndpoints: z.array(zAccessEndpoint).optional(),+ cliEndpoint: zAccessEndpoint.optional(),+})+export const zGetGroupSubjectsRes = z.object({subjects: z.array(zSubject).optional(),})@@ -798,6 +1814,72 @@ export const zToggleEndpointRequest = z.object({enabled: z.boolean().optional(),})+export const zToggleTraceProviderRequest = z.object({+ id: z.string().optional(),+ enabled: z.boolean().optional(),+})++/**+ * TraceProvider is one configured trace-export destination. Trace data+ * collected by the enterprise collector is fanned out to every enabled+ * destination. Credentials carries per-provider secret values (e.g. Langfuse+ * public/secret keys); Settings carries non-secret options (e.g. host,+ * project). Secret credential values are redacted on read and preserved on+ * write when the client echoes the redaction sentinel back (same round-trip+ * contract as endpoint headers / TLS keys).+ */+export const zTraceProvider = z.object({+ id: z.string().optional(),+ name: z.string().optional(),+ provider: z.string().optional(),+ endpoint: z.string().optional(),+ protocol: z.string().optional(),+ credentials: z.record(z.string(), z.string()).optional(),+ settings: z.record(z.string(), z.string()).optional(),+ enabled: z.boolean().optional(),+})++/**+ * TestTraceProviderRequest tests connectivity/auth for a destination config+ * before (or without) persisting it. When credentials carry the redaction+ * sentinel, the stored secret for the destination with the same id is used.+ */+export const zTestTraceProviderRequest = z.object({+ provider: zTraceProvider.optional(),+})++/**+ * TraceProviderField describes one credential or setting field of a provider in+ * the static catalog: the key the dashboard sends back, its display label,+ * whether it is required, and (for credentials) whether it is a secret that+ * gets redacted.+ */+export const zTraceProviderField = z.object({+ key: z.string().optional(),+ displayName: z.string().optional(),+ required: z.boolean().optional(),+ secret: z.boolean().optional(),+})++/**+ * TraceProviderDescriptor is one entry in the static provider catalog: the+ * field definitions and transport defaults for a provider type. The dashboard+ * uses it to render the add/edit form and to know which fields are secret.+ */+export const zTraceProviderDescriptor = z.object({+ provider: z.string().optional(),+ displayName: z.string().optional(),+ credentialFields: z.array(zTraceProviderField).optional(),+ settingFields: z.array(zTraceProviderField).optional(),+ defaultProtocol: z.string().optional(),+ supportedProtocols: z.array(z.string()).optional(),+})++export const zListTraceProvidersReply = z.object({+ providers: z.array(zTraceProvider).optional(),+ catalog: z.array(zTraceProviderDescriptor).optional(),+})+export const zUpdateAccessModeReq = z.object({appId: z.string().optional(),accessMode: z.string().optional(),@@ -894,7 +1976,7 @@ export const zUpdateOfflineLicenseReq = z.object({})export const zUpdatePluginInstallationSettingsRequest = z.object({- pluginInstallationScope: z.int().optional(),+ pluginInstallationScope: zPluginInstallationScope.optional(),restrictToMarketplaceOnly: z.boolean().optional(),})@@ -908,15 +1990,15 @@ export const zUpdateResourceGroupRequest = z.object({.min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),- rpm_action: z.int().optional(),+ rpm_action: zLimitAction.optional(),concurrency_limit: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),- concurrency_action: z.int().optional(),+ concurrency_action: zLimitAction.optional(),token_quota: z.string().optional(),- token_action: z.int().optional(),+ token_action: zLimitAction.optional(),})export const zUpdateUserReply = z.object({@@ -963,6 +2045,18 @@ export const zUpdateWorkspaceReq = z.object({status: z.string().optional(),})+export const zUpsertTraceProviderReply = z.object({+ provider: zTraceProvider.optional(),+})++/**+ * UpsertTraceProviderRequest creates a destination when id is empty (a new id+ * is allocated) or updates the destination with the given id otherwise.+ */+export const zUpsertTraceProviderRequest = z.object({+ provider: zTraceProvider.optional(),+})+export const zWebAppAuthInfo = z.object({allowSso: z.boolean().optional(),allowEmailCodeLogin: z.boolean().optional(),@@ -985,6 +2079,7 @@ export const zInfoConfigReply = z.object({Branding: zBrandingInfo.optional(),WebAppAuth: zWebAppAuthInfo.optional(),PluginInstallationPermission: zPluginInstallationPermissionInfo.optional(),+ EnableAppDeploy: z.boolean().optional(),})export const zWebOAuth2LoginReply = z.object({@@ -1058,6 +2153,28 @@ export const zUpdateWorkspacePermissionReq = z.object({permission: zWorkspacePermission.optional(),})+/**+ * CursorPagination: pagination by cursor token+ */+export const zCursorPagination = z.object({+ pageSize: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ nextCursor: z.string().optional(),+ prevCursor: z.string().optional(),+ hasNextPage: z.boolean().optional(),+ hasPrevPage: z.boolean().optional(),+ totalCount: z.string().optional(),+})++export const zListAppRunnerLogsResponse = z.object({+ appRunnerLogs: z.array(zAppRunnerLog),+ pagination: zCursorPagination,+ lastArchived: z.iso.datetime().optional(),+})+/*** Pagination : Just for pagination by page*/@@ -1084,6 +2201,61 @@ export const zPagination = z.object({.optional(),})+export const zDashboardListAppInstancesResponse = z.object({+ appInstances: z.array(zAppInstance),+ pagination: zPagination,+})++export const zDashboardListEnvironmentDeploymentsResponse = z.object({+ deployments: z.array(zEnvironmentDeploymentHistoryItem).optional(),+ pagination: zPagination.optional(),+})++export const zListAppInstanceSummariesResponse = z.object({+ appInstanceSummaries: z.array(zAppInstanceSummary),+ pagination: zPagination,+})++export const zListAppInstancesResponse = z.object({+ appInstances: z.array(zAppInstance),+ pagination: zPagination,+})++export const zListDeploymentsResponse = z.object({+ deployments: z.array(zDeployment),+ pagination: zPagination,+})++export const zListEnvironmentAppInstancesResponse = z.object({+ appInstances: z.array(zEnvironmentAppInstance).optional(),+ pagination: zPagination.optional(),+})++export const zListEnvironmentsResponse = z.object({+ environments: z.array(zEnvironment),+ pagination: zPagination,+})++export const zListReleaseSummariesResponse = z.object({+ releaseSummaries: z.array(zReleaseSummary),+ pagination: zPagination,+})++export const zListReleasesResponse = z.object({+ releases: z.array(zRelease),+ pagination: zPagination,+})++export const zListRollbackTargetsResponse = z.object({+ rollbackTargets: z.array(zRollbackTarget),+ pagination: zPagination,+})++export const zListAccessSubjectsReply = z.object({+ subjects: z.array(zSubject).optional(),+ pagination: zPagination.optional(),+})+export const zListMembersReply = z.object({data: z.array(zAccountDetail).optional(),pagination: zPagination.optional(),@@ -1104,6 +2276,469 @@ export const zListWorkspacesReply = z.object({pagination: zPagination.optional(),})+export const zAccessSubjectServiceListAccessSubjectsQuery = z.object({+ keyword: z.string().optional(),+ groupId: z.string().optional(),+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+})++/**+ * OK+ */+export const zAccessSubjectServiceListAccessSubjectsResponse = zListAccessSubjectsReply++export const zAppInstanceServiceListAppInstanceSummariesQuery = z.object({+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ displayName: z.string().optional(),+ environmentId: z.string().optional(),+})++/**+ * OK+ */+export const zAppInstanceServiceListAppInstanceSummariesResponse = zListAppInstanceSummariesResponse++export const zAppInstanceServiceListAppInstancesQuery = z.object({+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ displayName: z.string().optional(),+ environmentId: z.string().optional(),+})++/**+ * OK+ */+export const zAppInstanceServiceListAppInstancesResponse = zListAppInstancesResponse++export const zAppInstanceServiceCreateAppInstanceBody = zCreateAppInstanceRequest++/**+ * OK+ */+export const zAppInstanceServiceCreateAppInstanceResponse = zCreateAppInstanceResponse++export const zAppInstanceServiceDeleteAppInstancePath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAppInstanceServiceDeleteAppInstanceResponse = zDeleteAppInstanceResponse++export const zAppInstanceServiceGetAppInstancePath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAppInstanceServiceGetAppInstanceResponse = zGetAppInstanceResponse++export const zAppInstanceServiceUpdateAppInstanceBody = zUpdateAppInstanceRequest++export const zAppInstanceServiceUpdateAppInstancePath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAppInstanceServiceUpdateAppInstanceResponse = zUpdateAppInstanceResponse++export const zAccessServiceGetAccessChannelsPath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceGetAccessChannelsResponse = zGetAccessChannelsResponse++export const zAccessServiceUpdateAccessChannelsBody = zUpdateAccessChannelsRequest++export const zAccessServiceUpdateAccessChannelsPath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceUpdateAccessChannelsResponse = zUpdateAccessChannelsResponse++export const zAccessServiceGetAccessSettingsPath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceGetAccessSettingsResponse = zGetAccessSettingsResponse++export const zDeploymentServiceListDeploymentsPath = z.object({+ appInstanceId: z.string(),+})++export const zDeploymentServiceListDeploymentsQuery = z.object({+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ environmentId: z.string().optional(),+})++/**+ * OK+ */+export const zDeploymentServiceListDeploymentsResponse = zListDeploymentsResponse++export const zAccessServiceGetDeveloperApiSettingsPath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceGetDeveloperApiSettingsResponse = zGetDeveloperApiSettingsResponse++export const zDeploymentServiceListEnvironmentDeploymentsPath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zDeploymentServiceListEnvironmentDeploymentsResponse+ = zListEnvironmentDeploymentsResponse++export const zAccessServiceGetAccessPolicyPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceGetAccessPolicyResponse = zGetAccessPolicyResponse++export const zAccessServiceUpdateAccessPolicyBody = zUpdateAccessPolicyRequest++export const zAccessServiceUpdateAccessPolicyPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceUpdateAccessPolicyResponse = zUpdateAccessPolicyResponse++export const zAccessServiceListApiKeysPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceListApiKeysResponse = zListApiKeysResponse++export const zAccessServiceCreateApiKeyBody = zCreateApiKeyRequest++export const zAccessServiceCreateApiKeyPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceCreateApiKeyResponse = zCreateApiKeyResponse++export const zAccessServiceDeleteApiKeyPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+ apiKeyId: z.string(),+})++/**+ * OK+ */+export const zAccessServiceDeleteApiKeyResponse = zDeleteApiKeyResponse++export const zDeploymentServiceListRollbackTargetsPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++export const zDeploymentServiceListRollbackTargetsQuery = z.object({+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+})++/**+ * OK+ */+export const zDeploymentServiceListRollbackTargetsResponse = zListRollbackTargetsResponse++export const zDeploymentServiceCancelDeploymentBody = zCancelDeploymentRequest++export const zDeploymentServiceCancelDeploymentPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zDeploymentServiceCancelDeploymentResponse = zCancelDeploymentResponse++export const zDeploymentServicePromoteBody = zPromoteRequest++export const zDeploymentServicePromotePath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zDeploymentServicePromoteResponse = zPromoteResponse++export const zDeploymentServiceRollbackBody = zRollbackRequest++export const zDeploymentServiceRollbackPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zDeploymentServiceRollbackResponse = zRollbackResponse++export const zDeploymentServiceUndeployBody = zUndeployRequest++export const zDeploymentServiceUndeployPath = z.object({+ appInstanceId: z.string(),+ environmentId: z.string(),+})++/**+ * OK+ */+export const zDeploymentServiceUndeployResponse = zUndeployResponse++export const zReleaseServiceListReleaseSummariesPath = z.object({+ appInstanceId: z.string(),+})++export const zReleaseServiceListReleaseSummariesQuery = z.object({+ releaseId: z.string().optional(),+ displayName: z.string().optional(),+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ environmentId: z.string().optional(),+})++/**+ * OK+ */+export const zReleaseServiceListReleaseSummariesResponse = zListReleaseSummariesResponse++export const zReleaseServiceListReleasesPath = z.object({+ appInstanceId: z.string(),+})++export const zReleaseServiceListReleasesQuery = z.object({+ releaseId: z.string().optional(),+ displayName: z.string().optional(),+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ environmentId: z.string().optional(),+})++/**+ * OK+ */+export const zReleaseServiceListReleasesResponse = zListReleasesResponse++export const zReleaseServiceComputeReleaseDeploymentViewPath = z.object({+ appInstanceId: z.string(),+})++export const zReleaseServiceComputeReleaseDeploymentViewQuery = z.object({+ releaseId: z.string().optional(),+ environmentId: z.string().optional(),+})++/**+ * OK+ */+export const zReleaseServiceComputeReleaseDeploymentViewResponse+ = zComputeReleaseDeploymentViewResponse++export const zAppInstanceServiceGetAppInstanceOverviewPath = z.object({+ appInstanceId: z.string(),+})++/**+ * OK+ */+export const zAppInstanceServiceGetAppInstanceOverviewResponse = zGetAppInstanceOverviewResponse++export const zDeploymentServiceDeployBody = zDeployRequest++/**+ * OK+ */+export const zDeploymentServiceDeployResponse = zDeployResponse++export const zEnvironmentServiceListEnvironmentsQuery = z.object({+ environmentId: z.string().optional(),+ displayName: z.string().optional(),+ pageNumber: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+ resultsPerPage: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),+})++/**+ * OK+ */+export const zEnvironmentServiceListEnvironmentsResponse = zListEnvironmentsResponse++export const zReleaseServiceCreateReleaseBody = zCreateReleaseRequest++/**+ * OK+ */+export const zReleaseServiceCreateReleaseResponse = zCreateReleaseResponse++export const zReleaseServiceDeleteReleasePath = z.object({+ releaseId: z.string(),+})++/**+ * OK+ */+export const zReleaseServiceDeleteReleaseResponse = zDeleteReleaseResponse++export const zReleaseServiceGetReleasePath = z.object({+ releaseId: z.string(),+})++/**+ * OK+ */+export const zReleaseServiceGetReleaseResponse = zGetReleaseResponse++export const zReleaseServiceUpdateReleaseBody = zUpdateReleaseRequest++export const zReleaseServiceUpdateReleasePath = z.object({+ releaseId: z.string(),+})++/**+ * OK+ */+export const zReleaseServiceUpdateReleaseResponse = zUpdateReleaseResponse++export const zReleaseServiceExportReleaseDslPath = z.object({+ releaseId: z.string(),+})++/**+ * OK+ */+export const zReleaseServiceExportReleaseDslResponse = zExportReleaseDslResponse++export const zReleaseServiceListReleaseCredentialCandidatesPath = z.object({+ releaseId: z.string(),+})++/**+ * OK+ */+export const zReleaseServiceListReleaseCredentialCandidatesResponse+ = zListReleaseCredentialCandidatesResponse++export const zReleaseServiceComputeDeploymentOptionsBody = zComputeDeploymentOptionsRequest++/**+ * OK+ */+export const zReleaseServiceComputeDeploymentOptionsResponse = zComputeDeploymentOptionsResponse++export const zReleaseServicePrecheckReleaseBody = zPrecheckReleaseRequest++/**+ * OK+ */+export const zReleaseServicePrecheckReleaseResponse = zPrecheckReleaseResponse+/*** OK*/diff --git a/packages/contracts/openapi-ts.enterprise.config.ts b/packages/contracts/openapi-ts.enterprise.config.tsindex 3c9bc903ab4..aae8dcb215b 100644--- a/packages/contracts/openapi-ts.enterprise.config.ts+++ b/packages/contracts/openapi-ts.enterprise.config.ts@@ -7,9 +7,36 @@ import yaml from 'js-yaml'type JsonObject = Record<string, unknown>type OpenApiDocument = JsonObject & {+ components?: OpenApiComponentspaths?: Record<string, unknown>}+type OpenApiComponents = JsonObject & {+ schemas?: Record<string, OpenApiSchema>+}++type OpenApiMediaType = JsonObject & {+ schema?: unknown+}++type OpenApiOperation = JsonObject & {+ operationId?: string+ responses?: Record<string, OpenApiResponse>+}++type OpenApiPathItem = Record<string, unknown>++type OpenApiResponse = JsonObject & {+ content?: Record<string, OpenApiMediaType>+}++type OpenApiSchema = JsonObject & {+ enum?: unknown[]+ format?: string+ properties?: Record<string, OpenApiSchema>+ type?: string | string[]+}+type ContractOperation = {id: stringoperationId?: string@@ -21,9 +48,30 @@ const enterpriseServerDir = process.env.DIFY_ENTERPRISE_SERVER? path.resolve(process.env.DIFY_ENTERPRISE_SERVER): path.resolve(currentDir, '../../../dify-enterprise/server')const enterpriseOpenApiPath = path.join(enterpriseServerDir, 'pkg/apis/enterprise/openapi.yaml')+const operationMethods = new Set(['delete', 'get', 'patch', 'post', 'put'])const isConsoleApiPath = (routePath: string) => routePath.startsWith('/console/api/')+const isObject = (value: unknown): value is JsonObject => {+ return !!value && typeof value === 'object' && !Array.isArray(value)+}++const isOpenApiSchema = (value: unknown): value is OpenApiSchema => {+ return isObject(value)+}++const asOpenApiOperation = (value: unknown): OpenApiOperation | undefined => {+ return isObject(value) ? value as OpenApiOperation : undefined+}++const asOpenApiResponse = (value: unknown): OpenApiResponse | undefined => {+ return isObject(value) ? value as OpenApiResponse : undefined+}++const asOpenApiMediaType = (value: unknown): OpenApiMediaType | undefined => {+ return isObject(value) ? value as OpenApiMediaType : undefined+}+const stripConsoleApiPrefix = (routePath: string) => {if (isConsoleApiPath(routePath))return routePath.replace('/console/api', '')@@ -34,9 +82,18 @@ const stripConsoleApiPrefix = (routePath: string) => {const stripSchemaNamePrefix = (schemaName: string) => {return schemaName.replace(/^dify\.enterprise\.api\.enterprise\./, '')+ .replace(/^dify\.enterprise\.api\.appdeploy\.v1\./, '')+ .replace(/^dify\.enterprise\.api\.appdeploy\./, '').replace(/^pagination\./, '')}+const contractTagSegment = (tag?: string) => {+ if (tag === 'EnterpriseAppDeployConsole')+ return 'AppDeploy'++ return tag || 'default'+}+const contractNameSegments = (operation: ContractOperation) => {const operationId = operation.operationId || operation.idconst tag = operation.tags?.[0]@@ -48,7 +105,165 @@ const contractNameSegments = (operation: ContractOperation) => {}const contractPathSegments = (operation: ContractOperation) => {- return [operation.tags?.[0] || 'default', ...contractNameSegments(operation)]+ return [contractTagSegment(operation.tags?.[0]), ...contractNameSegments(operation)]+}++const hasSchemaLessResponseContent = (operation: OpenApiOperation) => {+ if (!isObject(operation.responses))+ return false++ return Object.values(operation.responses).some((response) => {+ const openApiResponse = asOpenApiResponse(response)+ if (!openApiResponse || !isObject(openApiResponse.content))+ return false++ return Object.values(openApiResponse.content).some((mediaType) => {+ const openApiMediaType = asOpenApiMediaType(mediaType)+ return !!openApiMediaType && !('schema' in openApiMediaType)+ })+ })+}++// protoc-gen-openapi emits google.api.HttpBody responses as `*/*: {}`. Skip these+// raw download operations until the source OpenAPI exposes an explicit schema.+const stripSchemaLessResponseOperations = (pathItem: OpenApiPathItem) => {+ return Object.fromEntries(+ Object.entries(pathItem).filter(([method, operation]) => {+ if (!operationMethods.has(method.toLowerCase()))+ return true++ const openApiOperation = asOpenApiOperation(operation)+ return !openApiOperation || !hasSchemaLessResponseContent(openApiOperation)+ }),+ )+}++const toWords = (value: string) => {+ return value+ .replace(/[{}]/g, '')+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .split(/[^a-z0-9]+/i)+ .filter(Boolean)+}++const toPascalCase = (words: string[]) => {+ return words.map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('')+}++const commonWordPrefix = (values: string[]) => {+ const wordLists = values.map(value => value.split('_'))+ const firstWords = wordLists[0] ?? []+ const prefix: string[] = []++ for (const [index, word] of firstWords.entries()) {+ if (!wordLists.every(words => words[index] === word))+ break++ prefix.push(word)+ }++ return prefix+}++const enumSchemaNameFromValues = (values: unknown[]) => {+ if (values.length === 0 || !values.every(value => typeof value === 'string'))+ return undefined++ const prefix = commonWordPrefix(values)+ if (prefix.length < 2)+ return undefined++ return toPascalCase(prefix.map(word => word.toLowerCase()))+}++const findSchemaEntry = (+ schemas: Record<string, OpenApiSchema>,+ schemaName: string,+): [string, OpenApiSchema] | undefined => {+ return Object.entries(schemas)+ .find(([name]) => stripSchemaNamePrefix(name) === schemaName)+}++const enumValuesKey = (values: unknown[]) => JSON.stringify(values)++const reusableEnumSchema = (propertySchema: OpenApiSchema): OpenApiSchema => ({+ ...(propertySchema.format ? { format: propertySchema.format } : {}),+ enum: propertySchema.enum,+ type: propertySchema.type ?? 'string',+})++const enumSchemaKey = (+ schemas: Record<string, OpenApiSchema>,+ preferredName: string,+ valuesKey: string,+ valuesToSchemaKey: Map<string, string>,+ schemaName: string,+ propertyName: string,+) => {+ const existingKey = valuesToSchemaKey.get(valuesKey)+ if (existingKey)+ return existingKey++ const existingEnumEntry = findSchemaEntry(schemas, preferredName)+ if (!existingEnumEntry)+ return preferredName++ const existingEnumValues = existingEnumEntry[1].enum+ if (Array.isArray(existingEnumValues) && enumValuesKey(existingEnumValues) === valuesKey)+ return existingEnumEntry[0]++ return `${stripSchemaNamePrefix(schemaName)}${toPascalCase(toWords(propertyName))}`+}++const promoteInlineEnumSchema = (+ schemas: Record<string, OpenApiSchema>,+ schemaName: string,+ properties: Record<string, OpenApiSchema>,+ propertyName: string,+ propertySchema: OpenApiSchema,+ valuesToSchemaKey: Map<string, string>,+) => {+ if (!Array.isArray(propertySchema.enum))+ return++ const preferredName = enumSchemaNameFromValues(propertySchema.enum)+ if (!preferredName)+ return++ const valuesKey = enumValuesKey(propertySchema.enum)+ const key = enumSchemaKey(schemas, preferredName, valuesKey, valuesToSchemaKey, schemaName, propertyName)++ if (!schemas[key])+ schemas[key] = reusableEnumSchema(propertySchema)++ valuesToSchemaKey.set(valuesKey, key)+ properties[propertyName] = {+ $ref: `#/components/schemas/${key}`,+ }+}++// gnostic's protoc-gen-openapi inlines proto enum schemas into every field.+// Promote prefixable inline enums to reusable schemas so Hey API can emit+// runtime enum objects from the generated contract.+const promoteReusableEnumSchemasForHeyApi = (document: OpenApiDocument) => {+ const schemas = document.components?.schemas+ if (!schemas)+ return++ const valuesToSchemaKey = new Map<string, string>()++ Object.entries(schemas).forEach(([schemaName, schema]) => {+ const properties = schema.properties+ if (!properties)+ return++ Object.entries(properties).forEach(([propertyName, propertySchema]) => {+ if (!isOpenApiSchema(propertySchema))+ return++ promoteInlineEnumSchema(schemas, schemaName, properties, propertyName, propertySchema, valuesToSchemaKey)+ })+ })}const normalizeEnterpriseOpenApi = () => {@@ -63,9 +278,17 @@ const normalizeEnterpriseOpenApi = () => {document.paths = Object.fromEntries(Object.entries(paths).filter(([routePath]) => isConsoleApiPath(routePath))- .map(([routePath, pathItem]) => [stripConsoleApiPrefix(routePath), pathItem]),+ .map(([routePath, pathItem]) => {+ if (!isObject(pathItem))+ return [stripConsoleApiPrefix(routePath), pathItem]++ return [stripConsoleApiPrefix(routePath), stripSchemaLessResponseOperations(pathItem)]+ })+ .filter(([, pathItem]) => !isObject(pathItem) || Object.keys(pathItem).length > 0),)+ promoteReusableEnumSchemasForHeyApi(document)+return document}@@ -97,6 +320,9 @@ export default defineConfig({{name: '@hey-api/typescript',comments: false,+ enums: {+ mode: 'javascript',+ },},'zod',{diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d189883bd0a..3932cb6d87a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -168,6 +168,9 @@ catalogs:'@tanstack/eslint-plugin-query':specifier: 5.101.0version: 5.101.0+ '@tanstack/query-core':+ specifier: 5.101.0+ version: 5.101.0'@tanstack/react-form':specifier: 1.33.0version: 1.33.0@@ -393,6 +396,12 @@ catalogs:jotai:specifier: 2.20.1version: 2.20.1+ jotai-scope:+ specifier: 0.11.0+ version: 0.11.0+ jotai-tanstack-query:+ specifier: 0.11.0+ version: 0.11.0js-audio-recorder:specifier: 1.0.7version: 1.0.7@@ -1096,6 +1105,9 @@ importers:'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.20([email protected])+ '@tanstack/query-core':+ specifier: 'catalog:'+ version: 5.101.0'@tanstack/react-form':specifier: 'catalog:'@@ -1189,6 +1201,12 @@ importers:jotai:specifier: 'catalog:'version: 2.20.1(@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected])+ jotai-scope:+ specifier: 'catalog:'+ version: 0.11.0([email protected](@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected]))([email protected])+ jotai-tanstack-query:+ specifier: 'catalog:'+ version: 0.11.0(@tanstack/[email protected])(@tanstack/[email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected]))([email protected])js-audio-recorder:specifier: 'catalog:'version: 1.0.7@@ -7198,6 +7216,26 @@ packages:resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}hasBin: true+ resolution: {integrity: sha512-ofiW0Z0i3lTw509Gx0+T6fqsDPMDxMn+AHmNs9iF9OA8CmK1/0xRprPxuZ89UZdBzt6jcrTYdunNZSF2255zJQ==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ jotai: '>=2.20.0'+ react: '>=16.0.0'++ resolution: {integrity: sha512-Ys0u0IuuS6/okUJOulFTdCVfVaeKbm1+lKVSN9zHhIxtrAXl9FM4yu7fNvxM6fSz/NCE9tZOKR0MQ3hvplaH8A==}+ peerDependencies:+ '@tanstack/query-core': '*'+ '@tanstack/react-query': '*'+ jotai: '>=2.0.0'+ react: ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ '@tanstack/react-query':+ optional: true+ react:+ optional: true+resolution: {integrity: sha512-dnuKfU/GLi8B28RRMjQ3AfoN7kfzP8o41+AX2FmITZqEMY8PHnjABq+VkEooomLwYaGjda+pgy0yFSjaHX/ZPg==}engines: {node: '>=12.20.0'}@@ -16182,6 +16220,19 @@ snapshots:+ [email protected]([email protected](@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected]))([email protected]):+ dependencies:+ jotai: 2.20.1(@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected])+ react: 19.2.7++ [email protected](@tanstack/[email protected])(@tanstack/[email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected]))([email protected]):+ dependencies:+ '@tanstack/query-core': 5.101.0+ jotai: 2.20.1(@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected])+ optionalDependencies:+ '@tanstack/react-query': 5.101.0([email protected])+ react: 19.2.7+[email protected](@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected]):optionalDependencies:'@babel/core': 7.29.7@@ -19321,6 +19372,7 @@ time:'@tailwindcss/[email protected]': '2026-06-08T10:34:41.124Z''@tailwindcss/[email protected]': '2026-06-12T17:59:45.667Z''@tanstack/[email protected]': '2026-06-02T19:24:31.866Z'+ '@tanstack/[email protected]': '2026-06-02T19:24:32.202Z''@tanstack/[email protected]': '2026-05-28T17:05:42.660Z''@tanstack/[email protected]': '2026-04-25T12:28:06.989Z''@tanstack/[email protected]': '2026-06-02T19:24:39.383Z'@@ -19397,6 +19449,8 @@ time:[email protected]: '2026-06-03T14:14:17.016Z'[email protected]: '2026-04-20T06:18:25.132Z'[email protected]: '2026-05-08T15:09:33.021Z'+ [email protected]: '2026-05-13T18:43:15.331Z'+ [email protected]: '2025-08-01T02:55:49.826Z'[email protected]: '2026-06-11T06:30:45.782Z'[email protected]: '2021-01-09T10:20:49.923Z'[email protected]: '2026-05-29T10:51:39.065Z'diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 313f2102ebf..8aaafed7267 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -106,6 +106,7 @@ catalog:'@tailwindcss/typography': 0.5.20'@tailwindcss/vite': 4.3.1'@tanstack/eslint-plugin-query': 5.101.0+ '@tanstack/query-core': 5.101.0'@tanstack/react-form': 1.33.0'@tanstack/react-hotkeys': 0.10.0'@tanstack/react-query': 5.101.0@@ -181,6 +182,8 @@ catalog:iconify-import-svg: 0.2.0immer: 11.1.8jotai: 2.20.1+ jotai-scope: 0.11.0+ jotai-tanstack-query: 0.11.0js-audio-recorder: 1.0.7js-cookie: 3.0.8js-yaml: 4.2.0diff --git a/web/__tests__/app/app-access-control-flow.test.tsx b/web/__tests__/app/app-access-control-flow.test.tsxindex e1284bfc5b5..415b48c5cad 100644--- a/web/__tests__/app/app-access-control-flow.test.tsx+++ b/web/__tests__/app/app-access-control-flow.test.tsx@@ -1,7 +1,7 @@import { fireEvent, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'-import AppPublisher from '@/app/components/app/app-publisher'+import { AppPublisher } from '@/app/components/app/app-publisher'import { AccessMode } from '@/models/access-control'import { AppModeEnum } from '@/types/app'@@ -89,7 +89,7 @@ vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', ()}))vi.mock('@/app/components/app/app-access-control', () => ({- default: ({+ AccessControl: ({onConfirm,onClose,}: {diff --git a/web/__tests__/app/app-publisher-flow.test.tsx b/web/__tests__/app/app-publisher-flow.test.tsxindex d598051f72c..593211ce9dd 100644--- a/web/__tests__/app/app-publisher-flow.test.tsx+++ b/web/__tests__/app/app-publisher-flow.test.tsx@@ -1,12 +1,11 @@import { fireEvent, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'-import AppPublisher from '@/app/components/app/app-publisher'+import { AppPublisher } from '@/app/components/app/app-publisher'import { AccessMode } from '@/models/access-control'import { AppModeEnum } from '@/types/app'const mockTrackEvent = vi.fn()-const mockRefetch = vi.fn()const mockFetchInstalledAppList = vi.fn()const mockFetchAppDetailDirect = vi.fn()const mockToastError = vi.fn()@@ -64,7 +63,6 @@ vi.mock('@/service/access-control', () => ({useGetUserCanAccessApp: () => ({data: { result: true },isLoading: false,- refetch: mockRefetch,}),useAppWhiteListSubjects: () => ({data: { groups: [], members: [] },@@ -115,7 +113,7 @@ vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', ()}))vi.mock('@/app/components/app/app-access-control', () => ({- default: () => <div data-testid="app-access-control" />,+ AccessControl: () => <div data-testid="app-access-control" />,}))vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))@@ -182,8 +180,6 @@ describe('App Publisher Flow', () => {app_name: 'Demo App',}))})-- expect(mockRefetch).toHaveBeenCalled()})it('opens embedded modal and resolves the installed explore target', async () => {diff --git a/web/__tests__/apps/app-card-operations-flow.test.tsx b/web/__tests__/apps/app-card-operations-flow.test.tsxindex 5702755a5c8..67bd892b4ec 100644--- a/web/__tests__/apps/app-card-operations-flow.test.tsx+++ b/web/__tests__/apps/app-card-operations-flow.test.tsx@@ -13,7 +13,7 @@ import type { App } from '@/types/app'import { fireEvent, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'-import AppCard from '@/app/components/apps/app-card'+import { AppCard } from '@/app/components/apps/app-card'import { AccessMode } from '@/models/access-control'import { exportAppConfig, updateAppInfo } from '@/service/apps'import { AppModeEnum } from '@/types/app'@@ -64,10 +64,10 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {})vi.mock('@/next/dynamic', () => ({- default: (loader: () => Promise<{ default: React.ComponentType }>) => {+ default: (loader: () => Promise<React.ComponentType | { default: React.ComponentType }>) => {let Component: React.ComponentType<Record<string, unknown>> | null = nullloader().then((mod) => {- Component = mod.default as React.ComponentType<Record<string, unknown>>+ Component = (typeof mod === 'function' ? mod : mod.default) as React.ComponentType<Record<string, unknown>>}).catch(() => {})const Wrapper = (props: Record<string, unknown>) => {if (Component)@@ -201,7 +201,7 @@ vi.mock('@/app/components/workflow/dsl-export-confirm-modal', () => ({}))vi.mock('@/app/components/app/app-access-control', () => ({- default: ({ onConfirm, onClose }: Record<string, unknown>) => (+ AccessControl: ({ onConfirm, onClose }: Record<string, unknown>) => (<div data-testid="access-control-modal"><button data-testid="confirm-access" onClick={onConfirm as () => void}>Confirm</button><button data-testid="cancel-access" onClick={onClose as () => void}>Cancel</button>diff --git a/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsx b/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsxindex 67b50f94096..f26723d0199 100644--- a/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsx+++ b/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsx@@ -1,13 +1,16 @@+import type { ReactNode } from 'react'import { useQuery } from '@tanstack/react-query'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import RoleRouteGuard from '../role-route-guard'+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'+import { RoleRouteGuard } from '../role-route-guard'const mocks = vi.hoisted(() => ({redirect: vi.fn((url: string) => {throw new Error(`NEXT_REDIRECT:${url}`)}),currentWorkspaceQueryOptions: vi.fn(() => ({ queryKey: ['console', 'workspaces', 'current', 'post'] })),+ systemFeaturesQueryKey: vi.fn(() => ['console', 'systemFeatures', 'get']),}))let mockPathname = '/apps'@@ -27,6 +30,11 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: mocks.systemFeaturesQueryKey,+ },+ },workspaces: {current: {post: {@@ -39,6 +47,19 @@ vi.mock('@/service/client', () => ({const mockUseQuery = vi.mocked(useQuery)+function renderGuard(children: ReactNode) {+ return renderWithSystemFeatures(+ <RoleRouteGuard>+ {children}+ </RoleRouteGuard>,+ {+ systemFeatures: {+ enable_app_deploy: true,+ },+ },+ )+}+const setCurrentWorkspaceQuery = (overrides: { role?: string, isPending?: boolean } = {}) => {mockUseQuery.mockReturnValue({data: overrides.role,@@ -56,11 +77,7 @@ describe('RoleRouteGuard', () => {it('should render loading while workspace is loading', () => {setCurrentWorkspaceQuery({ isPending: true })- render((- <RoleRouteGuard>- <div>content</div>- </RoleRouteGuard>- ))+ renderGuard(<div>content</div>)expect(screen.getByRole('status')).toBeInTheDocument()expect(screen.queryByText('content')).not.toBeInTheDocument()@@ -73,11 +90,16 @@ describe('RoleRouteGuard', () => {it('should redirect dataset operator on guarded routes', () => {setCurrentWorkspaceQuery({ role: 'dataset_operator' })- expect(() => render((- <RoleRouteGuard>- <div>content</div>- </RoleRouteGuard>- ))).toThrow('NEXT_REDIRECT:/datasets')+ expect(() => renderGuard(<div>content</div>)).toThrow('NEXT_REDIRECT:/datasets')++ expect(mocks.redirect).toHaveBeenCalledWith('/datasets')+ })++ it('should redirect dataset operator on deployments routes', () => {+ mockPathname = '/deployments/create'+ setCurrentWorkspaceQuery({ role: 'dataset_operator' })++ expect(() => renderGuard(<div>content</div>)).toThrow('NEXT_REDIRECT:/datasets')expect(mocks.redirect).toHaveBeenCalledWith('/datasets')})@@ -86,11 +108,7 @@ describe('RoleRouteGuard', () => {mockPathname = '/plugins'setCurrentWorkspaceQuery({ role: 'dataset_operator' })- render((- <RoleRouteGuard>- <div>content</div>- </RoleRouteGuard>- ))+ renderGuard(<div>content</div>)expect(screen.getByText('content')).toBeInTheDocument()expect(mocks.redirect).not.toHaveBeenCalled()@@ -100,11 +118,7 @@ describe('RoleRouteGuard', () => {mockPathname = '/plugins'setCurrentWorkspaceQuery({ isPending: true })- render((- <RoleRouteGuard>- <div>content</div>- </RoleRouteGuard>- ))+ renderGuard(<div>content</div>)expect(screen.getByText('content')).toBeInTheDocument()expect(screen.queryByRole('status')).not.toBeInTheDocument()diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/access/page.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/access/page.tsxnew file mode 100644index 00000000000..5fa2ff42250--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/access/page.tsx@@ -0,0 +1,8 @@+import { AccessTab } from '@/features/deployments/detail/access-tab'++export default async function InstanceDetailAccessPage({ params }: {+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params+ return <AccessTab appInstanceId={appInstanceId} />+}diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/api-tokens/page.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/api-tokens/page.tsxnew file mode 100644index 00000000000..6fb643008ad--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/api-tokens/page.tsx@@ -0,0 +1,8 @@+import { DeveloperApiTab } from '@/features/deployments/detail/developer-api-tab'++export default async function InstanceDetailApiTokensPage({ params }: {+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params+ return <DeveloperApiTab appInstanceId={appInstanceId} />+}diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/instances/page.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/instances/page.tsxnew file mode 100644index 00000000000..d51bcfd5898--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/instances/page.tsx@@ -0,0 +1,8 @@+import { DeployTab } from '@/features/deployments/detail/deploy-tab'++export default async function InstanceDetailInstancesPage({ params }: {+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params+ return <DeployTab appInstanceId={appInstanceId} />+}diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/layout.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/layout.tsxnew file mode 100644index 00000000000..4e39b066201--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/layout.tsx@@ -0,0 +1,15 @@+import type { ReactNode } from 'react'+import { InstanceDetail } from '@/features/deployments/detail'++export default async function InstanceDetailLayout({ children, params }: {+ children: ReactNode+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params++ return (+ <InstanceDetail appInstanceId={appInstanceId}>+ {children}+ </InstanceDetail>+ )+}diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/overview/page.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/overview/page.tsxnew file mode 100644index 00000000000..7362d075a29--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/overview/page.tsx@@ -0,0 +1,8 @@+import { OverviewTab } from '@/features/deployments/detail/overview-tab'++export default async function InstanceDetailOverviewPage({ params }: {+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params+ return <OverviewTab appInstanceId={appInstanceId} />+}diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/page.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/page.tsxnew file mode 100644index 00000000000..b0ae57a3a87--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/page.tsx@@ -0,0 +1,8 @@+import { redirect } from '@/next/navigation'++export default async function InstanceDetailPage({ params }: {+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params+ redirect(`/deployments/${appInstanceId}/overview`)+}diff --git a/web/app/(commonLayout)/deployments/[appInstanceId]/releases/page.tsx b/web/app/(commonLayout)/deployments/[appInstanceId]/releases/page.tsxnew file mode 100644index 00000000000..ee5e689cc65--- /dev/null+++ b/web/app/(commonLayout)/deployments/[appInstanceId]/releases/page.tsx@@ -0,0 +1,8 @@+import { VersionsTab } from '@/features/deployments/detail/versions-tab'++export default async function InstanceDetailReleasesPage({ params }: {+ params: Promise<{ appInstanceId: string }>+}) {+ const { appInstanceId } = await params+ return <VersionsTab appInstanceId={appInstanceId} />+}diff --git a/web/app/(commonLayout)/deployments/create/page.tsx b/web/app/(commonLayout)/deployments/create/page.tsxnew file mode 100644index 00000000000..1e85fbdffa7--- /dev/null+++ b/web/app/(commonLayout)/deployments/create/page.tsx@@ -0,0 +1,12 @@+'use client'++import { useTranslation } from 'react-i18next'+import { CreateDeploymentGuide } from '@/features/deployments/create-guide'+import useDocumentTitle from '@/hooks/use-document-title'++export default function CreateDeploymentPage() {+ const { t } = useTranslation('deployments')+ useDocumentTitle(t('documentTitle.create'))++ return <CreateDeploymentGuide />+}diff --git a/web/app/(commonLayout)/deployments/layout.tsx b/web/app/(commonLayout)/deployments/layout.tsxnew file mode 100644index 00000000000..eb522444778--- /dev/null+++ b/web/app/(commonLayout)/deployments/layout.tsx@@ -0,0 +1,13 @@+import type { ReactNode } from 'react'+import { DeployDrawer } from '@/features/deployments/deploy-drawer'++export default function DeploymentsLayout({ children }: {+ children: ReactNode+}) {+ return (+ <>+ {children}+ <DeployDrawer />+ </>+ )+}diff --git a/web/app/(commonLayout)/deployments/page.tsx b/web/app/(commonLayout)/deployments/page.tsxnew file mode 100644index 00000000000..753f0a1837f--- /dev/null+++ b/web/app/(commonLayout)/deployments/page.tsx@@ -0,0 +1,10 @@+'use client'+import { useTranslation } from 'react-i18next'+import { DeploymentsList } from '@/features/deployments/list'+import useDocumentTitle from '@/hooks/use-document-title'++export default function DeploymentsPage() {+ const { t } = useTranslation('deployments')+ useDocumentTitle(t('documentTitle.list'))+ return <DeploymentsList />+}diff --git a/web/app/(commonLayout)/layout.tsx b/web/app/(commonLayout)/layout.tsxindex fa0ce21bbb8..4d6bdf7984c 100644--- a/web/app/(commonLayout)/layout.tsx+++ b/web/app/(commonLayout)/layout.tsx@@ -16,9 +16,9 @@ import { ModalContextProvider } from '@/context/modal-context-provider'import { ProviderContextProvider } from '@/context/provider-context-provider'import PartnerStack from '../components/billing/partner-stack'import { CommonLayoutHydrationBoundary } from './hydration-boundary'-import RoleRouteGuard from './role-route-guard'+import { RoleRouteGuard } from './role-route-guard'-const Layout = async ({ children }: { children: ReactNode }) => {+export default async function Layout({ children }: { children: ReactNode }) {return (<><GoogleAnalyticsScripts />@@ -49,4 +49,3 @@ const Layout = async ({ children }: { children: ReactNode }) => {</>)}-export default Layoutdiff --git a/web/app/(commonLayout)/role-route-guard.tsx b/web/app/(commonLayout)/role-route-guard.tsxindex 482a13c5d26..05cf59aee42 100644--- a/web/app/(commonLayout)/role-route-guard.tsx+++ b/web/app/(commonLayout)/role-route-guard.tsx@@ -1,28 +1,38 @@'use client'import type { ReactNode } from 'react'-import { useQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import Loading from '@/app/components/base/loading'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { redirect, usePathname } from '@/next/navigation'import { consoleQuery } from '@/service/client'-const datasetOperatorRedirectRoutes = ['/', '/apps', '/app', '/snippets', '/explore', '/tools', '/integrations'] as const+const datasetOperatorRedirectRoutes = ['/', '/apps', '/app', '/deployments', '/snippets', '/explore', '/tools', '/integrations'] as const-const isPathUnderRoute = (pathname: string, route: string) => pathname === route || pathname.startsWith(`${route}/`)+function isPathUnderRoute(pathname: string, route: string) {+ return pathname === route || pathname.startsWith(`${route}/`)+}-export default function RoleRouteGuard({ children }: { children: ReactNode }) {+export function RoleRouteGuard({ children }: { children: ReactNode }) {const currentWorkspaceRoleQuery = useQuery(consoleQuery.workspaces.current.post.queryOptions({select: workspace => workspace.role,}))+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const pathname = usePathname()const shouldGuardRoute = datasetOperatorRedirectRoutes.some(route => isPathUnderRoute(pathname, route))- const shouldRedirect = shouldGuardRoute && !currentWorkspaceRoleQuery.isPending && currentWorkspaceRoleQuery.data === 'dataset_operator'+ const shouldRedirectDatasetOperator = shouldGuardRoute+ && !currentWorkspaceRoleQuery.isPending+ && currentWorkspaceRoleQuery.data === 'dataset_operator'+ const shouldRedirectAppDeploy = isPathUnderRoute(pathname, '/deployments') && !systemFeatures.enable_app_deploy// Block rendering only for guarded routes to avoid permission flicker.if (shouldGuardRoute && currentWorkspaceRoleQuery.isPending)return <Loading type="app" />- if (shouldRedirect)+ if (shouldRedirectAppDeploy)+ redirect('/apps')++ if (shouldRedirectDatasetOperator)redirect('/datasets')return <>{children}</>diff --git a/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsxindex 03a35bd52ab..acbdf1281e5 100644--- a/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx@@ -1,5 +1,5 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import AccessControlDialog from '../access-control-dialog'+import { AccessControlDialog } from '../access-control-dialog'describe('AccessControlDialog', () => {it('should render dialog content when visible', () => {diff --git a/web/app/components/app/app-access-control/__tests__/access-control-item.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control-item.spec.tsxindex b1a862a13c9..0972a654751 100644--- a/web/app/components/app/app-access-control/__tests__/access-control-item.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/access-control-item.spec.tsx@@ -1,45 +1,43 @@import { fireEvent, render, screen } from '@testing-library/react'-import useAccessControlStore from '@/context/access-control-store'import { AccessMode } from '@/models/access-control'-import AccessControlItem from '../access-control-item'+import { AccessControlItem } from '../access-control-item'+import { AccessControlRadioGroupHarness } from './access-control-radio-group-harness'+import { createAccessControlDraftHarness } from './access-control-test-utils'describe('AccessControlItem', () => {beforeEach(() => {vi.clearAllMocks()- useAccessControlStore.setState({- appId: '',- specificGroups: [],- specificMembers: [],- currentMenu: AccessMode.PUBLIC,- selectedGroupsForBreadcrumb: [],- })})it('should update current menu when selecting a different access type', () => {- render(- <AccessControlItem type={AccessMode.ORGANIZATION}>- <span>Organization Only</span>- </AccessControlItem>,+ const harness = createAccessControlDraftHarness(+ <AccessControlRadioGroupHarness>+ <AccessControlItem type={AccessMode.ORGANIZATION}>+ <span>Organization Only</span>+ </AccessControlItem>+ </AccessControlRadioGroupHarness>,+ { currentMenu: AccessMode.PUBLIC },)+ render(harness.element)- const option = screen.getByText('Organization Only').parentElement as HTMLElement+ const option = screen.getByRole('radio', { name: 'Organization Only' })fireEvent.click(option)- expect(useAccessControlStore.getState().currentMenu).toBe(AccessMode.ORGANIZATION)+ expect(harness.getSnapshot().currentMenu).toBe(AccessMode.ORGANIZATION)})it('should keep the selected state for the active access type', () => {- useAccessControlStore.setState({- currentMenu: AccessMode.ORGANIZATION,- })-- render(- <AccessControlItem type={AccessMode.ORGANIZATION}>- <span>Organization Only</span>- </AccessControlItem>,+ const harness = createAccessControlDraftHarness(+ <AccessControlRadioGroupHarness>+ <AccessControlItem type={AccessMode.ORGANIZATION}>+ <span>Organization Only</span>+ </AccessControlItem>+ </AccessControlRadioGroupHarness>,+ { currentMenu: AccessMode.ORGANIZATION },)+ render(harness.element)- const option = screen.getByText('Organization Only').parentElement as HTMLElement- expect(option).toHaveClass('border-components-option-card-option-selected-border')+ const option = screen.getByRole('radio', { name: 'Organization Only' })+ expect(option).toHaveAttribute('data-checked')})})diff --git a/web/app/components/app/app-access-control/__tests__/access-control-radio-group-harness.tsx b/web/app/components/app/app-access-control/__tests__/access-control-radio-group-harness.tsxnew file mode 100644index 00000000000..8dc6cbd75cb--- /dev/null+++ b/web/app/components/app/app-access-control/__tests__/access-control-radio-group-harness.tsx@@ -0,0 +1,17 @@+import type { ReactNode } from 'react'+import type { AccessMode } from '@/models/access-control'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'+import { useAccessControlStore } from '../store'++export function AccessControlRadioGroupHarness({ children }: {+ children: ReactNode+}) {+ const currentMenu = useAccessControlStore(state => state.currentMenu)+ const setCurrentMenu = useAccessControlStore(state => state.setCurrentMenu)++ return (+ <RadioGroup<AccessMode> value={currentMenu} onValueChange={setCurrentMenu}>+ {children}+ </RadioGroup>+ )+}diff --git a/web/app/components/app/app-access-control/__tests__/access-control-test-utils.ts b/web/app/components/app/app-access-control/__tests__/access-control-test-utils.tsnew file mode 100644index 00000000000..2a6f27b8331--- /dev/null+++ b/web/app/components/app/app-access-control/__tests__/access-control-test-utils.ts@@ -0,0 +1,71 @@+import type { ReactNode } from 'react'+import type { AccessControlDraft, AccessControlStore } from '../store'+import { createElement } from 'react'+import { AccessMode } from '@/models/access-control'+import { useAccessControlStore } from '../store'+import { AccessControlDraftProvider } from '../store-provider'++const emptyDraft = {+ appId: '',+ currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS,+ specificGroups: [],+ specificMembers: [],+ selectedGroupsForBreadcrumb: [],+} satisfies Required<AccessControlDraft>++function draftKey(draft: AccessControlDraft) {+ return [+ draft.appId ?? '',+ draft.currentMenu,+ draft.specificGroups?.map(group => group.id).join(',') ?? '',+ draft.specificMembers?.map(member => member.id).join(',') ?? '',+ draft.selectedGroupsForBreadcrumb?.map(group => group.id).join(',') ?? '',+ ].join(':')+}++function completeDraft(initialDraft: Partial<AccessControlDraft> = {}): Required<AccessControlDraft> {+ return {+ ...emptyDraft,+ ...initialDraft,+ }+}++function SnapshotProbe({ onSnapshot }: {+ onSnapshot: (snapshot: AccessControlStore) => void+}) {+ onSnapshot(useAccessControlStore(state => state))+ return null+}++export function createAccessControlDraftHarness(+ children: ReactNode,+ initialDraft?: Partial<AccessControlDraft>,+) {+ const draft = completeDraft(initialDraft)+ let snapshot: AccessControlStore = {+ appId: draft.appId,+ specificGroups: draft.specificGroups,+ setSpecificGroups: () => undefined,+ specificMembers: draft.specificMembers,+ setSpecificMembers: () => undefined,+ currentMenu: draft.currentMenu,+ setCurrentMenu: () => undefined,+ selectedGroupsForBreadcrumb: draft.selectedGroupsForBreadcrumb,+ setSelectedGroupsForBreadcrumb: () => undefined,+ }++ return {+ element: createElement(+ AccessControlDraftProvider,+ {+ draftKey: draftKey(draft),+ initialDraft: draft,+ },+ createElement(SnapshotProbe, {+ onSnapshot: nextSnapshot => snapshot = nextSnapshot,+ }),+ children,+ ),+ getSnapshot: () => snapshot,+ }+}diff --git a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsxindex 52c2a0dd543..1a8a181f68c 100644--- a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx@@ -1,24 +1,23 @@import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'import type { App } from '@/types/app'+import { SubjectType as EnterpriseSubjectType } from '@dify/contracts/enterprise/types.gen'import { toast } from '@langgenius/dify-ui/toast'import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'-import useAccessControlStore from '@/context/access-control-store'import { AccessMode, SubjectType } from '@/models/access-control'-import AccessControlDialog from '../access-control-dialog'-import AccessControlItem from '../access-control-item'-import AddMemberOrGroupDialog from '../add-member-or-group-pop'-import AccessControl from '../index'-import SpecificGroupsOrMembers from '../specific-groups-or-members'+import { AccessControlDialog } from '../access-control-dialog'+import { AccessControlItem } from '../access-control-item'+import { AddMemberOrGroupDialog } from '../add-member-or-group-pop'+import { AccessControl } from '../index'+import { SpecificGroupsOrMembers } from '../specific-groups-or-members'+import { AccessControlRadioGroupHarness } from './access-control-radio-group-harness'+import { createAccessControlDraftHarness } from './access-control-test-utils'const mockUseAppWhiteListSubjects = vi.fn()const mockUseSearchForWhiteListCandidates = vi.fn()-const mockMutateAsync = vi.fn()-const mockUseUpdateAccessMode = vi.fn(() => ({- isPending: false,- mutateAsync: mockMutateAsync,-}))+const mockMutate = vi.fn()+const mockUseMutation = vi.hoisted(() => vi.fn())const intersectionObserverMocks = vi.hoisted(() => ({callback: null as null | ((entries: Array<{ isIntersecting: boolean }>) => void),}))@@ -39,9 +38,16 @@ vi.mock('@/context/app-context', () => ({vi.mock('@/service/access-control', () => ({useAppWhiteListSubjects: (...args: unknown[]) => mockUseAppWhiteListSubjects(...args),useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),- useUpdateAccessMode: () => mockUseUpdateAccessMode(),}))+vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useMutation: (...args: unknown[]) => mockUseMutation(...args),+ }+})+vi.mock('ahooks', async (importOriginal) => {const actual = await importOriginal<typeof import('ahooks')>()return {@@ -94,10 +100,12 @@ beforeAll(() => {})beforeEach(() => {- mockMutateAsync.mockResolvedValue(undefined)- mockUseUpdateAccessMode.mockReturnValue({+ mockMutate.mockImplementation((_: unknown, options?: { onSuccess?: () => void }) => {+ options?.onSuccess?.()+ })+ mockUseMutation.mockReturnValue({isPending: false,- mutateAsync: mockMutateAsync,+ mutate: mockMutate,})mockUseAppWhiteListSubjects.mockReturnValue({isPending: false,@@ -117,33 +125,39 @@ beforeEach(() => {// AccessControlItem handles selected vs. unselected styling and click state updatesdescribe('AccessControlItem', () => {it('should update current menu when selecting a different access type', () => {- useAccessControlStore.setState({ currentMenu: AccessMode.PUBLIC })- render(- <AccessControlItem type={AccessMode.ORGANIZATION}>- <span>Organization Only</span>- </AccessControlItem>,+ const harness = createAccessControlDraftHarness(+ <AccessControlRadioGroupHarness>+ <AccessControlItem type={AccessMode.ORGANIZATION}>+ <span>Organization Only</span>+ </AccessControlItem>+ </AccessControlRadioGroupHarness>,+ { currentMenu: AccessMode.PUBLIC },)+ render(harness.element)- const option = screen.getByText('Organization Only').parentElement as HTMLElement+ const option = screen.getByRole('radio', { name: 'Organization Only' })expect(option).toHaveClass('cursor-pointer')fireEvent.click(option)- expect(useAccessControlStore.getState().currentMenu).toBe(AccessMode.ORGANIZATION)+ expect(harness.getSnapshot().currentMenu).toBe(AccessMode.ORGANIZATION)})it('should keep current menu when clicking the selected access type', () => {- useAccessControlStore.setState({ currentMenu: AccessMode.ORGANIZATION })- render(- <AccessControlItem type={AccessMode.ORGANIZATION}>- <span>Organization Only</span>- </AccessControlItem>,+ const harness = createAccessControlDraftHarness(+ <AccessControlRadioGroupHarness>+ <AccessControlItem type={AccessMode.ORGANIZATION}>+ <span>Organization Only</span>+ </AccessControlItem>+ </AccessControlRadioGroupHarness>,+ { currentMenu: AccessMode.ORGANIZATION },)+ render(harness.element)- const option = screen.getByText('Organization Only').parentElement as HTMLElement+ const option = screen.getByRole('radio', { name: 'Organization Only' })fireEvent.click(option)- expect(useAccessControlStore.getState().currentMenu).toBe(AccessMode.ORGANIZATION)+ expect(harness.getSnapshot().currentMenu).toBe(AccessMode.ORGANIZATION)})})@@ -180,32 +194,40 @@ describe('AccessControlDialog', () => {// SpecificGroupsOrMembers syncs store state with fetched data and supports removalsdescribe('SpecificGroupsOrMembers', () => {it('should render collapsed view when not in specific selection mode', () => {- useAccessControlStore.setState({ currentMenu: AccessMode.ORGANIZATION })+ const harness = createAccessControlDraftHarness(+ <SpecificGroupsOrMembers />,+ { currentMenu: AccessMode.ORGANIZATION },+ )- render(<SpecificGroupsOrMembers />)+ render(harness.element)expect(screen.getByText('app.accessControlDialog.accessItems.specific')).toBeInTheDocument()expect(screen.queryByText(baseGroup.name)).not.toBeInTheDocument()})it('should show loading state while pending', async () => {- useAccessControlStore.setState({ appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS })- mockUseAppWhiteListSubjects.mockReturnValue({- isPending: true,- data: undefined,- })+ const harness = createAccessControlDraftHarness(+ <SpecificGroupsOrMembers loading />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )- const { container } = render(<SpecificGroupsOrMembers />)+ render(harness.element)- await waitFor(() => {- expect(container.querySelector('.spin-animation')).toBeInTheDocument()- })+ expect(screen.getByRole('status', { name: 'common.loading' })).toBeInTheDocument()})it('should render fetched groups and members and support removal', async () => {- useAccessControlStore.setState({ appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS })+ const harness = createAccessControlDraftHarness(+ <SpecificGroupsOrMembers />,+ {+ appId: 'app-1',+ currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS,+ specificGroups: [baseGroup],+ specificMembers: [baseMember],+ },+ )- render(<SpecificGroupsOrMembers />)+ render(harness.element)await waitFor(() => {expect(screen.getByText(baseGroup.name)).toBeInTheDocument()@@ -234,8 +256,12 @@ describe('SpecificGroupsOrMembers', () => {describe('AddMemberOrGroupDialog', () => {it('should open search popover and display candidates', async () => {const user = userEvent.setup()+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )- render(<AddMemberOrGroupDialog />)+ render(harness.element)await user.click(screen.getByText('common.operation.add'))@@ -246,17 +272,21 @@ describe('AddMemberOrGroupDialog', () => {it('should allow selecting members and expanding groups', async () => {const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))const expandButton = screen.getByText('app.accessControlDialog.operateGroupAndMember.expand')await user.click(expandButton)- expect(useAccessControlStore.getState().selectedGroupsForBreadcrumb).toEqual([baseGroup])+ expect(harness.getSnapshot().selectedGroupsForBreadcrumb).toEqual([baseGroup])await user.click(screen.getByRole('option', { name: /Member One/ }))- expect(useAccessControlStore.getState().specificMembers).toEqual([baseMember])+ expect(harness.getSnapshot().specificMembers).toEqual([baseMember])})it('should update the keyword, fetch the next page, and support deselection and breadcrumb reset', async () => {@@ -269,7 +299,11 @@ describe('AddMemberOrGroupDialog', () => {})const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))await user.type(screen.getByPlaceholderText('app.accessControlDialog.operateGroupAndMember.searchPlaceholder'), 'Group')@@ -286,9 +320,9 @@ describe('AddMemberOrGroupDialog', () => {fireEvent.click(screen.getByText('app.accessControlDialog.operateGroupAndMember.expand'))fireEvent.click(screen.getByText('app.accessControlDialog.operateGroupAndMember.allMembers'))- expect(useAccessControlStore.getState().specificGroups).toEqual([])- expect(useAccessControlStore.getState().specificMembers).toEqual([])- expect(useAccessControlStore.getState().selectedGroupsForBreadcrumb).toEqual([])+ expect(harness.getSnapshot().specificGroups).toEqual([])+ expect(harness.getSnapshot().specificMembers).toEqual([])+ expect(harness.getSnapshot().selectedGroupsForBreadcrumb).toEqual([])expect(fetchNextPage).not.toHaveBeenCalled()})@@ -301,7 +335,11 @@ describe('AddMemberOrGroupDialog', () => {})const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))@@ -315,10 +353,6 @@ describe('AccessControl', () => {const onClose = vi.fn()const onConfirm = vi.fn()const toastSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')- useAccessControlStore.setState({- specificGroups: [baseGroup],- specificMembers: [baseMember],- })const app = {id: 'app-id-1',access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,@@ -332,21 +366,22 @@ describe('AccessControl', () => {/>,)- await waitFor(() => {- expect(useAccessControlStore.getState().currentMenu).toBe(AccessMode.SPECIFIC_GROUPS_MEMBERS)- })-fireEvent.click(screen.getByText('common.operation.confirm'))await waitFor(() => {- expect(mockMutateAsync).toHaveBeenCalledWith({- appId: app.id,- accessMode: AccessMode.SPECIFIC_GROUPS_MEMBERS,- subjects: [- { subjectId: baseGroup.id, subjectType: SubjectType.GROUP },- { subjectId: baseMember.id, subjectType: SubjectType.ACCOUNT },- ],- })+ expect(mockMutate).toHaveBeenCalledWith(+ {+ body: {+ appId: app.id,+ accessMode: AccessMode.SPECIFIC_GROUPS_MEMBERS,+ subjects: [+ { subjectId: baseGroup.id, subjectType: EnterpriseSubjectType.SUBJECT_TYPE_GROUP },+ { subjectId: baseMember.id, subjectType: EnterpriseSubjectType.SUBJECT_TYPE_ACCOUNT },+ ],+ },+ },+ expect.objectContaining({ onSuccess: expect.any(Function) }),+ )expect(toastSpy).toHaveBeenCalledWith('app.accessControlDialog.updateSuccess')expect(onConfirm).toHaveBeenCalled()})diff --git a/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx b/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsxindex d34756e85e4..b447e9c381b 100644--- a/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx@@ -1,9 +1,9 @@import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import useAccessControlStore from '@/context/access-control-store'-import { SubjectType } from '@/models/access-control'-import AddMemberOrGroupDialog from '../add-member-or-group-pop'+import { AccessMode, SubjectType } from '@/models/access-control'+import { AddMemberOrGroupDialog } from '../add-member-or-group-pop'+import { createAccessControlDraftHarness } from './access-control-test-utils'const mockUseSearchForWhiteListCandidates = vi.fn()const intersectionObserverMocks = vi.hoisted(() => ({@@ -69,13 +69,6 @@ describe('AddMemberOrGroupDialog', () => {beforeEach(() => {vi.clearAllMocks()- useAccessControlStore.setState({- appId: 'app-1',- specificGroups: [],- specificMembers: [],- currentMenu: SubjectType.GROUP as never,- selectedGroupsForBreadcrumb: [],- })mockUseSearchForWhiteListCandidates.mockReturnValue({isLoading: false,isFetchingNextPage: false,@@ -88,7 +81,11 @@ describe('AddMemberOrGroupDialog', () => {it('should open the search popover and display candidates', async () => {const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))@@ -99,16 +96,20 @@ describe('AddMemberOrGroupDialog', () => {it('should allow expanding groups and selecting members', async () => {const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))await user.click(screen.getByText('app.accessControlDialog.operateGroupAndMember.expand'))- expect(useAccessControlStore.getState().selectedGroupsForBreadcrumb).toEqual([baseGroup])+ expect(harness.getSnapshot().selectedGroupsForBreadcrumb).toEqual([baseGroup])await user.click(screen.getByRole('option', { name: /Member One/ }))- expect(useAccessControlStore.getState().specificMembers).toEqual([baseMember])+ expect(harness.getSnapshot().specificMembers).toEqual([baseMember])})it('should show the empty state when no candidates are returned', async () => {@@ -120,7 +121,11 @@ describe('AddMemberOrGroupDialog', () => {})const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ { appId: 'app-1', currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))@@ -128,9 +133,6 @@ describe('AddMemberOrGroupDialog', () => {})it('should keep breadcrumbs visible when the current group has no candidates', async () => {- useAccessControlStore.setState({- selectedGroupsForBreadcrumb: [baseGroup],- })mockUseSearchForWhiteListCandidates.mockReturnValue({isLoading: false,isFetchingNextPage: false,@@ -139,7 +141,15 @@ describe('AddMemberOrGroupDialog', () => {})const user = userEvent.setup()- render(<AddMemberOrGroupDialog />)+ const harness = createAccessControlDraftHarness(+ <AddMemberOrGroupDialog />,+ {+ appId: 'app-1',+ currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS,+ selectedGroupsForBreadcrumb: [baseGroup],+ },+ )+ render(harness.element)await user.click(screen.getByText('common.operation.add'))@@ -149,6 +159,6 @@ describe('AddMemberOrGroupDialog', () => {await user.click(screen.getByRole('button', { name: 'app.accessControlDialog.operateGroupAndMember.allMembers' }))- expect(useAccessControlStore.getState().selectedGroupsForBreadcrumb).toEqual([])+ expect(harness.getSnapshot().selectedGroupsForBreadcrumb).toEqual([])})})diff --git a/web/app/components/app/app-access-control/__tests__/index.spec.tsx b/web/app/components/app/app-access-control/__tests__/index.spec.tsxindex 74e7d7046c0..f3cb47f16b8 100644--- a/web/app/components/app/app-access-control/__tests__/index.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/index.spec.tsx@@ -3,9 +3,8 @@ import type { App } from '@/types/app'import { toast } from '@langgenius/dify-ui/toast'import { fireEvent, screen, waitFor } from '@testing-library/react'import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'-import useAccessControlStore from '@/context/access-control-store'import { AccessMode } from '@/models/access-control'-import AccessControl from '../index'+import { AccessControl } from '../index'let mockWebappAuth = {enabled: true,@@ -18,20 +17,24 @@ const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {systemFeatures: { webapp_auth: mockWebappAuth },})-const mockMutateAsync = vi.fn()-const mockUseUpdateAccessMode = vi.fn(() => ({- isPending: false,- mutateAsync: mockMutateAsync,-}))+const mockMutate = vi.fn()+const mockUseMutation = vi.hoisted(() => vi.fn())const mockUseAppWhiteListSubjects = vi.fn()const mockUseSearchForWhiteListCandidates = vi.fn()vi.mock('@/service/access-control', () => ({useAppWhiteListSubjects: (...args: unknown[]) => mockUseAppWhiteListSubjects(...args),useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),- useUpdateAccessMode: () => mockUseUpdateAccessMode(),}))+vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useMutation: (...args: unknown[]) => mockUseMutation(...args),+ }+})+describe('AccessControl', () => {beforeEach(() => {vi.clearAllMocks()@@ -41,14 +44,13 @@ describe('AccessControl', () => {allow_email_password_login: false,allow_email_code_login: false,}- useAccessControlStore.setState({- appId: '',- specificGroups: [],- specificMembers: [],- currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS,- selectedGroupsForBreadcrumb: [],+ mockMutate.mockImplementation((_: unknown, options?: { onSuccess?: () => void }) => {+ options?.onSuccess?.()+ })+ mockUseMutation.mockReturnValue({+ isPending: false,+ mutate: mockMutate,})- mockMutateAsync.mockResolvedValue(undefined)mockUseAppWhiteListSubjects.mockReturnValue({isPending: false,data: {@@ -81,18 +83,18 @@ describe('AccessControl', () => {/>,)- await waitFor(() => {- expect(useAccessControlStore.getState().appId).toBe(app.id)- expect(useAccessControlStore.getState().currentMenu).toBe(AccessMode.PUBLIC)- })-fireEvent.click(screen.getByText('common.operation.confirm'))await waitFor(() => {- expect(mockMutateAsync).toHaveBeenCalledWith({- appId: app.id,- accessMode: AccessMode.PUBLIC,- })+ expect(mockMutate).toHaveBeenCalledWith(+ {+ body: {+ appId: app.id,+ accessMode: AccessMode.PUBLIC,+ },+ },+ expect.objectContaining({ onSuccess: expect.any(Function) }),+ )expect(toastSpy).toHaveBeenCalledWith('app.accessControlDialog.updateSuccess')expect(onConfirm).toHaveBeenCalledTimes(1)})@@ -116,4 +118,30 @@ describe('AccessControl', () => {expect(screen.getByText('app.accessControlDialog.accessItems.external')).toBeInTheDocument()expect(screen.getByText('app.accessControlDialog.accessItems.anyone')).toBeInTheDocument()})++ it('should prevent confirming specific access before subjects are loaded', () => {+ mockUseAppWhiteListSubjects.mockReturnValue({+ isPending: true,+ data: undefined,+ })++ render(+ <AccessControl+ app={{ id: 'app-id-3', access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS } as App}+ onClose={vi.fn()}+ />,+ )++ const confirmButton = screen.getByRole('button', { name: 'common.operation.confirm' })+ const organizationOption = screen.getByRole('radio', {+ name: 'app.accessControlDialog.accessItems.organization',+ })++ expect(confirmButton).toBeDisabled()+ expect(organizationOption).toHaveAttribute('aria-disabled', 'true')++ fireEvent.click(confirmButton)++ expect(mockMutate).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsx b/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsxindex e7635219405..044e5aa3d60 100644--- a/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsx@@ -1,17 +1,13 @@import type { AccessControlAccount, AccessControlGroup } from '@/models/access-control'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import useAccessControlStore from '@/context/access-control-store'import { AccessMode } from '@/models/access-control'-import SpecificGroupsOrMembers from '../specific-groups-or-members'+import { SpecificGroupsOrMembers } from '../specific-groups-or-members'+import { createAccessControlDraftHarness } from './access-control-test-utils'-const mockUseAppWhiteListSubjects = vi.fn()+const mockUseSearchForWhiteListCandidates = vi.fn()vi.mock('@/service/access-control', () => ({- useAppWhiteListSubjects: (...args: unknown[]) => mockUseAppWhiteListSubjects(...args),-}))--vi.mock('../add-member-or-group-pop', () => ({- default: () => <div data-testid="add-member-or-group-dialog" />,+ useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),}))const createGroup = (overrides: Partial<AccessControlGroup> = {}): AccessControlGroup => ({@@ -36,50 +32,48 @@ describe('SpecificGroupsOrMembers', () => {beforeEach(() => {vi.clearAllMocks()- useAccessControlStore.setState({- appId: '',- specificGroups: [],- specificMembers: [],- currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS,- selectedGroupsForBreadcrumb: [],- })- mockUseAppWhiteListSubjects.mockReturnValue({- isPending: false,- data: {- groups: [baseGroup],- members: [baseMember],- },+ mockUseSearchForWhiteListCandidates.mockReturnValue({+ isLoading: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ data: { pages: [] },})})it('should render the collapsed row when not in specific mode', () => {- useAccessControlStore.setState({- currentMenu: AccessMode.ORGANIZATION,- })+ const harness = createAccessControlDraftHarness(+ <SpecificGroupsOrMembers />,+ { currentMenu: AccessMode.ORGANIZATION },+ )- render(<SpecificGroupsOrMembers />)+ render(harness.element)expect(screen.getByText('app.accessControlDialog.accessItems.specific')).toBeInTheDocument()- expect(screen.queryByTestId('add-member-or-group-dialog')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.operation.add' })).not.toBeInTheDocument()})- it('should show loading while whitelist subjects are pending', async () => {- mockUseAppWhiteListSubjects.mockReturnValue({- isPending: true,- data: undefined,- })+ it('should show loading when the selected subjects are pending', async () => {+ const harness = createAccessControlDraftHarness(<SpecificGroupsOrMembers loading />)+ render(harness.element)- const { container } = render(<SpecificGroupsOrMembers />)+ expect(screen.getByRole('combobox', { name: 'common.operation.add' })).toBeDisabled()await waitFor(() => {- expect(container.querySelector('.spin-animation')).toBeInTheDocument()+ expect(screen.getByRole('status', { name: 'common.loading' })).toBeInTheDocument()})})it('should render fetched groups and members and support removal', async () => {- useAccessControlStore.setState({ appId: 'app-1' })+ const harness = createAccessControlDraftHarness(+ <SpecificGroupsOrMembers />,+ {+ appId: 'app-1',+ specificGroups: [baseGroup],+ specificMembers: [baseMember],+ },+ )- render(<SpecificGroupsOrMembers />)+ render(harness.element)await waitFor(() => {expect(screen.getByText(baseGroup.name)).toBeInTheDocument()@@ -91,9 +85,9 @@ describe('SpecificGroupsOrMembers', () => {const memberRemove = removeButtons[1]!fireEvent.click(groupRemove)- expect(useAccessControlStore.getState().specificGroups).toEqual([])+ expect(harness.getSnapshot().specificGroups).toEqual([])fireEvent.click(memberRemove)- expect(useAccessControlStore.getState().specificMembers).toEqual([])+ expect(harness.getSnapshot().specificMembers).toEqual([])})})diff --git a/web/app/components/app/app-access-control/access-control-dialog-content.tsx b/web/app/components/app/app-access-control/access-control-dialog-content.tsxnew file mode 100644index 00000000000..fb1f324a0ea--- /dev/null+++ b/web/app/components/app/app-access-control/access-control-dialog-content.tsx@@ -0,0 +1,110 @@+'use client'++import type { ReactNode } from 'react'+import type { SpecificGroupsOrMembersProps } from './specific-groups-or-members'+import { Button } from '@langgenius/dify-ui/button'+import { DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'+import { useTranslation } from 'react-i18next'+import { AccessMode } from '@/models/access-control'+import { AccessControlItem } from './access-control-item'+import { SpecificGroupsOrMembers, WebAppSSONotEnabledTip } from './specific-groups-or-members'+import { useAccessControlStore } from './store'++type AccessControlDialogContentProps = {+ title?: ReactNode+ description?: ReactNode+ accessLabel?: ReactNode+ hideExternal?: boolean+ hideExternalTip?: boolean+ saving?: boolean+ controlsDisabled?: boolean+ confirmDisabled?: boolean+ specificGroupsOrMembersProps?: SpecificGroupsOrMembersProps+ onClose: () => void+ onConfirm: () => void+}++export function AccessControlDialogContent({+ title,+ description,+ accessLabel,+ hideExternal = false,+ hideExternalTip = false,+ saving = false,+ controlsDisabled = false,+ confirmDisabled = false,+ specificGroupsOrMembersProps,+ onClose,+ onConfirm,+}: AccessControlDialogContentProps) {+ const { t } = useTranslation()+ const currentMenu = useAccessControlStore(s => s.currentMenu)+ const setCurrentMenu = useAccessControlStore(s => s.setCurrentMenu)++ return (+ <div className="flex flex-col gap-y-3">+ <div className="pt-6 pr-14 pb-3 pl-6">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {title ?? t('accessControlDialog.title', { ns: 'app' })}+ </DialogTitle>+ <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">+ {description ?? t('accessControlDialog.description', { ns: 'app' })}+ </DialogDescription>+ </div>+ <RadioGroup<AccessMode>+ value={currentMenu}+ onValueChange={setCurrentMenu}+ className="flex flex-col items-stretch gap-y-1 px-6 pb-3"+ aria-labelledby="access-control-options-label"+ disabled={controlsDisabled}+ >+ <div className="leading-6">+ <p id="access-control-options-label" className="system-sm-medium text-text-tertiary">+ {accessLabel ?? t('accessControlDialog.accessLabel', { ns: 'app' })}+ </p>+ </div>+ <AccessControlItem type={AccessMode.ORGANIZATION}>+ <div className="flex items-center p-3">+ <div className="flex grow items-center gap-x-2">+ <span className="i-ri-building-line size-4 text-text-primary" aria-hidden="true" />+ <p className="system-sm-medium text-text-primary">+ {t('accessControlDialog.accessItems.organization', { ns: 'app' })}+ </p>+ </div>+ </div>+ </AccessControlItem>+ <AccessControlItem type={AccessMode.SPECIFIC_GROUPS_MEMBERS}>+ <SpecificGroupsOrMembers {...specificGroupsOrMembersProps} />+ </AccessControlItem>+ {!hideExternal && (+ <AccessControlItem type={AccessMode.EXTERNAL_MEMBERS}>+ <div className="flex items-center p-3">+ <div className="flex grow items-center gap-x-2">+ <span className="i-ri-verified-badge-line size-4 text-text-primary" aria-hidden="true" />+ <p className="system-sm-medium text-text-primary">+ {t('accessControlDialog.accessItems.external', { ns: 'app' })}+ </p>+ </div>+ {!hideExternalTip && <WebAppSSONotEnabledTip />}+ </div>+ </AccessControlItem>+ )}+ <AccessControlItem type={AccessMode.PUBLIC}>+ <div className="flex items-center gap-x-2 p-3">+ <span className="i-ri-global-line size-4 text-text-primary" aria-hidden="true" />+ <p className="system-sm-medium text-text-primary">+ {t('accessControlDialog.accessItems.anyone', { ns: 'app' })}+ </p>+ </div>+ </AccessControlItem>+ </RadioGroup>+ <div className="flex items-center justify-end gap-x-2 p-6 pt-5">+ <Button disabled={saving} onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>+ <Button disabled={confirmDisabled || saving} loading={saving} variant="primary" onClick={onConfirm}>+ {t('operation.confirm', { ns: 'common' })}+ </Button>+ </div>+ </div>+ )+}diff --git a/web/app/components/app/app-access-control/access-control-dialog.tsx b/web/app/components/app/app-access-control/access-control-dialog.tsxindex a863935f90d..c29e73aa9a4 100644--- a/web/app/components/app/app-access-control/access-control-dialog.tsx+++ b/web/app/components/app/app-access-control/access-control-dialog.tsx@@ -5,7 +5,6 @@ import {DialogCloseButton,DialogContent,} from '@langgenius/dify-ui/dialog'-import { useCallback } from 'react'type DialogProps = {className?: string@@ -14,21 +13,17 @@ type DialogProps = {onClose?: () => void}-const AccessControlDialog = ({+export function AccessControlDialog({className,children,show,onClose,-}: DialogProps) => {- const close = useCallback(() => {- onClose?.()- }, [onClose])-+}: DialogProps) {return (- <Dialog open={show} disablePointerDismissal onOpenChange={open => !open && close()}>+ <Dialog open={show} disablePointerDismissal onOpenChange={open => !open && onClose?.()}><DialogContentclassName={cn(- 'h-auto max-h-[calc(100dvh-2rem)] min-h-[323px] w-[600px] max-w-none overflow-y-auto rounded-2xl border-none bg-components-panel-bg p-0 shadow-xl transition-all',+ 'h-auto max-h-[calc(100dvh-2rem)] min-h-[323px] w-[600px] max-w-none overflow-y-auto rounded-2xl border-none bg-components-panel-bg p-0 shadow-xl transition-shadow',className,)}>@@ -38,5 +33,3 @@ const AccessControlDialog = ({</Dialog>)}--export default AccessControlDialogdiff --git a/web/app/components/app/app-access-control/access-control-item.tsx b/web/app/components/app/app-access-control/access-control-item.tsxindex cc2cf94f0c4..5913a7e47f8 100644--- a/web/app/components/app/app-access-control/access-control-item.tsx+++ b/web/app/components/app/app-access-control/access-control-item.tsx@@ -1,37 +1,26 @@'use client'-import type { FC, PropsWithChildren } from 'react'+import type { PropsWithChildren } from 'react'import type { AccessMode } from '@/models/access-control'-import useAccessControlStore from '@/context/access-control-store'+import { cn } from '@langgenius/dify-ui/cn'+import { RadioRoot } from '@langgenius/dify-ui/radio'-type AccessControlItemProps = PropsWithChildren<{+export function AccessControlItem({ type, children }: PropsWithChildren<{type: AccessMode-}>--const AccessControlItem: FC<AccessControlItemProps> = ({ type, children }) => {- const currentMenu = useAccessControlStore(s => s.currentMenu)- const setCurrentMenu = useAccessControlStore(s => s.setCurrentMenu)- if (currentMenu !== type) {- return (- <div- className="cursor-pointer rounded-[10px] border- border-components-option-card-option-border bg-components-option-card-option-bg- hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover"- onClick={() => setCurrentMenu(type)}- >- {children}- </div>- )- }-+}>) {return (- <div className="rounded-[10px] border-[1.5px]- border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg shadow-sm"+ <RadioRoot<AccessMode>+ value={type}+ variant="unstyled"+ render={<div />}+ className={cn(+ 'cursor-pointer rounded-[10px] border-[0.5px] border-components-option-card-option-border bg-components-option-card-option-bg shadow-xs transition-colors',+ 'hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover',+ 'focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',+ 'data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:ring-[0.5px] data-checked:ring-components-option-card-option-selected-border data-checked:ring-inset',+ 'data-disabled:cursor-not-allowed data-disabled:opacity-60 data-disabled:hover:border-components-option-card-option-border data-disabled:hover:bg-components-option-card-option-bg',+ )}>{children}- </div>+ </RadioRoot>)}--AccessControlItem.displayName = 'AccessControlItem'--export default AccessControlItemdiff --git a/web/app/components/app/app-access-control/access-subject-selector/add-button.tsx b/web/app/components/app/app-access-control/access-subject-selector/add-button.tsxnew file mode 100644index 00000000000..43da1de6a70--- /dev/null+++ b/web/app/components/app/app-access-control/access-subject-selector/add-button.tsx@@ -0,0 +1,208 @@+'use client'++import type { ComboboxRootChangeEventDetails } from '@langgenius/dify-ui/combobox'+import type { AccessSubjectSelectionProps } from './types'+import type {+ AccessControlGroup,+ Subject,+} from '@/models/access-control'+import {+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxInputGroup,+ ComboboxList,+ ComboboxStatus,+ ComboboxTrigger,+} from '@langgenius/dify-ui/combobox'+import { useDebounce } from 'ahooks'+import { useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import { useSearchForWhiteListCandidates } from '@/service/access-control'+import { SelectedGroupsBreadCrumb, SubjectItem } from './subject-options'+import {+ getSubjectLabel,+ getSubjectValue,+ isSameSubject,+ selectionValueToSubjects,+ subjectsToSelectionValue,+} from './utils'++type AccessSubjectAddButtonProps = AccessSubjectSelectionProps & {+ disabled?: boolean+ breadcrumbGroups?: AccessControlGroup[]+ onBreadcrumbGroupsChange?: (groups: AccessControlGroup[]) => void+}++export function AccessSubjectAddButton({+ selectedGroups,+ selectedMembers,+ onChange,+ disabled,+ breadcrumbGroups,+ onBreadcrumbGroupsChange,+}: AccessSubjectAddButtonProps) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [keyword, setKeyword] = useState('')+ const [internalBreadcrumbGroups, setInternalBreadcrumbGroups] = useState<AccessControlGroup[]>([])+ const scrollRootRef = useRef<HTMLDivElement>(null)+ const anchorRef = useRef<HTMLDivElement>(null)+ const selectedGroupsForBreadcrumb = breadcrumbGroups ?? internalBreadcrumbGroups+ const setSelectedGroupsForBreadcrumb = onBreadcrumbGroupsChange ?? setInternalBreadcrumbGroups+ const debouncedKeyword = useDebounce(keyword, { wait: 500 })++ const lastAvailableGroup = selectedGroupsForBreadcrumb[selectedGroupsForBreadcrumb.length - 1]+ const { isLoading, isFetchingNextPage, fetchNextPage, data } = useSearchForWhiteListCandidates({+ keyword: debouncedKeyword,+ groupId: lastAvailableGroup?.id,+ resultsPerPage: 10,+ }, open && !disabled)+ const pages = data?.pages ?? []+ const subjects = pages.flatMap(page => page.subjects ?? [])+ const selectedSubjects = selectionValueToSubjects({+ groups: selectedGroups,+ members: selectedMembers,+ })+ const hasResults = pages.length > 0 && subjects.length > 0+ const shouldShowBreadcrumb = hasResults || selectedGroupsForBreadcrumb.length > 0+ const hasMore = pages[pages.length - 1]?.hasMore ?? false++ useEffect(() => {+ let observer: IntersectionObserver | undefined+ if (anchorRef.current) {+ observer = new IntersectionObserver((entries) => {+ if (entries[0]!.isIntersecting && !isLoading && !isFetchingNextPage && hasMore)+ fetchNextPage()+ }, { root: scrollRootRef.current, rootMargin: '20px' })+ observer.observe(anchorRef.current)+ }+ return () => observer?.disconnect()+ }, [fetchNextPage, hasMore, isFetchingNextPage, isLoading])++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen && disabled)+ return+ if (!nextOpen)+ setKeyword('')++ setOpen(nextOpen)+ }++ const handleInputValueChange = (inputValue: string, details: ComboboxRootChangeEventDetails) => {+ if (!disabled && details.reason !== 'item-press')+ setKeyword(inputValue)+ }++ const handleValueChange = (nextSubjects: Subject[]) => {+ onChange(subjectsToSelectionValue(nextSubjects))+ }++ return (+ <Combobox<Subject, true>+ multiple+ open={open}+ value={selectedSubjects}+ inputValue={keyword}+ items={subjects}+ disabled={disabled}+ itemToStringLabel={getSubjectLabel}+ itemToStringValue={getSubjectValue}+ isItemEqualToValue={isSameSubject}+ filter={null}+ onOpenChange={handleOpenChange}+ onInputValueChange={handleInputValueChange}+ onValueChange={handleValueChange}+ >+ <ComboboxTrigger+ aria-label={t('operation.add', { ns: 'common' })}+ icon={false}+ size="small"+ disabled={disabled}+ className="h-6 w-auto min-w-[52px] shrink-0 rounded-md border-0 bg-transparent px-2 py-0 text-xs font-medium text-components-button-secondary-accent-text hover:bg-state-accent-hover focus-visible:bg-state-accent-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-accent-hover"+ >+ <span className="inline-flex min-w-0 items-center justify-center gap-x-0.5 whitespace-nowrap">+ <span className="i-ri-add-circle-fill size-4 shrink-0" aria-hidden="true" />+ <span className="shrink-0">{t('operation.add', { ns: 'common' })}</span>+ </span>+ </ComboboxTrigger>+ <ComboboxContent+ placement="bottom-end"+ alignOffset={300}+ popupClassName="relative flex max-h-[400px] w-[400px] flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-0 shadow-lg backdrop-blur-[5px]"+ >+ <div ref={scrollRootRef} className="min-h-0 overflow-y-auto">+ <div className="sticky top-0 z-10 bg-components-panel-bg-blur p-2 pb-0.5 backdrop-blur-[5px]">+ <ComboboxInputGroup className="h-8 min-h-8 px-2">+ <span className="mr-0.5 i-ri-search-line size-4 shrink-0 text-text-tertiary" aria-hidden="true" />+ <ComboboxInput+ aria-label={t('accessControlDialog.operateGroupAndMember.searchPlaceholder', { ns: 'app' })}+ placeholder={t('accessControlDialog.operateGroupAndMember.searchPlaceholder', { ns: 'app' })}+ className="block h-4.5 grow px-1 py-0 text-[13px] text-text-primary"+ />+ </ComboboxInputGroup>+ </div>+ {isLoading+ ? (+ <ComboboxStatus className="p-1">+ <SubjectOptionsSkeleton />+ </ComboboxStatus>+ )+ : (+ <>+ {shouldShowBreadcrumb && (+ <div className="flex h-7 items-center px-2 py-0.5">+ <SelectedGroupsBreadCrumb+ selectedGroupsForBreadcrumb={selectedGroupsForBreadcrumb}+ onChange={setSelectedGroupsForBreadcrumb}+ />+ </div>+ )}+ {hasResults+ ? (+ <>+ <ComboboxList className="max-h-none p-1">+ {(subject: Subject) => (+ <SubjectItem+ key={getSubjectValue(subject)}+ subject={subject}+ selectedGroups={selectedGroups}+ selectedMembers={selectedMembers}+ onExpandGroup={group => setSelectedGroupsForBreadcrumb([...selectedGroupsForBreadcrumb, group])}+ />+ )}+ </ComboboxList>+ {isFetchingNextPage && <Loading />}+ <div ref={anchorRef} className="h-0" />+ </>+ )+ : (+ <ComboboxEmpty className="flex h-7 items-center justify-center px-2 py-0.5">+ {t('accessControlDialog.operateGroupAndMember.noResult', { ns: 'app' })}+ </ComboboxEmpty>+ )}+ </>+ )}+ </div>+ </ComboboxContent>+ </Combobox>+ )+}++function SubjectOptionsSkeleton() {+ return (+ <div className="flex flex-col gap-1">+ {[0, 1, 2, 3, 4].map(index => (+ <div key={index} className="flex min-h-8 items-center gap-2 rounded-lg p-1 pl-2">+ <SkeletonRectangle className="my-0 size-4 shrink-0 animate-pulse rounded-sm" />+ <SkeletonRectangle className="my-0 size-5 shrink-0 animate-pulse rounded-full" />+ <SkeletonRectangle className="my-0 h-3.5 w-32 animate-pulse" />+ <SkeletonRectangle className="my-0 h-3 w-16 animate-pulse" />+ </div>+ ))}+ </div>+ )+}diff --git a/web/app/components/app/app-access-control/access-subject-selector/selection-list.tsx b/web/app/components/app/app-access-control/access-subject-selector/selection-list.tsxnew file mode 100644index 00000000000..4a7a545d62f--- /dev/null+++ b/web/app/components/app/app-access-control/access-subject-selector/selection-list.tsx@@ -0,0 +1,207 @@+'use client'++import type { ReactNode } from 'react'+import type { AccessSubjectSelectionProps } from './types'+import type {+ AccessControlAccount,+ AccessControlGroup,+} from '@/models/access-control'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'++type AccessSubjectSelectionListProps = AccessSubjectSelectionProps & {+ loading?: boolean+ className?: string+}++export function AccessSubjectSelectionList({+ selectedGroups,+ selectedMembers,+ onChange,+ loading,+ className,+}: AccessSubjectSelectionListProps) {+ return (+ <div className={cn('flex max-h-[400px] flex-col gap-y-2 overflow-y-auto rounded-lg bg-background-section p-2', className)}>+ {loading+ ? <AccessSubjectSelectionListSkeleton />+ : (+ <RenderGroupsAndMembers+ selectedGroups={selectedGroups}+ selectedMembers={selectedMembers}+ onChange={onChange}+ />+ )}+ </div>+ )+}++function AccessSubjectSelectionListSkeleton() {+ const { t } = useTranslation()++ return (+ <div role="status" aria-busy="true" aria-label={t('loading', { ns: 'common' })} className="flex flex-col gap-y-2">+ <SkeletonRectangle className="my-0 h-3 w-14 animate-pulse" />+ <div className="flex flex-row flex-wrap gap-1">+ {[0, 1].map(index => (+ <SelectedItemSkeleton key={index} withMeta />+ ))}+ </div>+ <SkeletonRectangle className="my-0 h-3 w-16 animate-pulse" />+ <div className="flex flex-row flex-wrap gap-1">+ {[0, 1, 2].map(index => (+ <SelectedItemSkeleton key={index} />+ ))}+ </div>+ </div>+ )+}++function SelectedItemSkeleton({ withMeta = false }: {+ withMeta?: boolean+}) {+ return (+ <div className="flex items-center gap-x-1 rounded-full border-[0.5px] border-components-panel-border-subtle bg-components-badge-white-to-dark p-1 pr-1.5 shadow-xs">+ <SkeletonRectangle className="my-0 size-5 animate-pulse rounded-full" />+ <SkeletonRectangle className="my-0 h-3 w-20 animate-pulse" />+ {withMeta && <SkeletonRectangle className="my-0 h-3 w-5 animate-pulse" />}+ <SkeletonRectangle className="my-0 size-4 animate-pulse rounded-full" />+ </div>+ )+}++function RenderGroupsAndMembers({+ selectedGroups,+ selectedMembers,+ onChange,+}: AccessSubjectSelectionProps) {+ const { t } = useTranslation()+ if (selectedGroups.length <= 0 && selectedMembers.length <= 0) {+ return (+ <div className="px-2 pt-5 pb-1.5">+ <p className="text-center system-xs-regular text-text-tertiary">+ {t('accessControlDialog.noGroupsOrMembers', { ns: 'app' })}+ </p>+ </div>+ )+ }++ return (+ <>+ <p className="sticky top-0 system-2xs-medium-uppercase text-text-tertiary">+ {t('accessControlDialog.groups', { ns: 'app', count: selectedGroups.length ?? 0 })}+ </p>+ <div className="flex flex-row flex-wrap gap-1">+ {selectedGroups.map(group => (+ <SelectedGroupItem+ key={group.id}+ group={group}+ selectedGroups={selectedGroups}+ selectedMembers={selectedMembers}+ onChange={onChange}+ />+ ))}+ </div>+ <p className="sticky top-0 system-2xs-medium-uppercase text-text-tertiary">+ {t('accessControlDialog.members', { ns: 'app', count: selectedMembers.length ?? 0 })}+ </p>+ <div className="flex flex-row flex-wrap gap-1">+ {selectedMembers.map(member => (+ <SelectedMemberItem+ key={member.id}+ member={member}+ selectedGroups={selectedGroups}+ selectedMembers={selectedMembers}+ onChange={onChange}+ />+ ))}+ </div>+ </>+ )+}++type SelectedGroupItemProps = AccessSubjectSelectionProps & {+ group: AccessControlGroup+}++function SelectedGroupItem({+ group,+ selectedGroups,+ selectedMembers,+ onChange,+}: SelectedGroupItemProps) {+ const handleRemoveGroup = () => {+ onChange({+ groups: selectedGroups.filter(selectedGroup => selectedGroup.id !== group.id),+ members: selectedMembers,+ })+ }++ return (+ <SelectedBaseItem+ icon={<span className="i-ri-organization-chart h-[14px] w-[14px] text-components-avatar-shape-fill-stop-0" aria-hidden="true" />}+ onRemove={handleRemoveGroup}+ >+ <p className="system-xs-regular text-text-primary">{group.name}</p>+ <p className="system-xs-regular text-text-tertiary">{group.groupSize}</p>+ </SelectedBaseItem>+ )+}++type SelectedMemberItemProps = AccessSubjectSelectionProps & {+ member: AccessControlAccount+}++function SelectedMemberItem({+ member,+ selectedGroups,+ selectedMembers,+ onChange,+}: SelectedMemberItemProps) {+ const handleRemoveMember = () => {+ onChange({+ groups: selectedGroups,+ members: selectedMembers.filter(selectedMember => selectedMember.id !== member.id),+ })+ }++ return (+ <SelectedBaseItem+ icon={<Avatar size="xxs" avatar={null} name={member.name} />}+ onRemove={handleRemoveMember}+ >+ <p className="system-xs-regular text-text-primary">{member.name}</p>+ </SelectedBaseItem>+ )+}++type SelectedBaseItemProps = {+ icon: ReactNode+ children: ReactNode+ onRemove?: () => void+}++function SelectedBaseItem({ icon, onRemove, children }: SelectedBaseItemProps) {+ const { t } = useTranslation()++ return (+ <div className="group flex flex-row items-center gap-x-1 rounded-full border-[0.5px] border-components-panel-border-subtle bg-components-badge-white-to-dark p-1 pr-1.5 shadow-xs">+ <div className="size-5 overflow-hidden rounded-full bg-components-icon-bg-blue-solid">+ <div className="flex size-full items-center justify-center bg-[image:var(--color-access-app-icon-mask-bg)]">+ {icon}+ </div>+ </div>+ {children}+ <button+ type="button"+ className="flex size-4 cursor-pointer items-center justify-center border-none bg-transparent p-0 focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ aria-label={t('operation.remove', { ns: 'common' })}+ onClick={onRemove}+ >+ <span className="i-ri-close-circle-fill h-[14px] w-[14px] text-text-quaternary" aria-hidden="true" />+ </button>+ </div>+ )+}diff --git a/web/app/components/app/app-access-control/access-subject-selector/subject-options.tsx b/web/app/components/app/app-access-control/access-subject-selector/subject-options.tsxnew file mode 100644index 00000000000..1a09df73636--- /dev/null+++ b/web/app/components/app/app-access-control/access-subject-selector/subject-options.tsx@@ -0,0 +1,217 @@+'use client'++import type { ReactNode } from 'react'+import type {+ AccessControlAccount,+ AccessControlGroup,+ Subject,+ SubjectAccount,+ SubjectGroup,+} from '@/models/access-control'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ ComboboxItem,+ ComboboxItemText,+} from '@langgenius/dify-ui/combobox'+import { useTranslation } from 'react-i18next'+import { useSelector } from '@/context/app-context'+import { SubjectType } from '@/models/access-control'++export function SubjectItem({+ subject,+ selectedGroups,+ selectedMembers,+ onExpandGroup,+}: {+ subject: Subject+ selectedGroups: AccessControlGroup[]+ selectedMembers: AccessControlAccount[]+ onExpandGroup: (group: AccessControlGroup) => void+}) {+ if (subject.subjectType === SubjectType.GROUP) {+ return (+ <GroupItem+ group={(subject as SubjectGroup).groupData}+ subject={subject}+ selectedGroups={selectedGroups}+ onExpandGroup={onExpandGroup}+ />+ )+ }++ return (+ <MemberItem+ member={(subject as SubjectAccount).accountData}+ subject={subject}+ selectedMembers={selectedMembers}+ />+ )+}++export function SelectedGroupsBreadCrumb({+ selectedGroupsForBreadcrumb,+ onChange,+}: {+ selectedGroupsForBreadcrumb: AccessControlGroup[]+ onChange: (groups: AccessControlGroup[]) => void+}) {+ const { t } = useTranslation()++ const handleBreadCrumbClick = (index: number) => {+ const newGroups = selectedGroupsForBreadcrumb.slice(0, index + 1)+ onChange(newGroups)+ }+ const handleReset = () => {+ onChange([])+ }+ const hasBreadcrumb = selectedGroupsForBreadcrumb.length > 0++ return (+ <div className="flex h-7 items-center gap-x-0.5 px-2 py-0.5">+ {hasBreadcrumb+ ? (+ <button+ type="button"+ className="cursor-pointer border-none bg-transparent p-0 text-left system-xs-regular text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ onClick={handleReset}+ >+ {t('accessControlDialog.operateGroupAndMember.allMembers', { ns: 'app' })}+ </button>+ )+ : (+ <span className="system-xs-regular text-text-tertiary">{t('accessControlDialog.operateGroupAndMember.allMembers', { ns: 'app' })}</span>+ )}+ {selectedGroupsForBreadcrumb.map((group, index) => {+ const isLastGroup = index === selectedGroupsForBreadcrumb.length - 1++ return (+ <div key={group.id} className="flex items-center gap-x-0.5 system-xs-regular text-text-tertiary">+ <span>/</span>+ {isLastGroup+ ? <span>{group.name}</span>+ : (+ <button+ type="button"+ className="cursor-pointer border-none bg-transparent p-0 text-left system-xs-regular text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ onClick={() => handleBreadCrumbClick(index)}+ >+ {group.name}+ </button>+ )}+ </div>+ )+ })}+ </div>+ )+}++type GroupItemProps = {+ group: AccessControlGroup+ subject: Subject+ selectedGroups: AccessControlGroup[]+ onExpandGroup: (group: AccessControlGroup) => void+}++function GroupItem({ group, subject, selectedGroups, onExpandGroup }: GroupItemProps) {+ const { t } = useTranslation()+ const isChecked = selectedGroups.some(selectedGroup => selectedGroup.id === group.id)++ return (+ <div className="flex items-center gap-2 rounded-lg hover:bg-state-base-hover">+ <ComboboxBaseItem subject={subject}>+ <SelectionBox checked={isChecked} />+ <ComboboxItemText className="flex grow items-center px-0">+ <div className="mr-2 size-5 overflow-hidden rounded-full bg-components-icon-bg-blue-solid">+ <div className="flex size-full items-center justify-center bg-[image:var(--color-access-app-icon-mask-bg)]">+ <span className="i-ri-organization-chart h-[14px] w-[14px] text-components-avatar-shape-fill-stop-0" aria-hidden="true" />+ </div>+ </div>+ <span className="mr-1 system-sm-medium text-text-secondary">{group.name}</span>+ <span className="system-xs-regular text-text-tertiary">{group.groupSize}</span>+ </ComboboxItemText>+ </ComboboxBaseItem>+ <Button+ size="small"+ disabled={isChecked}+ variant="ghost-accent"+ className="mr-1 flex shrink-0 items-center justify-between px-1.5 py-1"+ onPointerDown={event => event.preventDefault()}+ onClick={() => onExpandGroup(group)}+ >+ <span className="px-[3px]">{t('accessControlDialog.operateGroupAndMember.expand', { ns: 'app' })}</span>+ <span className="i-ri-arrow-right-s-line size-4" aria-hidden="true" />+ </Button>+ </div>+ )+}++type MemberItemProps = {+ member: AccessControlAccount+ subject: Subject+ selectedMembers: AccessControlAccount[]+}++function MemberItem({ member, subject, selectedMembers }: MemberItemProps) {+ const currentUser = useSelector(s => s.userProfile)+ const { t } = useTranslation()+ const isChecked = selectedMembers.some(selectedMember => selectedMember.id === member.id)+ return (+ <ComboboxBaseItem subject={subject} className="pr-3">+ <SelectionBox checked={isChecked} />+ <ComboboxItemText className="flex grow items-center px-0">+ <div className="mr-2 size-5 overflow-hidden rounded-full bg-components-icon-bg-blue-solid">+ <div className="flex size-full items-center justify-center bg-[image:var(--color-access-app-icon-mask-bg)]">+ <Avatar size="xxs" avatar={null} name={member.name} />+ </div>+ </div>+ <span className="mr-1 system-sm-medium text-text-secondary">{member.name}</span>+ {currentUser.email === member.email && (+ <span className="system-xs-regular text-text-tertiary">+ (+ {t('you', { ns: 'common' })}+ )+ </span>+ )}+ </ComboboxItemText>+ <span className="system-xs-regular text-text-quaternary">{member.email}</span>+ </ComboboxBaseItem>+ )+}++type ComboboxBaseItemProps = {+ className?: string+ subject: Subject+ children: ReactNode+}++function ComboboxBaseItem({ children, className, subject }: ComboboxBaseItemProps) {+ return (+ <ComboboxItem+ value={subject}+ className={cn(+ 'mx-0 flex min-h-8 grow grid-cols-none items-center gap-2 rounded-lg p-1 pl-2',+ className,+ )}+ >+ {children}+ </ComboboxItem>+ )+}++function SelectionBox({ checked }: { checked: boolean }) {+ return (+ <span+ aria-hidden="true"+ className={cn(+ 'flex size-4 shrink-0 items-center justify-center rounded-sm shadow-xs shadow-shadow-shadow-3',+ checked+ ? 'bg-components-checkbox-bg text-components-checkbox-icon'+ : 'border border-components-checkbox-border bg-components-checkbox-bg-unchecked',+ )}+ >+ {checked && <span className="i-ri-check-line size-3" />}+ </span>+ )+}diff --git a/web/app/components/app/app-access-control/access-subject-selector/types.ts b/web/app/components/app/app-access-control/access-subject-selector/types.tsnew file mode 100644index 00000000000..649b2c22df1--- /dev/null+++ b/web/app/components/app/app-access-control/access-subject-selector/types.ts@@ -0,0 +1,15 @@+import type {+ AccessControlAccount,+ AccessControlGroup,+} from '@/models/access-control'++export type AccessSubjectSelectionValue = {+ groups: AccessControlGroup[]+ members: AccessControlAccount[]+}++export type AccessSubjectSelectionProps = {+ selectedGroups: AccessControlGroup[]+ selectedMembers: AccessControlAccount[]+ onChange: (value: AccessSubjectSelectionValue) => void+}diff --git a/web/app/components/app/app-access-control/access-subject-selector/utils.ts b/web/app/components/app/app-access-control/access-subject-selector/utils.tsnew file mode 100644index 00000000000..70917bf02cf--- /dev/null+++ b/web/app/components/app/app-access-control/access-subject-selector/utils.ts@@ -0,0 +1,64 @@+import type { AccessSubjectSelectionValue } from './types'+import type {+ AccessControlAccount,+ AccessControlGroup,+ Subject,+ SubjectAccount,+ SubjectGroup,+} from '@/models/access-control'+import { SubjectType } from '@/models/access-control'++function groupToSubject(group: AccessControlGroup): SubjectGroup {+ return {+ subjectId: group.id,+ subjectType: SubjectType.GROUP,+ groupData: group,+ }+}++function memberToSubject(member: AccessControlAccount): SubjectAccount {+ return {+ subjectId: member.id,+ subjectType: SubjectType.ACCOUNT,+ accountData: member,+ }+}++export function getSubjectLabel(subject: Subject) {+ if (subject.subjectType === SubjectType.GROUP)+ return (subject as SubjectGroup).groupData.name++ return (subject as SubjectAccount).accountData.name+}++export function getSubjectValue(subject: Subject) {+ return `${subject.subjectType}:${subject.subjectId}`+}++export function isSameSubject(item: Subject, value: Subject) {+ return item.subjectId === value.subjectId && item.subjectType === value.subjectType+}++export function selectionValueToSubjects({+ groups,+ members,+}: AccessSubjectSelectionValue) {+ return [+ ...groups.map(groupToSubject),+ ...members.map(memberToSubject),+ ]+}++export function subjectsToSelectionValue(subjects: Subject[]): AccessSubjectSelectionValue {+ const groups: AccessControlGroup[] = []+ const members: AccessControlAccount[] = []++ subjects.forEach((subject) => {+ if (subject.subjectType === SubjectType.GROUP)+ groups.push((subject as SubjectGroup).groupData)+ else+ members.push((subject as SubjectAccount).accountData)+ })++ return { groups, members }+}diff --git a/web/app/components/app/app-access-control/add-member-or-group-pop.tsx b/web/app/components/app/app-access-control/add-member-or-group-pop.tsxindex 5c09699f733..c1df04d257c 100644--- a/web/app/components/app/app-access-control/add-member-or-group-pop.tsx+++ b/web/app/components/app/app-access-control/add-member-or-group-pop.tsx@@ -1,369 +1,31 @@'use client'-import type { ComboboxRootChangeEventDetails } from '@langgenius/dify-ui/combobox'-import type { AccessControlAccount, AccessControlGroup, Subject, SubjectAccount, SubjectGroup } from '@/models/access-control'-import { Avatar } from '@langgenius/dify-ui/avatar'-import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'+import {- Combobox,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxInputGroup,- ComboboxItem,- ComboboxItemText,- ComboboxList,- ComboboxStatus,- ComboboxTrigger,-} from '@langgenius/dify-ui/combobox'-import { RiAddCircleFill, RiArrowRightSLine, RiOrganizationChart } from '@remixicon/react'-import { useDebounce } from 'ahooks'-import { useEffect, useRef, useState } from 'react'-import { useTranslation } from 'react-i18next'-import { useSelector } from '@/context/app-context'-import { SubjectType } from '@/models/access-control'-import { useSearchForWhiteListCandidates } from '@/service/access-control'-import useAccessControlStore from '../../../../context/access-control-store'-import Loading from '../../base/loading'+ AccessSubjectAddButton,+} from './access-subject-selector/add-button'+import { useAccessControlStore } from './store'-export default function AddMemberOrGroupDialog() {- const { t } = useTranslation()- const [open, setOpen] = useState(false)- const [keyword, setKeyword] = useState('')- const scrollRootRef = useRef<HTMLDivElement>(null)- const anchorRef = useRef<HTMLDivElement>(null)+export function AddMemberOrGroupDialog({ disabled = false }: {+ disabled?: boolean+}) {const specificGroups = useAccessControlStore(s => s.specificGroups)const setSpecificGroups = useAccessControlStore(s => s.setSpecificGroups)const specificMembers = useAccessControlStore(s => s.specificMembers)const setSpecificMembers = useAccessControlStore(s => s.setSpecificMembers)const selectedGroupsForBreadcrumb = useAccessControlStore(s => s.selectedGroupsForBreadcrumb)- const debouncedKeyword = useDebounce(keyword, { wait: 500 })-- const lastAvailableGroup = selectedGroupsForBreadcrumb[selectedGroupsForBreadcrumb.length - 1]- const { isLoading, isFetchingNextPage, fetchNextPage, data } = useSearchForWhiteListCandidates({ keyword: debouncedKeyword, groupId: lastAvailableGroup?.id, resultsPerPage: 10 }, open)- const pages = data?.pages ?? []- const subjects = pages.flatMap(page => page.subjects ?? [])- const selectedSubjects = [- ...specificGroups.map(groupToSubject),- ...specificMembers.map(memberToSubject),- ]- const hasResults = pages.length > 0 && subjects.length > 0- const shouldShowBreadcrumb = hasResults || selectedGroupsForBreadcrumb.length > 0- const hasMore = pages[pages.length - 1]?.hasMore ?? false-- useEffect(() => {- let observer: IntersectionObserver | undefined- if (anchorRef.current) {- observer = new IntersectionObserver((entries) => {- if (entries[0]!.isIntersecting && !isLoading && hasMore)- fetchNextPage()- }, { root: scrollRootRef.current, rootMargin: '20px' })- observer.observe(anchorRef.current)- }- return () => observer?.disconnect()- }, [isLoading, fetchNextPage, hasMore])-- const handleOpenChange = (nextOpen: boolean) => {- if (!nextOpen)- setKeyword('')-- setOpen(nextOpen)- }-- const handleInputValueChange = (inputValue: string, details: ComboboxRootChangeEventDetails) => {- if (details.reason !== 'item-press')- setKeyword(inputValue)- }-- const handleValueChange = (nextSubjects: Subject[]) => {- const nextGroups: AccessControlGroup[] = []- const nextMembers: AccessControlAccount[] = []-- for (const subject of nextSubjects) {- if (subject.subjectType === SubjectType.GROUP)- nextGroups.push((subject as SubjectGroup).groupData)- else- nextMembers.push((subject as SubjectAccount).accountData)- }-- setSpecificGroups(nextGroups)- setSpecificMembers(nextMembers)- }-- return (- <Combobox<Subject, true>- multiple- open={open}- value={selectedSubjects}- inputValue={keyword}- items={subjects}- itemToStringLabel={getSubjectLabel}- itemToStringValue={getSubjectValue}- isItemEqualToValue={isSameSubject}- filter={null}- onOpenChange={handleOpenChange}- onInputValueChange={handleInputValueChange}- onValueChange={handleValueChange}- >- <ComboboxTrigger- aria-label={t('operation.add', { ns: 'common' })}- icon={false}- size="small"- className="flex h-6 w-auto shrink-0 items-center gap-x-0.5 rounded-md border-0 bg-transparent px-2 py-0 text-xs font-medium text-components-button-secondary-accent-text hover:bg-state-accent-hover focus-visible:bg-state-accent-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-accent-hover"- >- <RiAddCircleFill className="size-4" aria-hidden="true" />- <span>{t('operation.add', { ns: 'common' })}</span>- </ComboboxTrigger>- <ComboboxContent- placement="bottom-end"- alignOffset={300}- popupClassName="relative flex max-h-[400px] w-[400px] flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-0 shadow-lg backdrop-blur-[5px]"- >- <div ref={scrollRootRef} className="min-h-0 overflow-y-auto">- <div className="sticky top-0 z-10 bg-components-panel-bg-blur p-2 pb-0.5 backdrop-blur-[5px]">- <ComboboxInputGroup className="h-8 min-h-8 px-2">- <span className="mr-0.5 i-ri-search-line size-4 shrink-0 text-text-tertiary" aria-hidden="true" />- <ComboboxInput- aria-label={t('accessControlDialog.operateGroupAndMember.searchPlaceholder', { ns: 'app' })}- placeholder={t('accessControlDialog.operateGroupAndMember.searchPlaceholder', { ns: 'app' })}- className="block h-4.5 grow px-1 py-0 text-[13px] text-text-primary"- />- </ComboboxInputGroup>- </div>- {isLoading- ? (- <ComboboxStatus className="p-1">- <Loading />- </ComboboxStatus>- )- : (- <>- {shouldShowBreadcrumb && (- <div className="flex h-7 items-center px-2 py-0.5">- <SelectedGroupsBreadCrumb />- </div>- )}- {hasResults- ? (- <>- <ComboboxList className="max-h-none p-1">- {(subject: Subject) => <SubjectItem key={getSubjectValue(subject)} subject={subject} />}- </ComboboxList>- {isFetchingNextPage && <Loading />}- <div ref={anchorRef} className="h-0" />- </>- )- : (- <ComboboxEmpty className="flex h-7 items-center justify-center px-2 py-0.5">- {t('accessControlDialog.operateGroupAndMember.noResult', { ns: 'app' })}- </ComboboxEmpty>- )}- </>- )}- </div>- </ComboboxContent>- </Combobox>- )-}--function groupToSubject(group: AccessControlGroup): SubjectGroup {- return {- subjectId: group.id,- subjectType: SubjectType.GROUP,- groupData: group,- }-}--function memberToSubject(member: AccessControlAccount): SubjectAccount {- return {- subjectId: member.id,- subjectType: SubjectType.ACCOUNT,- accountData: member,- }-}--function getSubjectLabel(subject: Subject) {- if (subject.subjectType === SubjectType.GROUP)- return (subject as SubjectGroup).groupData.name-- return (subject as SubjectAccount).accountData.name-}--function getSubjectValue(subject: Subject) {- return `${subject.subjectType}:${subject.subjectId}`-}--function isSameSubject(item: Subject, value: Subject) {- return item.subjectId === value.subjectId && item.subjectType === value.subjectType-}--function SubjectItem({ subject }: { subject: Subject }) {- if (subject.subjectType === SubjectType.GROUP)- return <GroupItem group={(subject as SubjectGroup).groupData} subject={subject} />-- return <MemberItem member={(subject as SubjectAccount).accountData} subject={subject} />-}--function SelectedGroupsBreadCrumb() {- const selectedGroupsForBreadcrumb = useAccessControlStore(s => s.selectedGroupsForBreadcrumb)- const setSelectedGroupsForBreadcrumb = useAccessControlStore(s => s.setSelectedGroupsForBreadcrumb)- const { t } = useTranslation()-- const handleBreadCrumbClick = (index: number) => {- const newGroups = selectedGroupsForBreadcrumb.slice(0, index + 1)- setSelectedGroupsForBreadcrumb(newGroups)- }- const handleReset = () => {- setSelectedGroupsForBreadcrumb([])- }- const hasBreadcrumb = selectedGroupsForBreadcrumb.length > 0-- return (- <div className="flex h-7 items-center gap-x-0.5 px-2 py-0.5">- {hasBreadcrumb- ? (- <button- type="button"- className="cursor-pointer border-none bg-transparent p-0 text-left system-xs-regular text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"- onClick={handleReset}- >- {t('accessControlDialog.operateGroupAndMember.allMembers', { ns: 'app' })}- </button>- )- : (- <span className="system-xs-regular text-text-tertiary">{t('accessControlDialog.operateGroupAndMember.allMembers', { ns: 'app' })}</span>- )}- {selectedGroupsForBreadcrumb.map((group, index) => {- const isLastGroup = index === selectedGroupsForBreadcrumb.length - 1-- return (- <div key={index} className="flex items-center gap-x-0.5 system-xs-regular text-text-tertiary">- <span>/</span>- {isLastGroup- ? <span>{group.name}</span>- : (- <button- type="button"- className="cursor-pointer border-none bg-transparent p-0 text-left system-xs-regular text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"- onClick={() => handleBreadCrumbClick(index)}- >- {group.name}- </button>- )}- </div>- )- })}- </div>- )-}--type GroupItemProps = {- group: AccessControlGroup- subject: Subject-}-function GroupItem({ group, subject }: GroupItemProps) {- const { t } = useTranslation()- const specificGroups = useAccessControlStore(s => s.specificGroups)- const selectedGroupsForBreadcrumb = useAccessControlStore(s => s.selectedGroupsForBreadcrumb)const setSelectedGroupsForBreadcrumb = useAccessControlStore(s => s.setSelectedGroupsForBreadcrumb)- const isChecked = specificGroups.some(g => g.id === group.id)-- const handleExpandClick = () => {- setSelectedGroupsForBreadcrumb([...selectedGroupsForBreadcrumb, group])- }-- return (- <div className="flex items-center gap-2 rounded-lg hover:bg-state-base-hover">- <BaseItem subject={subject}>- <SelectionBox checked={isChecked} />- <ComboboxItemText className="flex grow items-center px-0">- <div className="mr-2 size-5 overflow-hidden rounded-full bg-components-icon-bg-blue-solid">- <div className="bg-access-app-icon-mask-bg flex size-full items-center justify-center">- <RiOrganizationChart className="h-[14px] w-[14px] text-components-avatar-shape-fill-stop-0" aria-hidden="true" />- </div>- </div>- <span className="mr-1 system-sm-medium text-text-secondary">{group.name}</span>- <span className="system-xs-regular text-text-tertiary">{group.groupSize}</span>- </ComboboxItemText>- </BaseItem>- <Button- size="small"- disabled={isChecked}- variant="ghost-accent"- className="mr-1 flex shrink-0 items-center justify-between px-1.5 py-1"- onPointerDown={event => event.preventDefault()}- onClick={handleExpandClick}- >- <span className="px-[3px]">{t('accessControlDialog.operateGroupAndMember.expand', { ns: 'app' })}</span>- <RiArrowRightSLine className="size-4" aria-hidden="true" />- </Button>- </div>- )-}--type MemberItemProps = {- member: AccessControlAccount- subject: Subject-}-function MemberItem({ member, subject }: MemberItemProps) {- const currentUser = useSelector(s => s.userProfile)- const { t } = useTranslation()- const specificMembers = useAccessControlStore(s => s.specificMembers)- const isChecked = specificMembers.some(m => m.id === member.id)- return (- <BaseItem subject={subject} className="pr-3">- <SelectionBox checked={isChecked} />- <ComboboxItemText className="flex grow items-center px-0">- <div className="mr-2 size-5 overflow-hidden rounded-full bg-components-icon-bg-blue-solid">- <div className="bg-access-app-icon-mask-bg flex size-full items-center justify-center">- <Avatar size="xxs" avatar={null} name={member.name} />- </div>- </div>- <span className="mr-1 system-sm-medium text-text-secondary">{member.name}</span>- {currentUser.email === member.email && (- <span className="system-xs-regular text-text-tertiary">- (- {t('you', { ns: 'common' })}- )- </span>- )}- </ComboboxItemText>- <span className="system-xs-regular text-text-quaternary">{member.email}</span>- </BaseItem>- )-}--type BaseItemProps = {- className?: string- subject: Subject- children: React.ReactNode-}-function BaseItem({ children, className, subject }: BaseItemProps) {- return (- <ComboboxItem- value={subject}- className={cn(- 'mx-0 flex min-h-8 grow grid-cols-none items-center gap-2 rounded-lg p-1 pl-2',- className,- )}- >- {children}- </ComboboxItem>- )-}-function SelectionBox({ checked }: { checked: boolean }) {return (- <span- aria-hidden="true"- className={cn(- 'flex size-4 shrink-0 items-center justify-center rounded-sm shadow-xs shadow-shadow-shadow-3',- checked- ? 'bg-components-checkbox-bg text-components-checkbox-icon'- : 'border border-components-checkbox-border bg-components-checkbox-bg-unchecked',- )}- >- {checked && <span className="i-ri-check-line size-3" />}- </span>+ <AccessSubjectAddButton+ selectedGroups={specificGroups}+ selectedMembers={specificMembers}+ disabled={disabled}+ breadcrumbGroups={selectedGroupsForBreadcrumb}+ onBreadcrumbGroupsChange={setSelectedGroupsForBreadcrumb}+ onChange={({ groups, members }) => {+ setSpecificGroups(groups)+ setSpecificMembers(members)+ }}+ />)}diff --git a/web/app/components/app/app-access-control/index.tsx b/web/app/components/app/app-access-control/index.tsxindex 1deb0fa2108..d07e6b1b7d7 100644--- a/web/app/components/app/app-access-control/index.tsx+++ b/web/app/components/app/app-access-control/index.tsx@@ -1,20 +1,18 @@'use client'-import type { Subject } from '@/models/access-control'+import type { Subject as EnterpriseSubject } from '@dify/contracts/enterprise/types.gen'import type { App } from '@/types/app'-import { Button } from '@langgenius/dify-ui/button'-import { DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { SubjectType as EnterpriseSubjectType } from '@dify/contracts/enterprise/types.gen'import { toast } from '@langgenius/dify-ui/toast'-import { RiBuildingLine, RiGlobalLine, RiVerifiedBadgeLine } from '@remixicon/react'-import { useSuspenseQuery } from '@tanstack/react-query'-import { useCallback, useEffect } from 'react'+import { useMutation, useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { AccessMode, SubjectType } from '@/models/access-control'-import { useUpdateAccessMode } from '@/service/access-control'-import useAccessControlStore from '../../../../context/access-control-store'-import AccessControlDialog from './access-control-dialog'-import AccessControlItem from './access-control-item'-import SpecificGroupsOrMembers, { WebAppSSONotEnabledTip } from './specific-groups-or-members'+import { AccessMode } from '@/models/access-control'+import { useAppWhiteListSubjects } from '@/service/access-control'+import { consoleQuery } from '@/service/client'+import { AccessControlDialog } from './access-control-dialog'+import { AccessControlDialogContent } from './access-control-dialog-content'+import { useAccessControlStore } from './store'+import { AccessControlDraftProvider } from './store-provider'type AccessControlProps = {app: App@@ -22,92 +20,113 @@ type AccessControlProps = {onConfirm?: () => void}-export default function AccessControl(props: AccessControlProps) {+export function AccessControl(props: AccessControlProps) {const { app, onClose, onConfirm } = propsconst { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const setAppId = useAccessControlStore(s => s.setAppId)- const specificGroups = useAccessControlStore(s => s.specificGroups)- const specificMembers = useAccessControlStore(s => s.specificMembers)- const currentMenu = useAccessControlStore(s => s.currentMenu)- const setCurrentMenu = useAccessControlStore(s => s.setCurrentMenu)- const hideTip = systemFeatures.webapp_auth.enabled+ const hideExternalTip = systemFeatures.webapp_auth.enabled&& (systemFeatures.webapp_auth.allow_sso|| systemFeatures.webapp_auth.allow_email_password_login|| systemFeatures.webapp_auth.allow_email_code_login)+ const initialAccessMode = app.access_mode ?? AccessMode.SPECIFIC_GROUPS_MEMBERS+ const whiteListSubjectsQuery = useAppWhiteListSubjects(+ app.id,+ initialAccessMode === AccessMode.SPECIFIC_GROUPS_MEMBERS,+ )+ const initialSpecificGroups = whiteListSubjectsQuery.data?.groups ?? []+ const initialSpecificMembers = whiteListSubjectsQuery.data?.members ?? []+ const draftKey = [+ app.id,+ initialAccessMode,+ initialSpecificGroups.map(group => group.id).join(','),+ initialSpecificMembers.map(member => member.id).join(','),+ ].join(':')- useEffect(() => {- setAppId(app.id)- setCurrentMenu(app.access_mode ?? AccessMode.SPECIFIC_GROUPS_MEMBERS)- }, [app, setAppId, setCurrentMenu])+ return (+ <AccessControlDraftProvider+ draftKey={draftKey}+ initialDraft={{+ appId: app.id,+ currentMenu: initialAccessMode,+ specificGroups: initialSpecificGroups,+ specificMembers: initialSpecificMembers,+ selectedGroupsForBreadcrumb: [],+ }}+ >+ <AccessControlForm+ app={app}+ hideExternalTip={hideExternalTip}+ subjectsLoading={initialAccessMode === AccessMode.SPECIFIC_GROUPS_MEMBERS && whiteListSubjectsQuery.isPending}+ onClose={onClose}+ onConfirm={onConfirm}+ successMessage={t('accessControlDialog.updateSuccess', { ns: 'app' })}+ />+ </AccessControlDraftProvider>+ )+}- const { isPending, mutateAsync: updateAccessMode } = useUpdateAccessMode()- const handleConfirm = useCallback(async () => {+function AccessControlForm({+ app,+ hideExternalTip,+ subjectsLoading,+ successMessage,+ onClose,+ onConfirm,+}: {+ app: App+ hideExternalTip: boolean+ subjectsLoading: boolean+ successMessage: string+ onClose: () => void+ onConfirm?: () => void+}) {+ const specificGroups = useAccessControlStore(s => s.specificGroups)+ const specificMembers = useAccessControlStore(s => s.specificMembers)+ const currentMenu = useAccessControlStore(s => s.currentMenu)+ const { isPending, mutate: updateAccessMode } = useMutation(consoleQuery.explore.updateAppAccessMode.mutationOptions())++ function handleConfirm() {const submitData: {appId: stringaccessMode: AccessMode- subjects?: Pick<Subject, 'subjectId' | 'subjectType'>[]+ subjects?: Pick<EnterpriseSubject, 'subjectId' | 'subjectType'>[]} = { appId: app.id, accessMode: currentMenu }if (currentMenu === AccessMode.SPECIFIC_GROUPS_MEMBERS) {- const subjects: Pick<Subject, 'subjectId' | 'subjectType'>[] = []+ const subjects: Pick<EnterpriseSubject, 'subjectId' | 'subjectType'>[] = []specificGroups.forEach((group) => {- subjects.push({ subjectId: group.id, subjectType: SubjectType.GROUP })+ subjects.push({ subjectId: group.id, subjectType: EnterpriseSubjectType.SUBJECT_TYPE_GROUP })})specificMembers.forEach((member) => {subjects.push({subjectId: member.id,- subjectType: SubjectType.ACCOUNT,+ subjectType: EnterpriseSubjectType.SUBJECT_TYPE_ACCOUNT,})})submitData.subjects = subjects}- await updateAccessMode(submitData)- toast.success(t('accessControlDialog.updateSuccess', { ns: 'app' }))- onConfirm?.()- }, [updateAccessMode, app, specificGroups, specificMembers, t, onConfirm, currentMenu])+ updateAccessMode({+ body: submitData,+ }, {+ onSuccess: () => {+ toast.success(successMessage)+ onConfirm?.()+ },+ })+ }+return (<AccessControlDialog show onClose={onClose}>- <div className="flex flex-col gap-y-3">- <div className="pt-6 pr-14 pb-3 pl-6">- <DialogTitle className="title-2xl-semi-bold text-text-primary">{t('accessControlDialog.title', { ns: 'app' })}</DialogTitle>- <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">{t('accessControlDialog.description', { ns: 'app' })}</DialogDescription>- </div>- <div className="flex flex-col gap-y-1 px-6 pb-3">- <div className="leading-6">- <p className="system-sm-medium text-text-tertiary">{t('accessControlDialog.accessLabel', { ns: 'app' })}</p>- </div>- <AccessControlItem type={AccessMode.ORGANIZATION}>- <div className="flex items-center p-3">- <div className="flex grow items-center gap-x-2">- <RiBuildingLine className="size-4 text-text-primary" />- <p className="system-sm-medium text-text-primary">{t('accessControlDialog.accessItems.organization', { ns: 'app' })}</p>- </div>- </div>- </AccessControlItem>- <AccessControlItem type={AccessMode.SPECIFIC_GROUPS_MEMBERS}>- <SpecificGroupsOrMembers />- </AccessControlItem>- <AccessControlItem type={AccessMode.EXTERNAL_MEMBERS}>- <div className="flex items-center p-3">- <div className="flex grow items-center gap-x-2">- <RiVerifiedBadgeLine className="size-4 text-text-primary" />- <p className="system-sm-medium text-text-primary">{t('accessControlDialog.accessItems.external', { ns: 'app' })}</p>- </div>- {!hideTip && <WebAppSSONotEnabledTip />}- </div>- </AccessControlItem>- <AccessControlItem type={AccessMode.PUBLIC}>- <div className="flex items-center gap-x-2 p-3">- <RiGlobalLine className="size-4 text-text-primary" />- <p className="system-sm-medium text-text-primary">{t('accessControlDialog.accessItems.anyone', { ns: 'app' })}</p>- </div>- </AccessControlItem>- </div>- <div className="flex items-center justify-end gap-x-2 p-6 pt-5">- <Button onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>- <Button disabled={isPending} loading={isPending} variant="primary" onClick={handleConfirm}>{t('operation.confirm', { ns: 'common' })}</Button>- </div>- </div>+ <AccessControlDialogContent+ hideExternalTip={hideExternalTip}+ saving={isPending}+ controlsDisabled={subjectsLoading || isPending}+ confirmDisabled={subjectsLoading}+ specificGroupsOrMembersProps={{+ loading: subjectsLoading,+ }}+ onClose={onClose}+ onConfirm={handleConfirm}+ /></AccessControlDialog>)}diff --git a/web/app/components/app/app-access-control/specific-groups-or-members.tsx b/web/app/components/app/app-access-control/specific-groups-or-members.tsxindex 982a018930c..4ccac83a1d3 100644--- a/web/app/components/app/app-access-control/specific-groups-or-members.tsx+++ b/web/app/components/app/app-access-control/specific-groups-or-members.tsx@@ -1,34 +1,30 @@'use client'-import type { AccessControlAccount, AccessControlGroup } from '@/models/access-control'-import { Avatar } from '@langgenius/dify-ui/avatar'-import { RiCloseCircleFill, RiLockLine, RiOrganizationChart } from '@remixicon/react'-import { useCallback, useEffect } from 'react'import { useTranslation } from 'react-i18next'import { AccessMode } from '@/models/access-control'-import { useAppWhiteListSubjects } from '@/service/access-control'-import useAccessControlStore from '../../../../context/access-control-store'import { Infotip } from '../../base/infotip'-import Loading from '../../base/loading'-import AddMemberOrGroupDialog from './add-member-or-group-pop'+import { AccessSubjectSelectionList } from './access-subject-selector/selection-list'+import { AddMemberOrGroupDialog } from './add-member-or-group-pop'+import { useAccessControlStore } from './store'-export default function SpecificGroupsOrMembers() {+export type SpecificGroupsOrMembersProps = {+ loading?: boolean+}++export function SpecificGroupsOrMembers({+ loading = false,+}: SpecificGroupsOrMembersProps) {const currentMenu = useAccessControlStore(s => s.currentMenu)- const appId = useAccessControlStore(s => s.appId)+ const specificGroups = useAccessControlStore(s => s.specificGroups)const setSpecificGroups = useAccessControlStore(s => s.setSpecificGroups)+ const specificMembers = useAccessControlStore(s => s.specificMembers)const setSpecificMembers = useAccessControlStore(s => s.setSpecificMembers)const { t } = useTranslation()- const { isPending, data } = useAppWhiteListSubjects(appId, Boolean(appId) && currentMenu === AccessMode.SPECIFIC_GROUPS_MEMBERS)- useEffect(() => {- setSpecificGroups(data?.groups ?? [])- setSpecificMembers(data?.members ?? [])- }, [data, setSpecificGroups, setSpecificMembers])-if (currentMenu !== AccessMode.SPECIFIC_GROUPS_MEMBERS) {return (<div className="flex items-center p-3"><div className="flex grow items-center gap-x-2">- <RiLockLine className="size-4 text-text-primary" />+ <span className="i-ri-lock-line size-4 text-text-primary" aria-hidden="true" /><p className="system-sm-medium text-text-primary">{t('accessControlDialog.accessItems.specific', { ns: 'app' })}</p></div></div>@@ -39,105 +35,24 @@ export default function SpecificGroupsOrMembers() {<div><div className="flex items-center gap-x-1 p-3"><div className="flex grow items-center gap-x-1">- <RiLockLine className="size-4 text-text-primary" />+ <span className="i-ri-lock-line size-4 text-text-primary" aria-hidden="true" /><p className="system-sm-medium text-text-primary">{t('accessControlDialog.accessItems.specific', { ns: 'app' })}</p></div><div className="flex items-center gap-x-1">- <AddMemberOrGroupDialog />+ <AddMemberOrGroupDialog disabled={loading} /></div></div><div className="px-1 pb-1">- <div className="flex max-h-[400px] flex-col gap-y-2 overflow-y-auto rounded-lg bg-background-section p-2">- {isPending ? <Loading /> : <RenderGroupsAndMembers />}- </div>- </div>- </div>- )-}--function RenderGroupsAndMembers() {- const { t } = useTranslation()- const specificGroups = useAccessControlStore(s => s.specificGroups)- const specificMembers = useAccessControlStore(s => s.specificMembers)- if (specificGroups.length <= 0 && specificMembers.length <= 0)- return <div className="px-2 pt-5 pb-1.5"><p className="text-center system-xs-regular text-text-tertiary">{t('accessControlDialog.noGroupsOrMembers', { ns: 'app' })}</p></div>- return (- <>- <p className="sticky top-0 system-2xs-medium-uppercase text-text-tertiary">{t('accessControlDialog.groups', { ns: 'app', count: specificGroups.length ?? 0 })}</p>- <div className="flex flex-row flex-wrap gap-1">- {specificGroups.map((group, index) => <GroupItem key={index} group={group} />)}- </div>- <p className="sticky top-0 system-2xs-medium-uppercase text-text-tertiary">{t('accessControlDialog.members', { ns: 'app', count: specificMembers.length ?? 0 })}</p>- <div className="flex flex-row flex-wrap gap-1">- {specificMembers.map((member, index) => <MemberItem key={index} member={member} />)}- </div>- </>- )-}--type GroupItemProps = {- group: AccessControlGroup-}-function GroupItem({ group }: GroupItemProps) {- const specificGroups = useAccessControlStore(s => s.specificGroups)- const setSpecificGroups = useAccessControlStore(s => s.setSpecificGroups)- const handleRemoveGroup = useCallback(() => {- setSpecificGroups(specificGroups.filter(g => g.id !== group.id))- }, [group, setSpecificGroups, specificGroups])- return (- <BaseItem- icon={<RiOrganizationChart className="h-[14px] w-[14px] text-components-avatar-shape-fill-stop-0" />}- onRemove={handleRemoveGroup}- >- <p className="system-xs-regular text-text-primary">{group.name}</p>- <p className="system-xs-regular text-text-tertiary">{group.groupSize}</p>- </BaseItem>- )-}--type MemberItemProps = {- member: AccessControlAccount-}-function MemberItem({ member }: MemberItemProps) {- const specificMembers = useAccessControlStore(s => s.specificMembers)- const setSpecificMembers = useAccessControlStore(s => s.setSpecificMembers)- const handleRemoveMember = useCallback(() => {- setSpecificMembers(specificMembers.filter(m => m.id !== member.id))- }, [member, setSpecificMembers, specificMembers])- return (- <BaseItem- icon={<Avatar size="xxs" avatar={null} name={member.name} />}- onRemove={handleRemoveMember}- >- <p className="system-xs-regular text-text-primary">{member.name}</p>- </BaseItem>- )-}--type BaseItemProps = {- icon: React.ReactNode- children: React.ReactNode- onRemove?: () => void-}-function BaseItem({ icon, onRemove, children }: BaseItemProps) {- const { t } = useTranslation()-- return (- <div className="group flex flex-row items-center gap-x-1 rounded-full border-[0.5px] border-components-panel-border-subtle bg-components-badge-white-to-dark p-1 pr-1.5 shadow-xs">- <div className="size-5 overflow-hidden rounded-full bg-components-icon-bg-blue-solid">- <div className="bg-access-app-icon-mask-bg flex size-full items-center justify-center">- {icon}- </div>+ <AccessSubjectSelectionList+ selectedGroups={specificGroups}+ selectedMembers={specificMembers}+ loading={loading}+ onChange={({ groups, members }) => {+ setSpecificGroups(groups)+ setSpecificMembers(members)+ }}+ /></div>- {children}- <button- type="button"- className="flex size-4 cursor-pointer items-center justify-center border-none bg-transparent p-0 focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"- aria-label={t('operation.remove', { ns: 'common' })}- onClick={onRemove}- >- <RiCloseCircleFill className="h-[14px] w-[14px] text-text-quaternary" aria-hidden="true" />- </button></div>)}diff --git a/web/app/components/app/app-access-control/store-provider.tsx b/web/app/components/app/app-access-control/store-provider.tsxnew file mode 100644index 00000000000..7b8563289b1--- /dev/null+++ b/web/app/components/app/app-access-control/store-provider.tsx@@ -0,0 +1,34 @@+'use client'++import type { ReactNode } from 'react'+import type { AccessControlDraft, AccessControlStoreApi } from './store'+import { useRef } from 'react'+import { AccessControlStoreContext, createAccessControlStore } from './store'++export function AccessControlDraftProvider({+ children,+ draftKey,+ initialDraft,+}: {+ children?: ReactNode+ draftKey: string+ initialDraft: AccessControlDraft+}) {+ const storeRef = useRef<{+ draftKey: string+ store: AccessControlStoreApi+ } | undefined>(undefined)++ if (!storeRef.current || storeRef.current.draftKey !== draftKey) {+ storeRef.current = {+ draftKey,+ store: createAccessControlStore(initialDraft),+ }+ }++ return (+ <AccessControlStoreContext value={storeRef.current.store}>+ {children}+ </AccessControlStoreContext>+ )+}diff --git a/web/app/components/app/app-access-control/store.ts b/web/app/components/app/app-access-control/store.tsnew file mode 100644index 00000000000..7b863c2f93c--- /dev/null+++ b/web/app/components/app/app-access-control/store.ts@@ -0,0 +1,52 @@+import type { StoreApi } from 'zustand'+import type { AccessControlAccount, AccessControlGroup, AccessMode } from '@/models/access-control'+import type { App } from '@/types/app'+import { createContext, use } from 'react'+import { useStore } from 'zustand'+import { createStore } from 'zustand/vanilla'++export type AccessControlDraft = {+ appId?: App['id']+ currentMenu: AccessMode+ specificGroups?: AccessControlGroup[]+ specificMembers?: AccessControlAccount[]+ selectedGroupsForBreadcrumb?: AccessControlGroup[]+}++export type AccessControlStore = {+ appId: App['id']+ specificGroups: AccessControlGroup[]+ setSpecificGroups: (specificGroups: AccessControlGroup[]) => void+ specificMembers: AccessControlAccount[]+ setSpecificMembers: (specificMembers: AccessControlAccount[]) => void+ currentMenu: AccessMode+ setCurrentMenu: (currentMenu: AccessMode) => void+ selectedGroupsForBreadcrumb: AccessControlGroup[]+ setSelectedGroupsForBreadcrumb: (selectedGroupsForBreadcrumb: AccessControlGroup[]) => void+}++export type AccessControlStoreApi = StoreApi<AccessControlStore>++export function createAccessControlStore(initialDraft: AccessControlDraft) {+ return createStore<AccessControlStore>(set => ({+ appId: initialDraft.appId ?? '',+ specificGroups: initialDraft.specificGroups ?? [],+ setSpecificGroups: specificGroups => set({ specificGroups }),+ specificMembers: initialDraft.specificMembers ?? [],+ setSpecificMembers: specificMembers => set({ specificMembers }),+ currentMenu: initialDraft.currentMenu,+ setCurrentMenu: currentMenu => set({ currentMenu }),+ selectedGroupsForBreadcrumb: initialDraft.selectedGroupsForBreadcrumb ?? [],+ setSelectedGroupsForBreadcrumb: selectedGroupsForBreadcrumb => set({ selectedGroupsForBreadcrumb }),+ }))+}++export const AccessControlStoreContext = createContext<AccessControlStoreApi | undefined>(undefined)++export function useAccessControlStore<T>(selector: (state: AccessControlStore) => T) {+ const store = use(AccessControlStoreContext)+ if (!store)+ throw new Error('useAccessControlStore must be used inside AccessControlDraftProvider')++ return useStore(store, selector)+}diff --git a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsxindex e9e54d11068..5c4d8a22c16 100644--- a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx@@ -39,7 +39,7 @@ vi.mock('react-i18next', () => ({}))vi.mock('@/app/components/app/app-publisher', () => ({- default: (props: Record<string, any>) => {+ AppPublisher: (props: Record<string, any>) => {mockAppPublisherProps.current = propsreturn (<div>diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsxindex e8f617e049a..f918b28a898 100644--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx@@ -5,7 +5,7 @@ import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-featuresimport { AccessMode } from '@/models/access-control'import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'-import AppPublisher from '../index'+import { AppPublisher } from '../index'const render = (ui: React.ReactElement) => renderWithSystemFeatures(ui, {systemFeatures: { webapp_auth: { enabled: true } },@@ -16,6 +16,7 @@ const mockOnToggle = vi.fn()const mockSetAppDetail = vi.fn()const mockTrackEvent = vi.fn()const mockRefetch = vi.fn()+const mockUseGetUserCanAccessApp = vi.fn()const mockOpenAsyncWindow = vi.fn()const mockFetchInstalledAppList = vi.fn()const mockFetchAppDetailDirect = vi.fn()@@ -65,11 +66,14 @@ vi.mock('@/hooks/use-async-window-open', () => ({}))vi.mock('@/service/access-control', () => ({- useGetUserCanAccessApp: () => ({- data: { result: true },- isLoading: false,- refetch: mockRefetch,- }),+ useGetUserCanAccessApp: (params: unknown) => {+ mockUseGetUserCanAccessApp(params)+ return {+ data: { result: true },+ isLoading: false,+ refetch: mockRefetch,+ }+ },useAppWhiteListSubjects: () => ({data: { groups: [], members: [] },isLoading: false,@@ -128,7 +132,7 @@ vi.mock('@/app/components/app/overview/embedded', () => ({}))vi.mock('../../app-access-control', () => ({- default: ({ onConfirm, onClose }: { onConfirm: () => Promise<void>, onClose: () => void }) => (+ AccessControl: ({ onConfirm, onClose }: { onConfirm: () => Promise<void>, onClose: () => void }) => (<div data-testid="access-control"><button onClick={() => void onConfirm()}>confirm-access-control</button><button onClick={onClose}>close-access-control</button>@@ -212,7 +216,7 @@ describe('AppPublisher', () => {})})- it('should open the publish popover and refetch access permission data', async () => {+ it('should enable access permission query when the publish popover opens', async () => {render(<AppPublisherpublishedAt={Date.now()}@@ -226,8 +230,12 @@ describe('AppPublisher', () => {expect(mockOnToggle).toHaveBeenCalledWith(true)await waitFor(() => {- expect(mockRefetch).toHaveBeenCalledTimes(1)+ expect(mockUseGetUserCanAccessApp).toHaveBeenCalledWith({+ appId: 'app-1',+ enabled: true,+ })})+ expect(mockRefetch).not.toHaveBeenCalled()})it('should publish and track the publish event', async () => {diff --git a/web/app/components/app/app-publisher/features-wrapper.tsx b/web/app/components/app/app-publisher/features-wrapper.tsxindex 3189eb89908..b26f6ebf799 100644--- a/web/app/components/app/app-publisher/features-wrapper.tsx+++ b/web/app/components/app/app-publisher/features-wrapper.tsx@@ -14,7 +14,7 @@ import { produce } from 'immer'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import AppPublisher from '@/app/components/app/app-publisher'+import { AppPublisher } from '@/app/components/app/app-publisher'import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'import { SupportUploadFileTypes } from '@/app/components/workflow/types'diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex de5b1a9a4af..961c33cf72f 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -10,12 +10,8 @@ import { toast } from '@langgenius/dify-ui/toast'import { useHotkey } from '@tanstack/react-hotkeys'import { useSuspenseQuery } from '@tanstack/react-query'import {-- memo,use,- useCallback,useEffect,- useMemo,useState,} from 'react'import { useTranslation } from 'react-i18next'@@ -47,7 +43,7 @@ import { useInvalidateAppWorkflow } from '@/service/use-workflow'import { fetchPublishedWorkflow } from '@/service/workflow'import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'-import AccessControl from '../app-access-control'+import { AccessControl } from '../app-access-control'import {PublisherAccessSection,PublisherActionsSection,@@ -94,7 +90,7 @@ type AppPublisherPublishHandlertype AppPublisherRestoreHandler = () => Promise<unknown> | unknown-const AppPublisher = ({+export function AppPublisher({disabled = false,publishDisabled = false,publishedAt,@@ -114,7 +110,7 @@ const AppPublisher = ({hasTriggerNode = false,startNodeLimitExceeded = false,hasHumanInputNode = false,-}: AppPublisherProps) => {+}: AppPublisherProps) {const { t } = useTranslation()const [published, setPublished] = useState(false)@@ -137,50 +133,37 @@ const AppPublisher = ({const appURL = getPublisherAppUrl({ appBaseUrl: appBaseURL, accessToken, mode: appDetail?.mode })const isChatApp = [AppModeEnum.CHAT, AppModeEnum.AGENT_CHAT, AppModeEnum.COMPLETION].includes(appDetail?.mode || AppModeEnum.CHAT)- const hiddenLaunchVariables = useMemo<WorkflowHiddenStartVariable[]>(- () => (inputs ?? []).filter(input => input.hide === true),- [inputs],- )- const supportedWorkflowLaunchVariables = useMemo(- () => hiddenLaunchVariables.filter(isWorkflowLaunchInputSupported),- [hiddenLaunchVariables],- )- const unsupportedWorkflowLaunchVariables = useMemo(- () => hiddenLaunchVariables.filter(variable => !isWorkflowLaunchInputSupported(variable)),- [hiddenLaunchVariables],- )- const initialWorkflowLaunchValues = useMemo(- () => createWorkflowLaunchInitialValues(supportedWorkflowLaunchVariables),- [supportedWorkflowLaunchVariables],- )-- const { data: userCanAccessApp, isLoading: isGettingUserCanAccessApp, refetch } = useGetUserCanAccessApp({ appId: appDetail?.id, enabled: false })+ const hiddenLaunchVariables: WorkflowHiddenStartVariable[] = (inputs ?? []).filter(input => input.hide === true)+ const supportedWorkflowLaunchVariables = hiddenLaunchVariables.filter(isWorkflowLaunchInputSupported)+ const unsupportedWorkflowLaunchVariables = hiddenLaunchVariables.filter(variable => !isWorkflowLaunchInputSupported(variable))+ const initialWorkflowLaunchValues = createWorkflowLaunchInitialValues(supportedWorkflowLaunchVariables)++ const shouldLoadUserCanAccessApp = Boolean(appDetail?.id && open && systemFeatures.webapp_auth.enabled)+ const { data: userCanAccessApp, isLoading: isGettingUserCanAccessApp } = useGetUserCanAccessApp({+ appId: appDetail?.id,+ enabled: shouldLoadUserCanAccessApp,+ })const { data: appAccessSubjects, isLoading: isGettingAppWhiteListSubjects } = useAppWhiteListSubjects(appDetail?.id, open && systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS)const invalidateAppWorkflow = useInvalidateAppWorkflow()const openAsyncWindow = useAsyncWindowOpen()- const isAppAccessSet = useMemo(() => isPublisherAccessConfigured(appDetail, appAccessSubjects), [appAccessSubjects, appDetail])+ const isAppAccessSet = isPublisherAccessConfigured(appDetail, appAccessSubjects)- const noAccessPermission = useMemo(() => Boolean(+ const noAccessPermission = Boolean(systemFeatures.webapp_auth.enabled&& appDetail&& appDetail.access_mode !== AccessMode.EXTERNAL_MEMBERS&& !userCanAccessApp?.result,- ), [systemFeatures, appDetail, userCanAccessApp])- const disabledFunctionButton = useMemo(() => (!publishedAt || missingStartNode || noAccessPermission), [publishedAt, missingStartNode, noAccessPermission])- const disabledFunctionTooltip = useMemo(() => getDisabledFunctionTooltip({+ )+ const disabledFunctionButton = !publishedAt || missingStartNode || noAccessPermission+ const disabledFunctionTooltip = getDisabledFunctionTooltip({t,publishedAt,missingStartNode,noAccessPermission,- }), [missingStartNode, noAccessPermission, publishedAt, t])-- useEffect(() => {- if (systemFeatures.webapp_auth.enabled && open && appDetail)- refetch()- }, [open, appDetail, refetch, systemFeatures])+ })- const handlePublish = useCallback(async (params?: ModelAndParameter | PublishWorkflowParams) => {+ async function handlePublish(params?: ModelAndParameter | PublishWorkflowParams) {try {await onPublish?.(params)setPublished(true)@@ -212,17 +195,17 @@ const AppPublisher = ({console.warn('[app-publisher] publish failed', error)setPublished(false)}- }, [appDetail, onPublish, invalidateAppWorkflow])+ }- const handleRestore = useCallback(async () => {+ async function handleRestore() {try {await onRestore?.()setOpen(false)}catch { }- }, [onRestore])+ }- const handleOpenChange = useCallback((nextOpen: boolean) => {+ function handleOpenChange(nextOpen: boolean) {if (disabled) {setOpen(false)return@@ -233,9 +216,9 @@ const AppPublisher = ({if (nextOpen)setPublished(false)- }, [disabled, onToggle])+ }- const handleOpenInExplore = useCallback(async () => {+ async function handleOpenInExplore() {await openAsyncWindow(async () => {if (!appDetail?.id)throw new Error('App not found')@@ -248,9 +231,9 @@ const AppPublisher = ({toast.error(`${err.message || err}`)},})- }, [appDetail?.id, openAsyncWindow])+ }- const handleAccessControlUpdate = useCallback(async () => {+ async function handleAccessControlUpdate() {if (!appDetail)returntry {@@ -260,22 +243,22 @@ const AppPublisher = ({finally {setShowAppAccessControl(false)}- }, [appDetail, setAppDetail])+ }- const handleOpenWorkflowLaunchDialog = useCallback((targetUrl: string) => {+ function handleOpenWorkflowLaunchDialog(targetUrl: string) {setWorkflowLaunchValues(initialWorkflowLaunchValues)setWorkflowLaunchTargetUrl(targetUrl)setWorkflowLaunchDialogOpen(true)- }, [initialWorkflowLaunchValues])+ }- const handleWorkflowLaunchValueChange = useCallback((variable: string, value: WorkflowLaunchInputValue) => {+ function handleWorkflowLaunchValueChange(variable: string, value: WorkflowLaunchInputValue) {setWorkflowLaunchValues(prev => ({...prev,[variable]: value,}))- }, [])+ }- const handleWorkflowLaunchConfirm = useCallback(async (event: FormEvent<HTMLFormElement>) => {+ async function handleWorkflowLaunchConfirm(event: FormEvent<HTMLFormElement>) {event.preventDefault()const targetUrl = await buildWorkflowLaunchUrl({@@ -286,8 +269,9 @@ const AppPublisher = ({window.open(targetUrl, '_blank')setWorkflowLaunchDialogOpen(false)- }, [supportedWorkflowLaunchVariables, workflowLaunchTargetUrl, workflowLaunchValues])- const handlePublishToMarketplace = useCallback(async () => {+ }++ async function handlePublishToMarketplace() {if (!appDetail?.id || publishingToMarketplace)returnsetPublishingToMarketplace(true)@@ -302,7 +286,7 @@ const AppPublisher = ({finally {setPublishingToMarketplace(false)}- }, [appDetail?.id, publishingToMarketplace, t])+ }useHotkey('Mod+Shift+P', (e) => {e.preventDefault()@@ -340,11 +324,13 @@ const AppPublisher = ({: undefinedconst workflowToolVisible = appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNodeconst workflowToolPublished = !!toolPublished- const closeWorkflowToolDrawer = useCallback(() => setWorkflowToolDrawerOpen(false), [])- const workflowToolIcon = useMemo(() => ({+ function closeWorkflowToolDrawer() {+ setWorkflowToolDrawerOpen(false)+ }+ const workflowToolIcon = {content: (appDetail?.icon_type === 'image' ? '🤖' : appDetail?.icon) || '🤖',background: (appDetail?.icon_type === 'image' ? appDefaultIconBackground : appDetail?.icon_background) || appDefaultIconBackground,- }), [appDetail?.icon, appDetail?.icon_background, appDetail?.icon_type])+ }const workflowTool = useConfigureButton({enabled: workflowToolVisible,published: workflowToolPublished,@@ -359,16 +345,16 @@ const AppPublisher = ({onRefreshData,onConfigured: closeWorkflowToolDrawer,})- const openWorkflowToolDrawer = useCallback(() => {+ function openWorkflowToolDrawer() {handleOpenChange(false)setWorkflowToolDrawerOpen(true)- }, [handleOpenChange])- const upgradeHighlightStyle = useMemo(() => ({+ }+ const upgradeHighlightStyle = {background: 'linear-gradient(97deg, var(--components-input-border-active-prompt-1, rgba(11, 165, 236, 0.95)) -3.64%, var(--components-input-border-active-prompt-2, rgba(21, 90, 239, 0.95)) 45.14%)',WebkitBackgroundClip: 'text',backgroundClip: 'text',WebkitTextFillColor: 'transparent',- }), [])+ }return (<>@@ -497,5 +483,3 @@ const AppPublisher = ({</>)}--export default memo(AppPublisher)diff --git a/web/app/components/app/overview/__tests__/app-card-sections.spec.tsx b/web/app/components/app/overview/__tests__/app-card-sections.spec.tsxindex d3f83d5d9cf..88d2bf6f91c 100644--- a/web/app/components/app/overview/__tests__/app-card-sections.spec.tsx+++ b/web/app/components/app/overview/__tests__/app-card-sections.spec.tsx@@ -26,7 +26,7 @@ vi.mock('../customize', () => ({}))vi.mock('../../app-access-control', () => ({- default: ({ onClose, onConfirm }: { onClose: () => void, onConfirm: () => void }) => (+ AccessControl: ({ onClose, onConfirm }: { onClose: () => void, onConfirm: () => void }) => (<div data-testid="access-control"><button type="button" onClick={onClose}>close-access</button><button type="button" onClick={onConfirm}>confirm-access</button>diff --git a/web/app/components/app/overview/__tests__/app-card.spec.tsx b/web/app/components/app/overview/__tests__/app-card.spec.tsxindex 1e9ba71a4ff..77b6c51b297 100644--- a/web/app/components/app/overview/__tests__/app-card.spec.tsx+++ b/web/app/components/app/overview/__tests__/app-card.spec.tsx@@ -90,7 +90,7 @@ vi.mock('../customize', () => ({}))vi.mock('../../app-access-control', () => ({- default: ({ onConfirm, onClose }: { onConfirm: () => Promise<void>, onClose: () => void }) => (+ AccessControl: ({ onConfirm, onClose }: { onConfirm: () => Promise<void>, onClose: () => void }) => (<div data-testid="access-control-modal"><button onClick={() => void onConfirm()}>confirm-access-control</button><button onClick={onClose}>close-access-control</button>diff --git a/web/app/components/app/overview/app-card-sections.tsx b/web/app/components/app/overview/app-card-sections.tsxindex 00fa0cf4afc..61f509b27b4 100644--- a/web/app/components/app/overview/app-card-sections.tsx+++ b/web/app/components/app/overview/app-card-sections.tsx@@ -37,7 +37,7 @@ import Divider from '@/app/components/base/divider'import ShareQRCode from '@/app/components/base/qrcode'import { AccessMode } from '@/models/access-control'import { AppModeEnum } from '@/types/app'-import AccessControl from '../app-access-control'+import { AccessControl } from '../app-access-control'import CustomizeModal from './customize'import EmbeddedModal from './embedded'import SettingsModal from './settings'diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsxindex c790b414f67..831ad2f08bc 100644--- a/web/app/components/apps/__tests__/app-card.spec.tsx+++ b/web/app/components/apps/__tests__/app-card.spec.tsx@@ -8,7 +8,7 @@ import * as appsService from '@/service/apps'import * as exploreService from '@/service/explore'import * as workflowService from '@/service/workflow'import { AppModeEnum } from '@/types/app'-import AppCard from '../app-card'+import { AppCard } from '../app-card'let mockWebappAuthEnabled = false@@ -1731,7 +1731,7 @@ describe('AppCard', () => {vi.resetModules()vi.doMock('@langgenius/dify-ui/alert-dialog', createMockAlertDialogModule)- const { default: IsolatedAppCard } = await import('../app-card')+ const { AppCard: IsolatedAppCard } = await import('../app-card')render(<IsolatedAppCard app={mockApp} />)fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))@@ -1753,7 +1753,7 @@ describe('AppCard', () => {vi.resetModules()vi.doMock('@langgenius/dify-ui/alert-dialog', createMockAlertDialogModule)- const { default: IsolatedAppCard } = await import('../app-card')+ const { AppCard: IsolatedAppCard } = await import('../app-card')render(<IsolatedAppCard app={mockApp} />)fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))@@ -1773,7 +1773,7 @@ describe('AppCard', () => {mockDeleteMutationPending = truevi.doMock('@langgenius/dify-ui/alert-dialog', createMockAlertDialogModule)- const { default: IsolatedAppCard } = await import('../app-card')+ const { AppCard: IsolatedAppCard } = await import('../app-card')render(<IsolatedAppCard app={mockApp} />)fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex 22c86a1fbeb..6ff5ae6e10f 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -276,6 +276,9 @@ vi.mock('@/next/dynamic', () => ({}))vi.mock('../app-card', () => ({+ AppCard: ({ app }: { app: { id: string, name: string } }) => {+ return React.createElement('div', { 'data-testid': `app-card-${app.id}`, 'role': 'article' }, app.name)+ },AppCardActionBar: ({ app, onRefresh }: { app: { id: string }, onRefresh?: () => void }) => {return React.createElement('button', {'data-testid': `app-card-action-bar-${app.id}`,diff --git a/web/app/components/apps/app-card.tsx b/web/app/components/apps/app-card.tsxindex 2d6e1e6ee31..09c7f7f8d25 100644--- a/web/app/components/apps/app-card.tsx+++ b/web/app/components/apps/app-card.tsx@@ -1,5 +1,6 @@'use client'+import type { FormEvent, FormEventHandler, MouseEvent } from 'react'import type { DuplicateAppModalProps } from '@/app/components/app/duplicate-modal'import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'import type { EnvironmentVariable } from '@/app/components/workflow/types'@@ -31,7 +32,6 @@ import {} from '@langgenius/dify-ui/tooltip'import { useSuspenseQuery } from '@tanstack/react-query'import { useSetLocalStorage } from 'foxact/use-local-storage'-import * as React from 'react'import { useCallback, useId, useMemo, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import { AppTypeIcon } from '@/app/components/app/type-selector'@@ -72,7 +72,7 @@ const SwitchAppModal = dynamic(() => import('@/app/components/app/switch-app-modconst DSLExportConfirmModal = dynamic(() => import('@/app/components/workflow/dsl-export-confirm-modal'), {ssr: false,})-const AccessControl = dynamic(() => import('@/app/components/app/app-access-control'), {+const AccessControl = dynamic(() => import('@/app/components/app/app-access-control').then(mod => mod.AccessControl), {ssr: false,})@@ -140,7 +140,7 @@ type AppCardOperationsMenuProps = {onAccessControl: () => void}-const AppCardOperationsMenu: React.FC<AppCardOperationsMenuProps> = ({+function AppCardOperationsMenu({app,shouldShowSwitchOption,shouldShowOpenInExploreOption,@@ -151,17 +151,17 @@ const AppCardOperationsMenu: React.FC<AppCardOperationsMenuProps> = ({onSwitch,onDelete,onAccessControl,-}) => {+}: AppCardOperationsMenuProps) {const { t } = useTranslation()const openAsyncWindow = useAsyncWindowOpen()- const handleMenuAction = useCallback((e: React.MouseEvent<HTMLElement>, action: () => void) => {+ function handleMenuAction(e: MouseEvent<HTMLElement>, action: () => void) {e.stopPropagation()e.preventDefault()action()- }, [])+ }- const handleOpenInstalledApp = useCallback(async (e: React.MouseEvent<HTMLElement>) => {+ async function handleOpenInstalledApp(e: MouseEvent<HTMLElement>) {e.stopPropagation()e.preventDefault()try {@@ -180,7 +180,7 @@ const AppCardOperationsMenu: React.FC<AppCardOperationsMenuProps> = ({const message = e instanceof Error ? e.message : `${e}`toast.error(message)}- }, [app.id, openAsyncWindow])+ }return (<>@@ -234,7 +234,7 @@ const AppCardOperationsMenu: React.FC<AppCardOperationsMenuProps> = ({type AppCardOperationsMenuContentProps = Omit<AppCardOperationsMenuProps, 'shouldShowOpenInExploreOption'>-const AppCardOperationsMenuContent: React.FC<AppCardOperationsMenuContentProps> = (props) => {+function AppCardOperationsMenuContent(props: AppCardOperationsMenuContentProps) {const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { data: userCanAccessApp, isLoading: isGettingUserCanAccessApp } = useGetUserCanAccessApp({appId: props.app.id,@@ -260,7 +260,7 @@ type AppCardActionBarProps = {onRefresh?: () => void}-export const AppCardActionBar: React.FC<AppCardActionBarProps> = ({ app, onRefresh }) => {+export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {const { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { isCurrentWorkspaceEditor } = useAppContext()@@ -304,7 +304,7 @@ export const AppCardActionBar: React.FC<AppCardActionBarProps> = ({ app, onRefreconst isDeleteConfirmDisabled = isDeleting || confirmDeleteInput !== app.name- const onDeleteDialogSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {+ const onDeleteDialogSubmit: FormEventHandler<HTMLFormElement> = useCallback((e) => {e.preventDefault()if (isDeleteConfirmDisabled)return@@ -442,7 +442,7 @@ export const AppCardActionBar: React.FC<AppCardActionBarProps> = ({ app, onRefresetShowAccessControl(false)}, [onRefresh, setShowAccessControl])- const handleToggleStar = useCallback(async (e: React.MouseEvent<HTMLButtonElement>) => {+ const handleToggleStar = useCallback(async (e: MouseEvent<HTMLButtonElement>) => {e.stopPropagation()e.preventDefault()@@ -651,7 +651,7 @@ export const AppCardActionBar: React.FC<AppCardActionBarProps> = ({ app, onRefre)}-const AppCard = ({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () => { } }: AppCardProps) => {+export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () => {} }: AppCardProps) {const { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { isCurrentWorkspaceEditor } = useAppContext()@@ -670,7 +670,7 @@ const AppCard = ({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () =>const { mutateAsync: mutateToggleAppStar, isPending: isTogglingStar } = useToggleAppStarMutation()const setNeedRefresh = useSetLocalStorage<string>(NEED_REFRESH_APP_LIST_KEY, { raw: true })- const onConfirmDelete = useCallback(async () => {+ async function onConfirmDelete() {try {await mutateDeleteApp(app.id)toast.success(t('appDeleted', { ns: 'app' }))@@ -682,63 +682,63 @@ const AppCard = ({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () =>const message = e instanceof Error ? e.message : ''toast.error(`${t('appDeleteFailed', { ns: 'app' })}${message ? `: ${message}` : ''}`)}- }, [app.id, mutateDeleteApp, onPlanInfoChanged, t])+ }- const onDeleteDialogOpenChange = useCallback((open: boolean) => {+ function onDeleteDialogOpenChange(open: boolean) {if (isDeleting)returnsetShowConfirmDelete(open)if (!open)setConfirmDeleteInput('')- }, [isDeleting])+ }const isDeleteConfirmDisabled = isDeleting || confirmDeleteInput !== app.name- const onDeleteDialogSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {- e.preventDefault()+ function onDeleteDialogSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault()if (isDeleteConfirmDisabled)returnvoid onConfirmDelete()- }, [isDeleteConfirmDisabled, onConfirmDelete])+ }- const handleShowEditModal = useCallback(() => {+ function handleShowEditModal() {setIsOperationsMenuOpen(false)queueMicrotask(() => {setShowEditModal(true)})- }, [])+ }- const handleShowDuplicateModal = useCallback(() => {+ function handleShowDuplicateModal() {setIsOperationsMenuOpen(false)queueMicrotask(() => {setShowDuplicateModal(true)})- }, [])+ }- const handleShowSwitchModal = useCallback(() => {+ function handleShowSwitchModal() {setIsOperationsMenuOpen(false)queueMicrotask(() => {setShowSwitchModal(true)})- }, [])+ }- const handleShowDeleteConfirm = useCallback(() => {+ function handleShowDeleteConfirm() {setIsOperationsMenuOpen(false)queueMicrotask(() => {setShowConfirmDelete(true)})- }, [])+ }- const handleShowAccessControl = useCallback(() => {+ function handleShowAccessControl() {setIsOperationsMenuOpen(false)queueMicrotask(() => {setShowAccessControl(true)})- }, [])+ }- const onEdit: CreateAppModalProps['onConfirm'] = useCallback(async ({+ const onEdit: CreateAppModalProps['onConfirm'] = async ({name,icon_type,icon,@@ -766,7 +766,7 @@ const AppCard = ({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () =>catch (e) {toast.error(e instanceof Error ? e.message : t('editFailed', { ns: 'app' }))}- }, [app.id, onRefresh, t])+ }const onCopy: DuplicateAppModalProps['onConfirm'] = async ({ name, icon_type, icon, icon_background }) => {try {@@ -831,11 +831,11 @@ const AppCard = ({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () =>setShowSwitchModal(false)}- const onUpdateAccessControl = useCallback(() => {+ function onUpdateAccessControl() {if (onRefresh)onRefresh()setShowAccessControl(false)- }, [onRefresh, setShowAccessControl])+ }const handleToggleStar = useCallback(async (e: React.MouseEvent<HTMLButtonElement>) => {e.stopPropagation()@@ -1163,5 +1163,3 @@ const AppCard = ({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () =></>)}--export default React.memo(AppCard)diff --git a/web/app/components/apps/list.tsx b/web/app/components/apps/list.tsxindex b9aad31cf39..58f9604b958 100644--- a/web/app/components/apps/list.tsx+++ b/web/app/components/apps/list.tsx@@ -15,7 +15,7 @@ import { CheckModal } from '@/hooks/use-pay'import { usePathname, useRouter, useSearchParams } from '@/next/navigation'import { consoleQuery } from '@/service/client'import { AppModeEnum } from '@/types/app'-import AppCard from './app-card'+import { AppCard } from './app-card'import { AppCardSkeleton } from './app-card-skeleton'import { AppListCreationModals } from './app-list-creation-modals'import { AppListHeaderFilters } from './app-list-header-filters'diff --git a/web/app/components/header/__tests__/index.spec.tsx b/web/app/components/header/__tests__/index.spec.tsxindex d1a71c9bcd8..4368ac2fc4e 100644--- a/web/app/components/header/__tests__/index.spec.tsx+++ b/web/app/components/header/__tests__/index.spec.tsx@@ -2,7 +2,7 @@ import type { AnchorHTMLAttributes, ReactElement } from 'react'import { fireEvent, screen } from '@testing-library/react'import { vi } from 'vitest'import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'-import Header from '../index'+import { Header } from '../index'function createMockComponent(testId: string) {return () => <div data-testid={testId} />@@ -21,7 +21,7 @@ vi.mock('@/app/components/header/app-nav', () => ({}))vi.mock('@/app/components/header/dataset-nav', () => ({- default: createMockComponent('dataset-nav'),+ DatasetNav: createMockComponent('dataset-nav'),}))vi.mock('@/app/components/header/env-nav', () => ({@@ -29,7 +29,7 @@ vi.mock('@/app/components/header/env-nav', () => ({}))vi.mock('@/app/components/header/explore-nav', () => ({- default: createMockComponent('explore-nav'),+ ExploreNav: createMockComponent('explore-nav'),}))vi.mock('@/app/components/header/license-env', () => ({@@ -41,7 +41,7 @@ vi.mock('@/app/components/header/plugins-nav', () => ({}))vi.mock('@/app/components/header/tools-nav', () => ({- default: createMockComponent('tools-nav'),+ ToolsNav: createMockComponent('tools-nav'),}))vi.mock('@/app/components/header/plan-badge', () => ({diff --git a/web/app/components/header/dataset-nav/__tests__/index.spec.tsx b/web/app/components/header/dataset-nav/__tests__/index.spec.tsxindex 56c3c4bee08..7df00f5c8f0 100644--- a/web/app/components/header/dataset-nav/__tests__/index.spec.tsx+++ b/web/app/components/header/dataset-nav/__tests__/index.spec.tsx@@ -10,7 +10,7 @@ import {useDatasetDetail,useDatasetList,} from '@/service/knowledge/use-dataset'-import DatasetNav from '../index'+import { DatasetNav } from '../index'vi.mock('@/next/navigation', () => ({useParams: vi.fn(),@@ -174,30 +174,34 @@ describe('DatasetNav', () => {expect(within(menu).getByText('Null Icon Dataset')).toBeInTheDocument()})- it('should navigate to correct link when an item is clicked', () => {- render(<DatasetNav />)+ it('should navigate to correct links for navigation items', () => {+ const { unmount } = render(<DatasetNav />)const selector = screen.getByRole('button', { name: /Test Dataset/i })fireEvent.click(selector)const menu = screen.getByRole('menu')const pipelineItem = within(menu).getByText('Pipeline Dataset')- fireEvent.click(pipelineItem)// dataset-2 is rag_pipeline and not published -> /datasets/dataset-2/pipeline+ fireEvent.click(pipelineItem)expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-2/pipeline')- fireEvent.click(selector)- const menu2 = screen.getByRole('menu')- const externalItem = within(menu2).getByText('External Dataset')- fireEvent.click(externalItem)+ unmount()+ mockPush.mockClear()+ render(<DatasetNav />)+ fireEvent.click(screen.getByRole('button', { name: /Test Dataset/i }))++ const externalItem = within(screen.getByRole('menu')).getByText('External Dataset')// dataset-3 is provider external -> /datasets/dataset-3/hitTesting+ fireEvent.click(externalItem)expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-3/hitTesting')- fireEvent.click(selector)- const menu3 = screen.getByRole('menu')- const publishedItem = within(menu3).getByText('Published Pipeline')- fireEvent.click(publishedItem)+ mockPush.mockClear()+ fireEvent.click(screen.getByRole('button', { name: /Test Dataset/i }))++ const publishedItem = within(screen.getByRole('menu')).getByText('Published Pipeline')// dataset-4 is rag_pipeline and published -> /datasets/dataset-4/documents+ fireEvent.click(publishedItem)expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-4/documents')})})diff --git a/web/app/components/header/dataset-nav/index.tsx b/web/app/components/header/dataset-nav/index.tsxindex 394ecca26f1..578fcc4797a 100644--- a/web/app/components/header/dataset-nav/index.tsx+++ b/web/app/components/header/dataset-nav/index.tsx@@ -3,32 +3,71 @@import type { NavItem } from '../nav/nav-selector'import type { DataSet, IconInfo } from '@/models/datasets'import { flatten } from 'es-toolkit/compat'-import { useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useParams, useRouter } from '@/next/navigation'import { useDatasetDetail, useDatasetList } from '@/service/knowledge/use-dataset'import { basePath } from '@/utils/var'import Nav from '../nav'-const DEFAULT_DATASET_ICON: IconInfo = {- icon_type: 'emoji',+const DEFAULT_DATASET_ICON_INFO = {icon: '📙',+ icon_type: 'emoji',icon_background: '#FFF4ED',icon_url: '',-}+} satisfies IconInfotype NullableDatasetIconInfo = Partial<{[Key in keyof IconInfo]: IconInfo[Key] | null}>-const normalizeDatasetIconInfo = (iconInfo?: NullableDatasetIconInfo | null): IconInfo => ({- icon_type: iconInfo?.icon_type ?? DEFAULT_DATASET_ICON.icon_type,- icon: iconInfo?.icon ?? DEFAULT_DATASET_ICON.icon,- icon_background: iconInfo?.icon_background ?? DEFAULT_DATASET_ICON.icon_background,- icon_url: iconInfo?.icon_url ?? DEFAULT_DATASET_ICON.icon_url,-})+function normalizeDatasetIconInfo(iconInfo?: NullableDatasetIconInfo | null): IconInfo {+ return {+ icon: iconInfo?.icon ?? DEFAULT_DATASET_ICON_INFO.icon,+ icon_type: iconInfo?.icon_type ?? DEFAULT_DATASET_ICON_INFO.icon_type,+ icon_background: iconInfo?.icon_background ?? DEFAULT_DATASET_ICON_INFO.icon_background,+ icon_url: iconInfo?.icon_url ?? DEFAULT_DATASET_ICON_INFO.icon_url,+ }+}++function datasetLink(dataset: DataSet) {+ const isPipelineUnpublished = dataset.runtime_mode === 'rag_pipeline' && !dataset.is_published+ const link = isPipelineUnpublished+ ? `/datasets/${dataset.id}/pipeline`+ : `/datasets/${dataset.id}/documents`-const DatasetNav = () => {+ return dataset.provider === 'external'+ ? `/datasets/${dataset.id}/hitTesting`+ : link+}++function currentDatasetNavItem(dataset: DataSet) {+ const iconInfo = normalizeDatasetIconInfo(dataset.icon_info)++ return {+ id: dataset.id,+ name: dataset.name,+ icon: iconInfo.icon,+ icon_type: iconInfo.icon_type,+ icon_background: iconInfo.icon_background ?? null,+ icon_url: iconInfo.icon_url ?? null,+ } satisfies Omit<NavItem, 'link'>+}++function datasetNavItem(dataset: DataSet) {+ const iconInfo = normalizeDatasetIconInfo(dataset.icon_info)++ return {+ id: dataset.id,+ name: dataset.name,+ link: datasetLink(dataset),+ icon: iconInfo.icon,+ icon_type: iconInfo.icon_type,+ icon_background: iconInfo.icon_background ?? null,+ icon_url: iconInfo.icon_url ?? null,+ } satisfies NavItem+}++export function DatasetNav() {const { t } = useTranslation()const router = useRouter()const { datasetId } = useParams()@@ -44,64 +83,23 @@ const DatasetNav = () => {})const datasetItems = flatten(datasetList?.pages.map(datasetData => datasetData.data))- const curNav = useMemo(() => {- if (!currentDataset)- return- const iconInfo = normalizeDatasetIconInfo(currentDataset.icon_info)- return {- id: currentDataset.id,- name: currentDataset.name,- icon: iconInfo.icon,- icon_type: iconInfo.icon_type,- icon_background: iconInfo.icon_background ?? null,- icon_url: iconInfo.icon_url ?? null,- } as Omit<NavItem, 'link'>- }, [currentDataset])+ const curNav = currentDataset ? currentDatasetNavItem(currentDataset) : undefined+ const navigationItems = datasetItems.map(datasetNavItem)+ const runtimeMode = currentDataset?.runtime_mode+ const createRoute = runtimeMode === 'rag_pipeline'+ ? `${basePath}/datasets/create-from-pipeline`+ : `${basePath}/datasets/create`- const getDatasetLink = useCallback((dataset: DataSet) => {- const isPipelineUnpublished = dataset.runtime_mode === 'rag_pipeline' && !dataset.is_published- const link = isPipelineUnpublished- ? `/datasets/${dataset.id}/pipeline`- : `/datasets/${dataset.id}/documents`- return dataset.provider === 'external'- ? `/datasets/${dataset.id}/hitTesting`- : link- }, [])-- const navigationItems = useMemo(() => {- return datasetItems.map((dataset) => {- const link = getDatasetLink(dataset)- const iconInfo = normalizeDatasetIconInfo(dataset.icon_info)- return {- id: dataset.id,- name: dataset.name,- link,- icon: iconInfo.icon,- icon_type: iconInfo.icon_type,- icon_background: iconInfo.icon_background ?? null,- icon_url: iconInfo.icon_url ?? null,- }- }) as NavItem[]- }, [datasetItems, getDatasetLink])-- const createRoute = useMemo(() => {- const runtimeMode = currentDataset?.runtime_mode- if (runtimeMode === 'rag_pipeline')- return `${basePath}/datasets/create-from-pipeline`- else- return `${basePath}/datasets/create`- }, [currentDataset?.runtime_mode])-- const handleLoadMore = useCallback(() => {- if (hasNextPage)- fetchNextPage()- }, [hasNextPage, fetchNextPage])+ function handleLoadMore() {+ if (hasNextPage && !isFetchingNextPage)+ void fetchNextPage()+ }return (<NavisApp={false}- icon={<span className="i-ri-book-2-line size-4" />}- activeIcon={<span className="i-ri-book-2-fill size-4" />}+ icon={<span aria-hidden className="i-ri-book-2-line size-4" />}+ activeIcon={<span aria-hidden className="i-ri-book-2-fill size-4" />}text={t('menus.datasets', { ns: 'common' })}activeSegment="datasets"link="/datasets"@@ -114,5 +112,3 @@ const DatasetNav = () => {/>)}--export default DatasetNavdiff --git a/web/app/components/header/explore-nav/__tests__/index.spec.tsx b/web/app/components/header/explore-nav/__tests__/index.spec.tsxindex b01bac710f6..07617b337a5 100644--- a/web/app/components/header/explore-nav/__tests__/index.spec.tsx+++ b/web/app/components/header/explore-nav/__tests__/index.spec.tsx@@ -1,7 +1,7 @@import type { Mock } from 'vitest'import { render, screen } from '@testing-library/react'import { usePathname, useSelectedLayoutSegment } from '@/next/navigation'-import ExploreNav from '../index'+import { ExploreNav } from '../index'vi.mock('@/next/navigation', () => ({usePathname: vi.fn(),diff --git a/web/app/components/header/explore-nav/index.tsx b/web/app/components/header/explore-nav/index.tsxindex 3f3f57b0296..f42326e2100 100644--- a/web/app/components/header/explore-nav/index.tsx+++ b/web/app/components/header/explore-nav/index.tsx@@ -9,13 +9,11 @@ import { useTranslation } from 'react-i18next'import Link from '@/next/link'import { usePathname, useSelectedLayoutSegment } from '@/next/navigation'-type ExploreNavProps = {- className?: string-}--const ExploreNav = ({+export function ExploreNav({className,-}: ExploreNavProps) => {+}: {+ className?: string+}) {const { t } = useTranslation()const pathname = usePathname()const selectedSegment = useSelectedLayoutSegment()@@ -31,11 +29,9 @@ const ExploreNav = ({? <RiPlanetFill className="size-4" />: <RiPlanetLine className="size-4" />}- <div className="ml-2 max-[1024px]:hidden">+ <div className="ml-2 max-[1120px]:hidden">{t('menus.explore', { ns: 'common' })}</div></Link>)}--export default ExploreNavdiff --git a/web/app/components/header/index.tsx b/web/app/components/header/index.tsxindex afbe6b030f3..d604f96dbd5 100644--- a/web/app/components/header/index.tsx+++ b/web/app/components/header/index.tsx@@ -1,25 +1,25 @@'use client'import { useSuspenseQuery } from '@tanstack/react-query'-import { useCallback } from 'react'import DifyLogo from '@/app/components/base/logo/dify-logo'import WorkplaceSelector from '@/app/components/header/account-dropdown/workplace-selector'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useAppContext } from '@/context/app-context'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { DeploymentsNav } from '@/features/deployments/nav'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import Link from '@/next/link'import { Plan } from '../billing/type'import AccountDropdown from './account-dropdown'import AppNav from './app-nav'-import DatasetNav from './dataset-nav'+import { DatasetNav } from './dataset-nav'import EnvNav from './env-nav'-import ExploreNav from './explore-nav'+import { ExploreNav } from './explore-nav'import LicenseNav from './license-env'import { PlanBadge } from './plan-badge'import PluginsNav from './plugins-nav'-import ToolsNav from './tools-nav'+import { ToolsNav } from './tools-nav'const navClassName = `flex items-center relative px-3 h-8 rounded-xl@@ -27,7 +27,7 @@ const navClassName = `cursor-pointer`-const Header = () => {+export function Header() {const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()const media = useBreakpoints()const isMobile = media === MediaType.mobile@@ -36,12 +36,14 @@ const Header = () => {const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const isFreePlan = plan.type === Plan.sandboxconst isBrandingEnabled = systemFeatures.branding.enabled- const handlePlanClick = useCallback(() => {+ const canUseAppDeploy = isCurrentWorkspaceEditor && systemFeatures.enable_app_deploy++ function handlePlanClick() {if (isFreePlan)setShowPricingModal()elsesetShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.BILLING })- }, [isFreePlan, setShowAccountSettingModal, setShowPricingModal])+ }const logoLabel = isBrandingEnabled && systemFeatures.branding.application_title ? systemFeatures.branding.application_title : 'Dify'const renderLogo = () => (@@ -72,18 +74,17 @@ const Header = () => {<WorkplaceSelector />{enableBilling ? <PlanBadge allowHover sandboxAsUpgrade plan={plan.type} onClick={handlePlanClick} /> : <LicenseNav />}</div>- <div className="flex items-center">- <div className="mr-2">- <PluginsNav />- </div>+ <div className="flex items-center gap-2">+ <PluginsNav /><AccountDropdown /></div></div>- <div className="my-1 flex items-center justify-center space-x-1">+ <div className="my-1 flex items-center justify-center gap-1">{!isCurrentWorkspaceDatasetOperator && <ExploreNav className={navClassName} />}{!isCurrentWorkspaceDatasetOperator && <AppNav />}{(isCurrentWorkspaceEditor || isCurrentWorkspaceDatasetOperator) && <DatasetNav />}{!isCurrentWorkspaceDatasetOperator && <ToolsNav className={navClassName} />}+ {canUseAppDeploy && <DeploymentsNav />}</div></div>)@@ -91,26 +92,24 @@ const Header = () => {return (<div className="flex h-[56px] items-center">- <div className="flex min-w-0 flex-1 items-center pr-2 pl-3 min-[1280px]:pr-3">+ <div className="flex min-w-0 flex-1 items-center overflow-hidden pr-2 pl-3 min-[1280px]:pr-3">{renderLogo()}<div className="mx-1.5 shrink-0 font-light text-divider-deep">/</div><WorkplaceSelector />{enableBilling ? <PlanBadge allowHover sandboxAsUpgrade plan={plan.type} onClick={handlePlanClick} /> : <LicenseNav />}</div>- <div className="flex items-center space-x-2">+ <div className="flex min-w-0 items-center justify-center gap-2 overflow-hidden py-3">{!isCurrentWorkspaceDatasetOperator && <ExploreNav className={navClassName} />}{!isCurrentWorkspaceDatasetOperator && <AppNav />}{(isCurrentWorkspaceEditor || isCurrentWorkspaceDatasetOperator) && <DatasetNav />}{!isCurrentWorkspaceDatasetOperator && <ToolsNav className={navClassName} />}+ {canUseAppDeploy && <DeploymentsNav />}</div>- <div className="flex min-w-0 flex-1 items-center justify-end pr-3 pl-2 min-[1280px]:pl-3">+ <div className="flex min-w-0 flex-1 items-center justify-end gap-2 pr-3 pl-2 min-[1280px]:pl-3"><EnvNav />- <div className="mr-2">- <PluginsNav />- </div>+ <PluginsNav /><AccountDropdown /></div></div>)}-export default Headerdiff --git a/web/app/components/header/nav/__tests__/index.spec.tsx b/web/app/components/header/nav/__tests__/index.spec.tsxindex 2dd2843c52f..c64eec87387 100644--- a/web/app/components/header/nav/__tests__/index.spec.tsx+++ b/web/app/components/header/nav/__tests__/index.spec.tsx@@ -12,14 +12,18 @@ import * as React from 'react'import { vi } from 'vitest'import { useStore as useAppStore } from '@/app/components/app/store'import { useAppContext } from '@/context/app-context'-import { useRouter, useSelectedLayoutSegment } from '@/next/navigation'+import { useSelectedLayoutSegment } from '@/next/navigation'import { AppModeEnum } from '@/types/app'import Nav from '../index'+const mockPush = vi.fn()+// Mock next/navigationvi.mock('@/next/navigation', () => ({useSelectedLayoutSegment: vi.fn(),- useRouter: vi.fn(),+ useRouter: () => ({+ push: mockPush,+ }),}))// Mock app store@@ -56,7 +60,6 @@ describe('Nav Component', () => {const mockSetAppDetail = vi.fn()const mockOnCreate = vi.fn()const mockOnLoadMore = vi.fn()- const mockPush = vi.fn()const navigationItems: NavItem[] = [{@@ -100,9 +103,6 @@ describe('Nav Component', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: true,} as unknown as AppContextValue)- vi.mocked(useRouter).mockReturnValue({- push: mockPush,- } as unknown as ReturnType<typeof useRouter>)})describe('Rendering', () => {@@ -139,9 +139,9 @@ describe('Nav Component', () => {)expect(screen.getByText('Nav Text')).toBeInTheDocument()- expect(screen.getByText('Nav Text')).toHaveClass('max-[1024px]:hidden')+ expect(screen.getByText('Nav Text')).toHaveClass('max-[1120px]:hidden')expect(screen.getByRole('link', { name: 'SNIPPETS' })).toHaveAttribute('href', '/snippets')- expect(screen.getByRole('link', { name: 'SNIPPETS' })).not.toHaveClass('max-[1024px]:hidden')+ expect(screen.getByRole('link', { name: 'SNIPPETS' })).not.toHaveClass('max-[1120px]:hidden')})it('should not show hover background if not activated', () => {@@ -213,7 +213,7 @@ describe('Nav Component', () => {})})- it('should navigate when an item is selected', async () => {+ it('should clear app detail and navigate when an item is selected', async () => {vi.mocked(useSelectedLayoutSegment).mockReturnValue('snippets')render(<Nav {...defaultProps} activeSegment={['apps', 'app', 'snippets']} curNav={curNav} />)const selectorButton = screen.getByRole('button', { name: /Item 1/i })@@ -228,6 +228,7 @@ describe('Nav Component', () => {fireEvent.click(item2)})+ expect(mockSetAppDetail).toHaveBeenCalled()expect(mockPush).toHaveBeenCalledWith('/item2')})@@ -248,7 +249,7 @@ describe('Nav Component', () => {})}- expect(mockPush).not.toHaveBeenCalled()+ expect(mockSetAppDetail).not.toHaveBeenCalled()})it('should call onCreate when create button is clicked', async () => {diff --git a/web/app/components/header/nav/index.tsx b/web/app/components/header/nav/index.tsxindex e5518f43d05..94acdd3f685 100644--- a/web/app/components/header/nav/index.tsx+++ b/web/app/components/header/nav/index.tsx@@ -7,7 +7,7 @@ import { useState } from 'react'import { useStore as useAppStore } from '@/app/components/app/store'import Link from '@/next/link'import { useSelectedLayoutSegment } from '@/next/navigation'-import NavSelector from './nav-selector'+import { NavSelector } from './nav-selector'type INavProps = {icon: React.ReactNode@@ -46,12 +46,12 @@ const Nav = ({return (<div className={`- flex h-8 max-w-167.5 shrink-0 items-center rounded-xl px-0.5 text-sm font-medium max-[1024px]:max-w-100+ flex h-8 max-w-167.5 min-w-0 items-center rounded-xl px-0.5 text-sm font-medium max-[1120px]:max-w-100${isActivated && 'bg-components-main-nav-nav-button-bg-active font-semibold shadow-md'}${!curNav && !isActivated && 'hover:bg-components-main-nav-nav-button-bg-hover'}`}>- <Link href={link}>+ <Link href={link} className="shrink-0"><divonClick={(e) => {// Don't clear state if opening in new tab/window@@ -74,7 +74,7 @@ const Nav = ({: icon}</div>- <div className="ml-2 max-[1024px]:hidden">+ <div className="ml-2 max-[1120px]:hidden">{text}</div></div>@@ -82,7 +82,7 @@ const Nav = ({{curNav && isActivated && (<>- <div className="font-light text-divider-deep">/</div>+ <div className="shrink-0 font-light text-divider-deep">/</div><NavSelectorisApp={isApp}curNav={curNav}@@ -98,12 +98,12 @@ const Nav = ({{!curNav && shouldShowActiveLink && (<>- <div className="font-light text-divider-deep">/</div>+ <div className="shrink-0 font-light text-divider-deep">/</div><Linkhref={activeLink.link}- className="hover:bg-components-main-nav-nav-button-bg-active-hover flex h-7 cursor-pointer items-center rounded-[10px] px-2.5 text-components-main-nav-nav-button-text-active"+ className="hover:bg-components-main-nav-nav-button-bg-active-hover flex h-7 min-w-0 cursor-pointer items-center rounded-[10px] px-2.5 text-components-main-nav-nav-button-text-active">- {activeLink.text}+ <span className="truncate">{activeLink.text}</span></Link></>)diff --git a/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx b/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsxindex aaabe456132..7f1a232f407 100644--- a/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx@@ -5,13 +5,15 @@ import userEvent from '@testing-library/user-event'import { vi } from 'vitest'import { useStore as useAppStore } from '@/app/components/app/store'import { useAppContext } from '@/context/app-context'-import { useRouter } from '@/next/navigation'import { AppModeEnum } from '@/types/app'-import NavSelector from '../index'+import { NavSelector } from '../index'++const mockPush = vi.fn()-// Mock next/navigationvi.mock('@/next/navigation', () => ({- useRouter: vi.fn(),+ useRouter: () => ({+ push: mockPush,+ }),}))// Mock app store@@ -28,7 +30,6 @@ describe('NavSelector Component', () => {const mockSetAppDetail = vi.fn()const mockOnCreate = vi.fn()const mockOnLoadMore = vi.fn()- const mockPush = vi.fn()const navigationItems: NavItem[] = [{@@ -70,9 +71,6 @@ describe('NavSelector Component', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: true,} as unknown as AppContextValue)- vi.mocked(useRouter).mockReturnValue({- push: mockPush,- } as unknown as ReturnType<typeof useRouter>)})describe('Rendering', () => {@@ -101,7 +99,7 @@ describe('NavSelector Component', () => {expect(screen.getByText('Item 2'))!.toBeInTheDocument()})- it('should navigate and call setAppDetail when an item is clicked', async () => {+ it('should call setAppDetail and navigate when an item is clicked', async () => {render(<NavSelector {...defaultProps} />)const button = screen.getByRole('button')await act(async () => {@@ -115,7 +113,7 @@ describe('NavSelector Component', () => {expect(mockPush).toHaveBeenCalledWith('/item2')})- it('should not navigate if current item is clicked', async () => {+ it('should render current item without a route link', async () => {render(<NavSelector {...defaultProps} />)const button = screen.getByRole('button')await act(async () => {@@ -128,7 +126,8 @@ describe('NavSelector Component', () => {fireEvent.click(listItem)})}- expect(mockPush).not.toHaveBeenCalled()+ expect(listItem?.closest('a')).toBeNull()+ expect(mockSetAppDetail).not.toHaveBeenCalled()})it('should call onCreate when create button is clicked (non-app mode)', async () => {diff --git a/web/app/components/header/nav/nav-selector/index.tsx b/web/app/components/header/nav/nav-selector/index.tsxindex 057e50dabf0..853011cd289 100644--- a/web/app/components/header/nav/nav-selector/index.tsx+++ b/web/app/components/header/nav/nav-selector/index.tsx@@ -53,14 +53,14 @@ type AppCreateMenuProps = {onCreate: (state: string) => void}-const AppCreateMenu = ({+function AppCreateMenu({createText,startFromBlankText,startFromTemplateText,importDSLText,onCreate,-}: AppCreateMenuProps) => {- const handleCreate = (state: string) => {+}: AppCreateMenuProps) {+ function handleCreate(state: string) {onCreate(state)}@@ -111,9 +111,65 @@ const AppCreateMenu = ({)}-const NavSelector = ({ curNav, navigationItems, createText, isApp, onCreate, onLoadMore, isLoadingMore }: INavSelectorProps) => {- const { t } = useTranslation()+function NavSelectorItemContent({ nav }: {+ nav: NavItem+}) {+ return (+ <>+ <div className="relative mr-2 size-6 shrink-0 rounded-md">+ <AppIcon+ size="tiny"+ iconType={nav.icon_type}+ icon={nav.icon}+ background={nav.icon_background}+ imageUrl={nav.icon_url}+ />+ {!!nav.mode && (+ <AppTypeIcon type={nav.mode} wrapperClassName="absolute -bottom-0.5 -right-0.5 h-3.5 w-3.5 shadow-sm" className="size-2.5" />+ )}+ </div>+ <div className="min-w-0 truncate">+ {nav.name}+ </div>+ </>+ )+}++function NavSelectorRouteItem({ nav, isCurrent, onBeforeNavigate }: {+ nav: NavItem+ isCurrent: boolean+ onBeforeNavigate: () => void+}) {const router = useRouter()+ const className = 'h-auto truncate px-3 py-[6px] text-[14px] font-normal text-text-secondary'++ function handleNavigate() {+ onBeforeNavigate()+ router.push(nav.link)+ }++ if (isCurrent) {+ return (+ <DropdownMenuItem+ className={className}+ >+ <NavSelectorItemContent nav={nav} />+ </DropdownMenuItem>+ )+ }++ return (+ <DropdownMenuItem+ className={className}+ onClick={handleNavigate}+ >+ <NavSelectorItemContent nav={nav} />+ </DropdownMenuItem>+ )+}++export function NavSelector({ curNav, navigationItems, createText, isApp, onCreate, onLoadMore, isLoadingMore }: INavSelectorProps) {+ const { t } = useTranslation()const { isCurrentWorkspaceEditor } = useAppContext()const setAppDetail = useAppStore(state => state.setAppDetail)@@ -130,11 +186,11 @@ const NavSelector = ({ curNav, navigationItems, createText, isApp, onCreate, onL<DropdownMenu modal={false}><DropdownMenuTriggerclassName={cn(- 'hover:hover:bg-components-main-nav-nav-button-bg-active-hover group inline-flex h-7 items-center justify-center rounded-[10px] pr-2.5 pl-2 text-[14px] font-semibold text-components-main-nav-nav-button-text-active outline-hidden',+ 'hover:hover:bg-components-main-nav-nav-button-bg-active-hover group inline-flex h-7 min-w-0 items-center justify-center rounded-[10px] pr-2.5 pl-2 text-[14px] font-semibold text-components-main-nav-nav-button-text-active outline-hidden','focus-visible:bg-components-main-nav-nav-button-bg-active focus-visible:ring-1 focus-visible:ring-components-input-border-hover data-popup-open:bg-components-main-nav-nav-button-bg-active',)}>- <div className="max-w-[157px] truncate" title={curNav?.name}>{curNav?.name}</div>+ <div className="max-w-[157px] min-w-0 truncate">{curNav?.name}</div><RiArrowDownSLineclassName="ml-1 size-3 shrink-0 opacity-50 group-hover:opacity-100 group-data-popup-open:opacity-100"aria-hidden="true"@@ -148,33 +204,12 @@ const NavSelector = ({ curNav, navigationItems, createText, isApp, onCreate, onL<div className="max-h-[50vh] overflow-auto px-1 py-1" onScroll={handleScroll}>{navigationItems.map(nav => (- <DropdownMenuItem+ <NavSelectorRouteItemkey={nav.id}- className="h-auto truncate px-3 py-[6px] text-[14px] font-normal text-text-secondary"- onClick={() => {- if (curNav?.id === nav.id)- return- setAppDetail()- router.push(nav.link)- }}- title={nav.name}- >- <div className="relative mr-2 size-6 shrink-0 rounded-md">- <AppIcon- size="tiny"- iconType={nav.icon_type}- icon={nav.icon}- background={nav.icon_background}- imageUrl={nav.icon_url}- />- {!!nav.mode && (- <AppTypeIcon type={nav.mode} wrapperClassName="absolute -bottom-0.5 -right-0.5 h-3.5 w-3.5 shadow-sm" className="size-2.5" />- )}- </div>- <div className="min-w-0 truncate">- {nav.name}- </div>- </DropdownMenuItem>+ nav={nav}+ isCurrent={curNav?.id === nav.id}+ onBeforeNavigate={setAppDetail}+ />))}{isLoadingMore && (@@ -209,5 +244,3 @@ const NavSelector = ({ curNav, navigationItems, createText, isApp, onCreate, onL</DropdownMenu>)}--export default NavSelectordiff --git a/web/app/components/header/tools-nav/__tests__/index.spec.tsx b/web/app/components/header/tools-nav/__tests__/index.spec.tsxindex d5646e09d7f..018efc9faee 100644--- a/web/app/components/header/tools-nav/__tests__/index.spec.tsx+++ b/web/app/components/header/tools-nav/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import { render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import ToolsNav from '../index'+import { ToolsNav } from '../index'const mockUseSelectedLayoutSegment = vi.fn()vi.mock('@/next/navigation', () => ({diff --git a/web/app/components/header/tools-nav/index.tsx b/web/app/components/header/tools-nav/index.tsxindex 22f6818a7a9..d4a6c17fd00 100644--- a/web/app/components/header/tools-nav/index.tsx+++ b/web/app/components/header/tools-nav/index.tsx@@ -10,13 +10,11 @@ import { buildIntegrationPath } from '@/app/components/integrations/routes'import Link from '@/next/link'import { useSelectedLayoutSegment } from '@/next/navigation'-type ToolsNavProps = {- className?: string-}--const ToolsNav = ({+export function ToolsNav({className,-}: ToolsNavProps) => {+}: {+ className?: string+}) {const { t } = useTranslation()const selectedSegment = useSelectedLayoutSegment()const activated = selectedSegment === 'integrations' || selectedSegment === 'tools'@@ -31,11 +29,9 @@ const ToolsNav = ({? <RiHammerFill className="size-4" />: <RiHammerLine className="size-4" />}- <div className="ml-2 max-[1024px]:hidden">+ <div className="ml-2 max-[1120px]:hidden">{t('menus.tools', { ns: 'common' })}</div></Link>)}--export default ToolsNavdiff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsxindex 684a66d87fd..0d3fee692d4 100644--- a/web/app/components/main-nav/__tests__/index.spec.tsx+++ b/web/app/components/main-nav/__tests__/index.spec.tsx@@ -159,6 +159,15 @@ vi.mock('@/app/components/app-sidebar/dataset-detail-top', () => ({),}))+vi.mock('@/features/deployments/detail/deployment-sidebar', () => ({+ DeploymentDetailSection: ({ expand }: { expand: boolean }) => <div data-testid="deployment-detail-section" data-expand={expand} />,+ DeploymentDetailTop: ({ expand, onToggle }: { expand: boolean, onToggle: () => void }) => (+ <div data-testid="deployment-detail-top" data-expand={expand}>+ <button type="button" data-testid="deployment-detail-toggle" onClick={onToggle}>Toggle</button>+ </div>+ ),+}))+vi.mock('@/context/i18n', () => ({useLocale: () => 'en-US',useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,@@ -240,8 +249,10 @@ const appContextValue: AppContextValue = {isValidatingCurrentWorkspace: false,}+type MainNavSystemFeatures = NonNullable<Parameters<typeof renderWithSystemFeatures>[1]>['systemFeatures']+const renderMainNav = (- systemFeatures = { branding: { enabled: false } },+ systemFeatures: MainNavSystemFeatures = { branding: { enabled: false } },options: { store?: ReturnType<typeof createStore>, extra?: ReactNode } = {},) => {const queryClient = createTestQueryClient()@@ -325,6 +336,22 @@ describe('MainNav', () => {expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toHaveAttribute('href', '/marketplace')})+ it('renders deployments in primary navigation when app deploy is enabled', () => {+ renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })++ const marketplaceLink = screen.getByRole('link', { name: /common.mainNav.marketplace/ })+ const deploymentsLink = screen.getByRole('link', { name: /common.menus.deployments/ })++ expect(deploymentsLink).toHaveAttribute('href', '/deployments')+ expect(marketplaceLink.compareDocumentPosition(deploymentsLink)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)+ })++ it('hides deployments in primary navigation when app deploy is disabled', () => {+ renderMainNav({ branding: { enabled: false }, enable_app_deploy: false })++ expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()+ })+it('aligns the global navigation spacing with the main sidebar design', () => {mockInstalledApps = [createInstalledApp()]@@ -452,12 +479,13 @@ describe('MainNav', () => {isCurrentWorkspaceOwner: false,})- renderMainNav()+ renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })expect(screen.getByRole('link', { name: /common.mainNav.home/ })).toBeInTheDocument()expect(screen.getByRole('link', { name: /common.menus.apps/ })).toBeInTheDocument()expect(screen.queryByRole('link', { name: /common.menus.datasets/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.mainNav.integrations/ })).toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toBeInTheDocument()})@@ -624,6 +652,50 @@ describe('MainNav', () => {expect(screen.getByTestId('dataset-detail-section')).toHaveAttribute('data-expand', 'true')})+ it('replaces global navigation with deployment detail navigation on deployment routes', () => {+ mockPathname = '/deployments/app-instance-1/releases'++ renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })++ expect(screen.getByTestId('deployment-detail-top')).toBeInTheDocument()+ expect(screen.getByTestId('deployment-detail-section')).toBeInTheDocument()+ expect(screen.getByTestId('deployment-detail-top')).toHaveAttribute('data-expand', 'true')+ expect(screen.getByTestId('deployment-detail-section')).toHaveAttribute('data-expand', 'true')+ expect(screen.getByRole('complementary')).toHaveClass('w-[248px]')+ expect(screen.getByRole('complementary')).toHaveClass('p-1')+ expect(screen.getByRole('complementary')).toHaveClass('bg-background-body')+ expect(screen.queryByRole('button', { name: 'common.mainNav.workspace.openMenu' })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /common.mainNav.home/ })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()+ })++ it('collapses deployment detail navigation from the top-right toggle', () => {+ mockPathname = '/deployments/app-instance-1/releases'++ renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })+ fireEvent.click(screen.getByTestId('deployment-detail-toggle'))++ expect(screen.getByRole('complementary')).toHaveClass('w-16')+ expect(screen.getByRole('complementary')).toHaveClass('p-1')+ expect(screen.getByTestId('deployment-detail-top')).toHaveAttribute('data-expand', 'false')+ expect(screen.getByTestId('deployment-detail-section')).toHaveAttribute('data-expand', 'false')+ expect(localStorage.getItem('app-detail-collapse-or-expand')).toBe('collapse')+ })++ it.each([+ '/deployments',+ '/deployments/create',+ ])('keeps global navigation on deployment collection route %s', (pathname) => {+ mockPathname = pathname++ renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })++ expect(screen.queryByTestId('deployment-detail-top')).not.toBeInTheDocument()+ expect(screen.queryByTestId('deployment-detail-section')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.mainNav.workspace.openMenu' })).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /common.menus.deployments/ })).toHaveAttribute('href', '/deployments')+ })+it('registers the detail navigation shortcut to run while inputs are focused', () => {mockPathname = '/app/app-1/overview'diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsxindex ccb149978d8..340d40c7596 100644--- a/web/app/components/main-nav/index.tsx+++ b/web/app/components/main-nav/index.tsx@@ -17,6 +17,7 @@ import DifyLogo from '@/app/components/base/logo/dify-logo'import EnvNav from '@/app/components/header/env-nav'import { buildIntegrationPath } from '@/app/components/integrations/routes'import { useAppContext } from '@/context/app-context'+import { DeploymentDetailSection, DeploymentDetailTop } from '@/features/deployments/detail/deployment-sidebar'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import Link from '@/next/link'import { usePathname } from '@/next/navigation'@@ -29,6 +30,7 @@ import { WorkspaceCard } from './components/workspace-card'const DATASET_COLLECTION_ROUTES = new Set(['create', 'create-from-pipeline', 'connect'])const DATASET_DOCUMENT_CREATION_ROUTES = new Set(['create', 'create-from-pipeline'])+const DEPLOYMENT_COLLECTION_ROUTES = new Set(['create'])const DETAIL_SIDEBAR_STORAGE_KEY = 'app-detail-collapse-or-expand'const secondarySidebarHelpTriggerIcon = <span aria-hidden className="i-ri-question-line size-4 shrink-0" />@@ -60,6 +62,12 @@ const isDatasetDetailPathname = (pathname: string) => {return true}+const isDeploymentDetailPathname = (pathname: string) => {+ const [section, appInstanceId] = pathname.split('/').filter(Boolean)++ return section === 'deployments' && !!appInstanceId && !DEPLOYMENT_COLLECTION_ROUTES.has(appInstanceId)+}+const isSnippetDetailPathname = (pathname: string) => {const [section, snippetId] = pathname.split('/').filter(Boolean)@@ -74,10 +82,12 @@ const MainNav = ({const { langGeniusVersionInfo, isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor } = useAppContext()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const showEnvTag = langGeniusVersionInfo.current_env === 'TESTING' || langGeniusVersionInfo.current_env === 'DEVELOPMENT'+ const canUseAppDeploy = isCurrentWorkspaceEditor && systemFeatures.enable_app_deployconst showAppDetailNavigation = !isCurrentWorkspaceDatasetOperator && pathname.startsWith('/app/')const showDatasetDetailNavigation = isDatasetDetailPathname(pathname)+ const showDeploymentDetailNavigation = canUseAppDeploy && !isCurrentWorkspaceDatasetOperator && isDeploymentDetailPathname(pathname)const showSnippetDetailBottomNavigation = isSnippetDetailPathname(pathname)- const showDetailNavigation = showAppDetailNavigation || showDatasetDetailNavigation+ const showDetailNavigation = showAppDetailNavigation || showDatasetDetailNavigation || showDeploymentDetailNavigationconst { hasAppDetail, appSidebarExpand, setAppDetail, setAppSidebarExpand } = useAppStore(useShallow(state => ({hasAppDetail: !!state.appDetail,appSidebarExpand: state.appSidebarExpand,@@ -213,7 +223,16 @@ const MainNav = ({icon: 'i-custom-vender-main-nav-marketplace',activeIcon: 'i-custom-vender-main-nav-marketplace-active',},- ], [isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor, t])+ ...(canUseAppDeploy+ ? [{+ href: '/deployments',+ label: t('menus.deployments', { ns: 'common' }),+ active: (path: string) => path.startsWith('/deployments'),+ icon: 'i-ri-rocket-line',+ activeIcon: 'i-ri-rocket-fill',+ }]+ : []),+ ], [canUseAppDeploy, isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor, t])const renderLogo = () => (<Link@@ -272,12 +291,19 @@ const MainNav = ({onToggle={handleToggleDetailNavigation}/>)- : (- <DatasetDetailTop- expand={detailNavigationVisibleExpanded}- onToggle={handleToggleDetailNavigation}- />- )+ : showDatasetDetailNavigation+ ? (+ <DatasetDetailTop+ expand={detailNavigationVisibleExpanded}+ onToggle={handleToggleDetailNavigation}+ />+ )+ : (+ <DeploymentDetailTop+ expand={detailNavigationVisibleExpanded}+ onToggle={handleToggleDetailNavigation}+ />+ ): showSnippetDetailBottomNavigation? null: (@@ -294,7 +320,9 @@ const MainNav = ({{showDetailNavigation? showAppDetailNavigation? <AppDetailSection expand={detailNavigationVisibleExpanded} />- : <DatasetDetailSection expand={detailNavigationVisibleExpanded} />+ : showDatasetDetailNavigation+ ? <DatasetDetailSection expand={detailNavigationVisibleExpanded} />+ : <DeploymentDetailSection expand={detailNavigationVisibleExpanded} />: showSnippetDetailBottomNavigation? null: (diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsxindex d1e471cc514..bd8f54890e3 100644--- a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx+++ b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx@@ -101,7 +101,7 @@ vi.mock('reactflow', () => ({}))vi.mock('@/app/components/app/app-publisher', () => ({- default: (props: AppPublisherProps) => {+ AppPublisher: (props: AppPublisherProps) => {const inputs = props.inputs ?? []return (<divdiff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsxindex 1c4eeed4173..481f57e8e39 100644--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx@@ -16,7 +16,7 @@ import {} from 'react'import { useTranslation } from 'react-i18next'import { useEdges } from 'reactflow'-import AppPublisher from '@/app/components/app/app-publisher'+import { AppPublisher } from '@/app/components/app/app-publisher'import { useStore as useAppStore } from '@/app/components/app/store'import { useFeatures } from '@/app/components/base/features/hooks'import { Plan } from '@/app/components/billing/type'diff --git a/web/app/components/workflow/utils/common.ts b/web/app/components/workflow/utils/common.tsindex 0f5dacf3f28..a850e1cb6c6 100644--- a/web/app/components/workflow/utils/common.ts+++ b/web/app/components/workflow/utils/common.ts@@ -4,7 +4,7 @@* @param fallbackText - Text to show when finishedAt is not available (default: 'Running')* @returns Formatted string like " (14:30:25)" or " (Running)"*/-export const formatWorkflowRunIdentifier = (finishedAt?: number, fallbackText = 'Running'): string => {+export function formatWorkflowRunIdentifier(finishedAt?: number, fallbackText = 'Running'): string {if (!finishedAt) {const capitalized = fallbackText.charAt(0).toUpperCase() + fallbackText.slice(1)return ` (${capitalized})`diff --git a/web/context/access-control-store.ts b/web/context/access-control-store.tsdeleted file mode 100644index 1cb8eb98489..00000000000--- a/web/context/access-control-store.ts+++ /dev/null@@ -1,34 +0,0 @@-import type { AccessControlAccount, AccessControlGroup } from '@/models/access-control'-import type { App } from '@/types/app'-import { create } from 'zustand'-import { AccessMode } from '@/models/access-control'--type AccessControlStore = {- appId: App['id']- setAppId: (appId: App['id']) => void- specificGroups: AccessControlGroup[]- setSpecificGroups: (specificGroups: AccessControlGroup[]) => void- specificMembers: AccessControlAccount[]- setSpecificMembers: (specificMembers: AccessControlAccount[]) => void- currentMenu: AccessMode- setCurrentMenu: (currentMenu: AccessMode) => void- selectedGroupsForBreadcrumb: AccessControlGroup[]- setSelectedGroupsForBreadcrumb: (selectedGroupsForBreadcrumb: AccessControlGroup[]) => void-}--const useAccessControlStore = create<AccessControlStore>((set) => {- return {- appId: '',- setAppId: appId => set({ appId }),- specificGroups: [],- setSpecificGroups: specificGroups => set({ specificGroups }),- specificMembers: [],- setSpecificMembers: specificMembers => set({ specificMembers }),- currentMenu: AccessMode.SPECIFIC_GROUPS_MEMBERS,- setCurrentMenu: currentMenu => set({ currentMenu }),- selectedGroupsForBreadcrumb: [],- setSelectedGroupsForBreadcrumb: selectedGroupsForBreadcrumb => set({ selectedGroupsForBreadcrumb }),- }-})--export default useAccessControlStorediff --git a/web/context/query-client.tsx b/web/context/query-client.tsxindex 2b95159396e..84e726c1c0e 100644--- a/web/context/query-client.tsx+++ b/web/context/query-client.tsx@@ -2,6 +2,8 @@import type { QueryClient } from '@tanstack/react-query'import { QueryClientProvider } from '@tanstack/react-query'+import { queryClientAtom } from 'jotai-tanstack-query'+import { useHydrateAtoms } from 'jotai/react/utils'import { isServer } from '@/utils/client'import { makeQueryClient } from './query-client-server'@@ -20,7 +22,21 @@ export const TanstackQueryInitializer = ({ children }: { children: React.ReactNoconst queryClient = getQueryClient()return (<QueryClientProvider client={queryClient}>- {children}+ <HydrateJotaiQueryClient queryClient={queryClient}>+ {children}+ </HydrateJotaiQueryClient></QueryClientProvider>)}++function HydrateJotaiQueryClient({+ children,+ queryClient,+}: {+ children: React.ReactNode+ queryClient: QueryClient+}) {+ useHydrateAtoms(new Map([[queryClientAtom, queryClient]]))++ return children+}diff --git a/web/contract/console/explore.ts b/web/contract/console/explore.tsindex 977efab8a1e..0ff93471360 100644--- a/web/contract/console/explore.ts+++ b/web/contract/console/explore.ts@@ -1,3 +1,4 @@+import type { Subject } from '@dify/contracts/enterprise/types.gen'import type { ChatConfig } from '@/app/components/base/chat/types'import type { AccessMode } from '@/models/access-control'import type { Banner } from '@/models/app'@@ -35,6 +36,12 @@ type AppAccessModeResponse = {accessMode: AccessMode}+type UpdateAppAccessModeBody = {+ appId: string+ accessMode: AccessMode+ subjects?: Pick<Subject, 'subjectId' | 'subjectType'>[]+}+export const exploreAppsContract = base.route({path: '/explore/apps',@@ -96,6 +103,14 @@ export const exploreInstalledAppAccessModeContract = base.input(type<{ query: { appId: string } }>()).output(type<AppAccessModeResponse>())+export const exploreInstalledAppAccessModeUpdateContract = base+ .route({+ path: '/enterprise/webapp/app/access-mode',+ method: 'POST',+ })+ .input(type<{ body: UpdateAppAccessModeBody }>())+ .output(type<unknown>())+export const exploreInstalledAppParametersContract = base.route({path: '/installed-apps/{appId}/parameters',diff --git a/web/contract/router.ts b/web/contract/router.tsindex 2933192304f..84df265e918 100644--- a/web/contract/router.ts+++ b/web/contract/router.ts@@ -15,6 +15,7 @@ import {exploreAppsContract,exploreBannersContract,exploreInstalledAppAccessModeContract,+ exploreInstalledAppAccessModeUpdateContract,exploreInstalledAppMetaContract,exploreInstalledAppParametersContract,exploreInstalledAppPinContract,@@ -124,6 +125,7 @@ export const consoleRouterContract = {uninstallInstalledApp: exploreInstalledAppUninstallContract,updateInstalledApp: exploreInstalledAppPinContract,appAccessMode: exploreInstalledAppAccessModeContract,+ updateAppAccessMode: exploreInstalledAppAccessModeUpdateContract,installedAppParameters: exploreInstalledAppParametersContract,installedAppMeta: exploreInstalledAppMetaContract,banners: exploreBannersContract,diff --git a/web/features/deployments/components/__tests__/env-var-bindings-utils.spec.ts b/web/features/deployments/components/__tests__/env-var-bindings-utils.spec.tsnew file mode 100644index 00000000000..4541f075e25--- /dev/null+++ b/web/features/deployments/components/__tests__/env-var-bindings-utils.spec.ts@@ -0,0 +1,53 @@+import type { EnvVarSlot } from '@dify/contracts/enterprise/types.gen'+import { EnvVarValueType } from '@dify/contracts/enterprise/types.gen'+import { describe, expect, it } from 'vitest'+import {+ envVarBindingSlotFromContract,+ envVarBindingValueType,+} from '../env-var-bindings-utils'++function slot(overrides: Partial<EnvVarSlot>): EnvVarSlot {+ return {+ key: 'API_KEY',+ valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ description: '',+ ...overrides,+ }+}++describe('env var binding value type normalization', () => {+ it('should normalize generated and DSL value types', () => {+ expect(envVarBindingValueType(EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER)).toBe('number')+ expect(envVarBindingValueType('number')).toBe('number')+ expect(envVarBindingValueType(EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET)).toBe('secret')+ expect(envVarBindingValueType('secret')).toBe('secret')+ expect(envVarBindingValueType(EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING)).toBe('string')+ expect(envVarBindingValueType()).toBe('string')+ })+})++describe('env var contract slot conversion', () => {+ it('should trim keys and preserve default and last value availability', () => {+ expect(envVarBindingSlotFromContract(slot({+ key: ' API_TOKEN ',+ valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET,+ defaultValue: '',+ lastValue: 'previous',+ }))).toMatchObject({+ key: 'API_TOKEN',+ valueType: 'secret',+ hasDefaultValue: true,+ hasLastValue: true,+ })+ })++ it('should ignore blank keys and mark absent values as unavailable', () => {+ expect(envVarBindingSlotFromContract(slot({ key: ' ' }))).toBeUndefined()+ expect(envVarBindingSlotFromContract(slot({ key: 'PORT', valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER }))).toMatchObject({+ key: 'PORT',+ valueType: 'number',+ hasDefaultValue: false,+ hasLastValue: false,+ })+ })+})diff --git a/web/features/deployments/components/__tests__/runtime-credential-bindings-utils.spec.ts b/web/features/deployments/components/__tests__/runtime-credential-bindings-utils.spec.tsnew file mode 100644index 00000000000..54b67adad22--- /dev/null+++ b/web/features/deployments/components/__tests__/runtime-credential-bindings-utils.spec.ts@@ -0,0 +1,129 @@+import type {+ CredentialCandidate,+ CredentialSlot,+} from '@dify/contracts/enterprise/types.gen'+import { PluginCategory } from '@dify/contracts/enterprise/types.gen'+import { describe, expect, it } from 'vitest'+import {+ hasMissingRequiredRuntimeCredentialBinding,+ runtimeCredentialCandidateOptions,+ runtimeCredentialProviderName,+ runtimeCredentialSlotKey,+ selectedDeploymentRuntimeCredentials,+ selectedRuntimeCredentialSelections,+} from '../runtime-credential-bindings-utils'++function candidate(overrides: Partial<CredentialCandidate>): CredentialCandidate {+ return {+ credentialId: 'credential-1',+ providerId: 'langgenius/openai',+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ displayName: 'OpenAI key',+ fromEnterprise: false,+ ...overrides,+ }+}++function slot(overrides: Partial<CredentialSlot>): CredentialSlot {+ return {+ providerId: 'langgenius/openai',+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ candidates: [+ candidate({ credentialId: 'credential-1', displayName: 'Primary key' }),+ candidate({ credentialId: 'credential-2', displayName: 'Backup key' }),+ ],+ lastCredentialId: '',+ ...overrides,+ }+}++describe('runtime credential provider names', () => {+ it('should resolve known provider slugs and title-case custom slugs', () => {+ expect(runtimeCredentialProviderName('langgenius/openai')).toBe('OpenAI')+ expect(runtimeCredentialProviderName('langgenius/azure_openai')).toBe('Azure OpenAI')+ expect(runtimeCredentialProviderName('custom/my-provider')).toBe('My Provider')+ expect(runtimeCredentialProviderName('/')).toBeUndefined()+ })+})++describe('runtime credential selection helpers', () => {+ it('should build stable slot keys and candidate labels', () => {+ const credentialSlot = slot({+ candidates: [+ candidate({+ credentialId: 'credential-1',+ providerId: 'langgenius/openai',+ displayName: 'Production key · langgenius/openai',+ }),+ candidate({+ credentialId: 'credential-2',+ providerId: 'langgenius/openai',+ displayName: 'Backup key (langgenius/openai)',+ }),+ candidate({+ credentialId: 'credential-3',+ providerId: 'langgenius/openai',+ displayName: '',+ }),+ ],+ })++ expect(runtimeCredentialSlotKey(credentialSlot)).toBe('langgenius/openai:PLUGIN_CATEGORY_MODEL')+ expect(runtimeCredentialCandidateOptions(credentialSlot)).toEqual([+ { value: 'credential-1', label: 'Production key' },+ { value: 'credential-2', label: 'Backup key' },+ { value: 'credential-3', label: 'credential-3' },+ ])+ })++ it('should prefer valid manual selections before last or only candidates', () => {+ const firstSlot = slot({+ providerId: 'langgenius/openai',+ lastCredentialId: 'credential-2',+ })+ const secondSlot = slot({+ providerId: 'langgenius/bedrock',+ candidates: [candidate({ credentialId: 'bedrock-1', providerId: 'langgenius/bedrock' })],+ lastCredentialId: '',+ })+ const thirdSlot = slot({+ providerId: 'custom/empty',+ candidates: [+ candidate({ credentialId: 'empty-1', providerId: 'custom/empty' }),+ candidate({ credentialId: 'empty-2', providerId: 'custom/empty' }),+ ],+ lastCredentialId: 'stale',+ })++ expect(selectedRuntimeCredentialSelections(+ [firstSlot, secondSlot, thirdSlot],+ {+ [runtimeCredentialSlotKey(firstSlot)]: 'credential-1',+ [runtimeCredentialSlotKey(secondSlot)]: 'stale',+ },+ )).toEqual({+ [runtimeCredentialSlotKey(firstSlot)]: 'credential-1',+ [runtimeCredentialSlotKey(secondSlot)]: 'bedrock-1',+ })+ })++ it('should convert selected credentials into deployment payload inputs', () => {+ const firstSlot = slot({ providerId: 'langgenius/openai' })+ const secondSlot = slot({ providerId: 'langgenius/bedrock' })++ expect(hasMissingRequiredRuntimeCredentialBinding(firstSlot)).toBe(true)+ expect(hasMissingRequiredRuntimeCredentialBinding(firstSlot, 'credential-1')).toBe(false)+ expect(selectedDeploymentRuntimeCredentials(+ [firstSlot, secondSlot],+ {+ [runtimeCredentialSlotKey(firstSlot)]: 'credential-1',+ },+ )).toEqual([+ {+ providerId: 'langgenius/openai',+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ credentialId: 'credential-1',+ },+ ])+ })+})diff --git a/web/features/deployments/components/deployment-actions/delete-dialog.tsx b/web/features/deployments/components/deployment-actions/delete-dialog.tsxnew file mode 100644index 00000000000..e2a79e060b6--- /dev/null+++ b/web/features/deployments/components/deployment-actions/delete-dialog.tsx@@ -0,0 +1,88 @@+'use client'++import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { useRouter } from '@/next/navigation'+import { consoleQuery } from '@/service/client'++export function DeleteDeploymentDialog({+ appInstanceId,+ appName,+ open,+ onOpenChange,+}: {+ appInstanceId: string+ appName?: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('deployments')+ const router = useRouter()+ const deleteInstance = useMutation(consoleQuery.enterprise.appInstanceService.deleteAppInstance.mutationOptions())+ const displayName = appName || appInstanceId++ function handleDelete() {+ deleteInstance.mutate(+ {+ params: {+ appInstanceId,+ },+ },+ {+ onSuccess: () => {+ toast.success(t('settings.deleted'))+ router.push('/deployments')+ },+ onError: () => {+ toast.error(t('settings.deleteFailed'))+ },+ onSettled: () => {+ onOpenChange(false)+ },+ },+ )+ }++ return (+ <AlertDialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen && deleteInstance.isPending)+ return+ onOpenChange(nextOpen)+ }}+ >+ <AlertDialogContent className="w-120">+ <div className="flex flex-col gap-3 px-6 pt-6 pb-2">+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('settings.deleteConfirmTitle')}+ </AlertDialogTitle>+ <AlertDialogDescription className="system-sm-regular text-text-tertiary">+ {t('settings.deleteConfirmDesc', { name: displayName })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions className="pt-3">+ <AlertDialogCancelButton variant="secondary" disabled={deleteInstance.isPending}>+ {t('createModal.cancel')}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton+ loading={deleteInstance.isPending}+ onClick={handleDelete}+ >+ {t('settings.delete')}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/web/features/deployments/components/deployment-actions/edit-dialog.tsx b/web/features/deployments/components/deployment-actions/edit-dialog.tsxnew file mode 100644index 00000000000..a1a367022a1--- /dev/null+++ b/web/features/deployments/components/deployment-actions/edit-dialog.tsx@@ -0,0 +1,206 @@+'use client'++import type { AppInstance } from '@dify/contracts/enterprise/types.gen'+import type { FormEvent } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { Input } from '@langgenius/dify-ui/input'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation, useQuery } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import { consoleQuery } from '@/service/client'++type EditDeploymentFormValues = {+ name: string+ description: string+}++function EditDeploymentFormSkeleton() {+ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-2">+ <SkeletonRectangle className="my-0 h-3 w-24 animate-pulse" />+ <SkeletonRectangle className="my-0 h-8 w-full animate-pulse rounded-lg" />+ </div>+ <div className="flex flex-col gap-2">+ <SkeletonRectangle className="my-0 h-3 w-28 animate-pulse" />+ <SkeletonRectangle className="my-0 h-24 w-full animate-pulse rounded-lg" />+ </div>+ <SkeletonRow className="justify-end gap-2">+ <SkeletonRectangle className="my-0 h-8 w-16 animate-pulse rounded-lg" />+ <SkeletonRectangle className="my-0 h-8 w-24 animate-pulse rounded-lg" />+ </SkeletonRow>+ </div>+ )+}++function EditDeploymentForm({+ app,+ isSaving,+ onClose,+ onSubmit,+}: {+ app: AppInstance+ isSaving: boolean+ onClose: () => void+ onSubmit: (values: EditDeploymentFormValues) => void+}) {+ const { t } = useTranslation('deployments')+ const initialName = app.displayName+ const initialDescription = app.description+ const [name, setName] = useState(initialName)+ const [description, setDescription] = useState(initialDescription)+ const normalizedName = name.trim()+ const normalizedDescription = description.trim()+ const canSave = Boolean(normalizedName && (normalizedName !== initialName || normalizedDescription !== initialDescription) && !isSaving)++ function handleSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault()+ if (!canSave)+ return++ onSubmit({+ name: normalizedName,+ description: normalizedDescription,+ })+ }++ return (+ <form className="flex flex-col gap-4" onSubmit={handleSubmit}>+ <div className="flex flex-col gap-2">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="deployment-edit-name">+ {t('settings.name')}+ </label>+ <Input+ id="deployment-edit-name"+ type="text"+ value={name}+ onChange={event => setName(event.target.value)}+ className="h-8"+ />+ </div>+ <div className="flex flex-col gap-2">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="deployment-edit-description">+ {t('settings.description')}+ </label>+ <Textarea+ id="deployment-edit-description"+ value={description}+ onValueChange={setDescription}+ className="min-h-24"+ />+ </div>+ <div className="flex justify-end gap-2 pt-2">+ <Button+ type="button"+ variant="secondary"+ disabled={isSaving}+ onClick={onClose}+ >+ {t('createModal.cancel')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ disabled={!canSave}+ loading={isSaving}+ >+ {t('settings.save')}+ </Button>+ </div>+ </form>+ )+}++export function EditDeploymentDialog({+ appInstanceId,+ open,+ onOpenChange,+}: {+ appInstanceId: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('deployments')+ const updateInstance = useMutation(consoleQuery.enterprise.appInstanceService.updateAppInstance.mutationOptions())+ const instanceQuery = useQuery(consoleQuery.enterprise.appInstanceService.getAppInstance.queryOptions({+ input: {+ params: { appInstanceId },+ },+ enabled: open,+ }))+ const app = instanceQuery.data?.appInstance+ const formKey = app ? `${app.id}-${app.displayName}-${app.description}` : 'loading'++ function handleOpenChange(nextOpen: boolean) {+ if (!nextOpen && updateInstance.isPending)+ return+ onOpenChange(nextOpen)+ }++ function handleClose() {+ handleOpenChange(false)+ }++ function handleSubmit(values: EditDeploymentFormValues) {+ updateInstance.mutate(+ {+ params: {+ appInstanceId,+ },+ body: {+ appInstanceId,+ displayName: values.name,+ description: values.description || undefined,+ },+ },+ {+ onSuccess: () => {+ toast.success(t('settings.updated'))+ onOpenChange(false)+ },+ onError: () => {+ toast.error(t('settings.updateFailed'))+ },+ },+ )+ }++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="w-120 max-w-[calc(100vw-32px)] p-0">+ <DialogCloseButton disabled={updateInstance.isPending} />+ <div className="border-b border-divider-subtle px-6 py-5">+ <DialogTitle className="title-xl-semi-bold text-text-primary">+ {t('card.menu.editInfo')}+ </DialogTitle>+ </div>+ <div className="px-6 py-5">+ {instanceQuery.isLoading+ ? <EditDeploymentFormSkeleton />+ : instanceQuery.isError+ ? <div className="system-sm-regular text-text-tertiary">{t('common.loadFailed')}</div>+ : app+ ? (+ <EditDeploymentForm+ key={formKey}+ app={app}+ isSaving={updateInstance.isPending}+ onClose={handleClose}+ onSubmit={handleSubmit}+ />+ )+ : <div className="system-sm-regular text-text-tertiary">{t('detail.notFound')}</div>}+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/deployments/components/deployment-actions/index.spec.tsx b/web/features/deployments/components/deployment-actions/index.spec.tsxnew file mode 100644index 00000000000..42229edd338--- /dev/null+++ b/web/features/deployments/components/deployment-actions/index.spec.tsx@@ -0,0 +1,34 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { DeploymentActionsMenu } from './index'++vi.mock('@langgenius/dify-ui/dropdown-menu', () => import('@/__mocks__/base-ui-dropdown-menu'))++vi.mock('./edit-dialog', () => ({+ EditDeploymentDialog: () => null,+}))++vi.mock('./delete-dialog', () => ({+ DeleteDeploymentDialog: () => null,+}))++describe('DeploymentActionsMenu', () => {+ it('keeps the trigger wrapper visible while the menu is open', () => {+ const { container } = render(+ <DeploymentActionsMenu+ appInstanceId="app-instance-1"+ placement="bottom-end"+ className="pointer-events-none opacity-0"+ />,+ )++ const wrapper = container.querySelector('[role="presentation"]') as HTMLElement+ expect(wrapper).toHaveClass('pointer-events-none', 'opacity-0')++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))++ expect(screen.getByText('deployments.card.menu.editInfo')).toBeInTheDocument()+ expect(wrapper).toHaveClass('pointer-events-auto', 'opacity-100')+ expect(wrapper).not.toHaveClass('pointer-events-none', 'opacity-0')+ })+})diff --git a/web/features/deployments/components/deployment-actions/index.tsx b/web/features/deployments/components/deployment-actions/index.tsxnew file mode 100644index 00000000000..7db4e6c9db3--- /dev/null+++ b/web/features/deployments/components/deployment-actions/index.tsx@@ -0,0 +1,101 @@+'use client'++import type { ComponentProps } from 'react'+import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { DeleteDeploymentDialog } from './delete-dialog'+import { EditDeploymentDialog } from './edit-dialog'++const ACTION_TRIGGER_CLASS_NAME = cn(+ 'inline-flex size-8 items-center justify-center rounded-lg bg-components-panel-bg text-text-tertiary shadow-xs outline-hidden',+ 'hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid',+ 'data-popup-open:bg-state-base-hover data-popup-open:text-text-secondary',+)++type DeploymentActionsMenuProps = {+ appInstanceId: string+ appName?: string+ className?: string+ triggerClassName?: string+ placement: ComponentProps<typeof DropdownMenuContent>['placement']+ sideOffset?: ComponentProps<typeof DropdownMenuContent>['sideOffset']+}++export function DeploymentActionsMenu({+ appInstanceId,+ appName,+ className,+ triggerClassName,+ placement,+ sideOffset,+}: DeploymentActionsMenuProps) {+ const { t } = useTranslation('deployments')+ const [menuOpen, setMenuOpen] = useState(false)+ const [editOpen, setEditOpen] = useState(false)+ const [deleteOpen, setDeleteOpen] = useState(false)++ function openEditDialog() {+ setMenuOpen(false)+ setEditOpen(true)+ }++ function openDeleteDialog() {+ setMenuOpen(false)+ setDeleteOpen(true)+ }++ return (+ <div+ role="presentation"+ className={cn(className, menuOpen && 'pointer-events-auto opacity-100')}+ onClick={event => event.stopPropagation()}+ onKeyDown={event => event.stopPropagation()}+ >+ <DropdownMenu modal={false} open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger+ aria-label={t('card.moreActions')}+ className={cn(ACTION_TRIGGER_CLASS_NAME, triggerClassName)}+ >+ <span aria-hidden className="i-ri-more-fill size-4" />+ </DropdownMenuTrigger>+ {menuOpen && (+ <DropdownMenuContent placement={placement} sideOffset={sideOffset} popupClassName="min-w-44">+ <DropdownMenuItem className="gap-2 px-3" onClick={openEditDialog}>+ <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">{t('card.menu.editInfo')}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ className="gap-2 px-3"+ onClick={openDeleteDialog}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />+ <span className="system-sm-regular">{t('card.menu.delete')}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ )}+ </DropdownMenu>++ <EditDeploymentDialog+ appInstanceId={appInstanceId}+ open={editOpen}+ onOpenChange={setEditOpen}+ />+ <DeleteDeploymentDialog+ appInstanceId={appInstanceId}+ appName={appName}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ />+ </div>+ )+}diff --git a/web/features/deployments/components/empty-state.tsx b/web/features/deployments/components/empty-state.tsxnew file mode 100644index 00000000000..fe2fe2d3217--- /dev/null+++ b/web/features/deployments/components/empty-state.tsx@@ -0,0 +1,143 @@+'use client'++import type { ReactNode } from 'react'+import { cn } from '@langgenius/dify-ui/cn'++type DeploymentEmptyStateVariant = 'page' | 'list' | 'section' | 'compact'+type DeploymentStateMessageVariant = 'page' | 'list' | 'section' | 'compact' | 'embedded'+type DeploymentEmptyStateAlign = 'center' | 'start'++type DeploymentEmptyStateProps = {+ icon?: string+ title: ReactNode+ description?: ReactNode+ action?: ReactNode+ variant?: DeploymentEmptyStateVariant+ align?: DeploymentEmptyStateAlign+ className?: string+}++type DeploymentStateMessageProps = {+ children: ReactNode+ variant?: DeploymentStateMessageVariant+ className?: string+}++type DeploymentNoticeStateProps = {+ children: ReactNode+ icon?: string+ className?: string+}++const emptyStateContainerClassNames: Record<DeploymentEmptyStateVariant, string> = {+ page: 'col-span-full min-h-80 rounded-xl border border-divider-subtle bg-background-default-subtle px-6 py-12',+ list: 'min-h-60 rounded-lg border border-divider-subtle bg-background-default-subtle px-6 py-12',+ section: 'min-h-36 rounded-lg border border-divider-subtle bg-background-default-subtle px-6 py-8',+ compact: 'min-h-14 rounded-lg border border-divider-subtle bg-background-default-subtle px-3 py-3',+}++const stateMessageClassNames: Record<DeploymentStateMessageVariant, string> = {+ page: 'col-span-full flex min-h-80 items-center justify-center rounded-xl border border-dashed border-divider-subtle bg-background-default-subtle px-6 py-12 text-center system-sm-regular text-text-tertiary',+ list: 'flex min-h-36 items-center justify-center rounded-lg border border-dashed border-divider-subtle bg-background-default-subtle px-6 py-12 text-center system-sm-regular text-text-tertiary',+ section: 'flex min-h-24 items-center justify-center rounded-lg border border-dashed border-divider-subtle bg-background-default-subtle px-4 py-6 text-center system-sm-regular text-text-tertiary',+ compact: 'rounded-lg border border-dashed border-divider-subtle bg-background-default-subtle px-3 py-3 system-sm-regular text-text-tertiary',+ embedded: 'px-4 py-10 text-center system-sm-regular text-text-tertiary',+}++export function DeploymentEmptyState({+ icon,+ title,+ description,+ action,+ variant = 'list',+ align,+ className,+}: DeploymentEmptyStateProps) {+ const effectiveAlign = align ?? (variant === 'compact' ? 'start' : 'center')+ const isLarge = variant === 'page' || variant === 'list'+ const hasDescription = Boolean(description)+ const hasAction = Boolean(action)+ const hasIcon = Boolean(icon)++ return (+ <div+ data-slot="deployment-empty-state"+ className={cn(+ 'flex flex-col justify-center border-dashed',+ effectiveAlign === 'center' ? 'items-center text-center' : 'items-start text-left',+ emptyStateContainerClassNames[variant],+ className,+ )}+ >+ {hasIcon && (+ <span+ className={cn(+ 'flex items-center justify-center border border-components-panel-border bg-background-default-subtle text-text-tertiary',+ variant === 'compact' ? 'mb-2 size-8 rounded-lg' : 'mb-4',+ isLarge && 'size-11 rounded-xl',+ variant === 'section' && 'size-10 rounded-lg bg-background-section-burn',+ )}+ >+ <span+ className={cn(+ icon,+ isLarge ? 'size-5' : variant === 'section' ? 'size-4.5' : 'size-4',+ )}+ aria-hidden="true"+ />+ </span>+ )}+ <div+ className={cn(+ isLarge+ ? 'system-md-semibold text-text-primary'+ : variant === 'compact' && !hasIcon && !hasDescription+ ? 'system-sm-regular text-text-tertiary'+ : 'system-sm-medium text-text-secondary',+ )}+ >+ {title}+ </div>+ {hasDescription && (+ <p+ className={cn(+ 'mt-1 max-w-120 text-text-tertiary',+ isLarge ? 'system-sm-regular' : 'system-xs-regular',+ )}+ >+ {description}+ </p>+ )}+ {hasAction && (+ <div className={isLarge ? 'mt-5' : variant === 'compact' ? 'mt-3' : 'mt-4'}>+ {action}+ </div>+ )}+ </div>+ )+}++export function DeploymentStateMessage({+ children,+ variant = 'list',+ className,+}: DeploymentStateMessageProps) {+ return (+ <div className={cn(stateMessageClassNames[variant], className)}>+ {children}+ </div>+ )+}++export function DeploymentNoticeState({+ children,+ icon = 'i-ri-information-line',+ className,+}: DeploymentNoticeStateProps) {+ return (+ <div className={cn('flex min-h-9 items-start gap-1.5 rounded-lg border border-divider-subtle bg-background-default-subtle px-3 py-2 system-xs-regular text-text-tertiary', className)}>+ <span className={cn(icon, 'mt-0.5 size-3.5 shrink-0 text-text-quaternary')} aria-hidden="true" />+ <span className="min-w-0">{children}</span>+ </div>+ )+}diff --git a/web/features/deployments/components/env-var-bindings-utils.ts b/web/features/deployments/components/env-var-bindings-utils.tsnew file mode 100644index 00000000000..422fdfbca5f--- /dev/null+++ b/web/features/deployments/components/env-var-bindings-utils.ts@@ -0,0 +1,29 @@+import type { EnvVarSlot } from '@dify/contracts/enterprise/types.gen'+import type { EnvVarBindingSlot } from './env-var-bindings'++export function envVarBindingValueType(valueType?: EnvVarSlot['valueType'] | string): EnvVarBindingSlot['valueType'] {+ switch (valueType) {+ case 'ENV_VAR_VALUE_TYPE_NUMBER':+ case 'number':+ return 'number'+ case 'ENV_VAR_VALUE_TYPE_SECRET':+ case 'secret':+ return 'secret'+ default:+ return 'string'+ }+}++export function envVarBindingSlotFromContract(slot: EnvVarSlot): EnvVarBindingSlot | undefined {+ const key = slot.key.trim()+ if (!key)+ return undefined++ return {+ ...slot,+ key,+ valueType: envVarBindingValueType(slot.valueType),+ hasDefaultValue: slot.defaultValue !== undefined,+ hasLastValue: slot.lastValue !== undefined,+ }+}diff --git a/web/features/deployments/components/env-var-bindings.tsx b/web/features/deployments/components/env-var-bindings.tsxnew file mode 100644index 00000000000..714e0c95623--- /dev/null+++ b/web/features/deployments/components/env-var-bindings.tsx@@ -0,0 +1,245 @@+'use client'++import type { EnvVarInput, EnvVarSlot } from '@dify/contracts/enterprise/types.gen'+import type {+ InputHTMLAttributes,+} from 'react'+import { EnvVarValueSource as ApiEnvVarValueSource } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@langgenius/dify-ui/segmented-control'+import { TitleTooltip } from './title-tooltip'++export type EnvVarValueSource = NonNullable<EnvVarInput['valueSource']>+type EnvVarValueType = 'string' | 'number' | 'secret'+// Contract EnvVarSlot carries an EnvVarValueType enum and signals default/last+// presence via optional fields; binding slots keep the legacy lowercase value+// type plus explicit has* flags because DSL-metadata slots share this shape.+// Adapters live in env-var-bindings-utils.ts.+export type EnvVarBindingSlot = Omit<EnvVarSlot, 'valueType'> & {+ key: string+ valueType: EnvVarValueType+ hasDefaultValue?: boolean+ hasLastValue?: boolean+}+export type EnvVarValueSelection = {+ valueSource: EnvVarValueSource+ value?: string+}+export type EnvVarValues = Record<string, EnvVarValueSelection>+type EnvVarDefaultSourcePriority = 'dslDefault' | 'lastDeployment'++type EnvVarValueSourceOption = {+ value: EnvVarValueSource+ label: string+}++type EnvVarBindingsPanelProps = {+ slots: EnvVarBindingSlot[]+ values: EnvVarValues+ title: string+ hint: string+ envVarPlaceholder: string+ literalSourceLabel: string+ defaultSourceLabel: string+ lastDeploymentSourceLabel: string+ valueTypeLabels: Record<EnvVarValueType, string>+ sourceAriaLabel: (key: string) => string+ defaultSourcePriority?: EnvVarDefaultSourcePriority+ envVarCountLabel?: string+ missingRequiredLabel?: string+ showMissingRequired?: boolean+ listScrollable?: boolean+ onChange: (key: string, value: EnvVarValueSelection) => void+ className?: string+ listClassName?: string+}++const ENV_VAR_INPUT_TYPES = {+ string: 'text',+ number: 'number',+ secret: 'password',+} satisfies Record<EnvVarValueType, InputHTMLAttributes<HTMLInputElement>['type']>++function envVarInputId(index: number, key: string) {+ const safeKey = key.replace(/[^\w-]/g, '-')++ return `env-var-binding-${index}-${safeKey}`+}++function envVarValueSourceOptions(slot: EnvVarBindingSlot, labels: {+ literal: string+ defaultValue: string+ lastDeployment: string+}): EnvVarValueSourceOption[] {+ const options: EnvVarValueSourceOption[] = [+ {+ value: ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ label: labels.literal,+ },+ ]++ if (slot.hasDefaultValue) {+ options.push({+ value: ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT,+ label: labels.defaultValue,+ })+ }++ if (slot.hasLastValue) {+ options.push({+ value: ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT,+ label: labels.lastDeployment,+ })+ }++ return options+}++export function EnvVarBindingsPanel({+ slots,+ values,+ title,+ hint,+ envVarPlaceholder,+ literalSourceLabel,+ defaultSourceLabel,+ lastDeploymentSourceLabel,+ valueTypeLabels,+ sourceAriaLabel,+ defaultSourcePriority,+ envVarCountLabel,+ missingRequiredLabel,+ showMissingRequired = false,+ listScrollable = true,+ onChange,+ className,+ listClassName,+}: EnvVarBindingsPanelProps) {+ if (slots.length === 0)+ return null++ return (+ <div className={cn('overflow-hidden rounded-xl border border-divider-subtle bg-background-default-subtle', className)}>+ <div className="flex min-w-0 flex-col gap-0.5 px-3 py-2.5">+ <div className="flex min-w-0 items-center gap-2">+ <div className="system-xs-medium-uppercase text-text-tertiary">{title}</div>+ <span className="shrink-0 rounded-md bg-background-default px-1.5 py-0.5 system-2xs-medium text-text-tertiary">+ {envVarCountLabel ?? slots.length}+ </span>+ </div>+ <span className="system-xs-regular text-text-tertiary">{hint}</span>+ </div>+ <div+ className={cn(+ 'border-t border-divider-subtle',+ listScrollable ? 'max-h-[min(360px,34dvh)] overflow-y-auto' : 'overflow-visible',+ listClassName,+ )}+ >+ {slots.map((slot, index) => {+ const description = slot.description+ const inputId = envVarInputId(index, slot.key)+ const selection = values[slot.key]+ const defaultValueSource = defaultSourcePriority === 'lastDeployment' && slot.hasLastValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT+ : slot.hasDefaultValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT+ : slot.hasLastValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT+ : ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL+ const valueSource = selection?.valueSource ?? defaultValueSource+ const invalidLiteralNumber = slot.valueType === 'number' && Number.isNaN(Number(selection?.value))+ const missing = showMissingRequired+ && valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL+ && (!selection?.value || invalidLiteralNumber)+ const sourceOptions = envVarValueSourceOptions(slot, {+ literal: literalSourceLabel,+ defaultValue: defaultSourceLabel,+ lastDeployment: lastDeploymentSourceLabel,+ })+ const isLiteralValue = valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL+ const displayValue = valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT+ ? slot.defaultValue+ : valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT+ ? slot.lastValue+ : selection?.value++ return (+ <div key={slot.key} className="flex min-w-0 flex-col gap-2 border-b border-divider-subtle px-3 py-3 last:border-b-0">+ <div className="flex min-w-0 flex-col gap-2.5">+ <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-1.5">+ <span aria-hidden="true" className="i-custom-vender-line-others-env size-4 shrink-0 text-util-colors-violet-violet-600" />+ <TitleTooltip content={slot.key}>+ <label className="truncate font-mono system-sm-semibold text-text-primary" htmlFor={inputId}>+ {slot.key}+ </label>+ </TitleTooltip>+ <span className="shrink-0 system-sm-medium text-text-tertiary">+ {valueTypeLabels[slot.valueType]}+ </span>+ {slot.valueType === 'secret' && (+ <span aria-hidden="true" className="i-ri-lock-2-line size-3 shrink-0 text-text-tertiary" />+ )}+ </div>+ {sourceOptions.length > 1 && (+ <SegmentedControl<EnvVarValueSource>+ aria-label={sourceAriaLabel(slot.key)}+ value={[valueSource]}+ onValueChange={(value) => {+ const nextSource = value[0]+ if (!nextSource)+ return+ onChange(slot.key, {+ value: selection?.value,+ valueSource: nextSource,+ })+ }}+ className="shrink-0"+ >+ {sourceOptions.map(option => (+ <SegmentedControlItem key={option.value} value={option.value} className="px-2 system-xs-medium">+ {option.label}+ </SegmentedControlItem>+ ))}+ </SegmentedControl>+ )}+ </div>+ {description && (+ <TitleTooltip content={description}>+ <div className="line-clamp-2 system-xs-regular text-text-tertiary">+ {description}+ </div>+ </TitleTooltip>+ )}+ <Input+ id={inputId}+ type={ENV_VAR_INPUT_TYPES[slot.valueType]}+ value={displayValue ?? ''}+ onChange={event => onChange(slot.key, {+ value: event.target.value,+ valueSource: ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ })}+ placeholder={envVarPlaceholder}+ autoComplete="off"+ disabled={!isLiteralValue}+ required+ className="h-8"+ />+ </div>+ {missing && missingRequiredLabel && (+ <div className="system-xs-regular text-text-destructive">+ {missingRequiredLabel}+ </div>+ )}+ </div>+ )+ })}+ </div>+ </div>+ )+}diff --git a/web/features/deployments/components/runtime-credential-bindings-utils.ts b/web/features/deployments/components/runtime-credential-bindings-utils.tsnew file mode 100644index 00000000000..d80dc0b53c9--- /dev/null+++ b/web/features/deployments/components/runtime-credential-bindings-utils.ts@@ -0,0 +1,115 @@+import type {+ CredentialCandidate,+ CredentialSelectionInput,+ CredentialSlot,+} from '@dify/contracts/enterprise/types.gen'++export type RuntimeCredentialBindingSelections = Record<string, string>++export type RuntimeCredentialSelectOption = {+ value: string+ label: string+}++const PROVIDER_DISPLAY_NAMES: Record<string, string> = {+ azure_openai: 'Azure OpenAI',+ bedrock: 'Amazon Bedrock',+ gemini: 'Gemini',+ google: 'Google',+ openai: 'OpenAI',+ vertex_ai: 'Vertex AI',+ volcengine_maas: 'Volcengine',+}++function providerSlug(providerId: string) {+ const parts = providerId.split('/').filter(Boolean)+ return parts[parts.length - 1]+}++function titleCaseProviderName(value: string) {+ return value+ .split(/[-_]/)+ .filter(Boolean)+ .map(part => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)+ .join(' ')+}++export function runtimeCredentialSlotKey(slot: CredentialSlot) {+ return [slot.providerId, slot.category].join(':')+}++export function runtimeCredentialProviderName(providerId: string) {+ const slug = providerSlug(providerId)+ if (!slug)+ return undefined++ return PROVIDER_DISPLAY_NAMES[slug.toLowerCase()] ?? titleCaseProviderName(slug)+}++function runtimeCredentialCandidateLabel(candidate: CredentialCandidate) {+ const fallback = candidate.credentialId+ const rawLabel = candidate.displayName.trim() || fallback+ const providerId = candidate.providerId.trim()++ const providerSuffixes = [+ ` · ${providerId}`,+ ` - ${providerId}`,+ ` (${providerId})`,+ ]+ const label = providerSuffixes.reduce((nextLabel, suffix) => {+ return nextLabel.endsWith(suffix)+ ? nextLabel.slice(0, -suffix.length).trim()+ : nextLabel+ }, rawLabel)++ return label || fallback+}++export function runtimeCredentialCandidateOptions(slot: CredentialSlot): RuntimeCredentialSelectOption[] {+ return slot.candidates.map(candidate => ({+ value: candidate.credentialId,+ label: runtimeCredentialCandidateLabel(candidate),+ }))+}++export function hasMissingRequiredRuntimeCredentialBinding(_slot: CredentialSlot, selectedValue?: string) {+ return !selectedValue+}++export function selectedRuntimeCredentialSelections(+ slots: CredentialSlot[],+ manualBindings: RuntimeCredentialBindingSelections,+): RuntimeCredentialBindingSelections {+ const next: RuntimeCredentialBindingSelections = {}+ for (const slot of slots) {+ const slotKey = runtimeCredentialSlotKey(slot)+ const candidates = runtimeCredentialCandidateOptions(slot)+ const existing = manualBindings[slotKey]+ if (existing && candidates.some(candidate => candidate.value === existing))+ next[slotKey] = existing+ else if (slot.lastCredentialId && candidates.some(candidate => candidate.value === slot.lastCredentialId))+ next[slotKey] = slot.lastCredentialId+ else if (candidates.length === 1 && candidates[0])+ next[slotKey] = candidates[0].value+ }+ return next+}++export function selectedDeploymentRuntimeCredentials(+ slots: CredentialSlot[],+ selections: RuntimeCredentialBindingSelections,+): CredentialSelectionInput[] {+ return slots+ .flatMap((slot): CredentialSelectionInput[] => {+ const slotKey = runtimeCredentialSlotKey(slot)+ const selectedValue = selections[slotKey]+ if (!selectedValue)+ return []++ return [{+ providerId: slot.providerId,+ category: slot.category,+ credentialId: selectedValue,+ }]+ })+}diff --git a/web/features/deployments/components/runtime-credential-bindings.tsx b/web/features/deployments/components/runtime-credential-bindings.tsxnew file mode 100644index 00000000000..13e50eaf89e--- /dev/null+++ b/web/features/deployments/components/runtime-credential-bindings.tsx@@ -0,0 +1,197 @@+'use client'++import type {+ CredentialSlot,+} from '@dify/contracts/enterprise/types.gen'+import type {+ RuntimeCredentialBindingSelections,+ RuntimeCredentialSelectOption,+} from './runtime-credential-bindings-utils'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectTrigger,+} from '@langgenius/dify-ui/select'+import { useTranslation } from 'react-i18next'+import {+ hasMissingRequiredRuntimeCredentialBinding,+ runtimeCredentialCandidateOptions,+ runtimeCredentialProviderName,+ runtimeCredentialSlotKey,+} from './runtime-credential-bindings-utils'+import { TitleTooltip } from './title-tooltip'++type RuntimeCredentialBindingsPanelProps = {+ slots: CredentialSlot[]+ selections: RuntimeCredentialBindingSelections+ title: string+ hint: string+ noBindingRequiredLabel: string+ noCredentialCandidatesLabel: string+ selectCredentialLabel: string+ missingRequiredLabel: string+ bindingCountLabel?: string+ showMissingRequired?: boolean+ listScrollable?: boolean+ onChange: (slotKey: string, value: string) => void+ className?: string+ listClassName?: string+}++function RuntimeCredentialSelect({+ ariaLabel,+ value,+ options,+ placeholder,+ onChange,+}: {+ ariaLabel: string+ value?: string+ options: RuntimeCredentialSelectOption[]+ placeholder: string+ onChange: (value: string) => void+}) {+ const selectedOption = options.find(option => option.value === value)++ return (+ <Select+ value={value ?? null}+ onValueChange={(next) => {+ if (!next)+ return+ onChange(next)+ }}+ disabled={options.length === 0}+ >+ <SelectTrigger+ aria-label={ariaLabel}+ className={cn(+ 'h-8 min-w-0 px-2 text-left system-sm-medium',+ !selectedOption && 'text-text-quaternary',+ )}+ >+ {selectedOption?.label ?? placeholder}+ </SelectTrigger>+ <SelectContent popupClassName="w-(--anchor-width)">+ {options.map(option => (+ <SelectItem key={option.value} value={option.value}>+ <TitleTooltip content={option.label}>+ <SelectItemText>{option.label}</SelectItemText>+ </TitleTooltip>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}++export function RuntimeCredentialBindingsPanel({+ slots,+ selections,+ title,+ hint,+ noBindingRequiredLabel,+ noCredentialCandidatesLabel,+ selectCredentialLabel,+ missingRequiredLabel,+ bindingCountLabel,+ showMissingRequired = false,+ listScrollable = true,+ onChange,+ className,+ listClassName,+}: RuntimeCredentialBindingsPanelProps) {+ const { t } = useTranslation('plugin')++ return (+ <div className={cn('overflow-hidden rounded-xl border border-divider-subtle bg-background-default-subtle', className)}>+ <div className="flex min-w-0 flex-col gap-0.5 px-3 py-2.5">+ <div className="flex min-w-0 items-center gap-2">+ <div className="system-xs-medium-uppercase text-text-tertiary">{title}</div>+ {slots.length > 0 && (+ <span className="shrink-0 rounded-md bg-background-default px-1.5 py-0.5 system-2xs-medium text-text-tertiary">+ {bindingCountLabel ?? slots.length}+ </span>+ )}+ </div>+ <span className="system-xs-regular text-text-tertiary">{hint}</span>+ </div>+ {slots.length === 0+ ? (+ <div className="border-t border-divider-subtle px-3 py-3 system-sm-regular text-text-quaternary">+ {noBindingRequiredLabel}+ </div>+ )+ : (+ <div+ className={cn(+ 'border-t border-divider-subtle',+ listScrollable ? 'max-h-[min(360px,34dvh)] overflow-y-auto' : 'overflow-visible',+ listClassName,+ )}+ >+ {slots.map((slot) => {+ const slotKey = runtimeCredentialSlotKey(slot)+ const candidates = runtimeCredentialCandidateOptions(slot)+ const selectedValue = selections[slotKey]+ const missing = showMissingRequired && hasMissingRequiredRuntimeCredentialBinding(slot, selectedValue)+ const slotName = runtimeCredentialProviderName(slot.providerId) ?? slotKey+ const categoryLabel = slot.category === 'PLUGIN_CATEGORY_MODEL'+ ? t('categorySingle.model')+ : slot.category === 'PLUGIN_CATEGORY_TOOL'+ ? t('categorySingle.tool')+ : undefined++ return (+ <div key={slotKey} className="flex flex-col gap-2 border-b border-divider-subtle px-3 py-3 last:border-b-0">+ <div className="flex min-w-0 flex-col gap-2.5">+ <div className="flex min-w-0 flex-col gap-1.5">+ <div className="flex min-w-0 items-center gap-1.5">+ <TitleTooltip content={slotName}>+ <span className="truncate system-sm-semibold text-text-primary">+ {slotName}+ </span>+ </TitleTooltip>+ </div>+ <div className="flex flex-wrap items-center gap-1.5">+ {categoryLabel && (+ <span className="shrink-0 rounded-md bg-util-colors-blue-light-blue-light-50 px-1.5 py-0.5 system-2xs-medium-uppercase text-util-colors-blue-blue-600">+ {categoryLabel}+ </span>+ )}+ </div>+ </div>+ {candidates.length === 0+ ? (+ <div className="rounded-lg border border-divider-subtle bg-background-default px-2 py-1.5 system-sm-regular text-text-quaternary">+ {noCredentialCandidatesLabel}+ </div>+ )+ : (+ <RuntimeCredentialSelect+ ariaLabel={slotName}+ value={selectedValue}+ onChange={value => onChange(slotKey, value)}+ options={candidates}+ placeholder={selectCredentialLabel}+ />+ )}+ </div>+ {missing && (+ <div className="system-xs-regular text-text-destructive">+ {missingRequiredLabel}+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+}diff --git a/web/features/deployments/components/title-tooltip.spec.tsx b/web/features/deployments/components/title-tooltip.spec.tsxnew file mode 100644index 00000000000..ccf92313079--- /dev/null+++ b/web/features/deployments/components/title-tooltip.spec.tsx@@ -0,0 +1,71 @@+import type { ReactNode } from 'react'+import { fireEvent, render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { TitleTooltip } from './title-tooltip'++vi.mock('@langgenius/dify-ui/tooltip', () => ({+ Tooltip: ({ children }: { children: ReactNode }) => (+ <div data-testid="tooltip">+ {children}+ </div>+ ),+ TooltipTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,+ TooltipContent: ({ children }: { children: ReactNode }) => (+ <div role="tooltip">+ {children}+ </div>+ ),+}))++function setElementSize(element: HTMLElement, {+ clientWidth,+ scrollWidth,+}: {+ clientWidth: number+ scrollWidth: number+}) {+ Object.defineProperties(element, {+ clientWidth: { configurable: true, value: clientWidth },+ scrollWidth: { configurable: true, value: scrollWidth },+ })+}++describe('TitleTooltip', () => {+ it('does not show duplicate content when the trigger is not truncated', () => {+ render(+ <TitleTooltip content="11">+ <p>11</p>+ </TitleTooltip>,+ )++ fireEvent.pointerOver(screen.getByText('11'))++ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()+ })++ it('shows duplicate content when the trigger is truncated', () => {+ render(+ <TitleTooltip content="Long deployment name">+ <p>Long deployment name</p>+ </TitleTooltip>,+ )++ const trigger = screen.getByText('Long deployment name')+ setElementSize(trigger, { clientWidth: 80, scrollWidth: 160 })+ fireEvent.pointerOver(trigger)++ expect(screen.getByRole('tooltip')).toHaveTextContent('Long deployment name')+ })++ it('shows content that adds information beyond the trigger text', () => {+ render(+ <TitleTooltip content="Disabled until an initial release exists">+ <button type="button">Deploy</button>+ </TitleTooltip>,+ )++ fireEvent.pointerOver(screen.getByRole('button', { name: 'Deploy' }))++ expect(screen.getByRole('tooltip')).toHaveTextContent('Disabled until an initial release exists')+ })+})diff --git a/web/features/deployments/components/title-tooltip.tsx b/web/features/deployments/components/title-tooltip.tsxnew file mode 100644index 00000000000..f10f2708b27--- /dev/null+++ b/web/features/deployments/components/title-tooltip.tsx@@ -0,0 +1,74 @@+'use client'++import type { FocusEvent, PointerEvent, ReactElement, ReactNode } from 'react'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { cloneElement, useState } from 'react'++type TriggerProps = {+ onFocusCapture?: (event: FocusEvent<HTMLElement>) => void+ onPointerOverCapture?: (event: PointerEvent<HTMLElement>) => void+}++function normalizeText(value: string) {+ return value.replace(/\s+/g, ' ').trim()+}++function contentText(content: ReactNode) {+ if (typeof content === 'string' || typeof content === 'number')+ return String(content)+}++function isOverflowing(element: HTMLElement) {+ return element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight+}++function shouldShowTooltipContent(element: HTMLElement, content: ReactNode) {+ const text = contentText(content)+ if (text === undefined)+ return true++ if (normalizeText(text) !== normalizeText(element.textContent ?? ''))+ return true++ return isOverflowing(element)+}++export function TitleTooltip({+ children,+ content,+}: {+ children: ReactElement+ content?: ReactNode+}) {+ const [shouldShowContent, setShouldShowContent] = useState(false)++ if (!content)+ return children++ const childProps = children.props as TriggerProps++ function updateShouldShowContent(element: HTMLElement) {+ setShouldShowContent(shouldShowTooltipContent(element, content))+ }++ // eslint-disable-next-line react/no-clone-element -- Preserve the trigger element while adding overflow checks.+ const trigger = cloneElement(children as ReactElement<TriggerProps>, {+ onFocusCapture: (event) => {+ childProps.onFocusCapture?.(event)+ updateShouldShowContent(event.currentTarget)+ },+ onPointerOverCapture: (event) => {+ childProps.onPointerOverCapture?.(event)+ updateShouldShowContent(event.currentTarget)+ },+ })++ return (+ <Tooltip>+ <TooltipTrigger render={trigger} />+ {shouldShowContent && (+ <TooltipContent>{content}</TooltipContent>+ )}+ </Tooltip>+ )+}diff --git a/web/features/deployments/components/unsupported-dsl-nodes-alert.tsx b/web/features/deployments/components/unsupported-dsl-nodes-alert.tsxnew file mode 100644index 00000000000..f252586ce64--- /dev/null+++ b/web/features/deployments/components/unsupported-dsl-nodes-alert.tsx@@ -0,0 +1,69 @@+'use client'++import type { UnsupportedDslNode } from '../shared/domain/error'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'++function translatedNodeType(type: string | undefined, t: ReturnType<typeof useTranslation>['t']) {+ if (!type)+ return t('unsupportedDslNodes.unknownType')++ return t(`blocks.${type}`, {+ defaultValue: type,+ ns: 'workflow',+ })+}++function unsupportedNodeTypeLabels(nodes: UnsupportedDslNode[], t: ReturnType<typeof useTranslation>['t']) {+ return Array.from(new Set(nodes.map(node => translatedNodeType(node.type, t))))+}++function formattedNodeTypeList(labels: string[], language: string) {+ if (labels.length === 0)+ return ''++ try {+ return new Intl.ListFormat(language, { type: 'conjunction' }).format(labels)+ }+ catch {+ return labels.join(', ')+ }+}++export function UnsupportedDslNodesAlert({ nodes, className }: {+ nodes: UnsupportedDslNode[]+ className?: string+}) {+ const { i18n, t } = useTranslation('deployments')++ if (nodes.length === 0)+ return null++ const nodeTypeLabels = unsupportedNodeTypeLabels(nodes, t)+ const nodeTypes = formattedNodeTypeList(nodeTypeLabels, i18n.language)+ const description = nodeTypes+ ? t('unsupportedDslNodes.descriptionWithTypes', { nodeTypes })+ : t('unsupportedDslNodes.description')++ return (+ <div+ role="alert"+ className={cn(+ 'rounded-lg border border-util-colors-red-red-200 bg-util-colors-red-red-50 p-3',+ className,+ )}+ >+ <div className="flex items-start gap-2">+ <span aria-hidden className="mt-0.5 i-ri-error-warning-fill size-4 shrink-0 text-text-destructive" />+ <div className="min-w-0 grow">+ <div className="system-sm-semibold text-text-primary">+ {t('unsupportedDslNodes.title')}+ </div>+ <p className="mt-0.5 system-xs-regular text-text-secondary">+ {description}+ </p>+ </div>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/create-guide/index.tsx b/web/features/deployments/create-guide/index.tsxnew file mode 100644index 00000000000..462b869e7e5--- /dev/null+++ b/web/features/deployments/create-guide/index.tsx@@ -0,0 +1,35 @@+'use client'++import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'+import { useTranslation } from 'react-i18next'+import Link from '@/next/link'+import { useRouter } from '@/next/navigation'+import { CreateDeploymentGuideProvider } from './state/provider'+import { CreateDeploymentGuideShell } from './ui/shell'++export function CreateDeploymentGuide() {+ const { t } = useTranslation('deployments')+ const router = useRouter()++ return (+ <Dialog open onOpenChange={open => !open && router.push('/deployments')}>+ <DialogContent+ backdropClassName="bg-background-overlay-backdrop backdrop-blur-[6px]"+ className="top-4 bottom-4 h-auto max-h-none w-[min(calc(100vw-2rem),1120px)] max-w-none translate-y-0 overflow-hidden border-effects-highlight bg-background-default-subtle p-0"+ >+ <main className="relative flex h-full min-w-0 grow flex-col overflow-hidden">+ <Link+ href="/deployments"+ aria-label={t('createGuide.nav.back')}+ className="absolute top-3 right-3 z-50 flex h-9 w-9 cursor-pointer items-center justify-center rounded-[10px] bg-components-button-tertiary-bg hover:bg-components-button-tertiary-bg-hover"+ >+ <span aria-hidden="true" className="i-ri-close-large-line h-3.5 w-3.5 text-components-button-tertiary-text" />+ </Link>+ <CreateDeploymentGuideProvider>+ <CreateDeploymentGuideShell />+ </CreateDeploymentGuideProvider>+ </main>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/deployments/create-guide/state/environment.ts b/web/features/deployments/create-guide/state/environment.tsnew file mode 100644index 00000000000..9d7e27cb144--- /dev/null+++ b/web/features/deployments/create-guide/state/environment.ts@@ -0,0 +1,9 @@+import type { Environment } from '@dify/contracts/enterprise/types.gen'++export function environmentMatchesIdentifier(environment: Environment, identifier: string) {+ const normalizedIdentifier = identifier.trim()+ if (!normalizedIdentifier)+ return false++ return environment.id === normalizedIdentifier || environment.displayName === normalizedIdentifier+}diff --git a/web/features/deployments/create-guide/state/index.ts b/web/features/deployments/create-guide/state/index.tsnew file mode 100644index 00000000000..06dab290172--- /dev/null+++ b/web/features/deployments/create-guide/state/index.ts@@ -0,0 +1,920 @@+'use client'++import type {+ DeployRequest,+ EnvVarInput,+} from '@dify/contracts/enterprise/types.gen'+import type { Getter } from 'jotai/vanilla'+import type { EnvVarBindingSlot, EnvVarValues, EnvVarValueSelection } from '@/features/deployments/components/env-var-bindings'+import type { RuntimeCredentialBindingSelections } from '@/features/deployments/components/runtime-credential-bindings-utils'+import type { UnsupportedDslNode } from '@/features/deployments/shared/domain/error'+import type { App } from '@/types/app'+import { EnvVarValueSource as ApiEnvVarValueSource } from '@dify/contracts/enterprise/types.gen'+import { keepPreviousData } from '@tanstack/react-query'+import { atom } from 'jotai'+import { atomWithInfiniteQuery, atomWithMutation, atomWithQuery } from 'jotai-tanstack-query'+import { envVarBindingSlotFromContract, envVarBindingValueType } from '@/features/deployments/components/env-var-bindings-utils'+import {+ hasMissingRequiredRuntimeCredentialBinding,+ runtimeCredentialSlotKey,+ selectedDeploymentRuntimeCredentials,+ selectedRuntimeCredentialSelections,+} from '@/features/deployments/components/runtime-credential-bindings-utils'+import {+ dslAppName,+ dslEnvVarSlots,+ encodeDslContent,+ isWorkflowDsl,+} from '@/features/deployments/shared/domain/dsl'+import { unsupportedDslNodeError } from '@/features/deployments/shared/domain/error'+import { createDeploymentIdempotencyKey } from '@/features/deployments/shared/domain/idempotency'+import {+ DEPLOYMENT_PAGE_SIZE,+ getNextPageParamFromPagination,+ SOURCE_APPS_PAGE_SIZE,+} from '@/features/deployments/shared/domain/pagination'+import { consoleQuery } from '@/service/client'+import { AppModeEnum } from '@/types/app'+import { environmentMatchesIdentifier } from './environment'++export type GuideMethod = 'bindApp' | 'importDsl'+export type GuideStep = 'source' | 'release' | 'target'+export type WorkflowSourceApp = App & { mode: Extract<AppModeEnum, 'workflow'> }++const RANDOM_SUFFIX_ALPHABET = 'abcdefghijklmnopqrstuvwxyz'+const RANDOM_SUFFIX_LENGTH = 4+const RANDOM_SUFFIX_FALLBACK_LENGTH = 6+const RANDOM_SUFFIX_MAX_ATTEMPTS = 16++function randomLetterCombination(length: number) {+ const randomValues = new Uint8Array(length)++ if (globalThis.crypto) {+ globalThis.crypto.getRandomValues(randomValues)+ }+ else {+ randomValues.forEach((_, index) => {+ randomValues[index] = Math.floor(Math.random() * 256)+ })+ }++ return Array.from(randomValues, value => RANDOM_SUFFIX_ALPHABET[value % RANDOM_SUFFIX_ALPHABET.length]).join('')+}++function availableInstanceName(sourceName: string, existingNameSet: Set<string>) {+ if (!existingNameSet.has(sourceName))+ return sourceName++ for (let attempt = 0; attempt < RANDOM_SUFFIX_MAX_ATTEMPTS; attempt++) {+ const candidate = `${sourceName}-${randomLetterCombination(RANDOM_SUFFIX_LENGTH)}`+ if (!existingNameSet.has(candidate))+ return candidate+ }++ return `${sourceName}-${randomLetterCombination(RANDOM_SUFFIX_FALLBACK_LENGTH)}`+}++function envVarValueSource(slot: EnvVarBindingSlot, selection: EnvVarValueSelection | undefined) {+ return selection?.valueSource+ ?? (slot.hasDefaultValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT+ : slot.hasLastValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT+ : ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL)+}++function envVarSelectionReady(slot: EnvVarBindingSlot, selection: EnvVarValueSelection | undefined) {+ const valueSource = envVarValueSource(slot, selection)++ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT)+ return Boolean(slot.hasLastValue)+ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT)+ return Boolean(slot.hasDefaultValue)+ if (!selection?.value)+ return false++ return slot.valueType !== 'number' || !Number.isNaN(Number(selection.value))+}++function envVarInput(slot: EnvVarBindingSlot, selection: EnvVarValueSelection | undefined): EnvVarInput[] {+ const valueSource = envVarValueSource(slot, selection)++ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT) {+ return slot.hasLastValue+ ? [{ key: slot.key, valueSource }]+ : []+ }++ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT) {+ return slot.hasDefaultValue+ ? [{ key: slot.key, valueSource }]+ : []+ }++ if (!selection?.value || (slot.valueType === 'number' && Number.isNaN(Number(selection.value))))+ return []++ return [{+ key: slot.key,+ value: selection.value,+ valueSource,+ }]+}++// Workflow primitives+export const stepAtom = atom<GuideStep>('source')+export const methodAtom = atom<GuideMethod>('bindApp')++// Source primitives+export const sourceSearchTextAtom = atom('')+export const selectedAppAtom = atom<WorkflowSourceApp | undefined>(undefined)++// DSL primitives and derived state+export const dslFileAtom = atom<File | undefined>(undefined)+const dslContentAtom = atom('')+export const isReadingDslAtom = atom(false)+export const dslReadErrorAtom = atom(false)+const dslReadTokenAtom = atom(0)++export const dslDefaultAppNameAtom = atom((get) => {+ const dslContent = get(dslContentAtom)++ return dslContent ? dslAppName(dslContent) : ''+})++export const dslUnsupportedModeAtom = atom((get) => {+ const dslContent = get(dslContentAtom)++ return get(methodAtom) === 'importDsl'+ && Boolean(dslContent.trim())+ && !get(isReadingDslAtom)+ && !get(dslReadErrorAtom)+ && !isWorkflowDsl(dslContent)+})++const importDslReadyAtom = atom((get) => {+ return Boolean(get(dslContentAtom).trim())+ && !get(isReadingDslAtom)+ && !get(dslReadErrorAtom)+ && !get(dslUnsupportedModeAtom)+})++// Release primitives+export const instanceNameAtom = atom('')+export const instanceDescriptionAtom = atom('')+export const releaseNameAtom = atom('')+export const releaseDescriptionAtom = atom('')+const autoFilledInstanceNameAtom = atom('')+const autoFilledReleaseNameAtom = atom('')++// Target primitives+export const selectedEnvironmentIdAtom = atom('')+const manualBindingSelectionsAtom = atom<RuntimeCredentialBindingSelections>({})+export const envVarValuesAtom = atom<EnvVarValues>({})++// Submission primitives+const submissionUnsupportedDslNodesAtom = atom<UnsupportedDslNode[]>([])+const isCreatingDeploymentAtom = atom(false)+export const isCreatingReleaseOnlyAtom = atom(false)++export const isSubmittingDeploymentGuideAtom = atom(get => (+ get(isCreatingDeploymentAtom) || get(isCreatingReleaseOnlyAtom)+))++// Query and remote data+export const sourceAppsQueryAtom = atomWithInfiniteQuery((get) => {+ const sourceSearchText = get(sourceSearchTextAtom)++ return {+ ...consoleQuery.apps.list.infiniteOptions({+ input: pageParam => ({+ query: {+ page: Number(pageParam),+ limit: SOURCE_APPS_PAGE_SIZE,+ name: sourceSearchText,+ mode: AppModeEnum.WORKFLOW,+ },+ }),+ getNextPageParam: lastPage => lastPage.has_more ? lastPage.page + 1 : undefined,+ initialPageParam: 1,+ placeholderData: keepPreviousData,+ }),+ enabled: get(methodAtom) === 'bindApp',+ }+})++export const effectiveSelectedAppAtom = atom((get) => {+ const selectedApp = get(selectedAppAtom)+ if (selectedApp)+ return selectedApp++ const sourceAppsQuery = get(sourceAppsQueryAtom)+ if (sourceAppsQuery.isPlaceholderData)+ return undefined++ const sourceApps = (sourceAppsQuery.data?.pages.flatMap(page => page.data) ?? []) as WorkflowSourceApp[]++ return sourceApps[0]+})++function sourceReady(get: Getter) {+ const method = get(methodAtom)++ return method === 'importDsl'+ ? get(importDslReadyAtom)+ : Boolean(get(effectiveSelectedAppAtom)?.id)+}++const existingInstanceNamesQueryAtom = atomWithInfiniteQuery(() => ({+ ...consoleQuery.enterprise.appInstanceService.listAppInstances.infiniteOptions({+ input: pageParam => ({+ query: {+ pageNumber: Number(pageParam),+ resultsPerPage: DEPLOYMENT_PAGE_SIZE,+ },+ }),+ getNextPageParam: lastPage => getNextPageParamFromPagination(lastPage.pagination),+ initialPageParam: 1,+ }),+ placeholderData: keepPreviousData,+}))++const instanceNameConflictQueryAtom = atomWithQuery((get) => {+ const submittedInstanceName = get(instanceNameAtom).trim()++ return consoleQuery.enterprise.appInstanceService.listAppInstances.queryOptions({+ input: {+ query: {+ pageNumber: 1,+ resultsPerPage: 1,+ displayName: submittedInstanceName,+ },+ },+ enabled: Boolean(submittedInstanceName),+ })+})++export const deployableEnvironmentsQueryAtom = atomWithQuery((get) => {+ return consoleQuery.enterprise.environmentService.listEnvironments.queryOptions({+ input: {+ query: {+ // The guide offers every deployable environment at once; environment+ // count is capped well below the 100-per-page maximum.+ pageNumber: 1,+ resultsPerPage: 100,+ },+ },+ enabled: sourceReady(get),+ })+})++const precheckReleaseQueryAtom = atomWithQuery((get) => {+ const method = get(methodAtom)+ const effectiveSelectedApp = get(effectiveSelectedAppAtom)+ const dslContent = get(dslContentAtom)+ const enabled = sourceReady(get)++ // PrecheckRelease takes exactly one source arm (dsl | sourceAppId).+ const precheckReleaseQueryOptions = method === 'importDsl'+ ? consoleQuery.enterprise.releaseService.precheckRelease.queryOptions({+ input: {+ body: {+ dsl: dslContent.trim() ? encodeDslContent(dslContent) : '',+ },+ },+ enabled,+ })+ : consoleQuery.enterprise.releaseService.precheckRelease.queryOptions({+ input: {+ body: {+ sourceAppId: effectiveSelectedApp?.id ?? '',+ },+ },+ enabled: enabled && Boolean(effectiveSelectedApp?.id),+ })++ return {+ ...precheckReleaseQueryOptions,+ retry: false,+ }+})++function precheckReleaseReady(get: Getter) {+ const precheckReleaseQuery = get(precheckReleaseQueryAtom)++ return sourceReady(get)+ && precheckReleaseQuery.isSuccess+ && Boolean(precheckReleaseQuery.data?.canCreate)+ && (precheckReleaseQuery.data?.unsupportedNodes.length ?? 0) === 0+ && get(submissionUnsupportedDslNodesAtom).length === 0+}++export const deploymentOptionsQueryAtom = atomWithQuery((get) => {+ const method = get(methodAtom)+ const effectiveSelectedApp = get(effectiveSelectedAppAtom)+ const dslContent = get(dslContentAtom)+ const enabled = precheckReleaseReady(get)++ // ComputeDeploymentOptions takes exactly one source arm (dsl | sourceAppId | releaseId).+ const deploymentOptionsQueryOptions = method === 'importDsl'+ ? consoleQuery.enterprise.releaseService.computeDeploymentOptions.queryOptions({+ input: {+ body: {+ dsl: dslContent.trim() ? encodeDslContent(dslContent) : '',+ },+ },+ enabled,+ })+ : consoleQuery.enterprise.releaseService.computeDeploymentOptions.queryOptions({+ input: {+ body: {+ sourceAppId: effectiveSelectedApp?.id ?? '',+ },+ },+ enabled: enabled && Boolean(effectiveSelectedApp?.id),+ })++ // oRPC encodes input before TanStack can skip work, so keep a valid input shape and gate requests with enabled.+ return {+ ...deploymentOptionsQueryOptions,+ retry: false,+ }+})++// Unsupported DSL state+export const unsupportedDslNodesAtom = atom((get): UnsupportedDslNode[] => {+ const submissionUnsupportedDslNodes = get(submissionUnsupportedDslNodesAtom)+ if (submissionUnsupportedDslNodes.length > 0)+ return submissionUnsupportedDslNodes++ if (!sourceReady(get))+ return []++ return get(precheckReleaseQueryAtom).data?.unsupportedNodes ?? []+})++const precheckReleaseReadyAtom = atom((get) => {+ return precheckReleaseReady(get)+})++const deploymentOptionsReadyAtom = atom((get) => {+ const deploymentOptionsQuery = get(deploymentOptionsQueryAtom)++ return sourceReady(get)+ && get(precheckReleaseReadyAtom)+ && deploymentOptionsQuery.isSuccess+})++const deploymentOptionsContentCheckedAtom = atom((get) => {+ const deploymentOptionsQuery = get(deploymentOptionsQueryAtom)+ const precheckReleaseQuery = get(precheckReleaseQueryAtom)+ const isLoadingOptions = deploymentOptionsQuery.isLoading || (deploymentOptionsQuery.isFetching && !deploymentOptionsQuery.data)+ const isCheckingReleaseContent = precheckReleaseQuery.isLoading || (precheckReleaseQuery.isFetching && !precheckReleaseQuery.data)++ if (!sourceReady(get) || isCheckingReleaseContent || isLoadingOptions)+ return false++ return get(precheckReleaseReadyAtom) && deploymentOptionsQuery.isSuccess+})++export const sourceCanGoNextAtom = atom((get) => {+ const method = get(methodAtom)+ const effectiveSelectedApp = get(effectiveSelectedAppAtom)+ const importDslReady = method === 'importDsl' && get(importDslReadyAtom)+ const bindAppReady = method === 'bindApp' && Boolean(effectiveSelectedApp?.id)++ return (importDslReady || bindAppReady) && get(deploymentOptionsContentCheckedAtom)+})++export const setSourceSearchTextAtom = atom(null, (get, set, value: string) => {+ if (get(sourceSearchTextAtom) === value)+ return++ set(sourceSearchTextAtom, value)+ set(selectedAppAtom, undefined)+ set(selectedEnvironmentIdAtom, '')+ set(manualBindingSelectionsAtom, {})+ set(envVarValuesAtom, {})+ set(submissionUnsupportedDslNodesAtom, [])+})++export const selectSourceAppAtom = atom(null, (_get, set, app: WorkflowSourceApp) => {+ set(selectedAppAtom, app)+ set(selectedEnvironmentIdAtom, '')+ set(manualBindingSelectionsAtom, {})+ set(envVarValuesAtom, {})+ set(submissionUnsupportedDslNodesAtom, [])+})++export const continueFromSourceAtom = atom(null, (get, set, {+ defaultDslAppName,+ defaultReleaseName,+}: {+ defaultDslAppName: string+ defaultReleaseName: string+}) => {+ if (!get(sourceCanGoNextAtom))+ return++ const method = get(methodAtom)+ const effectiveSelectedApp = get(effectiveSelectedAppAtom)+ if (method === 'bindApp' && effectiveSelectedApp)+ set(selectSourceAppAtom, effectiveSelectedApp)++ const sourceName = method === 'importDsl'+ ? get(dslDefaultAppNameAtom) || defaultDslAppName+ : effectiveSelectedApp?.name+ const nextInstanceName = sourceName?.trim()++ if (nextInstanceName) {+ const currentInstanceName = get(instanceNameAtom).trim()+ const autoFilledInstanceName = get(autoFilledInstanceNameAtom)+ const existingInstanceNamesQuery = get(existingInstanceNamesQueryAtom)+ const existingNameSet = new Set(+ existingInstanceNamesQuery.data?.pages.flatMap(page =>+ page.appInstances.flatMap((appInstance) => {+ const name = appInstance.displayName.trim()++ return name ? [name] : []+ }),+ ) ?? [],+ )++ if (!currentInstanceName || currentInstanceName === autoFilledInstanceName) {+ const nextAvailableInstanceName = availableInstanceName(nextInstanceName, existingNameSet)+ set(instanceNameAtom, nextAvailableInstanceName)+ set(autoFilledInstanceNameAtom, nextAvailableInstanceName)+ }+ }++ const currentReleaseName = get(releaseNameAtom).trim()+ const autoFilledReleaseName = get(autoFilledReleaseNameAtom)+ if (!currentReleaseName || currentReleaseName === autoFilledReleaseName) {+ set(releaseNameAtom, defaultReleaseName)+ set(autoFilledReleaseNameAtom, defaultReleaseName)+ }+ set(stepAtom, 'release')+})++// DSL actions+export const selectDslFileAtom = atom(null, async (get, set, dslFile?: File) => {+ set(selectedEnvironmentIdAtom, '')+ set(manualBindingSelectionsAtom, {})+ set(envVarValuesAtom, {})+ set(submissionUnsupportedDslNodesAtom, [])++ // Token guard prevents a slow read from an older file from overwriting the newest selection.+ const dslReadToken = get(dslReadTokenAtom) + 1+ set(dslReadTokenAtom, dslReadToken)+ set(dslFileAtom, dslFile)+ set(dslContentAtom, '')+ set(isReadingDslAtom, Boolean(dslFile))+ set(dslReadErrorAtom, false)++ if (!dslFile)+ return++ try {+ const content = await dslFile.text()+ if (get(dslReadTokenAtom) !== dslReadToken)+ return++ set(dslContentAtom, content)+ set(dslReadErrorAtom, false)+ }+ catch {+ if (get(dslReadTokenAtom) !== dslReadToken)+ return++ set(dslContentAtom, '')+ set(dslReadErrorAtom, true)+ }+ finally {+ if (get(dslReadTokenAtom) === dslReadToken)+ set(isReadingDslAtom, false)+ }+})++// Release derived state and actions+export const hasInstanceNameConflictAtom = atom((get) => {+ const submittedInstanceName = get(instanceNameAtom).trim()+ const instanceNameConflictQuery = get(instanceNameConflictQueryAtom)+ const existingInstanceNamesQuery = get(existingInstanceNamesQueryAtom)+ const existingInstanceNames = existingInstanceNamesQuery.data?.pages.flatMap(page =>+ page.appInstances.flatMap((appInstance) => {+ const name = appInstance.displayName.trim()++ return name ? [name] : []+ }),+ ) ?? []++ return Boolean(+ submittedInstanceName+ && (+ existingInstanceNames.includes(submittedInstanceName)+ || (instanceNameConflictQuery.data?.appInstances.some(appInstance => appInstance.displayName.trim() === submittedInstanceName) ?? false)+ ),+ )+})++const submittedReleaseReadyAtom = atom((get) => {+ return Boolean(sourceReady(get) && get(instanceNameAtom).trim() && get(releaseNameAtom).trim())+})++export const releaseCanGoNextAtom = atom((get) => {+ const submittedInstanceName = get(instanceNameAtom).trim()+ const instanceNameConflictQuery = get(instanceNameConflictQueryAtom)++ return Boolean(get(submittedReleaseReadyAtom))+ && !get(hasInstanceNameConflictAtom)+ && !(Boolean(submittedInstanceName) && instanceNameConflictQuery.isLoading)+ && get(deploymentOptionsContentCheckedAtom)+})++export const setInstanceNameAtom = atom(null, (_get, set, value: string) => {+ set(instanceNameAtom, value)+ set(autoFilledInstanceNameAtom, '')+ set(stepAtom, 'release')+})++export const setInstanceDescriptionAtom = atom(null, (_get, set, value: string) => {+ set(instanceDescriptionAtom, value)+ set(stepAtom, 'release')+})++export const setReleaseNameAtom = atom(null, (_get, set, value: string) => {+ set(releaseNameAtom, value)+ set(autoFilledReleaseNameAtom, '')+ set(stepAtom, 'release')+})++export const setReleaseDescriptionAtom = atom(null, (_get, set, value: string) => {+ set(releaseDescriptionAtom, value)+ set(stepAtom, 'release')+})++export const continueFromReleaseAtom = atom(null, (get, set) => {+ if (!get(releaseCanGoNextAtom))+ return++ set(selectedEnvironmentIdAtom, '')+ set(manualBindingSelectionsAtom, {})+ set(envVarValuesAtom, {})+ set(stepAtom, 'target')+})++// Target derived state and actions+export const deployableEnvironmentsAtom = atom((get) => {+ const deployableEnvironmentsQuery = get(deployableEnvironmentsQueryAtom)++ return sourceReady(get)+ ? deployableEnvironmentsQuery.data?.environments ?? []+ : []+})++const deployableEnvironmentsReadyAtom = atom((get) => {+ const deployableEnvironmentsQuery = get(deployableEnvironmentsQueryAtom)++ return sourceReady(get) && deployableEnvironmentsQuery.isSuccess+})++export const effectiveSelectedEnvironmentIdAtom = atom((get) => {+ return get(selectedEnvironmentIdAtom) || get(deployableEnvironmentsAtom)[0]?.id+})++export const deploymentTargetBindingSlotsAtom = atom((get) => {+ const deploymentOptionsQuery = get(deploymentOptionsQueryAtom)++ return sourceReady(get)+ ? deploymentOptionsQuery.data?.options?.credentialSlots?.filter(slot => runtimeCredentialSlotKey(slot)) ?? []+ : []+})++export const deploymentTargetBindingSelectionsAtom = atom((get) => {+ return selectedRuntimeCredentialSelections(+ get(deploymentTargetBindingSlotsAtom),+ get(manualBindingSelectionsAtom),+ )+})++const requiredBindingsReadyAtom = atom((get) => {+ const bindingSelections = get(deploymentTargetBindingSelectionsAtom)++ return get(deploymentTargetBindingSlotsAtom).every(slot =>+ !hasMissingRequiredRuntimeCredentialBinding(slot, bindingSelections[runtimeCredentialSlotKey(slot)]),+ )+})++export const deploymentTargetEnvVarSlotsAtom = atom((get) => {+ const method = get(methodAtom)+ const deploymentOptionsQuery = get(deploymentOptionsQueryAtom)+ const slots = sourceReady(get) ? deploymentOptionsQuery.data?.options?.envVarSlots : undefined+ const dslContent = get(dslContentAtom)++ // Deployment options own the canonical slot list; DSL metadata only enriches import-DSL defaults.+ const deploymentOptionEnvVarSlots = slots?.flatMap((slot): EnvVarBindingSlot[] => {+ const bindingSlot = envVarBindingSlotFromContract(slot)+ return bindingSlot ? [bindingSlot] : []+ }) ?? []+ const dslEnvVarMetadataSlots = method === 'importDsl' && dslContent+ ? dslEnvVarSlots(dslContent).flatMap((slot) => {+ const key = slot.key.trim()+ if (!key)+ return []++ return [{+ key,+ ...(slot.description ? { description: slot.description } : {}),+ ...(slot.defaultValue !== undefined ? { defaultValue: slot.defaultValue, hasDefaultValue: true } : {}),+ ...(slot.valueType ? { valueType: envVarBindingValueType(slot.valueType) } : {}),+ }]+ })+ : []++ if (dslEnvVarMetadataSlots.length === 0)+ return deploymentOptionEnvVarSlots++ const metadataByKey = new Map(+ dslEnvVarMetadataSlots.map(slot => [slot.key, slot] as const),+ )++ return deploymentOptionEnvVarSlots.map((slot) => {+ const metadata = metadataByKey.get(slot.key)+ if (!metadata)+ return slot++ const nextSlot = { ...slot }++ if (!nextSlot.description && metadata.description)+ nextSlot.description = metadata.description+ if (!nextSlot.hasDefaultValue && metadata.defaultValue !== undefined) {+ nextSlot.defaultValue = metadata.defaultValue+ nextSlot.hasDefaultValue = true+ }+ if (nextSlot.valueType === 'string' && metadata.valueType)+ nextSlot.valueType = metadata.valueType++ return nextSlot+ })+})++const requiredEnvVarsReadyAtom = atom((get) => {+ const envVarValues = get(envVarValuesAtom)++ return get(deploymentTargetEnvVarSlotsAtom).every(slot =>+ envVarSelectionReady(slot, envVarValues[slot.key]),+ )+})++export const canDeployAtom = atom((get) => {+ const effectiveSelectedEnvironmentId = get(effectiveSelectedEnvironmentIdAtom)+ const selectedEnvironment = effectiveSelectedEnvironmentId+ ? get(deployableEnvironmentsAtom).find(env => environmentMatchesIdentifier(env, effectiveSelectedEnvironmentId))+ : undefined++ return Boolean(+ selectedEnvironment?.id+ && get(deployableEnvironmentsReadyAtom)+ && get(deploymentOptionsReadyAtom)+ && get(requiredBindingsReadyAtom)+ && get(requiredEnvVarsReadyAtom)+ && get(submittedReleaseReadyAtom),+ )+})++export const canSkipDeploymentAtom = atom((get) => {+ return get(submittedReleaseReadyAtom) && get(deploymentOptionsReadyAtom)+})++export const selectBindingAtom = atom(null, (get, set, slot: string, value: string) => {+ set(manualBindingSelectionsAtom, {+ ...get(manualBindingSelectionsAtom),+ [slot]: value,+ })+})++export const setEnvVarAtom = atom(null, (get, set, key: string, value: EnvVarValueSelection) => {+ set(envVarValuesAtom, {+ ...get(envVarValuesAtom),+ [key]: value,+ })+})++// Workflow actions+export const selectMethodAtom = atom(null, (_get, set, method: GuideMethod) => {+ set(methodAtom, method)+ set(selectedEnvironmentIdAtom, '')+ set(manualBindingSelectionsAtom, {})+ set(envVarValuesAtom, {})+ set(submissionUnsupportedDslNodesAtom, [])+ set(stepAtom, 'source')+})++// Submission+const createAppInstanceMutationAtom = atomWithMutation(() =>+ consoleQuery.enterprise.appInstanceService.createAppInstance.mutationOptions(),+)++const createReleaseMutationAtom = atomWithMutation(() =>+ consoleQuery.enterprise.releaseService.createRelease.mutationOptions(),+)++const createInitialDeploymentMutationAtom = atomWithMutation(() =>+ consoleQuery.enterprise.deploymentService.deploy.mutationOptions(),+)++export class CreateDeploymentGuideSubmissionBlockedError extends Error {+ reason: 'unsupportedDslMode' | 'deployFailed'++ constructor(reason: 'unsupportedDslMode' | 'deployFailed') {+ super(reason)+ this.reason = reason+ this.name = 'CreateDeploymentGuideSubmissionBlockedError'+ }+}++export const createDeploymentGuideSubmissionAtom = atom(null, async (get, set, {+ deployToEnvironment,+}: {+ deployToEnvironment: boolean+}) => {+ const method = get(methodAtom)+ const dslContent = get(dslContentAtom)+ const submittedInstanceName = get(instanceNameAtom).trim()+ const submittedReleaseName = get(releaseNameAtom).trim()+ const submittedReleaseDescription = get(releaseDescriptionAtom).trim()++ if (get(isSubmittingDeploymentGuideAtom) || !get(submittedReleaseReadyAtom))+ return undefined++ const effectiveSelectedApp = get(effectiveSelectedAppAtom)+ const deployableEnvironmentsQuery = get(deployableEnvironmentsQueryAtom)+ const deploymentOptions = get(deploymentOptionsQueryAtom).data?.options+ const envVarSlots = get(deploymentTargetEnvVarSlotsAtom)+ const envVarValues = get(envVarValuesAtom)+ const bindingSlots = get(deploymentTargetBindingSlotsAtom)+ const bindingSelections = get(deploymentTargetBindingSelectionsAtom)+ const selectedEnvironmentId = get(selectedEnvironmentIdAtom)+ const effectiveSelectedEnvironmentId = selectedEnvironmentId || get(deployableEnvironmentsAtom)[0]?.id+ const selectedEnvironment = effectiveSelectedEnvironmentId+ ? get(deployableEnvironmentsAtom).find(env => environmentMatchesIdentifier(env, effectiveSelectedEnvironmentId))+ : undefined++ if (deployToEnvironment && !selectedEnvironment && !selectedEnvironmentId.trim())+ return undefined+ if (method === 'bindApp' && !effectiveSelectedApp?.id)+ return undefined+ if (method === 'importDsl' && !dslContent.trim())+ return undefined+ if (method === 'importDsl' && !isWorkflowDsl(dslContent))+ throw new CreateDeploymentGuideSubmissionBlockedError('unsupportedDslMode')++ set(submissionUnsupportedDslNodesAtom, [])++ try {+ if (!deployToEnvironment) {+ if (!get(canSkipDeploymentAtom))+ return undefined++ set(isCreatingReleaseOnlyAtom, true)++ try {+ const createdAppInstance = await get(createAppInstanceMutationAtom).mutateAsync({+ body: {+ displayName: submittedInstanceName,+ description: get(instanceDescriptionAtom).trim() || undefined,+ },+ })+ const appInstanceId = createdAppInstance.appInstance.id++ if (method === 'importDsl') {+ await get(createReleaseMutationAtom).mutateAsync({+ body: {+ appInstanceId,+ dsl: encodeDslContent(dslContent),+ displayName: submittedReleaseName,+ description: submittedReleaseDescription || undefined,+ createAppInstance: false,+ },+ })++ return appInstanceId+ }++ if (!effectiveSelectedApp?.id)+ return undefined++ await get(createReleaseMutationAtom).mutateAsync({+ body: {+ appInstanceId,+ sourceAppId: effectiveSelectedApp.id,+ displayName: submittedReleaseName,+ description: submittedReleaseDescription || undefined,+ createAppInstance: false,+ },+ })++ return appInstanceId+ }+ finally {+ set(isCreatingReleaseOnlyAtom, false)+ }+ }++ if (!get(canDeployAtom))+ return undefined++ set(isCreatingDeploymentAtom, true)++ try {+ const selectedEnvironmentIdentifier = selectedEnvironmentId.trim()+ const freshSelectedEnvironment = selectedEnvironment || (+ selectedEnvironmentIdentifier+ ? (await deployableEnvironmentsQuery.refetch()).data?.environments.find(environment =>+ environmentMatchesIdentifier(environment, selectedEnvironmentIdentifier),+ )+ : undefined+ )+ const targetEnvironmentId = freshSelectedEnvironment?.id+ if (!targetEnvironmentId)+ throw new CreateDeploymentGuideSubmissionBlockedError('deployFailed')++ if (!get(requiredBindingsReadyAtom))+ throw new Error('Missing required deployment binding.')+ if (!get(requiredEnvVarsReadyAtom))+ throw new Error('Missing required deployment environment variable.')++ const envVars = envVarSlots.flatMap(slot => envVarInput(slot, envVarValues[slot.key]))+ const commonDeploymentRequest = {+ newAppInstance: {+ displayName: submittedInstanceName,+ description: get(instanceDescriptionAtom).trim() || undefined,+ },+ environmentId: targetEnvironmentId,+ releaseName: submittedReleaseName,+ releaseDescription: submittedReleaseDescription || undefined,+ credentials: selectedDeploymentRuntimeCredentials(bindingSlots, bindingSelections),+ envVars,+ idempotencyKey: createDeploymentIdempotencyKey(),+ expectedDslDigest: deploymentOptions?.dslDigest,+ } satisfies Omit<DeployRequest, 'dsl' | 'sourceAppId'>+ const deploymentRequest = method === 'importDsl'+ ? {+ ...commonDeploymentRequest,+ dsl: encodeDslContent(dslContent),+ }+ : effectiveSelectedApp?.id+ ? {+ ...commonDeploymentRequest,+ sourceAppId: effectiveSelectedApp.id,+ }+ : undefined+ if (!deploymentRequest)+ return undefined++ const response = await get(createInitialDeploymentMutationAtom).mutateAsync({+ body: deploymentRequest,+ })++ return response.appInstance.id+ }+ finally {+ set(isCreatingDeploymentAtom, false)+ }+ }+ catch (error) {+ const unsupportedError = await unsupportedDslNodeError(error)+ if (unsupportedError?.nodes.length) {+ set(submissionUnsupportedDslNodesAtom, unsupportedError.nodes)++ return undefined+ }++ throw error+ }+})++// Scoped local state+export const createDeploymentGuideScopedAtoms = [+ stepAtom,+ methodAtom,+ sourceSearchTextAtom,+ selectedAppAtom,+ dslFileAtom,+ dslContentAtom,+ isReadingDslAtom,+ dslReadErrorAtom,+ dslReadTokenAtom,+ instanceNameAtom,+ instanceDescriptionAtom,+ releaseNameAtom,+ releaseDescriptionAtom,+ autoFilledInstanceNameAtom,+ autoFilledReleaseNameAtom,+ selectedEnvironmentIdAtom,+ manualBindingSelectionsAtom,+ envVarValuesAtom,+ submissionUnsupportedDslNodesAtom,+ isCreatingDeploymentAtom,+ isCreatingReleaseOnlyAtom,+]diff --git a/web/features/deployments/create-guide/state/provider.tsx b/web/features/deployments/create-guide/state/provider.tsxnew file mode 100644index 00000000000..5ebf3d8bd3a--- /dev/null+++ b/web/features/deployments/create-guide/state/provider.tsx@@ -0,0 +1,15 @@+'use client'++import type { ReactNode } from 'react'+import { ScopeProvider } from 'jotai-scope'+import { createDeploymentGuideScopedAtoms } from './index'++export function CreateDeploymentGuideProvider({ children }: {+ children: ReactNode+}) {+ return (+ <ScopeProvider atoms={createDeploymentGuideScopedAtoms}>+ {children}+ </ScopeProvider>+ )+}diff --git a/web/features/deployments/create-guide/ui/layout.tsx b/web/features/deployments/create-guide/ui/layout.tsxnew file mode 100644index 00000000000..e49e7654926--- /dev/null+++ b/web/features/deployments/create-guide/ui/layout.tsx@@ -0,0 +1,215 @@+'use client'++import type { ReactNode } from 'react'+import type { GuideStep } from '@/features/deployments/create-guide/state'+import { cn } from '@langgenius/dify-ui/cn'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useTranslation } from 'react-i18next'+import { TitleTooltip } from '@/features/deployments/components/title-tooltip'++const GUIDE_PROGRESS_STEPS: GuideStep[] = ['source', 'release', 'target']++function GuideStepIntro({ activeStep }: {+ activeStep: GuideStep+}) {+ const { t } = useTranslation('deployments')++ let title: string+ let description: string++ if (activeStep === 'source') {+ title = t('createGuide.source.title')+ description = t('createGuide.method.description')+ }+ else if (activeStep === 'release') {+ title = t('createGuide.release.title')+ description = t('createGuide.release.description')+ }+ else if (activeStep === 'target') {+ title = t('createGuide.target.title')+ description = t('createGuide.target.description')+ }+ else {+ return null+ }++ return (+ <div className="pb-4">+ <h2 className="system-md-semibold text-text-primary">{title}</h2>+ <p className="mt-1 max-w-150 system-sm-regular text-text-tertiary">{description}</p>+ </div>+ )+}++function GuideProgress({ activeStep }: {+ activeStep: GuideStep+}) {+ const { t } = useTranslation('deployments')+ const activeIndex = GUIDE_PROGRESS_STEPS.indexOf(activeStep)++ return (+ <ol className="grid grid-cols-3 gap-1.5">+ {GUIDE_PROGRESS_STEPS.map((step, index) => {+ const isActive = step === activeStep+ const isComplete = index < activeIndex+ const label = t(`createGuide.steps.${step}`)++ return (+ <TitleTooltip key={step} content={label}>+ <li+ aria-current={isActive ? 'step' : undefined}+ className={cn(+ 'flex min-w-0 items-start gap-1.5 px-1 py-1.5 system-xs-medium sm:items-center sm:gap-2 sm:px-2',+ isActive+ ? 'text-text-primary'+ : isComplete+ ? 'text-text-secondary'+ : 'text-text-quaternary',+ )}+ >+ <span+ aria-hidden+ className={cn(+ 'mt-1 size-2 shrink-0 rounded-full border-[1.5px] sm:mt-0',+ isActive+ ? 'border-text-primary bg-text-primary'+ : isComplete+ ? 'border-text-secondary bg-text-secondary'+ : 'border-text-quaternary bg-transparent',+ )}+ />+ <span className="line-clamp-2 min-w-0 leading-4">{label}</span>+ </li>+ </TitleTooltip>+ )+ })}+ </ol>+ )+}++function GuideProgressSummary({ activeStep }: {+ activeStep: GuideStep+}) {+ const { t } = useTranslation('deployments')+ const activeIndex = GUIDE_PROGRESS_STEPS.indexOf(activeStep)+ const activeStepNumber = activeIndex + 1++ let activeStepLabel: string+ if (activeStep === 'source')+ activeStepLabel = t('createGuide.steps.source')+ else if (activeStep === 'release')+ activeStepLabel = t('createGuide.steps.release')+ else if (activeStep === 'target')+ activeStepLabel = t('createGuide.steps.target')+ else+ return null++ if (activeIndex < 0)+ return null++ return (+ <div className="flex w-full min-w-0 flex-col gap-2">+ <div className="flex min-w-0 items-baseline justify-between gap-3">+ <span className="truncate system-sm-medium text-text-secondary">{activeStepLabel}</span>+ <span className="shrink-0 system-xs-regular text-text-quaternary">+ {activeStepNumber}+ /+ {GUIDE_PROGRESS_STEPS.length}+ </span>+ </div>+ <div className="grid grid-cols-3 gap-1" aria-hidden="true">+ {GUIDE_PROGRESS_STEPS.map((step, index) => (+ <span+ key={step}+ className={cn(+ 'h-1 rounded-full',+ index <= activeIndex ? 'bg-text-primary' : 'bg-divider-subtle',+ )}+ />+ ))}+ </div>+ </div>+ )+}++export function StepShell({ title, description, descriptionClassName, hideHeader, className, children }: {+ title: string+ description: string+ descriptionClassName?: string+ hideHeader?: boolean+ className?: string+ children: ReactNode+}) {+ return (+ <section aria-label={hideHeader ? title : undefined} className={cn('flex min-w-0 flex-col gap-4', className)}>+ {!hideHeader && (+ <div className="flex min-w-0 flex-col gap-0.5">+ <h2 className="system-md-semibold text-text-primary">{title}</h2>+ <p className={cn('system-sm-regular text-text-tertiary', descriptionClassName)}>{description}</p>+ </div>+ )}+ {children}+ </section>+ )+}++export function GuideCard({ children, actions, contentScrollable = true }: {+ children: ReactNode+ actions: ReactNode+ contentScrollable?: boolean+}) {+ return (+ <div className="flex min-h-0 w-full min-w-0 flex-1 flex-col">+ {contentScrollable+ ? (+ <ScrollArea+ className="min-h-0 flex-1"+ slotClassNames={{+ viewport: 'overscroll-contain',+ content: 'min-h-full pt-0.5 pb-6',+ scrollbar: 'data-[orientation=vertical]:-me-5 data-[orientation=vertical]:my-1',+ }}+ >+ {children}+ </ScrollArea>+ )+ : (+ <div className="min-h-0 flex-1 overflow-hidden pt-0.5 pb-6">+ {children}+ </div>+ )}+ {actions}+ </div>+ )+}++export function GuideFrame({ activeStep, children }: {+ activeStep: GuideStep+ children: ReactNode+}) {+ const { t } = useTranslation('deployments')++ return (+ <div className="relative flex h-full min-h-0 overflow-hidden bg-background-default-subtle">+ <div className="flex min-w-0 flex-1 shrink-0 justify-center overflow-hidden">+ <section+ aria-label={t('createGuide.title')}+ className="flex h-full w-full max-w-[840px] flex-col px-5 sm:px-8 lg:px-10"+ >+ <div className="h-5 sm:h-8 lg:h-12" />+ <div className="flex min-w-0 items-start justify-between gap-6 pt-1 pb-4">+ <h1 className="title-2xl-semi-bold text-text-primary">{t('createGuide.title')}</h1>+ <div className="hidden w-[184px] shrink-0 min-[1120px]:block">+ <GuideProgressSummary activeStep={activeStep} />+ </div>+ </div>+ <GuideStepIntro activeStep={activeStep} />+ <div className="mb-6 min-[1120px]:hidden">+ <GuideProgress activeStep={activeStep} />+ </div>+ {children}+ </section>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/create-guide/ui/release-step.tsx b/web/features/deployments/create-guide/ui/release-step.tsxnew file mode 100644index 00000000000..192351003ab--- /dev/null+++ b/web/features/deployments/create-guide/ui/release-step.tsx@@ -0,0 +1,209 @@+'use client'++import { Button } from '@langgenius/dify-ui/button'+import { Input } from '@langgenius/dify-ui/input'+import { useAtomValue, useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import {+ continueFromReleaseAtom,+ dslDefaultAppNameAtom,+ hasInstanceNameConflictAtom,+ instanceDescriptionAtom,+ instanceNameAtom,+ methodAtom,+ releaseCanGoNextAtom,+ releaseDescriptionAtom,+ releaseNameAtom,+ selectedAppAtom,+ setInstanceDescriptionAtom,+ setInstanceNameAtom,+ setReleaseDescriptionAtom,+ setReleaseNameAtom,+ stepAtom,+} from '@/features/deployments/create-guide/state'+import { StepShell } from './layout'++const releaseTextareaClassName = 'min-h-16 w-full resize-none appearance-none rounded-md border border-transparent bg-components-input-bg-normal p-2 px-3 system-sm-regular text-components-input-text-filled caret-primary-600 outline-hidden placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs'++export function ReleaseStepContent() {+ const { t } = useTranslation('deployments')++ return (+ <StepShell+ title={t('createGuide.release.title')}+ description={t('createGuide.release.description')}+ hideHeader+ >+ <div className="flex flex-col gap-6">+ <DeploymentInfoSection />+ <InitialReleaseSection />+ </div>+ </StepShell>+ )+}++function DeploymentInfoSection() {+ const { t } = useTranslation('deployments')++ return (+ <div className="flex flex-col gap-4">+ <h3 className="system-sm-semibold text-text-primary">+ {t('createGuide.release.deployInfo')}+ </h3>+ <InstanceNameField />+ <InstanceDescriptionField />+ </div>+ )+}++function InitialReleaseSection() {+ const { t } = useTranslation('deployments')++ return (+ <div className="flex flex-col gap-4">+ <h3 className="system-sm-semibold text-text-primary">+ {t('createGuide.release.firstVersion')}+ </h3>+ <ReleaseNameField />+ <ReleaseDescriptionField />+ </div>+ )+}++function InstanceNameField() {+ const { t } = useTranslation('deployments')+ const instanceName = useAtomValue(instanceNameAtom)+ const setInstanceName = useSetAtom(setInstanceNameAtom)+ const method = useAtomValue(methodAtom)+ const selectedApp = useAtomValue(selectedAppAtom)+ const dslDefaultAppName = useAtomValue(dslDefaultAppNameAtom)+ const instanceNamePlaceholder = method === 'importDsl'+ ? dslDefaultAppName || t('createGuide.dsl.defaultAppName')+ : selectedApp?.name+ const hasInstanceNameConflict = useAtomValue(hasInstanceNameConflictAtom)+ const instanceNameError = hasInstanceNameConflict+ ? t('createGuide.release.instanceNameConflict')+ : undefined+ const instanceNameErrorId = 'create-guide-instance-name-error'++ return (+ <div className="flex flex-col gap-2">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="create-guide-instance-name">+ {t('createGuide.release.instanceName')}+ </label>+ <Input+ id="create-guide-instance-name"+ value={instanceName}+ onChange={event => setInstanceName(event.target.value)}+ placeholder={instanceNamePlaceholder}+ required+ aria-invalid={instanceNameError ? true : undefined}+ aria-describedby={instanceNameError ? instanceNameErrorId : undefined}+ className="h-9"+ />+ {instanceNameError && (+ <div id={instanceNameErrorId} role="alert" className="system-xs-regular text-text-destructive">+ {instanceNameError}+ </div>+ )}+ </div>+ )+}++function InstanceDescriptionField() {+ const { t } = useTranslation('deployments')+ const instanceDescription = useAtomValue(instanceDescriptionAtom)+ const setInstanceDescription = useSetAtom(setInstanceDescriptionAtom)++ return (+ <div className="flex flex-col gap-2">+ <OptionalFieldLabel htmlFor="create-guide-instance-description">+ {t('createGuide.release.instanceDescription')}+ </OptionalFieldLabel>+ <textarea+ id="create-guide-instance-description"+ value={instanceDescription}+ onChange={event => setInstanceDescription(event.target.value)}+ placeholder={t('createGuide.release.instanceDescriptionPlaceholder')}+ className={releaseTextareaClassName}+ />+ </div>+ )+}++function ReleaseNameField() {+ const { t } = useTranslation('deployments')+ const releaseName = useAtomValue(releaseNameAtom)+ const setReleaseName = useSetAtom(setReleaseNameAtom)++ return (+ <div className="flex flex-col gap-2">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="create-guide-release-name">+ {t('createGuide.release.releaseName')}+ </label>+ <Input+ id="create-guide-release-name"+ value={releaseName}+ onChange={event => setReleaseName(event.target.value)}+ placeholder={t('createGuide.release.defaultName')}+ required+ className="h-9"+ />+ </div>+ )+}++function ReleaseDescriptionField() {+ const { t } = useTranslation('deployments')+ const releaseDescription = useAtomValue(releaseDescriptionAtom)+ const setReleaseDescription = useSetAtom(setReleaseDescriptionAtom)++ return (+ <div className="flex flex-col gap-2">+ <OptionalFieldLabel htmlFor="create-guide-release-description">+ {t('createGuide.release.releaseDescription')}+ </OptionalFieldLabel>+ <textarea+ id="create-guide-release-description"+ value={releaseDescription}+ onChange={event => setReleaseDescription(event.target.value)}+ placeholder={t('createGuide.release.releaseDescriptionPlaceholder')}+ className={releaseTextareaClassName}+ />+ </div>+ )+}++function OptionalFieldLabel({ children, htmlFor }: {+ children: string+ htmlFor: string+}) {+ const { t } = useTranslation('deployments')++ return (+ <div className="flex items-center gap-1.5">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor={htmlFor}>+ {children}+ </label>+ <span className="system-xs-regular text-text-quaternary">{t('versions.optional')}</span>+ </div>+ )+}++export function ReleaseActionButtons() {+ const { t } = useTranslation('deployments')+ const canGoNext = useAtomValue(releaseCanGoNextAtom)+ const setStep = useSetAtom(stepAtom)+ const continueFromRelease = useSetAtom(continueFromReleaseAtom)++ return (+ <>+ <Button type="button" variant="secondary" onClick={() => setStep('source')}>+ {t('createGuide.actions.back')}+ </Button>+ <Button type="button" variant="primary" disabled={!canGoNext} onClick={continueFromRelease}>+ {t('createGuide.actions.next')}+ </Button>+ </>+ )+}diff --git a/web/features/deployments/create-guide/ui/shell.tsx b/web/features/deployments/create-guide/ui/shell.tsxnew file mode 100644index 00000000000..55496b65127--- /dev/null+++ b/web/features/deployments/create-guide/ui/shell.tsx@@ -0,0 +1,78 @@+'use client'++import { useAtomValue } from 'jotai'+import { stepAtom } from '@/features/deployments/create-guide/state'+import { GuideCard, GuideFrame } from './layout'+import {+ ReleaseActionButtons,+ ReleaseStepContent,+} from './release-step'+import {+ SourceActionButtons,+ SourceStepContent,+} from './source-step'+import {+ TargetBackButton,+ TargetDeployButton,+ TargetSkipDeploymentButton,+ TargetStepContent,+} from './target-step'++export function CreateDeploymentGuideShell() {+ const step = useAtomValue(stepAtom)++ return (+ <GuideFrame activeStep={step}>+ <GuideCard+ contentScrollable={step !== 'source'}+ actions={<CreateDeploymentGuideActionBar />}+ >+ <CreateDeploymentGuideStepContent />+ </GuideCard>+ </GuideFrame>+ )+}++function CreateDeploymentGuideStepContent() {+ const step = useAtomValue(stepAtom)++ if (step === 'source') {+ return (+ <div className="flex h-full min-h-0 flex-col gap-7 pb-4">+ <SourceStepContent />+ </div>+ )+ }++ if (step === 'release') {+ return (+ <div className="flex h-full min-h-0 flex-col gap-7 pb-4">+ <ReleaseStepContent />+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-7 pb-4">+ <TargetStepContent />+ </div>+ )+}++function CreateDeploymentGuideActionBar() {+ const step = useAtomValue(stepAtom)++ return (+ <div className="sticky bottom-0 z-10 -mx-5 mt-auto flex items-center justify-end gap-2 border-t border-divider-subtle bg-background-default-subtle/95 px-5 py-4 backdrop-blur-sm sm:-mx-8 sm:px-8 lg:-mx-10 lg:px-10">+ {step === 'source' && <SourceActionButtons />}+ {step === 'release' && <ReleaseActionButtons />}+ {step === 'target' && (+ <>+ <TargetBackButton />+ <TargetSkipDeploymentButton />+ <TargetDeployButton />+ </>+ )}+ </div>+ )+}diff --git a/web/features/deployments/create-guide/ui/source-step.tsx b/web/features/deployments/create-guide/ui/source-step.tsxnew file mode 100644index 00000000000..832219f1b18--- /dev/null+++ b/web/features/deployments/create-guide/ui/source-step.tsx@@ -0,0 +1,360 @@+'use client'++import type { GuideMethod, WorkflowSourceApp } from '@/features/deployments/create-guide/state'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import { RadioRoot } from '@langgenius/dify-ui/radio'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'+import { useAtomValue, useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import Uploader from '@/app/components/app/create-from-dsl-modal/uploader'+import AppIcon from '@/app/components/base/app-icon'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import { DeploymentStateMessage } from '@/features/deployments/components/empty-state'+import { TitleTooltip } from '@/features/deployments/components/title-tooltip'+import { UnsupportedDslNodesAlert } from '@/features/deployments/components/unsupported-dsl-nodes-alert'+import {+ continueFromSourceAtom,+ dslFileAtom,+ dslReadErrorAtom,+ dslUnsupportedModeAtom,+ effectiveSelectedAppAtom,+ isReadingDslAtom,+ methodAtom,+ selectDslFileAtom,+ selectMethodAtom,+ selectSourceAppAtom,+ setSourceSearchTextAtom,+ sourceAppsQueryAtom,+ sourceCanGoNextAtom,+ sourceSearchTextAtom,+ unsupportedDslNodesAtom,+} from '@/features/deployments/create-guide/state'+import { StepShell } from './layout'++const sourceAppSkeletonKeys = ['first-source-app', 'second-source-app', 'third-source-app']++export function SourceStepContent() {+ const method = useAtomValue(methodAtom)+ const unsupportedDslNodes = useAtomValue(unsupportedDslNodesAtom)++ return (+ <div className="flex min-h-0 flex-1 flex-col gap-4">+ <SourceMethodSection />+ {method === 'bindApp' && (+ <SourceAppSelectionSection />+ )}+ {method === 'importDsl' && (+ <DslUploadSection />+ )}+ <UnsupportedDslNodesAlert nodes={unsupportedDslNodes} />+ </div>+ )+}++function SourceMethodSection() {+ const { t } = useTranslation('deployments')+ const method = useAtomValue(methodAtom)+ const selectMethod = useSetAtom(selectMethodAtom)++ return (+ <StepShell+ title={t('createGuide.steps.method')}+ description={t('createGuide.method.description')}+ descriptionClassName="lg:hidden"+ hideHeader+ >+ <RadioGroup<GuideMethod>+ value={method}+ onValueChange={selectMethod}+ className="flex flex-col items-stretch gap-2 sm:flex-row"+ >+ <SourceMethodCard+ value="bindApp"+ icon="i-ri-stack-line"+ title={t('createGuide.methods.bindApp.title')}+ description={t('createGuide.methods.bindApp.description')}+ />+ <SourceMethodCard+ value="importDsl"+ icon="i-ri-file-code-line"+ title={t('createGuide.methods.importDsl.title')}+ description={t('createGuide.methods.importDsl.description')}+ />+ </RadioGroup>+ </StepShell>+ )+}++function SourceMethodCard({ value, icon, title, description, badge }: {+ value: GuideMethod+ icon: string+ title: string+ description: string+ badge?: string+}) {+ return (+ <RadioRoot<GuideMethod>+ value={value}+ variant="unstyled"+ className={cn(+ `relative box-content h-[84px] w-full cursor-pointer rounded-xl border-[0.5px]+ border-components-option-card-option-border bg-components-panel-on-panel-item-bg p-3+ text-left shadow-xs outline-hidden hover:shadow-md focus-visible:ring-2+ focus-visible:ring-state-accent-solid sm:w-[240px]`,+ 'data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:shadow-md data-checked:ring-[0.5px] data-checked:ring-components-option-card-option-selected-border data-checked:ring-inset',+ )}+ >+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md border border-divider-subtle bg-background-default-subtle">+ <span className={cn('size-4 text-text-tertiary', icon)} aria-hidden="true" />+ </span>+ <span className="mt-2 mb-0.5 flex min-w-0 items-center gap-1">+ <span className="truncate system-sm-semibold text-text-secondary">{title}</span>+ {badge && (+ <span className="shrink-0 rounded-md bg-background-default-subtle px-1.5 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {badge}+ </span>+ )}+ </span>+ <span className="flex min-w-0 items-start gap-1">+ <TitleTooltip content={description}>+ <span className="line-clamp-2 min-w-0 grow system-xs-regular text-text-tertiary">+ {description}+ </span>+ </TitleTooltip>+ </span>+ </RadioRoot>+ )+}++function SourceAppSelectionSection() {+ const { t } = useTranslation('deployments')++ return (+ <StepShell+ title={t('createGuide.source.title')}+ description={t('createGuide.source.description')}+ descriptionClassName="lg:hidden"+ hideHeader+ className="min-h-0 flex-1"+ >+ <div className="flex min-h-0 flex-1 flex-col gap-3">+ <SourceSearchInput />+ <SourceAppList />+ </div>+ </StepShell>+ )+}++function SourceSearchInput() {+ const { t } = useTranslation('deployments')+ const sourceSearchText = useAtomValue(sourceSearchTextAtom)+ const setSourceSearchText = useSetAtom(setSourceSearchTextAtom)++ return (+ <div className="relative">+ <span className="pointer-events-none absolute top-1/2 left-2.5 i-ri-search-line size-4 -translate-y-1/2 text-text-tertiary" aria-hidden="true" />+ <Input+ id="create-guide-source-search"+ aria-label={t('createGuide.source.sourceApp')}+ value={sourceSearchText}+ onChange={event => setSourceSearchText(event.target.value)}+ placeholder={t('createGuide.source.searchPlaceholder')}+ className="h-9 pr-8 pl-8"+ />+ {sourceSearchText && (+ <button+ type="button"+ aria-label={t('createGuide.source.clearSearch')}+ onClick={() => setSourceSearchText('')}+ className="absolute top-1/2 right-2.5 flex size-4 -translate-y-1/2 items-center justify-center text-text-quaternary hover:text-text-secondary"+ >+ <span className="i-ri-close-circle-fill size-4" aria-hidden="true" />+ </button>+ )}+ </div>+ )+}++function SourceAppList() {+ const { t } = useTranslation('deployments')+ const selectSourceApp = useSetAtom(selectSourceAppAtom)+ const effectiveSelectedApp = useAtomValue(effectiveSelectedAppAtom)+ const sourceAppsQuery = useAtomValue(sourceAppsQueryAtom)+ const sourceApps = (sourceAppsQuery.data?.pages.flatMap(page => page.data) ?? []) as WorkflowSourceApp[]+ const sourceAppsLoading = sourceAppsQuery.isLoading || sourceAppsQuery.isPlaceholderData || (sourceAppsQuery.isFetching && sourceApps.length === 0)++ return (+ <div className="min-h-0 flex-1 overflow-y-auto rounded-lg border border-divider-subtle bg-background-default">+ {sourceAppsLoading+ ? <SourceAppSkeleton />+ : sourceApps.length === 0+ ? (+ <DeploymentStateMessage variant="embedded">+ {t('createGuide.source.empty')}+ </DeploymentStateMessage>+ )+ : (+ <div>+ {sourceApps.map(app => (+ <SourceAppOption+ key={app.id}+ app={app}+ selected={effectiveSelectedApp?.id === app.id}+ onSelect={() => selectSourceApp(app)}+ />+ ))}+ {sourceAppsQuery.hasNextPage && (+ <div className="flex justify-center border-t border-divider-subtle px-3 py-2">+ <Button+ type="button"+ size="small"+ disabled={sourceAppsQuery.isFetchingNextPage}+ onClick={() => {+ void sourceAppsQuery.fetchNextPage()+ }}+ >+ {sourceAppsQuery.isFetchingNextPage ? t('createModal.loadingApps') : t('createModal.loadMoreApps')}+ </Button>+ </div>+ )}+ </div>+ )}+ </div>+ )+}++function SourceAppSkeleton() {+ return (+ <div className="divide-y divide-divider-subtle">+ {sourceAppSkeletonKeys.map(key => (+ <SkeletonRow key={key} className="h-14 px-3 py-2">+ <SkeletonRectangle className="my-0 size-7 animate-pulse rounded-lg" />+ <div className="flex min-w-0 grow flex-col gap-1">+ <SkeletonRectangle className="my-0 h-3.5 w-2/3 animate-pulse" />+ <SkeletonRectangle className="my-0 h-2.5 w-1/3 animate-pulse" />+ </div>+ </SkeletonRow>+ ))}+ </div>+ )+}++function SourceAppOption({ app, onSelect, selected }: {+ app: WorkflowSourceApp+ onSelect: () => void+ selected: boolean+}) {+ return (+ <label+ className={cn(+ 'group flex min-h-14 cursor-pointer items-center gap-3 border-b border-b-divider-subtle px-3 py-2 transition-colors first:rounded-t-lg last:rounded-b-lg last:border-b-0',+ selected+ ? 'bg-state-accent-hover hover:bg-state-accent-hover'+ : 'bg-background-default hover:bg-state-base-hover',+ )}+ >+ <AppIcon+ className="shrink-0"+ size="xs"+ iconType={app.icon_type}+ icon={app.icon}+ background={app.icon_background}+ imageUrl={app.icon_url}+ />+ <span className="flex min-w-0 grow">+ <span className={cn('truncate system-sm-medium', selected ? 'text-text-accent' : 'text-text-primary')}>{app.name}</span>+ </span>+ <input+ type="radio"+ name="source-app"+ checked={selected}+ onChange={onSelect}+ className="sr-only"+ />+ <span+ className={cn(+ 'flex size-5 shrink-0 items-center justify-center rounded-full',+ selected ? 'bg-primary-600 text-text-primary-on-surface' : 'text-transparent',+ )}+ aria-hidden="true"+ >+ <span className="i-ri-check-line size-4" />+ </span>+ </label>+ )+}++function DslUploadSection() {+ const { t } = useTranslation('deployments')+ const dslFile = useAtomValue(dslFileAtom)+ const selectDslFile = useSetAtom(selectDslFileAtom)++ return (+ <StepShell title={t('createGuide.dsl.title')} description={t('createGuide.dsl.description')} hideHeader>+ <div className="flex flex-col gap-4 rounded-xl border border-components-panel-border bg-components-panel-bg-blur p-5">+ <div className="flex items-start gap-3">+ <span className="mt-0.5 i-ri-upload-cloud-2-line size-5 shrink-0 text-text-tertiary" aria-hidden="true" />+ <div className="flex min-w-0 flex-col gap-1">+ <div className="system-sm-semibold text-text-primary">{t('createGuide.dsl.dropTitle')}</div>+ <div className="system-sm-regular text-text-tertiary">{t('createGuide.dsl.dropDescription')}</div>+ </div>+ </div>+ <Uploader+ className="mt-0"+ file={dslFile}+ updateFile={selectDslFile}+ />+ <DslReadStatus />+ </div>+ </StepShell>+ )+}++function DslReadStatus() {+ const { t } = useTranslation('deployments')+ const isReadingDsl = useAtomValue(isReadingDslAtom)+ const dslReadError = useAtomValue(dslReadErrorAtom)+ const dslUnsupportedMode = useAtomValue(dslUnsupportedModeAtom)++ return (+ <>+ {isReadingDsl && (+ <div className="system-xs-regular text-text-tertiary">+ {t('createGuide.dsl.reading')}+ </div>+ )}+ {dslReadError && (+ <div className="system-xs-regular text-text-destructive">+ {t('createGuide.dsl.readFailed')}+ </div>+ )}+ {dslUnsupportedMode && (+ <div role="alert" className="system-xs-regular text-text-destructive">+ {t('createGuide.dsl.unsupportedMode')}+ </div>+ )}+ </>+ )+}++export function SourceActionButtons() {+ const { t } = useTranslation('deployments')+ const canGoNext = useAtomValue(sourceCanGoNextAtom)+ const continueFromSource = useSetAtom(continueFromSourceAtom)++ return (+ <Button+ type="button"+ variant="primary"+ disabled={!canGoNext}+ onClick={() => continueFromSource({+ defaultDslAppName: t('createGuide.dsl.defaultAppName'),+ defaultReleaseName: t('createGuide.release.defaultName'),+ })}+ >+ {t('createGuide.actions.next')}+ </Button>+ )+}diff --git a/web/features/deployments/create-guide/ui/target-step.tsx b/web/features/deployments/create-guide/ui/target-step.tsxnew file mode 100644index 00000000000..690d5131290--- /dev/null+++ b/web/features/deployments/create-guide/ui/target-step.tsx@@ -0,0 +1,356 @@+'use client'++import type { Environment } from '@dify/contracts/enterprise/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { RadioControl, RadioRoot } from '@langgenius/dify-ui/radio'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'+import { toast } from '@langgenius/dify-ui/toast'+import { useAtomValue, useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import {+ EnvVarBindingsPanel,+} from '@/features/deployments/components/env-var-bindings'+import {+ RuntimeCredentialBindingsPanel,+} from '@/features/deployments/components/runtime-credential-bindings'+import { TitleTooltip } from '@/features/deployments/components/title-tooltip'+import { UnsupportedDslNodesAlert } from '@/features/deployments/components/unsupported-dsl-nodes-alert'+import {+ canDeployAtom,+ canSkipDeploymentAtom,+ createDeploymentGuideSubmissionAtom,+ CreateDeploymentGuideSubmissionBlockedError,+ deployableEnvironmentsAtom,+ deployableEnvironmentsQueryAtom,+ deploymentOptionsQueryAtom,+ deploymentTargetBindingSelectionsAtom,+ deploymentTargetBindingSlotsAtom,+ deploymentTargetEnvVarSlotsAtom,+ effectiveSelectedEnvironmentIdAtom,+ envVarValuesAtom,+ isCreatingReleaseOnlyAtom,+ isSubmittingDeploymentGuideAtom,+ selectBindingAtom,+ selectedEnvironmentIdAtom,+ setEnvVarAtom,+ stepAtom,+ unsupportedDslNodesAtom,+} from '@/features/deployments/create-guide/state'+import { deploymentErrorMessage } from '@/features/deployments/shared/domain/error'+import { useRouter } from '@/next/navigation'+import { StepShell } from './layout'++const targetEnvironmentSkeletonKeys = ['first-target-environment', 'second-target-environment']+const targetBindingSkeletonKeys = ['first-target-binding', 'second-target-binding']++export function TargetStepContent() {+ const { t } = useTranslation('deployments')+ const unsupportedDslNodes = useAtomValue(unsupportedDslNodesAtom)++ return (+ <StepShell+ title={t('createGuide.target.title')}+ description={t('createGuide.target.description')}+ hideHeader+ >+ <div className="flex flex-col gap-6">+ <TargetEnvironmentSection />+ <UnsupportedDslNodesAlert nodes={unsupportedDslNodes} />+ <TargetBindingSection />+ <TargetEnvVarSection />+ </div>+ </StepShell>+ )+}++function TargetEnvironmentSection() {+ const { t } = useTranslation('deployments')+ const environmentsQuery = useAtomValue(deployableEnvironmentsQueryAtom)+ const environments = useAtomValue(deployableEnvironmentsAtom)+ const effectiveSelectedEnvironmentId = useAtomValue(effectiveSelectedEnvironmentIdAtom)+ const isEnvironmentError = environmentsQuery.isError+ const isEnvironmentLoading = environmentsQuery.isLoading || (environmentsQuery.isFetching && !environmentsQuery.data)+ const selectEnvironment = useSetAtom(selectedEnvironmentIdAtom)+ const hasEnvironmentOptions = environments.length > 0++ return (+ <div className="flex flex-col gap-3">+ <div className="system-xs-medium-uppercase text-text-tertiary">{t('createGuide.target.environment')}</div>+ {hasEnvironmentOptions+ ? (+ <RadioGroup<string>+ value={effectiveSelectedEnvironmentId}+ onValueChange={selectEnvironment}+ className="grid grid-cols-1 items-stretch gap-3 lg:grid-cols-2"+ >+ {environments.map(environment => (+ <EnvironmentOptionRow+ key={environment.id}+ environment={environment}+ />+ ))}+ </RadioGroup>+ )+ : isEnvironmentLoading+ ? <TargetEnvironmentSkeleton />+ : (+ <div className="rounded-lg border border-divider-subtle bg-background-default-subtle px-3 py-3 system-sm-regular text-text-quaternary">+ {isEnvironmentError+ ? t('createGuide.target.loadEnvironmentsFailed')+ : t('createGuide.target.noEnvironmentOptions')}+ </div>+ )}+ </div>+ )+}++function EnvironmentOptionRow({ environment }: {+ environment: Environment+}) {+ const { t } = useTranslation('deployments')+ const summary = environment.description.trim() || `${t(`mode.${environment.mode}`)} · ${t(`backend.${environment.backend}`)}`++ return (+ <RadioRoot<string>+ value={environment.id}+ variant="unstyled"+ className={cn(+ 'group flex cursor-pointer items-center gap-3 rounded-xl border p-3 outline-hidden',+ 'border-components-option-card-option-border bg-components-option-card-option-bg hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',+ 'focus-visible:ring-2 focus-visible:ring-state-accent-solid',+ 'data-checked:border-state-accent-solid data-checked:bg-state-accent-hover data-checked:shadow-xs',+ )}+ >+ <RadioControl />+ <span className="flex min-w-0 grow flex-col gap-1">+ <span className="truncate system-sm-semibold text-text-primary group-data-checked:text-text-accent">{environment.displayName}</span>+ <TitleTooltip content={summary}>+ <span className="line-clamp-1 system-xs-regular text-text-tertiary group-data-checked:text-text-secondary">+ {summary}+ </span>+ </TitleTooltip>+ </span>+ </RadioRoot>+ )+}++function TargetBindingSection() {+ const { t } = useTranslation('deployments')+ const deploymentOptionsQuery = useAtomValue(deploymentOptionsQueryAtom)+ const bindingSlots = useAtomValue(deploymentTargetBindingSlotsAtom)+ const bindingSelections = useAtomValue(deploymentTargetBindingSelectionsAtom)+ const isBindingError = deploymentOptionsQuery.isError+ const isBindingLoading = deploymentOptionsQuery.isLoading || (deploymentOptionsQuery.isFetching && !deploymentOptionsQuery.data)+ const selectBinding = useSetAtom(selectBindingAtom)+ const unsupportedDslNodes = useAtomValue(unsupportedDslNodesAtom)+ const shouldRender = !(isBindingError && unsupportedDslNodes.length > 0)++ if (!shouldRender)+ return null++ if (isBindingLoading || isBindingError) {+ return (+ <div className="overflow-hidden rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg">+ <div className="flex min-w-0 flex-col gap-0.5 px-3 py-2.5">+ <div className="system-xs-medium-uppercase text-text-tertiary">{t('createGuide.target.bindings')}</div>+ <span className="system-xs-regular text-text-tertiary">{t('createGuide.target.bindingHint')}</span>+ </div>+ {isBindingLoading+ ? <TargetBindingSkeleton />+ : (+ <div className="border-t border-divider-subtle px-3 py-3 system-sm-regular text-text-quaternary">+ {t('createGuide.target.loadBindingsFailed')}+ </div>+ )}+ </div>+ )+ }++ return (+ <RuntimeCredentialBindingsPanel+ slots={bindingSlots}+ selections={bindingSelections}+ title={t('createGuide.target.bindings')}+ hint={t('createGuide.target.bindingHint')}+ noBindingRequiredLabel={t('createGuide.target.noBindingRequired')}+ noCredentialCandidatesLabel={t('createGuide.target.noCredentialCandidates')}+ selectCredentialLabel={t('createGuide.target.selectCredential')}+ missingRequiredLabel={t('createGuide.target.missingRequiredBinding')}+ bindingCountLabel={t('createGuide.target.bindingCount', { count: bindingSlots.length })}+ onChange={selectBinding}+ listScrollable={false}+ className="border-components-option-card-option-border bg-components-option-card-option-bg"+ />+ )+}++function TargetEnvVarSection() {+ const { t } = useTranslation('deployments')+ const setEnvVar = useSetAtom(setEnvVarAtom)+ const envVarValues = useAtomValue(envVarValuesAtom)+ const deploymentOptionsQuery = useAtomValue(deploymentOptionsQueryAtom)+ const envVarSlots = useAtomValue(deploymentTargetEnvVarSlotsAtom)+ const isBindingError = deploymentOptionsQuery.isError+ const isBindingLoading = deploymentOptionsQuery.isLoading || (deploymentOptionsQuery.isFetching && !deploymentOptionsQuery.data)++ if (isBindingLoading || isBindingError)+ return null++ return (+ <EnvVarBindingsPanel+ slots={envVarSlots}+ values={envVarValues}+ title={t('createGuide.target.envVars')}+ hint={t('createGuide.target.envVarHint')}+ envVarPlaceholder={t('createGuide.target.envVarPlaceholder')}+ literalSourceLabel={t('createGuide.target.envVarSource.literal')}+ defaultSourceLabel={t('createGuide.target.envVarSource.default')}+ lastDeploymentSourceLabel={t('createGuide.target.envVarSource.lastDeployment')}+ valueTypeLabels={{+ string: t('createGuide.target.envVarType.string'),+ number: t('createGuide.target.envVarType.number'),+ secret: t('createGuide.target.envVarType.secret'),+ }}+ sourceAriaLabel={key => t('createGuide.target.envVarSource.ariaLabel', { key })}+ envVarCountLabel={t('createGuide.target.envVarCount', { count: envVarSlots.length })}+ onChange={setEnvVar}+ listScrollable={false}+ className="border-components-option-card-option-border bg-components-option-card-option-bg"+ />+ )+}++function TargetEnvironmentSkeleton() {+ return (+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">+ {targetEnvironmentSkeletonKeys.map(key => (+ <SkeletonRow key={key} className="h-17 rounded-xl border border-divider-subtle px-3 py-3">+ <SkeletonRectangle className="my-0 size-4 animate-pulse rounded-full" />+ <div className="flex min-w-0 grow flex-col gap-1.5">+ <SkeletonRectangle className="my-0 h-3.5 w-1/2 animate-pulse" />+ <SkeletonRectangle className="my-0 h-3 w-2/3 animate-pulse" />+ </div>+ </SkeletonRow>+ ))}+ </div>+ )+}++function TargetBindingSkeleton() {+ return (+ <div className="border-t border-divider-subtle">+ {targetBindingSkeletonKeys.map(key => (+ <SkeletonRow key={key} className="h-15 px-3 py-3">+ <div className="flex min-w-0 grow flex-col gap-1.5">+ <SkeletonRectangle className="my-0 h-3.5 w-1/3 animate-pulse" />+ <SkeletonRectangle className="my-0 h-3 w-1/2 animate-pulse" />+ </div>+ <SkeletonRectangle className="my-0 h-8 w-48 animate-pulse rounded-lg" />+ </SkeletonRow>+ ))}+ </div>+ )+}++export function TargetBackButton() {+ const { t } = useTranslation('deployments')+ const setStep = useSetAtom(stepAtom)+ const isSubmitting = useAtomValue(isSubmittingDeploymentGuideAtom)++ return (+ <Button type="button" variant="secondary" onClick={() => setStep('release')} disabled={isSubmitting}>+ {t('createGuide.actions.back')}+ </Button>+ )+}++export function TargetSkipDeploymentButton() {+ const { t } = useTranslation('deployments')+ const router = useRouter()+ const canSkipDeployment = useAtomValue(canSkipDeploymentAtom)+ const submitCreateDeploymentGuide = useSetAtom(createDeploymentGuideSubmissionAtom)+ const isSubmitting = useAtomValue(isSubmittingDeploymentGuideAtom)+ const isSkippingDeployment = useAtomValue(isCreatingReleaseOnlyAtom)+ const label = isSkippingDeployment+ ? t('createGuide.actions.creating')+ : t('createGuide.actions.skipDeploy')++ async function handleSkipDeployment() {+ if (!canSkipDeployment)+ return++ try {+ const appInstanceId = await submitCreateDeploymentGuide({ deployToEnvironment: false })+ if (appInstanceId)+ router.push(`/deployments/${appInstanceId}/overview`)+ }+ catch (error) {+ await showSubmissionError({+ error,+ fallbackMessage: t('createGuide.errors.createReleaseFailed'),+ unsupportedDslModeMessage: t('createGuide.dsl.unsupportedMode'),+ })+ }+ }++ return (+ <Button type="button" variant="secondary" disabled={!canSkipDeployment || isSubmitting} onClick={handleSkipDeployment}>+ {label}+ </Button>+ )+}++export function TargetDeployButton() {+ const { t } = useTranslation('deployments')+ const router = useRouter()+ const canDeploy = useAtomValue(canDeployAtom)+ const submitCreateDeploymentGuide = useSetAtom(createDeploymentGuideSubmissionAtom)+ const isSubmitting = useAtomValue(isSubmittingDeploymentGuideAtom)+ const isSkippingDeployment = useAtomValue(isCreatingReleaseOnlyAtom)+ const label = isSubmitting && !isSkippingDeployment+ ? t('createGuide.actions.deploying')+ : t('createGuide.actions.createAndDeploy')++ async function handleDeploy() {+ if (!canDeploy)+ return++ try {+ const appInstanceId = await submitCreateDeploymentGuide({ deployToEnvironment: true })+ if (appInstanceId)+ router.push(`/deployments/${appInstanceId}/overview`)+ }+ catch (error) {+ await showSubmissionError({+ error,+ fallbackMessage: t('createGuide.errors.deployFailed'),+ unsupportedDslModeMessage: t('createGuide.dsl.unsupportedMode'),+ })+ }+ }++ return (+ <Button type="button" variant="primary" disabled={!canDeploy || isSubmitting} onClick={handleDeploy}>+ {label}+ </Button>+ )+}++async function showSubmissionError({+ error,+ fallbackMessage,+ unsupportedDslModeMessage,+}: {+ error: unknown+ fallbackMessage: string+ unsupportedDslModeMessage: string+}) {+ if (error instanceof CreateDeploymentGuideSubmissionBlockedError) {+ toast.error(error.reason === 'unsupportedDslMode' ? unsupportedDslModeMessage : fallbackMessage)+ return+ }++ toast.error(await deploymentErrorMessage(error) || fallbackMessage)+}diff --git a/web/features/deployments/create-release/index.tsx b/web/features/deployments/create-release/index.tsxnew file mode 100644index 00000000000..3bfdde51bcd--- /dev/null+++ b/web/features/deployments/create-release/index.tsx@@ -0,0 +1,72 @@+'use client'++import type { ButtonProps } from '@langgenius/dify-ui/button'+import { Button } from '@langgenius/dify-ui/button'+import { useSetAtom } from 'jotai'+import { ScopeProvider } from 'jotai-scope'+import { useTranslation } from 'react-i18next'+import {+ createReleaseConfigAtom,+ createReleaseLocalAtoms,+ openCreateReleaseDialogAtom,+} from './state'+import { CreateReleaseDialog } from './ui/dialog'++function CreateReleaseTrigger({+ variant,+ size,+ label,+ className,+}: {+ variant: ButtonProps['variant']+ size: ButtonProps['size']+ label?: string+ className?: string+}) {+ const { t } = useTranslation('deployments')+ const openDialog = useSetAtom(openCreateReleaseDialogAtom)++ return (+ <Button+ size={size}+ variant={variant}+ className={className}+ onClick={openDialog}+ >+ {label ?? t('versions.createRelease')}+ </Button>+ )+}++export function CreateReleaseControl({+ appInstanceId,+ variant = 'primary',+ size = 'small',+ label,+ className,+}: {+ appInstanceId: string+ variant?: ButtonProps['variant']+ size?: ButtonProps['size']+ label?: string+ className?: string+}) {+ return (+ <ScopeProvider+ key={appInstanceId}+ atoms={[+ [createReleaseConfigAtom, { appInstanceId }],+ ...createReleaseLocalAtoms,+ ]}+ name="CreateRelease"+ >+ <CreateReleaseTrigger+ variant={variant}+ size={size}+ label={label}+ className={className}+ />+ <CreateReleaseDialog />+ </ScopeProvider>+ )+}diff --git a/web/features/deployments/create-release/state/index.ts b/web/features/deployments/create-release/state/index.tsnew file mode 100644index 00000000000..ee6bcf9d28b--- /dev/null+++ b/web/features/deployments/create-release/state/index.ts@@ -0,0 +1,122 @@+'use client'++import type { UnsupportedDslNode } from '../../shared/domain/error'+import type { CreateReleaseForm } from './use-create-release-form'+import { atom, useAtomValue } from 'jotai'+import { encodeDslContent, isWorkflowDsl } from '../../shared/domain/dsl'++type CreateReleaseConfig = {+ appInstanceId: string+}++export type CreateReleaseDslState = {+ dslContent: string+ dslReadError: boolean+ encodedDslContent: string+ hasDslContent: boolean+ isReadingDsl: boolean+ isWorkflowDslContent: boolean+}++export const createReleaseConfigAtom = atom<CreateReleaseConfig | undefined>(undefined)+export const createReleaseDialogOpenAtom = atom(false)+export const createReleaseFormAtom = atom<CreateReleaseForm | undefined>(undefined)+export const createReleaseSubmitUnsupportedDslNodesAtom = atom<UnsupportedDslNode[]>([])++const createReleaseDslContentAtom = atom('')+const createReleaseDslReadErrorAtom = atom(false)+const createReleaseDslReadingAtom = atom(false)+const createReleaseDslReadTokenAtom = atom(0)++export const createReleaseLocalAtoms = [+ createReleaseDialogOpenAtom,+ createReleaseDslContentAtom,+ createReleaseDslReadErrorAtom,+ createReleaseDslReadingAtom,+ createReleaseDslReadTokenAtom,+ createReleaseSubmitUnsupportedDslNodesAtom,+] as const++export const clearCreateReleaseSubmissionErrorAtom = atom(null, (_get, set) => {+ set(createReleaseSubmitUnsupportedDslNodesAtom, [])+})++export const resetCreateReleaseDslFileAtom = atom(null, (get, set) => {+ set(createReleaseDslReadTokenAtom, get(createReleaseDslReadTokenAtom) + 1)+ set(createReleaseDslContentAtom, '')+ set(createReleaseDslReadingAtom, false)+ set(createReleaseDslReadErrorAtom, false)+})++export const openCreateReleaseDialogAtom = atom(null, (_get, set) => {+ set(clearCreateReleaseSubmissionErrorAtom)+ set(resetCreateReleaseDslFileAtom)+ set(createReleaseDialogOpenAtom, true)+})++export const closeCreateReleaseDialogAtom = atom(null, (_get, set) => {+ set(createReleaseDialogOpenAtom, false)+ set(clearCreateReleaseSubmissionErrorAtom)+ set(resetCreateReleaseDslFileAtom)+})++export const selectCreateReleaseDslFileAtom = atom(null, async (get, set, file?: File) => {+ const readToken = get(createReleaseDslReadTokenAtom) + 1+ set(createReleaseDslReadTokenAtom, readToken)+ set(createReleaseDslContentAtom, '')+ set(createReleaseDslReadingAtom, false)+ set(createReleaseDslReadErrorAtom, false)++ if (!file)+ return++ set(createReleaseDslReadingAtom, true)+ try {+ const content = await file.text()+ if (get(createReleaseDslReadTokenAtom) !== readToken)+ return++ set(createReleaseDslContentAtom, content)+ }+ catch {+ if (get(createReleaseDslReadTokenAtom) !== readToken)+ return++ set(createReleaseDslReadErrorAtom, true)+ }+ finally {+ if (get(createReleaseDslReadTokenAtom) === readToken)+ set(createReleaseDslReadingAtom, false)+ }+})++export const createReleaseDslStateAtom = atom((get): CreateReleaseDslState => {+ const dslContent = get(createReleaseDslContentAtom)+ const hasDslContent = Boolean(dslContent.trim())+ const isWorkflowDslContent = hasDslContent ? isWorkflowDsl(dslContent) : false++ return {+ dslContent,+ dslReadError: get(createReleaseDslReadErrorAtom),+ encodedDslContent: hasDslContent && isWorkflowDslContent ? encodeDslContent(dslContent) : '',+ hasDslContent,+ isReadingDsl: get(createReleaseDslReadingAtom),+ isWorkflowDslContent,+ }+})++export function useCreateReleaseConfig() {+ const config = useAtomValue(createReleaseConfigAtom)+ if (!config)+ throw new Error('Missing create release config.')++ return config+}++export function useCreateReleaseFormApi() {+ const form = useAtomValue(createReleaseFormAtom)+ if (!form)+ throw new Error('Missing create release form.')++ return form+}diff --git a/web/features/deployments/create-release/state/types.ts b/web/features/deployments/create-release/state/types.tsnew file mode 100644index 00000000000..0ebb291ed7c--- /dev/null+++ b/web/features/deployments/create-release/state/types.ts@@ -0,0 +1,19 @@+import type { SourceAppPickerValue } from '../ui/source-app-picker-value'++export type ReleaseSourceMode = 'sourceApp' | 'dsl'++export type CreateReleaseFormValues = {+ releaseSourceMode: ReleaseSourceMode+ sourceApp?: SourceAppPickerValue+ dslFile?: File+ releaseName: string+ releaseDescription: string+}++export const DEFAULT_CREATE_RELEASE_FORM_VALUES: CreateReleaseFormValues = {+ releaseSourceMode: 'sourceApp',+ sourceApp: undefined,+ dslFile: undefined,+ releaseName: '',+ releaseDescription: '',+}diff --git a/web/features/deployments/create-release/state/use-create-release-form.ts b/web/features/deployments/create-release/state/use-create-release-form.tsnew file mode 100644index 00000000000..9e7c3b6e911--- /dev/null+++ b/web/features/deployments/create-release/state/use-create-release-form.ts@@ -0,0 +1,24 @@+'use client'++import type { CreateReleaseFormValues } from './types'+import { useForm } from '@tanstack/react-form'+import { DEFAULT_CREATE_RELEASE_FORM_VALUES } from './types'++export const RELEASE_NAME_REQUIRED_ERROR = 'releaseNameRequired'++export function validateReleaseName({ value }: {+ value: string+}) {+ return value.trim() ? undefined : RELEASE_NAME_REQUIRED_ERROR+}++export function useCreateReleaseForm({ onSubmit }: {+ onSubmit: (value: CreateReleaseFormValues) => Promise<void> | void+}) {+ return useForm({+ defaultValues: DEFAULT_CREATE_RELEASE_FORM_VALUES,+ onSubmit: ({ value }) => onSubmit(value),+ })+}++export type CreateReleaseForm = ReturnType<typeof useCreateReleaseForm>diff --git a/web/features/deployments/create-release/ui/actions.tsx b/web/features/deployments/create-release/ui/actions.tsxnew file mode 100644index 00000000000..cd2eee506ef--- /dev/null+++ b/web/features/deployments/create-release/ui/actions.tsx@@ -0,0 +1,91 @@+'use client'++import type { CreateReleaseFormValues } from '../state/types'+import { Button } from '@langgenius/dify-ui/button'+import { useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import {+ closeCreateReleaseDialogAtom,+ useCreateReleaseFormApi,+} from '../state'+import {+ createReleaseReadiness,+ useCreateReleaseSourceSelection,+ useReleaseContentCheck,+} from './use-release-content-check'++export function CreateReleaseActions() {+ const form = useCreateReleaseFormApi()++ return (+ <form.Subscribe selector={state => ({+ isSubmitting: state.isSubmitting,+ values: state.values,+ })}+ >+ {({ isSubmitting, values }) => (+ <CreateReleaseActionsContent+ formValues={values}+ isSubmitting={isSubmitting}+ />+ )}+ </form.Subscribe>+ )+}++function CreateReleaseActionsContent({+ formValues,+ isSubmitting,+}: {+ formValues: CreateReleaseFormValues+ isSubmitting: boolean+}) {+ const { t } = useTranslation('deployments')+ const closeDialog = useSetAtom(closeCreateReleaseDialogAtom)+ const sourceSelection = useCreateReleaseSourceSelection(formValues)+ const releaseContent = useReleaseContentCheck(sourceSelection)+ const { canCreate, isCheckingReleaseContent } = createReleaseReadiness({+ formValues,+ isSubmitting,+ releaseContent,+ })++ function requestClose() {+ if (isSubmitting)+ return++ closeDialog()+ }++ return (+ <div className="flex items-center justify-end gap-4 border-t border-divider-subtle bg-background-default-subtle px-6 py-4">+ <div className="flex shrink-0 justify-end gap-2">+ <Button+ type="button"+ variant="secondary"+ disabled={isSubmitting}+ onPointerDown={(event) => {+ event.preventDefault()+ event.stopPropagation()+ requestClose()+ }}+ onClick={(event) => {+ event.preventDefault()+ event.stopPropagation()+ requestClose()+ }}+ >+ {t('versions.cancelCreate')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ className="min-w-22"+ disabled={!canCreate}+ >+ {isSubmitting ? t('versions.creating') : isCheckingReleaseContent ? t('versions.checkingReleaseContent') : t('versions.create')}+ </Button>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/create-release/ui/content-feedback.tsx b/web/features/deployments/create-release/ui/content-feedback.tsxnew file mode 100644index 00000000000..24e4a573744--- /dev/null+++ b/web/features/deployments/create-release/ui/content-feedback.tsx@@ -0,0 +1,63 @@+'use client'++import type { CreateReleaseFormValues } from '../state/types'+import { useAtomValue } from 'jotai'+import { useTranslation } from 'react-i18next'+import { UnsupportedDslNodesAlert } from '../../components/unsupported-dsl-nodes-alert'+import {+ createReleaseSubmitUnsupportedDslNodesAtom,+ useCreateReleaseFormApi,+} from '../state'+import {+ useCreateReleaseSourceSelection,+ useReleaseContentCheck,+} from './use-release-content-check'++export function ReleaseContentFeedback() {+ const form = useCreateReleaseFormApi()++ return (+ <form.Subscribe selector={state => state.values}>+ {formValues => <ReleaseContentFeedbackContent formValues={formValues} />}+ </form.Subscribe>+ )+}++function ReleaseContentFeedbackContent({ formValues }: {+ formValues: CreateReleaseFormValues+}) {+ const { t } = useTranslation('deployments')+ const sourceSelection = useCreateReleaseSourceSelection(formValues)+ const releaseContent = useReleaseContentCheck(sourceSelection)+ const submitUnsupportedDslNodes = useAtomValue(createReleaseSubmitUnsupportedDslNodesAtom)+ // Precheck reports unsupported nodes at pick time; the post-submit atom stays+ // as the TOCTOU fallback when the content changes server-side between+ // precheck and create.+ const unsupportedDslNodes = releaseContent.unsupportedNodes.length > 0+ ? releaseContent.unsupportedNodes+ : submitUnsupportedDslNodes++ return (+ <>+ <UnsupportedDslNodesAlert nodes={unsupportedDslNodes} />++ {releaseContent.isCheckingReleaseContent && (+ <div className="rounded-lg border border-divider-subtle bg-background-default-subtle px-3 py-2 system-sm-regular text-text-tertiary">+ {t('versions.checkingReleaseContent')}+ </div>+ )}++ {releaseContent.matchedRelease && (+ <div role="alert" className="rounded-lg border border-util-colors-warning-warning-200 bg-util-colors-warning-warning-50 px-3 py-2 system-sm-regular text-util-colors-warning-warning-700">+ {t('versions.releaseAlreadyExists', { name: releaseContent.matchedRelease.displayName })}+ </div>+ )}++ {releaseContent.releaseContentCheckFailed && (+ <div role="alert" className="rounded-lg border border-util-colors-red-red-200 bg-util-colors-red-red-50 px-3 py-2 system-sm-regular text-util-colors-red-red-700">+ {t('versions.releaseContentCheckFailed')}+ </div>+ )}+ </>+ )+}diff --git a/web/features/deployments/create-release/ui/dialog.tsx b/web/features/deployments/create-release/ui/dialog.tsxnew file mode 100644index 00000000000..501600e73ac--- /dev/null+++ b/web/features/deployments/create-release/ui/dialog.tsx@@ -0,0 +1,203 @@+'use client'++import type { CreateReleaseFormValues } from '../state/types'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtomValue, useSetAtom } from 'jotai'+import { ScopeProvider } from 'jotai-scope'+import { useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import {+ closeCreateReleaseDialogAtom,+ createReleaseDialogOpenAtom,+ createReleaseFormAtom,+ openCreateReleaseDialogAtom,+ useCreateReleaseConfig,+ useCreateReleaseFormApi,+} from '../state'+import { useCreateReleaseForm } from '../state/use-create-release-form'+import { CreateReleaseActions } from './actions'+import { ReleaseContentFeedback } from './content-feedback'+import { ReleaseMetadataFields } from './metadata-fields'+import { workflowSourceAppPickerValue } from './source-app-picker-value'+import { ReleaseSourceSection } from './source-section'+import { useCreateReleaseSubmission } from './use-create-release-submission'++const DEFAULT_SOURCE_RELEASE_PAGE_SIZE = 1++function CreateReleaseCloseButton({ isSubmitting }: {+ isSubmitting: boolean+}) {+ const closeDialog = useSetAtom(closeCreateReleaseDialogAtom)++ function requestClose() {+ if (isSubmitting)+ return++ closeDialog()+ }++ return (+ <DialogCloseButton+ type="button"+ disabled={isSubmitting}+ onPointerDown={(event) => {+ event.preventDefault()+ event.stopPropagation()+ requestClose()+ }}+ onClick={(event) => {+ event.preventDefault()+ event.stopPropagation()+ requestClose()+ }}+ />+ )+}++function CreateReleaseDefaultSourceApp({ formValues }: {+ formValues: CreateReleaseFormValues+}) {+ const { appInstanceId } = useCreateReleaseConfig()+ const form = useCreateReleaseFormApi()+ const isDialogOpen = useAtomValue(createReleaseDialogOpenAtom)+ const latestReleaseQuery = useQuery(consoleQuery.enterprise.releaseService.listReleases.queryOptions({+ input: {+ params: { appInstanceId },+ query: {+ pageNumber: 1,+ resultsPerPage: DEFAULT_SOURCE_RELEASE_PAGE_SIZE,+ },+ },+ enabled: isDialogOpen,+ }))+ const latestSourceAppId = latestReleaseQuery.data?.releases[0]?.sourceAppId+ const defaultSourceAppInput = isDialogOpen && latestSourceAppId+ ? { params: { app_id: latestSourceAppId } }+ : undefined+ const defaultSourceAppQuery = useQuery(defaultSourceAppInput+ ? consoleQuery.apps.byAppId.get.queryOptions({+ input: defaultSourceAppInput,+ })+ : {+ queryFn: skipToken,+ queryKey: ['create-release', 'default-source-app'],+ })+ const defaultSourceApp = latestSourceAppId+ ? workflowSourceAppPickerValue(defaultSourceAppQuery.data, latestSourceAppId)+ : undefined++ useEffect(() => {+ if (!isDialogOpen || formValues.releaseSourceMode !== 'sourceApp' || formValues.sourceApp || !defaultSourceApp)+ return++ form.setFieldValue('sourceApp', defaultSourceApp)+ }, [defaultSourceApp, form, formValues.releaseSourceMode, formValues.sourceApp, isDialogOpen])++ return null+}++function CreateReleaseDialogForm() {+ const submitReleaseRef = useRef<(value: CreateReleaseFormValues) => Promise<void> | void>(() => undefined)+ const form = useCreateReleaseForm({+ onSubmit: value => submitReleaseRef.current(value),+ })++ return (+ <ScopeProvider atoms={[[createReleaseFormAtom, form]]}>+ <form.Subscribe selector={state => ({+ isSubmitting: state.isSubmitting,+ values: state.values,+ })}+ >+ {({ isSubmitting, values }) => (+ <CreateReleaseDialogSurface+ formValues={values}+ isSubmitting={isSubmitting}+ submitReleaseRef={submitReleaseRef}+ />+ )}+ </form.Subscribe>+ </ScopeProvider>+ )+}++function CreateReleaseDialogSurface({+ formValues,+ isSubmitting,+ submitReleaseRef,+}: {+ formValues: CreateReleaseFormValues+ isSubmitting: boolean+ submitReleaseRef: {+ current: (value: CreateReleaseFormValues) => Promise<void> | void+ }+}) {+ const open = useAtomValue(createReleaseDialogOpenAtom)+ const openDialog = useSetAtom(openCreateReleaseDialogAtom)+ const closeDialog = useSetAtom(closeCreateReleaseDialogAtom)+ const { t } = useTranslation('deployments')+ const form = useCreateReleaseFormApi()+ const submission = useCreateReleaseSubmission(formValues)+ submitReleaseRef.current = submission.createRelease++ function handleDialogOpenChange(nextOpen: boolean) {+ if (nextOpen) {+ openDialog()+ return+ }++ if (!isSubmitting)+ closeDialog()+ }++ return (+ <Dialog+ open={open}+ onOpenChange={handleDialogOpenChange}+ >+ <DialogContent className="top-[18dvh] w-140 max-w-[calc(100vw-32px)] translate-y-0 overflow-hidden p-0">+ <CreateReleaseDefaultSourceApp formValues={formValues} />+ <CreateReleaseCloseButton isSubmitting={isSubmitting} />+ <form+ noValidate+ autoComplete="off"+ onSubmit={(event) => {+ event.preventDefault()+ event.stopPropagation()+ void form.handleSubmit()+ }}+ >+ <div className="border-b border-divider-subtle px-6 py-5 pr-14">+ <div className="min-w-0">+ <DialogTitle className="title-xl-semi-bold text-text-primary">+ {t('versions.createRelease')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('versions.createReleaseDescription')}+ </DialogDescription>+ </div>+ </div>++ <div className="flex flex-col gap-5 px-6 py-5">+ <ReleaseSourceSection />+ <ReleaseContentFeedback />+ <ReleaseMetadataFields />+ </div>++ <CreateReleaseActions />+ </form>+ </DialogContent>+ </Dialog>+ )+}++export function CreateReleaseDialog() {+ const open = useAtomValue(createReleaseDialogOpenAtom)++ if (!open)+ return null++ return <CreateReleaseDialogForm />+}diff --git a/web/features/deployments/create-release/ui/metadata-fields.tsx b/web/features/deployments/create-release/ui/metadata-fields.tsxnew file mode 100644index 00000000000..ee82c0bf18f--- /dev/null+++ b/web/features/deployments/create-release/ui/metadata-fields.tsx@@ -0,0 +1,106 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { useCreateReleaseFormApi } from '../state'+import {+ RELEASE_NAME_REQUIRED_ERROR,+ validateReleaseName,+} from '../state/use-create-release-form'++const DESCRIPTION_MAX_LENGTH = 512+const DESCRIPTION_WARN_THRESHOLD = 460++function hasReleaseNameRequiredError(errors: unknown[]) {+ return errors.includes(RELEASE_NAME_REQUIRED_ERROR)+}++export function ReleaseMetadataFields() {+ const { t } = useTranslation('deployments')+ const form = useCreateReleaseFormApi()+ const releaseNameInputRef = useRef<HTMLInputElement>(null)++ useEffect(() => {+ releaseNameInputRef.current?.focus()+ }, [])++ return (+ <>+ <form.Field+ name="releaseName"+ validators={{+ onBlur: validateReleaseName,+ onChange: validateReleaseName,+ onSubmit: validateReleaseName,+ }}+ >+ {field => (+ <div className="flex flex-col gap-2">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="release-name">+ {t('versions.releaseNameLabel')}+ </label>+ <Input+ ref={releaseNameInputRef}+ id="release-name"+ name="releaseName"+ placeholder={t('versions.releaseNamePlaceholder')}+ maxLength={128}+ autoComplete="off"+ value={field.state.value}+ aria-invalid={hasReleaseNameRequiredError(field.state.meta.errors) || undefined}+ aria-describedby={hasReleaseNameRequiredError(field.state.meta.errors) ? 'release-name-error' : undefined}+ onBlur={field.handleBlur}+ onChange={event => field.handleChange(event.target.value)}+ className="h-9"+ />+ {hasReleaseNameRequiredError(field.state.meta.errors) && (+ <div id="release-name-error" role="alert" className="system-xs-regular text-text-destructive">+ {t('versions.releaseNameRequired')}+ </div>+ )}+ </div>+ )}+ </form.Field>++ <form.Field name="releaseDescription">+ {field => (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-3">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="release-description">+ {t('versions.releaseDescriptionLabel')}+ </label>+ <div className="flex items-center gap-2">+ <span className="system-xs-regular text-text-quaternary">+ {t('versions.optional')}+ </span>+ <span+ className={cn(+ 'system-xs-regular tabular-nums',+ field.state.value.length >= DESCRIPTION_WARN_THRESHOLD ? 'text-util-colors-warning-warning-700' : 'text-text-quaternary',+ )}+ >+ {field.state.value.length}+ /+ {DESCRIPTION_MAX_LENGTH}+ </span>+ </div>+ </div>+ <Textarea+ id="release-description"+ name="releaseDescription"+ placeholder={t('versions.releaseDescriptionPlaceholder')}+ maxLength={DESCRIPTION_MAX_LENGTH}+ autoComplete="off"+ value={field.state.value}+ onValueChange={field.handleChange}+ className="min-h-24 resize-none"+ />+ </div>+ )}+ </form.Field>+ </>+ )+}diff --git a/web/features/deployments/create-release/ui/source-app-mode.ts b/web/features/deployments/create-release/ui/source-app-mode.tsnew file mode 100644index 00000000000..478417e92a3--- /dev/null+++ b/web/features/deployments/create-release/ui/source-app-mode.ts@@ -0,0 +1,11 @@+import { AppModeEnum } from '@/types/app'++type WorkflowAppMode = Extract<AppModeEnum, 'workflow'>++export function isWorkflowAppMode(mode?: string | null): mode is WorkflowAppMode {+ return mode === AppModeEnum.WORKFLOW+}++export function isWorkflowApp<T extends { mode?: string | null }>(app?: T): app is T & { mode: WorkflowAppMode } {+ return isWorkflowAppMode(app?.mode)+}diff --git a/web/features/deployments/create-release/ui/source-app-picker-value.ts b/web/features/deployments/create-release/ui/source-app-picker-value.tsnew file mode 100644index 00000000000..dee3375d784--- /dev/null+++ b/web/features/deployments/create-release/ui/source-app-picker-value.ts@@ -0,0 +1,23 @@+import type { App } from '@/types/app'+import { isWorkflowAppMode } from './source-app-mode'++export type SourceAppPickerValue = Pick<App, 'id' | 'name'> & Partial<Pick<App, 'icon_type' | 'icon' | 'icon_background' | 'icon_url' | 'mode'>>++export function workflowSourceAppPickerValue(value: unknown, fallbackId: string): SourceAppPickerValue | undefined {+ if (!value || typeof value !== 'object')+ return undefined++ const record = value as Record<string, unknown>+ const mode = typeof record.mode === 'string' ? record.mode : undefined+ if (!isWorkflowAppMode(mode))+ return undefined++ const id = typeof record.id === 'string' && record.id ? record.id : fallbackId+ const name = typeof record.name === 'string' && record.name ? record.name : id++ return {+ id,+ name,+ mode,+ }+}diff --git a/web/features/deployments/create-release/ui/source-app-picker.tsx b/web/features/deployments/create-release/ui/source-app-picker.tsxnew file mode 100644index 00000000000..93b99e7fac2--- /dev/null+++ b/web/features/deployments/create-release/ui/source-app-picker.tsx@@ -0,0 +1,241 @@+'use client'+import type { SourceAppPickerValue } from './source-app-picker-value'+import type { App } from '@/types/app'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxInputGroup,+ ComboboxItem,+ ComboboxItemText,+ ComboboxList,+ ComboboxTrigger,+} from '@langgenius/dify-ui/combobox'+import { keepPreviousData, useInfiniteQuery } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import { consoleQuery } from '@/service/client'+import { AppModeEnum } from '@/types/app'+import { TitleTooltip } from '../../components/title-tooltip'+import { isWorkflowApp } from './source-app-mode'++const SOURCE_APP_PAGE_SIZE = 20+const SOURCE_APP_PICKER_SKELETON_KEYS = ['first-source-app', 'second-source-app', 'third-source-app']++function sourceAppSearchText(app: App) {+ return `${app.name} ${app.id}`.toLowerCase()+}++function SourceAppTrigger({ open, app }: {+ open: boolean+ app?: SourceAppPickerValue+}) {+ const { t } = useTranslation('deployments')++ return (+ <span+ className={cn(+ 'group flex h-10 cursor-pointer items-center gap-2 rounded-lg border border-transparent bg-components-input-bg-normal px-3 text-left hover:border-components-input-border-hover hover:bg-components-input-bg-hover',+ open && 'border-components-input-border-active bg-components-input-bg-active shadow-xs',+ app && 'pl-2',+ )}+ >+ {app && (+ <AppIcon+ className="shrink-0"+ size="xs"+ iconType={app.icon_type}+ icon={app.icon}+ background={app.icon_background}+ imageUrl={app.icon_url}+ />+ )}+ <TitleTooltip content={app?.name}>+ <span+ className={cn(+ 'min-w-0 grow truncate',+ app+ ? 'system-sm-medium text-components-input-text-filled'+ : 'system-sm-regular text-components-input-text-placeholder',+ )}+ >+ {app?.name ?? t('createModal.appPickerPlaceholder')}+ </span>+ </TitleTooltip>+ <span+ className={cn(+ 'i-ri-arrow-down-s-line size-4 shrink-0 text-text-quaternary group-hover:text-text-secondary',+ open && 'text-text-secondary',+ )}+ aria-hidden="true"+ />+ </span>+ )+}++function SourceAppOption({ app }: {+ app: App+}) {+ return (+ <ComboboxItem+ value={app}+ className="mx-0 grid-cols-[minmax(0,1fr)] gap-3 py-1 pr-3 pl-2"+ >+ <ComboboxItemText className="flex min-w-0 items-center gap-3 px-0">+ <AppIcon+ className="shrink-0"+ size="xs"+ iconType={app.icon_type}+ icon={app.icon}+ background={app.icon_background}+ imageUrl={app.icon_url}+ />+ <TitleTooltip content={`${app.name} (${app.id})`}>+ <span className="flex min-w-0 grow items-center gap-1 truncate system-sm-medium text-components-input-text-filled">+ <span className="truncate">{app.name}</span>+ <span className="shrink-0 text-text-tertiary">+ (+ {app.id.slice(0, 8)}+ )+ </span>+ </span>+ </TitleTooltip>+ </ComboboxItemText>+ </ComboboxItem>+ )+}++function SourceAppPickerSkeleton() {+ return (+ <div className="flex flex-col gap-2 px-3 py-3">+ {SOURCE_APP_PICKER_SKELETON_KEYS.map(key => (+ <SkeletonRow key={key} className="h-7 gap-3">+ <SkeletonRectangle className="my-0 size-5 animate-pulse rounded-md" />+ <SkeletonRectangle className="h-3 w-32 animate-pulse" />+ </SkeletonRow>+ ))}+ </div>+ )+}++export function SourceAppPicker({ value, onChange, ariaLabel }: {+ value?: SourceAppPickerValue+ onChange: (app: App) => void+ ariaLabel?: string+}) {+ const { t } = useTranslation('deployments')+ const [isShow, setIsShow] = useState(false)+ const [searchText, setSearchText] = useState('')++ const {+ data,+ isLoading,+ isFetchingNextPage,+ fetchNextPage,+ hasNextPage,+ } = useInfiniteQuery({+ ...consoleQuery.apps.list.infiniteOptions({+ input: pageParam => ({+ query: {+ page: Number(pageParam),+ limit: SOURCE_APP_PAGE_SIZE,+ name: searchText,+ mode: AppModeEnum.WORKFLOW,+ },+ }),+ getNextPageParam: lastPage => lastPage.has_more ? lastPage.page + 1 : undefined,+ initialPageParam: 1,+ placeholderData: keepPreviousData,+ }),+ })++ const apps = data?.pages.flatMap(page => page.data).filter(isWorkflowApp) ?? []++ return (+ <Combobox<App>+ items={apps}+ open={isShow}+ inputValue={searchText}+ onOpenChange={setIsShow}+ onInputValueChange={setSearchText}+ onValueChange={(app) => {+ if (!app)+ return+ onChange(app)+ setIsShow(false)+ }}+ itemToStringLabel={(app) => {+ if (!app)+ return ''++ return app.name+ }}+ itemToStringValue={(app) => {+ if (!app)+ return ''++ return app.id+ }}+ filter={(app, query) => sourceAppSearchText(app).includes(query.toLowerCase())}+ disabled={false}+ >+ <ComboboxTrigger+ aria-label={ariaLabel ?? t('createModal.sourceApp')}+ icon={false}+ className="block h-auto w-full border-0 bg-transparent p-0 text-left hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 data-open:bg-transparent"+ >+ <SourceAppTrigger open={isShow} app={value} />+ </ComboboxTrigger>+ <ComboboxContent+ placement="bottom-start"+ sideOffset={4}+ popupClassName="border-0 bg-transparent p-0 shadow-none backdrop-blur-none"+ >+ <div className="relative flex max-h-100 min-h-20 w-89 flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs">+ <div className="p-2 pb-1">+ <ComboboxInputGroup className="h-8 min-h-8 px-2">+ <span className="i-ri-search-line size-4 shrink-0 text-text-tertiary" aria-hidden="true" />+ <ComboboxInput+ aria-label={t('createModal.appSearchPlaceholder')}+ placeholder={t('createModal.appSearchPlaceholder')}+ className="block h-4.5 grow px-1 py-0 text-[13px] text-text-primary"+ />+ </ComboboxInputGroup>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-1">+ {(isLoading || isFetchingNextPage) && apps.length === 0 && <SourceAppPickerSkeleton />}+ <ComboboxList className="max-h-none p-0">+ {(app: App) => (+ <SourceAppOption key={app.id} app={app} />+ )}+ </ComboboxList>+ {!(isLoading || isFetchingNextPage) && (+ <ComboboxEmpty>+ {t('createModal.appSearchEmpty')}+ </ComboboxEmpty>+ )}+ {hasNextPage && (+ <div className="flex justify-center px-3 py-2">+ <Button+ type="button"+ size="small"+ disabled={isFetchingNextPage}+ onClick={() => {+ void fetchNextPage()+ }}+ >+ {isFetchingNextPage ? t('createModal.loadingApps') : t('createModal.loadMoreApps')}+ </Button>+ </div>+ )}+ </div>+ </div>+ </ComboboxContent>+ </Combobox>+ )+}diff --git a/web/features/deployments/create-release/ui/source-section.tsx b/web/features/deployments/create-release/ui/source-section.tsxnew file mode 100644index 00000000000..59d95a2f69e--- /dev/null+++ b/web/features/deployments/create-release/ui/source-section.tsx@@ -0,0 +1,153 @@+'use client'++import type { ReleaseSourceMode } from '../state/types'+import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'+import { useAtomValue, useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import Uploader from '@/app/components/app/create-from-dsl-modal/uploader'+import {+ clearCreateReleaseSubmissionErrorAtom,+ createReleaseDslStateAtom,+ resetCreateReleaseDslFileAtom,+ selectCreateReleaseDslFileAtom,+ useCreateReleaseFormApi,+} from '../state'+import { SourceAppPicker } from './source-app-picker'++function selectedReleaseSourceMode(value: readonly ReleaseSourceMode[] | undefined) {+ return value?.[0]+}++export function ReleaseSourceSection() {+ const { t } = useTranslation('deployments')+ const form = useCreateReleaseFormApi()+ const resetDslFile = useSetAtom(resetCreateReleaseDslFileAtom)+ const clearSubmissionError = useSetAtom(clearCreateReleaseSubmissionErrorAtom)++ return (+ <form.Field name="releaseSourceMode">+ {modeField => (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <label id="release-source-mode-label" className="system-xs-medium-uppercase text-text-tertiary">+ {t('versions.releaseSourceLabel')}+ </label>+ <SegmentedControl<ReleaseSourceMode>+ aria-labelledby="release-source-mode-label"+ value={[modeField.state.value]}+ onValueChange={(value) => {+ const nextMode = selectedReleaseSourceMode(value)+ if (!nextMode || nextMode === modeField.state.value)+ return++ clearSubmissionError()+ modeField.handleChange(nextMode)+ if (nextMode === 'sourceApp') {+ form.setFieldValue('dslFile', undefined)+ resetDslFile()+ }+ else {+ form.setFieldValue('sourceApp', undefined)+ }+ }}+ className="shrink-0"+ >+ <SegmentedControlItem value="sourceApp" className="gap-1.5">+ <span className="i-ri-apps-2-line size-4 shrink-0" aria-hidden="true" />+ <span>{t('versions.sourceAppOption')}</span>+ </SegmentedControlItem>+ <SegmentedControlItem value="dsl" className="gap-1.5">+ <span className="i-ri-upload-cloud-2-line size-4 shrink-0" aria-hidden="true" />+ <span>{t('versions.manualDslOption')}</span>+ </SegmentedControlItem>+ </SegmentedControl>+ </div>++ <div className="min-h-12">+ {modeField.state.value === 'sourceApp'+ ? <SourceAppField />+ : <DslFileField />}+ </div>+ </div>+ )}+ </form.Field>+ )+}++function SourceAppField() {+ const { t } = useTranslation('deployments')+ const form = useCreateReleaseFormApi()+ const clearSubmissionError = useSetAtom(clearCreateReleaseSubmissionErrorAtom)++ return (+ <form.Field name="sourceApp">+ {field => (+ <div className="flex min-h-12 items-center">+ <SourceAppPicker+ value={field.state.value}+ onChange={(app) => {+ field.handleChange(app)+ clearSubmissionError()+ }}+ ariaLabel={t('versions.sourceAppOption')}+ />+ </div>+ )}+ </form.Field>+ )+}++function DslFileField() {+ const { t } = useTranslation('deployments')+ const form = useCreateReleaseFormApi()+ const dslState = useAtomValue(createReleaseDslStateAtom)+ const clearSubmissionError = useSetAtom(clearCreateReleaseSubmissionErrorAtom)+ const selectDslFile = useSetAtom(selectCreateReleaseDslFileAtom)++ return (+ <form.Field name="dslFile">+ {field => (+ <div className="flex min-h-12 flex-col gap-2">+ <Uploader+ file={field.state.value}+ updateFile={(file) => {+ field.handleChange(file)+ clearSubmissionError()+ void selectDslFile(file)+ }}+ className="mt-0"+ />+ {dslState.isReadingDsl && (+ <div className="system-xs-regular text-text-tertiary">+ {t('versions.dslReading')}+ </div>+ )}+ {dslState.dslReadError && (+ <div role="alert" className="system-xs-regular text-util-colors-red-red-600">+ {t('versions.dslReadFailed')}+ </div>+ )}+ <DslUnsupportedModeError />+ </div>+ )}+ </form.Field>+ )+}++function DslUnsupportedModeError() {+ const { t } = useTranslation('deployments')+ const dslState = useAtomValue(createReleaseDslStateAtom)+ const hasUnsupportedDslMode = dslState.hasDslContent+ && !dslState.isReadingDsl+ && !dslState.dslReadError+ && !dslState.isWorkflowDslContent++ if (!hasUnsupportedDslMode)+ return null++ return (+ <div role="alert" className="system-xs-regular text-util-colors-red-red-600">+ {t('versions.dslUnsupportedMode')}+ </div>+ )+}diff --git a/web/features/deployments/create-release/ui/use-create-release-submission.ts b/web/features/deployments/create-release/ui/use-create-release-submission.tsnew file mode 100644index 00000000000..7c220255ef2--- /dev/null+++ b/web/features/deployments/create-release/ui/use-create-release-submission.ts@@ -0,0 +1,109 @@+'use client'++import type { CreateReleaseResponse } from '@dify/contracts/enterprise/types.gen'+import type { CreateReleaseFormValues } from '../state/types'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { deploymentErrorMessage, unsupportedDslNodeError } from '../../shared/domain/error'+import {+ clearCreateReleaseSubmissionErrorAtom,+ closeCreateReleaseDialogAtom,+ createReleaseSubmitUnsupportedDslNodesAtom,+ useCreateReleaseConfig,+} from '../state'+import {+ canCheckReleaseSourceContent,+ useCreateReleaseSourceSelection,+ useReleaseContentCheck,+} from './use-release-content-check'++export function useCreateReleaseSubmission(formValues: CreateReleaseFormValues) {+ const { t } = useTranslation('deployments')+ const { appInstanceId } = useCreateReleaseConfig()+ const sourceSelection = useCreateReleaseSourceSelection(formValues)+ const releaseContent = useReleaseContentCheck(sourceSelection)+ const closeDialog = useSetAtom(closeCreateReleaseDialogAtom)+ const createReleaseMutation = useMutation(consoleQuery.enterprise.releaseService.createRelease.mutationOptions())+ const clearSubmitError = useSetAtom(clearCreateReleaseSubmissionErrorAtom)+ const setUnsupportedDslNodes = useSetAtom(createReleaseSubmitUnsupportedDslNodesAtom)++ function clearSubmissionError() {+ createReleaseMutation.reset()+ clearSubmitError()+ }++ function handleSuccess(response: CreateReleaseResponse) {+ const createdName = response.release.displayName+ toast.success(t('versions.createSuccess', { name: createdName }))+ closeDialog()+ }++ async function handleError(error: unknown) {+ const unsupportedError = await unsupportedDslNodeError(error)+ if (unsupportedError?.nodes.length) {+ setUnsupportedDslNodes(unsupportedError.nodes)+ return+ }++ const message = await deploymentErrorMessage(error)+ toast.error(message || t('versions.createFailed'))+ }++ async function createRelease(value: CreateReleaseFormValues) {+ if (releaseContent.isCheckingReleaseContent)+ return++ const submittedReleaseName = value.releaseName.trim()+ if (!submittedReleaseName)+ return++ clearSubmissionError()+ try {+ if (!canCheckReleaseSourceContent(sourceSelection) || !releaseContent.releaseContentReady)+ return++ if (value.releaseSourceMode === 'dsl') {+ if (!sourceSelection.isWorkflowDslContent) {+ toast.error(t('versions.dslUnsupportedMode'))+ return+ }++ const response = await createReleaseMutation.mutateAsync({+ body: {+ appInstanceId,+ dsl: sourceSelection.encodedDslContent,+ displayName: submittedReleaseName,+ description: value.releaseDescription.trim() || undefined,+ createAppInstance: false,+ },+ })+ handleSuccess(response)+ return+ }++ if (!sourceSelection.selectedSourceAppId)+ return++ const response = await createReleaseMutation.mutateAsync({+ body: {+ appInstanceId,+ sourceAppId: sourceSelection.selectedSourceAppId,+ displayName: submittedReleaseName,+ description: value.releaseDescription.trim() || undefined,+ createAppInstance: false,+ },+ })+ handleSuccess(response)+ }+ catch (error) {+ await handleError(error)+ }+ }++ return {+ createRelease,+ }+}diff --git a/web/features/deployments/create-release/ui/use-release-content-check.ts b/web/features/deployments/create-release/ui/use-release-content-check.tsnew file mode 100644index 00000000000..a903daae143--- /dev/null+++ b/web/features/deployments/create-release/ui/use-release-content-check.ts@@ -0,0 +1,124 @@+'use client'++import type { CreateReleaseDslState } from '../state'+import type { CreateReleaseFormValues, ReleaseSourceMode } from '../state/types'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'+import { consoleQuery } from '@/service/client'+import {+ createReleaseDialogOpenAtom,+ createReleaseDslStateAtom,+ useCreateReleaseConfig,+} from '../state'++export type CreateReleaseSourceSelection = CreateReleaseDslState & {+ hasUnsupportedDslMode: boolean+ releaseSourceMode: ReleaseSourceMode+ selectedSourceAppId?: string+}++function createReleaseSourceSelection(+ formValues: CreateReleaseFormValues,+ dslState: CreateReleaseDslState,+): CreateReleaseSourceSelection {+ const hasUnsupportedDslMode = formValues.releaseSourceMode === 'dsl'+ && dslState.hasDslContent+ && !dslState.isReadingDsl+ && !dslState.dslReadError+ && !dslState.isWorkflowDslContent+ const selectedSourceAppId = formValues.releaseSourceMode === 'sourceApp' ? formValues.sourceApp?.id : undefined++ return {+ ...dslState,+ hasUnsupportedDslMode,+ releaseSourceMode: formValues.releaseSourceMode,+ selectedSourceAppId,+ }+}++export function canCheckReleaseSourceContent(releaseSource: CreateReleaseSourceSelection) {+ if (releaseSource.releaseSourceMode === 'sourceApp')+ return Boolean(releaseSource.selectedSourceAppId)++ return Boolean(+ releaseSource.hasDslContent+ && !releaseSource.isReadingDsl+ && !releaseSource.dslReadError+ && !releaseSource.hasUnsupportedDslMode,+ )+}++export function useReleaseContentCheck(releaseSource: CreateReleaseSourceSelection) {+ const { appInstanceId } = useCreateReleaseConfig()+ const isDialogOpen = useAtomValue(createReleaseDialogOpenAtom)+ const canCheckReleaseContent = isDialogOpen && canCheckReleaseSourceContent(releaseSource)+ // PrecheckRelease takes exactly one source arm (dsl | sourceAppId).+ const precheckSource = releaseSource.releaseSourceMode === 'sourceApp'+ ? (releaseSource.selectedSourceAppId ? { sourceAppId: releaseSource.selectedSourceAppId } : undefined)+ : { dsl: releaseSource.encodedDslContent }+ const precheckInput = canCheckReleaseContent && precheckSource+ ? {+ body: {+ appInstanceId,+ ...precheckSource,+ },+ }+ : undefined+ const precheckQuery = useQuery({+ ...(precheckInput+ ? consoleQuery.enterprise.releaseService.precheckRelease.queryOptions({+ input: precheckInput,+ })+ : {+ queryFn: skipToken,+ queryKey: ['create-release', 'release-precheck'],+ }),+ retry: false,+ })+ const matchedRelease = canCheckReleaseContent ? precheckQuery.data?.matchedRelease : undefined+ const unsupportedNodes = (canCheckReleaseContent ? precheckQuery.data?.unsupportedNodes : undefined) ?? []+ const isCheckingReleaseContent = canCheckReleaseContent && (precheckQuery.isLoading || precheckQuery.isFetching)+ const releaseContentCheckFailed = canCheckReleaseContent && precheckQuery.isError+ const releaseContentReady = canCheckReleaseContent+ && precheckQuery.isSuccess+ && !isCheckingReleaseContent+ && !releaseContentCheckFailed+ && Boolean(precheckQuery.data?.canCreate)++ return {+ isCheckingReleaseContent,+ matchedRelease,+ releaseContentCheckFailed,+ releaseContentReady,+ unsupportedNodes,+ }+}++export type ReleaseContentCheck = ReturnType<typeof useReleaseContentCheck>++export function useCreateReleaseSourceSelection(formValues: CreateReleaseFormValues) {+ const dslState = useAtomValue(createReleaseDslStateAtom)++ return createReleaseSourceSelection(formValues, dslState)+}++export function createReleaseReadiness({+ formValues,+ isSubmitting,+ releaseContent,+}: {+ formValues: CreateReleaseFormValues+ isSubmitting: boolean+ releaseContent: ReleaseContentCheck+}) {+ const canCreate = Boolean(+ formValues.releaseName.trim()+ && releaseContent.releaseContentReady+ && !isSubmitting,+ )++ return {+ canCreate,+ isCheckingReleaseContent: releaseContent.isCheckingReleaseContent,+ }+}diff --git a/web/features/deployments/deploy-drawer/index.tsx b/web/features/deployments/deploy-drawer/index.tsxnew file mode 100644index 00000000000..88d2bae02cc--- /dev/null+++ b/web/features/deployments/deploy-drawer/index.tsx@@ -0,0 +1,64 @@+'use client'++import {+ Drawer,+ DrawerBackdrop,+ DrawerCloseButton,+ DrawerContent,+ DrawerPopup,+ DrawerPortal,+ DrawerViewport,+} from '@langgenius/dify-ui/drawer'+import { useAtomValue, useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import {+ closeDeployDrawerAtom,+ deployDrawerAppInstanceIdAtom,+ deployDrawerEnvironmentIdAtom,+ deployDrawerOpenAtom,+ deployDrawerReleaseIdAtom,+} from './state'+import { DeployForm } from './ui/form'++export function DeployDrawer() {+ const { t } = useTranslation('deployments')+ const open = useAtomValue(deployDrawerOpenAtom)+ const drawerAppInstanceId = useAtomValue(deployDrawerAppInstanceIdAtom)+ const drawerEnvironmentId = useAtomValue(deployDrawerEnvironmentIdAtom)+ const drawerReleaseId = useAtomValue(deployDrawerReleaseIdAtom)+ const closeDeployDrawer = useSetAtom(closeDeployDrawerAtom)+ const formKey = `${drawerAppInstanceId ?? 'none'}-${drawerEnvironmentId ?? 'any'}-${drawerReleaseId ?? 'new'}-${open ? '1' : '0'}`++ return (+ <Drawer+ open={open}+ modal+ swipeDirection="right"+ onOpenChange={next => !next && closeDeployDrawer()}+ >+ <DrawerPortal>+ <DrawerBackdrop />+ <DrawerViewport>+ <DrawerPopup className="data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-[640px] data-[swipe-direction=right]:max-w-[calc(100vw-1rem)] data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border-[0.5px]">+ <DrawerCloseButton+ aria-label={t('deployDrawer.close')}+ className="absolute top-4 right-5 size-6 rounded-md"+ />+ <DrawerContent className="flex min-h-0 flex-1 flex-col bg-components-panel-bg p-0 pb-0">+ {!drawerAppInstanceId+ ? <div className="p-6 text-text-tertiary">{t('deployDrawer.notFound')}</div>+ : (+ <DeployForm+ key={formKey}+ appInstanceId={drawerAppInstanceId}+ lockedEnvId={drawerEnvironmentId}+ presetReleaseId={drawerReleaseId}+ />+ )}+ </DrawerContent>+ </DrawerPopup>+ </DrawerViewport>+ </DrawerPortal>+ </Drawer>+ )+}diff --git a/web/features/deployments/deploy-drawer/state/__tests__/index.spec.ts b/web/features/deployments/deploy-drawer/state/__tests__/index.spec.tsnew file mode 100644index 00000000000..394dd8d81b3--- /dev/null+++ b/web/features/deployments/deploy-drawer/state/__tests__/index.spec.ts@@ -0,0 +1,451 @@+import type {+ CredentialCandidate,+ CredentialSlot,+ Environment,+ EnvironmentDeployment,+ EnvVarSlot,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import type { Getter } from 'jotai'+import {+ EnvVarValueSource,+ EnvVarValueType,+ PluginCategory,+ RuntimeInstanceStatus,+} from '@dify/contracts/enterprise/types.gen'+import { atom, createStore } from 'jotai'+import { beforeEach, describe, expect, it, vi } from 'vitest'++type QueryResult = {+ data?: {+ options: DeploymentOptions+ }+ isLoading: boolean+ isFetching: boolean+ isError: boolean+}++type DeploymentOptions = {+ credentialSlots: CredentialSlot[]+ envVarSlots: EnvVarSlot[]+}++type MutationOptions = {+ mutationKey?: readonly string[]+}++type MutationResult = {+ isPending: boolean+ mutate: ReturnType<typeof vi.fn>+}++const mockDeploymentOptionsQuery = vi.hoisted<{ current: QueryResult }>(() => ({+ current: {+ isLoading: false,+ isFetching: false,+ isError: false,+ },+}))+const mockPromoteMutate = vi.hoisted(() => vi.fn())+const mockRollbackMutate = vi.hoisted(() => vi.fn())+const mockPromoteMutation = vi.hoisted<{ current: MutationResult }>(() => ({+ current: {+ isPending: false,+ mutate: mockPromoteMutate,+ },+}))+const mockRollbackMutation = vi.hoisted<{ current: MutationResult }>(() => ({+ current: {+ isPending: false,+ mutate: mockRollbackMutate,+ },+}))++vi.mock('jotai-tanstack-query', () => ({+ atomWithQuery: (createOptions: (get: Getter) => unknown) => atom((get) => {+ createOptions(get)+ return mockDeploymentOptionsQuery.current+ }),+ atomWithMutation: (createOptions: () => MutationOptions) => atom(() => {+ const options = createOptions()+ return options.mutationKey?.[0] === 'rollback'+ ? mockRollbackMutation.current+ : mockPromoteMutation.current+ }),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ enterprise: {+ releaseService: {+ computeDeploymentOptions: {+ queryOptions: ({ enabled, input }: { enabled: boolean, input: unknown }) => ({+ enabled,+ input,+ queryKey: ['computeDeploymentOptions', input],+ }),+ },+ },+ deploymentService: {+ promote: {+ mutationOptions: () => ({ mutationKey: ['promote'] }),+ },+ rollback: {+ mutationOptions: () => ({ mutationKey: ['rollback'] }),+ },+ },+ },+ },+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: vi.fn(),+ },+}))++vi.mock('../../shared/domain/idempotency', () => ({+ createDeploymentIdempotencyKey: () => 'deploy-idempotency-key',+}))++async function loadState() {+ return await import('../index')+}++function environment(overrides: Partial<Environment> = {}): Environment {+ return {+ id: 'environment-1',+ displayName: 'Production',+ description: '',+ mode: 'ENVIRONMENT_MODE_SHARED',+ backend: 'RUNTIME_BACKEND_K8S',+ status: 'ENVIRONMENT_STATUS_READY',+ statusMessage: '',+ cpuCount: 1,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ ...overrides,+ } as Environment+}++function release(overrides: Partial<Release> = {}): Release {+ return {+ id: 'release-1',+ appInstanceId: 'app-instance-1',+ displayName: 'Release 1',+ description: '',+ sourceAppId: 'source-app-1',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ createdBy: {+ id: 'account-1',+ displayName: 'Owner',+ },+ ...overrides,+ } as Release+}++function credentialCandidate(overrides: Partial<CredentialCandidate> = {}): CredentialCandidate {+ return {+ credentialId: 'credential-1',+ providerId: 'langgenius/openai',+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ displayName: 'Primary key',+ fromEnterprise: false,+ ...overrides,+ }+}++function credentialSlot(overrides: Partial<CredentialSlot> = {}): CredentialSlot {+ return {+ providerId: 'langgenius/openai',+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ candidates: [+ credentialCandidate({ credentialId: 'credential-1' }),+ credentialCandidate({ credentialId: 'credential-2', displayName: 'Backup key' }),+ ],+ lastCredentialId: '',+ ...overrides,+ }+}++function envVarSlot(overrides: Partial<EnvVarSlot> = {}): EnvVarSlot {+ return {+ key: 'API_KEY',+ valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ description: '',+ ...overrides,+ }+}++function runtimeRow(overrides: Partial<EnvironmentDeployment> = {}): EnvironmentDeployment {+ return {+ environment: environment(),+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ currentRelease: release({ id: 'release-1', createdAt: '2026-01-01T00:00:00.000Z' }),+ desiredRelease: release({ id: 'release-1', createdAt: '2026-01-01T00:00:00.000Z' }),+ ...overrides,+ } as EnvironmentDeployment+}++function deployConfig() {+ return {+ appInstanceId: 'app-instance-1',+ environments: [+ environment({ id: 'environment-1', displayName: 'Production' }),+ environment({ id: 'environment-2', displayName: 'Staging' }),+ ],+ releases: [+ release({ id: 'release-2', displayName: 'Release 2', createdAt: '2026-01-02T00:00:00.000Z' }),+ release({ id: 'release-1', displayName: 'Release 1', createdAt: '2026-01-01T00:00:00.000Z' }),+ ],+ runtimeRows: [runtimeRow()],+ defaultReleaseId: 'release-2',+ }+}++function setQueryOptions(options: DeploymentOptions) {+ mockDeploymentOptionsQuery.current = {+ data: {+ options,+ },+ isLoading: false,+ isFetching: false,+ isError: false,+ }+}++describe('deploy drawer state', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockDeploymentOptionsQuery.current = {+ isLoading: false,+ isFetching: false,+ isError: false,+ }+ mockPromoteMutation.current = {+ isPending: false,+ mutate: mockPromoteMutate,+ }+ mockRollbackMutation.current = {+ isPending: false,+ mutate: mockRollbackMutate,+ }+ })++ it('should open and close the deploy drawer with route identity', async () => {+ const state = await loadState()+ const store = createStore()++ store.set(state.openDeployDrawerAtom, {+ appInstanceId: 'app-instance-1',+ environmentId: 'environment-1',+ releaseId: 'release-2',+ })++ expect(store.get(state.deployDrawerOpenAtom)).toBe(true)+ expect(store.get(state.deployDrawerAppInstanceIdAtom)).toBe('app-instance-1')+ expect(store.get(state.deployDrawerEnvironmentIdAtom)).toBe('environment-1')+ expect(store.get(state.deployDrawerReleaseIdAtom)).toBe('release-2')++ store.set(state.closeDeployDrawerAtom)++ expect(store.get(state.deployDrawerOpenAtom)).toBe(false)+ expect(store.get(state.deployDrawerAppInstanceIdAtom)).toBeUndefined()+ expect(store.get(state.deployDrawerEnvironmentIdAtom)).toBeUndefined()+ expect(store.get(state.deployDrawerReleaseIdAtom)).toBeUndefined()+ })++ it('should derive default environment and release selections from config', async () => {+ const state = await loadState()+ const store = createStore()+ store.set(state.deployReadyFormConfigAtom, {+ ...deployConfig(),+ lockedEnvId: 'environment-2',+ presetReleaseId: 'release-1',+ releaseEmptyLabel: 'No releases',+ })++ expect(store.get(state.deploySelectedEnvironmentIdAtom)).toBe('environment-2')+ expect(store.get(state.deployLockedEnvironmentIdAtom)).toBe('environment-2')+ expect(store.get(state.deployLockedEnvironmentAtom)?.displayName).toBe('Staging')+ expect(store.get(state.deploySelectedReleaseIdAtom)).toBe('release-1')+ expect(store.get(state.deployDisplayedReleaseAtom)?.id).toBe('release-1')+ expect(store.get(state.deployIsExistingReleaseAtom)).toBe(true)+ expect(store.get(state.deployReleaseRowsAtom)).toHaveLength(2)+ expect(store.get(state.deployEnvironmentRowsAtom)).toHaveLength(2)+ expect(store.get(state.deployReleaseEmptyLabelAtom)).toBe('No releases')+ expect(store.get(state.deployHasSelectedEnvironmentAtom)).toBe(true)+ })++ it('should reset bindings, env vars, and validation state when target changes', async () => {+ const state = await loadState()+ const store = createStore()+ const slot = credentialSlot()+ store.set(state.deployReadyFormConfigAtom, deployConfig())+ setQueryOptions({+ credentialSlots: [slot],+ envVarSlots: [envVarSlot()],+ })++ store.set(state.selectDeployBindingAtom, 'langgenius/openai:PLUGIN_CATEGORY_MODEL', 'credential-1')+ store.set(state.setDeployEnvVarAtom, 'API_KEY', {+ value: 'secret',+ valueSource: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ })+ store.set(state.showDeployValidationErrorsAtom)++ expect(store.get(state.deploySelectedBindingsAtom)).toEqual({+ 'langgenius/openai:PLUGIN_CATEGORY_MODEL': 'credential-1',+ })+ expect(store.get(state.deployEnvVarValuesAtom)).toEqual({+ API_KEY: {+ value: 'secret',+ valueSource: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ },+ })+ expect(store.get(state.deployShowValidationErrorsAtom)).toBe(true)++ store.set(state.selectDeployEnvironmentAtom, 'environment-2')++ expect(store.get(state.deploySelectedEnvironmentIdAtom)).toBe('environment-2')+ expect(store.get(state.deploySelectedBindingsAtom)).toEqual({})+ expect(store.get(state.deployEnvVarValuesAtom)).toEqual({})+ expect(store.get(state.deployShowValidationErrorsAtom)).toBe(false)++ store.set(state.selectDeployReleaseAtom, 'release-1')+ expect(store.get(state.deploySelectedReleaseIdAtom)).toBe('release-1')+ })++ it('should derive binding and env var readiness from deployment options', async () => {+ const state = await loadState()+ const store = createStore()+ const slot = credentialSlot({+ lastCredentialId: 'credential-2',+ })+ store.set(state.deployReadyFormConfigAtom, deployConfig())+ setQueryOptions({+ credentialSlots: [slot],+ envVarSlots: [+ envVarSlot({+ key: 'PORT',+ valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,+ defaultValue: '8080',+ }),+ ],+ })++ expect(store.get(state.deployBindingSlotsAtom)).toEqual([slot])+ expect(store.get(state.deployEnvVarSlotsAtom)).toMatchObject([+ {+ key: 'PORT',+ valueType: 'number',+ hasDefaultValue: true,+ hasLastValue: false,+ },+ ])+ expect(store.get(state.deploySelectedBindingsAtom)).toEqual({+ 'langgenius/openai:PLUGIN_CATEGORY_MODEL': 'credential-2',+ })+ expect(store.get(state.canAttemptDeployAtom)).toBe(true)+ expect(store.get(state.canSubmitDeployAtom)).toBe(true)+ })++ it('should block submit until required literal env vars are valid', async () => {+ const state = await loadState()+ const store = createStore()+ store.set(state.deployReadyFormConfigAtom, deployConfig())+ setQueryOptions({+ credentialSlots: [+ credentialSlot({+ candidates: [credentialCandidate({ credentialId: 'credential-1' })],+ }),+ ],+ envVarSlots: [+ envVarSlot({+ key: 'PORT',+ valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,+ }),+ ],+ })++ expect(store.get(state.canAttemptDeployAtom)).toBe(true)+ expect(store.get(state.canSubmitDeployAtom)).toBe(false)++ store.set(state.setDeployEnvVarAtom, 'PORT', {+ value: 'abc',+ valueSource: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ })+ expect(store.get(state.canSubmitDeployAtom)).toBe(false)++ store.set(state.setDeployEnvVarAtom, 'PORT', {+ value: '3000',+ valueSource: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ })+ expect(store.get(state.canSubmitDeployAtom)).toBe(true)+ })++ it('should submit a promote deployment with selected credentials and env vars', async () => {+ const state = await loadState()+ const store = createStore()+ mockPromoteMutate.mockImplementation((_variables: unknown, options?: { onSuccess?: () => void }) => {+ options?.onSuccess?.()+ })+ store.set(state.deployReadyFormConfigAtom, deployConfig())+ setQueryOptions({+ credentialSlots: [+ credentialSlot({+ candidates: [credentialCandidate({ credentialId: 'credential-1' })],+ }),+ ],+ envVarSlots: [+ envVarSlot({+ key: 'API_KEY',+ valueType: EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET,+ }),+ ],+ })+ store.set(state.setDeployEnvVarAtom, 'API_KEY', {+ value: 'secret',+ valueSource: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ })++ store.set(state.deployReleaseSubmissionAtom, {+ deployFailedMessage: 'Deploy failed',+ })++ expect(mockPromoteMutate).toHaveBeenCalledWith(+ {+ params: {+ appInstanceId: 'app-instance-1',+ environmentId: 'environment-1',+ },+ body: {+ appInstanceId: 'app-instance-1',+ environmentId: 'environment-1',+ releaseId: 'release-2',+ credentials: [+ {+ providerId: 'langgenius/openai',+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ credentialId: 'credential-1',+ },+ ],+ envVars: [+ {+ key: 'API_KEY',+ value: 'secret',+ valueSource: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL,+ },+ ],+ idempotencyKey: expect.any(String),+ },+ },+ expect.objectContaining({+ onSuccess: expect.any(Function),+ onError: expect.any(Function),+ }),+ )+ expect(store.get(state.deployDrawerOpenAtom)).toBe(false)+ })+})diff --git a/web/features/deployments/deploy-drawer/state/index.ts b/web/features/deployments/deploy-drawer/state/index.tsnew file mode 100644index 00000000000..9d576a23ed9--- /dev/null+++ b/web/features/deployments/deploy-drawer/state/index.ts@@ -0,0 +1,442 @@+'use client'++import type {+ Environment,+ EnvironmentDeployment,+ EnvVarInput,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import type { Getter } from 'jotai'+import type {+ EnvVarBindingSlot,+ EnvVarValues,+ EnvVarValueSelection,+} from '../../components/env-var-bindings'+import type { RuntimeCredentialBindingSelections } from '../../components/runtime-credential-bindings-utils'+import { EnvVarValueSource as ApiEnvVarValueSource } from '@dify/contracts/enterprise/types.gen'+import { toast } from '@langgenius/dify-ui/toast'+import { atom } from 'jotai'+import { atomWithMutation, atomWithQuery } from 'jotai-tanstack-query'+import { consoleQuery } from '@/service/client'+import { envVarBindingSlotFromContract } from '../../components/env-var-bindings-utils'+import {+ hasMissingRequiredRuntimeCredentialBinding,+ runtimeCredentialSlotKey,+ selectedDeploymentRuntimeCredentials,+ selectedRuntimeCredentialSelections,+} from '../../components/runtime-credential-bindings-utils'+import { createDeploymentIdempotencyKey } from '../../shared/domain/idempotency'+import { releaseDeploymentAction } from '../../shared/domain/release-action'++type OpenDeployDrawerParams = {+ appInstanceId: string+ environmentId?: string+ releaseId?: string+}++export const deployDrawerOpenAtom = atom(false)+export const deployDrawerAppInstanceIdAtom = atom<string | undefined>(undefined)+export const deployDrawerEnvironmentIdAtom = atom<string | undefined>(undefined)+export const deployDrawerReleaseIdAtom = atom<string | undefined>(undefined)++export const openDeployDrawerAtom = atom(null, (_get, set, params: OpenDeployDrawerParams) => {+ set(deployDrawerAppInstanceIdAtom, params.appInstanceId)+ set(deployDrawerEnvironmentIdAtom, params.environmentId)+ set(deployDrawerReleaseIdAtom, params.releaseId)+ set(deployDrawerOpenAtom, true)+})++export const closeDeployDrawerAtom = atom(null, (_get, set) => {+ set(deployDrawerOpenAtom, false)+ set(deployDrawerAppInstanceIdAtom, undefined)+ set(deployDrawerEnvironmentIdAtom, undefined)+ set(deployDrawerReleaseIdAtom, undefined)+})++export type DeployReadyFormConfig = {+ appInstanceId: string+ environments: Environment[]+ releases: Release[]+ runtimeRows: EnvironmentDeployment[]+ defaultReleaseId?: string+ lockedEnvId?: string+ presetReleaseId?: string+ releaseEmptyLabel?: string+}++export const deployReadyFormConfigAtom = atom<DeployReadyFormConfig | undefined>(undefined)++const selectedEnvIdAtom = atom<string | undefined>(undefined)+const selectedReleaseIdAtom = atom<string | undefined>(undefined)+const manualBindingsAtom = atom<RuntimeCredentialBindingSelections>({})+export const deployEnvVarValuesAtom = atom<EnvVarValues>({})+const showValidationErrorsAtom = atom(false)+export const deployReadyFormLocalAtoms = [+ selectedEnvIdAtom,+ selectedReleaseIdAtom,+ manualBindingsAtom,+ deployEnvVarValuesAtom,+ showValidationErrorsAtom,+] as const++function formConfig(get: Getter) {+ const config = get(deployReadyFormConfigAtom)+ if (!config)+ throw new Error('Missing deploy ready form config.')++ return config+}++const resetDeployBindingsAtom = atom(null, (_get, set) => {+ set(manualBindingsAtom, {})+ set(deployEnvVarValuesAtom, {})+ set(showValidationErrorsAtom, false)+})++export const selectDeployEnvironmentAtom = atom(null, (_get, set, environmentId: string) => {+ set(selectedEnvIdAtom, environmentId)+ set(resetDeployBindingsAtom)+})++export const selectDeployReleaseAtom = atom(null, (_get, set, releaseId: string) => {+ set(selectedReleaseIdAtom, releaseId)+ set(resetDeployBindingsAtom)+})++export const showDeployValidationErrorsAtom = atom(null, (_get, set) => {+ set(showValidationErrorsAtom, true)+})++export const deployShowValidationErrorsAtom = atom((get) => {+ return get(showValidationErrorsAtom)+})++const deployPresetReleaseAtom = atom((get) => {+ const config = formConfig(get)+ return config.presetReleaseId ? config.releases.find(r => r.id === config.presetReleaseId) : undefined+})++export const deployDisplayedReleaseAtom = atom((get): Release | undefined => {+ return get(deployPresetReleaseAtom)+})++export const deployIsExistingReleaseAtom = atom((get) => {+ const config = formConfig(get)+ return Boolean(config.presetReleaseId)+})++export const deployReleaseRowsAtom = atom((get) => {+ return formConfig(get).releases+})++export const deployReleaseEmptyLabelAtom = atom((get) => {+ return formConfig(get).releaseEmptyLabel+})++export const deployEnvironmentRowsAtom = atom((get) => {+ return formConfig(get).environments+})++export const deployLockedEnvironmentIdAtom = atom((get) => {+ return formConfig(get).lockedEnvId+})++export const deploySelectedEnvironmentIdAtom = atom((get) => {+ const config = formConfig(get)+ return get(selectedEnvIdAtom) ?? config.lockedEnvId ?? config.environments[0]?.id+})++const deploySelectedEnvironmentAtom = atom((get) => {+ const config = formConfig(get)+ const selectedEnvironmentId = get(deploySelectedEnvironmentIdAtom)+ return selectedEnvironmentId+ ? config.environments.find(env => env.id === selectedEnvironmentId)+ : undefined+})++export const deploySelectedReleaseIdAtom = atom((get) => {+ const config = formConfig(get)+ const displayedRelease = get(deployDisplayedReleaseAtom)+ return get(selectedReleaseIdAtom) ?? displayedRelease?.id ?? config.defaultReleaseId+})++const deploySelectedReleaseAtom = atom((get) => {+ const config = formConfig(get)+ const selectedReleaseId = get(deploySelectedReleaseIdAtom)+ return selectedReleaseId+ ? config.releases.find(release => release.id === selectedReleaseId)+ : undefined+})++const deployTargetReleaseAtom = atom((get) => {+ return get(deployDisplayedReleaseAtom) ?? get(deploySelectedReleaseAtom)+})++export const deployLockedEnvironmentAtom = atom((get) => {+ const config = formConfig(get)+ return config.lockedEnvId+ ? config.environments.find(environment => environment.id === config.lockedEnvId)+ : undefined+})++export const deployTargetReleaseIdAtom = atom((get) => {+ const targetRelease = get(deployTargetReleaseAtom)+ return targetRelease?.id ?? get(deploySelectedReleaseIdAtom)+})++export const deployHasSelectedEnvironmentAtom = atom((get) => {+ return Boolean(get(deploySelectedEnvironmentAtom))+})++const releaseDeploymentOptionsQueryAtom = atomWithQuery((get) => {+ const hasSelectedEnvironment = get(deployHasSelectedEnvironmentAtom)+ const releaseId = get(deployTargetReleaseIdAtom)+ const selectedEnvironmentId = get(deploySelectedEnvironmentIdAtom)+ const enabled = Boolean(releaseId && selectedEnvironmentId && hasSelectedEnvironment)++ return {+ ...consoleQuery.enterprise.releaseService.computeDeploymentOptions.queryOptions({+ input: {+ body: {+ releaseId: releaseId ?? '',+ environmentId: selectedEnvironmentId ?? '',+ },+ },+ enabled,+ }),+ retry: false,+ }+})++export const deployBindingSlotsAtom = atom((get) => {+ const deploymentOptionsQuery = get(releaseDeploymentOptionsQueryAtom)++ return deploymentOptionsQuery.data?.options.credentialSlots.filter(slot => runtimeCredentialSlotKey(slot)) ?? []+})++export const deployEnvVarSlotsAtom = atom((get): EnvVarBindingSlot[] => {+ const deploymentOptionsQuery = get(releaseDeploymentOptionsQueryAtom)++ return deploymentOptionsQuery.data?.options.envVarSlots.flatMap((slot): EnvVarBindingSlot[] => {+ const bindingSlot = envVarBindingSlotFromContract(slot)+ return bindingSlot ? [bindingSlot] : []+ }) ?? []+})++export const deployIsBindingOptionsLoadingAtom = atom((get) => {+ const deploymentOptionsQuery = get(releaseDeploymentOptionsQueryAtom)+ const releaseId = get(deployTargetReleaseIdAtom)++ return Boolean(+ releaseId+ && get(deployHasSelectedEnvironmentAtom)+ && (deploymentOptionsQuery.isLoading || deploymentOptionsQuery.isFetching),+ )+})++export const deployHasBindingOptionsErrorAtom = atom((get) => {+ return get(releaseDeploymentOptionsQueryAtom).isError+})++const deployIsBindingOptionsReadyAtom = atom((get) => {+ const deploymentOptionsQuery = get(releaseDeploymentOptionsQueryAtom)+ const releaseId = get(deployTargetReleaseIdAtom)++ return Boolean(+ releaseId+ && get(deployHasSelectedEnvironmentAtom)+ && deploymentOptionsQuery.data+ && !get(deployIsBindingOptionsLoadingAtom)+ && !get(deployHasBindingOptionsErrorAtom),+ )+})++function deployEnvVarValueSource(slot: EnvVarBindingSlot, selection: EnvVarValueSelection | undefined) {+ return selection?.valueSource+ ?? (slot.hasLastValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT+ : slot.hasDefaultValue+ ? ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT+ : ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LITERAL)+}++function deployEnvVarInput(slot: EnvVarBindingSlot, selection: EnvVarValueSelection | undefined): EnvVarInput[] {+ const valueSource = deployEnvVarValueSource(slot, selection)++ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT) {+ return slot.hasLastValue+ ? [{ key: slot.key, valueSource }]+ : []+ }++ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT) {+ return slot.hasDefaultValue+ ? [{ key: slot.key, valueSource }]+ : []+ }++ if (!selection?.value || (slot.valueType === 'number' && Number.isNaN(Number(selection.value))))+ return []++ return [{+ key: slot.key,+ value: selection.value,+ valueSource,+ }]+}++function deployEnvVarSelectionReady(slot: EnvVarBindingSlot, selection: EnvVarValueSelection | undefined) {+ const valueSource = deployEnvVarValueSource(slot, selection)++ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYMENT)+ return Boolean(slot.hasLastValue)+ if (valueSource === ApiEnvVarValueSource.ENV_VAR_VALUE_SOURCE_DSL_DEFAULT)+ return Boolean(slot.hasDefaultValue)+ if (!selection?.value)+ return false++ return slot.valueType !== 'number' || !Number.isNaN(Number(selection.value))+}++export const deploySelectedBindingsAtom = atom((get) => {+ return selectedRuntimeCredentialSelections(get(deployBindingSlotsAtom), get(manualBindingsAtom))+})++const deployDeploymentCredentialsAtom = atom((get) => {+ return selectedDeploymentRuntimeCredentials(get(deployBindingSlotsAtom), get(deploySelectedBindingsAtom))+})++const deployDeploymentEnvVarsAtom = atom((get) => {+ const envVarValues = get(deployEnvVarValuesAtom)++ return get(deployEnvVarSlotsAtom).flatMap(slot => deployEnvVarInput(slot, envVarValues[slot.key]))+})++const deployRequiredBindingsReadyAtom = atom((get) => {+ const selectedBindings = get(deploySelectedBindingsAtom)++ return get(deployBindingSlotsAtom).every(slot =>+ !hasMissingRequiredRuntimeCredentialBinding(slot, selectedBindings[runtimeCredentialSlotKey(slot)]),+ )+})++const deployRequiredEnvVarsReadyAtom = atom((get) => {+ const envVarValues = get(deployEnvVarValuesAtom)++ return get(deployEnvVarSlotsAtom).every(slot =>+ deployEnvVarSelectionReady(slot, envVarValues[slot.key]),+ )+})++export const selectDeployBindingAtom = atom(null, (get, set, slot: string, value: string) => {+ set(manualBindingsAtom, {+ ...get(manualBindingsAtom),+ [slot]: value,+ })+})++export const setDeployEnvVarAtom = atom(null, (get, set, key: string, value: EnvVarValueSelection) => {+ set(deployEnvVarValuesAtom, {+ ...get(deployEnvVarValuesAtom),+ [key]: value,+ })+})++const promoteReleaseMutationAtom = atomWithMutation(() =>+ consoleQuery.enterprise.deploymentService.promote.mutationOptions(),+)++const rollbackReleaseMutationAtom = atomWithMutation(() =>+ consoleQuery.enterprise.deploymentService.rollback.mutationOptions(),+)++export const isDeployReleaseSubmittingAtom = atom((get) => {+ return get(promoteReleaseMutationAtom).isPending || get(rollbackReleaseMutationAtom).isPending+})++export const canAttemptDeployAtom = atom((get) => {+ return Boolean(+ get(deploySelectedEnvironmentIdAtom)+ && get(deploySelectedEnvironmentAtom)+ && get(deployTargetReleaseIdAtom)+ && get(deployIsBindingOptionsReadyAtom)+ && !get(isDeployReleaseSubmittingAtom),+ )+})++export const canSubmitDeployAtom = atom((get) => {+ return Boolean(+ get(canAttemptDeployAtom)+ && get(deployRequiredBindingsReadyAtom)+ && get(deployRequiredEnvVarsReadyAtom),+ )+})++export const deployReleaseSubmissionAtom = atom(null, (get, set, {+ deployFailedMessage,+}: {+ deployFailedMessage: string+}) => {+ const config = formConfig(get)+ const selectedEnvironmentId = get(deploySelectedEnvironmentIdAtom)+ const targetRelease = get(deployTargetReleaseAtom)+ const targetReleaseId = get(deployTargetReleaseIdAtom)++ if (!targetReleaseId || !selectedEnvironmentId)+ return++ const idempotencyKey = createDeploymentIdempotencyKey()+ const currentRelease = config.runtimeRows.find(row => row.environment.id === selectedEnvironmentId)?.currentRelease+ const action = releaseDeploymentAction({+ targetRelease,+ currentRelease,+ releaseRows: config.releases,+ isExistingRelease: true,+ })+ const mutationOptions = {+ onSuccess: () => {+ set(closeDeployDrawerAtom)+ },+ onError: () => {+ toast.error(deployFailedMessage)+ },+ }++ if (action === 'rollback') {+ get(rollbackReleaseMutationAtom).mutate(+ {+ params: {+ appInstanceId: config.appInstanceId,+ environmentId: selectedEnvironmentId,+ },+ body: {+ appInstanceId: config.appInstanceId,+ environmentId: selectedEnvironmentId,+ targetReleaseId,+ idempotencyKey,+ },+ },+ mutationOptions,+ )+ return+ }++ const deploymentEnvVars = get(deployDeploymentEnvVarsAtom)+ get(promoteReleaseMutationAtom).mutate(+ {+ params: {+ appInstanceId: config.appInstanceId,+ environmentId: selectedEnvironmentId,+ },+ body: {+ appInstanceId: config.appInstanceId,+ environmentId: selectedEnvironmentId,+ releaseId: targetReleaseId,+ credentials: get(deployDeploymentCredentialsAtom),+ envVars: deploymentEnvVars.length > 0 ? deploymentEnvVars : undefined,+ idempotencyKey,+ },+ },+ mutationOptions,+ )+})diff --git a/web/features/deployments/deploy-drawer/state/release-options.ts b/web/features/deployments/deploy-drawer/state/release-options.tsnew file mode 100644index 00000000000..5174f6e6204--- /dev/null+++ b/web/features/deployments/deploy-drawer/state/release-options.ts@@ -0,0 +1,25 @@+import type { EnvironmentDeployment, Release } from '@dify/contracts/enterprise/types.gen'++export function currentReleaseIdForEnvironment(rows: EnvironmentDeployment[], targetEnvironmentId?: string) {+ if (!targetEnvironmentId)+ return undefined++ return rows.find(row => row.environment.id === targetEnvironmentId)?.currentRelease?.id+}++export function selectableDeployReleases({+ releases,+ lockedEnvId,+ currentReleaseId,+ presetReleaseId,+}: {+ releases: Release[]+ lockedEnvId?: string+ currentReleaseId?: string+ presetReleaseId?: string+}) {+ if (!lockedEnvId || presetReleaseId || !currentReleaseId)+ return releases++ return releases.filter(release => release.id !== currentReleaseId)+}diff --git a/web/features/deployments/deploy-drawer/ui/form-sections.tsx b/web/features/deployments/deploy-drawer/ui/form-sections.tsxnew file mode 100644index 00000000000..d7d70bd81da--- /dev/null+++ b/web/features/deployments/deploy-drawer/ui/form-sections.tsx@@ -0,0 +1,197 @@+'use client'++import type { CredentialSlot, Environment } from '@dify/contracts/enterprise/types.gen'+import type { RuntimeCredentialBindingSelections } from '../../components/runtime-credential-bindings-utils'+import { DrawerDescription, DrawerTitle } from '@langgenius/dify-ui/drawer'+import { useAtomValue, useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'+import { DeploymentStateMessage } from '../../components/empty-state'+import { RuntimeCredentialBindingsPanel } from '../../components/runtime-credential-bindings'+import { formatDate, releaseCommit } from '../../shared/domain/release'+import {+ deployDisplayedReleaseAtom,+ deployEnvironmentRowsAtom,+ deployIsExistingReleaseAtom,+ deployLockedEnvironmentAtom,+ deployLockedEnvironmentIdAtom,+ deployReleaseEmptyLabelAtom,+ deployReleaseRowsAtom,+ deploySelectedEnvironmentIdAtom,+ deploySelectedReleaseIdAtom,+ selectDeployEnvironmentAtom,+ selectDeployReleaseAtom,+} from '../state'+import {+ DeploymentSelect,+ EnvironmentRow,+ Field,+} from './select'++export const DEPLOY_DRAWER_BINDING_LIST_CLASS_NAME = 'max-h-none overflow-visible'++function environmentOptionLabel(env: Environment, t: ReturnType<typeof useTranslation<'deployments'>>['t']) {+ const description = env.description.trim()+ if (description)+ return `${env.displayName} · ${description}`++ return `${env.displayName} · ${t(`mode.${env.mode}`)} · ${t(`backend.${env.backend}`)}`+}++export function BindingOptionsPanel({+ slots,+ selections,+ isLoading,+ hasError,+ bindingCountLabel,+ showMissingRequired,+ onChange,+}: {+ slots: CredentialSlot[]+ selections: RuntimeCredentialBindingSelections+ isLoading: boolean+ hasError: boolean+ bindingCountLabel: string+ showMissingRequired: boolean+ onChange: (slot: string, value: string) => void+}) {+ const { t } = useTranslation('deployments')++ if (isLoading) {+ return (+ <div className="rounded-xl border border-divider-subtle bg-background-default-subtle px-3 py-4">+ <SkeletonContainer className="gap-2">+ <SkeletonRectangle className="h-3 w-32 animate-pulse" />+ <SkeletonRectangle className="h-3 w-2/3 animate-pulse" />+ <SkeletonRectangle className="my-0 h-8 w-full animate-pulse rounded-lg" />+ </SkeletonContainer>+ </div>+ )+ }++ if (hasError) {+ return (+ <div className="rounded-xl border border-divider-subtle bg-background-default-subtle px-3 py-4 system-sm-regular text-text-destructive">+ {t('deployDrawer.bindingOptionsFailed')}+ </div>+ )+ }++ return (+ <RuntimeCredentialBindingsPanel+ slots={slots}+ selections={selections}+ title={t('deployDrawer.runtimeCredentials')}+ hint={t('deployDrawer.bindingSelectionHint')}+ noBindingRequiredLabel={t('deployDrawer.noBindingRequired')}+ noCredentialCandidatesLabel={t('deployDrawer.noCredentialCandidates')}+ selectCredentialLabel={t('deployDrawer.selectCredential')}+ missingRequiredLabel={t('deployDrawer.missingRequiredBinding')}+ bindingCountLabel={bindingCountLabel}+ showMissingRequired={showMissingRequired}+ listClassName={DEPLOY_DRAWER_BINDING_LIST_CLASS_NAME}+ onChange={onChange}+ />+ )+}++export function DeployFormHeader() {+ const { t } = useTranslation('deployments')++ return (+ <div className="shrink-0 border-b border-divider-subtle px-6 py-5 pr-14">+ <DrawerTitle className="title-xl-semi-bold text-text-primary">+ {t('deployDrawer.title')}+ </DrawerTitle>+ <DrawerDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('deployDrawer.description')}+ </DrawerDescription>+ </div>+ )+}++export function ReleaseField() {+ const { t } = useTranslation('deployments')+ const displayedRelease = useAtomValue(deployDisplayedReleaseAtom)+ const emptyLabel = useAtomValue(deployReleaseEmptyLabelAtom)+ const isExistingRelease = useAtomValue(deployIsExistingReleaseAtom)+ const releases = useAtomValue(deployReleaseRowsAtom)+ const selectedReleaseId = useAtomValue(deploySelectedReleaseIdAtom)+ const selectRelease = useSetAtom(selectDeployReleaseAtom)++ return (+ <Field label={t('deployDrawer.releaseLabel')}>+ {isExistingRelease && displayedRelease+ ? (+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between rounded-lg border border-components-panel-border bg-components-panel-bg-blur px-3 py-2">+ <div className="flex min-w-0 items-center gap-2">+ <span className="shrink-0 font-mono system-sm-semibold text-text-primary">{displayedRelease.displayName}</span>+ <span className="shrink-0 system-xs-regular text-text-tertiary">·</span>+ <span className="shrink-0 font-mono system-xs-regular text-text-tertiary">{releaseCommit(displayedRelease)}</span>+ </div>+ <span className="shrink-0 system-xs-regular text-text-quaternary">{formatDate(displayedRelease.createdAt)}</span>+ </div>+ <span className="system-xs-regular text-text-tertiary">+ {t('deployDrawer.existingReleaseHint')}+ </span>+ </div>+ )+ : releases.length === 0+ ? (+ <DeploymentStateMessage variant="compact">+ {emptyLabel ?? t('deployDrawer.noReleaseAvailable')}+ </DeploymentStateMessage>+ )+ : (+ <DeploymentSelect+ value={selectedReleaseId}+ onChange={selectRelease}+ options={releases.map(release => ({+ value: release.id,+ label: `${release.displayName} · ${releaseCommit(release)}`,+ }))}+ ariaLabel={t('deployDrawer.releaseLabel')}+ placeholder={t('deployDrawer.selectRelease')}+ />+ )}+ </Field>+ )+}++export function EnvironmentField() {+ const { t } = useTranslation('deployments')+ const environments = useAtomValue(deployEnvironmentRowsAtom)+ const lockedEnv = useAtomValue(deployLockedEnvironmentAtom)+ const lockedEnvId = useAtomValue(deployLockedEnvironmentIdAtom)+ const selectedEnvironmentId = useAtomValue(deploySelectedEnvironmentIdAtom)+ const selectEnvironment = useSetAtom(selectDeployEnvironmentAtom)++ return (+ <Field+ label={t('deployDrawer.targetEnv')}+ hint={lockedEnvId ? t('deployDrawer.lockedHint') : undefined}+ >+ {lockedEnv+ ? <EnvironmentRow env={lockedEnv} />+ : environments.length === 0+ ? (+ <DeploymentStateMessage variant="compact">+ {t('deployDrawer.noNewEnvironmentAvailable')}+ </DeploymentStateMessage>+ )+ : (+ <DeploymentSelect+ value={selectedEnvironmentId}+ onChange={selectEnvironment}+ options={environments.map(env => ({+ value: env.id,+ label: environmentOptionLabel(env, t),+ }))}+ ariaLabel={t('deployDrawer.targetEnv')}+ placeholder={t('deployDrawer.selectEnv')}+ />+ )}+ </Field>+ )+}diff --git a/web/features/deployments/deploy-drawer/ui/form-skeleton.tsx b/web/features/deployments/deploy-drawer/ui/form-skeleton.tsxnew file mode 100644index 00000000000..05251b3b1f4--- /dev/null+++ b/web/features/deployments/deploy-drawer/ui/form-skeleton.tsx@@ -0,0 +1,42 @@+'use client'++import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'++const DEPLOY_FORM_FIELD_SKELETON_KEYS = ['environment', 'release']++export function DeployFormSkeleton() {+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="shrink-0 border-b border-divider-subtle px-6 py-5 pr-14">+ <SkeletonContainer className="gap-2">+ <SkeletonRectangle className="h-5 w-44 animate-pulse" />+ <SkeletonRectangle className="h-3 w-72 animate-pulse" />+ </SkeletonContainer>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ <div className="flex flex-col gap-5">+ {DEPLOY_FORM_FIELD_SKELETON_KEYS.map(key => (+ <SkeletonContainer key={key} className="gap-2">+ <SkeletonRectangle className="h-3 w-24 animate-pulse" />+ <SkeletonRectangle className="my-0 h-9 w-full animate-pulse rounded-lg" />+ </SkeletonContainer>+ ))}++ <div className="rounded-xl border border-divider-subtle bg-background-default-subtle px-3 py-4">+ <SkeletonContainer className="gap-2">+ <SkeletonRectangle className="h-3 w-32 animate-pulse" />+ <SkeletonRectangle className="h-3 w-2/3 animate-pulse" />+ <SkeletonRectangle className="my-0 h-8 w-full animate-pulse rounded-lg" />+ </SkeletonContainer>+ </div>+ </div>+ </div>++ <SkeletonRow className="shrink-0 justify-end border-t border-divider-subtle bg-background-default-subtle px-6 py-4">+ <SkeletonRectangle className="my-0 h-8 w-18 animate-pulse rounded-lg" />+ <SkeletonRectangle className="my-0 h-8 w-22 animate-pulse rounded-lg" />+ </SkeletonRow>+ </div>+ )+}diff --git a/web/features/deployments/deploy-drawer/ui/form.tsx b/web/features/deployments/deploy-drawer/ui/form.tsxnew file mode 100644index 00000000000..354116eb015--- /dev/null+++ b/web/features/deployments/deploy-drawer/ui/form.tsx@@ -0,0 +1,269 @@+'use client'++import type {+ Environment,+ EnvironmentDeployment,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import { useQuery } from '@tanstack/react-query'+import { useAtomValue, useSetAtom } from 'jotai'+import { ScopeProvider } from 'jotai-scope'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { EnvVarBindingsPanel } from '../../components/env-var-bindings'+import { isAvailableDeploymentTarget } from '../../shared/domain/runtime-status'+import { canAttemptDeployAtom, canSubmitDeployAtom, closeDeployDrawerAtom, deployBindingSlotsAtom, deployEnvVarSlotsAtom, deployEnvVarValuesAtom, deployHasBindingOptionsErrorAtom, deployHasSelectedEnvironmentAtom, deployIsBindingOptionsLoadingAtom, deployReadyFormConfigAtom, deployReadyFormLocalAtoms, deployReleaseSubmissionAtom, deploySelectedBindingsAtom, deployShowValidationErrorsAtom, deployTargetReleaseIdAtom, isDeployReleaseSubmittingAtom, selectDeployBindingAtom, setDeployEnvVarAtom, showDeployValidationErrorsAtom } from '../state'+import {+ currentReleaseIdForEnvironment,+ selectableDeployReleases,+} from '../state/release-options'+import {+ BindingOptionsPanel,+ DEPLOY_DRAWER_BINDING_LIST_CLASS_NAME,+ DeployFormHeader,+ EnvironmentField,+ ReleaseField,+} from './form-sections'+import { DeployFormSkeleton } from './form-skeleton'++type DeployFormProps = {+ appInstanceId: string+ lockedEnvId?: string+ presetReleaseId?: string+}++type DeployReadyFormProps = DeployFormProps & {+ environments: Environment[]+ releases: Release[]+ runtimeRows: EnvironmentDeployment[]+ defaultReleaseId?: string+ releaseEmptyLabel?: string+}++function DeployRuntimeCredentialBindingsSection() {+ const { t } = useTranslation('deployments')+ const bindingSlots = useAtomValue(deployBindingSlotsAtom)+ const selectedBindings = useAtomValue(deploySelectedBindingsAtom)+ const isBindingOptionsLoading = useAtomValue(deployIsBindingOptionsLoadingAtom)+ const hasBindingOptionsError = useAtomValue(deployHasBindingOptionsErrorAtom)+ const showValidationErrors = useAtomValue(deployShowValidationErrorsAtom)+ const selectBinding = useSetAtom(selectDeployBindingAtom)++ return (+ <BindingOptionsPanel+ slots={bindingSlots}+ selections={selectedBindings}+ isLoading={isBindingOptionsLoading}+ hasError={hasBindingOptionsError}+ bindingCountLabel={t('deployDrawer.bindingCount', { count: bindingSlots.length })}+ showMissingRequired={showValidationErrors}+ onChange={selectBinding}+ />+ )+}++function DeployEnvVarBindingsSection() {+ const { t } = useTranslation('deployments')+ const envVarSlots = useAtomValue(deployEnvVarSlotsAtom)+ const envVarValues = useAtomValue(deployEnvVarValuesAtom)+ const isBindingOptionsLoading = useAtomValue(deployIsBindingOptionsLoadingAtom)+ const hasBindingOptionsError = useAtomValue(deployHasBindingOptionsErrorAtom)+ const showValidationErrors = useAtomValue(deployShowValidationErrorsAtom)+ const setDeployEnvVar = useSetAtom(setDeployEnvVarAtom)++ if (isBindingOptionsLoading || hasBindingOptionsError)+ return null++ return (+ <EnvVarBindingsPanel+ slots={envVarSlots}+ values={envVarValues}+ title={t('deployDrawer.envVars')}+ hint={t('deployDrawer.envVarHint')}+ envVarPlaceholder={t('deployDrawer.envVarPlaceholder')}+ literalSourceLabel={t('deployDrawer.envVarSource.literal')}+ defaultSourceLabel={t('deployDrawer.envVarSource.default')}+ lastDeploymentSourceLabel={t('deployDrawer.envVarSource.lastDeployment')}+ valueTypeLabels={{+ string: t('deployDrawer.envVarType.string'),+ number: t('deployDrawer.envVarType.number'),+ secret: t('deployDrawer.envVarType.secret'),+ }}+ sourceAriaLabel={key => t('deployDrawer.envVarSource.ariaLabel', { key })}+ defaultSourcePriority="lastDeployment"+ envVarCountLabel={t('deployDrawer.envVarCount', { count: envVarSlots.length })}+ missingRequiredLabel={t('deployDrawer.missingRequiredEnvVar')}+ listClassName={DEPLOY_DRAWER_BINDING_LIST_CLASS_NAME}+ showMissingRequired={showValidationErrors}+ onChange={setDeployEnvVar}+ />+ )+}++function DeployBindingsSection() {+ const targetReleaseId = useAtomValue(deployTargetReleaseIdAtom)+ const hasSelectedEnvironment = useAtomValue(deployHasSelectedEnvironmentAtom)++ if (!targetReleaseId || !hasSelectedEnvironment)+ return null++ return (+ <>+ <DeployRuntimeCredentialBindingsSection />+ <DeployEnvVarBindingsSection />+ </>+ )+}++function DeployFormBody() {+ return (+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ <div className="flex flex-col gap-5">+ <ReleaseField />+ <EnvironmentField />+ <DeployBindingsSection />+ </div>+ </div>+ )+}++function DeployFooter() {+ const { t } = useTranslation('deployments')+ const closeDeployDrawer = useSetAtom(closeDeployDrawerAtom)+ const showValidationErrors = useSetAtom(showDeployValidationErrorsAtom)+ const submitDeployRelease = useSetAtom(deployReleaseSubmissionAtom)+ const canAttemptDeploy = useAtomValue(canAttemptDeployAtom)+ const canDeploy = useAtomValue(canSubmitDeployAtom)+ const isSubmitting = useAtomValue(isDeployReleaseSubmittingAtom)+ const submitLabel = isSubmitting ? t('deployDrawer.deploying') : t('deployDrawer.deploy')++ function handleDeploy() {+ showValidationErrors()++ if (!canDeploy)+ return++ submitDeployRelease({+ deployFailedMessage: t('deployDrawer.deployFailed'),+ })+ }++ return (+ <div className="flex shrink-0 justify-end gap-2 border-t border-divider-subtle bg-background-default-subtle px-6 py-4">+ <Button type="button" variant="secondary" onClick={closeDeployDrawer}>+ {t('deployDrawer.cancel')}+ </Button>+ <Button variant="primary" disabled={!canAttemptDeploy} onClick={handleDeploy}>+ {submitLabel}+ </Button>+ </div>+ )+}++function deployReadyFormStoreKey({+ appInstanceId,+ environments,+ releases,+ runtimeRows,+ defaultReleaseId,+ lockedEnvId,+ presetReleaseId,+}: DeployReadyFormProps) {+ return [+ appInstanceId,+ lockedEnvId ?? 'any',+ presetReleaseId ?? 'new',+ defaultReleaseId ?? 'none',+ environments.map(env => env.id).join(','),+ releases.map(release => release.id).join(','),+ runtimeRows.map(row => `${row.environment.id}:${row.currentRelease?.id ?? 'none'}`).join(','),+ ].join('|')+}++function DeployReadyForm(config: DeployReadyFormProps) {+ return (+ <ScopeProvider+ atoms={[+ [deployReadyFormConfigAtom, config],+ ...deployReadyFormLocalAtoms,+ ]}+ name="DeployReadyForm"+ >+ <div className="flex min-h-0 flex-1 flex-col">+ <DeployFormHeader />+ <DeployFormBody />+ <DeployFooter />+ </div>+ </ScopeProvider>+ )+}++export function DeployForm({+ appInstanceId,+ lockedEnvId,+ presetReleaseId,+}: DeployFormProps) {+ const { t } = useTranslation('deployments')+ const releaseDeploymentViewQuery = useQuery(consoleQuery.enterprise.releaseService.computeReleaseDeploymentView.queryOptions({+ input: {+ params: { appInstanceId },+ },+ }))++ if (releaseDeploymentViewQuery.isLoading) {+ return <DeployFormSkeleton />+ }++ if (releaseDeploymentViewQuery.isError) {+ return (+ <div className="p-4 system-sm-regular text-text-destructive">+ {t('common.loadFailed')}+ </div>+ )+ }++ const deploymentView = releaseDeploymentViewQuery.data+ if (!deploymentView) {+ return (+ <div className="p-4 system-sm-regular text-text-destructive">+ {t('common.loadFailed')}+ </div>+ )+ }++ const runtimeRows = deploymentView.environmentDeployments+ const environments = runtimeRows+ .filter(row => lockedEnvId || isAvailableDeploymentTarget(row))+ .map(row => row.environment)+ const releaseRows = deploymentView.releases+ const currentReleaseId = currentReleaseIdForEnvironment(runtimeRows, lockedEnvId)+ const releases = selectableDeployReleases({+ releases: releaseRows,+ lockedEnvId,+ currentReleaseId,+ presetReleaseId,+ })+ const defaultReleaseId = releases[0]?.id+ const releaseEmptyLabel = lockedEnvId && !presetReleaseId && currentReleaseId+ ? t('deployDrawer.noOtherReleaseAvailable')+ : undefined+ const readyFormConfig = {+ appInstanceId,+ environments,+ releases,+ runtimeRows,+ defaultReleaseId,+ releaseEmptyLabel,+ lockedEnvId,+ presetReleaseId,+ }+ const formKey = deployReadyFormStoreKey(readyFormConfig)++ return (+ <DeployReadyForm+ key={formKey}+ {...readyFormConfig}+ />+ )+}diff --git a/web/features/deployments/deploy-drawer/ui/select.tsx b/web/features/deployments/deploy-drawer/ui/select.tsxnew file mode 100644index 00000000000..ec38d0e07f8--- /dev/null+++ b/web/features/deployments/deploy-drawer/ui/select.tsx@@ -0,0 +1,135 @@+'use client'++import type { Environment, EnvironmentStatus } from '@dify/contracts/enterprise/types.gen'+import { EnvironmentStatus as EnvironmentStatusEnum } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useTranslation } from 'react-i18next'+import { TitleTooltip } from '../../components/title-tooltip'+import { ModeBadge } from './status-badge'++export function Field({ label, hint, children }: {+ label: string+ hint?: string+ children: React.ReactNode+}) {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <div className="system-xs-medium-uppercase text-text-tertiary">{label}</div>+ {hint && <span className="system-xs-regular text-text-quaternary">{hint}</span>}+ </div>+ {children}+ </div>+ )+}++type SelectOption = {+ value?: string+ label: string+ disabled?: boolean+ disabledReason?: string+}++type SelectProps = {+ value?: string+ onChange: (value: string) => void+ options: SelectOption[]+ ariaLabel?: string+ placeholder?: string+}++export function DeploymentSelect({ value, onChange, options, ariaLabel, placeholder }: SelectProps) {+ const { t } = useTranslation('deployments')+ const selectedOption = options.find(option => option.value === value)++ return (+ <Select+ value={value ?? null}+ onValueChange={(next) => {+ if (!next)+ return+ onChange(next)+ }}+ disabled={options.length === 0}+ >+ <SelectTrigger+ aria-label={ariaLabel ?? placeholder ?? t('deployDrawer.defaultSelect')}+ className={cn(+ 'h-8 min-w-0 px-2 text-left system-sm-medium',+ !selectedOption && 'text-text-quaternary',+ )}+ >+ {selectedOption?.label ?? placeholder ?? t('deployDrawer.defaultSelect')}+ </SelectTrigger>+ <SelectContent popupClassName="w-(--anchor-width)">+ {options.map(opt => opt.value+ ? (+ <SelectItem+ key={opt.value}+ value={opt.value}+ disabled={opt.disabled}+ >+ <TitleTooltip content={opt.disabled ? opt.disabledReason : undefined}>+ <SelectItemText>{opt.label}</SelectItemText>+ </TitleTooltip>+ <SelectItemIndicator />+ </SelectItem>+ )+ : null)}+ </SelectContent>+ </Select>+ )+}++function EnvironmentHealthDot({ status }: {+ status: EnvironmentStatus+}) {+ const { t } = useTranslation('deployments')+ const label = t(`health.${status}`)+ const isReady = status === EnvironmentStatusEnum.ENVIRONMENT_STATUS_READY++ return (+ <Tooltip>+ <TooltipTrigger+ render={(+ <span+ aria-label={label}+ className={cn(+ 'flex size-4 shrink-0 items-center justify-center rounded-full',+ isReady ? 'bg-util-colors-green-green-50' : 'bg-util-colors-warning-warning-50',+ )}+ >+ <span+ aria-hidden+ className={cn(+ 'size-1.5 rounded-full',+ isReady ? 'bg-util-colors-green-green-500' : 'bg-util-colors-warning-warning-500',+ )}+ />+ </span>+ )}+ />+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ )+}++export function EnvironmentRow({ env }: { env: Environment }) {+ const { t } = useTranslation('deployments')+ const summary = env.description.trim() || t(`backend.${env.backend}`)++ return (+ <div className="flex items-center justify-between gap-3 rounded-lg border border-components-panel-border bg-components-panel-bg-blur px-3 py-2">+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2">+ <EnvironmentHealthDot status={env.status} />+ <span className="truncate system-sm-semibold text-text-primary">{env.displayName}</span>+ <ModeBadge mode={env.mode} />+ </div>+ <span className="line-clamp-1 system-xs-regular text-text-tertiary">{summary}</span>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/deploy-drawer/ui/status-badge.tsx b/web/features/deployments/deploy-drawer/ui/status-badge.tsxnew file mode 100644index 00000000000..a171ff3cdc6--- /dev/null+++ b/web/features/deployments/deploy-drawer/ui/status-badge.tsx@@ -0,0 +1,22 @@+'use client'+import type { EnvironmentMode } from '@dify/contracts/enterprise/types.gen'+import { EnvironmentMode as EnvironmentModeEnum } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'++const baseBadge = 'inline-flex items-center gap-1 rounded-md border px-2 py-0.5 system-xs-medium whitespace-nowrap'++export function ModeBadge({ mode, className }: {+ mode: EnvironmentMode+ className?: string+}) {+ const { t } = useTranslation('deployments')+ const style = mode === EnvironmentModeEnum.ENVIRONMENT_MODE_SHARED+ ? 'border-util-colors-green-green-200 bg-util-colors-green-green-50 text-util-colors-green-green-700'+ : 'border-util-colors-blue-blue-200 bg-util-colors-blue-blue-50 text-util-colors-blue-blue-700'+ return (+ <span className={cn(baseBadge, style, className)}>+ {t(`mode.${mode}`)}+ </span>+ )+}diff --git a/web/features/deployments/detail/access-tab.tsx b/web/features/deployments/detail/access-tab.tsxnew file mode 100644index 00000000000..fde0499d538--- /dev/null+++ b/web/features/deployments/detail/access-tab.tsx@@ -0,0 +1,35 @@+'use client'++import { useQuery } from '@tanstack/react-query'+import { consoleQuery } from '@/service/client'+import { AccessChannelsSection } from './settings-tab/access/channels-section'+import { AccessPermissionsSection } from './settings-tab/access/permissions-section'++export function AccessTab({ appInstanceId }: {+ appInstanceId: string+}) {+ const accessSettingsQuery = useQuery(consoleQuery.enterprise.accessService.getAccessSettings.queryOptions({+ input: {+ params: { appInstanceId },+ },+ }))++ return (+ <div className="flex w-full max-w-[960px] min-w-0 flex-col gap-y-4 px-6 py-6 sm:px-20 sm:py-8">+ <AccessChannelsSection+ appInstanceId={appInstanceId}+ accessChannels={accessSettingsQuery.data?.accessChannels}+ webAppEndpoints={accessSettingsQuery.data?.webAppEndpoints}+ cliEndpoint={accessSettingsQuery.data?.cliEndpoint}+ isLoading={accessSettingsQuery.isLoading}+ isError={accessSettingsQuery.isError}+ />+ <AccessPermissionsSection+ appInstanceId={appInstanceId}+ environmentPolicies={accessSettingsQuery.data?.environmentPolicies}+ isLoading={accessSettingsQuery.isLoading}+ isError={accessSettingsQuery.isError}+ />+ </div>+ )+}diff --git a/web/features/deployments/detail/common.tsx b/web/features/deployments/detail/common.tsxnew file mode 100644index 00000000000..a02feb9b2cb--- /dev/null+++ b/web/features/deployments/detail/common.tsx@@ -0,0 +1,96 @@+'use client'++import type { ReactNode } from 'react'+import { cn } from '@langgenius/dify-ui/cn'++type SectionProps = {+ title: string+ description?: string+ action?: ReactNode+ children: ReactNode+ layout?: 'block' | 'row'+ tone?: 'default' | 'destructive'+ showDivider?: boolean+}++export function Section({+ title,+ description,+ action,+ children,+ layout = 'block',+ tone = 'default',+ showDivider = true,+}: SectionProps) {+ const hasAction = Boolean(action)+ const titleClassName = cn(+ 'system-sm-semibold',+ tone === 'destructive'+ ? 'text-util-colors-red-red-700'+ : layout === 'row'+ ? 'text-text-secondary'+ : 'text-text-primary',+ )+ const descriptionClassName = cn(+ 'mt-1 body-xs-regular',+ tone === 'destructive' ? 'text-util-colors-red-red-600' : 'text-text-tertiary',+ )++ if (layout === 'row') {+ return (+ <section className={cn('py-4 first:pt-0 last:pb-0', showDivider && 'border-b border-divider-subtle last:border-b-0')}>+ <div className="flex flex-col gap-3 sm:flex-row sm:gap-x-6">+ <div className="flex min-w-0 shrink-0 flex-col sm:w-40 sm:pt-1">+ <div className={titleClassName}>+ {title}+ </div>+ {description && (+ <p className={descriptionClassName}>+ {description}+ </p>+ )}+ </div>+ <div className="min-w-0 grow">+ {hasAction+ ? (+ <div className="flex min-w-0 items-start gap-3">+ <div className="min-w-0 grow">+ {children}+ </div>+ <div className="shrink-0">+ {action}+ </div>+ </div>+ )+ : children}+ </div>+ </div>+ </section>+ )+ }++ return (+ <section className={cn('py-6 first:pt-0 last:pb-0', showDivider && 'border-b border-divider-subtle last:border-b-0')}>+ <div className="mb-3 flex min-w-0 flex-col">+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">+ <div className={titleClassName}>+ {title}+ </div>+ {hasAction && (+ <div className="shrink-0">+ {action}+ </div>+ )}+ </div>+ {description && (+ <p className={cn(descriptionClassName, 'max-w-150')}>+ {description}+ </p>+ )}+ </div>+ <div className="min-w-0">+ {children}+ </div>+ </section>+ )+}diff --git a/web/features/deployments/detail/deploy-tab.tsx b/web/features/deployments/detail/deploy-tab.tsxnew file mode 100644index 00000000000..17414e9712a--- /dev/null+++ b/web/features/deployments/detail/deploy-tab.tsx@@ -0,0 +1,125 @@+'use client'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import { consoleQuery } from '@/service/client'+import { DeploymentEmptyState, DeploymentStateMessage } from '../components/empty-state'+import { deploymentStatusPollingInterval, hasRuntimeInstanceDeployment } from '../shared/domain/runtime-status'+import { DeploymentEnvironmentList } from './deploy-tab/deployment-environment-list'+import { NewDeploymentButton } from './deploy-tab/new-deployment-button'+import {+ DetailTable,+ DetailTableBody,+ DetailTableCard,+ DetailTableCardList,+ DetailTableCell,+ DetailTableHead,+ DetailTableHeader,+ DetailTableRow,+} from './table'+import {+ DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES,+} from './table-styles'++const DEPLOYMENT_TABLE_ROW_SKELETON_KEYS = ['production', 'staging']++function DeploymentEnvironmentListSkeleton() {+ const { t } = useTranslation('deployments')++ return (+ <>+ <DetailTableCardList className="pc:hidden">+ {DEPLOYMENT_TABLE_ROW_SKELETON_KEYS.map(key => (+ <DetailTableCard key={key}>+ <div className="flex flex-col gap-3 p-4">+ <div className="flex min-w-0 flex-col gap-1.5">+ <SkeletonRectangle className="h-3 w-32 animate-pulse" />+ <SkeletonRectangle className="my-0 h-4 w-18 animate-pulse rounded-md" />+ </div>+ <div className="flex min-w-0 flex-col gap-1.5">+ <SkeletonRectangle className="h-2.5 w-24 animate-pulse" />+ <SkeletonRow className="gap-2">+ <SkeletonRectangle className="h-3 w-16 animate-pulse" />+ <SkeletonRectangle className="h-2.5 w-18 animate-pulse" />+ </SkeletonRow>+ </div>+ <SkeletonRectangle className="my-0 size-8 animate-pulse rounded-md" />+ </div>+ </DetailTableCard>+ ))}+ </DetailTableCardList>+ <div className="hidden pc:block">+ <DetailTable>+ <DetailTableHeader>+ <DetailTableRow>+ <DetailTableHead className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.environment}>{t('deployTab.col.environment')}</DetailTableHead>+ <DetailTableHead className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.status}>{t('deployTab.col.status')}</DetailTableHead>+ <DetailTableHead className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.currentRelease}>{t('deployTab.col.currentRelease')}</DetailTableHead>+ <DetailTableHead className={`${DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.actions} text-right`}>{t('deployTab.col.actions')}</DetailTableHead>+ </DetailTableRow>+ </DetailTableHeader>+ <DetailTableBody>+ {DEPLOYMENT_TABLE_ROW_SKELETON_KEYS.map(key => (+ <DetailTableRow key={key}>+ <DetailTableCell>+ <SkeletonRectangle className="h-3 w-32 animate-pulse" />+ </DetailTableCell>+ <DetailTableCell>+ <SkeletonRectangle className="my-0 h-4 w-18 animate-pulse rounded-md" />+ </DetailTableCell>+ <DetailTableCell>+ <SkeletonRow className="gap-2">+ <SkeletonRectangle className="h-3 w-16 animate-pulse" />+ <SkeletonRectangle className="h-2.5 w-18 animate-pulse" />+ </SkeletonRow>+ </DetailTableCell>+ <DetailTableCell className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.actions}>+ <div className="flex justify-end">+ <SkeletonRectangle className="my-0 size-8 animate-pulse rounded-md" />+ </div>+ </DetailTableCell>+ </DetailTableRow>+ ))}+ </DetailTableBody>+ </DetailTable>+ </div>+ </>+ )+}++export function DeployTab({ appInstanceId }: {+ appInstanceId: string+}) {+ const { t } = useTranslation('deployments')+ const environmentDeploymentsQuery = useQuery(consoleQuery.enterprise.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: { appInstanceId },+ },+ refetchInterval: query => deploymentStatusPollingInterval(query.state.data?.environmentDeployments),+ }))+ const environmentDeployments = environmentDeploymentsQuery.data+ const rows = environmentDeployments?.environmentDeployments.filter(hasRuntimeInstanceDeployment) ?? []+ const isLoading = environmentDeploymentsQuery.isLoading+ const hasError = environmentDeploymentsQuery.isError++ return (+ <div className="flex w-full min-w-0 flex-col gap-4 px-6 py-6">+ {isLoading+ ? <DeploymentEnvironmentListSkeleton />+ : hasError+ ? <DeploymentStateMessage variant="list">{t('common.loadFailed')}</DeploymentStateMessage>+ : rows.length === 0+ ? (+ <DeploymentEmptyState+ icon="i-ri-server-line"+ title={t('deployTab.emptyTitle')}+ description={t('deployTab.emptyDescription')}+ action={<NewDeploymentButton appInstanceId={appInstanceId} />}+ />+ )+ : (+ <DeploymentEnvironmentList appInstanceId={appInstanceId} rows={rows} />+ )}+ </div>+ )+}diff --git a/web/features/deployments/detail/deploy-tab/deployment-environment-list.tsx b/web/features/deployments/detail/deploy-tab/deployment-environment-list.tsxnew file mode 100644index 00000000000..d01d908aaaa--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/deployment-environment-list.tsx@@ -0,0 +1,163 @@+'use client'++import type { EnvironmentDeployment } from '@dify/contracts/enterprise/types.gen'+import { useTranslation } from 'react-i18next'+import { releaseCommit } from '../../shared/domain/release'+import { isUndeployedDeploymentRow } from '../../shared/domain/runtime-status'+import {+ DetailTable,+ DetailTableBody,+ DetailTableCard,+ DetailTableCardList,+ DetailTableCell,+ DetailTableHead,+ DetailTableHeader,+ DetailTableRow,+} from '../table'+import {+ DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES,+} from '../table-styles'+import { DeploymentRowActions } from './deployment-row-actions'+import { DeploymentStatusSummary } from './deployment-status-summary'++function EnvironmentSummary({ environment }: {+ environment: EnvironmentDeployment['environment']+}) {+ return (+ <span className="block truncate text-text-primary">+ {environment.displayName}+ </span>+ )+}++function CurrentReleaseSummary({ release }: {+ release: EnvironmentDeployment['currentRelease']+}) {+ if (!release)+ return <span className="text-text-quaternary">—</span>++ const commit = releaseCommit(release)++ return (+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex min-w-0 items-baseline gap-1.5">+ <span className="truncate text-text-primary">+ {release.displayName}+ </span>+ {commit !== '—' && (+ <span className="shrink-0 font-mono system-xs-regular text-text-tertiary">+ {commit}+ </span>+ )}+ </div>+ </div>+ )+}++function CurrentReleaseMobileSummary({ release }: {+ release: EnvironmentDeployment['currentRelease']+}) {+ const { t } = useTranslation('deployments')++ if (!release)+ return null++ return (+ <div className="flex min-w-0 flex-col gap-1">+ <span className="system-2xs-medium-uppercase text-text-tertiary">+ {t('deployTab.col.currentRelease')}+ </span>+ <CurrentReleaseSummary release={release} />+ </div>+ )+}++function DeploymentEnvironmentMobileRow({ appInstanceId, row }: {+ appInstanceId: string+ row: EnvironmentDeployment+}) {+ const envId = row.environment.id+ const release = row.currentRelease++ return (+ <DetailTableCard>+ <div className="flex flex-col gap-3 p-4 text-left">+ <div className="flex min-w-0 flex-col gap-1">+ <EnvironmentSummary environment={row.environment} />+ <DeploymentStatusSummary row={row} />+ </div>+ {!isUndeployedDeploymentRow(row) && <CurrentReleaseMobileSummary release={release} />}+ <div className="flex min-w-0 items-center justify-start gap-2">+ <DeploymentRowActions appInstanceId={appInstanceId} envId={envId} row={row} />+ </div>+ </div>+ </DetailTableCard>+ )+}++function DeploymentEnvironmentDesktopRows({ appInstanceId, rows }: {+ appInstanceId: string+ rows: EnvironmentDeployment[]+}) {+ return (+ <>+ {rows.map((row) => {+ const envId = row.environment.id+ return (+ <DetailTableRow key={envId}>+ <DetailTableCell>+ <EnvironmentSummary environment={row.environment} />+ </DetailTableCell>+ <DetailTableCell>+ <DeploymentStatusSummary row={row} />+ </DetailTableCell>+ <DetailTableCell>+ <CurrentReleaseSummary release={row.currentRelease} />+ </DetailTableCell>+ <DetailTableCell className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.actions}>+ <div className="flex min-h-8 justify-end">+ <DeploymentRowActions appInstanceId={appInstanceId} envId={envId} row={row} />+ </div>+ </DetailTableCell>+ </DetailTableRow>+ )+ })}+ </>+ )+}++export function DeploymentEnvironmentList({ appInstanceId, rows }: {+ appInstanceId: string+ rows: EnvironmentDeployment[]+}) {+ const { t } = useTranslation('deployments')++ return (+ <>+ <DetailTableCardList className="pc:hidden">+ {rows.map(row => (+ <DeploymentEnvironmentMobileRow+ key={row.environment.id}+ appInstanceId={appInstanceId}+ row={row}+ />+ ))}+ </DetailTableCardList>+ <div className="hidden pc:block">+ <DetailTable>+ <DetailTableHeader>+ <DetailTableRow>+ <DetailTableHead className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.environment}>{t('deployTab.col.environment')}</DetailTableHead>+ <DetailTableHead className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.status}>{t('deployTab.col.status')}</DetailTableHead>+ <DetailTableHead className={DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.currentRelease}>{t('deployTab.col.currentRelease')}</DetailTableHead>+ <DetailTableHead className={`${DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES.actions} text-right`}>{t('deployTab.col.actions')}</DetailTableHead>+ </DetailTableRow>+ </DetailTableHeader>+ <DetailTableBody>+ <DeploymentEnvironmentDesktopRows appInstanceId={appInstanceId} rows={rows} />+ </DetailTableBody>+ </DetailTable>+ </div>+ </>+ )+}diff --git a/web/features/deployments/detail/deploy-tab/deployment-error-dialog.tsx b/web/features/deployments/detail/deploy-tab/deployment-error-dialog.tsxnew file mode 100644index 00000000000..343d0aab701--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/deployment-error-dialog.tsx@@ -0,0 +1,76 @@+'use client'++import type { EnvironmentDeployment } from '@dify/contracts/enterprise/types.gen'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { useTranslation } from 'react-i18next'++function DeploymentErrorDetails({ error }: {+ error?: EnvironmentDeployment['error']+}) {+ const { t } = useTranslation('deployments')+ const message = error?.message?.trim() || t('deployTab.panel.unknownError')+ const metadata = [+ ...(error?.phase ? [{ label: t('deployTab.errorPhase'), value: error.phase }] : []),+ ...(error?.code ? [{ label: t('deployTab.errorCode'), value: error.code }] : []),+ ]++ return (+ <div className="rounded-xl border border-divider-subtle bg-background-default-subtle p-3">+ <div className="system-xs-medium-uppercase text-text-tertiary">+ {t('deployTab.errorMessage')}+ </div>+ <div className="mt-1 system-sm-regular break-words whitespace-pre-wrap text-text-secondary">+ {message}+ </div>+ {metadata.length > 0 && (+ <div className="mt-3 flex flex-wrap gap-2">+ {metadata.map(item => (+ <span+ key={item.label}+ className="inline-flex max-w-full items-center gap-1.5 rounded-md border border-divider-subtle bg-background-default px-2 py-1 system-xs-regular text-text-tertiary"+ >+ <span className="shrink-0 text-text-quaternary">{item.label}</span>+ <span className="truncate font-mono text-text-secondary">{item.value}</span>+ </span>+ ))}+ </div>+ )}+ </div>+ )+}++export function DeploymentErrorDialog({ open, row, onOpenChange }: {+ open: boolean+ row: EnvironmentDeployment+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('deployments')++ return (+ <AlertDialog open={open} onOpenChange={onOpenChange}>+ <AlertDialogContent className="w-120">+ <div className="flex flex-col gap-3 px-6 pt-6 pb-2">+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('deployTab.errorDialogTitle', { name: row.environment.displayName })}+ </AlertDialogTitle>+ <AlertDialogDescription className="system-sm-regular text-text-tertiary">+ {t('deployTab.errorDialogDesc')}+ </AlertDialogDescription>+ <DeploymentErrorDetails error={row.error} />+ </div>+ <AlertDialogActions className="pt-3">+ <AlertDialogCancelButton variant="secondary">+ {t('deployTab.closeError')}+ </AlertDialogCancelButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/web/features/deployments/detail/deploy-tab/deployment-row-actions-menu.tsx b/web/features/deployments/detail/deploy-tab/deployment-row-actions-menu.tsxnew file mode 100644index 00000000000..5561d2a3b2e--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/deployment-row-actions-menu.tsx@@ -0,0 +1,135 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { DETAIL_TABLE_ACTION_TRIGGER_CLASS_NAME } from '../table-styles'++export function DeploymentActionsDropdown({+ currentReleaseId,+ deployActionLabel,+ failedReleaseId,+ isDeployFailed,+ isDeploymentInProgress,+ isUndeployed,+ undeployActionDisabled,+ onDeploy,+ onRequestUndeploy,+ onViewError,+}: {+ currentReleaseId?: string+ deployActionLabel: string+ failedReleaseId?: string+ isDeployFailed: boolean+ isDeploymentInProgress: boolean+ isUndeployed: boolean+ undeployActionDisabled: boolean+ onDeploy: (releaseId?: string) => void+ onRequestUndeploy: () => void+ onViewError: () => void+}) {+ const { t } = useTranslation('deployments')+ const [open, setOpen] = useState(false)++ if (isDeploymentInProgress)+ return null++ function handleDeployAction(releaseId?: string) {+ onDeploy(releaseId)+ setOpen(false)+ }++ function handleViewError() {+ onViewError()+ setOpen(false)+ }++ function handleRequestUndeploy() {+ if (undeployActionDisabled)+ return++ onRequestUndeploy()+ setOpen(false)+ }++ return (+ <DropdownMenu modal={false} open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ aria-label={t('deployTab.moreActions')}+ className={DETAIL_TABLE_ACTION_TRIGGER_CLASS_NAME}+ >+ <span aria-hidden className="i-ri-more-fill size-4" />+ </DropdownMenuTrigger>+ {open && (+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="min-w-44">+ {isDeployFailed+ ? (+ <>+ <DropdownMenuItem+ className="gap-2 px-3"+ onClick={handleViewError}+ >+ <span aria-hidden className="i-ri-error-warning-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">{t('deployTab.viewError')}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ className="gap-2 px-3"+ onClick={() => handleDeployAction(failedReleaseId)}+ >+ <span aria-hidden className="i-ri-refresh-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">+ {failedReleaseId ? t('deployTab.retry') : t('deployTab.deployOtherVersion')}+ </span>+ </DropdownMenuItem>+ </>+ )+ : (+ <>+ {!isUndeployed && currentReleaseId && (+ <DropdownMenuItem+ className="gap-2 px-3"+ onClick={() => handleDeployAction(currentReleaseId)}+ >+ <span aria-hidden className="i-ri-refresh-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">{t('deployTab.redeploy')}</span>+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ className="gap-2 px-3"+ onClick={() => handleDeployAction()}+ >+ <span aria-hidden className="i-ri-rocket-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">{deployActionLabel}</span>+ </DropdownMenuItem>+ </>+ )}+ {!isUndeployed && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ disabled={undeployActionDisabled}+ aria-disabled={undeployActionDisabled}+ className={cn(+ 'gap-2 px-3',+ undeployActionDisabled && 'cursor-not-allowed opacity-60',+ )}+ onClick={handleRequestUndeploy}+ >+ <span aria-hidden className="i-ri-logout-box-line size-4 shrink-0" />+ <span className="system-sm-regular">{t('deployTab.undeploy')}</span>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ )}+ </DropdownMenu>+ )+}diff --git a/web/features/deployments/detail/deploy-tab/deployment-row-actions.tsx b/web/features/deployments/detail/deploy-tab/deployment-row-actions.tsxnew file mode 100644index 00000000000..33af0ae3f2a--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/deployment-row-actions.tsx@@ -0,0 +1,109 @@+'use client'++import type { EnvironmentDeployment } from '@dify/contracts/enterprise/types.gen'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { useMutation } from '@tanstack/react-query'+import { useSetAtom } from 'jotai'+import { useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { openDeployDrawerAtom } from '../../deploy-drawer/state'+import { createDeploymentIdempotencyKey } from '../../shared/domain/idempotency'+import { isRuntimeDeploymentInProgress, isUndeployedDeploymentRow } from '../../shared/domain/runtime-status'+import { DeploymentErrorDialog } from './deployment-error-dialog'+import { DeploymentActionsDropdown } from './deployment-row-actions-menu'+import { UndeployDeploymentDialog } from './undeploy-deployment-dialog'++export function DeploymentRowActions({ appInstanceId, envId, row }: {+ appInstanceId: string+ envId: string+ row: EnvironmentDeployment+}) {+ const { t } = useTranslation('deployments')+ const openDeployDrawer = useSetAtom(openDeployDrawerAtom)+ const undeployDeployment = useMutation(consoleQuery.enterprise.deploymentService.undeploy.mutationOptions())+ const isUndeployed = isUndeployedDeploymentRow(row)+ const status = row.status+ const [showUndeployConfirm, setShowUndeployConfirm] = useState(false)+ const [showErrorDetail, setShowErrorDetail] = useState(false)+ const [isUndeploying, setIsUndeploying] = useState(false)+ const undeployInFlightRef = useRef(false)+ const isUndeployRequesting = undeployDeployment.isPending || isUndeploying+ const undeployActionDisabled = isUndeployRequesting+ const isDeploymentInProgress = isRuntimeDeploymentInProgress(status)+ const isDeployFailed = status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED+ const currentReleaseId = row.currentRelease?.id+ const failedReleaseId = row.desiredRelease?.id ?? row.currentRelease?.id+ const deployActionLabel = isUndeployed+ ? t('deployDrawer.deploy')+ : t('deployTab.deployOtherVersion')++ function handleDeployAction(releaseId?: string) {+ openDeployDrawer({ appInstanceId, environmentId: envId, releaseId })+ }++ function handleUndeploy() {+ if (undeployInFlightRef.current)+ return+ undeployInFlightRef.current = true+ setIsUndeploying(true)+ undeployDeployment.mutate(+ {+ params: { appInstanceId, environmentId: envId },+ body: {+ appInstanceId,+ environmentId: envId,+ idempotencyKey: createDeploymentIdempotencyKey(),+ },+ },+ {+ onSettled: () => {+ undeployInFlightRef.current = false+ setIsUndeploying(false)+ setShowUndeployConfirm(false)+ },+ },+ )+ }++ return (+ <div+ role="presentation"+ className="flex shrink-0 items-center"+ onClick={e => e.stopPropagation()}+ onKeyDown={e => e.stopPropagation()}+ >+ <DeploymentActionsDropdown+ currentReleaseId={currentReleaseId}+ deployActionLabel={deployActionLabel}+ failedReleaseId={failedReleaseId}+ isDeployFailed={isDeployFailed}+ isDeploymentInProgress={isDeploymentInProgress}+ isUndeployed={isUndeployed}+ undeployActionDisabled={undeployActionDisabled}+ onDeploy={handleDeployAction}+ onRequestUndeploy={() => setShowUndeployConfirm(true)}+ onViewError={() => setShowErrorDetail(true)}+ />++ {isDeployFailed && (+ <DeploymentErrorDialog+ open={showErrorDetail}+ row={row}+ onOpenChange={setShowErrorDetail}+ />+ )}++ {!isUndeployed && !isDeploymentInProgress && (+ <UndeployDeploymentDialog+ open={showUndeployConfirm}+ row={row}+ isRequesting={isUndeployRequesting}+ disabled={undeployActionDisabled}+ onConfirm={handleUndeploy}+ onOpenChange={setShowUndeployConfirm}+ />+ )}+ </div>+ )+}diff --git a/web/features/deployments/detail/deploy-tab/deployment-status-summary.tsx b/web/features/deployments/detail/deploy-tab/deployment-status-summary.tsxnew file mode 100644index 00000000000..e5b58e9051e--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/deployment-status-summary.tsx@@ -0,0 +1,107 @@+'use client'++import type { EnvironmentDeployment } from '@dify/contracts/enterprise/types.gen'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { useTranslation } from 'react-i18next'+import {+ isUndeployedDeploymentRow,+} from '../../shared/domain/runtime-status'+import { DeploymentStatusBadge } from '../../shared/ui/deployment-status-badge'++export function DeploymentStatusSummary({ row }: {+ row: EnvironmentDeployment+}) {+ const { t } = useTranslation('deployments')+ const status = row.status++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING) {+ return (+ <DeploymentStatusBadge+ status={status}+ label={t(`status.${status}`)}+ variant="status-dot"+ />+ )+ }++ if (isUndeployedDeploymentRow(row)) {+ return (+ <DeploymentStatusBadge+ status={RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED}+ label={t(`status.${RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED}`)}+ variant="status-dot"+ />+ )+ }++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING) {+ const targetRelease = row.desiredRelease ?? row.currentRelease+ if (!targetRelease) {+ return (+ <DeploymentStatusBadge+ status={RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING}+ label={t(`status.${RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING}`)}+ variant="status-dot"+ />+ )+ }++ return (+ <DeploymentStatusBadge+ status={status}+ label={t('deployTab.status.deployingRelease', { release: targetRelease.displayName })}+ variant="status-dot"+ />+ )+ }++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED) {+ const hasRunningRelease = Boolean(row.currentRelease)+ return (+ <DeploymentStatusBadge+ status={status}+ label={t(hasRunningRelease ? 'deployTab.status.runningWithFailed' : 'deployTab.status.deployFailed')}+ variant="status-dot"+ />+ )+ }++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DRIFTED) {+ const hasRunningRelease = Boolean(row.currentRelease)+ return (+ <DeploymentStatusBadge+ status={status}+ label={t(hasRunningRelease ? 'deployTab.status.runningOutOfSync' : `status.${status}`)}+ variant="status-dot"+ />+ )+ }++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_INVALID) {+ return (+ <DeploymentStatusBadge+ status={status}+ label={t(`status.${status}`)}+ variant="status-dot"+ />+ )+ }++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED) {+ return (+ <DeploymentStatusBadge+ status={status}+ label={t(`status.${status}`)}+ variant="status-dot"+ />+ )+ }++ return (+ <DeploymentStatusBadge+ status={RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY}+ label={t(`status.${RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY}`)}+ variant="status-dot"+ />+ )+}diff --git a/web/features/deployments/detail/deploy-tab/new-deployment-button.tsx b/web/features/deployments/detail/deploy-tab/new-deployment-button.tsxnew file mode 100644index 00000000000..26b231dd6a8--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/new-deployment-button.tsx@@ -0,0 +1,45 @@+'use client'++import { Button } from '@langgenius/dify-ui/button'+import { useQuery } from '@tanstack/react-query'+import { useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { openDeployDrawerAtom } from '../../deploy-drawer/state'+import { deploymentStatusPollingInterval, hasRuntimeInstanceDeployment } from '../../shared/domain/runtime-status'++export function NewDeploymentButton({ appInstanceId }: {+ appInstanceId: string+}) {+ const { t } = useTranslation('deployments')+ const openDeployDrawer = useSetAtom(openDeployDrawerAtom)++ return (+ <Button+ size="medium"+ variant="primary"+ className="gap-1.5"+ onClick={() => openDeployDrawer({ appInstanceId })}+ >+ <span className="i-ri-rocket-line size-4 shrink-0" aria-hidden="true" />+ {t('deployTab.newDeployment')}+ </Button>+ )+}++export function NewDeploymentHeaderAction({ appInstanceId }: {+ appInstanceId: string+}) {+ const environmentDeploymentsQuery = useQuery(consoleQuery.enterprise.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: { appInstanceId },+ },+ refetchInterval: query => deploymentStatusPollingInterval(query.state.data?.environmentDeployments),+ }))+ const rows = environmentDeploymentsQuery.data?.environmentDeployments.filter(hasRuntimeInstanceDeployment) ?? []++ if (environmentDeploymentsQuery.isLoading || environmentDeploymentsQuery.isError || rows.length === 0)+ return null++ return <NewDeploymentButton appInstanceId={appInstanceId} />+}diff --git a/web/features/deployments/detail/deploy-tab/undeploy-deployment-dialog.tsx b/web/features/deployments/detail/deploy-tab/undeploy-deployment-dialog.tsxnew file mode 100644index 00000000000..a5ea48a0264--- /dev/null+++ b/web/features/deployments/detail/deploy-tab/undeploy-deployment-dialog.tsx@@ -0,0 +1,65 @@+'use client'++import type { EnvironmentDeployment } from '@dify/contracts/enterprise/types.gen'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { useTranslation } from 'react-i18next'++export function UndeployDeploymentDialog({+ disabled,+ isRequesting,+ open,+ row,+ onConfirm,+ onOpenChange,+}: {+ disabled: boolean+ isRequesting: boolean+ open: boolean+ row: EnvironmentDeployment+ onConfirm: () => void+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('deployments')++ function handleOpenChange(nextOpen: boolean) {+ if (isRequesting)+ return++ onOpenChange(nextOpen)+ }++ return (+ <AlertDialog open={open} onOpenChange={handleOpenChange}>+ <AlertDialogContent className="w-120">+ <div className="flex flex-col gap-3 px-6 pt-6 pb-2">+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('deployTab.undeployConfirmTitle', { name: row.environment.displayName })}+ </AlertDialogTitle>+ <AlertDialogDescription className="system-sm-regular text-text-tertiary">+ {t('deployTab.undeployConfirmDesc')}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions className="pt-3">+ <AlertDialogCancelButton variant="secondary" disabled={isRequesting}>+ {t('deployDrawer.cancel')}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton+ loading={isRequesting}+ disabled={disabled}+ onClick={onConfirm}+ >+ {t('deployTab.confirmUndeploy')}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/web/features/deployments/detail/deployment-sidebar.tsx b/web/features/deployments/detail/deployment-sidebar.tsxnew file mode 100644index 00000000000..efe86ba7b3d--- /dev/null+++ b/web/features/deployments/detail/deployment-sidebar.tsx@@ -0,0 +1,321 @@+'use client'++import type { ComponentProps, PropsWithoutRef } from 'react'+import type { InstanceDetailTabKey } from './tabs'+import type { NavIcon } from '@/app/components/app-sidebar/nav-link'+import { cn } from '@langgenius/dify-ui/cn'+import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { formatForDisplay } from '@tanstack/react-hotkeys'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import NavLink from '@/app/components/app-sidebar/nav-link'+import ToggleButton from '@/app/components/app-sidebar/toggle-button'+import Divider from '@/app/components/base/divider'+import SidebarLeftArrowIcon from '@/app/components/base/icons/src/vender/SidebarLeftArrowIcon'+import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'+import { useSetGotoAnythingOpen } from '@/app/components/goto-anything/atoms'+import Link from '@/next/link'+import { usePathname, useRouter } from '@/next/navigation'+import { consoleQuery } from '@/service/client'+import { DeploymentActionsMenu } from '../components/deployment-actions'+import { TitleTooltip } from '../components/title-tooltip'++type TabDef = {+ key: InstanceDetailTabKey+ icon: NavIcon+ selectedIcon: NavIcon+}++type TailwindNavIconProps = PropsWithoutRef<ComponentProps<'svg'>> & {+ title?: string+ titleId?: string+}++function OverviewIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-dashboard-2-line', className)} />+}+function OverviewSelectedIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-dashboard-2-fill', className)} />+}+function DeployIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-server-line', className)} />+}+function DeploySelectedIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-server-fill', className)} />+}+function VersionsIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-stack-line', className)} />+}+function VersionsSelectedIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-stack-fill', className)} />+}+function AccessIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-shield-user-line', className)} />+}+function AccessSelectedIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-shield-user-fill', className)} />+}+function ApiIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-code-s-slash-line', className)} />+}+function ApiSelectedIcon({ className }: TailwindNavIconProps) {+ return <span aria-hidden className={cn('i-ri-code-s-slash-fill', className)} />+}++const DEPLOYMENT_TABS: TabDef[] = [+ { key: 'overview', icon: OverviewIcon, selectedIcon: OverviewSelectedIcon },+ { key: 'instances', icon: DeployIcon, selectedIcon: DeploySelectedIcon },+ { key: 'releases', icon: VersionsIcon, selectedIcon: VersionsSelectedIcon },+ { key: 'access', icon: AccessIcon, selectedIcon: AccessSelectedIcon },+ { key: 'api-tokens', icon: ApiIcon, selectedIcon: ApiSelectedIcon },+]++const SEARCH_SHORTCUT = ['Mod', 'K']++const getDeploymentIdFromPathname = (pathname: string) => {+ const [section, appInstanceId] = pathname.split('/').filter(Boolean)+ return section === 'deployments' ? appInstanceId : undefined+}++function DeploymentIcon({ expand }: {+ expand: boolean+}) {+ return (+ <div+ className={cn(+ 'flex shrink-0 items-center justify-center rounded-lg bg-components-icon-bg-blue-solid text-text-primary-on-surface',+ expand ? 'size-10' : 'size-8',+ )}+ >+ <span aria-hidden className={cn('i-ri-rocket-fill', expand ? 'size-5' : 'size-4')} />+ </div>+ )+}++function DeploymentDetailInstanceInfo({ appInstanceId, expand }: {+ appInstanceId: string+ expand: boolean+}) {+ const { t } = useTranslation('deployments')+ const overviewQuery = useQuery(consoleQuery.enterprise.appInstanceService.getAppInstance.queryOptions({+ input: {+ params: { appInstanceId },+ },+ }))+ const app = overviewQuery.data?.appInstance+ const isLoading = !app && overviewQuery.isLoading+ const isUnavailable = !app || overviewQuery.isError+ const instanceName = app ? app.displayName : appInstanceId++ return (+ <div+ className={cn(+ 'rounded-xl hover:bg-state-base-hover',+ expand ? 'flex items-start gap-2 p-2' : 'flex items-center justify-center px-1 py-1.5',+ )}+ aria-label={!expand ? instanceName : undefined}+ >+ {isLoading+ ? (+ <>+ <SkeletonRectangle className={cn('my-0 animate-pulse rounded-lg', expand ? 'size-10' : 'size-8')} />+ {expand && (+ <SkeletonContainer className="min-w-0 flex-1 gap-1">+ <SkeletonRectangle className="my-0 h-5 w-32 animate-pulse" />+ <SkeletonRectangle className="my-0 h-3 w-20 animate-pulse" />+ </SkeletonContainer>+ )}+ </>+ )+ : isUnavailable+ ? (+ <>+ <div className="flex size-8 items-center justify-center rounded-lg bg-components-icon-bg-orange-solid text-text-primary-on-surface">+ <span className="i-ri-rocket-line size-4" />+ </div>+ {expand && (+ <div className="flex min-w-0 flex-1 flex-col items-start justify-center gap-0.5 self-stretch">+ <div className="w-full min-w-0 pr-1">+ <div className="truncate system-md-semibold whitespace-nowrap text-text-secondary">+ {t('detail.notFound')}+ </div>+ </div>+ <TitleTooltip content={appInstanceId}>+ <div className="max-w-full truncate font-mono system-2xs-regular text-text-tertiary">+ {appInstanceId}+ </div>+ </TitleTooltip>+ </div>+ )}+ </>+ )+ : (+ <>+ <DeploymentIcon expand={expand} />+ {expand && (+ <>+ <div className="flex min-w-0 flex-1 flex-col items-start justify-center gap-0.5 self-stretch">+ <div className="w-full min-w-0 pr-1">+ <TitleTooltip content={instanceName}>+ <div className="truncate system-md-semibold whitespace-nowrap text-text-secondary">+ {instanceName}+ </div>+ </TitleTooltip>+ </div>+ {app.description && (+ <TitleTooltip content={app.description}>+ <div className="line-clamp-2 system-xs-regular text-text-tertiary">+ {app.description}+ </div>+ </TitleTooltip>+ )}+ </div>+ <DeploymentActionsMenu+ appInstanceId={appInstanceId}+ appName={instanceName}+ placement="bottom-end"+ sideOffset={4}+ className="shrink-0"+ triggerClassName="size-5 rounded-md bg-transparent p-0.5 shadow-none"+ />+ </>+ )}+ </>+ )}+ </div>+ )+}++export function DeploymentDetailTop({+ expand = true,+ onToggle,+}: {+ expand?: boolean+ onToggle?: () => void+}) {+ const { t } = useTranslation()+ const router = useRouter()+ const setGotoAnythingOpen = useSetGotoAnythingOpen()++ if (!expand) {+ return (+ <div className="flex w-full items-center justify-center px-3 pt-2 pb-1">+ {onToggle && (+ <ToggleButton+ expand={expand}+ handleToggle={onToggle}+ icon={<SidebarLeftArrowIcon aria-hidden className="size-4" />}+ className="size-8 rounded-[10px] border-0 bg-transparent px-0 text-text-tertiary shadow-none hover:border-0 hover:bg-state-base-hover hover:text-text-secondary"+ />+ )}+ </div>+ )+ }++ return (+ <div className="flex items-center py-2 pr-2 pl-1">+ <div className="flex min-w-0 flex-1 items-center gap-px">+ <div className="flex shrink-0 items-center rounded-lg py-2 pr-1.5 pl-0.5 transition-colors hover:bg-background-default-hover">+ <button+ type="button"+ aria-label={t('operation.back', { ns: 'common' })}+ className="flex size-4 items-center justify-center text-text-tertiary hover:text-text-secondary"+ onClick={() => router.back()}+ >+ <span aria-hidden className="i-ri-arrow-left-s-line size-4" />+ </button>+ <Link+ href="/"+ aria-label={t('mainNav.home', { ns: 'common' })}+ className="flex size-4 items-center justify-center text-text-tertiary hover:text-text-secondary"+ >+ <span aria-hidden className="i-custom-vender-main-nav-app-home size-4" />+ </Link>+ </div>+ <span className="shrink-0 system-md-regular text-text-quaternary">+ /+ </span>+ <Link+ href="/deployments"+ className="shrink-0 truncate rounded-lg px-1.5 py-2 system-sm-semibold-uppercase text-text-secondary transition-colors hover:bg-background-default-hover hover:text-text-primary"+ >+ {t('menus.deployments', { ns: 'common' })}+ </Link>+ </div>+ <Tooltip>+ <TooltipTrigger+ render={(+ <button+ type="button"+ aria-label={t('gotoAnything.searchTitle', { ns: 'app' })}+ className="flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-[10px] text-text-tertiary transition-colors hover:bg-state-base-hover hover:text-text-secondary"+ onClick={() => setGotoAnythingOpen(true)}+ >+ <span aria-hidden className="i-custom-vender-main-nav-quick-search size-4" />+ </button>+ )}+ />+ <TooltipContent placement="bottom" className="flex items-center gap-1 rounded-lg border-[0.5px] border-components-panel-border bg-components-tooltip-bg p-1.5 system-xs-medium text-text-secondary shadow-lg backdrop-blur-[5px]">+ <span className="px-0.5">{t('gotoAnything.quickAction', { ns: 'app' })}</span>+ <KbdGroup>+ {SEARCH_SHORTCUT.map(key => (+ <Kbd key={key}>{formatForDisplay(key)}</Kbd>+ ))}+ </KbdGroup>+ </TooltipContent>+ </Tooltip>+ {onToggle && (+ <ToggleButton+ expand={expand}+ handleToggle={onToggle}+ icon={<SidebarLeftArrowIcon aria-hidden className="size-4" />}+ className="size-8 rounded-[10px] border-0 bg-transparent px-0 text-text-tertiary shadow-none hover:border-0 hover:bg-state-base-hover hover:text-text-secondary"+ />+ )}+ </div>+ )+}++export function DeploymentDetailSection({+ expand = true,+}: {+ expand?: boolean+}) {+ const { t } = useTranslation('deployments')+ const pathname = usePathname()+ const appInstanceId = getDeploymentIdFromPathname(pathname)++ if (!appInstanceId)+ return null++ return (+ <div className={cn('flex min-h-0 flex-1 flex-col', expand ? 'px-2 pb-2' : 'pb-2')}>+ {!expand && (+ <div className="flex w-full shrink-0 justify-center px-3.5 pt-0.5 pb-[3px]">+ <Divider+ type="horizontal"+ bgStyle="solid"+ className="my-0 h-px w-[27px] bg-divider-subtle"+ />+ </div>+ )}+ <div className="px-1 py-2">+ <DeploymentDetailInstanceInfo appInstanceId={appInstanceId} expand={expand} />+ </div>++ <nav className={cn('flex flex-col gap-y-0.5 py-1', expand ? 'px-1' : 'px-3')}>+ {DEPLOYMENT_TABS.map(tab => (+ <NavLink+ key={tab.key}+ mode={expand ? 'expand' : 'collapse'}+ iconMap={{ selected: tab.selectedIcon, normal: tab.icon }}+ name={t(`tabs.${tab.key}.name`)}+ href={`/deployments/${appInstanceId}/${tab.key}`}+ pathname={pathname}+ />+ ))}+ </nav>+ </div>+ )+}diff --git a/web/features/deployments/detail/developer-api-tab.tsx b/web/features/deployments/detail/developer-api-tab.tsxnew file mode 100644index 00000000000..6ee0e0a88da--- /dev/null+++ b/web/features/deployments/detail/developer-api-tab.tsx@@ -0,0 +1,13 @@+'use client'++import { DeveloperApiSection } from './settings-tab/access/developer-api-section'++export function DeveloperApiTab({ appInstanceId }: {+ appInstanceId: string+}) {+ return (+ <div className="flex w-full max-w-[960px] min-w-0 flex-col gap-y-4 px-6 py-6 sm:px-20 sm:py-8">+ <DeveloperApiSection appInstanceId={appInstanceId} />+ </div>+ )+}diff --git a/web/features/deployments/detail/index.tsx b/web/features/deployments/detail/index.tsxnew file mode 100644index 00000000000..5b1ec7a9f19--- /dev/null+++ b/web/features/deployments/detail/index.tsx@@ -0,0 +1,89 @@+'use client'++import type { ReactNode } from 'react'+import type { InstanceDetailTabKey } from './tabs'+import { useTranslation } from 'react-i18next'+import useDocumentTitle from '@/hooks/use-document-title'+import Link from '@/next/link'+import { useSelectedLayoutSegment } from '@/next/navigation'+import { CreateReleaseControl } from '../create-release'+import { NewDeploymentHeaderAction } from './deploy-tab/new-deployment-button'+import { DeveloperApiHeaderSwitch } from './settings-tab/access/developer-api-section'+import { INSTANCE_DETAIL_TAB_KEYS, isInstanceDetailTabKey } from './tabs'++function MobileDetailTabs({ appInstanceId, activeTab }: {+ appInstanceId: string+ activeTab: InstanceDetailTabKey+}) {+ const { t } = useTranslation('deployments')++ return (+ <nav+ aria-label={t('detail.mobileTabs')}+ className="border-b border-divider-subtle bg-components-panel-bg px-4 pc:hidden"+ >+ <div className="flex min-w-0 scrollbar-none gap-1 overflow-x-auto py-2">+ {INSTANCE_DETAIL_TAB_KEYS.map(tab => (+ <Link+ key={tab}+ href={`/deployments/${appInstanceId}/${tab}`}+ className={`inline-flex h-8 shrink-0 items-center rounded-lg px-3 system-sm-medium ${+ activeTab === tab+ ? 'bg-state-accent-hover text-text-accent'+ : 'text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary'+ }`}+ >+ {t(`tabs.${tab}.name`)}+ </Link>+ ))}+ </div>+ </nav>+ )+}++export function InstanceDetail({ appInstanceId, children }: {+ appInstanceId: string+ children: ReactNode+}) {+ const { t } = useTranslation('deployments')+ const selectedSegment = useSelectedLayoutSegment()+ const selectedTab = selectedSegment ?? undefined+ const activeTab: InstanceDetailTabKey = isInstanceDetailTabKey(selectedTab) ? selectedTab : 'overview'++ useDocumentTitle(t('documentTitle.detail'))++ return (+ <div className="relative m-1 ml-0 flex min-h-0 flex-1 overflow-hidden rounded-lg shadow-xs">+ <div className="min-w-0 grow overflow-hidden bg-components-panel-bg">+ <div className="h-full min-w-0 overflow-y-auto">+ <div className="flex min-h-full w-full flex-col">+ <div className="flex w-full flex-col gap-y-0.5 px-4 pt-3 pb-2 sm:px-6">+ <div className="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">+ <div className="min-w-0">+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">+ <div className="system-xl-semibold text-text-primary">{t(`tabs.${activeTab}.name`)}</div>+ {activeTab === 'api-tokens' && (+ <div className="shrink-0">+ <DeveloperApiHeaderSwitch appInstanceId={appInstanceId} />+ </div>+ )}+ </div>+ <div className="system-sm-regular text-text-tertiary">{t(`tabs.${activeTab}.description`)}</div>+ </div>+ {(activeTab === 'instances' || activeTab === 'releases') && (+ <div className="w-full shrink-0 pt-1 sm:w-auto sm:pt-1.5 [&_button]:w-full sm:[&_button]:w-auto">+ {activeTab === 'instances'+ ? <NewDeploymentHeaderAction appInstanceId={appInstanceId} />+ : <CreateReleaseControl appInstanceId={appInstanceId} size="medium" />}+ </div>+ )}+ </div>+ </div>+ <MobileDetailTabs appInstanceId={appInstanceId} activeTab={activeTab} />+ {children}+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/detail/overview-tab.tsx b/web/features/deployments/detail/overview-tab.tsxnew file mode 100644index 00000000000..3c0ffab519b--- /dev/null+++ b/web/features/deployments/detail/overview-tab.tsx@@ -0,0 +1,122 @@+'use client'++import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import Link from '@/next/link'+import { consoleQuery } from '@/service/client'+import { DeploymentStateMessage } from '../components/empty-state'+import { hasRuntimeInstanceDeployment } from '../shared/domain/runtime-status'+import { AccessStatusSection, AccessStatusSectionSkeleton, ApiTokenSummarySection, ApiTokenSummarySectionSkeleton } from './overview-tab/access-status-section'+import { EnvironmentStrip, EnvironmentStripSkeleton } from './overview-tab/environment-strip'+import { ReleaseHero, ReleaseHeroSkeleton } from './overview-tab/release-hero'++function OverviewLayout({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex w-full min-w-0 flex-col gap-6 px-6 py-6">+ {children}+ </div>+ )+}++function LatestReleaseSection({ appInstanceId, children }: {+ appInstanceId: string+ children: React.ReactNode+}) {+ const { t } = useTranslation('deployments')++ return (+ <section className="flex min-w-0 flex-col gap-3">+ <div className="flex min-w-0 items-baseline justify-between gap-3">+ <h3 className="system-sm-semibold text-text-primary">+ {t('overview.latestReleaseTitle')}+ </h3>+ <Link+ href={`/deployments/${appInstanceId}/releases`}+ className="inline-flex shrink-0 items-center gap-1 system-xs-medium text-text-tertiary transition-colors hover:text-text-secondary"+ >+ {t('overview.previousReleases.viewAll')}+ <span aria-hidden className="i-ri-arrow-right-line size-3.5" />+ </Link>+ </div>+ <div className="flex min-w-0 flex-col gap-3">+ {children}+ </div>+ </section>+ )+}++function OverviewLoadingSkeleton({ appInstanceId }: {+ appInstanceId: string+}) {+ return (+ <OverviewLayout>+ <EnvironmentStripSkeleton />+ <LatestReleaseSection appInstanceId={appInstanceId}>+ <ReleaseHeroSkeleton />+ </LatestReleaseSection>+ <AccessStatusSectionSkeleton />+ <ApiTokenSummarySectionSkeleton />+ </OverviewLayout>+ )+}++export function OverviewTab({ appInstanceId }: {+ appInstanceId: string+}) {+ const { t } = useTranslation('deployments')+ const input = { params: { appInstanceId } }+ const overviewQuery = useQuery(consoleQuery.enterprise.appInstanceService.getAppInstanceOverview.queryOptions({ input }))+ const overview = overviewQuery.data++ if (overviewQuery.isLoading)+ return <OverviewLoadingSkeleton appInstanceId={appInstanceId} />++ if (overviewQuery.isError) {+ return (+ <OverviewLayout>+ <DeploymentStateMessage variant="section">{t('common.loadFailed')}</DeploymentStateMessage>+ </OverviewLayout>+ )+ }++ if (!overview) {+ return (+ <OverviewLayout>+ <DeploymentStateMessage variant="section">{t('detail.notFound')}</DeploymentStateMessage>+ </OverviewLayout>+ )+ }++ const releaseRows = overview.recentReleases+ // recentReleases is a capped preview; totalReleaseCount is the true total.+ const releaseCount = overview.totalReleaseCount+ const runtimeRows = overview.environmentDeployments+ const deployedEnvironmentCount = runtimeRows.filter(hasRuntimeInstanceDeployment).length+ const latestRelease = releaseRows[0]+ const accessChannels = overview.accessChannels+ const apiKeySummary = overview.apiKeySummary++ return (+ <OverviewLayout>+ <EnvironmentStrip+ appInstanceId={appInstanceId}+ rows={runtimeRows}+ releaseRows={releaseRows}+ />+ <LatestReleaseSection appInstanceId={appInstanceId}>+ <ReleaseHero+ appInstanceId={appInstanceId}+ latestRelease={latestRelease}+ releaseCount={releaseCount}+ />+ </LatestReleaseSection>+ <AccessStatusSection appInstanceId={appInstanceId} accessChannels={accessChannels} />+ <ApiTokenSummarySection+ appInstanceId={appInstanceId}+ accessChannels={accessChannels}+ apiKeySummary={apiKeySummary}+ deployedEnvironmentCount={deployedEnvironmentCount}+ />+ </OverviewLayout>+ )+}diff --git a/web/features/deployments/detail/overview-tab/access-status-section.tsx b/web/features/deployments/detail/overview-tab/access-status-section.tsxnew file mode 100644index 00000000000..eb7aade343f--- /dev/null+++ b/web/features/deployments/detail/overview-tab/access-status-section.tsx@@ -0,0 +1,240 @@+'use client'++import type { AccessChannels, ApiKeySummary } from '@dify/contracts/enterprise/types.gen'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import Link from '@/next/link'+import { DeploymentStatusBadge } from '../../shared/ui/deployment-status-badge'+import { OVERVIEW_CARD_CLASS_NAME, OVERVIEW_ICON_CLASS_NAME, OVERVIEW_INTERACTIVE_CARD_CLASS_NAME } from './card-styles'++type AccessStatusSectionProps = {+ appInstanceId: string+ accessChannels?: AccessChannels+}++type ApiTokenSummarySectionProps = {+ appInstanceId: string+ accessChannels?: AccessChannels+ apiKeySummary?: ApiKeySummary+ deployedEnvironmentCount: number+}++type AccessStatusItem = {+ key: 'webapp' | 'cli'+ href: string+ icon: string+ label: string+ enabled: boolean+ meta: string+}++const ACCESS_STATUS_SKELETON_KEYS = ['webapp', 'cli']++export function AccessStatusSection({ appInstanceId, accessChannels }: AccessStatusSectionProps) {+ const { t } = useTranslation('deployments')+ const items: AccessStatusItem[] = [+ {+ key: 'webapp',+ href: `/deployments/${appInstanceId}/access`,+ icon: 'i-ri-global-line',+ label: t('card.access.webApp'),+ enabled: Boolean(accessChannels?.webAppEnabled),+ meta: t('overview.accessMeta.webApp'),+ },+ {+ key: 'cli',+ href: `/deployments/${appInstanceId}/access`,+ icon: 'i-ri-terminal-box-line',+ label: t('card.access.cli'),+ enabled: Boolean(accessChannels?.webAppEnabled),+ meta: t('overview.accessMeta.cli'),+ },+ ]++ return (+ <section className="flex min-w-0 flex-col gap-3">+ <h3 className="system-sm-semibold text-text-primary">+ {t('overview.accessStatus')}+ </h3>++ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,220px),1fr))] gap-3">+ {items.map(item => (+ <Link+ key={item.key}+ href={item.href}+ className={cn(+ OVERVIEW_INTERACTIVE_CARD_CLASS_NAME,+ 'group flex min-h-18 min-w-0 items-start gap-3',+ )}+ >+ <span+ aria-hidden+ className={OVERVIEW_ICON_CLASS_NAME}+ >+ <span className={cn('size-4', item.icon)} />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="flex min-w-0 items-center justify-between gap-3">+ <span className="truncate system-sm-medium text-text-primary">+ {item.label}+ </span>+ <span className="flex shrink-0 items-center gap-2">+ <StatusBadge enabled={item.enabled} />+ <span+ aria-hidden+ className="i-ri-arrow-right-line size-4 text-text-quaternary opacity-60 transition group-hover:translate-x-0.5 group-hover:opacity-100 group-focus-visible:translate-x-0.5 group-focus-visible:opacity-100"+ />+ </span>+ </span>+ <span className="truncate text-xs text-text-tertiary">+ {item.meta}+ </span>+ </span>+ </Link>+ ))}+ </div>+ </section>+ )+}++export function ApiTokenSummarySection({+ appInstanceId,+ accessChannels,+ apiKeySummary,+ deployedEnvironmentCount,+}: ApiTokenSummarySectionProps) {+ const { t } = useTranslation('deployments')+ const apiEnabled = Boolean(accessChannels?.developerApiEnabled)+ const apiKeyCount = apiKeySummary?.apiKeyCount ?? 0++ return (+ <section className="flex min-w-0 flex-col gap-3">+ <h3 className="system-sm-semibold text-text-primary">+ {t('overview.api')}+ </h3>++ <Link+ href={`/deployments/${appInstanceId}/api-tokens`}+ className={cn(+ OVERVIEW_INTERACTIVE_CARD_CLASS_NAME,+ 'group flex min-h-18 min-w-0 items-start gap-3',+ )}+ >+ <span aria-hidden className={OVERVIEW_ICON_CLASS_NAME}>+ <span className="i-ri-code-s-slash-line size-4" />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-2">+ <span className="flex min-w-0 items-center justify-between gap-3">+ <span className="truncate system-sm-medium text-text-primary">+ {t('card.access.api')}+ </span>+ <span className="flex shrink-0 items-center gap-2">+ <StatusBadge enabled={apiEnabled} />+ <span+ aria-hidden+ className="i-ri-arrow-right-line size-4 text-text-quaternary opacity-60 transition group-hover:translate-x-0.5 group-hover:opacity-100 group-focus-visible:translate-x-0.5 group-focus-visible:opacity-100"+ />+ </span>+ </span>+ {apiEnabled+ ? (+ <span className="flex min-w-0 flex-wrap gap-2">+ <span className="inline-flex h-6 min-w-0 items-center rounded-md bg-background-section-burn px-2 system-xs-medium text-text-secondary">+ {t('overview.apiKeysCount', { count: apiKeyCount })}+ </span>+ {/* "deployed environments" = envs with a runtime deployment, not envs-with-keys */}+ <span className="inline-flex h-6 min-w-0 items-center rounded-md bg-background-section-burn px-2 system-xs-medium text-text-secondary">+ {t('overview.apiTokenSummary.environments', { count: deployedEnvironmentCount })}+ </span>+ </span>+ )+ : (+ <span className="truncate text-xs text-text-tertiary">+ {t('overview.accessMeta.apiTokens')}+ </span>+ )}+ </span>+ </Link>+ </section>+ )+}++function StatusBadge({ enabled }: {+ enabled: boolean+}) {+ const { t } = useTranslation('deployments')++ return (+ <DeploymentStatusBadge+ status={enabled ? RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY : RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED}+ label={enabled ? t('overview.enabled') : t('overview.disabled')}+ />+ )+}++export function ApiTokenSummarySectionSkeleton() {+ const { t } = useTranslation('deployments')++ return (+ <section className="flex min-w-0 flex-col gap-3">+ <h3 className="system-sm-semibold text-text-primary">+ {t('overview.api')}+ </h3>+ <ApiTokenSummaryCardSkeleton />+ </section>+ )+}++function ApiTokenSummaryCardSkeleton() {+ return (+ <div+ data-slot="deployment-overview-api-token-card-skeleton"+ className={cn(OVERVIEW_CARD_CLASS_NAME, 'flex min-h-18 min-w-0 items-start gap-3')}+ >+ <SkeletonRectangle className="my-0 size-8 shrink-0 animate-pulse rounded-lg" />+ <span className="flex min-w-0 flex-1 flex-col gap-2">+ <span className="flex min-w-0 items-center justify-between gap-3">+ <SkeletonRectangle className="my-0 h-3.5 w-20 animate-pulse" />+ <SkeletonRectangle className="my-0 h-6 w-14 shrink-0 animate-pulse rounded-md" />+ </span>+ <span className="flex gap-2">+ <SkeletonRectangle className="my-0 h-6 w-24 animate-pulse rounded-md" />+ <SkeletonRectangle className="my-0 h-6 w-32 animate-pulse rounded-md" />+ </span>+ </span>+ </div>+ )+}++export function AccessStatusSectionSkeleton() {+ const { t } = useTranslation('deployments')++ return (+ <section className="flex min-w-0 flex-col gap-3">+ <h3 className="system-sm-semibold text-text-primary">+ {t('overview.accessStatus')}+ </h3>++ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,220px),1fr))] gap-3">+ {ACCESS_STATUS_SKELETON_KEYS.map(key => (+ <div+ key={key}+ data-slot="deployment-overview-access-card-skeleton"+ className={cn(OVERVIEW_CARD_CLASS_NAME, 'flex min-h-18 min-w-0 items-start gap-3')}+ >+ <SkeletonRectangle className="my-0 size-8 shrink-0 animate-pulse rounded-lg" />+ <span className="flex min-w-0 flex-1 flex-col gap-2">+ <span className="flex min-w-0 items-center justify-between gap-3">+ <SkeletonRectangle className="my-0 h-3.5 w-20 animate-pulse" />+ <SkeletonRectangle className="my-0 h-6 w-14 shrink-0 animate-pulse rounded-md" />+ </span>+ <SkeletonRectangle className="my-0 h-3 w-4/5 animate-pulse" />+ </span>+ </div>+ ))}+ </div>+ </section>+ )+}diff --git a/web/features/deployments/detail/overview-tab/card-styles.ts b/web/features/deployments/detail/overview-tab/card-styles.tsnew file mode 100644index 00000000000..07afcf3d0c2--- /dev/null+++ b/web/features/deployments/detail/overview-tab/card-styles.ts@@ -0,0 +1,10 @@+import { cn } from '@langgenius/dify-ui/cn'++export const OVERVIEW_CARD_CLASS_NAME = 'rounded-xl border border-components-panel-border bg-components-panel-bg p-4'++export const OVERVIEW_INTERACTIVE_CARD_CLASS_NAME = cn(+ OVERVIEW_CARD_CLASS_NAME,+ 'transition-colors hover:border-components-panel-border-subtle hover:bg-components-panel-on-panel-item-bg-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-components-button-primary-bg',+)++export const OVERVIEW_ICON_CLASS_NAME = 'flex size-8 shrink-0 items-center justify-center rounded-lg bg-background-section-burn text-text-tertiary'diff --git a/web/features/deployments/detail/overview-tab/environment-strip.tsx b/web/features/deployments/detail/overview-tab/environment-strip.tsxnew file mode 100644index 00000000000..1057458dfeb--- /dev/null+++ b/web/features/deployments/detail/overview-tab/environment-strip.tsx@@ -0,0 +1,148 @@+'use client'++import type { EnvironmentDeployment, Release } from '@dify/contracts/enterprise/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import Link from '@/next/link'+import { DeploymentEmptyState } from '../../components/empty-state'+import { openDeployDrawerAtom } from '../../deploy-drawer/state'+import { hasRuntimeInstanceDeployment } from '../../shared/domain/runtime-status'+import { OVERVIEW_CARD_CLASS_NAME } from './card-styles'+import { EnvironmentTile } from './environment-tile'++const OVERVIEW_RUNTIME_INSTANCE_LIMIT = 4++type EnvironmentStripProps = {+ appInstanceId: string+ rows: EnvironmentDeployment[]+ releaseRows: Release[]+}++export function EnvironmentStrip({ appInstanceId, rows, releaseRows }: EnvironmentStripProps) {+ const { t } = useTranslation('deployments')+ const runtimeRows = rows.filter(hasRuntimeInstanceDeployment)+ const previewRows = runtimeRows.slice(0, OVERVIEW_RUNTIME_INSTANCE_LIMIT)+ const hasRuntimeRows = runtimeRows.length > 0+ const hasRelease = releaseRows.length > 0++ return (+ <section className="flex flex-col gap-3">+ <div className="flex min-w-0 items-baseline justify-between gap-3">+ <h3 className="system-sm-semibold text-text-primary">{t('overview.strip.title')}</h3>+ {hasRuntimeRows && (+ <Link+ href={`/deployments/${appInstanceId}/instances`}+ className="inline-flex shrink-0 items-center gap-1 system-xs-medium text-text-tertiary transition-colors hover:text-text-secondary"+ >+ {t('overview.previousReleases.viewAll')}+ <span aria-hidden className="i-ri-arrow-right-line size-3.5" />+ </Link>+ )}+ </div>++ {!hasRuntimeRows+ ? <EnvironmentEmptyState appInstanceId={appInstanceId} canDeploy={hasRelease} />+ : (+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,360px),1fr))] gap-3">+ {previewRows.map(row => (+ <EnvironmentTile+ key={row.environment.id}+ appInstanceId={appInstanceId}+ row={row}+ releaseRows={releaseRows}+ />+ ))}+ </div>+ )}+ </section>+ )+}++function EnvironmentEmptyState({ appInstanceId, canDeploy }: {+ appInstanceId: string+ canDeploy: boolean+}) {+ const { t } = useTranslation('deployments')+ const openDeployDrawer = useSetAtom(openDeployDrawerAtom)++ return (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-server-line"+ title={t('overview.strip.emptyTitle')}+ description={canDeploy ? t('overview.strip.emptyDeployableDescription') : t('overview.strip.emptyDescription')}+ className="min-h-44"+ action={canDeploy+ ? (+ <Button+ type="button"+ variant="primary"+ size="medium"+ className="gap-1.5"+ onClick={() => openDeployDrawer({ appInstanceId })}+ >+ <span className="i-ri-rocket-line size-4 shrink-0" aria-hidden="true" />+ {t('overview.strip.deployToNewEnvironment')}+ </Button>+ )+ : undefined}+ />+ )+}++const SKELETON_KEYS = ['a', 'b', 'c']++function CardSkeletons() {+ return (+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,360px),1fr))] gap-3">+ {SKELETON_KEYS.map(key => (+ <EnvironmentTileSkeleton key={key} />+ ))}+ </div>+ )+}++function EnvironmentTileSkeleton() {+ return (+ <article+ data-slot="deployment-overview-environment-tile-skeleton"+ className={cn(OVERVIEW_CARD_CLASS_NAME, 'flex min-h-28 min-w-0 flex-col justify-between gap-4')}+ >+ <div className="flex min-w-0 items-center justify-between gap-3">+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <SkeletonRectangle className="my-0 size-8 shrink-0 animate-pulse rounded-lg" />+ <SkeletonRectangle className="my-0 h-3.5 w-28 animate-pulse" />+ </div>+ <SkeletonRow className="my-0 h-6 shrink-0 gap-1.5 rounded-md bg-background-section-burn px-2">+ <span className="size-1.5 shrink-0 rounded-full bg-text-quaternary" />+ <span className="h-2.5 w-8 rounded-xs bg-text-quaternary opacity-20" />+ </SkeletonRow>+ </div>++ <div className="flex min-w-0 items-end justify-between gap-3">+ <div className="min-w-0">+ <SkeletonRectangle className="my-0 h-2.5 w-20 animate-pulse" />+ <div className="mt-2 flex min-w-0 items-center gap-2">+ <SkeletonRectangle className="my-0 h-3.5 w-24 animate-pulse" />+ <SkeletonRectangle className="my-0 h-5 w-16 animate-pulse rounded" />+ </div>+ </div>+ <SkeletonRectangle className="my-0 h-8 w-22 shrink-0 animate-pulse rounded-md" />+ </div>+ </article>+ )+}++export function EnvironmentStripSkeleton() {+ const { t } = useTranslation('deployments')++ return (+ <section className="flex flex-col gap-3">+ <h3 className="system-sm-semibold text-text-primary">{t('overview.strip.title')}</h3>+ <CardSkeletons />+ </section>+ )+}diff --git a/web/features/deployments/detail/overview-tab/environment-tile-utils.spec.ts b/web/features/deployments/detail/overview-tab/environment-tile-utils.spec.tsnew file mode 100644index 00000000000..466862a5217--- /dev/null+++ b/web/features/deployments/detail/overview-tab/environment-tile-utils.spec.ts@@ -0,0 +1,143 @@+import type { TFunction } from 'i18next'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { describe, expect, it } from 'vitest'+import {+ renderActionLabel,+ renderDriftTitle,+ renderStatus,+ resolveConfig,+} from './environment-tile-utils'++const t = ((key: string, options?: Record<string, unknown>) => {+ return options ? `${key}:${JSON.stringify(options)}` : key+}) as TFunction<'deployments'>++describe('resolveConfig', () => {+ it('treats undeploying environments as in progress', () => {+ const config = resolveConfig({+ drift: { kind: 'up-to-date' },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING,+ hasAnyRelease: true,+ latestId: 'release-2',+ currentReleaseId: 'release-1',+ })++ expect(config.kind).toBe('deploying')+ expect(config.status).toBe(RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING)+ expect(config.intent).toBe('navigate')+ })++ it('disables empty environments when no release exists', () => {+ const config = resolveConfig({+ drift: { kind: 'undeployed' },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED,+ hasAnyRelease: false,+ latestId: undefined,+ currentReleaseId: undefined,+ })++ expect(config.kind).toBe('empty')+ expect(config.intent).toBe('disabled')+ expect(config.showRelease).toBe(false)+ expect(config.releaseId).toBeUndefined()+ })++ it('opens deploy drawer for undeployed environments when a release exists', () => {+ const config = resolveConfig({+ drift: { kind: 'undeployed' },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED,+ hasAnyRelease: true,+ latestId: 'release-2',+ currentReleaseId: undefined,+ })++ expect(config.kind).toBe('empty')+ expect(config.intent).toBe('drawer')+ expect(config.releaseId).toBe('release-2')+ })++ it('resolves failed environments to the current release first', () => {+ const config = resolveConfig({+ drift: { kind: 'behind', steps: 1 },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED,+ hasAnyRelease: true,+ latestId: 'release-2',+ currentReleaseId: 'release-1',+ })++ expect(config.kind).toBe('failed')+ expect(config.intent).toBe('drawer')+ expect(config.releaseId).toBe('release-1')+ })++ it('resolves up-to-date and behind environments to drawer actions', () => {+ expect(resolveConfig({+ drift: { kind: 'up-to-date' },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ hasAnyRelease: true,+ latestId: 'release-2',+ currentReleaseId: 'release-2',+ })).toMatchObject({+ kind: 'latest',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ intent: 'drawer',+ releaseId: 'release-2',+ })++ expect(resolveConfig({+ drift: { kind: 'behind', steps: 2 },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ hasAnyRelease: true,+ latestId: 'release-3',+ currentReleaseId: 'release-1',+ })).toMatchObject({+ kind: 'behind',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DRIFTED,+ intent: 'drawer',+ releaseId: 'release-3',+ })+ })++ it('treats unknown drift as an older release state', () => {+ const config = resolveConfig({+ drift: { kind: 'unknown' },+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ hasAnyRelease: true,+ latestId: 'release-3',+ currentReleaseId: 'release-1',+ })++ expect(config.kind).toBe('older')+ expect(config.status).toBe(RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED)+ expect(config.intent).toBe('drawer')+ expect(config.releaseId).toBe('release-3')+ })+})++describe('environment tile copy helpers', () => {+ it('renders action labels for deployment states', () => {+ expect(renderActionLabel('empty', false, t)).toBe('overview.cardAction.deployLatest')+ expect(renderActionLabel('older', true, t)).toBe('overview.cardAction.deployLatest')+ expect(renderActionLabel('behind', true, t)).toBe('overview.cardAction.deployLatest')+ expect(renderActionLabel('latest', true, t)).toBe('overview.cardAction.redeploy')+ expect(renderActionLabel('deploying', true, t)).toBe('overview.cardAction.viewProgress')+ expect(renderActionLabel('failed', true, t)).toBe('overview.cardAction.redeploy')+ expect(renderActionLabel('failed', false, t)).toBe('overview.cardAction.deployLatest')+ })++ it('renders status labels and drift titles with counts when needed', () => {+ expect(renderStatus('empty', { kind: 'undeployed' }, t)).toBe('overview.chip.empty')+ expect(renderStatus('latest', { kind: 'up-to-date' }, t)).toBe('overview.chip.latest')+ expect(renderStatus('older', { kind: 'unknown' }, t)).toBe('overview.chip.olderRelease')+ expect(renderStatus('deploying', { kind: 'unknown' }, t)).toBe('overview.chip.deploying')+ expect(renderStatus('failed', { kind: 'unknown' }, t)).toBe('overview.chip.failed')+ expect(renderStatus('behind', { kind: 'behind', steps: 3 }, t)).toBe('overview.chip.behind:{"count":3}')++ expect(renderDriftTitle('latest', { kind: 'up-to-date' }, t)).toBe('overview.chip.latestTooltip')+ expect(renderDriftTitle('behind', { kind: 'behind', steps: 2 }, t)).toBe('overview.chip.behindTooltip:{"count":2}')+ expect(renderDriftTitle('older', { kind: 'unknown' }, t)).toBe('overview.chip.olderReleaseTooltip')+ expect(renderDriftTitle('empty', { kind: 'undeployed' }, t)).toBe('overview.chip.emptyTooltip')+ expect(renderDriftTitle('deploying', { kind: 'unknown' }, t)).toBe('overview.chip.deployingTooltip')+ expect(renderDriftTitle('failed', { kind: 'unknown' }, t)).toBe('overview.chip.failedTooltip')+ })+})diff --git a/web/features/deployments/detail/overview-tab/environment-tile-utils.ts b/web/features/deployments/detail/overview-tab/environment-tile-utils.tsnew file mode 100644index 00000000000..aba4ee23cdd--- /dev/null+++ b/web/features/deployments/detail/overview-tab/environment-tile-utils.ts@@ -0,0 +1,152 @@+import type { RuntimeInstanceStatus as RuntimeInstanceStatusValue } from '@dify/contracts/enterprise/types.gen'+import type { TFunction } from 'i18next'+import type { computeDrift } from './overview-drift'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { isRuntimeDeploymentInProgress } from '../../shared/domain/runtime-status'++export type TileKind = 'empty' | 'latest' | 'behind' | 'older' | 'deploying' | 'failed'++export type TileConfig = {+ kind: TileKind+ status: RuntimeInstanceStatusValue+ actionClass: string+ showRelease: boolean+ intent: 'drawer' | 'navigate' | 'disabled'+ releaseId?: string+}++export function resolveConfig({ drift, status, hasAnyRelease, latestId, currentReleaseId }: {+ drift: ReturnType<typeof computeDrift>+ status: RuntimeInstanceStatusValue+ hasAnyRelease: boolean+ latestId: string | undefined+ currentReleaseId: string | undefined+}): TileConfig {+ if (isRuntimeDeploymentInProgress(status)) {+ return {+ kind: 'deploying',+ status,+ actionClass: 'text-text-secondary hover:bg-state-base-hover hover:text-text-primary',+ showRelease: true,+ intent: 'navigate',+ }+ }++ if (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED) {+ return {+ kind: 'failed',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED,+ actionClass: 'text-primary-600 hover:bg-state-accent-hover',+ showRelease: true,+ intent: 'drawer',+ releaseId: currentReleaseId ?? latestId,+ }+ }++ if (drift.kind === 'undeployed') {+ return {+ kind: 'empty',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED,+ actionClass: hasAnyRelease+ ? 'text-primary-600 hover:bg-state-accent-hover'+ : 'text-text-tertiary',+ showRelease: false,+ intent: hasAnyRelease ? 'drawer' : 'disabled',+ releaseId: latestId,+ }+ }++ if (drift.kind === 'up-to-date') {+ return {+ kind: 'latest',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ actionClass: 'text-text-secondary hover:bg-state-base-hover hover:text-text-primary',+ showRelease: true,+ intent: 'drawer',+ releaseId: currentReleaseId,+ }+ }++ if (drift.kind === 'behind') {+ return {+ kind: 'behind',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DRIFTED,+ actionClass: 'text-primary-600 hover:bg-state-accent-hover',+ showRelease: true,+ intent: 'drawer',+ releaseId: latestId,+ }+ }++ return {+ kind: 'older',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED,+ actionClass: 'text-primary-600 hover:bg-state-accent-hover',+ showRelease: true,+ intent: 'drawer',+ releaseId: latestId,+ }+}++export function renderActionLabel(+ kind: TileKind,+ hasCurrentRelease: boolean,+ t: TFunction<'deployments'>,+): string {+ switch (kind) {+ case 'empty':+ case 'older':+ case 'behind':+ return t('overview.cardAction.deployLatest')+ case 'latest':+ return t('overview.cardAction.redeploy')+ case 'deploying':+ return t('overview.cardAction.viewProgress')+ case 'failed':+ return hasCurrentRelease+ ? t('overview.cardAction.redeploy')+ : t('overview.cardAction.deployLatest')+ }+}++export function renderStatus(+ kind: TileKind,+ drift: ReturnType<typeof computeDrift>,+ t: TFunction<'deployments'>,+): string {+ switch (kind) {+ case 'empty':+ return t('overview.chip.empty')+ case 'latest':+ return t('overview.chip.latest')+ case 'behind':+ return t('overview.chip.behind', { count: drift.kind === 'behind' ? drift.steps : 0 })+ case 'older':+ return t('overview.chip.olderRelease')+ case 'deploying':+ return t('overview.chip.deploying')+ case 'failed':+ return t('overview.chip.failed')+ }+}++export function renderDriftTitle(+ kind: TileKind,+ drift: ReturnType<typeof computeDrift>,+ t: TFunction<'deployments'>,+): string {+ switch (kind) {+ case 'latest':+ return t('overview.chip.latestTooltip')+ case 'behind':+ return t('overview.chip.behindTooltip', { count: drift.kind === 'behind' ? drift.steps : 0 })+ case 'older':+ return t('overview.chip.olderReleaseTooltip')+ case 'empty':+ return t('overview.chip.emptyTooltip')+ case 'deploying':+ return t('overview.chip.deployingTooltip')+ case 'failed':+ return t('overview.chip.failedTooltip')+ }+}diff --git a/web/features/deployments/detail/overview-tab/environment-tile.tsx b/web/features/deployments/detail/overview-tab/environment-tile.tsxnew file mode 100644index 00000000000..ae35cc2c973--- /dev/null+++ b/web/features/deployments/detail/overview-tab/environment-tile.tsx@@ -0,0 +1,170 @@+'use client'++import type {+ EnvironmentDeployment,+ Release,+ RuntimeInstanceStatus as RuntimeInstanceStatusValue,+} from '@dify/contracts/enterprise/types.gen'+import type { TileConfig } from './environment-tile-utils'+import { cn } from '@langgenius/dify-ui/cn'+import { useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import Link from '@/next/link'+import { TitleTooltip } from '../../components/title-tooltip'+import { openDeployDrawerAtom } from '../../deploy-drawer/state'+import { releaseCommit } from '../../shared/domain/release'+import { DeploymentStatusBadge } from '../../shared/ui/deployment-status-badge'+import {+ deploymentStatusLabelKey,+} from '../../shared/ui/deployment-status-style'+import { OVERVIEW_ICON_CLASS_NAME, OVERVIEW_INTERACTIVE_CARD_CLASS_NAME } from './card-styles'+import {+ renderActionLabel,+ renderDriftTitle,+ renderStatus,+ resolveConfig,+} from './environment-tile-utils'+import { computeDrift, latestReleaseId } from './overview-drift'++type EnvironmentTileProps = {+ appInstanceId: string+ row: EnvironmentDeployment+ releaseRows: Release[]+}++export function EnvironmentTile({ appInstanceId, row, releaseRows }: EnvironmentTileProps) {+ const { t } = useTranslation('deployments')+ const openDeployDrawer = useSetAtom(openDeployDrawerAtom)++ const envId = row.environment.id+ const drift = computeDrift(row)+ const status = row.status+ const latestId = latestReleaseId(releaseRows)+ const hasAnyRelease = releaseRows.length > 0+ const currentReleaseId = row.currentRelease?.id+ const config = resolveConfig({ drift, status, hasAnyRelease, latestId, currentReleaseId })+ const isDisabled = config.intent === 'disabled'+ const showStatusSignal = config.kind !== 'deploying'+ const release = row.currentRelease+ const showRelease = config.showRelease && release+ const commit = releaseCommit(release)+ const tooltip = isDisabled+ ? t('overview.chip.needsReleaseFirst')+ : config.intent === 'navigate'+ ? t('overview.chip.openInDeployTab')+ : undefined++ function handleDrawerAction() {+ if (config.intent === 'disabled')+ return+ openDeployDrawer({ appInstanceId, environmentId: envId, releaseId: config.releaseId })+ }++ const actionClassName = cn(+ 'inline-flex h-8 max-w-full min-w-0 shrink-0 items-center justify-center rounded-md px-2.5 system-xs-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-components-button-primary-bg',+ config.actionClass,+ isDisabled && 'cursor-not-allowed opacity-60',+ )+ const actionLabel = renderActionLabel(config.kind, Boolean(currentReleaseId), t)+ const actionControl = config.intent === 'navigate'+ ? (+ <Link+ href={`/deployments/${appInstanceId}/instances`}+ className={actionClassName}+ >+ <span className="whitespace-nowrap">{actionLabel}</span>+ </Link>+ )+ : (+ <button+ type="button"+ disabled={isDisabled}+ onClick={handleDrawerAction}+ className={actionClassName}+ >+ <span className="whitespace-nowrap">{actionLabel}</span>+ </button>+ )++ return (+ <article+ data-slot="deployment-overview-environment-tile"+ className={cn(OVERVIEW_INTERACTIVE_CARD_CLASS_NAME, 'flex min-h-28 min-w-0 flex-col justify-between gap-4')}+ >+ <div className="flex min-w-0 items-center justify-between gap-3">+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <span aria-hidden className={OVERVIEW_ICON_CLASS_NAME}>+ <span className="i-ri-server-line size-4" />+ </span>+ <h4 className="truncate system-sm-medium text-text-primary">+ {row.environment.displayName}+ </h4>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <RuntimeStatusSignal status={status} t={t} />+ {showStatusSignal && <StatusSignal config={config} drift={drift} t={t} />}+ </div>+ </div>++ <div className="flex min-w-0 items-end justify-between gap-3">+ <div className="min-w-0">+ <div className="system-2xs-medium-uppercase text-text-tertiary">+ {t('deployTab.col.currentRelease')}+ </div>+ <div className="mt-1 flex min-w-0 items-center gap-2">+ <span className="min-w-0 truncate system-sm-semibold text-text-primary">+ {showRelease ? showRelease.displayName : '—'}+ </span>+ {showRelease && commit !== '—' && (+ <span className="shrink-0 rounded bg-background-section-burn px-1.5 py-0.5 font-mono system-xs-regular text-text-tertiary">+ {commit}+ </span>+ )}+ </div>+ </div>++ {tooltip+ ? (+ <TitleTooltip content={tooltip}>+ <span className="inline-flex max-w-full min-w-0 shrink-0">+ {actionControl}+ </span>+ </TitleTooltip>+ )+ : actionControl}+ </div>+ </article>+ )+}++function RuntimeStatusSignal({ status, t }: {+ status: RuntimeInstanceStatusValue+ t: ReturnType<typeof useTranslation<'deployments'>>['t']+}) {+ const label = t(deploymentStatusLabelKey(status))++ return (+ <TitleTooltip content={label}>+ <DeploymentStatusBadge status={status} label={label} />+ </TitleTooltip>+ )+}++function StatusSignal({ className, config, drift, t }: {+ className?: string+ config: TileConfig+ drift: ReturnType<typeof computeDrift>+ t: ReturnType<typeof useTranslation<'deployments'>>['t']+}) {+ const title = renderDriftTitle(config.kind, drift, t)++ return (+ <TitleTooltip content={title}>+ <DeploymentStatusBadge+ status={config.status}+ label={renderStatus(config.kind, drift, t)}+ className={className}+ />+ </TitleTooltip>+ )+}diff --git a/web/features/deployments/detail/overview-tab/overview-drift.ts b/web/features/deployments/detail/overview-tab/overview-drift.tsnew file mode 100644index 00000000000..862b1fd553c--- /dev/null+++ b/web/features/deployments/detail/overview-tab/overview-drift.ts@@ -0,0 +1,29 @@+import type { EnvironmentDeployment, Release } from '@dify/contracts/enterprise/types.gen'+import { isUndeployedDeploymentRow } from '../../shared/domain/runtime-status'++export type Drift+ = | { kind: 'undeployed' }+ | { kind: 'unknown' }+ | { kind: 'up-to-date' }+ | { kind: 'behind', steps: number }++export function computeDrift(row: EnvironmentDeployment): Drift {+ if (isUndeployedDeploymentRow(row))+ return { kind: 'undeployed' }++ if (!row.currentRelease)+ return { kind: 'unknown' }++ // releasesBehind is server-computed against the full release history (0 == up+ // to date). It is absent only when undetermined, which renders as unknown.+ const behind = row.releasesBehind+ if (behind == null)+ return { kind: 'unknown' }+ if (behind === 0)+ return { kind: 'up-to-date' }+ return { kind: 'behind', steps: behind }+}++export function latestReleaseId(releaseRows: Release[]): string | undefined {+ return releaseRows[0]?.id+}diff --git a/web/features/deployments/detail/overview-tab/release-hero.tsx b/web/features/deployments/detail/overview-tab/release-hero.tsxnew file mode 100644index 00000000000..b275b4b48d4--- /dev/null+++ b/web/features/deployments/detail/overview-tab/release-hero.tsx@@ -0,0 +1,168 @@+'use client'++import type { Release } from '@dify/contracts/enterprise/types.gen'+import type { ReactNode } from 'react'+import { ReleaseSource } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import Link from '@/next/link'+import { consoleQuery } from '@/service/client'+import { DeploymentEmptyState } from '../../components/empty-state'+import { TitleTooltip } from '../../components/title-tooltip'+import { CreateReleaseControl } from '../../create-release'+import { formatDate, releaseCommit } from '../../shared/domain/release'+import { OVERVIEW_CARD_CLASS_NAME, OVERVIEW_ICON_CLASS_NAME } from './card-styles'++type ReleaseHeroProps = {+ appInstanceId: string+ latestRelease?: Release+ releaseCount: number+}++type ReleaseMetaItemProps = {+ label?: string+ showSeparator?: boolean+ children: ReactNode+}++export function ReleaseHero({ appInstanceId, latestRelease, releaseCount }: ReleaseHeroProps) {+ const { t } = useTranslation('deployments')+ const { formatTimeFromNow } = useFormatTimeFromNow()++ if (!latestRelease) {+ return (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-stack-line"+ title={t('overview.hero.empty')}+ description={t('overview.hero.emptyDescription')}+ action={<CreateReleaseControl appInstanceId={appInstanceId} size="medium" />}+ className="min-h-44"+ />+ )+ }++ const author = latestRelease.createdBy.displayName+ const ago = formatTimeFromNow(new Date(latestRelease.createdAt).getTime())+ const createdAtTitle = formatDate(latestRelease.createdAt)+ const commit = releaseCommit(latestRelease)++ return (+ <div className={cn(OVERVIEW_CARD_CLASS_NAME, 'flex min-w-0 flex-col gap-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6')}>+ <div className="flex min-w-0 items-center gap-3">+ <span aria-hidden className={OVERVIEW_ICON_CLASS_NAME}>+ <span className="i-ri-stack-fill size-4" />+ </span>+ <div className="flex min-w-0 flex-col gap-1.5">+ <div className="flex min-w-0 items-center gap-2">+ <h4 className="truncate system-sm-semibold text-text-primary">+ {latestRelease.displayName}+ </h4>+ {commit !== '—' && (+ <TitleTooltip content={t('versions.commitTooltip', { commit })}>+ <span className="shrink-0 rounded bg-background-section-burn px-1.5 py-0.5 font-mono system-xs-regular text-text-tertiary">+ {commit}+ </span>+ </TitleTooltip>+ )}+ </div>+ <p className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 system-xs-regular text-text-tertiary">+ <ReleaseMetaItem label={t('versions.col.sourceApp')} showSeparator={false}>+ <LatestReleaseSource release={latestRelease} />+ </ReleaseMetaItem>+ {author && (+ <ReleaseMetaItem>+ {t('overview.hero.byName', { name: author })}+ </ReleaseMetaItem>+ )}+ {ago && (+ <ReleaseMetaItem>+ <TitleTooltip content={createdAtTitle}>+ <span>+ {ago}+ </span>+ </TitleTooltip>+ </ReleaseMetaItem>+ )}+ <ReleaseMetaItem>+ {t('overview.latestRelease.releaseCount', { count: releaseCount })}+ </ReleaseMetaItem>+ </p>+ </div>+ </div>+ </div>+ )+}++function ReleaseMetaItem({ label, showSeparator = true, children }: ReleaseMetaItemProps) {+ return (+ <span className="inline-flex min-w-0 items-center gap-1.5">+ {showSeparator && (+ <span aria-hidden className="text-text-quaternary">·</span>+ )}+ {label && (+ <span className="shrink-0 text-text-quaternary">{label}</span>+ )}+ <span className="min-w-0 truncate">{children}</span>+ </span>+ )+}++function LatestReleaseSource({ release }: {+ release: Release+}) {+ const { t } = useTranslation('deployments')+ const sourceAppId = release.sourceAppId+ const sourceAppQuery = useQuery(consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: sourceAppId ?? '' } },+ enabled: Boolean(sourceAppId),+ }))++ if (!sourceAppId) {+ return (+ <span>+ {release.source === ReleaseSource.RELEASE_SOURCE_UPLOAD ? t('versions.manualDslOption') : '—'}+ </span>+ )+ }++ const sourceAppName = sourceAppQuery.data?.name+ const label = sourceAppName || sourceAppId+ const title = sourceAppName ? `${sourceAppName} (${sourceAppId})` : sourceAppId++ return (+ <TitleTooltip content={title}>+ <Link+ href={`/app/${encodeURIComponent(sourceAppId)}/workflow`}+ target="_blank"+ rel="noreferrer"+ className="inline-flex max-w-full min-w-0 items-center gap-1 text-text-secondary transition-colors hover:text-text-accent"+ >+ <span className="min-w-0 truncate">{label}</span>+ <span className="i-ri-arrow-right-up-line size-3.5 shrink-0" aria-hidden="true" />+ </Link>+ </TitleTooltip>+ )+}++export function ReleaseHeroSkeleton() {+ return (+ <div+ data-slot="deployment-overview-release-hero-skeleton"+ className={cn(OVERVIEW_CARD_CLASS_NAME, 'flex min-w-0 items-start gap-3')}+ >+ <SkeletonRectangle className="my-0 size-8 shrink-0 animate-pulse rounded-lg" />+ <div className="flex min-w-0 flex-col gap-2">+ <SkeletonRectangle className="my-0 h-4 w-40 animate-pulse" />+ <div className="flex min-w-0 flex-wrap items-baseline gap-x-1.5 gap-y-1">+ <SkeletonRectangle className="my-0 h-3 w-32 animate-pulse" />+ <SkeletonRectangle className="my-0 h-3 w-14 animate-pulse" />+ <SkeletonRectangle className="my-0 h-3 w-28 animate-pulse" />+ </div>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/__tests__/access-policy.spec.ts b/web/features/deployments/detail/settings-tab/access/__tests__/access-policy.spec.tsnew file mode 100644index 00000000000..4a6bce99f87--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/__tests__/access-policy.spec.ts@@ -0,0 +1,159 @@+import type {+ AccessPolicy,+ Subject,+} from '@dify/contracts/enterprise/types.gen'+import { AccessMode, SubjectType } from '@dify/contracts/enterprise/types.gen'+import { describe, expect, it } from 'vitest'+import { AccessMode as AppAccessMode } from '@/models/access-control'+import {+ accessControlSelectionFromSubjects,+ accessModeToPermissionKey,+ appAccessModeToPermissionKey,+ normalizeResolvedSubject,+ permissionKeyToAccessMode,+ permissionKeyToAppAccessMode,+ policySubjects,+ selectedSubjectsFromPolicy,+ subjectsFromAccessControlSelection,+} from '../access-policy'++function policy(overrides: Partial<AccessPolicy>): AccessPolicy {+ return {+ id: 'policy-1',+ appInstanceId: 'app-instance-1',+ environmentId: 'environment-1',+ mode: AccessMode.ACCESS_MODE_PRIVATE_ALL,+ subjects: [],+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ ...overrides,+ }+}++describe('access policy mode mapping', () => {+ it('should map API access modes to deployment permission keys', () => {+ expect(accessModeToPermissionKey(AccessMode.ACCESS_MODE_PRIVATE)).toBe('specific')+ expect(accessModeToPermissionKey(AccessMode.ACCESS_MODE_PUBLIC)).toBe('anyone')+ expect(accessModeToPermissionKey(AccessMode.ACCESS_MODE_PRIVATE_ALL)).toBe('organization')+ expect(accessModeToPermissionKey()).toBe('organization')+ })++ it('should map permission keys to API and app access modes', () => {+ expect(permissionKeyToAccessMode('organization')).toBe(AccessMode.ACCESS_MODE_PRIVATE_ALL)+ expect(permissionKeyToAccessMode('specific')).toBe(AccessMode.ACCESS_MODE_PRIVATE)+ expect(permissionKeyToAccessMode('anyone')).toBe(AccessMode.ACCESS_MODE_PUBLIC)++ expect(permissionKeyToAppAccessMode('organization')).toBe(AppAccessMode.ORGANIZATION)+ expect(permissionKeyToAppAccessMode('specific')).toBe(AppAccessMode.SPECIFIC_GROUPS_MEMBERS)+ expect(permissionKeyToAppAccessMode('anyone')).toBe(AppAccessMode.PUBLIC)++ expect(appAccessModeToPermissionKey(AppAccessMode.SPECIFIC_GROUPS_MEMBERS)).toBe('specific')+ expect(appAccessModeToPermissionKey(AppAccessMode.PUBLIC)).toBe('anyone')+ expect(appAccessModeToPermissionKey(AppAccessMode.ORGANIZATION)).toBe('organization')+ })+})++describe('access policy subject conversion', () => {+ it('should normalize resolved group and account subjects', () => {+ expect(normalizeResolvedSubject({+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ groupData: {+ id: 'group-1',+ name: 'Admins',+ groupSize: 3,+ },+ })).toEqual({+ id: 'group-1',+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ name: 'Admins',+ memberCount: 3,+ })++ expect(normalizeResolvedSubject({+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ accountData: {+ id: 'account-1',+ email: '[email protected]',+ },+ })).toEqual({+ id: 'account-1',+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ name: '[email protected]',+ })+ })++ it('should ignore unsupported subjects and subjects without ids', () => {+ expect(normalizeResolvedSubject({ subjectType: SubjectType.SUBJECT_TYPE_GROUP })).toBeUndefined()+ expect(normalizeResolvedSubject({ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT })).toBeUndefined()+ expect(normalizeResolvedSubject({ subjectType: SubjectType.SUBJECT_TYPE_UNSPECIFIED } as Subject)).toBeUndefined()+ })++ it('should preserve labels when reading selected subjects from policy', () => {+ expect(selectedSubjectsFromPolicy(policy({+ subjects: [+ { subjectId: 'group-1', subjectType: SubjectType.SUBJECT_TYPE_GROUP },+ { subjectId: 'account-1', subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT },+ ],+ }), [+ {+ id: 'group-1',+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ name: 'Admins',+ memberCount: 3,+ },+ ])).toEqual([+ {+ id: 'group-1',+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ name: 'Admins',+ memberCount: 3,+ },+ {+ id: 'account-1',+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ },+ ])++ expect(selectedSubjectsFromPolicy()).toEqual([])+ })++ it('should convert between deployment subjects and access-control selections', () => {+ const subjects = [+ {+ id: 'group-1',+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ name: 'Admins',+ memberCount: 3,+ },+ {+ id: 'account-1',+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ name: 'Member',+ },+ ]++ expect(policySubjects(subjects)).toEqual([+ { subjectId: 'group-1', subjectType: SubjectType.SUBJECT_TYPE_GROUP },+ { subjectId: 'account-1', subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT },+ ])++ const selection = accessControlSelectionFromSubjects(subjects)+ expect(selection.groups).toEqual([+ {+ id: 'group-1',+ name: 'Admins',+ groupSize: 3,+ },+ ])+ expect(selection.members).toEqual([+ {+ id: 'account-1',+ name: 'Member',+ email: 'Member',+ avatar: '',+ avatarUrl: '',+ },+ ])+ expect(subjectsFromAccessControlSelection(selection)).toEqual(subjects)+ })+})diff --git a/web/features/deployments/detail/settings-tab/access/__tests__/api-key-generate-menu.spec.tsx b/web/features/deployments/detail/settings-tab/access/__tests__/api-key-generate-menu.spec.tsxnew file mode 100644index 00000000000..6d7d03bc94c--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/__tests__/api-key-generate-menu.spec.tsx@@ -0,0 +1,51 @@+import type { Environment } from '@dify/contracts/enterprise/types.gen'+import { fireEvent, render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { ApiKeyGenerateMenu } from '../api-key-generate-menu'++const mockMutate = vi.fn()+const mockUseMutation = vi.hoisted(() => vi.fn())++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useMutation: (...args: unknown[]) => mockUseMutation(...args),+ }+})++function createEnvironment(): Environment {+ return {+ id: 'environment-1',+ displayName: 'Production',+ } as Environment+}++describe('ApiKeyGenerateMenu', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseMutation.mockReturnValue({+ isPending: false,+ mutate: mockMutate,+ })+ })++ it('should show the required name error when submitting an empty name', () => {+ render(+ <ApiKeyGenerateMenu+ appInstanceId="app-instance-1"+ environments={[createEnvironment()]}+ onCreatedToken={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'deployments.access.api.newKey' }))+ fireEvent.change(screen.getByLabelText('deployments.access.api.nameLabel'), {+ target: { value: ' ' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'deployments.access.api.createKey' }))++ expect(screen.getByText('deployments.access.api.nameRequired')).toBeInTheDocument()+ expect(mockMutate).not.toHaveBeenCalled()+ })+})diff --git a/web/features/deployments/detail/settings-tab/access/__tests__/channels-section.spec.tsx b/web/features/deployments/detail/settings-tab/access/__tests__/channels-section.spec.tsxnew file mode 100644index 00000000000..730380b4284--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/__tests__/channels-section.spec.tsx@@ -0,0 +1,62 @@+import type { AccessChannels, AccessEndpoint } from '@dify/contracts/enterprise/types.gen'+import { render, screen } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { AccessChannelsSection } from '../channels-section'++const mockUseMutation = vi.hoisted(() => vi.fn())++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useMutation: (...args: unknown[]) => mockUseMutation(...args),+ }+})++function createAccessChannels(): AccessChannels {+ return {+ id: 'access-channels-1',+ appInstanceId: 'app-instance-1',+ webAppEnabled: true,+ developerApiEnabled: false,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ } as AccessChannels+}++function createEndpoint(endpointUrl: string): AccessEndpoint {+ return {+ environment: {+ id: 'environment-1',+ displayName: 'Production',+ },+ endpointUrl,+ } as AccessEndpoint+}++// Access channel rows keep their title, description, and endpoint content together.+describe('AccessChannelsSection', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseMutation.mockReturnValue({+ isPending: false,+ mutate: vi.fn(),+ })+ })++ it('should render channel descriptions when access channels are enabled', () => {+ render(+ <AccessChannelsSection+ appInstanceId="app-instance-1"+ accessChannels={createAccessChannels()}+ webAppEndpoints={[createEndpoint('https://app.example.com/webapp')]}+ cliEndpoint={createEndpoint('https://cli.example.com/entry')}+ isLoading={false}+ isError={false}+ />,+ )++ expect(screen.getByText('deployments.access.runAccess.webappDesc')).toBeInTheDocument()+ expect(screen.getByText('deployments.access.cli.description')).toBeInTheDocument()+ })+})diff --git a/web/features/deployments/detail/settings-tab/access/__tests__/permissions.spec.tsx b/web/features/deployments/detail/settings-tab/access/__tests__/permissions.spec.tsxnew file mode 100644index 00000000000..489550127b1--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/__tests__/permissions.spec.tsx@@ -0,0 +1,134 @@+import type { AccessPolicy, Environment, EnvironmentAccessPolicy } from '@dify/contracts/enterprise/types.gen'+import { AccessMode, SubjectType } from '@dify/contracts/enterprise/types.gen'+import { fireEvent, render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { EnvironmentPermissionRow } from '../permissions'+import { AccessPermissionsSection } from '../permissions-section'++const mockMutate = vi.fn()+const mockUseMutation = vi.hoisted(() => vi.fn())++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useMutation: (...args: unknown[]) => mockUseMutation(...args),+ }+})++function createEnvironment(overrides: Partial<Environment> = {}): Environment {+ return {+ id: 'environment-1',+ displayName: 'Production',+ ...overrides,+ } as Environment+}++function createAccessPolicy(): AccessPolicy {+ return {+ id: 'policy-1',+ appInstanceId: 'app-instance-1',+ environmentId: 'environment-1',+ mode: AccessMode.ACCESS_MODE_PRIVATE_ALL,+ subjects: [],+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }+}++function createSpecificAccessPolicy(): AccessPolicy {+ return {+ ...createAccessPolicy(),+ mode: AccessMode.ACCESS_MODE_PRIVATE,+ subjects: [+ {+ subjectId: 'group-1',+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ },+ {+ subjectId: 'member-1',+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ },+ ],+ }+}++function createEnvironmentAccessPolicy(): EnvironmentAccessPolicy {+ return {+ environment: createEnvironment(),+ policy: createAccessPolicy(),+ resolvedSubjects: [],+ }+}++describe('EnvironmentPermissionRow', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockMutate.mockImplementation((_variables: unknown, options?: { onError?: () => void }) => {+ options?.onError?.()+ })+ mockUseMutation.mockReturnValue({+ isPending: false,+ mutate: mockMutate,+ })+ })++ it('should keep the previous permission visible when updating the policy fails', () => {+ render(+ <EnvironmentPermissionRow+ appInstanceId="app-instance-1"+ environment={createEnvironment()}+ summaryPolicy={createAccessPolicy()}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /deployments\.access\.permissions\.editAriaLabel/ }))+ fireEvent.click(screen.getByRole('radio', { name: 'app.accessControlDialog.accessItems.anyone' }))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))++ expect(mockMutate).toHaveBeenCalled()+ expect(screen.getByText('deployments.access.permission.organization')).toBeInTheDocument()+ })++ it('should show specific subject counts in the access summary', () => {+ render(+ <EnvironmentPermissionRow+ appInstanceId="app-instance-1"+ environment={createEnvironment()}+ summaryPolicy={createSpecificAccessPolicy()}+ />,+ )++ const editButton = screen.getByRole('button', { name: /deployments\.access\.permissions\.editAriaLabel/ })++ expect(editButton).toHaveTextContent('deployments.access.permission.specific')+ expect(editButton).toHaveTextContent('deployments.access.members.groupCount:{"count":1}')+ expect(editButton).toHaveTextContent('deployments.access.members.memberCount:{"count":1}')+ })+})++// Access permissions render as simple environment rows without a table header.+describe('AccessPermissionsSection', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseMutation.mockReturnValue({+ isPending: false,+ mutate: mockMutate,+ })+ })++ it('should render permission rows without column headers', () => {+ render(+ <AccessPermissionsSection+ appInstanceId="app-instance-1"+ environmentPolicies={[createEnvironmentAccessPolicy()]}+ isLoading={false}+ isError={false}+ />,+ )++ expect(screen.getByText('Production')).toBeInTheDocument()+ expect(screen.queryByText('deployments.access.permissions.col.environment')).not.toBeInTheDocument()+ expect(screen.queryByText('deployments.access.permissions.col.permission')).not.toBeInTheDocument()+ })+})diff --git a/web/features/deployments/detail/settings-tab/access/access-policy.ts b/web/features/deployments/detail/settings-tab/access/access-policy.tsnew file mode 100644index 00000000000..d18707a1167--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/access-policy.ts@@ -0,0 +1,169 @@+import type {+ AccessPolicy,+ AccessMode as AccessPolicyMode,+ AccessSubject,+ SubjectType as AccessSubjectType,+ Subject,+} from '@dify/contracts/enterprise/types.gen'+import type { AccessSubjectSelectionValue } from '@/app/components/app/app-access-control/access-subject-selector/types'+import type {+ AccessControlAccount,+ AccessControlGroup,+} from '@/models/access-control'+import {+ AccessMode,+ SubjectType,+} from '@dify/contracts/enterprise/types.gen'+import { AccessMode as AppAccessMode } from '@/models/access-control'++export type AccessPermissionKind = 'organization' | 'specific' | 'anyone'++export const permissionIcon: Record<AccessPermissionKind, string> = {+ organization: 'i-ri-building-line',+ specific: 'i-ri-lock-line',+ anyone: 'i-ri-global-line',+}++export type SelectableAccessSubject = {+ id: string+ subjectType: AccessSubjectType+ name?: string+ memberCount?: number+}++export function accessModeToPermissionKey(mode?: AccessPolicy['mode']): AccessPermissionKind {+ if (mode === AccessMode.ACCESS_MODE_PRIVATE)+ return 'specific'+ if (mode === AccessMode.ACCESS_MODE_PUBLIC)+ return 'anyone'+ return 'organization'+}++export function permissionKeyToAccessMode(key: AccessPermissionKind): AccessPolicyMode {+ if (key === 'organization')+ return AccessMode.ACCESS_MODE_PRIVATE_ALL+ if (key === 'specific')+ return AccessMode.ACCESS_MODE_PRIVATE+ return AccessMode.ACCESS_MODE_PUBLIC+}++export function permissionKeyToAppAccessMode(key: AccessPermissionKind): AppAccessMode {+ if (key === 'organization')+ return AppAccessMode.ORGANIZATION+ if (key === 'specific')+ return AppAccessMode.SPECIFIC_GROUPS_MEMBERS+ return AppAccessMode.PUBLIC+}++export function appAccessModeToPermissionKey(mode: AppAccessMode): AccessPermissionKind {+ if (mode === AppAccessMode.SPECIFIC_GROUPS_MEMBERS)+ return 'specific'+ if (mode === AppAccessMode.PUBLIC)+ return 'anyone'+ return 'organization'+}++export function normalizeResolvedSubject(subject: Subject): SelectableAccessSubject | undefined {+ if (subject.subjectType === SubjectType.SUBJECT_TYPE_GROUP) {+ const id = subject.subjectId || subject.groupData?.id+ if (!id)+ return undefined++ return {+ id,+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ name: subject.groupData?.name,+ memberCount: subject.groupData?.groupSize,+ }+ }++ if (subject.subjectType === SubjectType.SUBJECT_TYPE_ACCOUNT) {+ const id = subject.subjectId || subject.accountData?.id+ if (!id)+ return undefined++ return {+ id,+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ name: subject.accountData?.name || subject.accountData?.email,+ }+ }++ return undefined+}++function getSubjectLabel(subject: SelectableAccessSubject) {+ return subject.name || subject.id+}++export function policySubjects(subjects: SelectableAccessSubject[]): AccessSubject[] {+ return subjects.map(subject => ({+ subjectId: subject.id,+ subjectType: subject.subjectType,+ }))+}++export function selectedSubjectsFromPolicy(policy?: AccessPolicy, labelSubjects: SelectableAccessSubject[] = []) {+ if (!policy)+ return []++ return policy.subjects+ .map((subject): SelectableAccessSubject => {+ const matchedSubject = labelSubjects.find(labelSubject =>+ labelSubject.id === subject.subjectId && labelSubject.subjectType === subject.subjectType,+ )+ return {+ id: subject.subjectId,+ subjectType: subject.subjectType,+ name: matchedSubject?.name,+ memberCount: matchedSubject?.memberCount,+ }+ })+}++function selectableSubjectToGroup(subject: SelectableAccessSubject): AccessControlGroup {+ return {+ id: subject.id,+ name: getSubjectLabel(subject),+ groupSize: subject.memberCount ?? 0,+ }+}++function selectableSubjectToAccount(subject: SelectableAccessSubject): AccessControlAccount {+ const label = getSubjectLabel(subject)++ return {+ id: subject.id,+ name: label,+ email: label,+ avatar: '',+ avatarUrl: '',+ }+}++export function accessControlSelectionFromSubjects(subjects: SelectableAccessSubject[]): AccessSubjectSelectionValue {+ return {+ groups: subjects+ .filter(subject => subject.subjectType === SubjectType.SUBJECT_TYPE_GROUP)+ .map(selectableSubjectToGroup),+ members: subjects+ .filter(subject => subject.subjectType === SubjectType.SUBJECT_TYPE_ACCOUNT)+ .map(selectableSubjectToAccount),+ }+}++export function subjectsFromAccessControlSelection(value: AccessSubjectSelectionValue): SelectableAccessSubject[] {+ return [+ ...value.groups.map((group): SelectableAccessSubject => ({+ id: group.id,+ subjectType: SubjectType.SUBJECT_TYPE_GROUP,+ name: group.name,+ memberCount: group.groupSize,+ })),+ ...value.members.map((member): SelectableAccessSubject => ({+ id: member.id,+ subjectType: SubjectType.SUBJECT_TYPE_ACCOUNT,+ name: member.name || member.email,+ })),+ ]+}diff --git a/web/features/deployments/detail/settings-tab/access/api-docs-drawer.tsx b/web/features/deployments/detail/settings-tab/access/api-docs-drawer.tsxnew file mode 100644index 00000000000..fb88bf0c9cf--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/api-docs-drawer.tsx@@ -0,0 +1,130 @@+'use client'++import type { App } from '@/types/app'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Drawer,+ DrawerBackdrop,+ DrawerCloseButton,+ DrawerContent,+ DrawerDescription,+ DrawerPopup,+ DrawerPortal,+ DrawerTitle,+ DrawerViewport,+} from '@langgenius/dify-ui/drawer'+import { useTranslation } from 'react-i18next'+import TemplateWorkflowEn from '@/app/components/develop/template/template_workflow.en.mdx'+import TemplateWorkflowJa from '@/app/components/develop/template/template_workflow.ja.mdx'+import TemplateWorkflowZh from '@/app/components/develop/template/template_workflow.zh.mdx'+import { useLocale } from '@/context/i18n'+import useTheme from '@/hooks/use-theme'+import { getDocLanguage } from '@/i18n-config/language'+import { AppModeEnum, Theme } from '@/types/app'++type PromptVariable = { key: string, name: string }+type WorkflowApiDocAppDetail = Pick<App, 'id' | 'mode' | 'api_base_url'>++type WorkflowDocTemplateProps = {+ appDetail: WorkflowApiDocAppDetail+ variables: PromptVariable[]+ inputs: Record<string, string>+}++const EMPTY_VARIABLES: PromptVariable[] = []+const EMPTY_INPUTS: Record<string, string> = {}++function WorkflowDocTemplate({ docLanguage, appDetail, variables, inputs }: WorkflowDocTemplateProps & {+ docLanguage: string+}) {+ if (docLanguage === 'zh') {+ return (+ <TemplateWorkflowZh+ appDetail={appDetail}+ variables={variables}+ inputs={inputs}+ />+ )+ }+ if (docLanguage === 'ja') {+ return (+ <TemplateWorkflowJa+ appDetail={appDetail}+ variables={variables}+ inputs={inputs}+ />+ )+ }++ return (+ <TemplateWorkflowEn+ appDetail={appDetail}+ variables={variables}+ inputs={inputs}+ />+ )+}++export function DeveloperApiDocsDrawer({+ open,+ appInstanceId,+ apiBaseUrl,+ onOpenChange,+}: {+ open: boolean+ appInstanceId: string+ apiBaseUrl: string+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('deployments')+ const locale = useLocale()+ const { theme } = useTheme()+ const docLanguage = getDocLanguage(locale)+ const appDetail: WorkflowApiDocAppDetail = {+ id: appInstanceId,+ mode: AppModeEnum.WORKFLOW,+ api_base_url: apiBaseUrl,+ }++ return (+ <Drawer+ open={open}+ modal+ swipeDirection="right"+ onOpenChange={onOpenChange}+ >+ <DrawerPortal>+ <DrawerBackdrop />+ <DrawerViewport>+ <DrawerPopup className="data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-[840px] data-[swipe-direction=right]:max-w-[calc(100vw-1rem)] data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border-[0.5px]">+ <DrawerCloseButton+ aria-label={t('access.api.docsClose')}+ className="absolute top-4 right-5 size-6 rounded-md"+ />+ <DrawerContent className="flex min-h-0 flex-1 flex-col bg-components-panel-bg p-0 pb-0">+ <div className="shrink-0 border-b border-divider-subtle px-6 py-5 pr-14">+ <DrawerTitle className="title-xl-semi-bold text-text-primary">+ {t('access.api.docsTitle')}+ </DrawerTitle>+ <DrawerDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('access.api.docsDescription')}+ </DrawerDescription>+ </div>++ <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-6 py-5">+ <article className={cn('prose max-w-none', theme === Theme.dark && 'prose-invert')}>+ <WorkflowDocTemplate+ docLanguage={docLanguage}+ appDetail={appDetail}+ variables={EMPTY_VARIABLES}+ inputs={EMPTY_INPUTS}+ />+ </article>+ </div>+ </DrawerContent>+ </DrawerPopup>+ </DrawerViewport>+ </DrawerPortal>+ </Drawer>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/api-key-generate-menu.tsx b/web/features/deployments/detail/settings-tab/access/api-key-generate-menu.tsxnew file mode 100644index 00000000000..e004d36ff13--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/api-key-generate-menu.tsx@@ -0,0 +1,237 @@+'use client'++import type { Environment } from '@dify/contracts/enterprise/types.gen'+import type { ButtonProps } from '@langgenius/dify-ui/button'+import type { FormEvent, ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { Input } from '@langgenius/dify-ui/input'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectLabel,+ SelectTrigger,+} from '@langgenius/dify-ui/select'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useEffect, useId, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { generateApiTokenName } from './api-token-name'++export function ApiKeyGenerateMenu({+ appInstanceId,+ environments,+ onCreatedToken,+ triggerVariant = 'secondary',+ triggerClassName,+ children,+}: {+ appInstanceId: string+ environments: Environment[]+ onCreatedToken: (token: string) => void+ triggerVariant?: ButtonProps['variant']+ triggerClassName?: string+ children?: (props: { trigger: ReactNode }) => ReactNode+}) {+ const { t } = useTranslation('deployments')+ const nameInputId = useId()+ const nameInputRef = useRef<HTMLInputElement>(null)+ const [createDialogOpen, setCreateDialogOpen] = useState(false)+ const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string>()+ const [draftName, setDraftName] = useState('')+ const [nameError, setNameError] = useState(false)+ const generateApiKey = useMutation(consoleQuery.enterprise.accessService.createApiKey.mutationOptions())+ const selectableEnvironments = environments+ const selectedEnvironment = selectedEnvironmentId+ ? selectableEnvironments.find(env => env.id === selectedEnvironmentId)+ : undefined+ const disabled = selectableEnvironments.length === 0+ const isCreating = generateApiKey.isPending++ useEffect(() => {+ if (createDialogOpen)+ nameInputRef.current?.focus()+ }, [createDialogOpen])++ function resetCreateDialog() {+ setCreateDialogOpen(false)+ setSelectedEnvironmentId(undefined)+ setDraftName('')+ setNameError(false)+ }++ function handleOpenCreateDialog() {+ const firstEnvironment = selectableEnvironments[0]+ if (!firstEnvironment)+ return++ setSelectedEnvironmentId(firstEnvironment.id)+ setDraftName(generateApiTokenName())+ setNameError(false)+ setCreateDialogOpen(true)+ }++ function handleEnvironmentChange(environmentId: string) {+ setSelectedEnvironmentId(environmentId)+ setNameError(false)+ }++ function handleDialogOpenChange(nextOpen: boolean) {+ if (nextOpen || isCreating)+ return++ resetCreateDialog()+ }++ function handleGenerateApiKey(event: FormEvent<HTMLFormElement>) {+ event.preventDefault()++ const name = draftName.trim()++ if (!selectedEnvironmentId || !name) {+ setNameError(true)+ return+ }++ generateApiKey.mutate(+ {+ params: {+ appInstanceId,+ environmentId: selectedEnvironmentId,+ },+ body: {+ appInstanceId,+ environmentId: selectedEnvironmentId,+ displayName: name,+ },+ },+ {+ onSuccess: (response) => {+ if (response.token)+ onCreatedToken(response.token)+ resetCreateDialog()+ },+ onError: () => {+ toast.error(t('access.api.createFailed'))+ },+ },+ )+ }++ const trigger = (+ <Button+ type="button"+ variant={triggerVariant}+ disabled={disabled}+ onClick={handleOpenCreateDialog}+ className={cn('gap-1.5', triggerClassName)}+ >+ <span className="i-ri-add-line size-4" aria-hidden="true" />+ {t('access.api.newKey')}+ </Button>+ )++ return (+ <>+ {children ? children({ trigger }) : trigger}+ <Dialog open={createDialogOpen} onOpenChange={handleDialogOpenChange}>+ <DialogContent className="w-120 max-w-[calc(100vw-32px)] overflow-hidden p-0">+ <DialogCloseButton disabled={isCreating} />+ <form onSubmit={handleGenerateApiKey}>+ <div className="border-b border-divider-subtle px-6 py-5 pr-14">+ <DialogTitle className="title-xl-semi-bold text-text-primary">+ {t('access.api.createKeyTitle')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('access.api.description')}+ </DialogDescription>+ </div>++ <div className="flex flex-col gap-4 px-6 py-5">+ <div>+ <label+ htmlFor={nameInputId}+ className="mb-1 block system-sm-medium text-text-secondary"+ >+ {t('access.api.nameLabel')}+ </label>+ <Input+ ref={nameInputRef}+ id={nameInputId}+ value={draftName}+ disabled={isCreating}+ aria-invalid={nameError || undefined}+ aria-describedby={nameError ? `${nameInputId}-error` : undefined}+ placeholder={t('access.api.namePlaceholder')}+ onChange={(event) => {+ setDraftName(event.target.value)+ if (nameError && event.target.value.trim())+ setNameError(false)+ }}+ />+ {nameError && (+ <div id={`${nameInputId}-error`} className="mt-1 system-xs-regular text-text-destructive">+ {t('access.api.nameRequired')}+ </div>+ )}+ </div>++ <div>+ <Select+ value={selectedEnvironmentId ?? null}+ disabled={isCreating}+ onValueChange={value => value && handleEnvironmentChange(value)}+ >+ <SelectLabel className="mb-1 block system-sm-medium text-text-secondary">+ {t('access.api.table.environment')}+ </SelectLabel>+ <SelectTrigger>+ {selectedEnvironment?.displayName ?? '—'}+ </SelectTrigger>+ <SelectContent>+ {selectableEnvironments.map(env => (+ <SelectItem key={env.id} value={env.id}>+ <SelectItemText>{env.displayName}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>++ <div className="flex justify-end gap-2 border-t border-divider-subtle bg-background-default-subtle px-6 py-4">+ <Button+ type="button"+ variant="secondary"+ disabled={isCreating}+ onClick={() => handleDialogOpenChange(false)}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button+ type="submit"+ variant="primary"+ loading={isCreating}+ disabled={isCreating || !selectedEnvironmentId}+ >+ {t('access.api.createKey')}+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ </>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/api-key-list.tsx b/web/features/deployments/detail/settings-tab/access/api-key-list.tsxnew file mode 100644index 00000000000..cf2a8553aee--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/api-key-list.tsx@@ -0,0 +1,253 @@+'use client'++import type {+ ApiKey,+ Environment,+} from '@dify/contracts/enterprise/types.gen'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { cn } from '@langgenius/dify-ui/cn'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import {+ DetailTable,+ DetailTableBody,+ DetailTableCard,+ DetailTableCardList,+ DetailTableCell,+ DetailTableHead,+ DetailTableHeader,+ DetailTableRow,+} from '../../table'+import {+ API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES,+} from '../../table-styles'++function ApiKeyName({ apiKey }: {+ apiKey: ApiKey+}) {+ return (+ <span className="block truncate text-text-primary">+ {apiKey.displayName}+ </span>+ )+}++function EnvironmentBadge({ environment }: {+ environment?: Environment+}) {+ return (+ <span className="inline-flex h-5 max-w-36 items-center rounded-md bg-background-section-burn px-1.5 text-xs text-text-tertiary">+ <span className="truncate">{environment?.displayName ?? '—'}</span>+ </span>+ )+}++function ApiKeyValue({ value }: {+ value: string+}) {+ return (+ <div className="flex h-8 min-w-0 items-center rounded-lg border border-components-input-border-active bg-components-input-bg-normal px-2">+ <div className="min-w-0 flex-1 truncate font-mono system-sm-medium text-text-secondary">+ {value}+ </div>+ </div>+ )+}++function RevokeApiKeyButton({ apiKey }: {+ apiKey: ApiKey+}) {+ const { t } = useTranslation('deployments')+ const [showRevokeConfirm, setShowRevokeConfirm] = useState(false)+ const revokeApiKey = useMutation(consoleQuery.enterprise.accessService.deleteApiKey.mutationOptions())+ const isRevoking = revokeApiKey.isPending+ const apiKeyName = apiKey.displayName++ function handleRevoke() {+ if (isRevoking)+ return++ revokeApiKey.mutate(+ {+ params: {+ appInstanceId: apiKey.appInstanceId,+ environmentId: apiKey.environmentId,+ apiKeyId: apiKey.id,+ },+ },+ {+ onSuccess: () => {+ setShowRevokeConfirm(false)+ toast.success(t('access.api.revokeSuccess'))+ },+ onError: () => {+ toast.error(t('access.api.revokeFailed'))+ },+ },+ )+ }++ function handleRevokeConfirmOpenChange(open: boolean) {+ if (isRevoking)+ return++ setShowRevokeConfirm(open)+ }++ return (+ <>+ <button+ type="button"+ onClick={() => setShowRevokeConfirm(true)}+ aria-label={t('access.revoke')}+ aria-busy={isRevoking}+ disabled={isRevoking}+ className={cn(+ 'inline-flex size-8 shrink-0 items-center justify-center rounded-md text-text-tertiary outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid',+ isRevoking+ ? 'cursor-not-allowed opacity-60'+ : 'hover:bg-state-destructive-hover hover:text-text-destructive',+ )}+ >+ <span className={cn(isRevoking ? 'i-ri-loader-2-line animate-spin' : 'i-ri-delete-bin-line', 'size-3.5')} />+ </button>+ <AlertDialog open={showRevokeConfirm} onOpenChange={handleRevokeConfirmOpenChange}>+ <AlertDialogContent>+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">+ {t('access.api.revokeConfirmTitle')}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">+ {t('access.api.revokeConfirmDescription', { name: apiKeyName })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton disabled={isRevoking}>+ {t('operation.cancel', { ns: 'common' })}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton loading={isRevoking} disabled={isRevoking} onClick={handleRevoke}>+ {t('access.revoke')}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}++function ApiKeyMobileRow({ apiKey, environment }: {+ apiKey: ApiKey+ environment?: Environment+}) {+ const { t } = useTranslation('deployments')+ const displayValue = apiKey.maskedToken++ return (+ <DetailTableCard>+ <div className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <ApiKeyName apiKey={apiKey} />+ <div className="mt-1">+ <EnvironmentBadge environment={environment} />+ </div>+ </div>+ <RevokeApiKeyButton apiKey={apiKey} />+ </div>+ <div className="flex min-w-0 flex-col gap-1">+ <span className="system-2xs-medium-uppercase text-text-tertiary">+ {t('access.api.table.key')}+ </span>+ <ApiKeyValue value={displayValue} />+ </div>+ </div>+ </DetailTableCard>+ )+}++function ApiKeyDesktopRow({ apiKey, environment }: {+ apiKey: ApiKey+ environment?: Environment+}) {+ const displayValue = apiKey.maskedToken++ return (+ <DetailTableRow>+ <DetailTableCell>+ <ApiKeyName apiKey={apiKey} />+ </DetailTableCell>+ <DetailTableCell>+ <EnvironmentBadge environment={environment} />+ </DetailTableCell>+ <DetailTableCell>+ <ApiKeyValue value={displayValue} />+ </DetailTableCell>+ <DetailTableCell>+ <div className="flex justify-end">+ <RevokeApiKeyButton apiKey={apiKey} />+ </div>+ </DetailTableCell>+ </DetailTableRow>+ )+}++function ApiKeyTableHeader() {+ const { t } = useTranslation('deployments')++ return (+ <DetailTableHeader>+ <DetailTableRow>+ <DetailTableHead className={API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.name}>{t('access.api.table.name')}</DetailTableHead>+ <DetailTableHead className={API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.environment}>{t('access.api.table.environment')}</DetailTableHead>+ <DetailTableHead className={API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.key}>{t('access.api.table.key')}</DetailTableHead>+ <DetailTableHead className={`${API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.action} text-right`}>{t('access.api.table.action')}</DetailTableHead>+ </DetailTableRow>+ </DetailTableHeader>+ )+}++export function ApiKeyList({ apiKeys, environments }: {+ apiKeys: ApiKey[]+ environments: Environment[]+}) {+ const environmentById = new Map(environments.map(environment => [environment.id, environment]))++ return (+ <>+ <DetailTableCardList className={cn('pc:hidden')}>+ {apiKeys.map(apiKey => (+ <ApiKeyMobileRow+ key={apiKey.id}+ apiKey={apiKey}+ environment={environmentById.get(apiKey.environmentId)}+ />+ ))}+ </DetailTableCardList>+ <div className="hidden pc:block">+ <DetailTable>+ <ApiKeyTableHeader />+ <DetailTableBody>+ {apiKeys.map(apiKey => (+ <ApiKeyDesktopRow+ key={apiKey.id}+ apiKey={apiKey}+ environment={environmentById.get(apiKey.environmentId)}+ />+ ))}+ </DetailTableBody>+ </DetailTable>+ </div>+ </>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/api-token-name.ts b/web/features/deployments/detail/settings-tab/access/api-token-name.tsnew file mode 100644index 00000000000..0f494a7a733--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/api-token-name.ts@@ -0,0 +1,39 @@+const API_TOKEN_NAME_ADJECTIVES = [+ 'ancient',+ 'autumn',+ 'bright',+ 'calm',+ 'crystal',+ 'gentle',+ 'golden',+ 'hidden',+ 'holy',+ 'quiet',+ 'rapid',+ 'silver',+]++const API_TOKEN_NAME_NOUNS = [+ 'brook',+ 'cloud',+ 'field',+ 'forest',+ 'harbor',+ 'lake',+ 'meadow',+ 'moon',+ 'river',+ 'stone',+ 'valley',+ 'wave',+]++function randomListItem(items: string[]) {+ return items[Math.floor(Math.random() * items.length)]!+}++export function generateApiTokenName() {+ const suffix = Math.floor(1000 + Math.random() * 9000)++ return `${randomListItem(API_TOKEN_NAME_ADJECTIVES)}-${randomListItem(API_TOKEN_NAME_NOUNS)}-${suffix}`+}diff --git a/web/features/deployments/detail/settings-tab/access/channels-section.tsx b/web/features/deployments/detail/settings-tab/access/channels-section.tsxnew file mode 100644index 00000000000..d3dde7936a4--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/channels-section.tsx@@ -0,0 +1,251 @@+'use client'++import type { AccessChannels, AccessEndpoint } from '@dify/contracts/enterprise/types.gen'+import type { ReactNode } from 'react'+import { Switch, SwitchSkeleton } from '@langgenius/dify-ui/switch'+import { useMutation } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import { consoleQuery } from '@/service/client'+import { DeploymentEmptyState, DeploymentNoticeState, DeploymentStateMessage } from '../../../components/empty-state'+import { Section } from '../../common'+import { CopyPill, EndpointRow } from './common'+import { getUrlOrigin } from './url'++const ACCESS_CHANNEL_SKELETON_SECTIONS = [+ { key: 'webapp' },+ { key: 'cli' },+]++function AccessChannelsSwitch({ appInstanceId, checked, accessChannels, disabled }: {+ appInstanceId: string+ checked: boolean+ accessChannels?: AccessChannels+ disabled?: boolean+}) {+ const { t } = useTranslation('deployments')+ const toggleAccessChannel = useMutation(consoleQuery.enterprise.accessService.updateAccessChannels.mutationOptions())++ return (+ <Switch+ aria-label={t('access.channels.title')}+ checked={checked}+ disabled={disabled}+ loading={toggleAccessChannel.isPending}+ onCheckedChange={(enabled) => {+ toggleAccessChannel.mutate({+ params: { appInstanceId },+ body: {+ appInstanceId,+ webAppEnabled: enabled,+ developerApiEnabled: accessChannels?.developerApiEnabled ?? false,+ },+ })+ }}+ />+ )+}++function AccessChannelsSkeleton() {+ return (+ <div className="overflow-hidden rounded-lg border border-divider-subtle bg-components-panel-bg">+ {ACCESS_CHANNEL_SKELETON_SECTIONS.map(section => (+ <SkeletonRow+ key={section.key}+ className="flex flex-col gap-3 border-t border-divider-subtle px-4 py-4 first:border-t-0 lg:flex-row lg:items-start"+ >+ <div className="flex min-w-0 gap-2.5 lg:w-70">+ <SkeletonRectangle className="my-0 size-7 shrink-0 animate-pulse rounded-lg" />+ <div className="flex min-w-0 flex-col gap-1.5">+ <SkeletonRectangle className="h-3.5 w-24 animate-pulse" />+ <SkeletonRectangle className="h-3 w-40 animate-pulse" />+ </div>+ </div>+ <SkeletonRectangle className="my-0 h-8 min-w-0 flex-1 animate-pulse rounded-lg" />+ </SkeletonRow>+ ))}+ </div>+ )+}++function ChannelInfo({ icon, title, description }: {+ icon: ReactNode+ title: string+ description?: string+}) {+ return (+ <div className="flex min-w-0 items-start gap-2.5">+ <span className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg bg-background-section-burn text-text-tertiary">+ {icon}+ </span>+ <div className="min-w-0">+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <span className="system-sm-medium text-text-primary">{title}</span>+ </div>+ {description && (+ <div className="system-xs-regular text-text-tertiary">{description}</div>+ )}+ </div>+ </div>+ )+}++function ChannelRow({ info, children }: {+ info: ReactNode+ children: ReactNode+}) {+ return (+ <div className="flex flex-col gap-3 border-t border-divider-subtle px-4 py-4 first:border-t-0 lg:flex-row lg:items-start">+ <div className="min-w-0 lg:w-70">+ {info}+ </div>+ <div className="min-w-0 flex-1">+ {children}+ </div>+ </div>+ )+}++export function AccessChannelsSection({+ appInstanceId,+ accessChannels,+ webAppEndpoints,+ cliEndpoint,+ isLoading,+ isError,+}: {+ appInstanceId: string+ accessChannels?: AccessChannels+ webAppEndpoints?: AccessEndpoint[]+ cliEndpoint?: AccessEndpoint+ isLoading: boolean+ isError: boolean+}) {+ const { t } = useTranslation('deployments')+ const runEnabled = accessChannels?.webAppEnabled ?? false+ const webappRows = webAppEndpoints?.flatMap((endpoint) => {+ const endpointUrl = endpoint.endpointUrl+ if (!endpointUrl)+ return []++ return [{+ endpoint,+ endpointUrl,+ }]+ }) ?? []+ const cliDomain = getUrlOrigin(cliEndpoint?.endpointUrl)+ const cliDocsUrl = cliDomain ? `${cliDomain}/cli` : undefined++ return (+ <Section+ title={t('access.channels.title')}+ action={(+ isLoading+ ? <SwitchSkeleton />+ : (+ <div className="flex items-center gap-2">+ <span className="system-xs-medium text-text-tertiary">+ {runEnabled ? t('overview.enabled') : t('overview.disabled')}+ </span>+ <AccessChannelsSwitch+ appInstanceId={appInstanceId}+ checked={runEnabled}+ accessChannels={accessChannels}+ disabled={isError}+ />+ </div>+ )+ )}+ >+ {isLoading+ ? <AccessChannelsSkeleton />+ : isError+ ? <DeploymentStateMessage variant="section">{t('common.loadFailed')}</DeploymentStateMessage>+ : runEnabled+ ? (+ <div className="overflow-hidden rounded-lg border border-divider-subtle bg-components-panel-bg">+ <ChannelRow+ info={(+ <ChannelInfo+ icon={<span className="i-ri-global-line size-3.5" aria-hidden="true" />}+ title={t('access.runAccess.webapp')}+ description={t('access.runAccess.webappDesc')}+ />+ )}+ >+ {webappRows.length > 0+ ? (+ <div className="flex flex-col gap-1.5">+ {webappRows.map(({ endpoint, endpointUrl }) => (+ <EndpointRow+ key={`webapp-${endpoint.environment?.id ?? endpointUrl}`}+ envName={endpoint.environment?.displayName ?? '—'}+ label={t('access.runAccess.urlLabel')}+ value={endpointUrl}+ openLabel={t('access.runAccess.openWebapp')}+ />+ ))}+ </div>+ )+ : (+ <DeploymentNoticeState>+ {t('access.runAccess.webappEmpty')}+ </DeploymentNoticeState>+ )}+ </ChannelRow>+ <ChannelRow+ info={(+ <ChannelInfo+ icon={<span className="i-ri-terminal-box-line size-3.5" aria-hidden="true" />}+ title={t('access.cli.title')}+ description={t('access.cli.description')}+ />+ )}+ >+ {cliDomain+ ? (+ <div className="flex flex-wrap items-center gap-2">+ <CopyPill+ label={t('access.cli.domain')}+ value={cliDomain}+ className="min-w-0 flex-1"+ />+ <a+ href={cliDocsUrl}+ target="_blank"+ rel="noreferrer"+ className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border border-components-button-secondary-border bg-components-button-secondary-bg px-3 system-sm-medium text-components-button-secondary-text hover:bg-components-button-secondary-bg-hover"+ >+ <span className="i-ri-download-cloud-2-line size-3.5" />+ {t('access.cli.install')}+ </a>+ <a+ href={cliDocsUrl}+ target="_blank"+ rel="noreferrer"+ className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border border-components-button-secondary-border bg-components-button-secondary-bg px-3 system-sm-medium text-components-button-secondary-text hover:bg-components-button-secondary-bg-hover"+ >+ <span className="i-ri-book-open-line size-3.5" />+ {t('access.cli.docs')}+ </a>+ </div>+ )+ : (+ <DeploymentNoticeState>+ {t('access.cli.empty')}+ </DeploymentNoticeState>+ )}+ </ChannelRow>+ </div>+ )+ : (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-toggle-line"+ title={t('access.channels.disabled')}+ description={t('access.channels.disabledHint')}+ />+ )}+ </Section>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/common.tsx b/web/features/deployments/detail/settings-tab/access/common.tsxnew file mode 100644index 00000000000..ba1fd405aea--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/common.tsx@@ -0,0 +1,78 @@+'use client'++import type { ReactNode } from 'react'+import { cn } from '@langgenius/dify-ui/cn'+import { toast } from '@langgenius/dify-ui/toast'+import { useClipboard } from 'foxact/use-clipboard'+import { useTranslation } from 'react-i18next'++type CopyPillProps = {+ label: string+ value: string+ prefix?: ReactNode+ className?: string+}++export function CopyPill({ label, value, prefix, className }: CopyPillProps) {+ const { t } = useTranslation('deployments')+ const { copied, copy } = useClipboard({+ onCopyError: () => {+ toast.error(t('access.copyFailed'))+ },+ })++ return (+ <div+ className={cn(+ 'flex h-8 items-center gap-1 rounded-lg border border-components-input-border-active bg-components-input-bg-normal pr-1 pl-1.5',+ className,+ )}+ >+ <div className="flex h-5 shrink-0 items-center rounded-md border border-divider-subtle px-1.5 system-2xs-medium text-text-tertiary">+ {label}+ </div>+ {prefix}+ <div className="min-w-0 flex-1 truncate px-1 font-mono system-sm-medium text-text-secondary">+ {value}+ </div>+ <div className="h-3.5 w-px shrink-0 bg-divider-regular" />+ <button+ type="button"+ onClick={() => copy(value)}+ aria-label={t('access.copy')}+ className="flex size-6 shrink-0 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary"+ >+ <span className={cn(copied ? 'i-ri-check-line' : 'i-ri-file-copy-line', 'size-3.5')} />+ </button>+ </div>+ )+}++type EndpointRowProps = {+ envName: string+ label: string+ value: string+ openLabel?: string+}++export function EndpointRow({ envName, label, value, openLabel }: EndpointRowProps) {+ return (+ <div className="grid items-center gap-x-3 gap-y-1.5 sm:grid-cols-[minmax(88px,108px)_minmax(0,1fr)_auto]">+ <span className="min-w-0 truncate system-xs-regular text-text-tertiary">+ {envName}+ </span>+ <CopyPill label={label} value={value} className="min-w-0" />+ {openLabel && (+ <a+ href={value}+ target="_blank"+ rel="noreferrer"+ className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border border-components-button-secondary-border bg-components-button-secondary-bg px-3 system-sm-medium text-components-button-secondary-text hover:bg-components-button-secondary-bg-hover"+ >+ <span className="i-ri-external-link-line size-3.5" />+ {openLabel}+ </a>+ )}+ </div>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/developer-api-created-token-dialog.tsx b/web/features/deployments/detail/settings-tab/access/developer-api-created-token-dialog.tsxnew file mode 100644index 00000000000..3582e53bdcc--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/developer-api-created-token-dialog.tsx@@ -0,0 +1,97 @@+'use client'++import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { toast } from '@langgenius/dify-ui/toast'+import { useClipboard } from 'foxact/use-clipboard'+import { useTranslation } from 'react-i18next'+import { CopyPill } from './common'++function buildCurlExample(apiUrl: string, token: string) {+ return `curl -X POST '${apiUrl}' \\+--header 'Authorization: Bearer ${token}' \\+--header 'Content-Type: application/json' \\+--data-raw '{+ "inputs": {},+ "response_mode": "streaming",+ "user": "abc-123"+}'`+}++function CurlExample({ apiUrl, token }: {+ apiUrl: string+ token: string+}) {+ const { t } = useTranslation('deployments')+ const curlExample = buildCurlExample(apiUrl, token)+ const { copied, copy } = useClipboard({+ onCopyError: () => {+ toast.error(t('access.copyFailed'))+ },+ })++ return (+ <div className="min-w-0 overflow-hidden rounded-lg border border-components-input-border-active bg-components-input-bg-normal">+ <div className="flex h-8 items-center justify-between gap-2 border-b border-divider-subtle pr-1.5 pl-3">+ <div className="min-w-0 truncate system-xs-semibold-uppercase text-text-secondary">+ {t('access.api.curlExampleTitle')}+ </div>+ <button+ type="button"+ onClick={() => copy(curlExample)}+ aria-label={t('access.api.copyCurlExample')}+ className="flex size-6 shrink-0 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary"+ >+ <span className={cn(copied ? 'i-ri-check-line' : 'i-ri-file-copy-line', 'size-3.5')} />+ </button>+ </div>+ <pre className="max-h-40 overflow-auto px-3 py-3 font-mono system-xs-regular whitespace-pre text-text-secondary">+ <code>{curlExample}</code>+ </pre>+ </div>+ )+}++export function CreatedApiTokenDialog({ token, apiUrl, onDismiss }: {+ token: string+ apiUrl?: string+ onDismiss: () => void+}) {+ const { t } = useTranslation('deployments')++ return (+ <Dialog open={Boolean(token)} onOpenChange={open => !open && onDismiss()} disablePointerDismissal>+ <DialogContent className="w-120 max-w-[calc(100vw-32px)] overflow-hidden p-0">+ <DialogCloseButton />+ <div className="border-b border-divider-subtle px-6 py-5 pr-14">+ <DialogTitle className="title-xl-semi-bold text-text-primary">+ {t('access.api.newTokenTitle')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('access.api.newTokenDescription')}+ </DialogDescription>+ </div>++ <div className="flex flex-col gap-5 px-6 py-5">+ <CopyPill+ label={t('access.api.newTokenLabel')}+ value={token}+ />+ {apiUrl && (+ <CurlExample+ apiUrl={apiUrl}+ token={token}+ />+ )}+ </div>++ <div className="flex justify-end border-t border-divider-subtle bg-background-default-subtle px-6 py-4">+ <Button variant="primary" onClick={onDismiss}>+ {t('operation.confirm', { ns: 'common' })}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/developer-api-section.tsx b/web/features/deployments/detail/settings-tab/access/developer-api-section.tsxnew file mode 100644index 00000000000..23496dc76ad--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/developer-api-section.tsx@@ -0,0 +1,268 @@+'use client'++import type {+ AccessChannels,+ ApiKey,+ Environment,+} from '@dify/contracts/enterprise/types.gen'+import type { ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { Switch, SwitchSkeleton } from '@langgenius/dify-ui/switch'+import { useMutation, useQuery } from '@tanstack/react-query'+import { atom, useAtom } from 'jotai'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { DeploymentEmptyState, DeploymentStateMessage } from '../../../components/empty-state'+import { DeveloperApiDocsDrawer } from './api-docs-drawer'+import { ApiKeyGenerateMenu } from './api-key-generate-menu'+import { ApiKeyList } from './api-key-list'+import { CopyPill } from './common'+import { CreatedApiTokenDialog } from './developer-api-created-token-dialog'+import { DeveloperApiSkeleton } from './developer-api-skeleton'++type CreatedApiToken = {+ appInstanceId: string+ token: string+}++const createdApiTokenAtom = atom<CreatedApiToken | undefined>(undefined)++function useDeveloperApiSettings(appInstanceId: string) {+ const developerApiSettingsQuery = useQuery(consoleQuery.enterprise.accessService.getDeveloperApiSettings.queryOptions({+ input: {+ params: { appInstanceId },+ },+ }))+ const accessChannels = developerApiSettingsQuery.data?.accessChannels+ const apiEnabled = accessChannels?.developerApiEnabled ?? false+ const environments = developerApiSettingsQuery.data?.environments ?? []+ const apiKeys: ApiKey[] = developerApiSettingsQuery.data?.apiKeys ?? []+ const apiUrl = developerApiSettingsQuery.data?.developerApiUrl.apiUrl++ return {+ apiEnabled,+ accessChannels,+ apiUrl,+ environments,+ apiKeys,+ isLoading: developerApiSettingsQuery.isLoading,+ isError: developerApiSettingsQuery.isError,+ }+}++function DeveloperApiSwitch({ appInstanceId, checked, accessChannels, disabled }: {+ appInstanceId: string+ checked: boolean+ accessChannels?: AccessChannels+ disabled?: boolean+}) {+ const { t } = useTranslation('deployments')+ const toggleDeveloperAPI = useMutation(consoleQuery.enterprise.accessService.updateAccessChannels.mutationOptions())++ return (+ <Switch+ aria-label={t('access.api.developerTitle')}+ checked={checked}+ disabled={disabled}+ loading={toggleDeveloperAPI.isPending}+ onCheckedChange={(enabled) => {+ toggleDeveloperAPI.mutate({+ params: { appInstanceId },+ body: {+ appInstanceId,+ webAppEnabled: accessChannels?.webAppEnabled ?? false,+ developerApiEnabled: enabled,+ },+ })+ }}+ />+ )+}++export function DeveloperApiHeaderSwitch({ appInstanceId }: {+ appInstanceId: string+}) {+ const { t } = useTranslation('deployments')+ const {+ apiEnabled,+ accessChannels,+ isLoading,+ isError,+ } = useDeveloperApiSettings(appInstanceId)++ if (isLoading)+ return <SwitchSkeleton />++ return (+ <div className="flex items-center gap-2">+ <span className="system-xs-medium text-text-tertiary">+ {apiEnabled ? t('overview.enabled') : t('overview.disabled')}+ </span>+ <DeveloperApiSwitch+ appInstanceId={appInstanceId}+ checked={apiEnabled}+ accessChannels={accessChannels}+ disabled={isError}+ />+ </div>+ )+}++function ApiKeyListSection({ apiKeys, environments, action }: {+ apiKeys: ApiKey[]+ environments: Environment[]+ action?: ReactNode+}) {+ const { t } = useTranslation('deployments')+ const hasAction = Boolean(action)++ return (+ <div className="flex flex-col gap-2">+ <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <div className="system-xs-semibold-uppercase text-text-tertiary">+ {t('access.api.keyList')}+ </div>+ {hasAction && (+ <div className="w-full shrink-0 sm:w-auto [&_button]:w-full sm:[&_button]:w-auto">+ {action}+ </div>+ )}+ </div>+ <ApiKeyList+ apiKeys={apiKeys}+ environments={environments}+ />+ </div>+ )+}++function DeveloperApiEndpoint({ appInstanceId, apiUrl }: {+ appInstanceId: string+ apiUrl: string+}) {+ const { t } = useTranslation('deployments')+ const [apiDocsOpen, setApiDocsOpen] = useState(false)++ return (+ <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center">+ <CopyPill+ label={t('access.api.endpoint')}+ value={apiUrl}+ className="min-w-0 flex-1"+ />+ <Button+ variant="secondary"+ className="shrink-0 gap-1.5"+ onClick={() => setApiDocsOpen(true)}+ >+ <span className="i-ri-file-list-3-line size-3.5" />+ {t('access.api.docs')}+ </Button>+ <DeveloperApiDocsDrawer+ open={apiDocsOpen}+ appInstanceId={appInstanceId}+ apiBaseUrl={apiUrl}+ onOpenChange={setApiDocsOpen}+ />+ </div>+ )+}++export function DeveloperApiSection({+ appInstanceId,+}: {+ appInstanceId: string+}) {+ const { t } = useTranslation('deployments')+ const [createdApiToken, setCreatedApiToken] = useAtom(createdApiTokenAtom)+ const {+ apiEnabled,+ apiUrl,+ apiKeys,+ environments,+ isLoading,+ isError,+ } = useDeveloperApiSettings(appInstanceId)+ const visibleCreatedApiToken = createdApiToken?.appInstanceId === appInstanceId+ ? createdApiToken.token+ : undefined+ const hasSelectableEnvironment = environments.some(environment => Boolean(environment.id))++ if (isLoading)+ return <DeveloperApiSkeleton />++ if (isError)+ return <DeploymentStateMessage variant="section">{t('common.loadFailed')}</DeploymentStateMessage>++ if (!apiEnabled) {+ return (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-toggle-line"+ title={t('access.api.disabled')}+ description={t('access.api.disabledHint')}+ />+ )+ }++ return (+ <div className="flex flex-col gap-4">+ {apiUrl && (+ <DeveloperApiEndpoint+ appInstanceId={appInstanceId}+ apiUrl={apiUrl}+ />+ )}+ {hasSelectableEnvironment+ ? (+ <ApiKeyGenerateMenu+ appInstanceId={appInstanceId}+ environments={environments}+ triggerVariant="primary"+ onCreatedToken={token => setCreatedApiToken({ appInstanceId, token })}+ >+ {({ trigger }) => apiKeys.length === 0+ ? (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-key-2-line"+ title={t('access.api.noKeysTitle')}+ description={t('access.api.noKeys')}+ action={trigger}+ />+ )+ : (+ <ApiKeyListSection+ apiKeys={apiKeys}+ environments={environments}+ action={trigger}+ />+ )}+ </ApiKeyGenerateMenu>+ )+ : apiKeys.length === 0+ ? (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-rocket-line"+ title={t('access.api.emptyTitle')}+ description={t('access.api.empty')}+ />+ )+ : (+ <ApiKeyListSection+ apiKeys={apiKeys}+ environments={environments}+ />+ )}+ {visibleCreatedApiToken && (+ <CreatedApiTokenDialog+ token={visibleCreatedApiToken}+ apiUrl={apiUrl}+ onDismiss={() => setCreatedApiToken(undefined)}+ />+ )}+ </div>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/developer-api-skeleton.tsx b/web/features/deployments/detail/settings-tab/access/developer-api-skeleton.tsxnew file mode 100644index 00000000000..ab1b92ff63f--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/developer-api-skeleton.tsx@@ -0,0 +1,112 @@+'use client'++import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import {+ DetailTable,+ DetailTableBody,+ DetailTableCard,+ DetailTableCardList,+ DetailTableCell,+ DetailTableHead,+ DetailTableHeader,+ DetailTableRow,+} from '../../table'+import { API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES } from '../../table-styles'++const DEVELOPER_API_KEY_SKELETON_KEYS = ['primary-key', 'secondary-key']++export function DeveloperApiSkeleton() {+ return (+ <div className="flex flex-col gap-4" data-slot="deployment-developer-api-skeleton">+ <ApiUrlSkeleton />+ <ApiKeyTableSkeleton />+ </div>+ )+}++function ApiUrlSkeleton() {+ return (+ <div+ className="flex h-8 items-center gap-1 rounded-lg border border-components-input-border-active bg-components-input-bg-normal pr-1 pl-1.5"+ data-slot="deployment-developer-api-url-skeleton"+ >+ <SkeletonRectangle className="my-0 h-5 w-16 shrink-0 animate-pulse rounded-md" />+ <SkeletonRectangle className="my-0 h-4 min-w-0 flex-1 animate-pulse" />+ <div className="h-3.5 w-px shrink-0 bg-divider-regular" />+ <SkeletonRectangle className="my-0 size-6 shrink-0 animate-pulse rounded-md" />+ </div>+ )+}++function ApiKeyTableSkeleton() {+ return (+ <>+ <DetailTableCardList className="pc:hidden">+ {DEVELOPER_API_KEY_SKELETON_KEYS.map(key => (+ <DetailTableCard key={key} data-slot="deployment-developer-api-mobile-row-skeleton">+ <div className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <SkeletonRectangle className="my-0 h-3.5 w-32 animate-pulse" />+ <SkeletonRectangle className="mt-2 h-5 w-20 animate-pulse rounded-md" />+ </div>+ <SkeletonRectangle className="my-0 size-8 shrink-0 animate-pulse rounded-md" />+ </div>+ <div className="flex min-w-0 flex-col gap-1">+ <SkeletonRectangle className="my-0 h-2.5 w-14 animate-pulse" />+ <SkeletonRectangle className="my-0 h-8 w-full animate-pulse rounded-lg" />+ </div>+ </div>+ </DetailTableCard>+ ))}+ </DetailTableCardList>+ <div className="hidden pc:block">+ <DetailTable>+ <ApiKeyTableHeaderSkeleton />+ <DetailTableBody>+ {DEVELOPER_API_KEY_SKELETON_KEYS.map(key => (+ <ApiKeyDesktopRowSkeleton key={key} />+ ))}+ </DetailTableBody>+ </DetailTable>+ </div>+ </>+ )+}++function ApiKeyTableHeaderSkeleton() {+ const { t } = useTranslation('deployments')++ return (+ <DetailTableHeader>+ <DetailTableRow>+ <DetailTableHead className={API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.name}>{t('access.api.table.name')}</DetailTableHead>+ <DetailTableHead className={API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.environment}>{t('access.api.table.environment')}</DetailTableHead>+ <DetailTableHead className={API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.key}>{t('access.api.table.key')}</DetailTableHead>+ <DetailTableHead className={`${API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES.action} text-right`}>{t('access.api.table.action')}</DetailTableHead>+ </DetailTableRow>+ </DetailTableHeader>+ )+}++function ApiKeyDesktopRowSkeleton() {+ return (+ <DetailTableRow data-slot="deployment-developer-api-desktop-row-skeleton">+ <DetailTableCell>+ <SkeletonRectangle className="my-0 h-3.5 w-32 animate-pulse" />+ </DetailTableCell>+ <DetailTableCell>+ <SkeletonRectangle className="my-0 h-5 w-20 animate-pulse rounded-md" />+ </DetailTableCell>+ <DetailTableCell>+ <SkeletonRectangle className="my-0 h-8 w-full animate-pulse rounded-lg" />+ </DetailTableCell>+ <DetailTableCell>+ <div className="flex justify-end">+ <SkeletonRectangle className="my-0 size-8 animate-pulse rounded-md" />+ </div>+ </DetailTableCell>+ </DetailTableRow>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/permission-row-components.tsx b/web/features/deployments/detail/settings-tab/access/permission-row-components.tsxnew file mode 100644index 00000000000..25913c33543--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/permission-row-components.tsx@@ -0,0 +1,163 @@+'use client'++import type {+ AccessPermissionKind,+ SelectableAccessSubject,+} from './access-policy'+import type { AccessSubjectSelectionValue } from '@/app/components/app/app-access-control/access-subject-selector/types'+import type { AccessControlDraft } from '@/app/components/app/app-access-control/store'+import { SubjectType } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import { AccessControlDialog } from '@/app/components/app/app-access-control/access-control-dialog'+import { AccessControlDialogContent } from '@/app/components/app/app-access-control/access-control-dialog-content'+import { useAccessControlStore } from '@/app/components/app/app-access-control/store'+import { AccessControlDraftProvider } from '@/app/components/app/app-access-control/store-provider'+import { AccessMode as AppAccessMode } from '@/models/access-control'+import {+ appAccessModeToPermissionKey,+ permissionIcon,+} from './access-policy'++export function PermissionSummaryButton({+ value,+ subjects,+ disabled,+ loading,+ environmentLabel,+ onClick,+}: {+ value: AccessPermissionKind+ subjects?: SelectableAccessSubject[]+ disabled?: boolean+ loading?: boolean+ environmentLabel: string+ onClick: () => void+}) {+ const { t } = useTranslation('deployments')+ const groupCount = subjects?.filter(subject => subject.subjectType === SubjectType.SUBJECT_TYPE_GROUP).length ?? 0+ const memberCount = (subjects?.length ?? 0) - groupCount+ const countLabels = [+ ...(groupCount > 0 ? [t('access.members.groupCount', { count: groupCount })] : []),+ ...(memberCount > 0 ? [t('access.members.memberCount', { count: memberCount })] : []),+ ]+ const specificSubjectLabel = value === 'specific'+ ? subjects && subjects.length > 0+ ? countLabels.join(' · ')+ : t('access.permission.specificDesc')+ : undefined+ const IconClassName = loading ? 'i-ri-loader-2-line animate-spin motion-reduce:animate-none' : permissionIcon[value]++ return (+ <button+ type="button"+ disabled={disabled}+ aria-label={t('access.permissions.editAriaLabel', { environment: environmentLabel })}+ onClick={onClick}+ className={cn(+ 'flex h-9 w-full min-w-0 cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal py-1 pr-2 pl-2.5 outline-hidden hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:ring-inset',+ disabled && 'cursor-not-allowed opacity-50 hover:bg-components-input-bg-normal',+ )}+ >+ <div className="flex min-w-0 grow items-center gap-x-1.5 pr-1">+ <span+ className={cn(IconClassName, 'size-4 shrink-0 text-text-secondary')}+ aria-hidden="true"+ />+ <p className="min-w-0 truncate text-left system-sm-medium text-text-secondary">+ {t(`access.permission.${value}`)}+ </p>+ </div>+ {specificSubjectLabel && (+ <p className="shrink-0 system-xs-regular text-text-tertiary">+ {specificSubjectLabel}+ </p>+ )}+ <div className="flex size-4 shrink-0 items-center justify-center">+ <span className="i-ri-arrow-right-s-line size-4 text-text-quaternary" aria-hidden="true" />+ </div>+ </button>+ )+}++export function DeploymentAccessControlDialog({+ initialDraft,+ subjectsLoading,+ saving,+ onClose,+ onSubmit,+}: {+ initialDraft: AccessControlDraft+ subjectsLoading?: boolean+ saving?: boolean+ onClose: () => void+ onSubmit: (kind: AccessPermissionKind, subjects: AccessSubjectSelectionValue) => void+}) {+ const draftKey = [+ initialDraft.currentMenu,+ initialDraft.specificGroups ? initialDraft.specificGroups.map(group => group.id).join(',') : 'no-groups',+ initialDraft.specificMembers ? initialDraft.specificMembers.map(member => member.id).join(',') : 'no-members',+ ].join(':')++ return (+ <AccessControlDraftProvider draftKey={draftKey} initialDraft={initialDraft}>+ <DeploymentAccessControlDialogBody+ subjectsLoading={subjectsLoading}+ saving={saving}+ onClose={onClose}+ onSubmit={onSubmit}+ />+ </AccessControlDraftProvider>+ )+}++function DeploymentAccessControlDialogBody({+ subjectsLoading,+ saving,+ onClose,+ onSubmit,+}: {+ subjectsLoading?: boolean+ saving?: boolean+ onClose: () => void+ onSubmit: (kind: AccessPermissionKind, subjects: AccessSubjectSelectionValue) => void+}) {+ const { t } = useTranslation('deployments')+ const currentMenu = useAccessControlStore(s => s.currentMenu)+ const specificGroups = useAccessControlStore(s => s.specificGroups)+ const specificMembers = useAccessControlStore(s => s.specificMembers)+ const specificSelected = currentMenu === AppAccessMode.SPECIFIC_GROUPS_MEMBERS+ const selectedSubjectCount = specificGroups.length + specificMembers.length+ const specificEmpty = specificSelected && selectedSubjectCount === 0+ const confirmDisabled = saving || (specificSelected && (subjectsLoading || specificEmpty))++ const handleConfirm = () => {+ if (confirmDisabled)+ return++ onSubmit(+ appAccessModeToPermissionKey(currentMenu),+ specificSelected+ ? { groups: specificGroups, members: specificMembers }+ : { groups: [], members: [] },+ )+ }++ return (+ <AccessControlDialog show onClose={onClose}>+ <AccessControlDialogContent+ title={t('access.permissions.editTitle')}+ description={t('access.permissions.editDescription')}+ hideExternal+ saving={saving}+ controlsDisabled={saving || subjectsLoading}+ confirmDisabled={confirmDisabled}+ specificGroupsOrMembersProps={{+ loading: subjectsLoading,+ }}+ onClose={onClose}+ onConfirm={handleConfirm}+ />+ </AccessControlDialog>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/permissions-section.tsx b/web/features/deployments/detail/settings-tab/access/permissions-section.tsxnew file mode 100644index 00000000000..52d83c55e63--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/permissions-section.tsx@@ -0,0 +1,75 @@+'use client'++import type { EnvironmentAccessPolicy } from '@dify/contracts/enterprise/types.gen'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import { DeploymentEmptyState, DeploymentStateMessage } from '../../../components/empty-state'+import { Section } from '../../common'+import { EnvironmentPermissionRow } from './permissions'++const ACCESS_PERMISSIONS_SKELETON_KEYS = ['production', 'staging', 'development']++function AccessPermissionsSkeleton() {+ return (+ <div className="flex min-w-0 flex-col">+ {ACCESS_PERMISSIONS_SKELETON_KEYS.map(key => (+ <div key={key} className="flex min-w-0 flex-col gap-2 border-b border-divider-subtle py-4 first:pt-0 last:border-b-0 last:pb-0">+ <SkeletonRectangle className="h-4 w-32 animate-pulse" />+ <SkeletonRectangle className="my-0 h-8 w-full animate-pulse rounded-lg" />+ </div>+ ))}+ </div>+ )+}++export function AccessPermissionsSection({+ appInstanceId,+ environmentPolicies,+ isLoading,+ isError,+}: {+ appInstanceId: string+ environmentPolicies?: EnvironmentAccessPolicy[]+ isLoading: boolean+ isError: boolean+}) {+ const { t } = useTranslation('deployments')+ const policyRows = environmentPolicies ?? []++ return (+ <Section+ title={t('access.permissions.title')}+ showDivider={false}+ >+ {isLoading+ ? <AccessPermissionsSkeleton />+ : isError+ ? <DeploymentStateMessage variant="section">{t('common.loadFailed')}</DeploymentStateMessage>+ : policyRows.length === 0+ ? (+ <DeploymentEmptyState+ variant="section"+ icon="i-ri-rocket-line"+ title={t('access.runAccess.noEnvsTitle')}+ description={t('access.runAccess.noEnvs')}+ />+ )+ : (+ <div className="flex min-w-0 flex-col">+ {policyRows.map((environmentPolicy) => {+ const environment = environmentPolicy.environment+ return (+ <EnvironmentPermissionRow+ key={environment.id}+ appInstanceId={appInstanceId}+ environment={environment}+ summaryPolicy={environmentPolicy.policy}+ resolvedSubjects={environmentPolicy.resolvedSubjects}+ />+ )+ })}+ </div>+ )}+ </Section>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/permissions.tsx b/web/features/deployments/detail/settings-tab/access/permissions.tsxnew file mode 100644index 00000000000..1ae3f4e0653--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/permissions.tsx@@ -0,0 +1,205 @@+'use client'++import type {+ AccessPolicy,+ Environment,+ Subject,+} from '@dify/contracts/enterprise/types.gen'+import type {+ AccessPermissionKind,+ SelectableAccessSubject,+} from './access-policy'+import type { AccessSubjectSelectionValue } from '@/app/components/app/app-access-control/access-subject-selector/types'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import {+ accessControlSelectionFromSubjects,+ accessModeToPermissionKey,+ normalizeResolvedSubject,+ permissionKeyToAccessMode,+ permissionKeyToAppAccessMode,+ policySubjects,+ selectedSubjectsFromPolicy,+ subjectsFromAccessControlSelection,+} from './access-policy'+import {+ DeploymentAccessControlDialog,+ PermissionSummaryButton,+} from './permission-row-components'++type EnvironmentPermissionRowProps = {+ appInstanceId: string+ disabled?: boolean+ environment: Environment+ summaryPolicy?: AccessPolicy+ resolvedSubjects?: Subject[]+}++export function EnvironmentPermissionRow({+ appInstanceId,+ disabled,+ environment,+ summaryPolicy,+ resolvedSubjects = [],+}: EnvironmentPermissionRowProps) {+ const { t } = useTranslation('deployments')+ const environmentId = environment.id+ const setEnvironmentAccessPolicy = useMutation(consoleQuery.enterprise.accessService.updateAccessPolicy.mutationOptions())+ const policy = summaryPolicy+ const policyKind = accessModeToPermissionKey(policy?.mode)+ const policyFingerprint = policy+ ? `${policy.mode}:${policy.subjects.map(subject => `${subject.subjectType}:${subject.subjectId}`).join(',')}`+ : 'no-policy'+ const [draft, setDraft] = useState<{+ fingerprint?: string+ kind?: AccessPermissionKind+ subjects?: SelectableAccessSubject[]+ }>({})+ const subjectLabelCandidates = [+ ...(draft.subjects ?? []),+ ...resolvedSubjects+ .flatMap((subject) => {+ const normalizedSubject = normalizeResolvedSubject(subject)+ return normalizedSubject ? [normalizedSubject] : []+ }),+ ]+ const hasDraft = draft.fingerprint === policyFingerprint+ const permissionKind = hasDraft && draft.kind ? draft.kind : policyKind+ const policySelectedSubjects = policyKind === 'specific' ? selectedSubjectsFromPolicy(policy, subjectLabelCandidates) : []+ const subjects = hasDraft && draft.subjects ? draft.subjects : policySelectedSubjects+ const subjectSelection = accessControlSelectionFromSubjects(subjects)+ const isSaving = setEnvironmentAccessPolicy.isPending+ const controlsDisabled = disabled || isSaving+ const envName = environment.displayName++ const persistPolicy = (+ nextKind: AccessPermissionKind,+ nextSubjects: SelectableAccessSubject[],+ options?: {+ onSuccess?: () => void+ },+ ) => {+ if (nextKind === 'specific' && nextSubjects.length === 0)+ return false++ setEnvironmentAccessPolicy.mutate(+ {+ params: {+ appInstanceId,+ environmentId,+ },+ body: {+ appInstanceId,+ environmentId,+ mode: permissionKeyToAccessMode(nextKind),+ subjects: nextKind === 'specific' ? policySubjects(nextSubjects) : [],+ },+ },+ {+ onSuccess: options?.onSuccess,+ onError: () => {+ toast.error(t('access.permission.updateFailed'))+ },+ },+ )+ return true+ }++ const handlePermissionSubmit = (+ nextKind: AccessPermissionKind,+ nextSelection: AccessSubjectSelectionValue,+ options?: {+ onSuccess?: () => void+ },+ ) => {+ const normalizedSubjects = nextKind === 'specific' ? subjectsFromAccessControlSelection(nextSelection) : []+ persistPolicy(nextKind, normalizedSubjects, {+ onSuccess: () => {+ setDraft({+ fingerprint: policyFingerprint,+ kind: nextKind,+ subjects: normalizedSubjects,+ })+ options?.onSuccess?.()+ },+ })+ }++ return (+ <div className="flex min-w-0 flex-col gap-2 border-b border-divider-subtle py-4 first:pt-0 last:border-b-0 last:pb-0">+ <div className="flex min-w-0 items-center">+ <span className="min-w-0 truncate system-sm-regular text-text-primary">+ {envName}+ </span>+ </div>+ <EnvironmentPermissionEditor+ permissionKind={permissionKind}+ subjectSelection={subjectSelection}+ subjects={subjects}+ disabled={controlsDisabled}+ environmentLabel={envName}+ saving={isSaving}+ onSubmit={handlePermissionSubmit}+ />+ </div>+ )+}++function EnvironmentPermissionEditor({+ permissionKind,+ subjectSelection,+ subjects,+ disabled,+ environmentLabel,+ saving,+ onSubmit,+}: {+ permissionKind: AccessPermissionKind+ subjectSelection: AccessSubjectSelectionValue+ subjects: SelectableAccessSubject[]+ disabled?: boolean+ environmentLabel: string+ saving?: boolean+ onSubmit: (+ nextKind: AccessPermissionKind,+ nextSelection: AccessSubjectSelectionValue,+ options?: { onSuccess?: () => void },+ ) => void+}) {+ const [dialogOpen, setDialogOpen] = useState(false)++ const handleSubmit = (nextKind: AccessPermissionKind, nextSelection: AccessSubjectSelectionValue) => {+ onSubmit(nextKind, nextSelection, {+ onSuccess: () => setDialogOpen(false),+ })+ }++ return (+ <>+ <PermissionSummaryButton+ value={permissionKind}+ subjects={subjects}+ disabled={disabled}+ loading={saving}+ environmentLabel={environmentLabel}+ onClick={() => setDialogOpen(true)}+ />+ {dialogOpen && (+ <DeploymentAccessControlDialog+ initialDraft={{+ currentMenu: permissionKeyToAppAccessMode(permissionKind),+ specificGroups: subjectSelection.groups,+ specificMembers: subjectSelection.members,+ selectedGroupsForBreadcrumb: [],+ }}+ saving={saving}+ onClose={() => setDialogOpen(false)}+ onSubmit={handleSubmit}+ />+ )}+ </>+ )+}diff --git a/web/features/deployments/detail/settings-tab/access/url.ts b/web/features/deployments/detail/settings-tab/access/url.tsnew file mode 100644index 00000000000..fe703043087--- /dev/null+++ b/web/features/deployments/detail/settings-tab/access/url.ts@@ -0,0 +1,10 @@+export function getUrlOrigin(url?: string) {+ if (!url)+ return undefined+ try {+ return new URL(url).origin+ }+ catch {+ return url+ }+}diff --git a/web/features/deployments/detail/table-styles.ts b/web/features/deployments/detail/table-styles.tsnew file mode 100644index 00000000000..e9ca904168b--- /dev/null+++ b/web/features/deployments/detail/table-styles.ts@@ -0,0 +1,31 @@+import { cn } from '@langgenius/dify-ui/cn'++export const DEPLOYMENT_DETAIL_TABLE_COLUMN_CLASS_NAMES = {+ actions: 'w-14 py-1.5 whitespace-nowrap',+ currentRelease: '',+ environment: 'whitespace-nowrap',+ status: 'whitespace-nowrap',+}++export const RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES = {+ action: 'w-14 py-1.5 whitespace-nowrap',+ author: 'whitespace-nowrap',+ createdAt: 'whitespace-nowrap',+ deployedTo: '',+ release: 'whitespace-nowrap',+ sourceApp: 'whitespace-nowrap',+}++export const API_KEY_DETAIL_TABLE_COLUMN_CLASS_NAMES = {+ action: 'w-16 py-1.5 whitespace-nowrap',+ environment: 'whitespace-nowrap',+ key: '',+ name: 'whitespace-nowrap',+}++export const DETAIL_TABLE_ACTION_TRIGGER_CLASS_NAME = cn(+ 'inline-flex size-8 items-center justify-center rounded-md text-text-tertiary outline-hidden',+ 'hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid',+ 'data-popup-open:bg-state-base-hover data-popup-open:text-text-secondary',+ 'disabled:cursor-not-allowed disabled:opacity-50',+)diff --git a/web/features/deployments/detail/table.tsx b/web/features/deployments/detail/table.tsxnew file mode 100644index 00000000000..eef2e5ee80d--- /dev/null+++ b/web/features/deployments/detail/table.tsx@@ -0,0 +1,91 @@+import type { ComponentProps } from 'react'+import { cn } from '@langgenius/dify-ui/cn'++type DetailTableProps = ComponentProps<'table'> & {+ containerClassName?: string+}++export function DetailTable({ className, containerClassName, ...props }: DetailTableProps) {+ return (+ <div+ data-slot="deployment-detail-table-container"+ className={cn('relative w-full min-w-0 pc:overflow-x-auto', containerClassName)}+ >+ <table+ data-slot="deployment-detail-table"+ className={cn('w-full max-w-full min-w-[700px] border-collapse border-0 text-sm', className)}+ {...props}+ />+ </div>+ )+}++export function DetailTableHeader({ className, ...props }: ComponentProps<'thead'>) {+ return (+ <thead+ data-slot="deployment-detail-table-header"+ className={cn('h-8 border-b border-divider-subtle system-xs-medium-uppercase text-text-tertiary [&_tr]:border-b-0 [&_tr]:hover:bg-transparent', className)}+ {...props}+ />+ )+}++export function DetailTableBody({ className, ...props }: ComponentProps<'tbody'>) {+ return (+ <tbody+ data-slot="deployment-detail-table-body"+ className={cn('system-sm-regular text-text-secondary', className)}+ {...props}+ />+ )+}++export function DetailTableRow({ className, ...props }: ComponentProps<'tr'>) {+ return (+ <tr+ data-slot="deployment-detail-table-row"+ className={cn('h-8 border-b border-divider-subtle transition-colors hover:bg-background-default-hover', className)}+ {...props}+ />+ )+}++export function DetailTableHead({ className, ...props }: ComponentProps<'th'>) {+ return (+ <th+ data-slot="deployment-detail-table-head"+ className={cn(className, 'box-border max-w-[200px] px-2.5 py-0 text-left align-middle font-medium whitespace-nowrap first:pl-3')}+ {...props}+ />+ )+}++export function DetailTableCell({ className, ...props }: ComponentProps<'td'>) {+ return (+ <td+ data-slot="deployment-detail-table-cell"+ className={cn(className, 'box-border max-w-[200px] px-2.5 py-[5px] align-middle first:pl-3')}+ {...props}+ />+ )+}++export function DetailTableCardList({ className, ...props }: ComponentProps<'div'>) {+ return (+ <div+ data-slot="deployment-detail-table-card-list"+ className={cn('overflow-hidden rounded-lg border border-divider-subtle bg-background-default', className)}+ {...props}+ />+ )+}++export function DetailTableCard({ className, ...props }: ComponentProps<'div'>) {+ return (+ <div+ data-slot="deployment-detail-table-card"+ className={cn('border-b border-divider-subtle last:border-b-0 hover:bg-background-default-hover', className)}+ {...props}+ />+ )+}diff --git a/web/features/deployments/detail/tabs.ts b/web/features/deployments/detail/tabs.tsnew file mode 100644index 00000000000..59820e9ca39--- /dev/null+++ b/web/features/deployments/detail/tabs.ts@@ -0,0 +1,9 @@+export const INSTANCE_DETAIL_TAB_KEYS = ['overview', 'instances', 'releases', 'access', 'api-tokens'] as const++export type InstanceDetailTabKey = typeof INSTANCE_DETAIL_TAB_KEYS[number]++const INSTANCE_DETAIL_TAB_KEY_SET = new Set<string>(INSTANCE_DETAIL_TAB_KEYS)++export function isInstanceDetailTabKey(value?: string): value is InstanceDetailTabKey {+ return value != null && INSTANCE_DETAIL_TAB_KEY_SET.has(value)+}diff --git a/web/features/deployments/detail/versions-tab.tsx b/web/features/deployments/detail/versions-tab.tsxnew file mode 100644index 00000000000..b58752711c4--- /dev/null+++ b/web/features/deployments/detail/versions-tab.tsx@@ -0,0 +1,12 @@+'use client'+import { ReleaseHistoryTable } from './versions-tab/release-history-table'++export function VersionsTab({ appInstanceId }: {+ appInstanceId: string+}) {+ return (+ <div className="flex w-full min-w-0 flex-col gap-4 px-6 py-6">+ <ReleaseHistoryTable appInstanceId={appInstanceId} />+ </div>+ )+}diff --git a/web/features/deployments/detail/versions-tab/__tests__/deploy-release-menu.spec.tsx b/web/features/deployments/detail/versions-tab/__tests__/deploy-release-menu.spec.tsxnew file mode 100644index 00000000000..7692cd3ad39--- /dev/null+++ b/web/features/deployments/detail/versions-tab/__tests__/deploy-release-menu.spec.tsx@@ -0,0 +1,104 @@+import type { Release } from '@dify/contracts/enterprise/types.gen'+import { ReleaseSource } from '@dify/contracts/enterprise/types.gen'+import { fireEvent, render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { DeployReleaseMenu } from '../deploy-release-menu'++const mockUseQuery = vi.hoisted(() => vi.fn())+const mockUseMutation = vi.hoisted(() => vi.fn())+const mockDeleteRelease = vi.fn()++vi.mock('@langgenius/dify-ui/dropdown-menu', () => import('@/__mocks__/base-ui-dropdown-menu'))++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQuery: (...args: unknown[]) => mockUseQuery(...args),+ useMutation: (...args: unknown[]) => mockUseMutation(...args),+ }+})++vi.mock('../edit-release-dialog', () => ({+ EditReleaseDialog: () => null,+}))++vi.mock('../delete-release-dialog', () => ({+ DeleteReleaseDialog: ({ open }: { open: boolean }) => open ? <div role="dialog">delete confirm</div> : null,+}))++vi.mock('../release-dsl-export', () => ({+ exportReleaseDsl: vi.fn(),+}))++function createRelease(): Release {+ return {+ id: 'release-1',+ appInstanceId: 'app-instance-1',+ displayName: 'Release 1',+ description: '',+ source: ReleaseSource.RELEASE_SOURCE_UPLOAD,+ gateCommitId: 'commit-1',+ requiredSlots: [],+ createdBy: {+ id: 'account-1',+ displayName: 'Dify Admin',+ },+ createdAt: '2026-01-01T00:00:00.000Z',+ }+}++function environmentDeploymentsErrorResult() {+ return {+ isError: true,+ isLoading: false,+ data: undefined,+ }+}++function appInstanceResult() {+ return {+ data: {+ appInstance: {+ displayName: 'Deployment 1',+ },+ },+ }+}++describe('DeployReleaseMenu', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseQuery.mockImplementation(() => {+ return mockUseQuery.mock.calls.length % 2 === 1+ ? environmentDeploymentsErrorResult()+ : appInstanceResult()+ })+ mockUseMutation.mockReturnValue({+ isPending: false,+ mutate: mockDeleteRelease,+ })+ })++ it('should disable release deletion when deployment usage cannot be checked', () => {+ const release = createRelease()++ render(+ <DeployReleaseMenu+ appInstanceId="app-instance-1"+ releaseId={release.id}+ releaseRows={[release]}+ />,+ )++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))+ const deleteItem = screen.getByRole('menuitem', { name: 'deployments.versions.deleteRelease' })++ expect(deleteItem).toHaveAttribute('aria-disabled', 'true')++ fireEvent.click(deleteItem)++ expect(screen.queryByText('delete confirm')).not.toBeInTheDocument()+ expect(mockDeleteRelease).not.toHaveBeenCalled()+ })+})diff --git a/web/features/deployments/detail/versions-tab/__tests__/release-history-rows.spec.tsx b/web/features/deployments/detail/versions-tab/__tests__/release-history-rows.spec.tsxnew file mode 100644index 00000000000..30f71655110--- /dev/null+++ b/web/features/deployments/detail/versions-tab/__tests__/release-history-rows.spec.tsx@@ -0,0 +1,85 @@+import type { ReleaseWithSummaryDeployments } from '../release-deployments'+import { ReleaseSource, RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { render, within } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { ReleaseHistoryRows } from '../release-history-rows'++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQuery: () => ({ data: undefined }),+ }+})++vi.mock('../deploy-release-menu', () => ({+ DeployReleaseMenu: () => <button type="button">Actions</button>,+}))++function createReleaseRow(overrides: Partial<ReleaseWithSummaryDeployments> = {}): ReleaseWithSummaryDeployments {+ return {+ id: 'release-1',+ appInstanceId: 'app-instance-1',+ displayName: 'Initial Release',+ description: '',+ source: ReleaseSource.RELEASE_SOURCE_UPLOAD,+ gateCommitId: '2f414f18abcdef',+ requiredSlots: [],+ createdBy: {+ id: 'account-1',+ displayName: 'Dify Admin',+ },+ createdAt: '2026-01-01T00:00:00.000Z',+ summaryDeployments: [],+ ...overrides,+ } as ReleaseWithSummaryDeployments+}++describe('ReleaseHistoryRows', () => {+ it('should render the desktop release list with the knowledge table style', () => {+ const { container } = render(+ <ReleaseHistoryRows+ appInstanceId="app-instance-1"+ releaseRows={[createReleaseRow()]}+ />,+ )++ const table = container.querySelector('table')+ const tableScope = within(table!)+ const header = table!.querySelector('thead')+ const headerCell = table!.querySelector('th')+ const bodyRow = table!.querySelector('tbody tr')++ expect(table).toHaveClass('w-full', 'border-collapse', 'border-0', 'text-sm')+ expect(header).toHaveClass('border-b', 'border-divider-subtle')+ expect(headerCell).not.toHaveClass('bg-background-section-burn', 'rounded-l-lg')+ expect(bodyRow).toHaveClass('h-8', 'border-b', 'border-divider-subtle', 'hover:bg-background-default-hover')+ expect(tableScope.getByText('Initial Release')).toBeInTheDocument()+ })++ it('should render release deployments with the dot status style', () => {+ const { container } = render(+ <ReleaseHistoryRows+ appInstanceId="app-instance-1"+ releaseRows={[+ createReleaseRow({+ summaryDeployments: [{+ environmentId: 'env-1',+ environmentName: 'test-cpu',+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY,+ }],+ }),+ ]}+ />,+ )++ const table = container.querySelector('table')+ const deploymentLabel = table!.querySelector('.text-util-colors-green-green-600')++ expect(deploymentLabel).toHaveTextContent('test-cpu')+ expect(deploymentLabel).toHaveClass('text-util-colors-green-green-600', 'system-xs-medium')+ expect(deploymentLabel).not.toHaveClass('border', 'rounded-md', 'bg-util-colors-green-green-50')+ expect(deploymentLabel).not.toHaveAttribute('data-base-ui-tooltip-trigger')+ expect(container.querySelector('.shadow-status-indicator-green-shadow')).toBeInTheDocument()+ })+})diff --git a/web/features/deployments/detail/versions-tab/delete-release-dialog.tsx b/web/features/deployments/detail/versions-tab/delete-release-dialog.tsxnew file mode 100644index 00000000000..5e60685f73c--- /dev/null+++ b/web/features/deployments/detail/versions-tab/delete-release-dialog.tsx@@ -0,0 +1,63 @@+'use client'++import type { Release } from '@dify/contracts/enterprise/types.gen'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { useTranslation } from 'react-i18next'++export function DeleteReleaseDialog({+ open,+ release,+ isDeleting,+ onOpenChange,+ onConfirm,+}: {+ open: boolean+ release: Release+ isDeleting: boolean+ onOpenChange: (open: boolean) => void+ onConfirm: () => void+}) {+ const { t } = useTranslation('deployments')++ return (+ <AlertDialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (isDeleting)+ return+ onOpenChange(nextOpen)+ }}+ >+ <AlertDialogContent className="w-120">+ <div className="flex flex-col gap-3 px-6 pt-6 pb-2">+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('versions.deleteConfirmTitle')}+ </AlertDialogTitle>+ <AlertDialogDescription className="system-sm-regular text-text-tertiary">+ {t('versions.deleteConfirmDesc', { name: release.displayName })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions className="pt-3">+ <AlertDialogCancelButton variant="secondary" disabled={isDeleting}>+ {t('versions.cancelDelete')}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton+ loading={isDeleting}+ disabled={isDeleting}+ onClick={onConfirm}+ >+ {t('versions.deleteRelease')}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/web/features/deployments/detail/versions-tab/deploy-release-menu-utils.spec.ts b/web/features/deployments/detail/versions-tab/deploy-release-menu-utils.spec.tsnew file mode 100644index 00000000000..0f5073bb102--- /dev/null+++ b/web/features/deployments/detail/versions-tab/deploy-release-menu-utils.spec.ts@@ -0,0 +1,65 @@+import type {+ Environment,+ EnvironmentDeployment,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import type { TFunction } from 'i18next'+import { ReleaseSource, RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { describe, expect, it } from 'vitest'+import { buildDeployMenuSections } from './deploy-release-menu-utils'++const t = ((key: string, options?: { name?: string }) => {+ return options?.name ? `${key}:${options.name}` : key+}) as unknown as TFunction<'deployments'>++function createRelease(id: string): Release {+ return {+ id,+ appInstanceId: 'app-instance-1',+ displayName: id,+ description: '',+ source: ReleaseSource.RELEASE_SOURCE_SOURCE_APP,+ gateCommitId: id,+ requiredSlots: [],+ createdBy: {+ id: 'account-1',+ displayName: 'Dify Admin',+ },+ createdAt: '2026-01-01T00:00:00.000Z',+ }+}++describe('buildDeployMenuSections', () => {+ it('disables deploy actions while an environment is undeploying', () => {+ const env = {+ id: 'env-1',+ displayName: 'Production',+ } as Environment+ const targetRelease = createRelease('release-1')+ const deployment = {+ appInstanceId: 'app-instance-1',+ environment: env,+ status: RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING,+ currentRelease: createRelease('release-0'),+ updatedAt: '2026-01-01T00:00:00.000Z',+ } as EnvironmentDeployment++ const sections = buildDeployMenuSections({+ environments: [env],+ environmentDeployments: [deployment],+ releaseRows: [targetRelease],+ releaseId: targetRelease.id,+ targetRelease,+ t,+ })++ expect(sections).toHaveLength(1)+ expect(sections[0]?.group).toBe('unavailable')+ expect(sections[0]?.rows[0]).toMatchObject({+ environmentId: env.id,+ state: 'deploying',+ label: 'versions.deployingTo:Production',+ disabledReason: 'versions.disabledReason.deploying',+ })+ })+})diff --git a/web/features/deployments/detail/versions-tab/deploy-release-menu-utils.ts b/web/features/deployments/detail/versions-tab/deploy-release-menu-utils.tsnew file mode 100644index 00000000000..9498aab0024--- /dev/null+++ b/web/features/deployments/detail/versions-tab/deploy-release-menu-utils.ts@@ -0,0 +1,150 @@+import type {+ Environment,+ EnvironmentDeployment,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import type { TFunction } from 'i18next'+import { releaseDeploymentAction } from '../../shared/domain/release-action'+import { isRuntimeDeploymentInProgress, isUndeployedDeploymentRow } from '../../shared/domain/runtime-status'++export type DeployMenuRowState = 'deploy' | 'rollback' | 'current' | 'deploying'++export type DeployMenuRow = {+ env?: Environment+ environmentId: string+ state: DeployMenuRowState+ label: string+ disabledReason?: string+}++export type DeployMenuGroup = 'deploy' | 'rollback' | 'unavailable'++export type DeployMenuSection = {+ group: DeployMenuGroup+ rows: DeployMenuRow[]+}++const GROUP_ORDER: DeployMenuGroup[] = ['deploy', 'rollback', 'unavailable']++function stateToGroup(state: DeployMenuRowState): DeployMenuGroup {+ if (state === 'rollback')+ return 'rollback'+ if (state === 'deploy')+ return 'deploy'+ return 'unavailable'+}++export function releaseUsageCount(releaseId: string, deploymentRows: EnvironmentDeployment[]) {+ const environmentIds = new Set<string>()++ deploymentRows.forEach((row) => {+ const usesRelease = row.currentRelease?.id === releaseId || row.desiredRelease?.id === releaseId+ if (usesRelease)+ environmentIds.add(row.environment.id)+ })++ return environmentIds.size+}++function buildDeployMenuRow({+ env,+ deploymentRows,+ releaseRows,+ releaseId,+ targetRelease,+ t,+}: {+ env: Environment+ deploymentRows: EnvironmentDeployment[]+ releaseRows: Release[]+ releaseId: string+ targetRelease: Release+ t: TFunction<'deployments'>+}): DeployMenuRow {+ const envId = env.id+ const envName = env.displayName+ const row = deploymentRows.find(item => item.environment.id === envId)+ const currentRelease = row?.currentRelease+ const isCurrent = currentRelease?.id === releaseId+ const isEnvironmentInProgress = isRuntimeDeploymentInProgress(row?.status)++ if (isEnvironmentInProgress) {+ return {+ env,+ environmentId: envId,+ state: 'deploying',+ label: t('versions.deployingTo', { name: envName }),+ disabledReason: t('versions.disabledReason.deploying'),+ }+ }+ if (isCurrent) {+ return {+ env,+ environmentId: envId,+ state: 'current',+ label: t('versions.currentOn', { name: envName }),+ disabledReason: t('versions.disabledReason.current', { name: envName }),+ }+ }++ const action = releaseDeploymentAction({+ targetRelease,+ currentRelease,+ releaseRows,+ isExistingRelease: true,+ })++ if (!row) {+ return {+ env,+ environmentId: envId,+ state: 'deploy',+ label: t('versions.deployTo', { name: envName }),+ }+ }+ if (action === 'rollback') {+ return {+ env,+ environmentId: envId,+ state: 'rollback',+ label: t('versions.rollbackTo', { name: envName }),+ }+ }+ return {+ env,+ environmentId: envId,+ state: 'deploy',+ label: t('versions.deployTo', { name: envName }),+ }+}++export function buildDeployMenuSections({+ environments,+ environmentDeployments,+ releaseRows,+ releaseId,+ targetRelease,+ t,+}: {+ environments: Environment[]+ environmentDeployments: EnvironmentDeployment[]+ releaseRows: Release[]+ releaseId: string+ targetRelease: Release+ t: TFunction<'deployments'>+}) {+ const deploymentRows = environmentDeployments.filter(row => !isUndeployedDeploymentRow(row))+ const menuRows = environments.map(env => buildDeployMenuRow({+ env,+ deploymentRows,+ releaseRows,+ releaseId,+ targetRelease,+ t,+ }))++ return GROUP_ORDER.map(group => ({+ group,+ rows: menuRows.filter(row => stateToGroup(row.state) === group),+ })).filter((section): section is DeployMenuSection => section.rows.length > 0)+}diff --git a/web/features/deployments/detail/versions-tab/deploy-release-menu.tsx b/web/features/deployments/detail/versions-tab/deploy-release-menu.tsxnew file mode 100644index 00000000000..f12a28ff896--- /dev/null+++ b/web/features/deployments/detail/versions-tab/deploy-release-menu.tsx@@ -0,0 +1,239 @@+'use client'++import type { Release } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation, useQuery } from '@tanstack/react-query'+import { useSetAtom } from 'jotai'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { TitleTooltip } from '../../components/title-tooltip'+import { openDeployDrawerAtom } from '../../deploy-drawer/state'+import { isUndeployedDeploymentRow } from '../../shared/domain/runtime-status'+import { DETAIL_TABLE_ACTION_TRIGGER_CLASS_NAME } from '../table-styles'+import { DeleteReleaseDialog } from './delete-release-dialog'+import {+ buildDeployMenuSections,+ releaseUsageCount,+} from './deploy-release-menu-utils'+import { EditReleaseDialog } from './edit-release-dialog'+import { exportReleaseDsl } from './release-dsl-export'++export function DeployReleaseMenu({ appInstanceId, releaseId, releaseRows, onDeleted }: {+ appInstanceId: string+ releaseId: string+ releaseRows: Release[]+ onDeleted?: () => void+}) {+ const { t } = useTranslation('deployments')+ const openDeployDrawer = useSetAtom(openDeployDrawerAtom)+ const [open, setOpen] = useState(false)+ const [showEditDialog, setShowEditDialog] = useState(false)+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)+ const [isExportingDsl, setIsExportingDsl] = useState(false)+ const environmentDeploymentsQuery = useQuery(consoleQuery.enterprise.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: { appInstanceId },+ },+ enabled: open,+ }))+ const { data: appInstanceData } = useQuery(consoleQuery.enterprise.appInstanceService.getAppInstance.queryOptions({+ input: {+ params: { appInstanceId },+ },+ enabled: open,+ }))+ const deleteRelease = useMutation(consoleQuery.enterprise.releaseService.deleteRelease.mutationOptions())++ const environments = (environmentDeploymentsQuery.data?.environmentDeployments ?? [])+ .map(row => row.environment)+ const deploymentRows = environmentDeploymentsQuery.data?.environmentDeployments.filter(row => !isUndeployedDeploymentRow(row)) ?? []+ const targetRelease = releaseRows.find(release => release.id === releaseId)+ const appInstanceName = appInstanceData?.appInstance.displayName++ if (!targetRelease)+ return null++ const targetReleaseName = targetRelease.displayName+ const deleteUsageCount = releaseUsageCount(releaseId, deploymentRows)+ const isCheckingDeleteUsage = open && environmentDeploymentsQuery.isLoading+ const hasDeleteUsageCheckFailed = open && environmentDeploymentsQuery.isError+ const isReleaseInUse = deleteUsageCount > 0+ const isDeletingRelease = deleteRelease.isPending+ const deleteDisabledReason = isCheckingDeleteUsage+ ? t('versions.disabledReason.checkingDeployments')+ : hasDeleteUsageCheckFailed+ ? t('versions.disabledReason.checkDeploymentsFailed')+ : isReleaseInUse+ ? t('versions.disabledReason.releaseInUse', { count: deleteUsageCount })+ : undefined+ const deleteActionDisabled = isDeletingRelease || isCheckingDeleteUsage || hasDeleteUsageCheckFailed || isReleaseInUse++ const handleExportDsl = async () => {+ if (isExportingDsl)+ return++ setIsExportingDsl(true)+ try {+ await exportReleaseDsl({ release: targetRelease, releaseId, appInstanceName })+ setOpen(false)+ }+ catch {+ toast.error(t('versions.exportDslFailed'))+ }+ finally {+ setIsExportingDsl(false)+ }+ }++ function handleDeleteRelease() {+ if (deleteActionDisabled)+ return++ deleteRelease.mutate(+ {+ params: {+ releaseId,+ },+ },+ {+ onSuccess: () => {+ setShowDeleteConfirm(false)+ toast.success(t('versions.deleteSuccess', { name: targetReleaseName }))+ onDeleted?.()+ },+ onError: () => {+ toast.error(t('versions.deleteFailed'))+ },+ },+ )+ }++ const groupedRows = buildDeployMenuSections({+ environments,+ environmentDeployments: environmentDeploymentsQuery.data?.environmentDeployments ?? [],+ releaseRows,+ releaseId,+ targetRelease,+ t,+ })++ return (+ <>+ <DropdownMenu modal={false} open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ aria-label={t('versions.moreActions')}+ className={DETAIL_TABLE_ACTION_TRIGGER_CLASS_NAME}+ >+ <span aria-hidden className="i-ri-more-fill size-4" />+ </DropdownMenuTrigger>+ {open && (+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="w-60">+ <DropdownMenuItem+ className="gap-2 px-3"+ onClick={() => {+ setOpen(false)+ setShowEditDialog(true)+ }}+ >+ <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">+ {t('versions.editRelease')}+ </span>+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={isExportingDsl}+ aria-disabled={isExportingDsl}+ className={cn(+ 'gap-2 px-3',+ isExportingDsl && 'cursor-not-allowed opacity-60',+ )}+ onClick={handleExportDsl}+ >+ <span aria-hidden className="i-ri-download-2-line size-4 shrink-0 text-text-tertiary" />+ <span className="system-sm-regular text-text-secondary">+ {isExportingDsl ? t('versions.exportingDsl') : t('versions.exportDsl')}+ </span>+ </DropdownMenuItem>+ {groupedRows.length > 0 && <div className="my-1 border-t border-divider-subtle" aria-hidden />}+ {groupedRows.map((section, sectionIndex) => (+ <div key={section.group}>+ {sectionIndex > 0 && <div className="my-1 border-t border-divider-subtle" aria-hidden />}+ <div className="px-3 pt-1.5 pb-1 system-2xs-medium-uppercase text-text-quaternary">+ {t(`versions.groupHeader.${section.group}`)}+ </div>+ {section.rows.map((row) => {+ const isDisabled = row.state === 'current' || row.state === 'deploying'+ return (+ <TitleTooltip key={row.environmentId} content={isDisabled ? row.disabledReason : undefined}>+ <DropdownMenuItem+ disabled={isDisabled}+ aria-disabled={isDisabled}+ className={cn(+ 'gap-2 px-3',+ isDisabled && 'cursor-not-allowed opacity-60',+ )}+ onClick={() => {+ if (isDisabled)+ return+ setOpen(false)+ openDeployDrawer({ appInstanceId, environmentId: row.environmentId, releaseId })+ }}+ >+ <span className="system-sm-regular text-text-secondary">+ {row.label}+ </span>+ </DropdownMenuItem>+ </TitleTooltip>+ )+ })}+ </div>+ ))}+ <div className="my-1 border-t border-divider-subtle" aria-hidden />+ <TitleTooltip content={deleteDisabledReason}>+ <DropdownMenuItem+ variant="destructive"+ disabled={deleteActionDisabled}+ aria-disabled={deleteActionDisabled}+ className={cn(+ 'gap-2 px-3',+ deleteActionDisabled && 'cursor-not-allowed opacity-60',+ )}+ onClick={() => {+ if (deleteActionDisabled)+ return+ setOpen(false)+ setShowDeleteConfirm(true)+ }}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />+ <span className="system-sm-regular">{t('versions.deleteRelease')}</span>+ </DropdownMenuItem>+ </TitleTooltip>+ </DropdownMenuContent>+ )}+ </DropdownMenu>++ <EditReleaseDialog+ release={targetRelease}+ open={showEditDialog}+ onOpenChange={setShowEditDialog}+ />++ <DeleteReleaseDialog+ open={showDeleteConfirm}+ release={targetRelease}+ isDeleting={isDeletingRelease}+ onOpenChange={setShowDeleteConfirm}+ onConfirm={handleDeleteRelease}+ />+ </>+ )+}diff --git a/web/features/deployments/detail/versions-tab/deployed-to-badge.tsx b/web/features/deployments/detail/versions-tab/deployed-to-badge.tsxnew file mode 100644index 00000000000..b0159043b78--- /dev/null+++ b/web/features/deployments/detail/versions-tab/deployed-to-badge.tsx@@ -0,0 +1,41 @@+'use client'++import type { ReleaseDeployment } from './release-deployments'+import { cn } from '@langgenius/dify-ui/cn'+import { StatusDot } from '@langgenius/dify-ui/status-dot'+import { useTranslation } from 'react-i18next'+import { isRuntimeDeploymentInProgress } from '../../shared/domain/runtime-status'+import {+ deploymentStatusDotStatus,+ deploymentStatusDotTextClassName,+} from '../../shared/ui/deployment-status-style'++export function DeployedToBadge({ item }: {+ item: ReleaseDeployment+}) {+ const { t } = useTranslation('deployments')+ const status = item.status+ const statusLabel = t(`versions.deployedStatus.${status}`)+ const dotStatus = deploymentStatusDotStatus(status)+ const isInProgress = isRuntimeDeploymentInProgress(status)+ const textClassName = deploymentStatusDotTextClassName(status)++ return (+ <span+ className={cn(+ 'inline-flex max-w-full cursor-default items-center system-xs-medium',+ textClassName,+ )}+ >+ <StatusDot+ status={dotStatus}+ className={cn('mr-2 shrink-0', isInProgress && 'animate-pulse')}+ />+ <span className="truncate">+ {item.environmentName}+ {' · '}+ {statusLabel}+ </span>+ </span>+ )+}diff --git a/web/features/deployments/detail/versions-tab/edit-release-dialog.tsx b/web/features/deployments/detail/versions-tab/edit-release-dialog.tsxnew file mode 100644index 00000000000..da57965ab3e--- /dev/null+++ b/web/features/deployments/detail/versions-tab/edit-release-dialog.tsx@@ -0,0 +1,188 @@+'use client'++import type { Release } from '@dify/contracts/enterprise/types.gen'+import type { FormEvent } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { Input } from '@langgenius/dify-ui/input'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'++type EditReleaseFormValues = {+ name: string+ description: string+}++function EditReleaseForm({+ release,+ isSaving,+ onClose,+ onSubmit,+}: {+ release: Release+ isSaving: boolean+ onClose: () => void+ onSubmit: (values: EditReleaseFormValues) => void+}) {+ const { t } = useTranslation('deployments')+ const initialName = release.displayName+ const initialDescription = release.description+ const [name, setName] = useState(initialName)+ const [description, setDescription] = useState(initialDescription)+ const normalizedName = name.trim()+ const normalizedDescription = description.trim()+ const nameRequired = !normalizedName+ const hasChanges = normalizedName !== initialName || normalizedDescription !== initialDescription+ const canSave = Boolean(!nameRequired && hasChanges && !isSaving)++ function handleSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault()+ if (!canSave)+ return++ onSubmit({+ name: normalizedName,+ description: normalizedDescription,+ })+ }++ return (+ <form className="flex flex-col gap-4" noValidate autoComplete="off" onSubmit={handleSubmit}>+ <div className="flex flex-col gap-2">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="release-edit-name">+ {t('versions.releaseNameLabel')}+ </label>+ <Input+ id="release-edit-name"+ type="text"+ value={name}+ maxLength={128}+ autoComplete="off"+ aria-invalid={nameRequired || undefined}+ aria-describedby={nameRequired ? 'release-edit-name-error' : undefined}+ onChange={event => setName(event.target.value)}+ className="h-8"+ />+ {nameRequired && (+ <div id="release-edit-name-error" role="alert" className="system-xs-regular text-text-destructive">+ {t('versions.releaseNameRequired')}+ </div>+ )}+ </div>+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-1.5">+ <label className="system-xs-medium-uppercase text-text-tertiary" htmlFor="release-edit-description">+ {t('versions.releaseDescriptionLabel')}+ </label>+ <span className="system-xs-regular text-text-quaternary">{t('versions.optional')}</span>+ </div>+ <Textarea+ id="release-edit-description"+ value={description}+ maxLength={512}+ autoComplete="off"+ onValueChange={setDescription}+ className="min-h-24"+ />+ </div>+ <div className="flex justify-end gap-2 pt-2">+ <Button+ type="button"+ variant="secondary"+ disabled={isSaving}+ onClick={onClose}+ >+ {t('versions.cancelEdit')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ disabled={!canSave}+ loading={isSaving}+ >+ {t('versions.saveEdit')}+ </Button>+ </div>+ </form>+ )+}++export function EditReleaseDialog({+ release,+ open,+ onOpenChange,+}: {+ release: Release+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('deployments')+ const updateRelease = useMutation(consoleQuery.enterprise.releaseService.updateRelease.mutationOptions())+ const formKey = `${release.id}-${release.displayName}-${release.description}`++ function handleOpenChange(nextOpen: boolean) {+ if (!nextOpen && updateRelease.isPending)+ return+ onOpenChange(nextOpen)+ }++ function handleSubmit(values: EditReleaseFormValues) {+ updateRelease.mutate(+ {+ params: {+ releaseId: release.id,+ },+ body: {+ releaseId: release.id,+ displayName: values.name,+ description: values.description,+ },+ },+ {+ onSuccess: (data) => {+ const updatedName = data.release.displayName+ toast.success(t('versions.editSuccess', { name: updatedName }))+ onOpenChange(false)+ },+ onError: () => {+ toast.error(t('versions.editFailed'))+ },+ },+ )+ }++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="w-120 max-w-[calc(100vw-32px)] p-0">+ <DialogCloseButton disabled={updateRelease.isPending} />+ <div className="border-b border-divider-subtle px-6 py-5 pr-14">+ <DialogTitle className="title-xl-semi-bold text-text-primary">+ {t('versions.editRelease')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('versions.editReleaseDescription')}+ </DialogDescription>+ </div>+ <div className="px-6 py-5">+ <EditReleaseForm+ key={formKey}+ release={release}+ isSaving={updateRelease.isPending}+ onClose={() => handleOpenChange(false)}+ onSubmit={handleSubmit}+ />+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/deployments/detail/versions-tab/release-deployments.ts b/web/features/deployments/detail/versions-tab/release-deployments.tsnew file mode 100644index 00000000000..cb6bfe77454--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-deployments.ts@@ -0,0 +1,49 @@+import type {+ Environment,+ Release,+ ReleaseSummary,+ RuntimeInstanceStatus as RuntimeInstanceStatusValue,+} from '@dify/contracts/enterprise/types.gen'+import {+ ReleaseEnvironmentActionKind,+ RuntimeInstanceStatus,+} from '@dify/contracts/enterprise/types.gen'++export type ReleaseDeployment = {+ environmentId: string+ environmentName: string+ status: RuntimeInstanceStatusValue+}++export type ReleaseWithSummaryDeployments = Release & {+ summaryDeployments: ReleaseDeployment[]+}++function dedupeReleaseDeployments(items: ReleaseDeployment[]) {+ return items.filter((item, index) => {+ return items.findIndex(candidate => candidate.environmentId === item.environmentId) === index+ })+}++function releaseSummaryEnvironmentDeployment(environment: Environment, status: RuntimeInstanceStatusValue): ReleaseDeployment {+ return {+ environmentId: environment.id,+ environmentName: environment.displayName,+ status,+ }+}++export function getReleaseSummaryDeployments(summary: ReleaseSummary) {+ // Each deployed environment carries its runtime status so a failed deployment+ // surfaces as failed instead of being assumed healthy.+ const deployedItems = summary.deployedEnvironments+ .map(deployment => releaseSummaryEnvironmentDeployment(deployment.environment, deployment.status))+ const actionItems = summary.environmentActions+ .filter(action => action.kind === ReleaseEnvironmentActionKind.RELEASE_ENVIRONMENT_ACTION_KIND_DEPLOYING)+ .map(action => releaseSummaryEnvironmentDeployment(action.environment, RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING))++ return dedupeReleaseDeployments([+ ...deployedItems,+ ...actionItems,+ ])+}diff --git a/web/features/deployments/detail/versions-tab/release-dsl-export.ts b/web/features/deployments/detail/versions-tab/release-dsl-export.tsnew file mode 100644index 00000000000..fa074bf5f87--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-dsl-export.ts@@ -0,0 +1,44 @@+import type { Release } from '@dify/contracts/enterprise/types.gen'+import { downloadBlob } from '@/utils/download'+import { fetchReleaseDsl } from './release-dsl'++const YAML_EXTENSION_PATTERN = /\.ya?ml$/i+const INVALID_FILENAME_CHARS_PATTERN = /[\\/:*?"<>|]+/g+const FILENAME_SEPARATOR_PATTERN = /[\s-]+/g++function sanitizeFileNamePart(value?: string) {+ if (!value)+ return ''++ return value+ .trim()+ .replace(YAML_EXTENSION_PATTERN, '')+ .replace(INVALID_FILENAME_CHARS_PATTERN, '-')+ .replace(FILENAME_SEPARATOR_PATTERN, '-')+ .replace(/^-+|-+$/g, '')+}++function releaseDslFileName({ release, appInstanceName }: {+ release: Release+ appInstanceName?: string+}) {+ const projectName = sanitizeFileNamePart(appInstanceName)+ const releaseName = sanitizeFileNamePart(release.displayName) || 'release'+ const baseName = [projectName, releaseName].filter(Boolean).join('-')++ return `${baseName}.yaml`+}++export async function exportReleaseDsl({ release, releaseId, appInstanceName }: {+ release: Release+ releaseId: string+ appInstanceName?: string+}) {+ const data = new Blob([await fetchReleaseDsl(releaseId)], {+ type: 'application/x-yaml;charset=utf-8',+ })+ downloadBlob({+ data,+ fileName: releaseDslFileName({ release, appInstanceName }),+ })+}diff --git a/web/features/deployments/detail/versions-tab/release-dsl.ts b/web/features/deployments/detail/versions-tab/release-dsl.tsnew file mode 100644index 00000000000..488bbd5fb92--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-dsl.ts@@ -0,0 +1,12 @@+import { consoleClient } from '@/service/client'++export async function fetchReleaseDsl(releaseId: string) {+ const response = await consoleClient.enterprise.releaseService.exportReleaseDsl({+ params: { releaseId },+ })++ if (!response.dsl)+ throw new Error('Invalid release DSL response')++ return response.dsl+}diff --git a/web/features/deployments/detail/versions-tab/release-history-deployments.tsx b/web/features/deployments/detail/versions-tab/release-history-deployments.tsxnew file mode 100644index 00000000000..6ac979f2602--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-history-deployments.tsx@@ -0,0 +1,20 @@+'use client'++import type { ReleaseDeployment } from './release-deployments'+import { DeployedToBadge } from './deployed-to-badge'++export function ReleaseDeploymentsContent({+ items,+}: {+ items: ReleaseDeployment[]+}) {+ if (items.length === 0)+ return <span className="text-text-quaternary">—</span>++ return items.map(item => (+ <DeployedToBadge+ key={`${item.environmentId}-${item.status}`}+ item={item}+ />+ ))+}diff --git a/web/features/deployments/detail/versions-tab/release-history-rows.tsx b/web/features/deployments/detail/versions-tab/release-history-rows.tsxnew file mode 100644index 00000000000..f8bb8ce8673--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-history-rows.tsx@@ -0,0 +1,241 @@+'use client'++import type { Release } from '@dify/contracts/enterprise/types.gen'+import type { ReleaseWithSummaryDeployments } from './release-deployments'+import { ReleaseSource } from '@dify/contracts/enterprise/types.gen'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import Link from '@/next/link'+import { consoleQuery } from '@/service/client'+import { TitleTooltip } from '../../components/title-tooltip'+import {+ formatDate,+ releaseCommit,+} from '../../shared/domain/release'+import {+ DetailTable,+ DetailTableBody,+ DetailTableCard,+ DetailTableCardList,+ DetailTableCell,+ DetailTableHead,+ DetailTableHeader,+ DetailTableRow,+} from '../table'+import { RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES } from '../table-styles'+import { DeployReleaseMenu } from './deploy-release-menu'+import {+ ReleaseDeploymentsContent,+} from './release-history-deployments'++function ReleaseTitleTooltip({ release }: {+ release: Release+}) {+ const { t } = useTranslation('deployments')++ return (+ <Tooltip>+ <TooltipTrigger+ render={(+ <span className="inline-flex max-w-full cursor-default truncate text-text-primary">+ {release.displayName}+ </span>+ )}+ />+ <TooltipContent>+ {t('versions.commitTooltip', { commit: releaseCommit(release) })}+ </TooltipContent>+ </Tooltip>+ )+}++function CreatedAtCell({ createdAt }: {+ createdAt: string+}) {+ const { formatTimeFromNow } = useFormatTimeFromNow()+ const ms = Date.parse(createdAt)+ if (Number.isNaN(ms))+ return <>{formatDate(createdAt)}</>+ return (+ <Tooltip>+ <TooltipTrigger+ render={(+ <span className="cursor-default">+ {formatTimeFromNow(ms)}+ </span>+ )}+ />+ <TooltipContent>{formatDate(createdAt)}</TooltipContent>+ </Tooltip>+ )+}++function ReleaseSourceCell({ release }: {+ release: Release+}) {+ const { t } = useTranslation('deployments')+ const sourceAppId = release.sourceAppId+ const sourceAppQuery = useQuery(consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: sourceAppId ?? '' } },+ enabled: Boolean(sourceAppId),+ }))++ if (!sourceAppId) {+ return (+ <span className="text-text-tertiary">+ {release.source === ReleaseSource.RELEASE_SOURCE_UPLOAD ? t('versions.manualDslOption') : '—'}+ </span>+ )+ }++ const sourceAppName = sourceAppQuery.data?.name+ const label = sourceAppName || sourceAppId+ const title = sourceAppName ? `${sourceAppName} (${sourceAppId})` : sourceAppId++ return (+ <TitleTooltip content={title}>+ <Link+ href={`/app/${encodeURIComponent(sourceAppId)}/workflow`}+ target="_blank"+ rel="noreferrer"+ className="inline-flex max-w-full min-w-0 items-center gap-1 text-text-secondary transition-colors hover:text-text-accent"+ >+ <span className="min-w-0 truncate">{label}</span>+ <span className="i-ri-arrow-right-up-line size-3.5 shrink-0" aria-hidden="true" />+ </Link>+ </TitleTooltip>+ )+}++function ReleaseHistoryMobileRows({ appInstanceId, releaseRows, onReleaseDeleted }: {+ appInstanceId: string+ releaseRows: ReleaseWithSummaryDeployments[]+ onReleaseDeleted?: () => void+}) {+ const { t } = useTranslation('deployments')++ return (+ <DetailTableCardList className="pc:hidden">+ {releaseRows.map((row) => {+ const release = row+ const releaseId = release.id+ const hasDeployments = row.summaryDeployments.length > 0++ return (+ <DetailTableCard key={releaseId}>+ <div className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <ReleaseTitleTooltip release={release} />+ <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 system-xs-regular text-text-secondary">+ <CreatedAtCell createdAt={release.createdAt} />+ <span aria-hidden>·</span>+ <span>{row.createdBy.displayName}</span>+ {(release.sourceAppId || release.source === ReleaseSource.RELEASE_SOURCE_UPLOAD) && (+ <>+ <span aria-hidden>·</span>+ <span className="inline-flex max-w-full min-w-0 items-baseline gap-1">+ <span className="shrink-0">{t('versions.col.sourceApp')}</span>+ <ReleaseSourceCell release={release} />+ </span>+ </>+ )}+ </div>+ </div>+ <div className="flex shrink-0 justify-end gap-1">+ <DeployReleaseMenu+ releaseId={releaseId}+ appInstanceId={appInstanceId}+ releaseRows={releaseRows}+ onDeleted={onReleaseDeleted}+ />+ </div>+ </div>+ {hasDeployments && (+ <div className="flex min-w-0 flex-wrap items-center gap-1">+ <ReleaseDeploymentsContent+ items={row.summaryDeployments}+ />+ </div>+ )}+ </div>+ </DetailTableCard>+ )+ })}+ </DetailTableCardList>+ )+}++export function ReleaseHistoryRows({ appInstanceId, releaseRows, onReleaseDeleted }: {+ appInstanceId: string+ releaseRows: ReleaseWithSummaryDeployments[]+ onReleaseDeleted?: () => void+}) {+ const { t } = useTranslation('deployments')++ return (+ <>+ <ReleaseHistoryMobileRows+ appInstanceId={appInstanceId}+ releaseRows={releaseRows}+ onReleaseDeleted={onReleaseDeleted}+ />+ <div className="hidden pc:block">+ <DetailTable className="min-w-[840px]">+ <DetailTableHeader>+ <DetailTableRow>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.release}>{t('versions.col.release')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.sourceApp}>{t('versions.col.sourceApp')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.createdAt}>{t('versions.col.createdAt')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.author}>{t('versions.col.author')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.deployedTo}>{t('versions.col.deployedTo')}</DetailTableHead>+ <DetailTableHead className={`${RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.action} text-right`}>{t('versions.col.action')}</DetailTableHead>+ </DetailTableRow>+ </DetailTableHeader>+ <DetailTableBody>+ {releaseRows.map((row) => {+ const release = row+ const releaseId = release.id++ return (+ <DetailTableRow key={releaseId}>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.release}>+ <ReleaseTitleTooltip release={release} />+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.sourceApp}>+ <ReleaseSourceCell release={release} />+ </DetailTableCell>+ <DetailTableCell className={`${RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.createdAt} text-text-secondary`}>+ <CreatedAtCell createdAt={release.createdAt} />+ </DetailTableCell>+ <DetailTableCell className={`${RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.author} truncate text-text-secondary`}>+ {row.createdBy.displayName}+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.deployedTo}>+ <div className="flex flex-wrap gap-1">+ <ReleaseDeploymentsContent+ items={row.summaryDeployments}+ />+ </div>+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.action}>+ <div className="flex justify-end">+ <DeployReleaseMenu+ releaseId={releaseId}+ appInstanceId={appInstanceId}+ releaseRows={releaseRows}+ onDeleted={onReleaseDeleted}+ />+ </div>+ </DetailTableCell>+ </DetailTableRow>+ )+ })}+ </DetailTableBody>+ </DetailTable>+ </div>+ </>+ )+}diff --git a/web/features/deployments/detail/versions-tab/release-history-table-skeleton.tsx b/web/features/deployments/detail/versions-tab/release-history-table-skeleton.tsxnew file mode 100644index 00000000000..b2c11bcae22--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-history-table-skeleton.tsx@@ -0,0 +1,96 @@+'use client'++import { useTranslation } from 'react-i18next'+import { SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import {+ DetailTable,+ DetailTableBody,+ DetailTableCard,+ DetailTableCardList,+ DetailTableCell,+ DetailTableHead,+ DetailTableHeader,+ DetailTableRow,+} from '../table'+import { RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES } from '../table-styles'++const RELEASE_TABLE_ROW_SKELETON_KEYS = ['latest', 'previous', 'older', 'archived', 'initial']++function ReleaseDeploymentsSkeleton() {+ return (+ <SkeletonRow className="gap-1">+ <SkeletonRectangle className="my-0 h-5 w-20 animate-pulse rounded-md" />+ <SkeletonRectangle className="my-0 h-5 w-18 animate-pulse rounded-md" />+ </SkeletonRow>+ )+}++export function ReleaseHistoryTableSkeleton() {+ const { t } = useTranslation('deployments')++ return (+ <>+ <DetailTableCardList className="pc:hidden">+ {RELEASE_TABLE_ROW_SKELETON_KEYS.map(key => (+ <DetailTableCard key={key}>+ <div className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <SkeletonRectangle className="h-3 w-24 animate-pulse" />+ <SkeletonRow className="mt-1 gap-2">+ <SkeletonRectangle className="h-3 w-28 animate-pulse" />+ <SkeletonRectangle className="h-3 w-20 animate-pulse" />+ </SkeletonRow>+ </div>+ <SkeletonRectangle className="my-0 h-7 w-8 animate-pulse rounded-lg" />+ </div>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <ReleaseDeploymentsSkeleton />+ </div>+ </div>+ </DetailTableCard>+ ))}+ </DetailTableCardList>+ <div className="hidden pc:block">+ <DetailTable className="min-w-[840px]">+ <DetailTableHeader>+ <DetailTableRow>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.release}>{t('versions.col.release')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.sourceApp}>{t('versions.col.sourceApp')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.createdAt}>{t('versions.col.createdAt')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.author}>{t('versions.col.author')}</DetailTableHead>+ <DetailTableHead className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.deployedTo}>{t('versions.col.deployedTo')}</DetailTableHead>+ <DetailTableHead className={`${RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.action} text-right`}>{t('versions.col.action')}</DetailTableHead>+ </DetailTableRow>+ </DetailTableHeader>+ <DetailTableBody>+ {RELEASE_TABLE_ROW_SKELETON_KEYS.map(key => (+ <DetailTableRow key={key}>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.release}>+ <SkeletonRectangle className="h-3 w-24 animate-pulse" />+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.sourceApp}>+ <SkeletonRectangle className="h-3 w-32 animate-pulse" />+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.createdAt}>+ <SkeletonRectangle className="h-3 w-24 animate-pulse" />+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.author}>+ <SkeletonRectangle className="h-3 w-24 animate-pulse" />+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.deployedTo}>+ <ReleaseDeploymentsSkeleton />+ </DetailTableCell>+ <DetailTableCell className={RELEASE_DETAIL_TABLE_COLUMN_CLASS_NAMES.action}>+ <div className="flex justify-end">+ <SkeletonRectangle className="my-0 size-8 animate-pulse rounded-md" />+ </div>+ </DetailTableCell>+ </DetailTableRow>+ ))}+ </DetailTableBody>+ </DetailTable>+ </div>+ </>+ )+}diff --git a/web/features/deployments/detail/versions-tab/release-history-table.tsx b/web/features/deployments/detail/versions-tab/release-history-table.tsxnew file mode 100644index 00000000000..9b402904d3a--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-history-table.tsx@@ -0,0 +1,88 @@+'use client'++import { Pagination } from '@langgenius/dify-ui/pagination'+import { keepPreviousData, useQuery } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { DeploymentEmptyState, DeploymentStateMessage } from '../../components/empty-state'+import { RELEASE_HISTORY_PAGE_SIZE } from '../../shared/domain/pagination'+import { ReleaseHistoryRows } from './release-history-rows'+import { ReleaseHistoryTableSkeleton } from './release-history-table-skeleton'+import { releaseRowFromSummary } from './release-history-types'++export function ReleaseHistoryTable({ appInstanceId }: {+ appInstanceId: string+}) {+ const { t } = useTranslation('deployments')+ const [currentPage, setCurrentPage] = useState(0)+ const releaseHistoryQuery = useQuery(consoleQuery.enterprise.releaseService.listReleaseSummaries.queryOptions({+ input: {+ params: { appInstanceId },+ query: {+ pageNumber: currentPage + 1,+ resultsPerPage: RELEASE_HISTORY_PAGE_SIZE,+ },+ },+ placeholderData: keepPreviousData,+ }))+ const isLoading = releaseHistoryQuery.isLoading+ const hasError = releaseHistoryQuery.isError++ if (isLoading)+ return <ReleaseHistoryTableSkeleton />++ if (hasError) {+ return (+ <DeploymentStateMessage variant="list">+ {t('common.loadFailed')}+ </DeploymentStateMessage>+ )+ }++ const releaseHistory = releaseHistoryQuery.data+ if (!releaseHistory) {+ return (+ <DeploymentStateMessage variant="list">+ {t('common.loadFailed')}+ </DeploymentStateMessage>+ )+ }++ const releaseRows = releaseHistory.releaseSummaries.map(releaseRowFromSummary)+ const totalReleases = releaseHistory.pagination.totalCount ?? releaseRows.length+ const totalReleasePages = Math.ceil(totalReleases / RELEASE_HISTORY_PAGE_SIZE)++ function handleReleaseDeleted() {+ if (releaseRows.length === 1 && currentPage > 0)+ setCurrentPage(page => Math.max(page - 1, 0))+ }++ if (releaseRows.length === 0) {+ return (+ <DeploymentEmptyState+ icon="i-ri-stack-line"+ title={t('versions.emptyTitle')}+ description={t('versions.emptyDescription')}+ />+ )+ }++ return (+ <div className="flex flex-col gap-3">+ <ReleaseHistoryRows+ appInstanceId={appInstanceId}+ releaseRows={releaseRows}+ onReleaseDeleted={handleReleaseDeleted}+ />+ {totalReleases > RELEASE_HISTORY_PAGE_SIZE && (+ <Pagination+ className="border-y border-divider-subtle"+ page={currentPage + 1}+ totalPages={totalReleasePages}+ onPageChange={page => setCurrentPage(page - 1)}+ />+ )}+ </div>+ )+}diff --git a/web/features/deployments/detail/versions-tab/release-history-types.ts b/web/features/deployments/detail/versions-tab/release-history-types.tsnew file mode 100644index 00000000000..72399a67e04--- /dev/null+++ b/web/features/deployments/detail/versions-tab/release-history-types.ts@@ -0,0 +1,10 @@+import type { ReleaseSummary } from '@dify/contracts/enterprise/types.gen'+import type { ReleaseWithSummaryDeployments } from './release-deployments'+import { getReleaseSummaryDeployments } from './release-deployments'++export function releaseRowFromSummary(summary: ReleaseSummary): ReleaseWithSummaryDeployments {+ return {+ ...summary.release,+ summaryDeployments: getReleaseSummaryDeployments(summary),+ }+}diff --git a/web/features/deployments/list/index.tsx b/web/features/deployments/list/index.tsxnew file mode 100644index 00000000000..af44215fe14--- /dev/null+++ b/web/features/deployments/list/index.tsx@@ -0,0 +1,41 @@+'use client'++import type { ReactNode } from 'react'+import { ScopeProvider } from 'jotai-scope'+import { useQueryState } from 'nuqs'+import {+ deploymentsListEnvironmentIdAtom,+ deploymentsListKeywordsAtom,+ envFilterQueryState,+ keywordsQueryState,+} from './state'+import { DeploymentsListShell } from './ui/shell'++function DeploymentsListStateBoundary({ children }: {+ children: ReactNode+}) {+ const [envFilter] = useQueryState('env', envFilterQueryState)+ const [keywords] = useQueryState('keywords', keywordsQueryState)+ const stateKey = `${envFilter ?? 'all'}:${keywords}`++ return (+ <ScopeProvider+ key={stateKey}+ atoms={[+ [deploymentsListEnvironmentIdAtom, envFilter],+ [deploymentsListKeywordsAtom, keywords],+ ]}+ name="DeploymentsList"+ >+ {children}+ </ScopeProvider>+ )+}++export function DeploymentsList() {+ return (+ <DeploymentsListStateBoundary>+ <DeploymentsListShell />+ </DeploymentsListStateBoundary>+ )+}diff --git a/web/features/deployments/list/state/index.ts b/web/features/deployments/list/state/index.tsnew file mode 100644index 00000000000..4853d131b62--- /dev/null+++ b/web/features/deployments/list/state/index.ts@@ -0,0 +1,87 @@+'use client'++import type { ListAppInstanceSummariesResponse } from '@dify/contracts/enterprise/types.gen'+import type { InfiniteData, QueryKey } from '@tanstack/react-query'+import { keepPreviousData } from '@tanstack/react-query'+import { atom } from 'jotai'+import { atomWithInfiniteQuery, atomWithQuery } from 'jotai-tanstack-query'+import { parseAsString } from 'nuqs'+import { consoleQuery } from '@/service/client'+import { getNextPageParamFromPagination, SOURCE_APPS_PAGE_SIZE } from '../../shared/domain/pagination'+import { deploymentStatusPollingInterval } from '../../shared/domain/runtime-status'++export const envFilterQueryState = parseAsString.withOptions({ history: 'push' })+export const keywordsQueryState = parseAsString.withDefault('').withOptions({ history: 'push' })++export const deploymentsListKeywordsAtom = atom('')+export const deploymentsListEnvironmentIdAtom = atom<string | null>(null)++function listDeploymentStatusPollingInterval(data?: InfiniteData<ListAppInstanceSummariesResponse>) {+ const rows = data?.pages?.flatMap(page =>+ page.appInstanceSummaries.flatMap(summary => summary.environmentDeployments),+ ) ?? []++ return deploymentStatusPollingInterval(rows)+}++export const deploymentsListQueryAtom = atomWithInfiniteQuery<+ ListAppInstanceSummariesResponse,+ Error,+ InfiniteData<ListAppInstanceSummariesResponse>,+ QueryKey,+ number+>((get) => {+ const queryKeywords = get(deploymentsListKeywordsAtom).trim()+ const queryEnvironmentId = get(deploymentsListEnvironmentIdAtom) ?? undefined++ return {+ ...consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.infiniteOptions({+ input: pageParam => ({+ query: {+ pageNumber: Number(pageParam),+ resultsPerPage: SOURCE_APPS_PAGE_SIZE,+ ...(queryEnvironmentId ? { environmentId: queryEnvironmentId } : {}),+ ...(queryKeywords ? { displayName: queryKeywords } : {}),+ },+ }),+ getNextPageParam: lastPage => getNextPageParamFromPagination(lastPage.pagination),+ initialPageParam: 1,+ placeholderData: keepPreviousData,+ }),+ refetchInterval: query => listDeploymentStatusPollingInterval(query.state.data),+ }+})++export const deploymentsListRowsAtom = atom((get) => {+ return get(deploymentsListQueryAtom).data?.pages.flatMap(page => page.appInstanceSummaries) ?? []+})++export const deploymentsListShowSkeletonAtom = atom((get) => {+ const deploymentsListQuery = get(deploymentsListQueryAtom)+ const pages = deploymentsListQuery.data?.pages ?? []++ return deploymentsListQuery.isLoading || (deploymentsListQuery.isFetching && pages.length === 0)+})++export const deploymentsListShowEmptyStateAtom = atom((get) => {+ return !get(deploymentsListShowSkeletonAtom)+ && !get(deploymentsListQueryAtom).isError+ && get(deploymentsListRowsAtom).length === 0+})++export const deploymentsListHasFilterAtom = atom((get) => {+ return Boolean(get(deploymentsListKeywordsAtom).trim() || get(deploymentsListEnvironmentIdAtom))+})++export const environmentsFilterQueryAtom = atomWithQuery(() =>+ consoleQuery.enterprise.environmentService.listEnvironments.queryOptions({+ input: {+ query: {+ // The filter lists every deployable environment; environment count is+ // capped well below the 100-per-page maximum.+ pageNumber: 1,+ resultsPerPage: 100,+ },+ },+ }),+)diff --git a/web/features/deployments/list/ui/create-deployment-button.tsx b/web/features/deployments/list/ui/create-deployment-button.tsxnew file mode 100644index 00000000000..75918bfe445--- /dev/null+++ b/web/features/deployments/list/ui/create-deployment-button.tsx@@ -0,0 +1,24 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import Link from '@/next/link'++export function CreateDeploymentButton({ className }: {+ className?: string+}) {+ const { t } = useTranslation('deployments')++ return (+ <Link+ href="/deployments/create"+ className={cn(+ 'inline-flex h-8 items-center gap-1.5 rounded-lg bg-primary-600 px-3 system-sm-medium whitespace-nowrap text-text-primary-on-surface hover:bg-primary-700',+ className,+ )}+ >+ <span className="i-ri-add-line size-4 shrink-0" aria-hidden="true" />+ <span>{t('list.createDeployment')}</span>+ </Link>+ )+}diff --git a/web/features/deployments/list/ui/environment-filter.tsx b/web/features/deployments/list/ui/environment-filter.tsxnew file mode 100644index 00000000000..c8468eec57f--- /dev/null+++ b/web/features/deployments/list/ui/environment-filter.tsx@@ -0,0 +1,111 @@+'use client'++import type { ReactNode } from 'react'+import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { useAtomValue } from 'jotai'+import { useQueryState } from 'nuqs'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ envFilterQueryState,+ environmentsFilterQueryAtom,+} from '../state'++type EnvironmentFilterOption = {+ value: string | null+ text: string+ icon: ReactNode+}++function EnvironmentOptionIcon() {+ return <span className="i-ri-server-line size-[14px]" />+}++export function EnvironmentFilter({ className }: {+ className?: string+}) {+ const { t } = useTranslation('deployments')+ const [open, setOpen] = useState(false)+ const [envFilter, setEnvFilter] = useQueryState('env', envFilterQueryState)+ const environmentsQuery = useAtomValue(environmentsFilterQueryAtom)+ const environmentOptions: EnvironmentFilterOption[] = environmentsQuery.data?.environments+ ?.map(environment => ({+ value: environment.id,+ text: environment.displayName,+ icon: <EnvironmentOptionIcon />,+ })) ?? []+ const filterOptions: EnvironmentFilterOption[] = [+ {+ value: null,+ text: t('filter.allEnvs'),+ icon: <span className="i-ri-apps-2-line size-[14px]" />,+ },+ ...environmentOptions,+ ]+ const selectedOption = filterOptions.find(option => option.value === envFilter)+ ?? (envFilter+ ? {+ value: envFilter,+ text: envFilter,+ icon: <EnvironmentOptionIcon />,+ }+ : filterOptions[0])+ const activeFilter = selectedOption?.value ?? null++ return (+ <DropdownMenu modal={false} open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ className={cn(+ 'flex h-8 max-w-full cursor-pointer items-center gap-1 rounded-lg border border-transparent bg-components-input-bg-normal px-2 text-left select-none',+ open && 'shadow-xs',+ className,+ )}+ >+ <div className="p-px text-text-tertiary">+ {selectedOption?.icon}+ </div>+ <div className="max-w-40 min-w-0 truncate system-sm-regular text-text-secondary">+ {selectedOption?.text}+ </div>+ <div className="shrink-0 p-px">+ <span className={cn('i-ri-arrow-down-s-line size-3.5 text-text-tertiary transition-transform', open && 'rotate-180')} />+ </div>+ </DropdownMenuTrigger>+ {open && (+ <DropdownMenuContent+ placement="bottom-start"+ sideOffset={4}+ popupClassName="w-60 rounded-lg border border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs"+ >+ <div className="max-h-72 overflow-auto p-1">+ {filterOptions.map(option => (+ <DropdownMenuItem+ key={option.value ?? 'all'}+ onClick={() => {+ void setEnvFilter(option.value)+ setOpen(false)+ }}+ className={cn(+ 'flex items-center gap-2 rounded-lg py-1.5 pr-2 pl-3 select-none',+ 'cursor-pointer hover:bg-state-base-hover',+ )}+ >+ <span className="shrink-0 text-text-tertiary">{option.icon}</span>+ <span className="grow truncate text-sm/5 text-text-tertiary">{option.text}</span>+ {option.value === activeFilter && (+ <span className="i-custom-vender-line-general-check size-4 shrink-0 text-text-secondary" />+ )}+ </DropdownMenuItem>+ ))}+ </div>+ </DropdownMenuContent>+ )}+ </DropdownMenu>+ )+}diff --git a/web/features/deployments/list/ui/instance-card-sections.tsx b/web/features/deployments/list/ui/instance-card-sections.tsxnew file mode 100644index 00000000000..821ebf63144--- /dev/null+++ b/web/features/deployments/list/ui/instance-card-sections.tsx@@ -0,0 +1,236 @@+'use client'++import type {+ AccessChannels,+ EnvironmentDeployment,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import type { ReactElement } from 'react'+import { ReleaseSource } from '@dify/contracts/enterprise/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'+import { PreviewCard, PreviewCardContent, PreviewCardTrigger } from '@langgenius/dify-ui/preview-card'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import Link from '@/next/link'+import { formatDate } from '../../shared/domain/release'+import { EnvironmentDeploymentBadge } from '../../shared/ui/deployment-status-badge'+import { deploymentStatusLabelKey } from '../../shared/ui/deployment-status-style'+import { getInstanceTabHref } from './instance-card-utils'++const VISIBLE_ENVIRONMENT_COUNT = 3++function releaseSourceLabel(release: Release | undefined, t: ReturnType<typeof useTranslation<'deployments'>>['t']) {+ if (release?.source === ReleaseSource.RELEASE_SOURCE_SOURCE_APP || release?.sourceAppId)+ return t('versions.sourceAppOption')+ if (release?.source === ReleaseSource.RELEASE_SOURCE_UPLOAD)+ return t('versions.manualDslOption')+ return '—'+}++export function ReleaseMetaTooltip({ release, deployed, children }: {+ release?: Release+ deployed: boolean+ children: ReactElement+}) {+ const { t } = useTranslation('deployments')++ if (!release)+ return children++ const rows = [+ { label: t('card.tooltip.releaseName'), value: release.displayName },+ { label: t('card.tooltip.deploymentStatus'), value: deployed ? t('card.tooltip.deployed') : t('card.tooltip.notDeployedShort') },+ { label: t('card.tooltip.source'), value: releaseSourceLabel(release, t) },+ { label: t('card.tooltip.createdAt'), value: formatDate(release.createdAt) },+ ]++ return (+ <PreviewCard>+ <PreviewCardTrigger render={children} />+ <PreviewCardContent popupClassName="px-3 py-2">+ <div className="flex min-w-48 flex-col gap-1">+ {rows.map(row => (+ <div key={row.label} className="flex justify-between gap-4">+ <span className="shrink-0 text-text-tertiary">{row.label}</span>+ <span className="min-w-0 truncate text-right text-text-secondary">{row.value}</span>+ </div>+ ))}+ </div>+ </PreviewCardContent>+ </PreviewCard>+ )+}++function EnvironmentChip({ row }: {+ row: EnvironmentDeployment+}) {+ const { t } = useTranslation('deployments')+ const name = row.environment.displayName+ const status = row.status+ const statusLabel = t(deploymentStatusLabelKey(status))+ const tooltipSummary = [+ name,+ row.currentRelease ? row.currentRelease.displayName : undefined,+ statusLabel,+ ].filter(Boolean).join(' · ')++ return (+ <Tooltip>+ <TooltipTrigger+ render={(+ <EnvironmentDeploymentBadge+ row={row}+ showStatus={false}+ summaryLabel={tooltipSummary}+ className="max-w-44"+ />+ )}+ />+ <TooltipContent>+ <span className="whitespace-nowrap text-text-secondary">{tooltipSummary}</span>+ </TooltipContent>+ </Tooltip>+ )+}++function EnvironmentOverflow({ rows }: {+ rows: EnvironmentDeployment[]+}) {+ const { t } = useTranslation('deployments')++ return (+ <Popover>+ <PopoverTrigger+ render={(+ <button+ type="button"+ className="inline-flex h-5 cursor-pointer items-center rounded-md bg-background-section-burn px-1.5 system-xs-medium text-text-tertiary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ {t('card.envOverflow', { count: rows.length })}+ </button>+ )}+ />+ <PopoverContent popupClassName="px-3 py-2">+ <div className="flex min-w-40 flex-col gap-1">+ {rows.map((row) => {+ const status = row.status+ const summary = [+ row.environment.displayName,+ row.currentRelease ? row.currentRelease.displayName : undefined,+ t(deploymentStatusLabelKey(status)),+ ].filter(Boolean).join(' · ')++ return (+ <span key={row.environment.id} className="whitespace-nowrap text-text-secondary">{summary}</span>+ )+ })}+ </div>+ </PopoverContent>+ </Popover>+ )+}++export function DeploymentStatusContent({+ rows,+ emptyAction,+}: {+ rows: EnvironmentDeployment[]+ emptyAction?: ReactElement+}) {+ const visibleRows = rows.slice(0, VISIBLE_ENVIRONMENT_COUNT)+ const overflowRows = rows.slice(VISIBLE_ENVIRONMENT_COUNT)++ if (rows.length > 0) {+ return (+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ {visibleRows.map(row => (+ <EnvironmentChip key={row.environment.id} row={row} />+ ))}+ {overflowRows.length > 0 && <EnvironmentOverflow rows={overflowRows} />}+ </div>+ )+ }++ if (emptyAction)+ return <div className="flex min-w-0 items-center">{emptyAction}</div>++ return null+}++export function DeploymentAccessLinks({ appInstanceId, access, isLoading }: {+ appInstanceId: string+ access?: AccessChannels+ isLoading?: boolean+}) {+ const { t } = useTranslation('deployments')++ if (isLoading) {+ return (+ <div role="group" aria-label={t('overview.accessStatus')} className="flex min-w-0 grow items-center gap-2">+ <SkeletonRectangle className="my-0 size-4 animate-pulse rounded-sm" />+ <SkeletonRectangle className="my-0 size-4 animate-pulse rounded-sm" />+ </div>+ )+ }++ const links = [+ ...(access?.webAppEnabled+ ? [{+ key: 'webapp',+ href: getInstanceTabHref(appInstanceId, 'access'),+ label: t('card.access.webApp'),+ icon: 'i-ri-global-line',+ }]+ : []),+ ...(access?.webAppEnabled+ ? [{+ key: 'cli',+ href: getInstanceTabHref(appInstanceId, 'access'),+ label: t('card.access.cli'),+ icon: 'i-ri-terminal-box-line',+ }]+ : []),+ ...(access?.developerApiEnabled+ ? [{+ key: 'api-tokens',+ href: getInstanceTabHref(appInstanceId, 'api-tokens'),+ label: t('card.access.api'),+ icon: 'i-ri-code-s-slash-line',+ }]+ : []),+ ]++ if (links.length === 0) {+ return (+ <div role="group" aria-label={t('overview.accessStatus')} className="flex min-w-0 grow items-center gap-1.5 text-text-quaternary">+ <span aria-hidden className="i-ri-link-unlink size-3.5 shrink-0" />+ <span className="truncate system-xs-regular">{t('card.access.none')}</span>+ </div>+ )+ }++ return (+ <div role="group" aria-label={t('overview.accessStatus')} className="flex min-w-0 grow items-center gap-2">+ {links.map(link => (+ <Tooltip key={link.key}>+ <TooltipTrigger+ render={(+ <Link+ href={link.href}+ aria-label={link.label}+ className={cn(+ 'inline-flex h-5 min-w-5 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary',+ )}+ >+ <span aria-hidden className={cn('size-3.5', link.icon)} />+ </Link>+ )}+ />+ <TooltipContent>{link.label}</TooltipContent>+ </Tooltip>+ ))}+ </div>+ )+}diff --git a/web/features/deployments/list/ui/instance-card-utils.ts b/web/features/deployments/list/ui/instance-card-utils.tsnew file mode 100644index 00000000000..dd1b3c40b3d--- /dev/null+++ b/web/features/deployments/list/ui/instance-card-utils.ts@@ -0,0 +1,21 @@+import type {+ EnvironmentDeployment,+ Release,+} from '@dify/contracts/enterprise/types.gen'+import type { InstanceDetailTabKey } from '../../detail/tabs'+import { isUndeployedDeploymentRow } from '../../shared/domain/runtime-status'++export function getInstanceTabHref(appInstanceId: string, tabKey: InstanceDetailTabKey) {+ return `/deployments/${appInstanceId}/${tabKey}`+}++export function isActiveDeployment(row: EnvironmentDeployment) {+ return !isUndeployedDeploymentRow(row)+}++export function isReleaseDeployed(release: Release | undefined, rows: EnvironmentDeployment[]) {+ if (!release)+ return false++ return rows.some(row => row.currentRelease?.id === release.id)+}diff --git a/web/features/deployments/list/ui/instance-card.tsx b/web/features/deployments/list/ui/instance-card.tsxnew file mode 100644index 00000000000..4f4649c134f--- /dev/null+++ b/web/features/deployments/list/ui/instance-card.tsx@@ -0,0 +1,129 @@+'use client'++import type {+ AppInstanceSummary,+} from '@dify/contracts/enterprise/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import { useSetAtom } from 'jotai'+import { useTranslation } from 'react-i18next'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import Link from '@/next/link'+import { DeploymentActionsMenu } from '../../components/deployment-actions'+import { CreateReleaseControl } from '../../create-release'+import { openDeployDrawerAtom } from '../../deploy-drawer/state'+import {+ DeploymentAccessLinks,+ DeploymentStatusContent,+ ReleaseMetaTooltip,+} from './instance-card-sections'+import {+ getInstanceTabHref,+ isActiveDeployment,+ isReleaseDeployed,+} from './instance-card-utils'++export function InstanceCard({ summary }: {+ summary: AppInstanceSummary+}) {+ const { t } = useTranslation('deployments')+ const { formatTimeFromNow } = useFormatTimeFromNow()+ const openDeployDrawer = useSetAtom(openDeployDrawerAtom)+ const appInstance = summary.appInstance+ const appInstanceId = appInstance.id+ const appName = appInstance.displayName+ const detailHref = getInstanceTabHref(appInstanceId, 'overview')+ const description = appInstance.description.trim()+ const access = summary.accessChannels+ const releaseRows = summary.latestRelease ? [summary.latestRelease] : []+ const hasRelease = releaseRows.length > 0+ const activeDeploymentRows = summary.environmentDeployments.filter(isActiveDeployment)+ const latestRelease = releaseRows[0]+ const latestReleaseTime = latestRelease?.createdAt+ const latestReleaseTimeMs = latestReleaseTime ? Date.parse(latestReleaseTime) : Number.NaN+ const latestReleaseDeployed = isReleaseDeployed(latestRelease, activeDeploymentRows)+ const releaseMeta = latestRelease+ ? [+ latestRelease.displayName,+ Number.isNaN(latestReleaseTimeMs) ? undefined : formatTimeFromNow(latestReleaseTimeMs),+ ].filter(Boolean).join(' · ')+ : t('card.notDeployed')+ const showDeployAction = hasRelease && activeDeploymentRows.length === 0+ const showFooterCreateReleaseAction = !hasRelease++ return (+ <div+ className="group relative col-span-1 inline-flex min-h-40 min-w-0 cursor-default flex-col rounded-xl border border-solid border-components-card-border bg-components-card-bg shadow-xs transition-[border-color,box-shadow] duration-200 ease-in-out hover:border-components-panel-border-subtle hover:shadow-md"+ >+ <DeploymentActionsMenu+ appInstanceId={appInstanceId}+ appName={appName}+ placement="bottom-end"+ sideOffset={4}+ className="pointer-events-none absolute top-3 right-3 z-10 opacity-0 transition-opacity group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100"+ triggerClassName="data-popup-open:pointer-events-auto data-popup-open:opacity-100"+ />+ <div className="flex min-h-0 flex-1 flex-col">+ <Link+ href={detailHref}+ className="block min-w-0 rounded-t-xl px-4 pt-4 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ >+ <h3 className="truncate title-md-semi-bold text-text-primary">+ {appName}+ </h3>+ {description+ ? (+ <p className="mt-2 line-clamp-2 system-xs-regular text-text-tertiary">+ {description}+ </p>+ )+ : (+ <p className="mt-2 truncate system-xs-regular text-text-quaternary">+ {t('card.noDescription')}+ </p>+ )}+ </Link>++ <div role="group" aria-label={t('card.tooltip.deploymentStatus')} className="min-h-8 px-4 pt-4 pb-3">+ <DeploymentStatusContent+ rows={activeDeploymentRows}+ emptyAction={showDeployAction+ ? (+ <Button+ variant="secondary-accent"+ size="small"+ className="max-w-full"+ onClick={() => openDeployDrawer({ appInstanceId })}+ >+ <span className="truncate">{t('card.menu.deploy')}</span>+ </Button>+ )+ : undefined}+ />+ </div>++ <div className="mt-auto flex min-h-11 min-w-0 items-center gap-3 border-t border-divider-subtle px-4 py-2">+ {showFooterCreateReleaseAction+ ? (+ <div className="-ml-2 flex min-w-0 grow items-center">+ <CreateReleaseControl+ appInstanceId={appInstanceId}+ variant="secondary-accent"+ label={t('card.createFirstRelease')}+ className="max-w-full"+ />+ </div>+ )+ : <DeploymentAccessLinks appInstanceId={appInstanceId} access={access} />}+ <ReleaseMetaTooltip release={latestRelease} deployed={latestReleaseDeployed}>+ <Link+ href={latestRelease ? getInstanceTabHref(appInstanceId, 'releases') : getInstanceTabHref(appInstanceId, 'instances')}+ className="min-w-0 shrink truncate text-right system-xs-medium text-text-secondary hover:text-text-primary"+ >+ {releaseMeta}+ </Link>+ </ReleaseMetaTooltip>+ </div>+ </div>+ </div>+ )+}diff --git a/web/features/deployments/list/ui/shell.tsx b/web/features/deployments/list/ui/shell.tsxnew file mode 100644index 00000000000..d564fa0114e--- /dev/null+++ b/web/features/deployments/list/ui/shell.tsx@@ -0,0 +1,224 @@+'use client'++import type { ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import { useAtomValue } from 'jotai'+import { debounce, useQueryState } from 'nuqs'+import { useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { StudioListHeader } from '@/app/components/apps/studio-list-header'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import { DeploymentEmptyState, DeploymentStateMessage } from '../../components/empty-state'+import {+ deploymentsListHasFilterAtom,+ deploymentsListQueryAtom,+ deploymentsListRowsAtom,+ deploymentsListShowEmptyStateAtom,+ deploymentsListShowSkeletonAtom,+ envFilterQueryState,+ keywordsQueryState,+} from '../state'+import { CreateDeploymentButton } from './create-deployment-button'+import { EnvironmentFilter } from './environment-filter'+import { InstanceCard } from './instance-card'++const INSTANCE_CARD_SKELETON_KEYS = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']++function DeploymentsListState({ children }: {+ children: ReactNode+}) {+ return <DeploymentStateMessage variant="page">{children}</DeploymentStateMessage>+}++function DeploymentsListEmpty() {+ const { t } = useTranslation('deployments')+ const hasAtomFilter = useAtomValue(deploymentsListHasFilterAtom)+ const [keywords, setKeywords] = useQueryState('keywords', keywordsQueryState)+ const [envFilter, setEnvFilter] = useQueryState('env', envFilterQueryState)+ const hasFilter = hasAtomFilter || Boolean(keywords.trim()) || Boolean(envFilter)++ function clearFilters() {+ void setKeywords(null)+ void setEnvFilter(null)+ }++ return (+ <DeploymentEmptyState+ variant="page"+ icon={hasFilter ? 'i-ri-search-line' : 'i-ri-rocket-line'}+ title={hasFilter ? t('list.emptyFilteredTitle') : t('list.emptyTitle')}+ description={hasFilter ? t('list.emptyFilteredDescription') : t('list.emptyDescription')}+ action={hasFilter+ ? (+ <Button variant="secondary" size="small" onClick={clearFilters}>+ {t('list.clearFilters')}+ </Button>+ )+ : <CreateDeploymentButton />}+ />+ )+}++function InstanceCardSkeleton() {+ return (+ <div className="col-span-1 inline-flex min-h-40 min-w-0 flex-col rounded-xl border border-solid border-components-card-border bg-components-card-bg shadow-xs">+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="min-w-0 px-4 pt-4">+ <SkeletonRectangle className="my-0 h-4 w-2/5 animate-pulse" />+ <SkeletonRectangle className="mt-2 h-3 w-3/5 animate-pulse" />+ </div>++ <div className="min-h-8 px-4 pt-4">+ <div className="flex min-w-0 items-center gap-1.5">+ <SkeletonRectangle className="my-0 h-5 w-18 animate-pulse rounded-md" />+ <SkeletonRectangle className="my-0 h-5 w-22 animate-pulse rounded-md" />+ </div>+ </div>++ <div className="mt-auto flex h-11 min-w-0 items-center border-t border-divider-subtle px-4">+ <div className="flex min-w-0 grow items-center gap-2">+ <SkeletonRectangle className="my-0 size-3.5 animate-pulse rounded-sm" />+ <SkeletonRectangle className="my-0 h-3 w-18 animate-pulse" />+ </div>+ <SkeletonRectangle className="my-0 h-3 w-24 animate-pulse" />+ </div>+ </div>+ </div>+ )+}++function DeploymentsListSkeleton() {+ return INSTANCE_CARD_SKELETON_KEYS.map(key => (+ <InstanceCardSkeleton key={key} />+ ))+}++function DeploymentsSearchInput({ className }: {+ className?: string+}) {+ const { t } = useTranslation('deployments')+ const [keywords, setKeywords] = useQueryState('keywords', keywordsQueryState)++ function handleKeywordsChange(next: string) {+ void setKeywords(next.trim() ? next : null, {+ limitUrlUpdates: next.trim() ? debounce(300) : undefined,+ shallow: false,+ })+ }++ return (+ <div className={cn('relative w-50', className)}>+ <span aria-hidden className="pointer-events-none absolute top-1/2 left-2.5 i-ri-search-line size-4 -translate-y-1/2 text-text-tertiary" />+ <Input+ className="h-8 pr-8 pl-8"+ aria-label={t('filter.searchPlaceholder')}+ placeholder={t('filter.searchPlaceholder')}+ value={keywords}+ onChange={e => handleKeywordsChange(e.target.value)}+ />+ {keywords && (+ <button+ type="button"+ aria-label={t('list.clearSearch')}+ className="absolute top-1/2 right-2.5 flex size-4 -translate-y-1/2 items-center justify-center text-text-quaternary hover:text-text-secondary"+ onClick={() => handleKeywordsChange('')}+ >+ <span aria-hidden className="i-ri-close-circle-fill size-4" />+ </button>+ )}+ </div>+ )+}++function DeploymentsListControls() {+ const { t } = useTranslation()++ return (+ <StudioListHeader+ title={(+ <div className="flex items-center">+ <h1 className="text-[18px]/[21.6px] font-semibold text-text-primary">{t('menus.deployments', { ns: 'common' })}</h1>+ </div>+ )}+ >+ <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <div className="flex min-w-0 items-center justify-between gap-2 sm:justify-start">+ <EnvironmentFilter className="min-w-0" />+ <CreateDeploymentButton className="shrink-0 sm:hidden" />+ </div>+ <DeploymentsSearchInput className="w-full sm:w-50 sm:shrink-0" />+ <CreateDeploymentButton className="hidden shrink-0 sm:ml-auto sm:inline-flex" />+ </div>+ </StudioListHeader>+ )+}++export function DeploymentsListShell() {+ const { t } = useTranslation('deployments')+ const containerRef = useRef<HTMLDivElement>(null)+ const anchorRef = useRef<HTMLDivElement>(null)+ const deploymentsListQuery = useAtomValue(deploymentsListQueryAtom)+ const appInstanceSummaries = useAtomValue(deploymentsListRowsAtom)+ const showSkeleton = useAtomValue(deploymentsListShowSkeletonAtom)+ const showEmptyState = useAtomValue(deploymentsListShowEmptyStateAtom)+ const {+ error,+ fetchNextPage,+ hasNextPage,+ isError,+ isFetchingNextPage,+ isLoading,+ } = deploymentsListQuery++ useEffect(() => {+ if (!hasNextPage || isLoading || isFetchingNextPage || error)+ return++ const anchor = anchorRef.current+ const container = containerRef.current+ if (!anchor || !container)+ return++ const observer = new IntersectionObserver((entries) => {+ if (entries[0]?.isIntersecting)+ void fetchNextPage()+ }, {+ root: container,+ rootMargin: '160px',+ threshold: 0.1,+ })++ observer.observe(anchor)+ return () => observer.disconnect()+ }, [error, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading])++ return (+ <div ref={containerRef} className="relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body">+ <DeploymentsListControls />+ <div className={cn(+ 'relative grid grow grid-cols-[repeat(auto-fill,minmax(min(100%,20rem),1fr))] content-start gap-4 px-8 pt-2',+ showEmptyState && 'overflow-hidden',+ )}+ >+ {showSkeleton+ ? <DeploymentsListSkeleton />+ : isError+ ? <DeploymentsListState>{t('common.loadFailed')}</DeploymentsListState>+ : appInstanceSummaries.length === 0+ ? <DeploymentsListEmpty />+ : appInstanceSummaries.map(summary => (+ <InstanceCard+ key={summary.appInstance.id}+ summary={summary}+ />+ ))}+ {isFetchingNextPage && <DeploymentsListSkeleton />}+ </div>++ <div ref={anchorRef} className="h-0" />+ <div className="py-4" />+ </div>+ )+}diff --git a/web/features/deployments/nav/index.tsx b/web/features/deployments/nav/index.tsxnew file mode 100644index 00000000000..ce5de6055d3--- /dev/null+++ b/web/features/deployments/nav/index.tsx@@ -0,0 +1,114 @@+'use client'++import type { AppInstance } from '@dify/contracts/enterprise/types.gen'+import type { NavItem } from '@/app/components/header/nav/nav-selector'+import { keepPreviousData, useInfiniteQuery, useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import Nav from '@/app/components/header/nav'+import { useParams, useRouter, useSelectedLayoutSegment } from '@/next/navigation'+import { consoleQuery } from '@/service/client'+import { getNextPageParamFromPagination, SOURCE_APPS_PAGE_SIZE } from '../shared/domain/pagination'++function navItemFromListApp(app: AppInstance): NavItem {+ const id = app.id++ return {+ id,+ name: app.displayName,+ link: `/deployments/${id}/overview`,+ icon_type: 'emoji',+ icon: '🚀',+ icon_background: '#E0EAFF',+ icon_url: null,+ }+}++function navItemFromOverview(instance?: AppInstance, fallbackId?: string): NavItem | undefined {+ const id = instance?.id ?? fallbackId+ if (!id)+ return undefined++ return {+ id,+ name: instance ? instance.displayName : id,+ link: `/deployments/${id}/overview`,+ icon_type: 'emoji',+ icon: '🚀',+ icon_background: '#E0EAFF',+ icon_url: null,+ }+}++export function DeploymentsNav() {+ const { t } = useTranslation()+ const router = useRouter()+ const selectedSegment = useSelectedLayoutSegment()+ const isActive = selectedSegment === 'deployments'+ const params = useParams<{ appInstanceId?: string }>()+ const appInstanceId = params?.appInstanceId++ const { data: currentInstance } = useQuery(consoleQuery.enterprise.appInstanceService.getAppInstance.queryOptions({+ input: {+ params: {+ appInstanceId: appInstanceId ?? '',+ },+ },+ enabled: isActive && Boolean(appInstanceId),+ select: data => data.appInstance,+ }))++ const listQuery = useInfiniteQuery({+ ...consoleQuery.enterprise.appInstanceService.listAppInstances.infiniteOptions({+ input: pageParam => ({+ query: {+ pageNumber: Number(pageParam),+ resultsPerPage: SOURCE_APPS_PAGE_SIZE,+ },+ }),+ getNextPageParam: lastPage => getNextPageParamFromPagination(lastPage.pagination),+ initialPageParam: 1,+ placeholderData: keepPreviousData,+ }),+ enabled: isActive,+ })+ const appNavItems = listQuery.data?.pages.flatMap(page =>+ page.appInstances.map(navItemFromListApp),+ ) ?? []+ const currentNavItem = navItemFromOverview(currentInstance, appInstanceId)++ const navigationItems: NavItem[] = isActive+ ? currentNavItem && !appNavItems.some(item => item.id === currentNavItem.id)+ ? [...appNavItems, currentNavItem]+ : appNavItems+ : []++ const curNav = appInstanceId+ ? navigationItems.find(item => item.id === appInstanceId)+ : undefined++ function handleCreate() {+ router.push('/deployments/create')+ }++ function handleLoadMore() {+ if (listQuery.hasNextPage && !listQuery.isFetchingNextPage)+ void listQuery.fetchNextPage()+ }++ return (+ <Nav+ isApp={false}+ icon={<span aria-hidden className="i-ri-rocket-line size-4" />}+ activeIcon={<span aria-hidden className="i-ri-rocket-fill size-4" />}+ text={t('menus.deployments', { ns: 'common' })}+ activeSegment="deployments"+ link="/deployments"+ curNav={curNav}+ navigationItems={navigationItems}+ createText={t('deployments:list.createDeployment')}+ onCreate={handleCreate}+ onLoadMore={handleLoadMore}+ isLoadingMore={listQuery.isFetchingNextPage}+ />+ )+}diff --git a/web/features/deployments/shared/domain/dsl.ts b/web/features/deployments/shared/domain/dsl.tsnew file mode 100644index 00000000000..5bfcd7c4178--- /dev/null+++ b/web/features/deployments/shared/domain/dsl.ts@@ -0,0 +1,150 @@+import { load as yamlLoad } from 'js-yaml'+import { AppModeEnum } from '@/types/app'++export type DslEnvVarSlot = {+ key: string+ description?: string+ defaultValue?: string+ hasDefaultValue?: boolean+ valueType?: string+}++type DslMetadata = {+ app?: {+ mode?: unknown+ name?: unknown+ }+ workflow?: {+ environment_variables?: unknown+ }+}++type DslEnvVarRecord = Record<string, unknown>++const ENV_VAR_DEFAULT_VALUE_FIELDS = ['value', 'default_value', 'defaultValue', 'default'] as const+const ENV_VAR_VALUE_TYPE_FIELDS = ['value_type', 'valueType', 'type'] as const+const MASKED_SECRET_PLACEHOLDERS = new Set(['[__HIDDEN__]'])++export function encodeDslContent(value: string) {+ const bytes = new TextEncoder().encode(value)+ const chunkSize = 0x8000+ const chunks: string[] = []++ for (let offset = 0; offset < bytes.length; offset += chunkSize)+ chunks.push(String.fromCharCode(...bytes.subarray(offset, offset + chunkSize)))++ return btoa(chunks.join(''))+}++function parseDsl(content: string) {+ try {+ return yamlLoad(content) as DslMetadata | undefined+ }+ catch {+ return undefined+ }+}++function isRecord(value: unknown): value is DslEnvVarRecord {+ return Boolean(value && typeof value === 'object' && !Array.isArray(value))+}++function stringValue(value: unknown) {+ return typeof value === 'string' ? value.trim() : ''+}++function normalizeEnvVarDefaultValue(value: unknown) {+ if (value === undefined || value === null)+ return undefined++ let normalizedValue: string | undefined+ if (typeof value === 'string') {+ normalizedValue = value+ }+ else if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {+ normalizedValue = String(value)+ }+ else {+ try {+ normalizedValue = JSON.stringify(value)+ }+ catch {+ normalizedValue = undefined+ }+ }++ if (!normalizedValue?.trim())+ return undefined+ if (MASKED_SECRET_PLACEHOLDERS.has(normalizedValue))+ return undefined++ return normalizedValue+}++function envVarDefaultValue(record: DslEnvVarRecord) {+ for (const field of ENV_VAR_DEFAULT_VALUE_FIELDS) {+ if (Object.prototype.hasOwnProperty.call(record, field))+ return normalizeEnvVarDefaultValue(record[field])+ }++ return undefined+}++function envVarValueType(record: DslEnvVarRecord) {+ for (const field of ENV_VAR_VALUE_TYPE_FIELDS) {+ const valueType = stringValue(record[field])+ if (valueType)+ return valueType+ }++ return undefined+}++export function dslAppName(content: string) {+ const name = parseDsl(content)?.app?.name++ return typeof name === 'string' ? name.trim() : ''+}++function dslAppMode(content: string) {+ return stringValue(parseDsl(content)?.app?.mode)+}++export function isWorkflowDsl(content: string) {+ return dslAppMode(content) === AppModeEnum.WORKFLOW+}++export function dslEnvVarSlots(content: string): DslEnvVarSlot[] {+ const environmentVariables = parseDsl(content)?.workflow?.environment_variables+ if (!Array.isArray(environmentVariables))+ return []++ const seenKeys = new Set<string>()++ return environmentVariables+ .flatMap((envVar): DslEnvVarSlot[] => {+ if (!isRecord(envVar))+ return []++ const key = stringValue(envVar.name ?? envVar.key ?? envVar.variable)+ if (!key || seenKeys.has(key))+ return []++ seenKeys.add(key)+ const description = stringValue(envVar.description)+ const defaultValue = envVarDefaultValue(envVar)+ const valueType = envVarValueType(envVar)++ return [{+ key,+ ...(description ? { description } : {}),+ ...(valueType ? { valueType } : {}),+ ...(defaultValue !== undefined+ ? {+ defaultValue,+ hasDefaultValue: true,+ }+ : {}),+ }]+ })+}diff --git a/web/features/deployments/shared/domain/error.ts b/web/features/deployments/shared/domain/error.tsnew file mode 100644index 00000000000..819f794ecb9--- /dev/null+++ b/web/features/deployments/shared/domain/error.ts@@ -0,0 +1,137 @@+type DeploymentErrorPayload = {+ message?: unknown+ error?: unknown+ reason?: unknown+ code?: unknown+ metadata?: unknown+ unsupported_nodes?: unknown+}++const APP_DEPLOY_UNSUPPORTED_DSL_NODE_TYPE = 'APPDEPLOY_UNSUPPORTED_DSL_NODE_TYPE'++export type UnsupportedDslNode = {+ id?: string+ type?: string+}++export type UnsupportedDslNodeError = {+ message?: string+ nodes: UnsupportedDslNode[]+}++function nonEmptyString(value: unknown) {+ if (typeof value !== 'string')+ return undefined++ const trimmedValue = value.trim()+ return trimmedValue || undefined+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function formatDeploymentError(data: DeploymentErrorPayload) {+ const message = nonEmptyString(data.message) ?? nonEmptyString(data.error)+ const reason = nonEmptyString(data.reason) ?? nonEmptyString(data.code)++ if (message && reason)+ return `${message} (${reason})`++ return message ?? reason+}++async function deploymentErrorData(error: unknown) {+ if (error instanceof Response && !error.bodyUsed) {+ try {+ return await error.clone().json() as DeploymentErrorPayload+ }+ catch {}+ }++ return undefined+}++function deploymentErrorReason(data: DeploymentErrorPayload) {+ return nonEmptyString(data.reason) ?? nonEmptyString(data.code)+}++function unsupportedNodesPayload(data: DeploymentErrorPayload) {+ if (isRecord(data.metadata))+ return data.metadata.unsupported_nodes++ return data.unsupported_nodes+}++function parsedJsonValue(value: string) {+ try {+ return JSON.parse(value) as unknown+ }+ catch {+ return undefined+ }+}++function unsupportedDslNode(value: unknown) {+ if (!isRecord(value))+ return undefined++ const id = nonEmptyString(value.id)+ const type = nonEmptyString(value.type)+ if (!id && !type)+ return undefined++ return {+ ...(id ? { id } : {}),+ ...(type ? { type } : {}),+ } satisfies UnsupportedDslNode+}++function unsupportedDslNodes(value: unknown) {+ const nodeList = typeof value === 'string' ? parsedJsonValue(value) : value+ if (!Array.isArray(nodeList))+ return []++ const seen = new Set<string>()+ const nodes: UnsupportedDslNode[] = []++ nodeList.forEach((item) => {+ const node = unsupportedDslNode(item)+ if (!node)+ return++ const key = `${node.id}\u0000${node.type}`+ if (seen.has(key))+ return++ seen.add(key)+ nodes.push(node)+ })++ return nodes+}++export async function unsupportedDslNodeError(error: unknown): Promise<UnsupportedDslNodeError | undefined> {+ const errorData = await deploymentErrorData(error)+ if (!errorData)+ return undefined++ if (deploymentErrorReason(errorData) !== APP_DEPLOY_UNSUPPORTED_DSL_NODE_TYPE)+ return undefined++ return {+ message: formatDeploymentError(errorData),+ nodes: unsupportedDslNodes(unsupportedNodesPayload(errorData)),+ }+}++export async function deploymentErrorMessage(error: unknown) {+ const errorData = await deploymentErrorData(error)+ if (errorData)+ return formatDeploymentError(errorData)++ if (error instanceof Error)+ return nonEmptyString(error.message)++ return undefined+}diff --git a/web/features/deployments/shared/domain/idempotency.ts b/web/features/deployments/shared/domain/idempotency.tsnew file mode 100644index 00000000000..c9056c38648--- /dev/null+++ b/web/features/deployments/shared/domain/idempotency.ts@@ -0,0 +1,6 @@+export function createDeploymentIdempotencyKey() {+ if (globalThis.crypto?.randomUUID)+ return globalThis.crypto.randomUUID()++ return `deployment-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`+}diff --git a/web/features/deployments/shared/domain/pagination.ts b/web/features/deployments/shared/domain/pagination.tsnew file mode 100644index 00000000000..a474cddec06--- /dev/null+++ b/web/features/deployments/shared/domain/pagination.ts@@ -0,0 +1,12 @@+import type { Pagination } from '@dify/contracts/enterprise/types.gen'++export const DEPLOYMENT_PAGE_SIZE = 100+export const RELEASE_HISTORY_PAGE_SIZE = 20+export const SOURCE_APPS_PAGE_SIZE = 100++export function getNextPageParamFromPagination(pagination?: Pagination) {+ const currentPage = pagination?.currentPage ?? 1+ const totalPages = pagination?.totalPages ?? 1++ return currentPage < totalPages ? currentPage + 1 : undefined+}diff --git a/web/features/deployments/shared/domain/release-action.ts b/web/features/deployments/shared/domain/release-action.tsnew file mode 100644index 00000000000..3e499b547ba--- /dev/null+++ b/web/features/deployments/shared/domain/release-action.ts@@ -0,0 +1,69 @@+import type { Release } from '@dify/contracts/enterprise/types.gen'++export type ReleaseDeploymentAction = 'deploy' | 'deployExistingRelease' | 'promote' | 'rollback'++function releaseCreatedAt(release: Release) {+ const time = Date.parse(release.createdAt)+ return Number.isFinite(time) ? time : undefined+}++function releaseById(releaseRows: Release[], releaseId?: string) {+ return releaseRows.find(release => release.id === releaseId)+}++function releaseOrderIndex(releaseRows: Release[], releaseId?: string) {+ return releaseRows.findIndex(release => release.id === releaseId)+}++function compareReleaseOrder(+ targetRelease: Release | undefined,+ currentRelease: Release,+ releaseRows: Release[],+) {+ if (!targetRelease)+ return undefined+ if (targetRelease.id === currentRelease.id)+ return 0++ const normalizedTargetRelease = releaseById(releaseRows, targetRelease.id) ?? targetRelease+ const normalizedCurrentRelease = releaseById(releaseRows, currentRelease.id) ?? currentRelease+ const targetCreatedAt = releaseCreatedAt(normalizedTargetRelease)+ const currentCreatedAt = releaseCreatedAt(normalizedCurrentRelease)++ if (targetCreatedAt !== undefined && currentCreatedAt !== undefined && targetCreatedAt !== currentCreatedAt)+ return targetCreatedAt > currentCreatedAt ? 1 : -1++ const targetIndex = releaseOrderIndex(releaseRows, targetRelease.id)+ const currentIndex = releaseOrderIndex(releaseRows, currentRelease.id)+ if (targetIndex >= 0 && currentIndex >= 0 && targetIndex !== currentIndex)+ return targetIndex < currentIndex ? 1 : -1++ return undefined+}++export function releaseDeploymentAction({+ targetRelease,+ currentRelease,+ releaseRows,+ isExistingRelease,+}: {+ targetRelease?: Release+ currentRelease?: Release+ releaseRows: Release[]+ isExistingRelease?: boolean+}): ReleaseDeploymentAction {+ if (!currentRelease)+ return isExistingRelease ? 'deployExistingRelease' : 'deploy'++ const order = compareReleaseOrder(targetRelease, currentRelease, releaseRows)+ if (order === -1)+ return 'rollback'+ if (order === 1)+ return 'promote'++ return targetRelease && targetRelease.id !== currentRelease.id+ ? 'promote'+ : isExistingRelease+ ? 'deployExistingRelease'+ : 'deploy'+}diff --git a/web/features/deployments/shared/domain/release.ts b/web/features/deployments/shared/domain/release.tsnew file mode 100644index 00000000000..c5bd71abe82--- /dev/null+++ b/web/features/deployments/shared/domain/release.ts@@ -0,0 +1,17 @@+import type { Release } from '@dify/contracts/enterprise/types.gen'+import { formatTime } from '@/utils/time'++export function formatDate(value?: string) {+ if (!value)+ return '—'++ const date = new Date(value)+ if (Number.isNaN(date.getTime()))+ return value.replace('T', ' ').replace(/\.\d+Z?$/, '').replace(/Z$/, '').slice(0, 16)++ return formatTime({ date, dateFormat: 'YYYY-MM-DD HH:mm' })+}++export function releaseCommit(release?: Release) {+ return release?.gateCommitId ? release.gateCommitId.slice(0, 8) : '—'+}diff --git a/web/features/deployments/shared/domain/runtime-status.ts b/web/features/deployments/shared/domain/runtime-status.tsnew file mode 100644index 00000000000..9a2540047c1--- /dev/null+++ b/web/features/deployments/shared/domain/runtime-status.ts@@ -0,0 +1,30 @@+import type { EnvironmentDeployment, RuntimeInstanceStatus as RuntimeInstanceStatusValue } from '@dify/contracts/enterprise/types.gen'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'++const DEPLOYMENT_STATUS_POLLING_INTERVAL = 3000++export function isUndeployedDeploymentRow(row: EnvironmentDeployment) {+ const status = row.status+ return status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED+ || (status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED+ && !row.currentRelease+ && !row.desiredRelease+ && !row.currentDeployment)+}++export function hasRuntimeInstanceDeployment(row: EnvironmentDeployment) {+ return !isUndeployedDeploymentRow(row)+}++export function isAvailableDeploymentTarget(row: EnvironmentDeployment) {+ return isUndeployedDeploymentRow(row)+}++export function isRuntimeDeploymentInProgress(status?: RuntimeInstanceStatusValue) {+ return status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING+ || status === RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING+}++export function deploymentStatusPollingInterval(rows?: EnvironmentDeployment[]) {+ return rows?.some(row => isRuntimeDeploymentInProgress(row.status)) ? DEPLOYMENT_STATUS_POLLING_INTERVAL : false+}diff --git a/web/features/deployments/shared/ui/__tests__/deployment-status-badge.spec.tsx b/web/features/deployments/shared/ui/__tests__/deployment-status-badge.spec.tsxnew file mode 100644index 00000000000..57056eaa90c--- /dev/null+++ b/web/features/deployments/shared/ui/__tests__/deployment-status-badge.spec.tsx@@ -0,0 +1,52 @@+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'+import { render, screen } from '@testing-library/react'+import { describe, expect, it } from 'vitest'+import { DeploymentStatusBadge } from '../deployment-status-badge'++describe('DeploymentStatusBadge', () => {+ it('should keep the original badge style by default', () => {+ const { container } = render(+ <DeploymentStatusBadge+ status={RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY}+ label="Running"+ />,+ )++ const badge = screen.getByText('Running').parentElement++ expect(badge).toHaveClass('border', 'rounded-md', 'bg-util-colors-green-green-50', 'system-2xs-medium-uppercase')+ expect(container.querySelector('.bg-util-colors-green-green-500')).not.toBeInTheDocument()+ expect(container.querySelector('.shadow-status-indicator-green-shadow')).toBeInTheDocument()+ })++ it('should render the status-dot variant like knowledge list status', () => {+ const { container } = render(+ <DeploymentStatusBadge+ status={RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY}+ label="Running"+ variant="status-dot"+ />,+ )++ const badge = screen.getByText('Running').parentElement++ expect(badge).not.toHaveClass('border', 'rounded-md', 'bg-util-colors-green-green-50')+ expect(badge).toHaveClass('system-2xs-medium-uppercase')+ expect(screen.getByText('Running')).not.toHaveClass('text-sm')+ expect(screen.getByText('Running')).toHaveClass('text-util-colors-green-green-600')+ expect(container.querySelector('.shadow-status-indicator-green-shadow')).toBeInTheDocument()+ })++ it('should keep the status dot pulsing for in-progress statuses', () => {+ const { container } = render(+ <DeploymentStatusBadge+ status={RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING}+ label="Deploying"+ variant="status-dot"+ />,+ )++ expect(screen.getByText('Deploying')).toHaveClass('text-util-colors-blue-light-blue-light-600')+ expect(container.querySelector('.shadow-status-indicator-blue-shadow')).toHaveClass('animate-pulse')+ })+})diff --git a/web/features/deployments/shared/ui/deployment-status-badge.tsx b/web/features/deployments/shared/ui/deployment-status-badge.tsxnew file mode 100644index 00000000000..dadb3953f4d--- /dev/null+++ b/web/features/deployments/shared/ui/deployment-status-badge.tsx@@ -0,0 +1,123 @@+'use client'++import type {+ EnvironmentDeployment,+ RuntimeInstanceStatus as RuntimeInstanceStatusValue,+} from '@dify/contracts/enterprise/types.gen'+import type { ComponentPropsWithRef } from 'react'+import { cn } from '@langgenius/dify-ui/cn'+import { StatusDot } from '@langgenius/dify-ui/status-dot'+import { useTranslation } from 'react-i18next'+import { isRuntimeDeploymentInProgress } from '../domain/runtime-status'+import {+ deploymentStatusDotStatus,+ deploymentStatusDotTextClassName,+ deploymentStatusLabelKey,+ deploymentStatusToneClassNames,+} from './deployment-status-style'++type DeploymentStatusBadgeProps = Omit<ComponentPropsWithRef<'span'>, 'children'> & {+ status: RuntimeInstanceStatusValue+ label: string+ variant?: 'badge' | 'status-dot'+}++export function DeploymentStatusBadge({+ status,+ label,+ className,+ variant = 'badge',+ ref,+ ...props+}: DeploymentStatusBadgeProps) {+ const isInProgress = isRuntimeDeploymentInProgress(status)++ if (variant === 'status-dot') {+ const dotStatus = deploymentStatusDotStatus(status)++ return (+ <span+ ref={ref}+ className={cn(+ 'inline-flex max-w-full cursor-default items-center system-2xs-medium-uppercase',+ className,+ )}+ {...props}+ >+ <StatusDot+ status={dotStatus}+ className={cn('mr-2', isInProgress && 'animate-pulse')}+ />+ <span className={cn('truncate', deploymentStatusDotTextClassName(status))}>+ {label}+ </span>+ </span>+ )+ }++ const toneClassNames = deploymentStatusToneClassNames(status)+ const dotStatus = deploymentStatusDotStatus(status)++ return (+ <span+ ref={ref}+ className={cn(+ 'inline-flex h-5 max-w-full cursor-default items-center gap-1 rounded-md border px-1.5 system-2xs-medium-uppercase',+ toneClassNames.badge,+ className,+ )}+ {...props}+ >+ <StatusDot+ status={dotStatus}+ className={cn('shrink-0', isInProgress && 'animate-pulse')}+ />+ <span className="truncate">{label}</span>+ </span>+ )+}++type EnvironmentDeploymentBadgeProps = Omit<ComponentPropsWithRef<'span'>, 'children' | 'title'> & {+ row: EnvironmentDeployment+ showStatus?: boolean+ summaryLabel?: string+}++export function EnvironmentDeploymentBadge({+ row,+ className,+ showStatus = true,+ summaryLabel,+ 'aria-label': ariaLabel,+ ref,+ ...props+}: EnvironmentDeploymentBadgeProps) {+ const { t } = useTranslation('deployments')+ const name = row.environment.displayName+ const status = row.status+ const toneClassNames = deploymentStatusToneClassNames(status)+ const dotStatus = deploymentStatusDotStatus(status)+ const isInProgress = isRuntimeDeploymentInProgress(status)+ const statusLabel = t(deploymentStatusLabelKey(status))+ const label = summaryLabel ?? `${name} · ${statusLabel}`+ const visibleLabel = showStatus ? `${name} · ${statusLabel}` : name++ return (+ <span+ ref={ref}+ aria-label={ariaLabel ?? label}+ className={cn(+ 'inline-flex h-5 max-w-full cursor-default items-center gap-1 rounded-md border px-1.5 system-xs-medium',+ toneClassNames.badge,+ className,+ )}+ {...props}+ >+ <StatusDot+ status={dotStatus}+ className={cn('shrink-0', isInProgress && 'animate-pulse')}+ />+ <span className="truncate">{visibleLabel}</span>+ </span>+ )+}diff --git a/web/features/deployments/shared/ui/deployment-status-style.ts b/web/features/deployments/shared/ui/deployment-status-style.tsnew file mode 100644index 00000000000..0997d8e3112--- /dev/null+++ b/web/features/deployments/shared/ui/deployment-status-style.ts@@ -0,0 +1,79 @@+import type { RuntimeInstanceStatus as RuntimeInstanceStatusValue } from '@dify/contracts/enterprise/types.gen'+import type { StatusDotStatus } from '@langgenius/dify-ui/status-dot'+import { RuntimeInstanceStatus } from '@dify/contracts/enterprise/types.gen'++type DeploymentStatusTone = 'neutral' | 'success' | 'warning' | 'danger' | 'info'+type DeploymentStatusLabelKey = `status.${RuntimeInstanceStatusValue}`++const STATUS_TONE: Record<RuntimeInstanceStatusValue, DeploymentStatusTone> = {+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED]: 'neutral',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED]: 'neutral',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING]: 'info',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY]: 'success',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED]: 'danger',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DRIFTED]: 'warning',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_INVALID]: 'danger',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING]: 'info',+}++const STATUS_DOT_STATUS: Record<RuntimeInstanceStatusValue, StatusDotStatus> = {+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED]: 'disabled',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED]: 'disabled',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING]: 'normal',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_READY]: 'success',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_FAILED]: 'error',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_DRIFTED]: 'warning',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_INVALID]: 'error',+ [RuntimeInstanceStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING]: 'normal',+}++const STATUS_DOT_TEXT_CLASS_NAMES: Record<StatusDotStatus, string> = {+ disabled: 'text-text-tertiary',+ error: 'text-util-colors-red-red-600',+ normal: 'text-util-colors-blue-light-blue-light-600',+ success: 'text-util-colors-green-green-600',+ warning: 'text-util-colors-warning-warning-600',+}++const TONE_CLASS_NAMES: Record<DeploymentStatusTone, { badge: string, dot: string }> = {+ danger: {+ badge: 'border-util-colors-red-red-200 bg-util-colors-red-red-50 text-util-colors-red-red-700',+ dot: 'bg-util-colors-red-red-500',+ },+ info: {+ badge: 'border-util-colors-blue-blue-200 bg-util-colors-blue-blue-50 text-util-colors-blue-blue-700',+ dot: 'bg-util-colors-blue-blue-500',+ },+ neutral: {+ badge: 'border-divider-subtle bg-background-section-burn text-text-tertiary',+ dot: 'bg-text-quaternary',+ },+ success: {+ badge: 'border-util-colors-green-green-200 bg-util-colors-green-green-50 text-util-colors-green-green-700',+ dot: 'bg-util-colors-green-green-500',+ },+ warning: {+ badge: 'border-util-colors-warning-warning-200 bg-util-colors-warning-warning-50 text-util-colors-warning-warning-700',+ dot: 'bg-util-colors-warning-warning-500',+ },+}++export function deploymentStatusLabelKey(status: RuntimeInstanceStatusValue): DeploymentStatusLabelKey {+ return `status.${status}`+}++function deploymentStatusTone(status: RuntimeInstanceStatusValue) {+ return STATUS_TONE[status]+}++export function deploymentStatusToneClassNames(status: RuntimeInstanceStatusValue) {+ return TONE_CLASS_NAMES[deploymentStatusTone(status)]+}++export function deploymentStatusDotStatus(status: RuntimeInstanceStatusValue) {+ return STATUS_DOT_STATUS[status]+}++export function deploymentStatusDotTextClassName(status: RuntimeInstanceStatusValue) {+ return STATUS_DOT_TEXT_CLASS_NAMES[deploymentStatusDotStatus(status)]+}diff --git a/web/features/system-features/config.ts b/web/features/system-features/config.tsindex 3932259800d..1161ac64184 100644--- a/web/features/system-features/config.ts+++ b/web/features/system-features/config.ts@@ -3,6 +3,7 @@ import { env } from '@/env'import { InstallationScope, LicenseStatus } from './constants'export const defaultSystemFeatures = {+ enable_app_deploy: false,sso_enforced_for_signin: false,sso_enforced_for_signin_protocol: '',enable_marketplace: false,diff --git a/web/i18n-config/resources.ts b/web/i18n-config/resources.tsindex 6cca6e97cba..d2d0f76be75 100644--- a/web/i18n-config/resources.ts+++ b/web/i18n-config/resources.ts@@ -13,6 +13,7 @@ import type datasetHitTesting from '../i18n/en-US/dataset-hit-testing.json'import type datasetPipeline from '../i18n/en-US/dataset-pipeline.json'import type datasetSettings from '../i18n/en-US/dataset-settings.json'import type dataset from '../i18n/en-US/dataset.json'+import type deployments from '../i18n/en-US/deployments.json'import type education from '../i18n/en-US/education.json'import type explore from '../i18n/en-US/explore.json'import type layout from '../i18n/en-US/layout.json'@@ -47,6 +48,7 @@ export type Resources = {datasetHitTesting: typeof datasetHitTestingdatasetPipeline: typeof datasetPipelinedatasetSettings: typeof datasetSettings+ deployments: typeof deploymentseducation: typeof educationexplore: typeof explorelayout: typeof layout@@ -81,6 +83,7 @@ export const namespaces = ['datasetHitTesting','datasetPipeline','datasetSettings',+ 'deployments','education','explore','layout',diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.jsonindex cf2ee19ac04..63c94d0e298 100644--- a/web/i18n/en-US/common.json+++ b/web/i18n/en-US/common.json@@ -311,6 +311,7 @@"menus.apps": "Studio","menus.datasets": "Knowledge","menus.datasetsTips": "COMING SOON: Import your own text data or write data in real-time via Webhook for LLM context enhancement.",+ "menus.deployments": "Deployments","menus.explore": "Explore","menus.exploreMarketplace": "Explore Marketplace","menus.newApp": "New App",diff --git a/web/i18n/en-US/deployments.json b/web/i18n/en-US/deployments.jsonnew file mode 100644index 00000000000..c557989ea42--- /dev/null+++ b/web/i18n/en-US/deployments.json@@ -0,0 +1,623 @@+{+ "access.api.backendTitle": "Backend service API",+ "access.api.copyCurlExample": "Copy cURL example",+ "access.api.createFailed": "Failed to generate API Token.",+ "access.api.createKey": "Generate API Token",+ "access.api.createKeyTitle": "Generate new API Token",+ "access.api.curlExampleTitle": "cURL example",+ "access.api.description": "Access this deployment over HTTP. Each API Token is scoped to one environment.",+ "access.api.developerTitle": "Developer API",+ "access.api.disabled": "API access is turned off for this deployment.",+ "access.api.disabledHint": "Enable API access to generate environment-scoped tokens.",+ "access.api.dismissToken": "Dismiss API Token",+ "access.api.docs": "API Docs",+ "access.api.docsClose": "Close API docs",+ "access.api.docsDescription": "View the Workflow API reference for this deployment.",+ "access.api.docsTitle": "Workflow API documentation",+ "access.api.empty": "Deploy to an environment first to start issuing API Tokens.",+ "access.api.emptyTitle": "No deployed environments",+ "access.api.endpoint": "Request URL",+ "access.api.envPrefix": "env: {{env}}",+ "access.api.keyList": "API Token list",+ "access.api.nameLabel": "API Token name",+ "access.api.namePlaceholder": "Enter an API Token name",+ "access.api.nameRequired": "API Token name is required.",+ "access.api.newKey": "Generate New API Token",+ "access.api.newTokenDescription": "This API Token is shown only once. Copy it before leaving this page.",+ "access.api.newTokenLabel": "API Token",+ "access.api.newTokenTitle": "API Token generated",+ "access.api.noKeys": "No API Tokens yet. Generate one to start calling the API.",+ "access.api.noKeysTitle": "No API Tokens yet",+ "access.api.revokeConfirmDescription": "The API Token \"{{name}}\" will stop working immediately. This action cannot be undone.",+ "access.api.revokeConfirmTitle": "Revoke API Token?",+ "access.api.revokeFailed": "Failed to revoke API Token.",+ "access.api.revokeSuccess": "API Token revoked",+ "access.api.table.action": "Action",+ "access.api.table.environment": "Environment",+ "access.api.table.key": "API Token",+ "access.api.table.name": "Name",+ "access.api.title": "API",+ "access.channels.col.channel": "Channel",+ "access.channels.col.endpoint": "Entry point",+ "access.channels.col.status": "Status",+ "access.channels.description": "WebApp and CLI entry points use the access permissions above.",+ "access.channels.disabled": "Access channels are turned off for this deployment.",+ "access.channels.disabledHint": "Enable access channels to expose WebApp and CLI entry points.",+ "access.channels.followPermission": "Follows permissions",+ "access.channels.title": "Access channels",+ "access.cli.description": "Invoke from the terminal with difyctl, suitable for scripts, automated workflows, or Agent integrations.",+ "access.cli.docs": "Usage guide",+ "access.cli.domain": "Domain",+ "access.cli.empty": "CLI endpoint not configured.",+ "access.cli.install": "Install CLI",+ "access.cli.title": "CLI",+ "access.copied": "Copied",+ "access.copy": "Copy",+ "access.copyFailed": "Copy failed",+ "access.copyToast": "Copied to clipboard",+ "access.hide": "Hide",+ "access.members.clearAll": "Clear all",+ "access.members.empty": "No matches found.",+ "access.members.groupCount_one": "{{count}} group",+ "access.members.groupCount_other": "{{count}} groups",+ "access.members.groups": "Groups",+ "access.members.individuals": "Members",+ "access.members.memberCount_one": "{{count}} member",+ "access.members.memberCount_other": "{{count}} members",+ "access.members.pickPlaceholder": "Select groups or members",+ "access.members.searchPlaceholder": "Search groups and members",+ "access.members.selectedLabel": "Selected",+ "access.permission.anyone": "Anyone with the link",+ "access.permission.anyoneDesc": "Anyone can access this deployment without logging in.",+ "access.permission.memberCount_one": "{{count}} member",+ "access.permission.memberCount_other": "{{count}} members",+ "access.permission.organization": "All members within the platform",+ "access.permission.organizationDesc": "All members within the platform",+ "access.permission.specific": "Specific members within the platform",+ "access.permission.specificDesc": "Select specific groups or members",+ "access.permission.specificUnavailable": "Specific member selection is disabled until real platform members and groups are connected.",+ "access.permission.updateFailed": "Failed to update access policy.",+ "access.permissions.col.environment": "Environment",+ "access.permissions.col.permission": "Access",+ "access.permissions.description": "Set access permissions for WebApp and CLI entry points in each environment.",+ "access.permissions.editAriaLabel": "Configure access for {{environment}}",+ "access.permissions.editDescription": "Set access permissions for WebApp and CLI entry points.",+ "access.permissions.editTitle": "Access permissions",+ "access.permissions.title": "Access permissions",+ "access.revoke": "Revoke",+ "access.runAccess.description": "Manage how users can run this deployment and who is allowed to access it per environment.",+ "access.runAccess.disabled": "Run access is turned off for this deployment.",+ "access.runAccess.mcp": "MCP",+ "access.runAccess.mcpDesc": "Expose this deployment as a Model Context Protocol server.",+ "access.runAccess.mcpEmpty": "MCP endpoint not configured.",+ "access.runAccess.noEnvs": "Deploy to an environment to configure access permissions.",+ "access.runAccess.noEnvsTitle": "No deployed environments",+ "access.runAccess.openWebapp": "Open WebApp",+ "access.runAccess.permissions": "Access permissions",+ "access.runAccess.permissionsDesc": "Who can access this deployment in each environment.",+ "access.runAccess.title": "Run access",+ "access.runAccess.urlLabel": "URL",+ "access.runAccess.webapp": "WebApp",+ "access.runAccess.webappDesc": "Hosted web page for end users.",+ "access.runAccess.webappEmpty": "Coming soon.",+ "access.show": "Show",+ "backend.RUNTIME_BACKEND_EXTERNAL": "External",+ "backend.RUNTIME_BACKEND_K8S": "K8S",+ "backend.RUNTIME_BACKEND_UNSPECIFIED": "Unknown",+ "card.access.api": "API Tokens",+ "card.access.apiShort": "API",+ "card.access.cli": "CLI",+ "card.access.cliShort": "CLI",+ "card.access.none": "No access",+ "card.access.webApp": "WebApp",+ "card.access.webAppShort": "Web",+ "card.createFirstRelease": "Create First Release",+ "card.deploy": "Deploy",+ "card.deploying": "{{count}} deploying",+ "card.envOverflow": "+ {{count}}",+ "card.failed": "{{count}} failed",+ "card.fromApp": "From {{name}}",+ "card.lastDeployed": "Last deployed {{time}}",+ "card.menu.delete": "Delete deployment",+ "card.menu.deleteDisabled": "Deployment deletion is not available for backend-managed deployments yet.",+ "card.menu.deploy": "Deploy to Environment",+ "card.menu.editInfo": "Edit Info",+ "card.menu.viewDetail": "View deployment detail",+ "card.moreActions": "More actions",+ "card.neverDeployed": "Not deployed yet",+ "card.noDescription": "No description provided.",+ "card.notDeployed": "Not deployed",+ "card.ready": "{{count}} running",+ "card.tooltip.createdAt": "Created",+ "card.tooltip.deployed": "Deployed",+ "card.tooltip.deploymentStatus": "Deployment",+ "card.tooltip.notDeployed": "This deployment has not been deployed to any environment yet.",+ "card.tooltip.notDeployedShort": "Not deployed",+ "card.tooltip.release": "Release",+ "card.tooltip.releaseName": "Release Name",+ "card.tooltip.source": "Source",+ "common.loadFailed": "Failed to load. Try again later.",+ "common.loading": "Loading...",+ "createGuide.actions.back": "Back",+ "createGuide.actions.cancel": "Cancel",+ "createGuide.actions.continue": "Continue",+ "createGuide.actions.createAndDeploy": "Create & Deploy",+ "createGuide.actions.creating": "Creating...",+ "createGuide.actions.deploy": "Deploy",+ "createGuide.actions.deploying": "Creating & deploying...",+ "createGuide.actions.next": "Next",+ "createGuide.actions.skipDeploy": "Skip, deploy later",+ "createGuide.description": "Create a deployment from a release source, basic info, and target environment.",+ "createGuide.dsl.defaultAppName": "Imported DSL app",+ "createGuide.dsl.description": "Upload a Workflow DSL package to create the deployment, first release, and optional environment deployment.",+ "createGuide.dsl.dropDescription": "Upload a Workflow YAML DSL package. Deployment options are resolved from this file before deploy.",+ "createGuide.dsl.dropTitle": "Upload Workflow DSL package",+ "createGuide.dsl.readFailed": "Failed to read the DSL file. Choose another file and try again.",+ "createGuide.dsl.reading": "Reading DSL file...",+ "createGuide.dsl.title": "Import DSL",+ "createGuide.dsl.unsupportedMode": "Only Workflow DSL files can be used for deployments.",+ "createGuide.errors.createReleaseFailed": "Failed to create the deployment or release.",+ "createGuide.errors.deployFailed": "Failed to deploy to the environment.",+ "createGuide.method.description": "Choose the source used to create the first release.",+ "createGuide.methods.bindApp.description": "Use an existing Workflow App in Studio as the release source.",+ "createGuide.methods.bindApp.title": "Bind existing Workflow App",+ "createGuide.methods.importDsl.description": "Upload a Workflow YAML DSL package and continue through the deployment UI.",+ "createGuide.methods.importDsl.title": "Import DSL",+ "createGuide.methods.mocked": "Mocked",+ "createGuide.nav.back": "Deployments",+ "createGuide.release.defaultName": "initial release",+ "createGuide.release.deployInfo": "Deployment Info",+ "createGuide.release.description": "Fill in deployment info and first release details.",+ "createGuide.release.firstVersion": "First Release",+ "createGuide.release.instanceDescription": "Deployment Description",+ "createGuide.release.instanceDescriptionPlaceholder": "Describe what this deployment is used for",+ "createGuide.release.instanceName": "Deployment Name",+ "createGuide.release.instanceNameConflict": "A deployment with this name already exists. Choose another name.",+ "createGuide.release.releaseDescription": "Release Description",+ "createGuide.release.releaseDescriptionPlaceholder": "Describe this release",+ "createGuide.release.releaseName": "Release Name",+ "createGuide.release.releaseNote": "Release Description",+ "createGuide.release.title": "Basic Info",+ "createGuide.source.availableApps_one": "{{count}} app",+ "createGuide.source.availableApps_other": "{{count}} apps",+ "createGuide.source.clearSearch": "Clear app search",+ "createGuide.source.description": "Choose the source used to create the first release.",+ "createGuide.source.empty": "No Workflow Apps found.",+ "createGuide.source.searchPlaceholder": "Search apps",+ "createGuide.source.sourceApp": "Workflow App",+ "createGuide.source.title": "Release Source",+ "createGuide.steps.method": "Release Source",+ "createGuide.steps.release": "Basic Info",+ "createGuide.steps.source": "Release Source",+ "createGuide.steps.target": "Deploy to Environment",+ "createGuide.target.bindingCount_one": "{{count}} binding",+ "createGuide.target.bindingCount_other": "{{count}} bindings",+ "createGuide.target.bindingHint": "Pick the credentials used by this release.",+ "createGuide.target.bindings": "Credentials",+ "createGuide.target.deferredBindingHint": "Credentials will be resolved from the real deployment plan during the final deploy action.",+ "createGuide.target.deferredEnvironmentHint": "The name is matched against the real environments after the deployment and release are created.",+ "createGuide.target.description": "Choose a target environment and provide the runtime settings this release needs there. This step can be skipped.",+ "createGuide.target.envVarCount_one": "{{count}} variable",+ "createGuide.target.envVarCount_other": "{{count}} variables",+ "createGuide.target.envVarHint": "For each environment variable this release needs, enter a custom value or use the value defined in the app.",+ "createGuide.target.envVarPlaceholder": "Enter value",+ "createGuide.target.envVarSource.ariaLabel": "Select the variable value source for {{key}}",+ "createGuide.target.envVarSource.default": "App value",+ "createGuide.target.envVarSource.lastDeployment": "Last deployed value",+ "createGuide.target.envVarSource.literal": "Custom value",+ "createGuide.target.envVarType.number": "Number",+ "createGuide.target.envVarType.secret": "Secret",+ "createGuide.target.envVarType.string": "String",+ "createGuide.target.envVars": "Environment Variables",+ "createGuide.target.environment": "Target Environment",+ "createGuide.target.environmentName": "Environment Name",+ "createGuide.target.environmentNamePlaceholder": "Production",+ "createGuide.target.loadBindingsFailed": "Failed to load credentials.",+ "createGuide.target.loadEnvironmentsFailed": "Failed to load deploy environments.",+ "createGuide.target.missingRequiredBinding": "Select a credential for this required binding.",+ "createGuide.target.noBindingRequired": "No credentials required.",+ "createGuide.target.noCredentialCandidates": "No available credentials.",+ "createGuide.target.noEnvironmentOptions": "No deploy environments available.",+ "createGuide.target.required": "Required",+ "createGuide.target.selectCredential": "Select a credential",+ "createGuide.target.title": "Deploy to Environment",+ "createGuide.title": "New Deployment",+ "createModal.appPickerPlaceholder": "Select a Workflow App",+ "createModal.appSearchEmpty": "No matching Workflow Apps",+ "createModal.appSearchPlaceholder": "Search Workflow Apps…",+ "createModal.cancel": "Cancel",+ "createModal.create": "Create",+ "createModal.createFailed": "Failed to create deployment.",+ "createModal.description": "Pick a Workflow App and create a deployment.",+ "createModal.descriptionLabel": "Description",+ "createModal.descriptionPlaceholder": "Describe what this deployment is used for",+ "createModal.loadMoreApps": "Load more apps",+ "createModal.loadingApps": "Loading apps…",+ "createModal.nameLabel": "Deployment Name",+ "createModal.namePlaceholder": "Deployment Name",+ "createModal.noApps": "No Workflow Apps found in this workspace. Create one in Studio first.",+ "createModal.selected": "Selected",+ "createModal.sourceApp": "Workflow App (required)",+ "createModal.title": "New Deployment",+ "deployDrawer.bindingCount_one": "{{count}} binding",+ "deployDrawer.bindingCount_other": "{{count}} bindings",+ "deployDrawer.bindingOptionsFailed": "Failed to load credential options.",+ "deployDrawer.bindingSelectionHint": "Choose the credentials used by this deployment.",+ "deployDrawer.bindingsDisabled": "Resolved from the release preview. Editing is not available yet.",+ "deployDrawer.cancel": "Cancel",+ "deployDrawer.close": "Close deployment drawer",+ "deployDrawer.defaultSelect": "Select...",+ "deployDrawer.deploy": "Deploy to Environment",+ "deployDrawer.deployExistingRelease": "Deploy to Environment",+ "deployDrawer.deployExistingReleaseDescription": "Select a release and target environment to deploy.",+ "deployDrawer.deployExistingReleaseTitle": "Deploy to Environment",+ "deployDrawer.deployFailed": "Failed to start deployment.",+ "deployDrawer.deploying": "Deploying...",+ "deployDrawer.description": "Select a release and target environment to deploy.",+ "deployDrawer.envVarCount_one": "{{count}} variable",+ "deployDrawer.envVarCount_other": "{{count}} variables",+ "deployDrawer.envVarHint": "For each environment variable this release needs, enter a custom value or use the value defined in the app.",+ "deployDrawer.envVarPlaceholder": "Enter value",+ "deployDrawer.envVarSource.ariaLabel": "Select the variable value source for {{key}}",+ "deployDrawer.envVarSource.default": "App value",+ "deployDrawer.envVarSource.lastDeployment": "Last deployed value",+ "deployDrawer.envVarSource.literal": "Custom value",+ "deployDrawer.envVarType.number": "Number",+ "deployDrawer.envVarType.secret": "Secret",+ "deployDrawer.envVarType.string": "String",+ "deployDrawer.envVars": "Environment Variables",+ "deployDrawer.existingReleaseHint": "This release will be deployed as-is. No new release will be created.",+ "deployDrawer.loadingBindings": "Resolving...",+ "deployDrawer.lockedHint": "Locked to current environment",+ "deployDrawer.missingRequiredBinding": "Select a credential for this required binding.",+ "deployDrawer.missingRequiredEnvVar": "Enter a value for this required environment variable.",+ "deployDrawer.modelCreds": "Model Credentials",+ "deployDrawer.needsValidation": " (needs validation)",+ "deployDrawer.newReleaseHint": "A new release will be created from the selected Workflow App YAML.",+ "deployDrawer.noBindingRequired": "Not required",+ "deployDrawer.noCredentialCandidates": "No available credentials.",+ "deployDrawer.noNewEnvironmentAvailable": "All available environments already have a deployment.",+ "deployDrawer.noOtherReleaseAvailable": "No other releases are available for this environment.",+ "deployDrawer.noReleaseAvailable": "Create a release before deploying to an environment.",+ "deployDrawer.notFound": "Deployment not found.",+ "deployDrawer.noteLabel": "Release Description (optional)",+ "deployDrawer.notePlaceholder": "e.g. Ship onboarding copy tweak",+ "deployDrawer.pluginCreds": "Plugin Credentials",+ "deployDrawer.promote": "Deploy",+ "deployDrawer.promoteDescription": "Select a release and target environment to deploy.",+ "deployDrawer.promoteTitle": "Deploy to Environment",+ "deployDrawer.readOnly": "Read-only",+ "deployDrawer.redeploy": "Deploy to Environment",+ "deployDrawer.redeployDescription": "Select a release and target environment to deploy.",+ "deployDrawer.redeployExistingReleaseHint": "The current release will be redeployed as-is. No new release will be created.",+ "deployDrawer.redeployTitle": "Deploy to Environment",+ "deployDrawer.releaseLabel": "Release",+ "deployDrawer.requiredBinding": "Required",+ "deployDrawer.rollback": "Deploy",+ "deployDrawer.rollbackDescription": "Select a release and target environment to deploy.",+ "deployDrawer.rollbackTitle": "Deploy to Environment",+ "deployDrawer.runtimeCredentials": "Credentials",+ "deployDrawer.secretPlaceholder": "secret",+ "deployDrawer.selectCredential": "Select a credential",+ "deployDrawer.selectEnv": "Select an environment",+ "deployDrawer.selectProviderCred": "Select {{provider}} credential",+ "deployDrawer.selectProviderKey": "Select {{provider}} key",+ "deployDrawer.selectRelease": "Select a release",+ "deployDrawer.targetEnv": "Target Environment",+ "deployDrawer.title": "Deploy to Environment",+ "deployDrawer.valuePlaceholder": "value",+ "deployTab.cancelDeployment": "Cancel deployment",+ "deployTab.closeError": "Close",+ "deployTab.col.actions": "Actions",+ "deployTab.col.currentRelease": "Current Release",+ "deployTab.col.environment": "Environment",+ "deployTab.col.status": "Status",+ "deployTab.col.updated": "Updated",+ "deployTab.collapseDetails": "Collapse deployment details",+ "deployTab.confirmUndeploy": "Undeploy",+ "deployTab.deployOtherVersion": "Deploy Another Release",+ "deployTab.deployToEnv": "Deploy to {{name}}",+ "deployTab.deployToNewEnv": "Deploy to New Environment...",+ "deployTab.empty": "No instances yet. Deploy to a new environment to get started.",+ "deployTab.emptyDescription": "Choose a release and target environment to make this deployment available to users.",+ "deployTab.emptyTitle": "No environments are running yet",+ "deployTab.envCount": "Environments",+ "deployTab.errorCode": "Code",+ "deployTab.errorDialogDesc": "Review the last failed deployment before retrying or deploying another release.",+ "deployTab.errorDialogTitle": "Deployment error in {{name}}",+ "deployTab.errorMessage": "Message",+ "deployTab.errorPhase": "Phase",+ "deployTab.expandDetails": "Expand deployment details",+ "deployTab.moreActions": "More actions",+ "deployTab.newDeployment": "Deploy to New Environment",+ "deployTab.panel.commit": "Commit ID",+ "deployTab.panel.deploymentId": "Deployment ID",+ "deployTab.panel.endpoints": "Endpoints",+ "deployTab.panel.envVars": "Environment Variables",+ "deployTab.panel.error": "Error",+ "deployTab.panel.failedRelease": "Failed Release",+ "deployTab.panel.health": "Health",+ "deployTab.panel.instanceInfo": "Instance Info",+ "deployTab.panel.modelCreds": "Model Credentials",+ "deployTab.panel.pluginCreds": "Plugin Credentials",+ "deployTab.panel.release": "Release",+ "deployTab.panel.releaseCreatedAt": "Release Created At",+ "deployTab.panel.releaseInfo": "Release Info",+ "deployTab.panel.replicas": "Replicas",+ "deployTab.panel.run": "Run",+ "deployTab.panel.runtimeBindings": "Credentials",+ "deployTab.panel.runtimeInfo": "Runtime Info",+ "deployTab.panel.runtimeMode": "Runtime Mode",+ "deployTab.panel.runtimeNote": "Runtime Note",+ "deployTab.panel.targetRelease": "Target Release",+ "deployTab.panel.unknownError": "Deployment failed.",+ "deployTab.promote": "Deploy",+ "deployTab.redeploy": "Redeploy",+ "deployTab.releaseCreatedAt": "Release created {{time}}",+ "deployTab.retry": "Retry",+ "deployTab.shortcut": "Shortcut",+ "deployTab.status.deployFailed": "Deploy failed",+ "deployTab.status.deployingRelease": "Deploying ({{release}})",+ "deployTab.status.runningOutOfSync": "Running (sync pending)",+ "deployTab.status.runningWithFailed": "Running (last deployment failed)",+ "deployTab.undeploy": "Undeploy",+ "deployTab.undeployConfirmDesc": "End-user access will stop immediately. The release can be redeployed later.",+ "deployTab.undeployConfirmTitle": "Undeploy from {{name}}?",+ "deployTab.undeployFrom": "Undeploy from {{name}}",+ "deployTab.undeployImpactTitle": "Affected instance",+ "deployTab.viewError": "View error",+ "deployTab.viewLogs": "View logs",+ "deployTab.viewProgress": "View progress",+ "detail.backToInstances": "Back to deployments",+ "detail.deployingCount": "{{count}} deploying",+ "detail.envCount_one": "{{count}} env",+ "detail.envCount_other": "{{count}} envs",+ "detail.failedCount": "{{count}} failed",+ "detail.mobileTabs": "Deployment sections",+ "detail.notFound": "Deployment not found",+ "detail.openSourceApp": "Open source {{name}}",+ "detail.sourceApp": "Source",+ "detail.sourceAppLink": "Source",+ "documentTitle.create": "New deployment · Deployments",+ "documentTitle.detail": "Deployment · Deployments",+ "documentTitle.list": "Deployments",+ "filter.allEnvs": "All environments",+ "filter.notDeployed": "Not deployed",+ "filter.searchPlaceholder": "Search deployments",+ "health.ENVIRONMENT_STATUS_ADMISSION": "Admission",+ "health.ENVIRONMENT_STATUS_BOOTSTRAPPING": "Bootstrapping",+ "health.ENVIRONMENT_STATUS_DELETING": "Deleting",+ "health.ENVIRONMENT_STATUS_FAILED": "Unavailable",+ "health.ENVIRONMENT_STATUS_READY": "Available",+ "health.ENVIRONMENT_STATUS_UNSPECIFIED": "Unknown",+ "list.clearFilters": "Clear filters",+ "list.clearSearch": "Clear deployment search",+ "list.createDeployment": "New",+ "list.empty": "No deployments found.",+ "list.emptyDescription": "Create a deployment from a Workflow App or Workflow DSL package to manage releases, environments, and access.",+ "list.emptyFilteredDescription": "No deployment matches the current search or environment filter.",+ "list.emptyFilteredTitle": "No matching deployments",+ "list.emptyTitle": "No deployments yet",+ "mode.ENVIRONMENT_MODE_ISOLATED": "Isolated",+ "mode.ENVIRONMENT_MODE_SHARED": "Shared",+ "mode.ENVIRONMENT_MODE_UNSPECIFIED": "Unknown",+ "newInstance.comingSoon": "Coming soon",+ "newInstance.fromStudio": "Select from Studio",+ "newInstance.importDSL": "Import DSL",+ "newInstance.title": "New Deployment",+ "overview.accessEndpoints": "Access endpoints",+ "overview.accessMeta.apiTokens": "Manage API Tokens",+ "overview.accessMeta.cli": "View CLI access",+ "overview.accessMeta.webApp": "Manage WebApp access",+ "overview.accessStatus": "Access",+ "overview.api": "API Tokens",+ "overview.apiKeysCount_one": "{{count}} API Token",+ "overview.apiKeysCount_other": "{{count}} API Tokens",+ "overview.apiTokenSummary.environments_one": "{{count}} deployed environment",+ "overview.apiTokenSummary.environments_other": "{{count}} deployed environments",+ "overview.availableForDeployment": "Available for deployment",+ "overview.basicInfo": "Basic info",+ "overview.cardAction.deployLatest": "Deploy Latest Release",+ "overview.cardAction.redeploy": "Redeploy",+ "overview.cardAction.viewProgress": "View deployment",+ "overview.chip.behindTooltip_one": "1 release behind latest. Deploy the latest release to update.",+ "overview.chip.behindTooltip_other": "{{count}} releases behind latest. Deploy the latest release to update.",+ "overview.chip.behind_one": "↑ 1",+ "overview.chip.behind_other": "↑ {{count}}",+ "overview.chip.deploying": "deploying",+ "overview.chip.deployingTooltip": "Deployment is in progress.",+ "overview.chip.empty": "empty",+ "overview.chip.emptyTooltip": "No release is deployed to this environment.",+ "overview.chip.failed": "failed",+ "overview.chip.failedTooltip": "The latest deployment attempt failed.",+ "overview.chip.latest": "latest",+ "overview.chip.latestTooltip": "This environment is running the latest release.",+ "overview.chip.needsReleaseFirst": "Create a Release first",+ "overview.chip.olderRelease": "older",+ "overview.chip.olderReleaseTooltip": "This environment is running an older release.",+ "overview.chip.openInDeployTab": "View deployment progress",+ "overview.cli": "CLI",+ "overview.configured": "Configured",+ "overview.createRelease": "Create Release",+ "overview.created": "Created",+ "overview.deploy": "Deploy",+ "overview.deployedEnvironments": "deployed",+ "overview.deploymentOverview": "Deployment overview",+ "overview.deploymentStatus": "Deployment status",+ "overview.description": "Description",+ "overview.developerApi": "Developer API",+ "overview.disabled": "Disabled",+ "overview.emptyValue": "Not set",+ "overview.enabled": "Enabled",+ "overview.enabledChannels": "access enabled",+ "overview.endUserAccess": "End-user access",+ "overview.environments": "Environments",+ "overview.hero.byName": "by {{name}}",+ "overview.hero.empty": "No releases yet",+ "overview.hero.emptyDescription": "Create a release from the current source before deploying.",+ "overview.hero.propagation_one": "deployed to {{count}}/{{total}} environment",+ "overview.hero.propagation_other": "deployed to {{count}}/{{total}} environments",+ "overview.hero.untargeted": "no environments configured yet",+ "overview.instanceDetails": "Deployment details",+ "overview.instanceId": "Deployment ID",+ "overview.latestRelease.releaseCount_one": "{{count}} release",+ "overview.latestRelease.releaseCount_other": "{{count}} releases",+ "overview.latestReleaseTitle": "Latest Release",+ "overview.manageDeployments": "Manage deployments",+ "overview.name": "Name",+ "overview.noAccessConfig": "No access configuration.",+ "overview.noReleaseYet": "Create a release before deploying to an environment.",+ "overview.notConfigured": "Not configured",+ "overview.previousReleases.empty": "No earlier releases yet.",+ "overview.previousReleases.retired": "Not currently deployed",+ "overview.previousReleases.title": "Previous releases",+ "overview.previousReleases.viewAll": "View All",+ "overview.ready": "Deployable",+ "overview.recentReleases": "Recent releases",+ "overview.releaseDeployedTitle": "{{release}} is deployed",+ "overview.releaseReadyTitle": "{{release}} is ready to deploy",+ "overview.serviceMap": "Service map",+ "overview.servingRelease": "Serving {{release}}",+ "overview.servingReleaseDescription": "This deployment is deployed to {{count}}/{{total}} environments.",+ "overview.strip.deployToNewEnvironment": "Deploy to new environment",+ "overview.strip.empty": "No environments configured.",+ "overview.strip.emptyDeployableDescription": "Deploy the latest release to an environment when you're ready.",+ "overview.strip.emptyDeployed": "No instances yet.",+ "overview.strip.emptyDescription": "Create a release before deploying to an environment.",+ "overview.strip.emptyTitle": "No instances yet",+ "overview.strip.summary_one": "1 of {{total}} on latest release",+ "overview.strip.summary_other": "{{count}} of {{total}} on latest release",+ "overview.strip.title": "Instances",+ "overview.switchSourceApp": "Switch source",+ "overview.switchSourceAppDescription": "Choose the Workflow App used as the source for future releases.",+ "overview.switchSourceAppHint": "After switching, only newly created releases use the new source. Historical releases and existing deployments are not changed.",+ "overview.targetRelease": "Target Release",+ "overview.webapp": "WebApp",+ "settings.danger": "Danger zone",+ "settings.dangerDesc": "Permanently delete this deployment and stop any running instances. This can't be undone.",+ "settings.delete": "Delete Deployment",+ "settings.deleteConfirmDesc": "Delete {{name}}? Every instance will stop running and be removed across all environments. This can't be undone.",+ "settings.deleteConfirmTitle": "Delete deployment",+ "settings.deleteFailed": "Failed to delete deployment.",+ "settings.deleteImpact": "Impact",+ "settings.deleteImpactInstance": "Deployment",+ "settings.deleteImpactTitle": "Affected deployment",+ "settings.deleteImpactValue": "The deployment is removed from the deployment list.",+ "settings.deleted": "Deployment deleted",+ "settings.description": "Description",+ "settings.descriptionHelp": "Manage this deployment's name, description, and other settings.",+ "settings.general": "General",+ "settings.name": "Deployment name",+ "settings.reset": "Reset",+ "settings.save": "Save Changes",+ "settings.updateFailed": "Failed to update deployment.",+ "settings.updated": "Deployment updated",+ "status.RUNTIME_INSTANCE_STATUS_DEPLOYING": "Deploying",+ "status.RUNTIME_INSTANCE_STATUS_DRIFTED": "Sync pending",+ "status.RUNTIME_INSTANCE_STATUS_FAILED": "Deploy failed",+ "status.RUNTIME_INSTANCE_STATUS_INVALID": "Invalid",+ "status.RUNTIME_INSTANCE_STATUS_READY": "Running",+ "status.RUNTIME_INSTANCE_STATUS_UNDEPLOYED": "Not deployed",+ "status.RUNTIME_INSTANCE_STATUS_UNDEPLOYING": "Undeploying",+ "status.RUNTIME_INSTANCE_STATUS_UNSPECIFIED": "Unknown",+ "subtitle": "Manage deployments across environments.",+ "tabs.access.description": "Manage access channels and access permissions.",+ "tabs.access.name": "Access",+ "tabs.api-tokens.description": "Manage API Tokens and invoke instances over HTTP.",+ "tabs.api-tokens.name": "API Tokens",+ "tabs.instances.description": "View and manage instances in deployed environments.",+ "tabs.instances.name": "Instances",+ "tabs.overview.description": "See the deployment's status across environments.",+ "tabs.overview.name": "Overview",+ "tabs.releases.description": "Create, deploy, and manage releases.",+ "tabs.releases.name": "Releases",+ "tabs.settings.description": "Manage this deployment's name, description, and other settings.",+ "tabs.settings.name": "Settings",+ "title": "Deployments",+ "unsupportedDslNodes.description": "This release contains nodes that the deployment runtime does not support yet. Remove or replace them in Studio, then try again.",+ "unsupportedDslNodes.descriptionWithTypes": "This release contains nodes that the deployment runtime does not support yet: {{nodeTypes}}. Remove or replace them in Studio, then try again.",+ "unsupportedDslNodes.title": "Unsupported nodes",+ "unsupportedDslNodes.unknownType": "Unknown type",+ "versions.cancelCreate": "Cancel",+ "versions.cancelDelete": "Cancel",+ "versions.cancelEdit": "Cancel",+ "versions.checkingReleaseContent": "Checking release content...",+ "versions.col.action": "Action",+ "versions.col.author": "Created by",+ "versions.col.commit": "Commit",+ "versions.col.createdAt": "Created at",+ "versions.col.deployedTo": "Deployed to",+ "versions.col.release": "Release",+ "versions.col.sourceApp": "Source",+ "versions.commitTooltip": "Commit {{commit}}",+ "versions.create": "Create",+ "versions.createFailed": "Failed to create release.",+ "versions.createRelease": "Create Release",+ "versions.createReleaseDescription": "Create a deployable release from a Workflow App or Workflow DSL file.",+ "versions.createReleaseHint": "New releases can be deployed to any environment.",+ "versions.createSuccess": "Release \"{{name}}\" created.",+ "versions.creating": "Creating...",+ "versions.currentOn": "Current Release on {{name}}",+ "versions.deleteConfirmDesc": "Release \"{{name}}\" will be permanently deleted. This can't be undone.",+ "versions.deleteConfirmTitle": "Delete release?",+ "versions.deleteFailed": "Failed to delete release.",+ "versions.deleteImpactDeployment": "Deployment status",+ "versions.deleteImpactNotDeployed": "Not currently deployed",+ "versions.deleteImpactRelease": "Release",+ "versions.deleteImpactTitle": "Delete impact",+ "versions.deleteRelease": "Delete Release",+ "versions.deleteSuccess": "Release \"{{name}}\" deleted.",+ "versions.deploy": "Deploy",+ "versions.deployTo": "Deploy to {{name}}",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING": "Deploying",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_DRIFTED": "Sync pending",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_FAILED": "Failed",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_INVALID": "Invalid",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_READY": "Running",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED": "Not deployed",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING": "Undeploying",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED": "Unknown",+ "versions.deployingTo": "{{name}} is deploying",+ "versions.disabledReason.checkDeploymentsFailed": "Could not verify deployment usage. Try again later.",+ "versions.disabledReason.checkingDeployments": "Checking deployment usage",+ "versions.disabledReason.current": "This release is already running on {{name}}",+ "versions.disabledReason.deploying": "Wait for the active deployment to finish",+ "versions.disabledReason.envDisabled": "This environment isn't deployable",+ "versions.disabledReason.releaseInUse_one": "Undeploy this release from {{count}} environment before deleting it",+ "versions.disabledReason.releaseInUse_other": "Undeploy this release from {{count}} environments before deleting it",+ "versions.dslReadFailed": "Failed to read the DSL file. Choose another file and try again.",+ "versions.dslReading": "Reading DSL file...",+ "versions.dslUnsupportedMode": "Only Workflow DSL files can be used for deployments.",+ "versions.editFailed": "Failed to update release.",+ "versions.editRelease": "Edit Release",+ "versions.editReleaseDescription": "Update this release's name and description.",+ "versions.editSuccess": "Release \"{{name}}\" updated.",+ "versions.empty": "No releases available yet.",+ "versions.emptyDescription": "Create the first release before deploying to an environment.",+ "versions.emptyTitle": "No releases yet",+ "versions.emptyWithCreate": "No releases yet. Create the first deployable release before deploying.",+ "versions.exportDsl": "Export DSL",+ "versions.exportDslFailed": "Failed to export DSL.",+ "versions.exportingDsl": "Exporting...",+ "versions.groupHeader.deploy": "Deploy",+ "versions.groupHeader.promote": "Deploy",+ "versions.groupHeader.rollback": "Deploy previous version",+ "versions.groupHeader.unavailable": "Unavailable",+ "versions.manualDslOption": "Upload DSL",+ "versions.moreActions": "More actions",+ "versions.optional": "Optional",+ "versions.promote": "Deploy",+ "versions.promoteTo": "Deploy to {{name}}",+ "versions.releaseAlreadyExists": "A release with the same content already exists: {{name}}.",+ "versions.releaseContentCheckFailed": "Failed to check release content.",+ "versions.releaseDescriptionLabel": "Description",+ "versions.releaseDescriptionPlaceholder": "Describe this release",+ "versions.releaseHistory": "Release history",+ "versions.releaseNameLabel": "Release Name",+ "versions.releaseNamePlaceholder": "Release Name",+ "versions.releaseNameRequired": "Enter a release name.",+ "versions.releaseSourceLabel": "Release Source",+ "versions.rollbackTo": "Deploy to {{name}}",+ "versions.saveEdit": "Save",+ "versions.sourceAppOption": "Workflow App"+}diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.jsonindex 7bd28568e04..d0fbf61e154 100644--- a/web/i18n/zh-Hans/common.json+++ b/web/i18n/zh-Hans/common.json@@ -311,6 +311,7 @@"menus.apps": "工作室","menus.datasets": "知识库","menus.datasetsTips": "即将到来:上传自己的长文本数据,或通过 Webhook 集成自己的数据源",+ "menus.deployments": "部署","menus.explore": "探索","menus.exploreMarketplace": "探索 Marketplace","menus.newApp": "创建应用",diff --git a/web/i18n/zh-Hans/deployments.json b/web/i18n/zh-Hans/deployments.jsonnew file mode 100644index 00000000000..9d80044e6f8--- /dev/null+++ b/web/i18n/zh-Hans/deployments.json@@ -0,0 +1,623 @@+{+ "access.api.backendTitle": "后端服务 API",+ "access.api.copyCurlExample": "复制 cURL 示例",+ "access.api.createFailed": "生成 API 令牌失败。",+ "access.api.createKey": "生成 API 令牌",+ "access.api.createKeyTitle": "生成新 API 令牌",+ "access.api.curlExampleTitle": "cURL 示例",+ "access.api.description": "通过 HTTP 调用该部署。每个 API 令牌仅在一个环境中生效。",+ "access.api.developerTitle": "开发者 API",+ "access.api.disabled": "该部署的 API 接入已关闭。",+ "access.api.disabledHint": "开启 API 接入后即可生成绑定环境的令牌。",+ "access.api.dismissToken": "关闭 API 令牌",+ "access.api.docs": "API 文档",+ "access.api.docsClose": "关闭 API 文档",+ "access.api.docsDescription": "查看该部署的工作流 API 参考。",+ "access.api.docsTitle": "工作流 API 文档",+ "access.api.empty": "请先部署到环境后再签发 API 令牌。",+ "access.api.emptyTitle": "暂无已部署环境",+ "access.api.endpoint": "请求地址",+ "access.api.envPrefix": "env:{{env}}",+ "access.api.keyList": "API 令牌列表",+ "access.api.nameLabel": "API 令牌名称",+ "access.api.namePlaceholder": "输入 API 令牌名称",+ "access.api.nameRequired": "请输入 API 令牌名称。",+ "access.api.newKey": "生成新 API 令牌",+ "access.api.newTokenDescription": "该明文 API 令牌仅本次显示,请在离开页面前复制保存。",+ "access.api.newTokenLabel": "API 令牌",+ "access.api.newTokenTitle": "API 令牌已生成",+ "access.api.noKeys": "尚无 API 令牌,生成一个即可调用 API。",+ "access.api.noKeysTitle": "暂无 API 令牌",+ "access.api.revokeConfirmDescription": "API 令牌「{{name}}」将立即失效,此操作无法撤销。",+ "access.api.revokeConfirmTitle": "撤销 API 令牌?",+ "access.api.revokeFailed": "撤销 API 令牌失败。",+ "access.api.revokeSuccess": "API 令牌已撤销",+ "access.api.table.action": "操作",+ "access.api.table.environment": "环境",+ "access.api.table.key": "API 令牌",+ "access.api.table.name": "名称",+ "access.api.title": "API",+ "access.channels.col.channel": "渠道",+ "access.channels.col.endpoint": "入口",+ "access.channels.col.status": "状态",+ "access.channels.description": "WebApp 与 CLI 入口遵循上方访问权限。",+ "access.channels.disabled": "该部署的接入渠道已关闭。",+ "access.channels.disabledHint": "开启接入渠道后即可开放 WebApp 和 CLI 入口。",+ "access.channels.followPermission": "随权限开放",+ "access.channels.title": "接入渠道",+ "access.cli.description": "通过 difyctl 在终端中调用,适合脚本、自动化流程或 Agent 集成",+ "access.cli.docs": "使用说明",+ "access.cli.domain": "域名",+ "access.cli.empty": "尚未配置 CLI 接入地址。",+ "access.cli.install": "安装 CLI",+ "access.cli.title": "CLI",+ "access.copied": "已复制",+ "access.copy": "复制",+ "access.copyFailed": "复制失败",+ "access.copyToast": "已复制到剪贴板",+ "access.hide": "隐藏",+ "access.members.clearAll": "全部清除",+ "access.members.empty": "未找到匹配结果。",+ "access.members.groupCount_one": "{{count}} 个分组",+ "access.members.groupCount_other": "{{count}} 个分组",+ "access.members.groups": "分组",+ "access.members.individuals": "成员",+ "access.members.memberCount_one": "{{count}} 位成员",+ "access.members.memberCount_other": "{{count}} 位成员",+ "access.members.pickPlaceholder": "选择分组或成员",+ "access.members.searchPlaceholder": "搜索分组和成员",+ "access.members.selectedLabel": "已选择",+ "access.permission.anyone": "任何人",+ "access.permission.anyoneDesc": "任何人均可访问该部署,无需登录",+ "access.permission.memberCount_one": "{{count}} 位成员",+ "access.permission.memberCount_other": "{{count}} 位成员",+ "access.permission.organization": "平台内所有成员",+ "access.permission.organizationDesc": "平台内所有成员",+ "access.permission.specific": "平台内指定成员",+ "access.permission.specificDesc": "选择指定的分组或成员",+ "access.permission.specificUnavailable": "特定成员暂未启用,需接入真实平台成员与分组后再开放。",+ "access.permission.updateFailed": "更新访问策略失败。",+ "access.permissions.col.environment": "环境",+ "access.permissions.col.permission": "访问范围",+ "access.permissions.description": "设置 WebApp 与 CLI 入口在每个环境中的访问权限。",+ "access.permissions.editAriaLabel": "配置 {{environment}} 的访问权限",+ "access.permissions.editDescription": "设置 WebApp 与 CLI 入口的访问权限。",+ "access.permissions.editTitle": "访问权限",+ "access.permissions.title": "访问权限",+ "access.revoke": "撤销",+ "access.runAccess.description": "管理用户如何运行该部署,以及在每个环境里谁可以访问。",+ "access.runAccess.disabled": "该部署的接入已关闭。",+ "access.runAccess.mcp": "MCP",+ "access.runAccess.mcpDesc": "将此部署作为 Model Context Protocol 服务器对外提供。",+ "access.runAccess.mcpEmpty": "尚未配置 MCP 端点。",+ "access.runAccess.noEnvs": "请先部署到环境后再配置访问权限。",+ "access.runAccess.noEnvsTitle": "暂无已部署环境",+ "access.runAccess.openWebapp": "打开 WebApp",+ "access.runAccess.permissions": "访问权限",+ "access.runAccess.permissionsDesc": "每个环境里可以访问该部署的人员。",+ "access.runAccess.title": "运行访问",+ "access.runAccess.urlLabel": "访问地址",+ "access.runAccess.webapp": "WebApp",+ "access.runAccess.webappDesc": "面向终端用户的托管 Web 页面。",+ "access.runAccess.webappEmpty": "即将支持。",+ "access.show": "显示",+ "backend.RUNTIME_BACKEND_EXTERNAL": "外部",+ "backend.RUNTIME_BACKEND_K8S": "K8S",+ "backend.RUNTIME_BACKEND_UNSPECIFIED": "未知",+ "card.access.api": "API 令牌",+ "card.access.apiShort": "API",+ "card.access.cli": "CLI",+ "card.access.cliShort": "CLI",+ "card.access.none": "未开启接入",+ "card.access.webApp": "WebApp",+ "card.access.webAppShort": "Web",+ "card.createFirstRelease": "创建首个版本",+ "card.deploy": "部署",+ "card.deploying": "{{count}} 个部署中",+ "card.envOverflow": "+ {{count}}",+ "card.failed": "{{count}} 个失败",+ "card.fromApp": "来自 {{name}}",+ "card.lastDeployed": "上次部署于 {{time}}",+ "card.menu.delete": "删除部署",+ "card.menu.deleteDisabled": "后端托管的部署暂不支持删除。",+ "card.menu.deploy": "部署到环境",+ "card.menu.editInfo": "编辑信息",+ "card.menu.viewDetail": "查看部署详情",+ "card.moreActions": "更多操作",+ "card.neverDeployed": "尚未部署",+ "card.noDescription": "暂无描述",+ "card.notDeployed": "未部署",+ "card.ready": "{{count}} 个运行中",+ "card.tooltip.createdAt": "创建时间",+ "card.tooltip.deployed": "已部署",+ "card.tooltip.deploymentStatus": "部署状态",+ "card.tooltip.notDeployed": "该部署尚未部署到任何环境。",+ "card.tooltip.notDeployedShort": "未部署",+ "card.tooltip.release": "版本",+ "card.tooltip.releaseName": "版本名称",+ "card.tooltip.source": "来源",+ "common.loadFailed": "加载失败,请稍后再试。",+ "common.loading": "加载中…",+ "createGuide.actions.back": "返回",+ "createGuide.actions.cancel": "取消",+ "createGuide.actions.continue": "继续",+ "createGuide.actions.createAndDeploy": "创建并部署",+ "createGuide.actions.creating": "创建中…",+ "createGuide.actions.deploy": "部署",+ "createGuide.actions.deploying": "创建并部署中…",+ "createGuide.actions.next": "下一步",+ "createGuide.actions.skipDeploy": "跳过,稍后部署",+ "createGuide.description": "通过版本来源、基本信息和目标环境新建部署。",+ "createGuide.dsl.defaultAppName": "导入的 DSL 应用",+ "createGuide.dsl.description": "上传工作流 DSL 包来新建部署、首个版本,并可部署到环境。",+ "createGuide.dsl.dropDescription": "上传工作流 YAML DSL 包。部署前会根据该文件解析部署选项。",+ "createGuide.dsl.dropTitle": "上传工作流 DSL 包",+ "createGuide.dsl.readFailed": "读取 DSL 文件失败。请选择其他文件后重试。",+ "createGuide.dsl.reading": "正在读取 DSL 文件…",+ "createGuide.dsl.title": "导入 DSL",+ "createGuide.dsl.unsupportedMode": "仅支持使用工作流 DSL 新建部署。",+ "createGuide.errors.createReleaseFailed": "新建部署或版本失败。",+ "createGuide.errors.deployFailed": "部署到环境失败。",+ "createGuide.method.description": "选择用于生成首个版本的来源。",+ "createGuide.methods.bindApp.description": "使用 Studio 中已有的工作流应用作为版本来源。",+ "createGuide.methods.bindApp.title": "绑定已有工作流应用",+ "createGuide.methods.importDsl.description": "上传工作流 YAML DSL 包,并继续完成部署配置。",+ "createGuide.methods.importDsl.title": "导入 DSL",+ "createGuide.methods.mocked": "模拟",+ "createGuide.nav.back": "部署",+ "createGuide.release.defaultName": "初始版本",+ "createGuide.release.deployInfo": "部署信息",+ "createGuide.release.description": "填写部署信息和首个版本信息。",+ "createGuide.release.firstVersion": "首个版本",+ "createGuide.release.instanceDescription": "部署描述",+ "createGuide.release.instanceDescriptionPlaceholder": "描述该部署的用途",+ "createGuide.release.instanceName": "部署名称",+ "createGuide.release.instanceNameConflict": "该部署名称已存在,请换一个名称。",+ "createGuide.release.releaseDescription": "版本描述",+ "createGuide.release.releaseDescriptionPlaceholder": "描述这个版本",+ "createGuide.release.releaseName": "版本名称",+ "createGuide.release.releaseNote": "版本描述",+ "createGuide.release.title": "基本信息",+ "createGuide.source.availableApps_one": "{{count}} 个应用",+ "createGuide.source.availableApps_other": "{{count}} 个应用",+ "createGuide.source.clearSearch": "清空应用搜索",+ "createGuide.source.description": "选择用于生成首个版本的来源。",+ "createGuide.source.empty": "未找到工作流应用。",+ "createGuide.source.searchPlaceholder": "搜索应用",+ "createGuide.source.sourceApp": "工作流应用",+ "createGuide.source.title": "版本来源",+ "createGuide.steps.method": "版本来源",+ "createGuide.steps.release": "基本信息",+ "createGuide.steps.source": "版本来源",+ "createGuide.steps.target": "部署到环境",+ "createGuide.target.bindingCount_one": "{{count}} 项",+ "createGuide.target.bindingCount_other": "{{count}} 项",+ "createGuide.target.bindingHint": "选择该版本使用的凭据。",+ "createGuide.target.bindings": "凭据",+ "createGuide.target.deferredBindingHint": "凭据会在最终部署时根据真实部署计划解析。",+ "createGuide.target.deferredEnvironmentHint": "新建部署和版本后,会根据真实环境进行匹配。",+ "createGuide.target.description": "选择目标环境,并提供此版本在该环境中所需的运行时设置。此步骤可跳过。",+ "createGuide.target.envVarCount_one": "{{count}} 项",+ "createGuide.target.envVarCount_other": "{{count}} 项",+ "createGuide.target.envVarHint": "为该版本需要的每个环境变量输入自定义值,或使用应用中定义的值。",+ "createGuide.target.envVarPlaceholder": "输入变量值",+ "createGuide.target.envVarSource.ariaLabel": "选择 {{key}} 的变量值来源",+ "createGuide.target.envVarSource.default": "应用中的值",+ "createGuide.target.envVarSource.lastDeployment": "上次部署值",+ "createGuide.target.envVarSource.literal": "自定义值",+ "createGuide.target.envVarType.number": "数字",+ "createGuide.target.envVarType.secret": "密钥",+ "createGuide.target.envVarType.string": "字符串",+ "createGuide.target.envVars": "环境变量",+ "createGuide.target.environment": "目标环境",+ "createGuide.target.environmentName": "环境名称",+ "createGuide.target.environmentNamePlaceholder": "生产环境",+ "createGuide.target.loadBindingsFailed": "加载凭据失败。",+ "createGuide.target.loadEnvironmentsFailed": "加载部署环境失败。",+ "createGuide.target.missingRequiredBinding": "请选择该必填绑定使用的凭据。",+ "createGuide.target.noBindingRequired": "无需凭据。",+ "createGuide.target.noCredentialCandidates": "没有可用凭据。",+ "createGuide.target.noEnvironmentOptions": "没有可用部署环境。",+ "createGuide.target.required": "必填",+ "createGuide.target.selectCredential": "选择凭据",+ "createGuide.target.title": "部署到环境",+ "createGuide.title": "新建部署",+ "createModal.appPickerPlaceholder": "选择工作流应用",+ "createModal.appSearchEmpty": "没有匹配的工作流应用",+ "createModal.appSearchPlaceholder": "搜索工作流应用…",+ "createModal.cancel": "取消",+ "createModal.create": "创建",+ "createModal.createFailed": "新建部署失败。",+ "createModal.description": "从 Studio 选择一个工作流应用并新建部署。",+ "createModal.descriptionLabel": "描述",+ "createModal.descriptionPlaceholder": "描述该部署的用途",+ "createModal.loadMoreApps": "加载更多应用",+ "createModal.loadingApps": "正在加载应用…",+ "createModal.nameLabel": "部署名称",+ "createModal.namePlaceholder": "部署名称",+ "createModal.noApps": "当前工作区还没有工作流应用,请先在 Studio 创建一个。",+ "createModal.selected": "已选择",+ "createModal.sourceApp": "工作流应用(必选)",+ "createModal.title": "新建部署",+ "deployDrawer.bindingCount_one": "{{count}} 项",+ "deployDrawer.bindingCount_other": "{{count}} 项",+ "deployDrawer.bindingOptionsFailed": "加载凭据选项失败。",+ "deployDrawer.bindingSelectionHint": "选择本次部署要使用的凭据。",+ "deployDrawer.bindingsDisabled": "来自版本预览的解析结果,暂不支持在这里编辑。",+ "deployDrawer.cancel": "取消",+ "deployDrawer.close": "关闭部署抽屉",+ "deployDrawer.defaultSelect": "选择…",+ "deployDrawer.deploy": "部署到环境",+ "deployDrawer.deployExistingRelease": "部署到环境",+ "deployDrawer.deployExistingReleaseDescription": "选择版本和目标环境,完成部署。",+ "deployDrawer.deployExistingReleaseTitle": "部署到环境",+ "deployDrawer.deployFailed": "启动部署失败。",+ "deployDrawer.deploying": "部署中…",+ "deployDrawer.description": "选择版本和目标环境,完成部署。",+ "deployDrawer.envVarCount_one": "{{count}} 项",+ "deployDrawer.envVarCount_other": "{{count}} 项",+ "deployDrawer.envVarHint": "为该版本需要的每个环境变量输入自定义值,或使用应用中定义的值。",+ "deployDrawer.envVarPlaceholder": "输入变量值",+ "deployDrawer.envVarSource.ariaLabel": "选择 {{key}} 的变量值来源",+ "deployDrawer.envVarSource.default": "应用中的值",+ "deployDrawer.envVarSource.lastDeployment": "上次部署值",+ "deployDrawer.envVarSource.literal": "自定义值",+ "deployDrawer.envVarType.number": "数字",+ "deployDrawer.envVarType.secret": "密钥",+ "deployDrawer.envVarType.string": "字符串",+ "deployDrawer.envVars": "环境变量",+ "deployDrawer.existingReleaseHint": "将直接部署该版本,不会创建新版本。",+ "deployDrawer.loadingBindings": "解析中…",+ "deployDrawer.lockedHint": "已锁定至当前环境",+ "deployDrawer.missingRequiredBinding": "请选择该必填绑定使用的凭据。",+ "deployDrawer.missingRequiredEnvVar": "请填写该必填环境变量。",+ "deployDrawer.modelCreds": "模型凭据",+ "deployDrawer.needsValidation": "(待验证)",+ "deployDrawer.newReleaseHint": "将基于所选工作流应用 YAML 创建一个新版本。",+ "deployDrawer.noBindingRequired": "无需配置",+ "deployDrawer.noCredentialCandidates": "没有可用凭据。",+ "deployDrawer.noNewEnvironmentAvailable": "所有可用环境都已有部署。",+ "deployDrawer.noOtherReleaseAvailable": "此环境没有其他可用版本。",+ "deployDrawer.noReleaseAvailable": "请先创建版本,再部署到环境。",+ "deployDrawer.notFound": "未找到部署。",+ "deployDrawer.noteLabel": "版本描述(可选)",+ "deployDrawer.notePlaceholder": "例如:优化引导文案",+ "deployDrawer.pluginCreds": "插件凭据",+ "deployDrawer.promote": "部署",+ "deployDrawer.promoteDescription": "选择版本和目标环境,完成部署。",+ "deployDrawer.promoteTitle": "部署到环境",+ "deployDrawer.readOnly": "只读",+ "deployDrawer.redeploy": "部署到环境",+ "deployDrawer.redeployDescription": "选择版本和目标环境,完成部署。",+ "deployDrawer.redeployExistingReleaseHint": "将重新部署当前版本,不会创建新版本。",+ "deployDrawer.redeployTitle": "部署到环境",+ "deployDrawer.releaseLabel": "版本",+ "deployDrawer.requiredBinding": "必填",+ "deployDrawer.rollback": "部署",+ "deployDrawer.rollbackDescription": "选择版本和目标环境,完成部署。",+ "deployDrawer.rollbackTitle": "部署到环境",+ "deployDrawer.runtimeCredentials": "凭据",+ "deployDrawer.secretPlaceholder": "机密值",+ "deployDrawer.selectCredential": "选择凭据",+ "deployDrawer.selectEnv": "选择一个环境",+ "deployDrawer.selectProviderCred": "选择 {{provider}} 凭据",+ "deployDrawer.selectProviderKey": "选择 {{provider}} 密钥",+ "deployDrawer.selectRelease": "选择一个版本",+ "deployDrawer.targetEnv": "目标环境",+ "deployDrawer.title": "部署到环境",+ "deployDrawer.valuePlaceholder": "值",+ "deployTab.cancelDeployment": "取消部署",+ "deployTab.closeError": "关闭",+ "deployTab.col.actions": "操作",+ "deployTab.col.currentRelease": "当前版本",+ "deployTab.col.environment": "环境",+ "deployTab.col.status": "状态",+ "deployTab.col.updated": "更新时间",+ "deployTab.collapseDetails": "收起部署详情",+ "deployTab.confirmUndeploy": "下线",+ "deployTab.deployOtherVersion": "部署其他版本",+ "deployTab.deployToEnv": "部署到 {{name}}",+ "deployTab.deployToNewEnv": "部署到新环境…",+ "deployTab.empty": "暂无实例。部署到新环境后即可开始使用。",+ "deployTab.emptyDescription": "选择版本和目标环境,让该部署可以被用户访问。",+ "deployTab.emptyTitle": "暂无运行中的环境",+ "deployTab.envCount": "环境",+ "deployTab.errorCode": "代码",+ "deployTab.errorDialogDesc": "重试或部署其他版本前,先查看上一次失败的部署原因。",+ "deployTab.errorDialogTitle": "{{name}} 的部署错误",+ "deployTab.errorMessage": "消息",+ "deployTab.errorPhase": "阶段",+ "deployTab.expandDetails": "展开部署详情",+ "deployTab.moreActions": "更多操作",+ "deployTab.newDeployment": "部署到新环境",+ "deployTab.panel.commit": "Commit ID",+ "deployTab.panel.deploymentId": "部署 ID",+ "deployTab.panel.endpoints": "端点",+ "deployTab.panel.envVars": "环境变量",+ "deployTab.panel.error": "错误",+ "deployTab.panel.failedRelease": "失败版本",+ "deployTab.panel.health": "健康检查",+ "deployTab.panel.instanceInfo": "实例信息",+ "deployTab.panel.modelCreds": "模型凭据",+ "deployTab.panel.pluginCreds": "插件凭据",+ "deployTab.panel.release": "版本",+ "deployTab.panel.releaseCreatedAt": "版本创建时间",+ "deployTab.panel.releaseInfo": "版本信息",+ "deployTab.panel.replicas": "副本数",+ "deployTab.panel.run": "运行",+ "deployTab.panel.runtimeBindings": "凭据",+ "deployTab.panel.runtimeInfo": "运行信息",+ "deployTab.panel.runtimeMode": "运行模式",+ "deployTab.panel.runtimeNote": "运行备注",+ "deployTab.panel.targetRelease": "目标版本",+ "deployTab.panel.unknownError": "部署失败。",+ "deployTab.promote": "部署",+ "deployTab.redeploy": "重新部署",+ "deployTab.releaseCreatedAt": "版本创建于 {{time}}",+ "deployTab.retry": "重试",+ "deployTab.shortcut": "快捷",+ "deployTab.status.deployFailed": "部署失败",+ "deployTab.status.deployingRelease": "部署中({{release}})",+ "deployTab.status.runningOutOfSync": "运行中(待同步)",+ "deployTab.status.runningWithFailed": "运行中(上次部署失败)",+ "deployTab.undeploy": "下线",+ "deployTab.undeployConfirmDesc": "用户访问将立即停止。该版本之后仍可重新部署。",+ "deployTab.undeployConfirmTitle": "从 {{name}} 下线?",+ "deployTab.undeployFrom": "从 {{name}} 下线",+ "deployTab.undeployImpactTitle": "受影响的实例",+ "deployTab.viewError": "查看错误",+ "deployTab.viewLogs": "查看日志",+ "deployTab.viewProgress": "查看进度",+ "detail.backToInstances": "返回部署",+ "detail.deployingCount": "{{count}} 个部署中",+ "detail.envCount_one": "{{count}} 个环境",+ "detail.envCount_other": "{{count}} 个环境",+ "detail.failedCount": "{{count}} 个失败",+ "detail.mobileTabs": "部署页面",+ "detail.notFound": "未找到部署",+ "detail.openSourceApp": "打开来源 {{name}}",+ "detail.sourceApp": "来源",+ "detail.sourceAppLink": "来源",+ "documentTitle.create": "新建部署 · 部署",+ "documentTitle.detail": "部署 · 部署",+ "documentTitle.list": "部署",+ "filter.allEnvs": "全部环境",+ "filter.notDeployed": "未部署",+ "filter.searchPlaceholder": "搜索部署",+ "health.ENVIRONMENT_STATUS_ADMISSION": "准入中",+ "health.ENVIRONMENT_STATUS_BOOTSTRAPPING": "启动中",+ "health.ENVIRONMENT_STATUS_DELETING": "删除中",+ "health.ENVIRONMENT_STATUS_FAILED": "不可用",+ "health.ENVIRONMENT_STATUS_READY": "可用",+ "health.ENVIRONMENT_STATUS_UNSPECIFIED": "未知",+ "list.clearFilters": "清空筛选",+ "list.clearSearch": "清空部署搜索",+ "list.createDeployment": "新建",+ "list.empty": "未找到部署。",+ "list.emptyDescription": "从工作流应用或工作流 DSL 包新建部署后,即可管理版本、环境和访问方式。",+ "list.emptyFilteredDescription": "当前搜索或环境筛选下没有匹配的部署。",+ "list.emptyFilteredTitle": "没有匹配的部署",+ "list.emptyTitle": "暂无部署",+ "mode.ENVIRONMENT_MODE_ISOLATED": "独立",+ "mode.ENVIRONMENT_MODE_SHARED": "共享",+ "mode.ENVIRONMENT_MODE_UNSPECIFIED": "未知",+ "newInstance.comingSoon": "即将支持",+ "newInstance.fromStudio": "从 Studio 选择",+ "newInstance.importDSL": "导入 DSL",+ "newInstance.title": "新建部署",+ "overview.accessEndpoints": "接入端点",+ "overview.accessMeta.apiTokens": "管理 API 访问令牌",+ "overview.accessMeta.cli": "查看 CLI 接入方式",+ "overview.accessMeta.webApp": "管理 WebApp 接入",+ "overview.accessStatus": "接入方式",+ "overview.api": "API 令牌",+ "overview.apiKeysCount_one": "{{count}} 个 API 令牌",+ "overview.apiKeysCount_other": "{{count}} 个 API 令牌",+ "overview.apiTokenSummary.environments_one": "{{count}} 个已部署环境",+ "overview.apiTokenSummary.environments_other": "{{count}} 个已部署环境",+ "overview.availableForDeployment": "可部署",+ "overview.basicInfo": "基本信息",+ "overview.cardAction.deployLatest": "部署最新版本",+ "overview.cardAction.redeploy": "重新部署",+ "overview.cardAction.viewProgress": "查看部署",+ "overview.chip.behindTooltip_one": "落后最新版本 1 个,可部署最新版本更新。",+ "overview.chip.behindTooltip_other": "落后最新版本 {{count}} 个,可部署最新版本更新。",+ "overview.chip.behind_one": "↑ 1",+ "overview.chip.behind_other": "↑ {{count}}",+ "overview.chip.deploying": "部署中",+ "overview.chip.deployingTooltip": "部署正在进行中。",+ "overview.chip.empty": "空",+ "overview.chip.emptyTooltip": "此环境尚未部署任何版本。",+ "overview.chip.failed": "失败",+ "overview.chip.failedTooltip": "最近一次部署失败。",+ "overview.chip.latest": "最新",+ "overview.chip.latestTooltip": "此环境正在运行最新版本。",+ "overview.chip.needsReleaseFirst": "请先创建版本",+ "overview.chip.olderRelease": "较旧",+ "overview.chip.olderReleaseTooltip": "此环境正在运行较早的版本。",+ "overview.chip.openInDeployTab": "查看部署进度",+ "overview.cli": "CLI",+ "overview.configured": "已配置",+ "overview.createRelease": "创建版本",+ "overview.created": "创建时间",+ "overview.deploy": "部署",+ "overview.deployedEnvironments": "已部署",+ "overview.deploymentOverview": "部署概览",+ "overview.deploymentStatus": "部署状态",+ "overview.description": "描述",+ "overview.developerApi": "开发者 API",+ "overview.disabled": "未启用",+ "overview.emptyValue": "未设置",+ "overview.enabled": "已启用",+ "overview.enabledChannels": "接入启用",+ "overview.endUserAccess": "终端用户接入",+ "overview.environments": "环境",+ "overview.hero.byName": "由 {{name}} 创建",+ "overview.hero.empty": "尚无版本",+ "overview.hero.emptyDescription": "先从当前来源创建版本,再部署到环境。",+ "overview.hero.propagation_one": "已部署到 {{total}} 个环境中的 {{count}} 个",+ "overview.hero.propagation_other": "已部署到 {{total}} 个环境中的 {{count}} 个",+ "overview.hero.untargeted": "尚未配置环境",+ "overview.instanceDetails": "部署详情",+ "overview.instanceId": "部署 ID",+ "overview.latestRelease.releaseCount_one": "共 {{count}} 个版本",+ "overview.latestRelease.releaseCount_other": "共 {{count}} 个版本",+ "overview.latestReleaseTitle": "最新版本",+ "overview.manageDeployments": "管理部署",+ "overview.name": "名称",+ "overview.noAccessConfig": "未配置接入方式。",+ "overview.noReleaseYet": "请先创建版本,再部署到环境。",+ "overview.notConfigured": "未配置",+ "overview.previousReleases.empty": "暂无更早的版本。",+ "overview.previousReleases.retired": "当前未部署",+ "overview.previousReleases.title": "历史版本",+ "overview.previousReleases.viewAll": "查看全部",+ "overview.ready": "可部署",+ "overview.recentReleases": "近期版本",+ "overview.releaseDeployedTitle": "{{release}} 已部署",+ "overview.releaseReadyTitle": "{{release}} 可以部署",+ "overview.serviceMap": "服务图",+ "overview.servingRelease": "正在运行 {{release}}",+ "overview.servingReleaseDescription": "该部署已部署到 {{count}}/{{total}} 个环境。",+ "overview.strip.deployToNewEnvironment": "部署到新环境",+ "overview.strip.empty": "尚未配置任何环境。",+ "overview.strip.emptyDeployableDescription": "已有版本后,可选择环境进行部署。",+ "overview.strip.emptyDeployed": "暂无实例。",+ "overview.strip.emptyDescription": "请先创建版本,再部署到环境。",+ "overview.strip.emptyTitle": "暂无实例",+ "overview.strip.summary_one": "{{total}} 个环境中 1 个已部署最新版本",+ "overview.strip.summary_other": "{{total}} 个环境中 {{count}} 个已部署最新版本",+ "overview.strip.title": "实例",+ "overview.switchSourceApp": "切换来源",+ "overview.switchSourceAppDescription": "选择后续新建版本使用的工作流应用来源。",+ "overview.switchSourceAppHint": "切换后,仅新建版本会使用新的来源;历史版本和现有部署不受影响。",+ "overview.targetRelease": "目标版本",+ "overview.webapp": "WebApp",+ "settings.danger": "危险区域",+ "settings.dangerDesc": "永久删除此部署并停止所有运行中的实例。此操作无法撤销。",+ "settings.delete": "删除部署",+ "settings.deleteConfirmDesc": "确定删除 {{name}}?所有实例都将停止运行,并从所有环境中移除。此操作无法撤销。",+ "settings.deleteConfirmTitle": "删除部署",+ "settings.deleteFailed": "删除部署失败。",+ "settings.deleteImpact": "影响",+ "settings.deleteImpactInstance": "部署",+ "settings.deleteImpactTitle": "受影响的部署",+ "settings.deleteImpactValue": "该部署会从部署列表中移除。",+ "settings.deleted": "部署已删除",+ "settings.description": "描述",+ "settings.descriptionHelp": "管理此部署的名称、描述和其他设置。",+ "settings.general": "常规",+ "settings.name": "部署名称",+ "settings.reset": "重置",+ "settings.save": "保存修改",+ "settings.updateFailed": "更新部署失败。",+ "settings.updated": "部署已更新",+ "status.RUNTIME_INSTANCE_STATUS_DEPLOYING": "部署中",+ "status.RUNTIME_INSTANCE_STATUS_DRIFTED": "待同步",+ "status.RUNTIME_INSTANCE_STATUS_FAILED": "部署失败",+ "status.RUNTIME_INSTANCE_STATUS_INVALID": "异常",+ "status.RUNTIME_INSTANCE_STATUS_READY": "运行中",+ "status.RUNTIME_INSTANCE_STATUS_UNDEPLOYED": "未部署",+ "status.RUNTIME_INSTANCE_STATUS_UNDEPLOYING": "下线中",+ "status.RUNTIME_INSTANCE_STATUS_UNSPECIFIED": "未知",+ "subtitle": "在不同环境中管理部署。",+ "tabs.access.description": "管理接入渠道与访问权限。",+ "tabs.access.name": "接入方式",+ "tabs.api-tokens.description": "管理 API 令牌,通过 HTTP 调用各环境中的实例。",+ "tabs.api-tokens.name": "API 令牌",+ "tabs.instances.description": "查看和管理各环境中的实例。",+ "tabs.instances.name": "实例",+ "tabs.overview.description": "查看此部署在各环境中的状态。",+ "tabs.overview.name": "概览",+ "tabs.releases.description": "创建、部署和管理版本。",+ "tabs.releases.name": "版本",+ "tabs.settings.description": "管理此部署的名称、描述和其他设置。",+ "tabs.settings.name": "设置",+ "title": "部署",+ "unsupportedDslNodes.description": "该版本包含当前部署运行时尚不支持的节点。请在 Studio 中移除或替换这些节点后重试。",+ "unsupportedDslNodes.descriptionWithTypes": "该版本包含当前部署运行时尚不支持的节点:{{nodeTypes}}。请在 Studio 中移除或替换后重试。",+ "unsupportedDslNodes.title": "不支持的节点",+ "unsupportedDslNodes.unknownType": "未知类型",+ "versions.cancelCreate": "取消",+ "versions.cancelDelete": "取消",+ "versions.cancelEdit": "取消",+ "versions.checkingReleaseContent": "正在检查版本内容…",+ "versions.col.action": "操作",+ "versions.col.author": "创建者",+ "versions.col.commit": "提交",+ "versions.col.createdAt": "创建时间",+ "versions.col.deployedTo": "已部署到",+ "versions.col.release": "版本",+ "versions.col.sourceApp": "来源",+ "versions.commitTooltip": "Commit {{commit}}",+ "versions.create": "创建",+ "versions.createFailed": "创建版本失败。",+ "versions.createRelease": "创建版本",+ "versions.createReleaseDescription": "从工作流应用或工作流 DSL 文件创建可部署版本。",+ "versions.createReleaseHint": "新版本可部署到任意环境。",+ "versions.createSuccess": "版本 \"{{name}}\" 已创建。",+ "versions.creating": "创建中…",+ "versions.currentOn": "{{name}} 当前版本",+ "versions.deleteConfirmDesc": "版本 \"{{name}}\" 将被永久删除,此操作无法撤销。",+ "versions.deleteConfirmTitle": "删除版本?",+ "versions.deleteFailed": "删除版本失败。",+ "versions.deleteImpactDeployment": "部署状态",+ "versions.deleteImpactNotDeployed": "当前未部署",+ "versions.deleteImpactRelease": "版本",+ "versions.deleteImpactTitle": "删除影响",+ "versions.deleteRelease": "删除版本",+ "versions.deleteSuccess": "版本 \"{{name}}\" 已删除。",+ "versions.deploy": "部署",+ "versions.deployTo": "部署到 {{name}}",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_DEPLOYING": "部署中",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_DRIFTED": "待同步",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_FAILED": "失败",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_INVALID": "异常",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_READY": "运行中",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYED": "未部署",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_UNDEPLOYING": "下线中",+ "versions.deployedStatus.RUNTIME_INSTANCE_STATUS_UNSPECIFIED": "未知",+ "versions.deployingTo": "{{name}} 正在部署",+ "versions.disabledReason.checkDeploymentsFailed": "无法确认部署使用情况,请稍后重试。",+ "versions.disabledReason.checkingDeployments": "正在检查部署使用情况",+ "versions.disabledReason.current": "{{name}} 已运行此版本",+ "versions.disabledReason.deploying": "请等待当前部署完成",+ "versions.disabledReason.envDisabled": "此环境不可部署",+ "versions.disabledReason.releaseInUse_one": "请先从 {{count}} 个环境中取消部署此版本,再删除它",+ "versions.disabledReason.releaseInUse_other": "请先从 {{count}} 个环境中取消部署此版本,再删除它",+ "versions.dslReadFailed": "读取 DSL 文件失败。请选择其他文件后重试。",+ "versions.dslReading": "正在读取 DSL 文件…",+ "versions.dslUnsupportedMode": "仅支持使用工作流 DSL 创建部署版本。",+ "versions.editFailed": "更新版本失败。",+ "versions.editRelease": "编辑版本",+ "versions.editReleaseDescription": "更新此版本的名称和描述。",+ "versions.editSuccess": "版本 \"{{name}}\" 已更新。",+ "versions.empty": "暂无可用版本。",+ "versions.emptyDescription": "先创建第一个版本,再部署到目标环境。",+ "versions.emptyTitle": "暂无版本",+ "versions.emptyWithCreate": "暂无版本,请先创建第一个可部署版本。",+ "versions.exportDsl": "导出 DSL",+ "versions.exportDslFailed": "导出 DSL 失败。",+ "versions.exportingDsl": "正在导出…",+ "versions.groupHeader.deploy": "部署",+ "versions.groupHeader.promote": "部署",+ "versions.groupHeader.rollback": "部署历史版本",+ "versions.groupHeader.unavailable": "不可用",+ "versions.manualDslOption": "上传 DSL",+ "versions.moreActions": "更多操作",+ "versions.optional": "可选",+ "versions.promote": "部署",+ "versions.promoteTo": "部署到 {{name}}",+ "versions.releaseAlreadyExists": "相同内容的版本已存在:{{name}}。",+ "versions.releaseContentCheckFailed": "检查版本内容失败。",+ "versions.releaseDescriptionLabel": "描述",+ "versions.releaseDescriptionPlaceholder": "描述这个版本",+ "versions.releaseHistory": "版本历史",+ "versions.releaseNameLabel": "版本名称",+ "versions.releaseNamePlaceholder": "版本名称",+ "versions.releaseNameRequired": "请输入版本名称。",+ "versions.releaseSourceLabel": "版本来源",+ "versions.rollbackTo": "部署到 {{name}}",+ "versions.saveEdit": "保存",+ "versions.sourceAppOption": "工作流应用"+}diff --git a/web/knip.config.ts b/web/knip.config.tsindex b18639e64f7..dfd9adf79a1 100644--- a/web/knip.config.ts+++ b/web/knip.config.ts@@ -15,6 +15,8 @@ const config: KnipConfig = {],ignoreBinaries: ['only-allow',+ 'pbcopy',+ 'which',],ignoreDependencies: ['@iconify-json/*',diff --git a/web/models/access-control.ts b/web/models/access-control.tsindex d0e58d645b4..f09db659613 100644--- a/web/models/access-control.ts+++ b/web/models/access-control.ts@@ -1,27 +1,31 @@-export enum SubjectType {- GROUP = 'group',- ACCOUNT = 'account',-}+export const SubjectType = {+ GROUP: 'group',+ ACCOUNT: 'account',+} as const-export enum AccessMode {- PUBLIC = 'public',- SPECIFIC_GROUPS_MEMBERS = 'private',- ORGANIZATION = 'private_all',- EXTERNAL_MEMBERS = 'sso_verified',-}+export type SubjectType = typeof SubjectType[keyof typeof SubjectType]++export const AccessMode = {+ PUBLIC: 'public',+ SPECIFIC_GROUPS_MEMBERS: 'private',+ ORGANIZATION: 'private_all',+ EXTERNAL_MEMBERS: 'sso_verified',+} as const++export type AccessMode = typeof AccessMode[keyof typeof AccessMode]export type AccessControlGroup = {- id: 'string'- name: 'string'- groupSize: 5+ id: string+ name: string+ groupSize: number}export type AccessControlAccount = {- id: 'string'- name: 'string'- email: 'string'- avatar: 'string'- avatarUrl: 'string'+ id: string+ name: string+ email: string+ avatar: string+ avatarUrl: string}export type SubjectGroup = { subjectId: string, subjectType: SubjectType, groupData: AccessControlGroup }diff --git a/web/package.json b/web/package.jsonindex d1d581ad7bf..686bc5b04b1 100644--- a/web/package.json+++ b/web/package.json@@ -73,6 +73,7 @@"@svgdotjs/svg.js": "catalog:","@t3-oss/env-nextjs": "catalog:","@tailwindcss/typography": "catalog:",+ "@tanstack/query-core": "catalog:","@tanstack/react-form": "catalog:","@tanstack/react-hotkeys": "catalog:","@tanstack/react-query": "catalog:",@@ -104,6 +105,8 @@"i18next-resources-to-backend": "catalog:","immer": "catalog:","jotai": "catalog:",+ "jotai-scope": "catalog:",+ "jotai-tanstack-query": "catalog:","js-audio-recorder": "catalog:","js-cookie": "catalog:","js-yaml": "catalog:",diff --git a/web/service/access-control.ts b/web/service/access-control.tsindex 40ef1cfdea7..d6eabf05ef0 100644--- a/web/service/access-control.ts+++ b/web/service/access-control.ts@@ -1,8 +1,7 @@-import type { AccessControlAccount, AccessControlGroup, AccessMode, Subject } from '@/models/access-control'-import type { App } from '@/types/app'-import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { get, post } from './base'+import { get } from './base'import { getUserCanAccess } from './share'const NAME_SPACE = 'access-control'@@ -49,27 +48,6 @@ export const useSearchForWhiteListCandidates = (query: { keyword?: string, group})}-type UpdateAccessModeParams = {- appId: App['id']- subjects?: Pick<Subject, 'subjectId' | 'subjectType'>[]- accessMode: AccessMode-}--export const useUpdateAccessMode = () => {- const queryClient = useQueryClient()- return useMutation({- mutationKey: [NAME_SPACE, 'update-access-mode'],- mutationFn: (params: UpdateAccessModeParams) => {- return post('/enterprise/webapp/app/access-mode', { body: params })- },- onSuccess: () => {- queryClient.invalidateQueries({- queryKey: [NAME_SPACE, 'app-whitelist-subjects'],- })- },- })-}-export const useGetUserCanAccessApp = ({ appId, isInstalledApp = true, enabled }: { appId?: string, isInstalledApp?: boolean, enabled?: boolean }) => {// useQuery (not useSuspenseQuery) to keep this service hook's call contract// unchanged from the zustand era: callers should not need a Suspense boundary.diff --git a/web/service/client.ts b/web/service/client.tsindex 84a8c7a43df..3a26185a9b3 100644--- a/web/service/client.ts+++ b/web/service/client.ts@@ -1,6 +1,13 @@import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'+import type {+ GetReleaseResponse,+ ListReleasesResponse,+ PrecheckReleaseRequest,+} from '@dify/contracts/enterprise/types.gen'import type { ContractRouterClient } from '@orpc/contract'import type { JsonifiedClient } from '@orpc/openapi-client'+import type { RouterUtils } from '@orpc/tanstack-query'+import type { QueryClient, QueryKey } from '@tanstack/react-query'import type { Tag } from '@/contract/console/tags'import { createORPCClient, onError } from '@orpc/client'import { OpenAPILink } from '@orpc/openapi-client/fetch'@@ -18,9 +25,11 @@ import {import { isClient } from '@/utils/client'import { request } from './base'-const getMarketplaceHeaders = () => new Headers({- 'X-Dify-Version': !IS_MARKETPLACE ? APP_VERSION : '999.0.0',-})+function getMarketplaceHeaders() {+ return new Headers({+ 'X-Dify-Version': !IS_MARKETPLACE ? APP_VERSION : '999.0.0',+ })+}function isURL(path: string) {try {@@ -66,6 +75,252 @@ const marketplaceLink = new OpenAPILink(marketplaceRouterContract, {export const marketplaceClient: JsonifiedClient<ContractRouterClient<typeof marketplaceRouterContract>> = createORPCClient(marketplaceLink)export const marketplaceQuery = createTanstackQueryUtils(marketplaceClient, { path: ['marketplace'] })+const APP_DEPLOY_SOURCE_APPS_PAGE_SIZE = 100+const APP_DEPLOY_READINESS_RETRY_DELAYS = [0, 300, 700, 1200]++type AppDeployInvalidationOptions = {+ appInstances?: boolean+ appInstanceSummaries?: boolean+ appInstance?: boolean+ appInstanceOverview?: boolean+ environmentDeployments?: boolean+ releases?: boolean+ releaseSummaries?: boolean+ releaseDeploymentView?: boolean+ accessChannels?: boolean+ accessSettings?: boolean+ developerApiSettings?: boolean+}++type ConsoleQueryUtils = RouterUtils<JsonifiedClient<ContractRouterClient<typeof consoleRouterContract>>>++const defaultAppDeployInvalidationOptions = {+ appInstances: true,+ appInstanceSummaries: true,+ appInstance: true,+ appInstanceOverview: true,+ environmentDeployments: true,+ releases: true,+ releaseSummaries: true,+ releaseDeploymentView: true,+ accessChannels: true,+ accessSettings: true,+ developerApiSettings: true,+} satisfies Required<AppDeployInvalidationOptions>++function invalidateQueryKeys(client: QueryClient, queryKeys: QueryKey[]) {+ return Promise.all(queryKeys.map(queryKey => client.invalidateQueries({ queryKey })))+}++function appInstanceQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.appInstanceService.getAppInstance.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function appInstanceOverviewQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.appInstanceService.getAppInstanceOverview.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function environmentDeploymentsQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.deploymentService.listEnvironmentDeployments.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function releasesQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.releaseService.listReleases.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function releaseSummariesQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.releaseService.listReleaseSummaries.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function releaseDeploymentViewQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.releaseService.computeReleaseDeploymentView.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function releaseQueryKey(query: ConsoleQueryUtils, releaseId: string) {+ return query.enterprise.releaseService.getRelease.key({+ type: 'query',+ input: { params: { releaseId } },+ })+}++function cachedReleaseAppInstanceId(+ query: ConsoleQueryUtils,+ client: QueryClient,+ releaseId: string,+) {+ const listQueries = client.getQueriesData<ListReleasesResponse>({+ queryKey: query.enterprise.releaseService.listReleases.key({ type: 'query' }),+ })+ for (const [, data] of listQueries) {+ const appInstanceId = data?.releases?.find(release => release.id === releaseId)?.appInstanceId+ if (appInstanceId)+ return appInstanceId+ }++ const releaseQueries = client.getQueriesData<GetReleaseResponse>({+ queryKey: query.enterprise.releaseService.getRelease.key({ type: 'query' }),+ })+ for (const [, data] of releaseQueries) {+ const release = data?.release+ if (release?.id === releaseId && release.appInstanceId)+ return release.appInstanceId+ }+}++function precheckReleaseQueryKey(query: ConsoleQueryUtils, body: PrecheckReleaseRequest) {+ return query.enterprise.releaseService.precheckRelease.key({+ type: 'query',+ input: { body },+ })+}++function accessChannelsQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.accessService.getAccessChannels.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function accessSettingsQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.accessService.getAccessSettings.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function developerApiSettingsQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {+ return query.enterprise.accessService.getDeveloperApiSettings.key({+ type: 'query',+ input: { params: { appInstanceId } },+ })+}++function apiKeysQueryKey(query: ConsoleQueryUtils, appInstanceId: string, environmentId: string) {+ return query.enterprise.accessService.listApiKeys.key({+ type: 'query',+ input: { params: { appInstanceId, environmentId } },+ })+}++function accessPolicyQueryKey(query: ConsoleQueryUtils, appInstanceId: string, environmentId: string) {+ return query.enterprise.accessService.getAccessPolicy.key({+ type: 'query',+ input: { params: { appInstanceId, environmentId } },+ })+}++function invalidateAppDeployQueries(+ query: ConsoleQueryUtils,+ client: QueryClient,+ appInstanceId: string,+ options: AppDeployInvalidationOptions = {},+) {+ const resolvedOptions = {+ ...defaultAppDeployInvalidationOptions,+ ...options,+ }+ const queryKeys: QueryKey[] = []++ if (resolvedOptions.appInstances)+ queryKeys.push(query.enterprise.appInstanceService.listAppInstances.key())+ if (resolvedOptions.appInstanceSummaries)+ queryKeys.push(query.enterprise.appInstanceService.listAppInstanceSummaries.key())+ if (resolvedOptions.appInstance)+ queryKeys.push(appInstanceQueryKey(query, appInstanceId))+ if (resolvedOptions.appInstanceOverview)+ queryKeys.push(appInstanceOverviewQueryKey(query, appInstanceId))+ if (resolvedOptions.environmentDeployments)+ queryKeys.push(environmentDeploymentsQueryKey(query, appInstanceId))+ if (resolvedOptions.releases)+ queryKeys.push(releasesQueryKey(query, appInstanceId))+ if (resolvedOptions.releaseSummaries)+ queryKeys.push(releaseSummariesQueryKey(query, appInstanceId))+ if (resolvedOptions.releaseDeploymentView)+ queryKeys.push(releaseDeploymentViewQueryKey(query, appInstanceId))+ if (resolvedOptions.accessChannels)+ queryKeys.push(accessChannelsQueryKey(query, appInstanceId))+ if (resolvedOptions.accessSettings)+ queryKeys.push(accessSettingsQueryKey(query, appInstanceId))+ if (resolvedOptions.developerApiSettings)+ queryKeys.push(developerApiSettingsQueryKey(query, appInstanceId))++ return invalidateQueryKeys(client, queryKeys)+}++function removeAppDeployQueries(query: ConsoleQueryUtils, client: QueryClient, appInstanceId: string) {+ const queryKeys = [+ appInstanceQueryKey(query, appInstanceId),+ appInstanceOverviewQueryKey(query, appInstanceId),+ environmentDeploymentsQueryKey(query, appInstanceId),+ releasesQueryKey(query, appInstanceId),+ releaseSummariesQueryKey(query, appInstanceId),+ releaseDeploymentViewQueryKey(query, appInstanceId),+ accessChannelsQueryKey(query, appInstanceId),+ accessSettingsQueryKey(query, appInstanceId),+ developerApiSettingsQueryKey(query, appInstanceId),+ ]++ queryKeys.forEach(queryKey => client.removeQueries({ queryKey }))+}++async function invalidateReleaseMutationQueries(+ query: ConsoleQueryUtils,+ client: QueryClient,+ releaseId: string,+ appInstanceId?: string,+ options: {+ removeRelease?: boolean+ } = {},+) {+ const releaseDetailQueryKey = releaseQueryKey(query, releaseId)+ if (options.removeRelease) {+ client.removeQueries({+ queryKey: releaseDetailQueryKey,+ })+ }+ else {+ await client.invalidateQueries({+ queryKey: releaseDetailQueryKey,+ })+ }++ if (appInstanceId) {+ return invalidateAppDeployQueries(query, client, appInstanceId, {+ accessChannels: false,+ accessSettings: false,+ developerApiSettings: false,+ })+ }++ return invalidateQueryKeys(client, [+ query.enterprise.appInstanceService.listAppInstances.key(),+ query.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ query.enterprise.releaseService.listReleases.key({ type: 'query' }),+ query.enterprise.releaseService.listReleaseSummaries.key({ type: 'query' }),+ query.enterprise.releaseService.computeReleaseDeploymentView.key({ type: 'query' }),+ query.enterprise.appInstanceService.getAppInstance.key({ type: 'query' }),+ query.enterprise.appInstanceService.getAppInstanceOverview.key({ type: 'query' }),+ ])+}+const consoleLink = new OpenAPILink(consoleRouterContract, {url: getBaseURL(API_PREFIX),fetch: (input, init) => {@@ -87,9 +342,25 @@ const consoleLink = new OpenAPILink(consoleRouterContract, {export const consoleClient: JsonifiedClient<ContractRouterClient<typeof consoleRouterContract>> = createORPCClient(consoleLink)-export const consoleQuery = createTanstackQueryUtils(consoleClient, {+export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQueryUtils(consoleClient, {path: ['console'],experimental_defaults: {+ explore: {+ updateAppAccessMode: {+ mutationOptions: {+ onSuccess: (_data, _variables, _onMutateResult, context) => {+ return Promise.all([+ context.client.invalidateQueries({+ queryKey: consoleQuery.explore.appAccessMode.key({ type: 'query' }),+ }),+ context.client.invalidateQueries({+ queryKey: ['access-control', 'app-whitelist-subjects'],+ }),+ ])+ },+ },+ },+ },apiBasedExtension: {post: {mutationOptions: {@@ -173,5 +444,239 @@ export const consoleQuery = createTanstackQueryUtils(consoleClient, {},},},+ enterprise: {+ appInstanceService: {+ createAppInstance: {+ mutationOptions: {+ onSuccess: async (data, _variables, _result, context) => {+ const appInstanceId = data.appInstance?.id+ if (appInstanceId) {+ for (const delay of APP_DEPLOY_READINESS_RETRY_DELAYS) {+ if (delay > 0)+ await new Promise(resolve => setTimeout(resolve, delay))++ const listResponse = await context.client+ .fetchQuery(consoleQuery.enterprise.appInstanceService.listAppInstances.queryOptions({+ input: {+ query: {+ pageNumber: 1,+ resultsPerPage: APP_DEPLOY_SOURCE_APPS_PAGE_SIZE,+ },+ },+ }))+ .catch(() => undefined)++ if (listResponse?.appInstances?.some(app => app.id === appInstanceId))+ break+ }+ }++ await context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstances.key(),+ })+ await context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ })+ },+ },+ },+ updateAppInstance: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId, {+ environmentDeployments: false,+ releases: false,+ accessChannels: false,+ })+ },+ },+ },+ deleteAppInstance: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ removeAppDeployQueries(consoleQuery, context.client, appInstanceId)++ return Promise.all([+ context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstances.key(),+ }),+ context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ }),+ ])+ },+ },+ },+ },+ releaseService: {+ createRelease: {+ mutationOptions: {+ onSuccess: (data, variables, _result, context) => {+ const appInstanceId = data.release?.appInstanceId ?? data.appInstance?.id ?? variables.body.appInstanceId+ const { dsl, sourceAppId } = variables.body+ if (!appInstanceId) {+ return Promise.all([+ context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstances.key(),+ }),+ context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ }),+ ])+ }++ const appDeployInvalidation = invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId, {+ environmentDeployments: false,+ accessChannels: false,+ })+ if (!dsl && !sourceAppId)+ return appDeployInvalidation++ return Promise.all([+ appDeployInvalidation,+ context.client.invalidateQueries({+ queryKey: precheckReleaseQueryKey(consoleQuery, {+ appInstanceId,+ ...(dsl ? { dsl } : { sourceAppId }),+ }),+ }),+ ])+ },+ },+ },+ deleteRelease: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const releaseId = variables.params.releaseId+ const appInstanceId = cachedReleaseAppInstanceId(consoleQuery, context.client, releaseId)++ return invalidateReleaseMutationQueries(consoleQuery, context.client, releaseId, appInstanceId, {+ removeRelease: true,+ })+ },+ },+ },+ updateRelease: {+ mutationOptions: {+ onSuccess: (data, variables, _result, context) => {+ const releaseId = variables.params.releaseId+ const appInstanceId = data.release?.appInstanceId+ ?? cachedReleaseAppInstanceId(consoleQuery, context.client, releaseId)++ return invalidateReleaseMutationQueries(consoleQuery, context.client, releaseId, appInstanceId)+ },+ },+ },+ },+ deploymentService: {+ deploy: {+ mutationOptions: {+ onSuccess: (data, _variables, _result, context) => {+ // Deploy always creates a new AppInstance, so the reply carries it.+ const appInstanceId = data.appInstance?.id ?? data.release?.appInstanceId+ if (!appInstanceId) {+ return Promise.all([+ context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstances.key(),+ }),+ context.client.invalidateQueries({+ queryKey: consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ }),+ ])+ }++ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId)+ },+ },+ },+ cancelDeployment: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId)+ },+ },+ },+ promote: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId)+ },+ },+ },+ rollback: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId)+ },+ },+ },+ undeploy: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId)+ },+ },+ },+ },+ accessService: {+ createApiKey: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ const environmentId = variables.params.environmentId+ return invalidateQueryKeys(context.client, [+ appInstanceQueryKey(consoleQuery, appInstanceId),+ appInstanceOverviewQueryKey(consoleQuery, appInstanceId),+ consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ accessChannelsQueryKey(consoleQuery, appInstanceId),+ developerApiSettingsQueryKey(consoleQuery, appInstanceId),+ apiKeysQueryKey(consoleQuery, appInstanceId, environmentId),+ ])+ },+ },+ },+ deleteApiKey: {+ mutationOptions: {+ onSuccess: (_data, _variables, _result, context) => {+ return invalidateQueryKeys(context.client, [+ consoleQuery.enterprise.accessService.listApiKeys.key({ type: 'query' }),+ consoleQuery.enterprise.accessService.getDeveloperApiSettings.key({ type: 'query' }),+ consoleQuery.enterprise.appInstanceService.getAppInstanceOverview.key({ type: 'query' }),+ consoleQuery.enterprise.appInstanceService.listAppInstanceSummaries.key(),+ ])+ },+ },+ },+ updateAccessChannels: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const appInstanceId = variables.params.appInstanceId+ return invalidateAppDeployQueries(consoleQuery, context.client, appInstanceId, {+ environmentDeployments: false,+ releases: false,+ })+ },+ },+ },+ updateAccessPolicy: {+ mutationOptions: {+ onSuccess: (_data, variables, _result, context) => {+ const { appInstanceId, environmentId } = variables.params+ return invalidateQueryKeys(context.client, [+ accessPolicyQueryKey(consoleQuery, appInstanceId, environmentId),+ accessChannelsQueryKey(consoleQuery, appInstanceId),+ accessSettingsQueryKey(consoleQuery, appInstanceId),+ ])+ },+ },+ },+ },+ },},})diff --git a/web/utils/clipboard.ts b/web/utils/clipboard.tsindex f2ce93c8fe8..41406d4540f 100644--- a/web/utils/clipboard.ts+++ b/web/utils/clipboard.ts@@ -1,6 +1,13 @@export async function writeTextToClipboard(text: string): Promise<void> {- if (window.isSecureContext && navigator.clipboard && navigator.clipboard.writeText)- return navigator.clipboard.writeText(text)+ if (window.isSecureContext && navigator.clipboard && navigator.clipboard.writeText) {+ try {+ await navigator.clipboard.writeText(text)+ return+ }+ catch {+ // Fall through to the legacy path when browsers deny Clipboard API access.+ }+ }return fallbackCopyTextToClipboard(text)}@@ -27,7 +34,7 @@ async function fallbackCopyTextToClipboard(text: string): Promise<void> {}}-function convertAnyToError(err: any): Error {+function convertAnyToError(err: unknown): Error {if (err instanceof Error)return err