mirror of
https://github.com/open-webui/computer.git
synced 2026-11-20 21:41:54 +03:00
refac
This commit is contained in:
@@ -121,7 +121,7 @@ Open WebUI Computer exposes an OpenAI-compatible API (`/v1/chat/completions`). A
|
||||
|---|---|
|
||||
| 🎙️ **Voice memos** | Record audio, auto-transcribe to markdown. |
|
||||
| 💬 **Message queue** | Queue follow-up messages while the AI is responding. |
|
||||
| 🔔 **Notifications** | Browser notifications and webhooks (Slack, Discord, Teams) when tasks finish. |
|
||||
| 🔔 **Notifications** | Browser notifications plus named webhook or bot targets for chat events. |
|
||||
| 📊 **Usage** | Token counts and timing on every response. |
|
||||
| 📄 **System prompts** | Per-model, per-workspace, or global. Template variables included. |
|
||||
| 📋 **Audit logging** | Structured audit trail of all API mutations with automatic redaction of sensitive data. |
|
||||
|
||||
@@ -19,6 +19,7 @@ from cptr.routers import (
|
||||
git_router,
|
||||
images_router,
|
||||
memory_router,
|
||||
notifications_router,
|
||||
proxy_router,
|
||||
search_router,
|
||||
skills_router,
|
||||
@@ -267,6 +268,7 @@ app.include_router(gateway_router)
|
||||
app.include_router(git_router)
|
||||
app.include_router(images_router)
|
||||
app.include_router(memory_router)
|
||||
app.include_router(notifications_router)
|
||||
app.include_router(proxy_router)
|
||||
app.include_router(search_router)
|
||||
app.include_router(skills_router)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Application event definitions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EventDefinition:
|
||||
name: str
|
||||
label: str
|
||||
|
||||
|
||||
class EventDefinitions:
|
||||
CHAT_FINISHED = EventDefinition("chat.finished", "Chat finished")
|
||||
CHAT_FAILED = EventDefinition("chat.failed", "Chat failed")
|
||||
NOTIFICATION_TEST = EventDefinition("notification.test", "Test notification")
|
||||
NOTIFICATION_MANUAL = EventDefinition("manual.notify", "Notification")
|
||||
|
||||
|
||||
EVENTS = EventDefinitions()
|
||||
|
||||
CHAT_NOTIFICATION_EVENTS = (
|
||||
EVENTS.CHAT_FINISHED,
|
||||
EVENTS.CHAT_FAILED,
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export const CHAT_NOTIFICATION_EVENTS = {
|
||||
FINISHED: 'chat.finished',
|
||||
FAILED: 'chat.failed'
|
||||
} as const;
|
||||
|
||||
export type ChatNotificationEvent =
|
||||
(typeof CHAT_NOTIFICATION_EVENTS)[keyof typeof CHAT_NOTIFICATION_EVENTS];
|
||||
export type NotificationDelivery = 'away' | 'always';
|
||||
export type NotificationTargetType = 'webhook' | 'bot';
|
||||
|
||||
export interface NotificationTarget {
|
||||
id: string;
|
||||
type: NotificationTargetType;
|
||||
enabled: boolean;
|
||||
events: ChatNotificationEvent[];
|
||||
delivery: NotificationDelivery;
|
||||
config: {
|
||||
url_masked?: string;
|
||||
bot_id?: string;
|
||||
destination_chat_id?: string;
|
||||
};
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
export interface BotOption {
|
||||
id: string;
|
||||
name: string;
|
||||
platform: string;
|
||||
is_active: boolean;
|
||||
is_running: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationTargetPayload {
|
||||
id?: string;
|
||||
type?: NotificationTargetType;
|
||||
enabled?: boolean;
|
||||
events?: ChatNotificationEvent[];
|
||||
delivery?: NotificationDelivery;
|
||||
config?: Record<string, string>;
|
||||
}
|
||||
|
||||
export async function listNotificationTargets(): Promise<NotificationTarget[]> {
|
||||
const data = await fetchJSON<{ targets: NotificationTarget[] }>('/api/notifications/targets');
|
||||
return data.targets;
|
||||
}
|
||||
|
||||
export function createNotificationTarget(payload: NotificationTargetPayload) {
|
||||
return fetchJSON<NotificationTarget>('/api/notifications/targets', jsonBody(payload));
|
||||
}
|
||||
|
||||
export function updateNotificationTarget(id: string, payload: NotificationTargetPayload) {
|
||||
return fetchJSON<NotificationTarget>(`/api/notifications/targets/${id}`, {
|
||||
...jsonBody(payload),
|
||||
method: 'PUT'
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteNotificationTarget(id: string) {
|
||||
return fetchJSON<{ ok: boolean }>(`/api/notifications/targets/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function testNotificationTarget(id: string) {
|
||||
return fetchJSON<{ ok: boolean }>(`/api/notifications/targets/${id}/test`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function listNotificationBotOptions(): Promise<BotOption[]> {
|
||||
const data = await fetchJSON<{ bots: BotOption[] }>('/api/notifications/bot-options');
|
||||
return data.bots;
|
||||
}
|
||||
@@ -1,60 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { streamingBehavior, showUpdateToastPref } from '$lib/stores';
|
||||
import type { StreamingBehavior } from '$lib/stores';
|
||||
import { t, locale, changeLocale, supportedLocales } from '$lib/i18n';
|
||||
import { notificationsEnabled, notificationSound } from '$lib/stores/chat';
|
||||
import { fetchJSON } from '$lib/apis';
|
||||
import { updateConfig } from '$lib/apis/admin';
|
||||
import { session } from '$lib/session';
|
||||
import ToggleSwitch from '../common/ToggleSwitch.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
// ── Webhook URL ─────────────────────────────────────────────
|
||||
let webhookUrl = $state('');
|
||||
let webhookUrlOriginal = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
let dirty = $derived(webhookUrl.trim() !== webhookUrlOriginal);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const data = await fetchJSON<{ config: Record<string, any> }>(
|
||||
'/api/admin/config/notifications'
|
||||
);
|
||||
const url = data.config?.['notifications.webhook_url'] || '';
|
||||
webhookUrl = url;
|
||||
webhookUrlOriginal = url;
|
||||
} catch {}
|
||||
});
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await updateConfig({ 'notifications.webhook_url': webhookUrl.trim() || null });
|
||||
webhookUrlOriginal = webhookUrl.trim();
|
||||
toast.success($t('settings.saved'));
|
||||
} catch {
|
||||
toast.error($t('general.webhookUrlSaveFailed'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleNotifications() {
|
||||
if (!$notificationsEnabled) {
|
||||
if ('Notification' in window) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission === 'granted') {
|
||||
notificationsEnabled.set(true);
|
||||
} else {
|
||||
toast.error($t('general.notificationPermissionDenied'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
notificationsEnabled.set(false);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
@@ -72,49 +21,6 @@
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<!-- Notifications -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
|
||||
{$t('general.notifications')}
|
||||
</h3>
|
||||
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<!-- Browser notifications toggle -->
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('general.browserNotifications')}</span
|
||||
>
|
||||
<ToggleSwitch value={$notificationsEnabled} onchange={() => toggleNotifications()} />
|
||||
</label>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('general.browserNotificationsDesc')}
|
||||
</p>
|
||||
|
||||
<!-- Sound toggle -->
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('general.notificationSound')}</span
|
||||
>
|
||||
<ToggleSwitch value={$notificationSound} onchange={(v) => notificationSound.set(v)} />
|
||||
</label>
|
||||
|
||||
<!-- Webhook URL -->
|
||||
<div class="mt-1">
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="webhook-url">
|
||||
{$t('general.webhookUrl')}
|
||||
</label>
|
||||
<input
|
||||
id="webhook-url"
|
||||
type="url"
|
||||
bind:value={webhookUrl}
|
||||
placeholder="https://hooks.slack.com/services/..."
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 mt-1">
|
||||
{$t('general.webhookUrlHint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if $session?.role === 'admin'}
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.updates')}</h3>
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
@@ -146,15 +52,4 @@
|
||||
{$streamingBehavior === 'queue' ? $t('general.queueDesc') : $t('general.interruptDesc')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 pt-3 flex justify-end">
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100
|
||||
disabled:opacity-30 disabled:pointer-events-none"
|
||||
onclick={save}
|
||||
disabled={saving}
|
||||
>
|
||||
{#if saving}{$t('settings.saving')}{:else}{$t('settings.save')}{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { t } from '$lib/i18n';
|
||||
import { notificationsEnabled, notificationSound } from '$lib/stores/chat';
|
||||
import {
|
||||
createNotificationTarget,
|
||||
CHAT_NOTIFICATION_EVENTS,
|
||||
deleteNotificationTarget,
|
||||
listNotificationBotOptions,
|
||||
listNotificationTargets,
|
||||
testNotificationTarget,
|
||||
updateNotificationTarget,
|
||||
type BotOption,
|
||||
type ChatNotificationEvent,
|
||||
type NotificationDelivery,
|
||||
type NotificationTarget,
|
||||
type NotificationTargetType
|
||||
} from '$lib/apis/notifications';
|
||||
import Icon from '../Icon.svelte';
|
||||
import Modal from '../Modal.svelte';
|
||||
import ToggleSwitch from '../common/ToggleSwitch.svelte';
|
||||
|
||||
const eventOptions: { value: ChatNotificationEvent; label: string }[] = [
|
||||
{ value: CHAT_NOTIFICATION_EVENTS.FINISHED, label: 'general.chatFinished' },
|
||||
{ value: CHAT_NOTIFICATION_EVENTS.FAILED, label: 'general.chatFailed' }
|
||||
];
|
||||
|
||||
let targets = $state<NotificationTarget[]>([]);
|
||||
let botOptions = $state<BotOption[]>([]);
|
||||
let loadingTargets = $state(false);
|
||||
let savingTarget = $state(false);
|
||||
let editingId = $state<string | null>(null);
|
||||
let formOpen = $state(false);
|
||||
let form = $state({
|
||||
id: '',
|
||||
type: 'webhook' as NotificationTargetType,
|
||||
url: '',
|
||||
bot_id: '',
|
||||
destination_chat_id: '',
|
||||
enabled: true,
|
||||
events: [] as ChatNotificationEvent[],
|
||||
delivery: 'away' as NotificationDelivery
|
||||
});
|
||||
let targetTypes = $derived<NotificationTargetType[]>(
|
||||
botOptions.length ? ['webhook', 'bot'] : ['webhook']
|
||||
);
|
||||
|
||||
onMount(() => {
|
||||
void loadNotificationTargets();
|
||||
});
|
||||
|
||||
async function loadNotificationTargets() {
|
||||
loadingTargets = true;
|
||||
try {
|
||||
const [nextTargets, bots] = await Promise.all([
|
||||
listNotificationTargets(),
|
||||
listNotificationBotOptions()
|
||||
]);
|
||||
targets = nextTargets;
|
||||
botOptions = bots;
|
||||
} catch {
|
||||
toast.error($t('general.notificationTargetsLoadFailed'));
|
||||
} finally {
|
||||
loadingTargets = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleNotifications() {
|
||||
if (!$notificationsEnabled) {
|
||||
if ('Notification' in window) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission === 'granted') {
|
||||
notificationsEnabled.set(true);
|
||||
} else {
|
||||
toast.error($t('general.notificationPermissionDenied'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
notificationsEnabled.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openNewTarget(type: NotificationTargetType = 'webhook') {
|
||||
if (type === 'bot' && !botOptions.length) type = 'webhook';
|
||||
editingId = null;
|
||||
formOpen = true;
|
||||
form = {
|
||||
id: '',
|
||||
type,
|
||||
url: '',
|
||||
bot_id: botOptions[0]?.id || '',
|
||||
destination_chat_id: '',
|
||||
enabled: true,
|
||||
events: [],
|
||||
delivery: 'away'
|
||||
};
|
||||
}
|
||||
|
||||
function openEditTarget(target: NotificationTarget) {
|
||||
editingId = target.id;
|
||||
formOpen = true;
|
||||
form = {
|
||||
id: target.id,
|
||||
type: target.type,
|
||||
url: '',
|
||||
bot_id: target.config.bot_id || botOptions[0]?.id || '',
|
||||
destination_chat_id: target.config.destination_chat_id || '',
|
||||
enabled: target.enabled,
|
||||
events: [...target.events],
|
||||
delivery: target.delivery
|
||||
};
|
||||
}
|
||||
|
||||
function toggleFormEvent(event: ChatNotificationEvent) {
|
||||
form.events = form.events.includes(event)
|
||||
? form.events.filter((item) => item !== event)
|
||||
: [...form.events, event];
|
||||
}
|
||||
|
||||
async function saveTarget() {
|
||||
savingTarget = true;
|
||||
try {
|
||||
const originalId = editingId;
|
||||
const payload: any = {
|
||||
id: form.id.trim(),
|
||||
type: form.type,
|
||||
enabled: form.enabled,
|
||||
events: form.events,
|
||||
delivery: form.delivery
|
||||
};
|
||||
if (form.type === 'webhook') {
|
||||
if (!editingId || form.url.trim()) payload.config = { url: form.url.trim() };
|
||||
} else {
|
||||
payload.config = {
|
||||
bot_id: form.bot_id,
|
||||
destination_chat_id: form.destination_chat_id.trim()
|
||||
};
|
||||
}
|
||||
const saved = originalId
|
||||
? await updateNotificationTarget(originalId, payload)
|
||||
: await createNotificationTarget(payload);
|
||||
targets = originalId
|
||||
? targets.map((target) => (target.id === originalId ? saved : target))
|
||||
: [...targets, saved];
|
||||
formOpen = false;
|
||||
toast.success($t('settings.saved'));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
} finally {
|
||||
savingTarget = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function patchTarget(target: NotificationTarget, patch: Partial<NotificationTarget>) {
|
||||
try {
|
||||
const saved = await updateNotificationTarget(target.id, patch as any);
|
||||
targets = targets.map((item) => (item.id === saved.id ? saved : item));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function removeTarget(target: NotificationTarget) {
|
||||
try {
|
||||
await deleteNotificationTarget(target.id);
|
||||
targets = targets.filter((item) => item.id !== target.id);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function sendTest(target: NotificationTarget) {
|
||||
try {
|
||||
await testNotificationTarget(target.id);
|
||||
toast.success($t('general.testSent'));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover pr-1.5 -mr-1.5">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
|
||||
{$t('general.notifications')}
|
||||
</h2>
|
||||
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">
|
||||
{$t('general.browserNotifications')}
|
||||
</span>
|
||||
<ToggleSwitch value={$notificationsEnabled} onchange={() => toggleNotifications()} />
|
||||
</label>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('general.browserNotificationsDesc')}
|
||||
</p>
|
||||
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">
|
||||
{$t('general.notificationSound')}
|
||||
</span>
|
||||
<ToggleSwitch value={$notificationSound} onchange={(v) => notificationSound.set(v)} />
|
||||
</label>
|
||||
|
||||
<div class="mt-3 flex items-center justify-between">
|
||||
<span class="text-xs font-medium text-gray-700 dark:text-gray-300">
|
||||
{$t('general.notificationTargets')}
|
||||
</span>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={() => openNewTarget()}
|
||||
title={$t('general.addNotificationTarget')}
|
||||
aria-label={$t('general.addNotificationTarget')}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if loadingTargets}
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600">{$t('common.loading')}</p>
|
||||
{:else if !targets.length}
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.noNotificationTargets')}
|
||||
</p>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-2">
|
||||
{#each targets as target}
|
||||
<div class="rounded-lg border border-gray-200 dark:border-white/8 p-2">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="truncate text-xs font-medium text-gray-800 dark:text-gray-200">
|
||||
{target.id}
|
||||
</span>
|
||||
<span class="text-[0.625rem] uppercase text-gray-400 dark:text-gray-600">
|
||||
{target.type === 'webhook' ? $t('general.webhook') : $t('general.bot')}
|
||||
</span>
|
||||
</div>
|
||||
<p class="truncate text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{target.type === 'webhook'
|
||||
? target.config.url_masked
|
||||
: target.config.destination_chat_id}
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={target.enabled}
|
||||
onchange={(v) => patchTarget(target, { enabled: v })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-2">
|
||||
<div class="mb-1 text-[0.625rem] font-medium text-gray-400 dark:text-gray-600">
|
||||
{$t('general.automaticEvents')}
|
||||
</div>
|
||||
{#if target.events.length}
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each eventOptions.filter((event) => target.events.includes(event.value)) as event}
|
||||
<button
|
||||
class="h-6 rounded-md bg-gray-200/60 px-2 text-[0.6875rem] text-gray-900 transition-colors hover:bg-gray-200 dark:bg-white/10 dark:text-white dark:hover:bg-white/15"
|
||||
onclick={() =>
|
||||
patchTarget(target, {
|
||||
events: target.events.filter((item) => item !== event.value)
|
||||
})}
|
||||
>
|
||||
{$t(event.label)}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.noChatAlerts')}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-2 flex items-end justify-between gap-2">
|
||||
{#if target.events.length}
|
||||
<div>
|
||||
<div class="mb-1 text-[0.625rem] font-medium text-gray-400 dark:text-gray-600">
|
||||
{$t('general.automaticDelivery')}
|
||||
</div>
|
||||
<div class="flex gap-1">
|
||||
{#each ['away', 'always'] as mode}
|
||||
<button
|
||||
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors
|
||||
{target.delivery === mode
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() =>
|
||||
patchTarget(target, { delivery: mode as NotificationDelivery })}
|
||||
>
|
||||
{mode === 'away' ? $t('general.onlyWhenAway') : $t('general.always')}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div></div>
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
class="text-[0.6875rem] text-gray-500 hover:text-gray-900 dark:hover:text-white"
|
||||
onclick={() => sendTest(target)}
|
||||
>
|
||||
{$t('general.sendTest')}
|
||||
</button>
|
||||
<button
|
||||
class="text-[0.6875rem] text-gray-500 hover:text-gray-900 dark:hover:text-white"
|
||||
onclick={() => openEditTarget(target)}
|
||||
>
|
||||
{$t('common.edit')}
|
||||
</button>
|
||||
<button
|
||||
class="text-[0.6875rem] text-red-500 hover:text-red-600"
|
||||
onclick={() => removeTarget(target)}
|
||||
>
|
||||
{$t('common.remove')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if formOpen}
|
||||
<Modal onclose={() => (formOpen = false)} class="w-full max-w-md mx-4">
|
||||
<div class="p-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">
|
||||
{editingId ? $t('common.edit') : $t('general.addNotificationTarget')}
|
||||
</h2>
|
||||
|
||||
<div class="mb-2 flex gap-1">
|
||||
{#each targetTypes as type}
|
||||
<button
|
||||
class="h-7 rounded-md px-2 text-xs transition-colors
|
||||
{form.type === type
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() => (form.type = type)}
|
||||
>
|
||||
{type === 'webhook' ? $t('general.webhook') : $t('general.bot')}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.targetIdForNotify')}
|
||||
</label>
|
||||
<input
|
||||
bind:value={form.id}
|
||||
placeholder={$t('general.targetId')}
|
||||
autofocus
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
|
||||
{#if form.type === 'webhook'}
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('general.webhook')}
|
||||
</label>
|
||||
<input
|
||||
type="url"
|
||||
bind:value={form.url}
|
||||
placeholder={editingId ? $t('general.keepWebhookUrl') : 'https://hooks.slack.com/services/...'}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
{:else}
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('general.bot')}
|
||||
</label>
|
||||
<select
|
||||
bind:value={form.bot_id}
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
{#each botOptions as bot}
|
||||
<option value={bot.id}>
|
||||
{bot.name} ({bot.platform}){bot.is_running ? '' : ' - stopped'}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('general.platformDestinationId')}
|
||||
</label>
|
||||
<input
|
||||
bind:value={form.destination_chat_id}
|
||||
placeholder={$t('general.platformDestinationId')}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<label class="block text-[0.625rem] text-gray-400 dark:text-gray-600 mt-3 mb-1">
|
||||
{$t('general.automaticEvents')}
|
||||
</label>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each eventOptions as event}
|
||||
<button
|
||||
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors
|
||||
{form.events.includes(event.value)
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() => toggleFormEvent(event.value)}
|
||||
>
|
||||
{$t(event.label)}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if form.events.length}
|
||||
<label class="block text-[0.625rem] text-gray-400 dark:text-gray-600 mt-3 mb-1">
|
||||
{$t('general.automaticDelivery')}
|
||||
</label>
|
||||
<div class="flex gap-1">
|
||||
{#each ['away', 'always'] as mode}
|
||||
<button
|
||||
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors
|
||||
{form.delivery === mode
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() => (form.delivery = mode as NotificationDelivery)}
|
||||
>
|
||||
{mode === 'away' ? $t('general.onlyWhenAway') : $t('general.always')}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<p class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-3">
|
||||
{$t('general.notifyToolAlwaysSends')}
|
||||
</p>
|
||||
|
||||
<div class="flex justify-end gap-3 mt-4">
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => (formOpen = false)}
|
||||
>
|
||||
{$t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-700 hover:text-gray-900 disabled:opacity-30 dark:text-gray-300 dark:hover:text-white transition-colors duration-100"
|
||||
onclick={saveTarget}
|
||||
disabled={savingTarget || (form.type === 'bot' && !botOptions.length)}
|
||||
>
|
||||
{savingTarget ? $t('settings.saving') : $t('settings.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
{/if}
|
||||
@@ -3,6 +3,7 @@
|
||||
import Icon from './Icon.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
import General from './Settings/General.svelte';
|
||||
import Notifications from './Settings/Notifications.svelte';
|
||||
import Appearance from './Settings/Appearance.svelte';
|
||||
import Memory from './Settings/Memory.svelte';
|
||||
import PWA from './Settings/PWA.svelte';
|
||||
@@ -25,6 +26,7 @@
|
||||
|
||||
type Tab =
|
||||
| 'general'
|
||||
| 'notifications'
|
||||
| 'appearance'
|
||||
| 'memory'
|
||||
| 'pwa'
|
||||
@@ -76,6 +78,7 @@
|
||||
const tabs: SettingsTab[] = [
|
||||
{ id: 'general', label: $t('settings.general'), icon: 'settings' },
|
||||
{ id: 'appearance', label: $t('settings.appearance'), icon: 'sun-light' },
|
||||
{ id: 'notifications', label: $t('general.notifications'), icon: 'chat-bubble' },
|
||||
{ id: 'keyboard', label: $t('settings.keyboard'), icon: 'terminal' },
|
||||
{ id: 'account', label: $t('settings.account'), icon: 'user' }
|
||||
];
|
||||
@@ -178,6 +181,8 @@
|
||||
<div class="flex-1 overflow-y-auto scrollbar-none min-h-0 p-4 md:px-5">
|
||||
{#if activeTab === 'general'}
|
||||
<General />
|
||||
{:else if activeTab === 'notifications'}
|
||||
<Notifications />
|
||||
{:else if activeTab === 'appearance'}
|
||||
<Appearance />
|
||||
{:else if activeTab === 'memory'}
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "Systembenachrichtigungen anzeigen, wenn eine Aufgabe abgeschlossen ist und der Tab nicht fokussiert ist.",
|
||||
"general.notificationSound": "Benachrichtigungston",
|
||||
"general.notificationPermissionDenied": "Browser-Benachrichtigungserlaubnis verweigert",
|
||||
"general.webhookUrl": "Webhook-URL",
|
||||
"general.webhookUrlSaved": "Webhook-URL gespeichert",
|
||||
"general.webhookUrlSaveFailed": "Webhook-URL konnte nicht gespeichert werden",
|
||||
"general.webhookUrlHint": "Unterstützt Slack, Discord, Teams und generische JSON-Webhooks.",
|
||||
"general.notificationTargets": "Benachrichtigungsziele",
|
||||
"general.addNotificationTarget": "Benachrichtigungsziel hinzufügen",
|
||||
"general.noNotificationTargets": "Noch keine Benachrichtigungsziele.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat beendet",
|
||||
"general.chatFailed": "Chat fehlgeschlagen",
|
||||
"general.automaticEvents": "Chat-Hinweise (optional)",
|
||||
"general.noChatAlerts": "Keine Chat-Hinweise",
|
||||
"general.automaticDelivery": "Chat-Hinweise senden",
|
||||
"general.onlyWhenAway": "Nur wenn ich abwesend bin",
|
||||
"general.always": "Immer",
|
||||
"general.sendTest": "Test senden",
|
||||
"general.platformDestinationId": "Plattform-Ziel-ID",
|
||||
"general.targetId": "Ziel-ID",
|
||||
"general.targetIdForNotify": "Ziel-ID",
|
||||
"general.notifyToolAlwaysSends": "Agenten können dieses Ziel auch aus einem Chat benachrichtigen.",
|
||||
"general.keepWebhookUrl": "Leer lassen, um die aktuelle URL zu behalten",
|
||||
"general.testSent": "Test gesendet",
|
||||
"general.notificationTargetsLoadFailed": "Benachrichtigungsziele konnten nicht geladen werden",
|
||||
"general.notificationTargetSaveFailed": "Benachrichtigungsziel konnte nicht gespeichert werden",
|
||||
"general.updates": "Aktualisierungen",
|
||||
"general.updateNotifications": "Update-Benachrichtigungen",
|
||||
"general.updateNotificationsDesc": "Eine Benachrichtigung anzeigen, wenn eine neue Version von Computer verfügbar ist.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "Show OS-level notifications when a task completes and the tab is not focused.",
|
||||
"general.notificationSound": "Notification sound",
|
||||
"general.notificationPermissionDenied": "Browser notification permission denied",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL saved",
|
||||
"general.webhookUrlSaveFailed": "Failed to save webhook URL",
|
||||
"general.webhookUrlHint": "Supports Slack, Discord, Teams, and generic JSON webhooks.",
|
||||
"general.notificationTargets": "Notification targets",
|
||||
"general.addNotificationTarget": "Add notification target",
|
||||
"general.noNotificationTargets": "No notification targets yet.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat finished",
|
||||
"general.chatFailed": "Chat failed",
|
||||
"general.automaticEvents": "Chat alerts (optional)",
|
||||
"general.noChatAlerts": "No chat alerts",
|
||||
"general.automaticDelivery": "Send chat alerts",
|
||||
"general.onlyWhenAway": "Only when I'm away",
|
||||
"general.always": "Always",
|
||||
"general.sendTest": "Send test",
|
||||
"general.platformDestinationId": "Platform destination ID",
|
||||
"general.targetId": "Target ID",
|
||||
"general.targetIdForNotify": "Target ID",
|
||||
"general.notifyToolAlwaysSends": "Agents can also notify this target from a chat.",
|
||||
"general.keepWebhookUrl": "Leave blank to keep current URL",
|
||||
"general.testSent": "Test sent",
|
||||
"general.notificationTargetsLoadFailed": "Failed to load notification targets",
|
||||
"general.notificationTargetSaveFailed": "Failed to save notification target",
|
||||
"general.updates": "Updates",
|
||||
"general.updateNotifications": "Update notifications",
|
||||
"general.updateNotificationsDesc": "Show a toast when a new version of Computer is available.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "Mostrar notificaciones del sistema cuando una tarea se completa y la pestaña no está enfocada.",
|
||||
"general.notificationSound": "Sonido de notificación",
|
||||
"general.notificationPermissionDenied": "Permiso de notificación del navegador denegado",
|
||||
"general.webhookUrl": "URL del webhook",
|
||||
"general.webhookUrlSaved": "URL del webhook guardada",
|
||||
"general.webhookUrlSaveFailed": "Error al guardar URL del webhook",
|
||||
"general.webhookUrlHint": "Compatible con Slack, Discord, Teams y webhooks JSON genéricos.",
|
||||
"general.notificationTargets": "Destinos de notificación",
|
||||
"general.addNotificationTarget": "Agregar destino de notificación",
|
||||
"general.noNotificationTargets": "Aún no hay destinos de notificación.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat finalizado",
|
||||
"general.chatFailed": "Chat fallido",
|
||||
"general.automaticEvents": "Alertas de chat (opcional)",
|
||||
"general.noChatAlerts": "Sin alertas de chat",
|
||||
"general.automaticDelivery": "Enviar alertas de chat",
|
||||
"general.onlyWhenAway": "Solo cuando estoy ausente",
|
||||
"general.always": "Siempre",
|
||||
"general.sendTest": "Enviar prueba",
|
||||
"general.platformDestinationId": "ID de destino de la plataforma",
|
||||
"general.targetId": "ID del destino",
|
||||
"general.targetIdForNotify": "ID del destino",
|
||||
"general.notifyToolAlwaysSends": "Los agentes también pueden notificar a este destino desde un chat.",
|
||||
"general.keepWebhookUrl": "Deja en blanco para conservar la URL actual",
|
||||
"general.testSent": "Prueba enviada",
|
||||
"general.notificationTargetsLoadFailed": "Error al cargar destinos de notificación",
|
||||
"general.notificationTargetSaveFailed": "Error al guardar destino de notificación",
|
||||
"general.updates": "Actualizaciones",
|
||||
"general.updateNotifications": "Notificaciones de actualización",
|
||||
"general.updateNotificationsDesc": "Mostrar un aviso cuando hay una nueva versión de Computer disponible.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "Afficher les notifications du système lorsqu'une tâche se termine et que l'onglet n'est pas actif.",
|
||||
"general.notificationSound": "Son de notification",
|
||||
"general.notificationPermissionDenied": "Permission de notification du navigateur refusée",
|
||||
"general.webhookUrl": "URL du webhook",
|
||||
"general.webhookUrlSaved": "URL du webhook enregistrée",
|
||||
"general.webhookUrlSaveFailed": "Échec de l'enregistrement de l'URL du webhook",
|
||||
"general.webhookUrlHint": "Prend en charge Slack, Discord, Teams et les webhooks JSON génériques.",
|
||||
"general.notificationTargets": "Cibles de notification",
|
||||
"general.addNotificationTarget": "Ajouter une cible de notification",
|
||||
"general.noNotificationTargets": "Aucune cible de notification pour l’instant.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat terminé",
|
||||
"general.chatFailed": "Échec du chat",
|
||||
"general.automaticEvents": "Alertes de chat (facultatif)",
|
||||
"general.noChatAlerts": "Aucune alerte de chat",
|
||||
"general.automaticDelivery": "Envoyer les alertes de chat",
|
||||
"general.onlyWhenAway": "Seulement quand je suis absent",
|
||||
"general.always": "Toujours",
|
||||
"general.sendTest": "Envoyer un test",
|
||||
"general.platformDestinationId": "ID de destination de la plateforme",
|
||||
"general.targetId": "ID de la cible",
|
||||
"general.targetIdForNotify": "ID de la cible",
|
||||
"general.notifyToolAlwaysSends": "Les agents peuvent aussi notifier cette cible depuis un chat.",
|
||||
"general.keepWebhookUrl": "Laisser vide pour conserver l’URL actuelle",
|
||||
"general.testSent": "Test envoyé",
|
||||
"general.notificationTargetsLoadFailed": "Échec du chargement des cibles de notification",
|
||||
"general.notificationTargetSaveFailed": "Échec de l’enregistrement de la cible de notification",
|
||||
"general.updates": "Mises à jour",
|
||||
"general.updateNotifications": "Notifications de mise à jour",
|
||||
"general.updateNotificationsDesc": "Afficher une notification lorsqu'une nouvelle version de Computer est disponible.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "タスク完了時にタブがフォーカスされていない場合、OS通知を表示します。",
|
||||
"general.notificationSound": "通知音",
|
||||
"general.notificationPermissionDenied": "ブラウザ通知の許可が拒否されました",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URLを保存しました",
|
||||
"general.webhookUrlSaveFailed": "Webhook URLの保存に失敗しました",
|
||||
"general.webhookUrlHint": "Slack、Discord、Teams、汎用JSONウェブフックに対応。",
|
||||
"general.notificationTargets": "通知先",
|
||||
"general.addNotificationTarget": "通知先を追加",
|
||||
"general.noNotificationTargets": "通知先はまだありません。",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "チャット完了",
|
||||
"general.chatFailed": "チャット失敗",
|
||||
"general.automaticEvents": "チャット通知(任意)",
|
||||
"general.noChatAlerts": "チャット通知なし",
|
||||
"general.automaticDelivery": "チャット通知を送信",
|
||||
"general.onlyWhenAway": "離席中のみ",
|
||||
"general.always": "常に",
|
||||
"general.sendTest": "テスト送信",
|
||||
"general.platformDestinationId": "プラットフォーム送信先ID",
|
||||
"general.targetId": "通知先ID",
|
||||
"general.targetIdForNotify": "通知先ID",
|
||||
"general.notifyToolAlwaysSends": "エージェントはチャットからこの通知先へ通知することもできます。",
|
||||
"general.keepWebhookUrl": "現在のURLを保持する場合は空欄",
|
||||
"general.testSent": "テストを送信しました",
|
||||
"general.notificationTargetsLoadFailed": "通知先の読み込みに失敗しました",
|
||||
"general.notificationTargetSaveFailed": "通知先の保存に失敗しました",
|
||||
"general.updates": "アップデート",
|
||||
"general.updateNotifications": "アップデート通知",
|
||||
"general.updateNotificationsDesc": "Computerの新しいバージョンが利用可能な場合にトーストを表示します。",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "작업이 완료되고 탭이 포커스되지 않았을 때 OS 알림을 표시합니다.",
|
||||
"general.notificationSound": "알림 소리",
|
||||
"general.notificationPermissionDenied": "브라우저 알림 권한이 거부되었습니다",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL이 저장되었습니다",
|
||||
"general.webhookUrlSaveFailed": "Webhook URL 저장에 실패했습니다",
|
||||
"general.webhookUrlHint": "Slack, Discord, Teams 및 일반 JSON 웹훅을 지원합니다.",
|
||||
"general.notificationTargets": "알림 대상",
|
||||
"general.addNotificationTarget": "알림 대상 추가",
|
||||
"general.noNotificationTargets": "아직 알림 대상이 없습니다.",
|
||||
"general.webhook": "웹훅",
|
||||
"general.bot": "봇",
|
||||
"general.chatFinished": "채팅 완료",
|
||||
"general.chatFailed": "채팅 실패",
|
||||
"general.automaticEvents": "채팅 알림 (선택 사항)",
|
||||
"general.noChatAlerts": "채팅 알림 없음",
|
||||
"general.automaticDelivery": "채팅 알림 보내기",
|
||||
"general.onlyWhenAway": "자리 비움일 때만",
|
||||
"general.always": "항상",
|
||||
"general.sendTest": "테스트 보내기",
|
||||
"general.platformDestinationId": "플랫폼 대상 ID",
|
||||
"general.targetId": "대상 ID",
|
||||
"general.targetIdForNotify": "대상 ID",
|
||||
"general.notifyToolAlwaysSends": "에이전트가 채팅에서 이 대상으로 알림을 보낼 수도 있습니다.",
|
||||
"general.keepWebhookUrl": "현재 URL을 유지하려면 비워 두세요",
|
||||
"general.testSent": "테스트를 보냈습니다",
|
||||
"general.notificationTargetsLoadFailed": "알림 대상을 불러오지 못했습니다",
|
||||
"general.notificationTargetSaveFailed": "알림 대상을 저장하지 못했습니다",
|
||||
"general.updates": "업데이트",
|
||||
"general.updateNotifications": "업데이트 알림",
|
||||
"general.updateNotificationsDesc": "Computer의 새 버전이 사용 가능할 때 알림을 표시합니다.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "Mostrar notificações do sistema quando uma tarefa é concluída e a aba não está em foco.",
|
||||
"general.notificationSound": "Som de notificação",
|
||||
"general.notificationPermissionDenied": "Permissão de notificação do navegador negada",
|
||||
"general.webhookUrl": "URL do webhook",
|
||||
"general.webhookUrlSaved": "URL do webhook salva",
|
||||
"general.webhookUrlSaveFailed": "Falha ao salvar URL do webhook",
|
||||
"general.webhookUrlHint": "Suporta Slack, Discord, Teams e webhooks JSON genéricos.",
|
||||
"general.notificationTargets": "Destinos de notificação",
|
||||
"general.addNotificationTarget": "Adicionar destino de notificação",
|
||||
"general.noNotificationTargets": "Ainda não há destinos de notificação.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat concluído",
|
||||
"general.chatFailed": "Chat falhou",
|
||||
"general.automaticEvents": "Alertas de chat (opcional)",
|
||||
"general.noChatAlerts": "Sem alertas de chat",
|
||||
"general.automaticDelivery": "Enviar alertas de chat",
|
||||
"general.onlyWhenAway": "Só quando eu estiver ausente",
|
||||
"general.always": "Sempre",
|
||||
"general.sendTest": "Enviar teste",
|
||||
"general.platformDestinationId": "ID do destino na plataforma",
|
||||
"general.targetId": "ID do destino",
|
||||
"general.targetIdForNotify": "ID do destino",
|
||||
"general.notifyToolAlwaysSends": "Agentes também podem notificar este destino a partir de um chat.",
|
||||
"general.keepWebhookUrl": "Deixe em branco para manter a URL atual",
|
||||
"general.testSent": "Teste enviado",
|
||||
"general.notificationTargetsLoadFailed": "Falha ao carregar destinos de notificação",
|
||||
"general.notificationTargetSaveFailed": "Falha ao salvar destino de notificação",
|
||||
"general.updates": "Atualizações",
|
||||
"general.updateNotifications": "Notificações de atualização",
|
||||
"general.updateNotificationsDesc": "Mostrar um aviso quando uma nova versão do Computer estiver disponível.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "Показывать уведомления ОС при завершении задачи, когда вкладка не в фокусе.",
|
||||
"general.notificationSound": "Звук уведомления",
|
||||
"general.notificationPermissionDenied": "Разрешение на уведомления браузера отклонено",
|
||||
"general.webhookUrl": "URL вебхука",
|
||||
"general.webhookUrlSaved": "URL вебхука сохранён",
|
||||
"general.webhookUrlSaveFailed": "Не удалось сохранить URL вебхука",
|
||||
"general.webhookUrlHint": "Поддерживает Slack, Discord, Teams и универсальные JSON-вебхуки.",
|
||||
"general.notificationTargets": "Цели уведомлений",
|
||||
"general.addNotificationTarget": "Добавить цель уведомления",
|
||||
"general.noNotificationTargets": "Целей уведомлений пока нет.",
|
||||
"general.webhook": "Вебхук",
|
||||
"general.bot": "Бот",
|
||||
"general.chatFinished": "Чат завершён",
|
||||
"general.chatFailed": "Ошибка чата",
|
||||
"general.automaticEvents": "Оповещения чата (необязательно)",
|
||||
"general.noChatAlerts": "Нет оповещений чата",
|
||||
"general.automaticDelivery": "Отправлять оповещения чата",
|
||||
"general.onlyWhenAway": "Только когда меня нет",
|
||||
"general.always": "Всегда",
|
||||
"general.sendTest": "Отправить тест",
|
||||
"general.platformDestinationId": "ID назначения платформы",
|
||||
"general.targetId": "ID цели",
|
||||
"general.targetIdForNotify": "ID цели",
|
||||
"general.notifyToolAlwaysSends": "Агенты также могут уведомлять эту цель из чата.",
|
||||
"general.keepWebhookUrl": "Оставьте пустым, чтобы сохранить текущий URL",
|
||||
"general.testSent": "Тест отправлен",
|
||||
"general.notificationTargetsLoadFailed": "Не удалось загрузить цели уведомлений",
|
||||
"general.notificationTargetSaveFailed": "Не удалось сохранить цель уведомлений",
|
||||
"general.updates": "Обновления",
|
||||
"general.updateNotifications": "Уведомления об обновлениях",
|
||||
"general.updateNotificationsDesc": "Показывать уведомление, когда доступна новая версия Computer.",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "当任务完成且标签页未聚焦时显示系统通知。",
|
||||
"general.notificationSound": "通知声音",
|
||||
"general.notificationPermissionDenied": "浏览器通知权限被拒绝",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL 已保存",
|
||||
"general.webhookUrlSaveFailed": "保存 Webhook URL 失败",
|
||||
"general.webhookUrlHint": "支持 Slack、Discord、Teams 和通用 JSON Webhook。",
|
||||
"general.notificationTargets": "通知目标",
|
||||
"general.addNotificationTarget": "添加通知目标",
|
||||
"general.noNotificationTargets": "还没有通知目标。",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "机器人",
|
||||
"general.chatFinished": "聊天已完成",
|
||||
"general.chatFailed": "聊天失败",
|
||||
"general.automaticEvents": "聊天提醒(可选)",
|
||||
"general.noChatAlerts": "没有聊天提醒",
|
||||
"general.automaticDelivery": "发送聊天提醒",
|
||||
"general.onlyWhenAway": "仅在我离开时",
|
||||
"general.always": "始终",
|
||||
"general.sendTest": "发送测试",
|
||||
"general.platformDestinationId": "平台目标 ID",
|
||||
"general.targetId": "目标 ID",
|
||||
"general.targetIdForNotify": "目标 ID",
|
||||
"general.notifyToolAlwaysSends": "代理也可以从聊天中通知此目标。",
|
||||
"general.keepWebhookUrl": "留空以保留当前 URL",
|
||||
"general.testSent": "测试已发送",
|
||||
"general.notificationTargetsLoadFailed": "无法加载通知目标",
|
||||
"general.notificationTargetSaveFailed": "无法保存通知目标",
|
||||
"general.updates": "更新",
|
||||
"general.updateNotifications": "更新通知",
|
||||
"general.updateNotificationsDesc": "当 Computer 有新版本可用时显示提示。",
|
||||
|
||||
@@ -399,10 +399,27 @@
|
||||
"general.browserNotificationsDesc": "當任務完成且分頁未聚焦時顯示系統通知。",
|
||||
"general.notificationSound": "通知聲音",
|
||||
"general.notificationPermissionDenied": "瀏覽器通知權限被拒絕",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL 已儲存",
|
||||
"general.webhookUrlSaveFailed": "儲存 Webhook URL 失敗",
|
||||
"general.webhookUrlHint": "支援 Slack、Discord、Teams 和通用 JSON Webhook。",
|
||||
"general.notificationTargets": "通知目標",
|
||||
"general.addNotificationTarget": "新增通知目標",
|
||||
"general.noNotificationTargets": "尚無通知目標。",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "機器人",
|
||||
"general.chatFinished": "聊天已完成",
|
||||
"general.chatFailed": "聊天失敗",
|
||||
"general.automaticEvents": "聊天提醒(選用)",
|
||||
"general.noChatAlerts": "沒有聊天提醒",
|
||||
"general.automaticDelivery": "傳送聊天提醒",
|
||||
"general.onlyWhenAway": "僅在我離開時",
|
||||
"general.always": "一律",
|
||||
"general.sendTest": "傳送測試",
|
||||
"general.platformDestinationId": "平台目標 ID",
|
||||
"general.targetId": "目標 ID",
|
||||
"general.targetIdForNotify": "目標 ID",
|
||||
"general.notifyToolAlwaysSends": "代理也可以從聊天中通知此目標。",
|
||||
"general.keepWebhookUrl": "留空以保留目前 URL",
|
||||
"general.testSent": "測試已傳送",
|
||||
"general.notificationTargetsLoadFailed": "無法載入通知目標",
|
||||
"general.notificationTargetSaveFailed": "無法儲存通知目標",
|
||||
"general.updates": "更新",
|
||||
"general.updateNotifications": "更新通知",
|
||||
"general.updateNotificationsDesc": "當 Computer 有新版本可用時顯示提示。",
|
||||
|
||||
@@ -13,6 +13,7 @@ from cptr.routers.files import router as files_router
|
||||
from cptr.routers.git import router as git_router
|
||||
from cptr.routers.images import router as images_router
|
||||
from cptr.routers.memory import router as memory_router
|
||||
from cptr.routers.notifications import router as notifications_router
|
||||
from cptr.routers.proxy import router as proxy_router
|
||||
from cptr.routers.search import router as search_router
|
||||
from cptr.routers.skills import router as skills_router
|
||||
@@ -34,6 +35,7 @@ __all__ = [
|
||||
"git_router",
|
||||
"images_router",
|
||||
"memory_router",
|
||||
"notifications_router",
|
||||
"proxy_router",
|
||||
"search_router",
|
||||
"skills_router",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""User notification target API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.utils.notifications import (
|
||||
NotificationError,
|
||||
create_target,
|
||||
delete_target,
|
||||
get_bot_options,
|
||||
list_targets,
|
||||
test_target,
|
||||
update_target,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/notifications", tags=["notifications"])
|
||||
|
||||
|
||||
class TargetPayload(BaseModel):
|
||||
id: str | None = None
|
||||
type: str | None = None
|
||||
enabled: bool | None = None
|
||||
events: list[str] | None = None
|
||||
delivery: str | None = None
|
||||
config: dict | None = None
|
||||
|
||||
|
||||
def _user_id(request: Request) -> str:
|
||||
auth = getattr(request.state, "auth", None)
|
||||
if not auth or not auth.user_id:
|
||||
raise HTTPException(401, "authentication required")
|
||||
return auth.user_id
|
||||
|
||||
|
||||
def _payload(body: TargetPayload) -> dict:
|
||||
if hasattr(body, "model_dump"):
|
||||
return body.model_dump(exclude_unset=True)
|
||||
return body.dict(exclude_unset=True)
|
||||
|
||||
|
||||
def _error(exc: NotificationError) -> HTTPException:
|
||||
message = str(exc)
|
||||
status = 404 if "not found" in message else 400
|
||||
return HTTPException(status, message)
|
||||
|
||||
|
||||
@router.get("/targets")
|
||||
async def api_list_targets(request: Request):
|
||||
return {"targets": await list_targets(_user_id(request))}
|
||||
|
||||
|
||||
@router.post("/targets")
|
||||
async def api_create_target(request: Request, body: TargetPayload):
|
||||
try:
|
||||
return await create_target(_user_id(request), _payload(body))
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.put("/targets/{target_id}")
|
||||
async def api_update_target(request: Request, target_id: str, body: TargetPayload):
|
||||
try:
|
||||
return await update_target(_user_id(request), target_id, _payload(body))
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.delete("/targets/{target_id}")
|
||||
async def api_delete_target(request: Request, target_id: str):
|
||||
ok = await delete_target(_user_id(request), target_id)
|
||||
if not ok:
|
||||
raise HTTPException(404, "notification target not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/targets/{target_id}/test")
|
||||
async def api_test_target(request: Request, target_id: str):
|
||||
try:
|
||||
return await test_target(_user_id(request), target_id)
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.get("/bot-options")
|
||||
async def api_bot_options(request: Request):
|
||||
return {
|
||||
"bots": await get_bot_options(
|
||||
_user_id(request),
|
||||
bot_manager=getattr(request.app.state, "bot_manager", None),
|
||||
)
|
||||
}
|
||||
@@ -55,6 +55,11 @@ async def emit_to_user(user_id: str, data: dict):
|
||||
await sio.emit("events:chat", data, to=sid)
|
||||
|
||||
|
||||
def is_user_active(user_id: str) -> bool:
|
||||
"""Return True when the user has at least one connected app session."""
|
||||
return bool(_user_sids.get(user_id))
|
||||
|
||||
|
||||
def get_asgi_app(other_app):
|
||||
"""Wrap a FastAPI/Starlette app with the Socket.IO ASGI layer."""
|
||||
return socketio.ASGIApp(sio, other_asgi_app=other_app)
|
||||
|
||||
@@ -20,6 +20,7 @@ from dataclasses import dataclass, field
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_current_bot_manager: "BotManager | None" = None
|
||||
|
||||
# How often to edit the streaming message (seconds).
|
||||
STREAM_EDIT_INTERVAL = 2.0
|
||||
@@ -193,6 +194,10 @@ async def delete_bot_config(bot_id: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def get_current_bot_manager() -> "BotManager | None":
|
||||
return _current_bot_manager
|
||||
|
||||
|
||||
# ── Thread mapping via chat.meta ─────────────────────────────
|
||||
|
||||
|
||||
@@ -238,9 +243,11 @@ class BotManager:
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
global _current_bot_manager
|
||||
self._adapters: dict[str, BaseAdapter] = {} # bot_id → adapter
|
||||
self._tasks: dict[str, asyncio.Task] = {} # bot_id → polling task
|
||||
self._stream_tasks: dict[str, asyncio.Task] = {} # key → streaming task
|
||||
_current_bot_manager = self
|
||||
|
||||
# ── Lifecycle ──────────────────────────────────────────
|
||||
|
||||
@@ -317,6 +324,17 @@ class BotManager:
|
||||
def get_status(self) -> dict[str, bool]:
|
||||
return {bid: not t.done() for bid, t in self._tasks.items()}
|
||||
|
||||
async def send_notification(
|
||||
self,
|
||||
bot_id: str,
|
||||
destination_chat_id: str,
|
||||
text: str,
|
||||
) -> str | None:
|
||||
adapter = self._adapters.get(bot_id)
|
||||
if not adapter or not self.is_running(bot_id):
|
||||
raise RuntimeError("bot is not running")
|
||||
return await adapter.send(destination_chat_id, text)
|
||||
|
||||
# ── Adapter factory ────────────────────────────────────
|
||||
|
||||
def _create_adapter(self, bot: dict) -> BaseAdapter | None:
|
||||
|
||||
+29
-13
@@ -11,6 +11,7 @@ import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from cptr.events import EVENTS
|
||||
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
|
||||
from cptr.utils.context import resolve_compact_token_threshold, should_compact
|
||||
from cptr.utils.skills import discover_skills, load_skill, format_skill_content
|
||||
@@ -1182,6 +1183,27 @@ async def run_chat_task(
|
||||
workspace_name=ws_name,
|
||||
)
|
||||
|
||||
async def _notify_chat(event: str, message: str | None = None):
|
||||
try:
|
||||
from cptr.utils.notifications import EVENT_LABELS, send_chat_event
|
||||
|
||||
ws_name = workspace.rstrip("/").rsplit("/", 1)[-1] if workspace else ""
|
||||
body = message if message is not None else content
|
||||
await send_chat_event(
|
||||
user_id,
|
||||
event,
|
||||
{
|
||||
"title": EVENT_LABELS.get(event, "Chat"),
|
||||
"message": body[:300] if body else "",
|
||||
"chat_id": chat_id,
|
||||
"workspace": {"id": workspace, "name": ws_name} if workspace else None,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.debug(
|
||||
"[notifications] Error sending chat notification for %s", chat_id[:8], exc_info=True
|
||||
)
|
||||
|
||||
# Load existing state so continuations don't overwrite previous output
|
||||
msg = await ChatMessage.get_by_id(message_id)
|
||||
summary_message_id = message_id
|
||||
@@ -1495,6 +1517,7 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
await _notify_chat(EVENTS.CHAT_FINISHED.name)
|
||||
return
|
||||
|
||||
flushed_item = _flush_text()
|
||||
@@ -1503,6 +1526,7 @@ async def run_chat_task(
|
||||
await _save_message("agent stream ended", content=content, output=output_items, done=True)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
await _notify_chat(EVENTS.CHAT_FINISHED.name)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -1797,6 +1821,7 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
await _notify_chat(EVENTS.CHAT_FINISHED.name)
|
||||
return
|
||||
|
||||
# ── Process collected tool calls ────────────────────
|
||||
@@ -1853,7 +1878,7 @@ async def run_chat_task(
|
||||
)
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
await emit(output=item)
|
||||
await emit(output=item)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
return
|
||||
@@ -2013,6 +2038,7 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
await _notify_chat(EVENTS.CHAT_FINISHED.name)
|
||||
return
|
||||
|
||||
# Max iterations reached
|
||||
@@ -2025,6 +2051,7 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
await _notify_chat(EVENTS.CHAT_FAILED.name, "Max iterations reached.")
|
||||
|
||||
except asyncio.CancelledError:
|
||||
_flush_text()
|
||||
@@ -2066,6 +2093,7 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True, error=error_msg)
|
||||
await _notify_chat(EVENTS.CHAT_FAILED.name, error_msg)
|
||||
finally:
|
||||
# Guarantee the gateway SSE stream terminates. If emit()
|
||||
# already pushed a done/error event the sentinel is harmless
|
||||
@@ -2109,18 +2137,6 @@ async def run_chat_task(
|
||||
logger.debug(
|
||||
"[title] Error in title generation for chat %s", chat_id[:8], exc_info=True
|
||||
)
|
||||
# Fire webhook notification if configured
|
||||
try:
|
||||
webhook_url = await Config.get("notifications.webhook_url")
|
||||
if webhook_url:
|
||||
chat_obj = chat_obj or await Chat.get_by_id(chat_id)
|
||||
title = chat_obj.title if chat_obj else "Chat"
|
||||
preview = content[:300] if content else ""
|
||||
from cptr.utils.webhook import post_webhook
|
||||
|
||||
await post_webhook(webhook_url, title, preview)
|
||||
except Exception:
|
||||
logger.debug("[webhook] Error sending webhook for chat %s", chat_id[:8], exc_info=True)
|
||||
# Best-effort post-turn memory review. Runs detached and never competes
|
||||
# with queued user input processing.
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
"""User-owned chat notification targets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
import socket
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.events import CHAT_NOTIFICATION_EVENTS, EVENTS
|
||||
from cptr.models import UserStates
|
||||
from cptr.socket.main import is_user_active
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_EVENTS = {event.name for event in CHAT_NOTIFICATION_EVENTS}
|
||||
VALID_TYPES = {"webhook", "bot"}
|
||||
VALID_DELIVERY = {"away", "always"}
|
||||
|
||||
EVENT_LABELS = {event.name: event.label for event in CHAT_NOTIFICATION_EVENTS}
|
||||
|
||||
|
||||
class NotificationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _now() -> int:
|
||||
return int(time.time())
|
||||
|
||||
|
||||
async def _state(user_id: str) -> dict:
|
||||
return dict(await UserStates.get_data(user_id) or {})
|
||||
|
||||
|
||||
async def _save_state(user_id: str, data: dict) -> None:
|
||||
await UserStates.save_data(user_id, data)
|
||||
|
||||
|
||||
def _targets(data: dict) -> list[dict]:
|
||||
notifications = data.setdefault("notifications", {})
|
||||
targets = notifications.setdefault("targets", [])
|
||||
if not isinstance(targets, list):
|
||||
targets = []
|
||||
notifications["targets"] = targets
|
||||
return targets
|
||||
|
||||
|
||||
def _mask_url(url: str) -> str:
|
||||
parsed = urlparse(url)
|
||||
if not parsed.hostname:
|
||||
return "****"
|
||||
path = parsed.path or ""
|
||||
suffix = path[-4:] if len(path) > 4 else path
|
||||
return f"{parsed.scheme}://{parsed.hostname}/...{suffix}"
|
||||
|
||||
|
||||
def _public_target(target: dict) -> dict:
|
||||
public = {**target, "config": dict(target.get("config") or {})}
|
||||
if public.get("type") == "webhook":
|
||||
url = str(public["config"].pop("url", "") or "")
|
||||
public["config"]["url_masked"] = _mask_url(url) if url else ""
|
||||
return public
|
||||
|
||||
|
||||
def _validate_events(events) -> list[str]:
|
||||
if events is None:
|
||||
return []
|
||||
if not isinstance(events, list):
|
||||
raise NotificationError("events must be a list")
|
||||
cleaned = []
|
||||
for event in events:
|
||||
if event not in VALID_EVENTS:
|
||||
raise NotificationError(f"unsupported notification event: {event}")
|
||||
if event not in cleaned:
|
||||
cleaned.append(event)
|
||||
return cleaned
|
||||
|
||||
|
||||
def validate_webhook_url(url: str) -> str:
|
||||
url = (url or "").strip()
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise NotificationError("webhook URL must be http or https")
|
||||
|
||||
host = parsed.hostname.lower()
|
||||
if host in {"metadata.google.internal"} or host.endswith(".internal"):
|
||||
raise NotificationError("webhook URL host is not allowed")
|
||||
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80))
|
||||
except OSError as exc:
|
||||
raise NotificationError("webhook URL hostname could not be resolved") from exc
|
||||
|
||||
for info in infos:
|
||||
ip = ipaddress.ip_address(info[4][0])
|
||||
if (
|
||||
ip.is_loopback
|
||||
or ip.is_private
|
||||
or ip.is_link_local
|
||||
or ip.is_multicast
|
||||
or ip.is_reserved
|
||||
or ip.is_unspecified
|
||||
):
|
||||
raise NotificationError("webhook URL resolves to a blocked address")
|
||||
return url
|
||||
|
||||
|
||||
async def list_targets(user_id: str) -> list[dict]:
|
||||
data = await _state(user_id)
|
||||
visible = []
|
||||
for target in _targets(data):
|
||||
if target.get("type") == "bot":
|
||||
try:
|
||||
await _ensure_user_bot(user_id, str((target.get("config") or {}).get("bot_id") or ""))
|
||||
except NotificationError:
|
||||
continue
|
||||
visible.append(_public_target(target))
|
||||
return visible
|
||||
|
||||
|
||||
async def get_bot_options(user_id: str, bot_manager=None) -> list[dict]:
|
||||
from cptr.utils.bridge import get_bot_configs
|
||||
|
||||
status = bot_manager.get_status() if bot_manager else {}
|
||||
bots = []
|
||||
for bot in await get_bot_configs():
|
||||
if bot.get("user_id") != user_id:
|
||||
continue
|
||||
bots.append(
|
||||
{
|
||||
"id": bot.get("id"),
|
||||
"name": bot.get("name"),
|
||||
"platform": bot.get("platform"),
|
||||
"is_active": bool(bot.get("is_active", True)),
|
||||
"is_running": bool(status.get(bot.get("id"), False)),
|
||||
}
|
||||
)
|
||||
return bots
|
||||
|
||||
|
||||
async def _ensure_user_bot(user_id: str, bot_id: str) -> None:
|
||||
from cptr.utils.bridge import get_bot_by_id
|
||||
|
||||
bot = await get_bot_by_id(bot_id)
|
||||
if not bot or bot.get("user_id") != user_id:
|
||||
raise NotificationError("bot target is not available")
|
||||
|
||||
|
||||
def _validate_config(target_type: str, config: dict) -> dict:
|
||||
if not isinstance(config, dict):
|
||||
raise NotificationError("config must be an object")
|
||||
if target_type == "webhook":
|
||||
return {"url": validate_webhook_url(str(config.get("url") or ""))}
|
||||
if target_type == "bot":
|
||||
bot_id = str(config.get("bot_id") or "").strip()
|
||||
destination = str(config.get("destination_chat_id") or "").strip()
|
||||
if not bot_id:
|
||||
raise NotificationError("bot target requires bot_id")
|
||||
if not destination:
|
||||
raise NotificationError("bot target requires destination_chat_id")
|
||||
return {"bot_id": bot_id, "destination_chat_id": destination}
|
||||
raise NotificationError("unsupported notification target type")
|
||||
|
||||
|
||||
def _validate_target(payload: dict, existing: dict | None = None) -> dict:
|
||||
merged = {**(existing or {}), **payload}
|
||||
target_id = str(merged.get("id") or "").strip()
|
||||
target_type = str(merged.get("type") or "").strip()
|
||||
delivery = str(merged.get("delivery") or "away").strip()
|
||||
if not target_id:
|
||||
raise NotificationError("target id is required")
|
||||
if target_type not in VALID_TYPES:
|
||||
raise NotificationError("target type must be webhook or bot")
|
||||
if delivery not in VALID_DELIVERY:
|
||||
raise NotificationError("delivery must be away or always")
|
||||
config = _validate_config(target_type, dict(merged.get("config") or {}))
|
||||
now = _now()
|
||||
return {
|
||||
"id": target_id,
|
||||
"type": target_type,
|
||||
"enabled": bool(merged.get("enabled", True)),
|
||||
"events": _validate_events(merged.get("events", [])),
|
||||
"delivery": delivery,
|
||||
"config": config,
|
||||
"created_at": int(merged.get("created_at") or now),
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
|
||||
def _check_unique_id(targets: list[dict], new_id: str, old_id: str | None = None) -> None:
|
||||
lowered = new_id.lower()
|
||||
for target in targets:
|
||||
if target.get("id") != old_id and str(target.get("id", "")).lower() == lowered:
|
||||
raise NotificationError("notification target id already exists")
|
||||
|
||||
|
||||
async def create_target(user_id: str, payload: dict) -> dict:
|
||||
data = await _state(user_id)
|
||||
targets = _targets(data)
|
||||
target = _validate_target(payload)
|
||||
if target["type"] == "bot":
|
||||
await _ensure_user_bot(user_id, target["config"]["bot_id"])
|
||||
_check_unique_id(targets, target["id"])
|
||||
targets.append(target)
|
||||
await _save_state(user_id, data)
|
||||
return _public_target(target)
|
||||
|
||||
|
||||
async def update_target(user_id: str, target_id: str, payload: dict) -> dict:
|
||||
data = await _state(user_id)
|
||||
targets = _targets(data)
|
||||
for idx, current in enumerate(targets):
|
||||
if current.get("id") == target_id:
|
||||
target = _validate_target(payload, existing=current)
|
||||
if target["type"] == "bot":
|
||||
await _ensure_user_bot(user_id, target["config"]["bot_id"])
|
||||
_check_unique_id(targets, target["id"], target_id)
|
||||
targets[idx] = target
|
||||
await _save_state(user_id, data)
|
||||
return _public_target(target)
|
||||
raise NotificationError("notification target not found")
|
||||
|
||||
|
||||
async def delete_target(user_id: str, target_id: str) -> bool:
|
||||
data = await _state(user_id)
|
||||
targets = _targets(data)
|
||||
kept = [target for target in targets if target.get("id") != target_id]
|
||||
if len(kept) == len(targets):
|
||||
return False
|
||||
data["notifications"]["targets"] = kept
|
||||
await _save_state(user_id, data)
|
||||
return True
|
||||
|
||||
|
||||
async def _find_target(user_id: str, target_id: str) -> dict | None:
|
||||
data = await _state(user_id)
|
||||
needle = target_id.lower()
|
||||
for target in _targets(data):
|
||||
if str(target.get("id", "")).lower() == needle:
|
||||
return target
|
||||
return None
|
||||
|
||||
|
||||
def _webhook_payload(event: str, title: str, message: str, context: dict) -> dict:
|
||||
return {
|
||||
"event": event,
|
||||
"title": title,
|
||||
"message": message,
|
||||
"source": "computer",
|
||||
"chat_id": context.get("chat_id"),
|
||||
"workspace": context.get("workspace"),
|
||||
"created_at": _now(),
|
||||
}
|
||||
|
||||
|
||||
def _sink_payload(url: str, payload: dict) -> dict:
|
||||
title = payload["title"]
|
||||
message = payload["message"]
|
||||
if "hooks.slack.com" in url or "chat.googleapis.com" in url:
|
||||
return {"text": f"*{title}*\n{message}"}
|
||||
if "discord.com/api/webhooks" in url:
|
||||
content = f"**{title}**\n{message}"
|
||||
return {"content": content[:1997] + "..." if len(content) > 2000 else content}
|
||||
if "webhook.office.com" in url:
|
||||
return {
|
||||
"@type": "MessageCard",
|
||||
"@context": "http://schema.org/extensions",
|
||||
"themeColor": "0076D7",
|
||||
"summary": title,
|
||||
"sections": [
|
||||
{
|
||||
"activityTitle": title,
|
||||
"activitySubtitle": "Computer",
|
||||
"facts": [{"name": "Message", "value": message}],
|
||||
"markdown": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
async def _send_webhook(target: dict, event: str, title: str, message: str, context: dict) -> None:
|
||||
url = validate_webhook_url(str((target.get("config") or {}).get("url") or ""))
|
||||
payload = _webhook_payload(event, title, message, context)
|
||||
async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
|
||||
response = await client.post(url, json=_sink_payload(url, payload))
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
async def _send_bot(target: dict, title: str, message: str, context: dict) -> None:
|
||||
from cptr.utils.bridge import get_current_bot_manager
|
||||
|
||||
user_id = str(context.get("user_id") or "")
|
||||
if user_id:
|
||||
await _ensure_user_bot(user_id, str((target.get("config") or {}).get("bot_id") or ""))
|
||||
|
||||
manager = get_current_bot_manager()
|
||||
if not manager:
|
||||
raise NotificationError("bot manager is not running")
|
||||
workspace = (context.get("workspace") or {}).get("name") if isinstance(context.get("workspace"), dict) else ""
|
||||
header = f"[{title}] {workspace}".strip()
|
||||
text = f"{header}\n\n{message}".strip()
|
||||
config = target.get("config") or {}
|
||||
await manager.send_notification(config["bot_id"], config["destination_chat_id"], text)
|
||||
|
||||
|
||||
async def _deliver(target: dict, event: str, title: str, message: str, context: dict) -> None:
|
||||
if target.get("type") == "webhook":
|
||||
await _send_webhook(target, event, title, message, context)
|
||||
elif target.get("type") == "bot":
|
||||
await _send_bot(target, title, message, context)
|
||||
else:
|
||||
raise NotificationError("unsupported notification target type")
|
||||
|
||||
|
||||
async def test_target(user_id: str, target_id: str) -> dict:
|
||||
target = await _find_target(user_id, target_id)
|
||||
if not target:
|
||||
raise NotificationError("notification target not found")
|
||||
await _deliver(
|
||||
target,
|
||||
EVENTS.NOTIFICATION_TEST.name,
|
||||
EVENTS.NOTIFICATION_TEST.label,
|
||||
"Computer can reach this target.",
|
||||
{"chat_id": None, "workspace": None, "user_id": user_id},
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
async def send_chat_event(user_id: str, event: str, context: dict) -> None:
|
||||
if event not in VALID_EVENTS:
|
||||
return
|
||||
data = await _state(user_id)
|
||||
active = is_user_active(user_id)
|
||||
for target in list(_targets(data)):
|
||||
if not target.get("enabled", True):
|
||||
continue
|
||||
if event not in target.get("events", []):
|
||||
continue
|
||||
if target.get("delivery", "away") == "away" and active:
|
||||
continue
|
||||
try:
|
||||
await _deliver(
|
||||
target,
|
||||
event,
|
||||
str(context.get("title") or EVENT_LABELS[event]),
|
||||
str(context.get("message") or ""),
|
||||
{**context, "user_id": user_id},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"[notifications] failed to deliver %s to %s",
|
||||
event,
|
||||
target.get("id"),
|
||||
)
|
||||
|
||||
|
||||
async def notify_target(
|
||||
user_id: str,
|
||||
target_id: str,
|
||||
message: str,
|
||||
title: str | None = None,
|
||||
) -> str:
|
||||
target = await _find_target(user_id, target_id)
|
||||
if not target:
|
||||
raise NotificationError(f'notification target "{target_id}" was not found')
|
||||
if not target.get("enabled", True):
|
||||
raise NotificationError(f'notification target "{target_id}" is disabled')
|
||||
await _deliver(
|
||||
target,
|
||||
EVENTS.NOTIFICATION_MANUAL.name,
|
||||
title or "Notification",
|
||||
message,
|
||||
{"chat_id": None, "workspace": None, "user_id": user_id},
|
||||
)
|
||||
return f"Notification sent to {target.get('id')}."
|
||||
@@ -1887,6 +1887,26 @@ async def search_chats(
|
||||
)
|
||||
|
||||
|
||||
async def notify(target: str, message: str, title: str = "", *, __context__: dict) -> str:
|
||||
"""Send a notification to a named user notification target.
|
||||
|
||||
:param target: Notification target name from Settings > Notifications.
|
||||
:param message: Message body to send.
|
||||
:param title: Optional notification title.
|
||||
"""
|
||||
user_id = __context__.get("user_id")
|
||||
if not user_id:
|
||||
return "Error: authentication required."
|
||||
try:
|
||||
from cptr.utils.notifications import NotificationError, notify_target
|
||||
|
||||
return await notify_target(user_id, target, message, title or None)
|
||||
except NotificationError as exc:
|
||||
return f"Error: {exc}"
|
||||
except Exception as exc:
|
||||
return f"Error: failed to send notification: {exc}"
|
||||
|
||||
|
||||
# ── Registry ────────────────────────────────────────────────
|
||||
|
||||
TOOLS: dict[str, dict] = {
|
||||
@@ -1912,6 +1932,7 @@ TOOLS: dict[str, dict] = {
|
||||
"update_automation": {"fn": update_automation, "auto": False},
|
||||
"toggle_automation": {"fn": toggle_automation, "auto": False},
|
||||
"delete_automation": {"fn": delete_automation, "auto": False},
|
||||
"notify": {"fn": notify, "auto": False},
|
||||
"image_generate": {"fn": image_generate, "auto": False},
|
||||
"update_memory": {"fn": update_memory, "auto": True},
|
||||
}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
"""Webhook notifications: POST to Slack, Discord, Teams, or generic JSON.
|
||||
|
||||
Adapted from open-webui's webhook.py, using httpx instead of aiohttp.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def post_webhook(url: str, title: str, message: str) -> bool:
|
||||
"""Send a notification to a webhook URL.
|
||||
|
||||
Auto-detects Slack, Discord, Teams, and Google Chat webhook URLs
|
||||
and formats the payload accordingly. Falls back to generic JSON.
|
||||
|
||||
Returns True on success, False on failure (never raises).
|
||||
"""
|
||||
try:
|
||||
payload: dict = {}
|
||||
|
||||
# Slack and Google Chat
|
||||
if "hooks.slack.com" in url or "chat.googleapis.com" in url:
|
||||
payload["text"] = f"*{title}*\n{message}"
|
||||
|
||||
# Discord (2000 char limit)
|
||||
elif "discord.com/api/webhooks" in url:
|
||||
content = f"**{title}**\n{message}"
|
||||
if len(content) > 2000:
|
||||
content = content[:1980] + "... (truncated)"
|
||||
payload["content"] = content
|
||||
|
||||
# Microsoft Teams
|
||||
elif "webhook.office.com" in url:
|
||||
payload = {
|
||||
"@type": "MessageCard",
|
||||
"@context": "http://schema.org/extensions",
|
||||
"themeColor": "0076D7",
|
||||
"summary": title,
|
||||
"sections": [
|
||||
{
|
||||
"activityTitle": title,
|
||||
"activitySubtitle": "cptr",
|
||||
"facts": [{"name": "Message", "value": message}],
|
||||
"markdown": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
# Generic JSON
|
||||
else:
|
||||
payload = {
|
||||
"title": title,
|
||||
"message": message,
|
||||
"source": "cptr",
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(url, json=payload)
|
||||
r.raise_for_status()
|
||||
|
||||
logger.info("[webhook] Sent notification to %s", url[:50])
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception("[webhook] Failed to send notification to %s", url[:50])
|
||||
return False
|
||||
""", "Description": "Adapted from open-webui's webhook.py — uses httpx, supports Slack/Discord/Teams/generic JSON", "IsArtifact": false, "Overwrite": false, "TargetFile": "/Users/tim/Documents/workspace/computer/cptr/utils/webhook.py
|
||||
Reference in New Issue
Block a user