mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
0f1d358bec
commit
48f4c2c015
4 files changed
+195
-10
No files matched your search
@@ -16,6 +16,8 @@ export type AutomationData = {
|
||||
updated_at: number;
|
||||
last_run: AutomationRunData | null;
|
||||
next_runs: number[] | null;
|
||||
has_webhook: boolean;
|
||||
webhook_url: string | null;
|
||||
};
|
||||
|
||||
export type AutomationRunData = {
|
||||
@@ -81,3 +83,11 @@ export async function getAutomationRuns(
|
||||
): Promise<AutomationRunData[]> {
|
||||
return fetchJSON(`/api/automations/${id}/runs?skip=${skip}&limit=${limit}`);
|
||||
}
|
||||
|
||||
export async function generateWebhook(id: string): Promise<AutomationData> {
|
||||
return fetchJSON(`/api/automations/${id}/webhook`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function deleteWebhook(id: string): Promise<AutomationData> {
|
||||
return fetchJSON(`/api/automations/${id}/webhook`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
runAutomation,
|
||||
getAutomationById,
|
||||
getAutomationRuns,
|
||||
generateWebhook,
|
||||
deleteWebhook,
|
||||
type AutomationData,
|
||||
type AutomationRunData
|
||||
} from '$lib/apis/automations';
|
||||
@@ -139,6 +141,47 @@
|
||||
const freq = match[1].toLowerCase();
|
||||
return freq.charAt(0).toUpperCase() + freq.slice(1);
|
||||
}
|
||||
|
||||
// ── Webhook ──
|
||||
let webhookLoading = $state(false);
|
||||
let webhookCopied = $state(false);
|
||||
|
||||
async function handleGenerateWebhook() {
|
||||
if (!detail) return;
|
||||
webhookLoading = true;
|
||||
try {
|
||||
const updated = await generateWebhook(detail.id);
|
||||
detail = updated;
|
||||
items = items.map((i) => (i.id === updated.id ? updated : i));
|
||||
toast.success('Webhook enabled');
|
||||
} catch (e: any) {
|
||||
toast.error(e.message || 'Failed to generate webhook');
|
||||
} finally {
|
||||
webhookLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevokeWebhook() {
|
||||
if (!detail) return;
|
||||
webhookLoading = true;
|
||||
try {
|
||||
const updated = await deleteWebhook(detail.id);
|
||||
detail = updated;
|
||||
items = items.map((i) => (i.id === updated.id ? updated : i));
|
||||
toast.success('Webhook disabled');
|
||||
} catch (e: any) {
|
||||
toast.error(e.message || 'Failed to revoke webhook');
|
||||
} finally {
|
||||
webhookLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function copyWebhookUrl() {
|
||||
if (!detail?.webhook_url) return;
|
||||
navigator.clipboard.writeText(detail.webhook_url);
|
||||
webhookCopied = true;
|
||||
setTimeout(() => (webhookCopied = false), 2000);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full overflow-hidden">
|
||||
@@ -150,7 +193,7 @@
|
||||
</div>
|
||||
{:else if detail}
|
||||
<!-- Header -->
|
||||
<div class="flex items-center gap-2 h-9 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
<div class="flex items-center gap-2 h-9 {$sidebarOpen ? 'px-3' : 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
{#if !$sidebarOpen}
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
@@ -223,6 +266,49 @@
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Last run</span>
|
||||
<span class="text-xs text-gray-700 dark:text-gray-300">{formatTime(detail.last_run_at)}</span>
|
||||
</div>
|
||||
<div class="flex items-center min-h-[1.75rem] px-3">
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Webhook</span>
|
||||
{#if detail.webhook_url}
|
||||
<div class="flex items-center gap-1.5 min-w-0 flex-1">
|
||||
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono truncate">...?token={detail.webhook_url.split('token=')[1]?.slice(0, 12)}...</span>
|
||||
<button
|
||||
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75 shrink-0"
|
||||
onclick={copyWebhookUrl}
|
||||
>
|
||||
{webhookCopied ? 'Copied!' : 'Copy'}
|
||||
</button>
|
||||
</div>
|
||||
{:else if detail.has_webhook}
|
||||
<!-- Webhook enabled, URL not available -->
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-xs text-gray-700 dark:text-gray-300">Enabled</span>
|
||||
<span class="text-gray-300 dark:text-gray-600">·</span>
|
||||
<button
|
||||
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={handleGenerateWebhook}
|
||||
disabled={webhookLoading}
|
||||
>
|
||||
Regenerate
|
||||
</button>
|
||||
<span class="text-gray-300 dark:text-gray-600">·</span>
|
||||
<button
|
||||
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={handleRevokeWebhook}
|
||||
disabled={webhookLoading}
|
||||
>
|
||||
Disable
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={handleGenerateWebhook}
|
||||
disabled={webhookLoading}
|
||||
>
|
||||
Enable
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Prompt -->
|
||||
@@ -269,7 +355,7 @@
|
||||
{:else}
|
||||
<!-- ── List ── -->
|
||||
<!-- Header -->
|
||||
<div class="flex items-center gap-2 h-9 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
<div class="flex items-center gap-2 h-9 {$sidebarOpen ? 'px-3' : 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
{#if !$sidebarOpen}
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import secrets
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
@@ -32,8 +34,16 @@ def _get_user(request: Request) -> str:
|
||||
return auth.user_id
|
||||
|
||||
|
||||
def _automation_dict(a: Automation, last_run: AutomationRun | None = None, next_runs: list[int] | None = None) -> dict:
|
||||
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,
|
||||
@@ -50,6 +60,8 @@ def _automation_dict(a: Automation, last_run: AutomationRun | None = None, next_
|
||||
"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,
|
||||
}
|
||||
|
||||
|
||||
@@ -220,15 +232,43 @@ async def toggle_automation(automation_id: str, request: Request):
|
||||
|
||||
|
||||
@router.post("/{automation_id}/run")
|
||||
async def run_automation_now(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")
|
||||
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))
|
||||
asyncio.create_task(execute_automation(automation, webhook_payload=webhook_payload))
|
||||
return _automation_dict(automation)
|
||||
|
||||
|
||||
@@ -263,3 +303,46 @@ async def get_automation_runs(
|
||||
|
||||
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)
|
||||
@@ -111,11 +111,14 @@ async def scheduler_worker_loop(app) -> None:
|
||||
####################
|
||||
|
||||
|
||||
async def execute_automation(automation) -> None:
|
||||
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
|
||||
@@ -127,6 +130,9 @@ async def execute_automation(automation) -> None:
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user