Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions api/v1/endpoints/system_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
SystemConfigValidationErrorResponse,
TestLLMChannelRequest,
TestLLMChannelResponse,
TestNotificationChannelRequest,
TestNotificationChannelResponse,
UpdateSystemConfigRequest,
UpdateSystemConfigResponse,
ValidateSystemConfigRequest,
Expand Down Expand Up @@ -346,6 +348,50 @@ def test_llm_channel(
)


@router.post(
"/config/notification/test-channel",
response_model=TestNotificationChannelResponse,
responses={
200: {"description": "Notification channel test completed"},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Test one notification channel",
description="Send a short test notification using unsaved or saved notification configuration.",
)
def test_notification_channel(
request: TestNotificationChannelRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> TestNotificationChannelResponse:
"""Validate and test one notification channel without writing `.env`."""
try:
payload = service.test_notification_channel(
channel=request.channel,
items=[item.model_dump() for item in request.items],
mask_token=request.mask_token,
title=request.title,
content=request.content,
timeout_seconds=request.timeout_seconds,
)
return TestNotificationChannelResponse.model_validate(payload)
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=422,
detail={
"error": "validation_error",
"message": str(exc),
},
)
except Exception as exc:
logger.error("Failed to test notification channel: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to test notification channel",
},
)


@router.post(
"/config/llm/discover-models",
response_model=DiscoverLLMChannelModelsResponse,
Expand Down
50 changes: 50 additions & 0 deletions api/v1/schemas/system_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,19 @@
from pydantic import BaseModel, ConfigDict, Field

LLMCapabilityCheck = Literal["json", "tools", "vision", "stream"]
NotificationTestChannel = Literal[
"wechat",
"feishu",
"telegram",
"email",
"pushover",
"pushplus",
"serverchan3",
"custom",
"discord",
"slack",
"astrbot",
]


class SystemConfigOption(BaseModel):
Expand Down Expand Up @@ -204,6 +217,43 @@ class TestLLMChannelResponse(BaseModel):
capability_results: Dict[str, LLMCapabilityCheckResult] = Field(default_factory=dict)


class NotificationTestAttempt(BaseModel):
"""One notification delivery attempt result."""

channel: NotificationTestChannel
success: bool
message: str
target: Optional[str] = None
error_code: Optional[str] = None
stage: str = "notification_send"
retryable: bool = False
latency_ms: Optional[int] = None
http_status: Optional[int] = None


class TestNotificationChannelRequest(BaseModel):
"""Request payload for testing one notification channel."""

channel: NotificationTestChannel
items: List[SystemConfigUpdateItem] = Field(default_factory=list)
mask_token: str = "******"
title: str = Field(default="DSA 通知测试", min_length=1, max_length=80)
content: str = Field(default="这是一条来自 DSA Web 设置页的通知测试消息。", min_length=1, max_length=1000)
timeout_seconds: float = Field(default=20.0, ge=1.0, le=120.0)


class TestNotificationChannelResponse(BaseModel):
"""Response payload for one notification channel connectivity test."""

success: bool
message: str
error_code: Optional[str] = None
stage: Optional[str] = None
retryable: bool = False
latency_ms: Optional[int] = None
attempts: List[NotificationTestAttempt] = Field(default_factory=list)


class DiscoverLLMChannelModelsRequest(BaseModel):
"""Request payload for discovering models from one LLM channel."""

Expand Down
50 changes: 50 additions & 0 deletions apps/dsa-web/src/api/__tests__/systemConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,54 @@ describe('systemConfigApi', () => {
expect.objectContaining({ capability_checks: ['json', 'stream'] }),
);
});

it('sends notification channel test payloads with snake_case fields', async () => {
post.mockResolvedValueOnce({
data: {
success: true,
message: 'ok',
error_code: null,
stage: 'notification_send',
retryable: false,
latency_ms: 15,
attempts: [
{
channel: 'custom',
success: true,
message: 'sent',
target: 'https://example.com/hook?token=***',
error_code: null,
stage: 'notification_send',
retryable: false,
latency_ms: 15,
http_status: 200,
},
],
},
});

const result = await systemConfigApi.testNotificationChannel({
channel: 'custom',
items: [{ key: 'CUSTOM_WEBHOOK_URLS', value: 'https://example.com/hook?token=secret' }],
maskToken: '******',
title: 'hello',
content: 'world',
timeoutSeconds: 7,
});

expect(post).toHaveBeenCalledWith(
'/api/v1/system/config/notification/test-channel',
{
channel: 'custom',
items: [{ key: 'CUSTOM_WEBHOOK_URLS', value: 'https://example.com/hook?token=secret' }],
mask_token: '******',
title: 'hello',
content: 'world',
timeout_seconds: 7,
},
);
expect(result.latencyMs).toBe(15);
expect(result.attempts[0].errorCode).toBeNull();
expect(result.attempts[0].httpStatus).toBe(200);
});
});
24 changes: 24 additions & 0 deletions apps/dsa-web/src/api/systemConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import type {
SystemConfigValidationErrorResponse,
TestLLMChannelRequest,
TestLLMChannelResponse,
TestNotificationChannelRequest,
TestNotificationChannelResponse,
UpdateSystemConfigRequest,
UpdateSystemConfigResponse,
ValidateSystemConfigRequest,
Expand Down Expand Up @@ -99,6 +101,20 @@ function toSnakeTestChannelPayload(payload: TestLLMChannelRequest): Record<strin
return request;
}

function toSnakeNotificationTestPayload(payload: TestNotificationChannelRequest): Record<string, unknown> {
return {
channel: payload.channel,
items: (payload.items || []).map((item) => ({
key: item.key,
value: item.value,
})),
mask_token: payload.maskToken ?? '******',
title: payload.title ?? 'DSA 通知测试',
content: payload.content ?? '这是一条来自 DSA Web 设置页的通知测试消息。',
timeout_seconds: payload.timeoutSeconds ?? 20,
};
}

function toSnakeDiscoverModelsPayload(payload: DiscoverLLMChannelModelsRequest): Record<string, unknown> {
return {
name: payload.name,
Expand Down Expand Up @@ -152,6 +168,14 @@ export const systemConfigApi = {
return toCamelCase<TestLLMChannelResponse>(response.data);
},

async testNotificationChannel(payload: TestNotificationChannelRequest): Promise<TestNotificationChannelResponse> {
const response = await apiClient.post<Record<string, unknown>>(
'/api/v1/system/config/notification/test-channel',
toSnakeNotificationTestPayload(payload),
);
return toCamelCase<TestNotificationChannelResponse>(response.data);
},

async discoverLLMChannelModels(
payload: DiscoverLLMChannelModelsRequest,
): Promise<DiscoverLLMChannelModelsResponse> {
Expand Down
Loading
Loading