mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
refac
This commit is contained in:
1 parent
d99169d94e
commit
df343ee8de
7 files changed
+401
-15
No files matched your search
@@ -18,6 +18,7 @@
|
||||
} from '$lib/apis/files';
|
||||
import { fileIconName } from '$lib/utils/fileIcon';
|
||||
import Icon from './Icon.svelte';
|
||||
import Spinner from './common/Spinner.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
onClick?: () => void;
|
||||
onclose?: () => void;
|
||||
title?: string;
|
||||
content?: string;
|
||||
}
|
||||
|
||||
let { onClick = () => {}, onclose = () => {}, title = '', content = '' }: Props = $props();
|
||||
|
||||
let closeButtonEl: HTMLButtonElement;
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
let moved = false;
|
||||
const DRAG_THRESHOLD_PX = 6;
|
||||
|
||||
// ── Sound ──────────────────────────────────────────────────
|
||||
onMount(() => {
|
||||
if (!navigator.userActivation?.hasBeenActive) return;
|
||||
|
||||
const soundEnabled = localStorage.getItem('notificationSound') !== 'false';
|
||||
if (soundEnabled) {
|
||||
const audio = new Audio('/audio/notification.mp3');
|
||||
audio.play().catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
// ── Interaction ────────────────────────────────────────────
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
startX = e.clientX;
|
||||
startY = e.clientY;
|
||||
moved = false;
|
||||
(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (moved) return;
|
||||
const dx = e.clientX - startX;
|
||||
const dy = e.clientY - startY;
|
||||
if (dx * dx + dy * dy > DRAG_THRESHOLD_PX * DRAG_THRESHOLD_PX) {
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
|
||||
function onPointerUp(e: PointerEvent) {
|
||||
(e.currentTarget as HTMLElement).releasePointerCapture?.(e.pointerId);
|
||||
if (
|
||||
closeButtonEl &&
|
||||
(e.target === closeButtonEl || closeButtonEl.contains(e.target as Node))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!moved) {
|
||||
onClick();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
class="notification-toast group"
|
||||
onpointerdown={onPointerDown}
|
||||
onpointermove={onPointerMove}
|
||||
onpointerup={onPointerUp}
|
||||
onpointercancel={() => (moved = true)}
|
||||
>
|
||||
<!-- Close button -->
|
||||
<button
|
||||
bind:this={closeButtonEl}
|
||||
class="close-btn"
|
||||
aria-label="Dismiss notification"
|
||||
onclick={(e) => { e.stopPropagation(); onclose(); }}
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
|
||||
<path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Icon -->
|
||||
<div class="icon-wrap">
|
||||
<img src="/favicon.png" alt="cptr" class="w-5 h-5 rounded-full" />
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="content">
|
||||
{#if title}
|
||||
<div class="title">{title}</div>
|
||||
{/if}
|
||||
{#if content}
|
||||
<div class="body">{content}</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.notification-toast {
|
||||
position: relative;
|
||||
display: flex;
|
||||
gap: 0.625rem;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
min-width: var(--width, 300px);
|
||||
background: #111;
|
||||
color: #e0e0e0;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
border-radius: 1rem;
|
||||
padding: 0.75rem 1rem;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
:global(.dark) .notification-toast {
|
||||
background: #1a1a1a;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
position: absolute;
|
||||
top: -0.125rem;
|
||||
left: -0.125rem;
|
||||
padding: 0.125rem;
|
||||
border-radius: 9999px;
|
||||
opacity: 0;
|
||||
background: #222;
|
||||
color: #888;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.15s;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.group:hover .close-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
background: #333;
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.icon-wrap {
|
||||
flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
transform: translateY(-0.125rem);
|
||||
}
|
||||
|
||||
.content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.125rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.body {
|
||||
font-size: 12px;
|
||||
color: #aaa;
|
||||
font-weight: 400;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
@@ -4,10 +4,55 @@
|
||||
import { theme, streamingBehavior } from '$lib/stores';
|
||||
import type { Theme, 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 { onMount } from 'svelte';
|
||||
|
||||
function setTheme(v: Theme) {
|
||||
theme.set(v);
|
||||
}
|
||||
|
||||
// ── Webhook URL ─────────────────────────────────────────────
|
||||
let webhookUrl = $state('');
|
||||
let webhookLoading = $state(false);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const data = await fetchJSON<{ config: Record<string, any> }>('/api/admin/config/notifications');
|
||||
webhookUrl = data.config?.['notifications.webhook_url'] || '';
|
||||
} catch {}
|
||||
});
|
||||
|
||||
async function saveWebhookUrl() {
|
||||
webhookLoading = true;
|
||||
try {
|
||||
await fetchJSON('/api/admin/config', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ config: { 'notifications.webhook_url': webhookUrl.trim() || null } })
|
||||
});
|
||||
toast.success('Webhook URL saved');
|
||||
} catch {
|
||||
toast.error('Failed to save webhook URL');
|
||||
} finally {
|
||||
webhookLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleNotifications() {
|
||||
if (!$notificationsEnabled) {
|
||||
// Enabling: request permission
|
||||
if ('Notification' in window) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission === 'granted') {
|
||||
notificationsEnabled.set(true);
|
||||
} else {
|
||||
toast.error('Browser notification permission denied');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
notificationsEnabled.set(false);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
@@ -40,6 +85,74 @@
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<!-- Notifications -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">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">Browser notifications</span>
|
||||
<button
|
||||
class="relative w-8 h-[18px] rounded-full transition-colors duration-150
|
||||
{$notificationsEnabled ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-700'}"
|
||||
onclick={toggleNotifications}
|
||||
role="switch"
|
||||
aria-checked={$notificationsEnabled}
|
||||
>
|
||||
<span
|
||||
class="absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white shadow transition-transform duration-150
|
||||
{$notificationsEnabled ? 'translate-x-[14px]' : ''}"
|
||||
></span>
|
||||
</button>
|
||||
</label>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
Show OS-level notifications when a task completes and the tab is not focused.
|
||||
</p>
|
||||
|
||||
<!-- Sound toggle -->
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">Notification sound</span>
|
||||
<button
|
||||
class="relative w-8 h-[18px] rounded-full transition-colors duration-150
|
||||
{$notificationSound ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-700'}"
|
||||
onclick={() => notificationSound.update((v) => !v)}
|
||||
role="switch"
|
||||
aria-checked={$notificationSound}
|
||||
>
|
||||
<span
|
||||
class="absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white shadow transition-transform duration-150
|
||||
{$notificationSound ? 'translate-x-[14px]' : ''}"
|
||||
></span>
|
||||
</button>
|
||||
</label>
|
||||
|
||||
<!-- Webhook URL -->
|
||||
<div class="mt-1">
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="webhook-url">
|
||||
Webhook URL
|
||||
</label>
|
||||
<div class="flex gap-1.5 mt-1">
|
||||
<input
|
||||
id="webhook-url"
|
||||
type="url"
|
||||
bind:value={webhookUrl}
|
||||
placeholder="https://hooks.slack.com/services/..."
|
||||
class="flex-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"
|
||||
/>
|
||||
<button
|
||||
class="h-7 px-2.5 rounded-lg text-xs bg-gray-200/50 dark:bg-white/8 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors disabled:opacity-50"
|
||||
onclick={saveWebhookUrl}
|
||||
disabled={webhookLoading}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
|
||||
Supports Slack, Discord, Teams, and generic JSON webhooks.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Message queue</h3>
|
||||
<div class="flex gap-1">
|
||||
{#each [{ value: 'queue' as StreamingBehavior, label: 'Queue' }, { value: 'interrupt' as StreamingBehavior, label: 'Interrupt' }] as opt}
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
* Chat state: tracks whether chat is available (at least one connection configured).
|
||||
*/
|
||||
import { writable, get } from 'svelte/store';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { fetchJSON } from '$lib/apis';
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import { activeTab, openChatTab } from '$lib/stores';
|
||||
|
||||
export const chatEnabled = writable<boolean>(false);
|
||||
|
||||
@@ -27,10 +29,27 @@ export function unregisterStreamingChat(chatId: string) {
|
||||
/**
|
||||
* Bind a global socket listener that clears streamingChatTabs when a
|
||||
* chat's "done" event arrives -- even if the ChatPanel is not mounted.
|
||||
* Also fires browser notifications and in-app toasts.
|
||||
* Called once from the app layout.
|
||||
*/
|
||||
let globalListenerBound = false;
|
||||
|
||||
/** Whether browser notifications are enabled (persisted to localStorage). */
|
||||
export const notificationsEnabled = writable<boolean>(
|
||||
typeof localStorage !== 'undefined' ? localStorage.getItem('notificationsEnabled') === 'true' : false
|
||||
);
|
||||
notificationsEnabled.subscribe((v) => {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem('notificationsEnabled', String(v));
|
||||
});
|
||||
|
||||
/** Whether notification sound is enabled (persisted to localStorage). */
|
||||
export const notificationSound = writable<boolean>(
|
||||
typeof localStorage !== 'undefined' ? localStorage.getItem('notificationSound') !== 'false' : true
|
||||
);
|
||||
notificationSound.subscribe((v) => {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem('notificationSound', String(v));
|
||||
});
|
||||
|
||||
export function bindGlobalChatListener() {
|
||||
if (globalListenerBound) return;
|
||||
|
||||
@@ -41,17 +60,72 @@ export function bindGlobalChatListener() {
|
||||
return;
|
||||
}
|
||||
|
||||
socket.on('events:chat', (data: { chat_id: string; done?: boolean }) => {
|
||||
if (!data.done) return;
|
||||
const tabId = chatToTab.get(data.chat_id);
|
||||
if (tabId) {
|
||||
streamingChatTabs.update((s) => {
|
||||
const next = new Set(s);
|
||||
next.delete(tabId);
|
||||
return next;
|
||||
socket.on(
|
||||
'events:chat',
|
||||
(data: {
|
||||
chat_id: string;
|
||||
done?: boolean;
|
||||
title?: string;
|
||||
content?: string;
|
||||
workspace?: string;
|
||||
}) => {
|
||||
if (!data.done) return;
|
||||
|
||||
// Clear streaming indicator for the tab
|
||||
const tabId = chatToTab.get(data.chat_id);
|
||||
if (tabId) {
|
||||
streamingChatTabs.update((s) => {
|
||||
const next = new Set(s);
|
||||
next.delete(tabId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Notifications ──────────────────────────────────
|
||||
// Skip if user is actively viewing this chat
|
||||
const currentTab = get(activeTab);
|
||||
const isViewingThisChat =
|
||||
!document.hidden &&
|
||||
currentTab?.type === 'chat' &&
|
||||
currentTab?.path === data.chat_id;
|
||||
|
||||
if (isViewingThisChat) return;
|
||||
|
||||
const wsLabel = data.workspace ? `[${data.workspace}] ` : '';
|
||||
const title = `${wsLabel}${data.title || 'Chat'}`;
|
||||
const body = data.content || '';
|
||||
|
||||
// In-app toast
|
||||
import('$lib/components/NotificationToast.svelte').then((mod) => {
|
||||
const chatId = data.chat_id;
|
||||
const toastId = toast.custom(mod.default, {
|
||||
componentProps: {
|
||||
title,
|
||||
content: body,
|
||||
onClick: () => {
|
||||
openChatTab(chatId);
|
||||
toast.dismiss(toastId);
|
||||
},
|
||||
onclose: () => {
|
||||
toast.dismiss(toastId);
|
||||
}
|
||||
},
|
||||
duration: 10000,
|
||||
unstyled: true
|
||||
});
|
||||
});
|
||||
|
||||
// Browser notification (only when tab is hidden)
|
||||
if (document.hidden && get(notificationsEnabled)) {
|
||||
try {
|
||||
new Notification(`${title} • cptr`, {
|
||||
body: body.slice(0, 200),
|
||||
icon: '/favicon.png'
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
globalListenerBound = true;
|
||||
};
|
||||
|
||||
@@ -283,7 +283,7 @@
|
||||
{/if}
|
||||
|
||||
<Toaster
|
||||
position="bottom-center"
|
||||
position="top-right"
|
||||
toastOptions={{
|
||||
style:
|
||||
'font-size: 12px; font-family: var(--font-sans); background: #111; color: #e0e0e0; border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;'
|
||||
|
||||
Binary file not shown.
+30
-5
@@ -571,6 +571,17 @@ async def run_chat_task(
|
||||
"""Stream an output delta to the user."""
|
||||
await emit_to_user(user_id, {"chat_id": chat_id, "message_id": message_id, **data})
|
||||
|
||||
async def _emit_done():
|
||||
"""Emit done=True enriched with chat title and content preview."""
|
||||
try:
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
title = chat_obj.title if chat_obj else "Chat"
|
||||
except Exception:
|
||||
title = "Chat"
|
||||
preview = content[:300] if content else ""
|
||||
ws_name = workspace.rstrip("/").rsplit("/", 1)[-1] if workspace else ""
|
||||
await emit(done=True, title=title, content=preview, workspace=ws_name)
|
||||
|
||||
# Load existing state so continuations don't overwrite previous output
|
||||
msg = await ChatMessage.get_by_id(message_id)
|
||||
content = (msg.content or "") if msg else ""
|
||||
@@ -769,7 +780,7 @@ async def run_chat_task(
|
||||
done=True,
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
await _emit_done()
|
||||
return
|
||||
|
||||
elif event["type"] == "done":
|
||||
@@ -794,7 +805,7 @@ async def run_chat_task(
|
||||
done=True,
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
await _emit_done()
|
||||
return
|
||||
|
||||
# Max iterations reached
|
||||
@@ -806,13 +817,13 @@ async def run_chat_task(
|
||||
meta={"error": "max iterations reached"},
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
await _emit_done()
|
||||
|
||||
except asyncio.CancelledError:
|
||||
_flush_text()
|
||||
await ChatMessage.update(message_id, content=content, output=output_items, done=True)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
await _emit_done()
|
||||
except Exception as e:
|
||||
logger.exception(f"Chat task error for message {message_id}")
|
||||
_flush_text()
|
||||
@@ -824,7 +835,7 @@ async def run_chat_task(
|
||||
meta={"error": str(e)},
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
await _emit_done()
|
||||
finally:
|
||||
_tasks.pop(message_id, None)
|
||||
_task_state.pop(message_id, None)
|
||||
@@ -858,6 +869,20 @@ 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
|
||||
)
|
||||
# Process any queued follow-up messages
|
||||
try:
|
||||
await _process_queue(chat_id, user_id, workspace)
|
||||
|
||||
Reference in new issue
Block a user