-
Runs
+
{$t('automations.runs')}
{#if runs.length === 0}
-
No runs yet
+
{$t('automations.noRuns')}
{:else}
{#each runs as run}
@@ -340,7 +341,7 @@
setTimeout(() => openChatTab(run.chat_id!), 300);
}}
>
- view chat →
+ {$t('automations.viewChat')}
{/if}
{#if run.error}
@@ -360,12 +361,12 @@
{/if}
-
Automations
+
{$t('automations.title')}
{#if total > 0}
{total}
{/if}
@@ -376,14 +377,14 @@
bind:value={statusFilter}
onchange={loadList}
>
-
-
-
+
+
+
@@ -396,7 +397,7 @@
@@ -416,14 +417,14 @@
{:else if items.length === 0}
- {searchQuery ? 'No matches' : 'No automations yet'}
+ {searchQuery ? $t('automations.noMatches') : $t('automations.noAutomations')}
{#if !searchQuery}
{/if}
@@ -448,7 +449,7 @@
diff --git a/cptr/frontend/src/lib/components/common/ModelSelector.svelte b/cptr/frontend/src/lib/components/common/ModelSelector.svelte
index 5091d82..4dff816 100644
--- a/cptr/frontend/src/lib/components/common/ModelSelector.svelte
+++ b/cptr/frontend/src/lib/components/common/ModelSelector.svelte
@@ -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 @@
>
{$chatModels.length === 0
- ? 'No models available'
- : $chatModels.find((m) => m.id === selectedModel)?.name || 'Select model'} m.id === selectedModel)?.name || $t('modelSelector.selectModel')}
{#if $chatModels.length > 0}
{/snippet}
{#snippet empty()}
-
No matches
+
{$t('modelSelector.noMatches')}
{/snippet}
{/if}
diff --git a/cptr/frontend/src/lib/i18n/locales/de.json b/cptr/frontend/src/lib/i18n/locales/de.json
index aea7b5e..964c9c4 100644
--- a/cptr/frontend/src/lib/i18n/locales/de.json
+++ b/cptr/frontend/src/lib/i18n/locales/de.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json
index 88068ca..97fe5e5 100644
--- a/cptr/frontend/src/lib/i18n/locales/en.json
+++ b/cptr/frontend/src/lib/i18n/locales/en.json
@@ -301,5 +301,112 @@
"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>Esc1> 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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/es.json b/cptr/frontend/src/lib/i18n/locales/es.json
index 1d8206d..274bb79 100644
--- a/cptr/frontend/src/lib/i18n/locales/es.json
+++ b/cptr/frontend/src/lib/i18n/locales/es.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/fr.json b/cptr/frontend/src/lib/i18n/locales/fr.json
index 5f3461f..5b6498b 100644
--- a/cptr/frontend/src/lib/i18n/locales/fr.json
+++ b/cptr/frontend/src/lib/i18n/locales/fr.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/ja.json b/cptr/frontend/src/lib/i18n/locales/ja.json
index 42063da..87b1d3c 100644
--- a/cptr/frontend/src/lib/i18n/locales/ja.json
+++ b/cptr/frontend/src/lib/i18n/locales/ja.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/ko.json b/cptr/frontend/src/lib/i18n/locales/ko.json
index 4a37f59..bcf9602 100644
--- a/cptr/frontend/src/lib/i18n/locales/ko.json
+++ b/cptr/frontend/src/lib/i18n/locales/ko.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/pt-BR.json b/cptr/frontend/src/lib/i18n/locales/pt-BR.json
index 5f39676..fcf57e6 100644
--- a/cptr/frontend/src/lib/i18n/locales/pt-BR.json
+++ b/cptr/frontend/src/lib/i18n/locales/pt-BR.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/ru.json b/cptr/frontend/src/lib/i18n/locales/ru.json
index f4bf945..2c01255 100644
--- a/cptr/frontend/src/lib/i18n/locales/ru.json
+++ b/cptr/frontend/src/lib/i18n/locales/ru.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/zh-CN.json b/cptr/frontend/src/lib/i18n/locales/zh-CN.json
index be0981f..3433a9f 100644
--- a/cptr/frontend/src/lib/i18n/locales/zh-CN.json
+++ b/cptr/frontend/src/lib/i18n/locales/zh-CN.json
@@ -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"
}
diff --git a/cptr/frontend/src/lib/i18n/locales/zh-TW.json b/cptr/frontend/src/lib/i18n/locales/zh-TW.json
index 0f96c2f..4f313cf 100644
--- a/cptr/frontend/src/lib/i18n/locales/zh-TW.json
+++ b/cptr/frontend/src/lib/i18n/locales/zh-TW.json
@@ -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"
}
From 194b1a84d88ca96644b1b46b04ca2c50ad2ff247 Mon Sep 17 00:00:00 2001
From: Timothy Jaeryang Baek
Date: Fri, 12 Jun 2026 11:23:07 +0100
Subject: [PATCH 2/9] refac
---
.../components/chat/AssistantMessage.svelte | 70 +++++++++++++++++++
.../src/lib/components/chat/ChatPanel.svelte | 1 +
2 files changed, 71 insertions(+)
diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte
index fa9576a..e3eff4f 100644
--- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte
+++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte
@@ -11,6 +11,7 @@
content: string;
done: boolean;
output: any[] | null;
+ usage: Record | 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(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);
+ }
@@ -934,6 +954,56 @@
>
{/if}
+ {#if done && usage && Object.keys(usage).length > 0}
+
+
+ {#if showUsageTooltip}
+
+
+ {#each Object.entries(usage) as [key, value]}
+
+ {formatUsageLabel(key)}
+ {formatUsageValue(key, value)}
+
+ {/each}
+
+
+
+
+ {/if}
+
+ {/if}
{/if}
{/if}
diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte
index 1e1bfba..662950d 100644
--- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte
+++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte
@@ -929,6 +929,7 @@
content={msg.content}
done={msg.done}
output={msg.output}
+ usage={msg.usage}
{chatId}
messageId={msg.id}
{siblingIndex}
From d6a834650c8dfce6d8e8862d5e143a550f8a827c Mon Sep 17 00:00:00 2001
From: Timothy Jaeryang Baek
Date: Fri, 12 Jun 2026 11:25:09 +0100
Subject: [PATCH 3/9] refac
---
cptr/frontend/src/app.css | 1 +
1 file changed, 1 insertion(+)
diff --git a/cptr/frontend/src/app.css b/cptr/frontend/src/app.css
index 31bdf3e..64a0846 100644
--- a/cptr/frontend/src/app.css
+++ b/cptr/frontend/src/app.css
@@ -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;
From 1cc3109c62d362557e6373e9916ba9fe55160ee3 Mon Sep 17 00:00:00 2001
From: Timothy Jaeryang Baek
Date: Fri, 12 Jun 2026 11:29:05 +0100
Subject: [PATCH 4/9] refac
---
cptr/utils/chat_task.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py
index 4f1a4a5..f4e2d11 100644
--- a/cptr/utils/chat_task.py
+++ b/cptr/utils/chat_task.py
@@ -1000,6 +1000,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(
From 152ce6643f8c446a495ce27c1d7e5d6b384b9e0a Mon Sep 17 00:00:00 2001
From: Timothy Jaeryang Baek
Date: Fri, 12 Jun 2026 16:02:40 +0100
Subject: [PATCH 5/9] refac
---
cptr/utils/ai.py | 22 +++++++++++++++++-----
1 file changed, 17 insertions(+), 5 deletions(-)
diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py
index 072ba91..e162836 100644
--- a/cptr/utils/ai.py
+++ b/cptr/utils/ai.py
@@ -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):
From d22b01b5552363655f81ce3a0b613f08b51a6684 Mon Sep 17 00:00:00 2001
From: Timothy Jaeryang Baek
Date: Fri, 12 Jun 2026 16:07:13 +0100
Subject: [PATCH 6/9] refac
---
cptr/app.py | 15 +
cptr/frontend/src/lib/apis/bots.ts | 70 ++
.../components/Admin/CreateBotModal.svelte | 262 +++++++
.../src/lib/components/Admin/Messaging.svelte | 149 ++++
.../src/lib/components/SettingsModal.svelte | 5 +
cptr/frontend/src/lib/i18n/locales/en.json | 26 +-
cptr/models/__init__.py | 1 +
cptr/routers/__init__.py | 3 +
cptr/routers/bridge.py | 243 ++++++
cptr/routers/chat.py | 4 +
cptr/utils/adapters/__init__.py | 1 +
cptr/utils/adapters/discord.py | 259 +++++++
cptr/utils/adapters/telegram.py | 270 +++++++
cptr/utils/bridge.py | 718 ++++++++++++++++++
cptr/utils/chat_task.py | 13 +-
15 files changed, 2035 insertions(+), 4 deletions(-)
create mode 100644 cptr/frontend/src/lib/apis/bots.ts
create mode 100644 cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte
create mode 100644 cptr/frontend/src/lib/components/Admin/Messaging.svelte
create mode 100644 cptr/routers/bridge.py
create mode 100644 cptr/utils/adapters/__init__.py
create mode 100644 cptr/utils/adapters/discord.py
create mode 100644 cptr/utils/adapters/telegram.py
create mode 100644 cptr/utils/bridge.py
diff --git a/cptr/app.py b/cptr/app.py
index 4022736..27860af 100644
--- a/cptr/app.py
+++ b/cptr/app.py
@@ -9,6 +9,7 @@ from cptr.routers import (
admin_router,
auth_router,
automations_router,
+ bridge_router,
chat_router,
events_router,
files_router,
@@ -55,6 +56,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 +201,7 @@ 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(chat_router)
app.include_router(events_router)
app.include_router(files_router)
diff --git a/cptr/frontend/src/lib/apis/bots.ts b/cptr/frontend/src/lib/apis/bots.ts
new file mode 100644
index 0000000..e214aff
--- /dev/null
+++ b/cptr/frontend/src/lib/apis/bots.ts
@@ -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 | 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 {
+ return fetchJSON('/api/admin/bots');
+}
+
+export async function createBot(form: BotForm): Promise {
+ return fetchJSON('/api/admin/bots', jsonBody(form));
+}
+
+export async function updateBot(id: string, form: BotUpdate): Promise {
+ 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 }));
+}
diff --git a/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte b/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte
new file mode 100644
index 0000000..86c4265
--- /dev/null
+++ b/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte
@@ -0,0 +1,262 @@
+
+
+
+
+ {
+ if (e.key === 'Enter' && name.trim() && (bot || token.trim())) handleSubmit();
+ }}
+ >
+
+ {bot ? 'Edit Bot' : 'Add Bot'}
+
+
+ {#if !bot}
+
+
+
+
+
+
+
+
+
+
+
+ {:else}
+
+
+
+ {/if}
+
+
+
+
+
+ {#if !bot}
+
+ {/if}
+
+
+ {#if verifyResult}
+
+ {#if verifyResult.ok}
+ ✓ {verifyResult.info?.username ? `@${verifyResult.info.username}` : `ID: ${verifyResult.info?.id}`}
+ {:else}
+ ✗ {verifyResult.error}
+ {/if}
+
+ {/if}
+
+
+
+
Comma-separated user IDs. Leave empty to allow all.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{#if showWsMenu && wsBtnEl}
+ (showWsMenu = false)}
+ preferAbove={true}
+ maxHeight="15rem"
+ className="w-48"
+ />
+{/if}
diff --git a/cptr/frontend/src/lib/components/Admin/Messaging.svelte b/cptr/frontend/src/lib/components/Admin/Messaging.svelte
new file mode 100644
index 0000000..8b97415
--- /dev/null
+++ b/cptr/frontend/src/lib/components/Admin/Messaging.svelte
@@ -0,0 +1,149 @@
+
+
+
+
{$t('admin.messaging')}
+
+
+
+{#if loading}
+
+
+
+{:else}
+
+ {#each bots as bot}
+
+
+
+ {bot.platform === 'telegram' ? 'TG' : bot.platform === 'discord' ? 'DC' : bot.platform.slice(0, 2).toUpperCase()}
+
+
+
+
+ (editBot = bot)}
+ onkeydown={() => {}}
+ >
+ {bot.name}
+
+
+
+
+
+
+
+ toggleRunning(e, bot)}
+ onkeydown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleRunning(e, bot);
+ }
+ }}
+ >
+
+
+
+ {/each}
+
+ {#if bots.length === 0}
+
No messaging bots configured.
+ {/if}
+
+{/if}
+
+{#if showCreate}
+ (showCreate = false)} onsave={handleSaved} />
+{/if}
+
+{#if editBot}
+ (editBot = null)}
+ onsave={handleSaved}
+ />
+{/if}
diff --git a/cptr/frontend/src/lib/components/SettingsModal.svelte b/cptr/frontend/src/lib/components/SettingsModal.svelte
index 4f4bad8..a5de3f1 100644
--- a/cptr/frontend/src/lib/components/SettingsModal.svelte
+++ b/cptr/frontend/src/lib/components/SettingsModal.svelte
@@ -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 {
@@ -44,6 +46,7 @@
{ 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' }
]);
@@ -113,6 +116,8 @@
{:else if activeTab === 'models'}
+ {:else if activeTab === 'messaging'}
+
{:else if activeTab === 'admin_settings'}
{/if}
diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json
index 97fe5e5..cd1c64a 100644
--- a/cptr/frontend/src/lib/i18n/locales/en.json
+++ b/cptr/frontend/src/lib/i18n/locales/en.json
@@ -408,5 +408,29 @@
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation",
- "connections.failedToUpdate": "Failed to update connection"
+ "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)"
}
diff --git a/cptr/models/__init__.py b/cptr/models/__init__.py
index 4482216..3727577 100644
--- a/cptr/models/__init__.py
+++ b/cptr/models/__init__.py
@@ -21,3 +21,4 @@ __all__ = [
"Automation",
"AutomationRun",
]
+
diff --git a/cptr/routers/__init__.py b/cptr/routers/__init__.py
index ca203bc..78ed303 100644
--- a/cptr/routers/__init__.py
+++ b/cptr/routers/__init__.py
@@ -3,6 +3,7 @@
from cptr.routers.admin import router as admin_router
from cptr.routers.auth import router as auth_router
from cptr.routers.automations import router as automations_router
+from cptr.routers.bridge import router as bridge_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 +19,7 @@ __all__ = [
"admin_router",
"auth_router",
"automations_router",
+ "bridge_router",
"chat_router",
"events_router",
"files_router",
@@ -29,3 +31,4 @@ __all__ = [
"terminal_router",
"workspace_router",
]
+
diff --git a/cptr/routers/bridge.py b/cptr/routers/bridge.py
new file mode 100644
index 0000000..0d75a45
--- /dev/null
+++ b/cptr/routers/bridge.py
@@ -0,0 +1,243 @@
+"""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")}}
+
+ else:
+ raise HTTPException(400, f"Unsupported platform: {body.platform}")
+
+ except Exception as e:
+ return {"ok": False, "error": str(e)}
diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py
index a36e1da..d157547 100644
--- a/cptr/routers/chat.py
+++ b/cptr/routers/chat.py
@@ -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:
diff --git a/cptr/utils/adapters/__init__.py b/cptr/utils/adapters/__init__.py
new file mode 100644
index 0000000..9d00a6d
--- /dev/null
+++ b/cptr/utils/adapters/__init__.py
@@ -0,0 +1 @@
+"""Messaging platform adapters."""
diff --git a/cptr/utils/adapters/discord.py b/cptr/utils/adapters/discord.py
new file mode 100644
index 0000000..056755b
--- /dev/null
+++ b/cptr/utils/adapters/discord.py
@@ -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()
diff --git a/cptr/utils/adapters/telegram.py b/cptr/utils/adapters/telegram.py
new file mode 100644
index 0000000..6b6246c
--- /dev/null
+++ b/cptr/utils/adapters/telegram.py
@@ -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"]
diff --git a/cptr/utils/bridge.py b/cptr/utils/bridge.py
new file mode 100644
index 0000000..ba1ba00
--- /dev/null
+++ b/cptr/utils/bridge.py
@@ -0,0 +1,718 @@
+"""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)
+
+ 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"
+ "/reset — Same as /new\n"
+ "/help — Show this message"
+ )
+ if adapter:
+ try:
+ await adapter.send(event.chat_id, help_text)
+ 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
+
+
diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py
index f4e2d11..74d02c6 100644
--- a/cptr/utils/chat_task.py
+++ b/cptr/utils/chat_task.py
@@ -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()
From e1f98d6280ecbd1cae42f28210da3d48ab117a48 Mon Sep 17 00:00:00 2001
From: Timothy Jaeryang Baek
Date: Fri, 12 Jun 2026 16:17:08 +0100
Subject: [PATCH 7/9] refac
---
cptr/app.py | 2 +
.../components/Admin/CreateBotModal.svelte | 8 +-
.../src/lib/components/Admin/Messaging.svelte | 6 +-
cptr/frontend/src/lib/components/Icon.svelte | 19 ++
.../components/chat/AssistantMessage.svelte | 39 ++-
cptr/routers/__init__.py | 2 +
cptr/routers/bridge.py | 50 ++++
cptr/utils/adapters/signal.py | 218 +++++++++++++++
cptr/utils/adapters/slack.py | 249 ++++++++++++++++++
cptr/utils/adapters/whatsapp.py | 203 ++++++++++++++
cptr/utils/bridge.py | 12 +
11 files changed, 793 insertions(+), 15 deletions(-)
create mode 100644 cptr/utils/adapters/signal.py
create mode 100644 cptr/utils/adapters/slack.py
create mode 100644 cptr/utils/adapters/whatsapp.py
diff --git a/cptr/app.py b/cptr/app.py
index 27860af..4898808 100644
--- a/cptr/app.py
+++ b/cptr/app.py
@@ -10,6 +10,7 @@ from cptr.routers import (
auth_router,
automations_router,
bridge_router,
+ webhook_router,
chat_router,
events_router,
files_router,
@@ -202,6 +203,7 @@ 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)
diff --git a/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte b/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte
index 86c4265..31d8dbf 100644
--- a/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte
+++ b/cptr/frontend/src/lib/components/Admin/CreateBotModal.svelte
@@ -59,7 +59,10 @@
const platformHints: Record = {
telegram: 'Create a bot via @BotFather',
- discord: 'Create a bot in the Developer Portal'
+ 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() {
@@ -146,6 +149,9 @@
>
+
+
+