Merge pull request #23 from open-webui/main

0.2.0.
This commit is contained in:
Tim Baek
2026-06-09 13:17:35 +01:00
committed by GitHub
Unverified
67 changed files with 3530 additions and 275 deletions
+14
View File
@@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.2.0] - 2026-06-09
### Added
- ⏱️ **Automations.** Schedule recurring tasks that run on a timer. Each automation creates a real chat with full tool access, so they can do anything you'd do manually. Manage them from the new `/automations` page or ask the AI to create one.
- 🔔 **Task completion notifications.** Get a browser notification (with optional sound) when a background task finishes. Toggle in Settings > General.
- 🪝 **Webhook notifications.** Send alerts to Slack, Discord, Teams, or any webhook URL when tasks complete. Configure in Settings > General.
- 💬 **Sidebar chat history.** Each workspace now shows its recent chats directly in the sidebar. Click to reopen, updates live as new chats come in.
- 🗃️ **Config file sync.** Settings now persist to `config.toml` on disk, so your configuration survives across reinstalls and can be hand-edited.
### Changed
- 🎨 **Improved artifact cards.** File previews in chat now show a file icon and cleaner styling.
## [0.1.9] - 2026-06-07
### Fixed
+8
View File
@@ -8,6 +8,7 @@ from fastapi.staticfiles import StaticFiles
from cptr.routers import (
admin_router,
auth_router,
automations_router,
chat_router,
events_router,
files_router,
@@ -38,6 +39,12 @@ async def startup():
await reconcile_chat_state()
# Start automation scheduler
import asyncio
from cptr.utils.automations import scheduler_worker_loop
asyncio.create_task(scheduler_worker_loop(app))
# Auth middleware
@app.middleware("http")
@@ -169,6 +176,7 @@ async def get_config():
# Routers
app.include_router(admin_router)
app.include_router(auth_router)
app.include_router(automations_router)
app.include_router(chat_router)
app.include_router(events_router)
app.include_router(files_router)
+4
View File
@@ -32,3 +32,7 @@ CHAT_TOOL_COMMAND_MAX_CHARS = int(os.environ.get("CHAT_TOOL_COMMAND_MAX_CHARS",
STREAM_CONNECT_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_CONNECT_TIMEOUT", "30"))
STREAM_READ_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_READ_TIMEOUT", "300"))
STREAM_WRITE_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_WRITE_TIMEOUT", "600"))
# ── Automation scheduler ────────────────────────────────────
AUTOMATION_POLL_INTERVAL = int(os.environ.get("AUTOMATION_POLL_INTERVAL", "10"))
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.1.9",
"version": "0.2.0",
"type": "module",
"scripts": {
"dev": "vite dev",
+93
View File
@@ -0,0 +1,93 @@
import { fetchJSON, jsonBody } from './index';
export type AutomationData = {
id: string;
user_id: string;
name: string;
prompt: string;
model_id: string;
workspace: string;
rrule: string;
is_active: boolean;
last_run_at: number | null;
next_run_at: number | null;
meta: Record<string, any> | null;
created_at: number;
updated_at: number;
last_run: AutomationRunData | null;
next_runs: number[] | null;
has_webhook: boolean;
webhook_url: string | null;
};
export type AutomationRunData = {
id: string;
automation_id: string;
chat_id: string | null;
status: string;
error: string | null;
created_at: number;
};
export type AutomationForm = {
name: string;
prompt: string;
model_id: string;
workspace: string;
rrule: string;
is_active?: boolean;
};
export async function getAutomations(
workspace?: string,
query?: string,
status?: string,
page: number = 1
): Promise<{ items: AutomationData[]; total: number }> {
const params = new URLSearchParams();
if (workspace) params.set('workspace', workspace);
if (query) params.set('query', query);
if (status && status !== 'all') params.set('status', status);
if (page > 1) params.set('page', page.toString());
return fetchJSON(`/api/automations?${params}`);
}
export async function createAutomation(form: AutomationForm): Promise<AutomationData> {
return fetchJSON('/api/automations', jsonBody(form));
}
export async function getAutomationById(id: string): Promise<AutomationData> {
return fetchJSON(`/api/automations/${id}`);
}
export async function updateAutomation(id: string, form: AutomationForm): Promise<AutomationData> {
return fetchJSON(`/api/automations/${id}`, jsonBody(form));
}
export async function toggleAutomation(id: string): Promise<AutomationData> {
return fetchJSON(`/api/automations/${id}/toggle`, { method: 'POST' });
}
export async function runAutomation(id: string): Promise<AutomationData> {
return fetchJSON(`/api/automations/${id}/run`, { method: 'POST' });
}
export async function deleteAutomation(id: string): Promise<{ ok: boolean }> {
return fetchJSON(`/api/automations/${id}`, { method: 'DELETE' });
}
export async function getAutomationRuns(
id: string,
skip: number = 0,
limit: number = 50
): Promise<AutomationRunData[]> {
return fetchJSON(`/api/automations/${id}/runs?skip=${skip}&limit=${limit}`);
}
export async function generateWebhook(id: string): Promise<AutomationData> {
return fetchJSON(`/api/automations/${id}/webhook`, { method: 'POST' });
}
export async function deleteWebhook(id: string): Promise<AutomationData> {
return fetchJSON(`/api/automations/${id}/webhook`, { method: 'DELETE' });
}
+1
View File
@@ -25,6 +25,7 @@ export interface ChatInfo {
current_message_id: string | null;
created_at: number;
updated_at: number;
is_active?: boolean;
}
export interface ChatDetail {
@@ -7,6 +7,7 @@
import { listConnections, updateConnection, type Connection } from '$lib/apis/admin';
import { refreshChatState } from '$lib/stores/chat';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
let connections = $state<Connection[]>([]);
let loading = $state(true);
@@ -66,9 +67,7 @@
{#if loading}
<div class="flex justify-center py-8">
<div
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={16} />
</div>
{:else}
<div>
@@ -5,6 +5,7 @@
import { ApiError } from '$lib/apis';
import { refreshChatState } from '$lib/stores/chat';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
onclose: () => void;
@@ -171,9 +172,7 @@
class="text-[13px] 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"
>
{#if creating}
<div
class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={14} />
{:else}
{$t('connections.add')} →
{/if}
@@ -4,6 +4,7 @@
import { createUser as apiCreateUser } from '$lib/apis/admin';
import { ApiError } from '$lib/apis';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
onclose: () => void;
@@ -96,9 +97,7 @@
class="text-[13px] 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"
>
{#if creating}
<div
class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={14} />
{:else}
{$t('admin.create')}
{/if}
@@ -10,6 +10,7 @@
import { ApiError } from '$lib/apis';
import { refreshChatState } from '$lib/stores/chat';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
connection: Connection;
@@ -212,9 +213,7 @@
onclick={handleVerify}
>
{#if verifying}
<div
class="w-3 h-3 border border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={12} />
{:else}
{$t('connections.verify') || 'Verify'}
{/if}
@@ -226,9 +225,7 @@
class="text-[13px] 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"
>
{#if saving}
<div
class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={14} />
{:else}
{$t('settings.save') || 'Save'} →
{/if}
@@ -3,7 +3,8 @@
import { onMount } from 'svelte';
import { getAdminConfig, updateConfig as apiUpdateConfig } from '$lib/apis/admin';
import { t } from '$lib/i18n';
import ToggleSwitch from '$lib/components/ToggleSwitch.svelte';
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
let config = $state<Record<string, any>>({});
let loading = $state(true);
@@ -54,9 +55,7 @@
{#if loading}
<div class="flex justify-center py-8">
<div
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={16} />
</div>
{:else}
<!-- Auth settings -->
@@ -7,6 +7,7 @@
import { listUsers } from '$lib/apis/admin';
import { session } from '$lib/session';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface User {
user_id: string;
@@ -66,9 +67,7 @@
{#if loading}
<div class="flex justify-center py-8">
<div
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={16} />
</div>
{:else}
<div>
@@ -3,6 +3,7 @@
import { login, setup, signup } from '$lib/apis/auth';
import { ApiError } from '$lib/apis';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
mode: 'password' | 'pam';
@@ -111,9 +112,7 @@
disabled:opacity-30 disabled:pointer-events-none mt-2"
>
{#if loading}
<div
class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={14} />
{:else}
{isSetup
? $t('auth.createAccountBtn')
@@ -3,6 +3,7 @@
import Modal from './Modal.svelte';
import Icon from './Icon.svelte';
import { appVersion, lastSeenVersion, showChangelog } from '$lib/stores';
import Spinner from '$lib/components/common/Spinner.svelte';
type ChangelogEntry = { title: string; content: string; raw: string };
type VersionData = { date: string; [section: string]: string | ChangelogEntry[] };
@@ -147,9 +148,7 @@
</div>
{:else}
<div class="flex flex-col items-center justify-center py-16 gap-3">
<div
class="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400"
></div>
<Spinner size={16} />
<span class="text-[11px] text-gray-400 dark:text-gray-600">Loading release notes...</span>
</div>
{/if}
@@ -5,6 +5,7 @@
import { listDir } from '$lib/apis/files';
import Icon from './Icon.svelte';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
onclose: () => void;
@@ -317,9 +318,7 @@
placeholder={$t('directory.typePath')}
/>
{#if pathValid === 'checking'}
<div
class="w-3 h-3 border-[1.5px] border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin shrink-0"
></div>
<Spinner size={12} />
{:else if pathValid === 'valid'}
<span class="text-green-500 shrink-0 flex"><Icon name="check" size={12} /></span>
{:else if pathValid === 'invalid'}
@@ -384,9 +383,7 @@
<div bind:this={listEl} class="flex-1 overflow-y-auto p-1 min-h-0">
{#if loading}
<div class="flex items-center justify-center py-8">
<div
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={16} />
</div>
{:else if error}
<div class="flex flex-col items-center justify-center gap-2 py-8 text-center">
@@ -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';
@@ -761,9 +762,7 @@
{#if loading && initialLoad}
<div class="flex items-center justify-center py-12">
<div
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={16} />
</div>
{:else if error}
<div class="flex flex-col items-center justify-center py-12 gap-2">
@@ -18,6 +18,7 @@
import HtmlPreview from './preview/HtmlPreview.svelte';
import SvgPreview from './preview/SvgPreview.svelte';
import OfficePreview from './preview/OfficePreview.svelte';
import Spinner from './common/Spinner.svelte';
import { EditorState } from '@codemirror/state';
import {
EditorView,
@@ -173,7 +174,7 @@
if (type === 'added')
return 'bg-green-100 border-l-[3px] border-l-green-500 dark:bg-green-500/15 dark:border-l-green-400';
if (type === 'removed')
return 'bg-red-100 border-l-[3px] border-l-red-400 dark:bg-red-500/15 dark:border-l-red-400';
return 'bg-red-100 diff-gutter-removed dark:bg-red-500/15';
return '';
}
@@ -733,7 +734,7 @@
<div class="editor-area">
{#if loading}
<div class="state"><div class="spinner"></div></div>
<div class="state"><Spinner size={20} /></div>
{:else if error}
<div class="state error">{error}</div>
@@ -799,7 +800,7 @@
{:else if diffMode}
<!-- Diff view -->
{#if diffLoading}
<div class="state"><div class="spinner"></div></div>
<div class="state"><Spinner size={20} /></div>
{:else if diffFiles.length === 0}
<div class="state">
<p class="state-title">No changes</p>
@@ -1035,20 +1036,7 @@
color: var(--color-gray-500);
}
.spinner {
width: 20px;
height: 20px;
border: 2px solid var(--color-gray-700);
border-top-color: var(--color-gray-400);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* ── Diff view ────────────────────────────────────────── */
@@ -1132,4 +1120,16 @@
:global(.dark) .diff-ctx .diff-prefix {
color: var(--color-gray-600);
}
.diff-gutter-removed {
border-left: 3px solid transparent;
border-image: repeating-linear-gradient(
-45deg,
#ef4444 0,
#ef4444 1px,
transparent 1px,
transparent 3px
)
3;
}
</style>
@@ -19,6 +19,7 @@
import DropdownMenu from './DropdownMenu.svelte';
import { tooltip } from '$lib/tooltip';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
type GitFile = { path: string; status: string; staged: boolean };
type DiffHunk = { header: string; lines: { type: string; content: string }[] };
@@ -527,9 +528,7 @@
{/each}
{:else}
<div class="flex items-center justify-center h-10">
<div
class="w-3.5 h-3.5 border border-gray-300 dark:border-gray-600 border-t-gray-600 dark:border-t-gray-300 rounded-full animate-spin"
></div>
<Spinner size={14} />
</div>
{/if}
</div>
@@ -5,6 +5,7 @@
import { tooltip } from '$lib/tooltip';
import Icon from './Icon.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
type DiffLine = { type: 'added' | 'removed' | 'context'; content: string };
@@ -259,9 +260,7 @@
>
{#if loading && !gitStatus}
<div class="flex h-full items-center justify-center">
<div
class="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400"
></div>
<Spinner size={16} />
</div>
{:else if error && !gitStatus}
<div class="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
@@ -23,6 +23,7 @@
import { chatEnabled, streamingChatTabs } from '$lib/stores/chat';
import { keybindings, formatChord } from '$lib/stores/keybindings';
import Icon from './Icon.svelte';
import Spinner from './common/Spinner.svelte';
import DropdownMenu from './DropdownMenu.svelte';
import { tooltip } from '$lib/tooltip';
import { t } from '$lib/i18n';
@@ -289,7 +290,7 @@
oncontextmenu={(e) => handleContextMenu(e, tab)}
>
{#if tab.type === 'chat' && $streamingChatTabs.has(tab.id)}
<span class="tab-spinner" style="width: 14px; height: 14px;"></span>
<Spinner size={14} />
{:else}
<Icon name={tabIconName(tab)} size={14} />
{/if}
@@ -401,19 +402,5 @@
display: none;
}
.tab-spinner {
display: inline-block;
border: 2px solid currentColor;
border-top-color: transparent;
border-radius: 50%;
animation: tab-spin 0.8s linear infinite;
opacity: 0.7;
flex-shrink: 0;
}
@keyframes tab-spin {
to {
transform: rotate(360deg);
}
}
</style>
@@ -305,5 +305,10 @@
<path d="M7 14H17C17 14 20 13 20 9C20 7 18 6 16 6H8C6 6 4 7 4 9C4 13 7 14 7 14Z" />
<path d="M10 6V2" />
<path d="M14 6V2" />
{:else if name === 'play'}
<path d="M6.90588 4.53682C6.50592 4.2998 6 4.58808 6 5.05299V18.947C6 19.4119 6.50592 19.7002 6.90588 19.4632L18.629 12.5162C19.0211 12.2838 19.0211 11.7162 18.629 11.4838L6.90588 4.53682Z" />
{:else if name === 'clock'}
<circle cx="12" cy="12" r="10" />
<path d="M12 6V12H16.5" />
{/if}
</svg>
@@ -24,7 +24,7 @@
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="bg-white dark:bg-[#0a0a0a] dark:border dark:border-white/8 rounded-3xl overflow-hidden shadow-2xl {className}"
class="bg-white dark:bg-[#0a0a0a] dark:border dark:border-white/8 rounded-3xl overflow-visible shadow-2xl {className}"
onmousedown={(e) => e.stopPropagation()}
onkeydown={() => {}}
>
@@ -0,0 +1,104 @@
<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 relative flex gap-2.5 text-left w-full bg-white dark:bg-[#1a1a1a] text-gray-700 dark:text-gray-300 border border-black/[0.08] dark:border-white/[0.06] shadow-lg dark:shadow-none rounded-2xl py-3 px-4 cursor-pointer select-none"
onpointerdown={onPointerDown}
onpointermove={onPointerMove}
onpointerup={onPointerUp}
onpointercancel={() => (moved = true)}
>
<!-- Close button -->
<button
bind:this={closeButtonEl}
class="absolute -top-0.5 -left-0.5 p-0.5 rounded-full opacity-0 group-hover:opacity-100 bg-gray-200 dark:bg-[#222] text-gray-500 dark:text-gray-400 hover:bg-gray-300 dark:hover:bg-[#333] hover:text-gray-700 dark:hover:text-gray-300 border-none cursor-pointer transition-opacity duration-150 z-10"
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="shrink-0 self-start -translate-y-0.5">
<img src="/favicon.png" alt="cptr" class="w-5 h-5 rounded-full" />
</div>
<!-- Content -->
<div class="min-w-0">
{#if title}
<div class="text-[13px] font-medium mb-0.5 overflow-hidden text-ellipsis whitespace-nowrap text-gray-900 dark:text-white">{title}</div>
{/if}
{#if content}
<div class="text-xs text-gray-500 dark:text-[#aaa] font-normal line-clamp-2">{content}</div>
{/if}
</div>
</div>
<style>
.notification-toast {
min-width: var(--width, 300px);
}
</style>
@@ -3,6 +3,7 @@
import { getWelcome } from '$lib/apis/state';
import { listDir } from '$lib/apis/files';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
defaultName?: string;
@@ -175,9 +176,7 @@
<div bind:this={listEl} class="flex-1 overflow-y-auto p-1 min-h-0">
{#if loading}
<div class="flex items-center justify-center py-8">
<div
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={16} />
</div>
{:else if error}
<div class="flex flex-col items-center justify-center gap-2 py-8 text-center">
@@ -9,6 +9,7 @@
import { ApiError } from '$lib/apis';
import { session, setSession } from '$lib/session';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
let currentPassword = $state('');
let newPassword = $state('');
@@ -136,9 +137,7 @@
disabled={uploadingAvatar}
>
{#if uploadingAvatar}
<div
class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={20} />
{:else}
<img src={avatarUrl || '/user.png'} alt="Avatar" class="w-full h-full object-cover" />
<div
@@ -219,9 +218,7 @@
disabled:opacity-30 disabled:pointer-events-none"
>
{#if updatingPassword}
<div
class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={14} />
{:else}
{$t('account.updatePassword')}
{/if}
@@ -4,10 +4,56 @@
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 ToggleSwitch from '../common/ToggleSwitch.svelte';
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 +86,52 @@
{/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>
<ToggleSwitch value={$notificationsEnabled} onchange={() => toggleNotifications()} />
</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>
<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">
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}
+334 -22
View File
@@ -9,8 +9,11 @@
sidebarOpen,
sidebarWidth,
appVersion,
showChangelog
showChangelog,
openChatTab,
setActiveTab
} from '$lib/stores';
import { get } from 'svelte/store';
import Sortable from 'sortablejs';
import Icon from './Icon.svelte';
import DirectoryPicker from './DirectoryPicker.svelte';
@@ -20,6 +23,10 @@
import { tooltip } from '$lib/tooltip';
import { session, clearSession } from '$lib/session';
import { getWelcome } from '$lib/apis/state';
import { getChats, type ChatInfo } from '$lib/apis/chat';
import ChatItem from './common/ChatItem.svelte';
import { chatEnabled } from '$lib/stores/chat';
import { socketStore } from '$lib/stores/socket.svelte';
import { t } from '$lib/i18n';
import { onMount, onDestroy } from 'svelte';
@@ -36,6 +43,109 @@
let wsListEl: HTMLDivElement | undefined = $state();
let sortable: Sortable | null = null;
// ── Per-workspace chat history ──────────────────────────────
let expandedWorkspaces = $state<Set<string>>(new Set());
let wsChatsCache = $state<Map<string, ChatInfo[]>>(new Map());
let wsChatsLoading = $state<Set<string>>(new Set());
function toggleWorkspaceExpand(path: string) {
const next = new Set(expandedWorkspaces);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
// Lazy-fetch chats if not cached
if (!wsChatsCache.has(path)) {
fetchWorkspaceChats(path);
}
}
expandedWorkspaces = next;
}
async function fetchWorkspaceChats(path: string) {
if (wsChatsLoading.has(path)) return;
wsChatsLoading = new Set([...wsChatsLoading, path]);
try {
const data = await getChats(path, 5, 0, 'updated_at', 'desc');
wsChatsCache = new Map([...wsChatsCache, [path, data.chats || []]]);
} catch {
wsChatsCache = new Map([...wsChatsCache, [path, []]]);
} finally {
const next = new Set(wsChatsLoading);
next.delete(path);
wsChatsLoading = next;
}
}
function relativeTime(ts: number): string {
// ts is in milliseconds
const now = Date.now();
const diffMs = now - ts;
const diffSec = Math.floor(diffMs / 1000);
if (diffSec < 60) return 'now';
const diffMin = Math.floor(diffSec / 60);
if (diffMin < 60) return `${diffMin}m`;
const diffHr = Math.floor(diffMin / 60);
if (diffHr < 24) return `${diffHr}h`;
const diffDay = Math.floor(diffHr / 24);
if (diffDay < 30) return `${diffDay}d`;
const diffMonth = Math.floor(diffDay / 30);
return `${diffMonth}mo`;
}
function handleSidebarChatClick(chatId: string, wsPath: string, title: string) {
// If not already on this workspace, navigate first
const currentWsPath = $page.url.searchParams.get('workspace');
if ($page.url.pathname !== '/' || currentWsPath !== wsPath) {
goto(`/?workspace=${encodeURIComponent(wsPath)}`);
}
openChatTab(chatId, undefined, title);
if (typeof window !== 'undefined' && window.innerWidth < 768) {
sidebarOpen.set(false);
}
}
function handleShowMoreChats(wsPath: string) {
// Navigate to the workspace and focus an existing chat tab (landing/history)
// instead of always creating a new one
goto(`/?workspace=${encodeURIComponent(wsPath)}`);
// Check if there's already a chat tab showing the landing page (no specific chatId)
const ws = get(currentWorkspace);
if (ws) {
for (const group of ws.groups) {
const existing = group.tabs.find(
(t) => t.type === 'chat' && (t.path?.startsWith('new-') || t.path?.startsWith('pending-'))
);
if (existing) {
setActiveTab(existing.id, group.id);
if (typeof window !== 'undefined' && window.innerWidth < 768) sidebarOpen.set(false);
return;
}
}
}
openChatTab();
if (typeof window !== 'undefined' && window.innerWidth < 768) {
sidebarOpen.set(false);
}
}
// Socket listener for chat events — invalidate cache when chats update
const seenChatIds = new Set<string>();
function handleChatEvent(data: { chat_id: string; done?: boolean; title?: string; delta?: string; workspace?: string }) {
// Re-fetch on done, title update, or first event of a new chat
const isNew = !seenChatIds.has(data.chat_id);
seenChatIds.add(data.chat_id);
if (!data.done && !data.title && !isNew) return;
for (const path of expandedWorkspaces) {
fetchWorkspaceChats(path);
}
}
const MIN_WIDTH = 160;
const MAX_WIDTH = 400;
let isResizing = $state(false);
@@ -136,10 +246,25 @@
}
});
}
// Bind socket listener for chat cache invalidation
const tryBind = () => {
const socket = socketStore.getSocket();
if (!socket) {
setTimeout(tryBind, 200);
return;
}
socket.on('events:chat', handleChatEvent);
};
tryBind();
});
onDestroy(() => {
sortable?.destroy();
const socket = socketStore.getSocket();
if (socket) {
socket.off('events:chat', handleChatEvent);
}
});
</script>
@@ -183,6 +308,22 @@
</button>
</div>
<!-- Automations -->
<div class="px-1.5 mt-1 shrink-0">
<a
href="/automations"
class="flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100 no-underline"
onclick={(e) => {
e.preventDefault();
goto('/automations');
if (typeof window !== 'undefined' && window.innerWidth < 768) sidebarOpen.set(false);
}}
>
<Icon name="clock" size={14} />
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap">Automations</span>
</a>
</div>
<!-- Workspace section header -->
<div class="flex items-center justify-between h-8 pl-3.5 pr-1.5 shrink-0">
<span class="text-xs text-gray-400 dark:text-gray-500">{$t('sidebar.workspaces')}</span>
@@ -199,28 +340,81 @@
<!-- Workspace list -->
<div bind:this={wsListEl} class="flex-1 overflow-y-auto px-1.5">
{#each $workspaceList as ws (ws.path)}
<a
href="/?workspace={encodeURIComponent(ws.path)}"
class="group flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs font-medium transition-colors duration-100 no-underline
{ws.path === currentPath
? 'bg-gray-200/50 text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
onclick={(e) => handleWorkspaceClick(e, ws.path)}
>
<Icon name="folder" size={14} />
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
>{ws.name}</span
{@const isExpanded = expandedWorkspaces.has(ws.path)}
{@const chats = wsChatsCache.get(ws.path)}
{@const isLoading = wsChatsLoading.has(ws.path)}
<div class="ws-item">
<a
href="/?workspace={encodeURIComponent(ws.path)}"
class="group flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs font-medium transition-colors duration-100 no-underline
{ws.path === currentPath
? 'bg-gray-200/50 text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
onclick={(e) => handleWorkspaceClick(e, ws.path)}
>
<span
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 transition-all duration-75"
role="button"
tabindex="-1"
onclick={(e) => openWsMenu(e, ws.path)}
aria-label={$t('sidebar.workspaceOptions')}
>
<Icon name="three-dots" size={11} />
</span>
</a>
<!-- Icon: folder by default, chevron on hover (when chat enabled) -->
{#if $chatEnabled}
<span
class="ws-icon-toggle shrink-0"
role="button"
tabindex="-1"
onclick={(e) => {
e.stopPropagation();
e.preventDefault();
toggleWorkspaceExpand(ws.path);
}}
aria-label={isExpanded ? 'Collapse' : 'Expand'}
>
<span class="ws-icon-folder"><Icon name="folder" size={14} /></span>
<span class="ws-icon-chevron" style="transform: rotate({isExpanded ? '90deg' : '0deg'})">
<Icon name="chevron-right" size={11} />
</span>
</span>
{:else}
<Icon name="folder" size={14} />
{/if}
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
>{ws.name}</span
>
<span
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 transition-all duration-75"
role="button"
tabindex="-1"
onclick={(e) => openWsMenu(e, ws.path)}
aria-label={$t('sidebar.workspaceOptions')}
>
<Icon name="three-dots" size={11} />
</span>
</a>
<!-- Collapsible chat list -->
{#if $chatEnabled && isExpanded}
<div class="ws-chats">
{#if isLoading && !chats}
<div class="ws-chat-loading">
<span class="ws-chat-loading-dot"></span>
<span class="ws-chat-loading-dot"></span>
<span class="ws-chat-loading-dot"></span>
</div>
{:else if chats && chats.length > 0}
{#each chats as chat (chat.id)}
<ChatItem
{chat}
onclick={() => handleSidebarChatClick(chat.id, ws.path, chat.title)}
/>
{/each}
<button
class="ws-chat-show-more"
onclick={() => handleShowMoreChats(ws.path)}
>
{$t('sidebar.showMore')}
</button>
{:else if chats}
<!-- No chats yet, show nothing -->
{/if}
</div>
{/if}
</div>
{/each}
{#if $workspaceList.length === 0}
@@ -230,6 +424,8 @@
{/if}
</div>
<!-- Settings and profile footer pinned to the bottom -->
<div class="relative px-1 pb-0.5 shrink-0">
<button
@@ -382,4 +578,120 @@
background: rgba(150, 150, 150, 0.12);
}
}
/* ── Workspace chat items ────────────────────────────── */
.ws-item {
margin-bottom: 2px;
}
.ws-expand-btn {
display: none;
}
/* Icon toggle: folder by default, chevron on hover */
.ws-icon-toggle {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
cursor: pointer;
}
.ws-icon-folder {
display: flex;
transition: opacity 0.1s;
}
.ws-icon-chevron {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.1s, transform 0.1s;
color: #9ca3af;
}
:global(.dark) .ws-icon-chevron {
color: #6b7280;
}
/* On icon hover only, swap folder → chevron */
.ws-icon-toggle:hover .ws-icon-folder {
opacity: 0;
}
.ws-icon-toggle:hover .ws-icon-chevron {
opacity: 1;
}
.ws-chats {
padding-left: 4px;
padding-bottom: 4px;
}
.ws-chat-show-more {
display: block;
width: 100%;
padding: 2px 8px;
border: none;
background: none;
cursor: pointer;
font-size: 11px;
color: #b0b5be;
text-align: left;
transition: color 0.1s;
}
.ws-chat-show-more:hover {
color: #6b7280;
}
:global(.dark) .ws-chat-show-more {
color: #6b7280;
}
:global(.dark) .ws-chat-show-more:hover {
color: #9ca3af;
}
.ws-chat-loading {
display: flex;
gap: 4px;
padding: 6px 8px;
}
.ws-chat-loading-dot {
width: 4px;
height: 4px;
border-radius: 50%;
background: #9ca3af;
animation: dotPulse 1s ease-in-out infinite;
}
:global(.dark) .ws-chat-loading-dot {
background: #6b7280;
}
.ws-chat-loading-dot:nth-child(2) {
animation-delay: 0.15s;
}
.ws-chat-loading-dot:nth-child(3) {
animation-delay: 0.3s;
}
@keyframes dotPulse {
0%,
100% {
opacity: 0.3;
}
50% {
opacity: 1;
}
}
</style>
@@ -0,0 +1,169 @@
<script lang="ts">
/**
* Create / Edit automation modal.
* Uses shared ModelSelector and DropdownMenu components.
*/
import Modal from '../Modal.svelte';
import Icon from '../Icon.svelte';
import DropdownMenu from '../DropdownMenu.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import ScheduleDropdown from './ScheduleDropdown.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import type { AutomationData, AutomationForm } from '$lib/apis/automations';
import { createAutomation, updateAutomation } from '$lib/apis/automations';
import { toast } from 'svelte-sonner';
interface Props {
automation?: AutomationData | null;
onclose: () => void;
onsave: (automation: AutomationData) => void;
}
let { automation = null, onclose, onsave }: Props = $props();
let name = $state(automation?.name || '');
let prompt = $state(automation?.prompt || '');
let modelId = $state(automation?.model_id || $selectedModelId || '');
let workspace = $state(automation?.workspace || '');
let rrule = $state(automation?.rrule || 'RRULE:FREQ=DAILY;BYHOUR=9;BYMINUTE=0');
let saving = $state(false);
// Workspaces
let showWsMenu = $state(false);
let wsBtnEl: HTMLButtonElement | undefined = $state();
$effect(() => {
if (!workspace && $workspaceList.length > 0) {
workspace = $workspaceList[0].path;
}
});
let wsMenuItems = $derived(
$workspaceList.map((ws) => ({
label: ws.name,
icon: 'folder',
active: ws.path === workspace,
check: true,
onclick: () => { workspace = ws.path; }
}))
);
let selectedWsName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || 'Select workspace'
);
async function handleSubmit() {
if (!name.trim() || !prompt.trim() || !modelId || !workspace) return;
saving = true;
try {
const form: AutomationForm = {
name: name.trim(),
prompt: prompt.trim(),
model_id: modelId,
workspace,
rrule,
is_active: true
};
let result: AutomationData;
if (automation) {
result = await updateAutomation(automation.id, form);
} else {
result = await createAutomation(form);
}
onsave(result);
onclose();
} catch (e: any) {
toast.error(e.message || 'Failed to save automation');
} finally {
saving = false;
}
}
</script>
<Modal {onclose} class="w-full max-w-2xl">
<div>
<!-- Title input -->
<div class="px-5 pt-4 pb-2 flex items-center">
<input
class="w-full text-lg bg-transparent outline-none placeholder:text-gray-300 dark:placeholder:text-gray-700 text-gray-900 dark:text-white"
type="text"
bind:value={name}
placeholder="Automation title"
/>
<button
class="shrink-0 ml-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
onclick={onclose}
>
<Icon name="xmark" size={18} />
</button>
</div>
<!-- Prompt -->
<div class="px-5 pb-2">
<div class="mb-1 text-[11px] text-gray-400 dark:text-gray-500">Instructions</div>
<textarea
class="w-full text-xs bg-transparent outline-none placeholder:text-gray-300 dark:placeholder:text-gray-700 text-gray-700 dark:text-gray-300 resize-none"
bind:value={prompt}
rows={8}
style="min-height: 12rem;"
placeholder="Enter prompt here..."
></textarea>
</div>
<!-- Bottom toolbar -->
<div class="flex items-center justify-between px-4 pb-3.5 pt-1 gap-2">
<div class="flex items-center gap-1 flex-wrap flex-1 min-w-0">
<!-- Schedule -->
<ScheduleDropdown bind:rrule />
<!-- Model selector (shared component) -->
<ModelSelector bind:selectedModel={modelId} />
<!-- Workspace selector -->
<button
bind:this={wsBtnEl}
type="button"
class="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors duration-100"
onclick={() => (showWsMenu = !showWsMenu)}
>
<Icon name="folder" size={12} />
<span class="truncate max-w-[120px]">{selectedWsName}</span>
<svg class="w-3 h-3 opacity-50" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
</div>
<div class="flex items-center gap-2 shrink-0">
<button
class="px-3 py-1 text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
type="button"
onclick={onclose}
>
Cancel
</button>
<button
class="px-3.5 py-1.5 text-xs bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition-colors rounded-full disabled:opacity-50"
type="button"
onclick={handleSubmit}
disabled={saving || !name.trim() || !prompt.trim() || !modelId || !workspace}
>
{saving ? 'Saving...' : automation ? 'Save' : 'Create'}
</button>
</div>
</div>
</div>
</Modal>
{#if showWsMenu && wsBtnEl}
<DropdownMenu
items={wsMenuItems}
anchor={wsBtnEl}
onclose={() => (showWsMenu = false)}
preferAbove={true}
maxHeight="15rem"
className="w-48"
/>
{/if}
@@ -0,0 +1,472 @@
<script lang="ts">
/**
* Automations panel — list + detail view.
* Rendered as a full-page SvelteKit route.
*/
import { goto } from '$app/navigation';
import Icon from '../Icon.svelte';
import ToggleSwitch from '../common/ToggleSwitch.svelte';
import Spinner from '../common/Spinner.svelte';
import AutomationModal from './AutomationModal.svelte';
import { openChatTab, sidebarOpen } from '$lib/stores';
import {
getAutomations,
toggleAutomation,
deleteAutomation,
runAutomation,
getAutomationById,
getAutomationRuns,
generateWebhook,
deleteWebhook,
type AutomationData,
type AutomationRunData
} from '$lib/apis/automations';
import { toast } from 'svelte-sonner';
interface Props {
automationId?: string;
}
let { automationId }: Props = $props();
// ── List state ──
let items = $state<AutomationData[]>([]);
let total = $state(0);
let loading = $state(true);
let searchQuery = $state('');
let statusFilter = $state('all');
let showModal = $state(false);
let editingAutomation = $state<AutomationData | null>(null);
// ── Detail state ──
let detail = $state<AutomationData | null>(null);
let runs = $state<AutomationRunData[]>([]);
let detailLoading = $state(false);
async function loadList() {
loading = true;
try {
const res = await getAutomations(undefined, searchQuery || undefined, statusFilter);
items = res.items;
total = res.total;
} catch (e: any) {
toast.error(e.message || 'Failed to load automations');
} finally {
loading = false;
}
}
async function loadDetail(id: string) {
detailLoading = true;
try {
detail = await getAutomationById(id);
runs = await getAutomationRuns(id);
} catch (e: any) {
toast.error(e.message || 'Failed to load automation');
} finally {
detailLoading = false;
}
}
$effect(() => {
if (!automationId) {
loadList();
}
});
$effect(() => {
if (automationId) {
loadDetail(automationId);
}
});
async function handleToggle(a: AutomationData) {
try {
const updated = await toggleAutomation(a.id);
items = items.map((i) => (i.id === a.id ? updated : i));
if (detail?.id === a.id) detail = updated;
} catch (e: any) {
toast.error(e.message || 'Failed to toggle');
}
}
async function handleDelete(a: AutomationData) {
if (!confirm(`Delete "${a.name}"?`)) return;
try {
await deleteAutomation(a.id);
items = items.filter((i) => i.id !== a.id);
if (detail?.id === a.id) goto('/automations');
toast.success('Deleted');
} catch (e: any) {
toast.error(e.message || 'Failed to delete');
}
}
async function handleRunNow(a: AutomationData) {
try {
await runAutomation(a.id);
toast.success(`"${a.name}" triggered`);
} catch (e: any) {
toast.error(e.message || 'Failed to run');
}
}
function handleSave(saved: AutomationData) {
const idx = items.findIndex((i) => i.id === saved.id);
if (idx >= 0) {
items[idx] = saved;
items = [...items];
} else {
items = [saved, ...items];
}
if (detail?.id === saved.id) detail = saved;
showModal = false;
editingAutomation = null;
}
function formatTime(ns: number | null): string {
if (!ns) return '-';
return new Date(ns / 1_000_000).toLocaleString(undefined, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
function parseFrequency(rrule: string): string {
if (rrule.includes('COUNT=1')) return 'Once';
const match = rrule.match(/FREQ=(\w+)/);
if (!match) return 'Custom';
const freq = match[1].toLowerCase();
return freq.charAt(0).toUpperCase() + freq.slice(1);
}
// ── Webhook ──
let webhookLoading = $state(false);
let webhookCopied = $state(false);
async function handleGenerateWebhook() {
if (!detail) return;
webhookLoading = true;
try {
const updated = await generateWebhook(detail.id);
detail = updated;
items = items.map((i) => (i.id === updated.id ? updated : i));
toast.success('Webhook enabled');
} catch (e: any) {
toast.error(e.message || 'Failed to generate webhook');
} finally {
webhookLoading = false;
}
}
async function handleRevokeWebhook() {
if (!detail) return;
webhookLoading = true;
try {
const updated = await deleteWebhook(detail.id);
detail = updated;
items = items.map((i) => (i.id === updated.id ? updated : i));
toast.success('Webhook disabled');
} catch (e: any) {
toast.error(e.message || 'Failed to revoke webhook');
} finally {
webhookLoading = false;
}
}
function copyWebhookUrl() {
if (!detail?.webhook_url) return;
navigator.clipboard.writeText(detail.webhook_url);
webhookCopied = true;
setTimeout(() => (webhookCopied = false), 2000);
}
</script>
<div class="flex flex-col h-full overflow-hidden">
{#if automationId}
<!-- ── Detail ── -->
{#if detailLoading}
<div class="flex items-center justify-center py-12">
<Spinner size={16} />
</div>
{:else if detail}
<!-- Header -->
<div class="flex items-center gap-2 h-9 {$sidebarOpen ? 'px-3' : 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0">
{#if !$sidebarOpen}
<button
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
onclick={() => sidebarOpen.set(true)}
title="Toggle sidebar"
>
<Icon name="sidebar-expand" size={14} />
</button>
{/if}
<button
class="flex items-center gap-1 text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => goto('/automations')}
>
<Icon name="chevron-left" size={12} />
<span>Automations</span>
</button>
<span class="text-gray-300 dark:text-gray-600">/</span>
<span class="text-xs text-gray-900 dark:text-white truncate">{detail.name}</span>
<div class="ml-auto flex items-center gap-2">
<ToggleSwitch value={detail.is_active} onchange={() => handleToggle(detail!)} />
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => handleRunNow(detail!)}
title="Run now"
>
<Icon name="play" size={11} />
</button>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => { editingAutomation = detail; showModal = true; }}
title="Edit"
>
<Icon name="pencil" size={11} />
</button>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-red-500 transition-colors duration-75"
onclick={() => handleDelete(detail!)}
title="Delete"
>
<Icon name="trash" size={11} />
</button>
</div>
</div>
<!-- Content -->
<div class="flex-1 overflow-y-auto">
<!-- Info rows -->
<div class="border-b border-gray-200 dark:border-white/6">
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Status</span>
<div class="flex items-center gap-1.5">
<span class="w-1.5 h-1.5 rounded-full {detail.is_active ? 'bg-emerald-500' : 'bg-gray-400'}"></span>
<span class="text-xs text-gray-700 dark:text-gray-300">{detail.is_active ? 'Active' : 'Paused'}</span>
</div>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Schedule</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{parseFrequency(detail.rrule)}</span>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Model</span>
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono">{detail.model_id}</span>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Next run</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{formatTime(detail.next_run_at)}</span>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Last run</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{formatTime(detail.last_run_at)}</span>
</div>
<div class="flex items-center min-h-[1.75rem] px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Webhook</span>
{#if detail.webhook_url}
<div class="flex items-center gap-1.5 min-w-0 flex-1">
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono truncate">...?token={detail.webhook_url.split('token=')[1]?.slice(0, 12)}...</span>
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75 shrink-0"
onclick={copyWebhookUrl}
>
{webhookCopied ? 'Copied!' : 'Copy'}
</button>
</div>
{:else if detail.has_webhook}
<!-- Webhook enabled, URL not available -->
<div class="flex items-center gap-1.5">
<span class="text-[11px] text-gray-700 dark:text-gray-300">Enabled</span>
<span class="text-gray-300 dark:text-gray-600">·</span>
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={handleGenerateWebhook}
disabled={webhookLoading}
>
Regenerate
</button>
<span class="text-gray-300 dark:text-gray-600">·</span>
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={handleRevokeWebhook}
disabled={webhookLoading}
>
Disable
</button>
</div>
{:else}
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={handleGenerateWebhook}
disabled={webhookLoading}
>
Enable
</button>
{/if}
</div>
</div>
<!-- Prompt -->
<div class="border-b border-gray-200 dark:border-white/6 px-3 py-2">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">Prompt</div>
<div class="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap font-mono leading-relaxed max-h-32 overflow-y-auto">
{detail.prompt}
</div>
</div>
<!-- Runs -->
<div class="px-3 py-2">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">Runs</div>
{#if runs.length === 0}
<div class="text-[11px] text-gray-400 dark:text-gray-600 py-2">No runs yet</div>
{:else}
{#each runs as run}
<div class="flex items-center gap-2 h-7 text-xs">
<span class="w-1.5 h-1.5 rounded-full shrink-0 {run.status === 'success' ? 'bg-emerald-500' : 'bg-red-400'}"></span>
<span class="text-gray-500 dark:text-gray-400">{formatTime(run.created_at)}</span>
{#if run.chat_id}
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => {
const ws = detail?.workspace;
if (ws) {
goto(`/?workspace=${encodeURIComponent(ws)}`);
}
setTimeout(() => openChatTab(run.chat_id!), 300);
}}
>
view chat →
</button>
{/if}
{#if run.error}
<span class="text-[11px] text-red-400 truncate" title={run.error}>{run.error}</span>
{/if}
</div>
{/each}
{/if}
</div>
</div>
{/if}
{:else}
<!-- ── List ── -->
<!-- Header -->
<div class="flex items-center gap-2 h-9 {$sidebarOpen ? 'px-3' : 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0">
{#if !$sidebarOpen}
<button
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
onclick={() => sidebarOpen.set(true)}
title="Toggle sidebar"
>
<Icon name="sidebar-expand" size={14} />
</button>
{/if}
<span class="text-xs text-gray-900 dark:text-white">Automations</span>
{#if total > 0}
<span class="text-[11px] text-gray-400 dark:text-gray-600">{total}</span>
{/if}
<div class="ml-auto flex items-center gap-1">
<select
class="text-[11px] bg-transparent text-gray-400 dark:text-gray-500 outline-none cursor-pointer"
bind:value={statusFilter}
onchange={loadList}
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="paused">Paused</option>
</select>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => { editingAutomation = null; showModal = true; }}
title="New automation"
>
<Icon name="plus" size={13} />
</button>
</div>
</div>
<!-- Search -->
<div class="flex items-center gap-1.5 h-8 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
<Icon name="search" size={13} class="text-gray-400 shrink-0" />
<input
type="text"
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white placeholder:text-gray-400"
placeholder="Filter..."
bind:value={searchQuery}
oninput={loadList}
/>
{#if searchQuery}
<button class="text-gray-400 flex items-center" onclick={() => { searchQuery = ''; loadList(); }}>
<Icon name="xmark" size={11} />
</button>
{/if}
</div>
<!-- List -->
<div class="flex-1 overflow-y-auto p-1">
{#if loading}
<div class="flex items-center justify-center py-12">
<Spinner size={16} />
</div>
{:else if items.length === 0}
<div class="flex flex-col items-center justify-center py-12 gap-2">
<p class="text-xs text-gray-400 dark:text-gray-600">
{searchQuery ? 'No matches' : 'No automations yet'}
</p>
{#if !searchQuery}
<button
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-75"
onclick={() => { editingAutomation = null; showModal = true; }}
>
Create automation
</button>
{/if}
</div>
{:else}
{#each items as a (a.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex items-center gap-2 h-7 px-2 rounded-md"
>
<span class="w-1.5 h-1.5 rounded-full shrink-0 {a.is_active ? 'bg-emerald-500' : 'bg-gray-400'}"></span>
<button
class="text-xs text-gray-700 dark:text-gray-300 truncate flex-1 text-left hover:underline cursor-pointer transition-colors duration-75"
onclick={() => goto(`/automations/${a.id}`)}
>
{a.name}
</button>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0">{a.workspace.split('/').pop()}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0">·</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0">{parseFrequency(a.rrule)}</span>
<div class="flex items-center gap-2 shrink-0" onclick={(e) => e.stopPropagation()}>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => handleRunNow(a)}
title="Run now"
>
<Icon name="play" size={11} />
</button>
<div class="flex items-center" onclick={(e) => e.stopPropagation()}>
<ToggleSwitch value={a.is_active} onchange={() => handleToggle(a)} />
</div>
</div>
</div>
{/each}
{/if}
</div>
{/if}
</div>
{#if showModal}
<AutomationModal
automation={editingAutomation}
onclose={() => { showModal = false; editingAutomation = null; }}
onsave={handleSave}
/>
{/if}
@@ -0,0 +1,309 @@
<script lang="ts">
/**
* RRULE schedule builder dropdown.
* Uses fixed positioning so it's never clipped by ancestor overflow.
*/
import { t } from '$lib/i18n';
interface Props {
rrule: string;
onchange?: (rrule: string) => void;
}
let { rrule = $bindable(), onchange }: Props = $props();
type Frequency = 'ONCE' | 'HOURLY' | 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'CUSTOM';
const FREQUENCIES: { key: Frequency; label: string }[] = [
{ key: 'ONCE', label: 'Once' },
{ key: 'HOURLY', label: 'Hourly' },
{ key: 'DAILY', label: 'Daily' },
{ key: 'WEEKLY', label: 'Weekly' },
{ key: 'MONTHLY', label: 'Monthly' },
{ key: 'CUSTOM', label: 'Custom' }
];
const DAYS = [
{ key: 'MO', label: 'Mo' },
{ key: 'TU', label: 'Tu' },
{ key: 'WE', label: 'We' },
{ key: 'TH', label: 'Th' },
{ key: 'FR', label: 'Fr' },
{ key: 'SA', label: 'Sa' },
{ key: 'SU', label: 'Su' }
];
let frequency = $state<Frequency>('DAILY');
let hour = $state(9);
let minute = $state(0);
let selectedDays = $state<string[]>([]);
let monthDay = $state(1);
let onceDate = $state('');
let onceTime = $state('09:00');
let customRrule = $state('');
let showDropdown = $state(false);
// Fixed positioning
let triggerEl: HTMLButtonElement | undefined = $state();
let panelX = $state(0);
let panelY = $state(0);
function updatePosition() {
if (!triggerEl) return;
const rect = triggerEl.getBoundingClientRect();
panelX = rect.left;
panelY = rect.bottom + 4;
}
// Parse on mount
$effect(() => {
parseRrule(rrule);
});
function parseRrule(s: string) {
if (!s) return;
if (s.includes('COUNT=1')) {
frequency = 'ONCE';
const match = s.match(/DTSTART:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/);
if (match) {
onceDate = `${match[1]}-${match[2]}-${match[3]}`;
onceTime = `${match[4]}:${match[5]}`;
}
return;
}
const parts: Record<string, string> = {};
s.replace('RRULE:', '')
.split(';')
.forEach((p) => {
const [k, v] = p.split('=');
if (k && v) parts[k] = v;
});
const freq = parts.FREQ || 'DAILY';
if (!['HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY'].includes(freq)) {
frequency = 'CUSTOM';
customRrule = s;
return;
}
frequency = freq as Frequency;
hour = parseInt(parts.BYHOUR || '9');
minute = parseInt(parts.BYMINUTE || '0');
selectedDays = parts.BYDAY ? parts.BYDAY.split(',') : [];
monthDay = parseInt(parts.BYMONTHDAY || '1');
}
function buildRrule(): string {
if (frequency === 'CUSTOM') return customRrule;
if (frequency === 'ONCE') {
const dt = onceDate.replace(/-/g, '') + 'T' + onceTime.replace(/:/g, '') + '00';
return `DTSTART:${dt}\nRRULE:FREQ=DAILY;COUNT=1`;
}
let parts = [`FREQ=${frequency}`];
if (frequency === 'WEEKLY' && selectedDays.length) {
parts.push(`BYDAY=${selectedDays.join(',')}`);
}
if (frequency === 'MONTHLY') {
parts.push(`BYMONTHDAY=${monthDay}`);
}
if (['DAILY', 'WEEKLY', 'MONTHLY'].includes(frequency)) {
parts.push(`BYHOUR=${hour}`);
}
parts.push(`BYMINUTE=${minute}`);
return `RRULE:${parts.join(';')}`;
}
function emitChange() {
rrule = buildRrule();
onchange?.(rrule);
}
function toggleDay(day: string) {
if (selectedDays.includes(day)) {
selectedDays = selectedDays.filter((d) => d !== day);
} else {
selectedDays = [...selectedDays, day];
}
emitChange();
}
let scheduleLabel = $derived(
frequency === 'ONCE'
? 'Once'
: frequency === 'HOURLY'
? 'Hourly'
: frequency === 'DAILY'
? 'Daily'
: frequency === 'WEEKLY'
? 'Weekly'
: frequency === 'MONTHLY'
? 'Monthly'
: frequency === 'CUSTOM'
? 'Custom'
: 'Schedule'
);
</script>
<div class="schedule-dropdown">
<button
bind:this={triggerEl}
type="button"
class="schedule-trigger"
onclick={() => { updatePosition(); showDropdown = !showDropdown; }}
>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3.5 h-3.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
</svg>
<span>{scheduleLabel}</span>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-2.5 h-2.5">
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
</svg>
</button>
</div>
{#if showDropdown}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="fixed inset-0 z-[200]" onmousedown={() => (showDropdown = false)}></div>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="schedule-panel"
style="left:{panelX}px; top:{panelY}px;"
onmousedown={(e) => e.stopPropagation()}
>
<div class="px-2 text-xs text-gray-500 pt-1">Schedule</div>
<div class="px-1.5 py-0.5">
<select
class="w-full bg-transparent rounded-xl text-xs py-1.5 px-1.5 outline-none"
bind:value={frequency}
onchange={emitChange}
>
{#each FREQUENCIES as f}
<option value={f.key}>{f.label}</option>
{/each}
</select>
</div>
{#if frequency === 'CUSTOM'}
<div class="px-2 pb-2">
<input
type="text"
bind:value={customRrule}
placeholder="RRULE:FREQ=DAILY;BYHOUR=9;BYMINUTE=0"
class="w-full bg-transparent outline-none text-xs placeholder:text-gray-400 dark:placeholder:text-gray-600"
oninput={emitChange}
/>
</div>
{:else if frequency === 'ONCE'}
<div class="flex gap-2 flex-wrap items-center px-3 pb-2 text-xs">
<input
type="date"
bind:value={onceDate}
min={new Date().toISOString().split('T')[0]}
class="bg-transparent outline-none text-xs"
oninput={emitChange}
/>
<input
type="time"
bind:value={onceTime}
class="bg-transparent outline-none text-xs"
oninput={emitChange}
/>
</div>
{:else if frequency !== 'HOURLY'}
<div class="flex gap-2 flex-wrap items-center px-3 pb-2 text-xs">
<div class="flex items-center gap-1.5">
<span class="text-xs text-gray-500 mr-0.5">Time</span>
<input
type="time"
value={`${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`}
oninput={(e) => {
const [h, m] = e.currentTarget.value.split(':').map(Number);
hour = h;
minute = m;
emitChange();
}}
class="bg-transparent text-center outline-none text-xs"
/>
</div>
{#if frequency === 'MONTHLY'}
<div class="flex items-center gap-1.5">
<span class="text-xs text-gray-500">Day</span>
<input
type="number"
bind:value={monthDay}
min={1}
max={31}
class="w-8 bg-transparent text-center outline-none text-xs"
oninput={emitChange}
/>
</div>
{/if}
</div>
{#if frequency === 'WEEKLY'}
<div class="flex gap-1 px-2 pb-2">
{#each DAYS as d}
<button
type="button"
class="flex-1 py-1 text-xs rounded-xl transition {selectedDays.includes(d.key)
? 'bg-gray-100 dark:bg-gray-800 text-black dark:text-gray-100'
: 'text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200'}"
onclick={() => toggleDay(d.key)}
>
{d.label}
</button>
{/each}
</div>
{/if}
{/if}
</div>
{/if}
<style>
@reference "../../../app.css";
.schedule-dropdown {
position: relative;
}
.schedule-trigger {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 16px;
font-size: 12px;
color: var(--color-gray-600);
transition: background 0.1s;
}
:global(.dark) .schedule-trigger {
color: var(--color-gray-400);
}
.schedule-trigger:hover {
background: rgba(0, 0, 0, 0.05);
}
:global(.dark) .schedule-trigger:hover {
background: rgba(255, 255, 255, 0.05);
}
.schedule-panel {
position: fixed;
z-index: 201;
width: 12rem;
padding: 4px;
border-radius: 16px;
background: white;
border: 1px solid var(--color-gray-200);
box-shadow:
0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -2px rgba(0, 0, 0, 0.1);
}
:global(.dark) .schedule-panel {
background: #0a0a0a;
border-color: rgba(255, 255, 255, 0.08);
}
</style>
@@ -346,12 +346,11 @@
.trim()
.slice(0, 200)}
<button
class="w-full text-left my-2 rounded-xl
border border-gray-200 dark:border-white/10
hover:border-gray-300 dark:hover:border-white/15
bg-gray-50/50 dark:bg-white/[0.02]
hover:bg-gray-50 dark:hover:bg-white/[0.04]
transition-colors duration-150 cursor-pointer"
class="w-full text-left my-2 rounded-xl cursor-pointer
border border-gray-200 dark:border-white/8
hover:border-gray-300 dark:hover:border-white/12
hover:bg-gray-50/50 dark:hover:bg-white/[0.03]
transition-colors duration-150"
onclick={() => {
const ws = get(currentWorkspace);
if (ws && artifact.path) {
@@ -360,7 +359,10 @@
}
}}
>
<div class="flex items-center px-3 pt-2.5 pb-0.5">
<div class="flex items-center gap-2 px-3 pt-2.5 pb-0.5">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-3.5 shrink-0 text-gray-400 dark:text-gray-500">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
</svg>
<span class="text-xs font-medium text-gray-800 dark:text-gray-100"
>{artifact.title || 'Artifact'}</span
>
@@ -936,3 +938,5 @@
{/if}
{/if}
</div>
@@ -1,5 +1,6 @@
<script lang="ts">
import type { ChatInfo } from '$lib/apis/chat';
import ChatItem from '../common/ChatItem.svelte';
import DropdownMenu from '../DropdownMenu.svelte';
import Pagination from '../common/Pagination.svelte';
@@ -55,6 +56,9 @@
if (diffD < 7) return `${diffD}d ago`;
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
// Not used directly anymore (ChatItem has its own formatTime),
// but kept for the sort header display
</script>
{#snippet chevronUp()}
@@ -126,32 +130,11 @@
{/if}
{#each chats as chat (chat.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="group flex items-center gap-2 w-full h-7 px-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/4 transition-colors duration-75 cursor-pointer"
role="button"
tabindex="0"
<ChatItem
{chat}
onclick={() => onopen(chat.id)}
onkeydown={(e) => {
if (e.key === 'Enter') onopen(chat.id);
}}
>
<span class="flex-1 text-xs text-gray-500 dark:text-gray-500 truncate">{chat.title}</span>
<span class="text-[10px] text-gray-300 dark:text-gray-700 shrink-0"
>{formatTime(chat.updated_at)}</span
>
<button
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-300 dark:text-gray-700 hover:text-gray-500 dark:hover:text-gray-400 transition-all duration-75"
onclick={(e) => openMenu(e, chat.id)}
aria-label="Chat options"
>
<svg width="11" height="11" viewBox="0 0 16 16" fill="currentColor">
<circle cx="3" cy="8" r="1.5" />
<circle cx="8" cy="8" r="1.5" />
<circle cx="13" cy="8" r="1.5" />
</svg>
</button>
</div>
onmenu={(e) => openMenu(e, chat.id)}
/>
{/each}
{#if onpagechange}
<Pagination {page} {totalPages} {onpagechange} />
@@ -175,3 +158,4 @@
onclose={closeMenu}
/>
{/if}
@@ -12,13 +12,14 @@
import FileSuggestionPopup from './FileSuggestionPopup.svelte';
import { searchFiles } from '$lib/apis/files';
import { uploadFile } from '$lib/apis/files';
import ModelSelector from './ModelSelector.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import SendButton from './SendButton.svelte';
import PlusMenu from './PlusMenu.svelte';
import DictateButton from './DictateButton.svelte';
import QueuedMessageItem from './QueuedMessageItem.svelte';
import Icon from '../Icon.svelte';
import { planMode } from '$lib/stores';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
inputText: string;
@@ -397,7 +398,7 @@
<div class="relative group flex-shrink-0">
{#if upload.loading}
<div class="flex items-center justify-center size-8 bg-gray-50 dark:bg-white/5 rounded-xl border border-gray-200 dark:border-white/10 shadow-sm">
<div class="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
<Spinner size={16} />
</div>
{:else if upload.type === 'image'}
<img src={upload.url} alt={upload.name} class="size-8 object-cover rounded-xl border border-gray-200 dark:border-white/10 shadow-sm" />
@@ -452,6 +453,9 @@
onfiles={(files) => {
if (files) processFiles(Array.from(files));
}}
oncapture={(file) => {
processFiles([file]);
}}
/>
{#if $planMode}
<button
@@ -36,6 +36,7 @@
import UserMessage from './UserMessage.svelte';
import AssistantMessage from './AssistantMessage.svelte';
import ChatHistory from './ChatHistory.svelte';
import Spinner from '../common/Spinner.svelte';
interface Props {
workspace: string;
@@ -302,6 +303,20 @@
queue_processed?: boolean;
title?: string;
}) {
// On the landing page, update the chat list in place from socket events
if (isLanding) {
if (data.done) {
previousChats = previousChats.map((c) =>
c.id === data.chat_id ? { ...c, is_active: false } : c
);
}
if (data.title) {
previousChats = previousChats.map((c) =>
c.id === data.chat_id ? { ...c, title: data.title! } : c
);
}
}
if (data.chat_id !== chatId) return;
// Title generated by backend — update tab label
@@ -871,35 +886,9 @@
{:else}
<!-- Conversation view -->
{#if loading}
<div class="flex-1 flex items-center justify-center text-gray-400 dark:text-gray-500">
<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<style>
.chat-load-spin {
transform-origin: center;
animation: chat-load-spin 0.75s infinite linear;
}
@keyframes chat-load-spin {
100% {
transform: rotate(360deg);
}
}
</style>
<circle
cx="12"
cy="12"
r="10"
fill="none"
stroke="currentColor"
stroke-width="2"
opacity="0.15"
/>
<path
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
fill="currentColor"
class="chat-load-spin"
/>
</svg>
</div>
<div class="flex-1 flex items-center justify-center text-gray-400 dark:text-gray-500">
<Spinner size={24} />
</div>
{:else}
<div bind:this={messagesEl} class="flex-1 overflow-y-auto" onscroll={handleMessagesScroll}>
<div class="max-w-2xl mx-auto px-4 pt-4 pb-16 flex flex-col gap-4">
@@ -3,18 +3,20 @@
import { toolApprovalMode, planMode, type ToolApprovalMode } from '$lib/stores';
import { tooltip } from '$lib/tooltip';
import Icon from '../Icon.svelte';
import ToggleSwitch from '../ToggleSwitch.svelte';
import ToggleSwitch from '../common/ToggleSwitch.svelte';
interface Props {
onfiles: (files: FileList) => void;
oncapture?: (file: File) => void;
}
let { onfiles }: Props = $props();
let { onfiles, oncapture }: Props = $props();
let open = $state(false);
let tab = $state<'' | 'tools'>('');
let btnEl: HTMLButtonElement | undefined = $state();
let menuEl: HTMLDivElement | undefined = $state();
let inputEl: HTMLInputElement | undefined = $state();
let cameraInputEl: HTMLInputElement | undefined = $state();
let pos = $state<{ x: number; bottom: number }>({ x: -9999, bottom: -9999 });
let ready = $state(false);
@@ -64,6 +66,59 @@
}
}
function handleCameraChange() {
if (cameraInputEl?.files && cameraInputEl.files.length > 0) {
// Camera input returns image files — pass them through oncapture or onfiles
for (const file of Array.from(cameraInputEl.files)) {
if (oncapture) oncapture(file);
}
cameraInputEl.value = '';
}
}
function isMobileDevice(): boolean {
if (typeof navigator === 'undefined') return false;
const ua = navigator.userAgent || (navigator as any).vendor || (window as any).opera || '';
return /android|iphone|ipad|ipod|windows phone/i.test(ua);
}
async function captureHandler() {
open = false;
if (isMobileDevice()) {
// On mobile, open the camera
cameraInputEl?.click();
return;
}
// Desktop: use screen capture API
try {
const mediaStream = await navigator.mediaDevices.getDisplayMedia({
video: { cursor: 'never' } as any,
audio: false
});
const video = document.createElement('video');
video.srcObject = mediaStream;
await video.play();
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (ctx) ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
mediaStream.getTracks().forEach((t) => t.stop());
window.focus();
const blob = await new Promise<Blob | null>((res) => canvas.toBlob(res, 'image/png'));
if (blob) {
const file = new File([blob], `screen-capture-${Date.now()}.png`, { type: 'image/png' });
if (oncapture) oncapture(file);
}
video.srcObject = null;
} catch (err) {
console.error('Error capturing screen:', err);
}
}
function close() {
open = false;
ready = false;
@@ -87,6 +142,16 @@
onchange={handleFileChange}
/>
<!-- Hidden camera input for mobile capture -->
<input
bind:this={cameraInputEl}
type="file"
accept="image/*"
capture="environment"
class="hidden"
onchange={handleCameraChange}
/>
<button
bind:this={btnEl}
type="button"
@@ -146,6 +211,25 @@
<span class="flex-1 text-left truncate">Attach files</span>
</button>
<button
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-xs text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 hover:text-gray-900 dark:hover:text-white transition-colors duration-75"
onclick={captureHandler}
>
<svg
class="size-3.5 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
<circle cx="12" cy="13" r="4" />
</svg>
<span class="flex-1 text-left truncate">Capture</span>
</button>
<div class="h-px bg-gray-100/50 dark:bg-white/3 mx-1 my-0.5"></div>
<!-- Plan mode toggle -->
@@ -0,0 +1,62 @@
<script lang="ts">
/**
* Common chat list item used in sidebar and chat history.
* Shows title, relative time, optional spinner for active chats,
* and an optional context menu button.
*/
import type { ChatInfo } from '$lib/apis/chat';
import Spinner from './Spinner.svelte';
interface Props {
chat: ChatInfo;
onclick: () => void;
/** Optional menu button click handler */
onmenu?: (e: MouseEvent) => void;
}
let { chat, onclick, onmenu }: Props = $props();
function formatTime(ts: number): string {
const now = Date.now();
const diffMs = now - ts;
const diffSec = Math.floor(diffMs / 1000);
if (diffSec < 60) return 'now';
const diffMin = Math.floor(diffSec / 60);
if (diffMin < 60) return `${diffMin}m`;
const diffHr = Math.floor(diffMin / 60);
if (diffHr < 24) return `${diffHr}h`;
const diffDay = Math.floor(diffHr / 24);
if (diffDay < 7) return `${diffDay}d`;
const d = new Date(ts);
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex items-center gap-1.5 w-full h-7 px-2 rounded-md cursor-pointer transition-colors duration-75
hover:bg-gray-50 dark:hover:bg-white/3"
role="button"
tabindex="0"
onclick={onclick}
onkeydown={(e) => { if (e.key === 'Enter') onclick(); }}
title={chat.title}
>
{#if chat.is_active}
<Spinner size={10} borderWidth={1.5} class="opacity-50" />
{/if}
<span class="flex-1 text-xs text-gray-500 dark:text-gray-500 truncate min-w-0">{chat.title}</span>
<span class="text-[10px] text-gray-300 dark:text-gray-700 shrink-0 tabular-nums">{formatTime(chat.updated_at)}</span>
{#if onmenu}
<button
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-300 dark:text-gray-700 hover:text-gray-500 dark:hover:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/8 transition-all duration-75"
onclick={(e) => { e.stopPropagation(); onmenu?.(e); }}
aria-label="Chat options"
>
<svg width="11" height="11" viewBox="0 0 16 16" fill="currentColor">
<circle cx="3" cy="8" r="1.5" />
<circle cx="8" cy="8" r="1.5" />
<circle cx="13" cy="8" r="1.5" />
</svg>
</button>
{/if}
</div>
@@ -1,7 +1,7 @@
<script lang="ts">
import { tick } from 'svelte';
import { chatModels } from '$lib/stores/chat';
import DropdownMenu from '$lib/components/DropdownMenu.svelte';
import DropdownMenu from '../DropdownMenu.svelte';
interface Props {
selectedModel: string;
@@ -0,0 +1,44 @@
<script lang="ts">
interface Props {
/** Size in px or Tailwind class like '3.5' or '5'. Defaults to 16px. */
size?: number | string;
/** Border width in px. Scales automatically if not set. */
borderWidth?: number;
/** Extra CSS classes. */
class?: string;
}
let { size = 16, borderWidth, class: className = '' }: Props = $props();
const px = typeof size === 'number' ? size : parseFloat(size) * 4;
const bw = borderWidth ?? (px <= 12 ? 1.5 : 2);
</script>
<div
class="spinner {className}"
style="width:{px}px;height:{px}px;border-width:{bw}px"
role="status"
aria-label="Loading"
></div>
<style>
.spinner {
display: inline-block;
border-style: solid;
border-color: var(--color-gray-300);
border-top-color: var(--color-gray-600);
border-radius: 9999px;
animation: spin 0.75s linear infinite;
flex-shrink: 0;
}
:global(.dark) .spinner {
border-color: var(--color-gray-700);
border-top-color: var(--color-gray-400);
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { fetchHandler } from '$lib/apis';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
src: string;
@@ -296,7 +297,7 @@
<div class="office-view">
{#if loading}
<div class="state"><div class="spinner"></div></div>
<div class="state"><Spinner size={20} /></div>
{:else if error}
<div class="state error-msg">{error}</div>
{:else if isDocx}
@@ -350,20 +351,7 @@
color: #ef4444;
}
.spinner {
width: 20px;
height: 20px;
border: 2px solid var(--color-gray-700);
border-top-color: var(--color-gray-400);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* ── DOCX ────────────────────────────────────── */
@@ -2,6 +2,7 @@
import { onMount, onDestroy } from 'svelte';
import panzoom, { type PanZoom } from 'panzoom';
import { fetchHandler } from '$lib/apis';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
src: string;
@@ -228,7 +229,7 @@
<div class="pdf-viewer">
{#if loading}
<div class="state"><div class="spinner"></div></div>
<div class="state"><Spinner size={20} /></div>
{:else if error}
<div class="state error-msg">{error}</div>
{/if}
@@ -307,20 +308,7 @@
color: #ef4444;
}
.spinner {
width: 20px;
height: 20px;
border: 2px solid var(--color-gray-700);
border-top-color: var(--color-gray-400);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.zoom-toolbar {
position: absolute;
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { fetchHandler } from '$lib/apis';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
src: string;
@@ -28,7 +29,7 @@
try {
const initSqlJs = (await import('sql.js')).default;
const SQL = await initSqlJs({
locateFile: (file: string) => `https://sql.js.org/dist/${file}`
locateFile: () => `/sql-wasm.wasm`
});
const res = await fetchHandler(src);
@@ -147,7 +148,7 @@
<div class="sqlite-view">
{#if loading}
<div class="state"><div class="spinner"></div></div>
<div class="state"><Spinner size={20} /></div>
{:else if error}
<div class="state error-msg">{error}</div>
{:else}
@@ -252,20 +253,7 @@
color: #ef4444;
}
.spinner {
width: 20px;
height: 20px;
border: 2px solid var(--color-gray-700);
border-top-color: var(--color-gray-400);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* ── Tab bar ──────────────────────────────────── */
@@ -31,6 +31,7 @@
"sidebar.remove": "Remove",
"sidebar.workspaceOptions": "Workspace options",
"sidebar.closeSidebar": "Close sidebar",
"sidebar.showMore": "Show more",
"bar.newFile": "New File",
"bar.newTerminal": "New Terminal",
+2 -2
View File
@@ -666,7 +666,7 @@ export function openPreviewTab(port: number, targetGroupId?: string): void {
}));
}
export function openChatTab(chatId?: string, targetGroupId?: string): void {
export function openChatTab(chatId?: string, targetGroupId?: string, label?: string): void {
const ws = get(currentWorkspace);
if (!ws) return;
@@ -686,7 +686,7 @@ export function openChatTab(chatId?: string, targetGroupId?: string): void {
const newTab: Tab = {
id: nextId(),
type: 'chat',
label: 'New Chat',
label: label || 'New Chat',
path: chatId || `new-${Date.now()}`
};
+91 -9
View File
@@ -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,80 @@ 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: async () => {
// Navigate to workspace page first if not already there
const wsPath = data.workspace;
if (wsPath && window.location.pathname !== '/') {
const { goto } = await import('$app/navigation');
await goto(`/?workspace=${encodeURIComponent(wsPath)}`);
setTimeout(() => openChatTab(chatId), 300);
} else {
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;
};
+8 -9
View File
@@ -3,7 +3,9 @@
import '@xterm/xterm/css/xterm.css';
import { onMount } from 'svelte';
import { page } from '$app/stores';
import Bar from '$lib/components/Bar.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import Sidebar from '$lib/components/Sidebar.svelte';
import ShortcutBar from '$lib/components/ShortcutBar.svelte';
import GitBar from '$lib/components/GitBar.svelte';
@@ -233,9 +235,7 @@
{#if authState === 'checking'}
<!-- Loading spinner while checking auth -->
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black">
<div
class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={20} />
</div>
{:else if authState === 'needs_setup' || authState === 'needs_login'}
<!-- Auth screen -->
@@ -253,7 +253,7 @@
<Sidebar />
<div id="main-col" class="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden">
{#if !$currentWorkspace}
{#if !$currentWorkspace && $page.url.pathname === '/'}
<Bar />
{/if}
<main class="relative flex-1 min-h-0 overflow-hidden">
@@ -279,16 +279,15 @@
<ChangelogModal />
{:else}
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black">
<div
class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={20} />
</div>
{/if}
<Toaster
position="bottom-center"
position="top-right"
theme="system"
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;'
'font-size: 12px; font-family: var(--font-sans); background: transparent; border: none; box-shadow: none; border-radius: 8px; padding: 0;'
}}
/>
+4 -4
View File
@@ -33,6 +33,7 @@
import GroupTabBar from '$lib/components/GroupTabBar.svelte';
import Icon from '$lib/components/Icon.svelte';
import SystemInfo from '$lib/components/SystemInfo.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
let showPicker = $state(false);
@@ -47,7 +48,7 @@
if (wsPath && wsPath !== lastLoadedPath) {
lastLoadedPath = wsPath;
loadWorkspace(wsPath);
} else if (!wsPath && lastLoadedPath !== null) {
} else if (!wsPath) {
lastLoadedPath = null;
currentWorkspace.set(null);
}
@@ -433,14 +434,13 @@
</div>
{/each}
<!-- Fallback content for non-persisted states -->
{#if !groupTab || groupTab.type === 'files'}
<FileBrowser />
{:else if groupTab.type === 'terminal' && !groupTab.sessionId}
<div class="flex items-center justify-center h-full">
<div
class="w-5 h-5 border-2 border-gray-800 border-t-gray-400 rounded-full animate-spin"
></div>
<Spinner size={20} />
</div>
{/if}
{/if}
@@ -0,0 +1,9 @@
<script lang="ts">
import AutomationsPanel from '$lib/components/automations/AutomationsPanel.svelte';
</script>
<svelte:head>
<title>Automations / cptr</title>
</svelte:head>
<AutomationsPanel />
@@ -0,0 +1,12 @@
<script lang="ts">
import { page } from '$app/stores';
import AutomationsPanel from '$lib/components/automations/AutomationsPanel.svelte';
const automationId = $derived($page.params.id);
</script>
<svelte:head>
<title>Automation / cptr</title>
</svelte:head>
<AutomationsPanel {automationId} />
Binary file not shown.
BIN
View File
Binary file not shown.
@@ -0,0 +1,62 @@
"""add_automations + rename chat/chat_message to plural
Revision ID: 0002
Revises: 0001
Create Date: 2026-06-09
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import sqlite
revision = '0002'
down_revision = '0001'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ── Rename existing tables to plural ──
op.rename_table('chat', 'chats')
op.rename_table('chat_message', 'chat_messages')
# ── Create automation tables ──
op.create_table('automations',
sa.Column('id', sa.Text(), nullable=False),
sa.Column('user_id', sa.Text(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('prompt', sa.Text(), nullable=False),
sa.Column('model_id', sa.Text(), nullable=False),
sa.Column('workspace', sa.Text(), nullable=False),
sa.Column('rrule', sa.Text(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('last_run_at', sa.BigInteger(), nullable=True),
sa.Column('next_run_at', sa.BigInteger(), nullable=True),
sa.Column('meta', sqlite.JSON(), nullable=True),
sa.Column('created_at', sa.BigInteger(), nullable=False),
sa.Column('updated_at', sa.BigInteger(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_automation_next_run', 'automations', ['next_run_at'], unique=False)
op.create_table('automation_runs',
sa.Column('id', sa.Text(), nullable=False),
sa.Column('automation_id', sa.Text(), nullable=False),
sa.Column('chat_id', sa.Text(), nullable=True),
sa.Column('status', sa.Text(), nullable=False),
sa.Column('error', sa.Text(), nullable=True),
sa.Column('created_at', sa.BigInteger(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_automation_run_aid_created', 'automation_runs', ['automation_id', 'created_at'], unique=False)
op.create_index(op.f('ix_automation_runs_automation_id'), 'automation_runs', ['automation_id'], unique=False)
def downgrade() -> None:
op.drop_index('ix_automation_next_run', table_name='automations')
op.drop_table('automations')
op.drop_index(op.f('ix_automation_runs_automation_id'), table_name='automation_runs')
op.drop_index('ix_automation_run_aid_created', table_name='automation_runs')
op.drop_table('automation_runs')
op.rename_table('chats', 'chat')
op.rename_table('chat_messages', 'chat_message')
+3
View File
@@ -6,6 +6,7 @@ from cptr.models.workspaces import Workspace
from cptr.models.config import Config
from cptr.models.files import File
from cptr.models.chats import Chat, ChatMessage
from cptr.models.automations import Automation, AutomationRun
__all__ = [
"Base",
@@ -17,4 +18,6 @@ __all__ = [
"File",
"Chat",
"ChatMessage",
"Automation",
"AutomationRun",
]
+294
View File
@@ -0,0 +1,294 @@
"""Automation and AutomationRun models with data-access class methods."""
from __future__ import annotations
import uuid
from sqlalchemy import BigInteger, Boolean, Column, Index, Text, select, update, delete, func
from sqlalchemy.dialects.sqlite import JSON
from cptr.models.base import Base
from cptr.utils.db import get_db
def _uuid() -> str:
return str(uuid.uuid4())
class Automation(Base):
"""A scheduled automation that runs a prompt on a recurring basis."""
__tablename__ = "automations"
id = Column(Text, primary_key=True, default=_uuid)
user_id = Column(Text, nullable=False)
name = Column(Text, nullable=False)
prompt = Column(Text, nullable=False)
model_id = Column(Text, nullable=False)
workspace = Column(Text, nullable=False)
rrule = Column(Text, nullable=False)
is_active = Column(Boolean, nullable=False, default=True)
last_run_at = Column(BigInteger, nullable=True)
next_run_at = Column(BigInteger, nullable=True)
meta = Column(JSON, nullable=True)
created_at = Column(BigInteger, nullable=False)
updated_at = Column(BigInteger, nullable=False)
__table_args__ = (Index("ix_automation_next_run", "next_run_at"),)
# ── Class methods ────────────────────────────────────────
@staticmethod
async def get_by_id(automation_id: str) -> Automation | None:
async with await get_db() as db:
result = await db.execute(select(Automation).where(Automation.id == automation_id))
return result.scalar_one_or_none()
@staticmethod
async def get_all_by_user(user_id: str) -> list[Automation]:
async with await get_db() as db:
result = await db.execute(
select(Automation)
.where(Automation.user_id == user_id)
.order_by(Automation.created_at.desc())
)
return list(result.scalars().all())
@staticmethod
async def get_by_workspace(
user_id: str,
workspace: str | None = None,
status: str | None = None,
query: str | None = None,
skip: int = 0,
limit: int = 30,
) -> tuple[list[Automation], int]:
"""List automations with filtering. Returns (items, total)."""
async with await get_db() as db:
stmt = select(Automation).where(
Automation.user_id == user_id,
)
if workspace:
stmt = stmt.where(Automation.workspace == workspace)
if status == "active":
stmt = stmt.where(Automation.is_active == True) # noqa: E712
elif status == "paused":
stmt = stmt.where(Automation.is_active == False) # noqa: E712
if query:
search = f"%{query}%"
stmt = stmt.where(Automation.name.ilike(search))
# Count
count_result = await db.execute(
select(func.count()).select_from(stmt.subquery())
)
total = count_result.scalar() or 0
# Page
stmt = stmt.order_by(Automation.created_at.desc()).offset(skip).limit(limit)
result = await db.execute(stmt)
return list(result.scalars().all()), total
@staticmethod
async def create(
user_id: str,
name: str,
prompt: str,
model_id: str,
workspace: str,
rrule: str,
next_run_at: int | None,
is_active: bool = True,
meta: dict | None = None,
created_at: int = 0,
) -> Automation:
async with await get_db() as db:
automation = Automation(
user_id=user_id,
name=name,
prompt=prompt,
model_id=model_id,
workspace=workspace,
rrule=rrule,
is_active=is_active,
next_run_at=next_run_at,
meta=meta,
created_at=created_at,
updated_at=created_at,
)
db.add(automation)
await db.commit()
await db.refresh(automation)
return automation
@staticmethod
async def update_by_id(automation_id: str, updated_at: int = 0, **kwargs) -> bool:
if not kwargs:
return False
kwargs["updated_at"] = updated_at
async with await get_db() as db:
result = await db.execute(
update(Automation).where(Automation.id == automation_id).values(**kwargs)
)
await db.commit()
return result.rowcount > 0
@staticmethod
async def toggle(automation_id: str, next_run_at: int | None, updated_at: int = 0) -> Automation | None:
async with await get_db() as db:
result = await db.execute(select(Automation).where(Automation.id == automation_id))
row = result.scalar_one_or_none()
if not row:
return None
row.is_active = not row.is_active
row.next_run_at = next_run_at if row.is_active else None
row.updated_at = updated_at
await db.commit()
await db.refresh(row)
return row
@staticmethod
async def delete(automation_id: str) -> bool:
async with await get_db() as db:
# Delete runs first
await db.execute(delete(AutomationRun).where(AutomationRun.automation_id == automation_id))
result = await db.execute(delete(Automation).where(Automation.id == automation_id))
await db.commit()
return result.rowcount > 0
@staticmethod
async def claim_due(now_ns: int, limit: int = 10) -> list[Automation]:
"""Atomically claim due automations for execution.
Selects rows where next_run_at <= now and is_active=True,
then advances next_run_at so they won't be double-claimed.
"""
async with await get_db() as db:
result = await db.execute(
select(Automation)
.where(
Automation.is_active == True, # noqa: E712
Automation.next_run_at <= now_ns,
)
.order_by(Automation.next_run_at)
.limit(limit)
)
rows = list(result.scalars().all())
from cptr.utils.automations import next_run_ns
for row in rows:
row.last_run_at = now_ns
row.next_run_at = next_run_ns(row.rrule)
await db.commit()
return rows
@staticmethod
async def count_by_user(user_id: str) -> int:
async with await get_db() as db:
result = await db.execute(
select(func.count()).select_from(Automation).filter_by(user_id=user_id)
)
return result.scalar() or 0
class AutomationRun(Base):
"""A single execution record for an automation."""
__tablename__ = "automation_runs"
id = Column(Text, primary_key=True, default=_uuid)
automation_id = Column(Text, nullable=False, index=True)
chat_id = Column(Text, nullable=True)
status = Column(Text, nullable=False) # "success" | "error"
error = Column(Text, nullable=True)
created_at = Column(BigInteger, nullable=False)
__table_args__ = (
Index("ix_automation_run_aid_created", "automation_id", "created_at"),
)
# ── Class methods ────────────────────────────────────────
@staticmethod
async def create(
automation_id: str,
status: str,
chat_id: str | None = None,
error: str | None = None,
created_at: int = 0,
) -> AutomationRun:
async with await get_db() as db:
run = AutomationRun(
automation_id=automation_id,
chat_id=chat_id,
status=status,
error=error,
created_at=created_at,
)
db.add(run)
await db.commit()
await db.refresh(run)
return run
@staticmethod
async def get_latest(automation_id: str) -> AutomationRun | None:
async with await get_db() as db:
result = await db.execute(
select(AutomationRun)
.where(AutomationRun.automation_id == automation_id)
.order_by(AutomationRun.created_at.desc())
.limit(1)
)
return result.scalar_one_or_none()
@staticmethod
async def get_latest_batch(automation_ids: list[str]) -> dict[str, AutomationRun]:
"""Fetch the latest run for each automation in a single query."""
if not automation_ids:
return {}
async with await get_db() as db:
subq = (
select(
AutomationRun.automation_id,
func.max(AutomationRun.created_at).label("max_created"),
)
.where(AutomationRun.automation_id.in_(automation_ids))
.group_by(AutomationRun.automation_id)
.subquery()
)
result = await db.execute(
select(AutomationRun).join(
subq,
(AutomationRun.automation_id == subq.c.automation_id)
& (AutomationRun.created_at == subq.c.max_created),
)
)
rows = result.scalars().all()
return {row.automation_id: row for row in rows}
@staticmethod
async def get_by_automation(
automation_id: str,
skip: int = 0,
limit: int = 50,
) -> list[AutomationRun]:
async with await get_db() as db:
result = await db.execute(
select(AutomationRun)
.where(AutomationRun.automation_id == automation_id)
.order_by(AutomationRun.created_at.desc())
.offset(skip)
.limit(limit)
)
return list(result.scalars().all())
@staticmethod
async def delete_by_automation(automation_id: str) -> int:
async with await get_db() as db:
result = await db.execute(
delete(AutomationRun).where(AutomationRun.automation_id == automation_id)
)
await db.commit()
return result.rowcount
+3 -3
View File
@@ -18,7 +18,7 @@ def _uuid() -> str:
class Chat(Base):
"""A chat conversation. Workspace association lives in the filesystem."""
__tablename__ = "chat"
__tablename__ = "chats"
id = Column(Text, primary_key=True, default=_uuid)
user_id = Column(Text, ForeignKey("users.id"), nullable=False)
@@ -121,10 +121,10 @@ class Chat(Base):
class ChatMessage(Base):
"""A single message in a chat conversation."""
__tablename__ = "chat_message"
__tablename__ = "chat_messages"
id = Column(Text, primary_key=True, default=_uuid)
chat_id = Column(Text, ForeignKey("chat.id", ondelete="CASCADE"), nullable=False, index=True)
chat_id = Column(Text, ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, index=True)
parent_id = Column(Text, nullable=True)
role = Column(Text, nullable=False) # "user" | "assistant"
content = Column(Text, nullable=False) # Flattened text content
+13
View File
@@ -56,3 +56,16 @@ class Config(Base):
else:
db.add(Config(key=key, value=value))
await db.commit()
# Sync all config to config.toml so file mirrors DB
try:
all_config = await Config.get_all()
from cptr.utils.config import sync_config_to_toml
sync_config_to_toml(all_config)
except Exception:
import logging
logging.getLogger(__name__).warning(
"Failed to sync config to TOML", exc_info=True
)
+2
View File
@@ -2,6 +2,7 @@
from cptr.routers.admin import router as admin_router
from cptr.routers.auth import router as auth_router
from cptr.routers.automations import router as automations_router
from cptr.routers.chat import router as chat_router
from cptr.routers.events import router as events_router
from cptr.routers.files import router as files_router
@@ -14,6 +15,7 @@ from cptr.routers.workspace import router as workspace_router
__all__ = [
"admin_router",
"auth_router",
"automations_router",
"chat_router",
"events_router",
"files_router",
+348
View File
@@ -0,0 +1,348 @@
"""Automations router: CRUD + run for scheduled automations."""
from __future__ import annotations
import asyncio
import hashlib
import logging
import secrets
import time
from typing import Optional
from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel
from cptr.models.automations import Automation, AutomationRun
from cptr.utils.automations import next_n_runs_ns, next_run_ns, validate_rrule
from cptr.utils.config import check_access, now_ms
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/automations", tags=["automations"])
COOKIE_NAME = "cptr_session"
PAGE_SIZE = 30
def _get_user(request: Request) -> str:
"""Extract user_id from cookie, raise 401 if not authenticated."""
token = request.cookies.get(COOKIE_NAME)
client_host = request.client.host if request.client else "127.0.0.1"
auth = check_access(client_host=client_host, jwt_token=token)
if not auth or not auth.user_id:
raise HTTPException(401, "authentication required")
return auth.user_id
def _hash_token(token: str) -> str:
"""SHA-256 hash a webhook token."""
return hashlib.sha256(token.encode()).hexdigest()
def _automation_dict(a: Automation, last_run: AutomationRun | None = None, next_runs: list[int] | None = None, webhook_url: str | None = None) -> dict:
"""Serialize an Automation to a response dict."""
meta = a.meta or {}
has_webhook = bool(meta.get("webhook_token"))
return {
"id": a.id,
"user_id": a.user_id,
"name": a.name,
"prompt": a.prompt,
"model_id": a.model_id,
"workspace": a.workspace,
"rrule": a.rrule,
"is_active": a.is_active,
"last_run_at": a.last_run_at,
"next_run_at": a.next_run_at,
"meta": a.meta,
"created_at": a.created_at,
"updated_at": a.updated_at,
"last_run": _run_dict(last_run) if last_run else None,
"next_runs": next_runs,
"has_webhook": has_webhook,
"webhook_url": webhook_url,
}
def _run_dict(r: AutomationRun) -> dict:
return {
"id": r.id,
"automation_id": r.automation_id,
"chat_id": r.chat_id,
"status": r.status,
"error": r.error,
"created_at": r.created_at,
}
# ── List automations ────────────────────────────────────────
@router.get("")
async def list_automations(
request: Request,
workspace: Optional[str] = Query(None, description="Workspace path (omit for all)"),
query: Optional[str] = None,
status: Optional[str] = None,
page: int = Query(1, ge=1),
):
user_id = _get_user(request)
skip = (page - 1) * PAGE_SIZE
items, total = await Automation.get_by_workspace(
user_id=user_id,
workspace=workspace,
status=status,
query=query,
skip=skip,
limit=PAGE_SIZE,
)
# Batch-fetch latest runs
ids = [a.id for a in items]
latest_runs = await AutomationRun.get_latest_batch(ids) if ids else {}
return {
"items": [
_automation_dict(a, last_run=latest_runs.get(a.id))
for a in items
],
"total": total,
}
# ── Create automation ───────────────────────────────────────
class CreateAutomationRequest(BaseModel):
name: str
prompt: str
model_id: str
workspace: str
rrule: str
is_active: bool = True
@router.post("")
async def create_automation(body: CreateAutomationRequest, request: Request):
user_id = _get_user(request)
try:
validate_rrule(body.rrule)
except ValueError as e:
raise HTTPException(400, str(e))
nxt = next_run_ns(body.rrule)
now = now_ms()
automation = await Automation.create(
user_id=user_id,
name=body.name.strip(),
prompt=body.prompt.strip(),
model_id=body.model_id.strip(),
workspace=body.workspace,
rrule=body.rrule,
next_run_at=nxt,
is_active=body.is_active,
created_at=now,
)
return _automation_dict(automation, next_runs=next_n_runs_ns(body.rrule))
# ── Get automation by ID ────────────────────────────────────
@router.get("/{automation_id}")
async def get_automation(automation_id: str, request: Request):
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
last_run = await AutomationRun.get_latest(automation_id)
return _automation_dict(
automation,
last_run=last_run,
next_runs=next_n_runs_ns(automation.rrule),
)
# ── Update automation ───────────────────────────────────────
class UpdateAutomationRequest(BaseModel):
name: str
prompt: str
model_id: str
workspace: str
rrule: str
is_active: bool = True
@router.post("/{automation_id}")
async def update_automation(automation_id: str, body: UpdateAutomationRequest, request: Request):
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
try:
validate_rrule(body.rrule)
except ValueError as e:
raise HTTPException(400, str(e))
nxt = next_run_ns(body.rrule)
now = now_ms()
await Automation.update_by_id(
automation_id,
updated_at=now,
name=body.name.strip(),
prompt=body.prompt.strip(),
model_id=body.model_id.strip(),
workspace=body.workspace,
rrule=body.rrule,
is_active=body.is_active,
next_run_at=nxt,
)
updated = await Automation.get_by_id(automation_id)
last_run = await AutomationRun.get_latest(automation_id)
return _automation_dict(updated, last_run=last_run, next_runs=next_n_runs_ns(body.rrule))
# ── Toggle active/paused ───────────────────────────────────
@router.post("/{automation_id}/toggle")
async def toggle_automation(automation_id: str, request: Request):
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
nxt = next_run_ns(automation.rrule) if not automation.is_active else None
toggled = await Automation.toggle(automation_id, nxt, now_ms())
return _automation_dict(toggled)
# ── Run now ─────────────────────────────────────────────────
@router.post("/{automation_id}/run")
async def run_automation_now(
automation_id: str,
request: Request,
token: Optional[str] = Query(None, description="Webhook token for unauthenticated access"),
):
if token:
# Webhook path: validate token, no session required
automation = await Automation.get_by_id(automation_id)
if not automation:
raise HTTPException(404, "automation not found")
meta = automation.meta or {}
expected_hash = meta.get("webhook_token", "")
if not expected_hash or _hash_token(token) != expected_hash:
raise HTTPException(403, "invalid token")
if not automation.is_active:
raise HTTPException(409, "automation is paused")
# Inject webhook payload into prompt if request has a body
webhook_payload = None
try:
body = await request.json()
if body:
import json
webhook_payload = json.dumps(body, indent=2)
except Exception:
pass
else:
# Normal path: require session auth
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
webhook_payload = None
from cptr.utils.automations import execute_automation
asyncio.create_task(execute_automation(automation, webhook_payload=webhook_payload))
return _automation_dict(automation)
# ── Delete ──────────────────────────────────────────────────
@router.delete("/{automation_id}")
async def delete_automation(automation_id: str, request: Request):
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
await Automation.delete(automation_id)
return {"ok": True}
# ── Execution history ───────────────────────────────────────
@router.get("/{automation_id}/runs")
async def get_automation_runs(
automation_id: str,
request: Request,
skip: int = 0,
limit: int = 50,
):
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
runs = await AutomationRun.get_by_automation(automation_id, skip=skip, limit=limit)
return [_run_dict(r) for r in runs]
# ── Webhook management ──────────────────────────────────────
@router.post("/{automation_id}/webhook")
async def generate_webhook(automation_id: str, request: Request):
"""Generate or regenerate a webhook token for this automation.
Returns the plaintext webhook URL once. The token is stored as a
SHA-256 hash — the URL cannot be recovered after this response.
"""
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
plaintext = f"wh_{secrets.token_hex(20)}"
meta = dict(automation.meta or {})
meta["webhook_token"] = _hash_token(plaintext)
await Automation.update_by_id(automation_id, updated_at=now_ms(), meta=meta)
base = str(request.base_url).rstrip("/")
webhook_url = f"{base}/api/automations/{automation_id}/run?token={plaintext}"
updated = await Automation.get_by_id(automation_id)
return _automation_dict(updated, webhook_url=webhook_url)
@router.delete("/{automation_id}/webhook")
async def revoke_webhook(automation_id: str, request: Request):
"""Revoke the webhook token for this automation."""
user_id = _get_user(request)
automation = await Automation.get_by_id(automation_id)
if not automation or automation.user_id != user_id:
raise HTTPException(404, "automation not found")
meta = dict(automation.meta or {})
meta.pop("webhook_token", None)
await Automation.update_by_id(automation_id, updated_at=now_ms(), meta=meta)
updated = await Automation.get_by_id(automation_id)
return _automation_dict(updated)
+27 -2
View File
@@ -99,6 +99,11 @@ async def list_chats(
chats = await Chat.get_by_ids(chat_ids)
chat_map = {c.id: c for c in chats}
# Detect which chats have a running task (in-memory check, no DB hit)
from cptr.utils.chat_task import get_active_chat_ids
active_ids = get_active_chat_ids()
# Build response: only include chats owned by this user
result = []
for entry in chat_entries:
@@ -114,6 +119,7 @@ async def list_chats(
"current_message_id": chat.current_message_id,
"created_at": chat.created_at,
"updated_at": chat.updated_at,
"is_active": chat.id in active_ids,
}
)
@@ -347,7 +353,7 @@ async def send_message(body: SendMessageRequest, request: Request):
meta={"workspace": body.workspace, "params": body.params},
created_at=now_ms(),
)
# Ensure .cptr/chats/ dir exists (export will write the full JSON)
# Ensure .cptr/chats/ dir exists
chats_dir = Path(body.workspace) / ".cptr" / "chats"
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
@@ -410,7 +416,12 @@ async def send_message(body: SendMessageRequest, request: Request):
# Update chat pointer to new leaf
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
# Start background task (export_chat_to_file runs after task completes)
# Export JSON immediately so list_chats discovers it right away
from cptr.utils.chat_export import export_chat_to_file
await export_chat_to_file(chat.id)
# Start background task (export_chat_to_file also runs after task completes)
from cptr.utils.chat_task import start_task
start_task(
@@ -485,6 +496,20 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
"output": result,
}
)
# Emit artifact card if the tool produced an artifact
from cptr.utils.chat_task import build_artifact_item
artifact_item = build_artifact_item(call["name"], call.get("arguments", {}), result)
if artifact_item:
output.append(artifact_item)
from cptr.socket.main import emit_to_user
await emit_to_user(
user_id,
{"chat_id": chat_id, "message_id": message_id, "output": artifact_item},
)
await ChatMessage.update(message_id, output=output, done=False)
# Resolve connection and continue
+230
View File
@@ -0,0 +1,230 @@
"""Automation utilities: RRULE helpers, scheduler worker, execution.
The scheduler_worker_loop polls the DB for due automations and executes them
by creating a real chat and calling start_task() — the same agentic loop
that runs for interactive chats.
Environment:
AUTOMATION_POLL_INTERVAL – seconds between polls (default: 10)
"""
from __future__ import annotations
import asyncio
import logging
import random
import time
from datetime import datetime
from typing import Optional
from dateutil.rrule import rrulestr
logger = logging.getLogger(__name__)
####################
# RRULE Helpers
####################
def _parse_rule(s: str):
"""Parse RRULE with clock-aligned DTSTART for sub-daily frequencies.
MINUTELY/HOURLY rules use a fixed epoch DTSTART (2000-01-01 00:00)
so intervals snap to clock boundaries (e.g. every 5min = :00, :05, :10).
"""
raw = s.replace("RRULE:", "")
parts = dict(p.split("=", 1) for p in raw.split(";") if "=" in p)
freq = parts.get("FREQ", "")
if freq in ("MINUTELY", "HOURLY"):
epoch = datetime(2000, 1, 1, 0, 0, 0)
return rrulestr(s, dtstart=epoch, ignoretz=True)
return rrulestr(s, ignoretz=True)
def validate_rrule(s: str) -> None:
"""Raise ValueError if the RRULE is malformed or exhausted."""
try:
rule = _parse_rule(s)
except Exception as e:
raise ValueError(f"Invalid RRULE: {e}")
now = datetime.now()
if rule.after(now) is None:
raise ValueError("RRULE has no future occurrences")
def next_run_ns(s: str) -> Optional[int]:
"""Next occurrence as epoch nanoseconds."""
now = datetime.now()
dt = _parse_rule(s).after(now)
if dt is None:
return None
return int(dt.timestamp() * 1_000_000_000)
def next_n_runs_ns(s: str, n: int = 5) -> list[int]:
"""Compute next N occurrences for UI preview."""
rule = _parse_rule(s)
result = []
dt = datetime.now()
for _ in range(n):
dt = rule.after(dt)
if not dt:
break
result.append(int(dt.timestamp() * 1_000_000_000))
return result
####################
# Scheduler Worker
####################
async def scheduler_worker_loop(app) -> None:
"""Background scheduler for automation execution.
Runs on startup, polls every AUTOMATION_POLL_INTERVAL seconds.
Claims due automations and dispatches them as asyncio tasks.
"""
from cptr.env import AUTOMATION_POLL_INTERVAL
logger.info("Automation scheduler started (poll interval: %ds)", AUTOMATION_POLL_INTERVAL)
while True:
try:
from cptr.models.automations import Automation
batch = await Automation.claim_due(int(time.time_ns()), limit=10)
if batch:
logger.info("Claimed %d due automation(s)", len(batch))
for automation in batch:
asyncio.create_task(execute_automation(automation))
except Exception:
logger.exception("Scheduler worker error")
await asyncio.sleep(AUTOMATION_POLL_INTERVAL + random.uniform(0, 2))
####################
# Execute
####################
async def execute_automation(automation, webhook_payload: str | None = None) -> None:
"""Execute an automation by creating a chat and calling start_task().
Creates a real chat + messages, then uses the same agentic loop
as interactive chats, giving automations full tool-calling capabilities.
If webhook_payload is provided, {{webhook_payload}} in the prompt is
replaced with the payload content.
"""
from cptr.models import Chat, ChatMessage
from cptr.models.automations import AutomationRun
from cptr.utils.config import now_ms
from cptr.socket.main import emit_to_user
try:
workspace = automation.workspace
model_id = automation.model_id
prompt = automation.prompt
if webhook_payload:
prompt = prompt.replace("{{webhook_payload}}", webhook_payload)
# Create the chat
chat = await Chat.create(
user_id=automation.user_id,
title=automation.name,
meta={
"workspace": workspace,
"automation_id": automation.id,
"params": {},
},
created_at=now_ms(),
)
# Create user message
user_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
content=prompt,
created_at=now_ms(),
)
# Create assistant placeholder
assistant_msg = await ChatMessage.create(
chat_id=chat.id,
role="assistant",
content="",
parent_id=user_msg.id,
model=model_id,
done=False,
created_at=now_ms(),
)
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
# Write .cptr/chats/{id}.json marker so list_chats discovers it
from pathlib import Path
chats_dir = Path(workspace) / ".cptr" / "chats"
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
# Resolve connection for model
from cptr.routers.chat import _resolve_connection
connection, bare_model = await _resolve_connection(model_id)
# Start the agentic loop (same as interactive chat)
from cptr.utils.chat_task import start_task
start_task(
message_id=assistant_msg.id,
chat_id=chat.id,
user_id=automation.user_id,
connection=connection,
workspace=workspace,
model=bare_model,
)
# Notify frontend
await emit_to_user(
automation.user_id,
{
"type": "automation:result",
"automation_id": automation.id,
"name": automation.name,
"chat_id": chat.id,
"status": "success",
},
)
# Record successful run
await AutomationRun.create(
automation_id=automation.id,
status="success",
chat_id=chat.id,
created_at=int(time.time_ns()),
)
logger.info(
"Automation '%s' (%s) executed → chat %s",
automation.name,
automation.id[:8],
chat.id[:8],
)
except Exception as e:
logger.exception("Automation %s failed", automation.id)
try:
await AutomationRun.create(
automation_id=automation.id,
status="error",
error=str(e)[:4000],
created_at=int(time.time_ns()),
)
except Exception:
logger.exception("Failed to record automation run error")
+63 -22
View File
@@ -81,6 +81,11 @@ def get_live_state(message_id: str) -> dict | None:
return _task_state.get(message_id)
def get_active_chat_ids() -> set[str]:
"""Return the set of chat_ids that currently have a running task."""
return {cid for mid, cid in _task_chat.items() if mid in _tasks and not _tasks[mid].done()}
# ── Queue processing ────────────────────────────────────────
@@ -541,6 +546,32 @@ def _append_tool_to_messages(messages: list[dict], event: dict, result: str, pro
# ── Connection resolution ───────────────────────────────────
def build_artifact_item(tool_name: str, arguments: dict, result: str) -> dict | None:
"""Build an artifact output item if the tool call produced an artifact.
Works for both create_artifact and create_file with artifact_type.
Returns None if no artifact card should be shown.
"""
artifact_type = arguments.get("artifact_type", "")
if tool_name == "create_artifact":
artifact_type = artifact_type or "implementation_plan"
if not artifact_type:
return None
try:
meta = json.loads(result)
except (json.JSONDecodeError, TypeError):
meta = {}
return {
"type": "artifact",
"artifact_type": artifact_type,
"title": meta.get("title") or arguments.get("title") or artifact_type.replace("_", " ").title(),
"content": arguments.get("content", ""),
"path": meta.get("path") or arguments.get("path", ""),
}
def _default_base_url(provider: str) -> str:
return {
"anthropic": "https://api.anthropic.com/v1",
@@ -566,6 +597,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 ""
@@ -698,23 +740,8 @@ async def run_chat_task(
_sync_state()
# Artifact UI card: detect create_artifact or create_file with artifact_type
args = event["arguments"]
artifact_type = args.get("artifact_type", "")
if name == "create_artifact":
artifact_type = artifact_type or "implementation_plan"
if artifact_type:
# Parse metadata from tool result or build from args
try:
meta = json.loads(result)
except (json.JSONDecodeError, TypeError):
meta = {}
artifact_item = {
"type": "artifact",
"artifact_type": artifact_type,
"title": meta.get("title") or args.get("title") or artifact_type.replace("_", " ").title(),
"content": args.get("content", ""),
"path": meta.get("path", ""),
}
artifact_item = build_artifact_item(name, event["arguments"], result)
if artifact_item:
output_items.append(artifact_item)
await emit(output=artifact_item)
_sync_state()
@@ -764,7 +791,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":
@@ -789,7 +816,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
@@ -801,13 +828,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()
@@ -819,7 +846,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)
@@ -853,6 +880,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)
+76 -4
View File
@@ -84,10 +84,17 @@ def _parse_simple_toml(text: str) -> dict:
elif "=" in line and current_section:
key, _, value = line.partition("=")
key = key.strip()
# Handle quoted keys (e.g. "auth.signup_enabled")
if key.startswith('"') and key.endswith('"'):
key = key[1:-1]
elif key.startswith("'") and key.endswith("'"):
key = key[1:-1]
value = value.strip()
# Strip quotes
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
# Unescape
value = value.replace('\\"', '"').replace("\\\\", "\\")
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
elif value == "true":
@@ -114,15 +121,21 @@ def save_config(config: dict):
if isinstance(values, dict):
lines.append(f"[{section}]")
for k, v in values.items():
# Quote keys that contain dots (e.g. "auth.signup_enabled")
key_str = f'"{k}"' if "." in k else k
if isinstance(v, str):
lines.append(f'{k} = "{v}"')
# Escape backslashes and quotes in string values
escaped = v.replace("\\", "\\\\").replace('"', '\\"')
lines.append(f'{key_str} = "{escaped}"')
elif isinstance(v, bool):
lines.append(f"{k} = {'true' if v else 'false'}")
lines.append(f"{key_str} = {'true' if v else 'false'}")
elif isinstance(v, (int, float)):
lines.append(f"{key_str} = {v}")
elif isinstance(v, list):
items = ", ".join(f'"{i}"' if isinstance(i, str) else str(i) for i in v)
lines.append(f"{k} = [{items}]")
lines.append(f"{key_str} = [{items}]")
else:
lines.append(f"{k} = {v}")
lines.append(f"{key_str} = {v}")
lines.append("")
CONFIG_FILE.write_text("\n".join(lines))
_config_cache = config
@@ -133,6 +146,65 @@ def invalidate_config_cache():
_config_cache = None
# ── App Config ↔ TOML sync ──────────────────────────────────
def sync_config_to_toml(app_config: dict) -> None:
"""Sync app config (DB key-value pairs) into the [app_config] section of config.toml.
Preserves existing server-level sections ([server], [auth], etc.).
Complex values (lists, dicts) are JSON-encoded as strings.
Called after every Config.upsert() so the file mirrors the DB.
"""
import json as _json
config = load_config()
invalidate_config_cache() # Force re-read next time
# Build the app_config section
toml_section: dict = {}
for key, value in app_config.items():
if isinstance(value, (list, dict)):
# Store complex types as JSON strings
toml_section[key] = _json.dumps(value, ensure_ascii=False)
else:
toml_section[key] = value
config["app_config"] = toml_section
save_config(config)
def load_app_config_from_toml() -> dict:
"""Read the [app_config] section from config.toml.
Returns {key: value} dict with JSON strings decoded back to Python objects.
Called on startup to seed the DB config table from the file.
"""
import json as _json
invalidate_config_cache() # Force fresh read from disk
config = load_config()
raw = config.get("app_config", {})
if not isinstance(raw, dict):
return {}
result: dict = {}
for key, value in raw.items():
if isinstance(value, str):
# Try to decode JSON strings back to complex types
try:
decoded = _json.loads(value)
if isinstance(decoded, (list, dict)):
result[key] = decoded
else:
result[key] = value
except (ValueError, _json.JSONDecodeError):
result[key] = value
else:
result[key] = value
return result
# ── Password ─────────────────────────────────────────────────
+37
View File
@@ -48,3 +48,40 @@ async def init_db():
alembic_cfg.set_main_option("script_location", str(Path(__file__).parent.parent / "migrations"))
alembic_cfg.set_main_option("sqlalchemy.url", f"sqlite:///{DB_FILE}")
command.upgrade(alembic_cfg, "head")
# Seed DB config from config.toml (file is source of truth on startup)
await _seed_config_from_toml()
async def _seed_config_from_toml():
"""Load [app_config] from config.toml and upsert into the DB config table.
Called on every startup. The file always wins — this ensures config
survives DB loss and allows hand-editing the TOML file.
"""
import logging
logger = logging.getLogger(__name__)
try:
from cptr.utils.config import load_app_config_from_toml
app_config = load_app_config_from_toml()
if not app_config:
return
# Direct DB upsert (not via Config.upsert to avoid re-syncing back to file)
from cptr.models.config import Config as ConfigModel
async with get_session_factory()() as db:
for key, value in app_config.items():
existing = await db.get(ConfigModel, key)
if existing:
existing.value = value
else:
db.add(ConfigModel(key=key, value=value))
await db.commit()
logger.info("Loaded %d config key(s) from config.toml", len(app_config))
except Exception:
logger.warning("Failed to seed config from config.toml", exc_info=True)
+246 -2
View File
@@ -323,9 +323,28 @@ async def create_file(
:param overwrite: Set to true to overwrite an existing file.
:param artifact_type: Set to 'implementation_plan' to present a plan for user review before coding.
"""
# Artifact-only: skip workspace file write
# Artifact-only: save to .cptr/artifacts/ (same location as create_artifact)
if artifact_type and not path:
return f"Artifact created ({len(content)} bytes)"
from datetime import datetime, timezone
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
artifact_dir = Path(workspace) / ".cptr" / "artifacts"
artifact_dir.mkdir(parents=True, exist_ok=True)
artifact_path = artifact_dir / f"{ts}_{artifact_type}.md"
def _write_artifact():
artifact_path.write_text(content)
await asyncio.to_thread(_write_artifact)
rel_path = str(artifact_path.relative_to(Path(workspace)))
display_title = artifact_type.replace("_", " ").title()
return json.dumps({
"artifact_type": artifact_type,
"title": display_title,
"path": rel_path,
"bytes": len(content),
})
if not path:
return "Error: path is required when artifact_type is not set."
@@ -671,6 +690,226 @@ def _resolve_path(path: str, workspace: str) -> Path:
return full
async def create_automation(
name: str,
prompt: str,
rrule: str,
model_id: str = "",
*,
workspace: str,
) -> str:
"""Create a scheduled automation that runs a prompt on a recurring or one-time schedule.
The rrule parameter must be a valid iCalendar RRULE string. Common examples:
- Every day at 9am: "DTSTART:20250101T090000\\nRRULE:FREQ=DAILY"
- Every Monday at 8am: "DTSTART:20250106T080000\\nRRULE:FREQ=WEEKLY;BYDAY=MO"
- Every hour: "RRULE:FREQ=HOURLY;INTERVAL=1"
- Once at a specific time: "DTSTART:20250415T140000\\nRRULE:FREQ=DAILY;COUNT=1"
- First day of every month: "DTSTART:20250101T090000\\nRRULE:FREQ=MONTHLY;BYMONTHDAY=1"
:param name: A short descriptive name for the automation.
:param prompt: The instructions/prompt to execute on each run.
:param rrule: An iCalendar RRULE string defining the schedule.
:param model_id: Model to use (optional, defaults to the current chat model).
"""
try:
import time
from cptr.models.automations import Automation as AutomationModel
from cptr.utils.automations import next_run_ns, next_n_runs_ns, validate_rrule
# Validate RRULE
try:
validate_rrule(rrule)
except ValueError as e:
return json.dumps({"error": f"Invalid schedule: {e}"})
# If no model_id provided, try to detect from admin config
if not model_id:
try:
from cptr.models.config import AdminConfig
cfg = await AdminConfig.get()
model_id = (cfg.meta or {}).get("default_model", "") if cfg else ""
except Exception:
pass
if not model_id:
return json.dumps({"error": "Could not detect model. Please provide model_id."})
now_ns = int(time.time() * 1_000_000_000)
nxt = next_run_ns(rrule)
automation = await AutomationModel.create(
user_id="default",
name=name,
prompt=prompt,
model_id=model_id,
workspace=workspace,
rrule=rrule,
next_run_at=nxt,
is_active=True,
created_at=now_ns,
)
return json.dumps({
"status": "success",
"id": automation.id,
"name": automation.name,
"model_id": automation.model_id,
"is_active": automation.is_active,
"next_runs": next_n_runs_ns(rrule),
})
except Exception as e:
return json.dumps({"error": str(e)})
async def list_automations(
status: str = "",
count: int = 10,
*,
workspace: str,
) -> str:
"""List scheduled automations for the current workspace.
:param status: Filter by status: "active", "paused", or empty for all.
:param count: Maximum number of automations to return (default: 10).
"""
try:
from cptr.models.automations import Automation as AutomationModel
from cptr.utils.automations import next_n_runs_ns
items, total = await AutomationModel.get_by_workspace(
user_id="default",
workspace=workspace or None,
status=status or None,
limit=count,
)
automations = []
for item in items:
automations.append({
"id": item.id,
"name": item.name,
"prompt_snippet": item.prompt[:100] + ("..." if len(item.prompt) > 100 else ""),
"model_id": item.model_id,
"rrule": item.rrule,
"is_active": item.is_active,
"last_run_at": item.last_run_at,
"next_runs": next_n_runs_ns(item.rrule),
})
return json.dumps({"automations": automations, "total": total})
except Exception as e:
return json.dumps({"error": str(e)})
async def update_automation(
automation_id: str,
name: str = "",
prompt: str = "",
rrule: str = "",
model_id: str = "",
*,
workspace: str,
) -> str:
"""Update an existing automation. Only provided fields are changed.
:param automation_id: The ID of the automation to update.
:param name: New name (optional).
:param prompt: New prompt/instructions (optional).
:param rrule: New iCalendar RRULE schedule string (optional).
:param model_id: New model ID (optional).
"""
try:
import time
from cptr.models.automations import Automation as AutomationModel
from cptr.utils.automations import next_run_ns, next_n_runs_ns, validate_rrule
automation = await AutomationModel.get_by_id(automation_id)
if not automation:
return json.dumps({"error": "Automation not found"})
kwargs = {}
if name:
kwargs["name"] = name
if prompt:
kwargs["prompt"] = prompt
if model_id:
kwargs["model_id"] = model_id
if rrule:
try:
validate_rrule(rrule)
except ValueError as e:
return json.dumps({"error": f"Invalid schedule: {e}"})
kwargs["rrule"] = rrule
kwargs["next_run_at"] = next_run_ns(rrule)
if not kwargs:
return json.dumps({"error": "No fields to update"})
now_ns = int(time.time() * 1_000_000_000)
success = await AutomationModel.update_by_id(automation_id, updated_at=now_ns, **kwargs)
if not success:
return json.dumps({"error": "Failed to update automation"})
final_rrule = rrule or automation.rrule
return json.dumps({
"status": "success",
"id": automation_id,
"updated_fields": list(kwargs.keys()),
"next_runs": next_n_runs_ns(final_rrule),
})
except Exception as e:
return json.dumps({"error": str(e)})
async def toggle_automation(
automation_id: str,
*,
workspace: str,
) -> str:
"""Pause or resume a scheduled automation. If active, it will be paused. If paused, it will be resumed.
:param automation_id: The ID of the automation to toggle.
"""
try:
from cptr.models.automations import Automation as AutomationModel
from cptr.utils.automations import next_run_ns
automation = await AutomationModel.get_by_id(automation_id)
if not automation:
return json.dumps({"error": "Automation not found"})
nxt = next_run_ns(automation.rrule) if not automation.is_active else None
toggled = await AutomationModel.toggle(automation_id, next_run_at=nxt)
if not toggled:
return json.dumps({"error": "Failed to toggle automation"})
return json.dumps({
"status": "success",
"id": toggled.id,
"name": toggled.name,
"is_active": toggled.is_active,
})
except Exception as e:
return json.dumps({"error": str(e)})
async def delete_automation(
automation_id: str,
*,
workspace: str,
) -> str:
"""Delete a scheduled automation and all its run history.
:param automation_id: The ID of the automation to delete.
"""
try:
from cptr.models.automations import Automation as AutomationModel
automation = await AutomationModel.get_by_id(automation_id)
if not automation:
return json.dumps({"error": "Automation not found"})
name = automation.name
success = await AutomationModel.delete(automation_id)
if not success:
return json.dumps({"error": "Failed to delete automation"})
return json.dumps({"status": "success", "message": f'Automation "{name}" deleted'})
except Exception as e:
return json.dumps({"error": str(e)})
# ── Registry ────────────────────────────────────────────────
TOOLS: dict[str, dict] = {
@@ -681,6 +920,7 @@ TOOLS: dict[str, dict] = {
"check_task": {"fn": check_task, "auto": True},
"web_search": {"fn": web_search, "auto": True},
"read_url": {"fn": read_url, "auto": True},
"list_automations": {"fn": list_automations, "auto": True},
# Write / mutate (require approval unless auto_approve_all)
"create_file": {"fn": create_file, "auto": False},
"edit_file": {"fn": edit_file, "auto": False},
@@ -688,6 +928,10 @@ TOOLS: dict[str, dict] = {
"write_file": {"fn": write_file, "auto": False},
"run_command": {"fn": run_command, "auto": False},
"kill_task": {"fn": kill_task, "auto": False},
"create_automation": {"fn": create_automation, "auto": False},
"update_automation": {"fn": update_automation, "auto": False},
"toggle_automation": {"fn": toggle_automation, "auto": False},
"delete_automation": {"fn": delete_automation, "auto": False},
}
+72
View File
@@ -0,0 +1,72 @@
"""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
+2 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.1.9"
version = "0.2.0"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
@@ -17,6 +17,7 @@ dependencies = [
"PyJWT>=2.8",
"cryptography>=42.0",
"python-socketio[asgi]>=5.11",
"python-dateutil>=2.8",
"pywinpty>=2.0; sys_platform == 'win32'",
]
Generated
+24 -1
View File
@@ -338,7 +338,7 @@ wheels = [
[[package]]
name = "cptr"
version = "0.1.0"
version = "0.1.9"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },
@@ -353,6 +353,7 @@ dependencies = [
{ name = "fastapi", version = "0.136.3", source = { registry = "https://pypi.org/simple" }, extra = ["standard"], marker = "python_full_version >= '3.10'" },
{ name = "httpx" },
{ name = "pyjwt" },
{ name = "python-dateutil" },
{ name = "python-socketio" },
{ name = "pywinpty", marker = "sys_platform == 'win32'" },
{ name = "sqlalchemy", extra = ["asyncio"] },
@@ -379,6 +380,7 @@ requires-dist = [
{ name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" },
{ name = "httpx", specifier = ">=0.28.1" },
{ name = "pyjwt", specifier = ">=2.8" },
{ name = "python-dateutil", specifier = ">=2.8" },
{ name = "python-pam", marker = "extra == 'pam'", specifier = ">=2.0" },
{ name = "python-socketio", extras = ["asgi"], specifier = ">=5.11" },
{ name = "pywinpty", marker = "sys_platform == 'win32'", specifier = ">=2.0" },
@@ -1531,6 +1533,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274 },
]
[[package]]
name = "python-dateutil"
version = "2.9.0.post0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "six" },
]
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892 },
]
[[package]]
name = "python-dotenv"
version = "1.2.1"
@@ -1952,6 +1966,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/52/59/0782e51887ac6b07ffd1570e0364cf901ebc36345fea669969d2084baebb/simple_websocket-1.1.0-py3-none-any.whl", hash = "sha256:4af6069630a38ed6c561010f0e11a5bc0d4ca569b36306eb257cd9a192497c8c", size = 13842 },
]
[[package]]
name = "six"
version = "1.17.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050 },
]
[[package]]
name = "sqlalchemy"
version = "2.0.50"