Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat(notifications): add Telegram topic destinations (#3978)
Kyle Mendelle47164421a22
diff --git a/backend/pkg/utils/notifications/telegram_sender_test.go b/backend/pkg/utils/notifications/telegram_sender_test.goindex 5c50c6c8d..621d46ef9 100644--- a/backend/pkg/utils/notifications/telegram_sender_test.go+++ b/backend/pkg/utils/notifications/telegram_sender_test.go@@ -45,6 +45,26 @@ func TestBuildTelegramURL(t *testing.T) {},wantURL: "telegram://123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11@telegram?chats=%40mybot&title=Container+Updates",},+ {+ name: "config with topic destination",+ config: TelegramConfig{+ BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",+ ChatIDs: []string{"-1001234567890:42"},+ Preview: true,+ Notification: true,+ },+ wantURL: "telegram://123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11@telegram?chats=-1001234567890%3A42",+ },+ {+ name: "config with mixed chat and topic destinations",+ config: TelegramConfig{+ BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",+ ChatIDs: []string{"@channel", "-1001234567890:42", "-1001234567890:7"},+ Preview: true,+ Notification: true,+ },+ wantURL: "telegram://123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11@telegram?chats=%40channel%2C-1001234567890%3A42%2C-1001234567890%3A7",+ },}for _, tt := range tests {diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 0ef1a0815..67b27b146 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -2389,9 +2389,15 @@"notifications_telegram_bot_token_label": "Bot Token","notifications_telegram_bot_token_placeholder": "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11","notifications_telegram_bot_token_help": "The bot token from @BotFather",- "notifications_telegram_chat_ids_label": "Chat IDs",- "notifications_telegram_chat_ids_placeholder": "@channel, 123456789, @another_channel",- "notifications_telegram_chat_ids_help": "Comma-separated list of chat IDs or @channel names",+ "notifications_telegram_destinations_label": "Destinations",+ "notifications_telegram_destinations_help": "Each destination is a chat ID or @channel name. Add a topic ID to post into a specific forum topic of that group.",+ "notifications_telegram_add_destination": "Add destination",+ "notifications_telegram_chat_id_label": "Chat ID",+ "notifications_telegram_chat_id_placeholder": "@channel or -1001234567890",+ "notifications_telegram_chat_id_invalid": "Chat ID cannot contain a colon. Enter the topic in the Topic ID field instead",+ "notifications_telegram_topic_id_label": "Topic ID (Optional)",+ "notifications_telegram_topic_id_placeholder": "123",+ "notifications_telegram_topic_id_invalid": "Topic ID must be a positive whole number","notifications_telegram_title_label": "Title (Optional)","notifications_telegram_title_placeholder": "Arcane Notifications","notifications_telegram_title_help": "Custom title for notifications",diff --git a/frontend/src/lib/types/notifications.ts b/frontend/src/lib/types/notifications.tsindex 2cff47c0c..d6bf51650 100644--- a/frontend/src/lib/types/notifications.ts+++ b/frontend/src/lib/types/notifications.ts@@ -77,9 +77,14 @@ export interface EmailFormValues extends BaseProviderFormValues {authMode: EmailAuthMode;}+export interface TelegramDestination {+ chatId: string;+ topicId: string;+}+export interface TelegramFormValues extends BaseProviderFormValues {botToken: string;- chatIds: string;+ destinations: TelegramDestination[];preview: boolean;notification: boolean;title: string;@@ -278,13 +283,29 @@ export function emailSettingsToFormValues(settings?: NotificationSettings): Emai};}+function telegramChatIdsToDestinations(chatIds: string[]): TelegramDestination[] {+ const destinations = chatIds.map((entry) => {+ const separator = entry.indexOf(':');+ if (separator < 0) return { chatId: entry.trim(), topicId: '' };+ return { chatId: entry.slice(0, separator).trim(), topicId: entry.slice(separator + 1).trim() };+ });+ return destinations.length > 0 ? destinations : [{ chatId: '', topicId: '' }];+}++function telegramDestinationsToChatIds(destinations: TelegramDestination[]): string[] {+ return destinations+ .map(({ chatId, topicId }) => ({ chatId: chatId.trim(), topicId: topicId.trim() }))+ .filter(({ chatId, topicId }) => chatId.length > 0 || topicId.length > 0)+ .map(({ chatId, topicId }) => (topicId ? `${chatId}:${topicId}` : chatId));+}+export function telegramSettingsToFormValues(settings?: NotificationSettings): TelegramFormValues {const cfg = getConfig(settings);const events = getEvents(cfg);return {enabled: settings?.enabled ?? false,botToken: getString(cfg, 'botToken'),- chatIds: getStringArray(cfg, 'chatIds').join(', '),+ destinations: telegramChatIdsToDestinations(getStringArray(cfg, 'chatIds')),preview: getBoolean(cfg, 'preview', true),notification: getBoolean(cfg, 'notification', true),title: getString(cfg, 'title'),@@ -366,10 +387,7 @@ export function telegramFormValuesToSettings(values: TelegramFormValues): Notifienabled: values.enabled,config: {botToken: values.botToken,- chatIds: values.chatIds- .split(',')- .map((id) => id.trim())- .filter((id) => id.length > 0),+ chatIds: telegramDestinationsToChatIds(values.destinations),preview: values.preview,notification: values.notification,title: values.title,diff --git a/frontend/src/lib/utils/notification-providers.ts b/frontend/src/lib/utils/notification-providers.tsindex 2616a6dcc..82a1847f9 100644--- a/frontend/src/lib/utils/notification-providers.ts+++ b/frontend/src/lib/utils/notification-providers.ts@@ -146,9 +146,13 @@ export function createNotificationProviderFormState() as NotificationProviderFormState;}+function cloneProviderFormValues<K extends NotificationProviderKey>(values: ProviderFormValuesMap[K]): ProviderFormValuesMap[K] {+ return JSON.parse(JSON.stringify(values)) as ProviderFormValuesMap[K];+}+export function cloneNotificationProviderFormState(state: NotificationProviderFormState): NotificationProviderFormState {return Object.fromEntries(- NOTIFICATION_PROVIDER_KEYS.map((provider) => [provider, { ...state[provider] }])+ NOTIFICATION_PROVIDER_KEYS.map((provider) => [provider, cloneProviderFormValues(state[provider])])) as NotificationProviderFormState;}@@ -157,7 +161,7 @@ export function updateNotificationProviderFormState<K extends NotificationProvidprovider: K,values: ProviderFormValuesMap[K]): NotificationProviderFormState {- return { ...state, [provider]: { ...values } } as NotificationProviderFormState;+ return { ...state, [provider]: cloneProviderFormValues(values) } as NotificationProviderFormState;}export function getNotificationProviderDefinition<K extends NotificationProviderKey>(diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelteindex 1a092d39f..0dd7df6a8 100644--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte@@ -243,10 +243,10 @@async function handleSaveAndTest() {showUnsavedDialog = false;await onSubmit();- if (pendingTestAction) {+ if (!hasChanges && pendingTestAction) {await pendingTestAction();- pendingTestAction = null;}+ pendingTestAction = null;}</script>diff --git a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelteindex 9d9068d65..6653bca92 100644--- a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte+++ b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte@@ -4,6 +4,7 @@import type { NotificationProviderKey, ProviderFormValuesMap } from '#lib/types/notifications.js';import ProviderFormWrapper from './ProviderFormWrapper.svelte';import EventSubscriptions from './EventSubscriptions.svelte';+ import TelegramDestinationsEditor from './TelegramDestinationsEditor.svelte';import DynamicProviderFormBuilder from './DynamicProviderFormBuilder.svelte';import NotificationProviderTestMenu, {type NotificationProviderTestOption,@@ -154,7 +155,7 @@.object({enabled: z.boolean(),botToken: z.string(),- chatIds: z.string(),+ destinations: z.array(z.object({ chatId: z.string(), topicId: z.string() })),preview: z.boolean(),notification: z.boolean(),title: z.string(),@@ -163,13 +164,29 @@.superRefine((d, ctx) => {if (!d.enabled) return;addRequiredCredentialIssue(ctx, d.botToken, 'botToken', m.common_required());- if (!d.chatIds.trim()) {- ctx.addIssue({- code: 'custom',- message: m.common_required(),- path: ['chatIds']- });+ const destinations = d.destinations.map((row) => ({ chatId: row.chatId.trim(), topicId: row.topicId.trim() }));+ if (!destinations.some((row) => row.chatId || row.topicId)) {+ addCustomFieldIssue(ctx, 'destinations', m.common_required());}+ destinations.forEach((row, index) => {+ if (!row.chatId && !row.topicId) return;+ if (!row.chatId) {+ ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['destinations', index, 'chatId'] });+ } else if (row.chatId.includes(':')) {+ ctx.addIssue({+ code: 'custom',+ message: m.notifications_telegram_chat_id_invalid(),+ path: ['destinations', index, 'chatId']+ });+ }+ if (row.topicId && !/^[1-9]\d*$/.test(row.topicId)) {+ ctx.addIssue({+ code: 'custom',+ message: m.notifications_telegram_topic_id_invalid(),+ path: ['destinations', index, 'topicId']+ });+ }+ });}),signal: z.object({@@ -489,15 +506,6 @@helpText: m.notifications_telegram_bot_token_help(),inputType: 'password'},- {- kind: 'textarea',- key: 'chatIds',- id: 'telegram-chat-ids',- label: m.notifications_telegram_chat_ids_label(),- placeholder: m.notifications_telegram_chat_ids_placeholder(),- helpText: m.notifications_telegram_chat_ids_help(),- rows: 2- },{kind: 'input',key: 'title',@@ -1110,6 +1118,10 @@><DynamicProviderFormBuilder bind:values {disabled} errors={fieldErrors} schema={selectedSchema} />+ {#if provider === 'telegram' && 'destinations' in values}+ <TelegramDestinationsEditor bind:destinations={values.destinations} errors={fieldErrors} {disabled} />+ {/if}+<EventSubscriptionsproviderId={provider}bind:eventImageUpdate={values.eventImageUpdate}diff --git a/frontend/src/routes/(app)/settings/notifications/providers/TelegramDestinationsEditor.svelte b/frontend/src/routes/(app)/settings/notifications/providers/TelegramDestinationsEditor.sveltenew file mode 100644index 000000000..f7886c662--- /dev/null+++ b/frontend/src/routes/(app)/settings/notifications/providers/TelegramDestinationsEditor.svelte@@ -0,0 +1,82 @@+<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';+ import { Label } from '#lib/components/ui/label/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import { AddIcon, CloseIcon } from '#lib/icons/index.js';+ import type { TelegramDestination } from '#lib/types/notifications.js';++ let {+ destinations = $bindable([]),+ errors = {},+ disabled = false+ }: {+ destinations: TelegramDestination[];+ errors?: Record<string, string | undefined>;+ disabled?: boolean;+ } = $props();++ function addDestination() {+ destinations.push({ chatId: '', topicId: '' });+ }++ function removeDestination(index: number) {+ destinations.splice(index, 1);+ }+</script>++<div class="space-y-3">+ <div>+ <Label class="text-sm font-medium">{m.notifications_telegram_destinations_label()}</Label>+ <p class="text-sm text-muted-foreground">{m.notifications_telegram_destinations_help()}</p>+ </div>+ {#each destinations as destination, index (destination)}+ <div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:gap-3">+ <div class="flex-1">+ <TextInputWithLabel+ id={`telegram-chat-id-${index}`}+ value={destination.chatId}+ onChange={(value) => (destination.chatId = value)}+ label={m.notifications_telegram_chat_id_label()}+ placeholder={m.notifications_telegram_chat_id_placeholder()}+ error={errors[`destinations.${index}.chatId`]}+ {disabled}+ />+ </div>+ <div class="flex-1">+ <TextInputWithLabel+ id={`telegram-topic-id-${index}`}+ value={destination.topicId}+ onChange={(value) => (destination.topicId = value)}+ label={m.notifications_telegram_topic_id_label()}+ placeholder={m.notifications_telegram_topic_id_placeholder()}+ error={errors[`destinations.${index}.topicId`]}+ {disabled}+ />+ </div>+ <ArcaneButton+ action="base"+ tone="ghost"+ size="icon"+ onclick={() => removeDestination(index)}+ disabled={disabled || destinations.length <= 1}+ aria-label={m.common_remove()}+ class="shrink-0 self-end text-destructive hover:text-destructive sm:mt-7 sm:self-auto"+ icon={CloseIcon}+ />+ </div>+ {/each}+ {#if errors['destinations']}+ <p class="text-sm text-destructive">{errors['destinations']}</p>+ {/if}+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ onclick={addDestination}+ {disabled}+ class="w-fit"+ icon={AddIcon}+ customLabel={m.notifications_telegram_add_destination()}+ />+</div>diff --git a/frontend/src/routes/(app)/settings/notifications/providers/provider-form-validation.ts b/frontend/src/routes/(app)/settings/notifications/providers/provider-form-validation.tsindex ea58a2861..08f15d744 100644--- a/frontend/src/routes/(app)/settings/notifications/providers/provider-form-validation.ts+++ b/frontend/src/routes/(app)/settings/notifications/providers/provider-form-validation.ts@@ -1,13 +1,15 @@import type { z } from 'zod/v4';-export function mapZodFieldErrors<T extends object>(validation: z.ZodSafeParseResult<T>): Partial<Record<keyof T, string>> {- const errors: Partial<Record<keyof T, string>> = {};+export type ProviderFieldErrors<T extends object> = Partial<Record<keyof T, string>> & Record<string, string | undefined>;++export function mapZodFieldErrors<T extends object>(validation: z.ZodSafeParseResult<T>): ProviderFieldErrors<T> {+ const errors: Record<string, string | undefined> = {};if (validation.success) {- return errors;+ return errors as ProviderFieldErrors<T>;}for (const issue of validation.error.issues) {- const key = issue.path?.[0] as keyof T | undefined;+ const key = issue.path.map(String).join('.');if (!key || errors[key]) {continue;}@@ -15,5 +17,5 @@ export function mapZodFieldErrors<T extends object>(validation: z.ZodSafeParseReerrors[key] = issue.message;}- return errors;+ return errors as ProviderFieldErrors<T>;}diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.tsindex a803a4a3d..513522092 100644--- a/tests/spec/settings-notifications.spec.ts+++ b/tests/spec/settings-notifications.spec.ts@@ -32,7 +32,10 @@ test.describe('Notification settings', () => {const setupNotificationTest = async (page: Page,provider: string,- options: { failProviders?: ReadonlySet<string> } = {}+ options: {+ failProviders?: ReadonlySet<string>;+ initialSettings?: Array<Record<string, unknown>>;+ } = {}) => {const observedErrors: string[] = [];@@ -52,7 +55,8 @@ test.describe('Notification settings', () => {const savedProviders: string[] = [];// Saved settings are kept in memory and served back on GET so that a// reload round-trips them through the form like the real backend would.- const persistedSettings: Array<Record<string, unknown>> = [];+ const persistedSettings: Array<Record<string, unknown>> = [...(options.initialSettings ?? [])];+ const savedPayloads: Array<Record<string, unknown>> = [];await page.route('**/api/environments/*/notifications/settings', async (route) => {const req = route.request();@@ -70,6 +74,7 @@ test.describe('Notification settings', () => {const saved = req.postDataJSON() as Record<string, unknown>;const savedProvider = String(saved.provider ?? '');attemptedProviders.push(savedProvider);+ savedPayloads.push(saved);if (options.failProviders?.has(savedProvider)) {await route.fulfill({status: 500,@@ -121,10 +126,37 @@ test.describe('Notification settings', () => {wasTestEndpointCalled: () => testEndpointCalled,wasSaveEndpointCalled: () => saveEndpointCalled,getAttemptedProviders: () => [...attemptedProviders],- getSavedProviders: () => [...savedProviders]+ getSavedProviders: () => [...savedProviders],+ getSavedPayloads: () => [...savedPayloads]};};+ const telegramSettings = (chatIds: string[]) => ({+ provider: 'telegram',+ enabled: true,+ config: {+ chatIds,+ preview: true,+ notification: true,+ title: '',+ events: {+ image_update: true,+ container_update: true,+ vulnerability_found: true,+ prune_report: true,+ auto_heal: true+ }+ }+ });++ const telegramChatIds = (payload: Record<string, unknown>) =>+ (payload.config as { chatIds: string[] }).chatIds;++ const telegramRow = (page: Page, index: number) => ({+ chatId: page.locator(`#telegram-chat-id-${index}`),+ topicId: page.locator(`#telegram-topic-id-${index}`)+ });+test('saves only changed providers and retains failed providers as dirty', async ({ page }) => {const { getAttemptedProviders, getSavedProviders } = await setupNotificationTest(page,@@ -253,7 +285,7 @@ test.describe('Notification settings', () => {await page.getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11').fill('123456:TEST-TOKEN');- await page.getByPlaceholder('@channel, 123456789, @another_channel').fill('123456789');+ await telegramRow(page, 0).chatId.fill('123456789');await openTestMenu(page);await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();@@ -267,6 +299,123 @@ test.describe('Notification settings', () => {getErrorCheck();});+ test('loads, edits and saves telegram topic destinations', async ({ page }) => {+ const { getSavedPayloads, wasSaveEndpointCalled } = await setupNotificationTest(+ page,+ 'telegram',+ {+ initialSettings: [telegramSettings(['@channel', '-1001234567890:42'])]+ }+ );++ await openProviderTab(page, 'Telegram');+ const saveButton = page.getByRole('button', { name: 'Save', exact: true });+ const panel = page.getByRole('tabpanel').filter({ visible: true });++ // Existing chats and chatId:topicId entries load into separate fields.+ await expect(telegramRow(page, 0).chatId).toHaveValue('@channel');+ await expect(telegramRow(page, 0).topicId).toHaveValue('');+ await expect(telegramRow(page, 1).chatId).toHaveValue('-1001234567890');+ await expect(telegramRow(page, 1).topicId).toHaveValue('42');+ await expect(saveButton).toBeDisabled();++ // A second topic in the same group plus a plain chat.+ await panel.getByRole('button', { name: 'Add destination' }).click();+ await telegramRow(page, 2).chatId.fill(' -1001234567890 ');+ await telegramRow(page, 2).topicId.fill(' 7 ');+ await panel.getByRole('button', { name: 'Add destination' }).click();+ await telegramRow(page, 3).chatId.fill('123456789');+ await expect(saveButton).toBeEnabled();++ // The redacted bot token stays blank and does not block saving.+ await expect(page.getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')).toHaveValue(+ ''+ );+ await saveButton.click();+ await expect.poll(wasSaveEndpointCalled).toBe(true);+ expect(telegramChatIds(getSavedPayloads()[0])).toEqual([+ '@channel',+ '-1001234567890:42',+ '-1001234567890:7',+ '123456789'+ ]);+ await expect(saveButton).toBeDisabled();++ // Saved destinations round-trip through a reload.+ await page.reload();+ await openProviderTab(page, 'Telegram');+ await expect(telegramRow(page, 3).chatId).toHaveValue('123456789');+ await expect(telegramRow(page, 2).topicId).toHaveValue('7');++ // Clearing a topic marks the form dirty and Reset restores the baseline.+ await telegramRow(page, 1).topicId.fill('');+ await expect(saveButton).toBeEnabled();+ await page.getByRole('button', { name: 'Reset', exact: true }).click();+ await expect(telegramRow(page, 1).topicId).toHaveValue('42');+ await expect(saveButton).toBeDisabled();++ // Removing a row saves the remaining destinations in order.+ await panel.getByRole('button', { name: 'Remove' }).nth(1).click();+ await expect(telegramRow(page, 1).topicId).toHaveValue('7');+ await saveButton.click();+ await expect.poll(() => getSavedPayloads().length).toBe(2);+ expect(telegramChatIds(getSavedPayloads()[1])).toEqual([+ '@channel',+ '-1001234567890:7',+ '123456789'+ ]);+ });++ test('rejects invalid telegram destinations before saving or testing', async ({ page }) => {+ const { wasSaveEndpointCalled, wasTestEndpointCalled } = await setupNotificationTest(+ page,+ 'telegram'+ );++ await openProviderTab(page, 'Telegram');+ await enableCurrentProvider(page);+ await page+ .getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')+ .fill('123456:TEST-TOKEN');++ const saveButton = page.getByRole('button', { name: 'Save', exact: true });+ const panel = page.getByRole('tabpanel').filter({ visible: true });++ // Non-numeric and non-positive topics are rejected.+ await telegramRow(page, 0).chatId.fill('-1001234567890');+ await telegramRow(page, 0).topicId.fill('abc');+ await expect(panel.getByText('Topic ID must be a positive whole number')).toBeVisible();+ await saveButton.click();+ await expect(page.getByText('Please check the form for errors').first()).toBeVisible();+ expect(wasSaveEndpointCalled()).toBe(false);++ await telegramRow(page, 0).topicId.fill('0');+ await expect(panel.getByText('Topic ID must be a positive whole number')).toBeVisible();++ // A topic without a chat is incomplete.+ await telegramRow(page, 0).topicId.fill('5');+ await telegramRow(page, 0).chatId.fill('');+ await expect(panel.getByText('This field is required')).toBeVisible();++ // A colon in the chat field is not accepted as an inline topic.+ await telegramRow(page, 0).chatId.fill('-1001234567890:5');+ await expect(panel.getByText(/Chat ID cannot contain a colon/)).toBeVisible();++ // Save & Test is blocked while the form is invalid.+ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();+ await page.getByRole('button', { name: 'Save & Test', exact: true }).click();+ await expect(page.getByText('Please check the form for errors').first()).toBeVisible();+ expect(wasSaveEndpointCalled()).toBe(false);+ expect(wasTestEndpointCalled()).toBe(false);++ // Fixing the row lets the save go through.+ await telegramRow(page, 0).chatId.fill('-1001234567890');+ await expect(panel.getByText(/Chat ID cannot contain a colon/)).toHaveCount(0);+ await saveButton.click();+ await expect.poll(wasSaveEndpointCalled).toBe(true);+ });+test('should allow testing generic webhook notifications', async ({ page }) => {const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');