diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d45392..50f8f75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/cptr/app.py b/cptr/app.py index f47a414..94f2ebe 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -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) diff --git a/cptr/env.py b/cptr/env.py index cfbc5db..f0c16c7 100644 --- a/cptr/env.py +++ b/cptr/env.py @@ -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")) + diff --git a/cptr/frontend/package.json b/cptr/frontend/package.json index bdb0d47..53ad033 100644 --- a/cptr/frontend/package.json +++ b/cptr/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.1.9", + "version": "0.2.0", "type": "module", "scripts": { "dev": "vite dev", diff --git a/cptr/frontend/src/lib/apis/automations.ts b/cptr/frontend/src/lib/apis/automations.ts new file mode 100644 index 0000000..4b71a1a --- /dev/null +++ b/cptr/frontend/src/lib/apis/automations.ts @@ -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 | 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 { + return fetchJSON('/api/automations', jsonBody(form)); +} + +export async function getAutomationById(id: string): Promise { + return fetchJSON(`/api/automations/${id}`); +} + +export async function updateAutomation(id: string, form: AutomationForm): Promise { + return fetchJSON(`/api/automations/${id}`, jsonBody(form)); +} + +export async function toggleAutomation(id: string): Promise { + return fetchJSON(`/api/automations/${id}/toggle`, { method: 'POST' }); +} + +export async function runAutomation(id: string): Promise { + 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 { + return fetchJSON(`/api/automations/${id}/runs?skip=${skip}&limit=${limit}`); +} + +export async function generateWebhook(id: string): Promise { + return fetchJSON(`/api/automations/${id}/webhook`, { method: 'POST' }); +} + +export async function deleteWebhook(id: string): Promise { + return fetchJSON(`/api/automations/${id}/webhook`, { method: 'DELETE' }); +} diff --git a/cptr/frontend/src/lib/apis/chat.ts b/cptr/frontend/src/lib/apis/chat.ts index 2390664..0064f90 100644 --- a/cptr/frontend/src/lib/apis/chat.ts +++ b/cptr/frontend/src/lib/apis/chat.ts @@ -25,6 +25,7 @@ export interface ChatInfo { current_message_id: string | null; created_at: number; updated_at: number; + is_active?: boolean; } export interface ChatDetail { diff --git a/cptr/frontend/src/lib/components/Admin/Connections.svelte b/cptr/frontend/src/lib/components/Admin/Connections.svelte index a44bccd..dbd4a32 100644 --- a/cptr/frontend/src/lib/components/Admin/Connections.svelte +++ b/cptr/frontend/src/lib/components/Admin/Connections.svelte @@ -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([]); let loading = $state(true); @@ -66,9 +67,7 @@ {#if loading}
-
+
{:else}
diff --git a/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte b/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte index 86a81af..1fcbe53 100644 --- a/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte +++ b/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte @@ -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} -
+ {:else} {$t('connections.add')} โ†’ {/if} diff --git a/cptr/frontend/src/lib/components/Admin/CreateUserModal.svelte b/cptr/frontend/src/lib/components/Admin/CreateUserModal.svelte index 18ebf13..ef03fa9 100644 --- a/cptr/frontend/src/lib/components/Admin/CreateUserModal.svelte +++ b/cptr/frontend/src/lib/components/Admin/CreateUserModal.svelte @@ -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} -
+ {:else} {$t('admin.create')} {/if} diff --git a/cptr/frontend/src/lib/components/Admin/EditConnectionModal.svelte b/cptr/frontend/src/lib/components/Admin/EditConnectionModal.svelte index 4669659..0020ba0 100644 --- a/cptr/frontend/src/lib/components/Admin/EditConnectionModal.svelte +++ b/cptr/frontend/src/lib/components/Admin/EditConnectionModal.svelte @@ -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} -
+ {: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} -
+ {:else} {$t('settings.save') || 'Save'} โ†’ {/if} diff --git a/cptr/frontend/src/lib/components/Admin/Settings.svelte b/cptr/frontend/src/lib/components/Admin/Settings.svelte index c903c16..2668ec7 100644 --- a/cptr/frontend/src/lib/components/Admin/Settings.svelte +++ b/cptr/frontend/src/lib/components/Admin/Settings.svelte @@ -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>({}); let loading = $state(true); @@ -54,9 +55,7 @@ {#if loading}
-
+
{:else} diff --git a/cptr/frontend/src/lib/components/Admin/Users.svelte b/cptr/frontend/src/lib/components/Admin/Users.svelte index 895703e..e9c7030 100644 --- a/cptr/frontend/src/lib/components/Admin/Users.svelte +++ b/cptr/frontend/src/lib/components/Admin/Users.svelte @@ -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}
-
+
{:else}
diff --git a/cptr/frontend/src/lib/components/AuthScreen.svelte b/cptr/frontend/src/lib/components/AuthScreen.svelte index 62e90f9..48c305a 100644 --- a/cptr/frontend/src/lib/components/AuthScreen.svelte +++ b/cptr/frontend/src/lib/components/AuthScreen.svelte @@ -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} -
+ {:else} {isSetup ? $t('auth.createAccountBtn') diff --git a/cptr/frontend/src/lib/components/ChangelogModal.svelte b/cptr/frontend/src/lib/components/ChangelogModal.svelte index 14621c0..72012ef 100644 --- a/cptr/frontend/src/lib/components/ChangelogModal.svelte +++ b/cptr/frontend/src/lib/components/ChangelogModal.svelte @@ -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 @@
{:else}
-
+ Loading release notes...
{/if} diff --git a/cptr/frontend/src/lib/components/DirectoryPicker.svelte b/cptr/frontend/src/lib/components/DirectoryPicker.svelte index 79edf12..46c52e5 100644 --- a/cptr/frontend/src/lib/components/DirectoryPicker.svelte +++ b/cptr/frontend/src/lib/components/DirectoryPicker.svelte @@ -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'} -
+ {:else if pathValid === 'valid'} {:else if pathValid === 'invalid'} @@ -384,9 +383,7 @@
{#if loading}
-
+
{:else if error}
diff --git a/cptr/frontend/src/lib/components/FileBrowser.svelte b/cptr/frontend/src/lib/components/FileBrowser.svelte index 120a4a9..2cacaa1 100644 --- a/cptr/frontend/src/lib/components/FileBrowser.svelte +++ b/cptr/frontend/src/lib/components/FileBrowser.svelte @@ -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}
-
+
{:else if error}
diff --git a/cptr/frontend/src/lib/components/FileEditor.svelte b/cptr/frontend/src/lib/components/FileEditor.svelte index b89483b..70172cb 100644 --- a/cptr/frontend/src/lib/components/FileEditor.svelte +++ b/cptr/frontend/src/lib/components/FileEditor.svelte @@ -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 @@
{#if loading} -
+
{:else if error}
{error}
@@ -799,7 +800,7 @@ {:else if diffMode} {#if diffLoading} -
+
{:else if diffFiles.length === 0}

No changes

@@ -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; + } diff --git a/cptr/frontend/src/lib/components/GitBar.svelte b/cptr/frontend/src/lib/components/GitBar.svelte index 7f36483..8cf4ad2 100644 --- a/cptr/frontend/src/lib/components/GitBar.svelte +++ b/cptr/frontend/src/lib/components/GitBar.svelte @@ -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}
-
+
{/if}
diff --git a/cptr/frontend/src/lib/components/GitView.svelte b/cptr/frontend/src/lib/components/GitView.svelte index 5001830..2084745 100644 --- a/cptr/frontend/src/lib/components/GitView.svelte +++ b/cptr/frontend/src/lib/components/GitView.svelte @@ -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}
-
+
{:else if error && !gitStatus}
diff --git a/cptr/frontend/src/lib/components/GroupTabBar.svelte b/cptr/frontend/src/lib/components/GroupTabBar.svelte index a9372f2..3db0391 100644 --- a/cptr/frontend/src/lib/components/GroupTabBar.svelte +++ b/cptr/frontend/src/lib/components/GroupTabBar.svelte @@ -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)} - + {:else} {/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); - } - } diff --git a/cptr/frontend/src/lib/components/Icon.svelte b/cptr/frontend/src/lib/components/Icon.svelte index a66384d..73cebcd 100644 --- a/cptr/frontend/src/lib/components/Icon.svelte +++ b/cptr/frontend/src/lib/components/Icon.svelte @@ -305,5 +305,10 @@ + {:else if name === 'play'} + + {:else if name === 'clock'} + + {/if} diff --git a/cptr/frontend/src/lib/components/Modal.svelte b/cptr/frontend/src/lib/components/Modal.svelte index 8bec79d..de87202 100644 --- a/cptr/frontend/src/lib/components/Modal.svelte +++ b/cptr/frontend/src/lib/components/Modal.svelte @@ -24,7 +24,7 @@ >
e.stopPropagation()} onkeydown={() => {}} > diff --git a/cptr/frontend/src/lib/components/NotificationToast.svelte b/cptr/frontend/src/lib/components/NotificationToast.svelte new file mode 100644 index 0000000..2d1622f --- /dev/null +++ b/cptr/frontend/src/lib/components/NotificationToast.svelte @@ -0,0 +1,104 @@ + + + +
(moved = true)} +> + + + + +
+ cptr +
+ + +
+ {#if title} +
{title}
+ {/if} + {#if content} +
{content}
+ {/if} +
+
+ + + diff --git a/cptr/frontend/src/lib/components/SaveDialog.svelte b/cptr/frontend/src/lib/components/SaveDialog.svelte index 42a4bb5..da2ad44 100644 --- a/cptr/frontend/src/lib/components/SaveDialog.svelte +++ b/cptr/frontend/src/lib/components/SaveDialog.svelte @@ -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 @@
{#if loading}
-
+
{:else if error}
diff --git a/cptr/frontend/src/lib/components/Settings/Account.svelte b/cptr/frontend/src/lib/components/Settings/Account.svelte index 122c1a7..67428dc 100644 --- a/cptr/frontend/src/lib/components/Settings/Account.svelte +++ b/cptr/frontend/src/lib/components/Settings/Account.svelte @@ -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} -
+ {:else} Avatar
{#if updatingPassword} -
+ {:else} {$t('account.updatePassword')} {/if} diff --git a/cptr/frontend/src/lib/components/Settings/General.svelte b/cptr/frontend/src/lib/components/Settings/General.svelte index eeafe17..b2a6892 100644 --- a/cptr/frontend/src/lib/components/Settings/General.svelte +++ b/cptr/frontend/src/lib/components/Settings/General.svelte @@ -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 }>('/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); + } + }
@@ -40,6 +86,52 @@ {/each} + +

Notifications

+ +
+ + +

+ Show OS-level notifications when a task completes and the tab is not focused. +

+ + + + + +
+ +
+ + +
+

+ Supports Slack, Discord, Teams, and generic JSON webhooks. +

+
+
+

Message queue

{#each [{ value: 'queue' as StreamingBehavior, label: 'Queue' }, { value: 'interrupt' as StreamingBehavior, label: 'Interrupt' }] as opt} diff --git a/cptr/frontend/src/lib/components/Sidebar.svelte b/cptr/frontend/src/lib/components/Sidebar.svelte index a13693e..b353b80 100644 --- a/cptr/frontend/src/lib/components/Sidebar.svelte +++ b/cptr/frontend/src/lib/components/Sidebar.svelte @@ -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>(new Set()); + let wsChatsCache = $state>(new Map()); + let wsChatsLoading = $state>(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(); + + 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); + } }); @@ -183,6 +308,22 @@
+ + +
{$t('sidebar.workspaces')} @@ -199,28 +340,81 @@
{#each $workspaceList as ws (ws.path)} - handleWorkspaceClick(e, ws.path)} - > - - {ws.name} + handleWorkspaceClick(e, ws.path)} > - openWsMenu(e, ws.path)} - aria-label={$t('sidebar.workspaceOptions')} - > - - - + + {#if $chatEnabled} + { + e.stopPropagation(); + e.preventDefault(); + toggleWorkspaceExpand(ws.path); + }} + aria-label={isExpanded ? 'Collapse' : 'Expand'} + > + + + + + + {:else} + + {/if} + {ws.name} + openWsMenu(e, ws.path)} + aria-label={$t('sidebar.workspaceOptions')} + > + + + + + + {#if $chatEnabled && isExpanded} +
+ {#if isLoading && !chats} +
+ + + +
+ {:else if chats && chats.length > 0} + {#each chats as chat (chat.id)} + handleSidebarChatClick(chat.id, ws.path, chat.title)} + /> + {/each} + + {:else if chats} + + {/if} +
+ {/if} +
{/each} {#if $workspaceList.length === 0} @@ -230,6 +424,8 @@ {/if}
+ +
+
+ + +
+
Instructions
+ +
+ + +
+
+ + + + + + + + +
+ +
+ + +
+
+
+ + +{#if showWsMenu && wsBtnEl} + (showWsMenu = false)} + preferAbove={true} + maxHeight="15rem" + className="w-48" + /> +{/if} diff --git a/cptr/frontend/src/lib/components/automations/AutomationsPanel.svelte b/cptr/frontend/src/lib/components/automations/AutomationsPanel.svelte new file mode 100644 index 0000000..b6af222 --- /dev/null +++ b/cptr/frontend/src/lib/components/automations/AutomationsPanel.svelte @@ -0,0 +1,472 @@ + + +
+ {#if automationId} + + {#if detailLoading} +
+ +
+ {:else if detail} + +
+ {#if !$sidebarOpen} + + {/if} + + / + {detail.name} + +
+ handleToggle(detail!)} /> + + + +
+
+ + +
+ +
+
+ Status +
+ + {detail.is_active ? 'Active' : 'Paused'} +
+
+
+ Schedule + {parseFrequency(detail.rrule)} +
+
+ Model + {detail.model_id} +
+
+ Next run + {formatTime(detail.next_run_at)} +
+
+ Last run + {formatTime(detail.last_run_at)} +
+
+ Webhook + {#if detail.webhook_url} +
+ ...?token={detail.webhook_url.split('token=')[1]?.slice(0, 12)}... + +
+ {:else if detail.has_webhook} + +
+ Enabled + ยท + + ยท + +
+ {:else} + + {/if} +
+
+ + +
+
Prompt
+
+ {detail.prompt} +
+
+ + +
+
Runs
+ {#if runs.length === 0} +
No runs yet
+ {:else} + {#each runs as run} +
+ + {formatTime(run.created_at)} + {#if run.chat_id} + + {/if} + {#if run.error} + {run.error} + {/if} +
+ {/each} + {/if} +
+
+ {/if} + {:else} + + +
+ {#if !$sidebarOpen} + + {/if} + Automations + {#if total > 0} + {total} + {/if} + +
+ + +
+
+ + +
+ + + {#if searchQuery} + + {/if} +
+ + +
+ {#if loading} +
+ +
+ {:else if items.length === 0} +
+

+ {searchQuery ? 'No matches' : 'No automations yet'} +

+ {#if !searchQuery} + + {/if} +
+ {:else} + {#each items as a (a.id)} + +
+ + + {a.workspace.split('/').pop()} + ยท + {parseFrequency(a.rrule)} + +
e.stopPropagation()}> + +
e.stopPropagation()}> + handleToggle(a)} /> +
+
+
+ {/each} + {/if} +
+ {/if} +
+ +{#if showModal} + { showModal = false; editingAutomation = null; }} + onsave={handleSave} + /> +{/if} diff --git a/cptr/frontend/src/lib/components/automations/ScheduleDropdown.svelte b/cptr/frontend/src/lib/components/automations/ScheduleDropdown.svelte new file mode 100644 index 0000000..f551036 --- /dev/null +++ b/cptr/frontend/src/lib/components/automations/ScheduleDropdown.svelte @@ -0,0 +1,309 @@ + + +
+ +
+ +{#if showDropdown} + +
(showDropdown = false)}>
+ +
e.stopPropagation()} + > +
Schedule
+ +
+ +
+ + {#if frequency === 'CUSTOM'} +
+ +
+ {:else if frequency === 'ONCE'} +
+ + +
+ {:else if frequency !== 'HOURLY'} +
+
+ Time + { + const [h, m] = e.currentTarget.value.split(':').map(Number); + hour = h; + minute = m; + emitChange(); + }} + class="bg-transparent text-center outline-none text-xs" + /> +
+ + {#if frequency === 'MONTHLY'} +
+ Day + +
+ {/if} +
+ + {#if frequency === 'WEEKLY'} +
+ {#each DAYS as d} + + {/each} +
+ {/if} + {/if} +
+{/if} + + diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index 0262831..fa9576a 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -346,12 +346,11 @@ .trim() .slice(0, 200)} -
+ onmenu={(e) => openMenu(e, chat.id)} + /> {/each} {#if onpagechange} @@ -175,3 +158,4 @@ onclose={closeMenu} /> {/if} + diff --git a/cptr/frontend/src/lib/components/chat/ChatInput.svelte b/cptr/frontend/src/lib/components/chat/ChatInput.svelte index bd0a46d..2aa55ae 100644 --- a/cptr/frontend/src/lib/components/chat/ChatInput.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatInput.svelte @@ -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 @@
{#if upload.loading}
-
+
{:else if upload.type === 'image'} {upload.name} @@ -452,6 +453,9 @@ onfiles={(files) => { if (files) processFiles(Array.from(files)); }} + oncapture={(file) => { + processFiles([file]); + }} /> {#if $planMode} + +
diff --git a/cptr/frontend/src/lib/components/common/ChatItem.svelte b/cptr/frontend/src/lib/components/common/ChatItem.svelte new file mode 100644 index 0000000..fce1bd4 --- /dev/null +++ b/cptr/frontend/src/lib/components/common/ChatItem.svelte @@ -0,0 +1,62 @@ + + + +
{ if (e.key === 'Enter') onclick(); }} + title={chat.title} +> + {#if chat.is_active} + + {/if} + {chat.title} + {formatTime(chat.updated_at)} + {#if onmenu} + + {/if} +
diff --git a/cptr/frontend/src/lib/components/chat/ModelSelector.svelte b/cptr/frontend/src/lib/components/common/ModelSelector.svelte similarity index 97% rename from cptr/frontend/src/lib/components/chat/ModelSelector.svelte rename to cptr/frontend/src/lib/components/common/ModelSelector.svelte index e865101..e951c13 100644 --- a/cptr/frontend/src/lib/components/chat/ModelSelector.svelte +++ b/cptr/frontend/src/lib/components/common/ModelSelector.svelte @@ -1,7 +1,7 @@ + +
+ + diff --git a/cptr/frontend/src/lib/components/ToggleSwitch.svelte b/cptr/frontend/src/lib/components/common/ToggleSwitch.svelte similarity index 100% rename from cptr/frontend/src/lib/components/ToggleSwitch.svelte rename to cptr/frontend/src/lib/components/common/ToggleSwitch.svelte diff --git a/cptr/frontend/src/lib/components/preview/OfficePreview.svelte b/cptr/frontend/src/lib/components/preview/OfficePreview.svelte index f3c5164..de04f72 100644 --- a/cptr/frontend/src/lib/components/preview/OfficePreview.svelte +++ b/cptr/frontend/src/lib/components/preview/OfficePreview.svelte @@ -1,6 +1,7 @@ + + + Automations / cptr + + + diff --git a/cptr/frontend/src/routes/automations/[id]/+page.svelte b/cptr/frontend/src/routes/automations/[id]/+page.svelte new file mode 100644 index 0000000..8933a78 --- /dev/null +++ b/cptr/frontend/src/routes/automations/[id]/+page.svelte @@ -0,0 +1,12 @@ + + + + Automation / cptr + + + diff --git a/cptr/frontend/static/audio/notification.mp3 b/cptr/frontend/static/audio/notification.mp3 new file mode 100644 index 0000000..8bfa874 Binary files /dev/null and b/cptr/frontend/static/audio/notification.mp3 differ diff --git a/cptr/frontend/static/sql-wasm.wasm b/cptr/frontend/static/sql-wasm.wasm new file mode 100755 index 0000000..b32b664 Binary files /dev/null and b/cptr/frontend/static/sql-wasm.wasm differ diff --git a/cptr/migrations/versions/0002_add_automations.py b/cptr/migrations/versions/0002_add_automations.py new file mode 100644 index 0000000..b558731 --- /dev/null +++ b/cptr/migrations/versions/0002_add_automations.py @@ -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') diff --git a/cptr/models/__init__.py b/cptr/models/__init__.py index 1cefb1a..4482216 100644 --- a/cptr/models/__init__.py +++ b/cptr/models/__init__.py @@ -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", ] diff --git a/cptr/models/automations.py b/cptr/models/automations.py new file mode 100644 index 0000000..a2bcc53 --- /dev/null +++ b/cptr/models/automations.py @@ -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 diff --git a/cptr/models/chats.py b/cptr/models/chats.py index b7236b8..8fed6dd 100644 --- a/cptr/models/chats.py +++ b/cptr/models/chats.py @@ -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 diff --git a/cptr/models/config.py b/cptr/models/config.py index b7e5450..3e7a2f7 100644 --- a/cptr/models/config.py +++ b/cptr/models/config.py @@ -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 + ) diff --git a/cptr/routers/__init__.py b/cptr/routers/__init__.py index fca7904..b9ad358 100644 --- a/cptr/routers/__init__.py +++ b/cptr/routers/__init__.py @@ -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", diff --git a/cptr/routers/automations.py b/cptr/routers/automations.py new file mode 100644 index 0000000..5467bdc --- /dev/null +++ b/cptr/routers/automations.py @@ -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) diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index d014dc1..57e7342 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -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 diff --git a/cptr/utils/automations.py b/cptr/utils/automations.py new file mode 100644 index 0000000..aec13c9 --- /dev/null +++ b/cptr/utils/automations.py @@ -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") diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 8b61ec8..6353aa3 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -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) diff --git a/cptr/utils/config.py b/cptr/utils/config.py index 58035d0..0438144 100644 --- a/cptr/utils/config.py +++ b/cptr/utils/config.py @@ -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 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ diff --git a/cptr/utils/db.py b/cptr/utils/db.py index feeeabb..4b6e0fb 100644 --- a/cptr/utils/db.py +++ b/cptr/utils/db.py @@ -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) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 8df8e9a..ced4b87 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -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}, } diff --git a/cptr/utils/webhook.py b/cptr/utils/webhook.py new file mode 100644 index 0000000..b0b7e6d --- /dev/null +++ b/cptr/utils/webhook.py @@ -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 diff --git a/pyproject.toml b/pyproject.toml index c717af9..63cddbb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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'", ] diff --git a/uv.lock b/uv.lock index 18fad95..f21542d 100644 --- a/uv.lock +++ b/uv.lock @@ -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"