Skip to content

armgit / dify

Public Imported from GitHub
0

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.

refactor: migrate app tracing queries and harden monitoring configuration (#44150)

yyhab7677632d30
diff --git a/api/controllers/console/app/ops_trace.py b/api/controllers/console/app/ops_trace.py
index df425cb5b66..6d41deb4d1f 100644
--- a/api/controllers/console/app/ops_trace.py
+++ b/api/controllers/console/app/ops_trace.py
@@ -1,4 +1,3 @@
-from typing import Any
from uuid import UUID
from flask_restx import Resource
@@ -55,7 +54,7 @@ class TraceProviderQuery(BaseModel):
class TraceConfigPayload(BaseModel):
tracing_provider: str = Field(..., description="Tracing provider name")
- tracing_config: dict[str, Any] = Field(
+ tracing_config: dict[str, str | None] = Field(
...,
description="Tracing configuration data",
)
@@ -68,7 +67,7 @@ class TraceAppConfigResponse(ResponseModel):
id: str | None = None
app_id: str | None = None
tracing_provider: str | None = None
- tracing_config: dict[str, Any] | None = Field(default=None)
+ tracing_config: dict[str, str | None] | None = Field(default=None)
is_active: bool | None = None
created_at: str | None = None
updated_at: str | None = None
diff --git a/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py b/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py
index 11eca206243..c73e9a3b98b 100644
--- a/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py
@@ -256,24 +256,42 @@ def test_trace_app_config_get_empty_returns_exact_legacy_body(
)
+ ("provider", "config"),
+ [
+ ("langfuse", {"public_key": "pk", "secret_key": "******"}),
+ (
+ "mlflow",
+ {
+ "tracking_uri": "http://localhost:5000",
+ "experiment_id": "0",
+ "username": None,
+ "password": "******",
+ "project_url": "http://localhost:5000",
+ },
+ ),
+ ],
+)
def test_trace_app_config_get_configured_returns_exact_legacy_body(
app: Flask,
tracing_configs: MagicMock,
+ provider: str,
+ config: dict[str, str | None],
) -> None:
tracing_configs.get.return_value = AppTracingConfigRecord(
id="trace-config-1",
app_id=APP_ID,
- tracing_provider=PROVIDER,
- tracing_config={"public_key": "pk", "secret_key": "******"},
+ tracing_provider=provider,
+ tracing_config=config,
is_active=True,
created_at=datetime(2026, 1, 2, 3, 4, 5),
updated_at=datetime(2026, 1, 3, 4, 5, 6),
)
- with app.test_request_context("/?tracing_provider=langfuse"):
+ with app.test_request_context(f"/?tracing_provider={provider}"):
result = _original(ops_trace_module.TraceAppConfigApi.get)(
ops_trace_module.TraceAppConfigApi(),
- ops_trace_module.TraceProviderQuery(tracing_provider=PROVIDER),
+ ops_trace_module.TraceProviderQuery(tracing_provider=provider),
_request_context(),
UUID(APP_ID),
)
@@ -281,8 +299,8 @@ def test_trace_app_config_get_configured_returns_exact_legacy_body(
assert result == {
"id": "trace-config-1",
"app_id": APP_ID,
- "tracing_provider": PROVIDER,
- "tracing_config": {"public_key": "pk", "secret_key": "******"},
+ "tracing_provider": provider,
+ "tracing_config": config,
"is_active": True,
"created_at": "2026-01-02 03:04:05",
"updated_at": "2026-01-03 04:05:06",
@@ -296,15 +314,24 @@ def test_trace_app_config_get_configured_returns_exact_legacy_body(
pytest.param("patch", {"result": "success"}, id="update"),
],
)
+ ("provider", "config"),
+ [
+ ("langfuse", {"public_key": "pk", "secret_key": "sk"}),
+ ("mlflow", {"tracking_uri": "", "experiment_id": "0", "username": None, "password": "******"}),
+ ],
+)
def test_trace_app_config_write_returns_expected_response(
app: Flask,
tracing_configs: MagicMock,
method_name: str,
expected_result: object,
+ provider: str,
+ config: dict[str, str | None],
) -> None:
payload = ops_trace_module.TraceConfigPayload(
- tracing_provider=PROVIDER,
- tracing_config={"public_key": "pk", "secret_key": "sk"},
+ tracing_provider=provider,
+ tracing_config=config,
)
with app.test_request_context("/", method=method_name.upper()):
@@ -319,8 +346,8 @@ def test_trace_app_config_write_returns_expected_response(
_service_method(tracing_configs, method_name).assert_called_once_with(
context=_request_context(),
app_id=APP_ID,
- tracing_provider=PROVIDER,
- tracing_config={"public_key": "pk", "secret_key": "sk"},
+ tracing_provider=provider,
+ tracing_config=config,
)
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 45ec787871a..5860d4b709f 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -67,17 +67,6 @@
"count": 1
}
},
- "web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-panel.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 3
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 3
- },
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/(shareLayout)/webapp-reset-password/layout.tsx": {
"typescript/no-explicit-any": {
"count": 1
@@ -542,19 +531,6 @@
"count": 2
}
},
- "web/app/components/app/overview/apikey-info-panel/index.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- }
- },
- "web/app/components/app/overview/app-chart.tsx": {
- "react/only-export-components": {
- "count": 12
- }
- },
"web/app/components/app/text-generate/item/__tests__/index.spec.tsx": {
"typescript/no-explicit-any": {
"count": 2
@@ -4272,9 +4248,6 @@
"web/service/apps.ts": {
"no-restricted-imports": {
"count": 1
- },
- "typescript/no-explicit-any": {
- "count": 1
}
},
"web/service/base.spec.ts": {
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index 7db89bd3cee..168a6e6ee05 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -863,7 +863,7 @@ export type TraceAppConfigResponse = {
is_active?: boolean | null
result?: string | null
tracing_config?: {
- [key: string]: unknown
+ [key: string]: string | null
} | null
tracing_provider?: string | null
updated_at?: string | null
@@ -871,7 +871,7 @@ export type TraceAppConfigResponse = {
export type TraceConfigPayload = {
tracing_config: {
- [key: string]: unknown
+ [key: string]: string | null
}
tracing_provider: string
}
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 95e1f853adb..180496d352c 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -806,7 +806,7 @@ export const zTraceAppConfigResponse = z.object({
id: z.string().nullish(),
is_active: z.boolean().nullish(),
result: z.string().nullish(),
- tracing_config: z.record(z.string(), z.unknown()).nullish(),
+ tracing_config: z.record(z.string(), z.string().nullable()).nullish(),
tracing_provider: z.string().nullish(),
updated_at: z.string().nullish(),
})
@@ -815,7 +815,7 @@ export const zTraceAppConfigResponse = z.object({
* TraceConfigPayload
*/
export const zTraceConfigPayload = z.object({
- tracing_config: z.record(z.string(), z.unknown()),
+ tracing_config: z.record(z.string(), z.string().nullable()),
tracing_provider: z.string(),
})
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx
index 6eddad07aec..9cfacbf5f6b 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx
@@ -1,5 +1,7 @@
import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { act, screen, waitFor } from '@testing-library/react'
+import { Suspense } from 'react'
import { useStore } from '@/app/components/app/store'
import { consoleQuery } from '@/service/console'
import { renderWithConsoleQuery } from '@/test/console/query-data'
@@ -83,6 +85,59 @@ describe('AppDetailLayout', () => {
useStore.getState().setAppDetail()
})
+ it('shares the app detail request with the overview observer', async () => {
+ mockPathname = '/app/app-1/overview'
+ function OverviewConsumer() {
+ const { data } = useSuspenseQuery(
+ consoleQuery.apps.byAppId.get.queryOptions({
+ input: { params: { app_id: 'app-1' } },
+ }),
+ )
+ return <div>{data.name} statistics</div>
+ }
+ render(
+ <AppDetailLayout appId="app-1">
+ <Suspense fallback={<div>Loading overview</div>}>
+ <OverviewConsumer />
+ </Suspense>
+ </AppDetailLayout>,
+ )
+ expect(await screen.findByText('Demo App statistics')).toBeInTheDocument()
+ expect(mockAppResponse).toHaveBeenCalledTimes(1)
+ expect(screen.queryByText('Loading overview')).not.toBeInTheDocument()
+ })
+
+ it('hides the previous app while loading another app', async () => {
+ const { rerender } = render(
+ <AppDetailLayout appId="app-1">
+ <div>First app content</div>
+ </AppDetailLayout>,
+ )
+ await screen.findByText('First app content')
+ let resolveRequest!: (response: AppDetailWithSite) => void
+ mockAppResponse.mockImplementation(
+ () =>
+ new Promise<AppDetailWithSite>((resolve) => {
+ resolveRequest = resolve
+ }),
+ )
+ mockPathname = '/app/app-2/workflow'
+ rerender(
+ <AppDetailLayout appId="app-2">
+ <div>Second app content</div>
+ </AppDetailLayout>,
+ )
+ expect(screen.queryByText('First app content')).not.toBeInTheDocument()
+ expect(screen.queryByText('Second app content')).not.toBeInTheDocument()
+ await waitFor(() =>
+ expect(mockAppResponse).toHaveBeenCalledWith(expect.stringMatching(/\/apps\/app-2$/)),
+ )
+ await act(async () => {
+ resolveRequest(createAppDetail({ id: 'app-2' }))
+ })
+ expect(await screen.findByText('Second app content')).toBeInTheDocument()
+ })
+
describe('Document title', () => {
it.each([
['/app/app-1/workflow', 'common.appMenus.promptEng', AppModeEnum.WORKFLOW],
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
index 32e6279aa35..546091df0f8 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
@@ -1,12 +1,11 @@
'use client'
-import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
import type { FC } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import * as React from 'react'
-import { useEffect, useState } from 'react'
+import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { useShallow } from 'zustand/react/shallow'
import { useStore } from '@/app/components/app/store'
@@ -20,7 +19,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePathname, useRouter } from '@/next/navigation'
-import { consoleClient, consoleQuery } from '@/service/console'
+import { consoleQuery } from '@/service/console'
import { isNotFoundError } from '@/service/http-error'
import { AppModeEnum } from '@/types/app'
import { getRedirectionPath } from '@/utils/app-redirection'
@@ -71,17 +70,17 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
setAppDetail: state.setAppDetail,
})),
)
- const [isLoadingAppDetail, setIsLoadingAppDetail] = useState(false)
- const [appDetailRes, setAppDetailRes] = useState<AppDetailWithSite | null>(null)
- const routeAppDetail =
- appDetail?.id === appId ? appDetail : appDetailRes?.id === appId ? appDetailRes : null
const pageTitle = appDetailPageTitle(pathname, t)
- const { data: appName } = useQuery(
+ const {
+ data: appDetailRes,
+ error: appDetailError,
+ isPending: isLoadingAppDetail,
+ } = useQuery(
consoleQuery.apps.byAppId.get.queryOptions({
input: { params: { app_id: appId } },
- select: (detail) => detail.name,
}),
)
+ const routeAppDetail = appDetail?.id === appId ? appDetail : appDetailRes
const shouldBlockAgentResourceAccess =
routeAppDetail?.mode === AppModeEnum.AGENT && pathname.endsWith('/access-config')
const canViewAccessPoint =
@@ -100,45 +99,12 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
const shouldBlockAccessPointAccess = pathname.endsWith('/access-point') && !canViewAccessPoint
useDocumentTitle(
- `${pageTitle} · ${appName || t(($) => $['menus.appDetail'], { ns: 'navigation' })}`,
+ `${pageTitle} · ${appDetailRes?.name || t(($) => $['menus.appDetail'], { ns: 'navigation' })}`,
)
useEffect(() => {
- let ignore = false
-
- const currentAppDetail = useStore.getState().appDetail
- if (currentAppDetail?.id === appId) {
- return () => {
- ignore = true
- }
- }
-
- setAppDetail()
- void Promise.resolve().then(() => {
- if (!ignore) setIsLoadingAppDetail(true)
- })
- consoleClient.apps.byAppId
- .get({ params: { app_id: appId } })
- .then((res: AppDetailWithSite) => {
- if (ignore) return
-
- setAppDetailRes(res)
- })
- .catch((error: unknown) => {
- if (ignore) return
-
- if (isNotFoundError(error)) router.replace('/apps')
- })
- .finally(() => {
- if (ignore) return
-
- setIsLoadingAppDetail(false)
- })
-
- return () => {
- ignore = true
- }
- }, [appId, router, setAppDetail])
+ if (appDetailError && !appDetailRes && isNotFoundError(appDetailError)) router.replace('/apps')
+ }, [appDetailError, appDetailRes, router])
useEffect(() => {
if (
@@ -220,9 +186,11 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
workspacePermissionKeys,
])
+ if (appDetailError && !appDetailRes && !isNotFoundError(appDetailError)) throw appDetailError
+
const isWorkflowPage = pathname.endsWith('/workflow')
const content =
- !appDetail || shouldBlockAgentResourceAccess || shouldBlockAccessPointAccess ? (
+ appDetail?.id !== appId || shouldBlockAgentResourceAccess || shouldBlockAccessPointAccess ? (
<div className="flex min-w-0 grow items-center justify-center bg-background-body">
<LoadingPlaceholder />
</div>
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx
index ccc7db22152..33b1b207417 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx
@@ -4,7 +4,6 @@ import { renderWithConsoleQuery } from '@/test/console/query-data'
import ChartView from '../chart-view'
const testState = vi.hoisted(() => ({
- chartRenderSpy: vi.fn(),
conversationPeriodSpy: vi.fn(),
}))
@@ -20,54 +19,9 @@ vi.mock('@/context/i18n', () => ({
}))
vi.mock('@/app/components/app/overview/app-chart', () => ({
- AvgResponseTime: () => {
- testState.chartRenderSpy('avg-response-time')
- return <div>avg response time chart</div>
- },
- AvgSessionInteractions: () => {
- testState.chartRenderSpy('avg-session-interactions')
- return <div>avg session interactions chart</div>
- },
- AvgUserInteractions: () => {
- testState.chartRenderSpy('avg-user-interactions')
- return <div>avg user interactions chart</div>
- },
- ConversationsChart: ({ period }: { period: PeriodParams }) => {
- testState.chartRenderSpy('conversations')
+ AppCharts: ({ period, appMode }: { period: PeriodParams; appMode: string }) => {
testState.conversationPeriodSpy(period)
- return <div>conversations chart</div>
- },
- CostChart: () => {
- testState.chartRenderSpy('cost')
- return <div>cost chart</div>
- },
- EndUsersChart: () => {
- testState.chartRenderSpy('end-users')
- return <div>end users chart</div>
- },
- MessagesChart: () => {
- testState.chartRenderSpy('messages')
- return <div>messages chart</div>
- },
- TokenPerSecond: () => {
- testState.chartRenderSpy('token-per-second')
- return <div>token per second chart</div>
- },
- UserSatisfactionRate: () => {
- testState.chartRenderSpy('user-satisfaction-rate')
- return <div>user satisfaction rate chart</div>
- },
- WorkflowCostChart: () => {
- testState.chartRenderSpy('workflow-cost')
- return <div>workflow cost chart</div>
- },
- WorkflowDailyTerminalsChart: () => {
- testState.chartRenderSpy('workflow-daily-terminals')
- return <div>workflow daily terminals chart</div>
- },
- WorkflowMessagesChart: () => {
- testState.chartRenderSpy('workflow-messages')
- return <div>workflow messages chart</div>
+ return <div>{appMode} charts</div>
},
}))
@@ -101,19 +55,16 @@ describe('ChartView', () => {
expect(screen.getByRole('heading', { name: 'common.appMenus.overview' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'header action' })).toBeInTheDocument()
- expect(screen.getByText('conversations chart')).toBeInTheDocument()
- expect(screen.getByText('avg session interactions chart')).toBeInTheDocument()
+ expect(screen.getByText('chat charts')).toBeInTheDocument()
})
it('renders completion charts from the explicit app mode', () => {
renderWithConsoleQuery(<ChartView appId="app-1" appMode="completion" headerRight={null} />)
- expect(screen.getByText('avg response time chart')).toBeInTheDocument()
- expect(screen.queryByText('avg session interactions chart')).not.toBeInTheDocument()
+ expect(screen.getByText('completion charts')).toBeInTheDocument()
})
it('renders workflow charts from the explicit app mode', () => {
renderWithConsoleQuery(<ChartView appId="app-2" appMode="workflow" headerRight={null} />)
- expect(screen.getByText('workflow messages chart')).toBeInTheDocument()
- expect(screen.queryByText('conversations chart')).not.toBeInTheDocument()
+ expect(screen.getByText('workflow charts')).toBeInTheDocument()
})
})
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsx
index 39f7f664b3d..c9cd1af47a4 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsx
@@ -35,10 +35,6 @@ vi.mock('@/context/workspace-state', async () => {
}))
})
-vi.mock('@/app/components/app/overview/apikey-info-panel', () => ({
- default: () => <div>api key info panel</div>,
-}))
-
vi.mock('../chart-view', () => ({
default: ({ appId, headerRight }: { appId: string; headerRight: ReactNode }) => (
<div>
@@ -88,7 +84,6 @@ describe('OverviewView monitor permission', () => {
it('should not render overview page content when app monitor permission is missing', () => {
render(<OverviewView appId="app-1" />)
- expect(screen.queryByText('api key info panel')).not.toBeInTheDocument()
expect(screen.queryByText(/chart view app-1/)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'tracing' })).not.toBeInTheDocument()
})
@@ -98,7 +93,6 @@ describe('OverviewView monitor permission', () => {
render(<OverviewView appId="app-1" />)
- expect(screen.getByText('api key info panel')).toBeInTheDocument()
expect(screen.getByText(/chart view app-1/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'tracing' })).not.toBeInTheDocument()
})
@@ -111,7 +105,6 @@ describe('OverviewView monitor permission', () => {
render(<OverviewView appId="app-1" />)
- expect(screen.getByText('api key info panel')).toBeInTheDocument()
expect(screen.getByText(/chart view app-1/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'tracing' })).toBeInTheDocument()
})
@@ -121,7 +114,6 @@ describe('OverviewView monitor permission', () => {
render(<OverviewView appId="app-1" />)
- expect(screen.queryByText('api key info panel')).not.toBeInTheDocument()
expect(screen.queryByText(/chart view app-1/)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'tracing' })).not.toBeInTheDocument()
})
@@ -139,7 +131,6 @@ describe('Overview app identity', () => {
expect(screen.getByRole('button', { name: 'tracing' })).toBeInTheDocument()
rerender(<OverviewView appId="app-2" />)
- expect(screen.queryByText('api key info panel')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'tracing' })).not.toBeInTheDocument()
act(() => {
@@ -155,7 +146,7 @@ describe('Overview app identity', () => {
createAppDetailFixture({ id: 'app-2', permission_keys: [] }),
)
})
- await waitFor(() => expect(screen.queryByText('api key info panel')).not.toBeInTheDocument())
+ await waitFor(() => expect(screen.queryByText(/chart view app-2/)).not.toBeInTheDocument())
})
})
@@ -172,7 +163,6 @@ it('shows the page fallback until required app details resolve', async () => {
</Suspense>,
)
expect(screen.getByText('Loading overview')).toBeInTheDocument()
- expect(screen.queryByText('api key info panel')).not.toBeInTheDocument()
await act(async () => {
resolveRequest(
Response.json(
@@ -204,7 +194,6 @@ it('recovers an initial detail failure through the existing route error action',
</QueryErrorResetBoundary>,
)
const retry = await screen.findByRole('button', { name: 'common.errorBoundary.tryAgain' })
- expect(screen.queryByText('api key info panel')).not.toBeInTheDocument()
testState.request.mockResolvedValue(
Response.json(
createAppDetailFixture({
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx
index 09db8c10679..c8cda4c9719 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx
@@ -10,20 +10,7 @@ import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { TIME_PERIOD_MAPPING as LONG_TIME_PERIOD_MAPPING } from '@/app/components/app/log/filter'
-import {
- AvgResponseTime,
- AvgSessionInteractions,
- AvgUserInteractions,
- ConversationsChart,
- CostChart,
- EndUsersChart,
- MessagesChart,
- TokenPerSecond,
- UserSatisfactionRate,
- WorkflowCostChart,
- WorkflowDailyTerminalsChart,
- WorkflowMessagesChart,
-} from '@/app/components/app/overview/app-chart'
+import { AppCharts } from '@/app/components/app/overview/app-chart'
import { useDocLink } from '@/context/i18n'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import LongTimeRangePicker from './long-time-range-picker'
@@ -75,8 +62,6 @@ function ChartViewContent({
const isCloudEdition = deploymentEdition === 'CLOUD'
const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'
const docLink = useDocLink()
- const isChatApp = appMode !== 'completion' && appMode !== 'workflow'
- const isWorkflow = appMode === 'workflow'
const [period, setPeriod] = useState<PeriodParams>(() =>
isCloudEdition
? {
@@ -139,31 +124,7 @@ function ChartViewContent({
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-6 pt-2 pb-6">
- <div className="grid w-full grid-cols-1 gap-3 xl:grid-cols-2">
- {!isWorkflow && (
- <>
- <ConversationsChart period={period} id={appId} />
- <EndUsersChart period={period} id={appId} />
- {isChatApp ? (
- <AvgSessionInteractions period={period} id={appId} />
- ) : (
- <AvgResponseTime period={period} id={appId} />
- )}
- <TokenPerSecond period={period} id={appId} />
- <UserSatisfactionRate period={period} id={appId} />
- <CostChart period={period} id={appId} />
- {isChatApp && <MessagesChart period={period} id={appId} />}
- </>
- )}
- {isWorkflow && (
- <>
- <WorkflowMessagesChart period={period} id={appId} />
- <WorkflowDailyTerminalsChart period={period} id={appId} />
- <WorkflowCostChart period={period} id={appId} />
- <AvgUserInteractions period={period} id={appId} />
- </>
- )}
- </div>
+ <AppCharts id={appId} period={period} appMode={appMode} />
</div>
</div>
)
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx
index 2c86769c6dc..35541cb6e7c 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx
@@ -1,6 +1,6 @@
import { Suspense } from 'react'
import * as React from 'react'
-import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'
+import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import OverviewView from './view'
export type IDevelopProps = {
@@ -13,15 +13,7 @@ const Overview = async (props: IDevelopProps) => {
const { appId } = params
return (
- <Suspense
- fallback={
- <SkeletonContainer className="gap-4 p-6" aria-busy="true">
- <SkeletonRectangle className="h-6 w-48" />
- <SkeletonRectangle className="h-10 w-full" />
- <SkeletonRectangle className="h-96 w-full" />
- </SkeletonContainer>
- }
- >
+ <Suspense fallback={<LoadingPlaceholder className="h-full" />}>
<OverviewView appId={appId} />
</Suspense>
)
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/range-selector.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/range-selector.tsx
index e1be177fe04..a3e815b80ff 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/range-selector.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/range-selector.tsx
@@ -84,7 +84,7 @@ const RangeSelector: FC<Props> = ({ isCustomRange, ranges, onSelect }) => {
</SelectValue>
</SelectTrigger>
<SelectPortal>
- <SelectPositioner className="-translate-x-6">
+ <SelectPositioner>
<SelectPopup className="w-50">
<SelectList className="p-1">
{items.map((item) => (
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsx
index 56986414930..7b8315f4703 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsx
@@ -1,104 +1,376 @@
-import type { ComponentProps, ReactNode } from 'react'
-import { render, screen, waitFor } from '@testing-library/react'
-import { fetchTracingConfig, fetchTracingStatus, updateTracingStatus } from '@/service/apps'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { consoleQuery } from '@/service/console'
+import { createQueryClientWrapper } from '@/test/console/query-client'
+import { createTestQueryClient } from '@/test/query-client'
import Panel from '../panel'
-const testState = vi.hoisted(() => ({
- configButtonProps: [] as Array<{
- readOnly: boolean
- hasConfigured: boolean
- }>,
+const { request } = vi.hoisted(() => ({
+ request:
+ vi.fn<(url: string, init: RequestInit, options: { request: Request }) => Promise<Response>>(),
}))
+vi.mock('@/service/base', () => ({ request }))
+vi.mock('@/app/notifications', () => ({ toast: vi.fn() }))
-vi.mock('@/service/apps', () => ({
- fetchTracingStatus: vi.fn(),
- fetchTracingConfig: vi.fn(),
- updateTracingStatus: vi.fn(),
-}))
-
-vi.mock('@/app/notifications', () => ({
- toast: vi.fn(),
-}))
-
-vi.mock('@langgenius/dify-ui/status-dot', () => ({
- StatusDot: ({ status }: { status: string }) => <span data-testid="status-dot">{status}</span>,
-}))
-
-vi.mock('../config-button', () => ({
- default: ({
- children,
- ...props
- }: ComponentProps<'div'> & {
- readOnly: boolean
- hasConfigured: boolean
- children?: ReactNode
- }) => {
- testState.configButtonProps.push({
- readOnly: props.readOnly,
- hasConfigured: props.hasConfigured,
- })
+const langfuseConfig = {
+ public_key: 'public-key',
+ secret_key: '[__MASKED__]',
+ host: 'https://cloud.langfuse.com',
+}
- return (
- <div
- data-testid="config-button"
- data-read-only={String(props.readOnly)}
- data-has-configured={String(props.hasConfigured)}
- >
- {children}
- </div>
- )
- },
-}))
+function mockServer(configured = true) {
+ let status = { enabled: configured, tracing_provider: configured ? 'langfuse' : null }
+ let config: Record<string, unknown> | null = configured ? langfuseConfig : null
+ const writes: Array<{ method: string; body: unknown }> = []
+ request.mockImplementation(async (_url, _init, { request: sent }) => {
+ const url = new URL(sent.url)
+ if (url.pathname.endsWith('/trace')) {
+ if (sent.method === 'POST') {
+ status = await sent.json()
+ writes.push({ method: sent.method, body: status })
+ return Response.json({ result: 'success' })
+ }
+ return Response.json(status)
+ }
+ if (sent.method === 'GET') {
+ const providerConfig = url.searchParams.get('tracing_provider') === 'langfuse' ? config : null
+ return Response.json({ tracing_config: providerConfig, has_not_configured: !providerConfig })
+ }
+ if (sent.method === 'DELETE') {
+ config = null
+ writes.push({ method: sent.method, body: null })
+ return new Response(null, { status: 204 })
+ }
+ const body = await sent.json()
+ writes.push({ method: sent.method, body })
+ config = { ...body.tracing_config, secret_key: '[__MASKED__]' }
+ return Response.json({ result: 'success' })
+ })
+ return writes
+}
-const mockedFetchTracingStatus = vi.mocked(fetchTracingStatus)
-const mockedFetchTracingConfig = vi.mocked(fetchTracingConfig)
-const mockedUpdateTracingStatus = vi.mocked(updateTracingStatus)
+function renderPanel(readOnly = false) {
+ const client = createTestQueryClient()
+ const view = render(<Panel appId="app-1" readOnly={readOnly} />, {
+ wrapper: createQueryClientWrapper(client),
+ })
+ return { ...view, client }
+}
-const renderPanel = async (readOnly = true) => {
- render(<Panel appId="app-1" readOnly={readOnly} />)
- await screen.findAllByTestId('config-button')
+async function openConfiguredPanel() {
+ const user = userEvent.setup()
+ await user.click(await screen.findByText('app.tracing.enabled'))
+ await screen.findByText('app.tracing.tracing')
+ return user
}
describe('Tracing overview panel', () => {
beforeEach(() => {
- testState.configButtonProps = []
- mockedFetchTracingStatus.mockResolvedValue({
- enabled: false,
- tracing_provider: null,
- })
- mockedFetchTracingConfig.mockResolvedValue({
- tracing_provider: 'langfuse',
- tracing_config: {},
- has_not_configured: true,
- } as Awaited<ReturnType<typeof fetchTracingConfig>>)
- mockedUpdateTracingStatus.mockResolvedValue({
- result: 'success',
- })
+ vi.clearAllMocks()
})
- afterEach(() => {
- vi.clearAllMocks()
+ it('keeps the tracing entry visible and disabled until configuration is ready', async () => {
+ request.mockImplementation(() => new Promise<Response>(() => {}))
+ renderPanel()
+ expect(screen.getByRole('button', { name: 'app.tracing.title' })).toBeDisabled()
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
- it('marks tracing config as read-only when requested by its owner', async () => {
- await renderPanel()
+ it('offers retry when tracing cannot load instead of remaining in a loading state', async () => {
+ request.mockRejectedValue(new Error('Tracing unavailable'))
+ renderPanel()
+ const retry = await screen.findByRole('button', { name: /common.errorBoundary.tryAgain/ })
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ mockServer(false)
+ await userEvent.setup().click(retry)
+ expect(await screen.findByText('app.tracing.title')).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: /common.errorBoundary.tryAgain/ }),
+ ).not.toBeInTheDocument()
+ })
- await waitFor(() => {
- expect(testState.configButtonProps[0]).toMatchObject({
- readOnly: true,
- hasConfigured: false,
- })
+ it('keeps one disabled entry when status arrives before provider configurations', async () => {
+ mockServer()
+ const server = request.getMockImplementation()!
+ let resolveConfigs!: () => void
+ const configsReady = new Promise<void>((resolve) => {
+ resolveConfigs = resolve
+ })
+ request.mockImplementation(async (...args) => {
+ if (new URL(args[2].request.url).pathname.endsWith('/trace-config')) await configsReady
+ return server(...args)
})
+ const { client } = renderPanel()
+ await waitFor(() =>
+ expect(
+ client.getQueryData(
+ consoleQuery.apps.byAppId.trace.get.queryKey({ input: { params: { app_id: 'app-1' } } }),
+ ),
+ ).toEqual({ enabled: true, tracing_provider: 'langfuse' }),
+ )
+ expect(screen.getByRole('button')).toBeDisabled()
+ resolveConfigs()
+ await waitFor(() => expect(screen.getByRole('button')).toBeEnabled())
})
- it('allows tracing config when the owner grants write access', async () => {
- await renderPanel(false)
+ it('keeps healthy providers usable and retries only the unavailable provider', async () => {
+ const writes = mockServer()
+ const server = request.getMockImplementation()!
+ let unavailable = true
+ let resolveRetry!: () => void
+ const retryReady = new Promise<void>((resolve) => {
+ resolveRetry = resolve
+ })
+ request.mockImplementation(async (...args) => {
+ const url = new URL(args[2].request.url)
+ if (url.searchParams.get('tracing_provider') === 'langsmith')
+ return Response.json({ tracing_config: { api_key: 'key', project: 'project' } })
+ if (url.searchParams.get('tracing_provider') === 'phoenix') {
+ if (unavailable)
+ return Response.json(
+ { code: 'tracing_provider_unavailable', message: 'Unavailable' },
+ { status: 400 },
+ )
+ await retryReady
+ }
+ return server(...args)
+ })
+ const { client } = renderPanel()
+ await waitFor(() => expect(client.isFetching()).toBe(0))
+ const user = await openConfiguredPanel()
+ const phoenix = within(screen.getByRole('group', { name: 'app.tracing.phoenix.title' }))
+ expect(phoenix.queryByRole('button', { name: 'app.tracing.config' })).not.toBeInTheDocument()
+ expect(
+ phoenix.queryByRole('button', { name: 'app.tracing.phoenix.title' }),
+ ).not.toBeInTheDocument()
+ await user.click(screen.getByRole('switch'))
+ await waitFor(() => expect(screen.getByRole('switch')).not.toBeChecked())
+ expect(writes).toEqual([
+ { method: 'POST', body: { enabled: false, tracing_provider: 'langfuse' } },
+ ])
+ await user.click(screen.getByRole('button', { name: 'app.tracing.langsmith.title' }))
+ await waitFor(() => expect(screen.getByRole('switch')).toBeChecked())
+ expect(writes[1]).toEqual({
+ method: 'POST',
+ body: { enabled: true, tracing_provider: 'langsmith' },
+ })
- await waitFor(() => {
- expect(testState.configButtonProps[0]).toMatchObject({
- readOnly: false,
- hasConfigured: false,
- })
+ request.mockClear()
+ unavailable = false
+ await user.click(phoenix.getByRole('button', { name: 'common.errorBoundary.tryAgain' }))
+ expect(phoenix.getByRole('button', { name: 'common.errorBoundary.tryAgain' })).toBeDisabled()
+ expect(phoenix.queryByRole('button', { name: 'app.tracing.config' })).not.toBeInTheDocument()
+ expect(screen.getByRole('switch')).not.toHaveAttribute('aria-disabled', 'true')
+ resolveRetry()
+ expect(await phoenix.findByRole('button', { name: 'app.tracing.config' })).toBeEnabled()
+ expect(request).toHaveBeenCalledTimes(1)
+ expect(
+ new URL(request.mock.calls[0]![2].request.url).searchParams.get('tracing_provider'),
+ ).toBe('phoenix')
+ })
+
+ it('allows disabling tracing when its active provider configuration is unavailable', async () => {
+ const writes = mockServer()
+ const server = request.getMockImplementation()!
+ request.mockImplementation(async (...args) => {
+ if (new URL(args[2].request.url).searchParams.get('tracing_provider') === 'langfuse')
+ return Response.json(
+ { code: 'tracing_provider_unavailable', message: 'Unavailable' },
+ { status: 400 },
+ )
+ return server(...args)
})
+ const { client } = renderPanel()
+ await waitFor(() => expect(client.isFetching()).toBe(0))
+ const user = await openConfiguredPanel()
+ await user.click(screen.getByRole('switch'))
+ await waitFor(() => expect(screen.getByRole('switch')).not.toBeChecked())
+ expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
+ await user.click(screen.getByRole('switch'))
+ expect(writes).toEqual([
+ { method: 'POST', body: { enabled: false, tracing_provider: 'langfuse' } },
+ ])
+ })
+
+ it('shows one entry and requires a provider selection when saved configs have no active provider', async () => {
+ const writes = mockServer()
+ const { client } = renderPanel()
+ await waitFor(() => expect(client.isFetching()).toBe(0))
+ act(() =>
+ client.setQueryData(
+ consoleQuery.apps.byAppId.trace.get.queryKey({ input: { params: { app_id: 'app-1' } } }),
+ { enabled: false, tracing_provider: null },
+ ),
+ )
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button'))
+ expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
+ await user.click(screen.getByRole('button', { name: 'app.tracing.langfuse.title' }))
+ await waitFor(() => expect(screen.getByRole('switch')).toBeChecked())
+ expect(writes).toEqual([
+ { method: 'POST', body: { enabled: true, tracing_provider: 'langfuse' } },
+ ])
+ })
+
+ it('hides configuration for a read-only app with no providers', async () => {
+ mockServer(false)
+ const { client } = renderPanel(true)
+ await waitFor(() => expect(client.isFetching()).toBe(0))
+ expect(screen.queryByText('app.tracing.title')).not.toBeInTheDocument()
+ })
+
+ it('lets a read-only user inspect configured tracing without editing it', async () => {
+ mockServer()
+ renderPanel(true)
+ await openConfiguredPanel()
+ expect(screen.getByText('app.tracing.langfuse.description')).toBeInTheDocument()
+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()
+ expect(screen.queryByText('app.tracing.config')).not.toBeInTheDocument()
+ })
+
+ it('refreshes status after toggling without changing the selected provider', async () => {
+ const writes = mockServer()
+ renderPanel()
+ const user = await openConfiguredPanel()
+ await user.click(screen.getByRole('switch'))
+ await waitFor(() => expect(screen.getByRole('switch')).not.toBeChecked())
+ expect(writes).toEqual([
+ { method: 'POST', body: { enabled: false, tracing_provider: 'langfuse' } },
+ ])
+ })
+
+ it('opens configuration without selecting the provider and supports keyboard selection', async () => {
+ const writes = mockServer()
+ const { client } = renderPanel()
+ await waitFor(() => expect(client.isFetching()).toBe(0))
+ act(() =>
+ client.setQueryData(
+ consoleQuery.apps.byAppId.trace.get.queryKey({ input: { params: { app_id: 'app-1' } } }),
+ { enabled: true, tracing_provider: 'langsmith' },
+ ),
+ )
+ const user = await openConfiguredPanel()
+ const provider = within(screen.getByRole('group', { name: 'app.tracing.langfuse.title' }))
+ await user.click(provider.getByRole('button', { name: 'app.tracing.config' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() =>
+ expect(provider.getByRole('button', { name: 'app.tracing.config' })).toHaveFocus(),
+ )
+ expect(writes).toEqual([])
+
+ await user.tab({ shift: true })
+ await expect(provider.getByRole('button', { name: 'app.tracing.langfuse.title' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ await waitFor(() =>
+ expect(writes).toEqual([
+ { method: 'POST', body: { enabled: true, tracing_provider: 'langfuse' } },
+ ]),
+ )
+ })
+
+ it('saves a new provider before enabling it', async () => {
+ const writes = mockServer(false)
+ renderPanel()
+ const user = userEvent.setup()
+ await user.click(await screen.findByText('app.tracing.title'))
+ await user.click(screen.getAllByText('app.tracing.config')[0]!)
+ await user.type(
+ screen.getByRole('textbox', { name: 'app.tracing.configProvider.publicKey' }),
+ 'public-key',
+ )
+ await user.type(
+ screen.getByRole('textbox', { name: 'app.tracing.configProvider.secretKey' }),
+ 'secret-key',
+ )
+ await user.type(screen.getByRole('textbox', { name: 'Host' }), 'https://cloud.langfuse.com')
+ await user.click(screen.getByRole('button', { name: 'common.operation.saveAndEnable' }))
+ await waitFor(() =>
+ expect(writes).toEqual([
+ {
+ method: 'POST',
+ body: {
+ tracing_provider: 'langfuse',
+ tracing_config: { ...langfuseConfig, secret_key: 'secret-key' },
+ },
+ },
+ { method: 'POST', body: { enabled: true, tracing_provider: 'langfuse' } },
+ ]),
+ )
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: /app.tracing.configProvider.title/ }),
+ ).not.toBeInTheDocument(),
+ )
+ expect(screen.getByRole('switch')).toBeChecked()
+ })
+
+ it('reopens an edited provider from the refreshed masked config', async () => {
+ const writes = mockServer()
+ const { client } = renderPanel()
+ const user = await openConfiguredPanel()
+ await user.click(screen.getAllByText('app.tracing.config')[0]!)
+ const secret = screen.getByRole('textbox', { name: 'app.tracing.configProvider.secretKey' })
+ await user.clear(secret)
+ await user.type(secret, 'new-secret')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.save' }),
+ ).not.toBeInTheDocument(),
+ )
+ await waitFor(() => expect(client.isFetching()).toBe(0))
+ await user.click(screen.getAllByText('app.tracing.config')[0]!)
+ expect(
+ screen.getByRole('textbox', { name: 'app.tracing.configProvider.secretKey' }),
+ ).toHaveValue('[__MASKED__]')
+ expect(writes).toEqual([
+ {
+ method: 'PATCH',
+ body: {
+ tracing_provider: 'langfuse',
+ tracing_config: { ...langfuseConfig, secret_key: 'new-secret' },
+ },
+ },
+ ])
+ })
+
+ it('disables tracing after deleting the last selected provider', async () => {
+ const writes = mockServer()
+ renderPanel()
+ const user = await openConfiguredPanel()
+ await user.click(screen.getAllByText('app.tracing.config')[0]!)
+ await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() =>
+ expect(writes).toEqual([
+ { method: 'DELETE', body: null },
+ { method: 'POST', body: { enabled: false, tracing_provider: null } },
+ ]),
+ )
+ expect(await screen.findByText('app.tracing.title')).toBeInTheDocument()
+ })
+
+ it('keeps an open draft across config refreshes and starts a new session for another app', async () => {
+ mockServer()
+ const { client, rerender } = renderPanel()
+ const user = await openConfiguredPanel()
+ await user.click(screen.getAllByText('app.tracing.config')[0]!)
+ const host = screen.getByRole('textbox', { name: 'Host' })
+ await user.clear(host)
+ await user.type(host, 'https://draft.langfuse.com')
+ act(() =>
+ client.setQueryData(
+ consoleQuery.apps.byAppId.traceConfig.get.queryKey({
+ input: { params: { app_id: 'app-1' }, query: { tracing_provider: 'langfuse' } },
+ }),
+ { tracing_config: { ...langfuseConfig, host: 'https://server.langfuse.com' } },
+ ),
+ )
+ expect(host).toHaveValue('https://draft.langfuse.com')
+ rerender(<Panel appId="app-2" readOnly={false} />)
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await openConfiguredPanel()
+ await user.click(screen.getAllByText('app.tracing.config')[0]!)
+ expect(screen.getByRole('textbox', { name: 'Host' })).toHaveValue(langfuseConfig.host)
})
})
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/provider-config-modal.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/provider-config-modal.spec.tsx
index c9adb3a699f..1c37216c8b2 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/provider-config-modal.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/provider-config-modal.spec.tsx
@@ -1,45 +1,35 @@
-import type {
- AliyunConfig,
- ArizeConfig,
- DatabricksConfig,
- LangFuseConfig,
- LangSmithConfig,
- MLflowConfig,
- OpikConfig,
- PhoenixConfig,
- TencentConfig,
- WeaveConfig,
-} from '../type'
+import type { TraceConfigPayload } from '@dify/contracts/api/console/apps/types.gen'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createRef } from 'react'
import { toast } from '@/app/notifications'
-import { addTracingConfig, removeTracingConfig, updateTracingConfig } from '@/service/apps'
+import { httpErrorFromResponse } from '@/service/http-error'
+import { createQueryClientWrapper } from '@/test/console/query-client'
+import { createTestQueryClient } from '@/test/query-client'
import ConfigBtn from '../config-button'
import ProviderConfigModal from '../provider-config-modal'
import { TracingProvider } from '../type'
-vi.mock('@/service/apps', () => ({
- addTracingConfig: vi.fn(),
- removeTracingConfig: vi.fn(),
- updateTracingConfig: vi.fn(),
+const { request } = vi.hoisted(() => ({
+ request:
+ vi.fn<(url: string, init: RequestInit, options: { request: Request }) => Promise<Response>>(),
}))
+vi.mock('@/service/base', () => ({ request }))
+
+const expectRequest = async (method: string, body?: unknown) => {
+ expect(request).toHaveBeenCalledOnce()
+ const sent = request.mock.calls[0]![2].request
+ expect(sent.method).toBe(method)
+ expect(new URL(sent.url).pathname).toMatch(/\/apps\/app-id\/trace-config$/)
+ if (body) expect(await sent.clone().json()).toEqual(body)
+ else expect(new URL(sent.url).searchParams.get('tracing_provider')).toBe(TracingProvider.langfuse)
+}
vi.mock('@/app/notifications', () => ({
toast: vi.fn(),
}))
-type ProviderPayload =
- | AliyunConfig
- | ArizeConfig
- | DatabricksConfig
- | LangFuseConfig
- | LangSmithConfig
- | MLflowConfig
- | OpikConfig
- | PhoenixConfig
- | TencentConfig
- | WeaveConfig
-
const validConfigs = {
[TracingProvider.arize]: {
api_key: 'arize-api-key',
@@ -82,12 +72,12 @@ const validConfigs = {
},
[TracingProvider.mlflow]: {
tracking_uri: 'http://localhost:5000',
- experiment_id: 'experiment-id',
+ experiment_id: '123',
username: 'mlflow-user',
password: 'mlflow-password',
},
[TracingProvider.databricks]: {
- experiment_id: 'experiment-id',
+ experiment_id: '123',
host: 'https://workspace.cloud.databricks.com',
client_id: 'client-id',
client_secret: 'client-secret',
@@ -98,7 +88,7 @@ const validConfigs = {
endpoint: 'https://your-region.cls.tencentcs.com',
service_name: 'dify_app',
},
-} satisfies Record<TracingProvider, ProviderPayload>
+} satisfies Record<TracingProvider, TraceConfigPayload['tracing_config']>
const providerFieldLabels = [
[
@@ -141,7 +131,7 @@ const providerFieldLabels = [
const invalidConfigCases: Array<{
provider: TracingProvider
- payload: ProviderPayload
+ payload: TraceConfigPayload['tracing_config']
missingField: string
}> = [
{
@@ -222,17 +212,17 @@ const invalidConfigCases: Array<{
{
provider: TracingProvider.mlflow,
payload: { ...validConfigs[TracingProvider.mlflow], tracking_uri: '' },
- missingField: 'Tracking URI',
+ missingField: 'app.tracing.configProvider.trackingUri',
},
{
provider: TracingProvider.databricks,
payload: { ...validConfigs[TracingProvider.databricks], experiment_id: '' },
- missingField: 'Experiment ID',
+ missingField: 'app.tracing.configProvider.experimentId',
},
{
provider: TracingProvider.databricks,
payload: { ...validConfigs[TracingProvider.databricks], host: '' },
- missingField: 'Host',
+ missingField: 'app.tracing.configProvider.databricksHost',
},
{
provider: TracingProvider.tencent,
@@ -271,11 +261,11 @@ const renderConfigButton = () => {
mlflowConfig={null}
databricksConfig={null}
tencentConfig={null}
- onConfigUpdated={vi.fn()}
onConfigRemoved={vi.fn()}
>
- <button type="button">Open tracing</button>
+ Open tracing
</ConfigBtn>,
+ { wrapper: createQueryClientWrapper(createTestQueryClient()) },
)
}
@@ -284,7 +274,7 @@ const renderProviderConfigModal = ({
payload,
}: {
type?: TracingProvider
- payload?: ProviderPayload | null
+ payload?: TraceConfigPayload['tracing_config'] | null
} = {}) => {
const callbacks = {
onCancel: vi.fn(),
@@ -293,16 +283,28 @@ const renderProviderConfigModal = ({
onRemoved: vi.fn(),
}
+ const firstInputRef = createRef<HTMLInputElement>()
render(
- <ProviderConfigModal
- appId="app-id"
- type={type}
- payload={payload}
- onCancel={callbacks.onCancel}
- onSaved={callbacks.onSaved}
- onChosen={callbacks.onChosen}
- onRemoved={callbacks.onRemoved}
- />,
+ <Dialog
+ defaultOpen
+ disablePointerDismissal
+ onOpenChangeComplete={(open) => {
+ if (!open) callbacks.onCancel()
+ }}
+ >
+ <DialogContent initialFocus={firstInputRef}>
+ <ProviderConfigModal
+ appId="app-id"
+ type={type}
+ payload={payload}
+ firstInputRef={firstInputRef}
+ onSaved={callbacks.onSaved}
+ onChosen={callbacks.onChosen}
+ onRemoved={callbacks.onRemoved}
+ />
+ </DialogContent>
+ </Dialog>,
+ { wrapper: createQueryClientWrapper(createTestQueryClient()) },
)
return callbacks
@@ -311,13 +313,15 @@ const renderProviderConfigModal = ({
describe('ProviderConfigModal', () => {
beforeEach(() => {
vi.clearAllMocks()
- vi.mocked(addTracingConfig).mockResolvedValue({ result: 'success' })
- vi.mocked(updateTracingConfig).mockResolvedValue({ result: 'success' })
- vi.mocked(removeTracingConfig).mockResolvedValue({ result: 'success' })
+ request.mockImplementation(async (_url, _init, { request: sent }) =>
+ sent.method === 'DELETE'
+ ? new Response(null, { status: 204 })
+ : Response.json({ result: 'success' }),
+ )
})
describe('Nested Overlay Behavior', () => {
- it('should keep the provider config modal open when clicking inside it', async () => {
+ it('keeps the provider list open and starts a fresh draft after closing the dialog', async () => {
const user = userEvent.setup()
renderConfigButton()
@@ -336,19 +340,27 @@ describe('ProviderConfigModal', () => {
})
expect(screen.getByRole('dialog')).toBeInTheDocument()
- await user.click(screen.getByPlaceholderText('https://cloud.langfuse.com'))
-
+ const host = screen.getByRole('textbox', { name: 'Host' })
+ await user.clear(host)
+ await user.type(host, 'https://draft.langfuse.com')
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.close' }),
+ ).not.toBeInTheDocument(),
+ )
expect(screen.getByText('app.tracing.tracing')).toBeInTheDocument()
- expect(
- screen.getByText('app.tracing.configProvider.titleapp.tracing.langfuse.title'),
- ).toBeInTheDocument()
+ const configButton = screen.getAllByRole('button', { name: 'app.tracing.config' })[0]!
+ await waitFor(() => expect(configButton).toHaveFocus())
+ await user.click(configButton)
+ expect(screen.getByRole('textbox', { name: 'Host' })).toHaveValue('')
})
})
describe('Rendering', () => {
it.each(providerFieldLabels)(
'should render %s fields when adding a provider',
- (provider, expectedLabels) => {
+ async (provider, expectedLabels) => {
renderProviderConfigModal({ type: provider })
expect(
@@ -357,6 +369,9 @@ describe('ProviderConfigModal', () => {
expectedLabels.forEach((label) => {
expect(screen.getByRole('textbox', { name: label })).toBeInTheDocument()
})
+ await waitFor(() =>
+ expect(screen.getByRole('textbox', { name: expectedLabels[0] })).toHaveFocus(),
+ )
expect(
screen.getByRole('button', { name: 'common.operation.saveAndEnable' }),
).toBeInTheDocument()
@@ -365,7 +380,7 @@ describe('ProviderConfigModal', () => {
})
describe('Saving', () => {
- it('should add and choose the provider when saving a new config', async () => {
+ it('submits a new config with Enter and chooses the provider', async () => {
const user = userEvent.setup()
const callbacks = renderProviderConfigModal({ type: TracingProvider.langfuse })
@@ -378,20 +393,15 @@ describe('ProviderConfigModal', () => {
'public-key',
)
await user.type(screen.getByRole('textbox', { name: 'Host' }), 'https://cloud.langfuse.com')
- await user.click(screen.getByRole('button', { name: 'common.operation.saveAndEnable' }))
+ await user.keyboard('{Enter}')
- await waitFor(() => {
- expect(addTracingConfig).toHaveBeenCalledWith({
- appId: 'app-id',
- body: {
- tracing_provider: TracingProvider.langfuse,
- tracing_config: validConfigs[TracingProvider.langfuse],
- },
- })
+ await waitFor(() => expect(callbacks.onSaved).toHaveBeenCalledOnce())
+ await expectRequest('POST', {
+ tracing_provider: TracingProvider.langfuse,
+ tracing_config: validConfigs[TracingProvider.langfuse],
})
- expect(callbacks.onSaved).toHaveBeenCalledWith(validConfigs[TracingProvider.langfuse])
expect(callbacks.onChosen).toHaveBeenCalledWith(TracingProvider.langfuse)
- expect(toast).toHaveBeenCalledWith('common.api.success', { type: 'success' })
+ expect(toast).not.toHaveBeenCalled()
})
it.each(Object.values(TracingProvider))(
@@ -405,20 +415,139 @@ describe('ProviderConfigModal', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- await waitFor(() => {
- expect(updateTracingConfig).toHaveBeenCalledWith({
- appId: 'app-id',
- body: {
- tracing_provider: provider,
- tracing_config: validConfigs[provider],
- },
- })
+ await waitFor(() => expect(callbacks.onSaved).toHaveBeenCalledOnce())
+ await expectRequest('PATCH', {
+ tracing_provider: provider,
+ tracing_config: validConfigs[provider],
})
- expect(callbacks.onSaved).toHaveBeenCalledWith(validConfigs[provider])
expect(callbacks.onChosen).not.toHaveBeenCalled()
},
)
+ it.each([
+ [TracingProvider.langfuse, 'host', 'HTTPS://cloud.langfuse.com'],
+ [TracingProvider.langSmith, 'endpoint', 'HTTPS://api.smith.langchain.com'],
+ [TracingProvider.opik, 'url', 'HTTPS://www.comet.com/opik/api/'],
+ ] as const)('accepts case-insensitive URL schemes for %s', async (provider, key, value) => {
+ const user = userEvent.setup()
+ const payload = { ...validConfigs[provider], [key]: value }
+ const callbacks = renderProviderConfigModal({ type: provider, payload })
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ await waitFor(() => expect(callbacks.onSaved).toHaveBeenCalledOnce())
+ await expectRequest('PATCH', { tracing_provider: provider, tracing_config: payload })
+ })
+
+ it('displays nullable provider fields as empty without changing their submitted values', async () => {
+ const user = userEvent.setup()
+ const payload = { ...validConfigs[TracingProvider.mlflow], username: null }
+ const callbacks = renderProviderConfigModal({ type: TracingProvider.mlflow, payload })
+
+ expect(
+ screen.getByRole('textbox', { name: 'app.tracing.configProvider.username' }),
+ ).toHaveValue('')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ await waitFor(() => expect(callbacks.onSaved).toHaveBeenCalledOnce())
+ await expectRequest('PATCH', {
+ tracing_provider: TracingProvider.mlflow,
+ tracing_config: payload,
+ })
+ })
+
+ it('keeps the draft on failure, prevents duplicate saves while pending, and allows retry', async () => {
+ const user = userEvent.setup()
+ let resolveResponse!: (response: Response) => void
+ request.mockReturnValueOnce(
+ new Promise<Response>((resolve) => {
+ resolveResponse = resolve
+ }).then(async (response) => {
+ if (!response.ok) throw await httpErrorFromResponse(response)
+ return response
+ }),
+ )
+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const callbacks = renderProviderConfigModal({
+ payload: validConfigs[TracingProvider.langfuse],
+ })
+ const host = screen.getByRole('textbox', { name: 'Host' })
+ await user.clear(host)
+ await user.type(host, 'https://draft.langfuse.com')
+ const save = screen.getByRole('button', { name: 'common.operation.save' })
+
+ try {
+ await user.click(save)
+ await waitFor(() => expect(save).toHaveAttribute('aria-disabled', 'true'))
+ for (const input of screen.getAllByRole('textbox')) expect(input).toBeDisabled()
+ await user.type(host, '/unsaved')
+ expect(host).toHaveValue('https://draft.langfuse.com')
+ await user.click(save)
+ await waitFor(() => expect(request).toHaveBeenCalledOnce())
+ resolveResponse(Response.json({ message: 'Config rejected' }, { status: 400 }))
+
+ await waitFor(() => expect(save).not.toHaveAttribute('aria-disabled', 'true'))
+ for (const input of screen.getAllByRole('textbox')) expect(input).toBeEnabled()
+ expect(host).toHaveValue('https://draft.langfuse.com')
+ expect(screen.getByRole('alert')).toHaveTextContent('Config rejected')
+ expect(request.mock.calls[0]![2]).toMatchObject({ silent: true })
+ expect(toast).not.toHaveBeenCalled()
+ expect(callbacks.onSaved).not.toHaveBeenCalled()
+ expect(callbacks.onChosen).not.toHaveBeenCalled()
+
+ await user.click(save)
+ await waitFor(() => expect(callbacks.onSaved).toHaveBeenCalledOnce())
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ } finally {
+ logError.mockRestore()
+ }
+ })
+
+ it.each([
+ [TracingProvider.langfuse, 'host', 'Host', 'ftp://cloud.langfuse.com'],
+ [TracingProvider.langSmith, 'endpoint', 'Endpoint', 'http://api.smith.langchain.com'],
+ [TracingProvider.weave, 'endpoint', 'Endpoint', 'http://trace.wandb.ai'],
+ [TracingProvider.opik, 'url', 'Url', 'https://www.comet.com/opik/'],
+ [TracingProvider.mlflow, 'experiment_id', 'app.tracing.configProvider.experimentId', '1.5'],
+ [
+ TracingProvider.databricks,
+ 'experiment_id',
+ 'app.tracing.configProvider.experimentId',
+ '-1',
+ ],
+ [TracingProvider.aliyun, 'license_key', 'License Key', ' '],
+ [TracingProvider.tencent, 'token', 'Token', ' '],
+ ] as const)(
+ 'validates %s %s inline before sending credentials',
+ async (provider, key, label, value) => {
+ const user = userEvent.setup()
+ const callbacks = renderProviderConfigModal({
+ type: provider,
+ payload: { ...validConfigs[provider], [key]: value },
+ })
+ const field = screen.getByRole('textbox', { name: label })
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(request).not.toHaveBeenCalled()
+ expect(field).toBeInvalid()
+ expect(field).toHaveFocus()
+ expect(field).toHaveAccessibleDescription()
+
+ await user.clear(field)
+ const validConfig: TraceConfigPayload['tracing_config'] = validConfigs[provider]
+ await user.type(field, validConfig[key] ?? '')
+ await user.keyboard('{Enter}')
+
+ await waitFor(() => expect(callbacks.onSaved).toHaveBeenCalledOnce())
+ expect(field).toBeValid()
+ await expectRequest('PATCH', {
+ tracing_provider: provider,
+ tracing_config: validConfigs[provider],
+ })
+ },
+ )
+
it.each(invalidConfigCases)(
'should reject $provider config when $missingField is missing',
async ({ provider, payload, missingField }) => {
@@ -430,18 +559,22 @@ describe('ProviderConfigModal', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(updateTracingConfig).not.toHaveBeenCalled()
- expect(toast).toHaveBeenCalledWith(expect.stringContaining(missingField), { type: 'error' })
+ expect(request).not.toHaveBeenCalled()
+ const field = screen.getByRole('textbox', { name: missingField })
+ expect(field).toBeInvalid()
+ expect(field).toHaveFocus()
+ expect(field).toHaveAccessibleDescription()
+ expect(toast).not.toHaveBeenCalled()
},
)
})
describe('Closing And Removing', () => {
- it('should cancel when the cancel button is clicked', async () => {
+ it.each(['cancel', 'close'])('should dismiss when the %s button is clicked', async (action) => {
const user = userEvent.setup()
const callbacks = renderProviderConfigModal()
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await user.click(screen.getByRole('button', { name: `common.operation.${action}` }))
expect(callbacks.onCancel).toHaveBeenCalledTimes(1)
})
@@ -473,27 +606,30 @@ describe('ProviderConfigModal', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
- await waitFor(() => {
- expect(removeTracingConfig).toHaveBeenCalledWith({
- appId: 'app-id',
- provider: TracingProvider.langfuse,
- })
- })
- expect(callbacks.onRemoved).toHaveBeenCalledTimes(1)
- expect(toast).toHaveBeenCalledWith('common.api.remove', { type: 'success' })
+ await waitFor(() => expect(callbacks.onRemoved).toHaveBeenCalledOnce())
+ await expectRequest('DELETE')
+ expect(toast).not.toHaveBeenCalled()
})
- it('should return to the edit dialog when remove confirmation is canceled', async () => {
+ it('keeps the draft and returns focus to Remove when confirmation is canceled', async () => {
const user = userEvent.setup()
renderProviderConfigModal({
type: TracingProvider.langfuse,
payload: validConfigs[TracingProvider.langfuse],
})
+ const host = screen.getByRole('textbox', { name: 'Host' })
+ await user.clear(host)
+ await user.type(host, 'https://draft.langfuse.com')
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- expect(removeTracingConfig).not.toHaveBeenCalled()
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(host).toHaveValue('https://draft.langfuse.com')
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'common.operation.remove' })).toHaveFocus(),
+ )
+ expect(request).not.toHaveBeenCalled()
expect(
screen.getByText('app.tracing.configProvider.titleapp.tracing.langfuse.title'),
).toBeInTheDocument()
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-button.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-button.tsx
index 8b99b88d776..8bf0e632e61 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-button.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-button.tsx
@@ -1,6 +1,7 @@
'use client'
import type { FC } from 'react'
import type { PopupProps } from './config-popup'
+import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import * as React from 'react'
@@ -10,16 +11,35 @@ type Props = Readonly<{
readOnly: boolean
className?: string
hasConfigured: boolean
+ disabled?: boolean
children?: React.ReactNode
}> &
PopupProps
-const ConfigBtn: FC<Props> = ({ className, hasConfigured, children, ...popupProps }) => {
+const ConfigBtn: FC<Props> = ({
+ className,
+ hasConfigured,
+ disabled = false,
+ children,
+ ...popupProps
+}) => {
if (popupProps.readOnly && !hasConfigured) return null
return (
<Popover>
- <PopoverTrigger render={<div className={cn('select-none', className)}>{children}</div>} />
+ <PopoverTrigger
+ disabled={disabled}
+ render={
+ <Button
+ className={cn(
+ 'h-auto gap-0 rounded-xl border-components-panel-border bg-background-default-dodge p-2 hover:bg-background-default-lighter',
+ className,
+ )}
+ />
+ }
+ >
+ {children}
+ </PopoverTrigger>
<PopoverContent
placement="bottom-end"
sideOffset={12}
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-popup.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-popup.tsx
index e9a07e787a8..f6d6425a28c 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-popup.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/config-popup.tsx
@@ -1,25 +1,16 @@
'use client'
+import type { TraceAppConfigResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
import type { FC, JSX } from 'react'
-import type {
- AliyunConfig,
- ArizeConfig,
- DatabricksConfig,
- LangFuseConfig,
- LangSmithConfig,
- MLflowConfig,
- OpikConfig,
- PhoenixConfig,
- TencentConfig,
- WeaveConfig,
-} from './type'
+import type { ProviderConfigError } from './provider-panel'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { Separator } from '@langgenius/dify-ui/separator'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { Switch } from '@langgenius/dify-ui/switch'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { useBoolean } from 'ahooks'
import * as React from 'react'
-import { useCallback, useState } from 'react'
+import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import ProviderConfigModal from './provider-config-modal'
import ProviderPanel from './provider-panel'
@@ -30,40 +21,29 @@ const I18N_PREFIX = 'tracing'
export type PopupProps = {
appId: string
+ configErrors?: Partial<Record<TracingProvider, ProviderConfigError>>
+ onConfigRemoved: (provider: TracingProvider) => void
readOnly: boolean
enabled: boolean
onStatusChange: (enabled: boolean) => void
chosenProvider: TracingProvider | null
onChooseProvider: (provider: TracingProvider) => void
- arizeConfig: ArizeConfig | null
- phoenixConfig: PhoenixConfig | null
- langSmithConfig: LangSmithConfig | null
- langFuseConfig: LangFuseConfig | null
- opikConfig: OpikConfig | null
- weaveConfig: WeaveConfig | null
- aliyunConfig: AliyunConfig | null
- mlflowConfig: MLflowConfig | null
- databricksConfig: DatabricksConfig | null
- tencentConfig: TencentConfig | null
- onConfigUpdated: (
- provider: TracingProvider,
- payload:
- | ArizeConfig
- | PhoenixConfig
- | LangSmithConfig
- | LangFuseConfig
- | OpikConfig
- | WeaveConfig
- | AliyunConfig
- | TencentConfig
- | MLflowConfig
- | DatabricksConfig,
- ) => void
- onConfigRemoved: (provider: TracingProvider) => void
+ arizeConfig: TraceAppConfigResponse['tracing_config']
+ phoenixConfig: TraceAppConfigResponse['tracing_config']
+ langSmithConfig: TraceAppConfigResponse['tracing_config']
+ langFuseConfig: TraceAppConfigResponse['tracing_config']
+ opikConfig: TraceAppConfigResponse['tracing_config']
+ weaveConfig: TraceAppConfigResponse['tracing_config']
+ aliyunConfig: TraceAppConfigResponse['tracing_config']
+ mlflowConfig: TraceAppConfigResponse['tracing_config']
+ databricksConfig: TraceAppConfigResponse['tracing_config']
+ tencentConfig: TraceAppConfigResponse['tracing_config']
}
const ConfigPopup: FC<PopupProps> = ({
appId,
+ configErrors,
+ onConfigRemoved,
readOnly,
enabled,
onStatusChange,
@@ -79,25 +59,11 @@ const ConfigPopup: FC<PopupProps> = ({
mlflowConfig,
databricksConfig,
tencentConfig,
- onConfigUpdated,
- onConfigRemoved,
}) => {
const { t } = useTranslation(['app'])
-
- const [currentProvider, setCurrentProvider] = useState<TracingProvider | null>(
- TracingProvider.langfuse,
- )
- const [isShowConfigModal, { setTrue: showConfigModal, setFalse: hideConfigModal }] =
- useBoolean(false)
- const handleOnConfig = useCallback(
- (provider: TracingProvider) => {
- return () => {
- setCurrentProvider(provider)
- showConfigModal()
- }
- },
- [showConfigModal],
- )
+ const dialogActionsRef = React.useRef<DialogActions>(null)
+ const firstInputRef = React.useRef<HTMLInputElement>(null)
+ const closeConfig = () => dialogActionsRef.current?.close()
const handleOnChoose = useCallback(
(provider: TracingProvider) => {
@@ -108,69 +74,38 @@ const ConfigPopup: FC<PopupProps> = ({
[onChooseProvider],
)
- const handleConfigUpdated = useCallback(
- (
- payload:
- | ArizeConfig
- | PhoenixConfig
- | LangSmithConfig
- | LangFuseConfig
- | OpikConfig
- | WeaveConfig
- | AliyunConfig
- | MLflowConfig
- | DatabricksConfig
- | TencentConfig,
- ) => {
- onConfigUpdated(currentProvider!, payload)
- hideConfigModal()
- },
- [currentProvider, hideConfigModal, onConfigUpdated],
- )
-
- const handleConfigRemoved = useCallback(() => {
- onConfigRemoved(currentProvider!)
- hideConfigModal()
- }, [currentProvider, hideConfigModal, onConfigRemoved])
-
- const providerAllConfigured =
- arizeConfig &&
- phoenixConfig &&
- langSmithConfig &&
- langFuseConfig &&
- opikConfig &&
- weaveConfig &&
- aliyunConfig &&
- mlflowConfig &&
- databricksConfig &&
- tencentConfig
- const providerAllNotConfigured =
- !arizeConfig &&
- !phoenixConfig &&
- !langSmithConfig &&
- !langFuseConfig &&
- !opikConfig &&
- !weaveConfig &&
- !aliyunConfig &&
- !mlflowConfig &&
- !databricksConfig &&
- !tencentConfig
+ const providerConfigs = {
+ [TracingProvider.arize]: arizeConfig,
+ [TracingProvider.phoenix]: phoenixConfig,
+ [TracingProvider.langSmith]: langSmithConfig,
+ [TracingProvider.langfuse]: langFuseConfig,
+ [TracingProvider.opik]: opikConfig,
+ [TracingProvider.weave]: weaveConfig,
+ [TracingProvider.aliyun]: aliyunConfig,
+ [TracingProvider.mlflow]: mlflowConfig,
+ [TracingProvider.databricks]: databricksConfig,
+ [TracingProvider.tencent]: tencentConfig,
+ } satisfies Record<TracingProvider, TraceAppConfigResponse['tracing_config']>
+ const providerAllConfigured = Object.values(providerConfigs).every(Boolean)
+ const providerAllNotConfigured = Object.values(providerConfigs).every((config) => !config)
+
+ const cannotEnable = !enabled && (!chosenProvider || !providerConfigs[chosenProvider])
const switchContent = (
<Switch
+ aria-label={t(($) => $[`${I18N_PREFIX}.tracing`], { ns: 'app' })}
className="ml-3"
checked={enabled}
onCheckedChange={onStatusChange}
- disabled={providerAllNotConfigured}
+ disabled={cannotEnable}
/>
)
const arizePanel = (
<ProviderPanel
type={TracingProvider.arize}
+ configError={configErrors?.[TracingProvider.arize]}
readOnly={readOnly}
config={arizeConfig}
- hasConfigured={!!arizeConfig}
- onConfig={handleOnConfig(TracingProvider.arize)}
isChosen={chosenProvider === TracingProvider.arize}
onChoose={handleOnChoose(TracingProvider.arize)}
key="arize-provider-panel"
@@ -180,10 +115,9 @@ const ConfigPopup: FC<PopupProps> = ({
const phoenixPanel = (
<ProviderPanel
type={TracingProvider.phoenix}
+ configError={configErrors?.[TracingProvider.phoenix]}
readOnly={readOnly}
config={phoenixConfig}
- hasConfigured={!!phoenixConfig}
- onConfig={handleOnConfig(TracingProvider.phoenix)}
isChosen={chosenProvider === TracingProvider.phoenix}
onChoose={handleOnChoose(TracingProvider.phoenix)}
key="phoenix-provider-panel"
@@ -193,10 +127,9 @@ const ConfigPopup: FC<PopupProps> = ({
const langSmithPanel = (
<ProviderPanel
type={TracingProvider.langSmith}
+ configError={configErrors?.[TracingProvider.langSmith]}
readOnly={readOnly}
config={langSmithConfig}
- hasConfigured={!!langSmithConfig}
- onConfig={handleOnConfig(TracingProvider.langSmith)}
isChosen={chosenProvider === TracingProvider.langSmith}
onChoose={handleOnChoose(TracingProvider.langSmith)}
key="langSmith-provider-panel"
@@ -206,10 +139,9 @@ const ConfigPopup: FC<PopupProps> = ({
const langfusePanel = (
<ProviderPanel
type={TracingProvider.langfuse}
+ configError={configErrors?.[TracingProvider.langfuse]}
readOnly={readOnly}
config={langFuseConfig}
- hasConfigured={!!langFuseConfig}
- onConfig={handleOnConfig(TracingProvider.langfuse)}
isChosen={chosenProvider === TracingProvider.langfuse}
onChoose={handleOnChoose(TracingProvider.langfuse)}
key="langfuse-provider-panel"
@@ -219,10 +151,9 @@ const ConfigPopup: FC<PopupProps> = ({
const opikPanel = (
<ProviderPanel
type={TracingProvider.opik}
+ configError={configErrors?.[TracingProvider.opik]}
readOnly={readOnly}
config={opikConfig}
- hasConfigured={!!opikConfig}
- onConfig={handleOnConfig(TracingProvider.opik)}
isChosen={chosenProvider === TracingProvider.opik}
onChoose={handleOnChoose(TracingProvider.opik)}
key="opik-provider-panel"
@@ -232,10 +163,9 @@ const ConfigPopup: FC<PopupProps> = ({
const weavePanel = (
<ProviderPanel
type={TracingProvider.weave}
+ configError={configErrors?.[TracingProvider.weave]}
readOnly={readOnly}
config={weaveConfig}
- hasConfigured={!!weaveConfig}
- onConfig={handleOnConfig(TracingProvider.weave)}
isChosen={chosenProvider === TracingProvider.weave}
onChoose={handleOnChoose(TracingProvider.weave)}
key="weave-provider-panel"
@@ -245,10 +175,9 @@ const ConfigPopup: FC<PopupProps> = ({
const aliyunPanel = (
<ProviderPanel
type={TracingProvider.aliyun}
+ configError={configErrors?.[TracingProvider.aliyun]}
readOnly={readOnly}
config={aliyunConfig}
- hasConfigured={!!aliyunConfig}
- onConfig={handleOnConfig(TracingProvider.aliyun)}
isChosen={chosenProvider === TracingProvider.aliyun}
onChoose={handleOnChoose(TracingProvider.aliyun)}
key="aliyun-provider-panel"
@@ -258,10 +187,9 @@ const ConfigPopup: FC<PopupProps> = ({
const mlflowPanel = (
<ProviderPanel
type={TracingProvider.mlflow}
+ configError={configErrors?.[TracingProvider.mlflow]}
readOnly={readOnly}
config={mlflowConfig}
- hasConfigured={!!mlflowConfig}
- onConfig={handleOnConfig(TracingProvider.mlflow)}
isChosen={chosenProvider === TracingProvider.mlflow}
onChoose={handleOnChoose(TracingProvider.mlflow)}
key="mlflow-provider-panel"
@@ -271,10 +199,9 @@ const ConfigPopup: FC<PopupProps> = ({
const databricksPanel = (
<ProviderPanel
type={TracingProvider.databricks}
+ configError={configErrors?.[TracingProvider.databricks]}
readOnly={readOnly}
config={databricksConfig}
- hasConfigured={!!databricksConfig}
- onConfig={handleOnConfig(TracingProvider.databricks)}
isChosen={chosenProvider === TracingProvider.databricks}
onChoose={handleOnChoose(TracingProvider.databricks)}
key="databricks-provider-panel"
@@ -284,10 +211,9 @@ const ConfigPopup: FC<PopupProps> = ({
const tencentPanel = (
<ProviderPanel
type={TracingProvider.tencent}
+ configError={configErrors?.[TracingProvider.tencent]}
readOnly={readOnly}
config={tencentConfig}
- hasConfigured={!!tencentConfig}
- onConfig={handleOnConfig(TracingProvider.tencent)}
isChosen={chosenProvider === TracingProvider.tencent}
onChoose={handleOnChoose(TracingProvider.tencent)}
key="tencent-provider-panel"
@@ -345,111 +271,114 @@ const ConfigPopup: FC<PopupProps> = ({
return notConfiguredPanels
}
- const configuredProviderConfig = () => {
- if (currentProvider === TracingProvider.mlflow) return mlflowConfig
- if (currentProvider === TracingProvider.databricks) return databricksConfig
- if (currentProvider === TracingProvider.arize) return arizeConfig
- if (currentProvider === TracingProvider.phoenix) return phoenixConfig
- if (currentProvider === TracingProvider.langSmith) return langSmithConfig
- if (currentProvider === TracingProvider.langfuse) return langFuseConfig
- if (currentProvider === TracingProvider.opik) return opikConfig
- if (currentProvider === TracingProvider.aliyun) return aliyunConfig
- if (currentProvider === TracingProvider.tencent) return tencentConfig
- return weaveConfig
- }
-
return (
- <div className="w-105 rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-4 shadow-xl">
- <div className="flex items-center justify-between">
- <div className="flex items-center">
- <TracingIcon size="md" className="mr-2" />
- <div className="title-2xl-semi-bold text-text-primary">
- {t(($) => $[`${I18N_PREFIX}.tracing`], { ns: 'app' })}
- </div>
- </div>
- <div className="flex items-center">
- <StatusDot status={enabled ? 'success' : 'disabled'} />
- <div
- className={cn(
- 'ml-1 system-xs-semibold-uppercase text-text-tertiary',
- enabled && 'text-util-colors-green-green-600',
- )}
- >
- {t(($) => $[`${I18N_PREFIX}.${enabled ? 'enabled' : 'disabled'}`], { ns: 'app' })}
- </div>
- {!readOnly && (
- <>
- {providerAllNotConfigured ? (
- <Tooltip>
- <TooltipTrigger render={switchContent} />
- <TooltipContent>
- {t(($) => $[`${I18N_PREFIX}.disabledTip`], { ns: 'app' })}
- </TooltipContent>
- </Tooltip>
- ) : (
- switchContent
- )}
- </>
- )}
- </div>
- </div>
-
- <div className="mt-2 system-xs-regular text-text-tertiary">
- {t(($) => $[`${I18N_PREFIX}.tracingDescription`], { ns: 'app' })}
- </div>
- <Separator className="my-3 h-[0.5px]" />
- <div className="relative">
- {providerAllConfigured || providerAllNotConfigured ? (
- <>
- <div className="system-xs-medium-uppercase text-text-tertiary">
- {t(
- ($) =>
- $[
- `${I18N_PREFIX}.configProviderTitle.${providerAllConfigured ? 'configured' : 'notConfigured'}`
- ],
- { ns: 'app' },
- )}
- </div>
- <div className="mt-2 max-h-96 space-y-2 overflow-y-auto">
- {langfusePanel}
- {langSmithPanel}
- {opikPanel}
- {mlflowPanel}
- {databricksPanel}
- {weavePanel}
- {arizePanel}
- {phoenixPanel}
- {aliyunPanel}
- {tencentPanel}
+ <Dialog<TracingProvider> actionsRef={dialogActionsRef} disablePointerDismissal>
+ {({ payload: provider }) => (
+ <>
+ <div className="w-105 rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-4 shadow-xl">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center">
+ <TracingIcon size="md" className="mr-2" />
+ <div className="title-2xl-semi-bold text-text-primary">
+ {t(($) => $[`${I18N_PREFIX}.tracing`], { ns: 'app' })}
+ </div>
+ </div>
+ <div className="flex items-center">
+ <StatusDot status={enabled ? 'success' : 'disabled'} />
+ <div
+ className={cn(
+ 'ml-1 system-xs-semibold-uppercase text-text-tertiary',
+ enabled && 'text-util-colors-green-green-600',
+ )}
+ >
+ {t(($) => $[`${I18N_PREFIX}.${enabled ? 'enabled' : 'disabled'}`], { ns: 'app' })}
+ </div>
+ {!readOnly && (
+ <>
+ {cannotEnable ? (
+ <Tooltip>
+ <TooltipTrigger render={switchContent} />
+ <TooltipContent>
+ {t(($) => $[`${I18N_PREFIX}.disabledTip`], { ns: 'app' })}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ switchContent
+ )}
+ </>
+ )}
+ </div>
</div>
- </>
- ) : (
- <>
- <div className="system-xs-medium-uppercase text-text-tertiary">
- {t(($) => $[`${I18N_PREFIX}.configProviderTitle.configured`], { ns: 'app' })}
- </div>
- <div className="mt-2 max-h-40 space-y-2 overflow-y-auto">
- {configuredProviderPanel()}
+
+ <div className="mt-2 system-xs-regular text-text-tertiary">
+ {t(($) => $[`${I18N_PREFIX}.tracingDescription`], { ns: 'app' })}
</div>
- <div className="mt-3 system-xs-medium-uppercase text-text-tertiary">
- {t(($) => $[`${I18N_PREFIX}.configProviderTitle.moreProvider`], { ns: 'app' })}
+ <Separator className="my-3 h-[0.5px]" />
+ <div className="relative">
+ {providerAllConfigured || providerAllNotConfigured ? (
+ <>
+ <div className="system-xs-medium-uppercase text-text-tertiary">
+ {t(
+ ($) =>
+ $[
+ `${I18N_PREFIX}.configProviderTitle.${providerAllConfigured ? 'configured' : 'notConfigured'}`
+ ],
+ { ns: 'app' },
+ )}
+ </div>
+ <div className="mt-2 max-h-96 space-y-2 overflow-y-auto">
+ {langfusePanel}
+ {langSmithPanel}
+ {opikPanel}
+ {mlflowPanel}
+ {databricksPanel}
+ {weavePanel}
+ {arizePanel}
+ {phoenixPanel}
+ {aliyunPanel}
+ {tencentPanel}
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="system-xs-medium-uppercase text-text-tertiary">
+ {t(($) => $[`${I18N_PREFIX}.configProviderTitle.configured`], { ns: 'app' })}
+ </div>
+ <div className="mt-2 max-h-40 space-y-2 overflow-y-auto">
+ {configuredProviderPanel()}
+ </div>
+ <div className="mt-3 system-xs-medium-uppercase text-text-tertiary">
+ {t(($) => $[`${I18N_PREFIX}.configProviderTitle.moreProvider`], { ns: 'app' })}
+ </div>
+ <div className="mt-2 max-h-40 space-y-2 overflow-y-auto">
+ {moreProviderPanel()}
+ </div>
+ </>
+ )}
</div>
- <div className="mt-2 max-h-40 space-y-2 overflow-y-auto">{moreProviderPanel()}</div>
- </>
- )}
- </div>
- {isShowConfigModal && (
- <ProviderConfigModal
- appId={appId}
- type={currentProvider!}
- payload={configuredProviderConfig()}
- onCancel={hideConfigModal}
- onSaved={handleConfigUpdated}
- onChosen={onChooseProvider}
- onRemoved={handleConfigRemoved}
- />
+ </div>
+ <DialogContent
+ initialFocus={firstInputRef}
+ className="max-h-[calc(100dvh-2rem)] w-160 p-0"
+ >
+ {provider && (
+ <ProviderConfigModal
+ appId={appId}
+ type={provider}
+ payload={providerConfigs[provider]}
+ firstInputRef={firstInputRef}
+ onSaved={closeConfig}
+ onChosen={onChooseProvider}
+ onRemoved={() => {
+ onConfigRemoved(provider)
+ closeConfig()
+ }}
+ />
+ )}
+ </DialogContent>
+ </>
)}
- </div>
+ </Dialog>
)
}
export default React.memo(ConfigPopup)
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/field.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/field.tsx
deleted file mode 100644
index 26135bb5bc5..00000000000
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/field.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Input } from '@langgenius/dify-ui/input'
-import * as React from 'react'
-
-type Props = Readonly<{
- className?: string
- label: string
- labelClassName?: string
- value: string | number
- onChange: (value: string) => void
- isRequired?: boolean
- placeholder?: string
-}>
-
-const Field: FC<Props> = ({
- className,
- label,
- labelClassName,
- value,
- onChange,
- isRequired = false,
- placeholder = '',
-}) => {
- const inputId = React.useId()
-
- return (
- <div className={cn(className)}>
- <div className="flex py-1.75">
- <label
- htmlFor={inputId}
- className={cn(
- labelClassName,
- 'flex h-4.5 items-center text-[13px] font-medium text-text-primary',
- )}
- >
- {label}{' '}
- </label>
- {isRequired && <span className="ml-0.5 text-xs font-semibold text-[#D92D20]">*</span>}
- </div>
- <Input
- id={inputId}
- value={value}
- onValueChange={(nextValue) => onChange(nextValue)}
- className="h-9"
- placeholder={placeholder}
- />
- </div>
- )
-}
-export default React.memo(Field)
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx
index 98eb0aa32b7..c41d1d00d21 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx
@@ -1,33 +1,17 @@
'use client'
+import type { AppTracePayload } from '@dify/contracts/api/console/apps/types.gen'
import type { FC } from 'react'
-import type {
- AliyunConfig,
- ArizeConfig,
- DatabricksConfig,
- LangFuseConfig,
- LangSmithConfig,
- MLflowConfig,
- OpikConfig,
- PhoenixConfig,
- TencentConfig,
- WeaveConfig,
-} from './type'
-import type { TracingStatus } from '@/models/app'
+import type { ProviderConfigError } from './provider-panel'
+import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
-import { useBoolean } from 'ahooks'
+import { useMutation, useQueries, useQuery } from '@tanstack/react-query'
import * as React from 'react'
-import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { toast } from '@/app/notifications'
-import {
- fetchTracingConfig as doFetchTracingConfig,
- fetchTracingStatus,
- updateTracingStatus,
-} from '@/service/apps'
+import { consoleQuery } from '@/service/console'
import ConfigButton from './config-button'
import TracingIcon from './tracing-icon'
import { TracingProvider } from './type'
@@ -41,35 +25,55 @@ type PanelProps = {
const Panel: FC<PanelProps> = ({ appId, readOnly }) => {
const { t } = useTranslation(['app', 'common'])
- const [isLoaded, { setTrue: setLoaded }] = useBoolean(false)
-
- const [tracingStatus, setTracingStatus] = useState<TracingStatus | null>(null)
- const enabled = tracingStatus?.enabled || false
- const handleTracingStatusChange = async (tracingStatus: TracingStatus, noToast?: boolean) => {
- await updateTracingStatus({ appId, body: tracingStatus })
- setTracingStatus(tracingStatus)
- if (!noToast) {
- toast(
- t(($) => $['api.success'], { ns: 'common' }),
- { type: 'success' },
- )
- }
+ const statusQuery = useQuery(
+ consoleQuery.apps.byAppId.trace.get.queryOptions({
+ input: { params: { app_id: appId } },
+ }),
+ )
+ const tracingStatus = statusQuery.data
+ const providers = Object.values(TracingProvider)
+ const configQueries = useQueries({
+ queries: providers.map((provider) =>
+ consoleQuery.apps.byAppId.traceConfig.get.queryOptions({
+ input: { params: { app_id: appId }, query: { tracing_provider: provider } },
+ }),
+ ),
+ })
+ const configs = new Map(
+ providers.map((provider, index) => {
+ const response = configQueries[index]?.data
+ return [
+ provider,
+ response?.has_not_configured ? null : (response?.tracing_config ?? null),
+ ] as const
+ }),
+ )
+ const { mutate: updateTracingStatus } = useMutation(
+ consoleQuery.apps.byAppId.trace.post.mutationOptions(),
+ )
+ const enabled = tracingStatus?.enabled ?? false
+ const inUseTracingProvider =
+ providers.find((provider) => provider === tracingStatus?.tracing_provider) ?? null
+ const handleTracingStatusChange = (body: AppTracePayload, noToast = false) => {
+ updateTracingStatus(
+ { params: { app_id: appId }, body },
+ {
+ onSuccess: () => {
+ if (!noToast)
+ toast(
+ t(($) => $['api.success'], { ns: 'common' }),
+ { type: 'success' },
+ )
+ },
+ },
+ )
}
-
const handleTracingEnabledChange = (enabled: boolean) => {
- handleTracingStatusChange({
- tracing_provider: tracingStatus?.tracing_provider || null,
- enabled,
- })
+ handleTracingStatusChange({ tracing_provider: inUseTracingProvider, enabled })
}
const handleChooseProvider = (provider: TracingProvider) => {
- handleTracingStatusChange({
- tracing_provider: provider,
- enabled: true,
- })
+ handleTracingStatusChange({ tracing_provider: provider, enabled: true })
}
- const inUseTracingProvider: TracingProvider | null = tracingStatus?.tracing_provider || null
-
const providerIconClassMap: Record<TracingProvider, string> = {
[TracingProvider.arize]: 'i-custom-public-tracing-arize-icon w-18.5',
[TracingProvider.phoenix]: 'i-custom-public-tracing-phoenix-icon w-18.5',
@@ -86,236 +90,102 @@ const Panel: FC<PanelProps> = ({ appId, readOnly }) => {
? providerIconClassMap[inUseTracingProvider]
: undefined
- const [arizeConfig, setArizeConfig] = useState<ArizeConfig | null>(null)
- const [phoenixConfig, setPhoenixConfig] = useState<PhoenixConfig | null>(null)
- const [langSmithConfig, setLangSmithConfig] = useState<LangSmithConfig | null>(null)
- const [langFuseConfig, setLangFuseConfig] = useState<LangFuseConfig | null>(null)
- const [opikConfig, setOpikConfig] = useState<OpikConfig | null>(null)
- const [weaveConfig, setWeaveConfig] = useState<WeaveConfig | null>(null)
- const [aliyunConfig, setAliyunConfig] = useState<AliyunConfig | null>(null)
- const [mlflowConfig, setMLflowConfig] = useState<MLflowConfig | null>(null)
- const [databricksConfig, setDatabricksConfig] = useState<DatabricksConfig | null>(null)
- const [tencentConfig, setTencentConfig] = useState<TencentConfig | null>(null)
- const hasConfiguredTracing = !!(
- langSmithConfig ||
- langFuseConfig ||
- opikConfig ||
- weaveConfig ||
- arizeConfig ||
- phoenixConfig ||
- aliyunConfig ||
- mlflowConfig ||
- databricksConfig ||
- tencentConfig
- )
-
- const fetchTracingConfig = async () => {
- const getArizeConfig = async () => {
- const { tracing_config: arizeConfig, has_not_configured: arizeHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.arize })
- if (!arizeHasNotConfig) setArizeConfig(arizeConfig as ArizeConfig)
- }
- const getPhoenixConfig = async () => {
- const { tracing_config: phoenixConfig, has_not_configured: phoenixHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.phoenix })
- if (!phoenixHasNotConfig) setPhoenixConfig(phoenixConfig as PhoenixConfig)
- }
- const getLangSmithConfig = async () => {
- const { tracing_config: langSmithConfig, has_not_configured: langSmithHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.langSmith })
- if (!langSmithHasNotConfig) setLangSmithConfig(langSmithConfig as LangSmithConfig)
- }
- const getLangFuseConfig = async () => {
- const { tracing_config: langFuseConfig, has_not_configured: langFuseHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.langfuse })
- if (!langFuseHasNotConfig) setLangFuseConfig(langFuseConfig as LangFuseConfig)
- }
- const getOpikConfig = async () => {
- const { tracing_config: opikConfig, has_not_configured: OpikHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.opik })
- if (!OpikHasNotConfig) setOpikConfig(opikConfig as OpikConfig)
- }
- const getWeaveConfig = async () => {
- const { tracing_config: weaveConfig, has_not_configured: weaveHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.weave })
- if (!weaveHasNotConfig) setWeaveConfig(weaveConfig as WeaveConfig)
- }
- const getAliyunConfig = async () => {
- const { tracing_config: aliyunConfig, has_not_configured: aliyunHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.aliyun })
- if (!aliyunHasNotConfig) setAliyunConfig(aliyunConfig as AliyunConfig)
- }
- const getMLflowConfig = async () => {
- const { tracing_config: mlflowConfig, has_not_configured: mlflowHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.mlflow })
- if (!mlflowHasNotConfig) setMLflowConfig(mlflowConfig as MLflowConfig)
- }
- const getDatabricksConfig = async () => {
- const { tracing_config: databricksConfig, has_not_configured: databricksHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.databricks })
- if (!databricksHasNotConfig) setDatabricksConfig(databricksConfig as DatabricksConfig)
- }
- const getTencentConfig = async () => {
- const { tracing_config: tencentConfig, has_not_configured: tencentHasNotConfig } =
- await doFetchTracingConfig({ appId, provider: TracingProvider.tencent })
- if (!tencentHasNotConfig) setTencentConfig(tencentConfig as TencentConfig)
- }
- Promise.all([
- getArizeConfig(),
- getPhoenixConfig(),
- getLangSmithConfig(),
- getLangFuseConfig(),
- getOpikConfig(),
- getWeaveConfig(),
- getAliyunConfig(),
- getMLflowConfig(),
- getDatabricksConfig(),
- getTencentConfig(),
- ])
- }
-
- const handleTracingConfigUpdated = async (provider: TracingProvider) => {
- // call api to hide secret key value
- const { tracing_config } = await doFetchTracingConfig({ appId, provider })
- if (provider === TracingProvider.arize) setArizeConfig(tracing_config as ArizeConfig)
- else if (provider === TracingProvider.phoenix) setPhoenixConfig(tracing_config as PhoenixConfig)
- else if (provider === TracingProvider.langSmith)
- setLangSmithConfig(tracing_config as LangSmithConfig)
- else if (provider === TracingProvider.langfuse)
- setLangFuseConfig(tracing_config as LangFuseConfig)
- else if (provider === TracingProvider.opik) setOpikConfig(tracing_config as OpikConfig)
- else if (provider === TracingProvider.weave) setWeaveConfig(tracing_config as WeaveConfig)
- else if (provider === TracingProvider.aliyun) setAliyunConfig(tracing_config as AliyunConfig)
- else if (provider === TracingProvider.tencent) setTencentConfig(tracing_config as TencentConfig)
- }
-
+ const hasConfiguredTracing =
+ !!inUseTracingProvider || [...configs.values()].some((config) => config !== null)
const handleTracingConfigRemoved = (provider: TracingProvider) => {
- if (provider === TracingProvider.arize) setArizeConfig(null)
- else if (provider === TracingProvider.phoenix) setPhoenixConfig(null)
- else if (provider === TracingProvider.langSmith) setLangSmithConfig(null)
- else if (provider === TracingProvider.langfuse) setLangFuseConfig(null)
- else if (provider === TracingProvider.opik) setOpikConfig(null)
- else if (provider === TracingProvider.weave) setWeaveConfig(null)
- else if (provider === TracingProvider.aliyun) setAliyunConfig(null)
- else if (provider === TracingProvider.mlflow) setMLflowConfig(null)
- else if (provider === TracingProvider.databricks) setDatabricksConfig(null)
- else if (provider === TracingProvider.tencent) setTencentConfig(null)
if (provider === inUseTracingProvider) {
- handleTracingStatusChange(
- {
- enabled: false,
- tracing_provider: null,
- },
- true,
- )
+ handleTracingStatusChange({ enabled: false, tracing_provider: null }, true)
}
}
- useEffect(() => {
- ;(async () => {
- const tracingStatus = await fetchTracingStatus({ appId })
- setTracingStatus(tracingStatus)
- await fetchTracingConfig()
- setLoaded()
- })()
- }, [])
-
- if (!isLoaded) {
+ const configErrors: Partial<Record<TracingProvider, ProviderConfigError>> = {}
+ configQueries.forEach((query, index) => {
+ const provider = providers[index]
+ if (provider && query.isFetched && !query.data) {
+ configErrors[provider] = {
+ onRetry: () => {
+ void query.refetch()
+ },
+ isRetrying: query.isFetching,
+ }
+ }
+ })
+ const statusFailed = statusQuery.isError && !tracingStatus
+ if (statusFailed) {
return (
- <div className="mb-3 flex items-center justify-between">
- <div className="w-50">
- <LoadingPlaceholder />
- </div>
- </div>
+ <Button
+ variant="secondary"
+ disabled={statusQuery.isFetching}
+ onClick={() => {
+ void statusQuery.refetch()
+ }}
+ >
+ {t(($) => $['tracing.title'], { ns: 'app' })}
+ {' · '}
+ {t(($) => $['errorBoundary.tryAgain'], { ns: 'common' })}
+ </Button>
)
}
+ const isLoading =
+ statusQuery.isPending || configQueries.some((query) => query.isPending && !query.isFetched)
return (
<div className={cn('flex items-center justify-between')}>
- {!inUseTracingProvider && (
- <ConfigButton
- appId={appId}
- readOnly={readOnly}
- hasConfigured={false}
- enabled={enabled}
- onStatusChange={handleTracingEnabledChange}
- chosenProvider={inUseTracingProvider}
- onChooseProvider={handleChooseProvider}
- arizeConfig={arizeConfig}
- phoenixConfig={phoenixConfig}
- langSmithConfig={langSmithConfig}
- langFuseConfig={langFuseConfig}
- opikConfig={opikConfig}
- weaveConfig={weaveConfig}
- aliyunConfig={aliyunConfig}
- mlflowConfig={mlflowConfig}
- databricksConfig={databricksConfig}
- tencentConfig={tencentConfig}
- onConfigUpdated={handleTracingConfigUpdated}
- onConfigRemoved={handleTracingConfigRemoved}
- >
- <div
- className={cn(
- 'flex cursor-pointer items-center rounded-xl border-[0.5px] border-components-panel-border bg-background-default-dodge p-2 shadow-xs select-none hover:bg-background-default-lighter',
- )}
- >
- <TracingIcon size="md" />
- <div className="mx-2 system-sm-semibold text-text-secondary">
- {t(($) => $[`${I18N_PREFIX}.title`], { ns: 'app' })}
- </div>
- <div className="rounded-md p-1">
- <span className="i-ri-equalizer-2-line size-4 text-text-tertiary" />
- </div>
- <Separator decorative orientation="vertical" className="mx-2 h-3.5" />
- <div className="rounded-md p-1">
- <span className="i-ri-arrow-down-double-line size-4 text-text-tertiary" />
- </div>
- </div>
- </ConfigButton>
- )}
- {hasConfiguredTracing && (
- <ConfigButton
- appId={appId}
- readOnly={readOnly}
- hasConfigured
- enabled={enabled}
- onStatusChange={handleTracingEnabledChange}
- chosenProvider={inUseTracingProvider}
- onChooseProvider={handleChooseProvider}
- arizeConfig={arizeConfig}
- phoenixConfig={phoenixConfig}
- langSmithConfig={langSmithConfig}
- langFuseConfig={langFuseConfig}
- opikConfig={opikConfig}
- weaveConfig={weaveConfig}
- aliyunConfig={aliyunConfig}
- mlflowConfig={mlflowConfig}
- databricksConfig={databricksConfig}
- tencentConfig={tencentConfig}
- onConfigUpdated={handleTracingConfigUpdated}
- onConfigRemoved={handleTracingConfigRemoved}
- >
- <div
- className={cn(
- 'flex cursor-pointer items-center rounded-xl border-[0.5px] border-components-panel-border bg-background-default-dodge p-2 shadow-xs select-none hover:bg-background-default-lighter',
- )}
- >
- <div className="mr-1 ml-4 flex items-center">
+ <ConfigButton
+ key={appId}
+ appId={appId}
+ readOnly={readOnly}
+ disabled={isLoading}
+ hasConfigured={hasConfiguredTracing}
+ enabled={enabled}
+ onStatusChange={handleTracingEnabledChange}
+ chosenProvider={inUseTracingProvider}
+ onChooseProvider={handleChooseProvider}
+ arizeConfig={configs.get(TracingProvider.arize)}
+ phoenixConfig={configs.get(TracingProvider.phoenix)}
+ langSmithConfig={configs.get(TracingProvider.langSmith)}
+ langFuseConfig={configs.get(TracingProvider.langfuse)}
+ opikConfig={configs.get(TracingProvider.opik)}
+ weaveConfig={configs.get(TracingProvider.weave)}
+ aliyunConfig={configs.get(TracingProvider.aliyun)}
+ mlflowConfig={configs.get(TracingProvider.mlflow)}
+ databricksConfig={configs.get(TracingProvider.databricks)}
+ tencentConfig={configs.get(TracingProvider.tencent)}
+ configErrors={configErrors}
+ onConfigRemoved={handleTracingConfigRemoved}
+ >
+ {!isLoading && hasConfiguredTracing ? (
+ <>
+ <span className="mr-1 ml-4 flex items-center">
<StatusDot status={enabled ? 'success' : 'disabled'} />
- <div className="ml-1.5 system-xs-semibold-uppercase text-text-tertiary">
+ <span className="ml-1.5 system-xs-semibold-uppercase text-text-tertiary">
{t(($) => $[`${I18N_PREFIX}.${enabled ? 'enabled' : 'disabled'}`], { ns: 'app' })}
- </div>
- </div>
+ </span>
+ </span>
{inUseProviderIconClassName && (
<span aria-hidden className={cn(inUseProviderIconClassName, 'ml-1 h-4')} />
)}
- <div className="ml-2 rounded-md p-1">
+ <span className="ml-2 rounded-md p-1">
<span className="i-ri-equalizer-2-line size-4 text-text-tertiary" />
- </div>
+ </span>
<Separator decorative orientation="vertical" className="mx-2 h-3.5" />
- </div>
- </ConfigButton>
- )}
+ </>
+ ) : (
+ <>
+ <TracingIcon size="md" />
+ <span className="mx-2 system-sm-semibold text-text-secondary">
+ {t(($) => $[`${I18N_PREFIX}.title`], { ns: 'app' })}
+ </span>
+ <span className="rounded-md p-1">
+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary" />
+ </span>
+ <Separator decorative orientation="vertical" className="mx-2 h-3.5" />
+ <span className="rounded-md p-1">
+ <span className="i-ri-arrow-down-double-line size-4 text-text-tertiary" />
+ </span>
+ </>
+ )}
+ </ConfigButton>
</div>
)
}
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx
index d49b1b5e58b..4ee376f82da 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx
@@ -1,17 +1,9 @@
'use client'
-import type { FC } from 'react'
import type {
- AliyunConfig,
- ArizeConfig,
- DatabricksConfig,
- LangFuseConfig,
- LangSmithConfig,
- MLflowConfig,
- OpikConfig,
- PhoenixConfig,
- TencentConfig,
- WeaveConfig,
-} from './type'
+ TraceAppConfigResponse,
+ TraceConfigPayload,
+} from '@dify/contracts/api/console/apps/types.gen'
+import type { FC, RefObject } from 'react'
import {
AlertDialog,
AlertDialogCancelButton,
@@ -20,852 +12,765 @@ import {
AlertDialogDescription,
AlertDialogFooter,
AlertDialogTitle,
+ AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { DialogClose, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { Input } from '@langgenius/dify-ui/input'
import { Separator } from '@langgenius/dify-ui/separator'
-import { useBoolean } from 'ahooks'
+import { useMutation } from '@tanstack/react-query'
import * as React from 'react'
-import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { toast } from '@/app/notifications'
-import { addTracingConfig, removeTracingConfig, updateTracingConfig } from '@/service/apps'
+import { consoleQuery } from '@/service/console'
import { docURL } from './config'
-import Field from './field'
import { TracingProvider } from './type'
type Props = Readonly<{
appId: string
type: TracingProvider
- payload?:
- | ArizeConfig
- | PhoenixConfig
- | LangSmithConfig
- | LangFuseConfig
- | OpikConfig
- | WeaveConfig
- | AliyunConfig
- | MLflowConfig
- | DatabricksConfig
- | TencentConfig
- | null
+ payload?: TraceAppConfigResponse['tracing_config']
onRemoved: () => void
- onCancel: () => void
- onSaved: (
- payload:
- | ArizeConfig
- | PhoenixConfig
- | LangSmithConfig
- | LangFuseConfig
- | OpikConfig
- | WeaveConfig
- | AliyunConfig
- | MLflowConfig
- | DatabricksConfig
- | TencentConfig,
- ) => void
+ firstInputRef: RefObject<HTMLInputElement | null>
+ onSaved: () => void
onChosen: (provider: TracingProvider) => void
}>
const I18N_PREFIX = 'tracing.configProvider'
-const arizeConfigTemplate = {
- api_key: '',
- space_id: '',
- project: '',
- endpoint: '',
-}
-
-const phoenixConfigTemplate = {
- api_key: '',
- project: '',
- endpoint: '',
-}
-
-const langSmithConfigTemplate = {
- api_key: '',
- project: '',
- endpoint: '',
-}
-
-const langFuseConfigTemplate = {
- public_key: '',
- secret_key: '',
- host: '',
-}
-
-const opikConfigTemplate = {
- api_key: '',
- project: '',
- url: '',
- workspace: '',
-}
-
-const weaveConfigTemplate = {
- api_key: '',
- entity: '',
- project: '',
- endpoint: '',
- host: '',
-}
-
-const aliyunConfigTemplate = {
- app_name: '',
- license_key: '',
- endpoint: '',
-}
-
-const mlflowConfigTemplate = {
- tracking_uri: '',
- experiment_id: '',
- username: '',
- password: '',
-}
-
-const databricksConfigTemplate = {
- experiment_id: '',
- host: '',
- client_id: '',
- client_secret: '',
- personal_access_token: '',
-}
-
-const tencentConfigTemplate = {
- token: '',
- endpoint: '',
- service_name: '',
-}
-
const ProviderConfigModal: FC<Props> = ({
appId,
type,
payload,
onRemoved,
- onCancel,
+ firstInputRef,
onSaved,
onChosen,
}) => {
const { t } = useTranslation(['app', 'common', 'modelProvider'])
const isEdit = !!payload
- const isAdd = !isEdit
- const [isSaving, setIsSaving] = useState(false)
- const [config, setConfig] = useState<
- | ArizeConfig
- | PhoenixConfig
- | LangSmithConfig
- | LangFuseConfig
- | OpikConfig
- | WeaveConfig
- | AliyunConfig
- | MLflowConfig
- | DatabricksConfig
- | TencentConfig
- >(
- (() => {
- if (isEdit) return payload
-
- if (type === TracingProvider.arize) return arizeConfigTemplate
- else if (type === TracingProvider.phoenix) return phoenixConfigTemplate
- else if (type === TracingProvider.langSmith) return langSmithConfigTemplate
- else if (type === TracingProvider.langfuse) return langFuseConfigTemplate
- else if (type === TracingProvider.opik) return opikConfigTemplate
- else if (type === TracingProvider.aliyun) return aliyunConfigTemplate
- else if (type === TracingProvider.mlflow) return mlflowConfigTemplate
- else if (type === TracingProvider.databricks) return databricksConfigTemplate
- else if (type === TracingProvider.tencent) return tencentConfigTemplate
-
- return weaveConfigTemplate
- })(),
+ const createConfig = useMutation(
+ consoleQuery.apps.byAppId.traceConfig.post.mutationOptions({
+ context: { silent: true },
+ onSuccess: () => {
+ onSaved()
+ onChosen(type)
+ },
+ }),
)
- const [isConfigDialogOpen, { set: setIsConfigDialogOpen }] = useBoolean(true)
- const [
- isRemoveDialogOpen,
- { set: setIsRemoveDialogOpen, setTrue: showRemoveConfirm, setFalse: hideRemoveConfirm },
- ] = useBoolean(false)
-
- const handleRemove = useCallback(async () => {
- await removeTracingConfig({
- appId,
- provider: type,
- })
- toast(
- t(($) => $['api.remove'], { ns: 'common' }),
- { type: 'success' },
- )
- onRemoved()
- hideRemoveConfirm()
- }, [hideRemoveConfirm, appId, type, t, onRemoved])
-
- const handleConfigChange = useCallback(
- (key: string) => {
- return (value: string) => {
- setConfig({
- ...config,
- [key]: value,
- })
- }
- },
- [config],
+ const updateConfig = useMutation(
+ consoleQuery.apps.byAppId.traceConfig.patch.mutationOptions({
+ context: { silent: true },
+ onSuccess: onSaved,
+ }),
)
+ const removeConfig = useMutation(
+ consoleQuery.apps.byAppId.traceConfig.delete.mutationOptions({
+ onSuccess: onRemoved,
+ }),
+ )
+ const saveConfig = isEdit ? updateConfig : createConfig
- const checkValid = useCallback(() => {
- let errorMessage = ''
- if (type === TracingProvider.arize) {
- const postData = config as ArizeConfig
- if (!postData.api_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'API Key' })
- if (!postData.space_id)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'Space ID' })
- if (!errorMessage && !postData.project)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })
- }
-
- if (type === TracingProvider.phoenix) {
- const postData = config as PhoenixConfig
- if (!postData.api_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'API Key' })
- if (!errorMessage && !postData.project)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })
- }
-
- if (type === TracingProvider.langSmith) {
- const postData = config as LangSmithConfig
- if (!postData.api_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'API Key' })
- if (!errorMessage && !postData.project)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })
- }
-
- if (type === TracingProvider.langfuse) {
- const postData = config as LangFuseConfig
- if (!errorMessage && !postData.secret_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: t(($) => $[`${I18N_PREFIX}.secretKey`], { ns: 'app' }),
- })
- if (!errorMessage && !postData.public_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: t(($) => $[`${I18N_PREFIX}.publicKey`], { ns: 'app' }),
- })
- if (!errorMessage && !postData.host)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'Host' })
- }
-
- if (type === TracingProvider.opik) {
- // todo: check field validity
- // const postData = config as OpikConfig
- }
-
- if (type === TracingProvider.weave) {
- const postData = config as WeaveConfig
- if (!errorMessage && !postData.api_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'API Key' })
- if (!errorMessage && !postData.project)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })
- }
-
- if (type === TracingProvider.aliyun) {
- const postData = config as AliyunConfig
- if (!errorMessage && !postData.app_name)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'App Name' })
- if (!errorMessage && !postData.license_key)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'License Key' })
- if (!errorMessage && !postData.endpoint)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'Endpoint' })
- }
-
- if (type === TracingProvider.mlflow) {
- const postData = config as MLflowConfig
- if (!errorMessage && !postData.tracking_uri)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: 'Tracking URI',
- })
- }
-
- if (type === TracingProvider.databricks) {
- const postData = config as DatabricksConfig
- if (!errorMessage && !postData.experiment_id)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: 'Experiment ID',
- })
- if (!errorMessage && !postData.host)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'Host' })
- }
-
- if (type === TracingProvider.tencent) {
- const postData = config as TencentConfig
- if (!errorMessage && !postData.token)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'Token' })
- if (!errorMessage && !postData.endpoint)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: 'Endpoint' })
- if (!errorMessage && !postData.service_name)
- errorMessage = t(($) => $['errorMsg.fieldRequired'], {
- ns: 'common',
- field: 'Service Name',
- })
- }
-
- return errorMessage
- }, [config, t, type])
- const handleSave = useCallback(async () => {
- if (isSaving) return
- const errorMessage = checkValid()
- if (errorMessage) {
- toast(errorMessage, { type: 'error' })
- return
- }
- const action = isEdit ? updateTracingConfig : addTracingConfig
- try {
- await action({
- appId,
- body: {
- tracing_provider: type,
- tracing_config: config,
- },
- })
- toast(
- t(($) => $['api.success'], { ns: 'common' }),
- { type: 'success' },
- )
- onSaved(config)
- if (isAdd) onChosen(type)
- } finally {
- setIsSaving(false)
- }
- }, [appId, checkValid, config, isAdd, isEdit, isSaving, onChosen, onSaved, t, type])
+ const handleRemove = () => {
+ removeConfig.mutate({
+ params: { app_id: appId },
+ query: { tracing_provider: type },
+ })
+ }
- // Defer onCancel to onOpenChangeComplete so the dialog's exit animation
- // (scale/opacity transition) can finish before the parent unmounts this modal.
- const handleConfigDialogOpenChangeComplete = useCallback(
- (open: boolean) => {
- if (!open) onCancel()
- },
- [onCancel],
- )
+ const handleSave = (values: TraceConfigPayload['tracing_config']) => {
+ if (saveConfig.isPending) return
+ const config: TraceConfigPayload['tracing_config'] = {}
+ for (const [key, value] of Object.entries(values))
+ config[key] = value === '' && payload?.[key] === null ? null : value
+ saveConfig.mutate({
+ params: { app_id: appId },
+ body: { tracing_provider: type, tracing_config: config },
+ })
+ }
return (
<>
- {!isRemoveDialogOpen ? (
- <Dialog
- open={isConfigDialogOpen}
- onOpenChange={setIsConfigDialogOpen}
- onOpenChangeComplete={handleConfigDialogOpenChangeComplete}
- >
- <DialogContent className="max-h-[calc(100dvh-1rem)] w-auto max-w-[calc(100vw-1rem)] overflow-visible border-none bg-transparent p-0 shadow-none">
- <div className="flex items-center justify-center">
- <div className="mx-2 max-h-[calc(100vh-120px)] w-160 overflow-y-auto rounded-2xl bg-components-panel-bg shadow-xl">
- <div className="px-8 pt-8">
- <div className="mb-4 flex items-center justify-between">
- <div className="title-2xl-semi-bold text-text-primary">
- {t(($) => $[`${I18N_PREFIX}.title`], { ns: 'app' })}
- {t(($) => $[`tracing.${type}.title`], { ns: 'app' })}
- </div>
- </div>
+ <div className="flex items-center justify-between gap-4 px-8 pt-8 pb-4">
+ <DialogTitle className="min-w-0 flex-1 title-2xl-semi-bold text-text-primary">
+ {t(($) => $[`${I18N_PREFIX}.title`], { ns: 'app' })}
+ {t(($) => $[`tracing.${type}.title`], { ns: 'app' })}
+ </DialogTitle>
+ <DialogClose
+ render={
+ <IconButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} size="lg">
+ <span aria-hidden className="i-ri-close-line size-4" />
+ </IconButton>
+ }
+ />
+ </div>
- <div className="space-y-4">
- {type === TracingProvider.arize && (
- <>
- <Field
- label="API Key"
- labelClassName="text-sm!"
- isRequired
- value={(config as ArizeConfig).api_key}
- onChange={handleConfigChange('api_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'API Key',
- })!}
- />
- <Field
- label="Space ID"
- labelClassName="text-sm!"
- isRequired
- value={(config as ArizeConfig).space_id}
- onChange={handleConfigChange('space_id')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'Space ID',
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })!}
- labelClassName="text-sm!"
- isRequired
- value={(config as ArizeConfig).project}
- onChange={handleConfigChange('project')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })!}
- />
- <Field
- label="Endpoint"
- labelClassName="text-sm!"
- value={(config as ArizeConfig).endpoint}
- onChange={handleConfigChange('endpoint')}
- placeholder="https://otlp.arize.com"
- />
- </>
- )}
- {type === TracingProvider.phoenix && (
- <>
- <Field
- label="API Key"
- labelClassName="text-sm!"
- isRequired
- value={(config as PhoenixConfig).api_key}
- onChange={handleConfigChange('api_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'API Key',
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })!}
- labelClassName="text-sm!"
- isRequired
- value={(config as PhoenixConfig).project}
- onChange={handleConfigChange('project')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })!}
- />
- <Field
- label="Endpoint"
- labelClassName="text-sm!"
- value={(config as PhoenixConfig).endpoint}
- onChange={handleConfigChange('endpoint')}
- placeholder="https://app.phoenix.arize.com"
- />
- </>
- )}
- {type === TracingProvider.aliyun && (
- <>
- <Field
- label="License Key"
- labelClassName="text-sm!"
- isRequired
- value={(config as AliyunConfig).license_key}
- onChange={handleConfigChange('license_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'License Key',
- })!}
- />
- <Field
- label="Endpoint"
- labelClassName="text-sm!"
- value={(config as AliyunConfig).endpoint}
- onChange={handleConfigChange('endpoint')}
- placeholder="https://tracing.arms.aliyuncs.com"
- />
- <Field
- label="App Name"
- labelClassName="text-sm!"
- value={(config as AliyunConfig).app_name}
- onChange={handleConfigChange('app_name')}
- />
- </>
- )}
- {type === TracingProvider.tencent && (
- <>
- <Field
- label="Token"
- labelClassName="text-sm!"
- isRequired
- value={(config as TencentConfig).token}
- onChange={handleConfigChange('token')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'Token',
- })!}
- />
- <Field
- label="Endpoint"
- labelClassName="text-sm!"
- isRequired
- value={(config as TencentConfig).endpoint}
- onChange={handleConfigChange('endpoint')}
- placeholder="https://your-region.cls.tencentcs.com"
- />
- <Field
- label="Service Name"
- labelClassName="text-sm!"
- isRequired
- value={(config as TencentConfig).service_name}
- onChange={handleConfigChange('service_name')}
- placeholder="dify_app"
- />
- </>
- )}
- {type === TracingProvider.weave && (
- <>
- <Field
- label="API Key"
- labelClassName="text-sm!"
- isRequired
- value={(config as WeaveConfig).api_key}
- onChange={handleConfigChange('api_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'API Key',
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })!}
- labelClassName="text-sm!"
- isRequired
- value={(config as WeaveConfig).project}
- onChange={handleConfigChange('project')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })!}
- />
- <Field
- label="Entity"
- labelClassName="text-sm!"
- value={(config as WeaveConfig).entity}
- onChange={handleConfigChange('entity')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'Entity',
- })!}
- />
- <Field
- label="Endpoint"
- labelClassName="text-sm!"
- value={(config as WeaveConfig).endpoint}
- onChange={handleConfigChange('endpoint')}
- placeholder="https://trace.wandb.ai/"
- />
- <Field
- label="Host"
- labelClassName="text-sm!"
- value={(config as WeaveConfig).host}
- onChange={handleConfigChange('host')}
- placeholder="https://api.wandb.ai"
- />
- </>
- )}
- {type === TracingProvider.langSmith && (
- <>
- <Field
- label="API Key"
- labelClassName="text-sm!"
- isRequired
- value={(config as LangSmithConfig).api_key}
- onChange={handleConfigChange('api_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'API Key',
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })!}
- labelClassName="text-sm!"
- isRequired
- value={(config as LangSmithConfig).project}
- onChange={handleConfigChange('project')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })!}
- />
- <Field
- label="Endpoint"
- labelClassName="text-sm!"
- value={(config as LangSmithConfig).endpoint}
- onChange={handleConfigChange('endpoint')}
- placeholder="https://api.smith.langchain.com"
- />
- </>
- )}
- {type === TracingProvider.langfuse && (
- <>
- <Field
- label={t(($) => $[`${I18N_PREFIX}.secretKey`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as LangFuseConfig).secret_key}
- isRequired
- onChange={handleConfigChange('secret_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.secretKey`], { ns: 'app' }),
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.publicKey`], { ns: 'app' })!}
- labelClassName="text-sm!"
- isRequired
- value={(config as LangFuseConfig).public_key}
- onChange={handleConfigChange('public_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.publicKey`], { ns: 'app' }),
- })!}
- />
- <Field
- label="Host"
- labelClassName="text-sm!"
- isRequired
- value={(config as LangFuseConfig).host}
- onChange={handleConfigChange('host')}
- placeholder="https://cloud.langfuse.com"
- />
- </>
- )}
- {type === TracingProvider.opik && (
- <>
- <Field
- label="API Key"
- labelClassName="text-sm!"
- value={(config as OpikConfig).api_key}
- onChange={handleConfigChange('api_key')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: 'API Key',
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as OpikConfig).project}
- onChange={handleConfigChange('project')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
- })!}
- />
- <Field
- label="Workspace"
- labelClassName="text-sm!"
- value={(config as OpikConfig).workspace}
- onChange={handleConfigChange('workspace')}
- placeholder="default"
- />
- <Field
- label="Url"
- labelClassName="text-sm!"
- value={(config as OpikConfig).url}
- onChange={handleConfigChange('url')}
- placeholder="https://www.comet.com/opik/api/"
- />
- </>
- )}
- {type === TracingProvider.mlflow && (
- <>
- <Field
- label={t(($) => $[`${I18N_PREFIX}.trackingUri`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as MLflowConfig).tracking_uri}
- isRequired
- onChange={handleConfigChange('tracking_uri')}
- placeholder="http://localhost:5000"
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' })!}
- labelClassName="text-sm!"
- isRequired
- value={(config as MLflowConfig).experiment_id}
- onChange={handleConfigChange('experiment_id')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' }),
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.username`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as MLflowConfig).username}
- onChange={handleConfigChange('username')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.username`], { ns: 'app' }),
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.password`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as MLflowConfig).password}
- onChange={handleConfigChange('password')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.password`], { ns: 'app' }),
- })!}
- />
- </>
- )}
- {type === TracingProvider.databricks && (
- <>
- <Field
- label={t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as DatabricksConfig).experiment_id}
- onChange={handleConfigChange('experiment_id')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' }),
- })!}
- isRequired
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.databricksHost`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as DatabricksConfig).host}
- onChange={handleConfigChange('host')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.databricksHost`], { ns: 'app' }),
- })!}
- isRequired
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.clientId`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as DatabricksConfig).client_id}
- onChange={handleConfigChange('client_id')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.clientId`], { ns: 'app' }),
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.clientSecret`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as DatabricksConfig).client_secret}
- onChange={handleConfigChange('client_secret')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.clientSecret`], { ns: 'app' }),
- })!}
- />
- <Field
- label={t(($) => $[`${I18N_PREFIX}.personalAccessToken`], { ns: 'app' })!}
- labelClassName="text-sm!"
- value={(config as DatabricksConfig).personal_access_token}
- onChange={handleConfigChange('personal_access_token')}
- placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
- ns: 'app',
- key: t(($) => $[`${I18N_PREFIX}.personalAccessToken`], { ns: 'app' }),
- })!}
- />
- </>
- )}
- </div>
- <div className="my-8 flex h-8 items-center justify-between">
- <a
- className="flex items-center space-x-1 text-xs leading-4.5 font-normal text-primary-600"
- target="_blank"
- href={docURL[type]}
- >
- <span>
- {t(($) => $[`${I18N_PREFIX}.viewDocsLink`], {
+ <Form<TraceConfigPayload['tracing_config']> className="px-8 pb-8" onFormSubmit={handleSave}>
+ <div className="space-y-4">
+ {type === TracingProvider.arize && (
+ <>
+ <Field disabled={saveConfig.isPending} name="api_key">
+ <FieldLabel>
+ API Key
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ ref={firstInputRef}
+ required
+ defaultValue={payload?.api_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'API Key',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="space_id">
+ <FieldLabel>
+ Space ID
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ required
+ defaultValue={payload?.space_id ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'Space ID',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="project">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ required
+ defaultValue={payload?.project ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="endpoint">
+ <FieldLabel>Endpoint</FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ defaultValue={payload?.endpoint ?? ''}
+ placeholder="https://otlp.arize.com"
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.phoenix && (
+ <>
+ <Field disabled={saveConfig.isPending} name="api_key">
+ <FieldLabel>
+ API Key
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ ref={firstInputRef}
+ required
+ defaultValue={payload?.api_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'API Key',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="project">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ required
+ defaultValue={payload?.project ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="endpoint">
+ <FieldLabel>Endpoint</FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ defaultValue={payload?.endpoint ?? ''}
+ placeholder="https://app.phoenix.arize.com"
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.aliyun && (
+ <>
+ <Field disabled={saveConfig.isPending} name="license_key">
+ <FieldLabel>
+ License Key
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ pattern=".*\S.*"
+ ref={firstInputRef}
+ required
+ defaultValue={payload?.license_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'License Key',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="endpoint">
+ <FieldLabel>
+ Endpoint
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ required
+ defaultValue={payload?.endpoint ?? ''}
+ placeholder="https://tracing.arms.aliyuncs.com"
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="app_name">
+ <FieldLabel>
+ App Name
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input required defaultValue={payload?.app_name ?? ''} />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.tencent && (
+ <>
+ <Field disabled={saveConfig.isPending} name="token">
+ <FieldLabel>
+ Token
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ pattern=".*\S.*"
+ ref={firstInputRef}
+ required
+ defaultValue={payload?.token ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'Token',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="endpoint">
+ <FieldLabel>
+ Endpoint
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ required
+ defaultValue={payload?.endpoint ?? ''}
+ placeholder="https://your-region.cls.tencentcs.com"
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="service_name">
+ <FieldLabel>
+ Service Name
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input required defaultValue={payload?.service_name ?? ''} placeholder="dify_app" />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.weave && (
+ <>
+ <Field disabled={saveConfig.isPending} name="api_key">
+ <FieldLabel>
+ API Key
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ ref={firstInputRef}
+ required
+ defaultValue={payload?.api_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'API Key',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="project">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ required
+ defaultValue={payload?.project ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="entity">
+ <FieldLabel>Entity</FieldLabel>
+ <Input
+ defaultValue={payload?.entity ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'Entity',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="endpoint">
+ <FieldLabel>Endpoint</FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]://.+"
+ defaultValue={payload?.endpoint ?? ''}
+ placeholder="https://trace.wandb.ai/"
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="host">
+ <FieldLabel>Host</FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ defaultValue={payload?.host ?? ''}
+ placeholder="https://api.wandb.ai"
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.langSmith && (
+ <>
+ <Field disabled={saveConfig.isPending} name="api_key">
+ <FieldLabel>
+ API Key
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ ref={firstInputRef}
+ required
+ defaultValue={payload?.api_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'API Key',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="project">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ required
+ defaultValue={payload?.project ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="endpoint">
+ <FieldLabel>Endpoint</FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]://.+"
+ defaultValue={payload?.endpoint ?? ''}
+ placeholder="https://api.smith.langchain.com"
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.langfuse && (
+ <>
+ <Field disabled={saveConfig.isPending} name="secret_key">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.secretKey`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ ref={firstInputRef}
+ defaultValue={payload?.secret_key ?? ''}
+ required
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.secretKey`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="public_key">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.publicKey`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ required
+ defaultValue={payload?.public_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.publicKey`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="host">
+ <FieldLabel>
+ Host
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ required
+ defaultValue={payload?.host ?? ''}
+ placeholder="https://cloud.langfuse.com"
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.opik && (
+ <>
+ <Field disabled={saveConfig.isPending} name="api_key">
+ <FieldLabel>API Key</FieldLabel>
+ <Input
+ ref={firstInputRef}
+ defaultValue={payload?.api_key ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: 'API Key',
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="project">
+ <FieldLabel>{t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' })}</FieldLabel>
+ <Input
+ defaultValue={payload?.project ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.project`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="workspace">
+ <FieldLabel>Workspace</FieldLabel>
+ <Input defaultValue={payload?.workspace ?? ''} placeholder="default" />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="url">
+ <FieldLabel>Url</FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.*/api/"
+ defaultValue={payload?.url ?? ''}
+ placeholder="https://www.comet.com/opik/api/"
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.mlflow && (
+ <>
+ <Field disabled={saveConfig.isPending} name="tracking_uri">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.trackingUri`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ ref={firstInputRef}
+ defaultValue={payload?.tracking_uri ?? ''}
+ required
+ placeholder="http://localhost:5000"
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="experiment_id">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ inputMode="numeric"
+ pattern="\s*[0-9]+\s*"
+ required
+ defaultValue={payload?.experiment_id ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="username">
+ <FieldLabel>{t(($) => $[`${I18N_PREFIX}.username`], { ns: 'app' })}</FieldLabel>
+ <Input
+ defaultValue={payload?.username ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.username`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="password">
+ <FieldLabel>{t(($) => $[`${I18N_PREFIX}.password`], { ns: 'app' })}</FieldLabel>
+ <Input
+ defaultValue={payload?.password ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.password`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ {type === TracingProvider.databricks && (
+ <>
+ <Field disabled={saveConfig.isPending} name="experiment_id">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ inputMode="numeric"
+ pattern="\s*[0-9]+\s*"
+ ref={firstInputRef}
+ defaultValue={payload?.experiment_id ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.experimentId`], { ns: 'app' }),
+ })}
+ required
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="host">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.databricksHost`], { ns: 'app' })}
+ <span aria-hidden className="text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
+ <Input
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.+"
+ defaultValue={payload?.host ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.databricksHost`], { ns: 'app' }),
+ })}
+ required
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="client_id">
+ <FieldLabel>{t(($) => $[`${I18N_PREFIX}.clientId`], { ns: 'app' })}</FieldLabel>
+ <Input
+ defaultValue={payload?.client_id ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.clientId`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="client_secret">
+ <FieldLabel>{t(($) => $[`${I18N_PREFIX}.clientSecret`], { ns: 'app' })}</FieldLabel>
+ <Input
+ defaultValue={payload?.client_secret ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.clientSecret`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ <Field disabled={saveConfig.isPending} name="personal_access_token">
+ <FieldLabel>
+ {t(($) => $[`${I18N_PREFIX}.personalAccessToken`], { ns: 'app' })}
+ </FieldLabel>
+ <Input
+ defaultValue={payload?.personal_access_token ?? ''}
+ placeholder={t(($) => $[`${I18N_PREFIX}.placeholder`], {
+ ns: 'app',
+ key: t(($) => $[`${I18N_PREFIX}.personalAccessToken`], { ns: 'app' }),
+ })}
+ />
+ <FieldError />
+ </Field>
+ </>
+ )}
+ </div>
+ {saveConfig.error && (
+ <p role="alert" className="mt-4 system-sm-regular text-text-destructive">
+ {saveConfig.error.message}
+ </p>
+ )}
+ <div className="mt-8 flex items-center justify-between gap-4">
+ <a
+ className="flex items-center space-x-1 text-xs leading-4.5 font-normal text-primary-600"
+ target="_blank"
+ href={docURL[type]}
+ >
+ <span>
+ {t(($) => $[`${I18N_PREFIX}.viewDocsLink`], {
+ ns: 'app',
+ key: t(($) => $[`tracing.${type}.title`], { ns: 'app' }),
+ })}
+ </span>
+ <span aria-hidden className="i-custom-vender-line-general-link-external-02 size-3" />
+ </a>
+ <div className="flex items-center">
+ {isEdit && (
+ <>
+ <AlertDialog>
+ <AlertDialogTrigger
+ render={<Button className="h-9 text-sm font-medium" tone="destructive" />}
+ >
+ {t(($) => $['operation.remove'], { ns: 'common' })}
+ </AlertDialogTrigger>
+ <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(($) => $[`${I18N_PREFIX}.removeConfirmTitle`], {
ns: 'app',
key: t(($) => $[`tracing.${type}.title`], { ns: 'app' }),
})}
- </span>
- <span
- aria-hidden
- className="i-custom-vender-line-general-link-external-02 size-3"
- />
- </a>
- <div className="flex items-center">
- {isEdit && (
- <>
- <Button
- className="h-9 text-sm font-medium text-text-secondary"
- onClick={showRemoveConfirm}
- >
- <span className="text-[#D92D20]">
- {t(($) => $['operation.remove'], { ns: 'common' })}
- </span>
- </Button>
- <Separator orientation="vertical" className="mx-3 h-4.5" />
- </>
- )}
- <Button
- className="mr-2 h-9 text-sm font-medium text-text-secondary"
- onClick={() => setIsConfigDialogOpen(false)}
- >
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t(($) => $[`${I18N_PREFIX}.removeConfirmContent`], { ns: 'app' })}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton>
{t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button
- className="h-9 text-sm font-medium"
- variant="primary"
- onClick={handleSave}
- loading={isSaving}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ onClick={handleRemove}
+ loading={removeConfig.isPending}
>
- {t(($) => $[`operation.${isAdd ? 'saveAndEnable' : 'save'}`], {
- ns: 'common',
- })}
- </Button>
- </div>
- </div>
- </div>
- <div className="border-t-[0.5px] border-divider-regular">
- <div className="flex items-center justify-center bg-background-section-burn py-3 text-xs text-text-tertiary">
- <span
- aria-hidden
- className="mr-1 i-custom-vender-solid-security-lock-01 size-3 text-text-tertiary"
- />
- {t(($) => $['modelProvider.encrypted.front'], { ns: 'modelProvider' })}
- <a
- className="mx-1 text-primary-600"
- target="_blank"
- rel="noopener noreferrer"
- href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html"
- >
- PKCS1_OAEP
- </a>
- {t(($) => $['modelProvider.encrypted.back'], { ns: 'modelProvider' })}
- </div>
- </div>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- ) : (
- <AlertDialog open={isRemoveDialogOpen} onOpenChange={setIsRemoveDialogOpen}>
- <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(($) => $[`${I18N_PREFIX}.removeConfirmTitle`], {
- ns: 'app',
- key: t(($) => $[`tracing.${type}.title`], { ns: 'app' }),
- })!}
- </AlertDialogTitle>
- <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
- {t(($) => $[`${I18N_PREFIX}.removeConfirmContent`], { ns: 'app' })}
- </AlertDialogDescription>
- </div>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton onClick={handleRemove}>
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )}
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ <Separator orientation="vertical" className="mx-3 h-4.5" />
+ </>
+ )}
+ <DialogClose
+ render={<Button className="mr-2 h-9 text-sm font-medium text-text-secondary" />}
+ >
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ <Button
+ className="h-9 text-sm font-medium"
+ variant="primary"
+ type="submit"
+ loading={saveConfig.isPending}
+ >
+ {t(($) => $[`operation.${isEdit ? 'save' : 'saveAndEnable'}`], {
+ ns: 'common',
+ })}
+ </Button>
+ </div>
+ </div>
+ </Form>
+ <div className="border-t-[0.5px] border-divider-regular">
+ <div className="flex items-center justify-center bg-background-section-burn py-3 text-xs text-text-tertiary">
+ <span
+ aria-hidden
+ className="mr-1 i-custom-vender-solid-security-lock-01 size-3 text-text-tertiary"
+ />
+ {t(($) => $['modelProvider.encrypted.front'], { ns: 'modelProvider' })}
+ <a
+ className="mx-1 text-primary-600"
+ target="_blank"
+ rel="noopener noreferrer"
+ href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html"
+ >
+ PKCS1_OAEP
+ </a>
+ {t(($) => $['modelProvider.encrypted.back'], { ns: 'modelProvider' })}
+ </div>
+ </div>
</>
)
}
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-panel.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-panel.tsx
index 55c1fee7ac0..8825e15db35 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-panel.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-panel.tsx
@@ -1,22 +1,27 @@
'use client'
+import type { TraceAppConfigResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { FC } from 'react'
+import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { RiEqualizer2Line } from '@remixicon/react'
+import { DialogTrigger } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
-import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { TracingProvider } from './type'
const I18N_PREFIX = 'tracing'
+export type ProviderConfigError = {
+ onRetry: () => void
+ isRetrying: boolean
+}
+
type Props = Readonly<{
type: TracingProvider
readOnly: boolean
isChosen: boolean
- config: any
+ config: TraceAppConfigResponse['tracing_config']
+ configError?: ProviderConfigError
onChoose: () => void
- hasConfigured: boolean
- onConfig: () => void
}>
const getIconClassName = (type: TracingProvider) => {
@@ -34,56 +39,33 @@ const getIconClassName = (type: TracingProvider) => {
}[type]
}
-const ProviderPanel: FC<Props> = ({
- type,
- readOnly,
- isChosen,
- config,
- onChoose,
- hasConfigured,
- onConfig,
-}) => {
- const { t } = useTranslation(['app'])
+const ProviderPanel: FC<Props> = ({ type, readOnly, isChosen, config, configError, onChoose }) => {
+ const { t } = useTranslation(['app', 'common'])
const iconClassName = getIconClassName(type)
+ const hasConfigured = !!config
- const handleConfigBtnClick = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation()
- onConfig()
- },
- [onConfig],
- )
-
- const viewBtnClick = useCallback(
- (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
-
- const url = config?.project_url
- if (url) window.open(url, '_blank', 'noopener,noreferrer')
- },
- [config?.project_url],
- )
-
- const handleChosen = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation()
- if (isChosen || !hasConfigured || readOnly) return
- onChoose()
- },
- [hasConfigured, isChosen, onChoose, readOnly],
- )
return (
<div
className={cn(
- 'rounded-xl border-[1.5px] bg-background-section-burn px-4 py-3',
+ 'relative rounded-xl border-[1.5px] bg-background-section-burn px-4 py-3',
isChosen
? 'border-components-option-card-option-selected-border bg-background-section'
: 'border-transparent',
- !isChosen && hasConfigured && !readOnly && 'cursor-pointer',
)}
- onClick={handleChosen}
+ role="group"
+ aria-label={t(($) => $[`${I18N_PREFIX}.${type}.title`], { ns: 'app' })}
>
+ {hasConfigured && !configError && !readOnly && (
+ <button
+ type="button"
+ aria-label={t(($) => $[`${I18N_PREFIX}.${type}.title`], { ns: 'app' })}
+ aria-pressed={isChosen}
+ className="absolute inset-0 cursor-pointer rounded-xl focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ onClick={() => {
+ if (!isChosen) onChoose()
+ }}
+ />
+ )}
<div className="flex items-center justify-between space-x-1">
<div className="flex items-center">
<span aria-hidden className={cn(iconClassName, 'h-6')} />
@@ -93,29 +75,32 @@ const ProviderPanel: FC<Props> = ({
</div>
)}
</div>
- {!readOnly && (
- <div className="flex items-center justify-between space-x-1">
- {hasConfigured && (
- <div
- className="flex h-6 cursor-pointer items-center space-x-1 rounded-md border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-2 text-text-secondary shadow-xs"
- onClick={viewBtnClick}
- >
- <span aria-hidden className="i-custom-vender-solid-general-eye size-3" />
- <div className="text-xs font-medium">
+ {configError ? (
+ <Button size="small" disabled={configError.isRetrying} onClick={configError.onRetry}>
+ {t(($) => $['errorBoundary.tryAgain'], { ns: 'common' })}
+ </Button>
+ ) : (
+ !readOnly && (
+ <div className="relative flex items-center justify-between space-x-1">
+ {hasConfigured && (
+ <a
+ className={buttonVariants({ size: 'small' })}
+ href={config.project_url || undefined}
+ target="_blank"
+ rel="noopener noreferrer"
+ role={config.project_url ? undefined : 'link'}
+ aria-disabled={!config.project_url}
+ >
+ <span aria-hidden className="i-custom-vender-solid-general-eye size-3" />
{t(($) => $[`${I18N_PREFIX}.view`], { ns: 'app' })}
- </div>
- </div>
- )}
- <div
- className="flex h-6 cursor-pointer items-center space-x-1 rounded-md border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-2 text-text-secondary shadow-xs"
- onClick={handleConfigBtnClick}
- >
- <RiEqualizer2Line className="size-3" />
- <div className="text-xs font-medium">
+ </a>
+ )}
+ <DialogTrigger payload={type} render={<Button size="small" />}>
+ <span aria-hidden className="i-ri-equalizer-2-line size-3" />
{t(($) => $[`${I18N_PREFIX}.config`], { ns: 'app' })}
- </div>
+ </DialogTrigger>
</div>
- </div>
+ )
)}
</div>
<div className="mt-2 system-xs-regular text-text-tertiary">
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type.ts b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type.ts
index 83cc6be2637..254cce08963 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type.ts
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type.ts
@@ -12,70 +12,3 @@ export const TracingProvider = {
} as const
export type TracingProvider = (typeof TracingProvider)[keyof typeof TracingProvider]
-
-export type ArizeConfig = {
- api_key: string
- space_id: string
- project: string
- endpoint: string
-}
-
-export type PhoenixConfig = {
- api_key: string
- project: string
- endpoint: string
-}
-
-export type LangSmithConfig = {
- api_key: string
- project: string
- endpoint: string
-}
-
-export type LangFuseConfig = {
- public_key: string
- secret_key: string
- host: string
-}
-
-export type OpikConfig = {
- api_key: string
- project: string
- workspace: string
- url: string
-}
-
-export type WeaveConfig = {
- api_key: string
- entity: string
- project: string
- endpoint: string
- host: string
-}
-
-export type AliyunConfig = {
- app_name: string
- license_key: string
- endpoint: string
-}
-
-export type MLflowConfig = {
- tracking_uri: string
- experiment_id: string
- username: string
- password: string
-}
-
-export type DatabricksConfig = {
- experiment_id: string
- host: string
- client_id: string
- client_secret: string
- personal_access_token: string
-}
-
-export type TencentConfig = {
- token: string
- endpoint: string
- service_name: string
-}
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsx
index 982fadb3b27..f91c3195859 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsx
@@ -3,7 +3,6 @@
import { useSuspenseQueries } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import * as React from 'react'
-import ApikeyInfoPanel from '@/app/components/app/overview/apikey-info-panel'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { consoleQuery } from '@/service/console'
@@ -39,20 +38,15 @@ const OverviewView = ({ appId }: OverviewViewProps) => {
if (!appACLCapabilities.canMonitor) return null
return (
- <div className="flex h-full min-h-0 flex-col">
- <ApikeyInfoPanel />
- <div className="min-h-0 flex-1">
- <ChartView
- appId={appId}
- appMode={appDetail.mode}
- headerRight={
- appACLCapabilities.canConfigureTracing ? (
- <TracingPanel appId={appId} readOnly={false} />
- ) : null
- }
- />
- </div>
- </div>
+ <ChartView
+ appId={appId}
+ appMode={appDetail.mode}
+ headerRight={
+ appACLCapabilities.canConfigureTracing ? (
+ <TracingPanel appId={appId} readOnly={false} />
+ ) : null
+ }
+ />
)
}
diff --git a/web/app/components/app/monitoring/date-range-picker.tsx b/web/app/components/app/monitoring/date-range-picker.tsx
index a541aa5f01a..fb8f5c932b6 100644
--- a/web/app/components/app/monitoring/date-range-picker.tsx
+++ b/web/app/components/app/monitoring/date-range-picker.tsx
@@ -35,12 +35,14 @@ export function MonitoringDateRangePicker({ start, end, onStartChange, onEndChan
}}
>
<DatePickerLabel className="sr-only">{t(($) => $['picker.startDate'])}</DatePickerLabel>
- <DatePickerTrigger className="h-7 w-auto px-1">
+ <DatePickerTrigger className="h-7 w-auto bg-transparent px-1">
<DatePickerValue>{formatToLocalTime(start, locale, 'MMM D')}</DatePickerValue>
</DatePickerTrigger>
<DatePickerContent />
</DatePicker>
- <span aria-hidden="true">–</span>
+ <span aria-hidden="true" className="shrink-0 system-sm-regular text-text-tertiary">
+ -
+ </span>
<DatePicker
value={end.format('YYYY-MM-DD')}
minDate={start.format('YYYY-MM-DD')}
@@ -50,7 +52,7 @@ export function MonitoringDateRangePicker({ start, end, onStartChange, onEndChan
}}
>
<DatePickerLabel className="sr-only">{t(($) => $['picker.endDate'])}</DatePickerLabel>
- <DatePickerTrigger className="h-7 w-auto px-1">
+ <DatePickerTrigger className="h-7 w-auto bg-transparent px-1">
<DatePickerValue>{formatToLocalTime(end, locale, 'MMM D')}</DatePickerValue>
</DatePickerTrigger>
<DatePickerContent />
diff --git a/web/app/components/app/overview/__tests__/app-chart.spec.tsx b/web/app/components/app/overview/__tests__/app-chart.spec.tsx
index ad8a8bb2e47..8480d40cb6a 100644
--- a/web/app/components/app/overview/__tests__/app-chart.spec.tsx
+++ b/web/app/components/app/overview/__tests__/app-chart.spec.tsx
@@ -1,5 +1,8 @@
-import { render, screen } from '@testing-library/react'
-import Chart, { MessagesChart } from '../app-chart'
+import { act, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { consoleQuery } from '@/service/console'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import Chart, { AppCharts } from '../app-chart'
const reactEChartsMock = vi.fn()
vi.mock('echarts-for-react/esm/core', () => ({
@@ -9,12 +12,16 @@ vi.mock('echarts-for-react/esm/core', () => ({
},
}))
-const mockUseAppDailyMessages = vi.fn()
-
-vi.mock('@tanstack/react-query', () => ({
- useQuery: (...args: unknown[]) => mockUseAppDailyMessages(...args),
+const { request } = vi.hoisted(() => ({ request: vi.fn<() => Promise<Response>>() }))
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request,
}))
+beforeEach(() => {
+ request.mockReset()
+})
+
describe('app-chart', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -47,44 +54,89 @@ describe('app-chart', () => {
expect(screen.getByRole('img', { name: 'Chart' }))!.toBeInTheDocument()
})
})
+})
- describe('MessagesChart', () => {
- it('should render fallback chart data when the API returns no rows', () => {
- mockUseAppDailyMessages.mockReturnValue({
- data: { data: [] },
- isLoading: false,
- })
+it('starts workflow statistics together and reveals them only after the last response', async () => {
+ const responses: Array<(response: Response) => void> = []
+ request.mockImplementation(
+ () =>
+ new Promise<Response>((resolve) => {
+ responses.push(resolve)
+ }),
+ )
+ const { rerender } = render(
+ <AppCharts id="app-1" appMode="workflow" period={{ name: 'Today' }} />,
+ )
+ await waitFor(() => expect(responses).toHaveLength(4))
+ expect(screen.getAllByRole('region')).toHaveLength(4)
+ expect(screen.getAllByRole('status')).toHaveLength(4)
+ await act(async () => {
+ responses.slice(0, 3).forEach((resolve) => resolve(Response.json({ data: [] })))
+ })
+ expect(screen.queryByRole('img', { name: 'Chart' })).not.toBeInTheDocument()
+ expect(screen.getAllByRole('status')).toHaveLength(4)
+ await act(async () => {
+ responses[3]!(Response.json({ data: [] }))
+ })
+ expect(await screen.findAllByRole('img', { name: 'Chart' })).toHaveLength(4)
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
- render(
- <MessagesChart
- id="app-1"
- period={{
- name: 'Last week',
- query: {
- start: 'Jan 1, 2024',
- end: 'Jan 4, 2024',
- },
- }}
- />,
- )
+ responses.length = 0
+ rerender(
+ <AppCharts
+ id="app-1"
+ appMode="workflow"
+ period={{ name: 'Last week', query: { start: '2026-10-08 00:00', end: '2026-10-15 23:59' } }}
+ />,
+ )
+ await waitFor(() => expect(responses).toHaveLength(4))
+ await act(async () => {
+ responses.slice(0, 3).forEach((resolve) => resolve(Response.json({ data: [] })))
+ })
+ expect(screen.queryByRole('img', { name: 'Chart' })).not.toBeInTheDocument()
+ await act(async () => {
+ responses[3]!(Response.json({ data: [] }))
+ })
+ expect(await screen.findAllByRole('img', { name: 'Chart' })).toHaveLength(4)
+})
- expect(screen.getByText(/(?:^|\.)analysis\.totalMessages\.title(?=$|:)/))!.toBeInTheDocument()
- expect(screen.getByText('0'))!.toBeInTheDocument()
- expect(screen.getByRole('img', { name: 'Chart' }))!.toBeInTheDocument()
+it('renders zero-valued charts for an empty statistics response', async () => {
+ request.mockImplementation(async () => Response.json({ data: [] }))
+ render(<AppCharts id="app-1" appMode="workflow" period={{ name: 'Today' }} />)
+ expect(await screen.findAllByRole('img', { name: 'Chart' })).toHaveLength(4)
+ const messages = screen.getByRole('region', { name: /analysis.totalMessages.title/ })
+ expect(within(messages).getByText('0')).toBeInTheDocument()
+ expect(within(messages).queryByRole('alert')).not.toBeInTheDocument()
+})
- const chartProps = reactEChartsMock.mock.calls[0]![0] as {
- option: {
- dataset: { source: Array<Record<string, unknown>> }
- yAxis: { max: number }
- }
- opts: { renderer: string }
- }
- const options = chartProps.option
+it('recovers failed statistics through retry after the batch settles', async () => {
+ request.mockImplementation(async () => Response.json({ message: 'Unavailable' }, { status: 503 }))
+ render(<AppCharts id="app-1" appMode="workflow" period={{ name: 'Today' }} />)
+ const retries = await screen.findAllByRole('button', { name: 'common.errorBoundary.tryAgain' })
+ expect(retries).toHaveLength(4)
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ request.mockImplementation(async () => Response.json({ data: [] }))
+ const user = userEvent.setup()
+ await user.click(retries[0]!)
+ expect(await screen.findAllByRole('img', { name: 'Chart' })).toHaveLength(4)
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+})
- expect(chartProps.opts).toEqual({ renderer: 'svg' })
- expect(options.yAxis.max).toBe(500)
- expect(options.dataset.source).toHaveLength(3)
- expect(options.dataset.source[0]).toEqual({ date: 'Jan 1, 2024', message_count: 0 })
+it('retains loaded charts when a background statistics refresh fails', async () => {
+ request.mockImplementation(async () => Response.json({ data: [] }))
+ const { queryClient } = render(
+ <AppCharts id="app-1" appMode="workflow" period={{ name: 'Today' }} />,
+ )
+ await screen.findAllByRole('img', { name: 'Chart' })
+ request.mockImplementation(async () =>
+ Response.json({ message: 'Refresh unavailable' }, { status: 503 }),
+ )
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflow.statistics.key(),
})
})
+ expect(screen.getAllByRole('img', { name: 'Chart' })).toHaveLength(4)
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
})
diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx
deleted file mode 100644
index efe8a459829..00000000000
--- a/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { cleanup, screen } from '@testing-library/react'
-import {
- clearAllMocks,
- interactions,
- mockSetSettingsDestination,
- scenarios,
- setDeploymentEdition,
-} from './test-utils'
-
-afterEach(cleanup)
-
-describe('APIKeyInfoPanel - Cloud Edition', () => {
- beforeEach(() => {
- clearAllMocks()
- setDeploymentEdition('CLOUD')
- })
-
- it('hides the panel when an API key already exists', () => {
- const { container } = scenarios.withAPIKeySet()
- expect(container).toBeEmptyDOMElement()
- })
-
- it('opens provider settings from the primary action', () => {
- scenarios.withAPIKeyNotSet()
- interactions.clickMainButton()
- expect(mockSetSettingsDestination).toHaveBeenCalledWith('provider')
- })
-
- it('does not show the self-hosted Cloud link', () => {
- scenarios.withAPIKeyNotSet()
- expect(screen.queryByRole('link')).not.toBeInTheDocument()
- })
-
- it('dismisses the panel from the close action', () => {
- const { container } = scenarios.withAPIKeyNotSet()
- interactions.clickCloseButton(container)
- expect(container).toBeEmptyDOMElement()
- })
-})
diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx
deleted file mode 100644
index 75d6c60cef6..00000000000
--- a/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { cleanup, screen } from '@testing-library/react'
-import {
- clearAllMocks,
- interactions,
- mockSetSettingsDestination,
- scenarios,
- setDeploymentEdition,
- textKeys,
-} from './test-utils'
-
-afterEach(cleanup)
-
-describe('APIKeyInfoPanel - Community Edition', () => {
- beforeEach(() => {
- clearAllMocks()
- setDeploymentEdition('COMMUNITY')
- })
-
- it('hides the panel when an API key already exists', () => {
- const { container } = scenarios.withAPIKeySet()
- expect(container).toBeEmptyDOMElement()
- })
-
- it('opens provider settings from the primary action', () => {
- scenarios.withAPIKeyNotSet()
- interactions.clickMainButton()
- expect(mockSetSettingsDestination).toHaveBeenCalledWith('provider')
- })
-
- it('links self-hosted users to Dify Cloud safely', () => {
- scenarios.withAPIKeyNotSet()
- expect(screen.getByRole('link', { name: textKeys.selfHost.tryCloud })).toMatchObject({
- target: '_blank',
- rel: 'noopener noreferrer',
- })
- })
-
- it('dismisses the panel from the close action', () => {
- const { container } = scenarios.withAPIKeyNotSet()
- interactions.clickCloseButton(container)
- expect(container).toBeEmptyDOMElement()
- })
-})
diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
deleted file mode 100644
index 386ce075a67..00000000000
--- a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'
-import type { AvailableModelListResponse } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { RenderOptions } from '@testing-library/react'
-import { fireEvent, screen } from '@testing-library/react'
-import { consoleQuery } from '@/service/console'
-import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
-import APIKeyInfoPanel from '../index'
-
-const { mockRouterPush, mockSetSettingsDestination } = vi.hoisted(() => ({
- mockRouterPush: vi.fn(),
- mockSetSettingsDestination: vi.fn(),
-}))
-
-// Mock the modules before importing the functions
-
-vi.mock('nuqs', async (importOriginal) => {
- const actual = await importOriginal<typeof import('nuqs')>()
- return {
- ...actual,
- useQueryState: () => [null, mockSetSettingsDestination],
- }
-})
-
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({
- push: mockRouterPush,
- }),
-}))
-
-type MockOverrides = { hasActiveProvider?: boolean }
-
-type APIKeyInfoPanelRenderOptions = {
- mockOverrides?: MockOverrides
-} & Omit<RenderOptions, 'wrapper'>
-
-const mainButtonName = /appOverview\.apiKeyInfo\.setAPIBtn/
-let deploymentEdition: DeploymentEdition = 'COMMUNITY'
-
-// Custom render function
-function renderAPIKeyInfoPanel(options: APIKeyInfoPanelRenderOptions = {}) {
- const { mockOverrides, ...renderOptions } = options
-
- const queryClient = createConsoleQueryClient()
- queryClient.setQueryData(
- consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryKey({
- input: { params: { model_type: 'llm' } },
- }),
- {
- data: mockOverrides?.hasActiveProvider
- ? [
- {
- provider: 'openai',
- tenant_id: 'test-workspace',
- label: { en_US: 'OpenAI' },
- status: 'active',
- models: [],
- },
- ]
- : [],
- } satisfies AvailableModelListResponse,
- )
-
- return renderWithConsoleQuery(<APIKeyInfoPanel />, {
- ...renderOptions,
- queryClient,
- systemFeatures: { deployment_edition: deploymentEdition },
- })
-}
-
-// Helper functions for common test scenarios
-export const scenarios = {
- // Render with API key not set (default)
- withAPIKeyNotSet: (overrides: MockOverrides = {}) =>
- renderAPIKeyInfoPanel({
- mockOverrides: {
- hasActiveProvider: false,
- ...overrides,
- },
- }),
-
- // Render with API key already set
- withAPIKeySet: (overrides: MockOverrides = {}) =>
- renderAPIKeyInfoPanel({
- mockOverrides: {
- hasActiveProvider: true,
- ...overrides,
- },
- }),
-}
-
-// Common user interactions
-export const interactions = {
- // Click the main button
- clickMainButton: () => {
- const button = screen.getByRole('button', { name: mainButtonName })
- fireEvent.click(button)
- return button
- },
-
- // Click the close button
- clickCloseButton: (container: HTMLElement) => {
- const closeButton = container.querySelector('.absolute.right-4.top-4')
- if (closeButton) fireEvent.click(closeButton)
- return closeButton
- },
-}
-
-// Text content keys for assertions
-export const textKeys = {
- button: mainButtonName,
- selfHost: {
- titleRow1: /appOverview\.apiKeyInfo\.selfHost\.title\.row1/,
- titleRow2: /appOverview\.apiKeyInfo\.selfHost\.title\.row2/,
- setAPIBtn: /appOverview\.apiKeyInfo\.setAPIBtn/,
- tryCloud: /appOverview\.apiKeyInfo\.tryCloud/,
- },
- cloud: {
- trialTitle: /appOverview\.apiKeyInfo\.cloud\.trial\.title/,
- trialDescription: /appOverview\.apiKeyInfo\.cloud\.trial\.description/,
- setAPIBtn: /appOverview\.apiKeyInfo\.setAPIBtn/,
- },
-}
-
-// Setup and cleanup utilities
-export function clearAllMocks() {
- vi.clearAllMocks()
-}
-
-export function setDeploymentEdition(value: DeploymentEdition) {
- deploymentEdition = value
-}
-
-// Export mock functions for external access
-export { mockSetSettingsDestination }
diff --git a/web/app/components/app/overview/apikey-info-panel/index.tsx b/web/app/components/app/overview/apikey-info-panel/index.tsx
deleted file mode 100644
index 68c1626b3b1..00000000000
--- a/web/app/components/app/overview/apikey-info-panel/index.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import { RiCloseLine } from '@remixicon/react'
-import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
-import { useQueryState } from 'nuqs'
-import * as React from 'react'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import {
- settingsQueryParamName,
- settingsQueryParser,
-} from '@/app/components/header/account-setting/query-params'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import { consoleQuery } from '@/service/console'
-
-const APIKeyInfoPanel: FC = () => {
- const { data: deploymentEdition } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: ({ deployment_edition }) => deployment_edition,
- })
- const isCloud = deploymentEdition === 'CLOUD'
-
- const { data: hasActiveProvider = false } = useQuery(
- consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
- input: { params: { model_type: 'llm' } },
- select: (response) => response.data.some((provider) => provider.status === 'active'),
- }),
- )
- const [, setSettingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser)
-
- const { t } = useTranslation(['appOverview'])
-
- const [isShow, setIsShow] = useState(true)
-
- if (hasActiveProvider) return null
-
- if (!isShow) return null
-
- return (
- <div
- className={cn(
- 'border-components-panel-border bg-components-panel-bg',
- 'relative mb-6 rounded-2xl border p-8 shadow-md',
- )}
- >
- <div
- className={cn(
- 'text-[24px] font-semibold text-text-primary',
- isCloud ? 'flex h-8 items-center space-x-1' : 'mb-6 leading-8',
- )}
- >
- {isCloud && <span>😀</span>}
- {isCloud ? (
- <div>
- {t(($) => $['apiKeyInfo.cloud.trial.title'], {
- ns: 'appOverview',
- providerName: 'OpenAI',
- })}
- </div>
- ) : (
- <div>
- <div>{t(($) => $['apiKeyInfo.selfHost.title.row1'], { ns: 'appOverview' })}</div>
- <div>{t(($) => $['apiKeyInfo.selfHost.title.row2'], { ns: 'appOverview' })}</div>
- </div>
- )}
- </div>
- {isCloud && (
- <div className="mt-1 text-sm font-normal text-text-tertiary">
- {t(($) => $[`apiKeyInfo.cloud.${'trial'}.description`], { ns: 'appOverview' })}
- </div>
- )}
- <Button variant="primary" className="mt-2" onClick={() => setSettingsDestination('provider')}>
- <div className="text-sm font-medium">
- {t(($) => $['apiKeyInfo.setAPIBtn'], { ns: 'appOverview' })}
- </div>
- <span aria-hidden className="i-custom-vender-line-general-link-external-02 size-4" />
- </Button>
- {!isCloud && (
- <a
- className="mt-2 flex h-6.5 items-center space-x-1 p-1 text-xs font-medium text-primary-600"
- href="https://cloud.dify.ai/apps"
- target="_blank"
- rel="noopener noreferrer"
- >
- <div>{t(($) => $['apiKeyInfo.tryCloud'], { ns: 'appOverview' })}</div>
- <span aria-hidden className="i-custom-vender-line-general-link-external-02 size-3" />
- </a>
- )}
- <div
- onClick={() => setIsShow(false)}
- className="absolute top-4 right-4 flex size-8 cursor-pointer items-center justify-center"
- >
- <RiCloseLine className="size-4 text-text-tertiary" />
- </div>
- </div>
- )
-}
-export default React.memo(APIKeyInfoPanel)
diff --git a/web/app/components/app/overview/app-chart.tsx b/web/app/components/app/overview/app-chart.tsx
index aac66e4e936..2b63718489d 100644
--- a/web/app/components/app/overview/app-chart.tsx
+++ b/web/app/components/app/overview/app-chart.tsx
@@ -1,16 +1,18 @@
'use client'
+import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
import type { QueryKey, UseQueryOptions } from '@tanstack/react-query'
import type { Dayjs } from 'dayjs'
import type { SelectorParam } from 'i18next'
-import type { FC } from 'react'
+import type { ReactNode } from 'react'
import type { ChartRow } from './app-chart-utils'
+import { Button } from '@langgenius/dify-ui/button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
-import { useQuery } from '@tanstack/react-query'
+import { useQueries } from '@tanstack/react-query'
import ReactECharts from 'echarts-for-react/esm/core'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { echarts } from '@/app/components/base/line-chart/echarts'
-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
+import { SkeletonRectangle } from '@/app/components/base/skeleton'
import { consoleQuery } from '@/service/console'
import {
buildChartOptions,
@@ -41,7 +43,8 @@ export type PeriodParamsWithTimeRange = {
query?: TimeRange
}
-type IBizChartProps = {
+type AppChartsProps = {
+ appMode: AppDetailWithSite['mode']
period: PeriodParams
id: string
}
@@ -57,6 +60,50 @@ type IChartProps = {
chartData: { data: ChartRow[] }
}
+function ChartFrame({
+ title,
+ explanation,
+ className,
+ busy,
+ children,
+}: {
+ title: string
+ explanation: string
+ className?: string
+ busy?: boolean
+ children: ReactNode
+}) {
+ const titleId = React.useId()
+ return (
+ <section
+ aria-labelledby={titleId}
+ aria-busy={busy || undefined}
+ className={`flex h-79 w-full min-w-0 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg xl:min-w-120 ${className ?? ''}`}
+ >
+ <div className="flex h-11 shrink-0 items-center px-6 pt-6 pb-1">
+ <div className="flex min-w-0 items-center">
+ <div
+ id={titleId}
+ className="min-w-0 truncate system-sm-semibold-uppercase text-text-secondary"
+ title={title}
+ >
+ {title}
+ </div>
+ {explanation && (
+ <Infotip>
+ <InfotipTrigger aria-labelledby={titleId} className="ml-1" />
+ <InfotipContent aria-labelledby={titleId} className="w-60">
+ {explanation}
+ </InfotipContent>
+ </Infotip>
+ )}
+ </div>
+ </div>
+ {children}
+ </section>
+ )
+}
+
const ECHARTS_RENDER_OPTIONS = { renderer: 'svg' as const }
const Chart: React.FC<IChartProps> = ({
@@ -69,8 +116,6 @@ const Chart: React.FC<IChartProps> = ({
yMax,
className,
}) => {
- const titleId = React.useId()
-
const { t } = useTranslation(['appOverview'])
const statistics = chartData.data
const yField = getChartValueField(statistics, valueKey)
@@ -93,28 +138,7 @@ const Chart: React.FC<IChartProps> = ({
const isZeroSummary = !hasNonZeroChartData(statistics, yField)
return (
- <div
- className={`flex h-79 w-full min-w-0 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg xl:min-w-120 ${className ?? ''}`}
- >
- <div className="flex h-11 shrink-0 items-center px-6 pt-6 pb-1">
- <div className="flex min-w-0 items-center">
- <div
- id={titleId}
- className="min-w-0 truncate system-sm-semibold-uppercase text-text-secondary"
- title={title}
- >
- {title}
- </div>
- {explanation && (
- <Infotip>
- <InfotipTrigger aria-labelledby={titleId} className="ml-1" />
- <InfotipContent aria-labelledby={titleId} className="w-60">
- {explanation}
- </InfotipContent>
- </Infotip>
- )}
- </div>
- </div>
+ <ChartFrame title={title} explanation={explanation} className={className}>
<div className="flex h-8 shrink-0 items-baseline gap-1 px-6 py-1">
<div
className={`shrink-0 title-3xl-semi-bold ${isZeroSummary ? 'text-text-quaternary' : 'text-text-primary'}`}
@@ -138,7 +162,7 @@ const Chart: React.FC<IChartProps> = ({
style={{ height: '100%', width: '100%' }}
/>
</div>
- </div>
+ </ChartFrame>
)
}
@@ -191,65 +215,99 @@ type BizChartConfig<TData extends ChartResponse> = {
className?: string
}
-const createBizChartComponent = <TData extends ChartResponse>({
- chartType,
- titleKey,
- explanationKey,
- queryOptions,
- valueKey,
- emptyValueKey,
- yMaxWhenEmpty,
- isAvg,
- unitKey,
- className,
-}: BizChartConfig<TData>): FC<IBizChartProps> => {
- const BizChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation(['appOverview'])
- const { data: response, isLoading } = useQuery(queryOptions(id, period.query))
-
- if (isLoading || !response) return <LoadingPlaceholder />
-
- const noDataFlag = !response.data || response.data.length === 0
- const fallbackKey = emptyValueKey ?? valueKey
- const titleSelector: SelectorParam<'appOverview'> = CHART_TRANSLATION_SELECTOR_MAP[titleKey]
- const explanationSelector: SelectorParam<'appOverview'> =
- CHART_TRANSLATION_SELECTOR_MAP[explanationKey]
- const unitSelector: SelectorParam<'appOverview'> | undefined = unitKey
- ? CHART_TRANSLATION_SELECTOR_MAP[unitKey]
- : undefined
- const fallbackData = {
- data: getDefaultChartData({
- ...(period.query ?? defaultPeriod),
- ...(fallbackKey ? { key: fallbackKey } : {}),
- }),
- }
+function ChartCard({
+ response,
+ pending,
+ failed,
+ retry,
+ period,
+ config: {
+ chartType,
+ titleKey,
+ explanationKey,
+ valueKey,
+ emptyValueKey,
+ yMaxWhenEmpty,
+ isAvg,
+ unitKey,
+ className,
+ },
+}: {
+ config: BizChartConfig<ChartResponse>
+ response: ChartResponse | undefined
+ pending: boolean
+ failed: boolean
+ retry: () => void
+ period: PeriodParams
+}) {
+ const { t } = useTranslation(['appOverview', 'common'])
+ const fallbackKey = emptyValueKey ?? valueKey
+ const titleSelector: SelectorParam<'appOverview'> = CHART_TRANSLATION_SELECTOR_MAP[titleKey]
+ const explanationSelector: SelectorParam<'appOverview'> =
+ CHART_TRANSLATION_SELECTOR_MAP[explanationKey]
+ const unitSelector: SelectorParam<'appOverview'> | undefined = unitKey
+ ? CHART_TRANSLATION_SELECTOR_MAP[unitKey]
+ : undefined
+ const title = t(titleSelector, { ns: 'appOverview', defaultValue: titleKey })
+ const explanation = t(explanationSelector, { ns: 'appOverview', defaultValue: explanationKey })
+ if (pending || !response) {
return (
- <Chart
- basicInfo={{
- title: t(titleSelector, { ns: 'appOverview', defaultValue: titleKey }),
- explanation: t(explanationSelector, { ns: 'appOverview', defaultValue: explanationKey }),
- timePeriod: period.name,
- }}
- chartData={noDataFlag ? fallbackData : response}
- chartType={chartType}
- valueKey={valueKey}
- isAvg={isAvg}
- unit={
- unitKey && unitSelector
- ? t(unitSelector, { ns: 'appOverview', defaultValue: unitKey })
- : undefined
- }
- className={className}
- {...(noDataFlag && { yMax: yMaxWhenEmpty })}
- />
+ <ChartFrame title={title} explanation={explanation} className={className} busy={pending}>
+ {!pending && failed ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6">
+ <p role="alert" className="system-sm-regular text-text-tertiary">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ <Button variant="secondary" onClick={retry}>
+ {t(($) => $['errorBoundary.tryAgain'], { ns: 'common' })}
+ </Button>
+ </div>
+ ) : (
+ <div
+ role="status"
+ aria-label={t(($) => $.loading, { ns: 'common' })}
+ className="flex flex-1 flex-col gap-4 px-6 pt-1 pb-4"
+ >
+ <SkeletonRectangle className="h-6 w-16" />
+ <SkeletonRectangle className="w-full flex-1" />
+ </div>
+ )}
+ </ChartFrame>
)
}
- return BizChart
+ const noDataFlag = !response.data || response.data.length === 0
+ const fallbackData = {
+ data: getDefaultChartData({
+ ...(period.query ?? defaultPeriod),
+ ...(fallbackKey ? { key: fallbackKey } : {}),
+ }),
+ }
+
+ return (
+ <Chart
+ basicInfo={{
+ title,
+ explanation,
+ timePeriod: period.name,
+ }}
+ chartData={noDataFlag ? fallbackData : response}
+ chartType={chartType}
+ valueKey={valueKey}
+ isAvg={isAvg}
+ unit={
+ unitKey && unitSelector
+ ? t(unitSelector, { ns: 'appOverview', defaultValue: unitKey })
+ : undefined
+ }
+ className={className}
+ {...(noDataFlag && { yMax: yMaxWhenEmpty })}
+ />
+ )
}
-export const MessagesChart = createBizChartComponent({
+const MessagesChart: BizChartConfig<ChartResponse> = {
chartType: 'messages',
titleKey: 'analysis.totalMessages.title',
explanationKey: 'analysis.totalMessages.explanation',
@@ -260,9 +318,9 @@ export const MessagesChart = createBizChartComponent({
valueKey: 'message_count',
emptyValueKey: 'message_count',
yMaxWhenEmpty: 500,
-})
+}
-export const ConversationsChart = createBizChartComponent({
+const ConversationsChart: BizChartConfig<ChartResponse> = {
chartType: 'conversations',
titleKey: 'analysis.totalConversations.title',
explanationKey: 'analysis.totalConversations.explanation',
@@ -273,9 +331,9 @@ export const ConversationsChart = createBizChartComponent({
valueKey: 'conversation_count',
emptyValueKey: 'conversation_count',
yMaxWhenEmpty: 500,
-})
+}
-export const EndUsersChart = createBizChartComponent({
+const EndUsersChart: BizChartConfig<ChartResponse> = {
chartType: 'endUsers',
titleKey: 'analysis.activeUsers.title',
explanationKey: 'analysis.activeUsers.explanation',
@@ -286,9 +344,9 @@ export const EndUsersChart = createBizChartComponent({
valueKey: 'terminal_count',
emptyValueKey: 'terminal_count',
yMaxWhenEmpty: 500,
-})
+}
-export const AvgSessionInteractions = createBizChartComponent({
+const AvgSessionInteractions: BizChartConfig<ChartResponse> = {
chartType: 'conversations',
titleKey: 'analysis.avgSessionInteractions.title',
explanationKey: 'analysis.avgSessionInteractions.explanation',
@@ -300,9 +358,9 @@ export const AvgSessionInteractions = createBizChartComponent({
emptyValueKey: 'interactions',
yMaxWhenEmpty: 500,
isAvg: true,
-})
+}
-export const AvgResponseTime = createBizChartComponent({
+const AvgResponseTime: BizChartConfig<ChartResponse> = {
chartType: 'conversations',
titleKey: 'analysis.avgResponseTime.title',
explanationKey: 'analysis.avgResponseTime.explanation',
@@ -315,9 +373,9 @@ export const AvgResponseTime = createBizChartComponent({
yMaxWhenEmpty: 500,
isAvg: true,
unitKey: 'analysis.ms',
-})
+}
-export const TokenPerSecond = createBizChartComponent({
+const TokenPerSecond: BizChartConfig<ChartResponse> = {
chartType: 'conversations',
titleKey: 'analysis.tps.title',
explanationKey: 'analysis.tps.explanation',
@@ -331,9 +389,9 @@ export const TokenPerSecond = createBizChartComponent({
isAvg: true,
unitKey: 'analysis.tokenPS',
className: 'min-w-0',
-})
+}
-export const UserSatisfactionRate = createBizChartComponent({
+const UserSatisfactionRate: BizChartConfig<ChartResponse> = {
chartType: 'endUsers',
titleKey: 'analysis.userSatisfactionRate.title',
explanationKey: 'analysis.userSatisfactionRate.explanation',
@@ -346,9 +404,9 @@ export const UserSatisfactionRate = createBizChartComponent({
yMaxWhenEmpty: 1000,
isAvg: true,
className: 'h-full',
-})
+}
-export const CostChart = createBizChartComponent({
+const CostChart: BizChartConfig<ChartResponse> = {
chartType: 'costs',
titleKey: 'analysis.tokenUsage.title',
explanationKey: 'analysis.tokenUsage.explanation',
@@ -359,9 +417,9 @@ export const CostChart = createBizChartComponent({
valueKey: 'token_count',
emptyValueKey: 'token_count',
yMaxWhenEmpty: 100,
-})
+}
-export const WorkflowMessagesChart = createBizChartComponent({
+const WorkflowMessagesChart: BizChartConfig<ChartResponse> = {
chartType: 'conversations',
titleKey: 'analysis.totalMessages.title',
explanationKey: 'analysis.totalMessages.explanation',
@@ -372,9 +430,9 @@ export const WorkflowMessagesChart = createBizChartComponent({
valueKey: 'runs',
emptyValueKey: 'runs',
yMaxWhenEmpty: 500,
-})
+}
-export const WorkflowDailyTerminalsChart = createBizChartComponent({
+const WorkflowDailyTerminalsChart: BizChartConfig<ChartResponse> = {
chartType: 'endUsers',
titleKey: 'analysis.activeUsers.title',
explanationKey: 'analysis.activeUsers.explanation',
@@ -385,9 +443,9 @@ export const WorkflowDailyTerminalsChart = createBizChartComponent({
valueKey: 'terminal_count',
emptyValueKey: 'terminal_count',
yMaxWhenEmpty: 500,
-})
+}
-export const WorkflowCostChart = createBizChartComponent({
+const WorkflowCostChart: BizChartConfig<ChartResponse> = {
chartType: 'workflowCosts',
titleKey: 'analysis.tokenUsage.title',
explanationKey: 'analysis.tokenUsage.explanation',
@@ -398,9 +456,9 @@ export const WorkflowCostChart = createBizChartComponent({
valueKey: 'token_count',
emptyValueKey: 'token_count',
yMaxWhenEmpty: 100,
-})
+}
-export const AvgUserInteractions = createBizChartComponent({
+const AvgUserInteractions: BizChartConfig<ChartResponse> = {
chartType: 'conversations',
titleKey: 'analysis.avgUserInteractions.title',
explanationKey: 'analysis.avgUserInteractions.explanation',
@@ -412,5 +470,67 @@ export const AvgUserInteractions = createBizChartComponent({
emptyValueKey: 'interactions',
yMaxWhenEmpty: 500,
isAvg: true,
-})
+}
+const workflowCharts = [
+ WorkflowMessagesChart,
+ WorkflowDailyTerminalsChart,
+ WorkflowCostChart,
+ AvgUserInteractions,
+]
+const completionCharts = [
+ ConversationsChart,
+ EndUsersChart,
+ AvgResponseTime,
+ TokenPerSecond,
+ UserSatisfactionRate,
+ CostChart,
+]
+const chatCharts = [
+ ConversationsChart,
+ EndUsersChart,
+ AvgSessionInteractions,
+ TokenPerSecond,
+ UserSatisfactionRate,
+ CostChart,
+ MessagesChart,
+]
+
+export function AppCharts({ id, period, appMode }: AppChartsProps) {
+ const configs =
+ appMode === 'workflow'
+ ? workflowCharts
+ : appMode === 'completion'
+ ? completionCharts
+ : chatCharts
+ const queries = useQueries({
+ queries: configs.map((config) => config.queryOptions(id, period.query)),
+ })
+ const pending = queries.some((query) => query.isPending)
+ const retryFailedQueries = () => {
+ queries
+ .filter((query) => query.isError && !query.data)
+ .forEach((query) => {
+ void query.refetch()
+ })
+ }
+ return (
+ <div className="grid w-full grid-cols-1 gap-3 xl:grid-cols-2" aria-busy={pending || undefined}>
+ {configs.map((config, index) => {
+ const query = queries[index]!
+ return (
+ <ChartCard
+ key={config.titleKey}
+ config={config}
+ response={query.data}
+ pending={pending}
+ failed={query.isError}
+ retry={retryFailedQueries}
+ period={period}
+ />
+ )
+ })}
+ </div>
+ )
+}
+
export default Chart
diff --git a/web/i18n/locales/ar-TN/app-overview.json b/web/i18n/locales/ar-TN/app-overview.json
index 46d65354188..08d55e7489a 100644
--- a/web/i18n/locales/ar-TN/app-overview.json
+++ b/web/i18n/locales/ar-TN/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "سرعة إخراج الرمز",
"analysis.userSatisfactionRate.explanation": "عدد الإعجابات لكل 1000 رسالة. يشير هذا إلى النسبة التي يرضى فيها المستخدمون للغاية عن الإجابات.",
"analysis.userSatisfactionRate.title": "معدل رضا المستخدم",
- "apiKeyInfo.cloud.trial.description": "يتم توفير حصة التجربة لأغراض الاختبار الخاصة بك. قبل استنفاد حصة التجربة، يرجى إعداد مزود النموذج الخاص بك أو شراء حصة إضافية.",
- "apiKeyInfo.cloud.trial.title": "أنت تستخدم حصة تجربة {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "للبدء،",
- "apiKeyInfo.selfHost.title.row2": "قم بإعداد مزود النموذج الخاص بك أولاً.",
- "apiKeyInfo.setAPIBtn": "الذهاب لإعداد مزود النموذج",
- "apiKeyInfo.tryCloud": "أو جرب النسخة السحابية من Dify مع عرض مجاني",
"overview.apiInfo.accessibleAddress": "نقطة نهاية API",
"overview.apiInfo.doc": "مرجع API",
"overview.apiInfo.title": "واجهة برمجة تطبيقات خدمة الخلفية",
diff --git a/web/i18n/locales/az-AZ/app-overview.json b/web/i18n/locales/az-AZ/app-overview.json
index 5924f7c69de..1ceb50b6084 100644
--- a/web/i18n/locales/az-AZ/app-overview.json
+++ b/web/i18n/locales/az-AZ/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token çıxış sürəti",
"analysis.userSatisfactionRate.explanation": "Hər 1000 mesaja düşən bəyənmə sayı. Bu, istifadəçilərin çox razı qaldığı cavabların nisbətini göstərir.",
"analysis.userSatisfactionRate.title": "İstifadəçi məmnuniyyəti dərəcəsi",
- "apiKeyInfo.cloud.trial.description": "Sınaq kvotası sınaq məqsədləriniz üçün verilir. Sınaq kvotası bitməzdən əvvəl öz model provayderinizi quraşdırın və ya əlavə kvota alın.",
- "apiKeyInfo.cloud.trial.title": "{{providerName}} provayderinin sınaq kvotasından istifadə edirsiniz.",
- "apiKeyInfo.selfHost.title.row1": "Başlamaq üçün,",
- "apiKeyInfo.selfHost.title.row2": "əvvəlcə model provayderinizi quraşdırın.",
- "apiKeyInfo.setAPIBtn": "Model provayderinin quraşdırılmasına keç",
- "apiKeyInfo.tryCloud": "Və ya Dify-ın bulud versiyasını pulsuz kvota ilə sına",
"overview.apiInfo.accessibleAddress": "API son nöqtəsi",
"overview.apiInfo.doc": "API istinad sənədləri",
"overview.apiInfo.title": "Server xidməti API-si",
diff --git a/web/i18n/locales/de-DE/app-overview.json b/web/i18n/locales/de-DE/app-overview.json
index 480181604d4..4d10cee3a99 100644
--- a/web/i18n/locales/de-DE/app-overview.json
+++ b/web/i18n/locales/de-DE/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token-Ausgabegeschwindigkeit",
"analysis.userSatisfactionRate.explanation": "Die Anzahl der Likes pro 1.000 Nachrichten. Dies zeigt den Anteil der Antworten an, mit denen die Benutzer sehr zufrieden sind.",
"analysis.userSatisfactionRate.title": "Benutzerzufriedenheitsrate",
- "apiKeyInfo.cloud.trial.description": "Das Testkontingent wird für Ihre Testnutzung bereitgestellt. Bevor das Testkontingent aufgebraucht ist, richten Sie bitte Ihren eigenen Modellanbieter ein oder kaufen zusätzliches Kontingent.",
- "apiKeyInfo.cloud.trial.title": "Sie nutzen das Testkontingent von {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Um zu beginnen,",
- "apiKeyInfo.selfHost.title.row2": "richten Sie zuerst Ihren Modellanbieter ein.",
- "apiKeyInfo.setAPIBtn": "Zum Einrichten des Modellanbieters gehen",
- "apiKeyInfo.tryCloud": "Oder probieren Sie die Cloud-Version von Dify mit kostenlosem Angebot aus",
"overview.apiInfo.accessibleAddress": "API-Endpunkt",
"overview.apiInfo.doc": "API-Referenz",
"overview.apiInfo.title": "Backend-Service-API",
diff --git a/web/i18n/locales/en-US/app-overview.json b/web/i18n/locales/en-US/app-overview.json
index d7c659ed428..1f399e31299 100644
--- a/web/i18n/locales/en-US/app-overview.json
+++ b/web/i18n/locales/en-US/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token Output Speed",
"analysis.userSatisfactionRate.explanation": "The number of likes per 1,000 messages. This indicates the proportion of answers that users are highly satisfied with.",
"analysis.userSatisfactionRate.title": "User Satisfaction Rate",
- "apiKeyInfo.cloud.trial.description": "The trial quota is provided for your testing purposes. Before the trial quota is exhausted, please set up your own model provider or purchase additional quota.",
- "apiKeyInfo.cloud.trial.title": "You are using the {{providerName}} trial quota.",
- "apiKeyInfo.selfHost.title.row1": "To get started,",
- "apiKeyInfo.selfHost.title.row2": "setup your model provider first.",
- "apiKeyInfo.setAPIBtn": "Go to setup model provider",
- "apiKeyInfo.tryCloud": "Or try the cloud version of Dify with free quote",
"overview.apiInfo.accessibleAddress": "API Endpoint",
"overview.apiInfo.doc": "API Reference",
"overview.apiInfo.title": "Backend Service API",
diff --git a/web/i18n/locales/es-ES/app-overview.json b/web/i18n/locales/es-ES/app-overview.json
index 38f834b6f13..194d0ea614d 100644
--- a/web/i18n/locales/es-ES/app-overview.json
+++ b/web/i18n/locales/es-ES/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Velocidad de salida de tokens",
"analysis.userSatisfactionRate.explanation": "El número de likes por cada 1,000 mensajes. Esto indica la proporción de respuestas con las que los usuarios están muy satisfechos.",
"analysis.userSatisfactionRate.title": "Tasa de satisfacción del usuario",
- "apiKeyInfo.cloud.trial.description": "La cuota de prueba se proporciona para su uso de prueba. Antes de que se agoten las llamadas de la cuota de prueba, configure su propio proveedor de modelos o compre cuota adicional.",
- "apiKeyInfo.cloud.trial.title": "Estás utilizando la cuota de prueba de {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Para comenzar,",
- "apiKeyInfo.selfHost.title.row2": "configura primero tu proveedor de modelos.",
- "apiKeyInfo.setAPIBtn": "Ir a configurar proveedor de modelos",
- "apiKeyInfo.tryCloud": "O prueba la versión en la nube de Dify con una cotización gratuita",
"overview.apiInfo.accessibleAddress": "Punto final de la API",
"overview.apiInfo.doc": "Referencia de la API",
"overview.apiInfo.title": "API del servicio backend",
diff --git a/web/i18n/locales/fa-IR/app-overview.json b/web/i18n/locales/fa-IR/app-overview.json
index 41c17949c5b..ad81ffe3fda 100644
--- a/web/i18n/locales/fa-IR/app-overview.json
+++ b/web/i18n/locales/fa-IR/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "سرعت خروجی توکن",
"analysis.userSatisfactionRate.explanation": "تعداد لایک‌ها به ازای هر ۱۰۰۰ پیام. این نشان‌دهنده نسبت پاسخ‌هایی است که کاربران به شدت رضایت دارند.",
"analysis.userSatisfactionRate.title": "نرخ رضایت کاربران",
- "apiKeyInfo.cloud.trial.description": "سهمیه آزمایشی برای اهداف تست شما ارائه شده است. قبل از اینکه سهمیه آزمایشی تمام شود، لطفاً ارائه‌دهنده مدل خود را تنظیم کنید یا سهمیه اضافی خریداری کنید.",
- "apiKeyInfo.cloud.trial.title": "شما از سهمیه آزمایشی {{providerName}} استفاده می‌کنید.",
- "apiKeyInfo.selfHost.title.row1": "برای شروع،",
- "apiKeyInfo.selfHost.title.row2": "ابتدا ارائه‌دهنده مدل خود را تنظیم کنید.",
- "apiKeyInfo.setAPIBtn": "برو به تنظیمات ارائه‌دهنده مدل",
- "apiKeyInfo.tryCloud": "یا نسخه ابری Dify با سهمیه رایگان را امتحان کنید",
"overview.apiInfo.accessibleAddress": "نقطه پایانی API",
"overview.apiInfo.doc": "مرجع API",
"overview.apiInfo.title": "API سرویس بک‌اند",
diff --git a/web/i18n/locales/fr-FR/app-overview.json b/web/i18n/locales/fr-FR/app-overview.json
index 7a62652eaf5..0a5972a8729 100644
--- a/web/i18n/locales/fr-FR/app-overview.json
+++ b/web/i18n/locales/fr-FR/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Vitesse de sortie de token",
"analysis.userSatisfactionRate.explanation": "Le nombre de likes parmi 1 000 messages. Cela indique la proportion de réponses avec lesquelles les utilisateurs sont très satisfaits.",
"analysis.userSatisfactionRate.title": "Taux de satisfaction des utilisateurs",
- "apiKeyInfo.cloud.trial.description": "Le quota d'essai est fourni pour votre usage de test. Avant l'épuisement des appels de quota d'essai, veuillez configurer votre propre fournisseur de modèle ou acheter un quota supplémentaire.",
- "apiKeyInfo.cloud.trial.title": "Vous utilisez le quota d'essai de {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Pour commencer,",
- "apiKeyInfo.selfHost.title.row2": "configurez d'abord votre fournisseur de modèle.",
- "apiKeyInfo.setAPIBtn": "Aller à la configuration du fournisseur de modèle",
- "apiKeyInfo.tryCloud": "Ou essayez la version cloud de Dify avec un devis gratuit",
"overview.apiInfo.accessibleAddress": "Point de terminaison API",
"overview.apiInfo.doc": "Référence de l'API",
"overview.apiInfo.title": "API de service Backend",
diff --git a/web/i18n/locales/hi-IN/app-overview.json b/web/i18n/locales/hi-IN/app-overview.json
index 23de207b000..4be6a527a2a 100644
--- a/web/i18n/locales/hi-IN/app-overview.json
+++ b/web/i18n/locales/hi-IN/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "टोकन आउटपुट स्पीड",
"analysis.userSatisfactionRate.explanation": "प्रति 1,000 संदेशों में से पसंदों की संख्या। यह उन उत्तरों के अनुपात को इंगित करता है जिनसे उपयोगकर्ता अत्यधिक संतुष्ट हैं।",
"analysis.userSatisfactionRate.title": "उपयोगकर्ता संतोष दर",
- "apiKeyInfo.cloud.trial.description": "परीक्षण कोटा आपके परीक्षण उपयोग के लिए प्रदान किया गया है। कृपया परीक्षण कोटा कॉल समाप्त होने से पहले अपना स्वयं का मॉडल प्रदाता सेट करें या अतिरिक्त कोटा खरीदें।",
- "apiKeyInfo.cloud.trial.title": "आप {{providerName}} परीक्षण कोटा का उपयोग कर रहे हैं।",
- "apiKeyInfo.selfHost.title.row1": "शुरू करने के लिए,",
- "apiKeyInfo.selfHost.title.row2": "पहले अपना मॉडल प्रदाता सेटअप करें।",
- "apiKeyInfo.setAPIBtn": "मॉडल प्रदाता सेटअप पर जाएं",
- "apiKeyInfo.tryCloud": "या मुफ्त कोटा के साथ Dify का क्लाउड संस्करण आज़माएं",
"overview.apiInfo.accessibleAddress": "एपीआई एंडपॉइंट",
"overview.apiInfo.doc": "एपीआई संदर्भ",
"overview.apiInfo.title": "बैकएंड सेवा एपीआई",
diff --git a/web/i18n/locales/id-ID/app-overview.json b/web/i18n/locales/id-ID/app-overview.json
index fab90883ddf..17c6cd17fff 100644
--- a/web/i18n/locales/id-ID/app-overview.json
+++ b/web/i18n/locales/id-ID/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Kecepatan Keluaran Token",
"analysis.userSatisfactionRate.explanation": "Jumlah suka per 1.000 pesan. Ini menunjukkan proporsi jawaban yang sangat dipuaskan pengguna.",
"analysis.userSatisfactionRate.title": "Tingkat Kepuasan Pengguna",
- "apiKeyInfo.cloud.trial.description": "Kuota uji coba disediakan untuk tujuan pengujian Anda. Sebelum kuota uji coba habis, harap siapkan penyedia model Anda sendiri atau beli kuota tambahan.",
- "apiKeyInfo.cloud.trial.title": "Anda sedang menggunakan kuota percobaan {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Untuk memulai,",
- "apiKeyInfo.selfHost.title.row2": "Siapkan penyedia model Anda terlebih dahulu.",
- "apiKeyInfo.setAPIBtn": "Buka penyedia model penyiapan",
- "apiKeyInfo.tryCloud": "Atau coba Dify versi cloud dengan penawaran gratis",
"overview.apiInfo.accessibleAddress": "Titik Akhir API",
"overview.apiInfo.doc": "Referensi API",
"overview.apiInfo.title": "API Layanan Backend",
diff --git a/web/i18n/locales/it-IT/app-overview.json b/web/i18n/locales/it-IT/app-overview.json
index b0d7cc28742..7be22015f87 100644
--- a/web/i18n/locales/it-IT/app-overview.json
+++ b/web/i18n/locales/it-IT/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Velocità di Output dei Token",
"analysis.userSatisfactionRate.explanation": "Il numero di mi piace per 1.000 messaggi. Indica la proporzione di risposte con cui gli utenti sono molto soddisfatti.",
"analysis.userSatisfactionRate.title": "Tasso di Soddisfazione degli Utenti",
- "apiKeyInfo.cloud.trial.description": "La quota di prova è fornita per il tuo utilizzo di test. Prima che le chiamate della quota di prova siano esaurite, configura il tuo fornitore di modelli o acquista una quota aggiuntiva.",
- "apiKeyInfo.cloud.trial.title": "Stai usando la quota di prova di {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Per iniziare,",
- "apiKeyInfo.selfHost.title.row2": "configura prima il tuo fornitore di modelli.",
- "apiKeyInfo.setAPIBtn": "Vai a configurare il fornitore di modelli",
- "apiKeyInfo.tryCloud": "O prova la versione cloud di Dify con quota gratuita",
"overview.apiInfo.accessibleAddress": "Endpoint API",
"overview.apiInfo.doc": "Riferimento API",
"overview.apiInfo.title": "API del servizio backend",
diff --git a/web/i18n/locales/ja-JP/app-overview.json b/web/i18n/locales/ja-JP/app-overview.json
index e78626ff096..218c8424a20 100644
--- a/web/i18n/locales/ja-JP/app-overview.json
+++ b/web/i18n/locales/ja-JP/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "トークン出力速度",
"analysis.userSatisfactionRate.explanation": "1,000 件のメッセージあたりの「いいね」の数。これは、ユーザーが非常に満足している回答の割合を示します。",
"analysis.userSatisfactionRate.title": "ユーザー満足度率",
- "apiKeyInfo.cloud.trial.description": "トライアルクォータはテスト用に提供されます。トライアルクォータのコールが使い切られる前に、独自のモデルプロバイダを設定するか、追加のクォータを購入してください。",
- "apiKeyInfo.cloud.trial.title": "{{providerName}}トライアルクォータを使用しています。",
- "apiKeyInfo.selfHost.title.row1": "はじめるには、",
- "apiKeyInfo.selfHost.title.row2": "まずモデルプロバイダを設定してください。",
- "apiKeyInfo.setAPIBtn": "モデルプロバイダの設定へ",
- "apiKeyInfo.tryCloud": "または Dify のクラウドバージョンを無料見積もりでお試しください",
"overview.apiInfo.accessibleAddress": "API エンドポイント",
"overview.apiInfo.doc": "API リファレンス",
"overview.apiInfo.title": "バックエンドサービス API",
diff --git a/web/i18n/locales/ko-KR/app-overview.json b/web/i18n/locales/ko-KR/app-overview.json
index e27333e3dcf..d20afbdbe6b 100644
--- a/web/i18n/locales/ko-KR/app-overview.json
+++ b/web/i18n/locales/ko-KR/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "토큰 출력 속도",
"analysis.userSatisfactionRate.explanation": "1,000 개의 메시지 당 \"좋아요\" 수입니다. 이는 사용자가 매우 만족한 응답의 비율을 나타냅니다.",
"analysis.userSatisfactionRate.title": "사용자 만족도율",
- "apiKeyInfo.cloud.trial.description": "트라이얼 쿼터는 테스트용으로 제공됩니다. 트라이얼 쿼터 소진 전에 고유한 모델 제공자를 설정하거나 추가 쿼터를 구매하세요.",
- "apiKeyInfo.cloud.trial.title": "{{providerName}} 트라이얼 쿼터를 사용 중입니다.",
- "apiKeyInfo.selfHost.title.row1": "시작하려면,",
- "apiKeyInfo.selfHost.title.row2": "먼저 모델 제공자를 설정하세요.",
- "apiKeyInfo.setAPIBtn": "모델 제공자 설정으로 이동",
- "apiKeyInfo.tryCloud": "또는 Dify 의 클라우드 버전을 무료로 체험해보세요",
"overview.apiInfo.accessibleAddress": "API 엔드포인트",
"overview.apiInfo.doc": "API 레퍼런스",
"overview.apiInfo.title": "백엔드 서비스 API",
diff --git a/web/i18n/locales/lo-LA/app-overview.json b/web/i18n/locales/lo-LA/app-overview.json
index ac7a9228c9b..9eabca69148 100644
--- a/web/i18n/locales/lo-LA/app-overview.json
+++ b/web/i18n/locales/lo-LA/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "ຄວາມໄວການສົ່ງອອກ Token",
"analysis.userSatisfactionRate.explanation": "ຈຳນວນການກົດຖືກໃຈຕໍ່ 1,000 ຂໍ້ຄວາມ. ນີ້ບົ່ງບອກເຖິງສັດສ່ວນຂອງຄຳຕອບທີ່ຜູ້ໃຊ້ມີຄວາມເພິ່ງພໍໃຈສູງ.",
"analysis.userSatisfactionRate.title": "ອັດຕາຄວາມເພິ່ງພໍໃຈຂອງຜູ້ໃຊ້",
- "apiKeyInfo.cloud.trial.description": "ໂຄຕ້າທົດລອງແມ່ນໃຫ້ໄວ້ເພື່ອຈຸດປະສົງການທົດສອບຂອງທ່ານ. ກ່ອນທີ່ໂຄຕ້າທົດລອງຈະໝົດ, ກະລຸນາຕັ້ງຄ່າຜູ້ໃຫ້ບໍລິການໂມເດນຂອງທ່ານເອງ ຫຼື ຊື້ໂຄຕ້າເພີ່ມເຕີມ.",
- "apiKeyInfo.cloud.trial.title": "ທ່ານກຳລັງໃຊ້ໂຄຕ້າທົດລອງຂອງ {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "ເພື່ອເລີ່ມຕົ້ນ,",
- "apiKeyInfo.selfHost.title.row2": "ຕັ້ງຄ່າຜູ້ໃຫ້ບໍລິການໂມເດນຂອງທ່ານກ່ອນ.",
- "apiKeyInfo.setAPIBtn": "ໄປທີ່ການຕັ້ງຄ່າຜູ້ໃຫ້ບໍລິການໂມເດນ",
- "apiKeyInfo.tryCloud": "ຫຼື ລອງໃຊ້ເວີຊັນຄລາວຂອງ Dify ພ້ອມໂຄຕ້າຟຣີ",
"overview.apiInfo.accessibleAddress": "API Endpoint",
"overview.apiInfo.doc": "ເອກະສານອ້າງອີງ API",
"overview.apiInfo.title": "Backend Service API",
diff --git a/web/i18n/locales/nl-NL/app-overview.json b/web/i18n/locales/nl-NL/app-overview.json
index 926980e1249..0295fccb86b 100644
--- a/web/i18n/locales/nl-NL/app-overview.json
+++ b/web/i18n/locales/nl-NL/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token Output Speed",
"analysis.userSatisfactionRate.explanation": "The number of likes per 1,000 messages. This indicates the proportion of answers that users are highly satisfied with.",
"analysis.userSatisfactionRate.title": "User Satisfaction Rate",
- "apiKeyInfo.cloud.trial.description": "The trial quota is provided for your testing purposes. Before the trial quota is exhausted, please set up your own model provider or purchase additional quota.",
- "apiKeyInfo.cloud.trial.title": "You are using the {{providerName}} trial quota.",
- "apiKeyInfo.selfHost.title.row1": "To get started,",
- "apiKeyInfo.selfHost.title.row2": "setup your model provider first.",
- "apiKeyInfo.setAPIBtn": "Go to setup model provider",
- "apiKeyInfo.tryCloud": "Or try the cloud version of Dify with free quote",
"overview.apiInfo.accessibleAddress": "API Endpoint",
"overview.apiInfo.doc": "API Reference",
"overview.apiInfo.title": "Backend Service API",
diff --git a/web/i18n/locales/pl-PL/app-overview.json b/web/i18n/locales/pl-PL/app-overview.json
index 642a0c0ac97..8c930cf94f7 100644
--- a/web/i18n/locales/pl-PL/app-overview.json
+++ b/web/i18n/locales/pl-PL/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Szybkość wydajności tokenów",
"analysis.userSatisfactionRate.explanation": "Liczba polubień na 1000 wiadomości. Wskazuje to proporcję odpowiedzi, z których użytkownicy są bardzo zadowoleni.",
"analysis.userSatisfactionRate.title": "Wskaźnik zadowolenia użytkowników",
- "apiKeyInfo.cloud.trial.description": "Limit próbny jest dostarczany do użytku testowego. Zanim wykorzystasz dozwolone wywołania limitu próbnego, skonfiguruj swojego własnego dostawcę modelu lub zakup dodatkowy limit.",
- "apiKeyInfo.cloud.trial.title": "Korzystasz z limitu próbnego {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Aby rozpocząć,",
- "apiKeyInfo.selfHost.title.row2": "najpierw skonfiguruj swojego dostawcę modelu.",
- "apiKeyInfo.setAPIBtn": "Przejdź do konfiguracji dostawcy modelu",
- "apiKeyInfo.tryCloud": "Lub wypróbuj wersję chmurową Dify z darmowym limitem",
"overview.apiInfo.accessibleAddress": "Koniec API",
"overview.apiInfo.doc": "Dokumentacja API",
"overview.apiInfo.title": "API usługi w tle",
diff --git a/web/i18n/locales/pt-BR/app-overview.json b/web/i18n/locales/pt-BR/app-overview.json
index 009abc4367e..32d8e49bf41 100644
--- a/web/i18n/locales/pt-BR/app-overview.json
+++ b/web/i18n/locales/pt-BR/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Velocidade de Saída do Token",
"analysis.userSatisfactionRate.explanation": "O número de curtidas por 1.000 mensagens. Isso indica a proporção de respostas com as quais os usuários estão altamente satisfeitos.",
"analysis.userSatisfactionRate.title": "Taxa de Satisfação do Usuário",
- "apiKeyInfo.cloud.trial.description": "A cota de teste é fornecida para seu uso de teste. Antes que as chamadas de cota de teste se esgotem, configure seu próprio provedor de modelo ou compre cota adicional.",
- "apiKeyInfo.cloud.trial.title": "Você está usando a cota de teste da {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Para começar,",
- "apiKeyInfo.selfHost.title.row2": "configure primeiro seu provedor de modelo.",
- "apiKeyInfo.setAPIBtn": "Ir para configurar o provedor de modelo",
- "apiKeyInfo.tryCloud": "Ou experimente a versão em nuvem do Dify com cota gratuita",
"overview.apiInfo.accessibleAddress": "Endpoint da API",
"overview.apiInfo.doc": "Referência da API",
"overview.apiInfo.title": "API de Serviço de Back-end",
diff --git a/web/i18n/locales/ro-RO/app-overview.json b/web/i18n/locales/ro-RO/app-overview.json
index 590007c460f..d294fd21f61 100644
--- a/web/i18n/locales/ro-RO/app-overview.json
+++ b/web/i18n/locales/ro-RO/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Viteza de ieșire a tokenurilor",
"analysis.userSatisfactionRate.explanation": "Numărul de aprecieri la 1.000 de mesaje. Acest lucru indică proporția de răspunsuri cu care utilizatorii sunt foarte mulțumiți.",
"analysis.userSatisfactionRate.title": "Rata de satisfacție a utilizatorilor",
- "apiKeyInfo.cloud.trial.description": "Cota de probă este furnizată pentru utilizarea de testare. Înainte ca apelurile cotei de probă să se epuizeze, vă rugăm să configurați propriul furnizor de modele sau să achiziționați o cotă suplimentară.",
- "apiKeyInfo.cloud.trial.title": "Utilizați cota de probă a furnizorului {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Pentru a începe,",
- "apiKeyInfo.selfHost.title.row2": "configurați mai întâi furnizorul de modele.",
- "apiKeyInfo.setAPIBtn": "Mergeți la configurarea furnizorului de modele",
- "apiKeyInfo.tryCloud": "Sau încercați versiunea cloud a Dify cu cotă gratuită",
"overview.apiInfo.accessibleAddress": "Endpoint API",
"overview.apiInfo.doc": "Referință API",
"overview.apiInfo.title": "API serviciu backend",
diff --git a/web/i18n/locales/ru-RU/app-overview.json b/web/i18n/locales/ru-RU/app-overview.json
index 6a25558bff0..fa8ac253fb7 100644
--- a/web/i18n/locales/ru-RU/app-overview.json
+++ b/web/i18n/locales/ru-RU/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Скорость вывода токенов",
"analysis.userSatisfactionRate.explanation": "Количество лайков на 1000 сообщений. Это указывает на долю ответов, которыми пользователи довольны.",
"analysis.userSatisfactionRate.title": "Уровень удовлетворенности пользователей",
- "apiKeyInfo.cloud.trial.description": "Пробная квота предоставляется для тестирования. Прежде чем пробная квота будет исчерпана, пожалуйста, настройте своего собственного поставщика модели или приобретите дополнительную квоту.",
- "apiKeyInfo.cloud.trial.title": "Вы используете пробную квоту {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Чтобы начать,",
- "apiKeyInfo.selfHost.title.row2": "сначала настройте своего поставщика модели.",
- "apiKeyInfo.setAPIBtn": "Перейти к настройке поставщика модели",
- "apiKeyInfo.tryCloud": "Или попробуйте облачную версию Dify с бесплатной квотой",
"overview.apiInfo.accessibleAddress": "API Endpoint",
"overview.apiInfo.doc": "Справочник по API",
"overview.apiInfo.title": "API серверной части",
diff --git a/web/i18n/locales/sl-SI/app-overview.json b/web/i18n/locales/sl-SI/app-overview.json
index 24958d7f0f3..98712d28467 100644
--- a/web/i18n/locales/sl-SI/app-overview.json
+++ b/web/i18n/locales/sl-SI/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Hitrost izhoda žetonov",
"analysis.userSatisfactionRate.explanation": "Število všečkov na 1.000 sporočil. To kaže delež odgovorov, s katerimi so uporabniki zelo zadovoljni.",
"analysis.userSatisfactionRate.title": "Stopnja zadovoljstva uporabnikov",
- "apiKeyInfo.cloud.trial.description": "Poskusna kvota je namenjena vašemu testiranju. Preden se kvota izčrpa, nastavite lastnega ponudnika modela ali kupite dodatno kvoto.",
- "apiKeyInfo.cloud.trial.title": "Uporabljate {{providerName}} poskusno kvoto.",
- "apiKeyInfo.selfHost.title.row1": "Za začetek,",
- "apiKeyInfo.selfHost.title.row2": "najprej nastavite svojega ponudnika modela.",
- "apiKeyInfo.setAPIBtn": "Pojdi na nastavitev ponudnika modela",
- "apiKeyInfo.tryCloud": "Ali preizkusite oblačno različico Dify s prosto kvoto",
"overview.apiInfo.accessibleAddress": "Končna točka API-ja",
"overview.apiInfo.doc": "API referenca",
"overview.apiInfo.title": "API storitev v ozadju",
diff --git a/web/i18n/locales/th-TH/app-overview.json b/web/i18n/locales/th-TH/app-overview.json
index 9f721a4fe68..170050dd665 100644
--- a/web/i18n/locales/th-TH/app-overview.json
+++ b/web/i18n/locales/th-TH/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "ความเร็วในการส่งออกโทเค็น",
"analysis.userSatisfactionRate.explanation": "จํานวนไลค์ต่อ 1,000 ข้อความ สิ่งนี้บ่งชี้ถึงสัดส่วนของคําตอบที่ผู้ใช้พึงพอใจอย่างมาก",
"analysis.userSatisfactionRate.title": "อัตราความพึงพอใจของผู้ใช้",
- "apiKeyInfo.cloud.trial.description": "โควต้าทดลองใช้มีไว้เพื่อวัตถุประสงค์ในการทดสอบของคุณ ก่อนที่โควต้าทดลองใช้จะหมด โปรดตั้งค่าผู้ให้บริการโมเดลของคุณเองหรือซื้อโควต้าเพิ่มเติม",
- "apiKeyInfo.cloud.trial.title": "คุณกําลังใช้โควต้าทดลองใช้ {{providerName}}",
- "apiKeyInfo.selfHost.title.row1": "ในการเริ่มต้น",
- "apiKeyInfo.selfHost.title.row2": "ตั้งค่าผู้ให้บริการโมเดลของคุณก่อน",
- "apiKeyInfo.setAPIBtn": "ไปที่ผู้ให้บริการโมเดลการตั้งค่า",
- "apiKeyInfo.tryCloud": "หรือลองใช้ Dify เวอร์ชันคลาวด์พร้อมใบเสนอราคาฟรี",
"overview.apiInfo.accessibleAddress": "ปลายทาง API",
"overview.apiInfo.doc": "การอ้างอิง API",
"overview.apiInfo.title": "API บริการแบ็กเอนด์",
diff --git a/web/i18n/locales/tr-TR/app-overview.json b/web/i18n/locales/tr-TR/app-overview.json
index 4c9942b059b..deb3d6aabf6 100644
--- a/web/i18n/locales/tr-TR/app-overview.json
+++ b/web/i18n/locales/tr-TR/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token Çıktı Hızı",
"analysis.userSatisfactionRate.explanation": "Her 1.000 mesajda alınan beğeni sayısı. Bu, kullanıcıların çok memnun olduğu cevapların oranını gösterir.",
"analysis.userSatisfactionRate.title": "Kullanıcı Memnuniyet Oranı",
- "apiKeyInfo.cloud.trial.description": "Deneme kotası, test amaçlarınız için sağlanmıştır. Deneme kotası bitmeden önce kendi model sağlayıcınızı ayarlayın veya ek kota satın alın.",
- "apiKeyInfo.cloud.trial.title": "{{providerName}} deneme kotasını kullanıyorsunuz.",
- "apiKeyInfo.selfHost.title.row1": "Başlamak için,",
- "apiKeyInfo.selfHost.title.row2": "model sağlayıcınızı ayarlayın.",
- "apiKeyInfo.setAPIBtn": "Model sağlayıcısını ayarlamaya git",
- "apiKeyInfo.tryCloud": "Veya Dify'nin bulut sürümünü ücretsiz kotayla deneyin",
"overview.apiInfo.accessibleAddress": "API Uç Noktası",
"overview.apiInfo.doc": "API Referansı",
"overview.apiInfo.title": "Arka Uç Servis API'si",
diff --git a/web/i18n/locales/uk-UA/app-overview.json b/web/i18n/locales/uk-UA/app-overview.json
index a12db6097b5..0f8b8a3df34 100644
--- a/web/i18n/locales/uk-UA/app-overview.json
+++ b/web/i18n/locales/uk-UA/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Швидкість виведення токенів",
"analysis.userSatisfactionRate.explanation": "Кількість лайків на 1000 повідомлень. Це вказує на те, наскільки задоволені користувачі відповідями.",
"analysis.userSatisfactionRate.title": "Показник задоволення користувача",
- "apiKeyInfo.cloud.trial.description": "Квота пробного періоду надається для вашого тестувального використання. Перш ніж будуть вичерпані виклики квоти пробного періоду, налаштуйте свого власного постачальника моделей або придбайте додаткову квоту.",
- "apiKeyInfo.cloud.trial.title": "Ви використовуєте квоту пробного періоду {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Для початку,",
- "apiKeyInfo.selfHost.title.row2": "спочатку налаштуйте постачальника моделей.",
- "apiKeyInfo.setAPIBtn": "Перейти до налаштування постачальника моделей",
- "apiKeyInfo.tryCloud": "Або спробуйте хмарну версію Dify з безкоштовним цитатою",
"overview.apiInfo.accessibleAddress": "Кінцева точка API",
"overview.apiInfo.doc": "Довідка з API",
"overview.apiInfo.title": "API сервісу Backend",
diff --git a/web/i18n/locales/vi-VN/app-overview.json b/web/i18n/locales/vi-VN/app-overview.json
index b77ddb4a119..7ea5d88b51e 100644
--- a/web/i18n/locales/vi-VN/app-overview.json
+++ b/web/i18n/locales/vi-VN/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Tốc độ đầu ra token",
"analysis.userSatisfactionRate.explanation": "Số lượt thích trên mỗi 1.000 tin nhắn. Chỉ số này cho biết tỷ lệ câu trả lời mà người dùng rất hài lòng.",
"analysis.userSatisfactionRate.title": "Tỷ lệ hài lòng của người dùng",
- "apiKeyInfo.cloud.trial.description": "Gói dùng thử được cung cấp để bạn kiểm tra. Trước khi hết lượt gọi của gói dùng thử, vui lòng thiết lập nhà cung cấp mô hình riêng hoặc mua thêm hạn mức.",
- "apiKeyInfo.cloud.trial.title": "Bạn đang sử dụng gói dùng thử của {{providerName}}.",
- "apiKeyInfo.selfHost.title.row1": "Để bắt đầu,",
- "apiKeyInfo.selfHost.title.row2": "hãy thiết lập nhà cung cấp mô hình của bạn trước.",
- "apiKeyInfo.setAPIBtn": "Thiết lập nhà cung cấp mô hình",
- "apiKeyInfo.tryCloud": "Hoặc dùng thử phiên bản đám mây của Dify với gói miễn phí",
"overview.apiInfo.accessibleAddress": "Điểm cuối API",
"overview.apiInfo.doc": "Tài liệu tham khảo API",
"overview.apiInfo.title": "API dịch vụ backend",
diff --git a/web/i18n/locales/zh-Hans/app-overview.json b/web/i18n/locales/zh-Hans/app-overview.json
index 19e819161f7..b06ce9837b2 100644
--- a/web/i18n/locales/zh-Hans/app-overview.json
+++ b/web/i18n/locales/zh-Hans/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token 输出速度",
"analysis.userSatisfactionRate.explanation": "每 1000 条消息的点赞数。反映了用户对回答十分满意的比例。",
"analysis.userSatisfactionRate.title": "用户满意度",
- "apiKeyInfo.cloud.trial.description": "试用配额仅供您测试使用。在试用配额用完之前,请自行设置模型提供商或购买额外配额。",
- "apiKeyInfo.cloud.trial.title": "您正在使用 {{providerName}} 的试用配额。",
- "apiKeyInfo.selfHost.title.row1": "首先,",
- "apiKeyInfo.selfHost.title.row2": "设置您的模型提供商。",
- "apiKeyInfo.setAPIBtn": "设置模型提供商",
- "apiKeyInfo.tryCloud": "或者尝试使用 Dify 的云版本并使用试用配额",
"overview.apiInfo.accessibleAddress": "API Endpoint",
"overview.apiInfo.doc": "查阅 API 文档",
"overview.apiInfo.title": "后端服务 API",
diff --git a/web/i18n/locales/zh-Hant/app-overview.json b/web/i18n/locales/zh-Hant/app-overview.json
index 823817d4e33..c5621a90878 100644
--- a/web/i18n/locales/zh-Hant/app-overview.json
+++ b/web/i18n/locales/zh-Hant/app-overview.json
@@ -20,12 +20,6 @@
"analysis.tps.title": "Token 輸出速度",
"analysis.userSatisfactionRate.explanation": "每 1000 條訊息的點贊數。反映了使用者對回答十分滿意的比例。",
"analysis.userSatisfactionRate.title": "使用者滿意度",
- "apiKeyInfo.cloud.trial.description": "試用配額僅供您測試使用。在試用配額用完之前,請自行設定模型提供商或購買額外配額。",
- "apiKeyInfo.cloud.trial.title": "您正在使用 {{providerName}} 的試用配額。",
- "apiKeyInfo.selfHost.title.row1": "首先,",
- "apiKeyInfo.selfHost.title.row2": "設定您的模型提供商。",
- "apiKeyInfo.setAPIBtn": "設定模型提供商",
- "apiKeyInfo.tryCloud": "或者嘗試使用 Dify 的雲版本並使用試用配額",
"overview.apiInfo.accessibleAddress": "API Endpoint",
"overview.apiInfo.doc": "查閱 API 文件",
"overview.apiInfo.title": "後端服務 API",
diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.ts
index b2a539c4e70..44ae433f266 100644
--- a/web/i18n/resources.generated.d.ts
+++ b/web/i18n/resources.generated.d.ts
@@ -1374,12 +1374,6 @@ export default interface Resources {
'analysis.tps.title': 'Token Output Speed'
'analysis.userSatisfactionRate.explanation': 'The number of likes per 1,000 messages. This indicates the proportion of answers that users are highly satisfied with.'
'analysis.userSatisfactionRate.title': 'User Satisfaction Rate'
- 'apiKeyInfo.cloud.trial.description': 'The trial quota is provided for your testing purposes. Before the trial quota is exhausted, please set up your own model provider or purchase additional quota.'
- 'apiKeyInfo.cloud.trial.title': 'You are using the {{providerName}} trial quota.'
- 'apiKeyInfo.selfHost.title.row1': 'To get started,'
- 'apiKeyInfo.selfHost.title.row2': 'setup your model provider first.'
- 'apiKeyInfo.setAPIBtn': 'Go to setup model provider'
- 'apiKeyInfo.tryCloud': 'Or try the cloud version of Dify with free quote'
'overview.apiInfo.accessibleAddress': 'API Endpoint'
'overview.apiInfo.doc': 'API Reference'
'overview.apiInfo.title': 'Backend Service API'
diff --git a/web/models/app.ts b/web/models/app.ts
index 542b07de050..e7029febfdd 100644
--- a/web/models/app.ts
+++ b/web/models/app.ts
@@ -1,17 +1,3 @@
-import type {
- AliyunConfig,
- ArizeConfig,
- DatabricksConfig,
- LangFuseConfig,
- LangSmithConfig,
- MLflowConfig,
- OpikConfig,
- PhoenixConfig,
- TencentConfig,
- TracingProvider,
- WeaveConfig,
-} from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type'
-
export const DSLImportMode = {
YAML_CONTENT: 'yaml-content',
YAML_URL: 'yaml-url',
@@ -41,23 +27,3 @@ export type WorkflowOnlineUsersResponse = {
users: WorkflowOnlineUser[]
}>
}
-
-export type TracingStatus = {
- enabled: boolean
- tracing_provider: TracingProvider | null
-}
-
-export type TracingConfig = {
- tracing_provider: TracingProvider
- tracing_config:
- | ArizeConfig
- | PhoenixConfig
- | LangSmithConfig
- | LangFuseConfig
- | DatabricksConfig
- | MLflowConfig
- | OpikConfig
- | WeaveConfig
- | AliyunConfig
- | TencentConfig
-}
diff --git a/web/service/apps.ts b/web/service/apps.ts
index ffd82e1efaa..2a723b29af6 100644
--- a/web/service/apps.ts
+++ b/web/service/apps.ts
@@ -1,66 +1,4 @@
-import type { TracingProvider } from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type'
-import type { TracingConfig, TracingStatus } from '@/models/app'
-import type { CommonResponse } from '@/models/common'
-import { del, get, patch, post } from './base'
-
-// Tracing
-export const fetchTracingStatus = ({ appId }: { appId: string }): Promise<TracingStatus> => {
- return get<TracingStatus>(`/apps/${appId}/trace`)
-}
-
-export const updateTracingStatus = ({
- appId,
- body,
-}: {
- appId: string
- body: Record<string, any>
-}): Promise<CommonResponse> => {
- return post<CommonResponse>(`/apps/${appId}/trace`, { body })
-}
-
-export const fetchTracingConfig = ({
- appId,
- provider,
-}: {
- appId: string
- provider: TracingProvider
-}): Promise<TracingConfig & { has_not_configured: true }> => {
- return get<TracingConfig & { has_not_configured: true }>(`/apps/${appId}/trace-config`, {
- params: {
- tracing_provider: provider,
- },
- })
-}
-
-export const addTracingConfig = ({
- appId,
- body,
-}: {
- appId: string
- body: TracingConfig
-}): Promise<CommonResponse> => {
- return post<CommonResponse>(`/apps/${appId}/trace-config`, { body })
-}
-
-export const updateTracingConfig = ({
- appId,
- body,
-}: {
- appId: string
- body: TracingConfig
-}): Promise<CommonResponse> => {
- return patch<CommonResponse>(`/apps/${appId}/trace-config`, { body })
-}
-
-export const removeTracingConfig = ({
- appId,
- provider,
-}: {
- appId: string
- provider: TracingProvider
-}): Promise<CommonResponse> => {
- return del<CommonResponse>(`/apps/${appId}/trace-config?tracing_provider=${provider}`)
-}
+import { post } from './base'
type PublishToCreatorsPlatformResponse = {
redirect_url: string
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index f4792dce576..29236c03f06 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -433,6 +433,67 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
byAppId: {
+ trace: {
+ post: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.trace.get.queryKey({
+ input: { params: variables.params },
+ }),
+ })
+ },
+ },
+ },
+ },
+ traceConfig: {
+ post: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.traceConfig.get.queryKey({
+ input: {
+ params: variables.params,
+ query: { tracing_provider: variables.body.tracing_provider },
+ },
+ }),
+ })
+ },
+ },
+ },
+ patch: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.traceConfig.get.queryKey({
+ input: {
+ params: variables.params,
+ query: { tracing_provider: variables.body.tracing_provider },
+ },
+ }),
+ })
+ },
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.traceConfig.get.queryKey({
+ input: {
+ params: variables.params,
+ query: { tracing_provider: variables.query.tracing_provider },
+ },
+ }),
+ })
+ },
+ },
+ },
+ },
// Shared invalidation uses onSettled so feature-owned onSuccess callbacks can coexist.
apiEnable: {
post: {