Merge pull request #36 from open-webui/main

0.3.0
This commit is contained in:
Tim Baek authored and GitHub committed 2026-06-12 10:27:04 -05:00
commit ae98f2bbef
43 files changed
+4146 -190

No files matched your search

+16
View File
@@ -5,6 +5,22 @@ 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.3.0] - 2026-06-12
### Added
- 💬 **Messaging bots.** Connect your AI to Telegram, Discord, Slack, WhatsApp, and Signal from Settings. Each bot has full tool access, streams responses in real time, and syncs conversations back to the web UI. Use `/workspace` to switch projects and `/new` to start fresh conversations.
- 📊 **Usage tooltip.** Hover the info icon on completed messages to see token counts and timing.
### Changed
- 🔄 **Live tool progress.** See what tools are running as they execute, not just after they finish.
- 🌍 **i18n updates.** Full translation coverage across all 10 locales.
### Fixed
- 🐛 **Empty model selector.** Shows a helpful label when no models are configured.
## [0.2.3] - 2026-06-12
### Added
+17
View File
@@ -9,6 +9,8 @@ from cptr.routers import (
admin_router,
auth_router,
automations_router,
bridge_router,
webhook_router,
chat_router,
events_router,
files_router,
@@ -55,6 +57,19 @@ async def startup():
asyncio.create_task(scheduler_worker_loop(app))
# Start messaging bots
from cptr.utils.bridge import BotManager
app.state.bot_manager = BotManager()
asyncio.create_task(app.state.bot_manager.start_all())
@app.on_event("shutdown")
async def shutdown():
bot_manager = getattr(app.state, "bot_manager", None)
if bot_manager:
await bot_manager.stop_all()
# Auth middleware
@app.middleware("http")
@@ -187,6 +202,8 @@ async def get_config():
app.include_router(admin_router)
app.include_router(auth_router)
app.include_router(automations_router)
app.include_router(bridge_router)
app.include_router(webhook_router)
app.include_router(chat_router)
app.include_router(events_router)
app.include_router(files_router)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.2.3",
"version": "0.3.0",
"type": "module",
"scripts": {
"dev": "vite dev",
+1
View File
@@ -2,6 +2,7 @@
@plugin "@tailwindcss/typography";
@custom-variant dark (&:where(.dark, .dark *));
@custom-variant hover (&:hover);
@theme {
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, ui-sans-serif, system-ui, sans-serif;
+70
View File
@@ -0,0 +1,70 @@
import { fetchJSON, jsonBody } from './index';
export type BotData = {
id: string;
platform: string;
name: string;
workspace: string;
model_id: string;
token_masked: string;
allowed_senders: string[];
is_active: boolean;
is_running: boolean;
meta: Record<string, any> | null;
created_at: number;
updated_at: number;
};
export type BotForm = {
platform: string;
name: string;
workspace: string;
model_id: string;
token: string;
allowed_senders?: string[];
is_active?: boolean;
};
export type BotUpdate = {
name?: string;
workspace?: string;
model_id?: string;
token?: string;
allowed_senders?: string[];
is_active?: boolean;
};
export async function listBots(): Promise<BotData[]> {
return fetchJSON('/api/admin/bots');
}
export async function createBot(form: BotForm): Promise<BotData> {
return fetchJSON('/api/admin/bots', jsonBody(form));
}
export async function updateBot(id: string, form: BotUpdate): Promise<BotData> {
return fetchJSON(`/api/admin/bots/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form)
});
}
export async function deleteBot(id: string): Promise<{ ok: boolean }> {
return fetchJSON(`/api/admin/bots/${id}`, { method: 'DELETE' });
}
export async function startBot(id: string): Promise<{ ok: boolean; is_running: boolean }> {
return fetchJSON(`/api/admin/bots/${id}/start`, { method: 'POST' });
}
export async function stopBot(id: string): Promise<{ ok: boolean; is_running: boolean }> {
return fetchJSON(`/api/admin/bots/${id}/stop`, { method: 'POST' });
}
export async function verifyBotToken(
platform: string,
token: string
): Promise<{ ok: boolean; info?: { username: string; id: string }; error?: string }> {
return fetchJSON('/api/admin/bots/verify', jsonBody({ platform, token }));
}
@@ -48,7 +48,7 @@
// Revert
conn.enabled = !newVal;
connections = [...connections];
toast.error('Failed to update connection');
toast.error($t('connections.failedToUpdate'));
}
}
@@ -0,0 +1,268 @@
<script lang="ts">
/**
* Create / Edit bot modal.
* Follows the same pattern as CreateConnectionModal and AutomationModal.
*/
import Modal from '../Modal.svelte';
import Icon from '../Icon.svelte';
import DropdownMenu from '../DropdownMenu.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import { createBot, updateBot, verifyBotToken, type BotData, type BotForm } from '$lib/apis/bots';
import { toast } from 'svelte-sonner';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
bot?: BotData | null;
onclose: () => void;
onsave: () => void;
}
let { bot = null, onclose, onsave }: Props = $props();
let platform = $state(bot?.platform || 'telegram');
let name = $state(bot?.name || '');
let token = $state('');
let modelId = $state(bot?.model_id || $selectedModelId || '');
let workspace = $state(bot?.workspace || '');
let allowedSenders = $state(bot?.allowed_senders?.join(', ') || '');
let saving = $state(false);
// Token verification
let verifying = $state(false);
let verifyResult = $state<{ ok: boolean; info?: any; error?: string } | null>(null);
// Workspace dropdown
let showWsMenu = $state(false);
let wsBtnEl: HTMLButtonElement | undefined = $state();
$effect(() => {
if (!workspace && $workspaceList.length > 0) {
workspace = $workspaceList[0].path;
}
});
let wsMenuItems = $derived(
$workspaceList.map((ws) => ({
label: ws.name,
icon: 'folder',
active: ws.path === workspace,
check: true,
onclick: () => { workspace = ws.path; }
}))
);
let selectedWsName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || 'Select workspace'
);
const platformHints: Record<string, string> = {
telegram: 'Create a bot via @BotFather',
discord: 'Create a bot in the Developer Portal',
slack: 'Bot Token | App Token (pipe-separated)',
whatsapp: 'Access Token | Phone Number ID (pipe-separated)',
signal: 'signal-cli URL | Phone Number (pipe-separated)'
};
async function handleVerify() {
if (!token.trim()) return;
verifying = true;
verifyResult = null;
try {
verifyResult = await verifyBotToken(platform, token.trim());
} catch (e: any) {
verifyResult = { ok: false, error: e.message || 'Verification failed' };
} finally {
verifying = false;
}
}
async function handleSubmit() {
if (!name.trim() || !modelId || !workspace) return;
if (!bot && !token.trim()) return;
saving = true;
try {
if (bot) {
const update: any = {
name: name.trim(),
model_id: modelId,
workspace,
allowed_senders: allowedSenders.split(',').map((s) => s.trim()).filter(Boolean) || undefined
};
if (token.trim()) update.token = token.trim();
await updateBot(bot.id, update);
} else {
await createBot({
platform,
name: name.trim(),
token: token.trim(),
model_id: modelId,
workspace,
allowed_senders: allowedSenders.split(',').map((s) => s.trim()).filter(Boolean) || undefined
});
}
onsave();
onclose();
} catch (e: any) {
toast.error(e.message || 'Failed to save');
} finally {
saving = false;
}
}
</script>
<Modal {onclose} class="w-full max-w-md mx-4">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="p-4"
onkeydown={(e) => {
if (e.key === 'Enter' && name.trim() && (bot || token.trim())) handleSubmit();
}}
>
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">
{bot ? 'Edit Bot' : 'Add Bot'}
</h2>
{#if !bot}
<!-- Platform + Name on same row -->
<div class="flex gap-3">
<div class="flex-1">
<label class="text-[10px] text-gray-400 dark:text-gray-600">Name</label>
<input
type="text"
bind:value={name}
placeholder="My Bot"
autofocus
autocomplete="off"
spellcheck="false"
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5"
/>
</div>
<div class="w-28 shrink-0">
<label class="text-[10px] text-gray-400 dark:text-gray-600">Platform</label>
<select
bind:value={platform}
onchange={() => { verifyResult = null; }}
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
>
<option value="telegram">Telegram</option>
<option value="discord">Discord</option>
<option value="slack">Slack</option>
<option value="whatsapp">WhatsApp</option>
<option value="signal">Signal</option>
</select>
</div>
</div>
{:else}
<!-- Edit mode: just name -->
<label class="text-[10px] text-gray-400 dark:text-gray-600">Name</label>
<input
type="text"
bind:value={name}
placeholder="My Bot"
autofocus
autocomplete="off"
spellcheck="false"
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5"
/>
{/if}
<!-- Token -->
<label class="text-[10px] text-gray-400 dark:text-gray-600">
Token {#if bot}<span class="text-gray-300 dark:text-gray-700">({bot.token_masked})</span>{/if}
</label>
<div class="flex gap-2 items-center mb-0.5">
<input
type="password"
bind:value={token}
placeholder={bot ? 'Leave empty to keep current' : platformHints[platform] || 'Paste token'}
autocomplete="new-password"
class="flex-1 bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
/>
{#if !bot}
<button
type="button"
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors disabled:opacity-30"
onclick={handleVerify}
disabled={verifying || !token.trim()}
>
{#if verifying}
<Spinner size={10} />
{:else}
Verify
{/if}
</button>
{/if}
</div>
{#if verifyResult}
<p class="text-[10px] mb-1 text-gray-500 dark:text-gray-400">
{#if verifyResult.ok}
✓ {verifyResult.info?.username ? `@${verifyResult.info.username}` : `ID: ${verifyResult.info?.id}`}
{:else}
✗ {verifyResult.error}
{/if}
</p>
{/if}
<!-- Allowed senders -->
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">Allowed senders</label>
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">Comma-separated user IDs. Leave empty to allow all.</p>
<input
type="text"
bind:value={allowedSenders}
placeholder="123456789, 987654321"
autocomplete="off"
spellcheck="false"
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
/>
<!-- Bottom toolbar -->
<div class="flex items-center justify-between mt-3 pt-2 gap-2">
<div class="flex items-center gap-1 flex-1 min-w-0">
<!-- Model selector -->
<ModelSelector bind:selectedModel={modelId} />
<!-- Workspace selector -->
<button
bind:this={wsBtnEl}
type="button"
class="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors duration-100"
onclick={() => (showWsMenu = !showWsMenu)}
>
<Icon name="folder" size={12} />
<span class="truncate max-w-[120px]">{selectedWsName}</span>
<svg class="w-3 h-3 opacity-50" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
</div>
<button
type="button"
disabled={saving || !name.trim() || (!bot && !token.trim()) || !modelId || !workspace}
onclick={handleSubmit}
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}
<Spinner size={14} />
{:else}
{bot ? 'Save' : 'Add'} →
{/if}
</button>
</div>
</div>
</Modal>
{#if showWsMenu && wsBtnEl}
<DropdownMenu
items={wsMenuItems}
anchor={wsBtnEl}
onclose={() => (showWsMenu = false)}
preferAbove={true}
maxHeight="15rem"
className="w-48"
/>
{/if}
@@ -0,0 +1,149 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import Icon from '../Icon.svelte';
import CreateBotModal from './CreateBotModal.svelte';
import { onMount } from 'svelte';
import { listBots, deleteBot, startBot, stopBot, type BotData } from '$lib/apis/bots';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
let bots = $state<BotData[]>([]);
let loading = $state(true);
let showCreate = $state(false);
let editBot = $state<BotData | null>(null);
async function load() {
try {
bots = await listBots();
} catch {
toast.error('Failed to load bots');
} finally {
loading = false;
}
}
function handleSaved() {
showCreate = false;
editBot = null;
load();
}
async function toggleRunning(e: Event, bot: BotData) {
e.stopPropagation();
const wasRunning = bot.is_running;
// Optimistic
bot.is_running = !wasRunning;
bots = [...bots];
try {
if (wasRunning) {
await stopBot(bot.id);
} else {
await startBot(bot.id);
}
await load();
} catch {
bot.is_running = wasRunning;
bots = [...bots];
toast.error('Failed to toggle bot');
}
}
async function handleDelete(e: Event, bot: BotData) {
e.stopPropagation();
try {
await deleteBot(bot.id);
await load();
} catch {
toast.error('Failed to delete bot');
}
}
onMount(load);
</script>
<div class="flex items-center justify-between mb-4">
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('admin.messaging')}</h2>
<button
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => (showCreate = true)}
>
<Icon name="plus" size={14} />
</button>
</div>
{#if loading}
<div class="flex justify-center py-8">
<Spinner size={16} />
</div>
{:else}
<div>
{#each bots as bot}
<div class="group flex items-center gap-2 w-full h-7">
<!-- Platform icon -->
<span class="shrink-0
{bot.is_running ? 'text-gray-400 dark:text-gray-500' : 'text-gray-300 dark:text-gray-700'}">
<Icon name={bot.platform} size={14} />
</span>
<!-- Name (clickable to edit) -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="flex-1 text-[13px] truncate cursor-pointer
{bot.is_running ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
onclick={() => (editBot = bot)}
onkeydown={() => {}}
>
{bot.name}
</span>
<!-- Delete (hover) -->
<button
type="button"
class="opacity-0 group-hover:opacity-100 text-gray-300 dark:text-gray-700 hover:text-red-500 dark:hover:text-red-400 transition-all p-0.5"
onclick={(e) => handleDelete(e, bot)}
>
<Icon name="trash" size={11} />
</button>
<!-- Toggle switch -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
{bot.is_running ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
role="switch"
tabindex="-1"
aria-checked={bot.is_running}
onclick={(e) => toggleRunning(e, bot)}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleRunning(e, bot);
}
}}
>
<span
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
{bot.is_running ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
></span>
</span>
</div>
{/each}
{#if bots.length === 0}
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">No messaging bots configured.</p>
{/if}
</div>
{/if}
{#if showCreate}
<CreateBotModal onclose={() => (showCreate = false)} onsave={handleSaved} />
{/if}
{#if editBot}
<CreateBotModal
bot={editBot}
onclose={() => (editBot = null)}
onsave={handleSaved}
/>
{/if}
@@ -4,6 +4,7 @@
import Icon from './Icon.svelte';
import { appVersion, lastSeenVersion, showChangelog } from '$lib/stores';
import Spinner from '$lib/components/common/Spinner.svelte';
import { t } from '$lib/i18n';
type ChangelogEntry = { title: string; content: string; raw: string };
type VersionData = { date: string; [section: string]: string | ChangelogEntry[] };
@@ -61,10 +62,10 @@
<Modal onclose={handleClose} class="w-full max-w-3xl mx-4 md:mx-0 flex flex-col max-h-[52vh]">
<div class="flex items-center gap-3 px-4 pt-4 pb-2 shrink-0">
<div class="min-w-0 flex-1">
<h2 class="text-sm font-medium text-gray-900 dark:text-white">What's New</h2>
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('changelog.whatsNew')}</h2>
{#if $appVersion}
<p class="mt-0.5 text-[11px] text-gray-400 dark:text-gray-600">
Release Notes
{$t('changelog.releaseNotes')}
</p>
{/if}
</div>
@@ -138,18 +139,18 @@
</div>
{:else if error}
<div class="flex flex-col items-center justify-center py-16 gap-2 text-center">
<p class="text-xs text-gray-500 dark:text-gray-400">Couldn't load release notes.</p>
<p class="text-xs text-gray-500 dark:text-gray-400">{$t('changelog.loadError')}</p>
<button
class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600 hover:text-gray-900 dark:bg-white/6 dark:text-gray-400 dark:hover:text-white transition-colors duration-75"
onclick={() => (error = false)}
>
Retry
{$t('changelog.retry')}
</button>
</div>
{:else}
<div class="flex flex-col items-center justify-center py-16 gap-3">
<Spinner size={16} />
<span class="text-[11px] text-gray-400 dark:text-gray-600">Loading release notes...</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600">{$t('changelog.loading')}</span>
</div>
{/if}
</div>
@@ -159,7 +160,7 @@
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
onclick={handleClose}
>
Done
{$t('changelog.done')}
</button>
</div>
</Modal>
@@ -314,5 +314,24 @@
<path d="M12 2L2 7L12 12L22 7L12 2Z" />
<path d="M2 17L12 22L22 17" />
<path d="M2 12L12 17L22 12" />
{:else if name === 'telegram'}
<path d="M21 5L2 12.5L9 13.5M21 5L18.5 20L9 13.5M21 5L9 13.5M9 13.5V19L12.2488 15.7229" />
{:else if name === 'discord'}
<path d="M5.5 16C10.5 18.5 13.5 18.5 18.5 16" />
<path d="M15.5 17.5L16.5 19.5C16.5 19.5 20.6713 18.1717 22 16C22 15 22.5301 7.85339 19 5.5C17.5 4.5 15 4 15 4L14 6H12" />
<path d="M8.52832 17.5L7.52832 19.5C7.52832 19.5 3.35699 18.1717 2.02832 16C2.02832 15 1.49823 7.85339 5.02832 5.5C6.52832 4.5 9.02832 4 9.02832 4L10.0283 6H12.0283" />
<path d="M8.5 14C7.67157 14 7 13.1046 7 12C7 10.8954 7.67157 10 8.5 10C9.32843 10 10 10.8954 10 12C10 13.1046 9.32843 14 8.5 14Z" />
<path d="M15.5 14C14.6716 14 14 13.1046 14 12C14 10.8954 14.6716 10 15.5 10C16.3284 10 17 10.8954 17 12C17 13.1046 16.3284 14 15.5 14Z" />
{:else if name === 'slack'}
<path d="M10 3L6 21" />
<path d="M20.5 16H2.5" />
<path d="M22 7H4" />
<path d="M18 3L14 21" />
{:else if name === 'whatsapp'}
<path d="M22 12C22 17.5228 17.5228 22 12 22C10.1786 22 8.47087 21.513 7 20.6622L2 21.5L2.83209 16C2.29689 14.7751 2 13.4222 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12Z" />
<path d="M12.9604 13.8683L15.0399 13.4624L17 14.2149V16.0385C17 16.6449 16.4783 17.1073 15.8901 16.9783C14.3671 16.6444 11.5997 15.8043 9.67826 13.8683C7.84859 12.0248 7.22267 9.45734 7.01039 8.04128C6.92535 7.47406 7.3737 7 7.94306 7H9.83707L10.572 8.96888L10.1832 11.0701" />
{:else if name === 'signal'}
<path d="M8.5 11.5L11.5 14.5L16.5 9.5" />
<path d="M5 18L3.13036 4.91253C3.05646 4.39524 3.39389 3.91247 3.90398 3.79912L11.5661 2.09641C11.8519 2.03291 12.1481 2.03291 12.4339 2.09641L20.096 3.79912C20.6061 3.91247 20.9435 4.39524 20.8696 4.91252L19 18C18.9293 18.495 18.5 21.5 12 21.5C5.5 21.5 5.07071 18.495 5 18Z" />
{/if}
</svg>
@@ -29,7 +29,7 @@
target="_blank"
rel="noopener noreferrer"
class="text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>v{$latestVersion} available</a
>{$t('about.updateAvailable', { version: $latestVersion })}</a
>
{/if}
</div>
@@ -44,11 +44,11 @@
href="https://github.com/open-webui/computer/blob/main/LICENSE"
target="_blank"
rel="noopener noreferrer"
class="underline hover:text-gray-700 dark:hover:text-gray-300">Open Use License</a
class="underline hover:text-gray-700 dark:hover:text-gray-300">{$t('about.licenseName')}</a
>
<br />
Copyright © 2026 Open WebUI Inc. All rights reserved.
{$t('about.copyright')}
</p>
</div>
@@ -32,9 +32,9 @@
method: 'PUT',
body: JSON.stringify({ config: { 'notifications.webhook_url': webhookUrl.trim() || null } })
});
toast.success('Webhook URL saved');
toast.success($t('general.webhookUrlSaved'));
} catch {
toast.error('Failed to save webhook URL');
toast.error($t('general.webhookUrlSaveFailed'));
} finally {
webhookLoading = false;
}
@@ -48,7 +48,7 @@
if (permission === 'granted') {
notificationsEnabled.set(true);
} else {
toast.error('Browser notification permission denied');
toast.error($t('general.notificationPermissionDenied'));
}
}
} else {
@@ -88,28 +88,28 @@
</select>
<!-- Notifications -->
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Notifications</h3>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.notifications')}</h3>
<div class="flex flex-col gap-2.5">
<!-- Browser notifications toggle -->
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400">Browser notifications</span>
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('general.browserNotifications')}</span>
<ToggleSwitch value={$notificationsEnabled} onchange={() => toggleNotifications()} />
</label>
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
Show OS-level notifications when a task completes and the tab is not focused.
{$t('general.browserNotificationsDesc')}
</p>
<!-- Sound toggle -->
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400">Notification sound</span>
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('general.notificationSound')}</span>
<ToggleSwitch value={$notificationSound} onchange={(v) => notificationSound.set(v)} />
</label>
<!-- Webhook URL -->
<div class="mt-1">
<label class="text-xs text-gray-600 dark:text-gray-400" for="webhook-url">
Webhook URL
{$t('general.webhookUrl')}
</label>
<div class="flex gap-1.5 mt-1">
<input
@@ -124,29 +124,29 @@
onclick={saveWebhookUrl}
disabled={webhookLoading}
>
Save
{$t('settings.save')}
</button>
</div>
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
Supports Slack, Discord, Teams, and generic JSON webhooks.
{$t('general.webhookUrlHint')}
</p>
</div>
</div>
{#if $session?.role === 'admin'}
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Updates</h3>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.updates')}</h3>
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400">Update notifications</span>
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('general.updateNotifications')}</span>
<ToggleSwitch value={$showUpdateToastPref} onchange={(v) => showUpdateToastPref.set(v)} />
</label>
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
Show a toast when a new version of cptr is available.
{$t('general.updateNotificationsDesc')}
</p>
{/if}
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Message queue</h3>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.messageQueue')}</h3>
<div class="flex gap-1">
{#each [{ value: 'queue' as StreamingBehavior, label: 'Queue' }, { value: 'interrupt' as StreamingBehavior, label: 'Interrupt' }] as opt}
{#each [{ value: 'queue' as StreamingBehavior, label: $t('general.queue') }, { value: 'interrupt' as StreamingBehavior, label: $t('general.interrupt') }] as opt}
<button
class="flex items-center gap-1.5 h-7 px-2.5 rounded-lg text-xs transition-colors duration-100
{$streamingBehavior === opt.value
@@ -160,8 +160,8 @@
</div>
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
{$streamingBehavior === 'queue'
? 'Messages sent during generation are queued and sent after completion.'
: 'Sending a message cancels the current generation.'}
? $t('general.queueDesc')
: $t('general.interruptDesc')}
</p>
<div class="mt-auto pt-6 flex justify-end">
@@ -10,20 +10,21 @@
} from '$lib/stores/keybindings';
import type { ActionId } from '$lib/stores/keybindings';
import KeyPill from '../KeyPill.svelte';
import { t } from '$lib/i18n';
/** Action descriptions for the second line. */
const ACTION_DESCRIPTIONS: Record<ActionId, string> = {
newFile: 'Open a new untitled file',
newTerminal: 'Open a new terminal session',
newChat: 'Start a new AI chat',
closeTab: 'Close the active tab',
nextTab: 'Switch to the next tab',
prevTab: 'Switch to the previous tab',
quickOpen: 'Search and open files quickly',
openSettings: 'Open the settings panel',
toggleSplit: 'Toggle split editor view',
toggleSidebar: 'Show or hide the sidebar'
};
const ACTION_DESCRIPTIONS: Record<ActionId, string> = $derived({
newFile: $t('keyboard.newFile'),
newTerminal: $t('keyboard.newTerminal'),
newChat: $t('keyboard.newChat'),
closeTab: $t('keyboard.closeTab'),
nextTab: $t('keyboard.nextTab'),
prevTab: $t('keyboard.prevTab'),
quickOpen: $t('keyboard.quickOpen'),
openSettings: $t('keyboard.openSettings'),
toggleSplit: $t('keyboard.toggleSplit'),
toggleSidebar: $t('keyboard.toggleSidebar')
});
let recordingAction = $state<ActionId | null>(null);
@@ -77,18 +78,18 @@
<div class="flex flex-col min-h-full">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-medium text-gray-900 dark:text-white">Keyboard Shortcuts</h2>
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('keyboard.title')}</h2>
<button
class="text-[10px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
onclick={resetKeybindings}>Reset defaults</button
onclick={resetKeybindings}>{$t('keyboard.resetDefaults')}</button
>
</div>
<!-- Column headers -->
<div class="flex items-center gap-2 mb-0.5 px-1">
<span class="flex-1 text-[10px] font-medium text-gray-400 dark:text-gray-600">Command</span>
<span class="flex-1 text-[10px] font-medium text-gray-400 dark:text-gray-600">{$t('keyboard.command')}</span>
<span class="w-[140px] text-[10px] font-medium text-gray-400 dark:text-gray-600 text-right"
>Keybinding</span
>{$t('keyboard.keybinding')}</span
>
</div>
@@ -110,7 +111,7 @@
<div class="w-[140px] flex items-center justify-end shrink-0">
{#if isRecording}
<span class="recording-indicator">Press keys…</span>
<span class="recording-indicator">{$t('keyboard.pressKeys')}</span>
{:else if chord}
<button
class="cursor-pointer"
@@ -122,7 +123,7 @@
{:else}
<button
class="text-[10px] text-gray-500 dark:text-gray-600 cursor-pointer hover:text-gray-400 transition-colors duration-75"
onclick={() => startRecording(actionId)}>Unassigned</button
onclick={() => startRecording(actionId)}>{$t('keyboard.unassigned')}</button
>
{/if}
@@ -138,7 +139,7 @@
</div>
<p class="text-[10px] text-gray-400 dark:text-gray-600 mt-3">
Click a binding to rebind. Press <kbd class="kbd-inline">Esc</kbd> to cancel.
{$t('keyboard.rebindHint')}
</p>
</div>
@@ -8,6 +8,7 @@
import Users from './Admin/Users.svelte';
import Connections from './Admin/Connections.svelte';
import Models from './Admin/Models.svelte';
import Messaging from './Admin/Messaging.svelte';
import AdminSettings from './Admin/Settings.svelte';
import { session } from '$lib/session';
import { t } from '$lib/i18n';
@@ -20,6 +21,7 @@
| 'users'
| 'connections'
| 'models'
| 'messaging'
| 'admin_settings';
interface Props {
@@ -33,19 +35,20 @@
const isAdmin = $derived($session?.role === 'admin');
const personalTabs: { id: Tab; label: string; icon: string }[] = [
{ id: 'general', label: 'General', icon: 'settings' },
{ id: 'keyboard', label: 'Keyboard', icon: 'terminal' },
{ id: 'account', label: 'Account', icon: 'user' },
{ id: 'about', label: 'About', icon: 'info' }
];
const personalTabs: { id: Tab; label: string; icon: string }[] = $derived([
{ id: 'general', label: $t('settings.general'), icon: 'settings' },
{ id: 'keyboard', label: $t('settings.keyboard'), icon: 'terminal' },
{ id: 'account', label: $t('settings.account'), icon: 'user' },
{ id: 'about', label: $t('settings.about'), icon: 'info' }
]);
const adminTabs: { id: Tab; label: string; icon: string }[] = [
{ id: 'users', label: 'Users', icon: 'user' },
{ id: 'connections', label: 'Connections', icon: 'plug' },
{ id: 'models', label: 'Models', icon: 'cube' },
{ id: 'admin_settings', label: 'Configuration', icon: 'shield' }
];
const adminTabs: { id: Tab; label: string; icon: string }[] = $derived([
{ id: 'users', label: $t('admin.users'), icon: 'user' },
{ id: 'connections', label: $t('admin.connections'), icon: 'plug' },
{ id: 'models', label: $t('admin.models'), icon: 'cube' },
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
{ id: 'admin_settings', label: $t('settings.configuration'), icon: 'shield' }
]);
</script>
<Modal
@@ -80,7 +83,7 @@
<!-- Admin section -->
{#if isAdmin}
<span class="hidden md:block text-[10px] text-gray-400 dark:text-gray-600 px-2 mt-2 mb-0.5">Admin</span>
<span class="hidden md:block text-[10px] text-gray-400 dark:text-gray-600 px-2 mt-2 mb-0.5">{$t('sidebar.admin')}</span>
{#each adminTabs as tab}
<button
@@ -113,6 +116,8 @@
<Connections />
{:else if activeTab === 'models'}
<Models />
{:else if activeTab === 'messaging'}
<Messaging />
{:else if activeTab === 'admin_settings'}
<AdminSettings />
{/if}
@@ -12,6 +12,7 @@
import type { AutomationData, AutomationForm } from '$lib/apis/automations';
import { createAutomation, updateAutomation } from '$lib/apis/automations';
import { toast } from 'svelte-sonner';
import { t } from '$lib/i18n';
interface Props {
automation?: AutomationData | null;
@@ -49,7 +50,7 @@
);
let selectedWsName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || 'Select workspace'
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || $t('automationModal.selectWorkspace')
);
async function handleSubmit() {
@@ -75,7 +76,7 @@
onsave(result);
onclose();
} catch (e: any) {
toast.error(e.message || 'Failed to save automation');
toast.error(e.message || $t('automationModal.failedToSave'));
} finally {
saving = false;
}
@@ -90,7 +91,7 @@
class="w-full text-lg bg-transparent outline-none placeholder:text-gray-300 dark:placeholder:text-gray-700 text-gray-900 dark:text-white"
type="text"
bind:value={name}
placeholder="Automation title"
placeholder={$t('automationModal.titlePlaceholder')}
/>
<button
class="shrink-0 ml-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
@@ -102,13 +103,13 @@
<!-- Prompt -->
<div class="px-5 pb-2">
<div class="mb-1 text-[11px] text-gray-400 dark:text-gray-500">Instructions</div>
<div class="mb-1 text-[11px] text-gray-400 dark:text-gray-500">{$t('automationModal.instructions')}</div>
<textarea
class="w-full text-xs bg-transparent outline-none placeholder:text-gray-300 dark:placeholder:text-gray-700 text-gray-700 dark:text-gray-300 resize-none"
bind:value={prompt}
rows={8}
style="min-height: 12rem;"
placeholder="Enter prompt here..."
placeholder={$t('automationModal.promptPlaceholder')}
></textarea>
</div>
@@ -142,7 +143,7 @@
type="button"
onclick={onclose}
>
Cancel
{$t('automationModal.cancel')}
</button>
<button
class="px-3.5 py-1.5 text-xs bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition-colors rounded-full disabled:opacity-50"
@@ -150,7 +151,7 @@
onclick={handleSubmit}
disabled={saving || !name.trim() || !prompt.trim() || !modelId || !workspace}
>
{saving ? 'Saving...' : automation ? 'Save' : 'Create'}
{saving ? $t('automationModal.saving') : automation ? $t('automationModal.save') : $t('automationModal.createBtn')}
</button>
</div>
</div>
@@ -22,6 +22,7 @@
type AutomationRunData
} from '$lib/apis/automations';
import { toast } from 'svelte-sonner';
import { t } from '$lib/i18n';
interface Props {
automationId?: string;
@@ -50,7 +51,7 @@
items = res.items;
total = res.total;
} catch (e: any) {
toast.error(e.message || 'Failed to load automations');
toast.error(e.message || $t('automations.failedToLoad'));
} finally {
loading = false;
}
@@ -62,7 +63,7 @@
detail = await getAutomationById(id);
runs = await getAutomationRuns(id);
} catch (e: any) {
toast.error(e.message || 'Failed to load automation');
toast.error(e.message || $t('automations.failedToLoadOne'));
} finally {
detailLoading = false;
}
@@ -86,28 +87,28 @@
items = items.map((i) => (i.id === a.id ? updated : i));
if (detail?.id === a.id) detail = updated;
} catch (e: any) {
toast.error(e.message || 'Failed to toggle');
toast.error(e.message || $t('automations.failedToToggle'));
}
}
async function handleDelete(a: AutomationData) {
if (!confirm(`Delete "${a.name}"?`)) return;
if (!confirm($t('automations.deleteConfirm', { name: a.name }))) return;
try {
await deleteAutomation(a.id);
items = items.filter((i) => i.id !== a.id);
if (detail?.id === a.id) goto('/automations');
toast.success('Deleted');
toast.success($t('automations.deleted'));
} catch (e: any) {
toast.error(e.message || 'Failed to delete');
toast.error(e.message || $t('automations.failedToDelete'));
}
}
async function handleRunNow(a: AutomationData) {
try {
await runAutomation(a.id);
toast.success(`"${a.name}" triggered`);
toast.success($t('automations.triggered', { name: a.name }));
} catch (e: any) {
toast.error(e.message || 'Failed to run');
toast.error(e.message || $t('automations.failedToRun'));
}
}
@@ -153,9 +154,9 @@
const updated = await generateWebhook(detail.id);
detail = updated;
items = items.map((i) => (i.id === updated.id ? updated : i));
toast.success('Webhook enabled');
toast.success($t('automations.webhookEnabled'));
} catch (e: any) {
toast.error(e.message || 'Failed to generate webhook');
toast.error(e.message || $t('automations.failedToGenerateWebhook'));
} finally {
webhookLoading = false;
}
@@ -168,9 +169,9 @@
const updated = await deleteWebhook(detail.id);
detail = updated;
items = items.map((i) => (i.id === updated.id ? updated : i));
toast.success('Webhook disabled');
toast.success($t('automations.webhookDisabled'));
} catch (e: any) {
toast.error(e.message || 'Failed to revoke webhook');
toast.error(e.message || $t('automations.failedToRevokeWebhook'));
} finally {
webhookLoading = false;
}
@@ -198,7 +199,7 @@
<button
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
onclick={() => sidebarOpen.set(true)}
title="Toggle sidebar"
title={$t('automations.toggleSidebar')}
>
<Icon name="sidebar-expand" size={14} />
</button>
@@ -208,7 +209,7 @@
onclick={() => goto('/automations')}
>
<Icon name="chevron-left" size={12} />
<span>Automations</span>
<span>{$t('automations.title')}</span>
</button>
<span class="text-gray-300 dark:text-gray-600">/</span>
<span class="text-xs text-gray-900 dark:text-white truncate">{detail.name}</span>
@@ -218,21 +219,21 @@
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => handleRunNow(detail!)}
title="Run now"
title={$t('automations.runNow')}
>
<Icon name="play" size={11} />
</button>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => { editingAutomation = detail; showModal = true; }}
title="Edit"
title={$t('automationModal.save')}
>
<Icon name="pencil" size={11} />
</button>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-red-500 transition-colors duration-75"
onclick={() => handleDelete(detail!)}
title="Delete"
title={$t('admin.delete')}
>
<Icon name="trash" size={11} />
</button>
@@ -244,30 +245,30 @@
<!-- Info rows -->
<div class="border-b border-gray-200 dark:border-white/6">
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Status</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.status')}</span>
<div class="flex items-center gap-1.5">
<span class="w-1.5 h-1.5 rounded-full {detail.is_active ? 'bg-emerald-500' : 'bg-gray-400'}"></span>
<span class="text-xs text-gray-700 dark:text-gray-300">{detail.is_active ? 'Active' : 'Paused'}</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{detail.is_active ? $t('automations.active') : $t('automations.paused')}</span>
</div>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Schedule</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.schedule')}</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{parseFrequency(detail.rrule)}</span>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Model</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.model')}</span>
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono">{detail.model_id}</span>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Next run</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.nextRun')}</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{formatTime(detail.next_run_at)}</span>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">Last run</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.lastRun')}</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>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.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>
@@ -275,20 +276,20 @@
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'}
{webhookCopied ? $t('automations.copied') : $t('automations.copy')}
</button>
</div>
{:else if detail.has_webhook}
<!-- Webhook enabled, URL not available -->
<div class="flex items-center gap-1.5">
<span class="text-[11px] text-gray-700 dark:text-gray-300">Enabled</span>
<span class="text-[11px] text-gray-700 dark:text-gray-300">{$t('automations.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
{$t('automations.regenerate')}
</button>
<span class="text-gray-300 dark:text-gray-600">·</span>
<button
@@ -296,7 +297,7 @@
onclick={handleRevokeWebhook}
disabled={webhookLoading}
>
Disable
{$t('automations.disable')}
</button>
</div>
{:else}
@@ -305,7 +306,7 @@
onclick={handleGenerateWebhook}
disabled={webhookLoading}
>
Enable
{$t('automations.enable')}
</button>
{/if}
</div>
@@ -313,7 +314,7 @@
<!-- Prompt -->
<div class="border-b border-gray-200 dark:border-white/6 px-3 py-2">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">Prompt</div>
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">{$t('automations.prompt')}</div>
<div class="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap font-mono leading-relaxed max-h-32 overflow-y-auto">
{detail.prompt}
</div>
@@ -321,9 +322,9 @@
<!-- Runs -->
<div class="px-3 py-2">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">Runs</div>
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">{$t('automations.runs')}</div>
{#if runs.length === 0}
<div class="text-[11px] text-gray-400 dark:text-gray-600 py-2">No runs yet</div>
<div class="text-[11px] text-gray-400 dark:text-gray-600 py-2">{$t('automations.noRuns')}</div>
{:else}
{#each runs as run}
<div class="flex items-center gap-2 h-7 text-xs">
@@ -340,7 +341,7 @@
setTimeout(() => openChatTab(run.chat_id!), 300);
}}
>
view chat →
{$t('automations.viewChat')}
</button>
{/if}
{#if run.error}
@@ -360,12 +361,12 @@
<button
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
onclick={() => sidebarOpen.set(true)}
title="Toggle sidebar"
title={$t('automations.toggleSidebar')}
>
<Icon name="sidebar-expand" size={14} />
</button>
{/if}
<span class="text-xs text-gray-900 dark:text-white">Automations</span>
<span class="text-xs text-gray-900 dark:text-white">{$t('automations.title')}</span>
{#if total > 0}
<span class="text-[11px] text-gray-400 dark:text-gray-600">{total}</span>
{/if}
@@ -376,14 +377,14 @@
bind:value={statusFilter}
onchange={loadList}
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="paused">Paused</option>
<option value="all">{$t('automations.all')}</option>
<option value="active">{$t('automations.active')}</option>
<option value="paused">{$t('automations.paused')}</option>
</select>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => { editingAutomation = null; showModal = true; }}
title="New automation"
title={$t('automations.newAutomation')}
>
<Icon name="plus" size={13} />
</button>
@@ -396,7 +397,7 @@
<input
type="text"
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white placeholder:text-gray-400"
placeholder="Filter..."
placeholder={$t('automations.filter')}
bind:value={searchQuery}
oninput={loadList}
/>
@@ -416,14 +417,14 @@
{:else if items.length === 0}
<div class="flex flex-col items-center justify-center py-12 gap-2">
<p class="text-xs text-gray-400 dark:text-gray-600">
{searchQuery ? 'No matches' : 'No automations yet'}
{searchQuery ? $t('automations.noMatches') : $t('automations.noAutomations')}
</p>
{#if !searchQuery}
<button
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-75"
onclick={() => { editingAutomation = null; showModal = true; }}
>
Create automation
{$t('automations.create')}
</button>
{/if}
</div>
@@ -448,7 +449,7 @@
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => handleRunNow(a)}
title="Run now"
title={$t('automations.runNow')}
>
<Icon name="play" size={11} />
</button>
@@ -11,6 +11,7 @@
content: string;
done: boolean;
output: any[] | null;
usage: Record<string, number> | null;
chatId: string | null;
messageId: string;
siblingIndex?: number;
@@ -24,6 +25,7 @@
content,
done,
output,
usage,
chatId,
messageId,
siblingIndex = 0,
@@ -38,6 +40,7 @@
let editedContent = $state('');
let editedOutput = $state<any[] | null>(null);
let copied = $state(false);
let showUsageTooltip = $state(false);
let textareaEl: HTMLTextAreaElement;
// Track which tool call outputs are expanded
@@ -279,6 +282,23 @@
function groupHasRejected(calls: any[]): boolean {
return calls.some((c: any) => c.status === 'rejected');
}
/** Format usage data for tooltip display */
function formatUsageLabel(key: string): string {
return key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
}
function formatUsageValue(key: string, value: number): string {
if (key.includes('time') || key.includes('duration') || key.includes('latency')) {
if (value >= 1000) return `${(value / 1000).toFixed(2)}s`;
return `${value.toFixed(0)}ms`;
}
if (key.includes('token') || key.includes('count')) {
return value.toLocaleString();
}
if (Number.isInteger(value)) return value.toLocaleString();
return value.toFixed(2);
}
</script>
<div class="flex flex-col gap-1">
@@ -360,8 +380,19 @@
}}
>
<div class="flex items-center gap-2 px-3 pt-2.5 pb-0.5">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-3.5 shrink-0 text-gray-400 dark:text-gray-500">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="size-3.5 shrink-0 text-gray-400 dark:text-gray-500"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
/>
</svg>
<span class="text-xs font-medium text-gray-800 dark:text-gray-100"
>{artifact.title || 'Artifact'}</span
@@ -384,7 +415,7 @@
{@const isGroupOpen = expandedGroups.has(groupIdx)}
{@const hasPendingApproval = calls.some((c: any) => c.status === 'pending')}
<div class="w-full min-w-0">
<div class="w-full min-w-0 flex flex-col my-0.5">
<!-- Group header -->
<button
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
@@ -392,7 +423,9 @@
aria-expanded={isGroupOpen}
onclick={() => toggleGroupExpanded(groupIdx)}
>
<div class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}">
<div
class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}"
>
<!-- Status icon -->
{#if hasPending}
<div class="flex justify-center text-center">
@@ -526,14 +559,16 @@
{@const isExpanded = expandedCalls.has(callId)}
{@const pairedOutput = outputs.get(item.call_id)}
<div class="w-full min-w-0">
<div class="w-full min-w-0 flex flex-col">
<!-- Individual tool call row -->
<button
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
onclick={() => toggleCallExpanded(callId)}
>
<div
class="flex items-center gap-1.5 text-sm min-w-0 {isExecuting ? 'shimmer' : ''}"
class="flex items-center gap-1.5 text-sm min-w-0 {isExecuting
? 'shimmer'
: ''}"
>
<!-- Status icon -->
{#if isExecuting}
@@ -783,7 +818,8 @@
<div class="mt-1 space-y-0.5">
{#each calls.filter((c: any) => c.status === 'pending') as item}
<div class="flex items-center gap-2 py-1 px-1">
<span class="text-xs text-gray-500 dark:text-gray-400 flex-1 min-w-0 line-clamp-1"
<span
class="text-xs text-gray-500 dark:text-gray-400 flex-1 min-w-0 line-clamp-1"
>{toolLabel(item.name, item.arguments || {})}</span
>
<span class="flex gap-1 shrink-0">
@@ -934,9 +970,60 @@
>
</button>
{/if}
{#if done && usage && Object.keys(usage).length > 0}
<div class="relative flex items-center">
<button
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
onclick={() => (showUsageTooltip = !showUsageTooltip)}
onmouseenter={() => (showUsageTooltip = true)}
onmouseleave={() => (showUsageTooltip = false)}
aria-label="Usage info"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="2"
stroke="currentColor"
class="w-3.5 h-3.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z"
/>
</svg>
</button>
{#if showUsageTooltip}
<div
class="absolute bottom-full left-1/2 -translate-x-1/2 mb-1.5 z-50
bg-gray-900 dark:bg-gray-800 text-gray-100 dark:text-gray-100
rounded-lg shadow-lg px-2.5 py-1.5 text-[10px] font-mono
whitespace-nowrap pointer-events-none
min-w-[160px] border border-transparent dark:border-gray-700"
>
<div class="space-y-0.5">
{#each Object.entries(usage) as [key, value]}
<div class="flex justify-between gap-4">
<span class="text-gray-400 dark:text-gray-400">{formatUsageLabel(key)}</span>
<span class="tabular-nums text-white dark:text-gray-200"
>{formatUsageValue(key, value)}</span
>
</div>
{/each}
</div>
<!-- Arrow -->
<div
class="absolute top-full left-1/2 -translate-x-1/2 w-0 h-0
border-l-[5px] border-l-transparent
border-r-[5px] border-r-transparent
border-t-[5px] border-t-gray-900 dark:border-t-gray-800"
></div>
</div>
{/if}
</div>
{/if}
</div>
{/if}
{/if}
</div>
@@ -929,6 +929,7 @@
content={msg.content}
done={msg.done}
output={msg.output}
usage={msg.usage}
{chatId}
messageId={msg.id}
{siblingIndex}
@@ -2,6 +2,7 @@
import { tick } from 'svelte';
import { chatModels } from '$lib/stores/chat';
import DropdownMenu from '../DropdownMenu.svelte';
import { t } from '$lib/i18n';
interface Props {
selectedModel: string;
@@ -52,8 +53,8 @@
>
<span class="truncate max-w-[160px]"
>{$chatModels.length === 0
? 'No models available'
: $chatModels.find((m) => m.id === selectedModel)?.name || 'Select model'}</span
? $t('modelSelector.noModels')
: $chatModels.find((m) => m.id === selectedModel)?.name || $t('modelSelector.selectModel')}</span
>
{#if $chatModels.length > 0}
<svg
@@ -96,7 +97,7 @@
<input
bind:this={searchInputEl}
bind:value={search}
placeholder="Search..."
placeholder={$t('modelSelector.search')}
class="w-full bg-transparent text-[11px] text-gray-500 dark:text-gray-400 placeholder:text-gray-300 dark:placeholder:text-gray-600 outline-none"
onkeydown={(e) => {
if (e.key === 'Escape') open = false;
@@ -105,7 +106,7 @@
</div>
{/snippet}
{#snippet empty()}
<div class="px-3 py-1.5 text-[11px] text-gray-400 dark:text-gray-500 text-center">No matches</div>
<div class="px-3 py-1.5 text-[11px] text-gray-400 dark:text-gray-500 text-center">{$t('modelSelector.noMatches')}</div>
{/snippet}
</DropdownMenu>
{/if}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "Keine Ergebnisse gefunden",
"search.recentChats": "Letzte Chats",
"search.noRecentChats": "Keine letzten Chats",
"quickOpen.searchFiles": "Dateien suchen...",
"quickOpen.noFiles": "Keine Dateien gefunden",
"settings.back": "Zurück",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "Erbt den globalen Standard",
"models.templateVariables": "Variablen",
"models.resetToDefault": "Zurücksetzen",
"update.available": "Eine neue Version (v{{version}}) ist verfügbar.",
"update.viewRelease": "Versionshinweise ansehen →",
"update.updateAvailable": "Update verfügbar: v{{version}}"
"update.updateAvailable": "Update verfügbar: v{{version}}",
"general.notifications": "Benachrichtigungen",
"general.browserNotifications": "Browser-Benachrichtigungen",
"general.browserNotificationsDesc": "Systembenachrichtigungen anzeigen, wenn eine Aufgabe abgeschlossen ist und der Tab nicht fokussiert ist.",
"general.notificationSound": "Benachrichtigungston",
"general.notificationPermissionDenied": "Browser-Benachrichtigungserlaubnis verweigert",
"general.webhookUrl": "Webhook-URL",
"general.webhookUrlSaved": "Webhook-URL gespeichert",
"general.webhookUrlSaveFailed": "Webhook-URL konnte nicht gespeichert werden",
"general.webhookUrlHint": "Unterstützt Slack, Discord, Teams und generische JSON-Webhooks.",
"general.updates": "Aktualisierungen",
"general.updateNotifications": "Update-Benachrichtigungen",
"general.updateNotificationsDesc": "Eine Benachrichtigung anzeigen, wenn eine neue Version von cptr verfügbar ist.",
"general.messageQueue": "Nachrichtenwarteschlange",
"general.queue": "Warteschlange",
"general.interrupt": "Unterbrechen",
"general.queueDesc": "Während der Generierung gesendete Nachrichten werden in die Warteschlange gestellt und nach Abschluss gesendet.",
"general.interruptDesc": "Das Senden einer Nachricht bricht die aktuelle Generierung ab.",
"settings.keyboard": "Tastatur",
"settings.configuration": "Konfiguration",
"keyboard.title": "Tastenkürzel",
"keyboard.resetDefaults": "Zurücksetzen",
"keyboard.command": "Befehl",
"keyboard.keybinding": "Tastenkombination",
"keyboard.unassigned": "Nicht zugewiesen",
"keyboard.pressKeys": "Tasten drücken…",
"keyboard.rebindHint": "Klicken Sie auf eine Bindung zum Neuzuweisen. Esc zum Abbrechen.",
"changelog.whatsNew": "Neuigkeiten",
"changelog.releaseNotes": "Versionshinweise",
"changelog.loadError": "Versionshinweise konnten nicht geladen werden.",
"changelog.retry": "Erneut versuchen",
"changelog.loading": "Versionshinweise werden geladen...",
"changelog.done": "Fertig",
"modelSelector.noModels": "Keine Modelle verfügbar",
"modelSelector.selectModel": "Modell auswählen",
"modelSelector.noMatches": "Keine Treffer",
"modelSelector.search": "Suchen...",
"about.licenseName": "Open Use Lizenz",
"about.copyright": "Copyright © 2026 Open WebUI Inc. Alle Rechte vorbehalten.",
"about.updateAvailable": "v{{version}} verfügbar",
"connections.failedToUpdate": "Verbindung konnte nicht aktualisiert werden",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+132 -1
View File
@@ -301,5 +301,136 @@
"update.available": "A new version (v{{version}}) is available.",
"update.viewRelease": "View release notes →",
"update.updateAvailable": "Update available: v{{version}}"
"update.updateAvailable": "Update available: v{{version}}",
"general.notifications": "Notifications",
"general.browserNotifications": "Browser notifications",
"general.browserNotificationsDesc": "Show OS-level notifications when a task completes and the tab is not focused.",
"general.notificationSound": "Notification sound",
"general.notificationPermissionDenied": "Browser notification permission denied",
"general.webhookUrl": "Webhook URL",
"general.webhookUrlSaved": "Webhook URL saved",
"general.webhookUrlSaveFailed": "Failed to save webhook URL",
"general.webhookUrlHint": "Supports Slack, Discord, Teams, and generic JSON webhooks.",
"general.updates": "Updates",
"general.updateNotifications": "Update notifications",
"general.updateNotificationsDesc": "Show a toast when a new version of cptr is available.",
"general.messageQueue": "Message queue",
"general.queue": "Queue",
"general.interrupt": "Interrupt",
"general.queueDesc": "Messages sent during generation are queued and sent after completion.",
"general.interruptDesc": "Sending a message cancels the current generation.",
"settings.keyboard": "Keyboard",
"settings.configuration": "Configuration",
"keyboard.title": "Keyboard Shortcuts",
"keyboard.resetDefaults": "Reset defaults",
"keyboard.command": "Command",
"keyboard.keybinding": "Keybinding",
"keyboard.unassigned": "Unassigned",
"keyboard.pressKeys": "Press keys…",
"keyboard.rebindHint": "Click a binding to rebind. Press <1>Esc</1> to cancel.",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"changelog.whatsNew": "What's New",
"changelog.releaseNotes": "Release Notes",
"changelog.loadError": "Couldn't load release notes.",
"changelog.retry": "Retry",
"changelog.loading": "Loading release notes...",
"changelog.done": "Done",
"modelSelector.noModels": "No models available",
"modelSelector.selectModel": "Select model",
"modelSelector.noMatches": "No matches",
"modelSelector.search": "Search...",
"about.licenseName": "Open Use License",
"about.copyright": "Copyright © 2026 Open WebUI Inc. All rights reserved.",
"about.updateAvailable": "v{{version}} available",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation",
"connections.failedToUpdate": "Failed to update connection",
"admin.messaging": "Messaging",
"messaging.loadError": "Failed to load bots",
"messaging.fillRequired": "All fields are required",
"messaging.created": "Bot created",
"messaging.createError": "Failed to create bot",
"messaging.started": "Bot started",
"messaging.stopped": "Bot stopped",
"messaging.toggleError": "Failed to toggle bot",
"messaging.deleted": "Bot deleted",
"messaging.deleteError": "Failed to delete bot",
"messaging.empty": "No messaging bots configured",
"messaging.addFirst": "+ Add your first bot",
"messaging.addBot": "Add Bot",
"messaging.start": "Start",
"messaging.stop": "Stop",
"messaging.verify": "Verify",
"messaging.createBot": "Create Bot",
"messaging.tokenPlaceholder": "Bot token...",
"messaging.namePlaceholder": "Bot name...",
"messaging.workspacePlaceholder": "Workspace path (e.g. /Users/you/project)",
"messaging.modelPlaceholder": "Model ID (e.g. openrouter/claude-sonnet-4-20250514)",
"messaging.sendersPlaceholder": "Allowed user IDs (comma-separated, leave empty for all)"
}
+99 -25
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "Tu computadora, desde cualquier lugar.",
"auth.createAccountHint": "Crea tu cuenta para comenzar.",
"auth.signInSystemHint": "Inicia sesión con tu cuenta del sistema.",
"auth.setup": "Configuración",
@@ -20,7 +19,6 @@
"auth.minChars": "Mínimo 6 caracteres",
"auth.connectionFailed": "Error de conexión",
"auth.accountPending": "Cuenta creada. Esperando aprobación del administrador.",
"sidebar.workspaces": "Espacios de trabajo",
"sidebar.addWorkspace": "Agregar espacio de trabajo",
"sidebar.collapse": "Contraer",
@@ -32,14 +30,12 @@
"sidebar.workspaceOptions": "Opciones del espacio de trabajo",
"sidebar.closeSidebar": "Cerrar barra lateral",
"sidebar.showMore": "Mostrar más",
"bar.newFile": "Nuevo archivo",
"bar.newTerminal": "Nueva terminal",
"bar.closeTab": "Cerrar pestaña",
"bar.new": "Nuevo...",
"bar.sidebar": "Barra lateral",
"bar.toggleSidebar": "Alternar barra lateral",
"files.filter": "Filtrar...",
"files.refresh": "Actualizar",
"files.sort": "Ordenar",
@@ -74,7 +70,6 @@
"files.showHidden": "Mostrar dotfiles",
"files.hideHidden": "Ocultar dotfiles",
"files.failedToLoad": "Error al cargar el directorio",
"search.placeholder": "Buscar...",
"search.search": "Buscar",
"search.chats": "Chats",
@@ -82,10 +77,8 @@
"search.noResults": "No se encontraron resultados",
"search.recentChats": "Chats recientes",
"search.noRecentChats": "Sin chats recientes",
"quickOpen.searchFiles": "Buscar archivos...",
"quickOpen.noFiles": "No se encontraron archivos",
"settings.back": "Atrás",
"settings.general": "General",
"settings.account": "Cuenta",
@@ -93,18 +86,15 @@
"settings.save": "Guardar",
"settings.saved": "Guardado",
"settings.saving": "Guardando…",
"general.title": "General",
"general.theme": "Tema",
"general.light": "Claro",
"general.dark": "Oscuro",
"general.system": "Sistema",
"general.language": "Idioma",
"general.tools": "Herramientas",
"general.autoApproveTools": "Aprobar automáticamente todas las llamadas a herramientas",
"general.autoApproveToolsDesc": "Permitir automáticamente llamadas a herramientas (escribir, ejecutar, etc.) sin confirmación",
"account.title": "Cuenta",
"account.displayName": "Nombre para mostrar",
"account.displayNamePlaceholder": "Ingresa un nombre para mostrar",
@@ -122,11 +112,9 @@
"account.uploadFailed": "Error al subir",
"account.failedToUpdate": "Error al actualizar",
"account.failedToRemoveAvatar": "Error al eliminar el avatar",
"about.title": "Acerca de",
"about.license": "Licencia",
"about.createdBy": "Creado por Tim Baek, hecho en la Tierra",
"git.changes": "Cambios",
"git.history": "Historial",
"git.fetch": "Obtener",
@@ -169,7 +157,6 @@
"git.discard": "Descartar",
"git.copyFilePath": "Copiar ruta del archivo",
"git.copyRelativePath": "Copiar ruta relativa",
"admin.users": "Usuarios",
"admin.settings": "Configuración",
"admin.noUsers": "Sin usuarios",
@@ -200,9 +187,7 @@
"admin.delete": "Eliminar",
"admin.usernameRequired": "Nombre de usuario requerido",
"admin.minCharsPassword": "Mínimo 6 caracteres",
"admin.connections": "Conexiones",
"connections.loadError": "Error al cargar conexiones",
"connections.fieldsRequired": "Se requieren la URL base y la clave de API",
"connections.added": "Conexión agregada",
@@ -223,15 +208,12 @@
"connections.edit": "Editar conexión",
"connections.updated": "Conexión actualizada",
"connections.verify": "Verificar",
"bar.newChat": "Nuevo chat",
"home.start": "Inicio",
"home.openFolder": "Abrir carpeta...",
"home.recent": "Recientes",
"home.folders": "Carpetas",
"home.chatComingSoon": "Chat (próximamente)",
"directory.cancel": "Cancelar",
"directory.open": "Abrir \"{{name}}\"",
"directory.hidden": "Ocultos",
@@ -239,24 +221,20 @@
"directory.goBack": "Volver",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "Reintentar",
"saveDialog.fileNamePlaceholder": "Nombre de archivo…",
"saveDialog.emptyFolder": "Carpeta vacía",
"saveDialog.cancel": "Cancelar",
"saveDialog.save": "Guardar",
"saveDialog.hidden": "Ocultos",
"saveDialog.retry": "Reintentar",
"port.preview": "Vista previa",
"port.via": "vía {{name}}",
"system.title": "Sistema",
"system.cpu": "CPU",
"system.memory": "Memoria",
"system.disk": "Disco",
"system.cores": "{{count}} núcleos",
"system.process": "PROCESO",
"admin.web": "Web",
"admin.webEnabled": "Habilitar acceso web",
"admin.webEnabledHint": "La IA puede buscar en la web y obtener URLs.",
@@ -278,7 +256,6 @@
"admin.webCcKey": "Clave de API",
"admin.webCcModel": "Modelo",
"admin.webCcHint": "Cualquier endpoint compatible con OpenAI (ej. Perplexity Sonar, proxy LiteLLM)",
"admin.models": "Modelos",
"models.defaults": "Predeterminados",
"models.noDefaults": "Sin valores predeterminados globales",
@@ -297,8 +274,105 @@
"models.systemPromptInherited": "Hereda el predeterminado global",
"models.templateVariables": "Variables",
"models.resetToDefault": "Restablecer",
"update.available": "Hay una nueva versión (v{{version}}) disponible.",
"update.viewRelease": "Ver notas de la versión →",
"update.updateAvailable": "Actualización disponible: v{{version}}"
"update.updateAvailable": "Actualización disponible: v{{version}}",
"general.notifications": "Notificaciones",
"general.browserNotifications": "Notificaciones del navegador",
"general.browserNotificationsDesc": "Mostrar notificaciones del sistema cuando una tarea se completa y la pestaña no está enfocada.",
"general.notificationSound": "Sonido de notificación",
"general.notificationPermissionDenied": "Permiso de notificación del navegador denegado",
"general.webhookUrl": "URL del webhook",
"general.webhookUrlSaved": "URL del webhook guardada",
"general.webhookUrlSaveFailed": "Error al guardar URL del webhook",
"general.webhookUrlHint": "Compatible con Slack, Discord, Teams y webhooks JSON genéricos.",
"general.updates": "Actualizaciones",
"general.updateNotifications": "Notificaciones de actualización",
"general.updateNotificationsDesc": "Mostrar un aviso cuando hay una nueva versión de cptr disponible.",
"general.messageQueue": "Cola de mensajes",
"general.queue": "Cola",
"general.interrupt": "Interrumpir",
"general.queueDesc": "Los mensajes enviados durante la generación se ponen en cola y se envían al completarse.",
"general.interruptDesc": "Enviar un mensaje cancela la generación actual.",
"settings.keyboard": "Teclado",
"settings.configuration": "Configuración",
"keyboard.title": "Atajos de teclado",
"keyboard.resetDefaults": "Restablecer predeterminados",
"keyboard.command": "Comando",
"keyboard.keybinding": "Atajo",
"keyboard.unassigned": "Sin asignar",
"keyboard.pressKeys": "Presione teclas…",
"keyboard.rebindHint": "Haz clic en un atajo para reasignar. Presiona Esc para cancelar.",
"changelog.whatsNew": "Novedades",
"changelog.releaseNotes": "Notas de la versión",
"changelog.loadError": "No se pudieron cargar las notas de la versión.",
"changelog.retry": "Reintentar",
"changelog.loading": "Cargando notas de la versión...",
"changelog.done": "Listo",
"modelSelector.noModels": "Sin modelos disponibles",
"modelSelector.selectModel": "Seleccionar modelo",
"modelSelector.noMatches": "Sin coincidencias",
"modelSelector.search": "Buscar...",
"about.licenseName": "Licencia de Uso Abierto",
"about.copyright": "Copyright © 2026 Open WebUI Inc. Todos los derechos reservados.",
"about.updateAvailable": "v{{version}} disponible",
"connections.failedToUpdate": "Error al actualizar conexión",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "Aucun résultat trouvé",
"search.recentChats": "Conversations récentes",
"search.noRecentChats": "Aucune conversation récente",
"quickOpen.searchFiles": "Rechercher des fichiers...",
"quickOpen.noFiles": "Aucun fichier trouvé",
"settings.back": "Retour",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "Hérite de la valeur par défaut globale",
"models.templateVariables": "Variables",
"models.resetToDefault": "Réinitialiser",
"update.available": "Une nouvelle version (v{{version}}) est disponible.",
"update.viewRelease": "Voir les notes de version →",
"update.updateAvailable": "Mise à jour disponible : v{{version}}"
"update.updateAvailable": "Mise à jour disponible : v{{version}}",
"general.notifications": "Notifications",
"general.browserNotifications": "Notifications du navigateur",
"general.browserNotificationsDesc": "Afficher les notifications du système lorsqu'une tâche se termine et que l'onglet n'est pas actif.",
"general.notificationSound": "Son de notification",
"general.notificationPermissionDenied": "Permission de notification du navigateur refusée",
"general.webhookUrl": "URL du webhook",
"general.webhookUrlSaved": "URL du webhook enregistrée",
"general.webhookUrlSaveFailed": "Échec de l'enregistrement de l'URL du webhook",
"general.webhookUrlHint": "Prend en charge Slack, Discord, Teams et les webhooks JSON génériques.",
"general.updates": "Mises à jour",
"general.updateNotifications": "Notifications de mise à jour",
"general.updateNotificationsDesc": "Afficher une notification lorsqu'une nouvelle version de cptr est disponible.",
"general.messageQueue": "File de messages",
"general.queue": "File",
"general.interrupt": "Interrompre",
"general.queueDesc": "Les messages envoyés pendant la génération sont mis en file et envoyés après la fin.",
"general.interruptDesc": "L'envoi d'un message annule la génération en cours.",
"settings.keyboard": "Clavier",
"settings.configuration": "Configuration",
"keyboard.title": "Raccourcis clavier",
"keyboard.resetDefaults": "Réinitialiser",
"keyboard.command": "Commande",
"keyboard.keybinding": "Raccourci",
"keyboard.unassigned": "Non assigné",
"keyboard.pressKeys": "Appuyez sur des touches…",
"keyboard.rebindHint": "Cliquez sur un raccourci pour le modifier. Appuyez sur Échap pour annuler.",
"changelog.whatsNew": "Nouveautés",
"changelog.releaseNotes": "Notes de version",
"changelog.loadError": "Impossible de charger les notes de version.",
"changelog.retry": "Réessayer",
"changelog.loading": "Chargement des notes de version...",
"changelog.done": "Terminé",
"modelSelector.noModels": "Aucun modèle disponible",
"modelSelector.selectModel": "Sélectionner un modèle",
"modelSelector.noMatches": "Aucun résultat",
"modelSelector.search": "Rechercher...",
"about.licenseName": "Licence d'utilisation ouverte",
"about.copyright": "Copyright © 2026 Open WebUI Inc. Tous droits réservés.",
"about.updateAvailable": "v{{version}} disponible",
"connections.failedToUpdate": "Échec de la mise à jour de la connexion",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "結果が見つかりません",
"search.recentChats": "最近のチャット",
"search.noRecentChats": "最近のチャットはありません",
"quickOpen.searchFiles": "ファイルを検索...",
"quickOpen.noFiles": "ファイルが見つかりません",
"settings.back": "戻る",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "グローバルデフォルトを継承",
"models.templateVariables": "変数",
"models.resetToDefault": "リセット",
"update.available": "新しいバージョン (v{{version}}) が利用可能です。",
"update.viewRelease": "リリースノートを見る →",
"update.updateAvailable": "アップデート利用可能: v{{version}}"
"update.updateAvailable": "アップデート利用可能: v{{version}}",
"general.notifications": "通知",
"general.browserNotifications": "ブラウザ通知",
"general.browserNotificationsDesc": "タスク完了時にタブがフォーカスされていない場合、OS通知を表示します。",
"general.notificationSound": "通知音",
"general.notificationPermissionDenied": "ブラウザ通知の許可が拒否されました",
"general.webhookUrl": "Webhook URL",
"general.webhookUrlSaved": "Webhook URLを保存しました",
"general.webhookUrlSaveFailed": "Webhook URLの保存に失敗しました",
"general.webhookUrlHint": "Slack、Discord、Teams、汎用JSONウェブフックに対応。",
"general.updates": "アップデート",
"general.updateNotifications": "アップデート通知",
"general.updateNotificationsDesc": "cptrの新しいバージョンが利用可能な場合にトーストを表示します。",
"general.messageQueue": "メッセージキュー",
"general.queue": "キュー",
"general.interrupt": "中断",
"general.queueDesc": "生成中に送信されたメッセージはキューに入れられ、完了後に送信されます。",
"general.interruptDesc": "メッセージを送信すると現在の生成がキャンセルされます。",
"settings.keyboard": "キーボード",
"settings.configuration": "設定",
"keyboard.title": "キーボードショートカット",
"keyboard.resetDefaults": "デフォルトに戻す",
"keyboard.command": "コマンド",
"keyboard.keybinding": "キーバインド",
"keyboard.unassigned": "未設定",
"keyboard.pressKeys": "キーを押してください…",
"keyboard.rebindHint": "バインドをクリックして再設定。Escでキャンセル。",
"changelog.whatsNew": "新機能",
"changelog.releaseNotes": "リリースノート",
"changelog.loadError": "リリースノートを読み込めませんでした。",
"changelog.retry": "再試行",
"changelog.loading": "リリースノートを読み込み中...",
"changelog.done": "完了",
"modelSelector.noModels": "利用可能なモデルがありません",
"modelSelector.selectModel": "モデルを選択",
"modelSelector.noMatches": "一致なし",
"modelSelector.search": "検索...",
"about.licenseName": "オープンユースライセンス",
"about.copyright": "Copyright © 2026 Open WebUI Inc. All rights reserved.",
"about.updateAvailable": "v{{version}} が利用可能",
"connections.failedToUpdate": "接続の更新に失敗しました",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "결과를 찾을 수 없습니다",
"search.recentChats": "최근 채팅",
"search.noRecentChats": "최근 채팅 없음",
"quickOpen.searchFiles": "파일 검색...",
"quickOpen.noFiles": "파일을 찾을 수 없습니다",
"settings.back": "뒤로",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "글로벌 기본값 상속",
"models.templateVariables": "변수",
"models.resetToDefault": "초기화",
"update.available": "새 버전 (v{{version}})이 사용 가능합니다.",
"update.viewRelease": "릴리스 노트 보기 →",
"update.updateAvailable": "업데이트 가능: v{{version}}"
"update.updateAvailable": "업데이트 가능: v{{version}}",
"general.notifications": "알림",
"general.browserNotifications": "브라우저 알림",
"general.browserNotificationsDesc": "작업이 완료되고 탭이 포커스되지 않았을 때 OS 알림을 표시합니다.",
"general.notificationSound": "알림 소리",
"general.notificationPermissionDenied": "브라우저 알림 권한이 거부되었습니다",
"general.webhookUrl": "Webhook URL",
"general.webhookUrlSaved": "Webhook URL이 저장되었습니다",
"general.webhookUrlSaveFailed": "Webhook URL 저장에 실패했습니다",
"general.webhookUrlHint": "Slack, Discord, Teams 및 일반 JSON 웹훅을 지원합니다.",
"general.updates": "업데이트",
"general.updateNotifications": "업데이트 알림",
"general.updateNotificationsDesc": "cptr의 새 버전이 사용 가능할 때 알림을 표시합니다.",
"general.messageQueue": "메시지 대기열",
"general.queue": "대기열",
"general.interrupt": "중단",
"general.queueDesc": "생성 중 전송된 메시지는 대기열에 넣어지고 완료 후 전송됩니다.",
"general.interruptDesc": "메시지를 보내면 현재 생성이 취소됩니다.",
"settings.keyboard": "키보드",
"settings.configuration": "구성",
"keyboard.title": "키보드 단축키",
"keyboard.resetDefaults": "기본값 복원",
"keyboard.command": "명령",
"keyboard.keybinding": "키 바인딩",
"keyboard.unassigned": "미지정",
"keyboard.pressKeys": "키를 누르세요…",
"keyboard.rebindHint": "바인딩을 클릭하여 재설정. Esc로 취소.",
"changelog.whatsNew": "새로운 기능",
"changelog.releaseNotes": "릴리스 노트",
"changelog.loadError": "릴리스 노트를 불러올 수 없습니다.",
"changelog.retry": "재시도",
"changelog.loading": "릴리스 노트 불러오는 중...",
"changelog.done": "완료",
"modelSelector.noModels": "사용 가능한 모델 없음",
"modelSelector.selectModel": "모델 선택",
"modelSelector.noMatches": "결과 없음",
"modelSelector.search": "검색...",
"about.licenseName": "오픈 사용 라이선스",
"about.copyright": "Copyright © 2026 Open WebUI Inc. All rights reserved.",
"about.updateAvailable": "v{{version}} 사용 가능",
"connections.failedToUpdate": "연결 업데이트에 실패했습니다",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "Nenhum resultado encontrado",
"search.recentChats": "Conversas recentes",
"search.noRecentChats": "Sem conversas recentes",
"quickOpen.searchFiles": "Buscar arquivos...",
"quickOpen.noFiles": "Nenhum arquivo encontrado",
"settings.back": "Voltar",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "Herda o padrão global",
"models.templateVariables": "Variáveis",
"models.resetToDefault": "Redefinir",
"update.available": "Uma nova versão (v{{version}}) está disponível.",
"update.viewRelease": "Ver notas da versão →",
"update.updateAvailable": "Atualização disponível: v{{version}}"
"update.updateAvailable": "Atualização disponível: v{{version}}",
"general.notifications": "Notificações",
"general.browserNotifications": "Notificações do navegador",
"general.browserNotificationsDesc": "Mostrar notificações do sistema quando uma tarefa é concluída e a aba não está em foco.",
"general.notificationSound": "Som de notificação",
"general.notificationPermissionDenied": "Permissão de notificação do navegador negada",
"general.webhookUrl": "URL do webhook",
"general.webhookUrlSaved": "URL do webhook salva",
"general.webhookUrlSaveFailed": "Falha ao salvar URL do webhook",
"general.webhookUrlHint": "Suporta Slack, Discord, Teams e webhooks JSON genéricos.",
"general.updates": "Atualizações",
"general.updateNotifications": "Notificações de atualização",
"general.updateNotificationsDesc": "Mostrar um aviso quando uma nova versão do cptr estiver disponível.",
"general.messageQueue": "Fila de mensagens",
"general.queue": "Fila",
"general.interrupt": "Interromper",
"general.queueDesc": "Mensagens enviadas durante a geração são enfileiradas e enviadas após a conclusão.",
"general.interruptDesc": "Enviar uma mensagem cancela a geração atual.",
"settings.keyboard": "Teclado",
"settings.configuration": "Configuração",
"keyboard.title": "Atalhos de teclado",
"keyboard.resetDefaults": "Redefinir padrões",
"keyboard.command": "Comando",
"keyboard.keybinding": "Atalho",
"keyboard.unassigned": "Não atribuído",
"keyboard.pressKeys": "Pressione as teclas…",
"keyboard.rebindHint": "Clique em um atalho para reatribuir. Pressione Esc para cancelar.",
"changelog.whatsNew": "Novidades",
"changelog.releaseNotes": "Notas da versão",
"changelog.loadError": "Não foi possível carregar as notas da versão.",
"changelog.retry": "Tentar novamente",
"changelog.loading": "Carregando notas da versão...",
"changelog.done": "Concluído",
"modelSelector.noModels": "Nenhum modelo disponível",
"modelSelector.selectModel": "Selecionar modelo",
"modelSelector.noMatches": "Sem resultados",
"modelSelector.search": "Pesquisar...",
"about.licenseName": "Licença de Uso Aberto",
"about.copyright": "Copyright © 2026 Open WebUI Inc. Todos os direitos reservados.",
"about.updateAvailable": "v{{version}} disponível",
"connections.failedToUpdate": "Falha ao atualizar conexão",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "Результаты не найдены",
"search.recentChats": "Недавние чаты",
"search.noRecentChats": "Нет недавних чатов",
"quickOpen.searchFiles": "Поиск файлов...",
"quickOpen.noFiles": "Файлы не найдены",
"settings.back": "Назад",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "Наследует глобальные настройки",
"models.templateVariables": "Переменные",
"models.resetToDefault": "Сбросить",
"update.available": "Доступна новая версия (v{{version}}).",
"update.viewRelease": "Посмотреть заметки о выпуске →",
"update.updateAvailable": "Доступно обновление: v{{version}}"
"update.updateAvailable": "Доступно обновление: v{{version}}",
"general.notifications": "Уведомления",
"general.browserNotifications": "Уведомления браузера",
"general.browserNotificationsDesc": "Показывать уведомления ОС при завершении задачи, когда вкладка не в фокусе.",
"general.notificationSound": "Звук уведомления",
"general.notificationPermissionDenied": "Разрешение на уведомления браузера отклонено",
"general.webhookUrl": "URL вебхука",
"general.webhookUrlSaved": "URL вебхука сохранён",
"general.webhookUrlSaveFailed": "Не удалось сохранить URL вебхука",
"general.webhookUrlHint": "Поддерживает Slack, Discord, Teams и универсальные JSON-вебхуки.",
"general.updates": "Обновления",
"general.updateNotifications": "Уведомления об обновлениях",
"general.updateNotificationsDesc": "Показывать уведомление, когда доступна новая версия cptr.",
"general.messageQueue": "Очередь сообщений",
"general.queue": "Очередь",
"general.interrupt": "Прервать",
"general.queueDesc": "Сообщения, отправленные во время генерации, ставятся в очередь и отправляются после завершения.",
"general.interruptDesc": "Отправка сообщения отменяет текущую генерацию.",
"settings.keyboard": "Клавиатура",
"settings.configuration": "Конфигурация",
"keyboard.title": "Сочетания клавиш",
"keyboard.resetDefaults": "Сбросить настройки",
"keyboard.command": "Команда",
"keyboard.keybinding": "Клавиша",
"keyboard.unassigned": "Не назначено",
"keyboard.pressKeys": "Нажмите клавиши…",
"keyboard.rebindHint": "Нажмите на привязку для переназначения. Esc для отмены.",
"changelog.whatsNew": "Что нового",
"changelog.releaseNotes": "Примечания к выпуску",
"changelog.loadError": "Не удалось загрузить примечания к выпуску.",
"changelog.retry": "Повторить",
"changelog.loading": "Загрузка примечаний к выпуску...",
"changelog.done": "Готово",
"modelSelector.noModels": "Нет доступных моделей",
"modelSelector.selectModel": "Выбрать модель",
"modelSelector.noMatches": "Нет совпадений",
"modelSelector.search": "Поиск...",
"about.licenseName": "Открытая лицензия",
"about.copyright": "Copyright © 2026 Open WebUI Inc. Все права защищены.",
"about.updateAvailable": "v{{version}} доступна",
"connections.failedToUpdate": "Не удалось обновить подключение",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+99 -3
View File
@@ -77,7 +77,6 @@
"search.noResults": "未找到结果",
"search.recentChats": "最近对话",
"search.noRecentChats": "没有最近对话",
"quickOpen.searchFiles": "搜索文件...",
"quickOpen.noFiles": "未找到文件",
"settings.back": "返回",
@@ -275,8 +274,105 @@
"models.systemPromptInherited": "继承全局默认值",
"models.templateVariables": "变量",
"models.resetToDefault": "重置",
"update.available": "新版本 (v{{version}}) 可用。",
"update.viewRelease": "查看发行说明 →",
"update.updateAvailable": "有可用更新: v{{version}}"
"update.updateAvailable": "有可用更新: v{{version}}",
"general.notifications": "通知",
"general.browserNotifications": "浏览器通知",
"general.browserNotificationsDesc": "当任务完成且标签页未聚焦时显示系统通知。",
"general.notificationSound": "通知声音",
"general.notificationPermissionDenied": "浏览器通知权限被拒绝",
"general.webhookUrl": "Webhook URL",
"general.webhookUrlSaved": "Webhook URL 已保存",
"general.webhookUrlSaveFailed": "保存 Webhook URL 失败",
"general.webhookUrlHint": "支持 Slack、Discord、Teams 和通用 JSON Webhook。",
"general.updates": "更新",
"general.updateNotifications": "更新通知",
"general.updateNotificationsDesc": "当 cptr 有新版本可用时显示提示。",
"general.messageQueue": "消息队列",
"general.queue": "队列",
"general.interrupt": "中断",
"general.queueDesc": "生成期间发送的消息将排队,并在完成后发送。",
"general.interruptDesc": "发送消息会取消当前生成。",
"settings.keyboard": "键盘",
"settings.configuration": "配置",
"keyboard.title": "键盘快捷键",
"keyboard.resetDefaults": "恢复默认",
"keyboard.command": "命令",
"keyboard.keybinding": "快捷键",
"keyboard.unassigned": "未分配",
"keyboard.pressKeys": "按下按键…",
"keyboard.rebindHint": "点击绑定重新设置。按 Esc 取消。",
"changelog.whatsNew": "新功能",
"changelog.releaseNotes": "发行说明",
"changelog.loadError": "无法加载发行说明。",
"changelog.retry": "重试",
"changelog.loading": "正在加载发行说明...",
"changelog.done": "完成",
"modelSelector.noModels": "没有可用模型",
"modelSelector.selectModel": "选择模型",
"modelSelector.noMatches": "无匹配",
"modelSelector.search": "搜索...",
"about.licenseName": "开放使用许可",
"about.copyright": "Copyright © 2026 Open WebUI Inc. 保留所有权利。",
"about.updateAvailable": "v{{version}} 可用",
"connections.failedToUpdate": "更新连接失败",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+130 -11
View File
@@ -29,6 +29,7 @@
"sidebar.remove": "移除",
"sidebar.workspaceOptions": "工作區選項",
"sidebar.closeSidebar": "關閉側邊欄",
"sidebar.showMore": "顯示更多",
"bar.newFile": "新增檔案",
"bar.newTerminal": "新增終端機",
"bar.closeTab": "關閉分頁",
@@ -69,6 +70,13 @@
"files.showHidden": "顯示點檔",
"files.hideHidden": "隱藏點檔",
"files.failedToLoad": "載入目錄失敗",
"search.placeholder": "搜尋...",
"search.search": "搜尋",
"search.chats": "對話",
"search.files": "檔案",
"search.noResults": "找不到結果",
"search.recentChats": "最近對話",
"search.noRecentChats": "沒有最近對話",
"quickOpen.searchFiles": "搜尋檔案...",
"quickOpen.noFiles": "找不到檔案",
"settings.back": "返回",
@@ -194,8 +202,11 @@
"connections.baseUrl": "基礎 URL",
"connections.prefixId": "前綴 ID",
"connections.models": "模型(以逗號分隔,可選)",
"connections.modelsHint": "留空以從提供商自動探索。",
"connections.cancel": "取消",
"connections.add": "新增",
"connections.edit": "編輯連線",
"connections.updated": "連線已更新",
"connections.verify": "驗證",
"bar.newChat": "新增聊天",
"home.start": "開始",
@@ -245,15 +256,123 @@
"admin.webCcKey": "API 金鑰",
"admin.webCcModel": "模型",
"admin.webCcHint": "使用任何 OpenAI 相容端點(如 Perplexity Sonar、LiteLLM 代理)",
"admin.models": "Models",
"models.defaults": "Defaults",
"models.noModels": "No models available",
"models.failedToLoad": "Failed to load model config",
"models.failedToToggle": "Failed to toggle model",
"models.failedToSave": "Failed to save",
"models.systemPrompt": "System Prompt",
"models.systemPromptHint": "Default instructions sent to the model. Use {{VARIABLES}} for dynamic content.",
"models.systemPromptInherited": "Inherits global default",
"models.templateVariables": "Variables",
"models.resetToDefault": "Reset"
"admin.models": "模型",
"models.defaults": "預設值",
"models.noDefaults": "沒有全域預設值",
"models.noParams": "沒有參數",
"models.noModels": "沒有可用模型",
"models.addConnection": "請先新增連線。",
"models.failedToLoad": "載入模型設定失敗",
"models.failedToToggle": "切換模型失敗",
"models.failedToSave": "儲存失敗",
"models.savedDefaults": "全域預設值已儲存",
"models.savedParams": "{{name}} 的參數已儲存",
"models.add": "+ 新增",
"models.save": "儲存",
"models.systemPrompt": "系統提示詞",
"models.systemPromptHint": "傳送給模型的預設指令。使用 {{VARIABLES}} 插入動態內容。",
"models.systemPromptInherited": "繼承全域預設值",
"models.templateVariables": "變數",
"models.resetToDefault": "重設",
"update.available": "新版本 (v{{version}}) 可用。",
"update.viewRelease": "查看發行說明 →",
"update.updateAvailable": "有可用更新: v{{version}}",
"general.notifications": "通知",
"general.browserNotifications": "瀏覽器通知",
"general.browserNotificationsDesc": "當任務完成且分頁未聚焦時顯示系統通知。",
"general.notificationSound": "通知聲音",
"general.notificationPermissionDenied": "瀏覽器通知權限被拒絕",
"general.webhookUrl": "Webhook URL",
"general.webhookUrlSaved": "Webhook URL 已儲存",
"general.webhookUrlSaveFailed": "儲存 Webhook URL 失敗",
"general.webhookUrlHint": "支援 Slack、Discord、Teams 和通用 JSON Webhook。",
"general.updates": "更新",
"general.updateNotifications": "更新通知",
"general.updateNotificationsDesc": "當 cptr 有新版本可用時顯示提示。",
"general.messageQueue": "訊息佇列",
"general.queue": "佇列",
"general.interrupt": "中斷",
"general.queueDesc": "生成期間傳送的訊息會排入佇列,並在完成後傳送。",
"general.interruptDesc": "傳送訊息會取消目前的生成。",
"settings.keyboard": "鍵盤",
"settings.configuration": "設定",
"keyboard.title": "鍵盤快捷鍵",
"keyboard.resetDefaults": "恢復預設",
"keyboard.command": "指令",
"keyboard.keybinding": "快捷鍵",
"keyboard.unassigned": "未指定",
"keyboard.pressKeys": "按下按鍵…",
"keyboard.rebindHint": "點擊綁定重新設定。按 Esc 取消。",
"changelog.whatsNew": "最新消息",
"changelog.releaseNotes": "發行說明",
"changelog.loadError": "無法載入發行說明。",
"changelog.retry": "重試",
"changelog.loading": "正在載入發行說明...",
"changelog.done": "完成",
"modelSelector.noModels": "沒有可用模型",
"modelSelector.selectModel": "選擇模型",
"modelSelector.noMatches": "無匹配",
"modelSelector.search": "搜尋...",
"about.licenseName": "開放使用許可",
"about.copyright": "Copyright © 2026 Open WebUI Inc. 保留所有權利。",
"about.updateAvailable": "v{{version}} 可用",
"connections.failedToUpdate": "更新連線失敗",
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
"keyboard.quickOpen": "Search and open files quickly",
"keyboard.openSettings": "Open the settings panel",
"keyboard.toggleSplit": "Toggle split editor view",
"keyboard.toggleSidebar": "Show or hide the sidebar",
"automations.title": "Automations",
"automations.filter": "Filter...",
"automations.noMatches": "No matches",
"automations.noAutomations": "No automations yet",
"automations.create": "Create automation",
"automations.status": "Status",
"automations.active": "Active",
"automations.paused": "Paused",
"automations.all": "All",
"automations.schedule": "Schedule",
"automations.model": "Model",
"automations.nextRun": "Next run",
"automations.lastRun": "Last run",
"automations.webhook": "Webhook",
"automations.enabled": "Enabled",
"automations.regenerate": "Regenerate",
"automations.disable": "Disable",
"automations.enable": "Enable",
"automations.copied": "Copied!",
"automations.copy": "Copy",
"automations.prompt": "Prompt",
"automations.runs": "Runs",
"automations.noRuns": "No runs yet",
"automations.viewChat": "view chat →",
"automations.deleted": "Deleted",
"automations.webhookEnabled": "Webhook enabled",
"automations.webhookDisabled": "Webhook disabled",
"automations.failedToLoad": "Failed to load automations",
"automations.failedToLoadOne": "Failed to load automation",
"automations.failedToToggle": "Failed to toggle",
"automations.failedToDelete": "Failed to delete",
"automations.failedToRun": "Failed to run",
"automations.failedToGenerateWebhook": "Failed to generate webhook",
"automations.failedToRevokeWebhook": "Failed to revoke webhook",
"automations.triggered": "\"{{name}}\" triggered",
"automations.deleteConfirm": "Delete \"{{name}}\"?",
"automations.runNow": "Run now",
"automations.newAutomation": "New automation",
"automations.toggleSidebar": "Toggle sidebar",
"automationModal.titlePlaceholder": "Automation title",
"automationModal.instructions": "Instructions",
"automationModal.promptPlaceholder": "Enter prompt here...",
"automationModal.selectWorkspace": "Select workspace",
"automationModal.cancel": "Cancel",
"automationModal.saving": "Saving...",
"automationModal.save": "Save",
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation"
}
+1
View File
@@ -21,3 +21,4 @@ __all__ = [
"Automation",
"AutomationRun",
]
+5
View File
@@ -3,6 +3,8 @@
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.bridge import router as bridge_router
from cptr.routers.bridge import webhook_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
@@ -18,6 +20,8 @@ __all__ = [
"admin_router",
"auth_router",
"automations_router",
"bridge_router",
"webhook_router",
"chat_router",
"events_router",
"files_router",
@@ -29,3 +33,4 @@ __all__ = [
"terminal_router",
"workspace_router",
]
+293
View File
@@ -0,0 +1,293 @@
"""Admin API for messaging bots — CRUD + start/stop + token verification.
Bot configs are stored in the Config key-value store (not a separate table).
"""
from __future__ import annotations
import logging
import time
import uuid
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from cptr.routers.admin import require_admin
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/admin/bots", tags=["bots"])
# ── Request schemas ──────────────────────────────────────────
class BotCreate(BaseModel):
platform: str
name: str
workspace: str
model_id: str
token: str
allowed_senders: list[str] | None = None
is_active: bool = True
class BotUpdate(BaseModel):
name: str | None = None
workspace: str | None = None
model_id: str | None = None
token: str | None = None
allowed_senders: list[str] | None = None
is_active: bool | None = None
class TokenVerify(BaseModel):
platform: str
token: str
# ── Helpers ──────────────────────────────────────────────────
def _mask_token(token: str) -> str:
if not token or len(token) < 8:
return "****"
return f"{token[:4]}...{token[-4:]}"
def _serialize_bot(bot: dict, running: bool = False) -> dict:
"""Serialize a bot config for API response (token masked)."""
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import decrypt_key
try:
plain_token = decrypt_key(bot.get("token", ""), _get_jwt_secret())
masked = _mask_token(plain_token)
except Exception:
masked = "****"
return {
"id": bot.get("id"),
"platform": bot.get("platform"),
"name": bot.get("name"),
"workspace": bot.get("workspace"),
"model_id": bot.get("model_id"),
"token_masked": masked,
"allowed_senders": bot.get("allowed_senders") or [],
"is_active": bot.get("is_active", True),
"is_running": running,
"created_at": bot.get("created_at"),
"updated_at": bot.get("updated_at"),
}
# ── Endpoints ────────────────────────────────────────────────
@router.get("")
async def list_bots(request: Request):
auth = require_admin(request)
from cptr.utils.bridge import get_bot_configs
bots = await get_bot_configs()
# Filter to bots owned by this user
user_bots = [b for b in bots if b.get("user_id") == auth.user_id]
bot_manager = getattr(request.app.state, "bot_manager", None)
status = bot_manager.get_status() if bot_manager else {}
return [_serialize_bot(b, running=status.get(b["id"], False)) for b in user_bots]
@router.post("")
async def create_bot(request: Request, body: BotCreate):
auth = require_admin(request)
from cptr.utils.bridge import upsert_bot
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import encrypt_key
if body.platform not in ("telegram", "discord"):
raise HTTPException(400, f"Unsupported platform: {body.platform}")
now = int(time.time_ns())
bot = {
"id": str(uuid.uuid4()),
"user_id": auth.user_id,
"platform": body.platform,
"name": body.name,
"workspace": body.workspace,
"model_id": body.model_id,
"token": encrypt_key(body.token, _get_jwt_secret()),
"allowed_senders": body.allowed_senders,
"is_active": body.is_active,
"created_at": now,
"updated_at": now,
}
await upsert_bot(bot)
# Auto-start if active
if bot["is_active"]:
bot_manager = getattr(request.app.state, "bot_manager", None)
if bot_manager:
try:
await bot_manager.start_bot(bot)
except Exception:
logger.exception("Failed to auto-start bot %s", bot["id"][:8])
return _serialize_bot(bot)
@router.put("/{bot_id}")
async def update_bot(request: Request, bot_id: str, body: BotUpdate):
require_admin(request)
from cptr.utils.bridge import get_bot_by_id, upsert_bot
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import encrypt_key
bot = await get_bot_by_id(bot_id)
if not bot:
raise HTTPException(404, "Bot not found")
if body.name is not None:
bot["name"] = body.name
if body.workspace is not None:
bot["workspace"] = body.workspace
if body.model_id is not None:
bot["model_id"] = body.model_id
if body.token is not None:
bot["token"] = encrypt_key(body.token, _get_jwt_secret())
if body.allowed_senders is not None:
bot["allowed_senders"] = body.allowed_senders
if body.is_active is not None:
bot["is_active"] = body.is_active
bot["updated_at"] = int(time.time_ns())
await upsert_bot(bot)
# Restart if running (config changed)
bot_manager = getattr(request.app.state, "bot_manager", None)
if bot_manager and bot_manager.is_running(bot_id):
await bot_manager.stop_bot(bot_id)
if bot.get("is_active", True):
await bot_manager.start_bot(bot)
running = bot_manager.is_running(bot_id) if bot_manager else False
return _serialize_bot(bot, running=running)
@router.delete("/{bot_id}")
async def delete_bot(request: Request, bot_id: str):
require_admin(request)
from cptr.utils.bridge import delete_bot_config
bot_manager = getattr(request.app.state, "bot_manager", None)
if bot_manager and bot_manager.is_running(bot_id):
await bot_manager.stop_bot(bot_id)
ok = await delete_bot_config(bot_id)
if not ok:
raise HTTPException(404, "Bot not found")
return {"ok": True}
@router.post("/{bot_id}/start")
async def start_bot(request: Request, bot_id: str):
require_admin(request)
from cptr.utils.bridge import get_bot_by_id
bot = await get_bot_by_id(bot_id)
if not bot:
raise HTTPException(404, "Bot not found")
bot_manager = getattr(request.app.state, "bot_manager", None)
if not bot_manager:
raise HTTPException(500, "Bot manager not initialized")
if bot_manager.is_running(bot_id):
raise HTTPException(400, "Bot is already running")
await bot_manager.start_bot(bot)
return {"ok": True, "is_running": True}
@router.post("/{bot_id}/stop")
async def stop_bot(request: Request, bot_id: str):
require_admin(request)
bot_manager = getattr(request.app.state, "bot_manager", None)
if not bot_manager:
raise HTTPException(500, "Bot manager not initialized")
await bot_manager.stop_bot(bot_id)
return {"ok": True, "is_running": False}
@router.post("/verify")
async def verify_token(request: Request, body: TokenVerify):
require_admin(request)
try:
if body.platform == "telegram":
from cptr.utils.adapters.telegram import verify_token as tg_verify
info = await tg_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
elif body.platform == "discord":
from cptr.utils.adapters.discord import verify_token as dc_verify
info = await dc_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
elif body.platform == "slack":
from cptr.utils.adapters.slack import verify_token as slack_verify
info = await slack_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
elif body.platform == "whatsapp":
from cptr.utils.adapters.whatsapp import verify_token as wa_verify
info = await wa_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
elif body.platform == "signal":
from cptr.utils.adapters.signal import verify_token as sig_verify
info = await sig_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
else:
raise HTTPException(400, f"Unsupported platform: {body.platform}")
except Exception as e:
return {"ok": False, "error": str(e)}
# ── WhatsApp Webhook ─────────────────────────────────────────
webhook_router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
@webhook_router.get("/whatsapp/{bot_id}")
async def whatsapp_webhook_verify(bot_id: str, request: Request):
"""Meta webhook verification challenge (GET)."""
mode = request.query_params.get("hub.mode")
token = request.query_params.get("hub.verify_token")
challenge = request.query_params.get("hub.challenge")
if mode == "subscribe" and challenge:
# Accept any verify_token for now — user sets it in Meta dashboard
from starlette.responses import PlainTextResponse
return PlainTextResponse(challenge)
raise HTTPException(403, "Verification failed")
@webhook_router.post("/whatsapp/{bot_id}")
async def whatsapp_webhook_inbound(bot_id: str, request: Request):
"""Receive inbound WhatsApp messages via webhook."""
from cptr.utils.bridge import bot_manager
payload = await request.json()
adapter = bot_manager._adapters.get(bot_id)
if adapter:
from cptr.utils.adapters.whatsapp import WhatsAppAdapter
if isinstance(adapter, WhatsAppAdapter):
await adapter.handle_webhook(payload)
return {"status": "ok"}
+4
View File
@@ -213,6 +213,8 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
"""Discover models from a provider's /models endpoint."""
import httpx
from cptr.utils.ai import _openrouter_headers
secret = _get_jwt_secret()
api_key = decrypt_key(conn.get("api_key", ""), secret) if conn.get("api_key") else None
provider = conn.get("provider", "")
@@ -227,6 +229,7 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
headers={
"x-api-key": api_key or "",
"anthropic-version": "2023-06-01",
**_openrouter_headers(url),
},
)
if r.status_code == 200:
@@ -247,6 +250,7 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
url,
headers={
"Authorization": f"Bearer {api_key or ''}",
**_openrouter_headers(url),
},
)
if r.status_code == 200:
+1
View File
@@ -0,0 +1 @@
"""Messaging platform adapters."""
+259
View File
@@ -0,0 +1,259 @@
"""Discord adapter — zero SDK dependencies.
Uses raw WebSocket for the Discord Gateway and httpx for the REST API.
- Gateway v10 WebSocket: IDENTIFY → HEARTBEAT loop → MESSAGE_CREATE
- REST: ``POST /channels/{id}/messages`` for sending
- REST: ``PATCH /channels/{id}/messages/{id}`` for editing (streaming)
- REST: ``POST /channels/{id}/typing`` for typing indicators
"""
from __future__ import annotations
import asyncio
import json
import logging
import sys
from typing import Optional
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
GATEWAY_URL = "wss://gateway.discord.gg/?v=10&encoding=json"
API_BASE = "https://discord.com/api/v10"
MAX_MESSAGE_LEN = 2000
RECONNECT_BASE_DELAY = 2.0
RECONNECT_MAX_DELAY = 60.0
# Gateway opcodes
OP_DISPATCH = 0
OP_HEARTBEAT = 1
OP_IDENTIFY = 2
OP_RESUME = 6
OP_RECONNECT = 7
OP_INVALID_SESSION = 9
OP_HELLO = 10
OP_HEARTBEAT_ACK = 11
# Required gateway intents
INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15)
class DiscordAdapter(BaseAdapter):
"""Discord bot via raw Gateway WebSocket + REST API."""
platform = "discord"
def __init__(self, token: str) -> None:
super().__init__()
self._token = token
self._http: Optional[httpx.AsyncClient] = None
self._ws = None
self._running = False
self._bot_id: str = ""
self._session_id: str = ""
self._resume_url: str = ""
self._seq: Optional[int] = None
self._heartbeat_task: Optional[asyncio.Task] = None
self._gateway_task: Optional[asyncio.Task] = None
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._http = httpx.AsyncClient(
timeout=15,
headers={
"Authorization": f"Bot {self._token}",
"Content-Type": "application/json",
},
)
try:
resp = await self._http.get(f"{API_BASE}/users/@me")
resp.raise_for_status()
me = resp.json()
self._bot_id = me["id"]
logger.info("Discord bot connected: %s#%s", me.get("username"), me.get("discriminator"))
except Exception:
logger.exception("Discord token verification failed")
await self._http.aclose()
self._http = None
return False
self._running = True
self._gateway_task = asyncio.create_task(self._gateway_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._heartbeat_task and not self._heartbeat_task.done():
self._heartbeat_task.cancel()
if self._gateway_task and not self._gateway_task.done():
self._gateway_task.cancel()
try:
await self._gateway_task
except (asyncio.CancelledError, Exception):
pass
if self._ws:
try:
await self._ws.close()
except Exception:
pass
if self._http:
await self._http.aclose()
self._http = None
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
"""Send a message. Returns the message ID for later editing."""
if not self._http:
return None
chunks = chunk_message(text, MAX_MESSAGE_LEN)
msg_id = None
for chunk in chunks:
resp = await self._http.post(
f"{API_BASE}/channels/{chat_id}/messages",
json={"content": chunk},
)
if msg_id is None and resp.status_code == 200:
data = resp.json()
msg_id = data.get("id")
return msg_id
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Edit a previously sent message."""
if not self._http:
return
await self._http.patch(
f"{API_BASE}/channels/{chat_id}/messages/{message_id}",
json={"content": text[:MAX_MESSAGE_LEN]},
)
async def send_typing(self, chat_id: str) -> None:
if not self._http:
return
try:
await self._http.post(f"{API_BASE}/channels/{chat_id}/typing")
except Exception:
pass
# ── Gateway WebSocket ──────────────────────────────────
async def _gateway_loop(self) -> None:
delay = RECONNECT_BASE_DELAY
while self._running:
try:
await self._run_gateway_session()
delay = RECONNECT_BASE_DELAY
except asyncio.CancelledError:
return
except Exception as e:
logger.warning("Discord gateway error (%s), reconnecting in %.0fs", type(e).__name__, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
async def _run_gateway_session(self) -> None:
try:
import websockets
except ImportError:
logger.error("Discord adapter requires 'websockets' package. Install: pip install websockets")
self._running = False
return
url = self._resume_url or GATEWAY_URL
async with websockets.connect(url) as ws:
self._ws = ws
hello = json.loads(await ws.recv())
if hello.get("op") != OP_HELLO:
raise RuntimeError(f"Expected HELLO, got op={hello.get('op')}")
heartbeat_interval = hello["d"]["heartbeat_interval"] / 1000.0
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop(ws, heartbeat_interval))
if self._session_id and self._seq is not None:
await ws.send(json.dumps({
"op": OP_RESUME,
"d": {"token": self._token, "session_id": self._session_id, "seq": self._seq},
}))
else:
await ws.send(json.dumps({
"op": OP_IDENTIFY,
"d": {
"token": self._token,
"intents": INTENTS,
"properties": {"os": sys.platform, "browser": "cptr", "device": "cptr"},
},
}))
async for raw in ws:
if not self._running:
return
payload = json.loads(raw)
op = payload.get("op")
if op == OP_DISPATCH:
self._seq = payload.get("s")
event_type = payload.get("t")
data = payload.get("d", {})
if event_type == "READY":
self._session_id = data.get("session_id", "")
self._resume_url = data.get("resume_gateway_url", "")
logger.info("Discord gateway READY")
elif event_type == "MESSAGE_CREATE":
await self._handle_message_create(data)
elif op == OP_HEARTBEAT:
await ws.send(json.dumps({"op": OP_HEARTBEAT, "d": self._seq}))
elif op == OP_RECONNECT:
return
elif op == OP_INVALID_SESSION:
if not payload.get("d", False):
self._session_id = ""
self._seq = None
await asyncio.sleep(3)
return
async def _heartbeat_loop(self, ws, interval: float) -> None:
try:
while True:
await asyncio.sleep(interval)
await ws.send(json.dumps({"op": OP_HEARTBEAT, "d": self._seq}))
except (asyncio.CancelledError, Exception):
pass
async def _handle_message_create(self, data: dict) -> None:
author = data.get("author", {})
if author.get("bot", False) or author.get("id") == self._bot_id:
return
content = data.get("content", "").strip()
if not content:
return
event = MessageEvent(
platform="discord",
chat_id=data.get("channel_id", ""),
sender_id=author.get("id", ""),
sender_name=author.get("global_name") or author.get("username", "User"),
text=content,
)
if self.on_message:
await self.on_message(event)
async def verify_token(token: str) -> dict:
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get(
f"{API_BASE}/users/@me",
headers={"Authorization": f"Bot {token}"},
)
if resp.status_code == 401:
raise ValueError("Invalid Discord bot token")
resp.raise_for_status()
return resp.json()
+218
View File
@@ -0,0 +1,218 @@
"""Signal adapter — uses signal-cli REST API bridge.
Requires a running signal-cli-rest-api container:
docker run -p 8080:8080 bbernhard/signal-cli-rest-api
Token format: ``base_url|phone_number`` (pipe-separated).
Example: ``http://localhost:8080|+1234567890``
Uses polling on GET /v1/receive/{number} for inbound messages
and POST /v2/send for outbound messages.
"""
from __future__ import annotations
import asyncio
import logging
from typing import Optional
from urllib.parse import quote
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
MAX_MESSAGE_LEN = 4096
POLL_INTERVAL = 2.0 # seconds between receive polls
RECONNECT_BASE_DELAY = 2.0
RECONNECT_MAX_DELAY = 60.0
def _parse_token(token: str) -> tuple[str, str]:
"""Parse 'base_url|phone_number' format."""
if "|" in token:
base_url, phone = token.split("|", 1)
return base_url.strip().rstrip("/"), phone.strip()
raise ValueError("Signal token must be 'base_url|phone_number' (pipe-separated)")
class SignalAdapter(BaseAdapter):
"""Signal bot via signal-cli REST API bridge."""
platform = "signal"
def __init__(self, token: str) -> None:
super().__init__()
self._base_url, self._phone = _parse_token(token)
self._http: Optional[httpx.AsyncClient] = None
self._running = False
self._poll_task: Optional[asyncio.Task] = None
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._http = httpx.AsyncClient(timeout=30)
# Verify by fetching account info
try:
resp = await self._http.get(f"{self._base_url}/v1/about")
data = resp.json()
# Also verify the number is registered
resp2 = await self._http.get(
f"{self._base_url}/v1/identities/{quote(self._phone, safe='')}"
)
if resp2.status_code == 404:
raise ValueError(f"Phone number {self._phone} not registered with signal-cli")
logger.info(
"Signal adapter connected: %s (signal-cli %s)",
self._phone, data.get("versions", {}).get("signal-cli", "?"),
)
except httpx.ConnectError:
logger.error("Cannot connect to signal-cli REST API at %s", self._base_url)
await self._http.aclose()
self._http = None
return False
except Exception:
logger.exception("Signal verification failed")
await self._http.aclose()
self._http = None
return False
self._running = True
self._poll_task = asyncio.create_task(self._poll_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._poll_task and not self._poll_task.done():
self._poll_task.cancel()
try:
await self._poll_task
except (asyncio.CancelledError, Exception):
pass
if self._http:
await self._http.aclose()
self._http = None
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
if not self._http:
return None
chunks = chunk_message(text, MAX_MESSAGE_LEN)
timestamp = None
for chunk in chunks:
resp = await self._http.post(
f"{self._base_url}/v2/send",
json={
"message": chunk,
"number": self._phone,
"recipients": [chat_id],
},
)
data = resp.json()
if timestamp is None:
# signal-cli returns timestamp as message identifier
timestamp = str(data.get("timestamp", ""))
return timestamp
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Signal doesn't support message editing. No-op."""
pass
async def send_typing(self, chat_id: str) -> None:
"""Send typing indicator via signal-cli."""
if not self._http:
return
try:
await self._http.put(
f"{self._base_url}/v1/typing-indicator/{quote(self._phone, safe='')}",
json={"recipient": chat_id},
)
except Exception:
pass
# ── Polling ────────────────────────────────────────────
async def _poll_loop(self) -> None:
delay = RECONNECT_BASE_DELAY
while self._running:
try:
resp = await self._http.get(
f"{self._base_url}/v1/receive/{quote(self._phone, safe='')}",
timeout=30,
)
if resp.status_code == 200:
messages = resp.json()
for msg in messages:
try:
await self._process_message(msg)
except Exception:
logger.exception("Error processing Signal message")
delay = RECONNECT_BASE_DELAY
await asyncio.sleep(POLL_INTERVAL)
except asyncio.CancelledError:
return
except (httpx.ConnectError, httpx.ReadError, httpx.WriteError, OSError) as e:
logger.warning("Signal poll network error (%s), retrying in %.0fs", type(e).__name__, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
except Exception:
logger.exception("Signal poll error, retrying in %.0fs", delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
async def _process_message(self, msg: dict) -> None:
envelope = msg.get("envelope", {})
data_message = envelope.get("dataMessage")
if not data_message:
return
text = (data_message.get("message") or "").strip()
if not text:
return
source = envelope.get("source", "")
source_name = envelope.get("sourceName") or source
# Use source number as chat_id (DM) or groupId for groups
group_info = data_message.get("groupInfo")
chat_id = group_info.get("groupId", "") if group_info else source
event = MessageEvent(
platform="signal",
chat_id=chat_id,
sender_id=source,
sender_name=source_name,
text=text,
)
if self.on_message:
await self.on_message(event)
async def verify_token(token: str) -> dict:
"""Verify signal-cli REST API connection and phone number."""
base_url, phone = _parse_token(token)
async with httpx.AsyncClient(timeout=10) as client:
try:
resp = await client.get(f"{base_url}/v1/about")
data = resp.json()
except httpx.ConnectError:
raise ValueError(f"Cannot connect to signal-cli at {base_url}")
# Check phone number is registered
resp2 = await client.get(
f"{base_url}/v1/identities/{quote(phone, safe='')}"
)
if resp2.status_code == 404:
raise ValueError(f"Phone {phone} not registered with signal-cli")
return {
"username": phone,
"id": phone,
"version": data.get("versions", {}).get("signal-cli", "unknown"),
}
+249
View File
@@ -0,0 +1,249 @@
"""Slack adapter — zero SDK dependencies.
Uses Socket Mode WebSocket for receiving events (no public URL needed)
and the Slack Web API for sending messages via httpx.
Token format: ``xoxb-bottoken|xapp-apptoken`` (pipe-separated).
The bot token is used for API calls, the app-level token for Socket Mode.
"""
from __future__ import annotations
import asyncio
import json
import logging
from typing import Optional
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
API_BASE = "https://slack.com/api"
MAX_MESSAGE_LEN = 4000 # Slack max is ~4000 for text blocks
RECONNECT_BASE_DELAY = 2.0
RECONNECT_MAX_DELAY = 60.0
def _parse_token(token: str) -> tuple[str, str]:
"""Parse 'bot_token|app_token' format."""
if "|" in token:
bot, app = token.split("|", 1)
return bot.strip(), app.strip()
raise ValueError("Slack token must be 'xoxb-...|xapp-...' (pipe-separated)")
class SlackAdapter(BaseAdapter):
"""Slack bot via Socket Mode WebSocket + Web API."""
platform = "slack"
def __init__(self, token: str) -> None:
super().__init__()
bot_token, app_token = _parse_token(token)
self._bot_token = bot_token
self._app_token = app_token
self._http: Optional[httpx.AsyncClient] = None
self._ws = None
self._running = False
self._bot_id: str = ""
self._gateway_task: Optional[asyncio.Task] = None
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._http = httpx.AsyncClient(
timeout=15,
headers={"Authorization": f"Bearer {self._bot_token}"},
)
try:
resp = await self._http.post(f"{API_BASE}/auth.test")
data = resp.json()
if not data.get("ok"):
raise ValueError(data.get("error", "auth.test failed"))
self._bot_id = data.get("user_id", "")
logger.info("Slack bot connected: %s (team: %s)", data.get("user", "?"), data.get("team", "?"))
except Exception:
logger.exception("Slack auth.test failed")
await self._http.aclose()
self._http = None
return False
self._running = True
self._gateway_task = asyncio.create_task(self._socket_mode_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._gateway_task and not self._gateway_task.done():
self._gateway_task.cancel()
try:
await self._gateway_task
except (asyncio.CancelledError, Exception):
pass
if self._ws:
try:
await self._ws.close()
except Exception:
pass
if self._http:
await self._http.aclose()
self._http = None
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
if not self._http:
return None
chunks = chunk_message(text, MAX_MESSAGE_LEN)
msg_ts = None
for chunk in chunks:
resp = await self._http.post(
f"{API_BASE}/chat.postMessage",
json={"channel": chat_id, "text": chunk},
)
data = resp.json()
if msg_ts is None and data.get("ok"):
msg_ts = data.get("ts")
return msg_ts
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
if not self._http:
return
await self._http.post(
f"{API_BASE}/chat.update",
json={
"channel": chat_id,
"ts": message_id,
"text": text[:MAX_MESSAGE_LEN],
},
)
async def send_typing(self, chat_id: str) -> None:
# Slack doesn't have a direct typing indicator API for bots
pass
# ── Socket Mode ────────────────────────────────────────
async def _socket_mode_loop(self) -> None:
delay = RECONNECT_BASE_DELAY
while self._running:
try:
await self._run_socket_session()
delay = RECONNECT_BASE_DELAY
except asyncio.CancelledError:
return
except Exception as e:
logger.warning("Slack Socket Mode error (%s), reconnecting in %.0fs", type(e).__name__, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
async def _run_socket_session(self) -> None:
try:
import websockets
except ImportError:
logger.error("Slack adapter requires 'websockets' package. Install: pip install websockets")
self._running = False
return
# Get WebSocket URL via apps.connections.open
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(
f"{API_BASE}/apps.connections.open",
headers={"Authorization": f"Bearer {self._app_token}"},
)
data = resp.json()
if not data.get("ok"):
raise RuntimeError(f"apps.connections.open failed: {data.get('error')}")
ws_url = data["url"]
async with websockets.connect(ws_url) as ws:
self._ws = ws
async for raw in ws:
if not self._running:
return
payload = json.loads(raw)
msg_type = payload.get("type")
# Acknowledge all envelopes
envelope_id = payload.get("envelope_id")
if envelope_id:
await ws.send(json.dumps({"envelope_id": envelope_id}))
if msg_type == "disconnect":
logger.info("Slack Socket Mode disconnect requested")
return
if msg_type == "events_api":
event = payload.get("payload", {}).get("event", {})
await self._handle_event(event)
async def _handle_event(self, event: dict) -> None:
if event.get("type") != "message":
return
# Ignore bot messages, subtypes (edits, joins, etc.)
if event.get("bot_id") or event.get("subtype"):
return
if event.get("user") == self._bot_id:
return
text = (event.get("text") or "").strip()
if not text:
return
# Resolve display name
user_id = event.get("user", "")
sender_name = await self._resolve_name(user_id)
msg_event = MessageEvent(
platform="slack",
chat_id=event.get("channel", ""),
sender_id=user_id,
sender_name=sender_name,
text=text,
)
if self.on_message:
await self.on_message(msg_event)
async def _resolve_name(self, user_id: str) -> str:
if not self._http or not user_id:
return "User"
try:
resp = await self._http.get(f"{API_BASE}/users.info", params={"user": user_id})
data = resp.json()
if data.get("ok"):
user = data.get("user", {})
return user.get("real_name") or user.get("name") or "User"
except Exception:
pass
return "User"
async def verify_token(token: str) -> dict:
"""Verify a Slack bot token by calling auth.test."""
bot_token, app_token = _parse_token(token)
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(
f"{API_BASE}/auth.test",
headers={"Authorization": f"Bearer {bot_token}"},
)
data = resp.json()
if not data.get("ok"):
raise ValueError(data.get("error", "Invalid Slack token"))
# Also verify app token
resp2 = await client.post(
f"{API_BASE}/apps.connections.open",
headers={"Authorization": f"Bearer {app_token}"},
)
data2 = resp2.json()
if not data2.get("ok"):
raise ValueError(f"App token error: {data2.get('error', 'Invalid app token')}")
return {"username": data.get("user"), "id": data.get("user_id"), "team": data.get("team")}
+270
View File
@@ -0,0 +1,270 @@
"""Telegram adapter — zero SDK dependencies.
Uses raw httpx calls to the Telegram Bot API:
- ``sendMessageDraft`` for native streaming (Bot API 9.5+)
- ``editMessageText`` as fallback for older clients
- ``getUpdates`` long-polling for inbound messages
- ``sendChatAction(typing)`` for typing indicators
"""
from __future__ import annotations
import asyncio
import logging
from typing import Optional
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
API_BASE = "https://api.telegram.org/bot{token}"
POLL_TIMEOUT = 30 # seconds (Telegram long-poll)
MAX_MESSAGE_LEN = 4096
RECONNECT_BASE_DELAY = 2.0
RECONNECT_MAX_DELAY = 60.0
class TelegramAdapter(BaseAdapter):
"""Telegram bot via raw HTTP — getUpdates long-polling + native streaming."""
platform = "telegram"
def __init__(self, token: str) -> None:
super().__init__()
self._token = token
self._base = API_BASE.format(token=token)
self._client: Optional[httpx.AsyncClient] = None
self._offset: int = 0
self._poll_task: Optional[asyncio.Task] = None
self._running = False
self._bot_info: dict = {}
self._supports_draft: bool = True # Assume 9.5+, fallback on error
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._client = httpx.AsyncClient(timeout=httpx.Timeout(POLL_TIMEOUT + 10))
try:
info = await self._api("getMe")
self._bot_info = info
logger.info(
"Telegram bot connected: @%s (%s)",
info.get("username", "?"),
info.get("id", "?"),
)
except Exception:
logger.exception("Telegram getMe failed — bad token?")
await self._client.aclose()
self._client = None
return False
self._running = True
self._poll_task = asyncio.create_task(self._poll_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._poll_task and not self._poll_task.done():
self._poll_task.cancel()
try:
await self._poll_task
except (asyncio.CancelledError, Exception):
pass
if self._client:
await self._client.aclose()
self._client = None
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
"""Send a message. Returns the message ID for later editing."""
chunks = chunk_message(text, MAX_MESSAGE_LEN)
msg_id = None
for chunk in chunks:
result = await self._api(
"sendMessage",
chat_id=chat_id,
text=chunk,
parse_mode="Markdown",
disable_web_page_preview=True,
)
if msg_id is None and result:
msg_id = str(result.get("message_id", ""))
return msg_id
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Edit a previously sent message."""
try:
await self._api(
"editMessageText",
chat_id=chat_id,
message_id=int(message_id),
text=text[:MAX_MESSAGE_LEN],
parse_mode="Markdown",
disable_web_page_preview=True,
)
except TelegramAPIError as e:
if "message is not modified" in e.description.lower():
pass # Content unchanged, ignore
elif "parse" in e.description.lower():
# Markdown parse error — retry without parse_mode
await self._api(
"editMessageText",
chat_id=chat_id,
message_id=int(message_id),
text=text[:MAX_MESSAGE_LEN],
disable_web_page_preview=True,
)
else:
raise
async def send_draft(self, chat_id: str, text: str, draft_id: str | None = None) -> str:
"""Send a streaming draft using sendMessageDraft (Bot API 9.5+).
Returns the draft_id for subsequent updates.
Falls back to edit-based streaming if the API doesn't support drafts.
"""
if not self._supports_draft:
raise TelegramAPIError(400, "Draft not supported")
try:
params: dict = {
"chat_id": chat_id,
"text": text[:MAX_MESSAGE_LEN],
"parse_mode": "Markdown",
}
if draft_id:
params["draft_id"] = draft_id
result = await self._api("sendMessageDraft", **params)
return str(result.get("draft_id", result.get("message_id", "")))
except TelegramAPIError as e:
if e.code == 404 or "unknown method" in e.description.lower():
# API doesn't support sendMessageDraft — fall back
self._supports_draft = False
logger.info("Telegram sendMessageDraft not available, falling back to editMessageText")
raise
# Markdown parse failure — retry without parse_mode
if "parse" in e.description.lower():
params.pop("parse_mode", None)
result = await self._api("sendMessageDraft", **params)
return str(result.get("draft_id", result.get("message_id", "")))
raise
async def send_typing(self, chat_id: str) -> None:
try:
await self._api("sendChatAction", chat_id=chat_id, action="typing")
except Exception:
pass
# ── Polling ────────────────────────────────────────────
async def _poll_loop(self) -> None:
delay = RECONNECT_BASE_DELAY
while self._running:
try:
updates = await self._api(
"getUpdates",
offset=self._offset,
timeout=POLL_TIMEOUT,
allowed_updates=["message"],
)
delay = RECONNECT_BASE_DELAY
for update in updates:
try:
await self._process_update(update)
except Exception:
logger.exception("Error processing Telegram update")
except asyncio.CancelledError:
return
except httpx.TimeoutException:
continue
except (httpx.ConnectError, httpx.ReadError, httpx.WriteError, OSError) as e:
logger.warning("Telegram poll network error (%s), retrying in %.0fs", type(e).__name__, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
except Exception:
logger.exception("Telegram poll error, retrying in %.0fs", delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
async def _process_update(self, update: dict) -> None:
update_id = update.get("update_id", 0)
self._offset = max(self._offset, update_id + 1)
message = update.get("message")
if not message:
return
text = message.get("text") or message.get("caption") or ""
if not text.strip():
return
chat = message.get("chat", {})
sender = message.get("from", {})
event = MessageEvent(
platform="telegram",
chat_id=str(chat.get("id", "")),
sender_id=str(sender.get("id", "")),
sender_name=(
sender.get("first_name", "")
+ (" " + sender.get("last_name", "") if sender.get("last_name") else "")
).strip() or "User",
text=text,
)
if self.on_message:
await self.on_message(event)
# ── API helpers ────────────────────────────────────────
async def _api(self, method: str, **params) -> any:
if not self._client:
raise RuntimeError("Telegram client not connected")
url = f"{self._base}/{method}"
data = {k: v for k, v in params.items() if v is not None}
resp = await self._client.post(url, json=data)
body = resp.json()
if not body.get("ok"):
error_code = body.get("error_code", resp.status_code)
description = body.get("description", "Unknown error")
# Markdown parse failure — retry without parse_mode
if error_code == 400 and "parse" in description.lower() and "text" in data:
data.pop("parse_mode", None)
resp = await self._client.post(url, json=data)
body = resp.json()
if body.get("ok"):
return body.get("result")
raise TelegramAPIError(error_code, description)
return body.get("result")
class TelegramAPIError(Exception):
def __init__(self, code: int, description: str):
self.code = code
self.description = description
super().__init__(f"Telegram API error {code}: {description}")
async def verify_token(token: str) -> dict:
"""Verify a Telegram bot token by calling getMe."""
async with httpx.AsyncClient(timeout=10) as client:
url = f"{API_BASE.format(token=token)}/getMe"
resp = await client.get(url)
body = resp.json()
if not body.get("ok"):
raise TelegramAPIError(
body.get("error_code", resp.status_code),
body.get("description", "Invalid token"),
)
return body["result"]
+203
View File
@@ -0,0 +1,203 @@
"""WhatsApp adapter — zero SDK dependencies.
Uses Meta's WhatsApp Cloud API via httpx:
- Webhook endpoint for inbound messages (registered via FastAPI)
- REST POST to /messages for sending
- No native streaming; uses edit-via-context approach
Token format: ``access_token|phone_number_id`` (pipe-separated).
Requires a publicly accessible URL for webhook verification.
Configure the webhook URL in Meta's WhatsApp dashboard as:
https://your-domain/api/webhooks/whatsapp/{bot_id}
"""
from __future__ import annotations
import asyncio
import logging
from typing import Optional
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
API_BASE = "https://graph.facebook.com/v21.0"
MAX_MESSAGE_LEN = 4096
def _parse_token(token: str) -> tuple[str, str]:
"""Parse 'access_token|phone_number_id' format."""
if "|" in token:
access_token, phone_number_id = token.split("|", 1)
return access_token.strip(), phone_number_id.strip()
raise ValueError("WhatsApp token must be 'access_token|phone_number_id' (pipe-separated)")
class WhatsAppAdapter(BaseAdapter):
"""WhatsApp bot via Cloud API + webhook inbound."""
platform = "whatsapp"
def __init__(self, token: str, bot_id: str = "") -> None:
super().__init__()
self._access_token, self._phone_number_id = _parse_token(token)
self._bot_id = bot_id
self._http: Optional[httpx.AsyncClient] = None
self._running = False
self._message_queue: asyncio.Queue = asyncio.Queue()
self._process_task: Optional[asyncio.Task] = None
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._http = httpx.AsyncClient(
timeout=15,
headers={"Authorization": f"Bearer {self._access_token}"},
)
# Verify token by fetching phone number info
try:
resp = await self._http.get(f"{API_BASE}/{self._phone_number_id}")
data = resp.json()
if "error" in data:
raise ValueError(data["error"].get("message", "Invalid token"))
display_name = data.get("verified_name") or data.get("display_phone_number", "?")
logger.info("WhatsApp bot connected: %s (%s)", display_name, self._phone_number_id)
except Exception:
logger.exception("WhatsApp token verification failed")
await self._http.aclose()
self._http = None
return False
self._running = True
self._process_task = asyncio.create_task(self._process_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._process_task and not self._process_task.done():
self._process_task.cancel()
try:
await self._process_task
except (asyncio.CancelledError, Exception):
pass
if self._http:
await self._http.aclose()
self._http = None
# ── Webhook ingestion ──────────────────────────────────
async def handle_webhook(self, payload: dict) -> None:
"""Called by the webhook route to push inbound messages."""
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
for message in value.get("messages", []):
if message.get("type") != "text":
continue
sender = message.get("from", "")
text = message.get("text", {}).get("body", "").strip()
if not text:
continue
# Resolve sender name from contacts
contacts = value.get("contacts", [])
sender_name = "User"
for c in contacts:
if c.get("wa_id") == sender:
profile = c.get("profile", {})
sender_name = profile.get("name", sender)
break
event = MessageEvent(
platform="whatsapp",
chat_id=sender, # WhatsApp uses phone number as chat ID
sender_id=sender,
sender_name=sender_name,
text=text,
)
await self._message_queue.put(event)
async def _process_loop(self) -> None:
"""Process inbound messages from the webhook queue."""
while self._running:
try:
event = await asyncio.wait_for(self._message_queue.get(), timeout=5.0)
if self.on_message:
await self.on_message(event)
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
return
except Exception:
logger.exception("Error processing WhatsApp message")
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
if not self._http:
return None
chunks = chunk_message(text, MAX_MESSAGE_LEN)
msg_id = None
for chunk in chunks:
resp = await self._http.post(
f"{API_BASE}/{self._phone_number_id}/messages",
json={
"messaging_product": "whatsapp",
"to": chat_id,
"type": "text",
"text": {"body": chunk},
},
)
data = resp.json()
if msg_id is None:
messages = data.get("messages", [])
if messages:
msg_id = messages[0].get("id")
return msg_id
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""WhatsApp doesn't support message editing. Send a new message instead."""
# WhatsApp has no edit API — for streaming we just send new messages
# The stream loop will handle this gracefully
pass
async def send_typing(self, chat_id: str) -> None:
"""Send a 'typing' indicator (read receipt + typing)."""
if not self._http:
return
try:
# Mark as read (closest to typing indicator)
await self._http.post(
f"{API_BASE}/{self._phone_number_id}/messages",
json={
"messaging_product": "whatsapp",
"status": "read",
"message_id": "placeholder", # Not ideal but API requires it
},
)
except Exception:
pass
async def verify_token(token: str) -> dict:
"""Verify WhatsApp Cloud API credentials."""
access_token, phone_number_id = _parse_token(token)
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get(
f"{API_BASE}/{phone_number_id}",
headers={"Authorization": f"Bearer {access_token}"},
)
data = resp.json()
if "error" in data:
raise ValueError(data["error"].get("message", "Invalid credentials"))
return {
"username": data.get("verified_name") or data.get("display_phone_number"),
"id": phone_number_id,
}
+17 -5
View File
@@ -26,6 +26,17 @@ from cptr.env import (
logger = logging.getLogger(__name__)
def _openrouter_headers(url: str) -> dict[str, str]:
"""Return OpenRouter app-info headers when the URL is an OpenRouter endpoint."""
if "openrouter.ai" in url:
return {
"HTTP-Referer": "https://cptr.sh/",
"X-Title": "cptr / open-webui",
}
return {}
_STREAM_RETRY_ATTEMPTS = 3
_STREAM_TIMEOUT = httpx.Timeout(
STREAM_CONNECT_TIMEOUT_SECONDS,
@@ -87,6 +98,7 @@ async def chat_completion(
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
**_openrouter_headers(base_url),
},
)
elif api_type == "responses":
@@ -103,7 +115,7 @@ async def chat_completion(
resp = await client.post(
f"{base_url}/responses",
json=body_r,
headers={"Authorization": f"Bearer {api_key}"},
headers={"Authorization": f"Bearer {api_key}", **_openrouter_headers(base_url)},
)
else:
# OpenAI Chat Completions (default)
@@ -120,7 +132,7 @@ async def chat_completion(
resp = await client.post(
f"{base_url}/chat/completions",
json=body_cc,
headers={"Authorization": f"Bearer {api_key}"},
headers={"Authorization": f"Bearer {api_key}", **_openrouter_headers(base_url)},
)
if resp.status_code >= 400:
logger.debug(
@@ -231,7 +243,7 @@ async def stream_anthropic(
body.update(request_params)
# Remove None values
body = {k: v for k, v in body.items() if v is not None}
headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
headers = {"x-api-key": key, "anthropic-version": "2023-06-01", **_openrouter_headers(url)}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
@@ -365,7 +377,7 @@ async def stream_openai_completions(
body["tools"] = tools
if request_params:
body.update(request_params)
headers = {"Authorization": f"Bearer {key}"}
headers = {"Authorization": f"Bearer {key}", **_openrouter_headers(url)}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
@@ -510,7 +522,7 @@ async def stream_openai_responses(
body["tools"] = tools
if request_params:
body.update(request_params)
headers = {"Authorization": f"Bearer {key}"}
headers = {"Authorization": f"Bearer {key}", **_openrouter_headers(url)}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
+798
View File
@@ -0,0 +1,798 @@
"""Messaging bridge: adapter base class, BotManager lifecycle, and message routing.
Integrates external messaging platforms (Telegram, Discord, etc.) as alternative
frontends to cptr. Each platform adapter connects via its native protocol (long-
polling, WebSocket) and translates inbound messages into cptr chat tasks using the
same agentic loop as the web UI.
Bot configs are stored in the Config key-value store (same as connections).
Thread mappings (external chat → cptr chat) are stored in chat.meta.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Optional
logger = logging.getLogger(__name__)
# How often to edit the streaming message (seconds).
STREAM_EDIT_INTERVAL = 2.0
# Typing indicator refresh interval (seconds).
TYPING_INTERVAL = 5.0
# ── Adapter interface ────────────────────────────────────────
@dataclass
class MessageEvent:
"""Normalized inbound message from any platform."""
platform: str # "telegram", "discord", etc.
chat_id: str # Platform's chat/channel ID
sender_id: str # Platform's user ID
sender_name: str # Display name
text: str # Message content
class BaseAdapter(ABC):
"""Abstract base for messaging platform adapters.
Subclasses implement the required methods. The adapter does NOT
interpret message content — it only shuttles text between the platform
and the bridge core.
"""
platform: str = "unknown"
# Set by BotManager when the adapter is started.
on_message: Optional[Callable[[MessageEvent], Awaitable[None]]] = None
@abstractmethod
async def connect(self) -> bool:
"""Start listening for messages. Return True on success."""
...
@abstractmethod
async def disconnect(self) -> None:
"""Stop listening and release resources."""
...
@abstractmethod
async def send(self, chat_id: str, text: str) -> str | None:
"""Send a text message. Returns the platform message ID (for editing)."""
...
@abstractmethod
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Edit a previously sent message."""
...
@abstractmethod
async def send_typing(self, chat_id: str) -> None:
"""Show a typing indicator in the chat."""
...
# ── Message chunking ─────────────────────────────────────────
def chunk_message(text: str, max_len: int = 4096) -> list[str]:
"""Split a long message at paragraph / sentence boundaries."""
if len(text) <= max_len:
return [text]
chunks: list[str] = []
remaining = text
while remaining:
if len(remaining) <= max_len:
chunks.append(remaining)
break
cut = remaining.rfind("\n\n", 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[:cut])
remaining = remaining[cut + 2:]
continue
cut = remaining.rfind("\n", 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[:cut])
remaining = remaining[cut + 1:]
continue
for sep in (". ", "! ", "? "):
cut = remaining.rfind(sep, 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[: cut + 1])
remaining = remaining[cut + 2:]
break
else:
chunks.append(remaining[:max_len])
remaining = remaining[max_len:]
return [c for c in chunks if c.strip()]
# ── Config-backed bot storage ────────────────────────────────
async def get_bot_configs() -> list[dict]:
"""Load all bot configs from the Config store."""
from cptr.models import Config
bots = await Config.get("bots")
return bots if isinstance(bots, list) else []
async def save_bot_configs(bots: list[dict]) -> None:
"""Save all bot configs to the Config store."""
from cptr.models import Config
await Config.upsert({"bots": bots})
async def get_bot_by_id(bot_id: str) -> dict | None:
"""Find a single bot config by ID."""
for bot in await get_bot_configs():
if bot.get("id") == bot_id:
return bot
return None
async def upsert_bot(bot: dict) -> None:
"""Insert or update a single bot config."""
bots = await get_bot_configs()
for i, b in enumerate(bots):
if b.get("id") == bot.get("id"):
bots[i] = bot
await save_bot_configs(bots)
return
bots.append(bot)
await save_bot_configs(bots)
async def delete_bot_config(bot_id: str) -> bool:
"""Remove a bot config by ID."""
bots = await get_bot_configs()
filtered = [b for b in bots if b.get("id") != bot_id]
if len(filtered) == len(bots):
return False
await save_bot_configs(filtered)
return True
# ── Thread mapping via chat.meta ─────────────────────────────
async def find_chat_for_thread(bot_id: str, external_thread_id: str) -> str | None:
"""Find an existing cptr chat_id for a platform thread.
Scans chats with matching bridge metadata. This is fine for the
small number of active bridge threads (typically < 100).
"""
from cptr.models import Chat
from cptr.utils.db import get_db
from sqlalchemy import select
async with await get_db() as db:
result = await db.execute(
select(Chat).where(Chat.user_id.isnot(None))
)
for chat in result.scalars():
meta = chat.meta or {}
if (
meta.get("bridge_bot_id") == bot_id
and meta.get("bridge_external_thread_id") == external_thread_id
):
return chat.id
return None
# ── BotManager ───────────────────────────────────────────────
class BotManager:
"""Manages messaging bot lifecycles.
Singleton attached to ``app.state.bot_manager``. Reads bot configs
from the Config store on startup, creates adapters, and runs them as
asyncio tasks.
"""
def __init__(self) -> None:
self._adapters: dict[str, BaseAdapter] = {} # bot_id → adapter
self._tasks: dict[str, asyncio.Task] = {} # bot_id → polling task
self._stream_tasks: dict[str, asyncio.Task] = {} # key → streaming task
# ── Lifecycle ──────────────────────────────────────────
async def start_all(self) -> None:
"""Load all active bots from Config and start them."""
bots = await get_bot_configs()
started = 0
for bot in bots:
if not bot.get("is_active", True):
continue
try:
await self.start_bot(bot)
started += 1
except Exception:
logger.exception("Failed to start bot %s", bot.get("name", "?"))
if started:
logger.info("Bot manager started %d bot(s)", started)
async def start_bot(self, bot: dict) -> None:
"""Start a single bot adapter."""
bot_id = bot["id"]
if bot_id in self._tasks:
logger.warning("Bot %s already running", bot_id[:8])
return
adapter = self._create_adapter(bot)
if adapter is None:
logger.error("Unknown platform '%s' for bot %s", bot.get("platform"), bot_id[:8])
return
adapter.on_message = lambda event, _bot=bot: self._handle_message(event, _bot)
self._adapters[bot_id] = adapter
async def _run() -> None:
try:
ok = await adapter.connect()
if not ok:
logger.error("Bot %s failed to connect", bot.get("name", "?"))
return
logger.info("Bot %s connected on %s", bot.get("name"), bot.get("platform"))
while True:
await asyncio.sleep(3600)
except asyncio.CancelledError:
pass
except Exception:
logger.exception("Bot %s crashed", bot_id[:8])
finally:
try:
await adapter.disconnect()
except Exception:
logger.debug("Adapter disconnect error", exc_info=True)
self._tasks[bot_id] = asyncio.create_task(_run())
async def stop_bot(self, bot_id: str) -> None:
task = self._tasks.pop(bot_id, None)
if task and not task.done():
task.cancel()
try:
await asyncio.wait_for(task, timeout=5.0)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass
self._adapters.pop(bot_id, None)
logger.info("Bot %s stopped", bot_id[:8])
async def stop_all(self) -> None:
for bot_id in list(self._tasks.keys()):
await self.stop_bot(bot_id)
def is_running(self, bot_id: str) -> bool:
task = self._tasks.get(bot_id)
return task is not None and not task.done()
def get_status(self) -> dict[str, bool]:
return {bid: not t.done() for bid, t in self._tasks.items()}
# ── Adapter factory ────────────────────────────────────
def _create_adapter(self, bot: dict) -> BaseAdapter | None:
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import decrypt_key
token = decrypt_key(bot["token"], _get_jwt_secret())
if bot["platform"] == "telegram":
from cptr.utils.adapters.telegram import TelegramAdapter
return TelegramAdapter(token=token)
if bot["platform"] == "discord":
from cptr.utils.adapters.discord import DiscordAdapter
return DiscordAdapter(token=token)
if bot["platform"] == "slack":
from cptr.utils.adapters.slack import SlackAdapter
return SlackAdapter(token=token)
if bot["platform"] == "whatsapp":
from cptr.utils.adapters.whatsapp import WhatsAppAdapter
return WhatsAppAdapter(token=token, bot_id=bot["id"])
if bot["platform"] == "signal":
from cptr.utils.adapters.signal import SignalAdapter
return SignalAdapter(token=token)
return None
# ── Message handling ───────────────────────────────────
async def _handle_message(self, event: MessageEvent, bot: dict) -> None:
"""Core message handler: auth → commands → thread map → create chat → start_task → stream."""
# 1. Auth check
allowed = bot.get("allowed_senders") or []
if allowed and event.sender_id not in allowed:
logger.debug("Ignoring unauthorized sender %s on bot %s", event.sender_id, bot["id"][:8])
return
adapter = self._adapters.get(bot["id"])
text = (event.text or "").strip()
# Normalize: strip Discord bot mention prefix (<@123456>)
# and Telegram command suffix (/cmd@BotName → /cmd)
import re
clean = re.sub(r"<@!?\d+>\s*", "", text).strip()
cmd = clean.split("@")[0].lower() if clean.startswith("/") else ""
# 2. Slash commands
if cmd in ("/new", "/reset", "/start"):
await self._create_chat(event, bot)
if adapter:
try:
await adapter.send(event.chat_id, "✨ New conversation started.")
except Exception:
pass
return
if cmd == "/help":
help_text = (
"/new — Start a new conversation\n"
"/workspace <name> — Switch workspace (starts new chat)\n"
"/workspaces — List available workspaces\n"
"/help — Show this message"
)
if adapter:
try:
await adapter.send(event.chat_id, help_text)
except Exception:
pass
return
if cmd == "/workspaces":
from cptr.models import Workspace
workspaces = await Workspace.get_by_user(bot["user_id"])
if not workspaces:
if adapter:
await adapter.send(event.chat_id, "No workspaces found.")
return
current = bot.get("workspace", "")
lines = []
for ws in workspaces:
marker = " ←" if ws.path == current else ""
lines.append(f"• {ws.name}{marker}")
if adapter:
try:
await adapter.send(event.chat_id, "\n".join(lines))
except Exception:
pass
return
if cmd == "/workspace":
# /workspace <name> — switch workspace
parts = clean.split(None, 1)
ws_name = parts[1].strip() if len(parts) > 1 else ""
if not ws_name:
if adapter:
await adapter.send(event.chat_id, "Usage: /workspace <name>")
return
from cptr.models import Workspace
workspaces = await Workspace.get_by_user(bot["user_id"])
match = None
ws_lower = ws_name.lower()
for ws in workspaces:
if ws.name.lower() == ws_lower or ws.path.lower().endswith("/" + ws_lower):
match = ws
break
# Fuzzy: partial match
if not match:
for ws in workspaces:
if ws_lower in ws.name.lower():
match = ws
break
if not match:
if adapter:
await adapter.send(event.chat_id, f"Workspace '{ws_name}' not found. Use /workspaces to list.")
return
# Update bot config with new workspace
from cptr.utils.config import Config
bots_raw = await Config.get("bots") or []
for b in bots_raw:
if b.get("id") == bot["id"]:
b["workspace"] = match.path
break
await Config.upsert({"bots": bots_raw})
bot["workspace"] = match.path
# Start a new chat in the new workspace
await self._create_chat(event, bot)
if adapter:
try:
await adapter.send(event.chat_id, f"✨ Switched to {match.name}\nNew conversation started.")
except Exception:
pass
return
if not clean:
return
# 3. Thread mapping — find or create a cptr chat
chat_id = await find_chat_for_thread(bot["id"], event.chat_id)
if not chat_id:
chat_id = await self._create_chat(event, bot)
# Use the cleaned text (bot mention stripped) for the actual message
event.text = clean
# 4. Dispatch task with streaming
await self._dispatch_task(chat_id, event, bot, adapter)
async def _create_chat(self, event: MessageEvent, bot: dict) -> str:
from cptr.models import Chat
from cptr.utils.config import now_ms
title = f"{event.sender_name} ({bot['platform']})"
chat = await Chat.create(
user_id=bot["user_id"],
title=title[:100],
meta={
"workspace": bot["workspace"],
"bridge_bot_id": bot["id"],
"bridge_platform": bot["platform"],
"bridge_external_thread_id": event.chat_id,
"params": {"tool_approval_mode": "full"},
},
created_at=now_ms(),
)
from pathlib import Path
chats_dir = Path(bot["workspace"]) / ".cptr" / "chats"
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
return chat.id
async def _dispatch_task(
self, chat_id: str, event: MessageEvent, bot: dict, adapter: BaseAdapter | None,
) -> None:
from cptr.models import Chat, ChatMessage
from cptr.routers.chat import _resolve_connection
from cptr.utils.chat_task import start_task, _task_chat
from cptr.utils.config import now_ms
# Get current chat state for parent_id threading
chat = await Chat.get_by_id(chat_id)
parent_id = chat.current_message_id if chat else None
# Don't dispatch if a task is already running for this chat
active_chat_ids = set(_task_chat.values())
if chat_id in active_chat_ids:
await ChatMessage.create(
chat_id=chat_id, role="user", content=event.text,
parent_id=parent_id,
meta={"queued": True}, created_at=now_ms(),
)
logger.info("[bridge] Queued message for busy chat %s", chat_id[:8])
return
# Create user message — parent_id chains to previous assistant reply
user_msg = await ChatMessage.create(
chat_id=chat_id, role="user", content=event.text,
parent_id=parent_id, created_at=now_ms(),
)
# Resolve model connection
try:
connection, bare_model = await _resolve_connection(bot["model_id"])
except Exception:
logger.exception("[bridge] Failed to resolve model %s", bot["model_id"])
if adapter:
await adapter.send(event.chat_id, "⚠️ Model connection error. Check settings.")
return
# Create assistant placeholder
assistant_msg = await ChatMessage.create(
chat_id=chat_id, role="assistant", content="", parent_id=user_msg.id,
model=bot["model_id"], done=False, created_at=now_ms(),
)
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
# Export JSON so the web UI can see the chat immediately
from cptr.utils.chat_export import export_chat_to_file
await export_chat_to_file(chat_id)
# Send initial "thinking" message for non-draft platforms (Discord)
# Telegram uses sendMessageDraft which handles this natively
platform_msg_id = None
if adapter and bot["platform"] != "telegram":
try:
platform_msg_id = await adapter.send(event.chat_id, "⏳ Thinking...")
except Exception:
logger.debug("[bridge] Failed to send initial message", exc_info=True)
# Start the streaming edit loop
stream_key = f"{bot['id']}:{event.chat_id}"
self._stream_tasks[stream_key] = asyncio.create_task(
self._stream_loop(
adapter, event.chat_id, platform_msg_id,
assistant_msg.id, bot,
)
)
# Start the agentic loop
start_task(
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=bot["user_id"],
connection=connection,
workspace=bot["workspace"],
model=bare_model,
)
logger.info("[bridge] Started task for bot %s, chat %s", bot["id"][:8], chat_id[:8])
async def _stream_loop(
self,
adapter: BaseAdapter | None,
platform_chat_id: str,
platform_msg_id: str | None,
task_message_id: str,
bot: dict,
) -> None:
"""Stream task output to the platform in real time.
Telegram: uses sendMessageDraft for smooth native streaming, then
sendMessage to persist the final response (drafts are ephemeral).
Discord: uses edit-based streaming (PATCH /messages).
"""
from cptr.utils.chat_task import _task_state, _tasks
if not adapter:
return
max_len = 4096 if bot["platform"] == "telegram" else 2000
last_sent = ""
is_telegram = bot["platform"] == "telegram"
# Telegram: use draft-based streaming
draft_id: int | None = None
use_draft = is_telegram
if use_draft:
try:
from cptr.utils.adapters.telegram import TelegramAdapter
if isinstance(adapter, TelegramAdapter):
# Start with empty draft → shows "Thinking..." placeholder
draft_id = await adapter.send_draft(platform_chat_id, "", None)
else:
use_draft = False
except Exception:
use_draft = False
logger.debug("[bridge] Draft not supported, falling back to edit", exc_info=True)
# Fallback: if draft failed or non-Telegram, ensure we have a message to edit
if not use_draft and not platform_msg_id:
try:
platform_msg_id = await adapter.send(platform_chat_id, "⏳ Thinking...")
except Exception:
logger.debug("[bridge] Failed to send fallback message", exc_info=True)
try:
while True:
task = _tasks.get(task_message_id)
task_done = task is None or task.done()
state = _task_state.get(task_message_id)
content = (state.get("content", "") if state else "").strip()
output_items = state.get("output", []) if state else []
# Build display: tool progress + text content
tool_lines = _render_tool_progress(output_items)
display_parts = []
if tool_lines:
display_parts.append(tool_lines)
if content:
display_parts.append(content)
display = "\n\n".join(display_parts).strip()
if display and display != last_sent:
display = display[:max_len]
if use_draft:
try:
draft_id = await adapter.send_draft(
platform_chat_id, display, draft_id
)
last_sent = display
except Exception:
use_draft = False
if not use_draft and platform_msg_id:
try:
await adapter.edit(platform_chat_id, platform_msg_id, display)
last_sent = display
except Exception:
pass
elif not display and not last_sent:
if not use_draft:
try:
await adapter.send_typing(platform_chat_id)
except Exception:
pass
if task_done:
break
await asyncio.sleep(STREAM_EDIT_INTERVAL)
# ── Task complete — send final response ──
from cptr.models import ChatMessage
msg = await ChatMessage.get_by_id(task_message_id)
final_content = (msg.content if msg else content).strip()
if not final_content:
if use_draft:
await adapter.send(platform_chat_id, "✅ Done (no text output)")
elif platform_msg_id:
await adapter.edit(platform_chat_id, platform_msg_id, "✅ Done (no text output)")
return
final_display = final_content
if use_draft:
# Draft is ephemeral — must send a real message to persist
chunks = chunk_message(final_display, max_len)
for chunk in chunks:
try:
await adapter.send(platform_chat_id, chunk)
except Exception:
logger.exception("[bridge] Failed to send final chunk")
else:
# Discord: edit the placeholder, then send overflow
if len(final_display) <= max_len and platform_msg_id:
try:
await adapter.edit(platform_chat_id, platform_msg_id, final_display)
return
except Exception:
pass
chunks = chunk_message(final_display, max_len)
if platform_msg_id and chunks:
try:
await adapter.edit(platform_chat_id, platform_msg_id, chunks[0])
chunks = chunks[1:]
except Exception:
pass
for chunk in chunks:
try:
await adapter.send(platform_chat_id, chunk)
except Exception:
logger.exception("[bridge] Failed to send reply chunk")
break
except asyncio.CancelledError:
pass
except Exception:
logger.exception("[bridge] Stream loop error")
# ── Tool call rendering ──────────────────────────────────────
# Map tool names to compact emoji + labels
_TOOL_ICONS = {
"bash": "💻",
"shell": "💻",
"run_command": "💻",
"read_file": "📄",
"write_file": "✏️",
"edit_file": "✏️",
"create_file": "✏️",
"replace_file": "✏️",
"search": "🔍",
"grep": "🔍",
"find_files": "🔍",
"web_search": "🌐",
"browser": "🌐",
"create_artifact": "📎",
}
def _render_tool_progress(output_items: list[dict]) -> str:
"""Render tool calls as compact status lines for streaming display.
Example output:
💻 `ls -la src/`
📄 `main.py` (reading)
✏️ `config.ts` (editing)
"""
lines = []
for item in output_items:
item_type = item.get("type", "")
if item_type != "function_call":
continue
name = item.get("name", "")
status = item.get("status", "")
args = item.get("arguments", {})
icon = _TOOL_ICONS.get(name, "🔧")
# Extract the most relevant argument for display
label = _tool_label(name, args)
status_text = "" if status == "completed" else " _(running)_"
lines.append(f"{icon} `{label}`{status_text}")
return "\n".join(lines[-5:]) # Show last 5 tool calls max
def _render_tool_summary(output_items: list[dict]) -> str:
"""Render a compact summary of all tools used (for final message).
Example: "🔧 Used 3 tools: bash, read_file, write_file"
"""
tool_names = []
for item in output_items:
if item.get("type") == "function_call":
name = item.get("name", "unknown")
if name not in tool_names:
tool_names.append(name)
if not tool_names:
return ""
count = sum(1 for i in output_items if i.get("type") == "function_call")
names = ", ".join(tool_names[:5])
if len(tool_names) > 5:
names += f" +{len(tool_names) - 5} more"
return f"🔧 _{count} tool call{'s' if count != 1 else ''}: {names}_"
def _tool_label(name: str, args: dict) -> str:
"""Extract a short, meaningful label from tool arguments."""
if isinstance(args, str):
return name
# Command execution
if name in ("bash", "shell", "run_command"):
cmd = args.get("command", args.get("cmd", ""))
if isinstance(cmd, str):
return cmd[:60] if cmd else name
return name
# File operations
for key in ("path", "file", "file_path", "filename", "target"):
val = args.get(key, "")
if val and isinstance(val, str):
# Just show the basename
parts = val.rsplit("/", 1)
return parts[-1] if parts else val
# Search
if name in ("search", "grep", "find_files"):
query = args.get("query", args.get("pattern", ""))
if isinstance(query, str):
return query[:40] if query else name
return name
+12 -3
View File
@@ -944,20 +944,27 @@ async def run_chat_task(
)
if should_auto:
# Show tool call in progress BEFORE execution
item["status"] = "in_progress"
output_items.append(item)
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
_sync_state()
if name == "create_artifact":
result = await create_artifact(**event["arguments"], workspace=workspace)
else:
result = await execute_tool(name, event["arguments"], {"workspace": workspace, "user_id": user_id, "model_id": model})
# Update status to completed
item["status"] = "completed"
output_items.append(item)
result_item = {
"type": "function_call_output",
"call_id": event["call_id"],
"output": result,
}
output_items.append(result_item)
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
await emit(output=result_item)
_sync_state()
@@ -1000,6 +1007,8 @@ async def run_chat_task(
elif event["type"] == "usage":
_flush_text()
usage = {k: v for k, v in event.items() if k != "type"}
if "total_tokens" not in usage:
usage["total_tokens"] = usage.get("input_tokens", 0) + usage.get("output_tokens", 0)
last_usage = usage
new_messages_since = 0
logger.info(
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.2.3"
version = "0.3.0"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"