diff --git a/README.ar.md b/README.ar.md
new file mode 100644
index 0000000000..b7175e5e3f
--- /dev/null
+++ b/README.ar.md
@@ -0,0 +1,132 @@
+
Open WebUI
+
+Open WebUI هو بيت للذكاء الاصطناعي : منصة قابلة للتوسعة وسهلة الاستخدام تستضيفها بنفسك، ومصممة للعمل بالكامل دون اتصال بالإنترنت. اربط النماذج المحلية عبر Ollama أو استخدم واجهات API المتوافقة مع OpenAI للنماذج المحلية والسحابية.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[استكشف Open WebUI →](https://docs.openwebui.com/)
+
+### التثبيت
+
+#### Python
+
+يتطلب Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+ثم افتح [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+ثم افتح [http://localhost:3000](http://localhost:3000).
+
+| وسم الصورة | المحتوى |
+| --- | --- |
+| `:main` | صورة قياسية تتضمن اعتماديات الذكاء الاصطناعي المحلي |
+| `:slim` | صورة خفيفة تستخدم خدمات خارجية للتضمينات واستخراج محتوى المستندات والصوت |
+| `:cuda` | Open WebUI مع تسريع CUDA |
+| `:ollama` | Open WebUI مرفقًا معه Ollama |
+| `:dev` | أحدث نسخة تطوير |
+
+أضف هذه الخيارات إلى `docker run` قبل اسم الصورة حسب الحاجة:
+
+| الخيار | الغرض |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | الاتصال بـ Ollama على خادم آخر |
+| `-e OPENAI_API_KEY=your_secret_key` | تعيين مفتاح API الخاص بك لدى OpenAI |
+| `-e HF_HUB_OFFLINE=1` | تعطيل تنزيل نماذج Hugging Face للاستخدام دون اتصال |
+| `--gpus all` | تمكين الوصول إلى وحدة معالجة الرسوميات Nvidia مع `:cuda` أو `:ollama`؛ يتطلب Nvidia Container Toolkit |
+
+راجع [دليل التثبيت باستخدام Docker](https://docs.openwebui.com/getting-started/quick-start/) للاطلاع على خطوات الإعداد وخيارات الضبط.
+
+#### تطبيق سطح المكتب
+
+[نزّل تطبيق سطح المكتب الأصلي](https://github.com/open-webui/desktop) لأنظمة macOS وWindows وLinux.
+
+[اقرأ الوثائق →](https://docs.openwebui.com/getting-started/)
+
+### المنظومة
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): طبقة التنفيذ التي تجعل Open WebUI بيئة متكاملة للوكلاء، مع تنسيق مؤسسي لمساحات عمل منفصلة لكل مستخدم.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): اعكس المجلدات والمستودعات وحاويات التخزين ومواقع الويكي في قواعد معرفة Open WebUI باستخدام المزامنة التزايدية.
+- [Open WebUI Computer](https://github.com/open-webui/computer): حاسوبك في أي متصفح: الملفات والمحرر والطرفية وGit ووكلاء الذكاء الاصطناعي الاختياريون، جميعها تعمل على جهازك الفعلي.
+
+راجع [وثائق المنظومة](https://docs.openwebui.com/ecosystem/) لمزيد من التفاصيل.
+
+### استكشاف الأخطاء والتحديثات
+
+راجع [دليل استكشاف الأخطاء](https://docs.openwebui.com/troubleshooting/) لحل مشكلات الاتصال، و[دليل التحديث](https://docs.openwebui.com/getting-started/updating) لتحديث تثبيتك.
+
+### الوثائق
+
+راجع [الوثائق](https://docs.openwebui.com/) للإعداد والاستخدام، و[خارطة الطريق](https://docs.openwebui.com/roadmap/) للاطلاع على الأعمال المخطط لها.
+
+لإعداد Docker Compose أو Kubernetes أو غيرهما، راجع [وثائق التثبيت](https://docs.openwebui.com/getting-started/).
+
+### الدعم
+
+[افتح بلاغًا](https://github.com/open-webui/open-webui/issues) أو [ابدأ نقاشًا](https://github.com/open-webui/open-webui/discussions).
+
+تجدنا على [Reddit](https://www.reddit.com/r/OpenWebUI/) و[X](https://x.com/OpenWebUI) و[Discord](https://discord.gg/5rJgQTnV4s).
+
+### الأمان
+
+أبلغ عن الثغرات بسرية عبر [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). تُقبل البلاغات الأمنية عبر GitHub فقط.
+
+### سجل النجوم
+
+
+
+
+
+
+
+
+
+#### الترخيص
+
+يتضمن كودًا يخضع لترخيص Open WebUI License الذي يشترط الحفاظ على هوية Open WebUI التجارية، ومساهمات سابقة تخضع لتراخيصها الأصلية. راجع [LICENSE](./LICENSE) و[LICENSE_HISTORY](./LICENSE_HISTORY) للاطلاع على الشروط والسجل.
+
+[المؤسسات](https://docs.openwebui.com/enterprise) · [الوظائف](https://careers.openwebui.com/) · [الرعاية](https://github.com/sponsors/open-webui)
+
+أنشأه [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.bn.md b/README.bn.md
new file mode 100644
index 0000000000..7b278800ba
--- /dev/null
+++ b/README.bn.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI হলো AI-এর একটি আপন ঠিকানা : একটি সম্প্রসারণযোগ্য, সহজে ব্যবহারযোগ্য ও নিজে হোস্ট করা যায় এমন প্ল্যাটফর্ম, যা সম্পূর্ণ অফলাইনে চলার জন্য তৈরি। Ollama দিয়ে স্থানীয় মডেল সংযুক্ত করুন, অথবা স্থানীয় ও ক্লাউড মডেলের জন্য OpenAI-সামঞ্জস্যপূর্ণ API ব্যবহার করুন।
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Open WebUI ঘুরে দেখুন →](https://docs.openwebui.com/)
+
+### ইনস্টলেশন
+
+#### Python
+
+Python 3.12 প্রয়োজন।
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+এরপর [http://localhost:8080](http://localhost:8080) খুলুন।
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+এরপর [http://localhost:3000](http://localhost:3000) খুলুন।
+
+| ইমেজ ট্যাগ | যা অন্তর্ভুক্ত আছে |
+| --- | --- |
+| `:main` | স্থানীয় AI-এর প্রয়োজনীয় ডিপেন্ডেন্সিসহ স্ট্যান্ডার্ড ইমেজ |
+| `:slim` | এম্বেডিং, ডকুমেন্ট থেকে তথ্য আহরণ ও ভয়েসের জন্য বাহ্যিক সেবা ব্যবহার করা হালকা ইমেজ |
+| `:cuda` | CUDA অ্যাক্সেলারেশনসহ Open WebUI |
+| `:ollama` | Ollama-সহ Open WebUI |
+| `:dev` | সর্বশেষ ডেভেলপমেন্ট বিল্ড |
+
+প্রয়োজন অনুযায়ী `docker run` কমান্ডে ইমেজের নামের আগে এই অপশনগুলো যোগ করুন:
+
+| অপশন | উদ্দেশ্য |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | অন্য সার্ভারে থাকা Ollama-তে সংযোগ করা |
+| `-e OPENAI_API_KEY=your_secret_key` | আপনার OpenAI API কী সেট করা |
+| `-e HF_HUB_OFFLINE=1` | অফলাইনে ব্যবহারের জন্য Hugging Face মডেল ডাউনলোড বন্ধ করা |
+| `--gpus all` | `:cuda` বা `:ollama`-এর জন্য Nvidia GPU ব্যবহারের অনুমতি দেওয়া; Nvidia Container Toolkit প্রয়োজন |
+
+সেটআপের নির্দেশনা ও কনফিগারেশন অপশনের জন্য [Docker ইনস্টলেশন নির্দেশিকা](https://docs.openwebui.com/getting-started/quick-start/) দেখুন।
+
+#### ডেস্কটপ অ্যাপ
+
+macOS, Windows ও Linux-এর জন্য [নেটিভ ডেস্কটপ অ্যাপ ডাউনলোড করুন](https://github.com/open-webui/desktop)।
+
+[ডকুমেন্টেশন পড়ুন →](https://docs.openwebui.com/getting-started/)
+
+### ইকোসিস্টেম
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI-কে একটি পূর্ণাঙ্গ এজেন্ট পরিবেশে পরিণত করার এক্সিকিউশন স্তর, যেখানে প্রত্যেক ব্যবহারকারীর ওয়ার্কস্পেসের জন্য এন্টারপ্রাইজ অর্কেস্ট্রেশন রয়েছে।
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): ইনক্রিমেন্টাল সিঙ্কের মাধ্যমে ফোল্ডার, রিপোজিটরি, বাকেট ও উইকির প্রতিলিপি Open WebUI-এর নলেজ বেসে রাখুন।
+- [Open WebUI Computer](https://github.com/open-webui/computer): যেকোনো ব্রাউজারে আপনার কম্পিউটার: ফাইল, এডিটর, টার্মিনাল, Git ও ঐচ্ছিক AI এজেন্ট—সবই আপনার আসল মেশিনে চলে।
+
+বিস্তারিত জানতে [ইকোসিস্টেম ডকুমেন্টেশন](https://docs.openwebui.com/ecosystem/) দেখুন।
+
+### সমস্যা সমাধান ও আপডেট
+
+সংযোগের সমস্যার জন্য [সমস্যা সমাধানের নির্দেশিকা](https://docs.openwebui.com/troubleshooting/) এবং আপনার ইনস্টলেশন আপডেট করতে [আপডেট নির্দেশিকা](https://docs.openwebui.com/getting-started/updating) দেখুন।
+
+### ডকুমেন্টেশন
+
+কনফিগারেশন ও ব্যবহারের জন্য [ডকুমেন্টেশন](https://docs.openwebui.com/) এবং পরিকল্পিত কাজের জন্য [রোডম্যাপ](https://docs.openwebui.com/roadmap/) দেখুন।
+
+Docker Compose, Kubernetes ও অন্যান্য সেটআপের জন্য [ইনস্টলেশন ডকুমেন্টেশন](https://docs.openwebui.com/getting-started/) দেখুন।
+
+### সহায়তা
+
+[একটি ইস্যু খুলুন](https://github.com/open-webui/open-webui/issues) বা [আলোচনা শুরু করুন](https://github.com/open-webui/open-webui/discussions)।
+
+আমাদের পাবেন [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) ও [Discord](https://discord.gg/5rJgQTnV4s)-এ।
+
+### নিরাপত্তা
+
+[GitHub Security Advisories](https://github.com/open-webui/open-webui/security)-এর মাধ্যমে গোপনে নিরাপত্তা দুর্বলতা জানান। নিরাপত্তাসংক্রান্ত রিপোর্ট কেবল GitHub-এর মাধ্যমেই গ্রহণ করা হয়।
+
+### স্টারের ইতিহাস
+
+
+
+
+
+
+
+
+
+#### লাইসেন্স
+
+এতে Open WebUI License-এর আওতাধীন কোড রয়েছে, যা Open WebUI ব্র্যান্ডিং অক্ষুণ্ণ রাখা বাধ্যতামূলক করে, এবং আগের অবদানগুলো তাদের নিজ নিজ মূল লাইসেন্সের আওতায় রয়েছে। শর্ত ও ইতিহাসের জন্য [LICENSE](./LICENSE) ও [LICENSE_HISTORY](./LICENSE_HISTORY) দেখুন।
+
+[এন্টারপ্রাইজ](https://docs.openwebui.com/enterprise) · [ক্যারিয়ার](https://careers.openwebui.com/) · [স্পনসর করুন](https://github.com/sponsors/open-webui)
+
+তৈরি করেছেন [Timothy Jaeryang Baek](https://github.com/tjbck)।
diff --git a/README.br.md b/README.br.md
new file mode 100644
index 0000000000..a9e2b35fcc
--- /dev/null
+++ b/README.br.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI é um lar para a IA : uma plataforma auto-hospedada, extensível e fácil de usar, feita para funcionar totalmente offline. Conecte modelos locais pelo Ollama ou use APIs compatíveis com OpenAI para modelos locais e na nuvem.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Explore o Open WebUI →](https://docs.openwebui.com/)
+
+### Instalação
+
+#### Python
+
+Requer Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Depois, abra [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Depois, abra [http://localhost:3000](http://localhost:3000).
+
+| Tag da imagem | Conteúdo |
+| --- | --- |
+| `:main` | Imagem padrão com dependências de IA local |
+| `:slim` | Imagem leve que usa serviços externos para embeddings, extração de documentos e voz |
+| `:cuda` | Open WebUI com aceleração CUDA |
+| `:ollama` | Open WebUI com Ollama incluído |
+| `:dev` | Build de desenvolvimento mais recente |
+
+Adicione estas opções ao `docker run` antes do nome da imagem, conforme necessário:
+
+| Opção | Finalidade |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Conectar ao Ollama em outro servidor |
+| `-e OPENAI_API_KEY=your_secret_key` | Definir sua chave de API da OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Desativar downloads de modelos do Hugging Face para uso offline |
+| `--gpus all` | Habilitar acesso à GPU Nvidia para `:cuda` ou `:ollama`; requer o Nvidia Container Toolkit |
+
+Consulte o [guia de instalação com Docker](https://docs.openwebui.com/getting-started/quick-start/) para instruções e opções de configuração.
+
+#### Aplicativo para desktop
+
+[Baixe o aplicativo nativo para desktop](https://github.com/open-webui/desktop) para macOS, Windows e Linux.
+
+[Leia a documentação →](https://docs.openwebui.com/getting-started/)
+
+### Ecossistema
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): A camada de execução que transforma o Open WebUI em um ambiente completo para agentes, com orquestração empresarial de espaços de trabalho por usuário.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Espelhe pastas, repositórios, buckets e wikis nas bases de conhecimento do Open WebUI com sincronização incremental.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Seu computador em qualquer navegador: arquivos, editor, terminal, Git e agentes de IA opcionais, executados na sua própria máquina.
+
+Consulte a [documentação do ecossistema](https://docs.openwebui.com/ecosystem/) para mais detalhes.
+
+### Solução de problemas e atualizações
+
+Consulte o [guia de solução de problemas](https://docs.openwebui.com/troubleshooting/) para problemas de conexão e o [guia de atualização](https://docs.openwebui.com/getting-started/updating) para atualizar sua instalação.
+
+### Documentação
+
+Consulte a [documentação](https://docs.openwebui.com/) para configuração e uso, e o [roteiro](https://docs.openwebui.com/roadmap/) para o trabalho planejado.
+
+Para Docker Compose, Kubernetes e outras formas de instalação, consulte a [documentação de instalação](https://docs.openwebui.com/getting-started/).
+
+### Suporte
+
+[Abra uma issue](https://github.com/open-webui/open-webui/issues) ou [inicie uma discussão](https://github.com/open-webui/open-webui/discussions).
+
+Encontre-nos no [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) e [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Segurança
+
+Relate vulnerabilidades de forma privada pelo [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Relatos de segurança são aceitos somente pelo GitHub.
+
+### Histórico de estrelas
+
+
+
+
+
+
+
+
+
+#### Licença
+
+Inclui código sob a Open WebUI License, que exige preservar a marca Open WebUI, e contribuições anteriores sob suas licenças originais. Consulte [LICENSE](./LICENSE) e [LICENSE_HISTORY](./LICENSE_HISTORY) para os termos e o histórico.
+
+[Empresas](https://docs.openwebui.com/enterprise) · [Carreiras](https://careers.openwebui.com/) · [Patrocine](https://github.com/sponsors/open-webui)
+
+Criado por [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.bs.md b/README.bs.md
new file mode 100644
index 0000000000..1debbbe58b
--- /dev/null
+++ b/README.bs.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI je dom za AI : proširiva platforma jednostavna za korištenje, koju sami hostujete i koja može raditi potpuno offline. Povežite lokalne modele putem Ollame ili koristite API-je kompatibilne s OpenAI-jem za lokalne modele i modele u oblaku.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Istražite Open WebUI →](https://docs.openwebui.com/)
+
+### Instalacija
+
+#### Python
+
+Potreban je Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Zatim otvorite [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Zatim otvorite [http://localhost:3000](http://localhost:3000).
+
+| Oznaka slike | Sadržaj |
+| --- | --- |
+| `:main` | Standardna slika sa zavisnostima za lokalni AI |
+| `:slim` | Lagana slika koja koristi vanjske servise za embeddinge, izdvajanje sadržaja dokumenata i govor |
+| `:cuda` | Open WebUI s CUDA ubrzanjem |
+| `:ollama` | Open WebUI s uključenom Ollamom |
+| `:dev` | Najnovija razvojna verzija |
+
+Po potrebi dodajte ove opcije u `docker run` prije naziva slike:
+
+| Opcija | Namjena |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Povezivanje s Ollamom na drugom serveru |
+| `-e OPENAI_API_KEY=your_secret_key` | Postavljanje OpenAI API ključa |
+| `-e HF_HUB_OFFLINE=1` | Isključivanje preuzimanja Hugging Face modela za rad offline |
+| `--gpus all` | Omogućavanje pristupa Nvidia GPU-u za `:cuda` ili `:ollama`; potreban je Nvidia Container Toolkit |
+
+Upute i opcije konfiguracije nalaze se u [vodiču za instalaciju putem Dockera](https://docs.openwebui.com/getting-started/quick-start/).
+
+#### Desktop aplikacija
+
+[Preuzmite nativnu desktop aplikaciju](https://github.com/open-webui/desktop) za macOS, Windows i Linux.
+
+[Pročitajte dokumentaciju →](https://docs.openwebui.com/getting-started/)
+
+### Ekosistem
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Izvršni sloj koji pretvara Open WebUI u potpuno okruženje za agente, s poslovnom orkestracijom zasebnih radnih prostora za svakog korisnika.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Preslikajte foldere, repozitorije, spremnike i wikije u baze znanja Open WebUI-ja uz inkrementalnu sinhronizaciju.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Vaš računar u bilo kojem pregledniku: datoteke, uređivač, terminal, Git i opcionalni AI agenti koji rade na vašem stvarnom računaru.
+
+Detalje potražite u [dokumentaciji ekosistema](https://docs.openwebui.com/ecosystem/).
+
+### Rješavanje problema i ažuriranja
+
+Za probleme s povezivanjem pogledajte [vodič za rješavanje problema](https://docs.openwebui.com/troubleshooting/), a za ažuriranje instalacije [vodič za ažuriranje](https://docs.openwebui.com/getting-started/updating).
+
+### Dokumentacija
+
+Za konfiguraciju i korištenje pogledajte [dokumentaciju](https://docs.openwebui.com/), a za planirani rad [plan razvoja](https://docs.openwebui.com/roadmap/).
+
+Za Docker Compose, Kubernetes i druge načine instalacije pogledajte [dokumentaciju za instalaciju](https://docs.openwebui.com/getting-started/).
+
+### Podrška
+
+[Otvorite prijavu](https://github.com/open-webui/open-webui/issues) ili [pokrenite raspravu](https://github.com/open-webui/open-webui/discussions).
+
+Pronađite nas na [Redditu](https://www.reddit.com/r/OpenWebUI/), [X-u](https://x.com/OpenWebUI) i [Discordu](https://discord.gg/5rJgQTnV4s).
+
+### Sigurnost
+
+Ranjivosti prijavite privatno putem [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sigurnosne prijave prihvatamo isključivo putem GitHuba.
+
+### Historija zvjezdica
+
+
+
+
+
+
+
+
+
+#### Licenca
+
+Sadrži kod pod licencom Open WebUI License, koja zahtijeva očuvanje brenda Open WebUI, te ranije doprinose pod njihovim izvornim licencama. Uslove i historiju pogledajte u [LICENSE](./LICENSE) i [LICENSE_HISTORY](./LICENSE_HISTORY).
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Karijere](https://careers.openwebui.com/) · [Sponzorišite](https://github.com/sponsors/open-webui)
+
+Autor: [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.da.md b/README.da.md
new file mode 100644
index 0000000000..fa8ce35aa7
--- /dev/null
+++ b/README.da.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI er et hjem til AI : en udvidelig og brugervenlig platform, som du selv hoster, og som er bygget til at køre helt offline. Tilslut lokale modeller via Ollama, eller brug OpenAI-kompatible API’er til lokale modeller og cloudmodeller.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Udforsk Open WebUI →](https://docs.openwebui.com/)
+
+### Installation
+
+#### Python
+
+Kræver Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Åbn derefter [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Åbn derefter [http://localhost:3000](http://localhost:3000).
+
+| Image-tag | Indhold |
+| --- | --- |
+| `:main` | Standardimage med afhængigheder til lokal AI |
+| `:slim` | Letvægtsimage med eksterne tjenester til embeddings, dokumentudtræk og tale |
+| `:cuda` | Open WebUI med CUDA-acceleration |
+| `:ollama` | Open WebUI med Ollama inkluderet |
+| `:dev` | Nyeste udviklingsbuild |
+
+Tilføj disse indstillinger til `docker run` før image-navnet efter behov:
+
+| Indstilling | Formål |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Opret forbindelse til Ollama på en anden server |
+| `-e OPENAI_API_KEY=your_secret_key` | Angiv din OpenAI-API-nøgle |
+| `-e HF_HUB_OFFLINE=1` | Deaktiver download af Hugging Face-modeller til offlinebrug |
+| `--gpus all` | Aktiver Nvidia-GPU-adgang for `:cuda` eller `:ollama`; kræver Nvidia Container Toolkit |
+
+Se [installationsvejledningen til Docker](https://docs.openwebui.com/getting-started/quick-start/) for opsætning og konfigurationsmuligheder.
+
+#### Desktop-app
+
+[Download den native desktop-app](https://github.com/open-webui/desktop) til macOS, Windows og Linux.
+
+[Læs dokumentationen →](https://docs.openwebui.com/getting-started/)
+
+### Økosystem
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Det eksekveringslag, der gør Open WebUI til et komplet agentmiljø, med enterprise-orkestrering af individuelle arbejdsområder til hver bruger.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Spejl mapper, repositories, buckets og wikier i Open WebUI Knowledge Bases med inkrementel synkronisering.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Din computer i enhver browser: filer, editor, terminal, Git og valgfrie AI-agenter, som kører på din egen maskine.
+
+Se [dokumentationen til økosystemet](https://docs.openwebui.com/ecosystem/) for flere oplysninger.
+
+### Fejlfinding og opdateringer
+
+Se [fejlfindingsvejledningen](https://docs.openwebui.com/troubleshooting/) ved forbindelsesproblemer og [opdateringsvejledningen](https://docs.openwebui.com/getting-started/updating) for at opdatere din installation.
+
+### Dokumentation
+
+Se [dokumentationen](https://docs.openwebui.com/) for konfiguration og brug samt [køreplanen](https://docs.openwebui.com/roadmap/) for planlagt arbejde.
+
+For Docker Compose, Kubernetes og andre opsætninger, se [installationsdokumentationen](https://docs.openwebui.com/getting-started/).
+
+### Hjælp
+
+[Opret et issue](https://github.com/open-webui/open-webui/issues), eller [start en diskussion](https://github.com/open-webui/open-webui/discussions).
+
+Find os på [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) og [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Sikkerhed
+
+Indberet sårbarheder fortroligt via [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sikkerhedsrapporter modtages kun via GitHub.
+
+### Stjernehistorik
+
+
+
+
+
+
+
+
+
+#### Licens
+
+Indeholder kode under Open WebUI License, som kræver, at Open WebUI-brandingen bevares, samt tidligere bidrag under deres oprindelige licenser. Se [LICENSE](./LICENSE) og [LICENSE_HISTORY](./LICENSE_HISTORY) for vilkår og historik.
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Karriere](https://careers.openwebui.com/) · [Støt projektet](https://github.com/sponsors/open-webui)
+
+Skabt af [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.de.md b/README.de.md
new file mode 100644
index 0000000000..7008185db6
--- /dev/null
+++ b/README.de.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI ist ein Zuhause für KI : eine erweiterbare, benutzerfreundliche Plattform zum Selbsthosten, die vollständig offline betrieben werden kann. Verbinde lokale Modelle über Ollama oder nutze OpenAI-kompatible APIs für lokale und cloudbasierte Modelle.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Open WebUI entdecken →](https://docs.openwebui.com/)
+
+### Installation
+
+#### Python
+
+Erfordert Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Öffne anschließend [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Öffne anschließend [http://localhost:3000](http://localhost:3000).
+
+| Image-Tag | Inhalt |
+| --- | --- |
+| `:main` | Standard-Image mit Abhängigkeiten für lokale KI |
+| `:slim` | Schlankes Image mit externen Diensten für Embeddings, Dokumentenextraktion und Sprache |
+| `:cuda` | Open WebUI mit CUDA-Beschleunigung |
+| `:ollama` | Open WebUI mit integriertem Ollama |
+| `:dev` | Neuester Entwicklungsbuild |
+
+Füge diese Optionen bei Bedarf vor dem Image-Namen zu `docker run` hinzu:
+
+| Option | Zweck |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Verbindung zu Ollama auf einem anderen Server |
+| `-e OPENAI_API_KEY=your_secret_key` | OpenAI-API-Schlüssel festlegen |
+| `-e HF_HUB_OFFLINE=1` | Downloads von Hugging-Face-Modellen für den Offlinebetrieb deaktivieren |
+| `--gpus all` | Nvidia-GPU-Zugriff für `:cuda` oder `:ollama` aktivieren; erfordert das Nvidia Container Toolkit |
+
+Einrichtung und Konfigurationsoptionen findest du in der [Docker-Installationsanleitung](https://docs.openwebui.com/getting-started/quick-start/).
+
+#### Desktop-App
+
+[Native Desktop-App herunterladen](https://github.com/open-webui/desktop) für macOS, Windows und Linux.
+
+[Dokumentation lesen →](https://docs.openwebui.com/getting-started/)
+
+### Ökosystem
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Die Ausführungsebene, die Open WebUI zu einer vollständigen Agentenumgebung macht, mit Enterprise-Orchestrierung für Arbeitsbereiche pro Benutzer.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Ordner, Repositories, Buckets und Wikis durch inkrementelle Synchronisierung in Open WebUI Knowledge Bases spiegeln.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Dein Computer in jedem Browser: Dateien, Editor, Terminal, Git und optionale KI-Agenten auf deinem eigenen Rechner.
+
+Weitere Informationen findest du in der [Ökosystem-Dokumentation](https://docs.openwebui.com/ecosystem/).
+
+### Fehlerbehebung und Updates
+
+Bei Verbindungsproblemen hilft die [Anleitung zur Fehlerbehebung](https://docs.openwebui.com/troubleshooting/); zum Aktualisieren deiner Installation gibt es die [Update-Anleitung](https://docs.openwebui.com/getting-started/updating).
+
+### Dokumentation
+
+Informationen zu Konfiguration und Nutzung findest du in der [Dokumentation](https://docs.openwebui.com/), geplante Arbeiten in der [Roadmap](https://docs.openwebui.com/roadmap/).
+
+Für Docker Compose, Kubernetes und weitere Installationsarten siehe die [Installationsdokumentation](https://docs.openwebui.com/getting-started/).
+
+### Hilfe
+
+[Erstelle ein Issue](https://github.com/open-webui/open-webui/issues) oder [starte eine Diskussion](https://github.com/open-webui/open-webui/discussions).
+
+Du findest uns auf [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) und [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Sicherheit
+
+Melde Sicherheitslücken vertraulich über [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sicherheitsmeldungen werden ausschließlich über GitHub angenommen.
+
+### GitHub-Sterne im Zeitverlauf
+
+
+
+
+
+
+
+
+
+#### Lizenz
+
+Enthält Code unter der Open WebUI License, die den Erhalt des Open-WebUI-Brandings vorschreibt, sowie frühere Beiträge unter ihren ursprünglichen Lizenzen. Bedingungen und Lizenzhistorie stehen in [LICENSE](./LICENSE) und [LICENSE_HISTORY](./LICENSE_HISTORY).
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Karriere](https://careers.openwebui.com/) · [Unterstützen](https://github.com/sponsors/open-webui)
+
+Erstellt von [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.es.md b/README.es.md
new file mode 100644
index 0000000000..de1a4438a2
--- /dev/null
+++ b/README.es.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI es un hogar para la IA : una plataforma autoalojada, extensible y fácil de usar, diseñada para funcionar completamente sin conexión. Conecta modelos locales mediante Ollama o usa API compatibles con OpenAI para modelos locales y en la nube.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Explora Open WebUI →](https://docs.openwebui.com/)
+
+### Instalación
+
+#### Python
+
+Requiere Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Después, abre [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Después, abre [http://localhost:3000](http://localhost:3000).
+
+| Etiqueta de imagen | Contenido |
+| --- | --- |
+| `:main` | Imagen estándar con dependencias de IA local |
+| `:slim` | Imagen ligera que usa servicios externos para embeddings, extracción de documentos y voz |
+| `:cuda` | Open WebUI con aceleración CUDA |
+| `:ollama` | Open WebUI con Ollama incluido |
+| `:dev` | Última compilación de desarrollo |
+
+Añade estas opciones a `docker run` antes del nombre de la imagen según lo necesites:
+
+| Opción | Función |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Conectarse a Ollama en otro servidor |
+| `-e OPENAI_API_KEY=your_secret_key` | Configurar tu clave de API de OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Desactivar las descargas de modelos de Hugging Face para el uso sin conexión |
+| `--gpus all` | Habilitar el acceso a GPU Nvidia para `:cuda` o `:ollama`; requiere Nvidia Container Toolkit |
+
+Consulta la [guía de instalación con Docker](https://docs.openwebui.com/getting-started/quick-start/) para ver las instrucciones y opciones de configuración.
+
+#### Aplicación de escritorio
+
+[Descarga la aplicación de escritorio nativa](https://github.com/open-webui/desktop) para macOS, Windows y Linux.
+
+[Lee la documentación →](https://docs.openwebui.com/getting-started/)
+
+### Ecosistema
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): La capa de ejecución que convierte Open WebUI en un entorno completo para agentes, con orquestación empresarial de espacios de trabajo por usuario.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Replica carpetas, repositorios, buckets y wikis en las bases de conocimiento de Open WebUI mediante sincronización incremental.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Tu ordenador en cualquier navegador: archivos, editor, terminal, Git y agentes de IA opcionales, ejecutándose en tu propia máquina.
+
+Consulta la [documentación del ecosistema](https://docs.openwebui.com/ecosystem/) para más información.
+
+### Resolución de problemas y actualizaciones
+
+Consulta la [guía de resolución de problemas](https://docs.openwebui.com/troubleshooting/) para los problemas de conexión y la [guía de actualización](https://docs.openwebui.com/getting-started/updating) para actualizar tu instalación.
+
+### Documentación
+
+Consulta la [documentación](https://docs.openwebui.com/) para la configuración y el uso, y la [hoja de ruta](https://docs.openwebui.com/roadmap/) para el trabajo previsto.
+
+Para Docker Compose, Kubernetes y otras instalaciones, consulta la [documentación de instalación](https://docs.openwebui.com/getting-started/).
+
+### Ayuda
+
+[Abre una incidencia](https://github.com/open-webui/open-webui/issues) o [inicia una discusión](https://github.com/open-webui/open-webui/discussions).
+
+Encuéntranos en [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) y [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Seguridad
+
+Comunica vulnerabilidades de forma privada mediante [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Solo se aceptan informes de seguridad a través de GitHub.
+
+### Historial de estrellas
+
+
+
+
+
+
+
+
+
+#### Licencia
+
+Incluye código bajo la Open WebUI License, que exige conservar la marca Open WebUI, y contribuciones anteriores bajo sus licencias originales. Consulta [LICENSE](./LICENSE) y [LICENSE_HISTORY](./LICENSE_HISTORY) para conocer las condiciones y el historial.
+
+[Empresas](https://docs.openwebui.com/enterprise) · [Empleo](https://careers.openwebui.com/) · [Patrocinar](https://github.com/sponsors/open-webui)
+
+Creado por [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.fr.md b/README.fr.md
new file mode 100644
index 0000000000..b65cf43c02
--- /dev/null
+++ b/README.fr.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI est un foyer pour l’IA : une plateforme auto-hébergée, extensible et facile à utiliser, conçue pour fonctionner entièrement hors ligne. Connectez des modèles locaux via Ollama ou utilisez des API compatibles avec OpenAI pour des modèles locaux et cloud.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Découvrir Open WebUI →](https://docs.openwebui.com/)
+
+### Installation
+
+#### Python
+
+Nécessite Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Ouvrez ensuite [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Ouvrez ensuite [http://localhost:3000](http://localhost:3000).
+
+| Tag de l’image | Contenu |
+| --- | --- |
+| `:main` | Image standard avec les dépendances d’IA locales |
+| `:slim` | Image légère utilisant des services externes pour les embeddings, l’extraction de documents et la voix |
+| `:cuda` | Open WebUI avec accélération CUDA |
+| `:ollama` | Open WebUI avec Ollama intégré |
+| `:dev` | Dernière version de développement |
+
+Ajoutez ces options à `docker run` avant le nom de l’image, selon vos besoins :
+
+| Option | Fonction |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Se connecter à Ollama sur un autre serveur |
+| `-e OPENAI_API_KEY=your_secret_key` | Définir votre clé API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Désactiver le téléchargement des modèles Hugging Face pour une utilisation hors ligne |
+| `--gpus all` | Activer l’accès aux GPU Nvidia pour `:cuda` ou `:ollama` ; nécessite Nvidia Container Toolkit |
+
+Consultez le [guide d’installation Docker](https://docs.openwebui.com/getting-started/quick-start/) pour les instructions et les options de configuration.
+
+#### Application de bureau
+
+[Téléchargez l’application de bureau native](https://github.com/open-webui/desktop) pour macOS, Windows et Linux.
+
+[Lire la documentation →](https://docs.openwebui.com/getting-started/)
+
+### Écosystème
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): La couche d’exécution qui fait d’Open WebUI un environnement complet pour les agents, avec une orchestration d’entreprise des espaces de travail individuels.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Répliquez dossiers, dépôts, buckets et wikis dans les bases de connaissances Open WebUI grâce à la synchronisation incrémentale.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Votre ordinateur dans n’importe quel navigateur : fichiers, éditeur, terminal, Git et agents IA facultatifs, exécutés sur votre propre machine.
+
+Consultez la [documentation de l’écosystème](https://docs.openwebui.com/ecosystem/) pour en savoir plus.
+
+### Dépannage et mises à jour
+
+Consultez le [guide de dépannage](https://docs.openwebui.com/troubleshooting/) pour les problèmes de connexion et le [guide de mise à jour](https://docs.openwebui.com/getting-started/updating) pour actualiser votre installation.
+
+### Documentation
+
+Consultez la [documentation](https://docs.openwebui.com/) pour la configuration et l’utilisation, et la [feuille de route](https://docs.openwebui.com/roadmap/) pour les travaux prévus.
+
+Pour Docker Compose, Kubernetes et les autres modes d’installation, consultez la [documentation d’installation](https://docs.openwebui.com/getting-started/).
+
+### Assistance
+
+[Ouvrez une issue](https://github.com/open-webui/open-webui/issues) ou [lancez une discussion](https://github.com/open-webui/open-webui/discussions).
+
+Retrouvez-nous sur [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) et [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Sécurité
+
+Signalez les vulnérabilités de manière confidentielle via [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Les signalements de sécurité sont acceptés uniquement sur GitHub.
+
+### Historique des étoiles
+
+
+
+
+
+
+
+
+
+#### Licence
+
+Inclut du code sous Open WebUI License, qui impose de conserver l’identité de marque Open WebUI, ainsi que des contributions antérieures sous leurs licences d’origine. Consultez [LICENSE](./LICENSE) et [LICENSE_HISTORY](./LICENSE_HISTORY) pour les conditions et l’historique.
+
+[Entreprise](https://docs.openwebui.com/enterprise) · [Carrières](https://careers.openwebui.com/) · [Soutenir](https://github.com/sponsors/open-webui)
+
+Créé par [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.gr.md b/README.gr.md
new file mode 100644
index 0000000000..857ac69740
--- /dev/null
+++ b/README.gr.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Το Open WebUI είναι ένα σπίτι για την τεχνητή νοημοσύνη : μια επεκτάσιμη, εύχρηστη πλατφόρμα που φιλοξενείτε εσείς, σχεδιασμένη να λειτουργεί πλήρως εκτός σύνδεσης. Συνδέστε τοπικά μοντέλα μέσω του Ollama ή χρησιμοποιήστε API συμβατά με το OpenAI για τοπικά μοντέλα και μοντέλα στο cloud.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Εξερευνήστε το Open WebUI →](https://docs.openwebui.com/)
+
+### Εγκατάσταση
+
+#### Python
+
+Απαιτείται Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Στη συνέχεια, ανοίξτε το [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Στη συνέχεια, ανοίξτε το [http://localhost:3000](http://localhost:3000).
+
+| Ετικέτα εικόνας | Περιεχόμενο |
+| --- | --- |
+| `:main` | Τυπική εικόνα με εξαρτήσεις για τοπική AI |
+| `:slim` | Ελαφριά εικόνα που χρησιμοποιεί εξωτερικές υπηρεσίες για embeddings, εξαγωγή περιεχομένου εγγράφων και φωνή |
+| `:cuda` | Open WebUI με επιτάχυνση CUDA |
+| `:ollama` | Open WebUI με ενσωματωμένο Ollama |
+| `:dev` | Νεότερη έκδοση ανάπτυξης |
+
+Προσθέστε αυτές τις επιλογές στο `docker run` πριν από το όνομα της εικόνας, ανάλογα με τις ανάγκες σας:
+
+| Επιλογή | Σκοπός |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Σύνδεση με Ollama σε άλλον διακομιστή |
+| `-e OPENAI_API_KEY=your_secret_key` | Ορισμός του κλειδιού API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Απενεργοποίηση λήψεων μοντέλων Hugging Face για χρήση εκτός σύνδεσης |
+| `--gpus all` | Ενεργοποίηση πρόσβασης σε GPU Nvidia για `:cuda` ή `:ollama`· απαιτείται Nvidia Container Toolkit |
+
+Δείτε τον [οδηγό εγκατάστασης με Docker](https://docs.openwebui.com/getting-started/quick-start/) για οδηγίες και επιλογές διαμόρφωσης.
+
+#### Εφαρμογή υπολογιστή
+
+[Κατεβάστε την εγγενή εφαρμογή υπολογιστή](https://github.com/open-webui/desktop) για macOS, Windows και Linux.
+
+[Διαβάστε την τεκμηρίωση →](https://docs.openwebui.com/getting-started/)
+
+### Οικοσύστημα
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Το επίπεδο εκτέλεσης που μετατρέπει το Open WebUI σε πλήρες περιβάλλον πρακτόρων, με εταιρική ενορχήστρωση χώρων εργασίας ανά χρήστη.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Αντικατοπτρίστε φακέλους, αποθετήρια, buckets και wiki στις βάσεις γνώσεων του Open WebUI με αυξητικό συγχρονισμό.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Ο υπολογιστής σας σε οποιονδήποτε περιηγητή: αρχεία, επεξεργαστής, τερματικό, Git και προαιρετικοί πράκτορες AI, που εκτελούνται στο πραγματικό σας μηχάνημα.
+
+Δείτε την [τεκμηρίωση του οικοσυστήματος](https://docs.openwebui.com/ecosystem/) για λεπτομέρειες.
+
+### Αντιμετώπιση προβλημάτων και ενημερώσεις
+
+Δείτε τον [οδηγό αντιμετώπισης προβλημάτων](https://docs.openwebui.com/troubleshooting/) για προβλήματα σύνδεσης και τον [οδηγό ενημέρωσης](https://docs.openwebui.com/getting-started/updating) για να ενημερώσετε την εγκατάστασή σας.
+
+### Τεκμηρίωση
+
+Δείτε την [τεκμηρίωση](https://docs.openwebui.com/) για τη διαμόρφωση και τη χρήση, και τον [οδικό χάρτη](https://docs.openwebui.com/roadmap/) για τις προγραμματισμένες εργασίες.
+
+Για Docker Compose, Kubernetes και άλλες εγκαταστάσεις, δείτε την [τεκμηρίωση εγκατάστασης](https://docs.openwebui.com/getting-started/).
+
+### Υποστήριξη
+
+[Ανοίξτε ένα issue](https://github.com/open-webui/open-webui/issues) ή [ξεκινήστε μια συζήτηση](https://github.com/open-webui/open-webui/discussions).
+
+Βρείτε μας στο [Reddit](https://www.reddit.com/r/OpenWebUI/), στο [X](https://x.com/OpenWebUI) και στο [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Ασφάλεια
+
+Αναφέρετε ευπάθειες ιδιωτικά μέσω των [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Οι αναφορές ασφάλειας γίνονται δεκτές μόνο μέσω του GitHub.
+
+### Ιστορικό αστεριών
+
+
+
+
+
+
+
+
+
+#### Άδεια χρήσης
+
+Περιλαμβάνει κώδικα υπό την Open WebUI License, η οποία απαιτεί τη διατήρηση της ταυτότητας του Open WebUI, καθώς και παλαιότερες συνεισφορές υπό τις αρχικές τους άδειες. Δείτε τα [LICENSE](./LICENSE) και [LICENSE_HISTORY](./LICENSE_HISTORY) για τους όρους και το ιστορικό.
+
+[Επιχειρήσεις](https://docs.openwebui.com/enterprise) · [Καριέρα](https://careers.openwebui.com/) · [Χορηγία](https://github.com/sponsors/open-webui)
+
+Δημιουργήθηκε από τον [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.it.md b/README.it.md
new file mode 100644
index 0000000000..b9982d8ab2
--- /dev/null
+++ b/README.it.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI è una casa per l’IA : una piattaforma self-hosted, estensibile e facile da usare, progettata per funzionare completamente offline. Collega modelli locali tramite Ollama oppure usa API compatibili con OpenAI per modelli locali e cloud.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Esplora Open WebUI →](https://docs.openwebui.com/)
+
+### Installazione
+
+#### Python
+
+Richiede Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Poi apri [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Poi apri [http://localhost:3000](http://localhost:3000).
+
+| Tag dell’immagine | Contenuto |
+| --- | --- |
+| `:main` | Immagine standard con dipendenze per l’IA locale |
+| `:slim` | Immagine leggera che usa servizi esterni per embedding, estrazione dei documenti e voce |
+| `:cuda` | Open WebUI con accelerazione CUDA |
+| `:ollama` | Open WebUI con Ollama incluso |
+| `:dev` | Ultima build di sviluppo |
+
+Aggiungi queste opzioni a `docker run` prima del nome dell’immagine, secondo necessità:
+
+| Opzione | Scopo |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Collegarsi a Ollama su un altro server |
+| `-e OPENAI_API_KEY=your_secret_key` | Impostare la chiave API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Disabilitare i download dei modelli Hugging Face per l’uso offline |
+| `--gpus all` | Abilitare l’accesso alla GPU Nvidia per `:cuda` o `:ollama`; richiede Nvidia Container Toolkit |
+
+Consulta la [guida all’installazione con Docker](https://docs.openwebui.com/getting-started/quick-start/) per le istruzioni e le opzioni di configurazione.
+
+#### App desktop
+
+[Scarica l’app desktop nativa](https://github.com/open-webui/desktop) per macOS, Windows e Linux.
+
+[Leggi la documentazione →](https://docs.openwebui.com/getting-started/)
+
+### Ecosistema
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Il livello di esecuzione che rende Open WebUI un ambiente completo per gli agenti, con orchestrazione enterprise degli spazi di lavoro per utente.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Replica cartelle, repository, bucket e wiki nelle basi di conoscenza di Open WebUI tramite sincronizzazione incrementale.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Il tuo computer in qualsiasi browser: file, editor, terminale, Git e agenti IA facoltativi, in esecuzione sulla tua macchina.
+
+Consulta la [documentazione dell’ecosistema](https://docs.openwebui.com/ecosystem/) per i dettagli.
+
+### Risoluzione dei problemi e aggiornamenti
+
+Consulta la [guida alla risoluzione dei problemi](https://docs.openwebui.com/troubleshooting/) per i problemi di connessione e la [guida agli aggiornamenti](https://docs.openwebui.com/getting-started/updating) per aggiornare l’installazione.
+
+### Documentazione
+
+Consulta la [documentazione](https://docs.openwebui.com/) per configurazione e utilizzo, e la [roadmap](https://docs.openwebui.com/roadmap/) per il lavoro previsto.
+
+Per Docker Compose, Kubernetes e altre installazioni, consulta la [documentazione di installazione](https://docs.openwebui.com/getting-started/).
+
+### Supporto
+
+[Apri una segnalazione](https://github.com/open-webui/open-webui/issues) oppure [avvia una discussione](https://github.com/open-webui/open-webui/discussions).
+
+Ci trovi su [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) e [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Sicurezza
+
+Segnala le vulnerabilità in privato tramite [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Le segnalazioni di sicurezza sono accettate solo tramite GitHub.
+
+### Cronologia delle stelle
+
+
+
+
+
+
+
+
+
+#### Licenza
+
+Include codice soggetto alla Open WebUI License, che richiede di mantenere il marchio Open WebUI, e contributi precedenti soggetti alle rispettive licenze originali. Consulta [LICENSE](./LICENSE) e [LICENSE_HISTORY](./LICENSE_HISTORY) per condizioni e cronologia.
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Lavora con noi](https://careers.openwebui.com/) · [Sostieni](https://github.com/sponsors/open-webui)
+
+Creato da [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.ja.md b/README.ja.md
new file mode 100644
index 0000000000..ccbe15bd93
--- /dev/null
+++ b/README.ja.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI は AI のためのホーム です。拡張可能で使いやすく、完全オフラインでの動作に対応したセルフホスト型プラットフォームです。Ollama でローカルモデルに接続するほか、OpenAI 互換 API を通じてローカルやクラウドのモデルを利用できます。
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Open WebUI をもっと知る →](https://docs.openwebui.com/)
+
+### インストール
+
+#### Python
+
+Python 3.12 が必要です。
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+その後、[http://localhost:8080](http://localhost:8080) を開きます。
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+その後、[http://localhost:3000](http://localhost:3000) を開きます。
+
+| イメージタグ | 内容 |
+| --- | --- |
+| `:main` | ローカル AI 用の依存パッケージを含む標準イメージ |
+| `:slim` | 埋め込み、ドキュメント抽出、音声処理に外部サービスを使う軽量イメージ |
+| `:cuda` | CUDA アクセラレーション対応の Open WebUI |
+| `:ollama` | Ollama を同梱した Open WebUI |
+| `:dev` | 最新の開発ビルド |
+
+必要に応じて、`docker run` のイメージ名の前に以下のオプションを追加してください。
+
+| オプション | 用途 |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 別のサーバー上の Ollama に接続 |
+| `-e OPENAI_API_KEY=your_secret_key` | OpenAI API キーを設定 |
+| `-e HF_HUB_OFFLINE=1` | オフライン利用のため Hugging Face のモデルダウンロードを無効化 |
+| `--gpus all` | `:cuda` または `:ollama` で Nvidia GPU を利用。Nvidia Container Toolkit が必要 |
+
+セットアップ手順と設定項目は [Docker インストールガイド](https://docs.openwebui.com/getting-started/quick-start/)をご覧ください。
+
+#### デスクトップアプリ
+
+macOS、Windows、Linux 向けの[ネイティブデスクトップアプリをダウンロード](https://github.com/open-webui/desktop)。
+
+[ドキュメントを読む →](https://docs.openwebui.com/getting-started/)
+
+### エコシステム
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI を完全なエージェント実行基盤にするアクション層。ユーザーごとのワークスペースを管理するエンタープライズ向けオーケストレーションにも対応。
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): フォルダー、リポジトリ、バケット、Wiki を差分同期し、Open WebUI のナレッジベースに反映。
+- [Open WebUI Computer](https://github.com/open-webui/computer): 自分のコンピューターをどのブラウザーからでも。ファイル、エディター、ターミナル、Git、任意の AI エージェントが実際のマシン上で動作。
+
+詳しくは[エコシステムのドキュメント](https://docs.openwebui.com/ecosystem/)をご覧ください。
+
+### トラブルシューティングと更新
+
+接続の問題は[トラブルシューティングガイド](https://docs.openwebui.com/troubleshooting/)、インストールの更新は[更新ガイド](https://docs.openwebui.com/getting-started/updating)をご覧ください。
+
+### ドキュメント
+
+設定と使い方は[ドキュメント](https://docs.openwebui.com/)、今後の予定は[ロードマップ](https://docs.openwebui.com/roadmap/)をご覧ください。
+
+Docker Compose、Kubernetes、その他の構成については[インストールドキュメント](https://docs.openwebui.com/getting-started/)をご覧ください。
+
+### サポート
+
+[Issue を作成](https://github.com/open-webui/open-webui/issues)するか、[ディスカッションを開始](https://github.com/open-webui/open-webui/discussions)してください。
+
+[Reddit](https://www.reddit.com/r/OpenWebUI/)、[X](https://x.com/OpenWebUI)、[Discord](https://discord.gg/5rJgQTnV4s)でも発信しています。
+
+### セキュリティ
+
+脆弱性は [GitHub Security Advisories](https://github.com/open-webui/open-webui/security) を通じて非公開で報告してください。セキュリティ報告は GitHub 経由でのみ受け付けています。
+
+### スター数の推移
+
+
+
+
+
+
+
+
+
+#### ライセンス
+
+Open WebUI のブランド表示の保持を求める Open WebUI License に基づくコードと、それぞれ元のライセンスが適用される過去の貢献が含まれています。条件と履歴は [LICENSE](./LICENSE) と [LICENSE_HISTORY](./LICENSE_HISTORY) をご覧ください。
+
+[エンタープライズ](https://docs.openwebui.com/enterprise) · [採用情報](https://careers.openwebui.com/) · [スポンサー](https://github.com/sponsors/open-webui)
+
+作成者:[Timothy Jaeryang Baek](https://github.com/tjbck)。
diff --git a/README.ko.md b/README.ko.md
new file mode 100644
index 0000000000..d44fc44b89
--- /dev/null
+++ b/README.ko.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI는 AI를 위한 집 입니다. 확장하기 쉽고 사용하기 편리하며, 완전한 오프라인 실행을 지원하는 셀프 호스팅 플랫폼입니다. Ollama로 로컬 모델에 연결하거나 OpenAI 호환 API를 통해 로컬 및 클라우드 모델을 사용하세요.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Open WebUI 둘러보기 →](https://docs.openwebui.com/)
+
+### 설치
+
+#### Python
+
+Python 3.12가 필요합니다.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+그런 다음 [http://localhost:8080](http://localhost:8080)을 여세요.
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+그런 다음 [http://localhost:3000](http://localhost:3000)을 여세요.
+
+| 이미지 태그 | 구성 |
+| --- | --- |
+| `:main` | 로컬 AI 의존성이 포함된 표준 이미지 |
+| `:slim` | 임베딩, 문서 추출, 음성 처리에 외부 서비스를 사용하는 경량 이미지 |
+| `:cuda` | CUDA 가속을 지원하는 Open WebUI |
+| `:ollama` | Ollama가 포함된 Open WebUI |
+| `:dev` | 최신 개발 빌드 |
+
+필요에 따라 `docker run`의 이미지 이름 앞에 다음 옵션을 추가하세요.
+
+| 옵션 | 용도 |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 다른 서버의 Ollama에 연결 |
+| `-e OPENAI_API_KEY=your_secret_key` | OpenAI API 키 설정 |
+| `-e HF_HUB_OFFLINE=1` | 오프라인 사용을 위해 Hugging Face 모델 다운로드 비활성화 |
+| `--gpus all` | `:cuda` 또는 `:ollama`에서 Nvidia GPU 사용 활성화. Nvidia Container Toolkit 필요 |
+
+설치 방법과 설정 옵션은 [Docker 설치 가이드](https://docs.openwebui.com/getting-started/quick-start/)를 참고하세요.
+
+#### 데스크톱 앱
+
+macOS, Windows, Linux용 [네이티브 데스크톱 앱을 다운로드하세요](https://github.com/open-webui/desktop).
+
+[문서 읽기 →](https://docs.openwebui.com/getting-started/)
+
+### 생태계
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI를 완전한 에이전트 실행 환경으로 만드는 실행 계층으로, 사용자별 작업 공간을 위한 엔터프라이즈 오케스트레이션을 제공합니다.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): 폴더, 저장소, 버킷, 위키를 증분 동기화하여 Open WebUI 지식 베이스에 반영합니다.
+- [Open WebUI Computer](https://github.com/open-webui/computer): 어떤 브라우저에서든 내 컴퓨터를 사용하세요. 파일, 편집기, 터미널, Git, 선택적으로 사용하는 AI 에이전트가 실제 내 컴퓨터에서 실행됩니다.
+
+자세한 내용은 [생태계 문서](https://docs.openwebui.com/ecosystem/)를 참고하세요.
+
+### 문제 해결 및 업데이트
+
+연결 문제는 [문제 해결 가이드](https://docs.openwebui.com/troubleshooting/)를, 설치 업데이트는 [업데이트 가이드](https://docs.openwebui.com/getting-started/updating)를 참고하세요.
+
+### 문서
+
+설정과 사용법은 [문서](https://docs.openwebui.com/)를, 예정된 작업은 [로드맵](https://docs.openwebui.com/roadmap/)을 참고하세요.
+
+Docker Compose, Kubernetes 및 기타 설치 방법은 [설치 문서](https://docs.openwebui.com/getting-started/)를 참고하세요.
+
+### 지원
+
+[이슈를 등록](https://github.com/open-webui/open-webui/issues)하거나 [토론을 시작](https://github.com/open-webui/open-webui/discussions)하세요.
+
+[Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI), [Discord](https://discord.gg/5rJgQTnV4s)에서도 만나보세요.
+
+### 보안
+
+취약점은 [GitHub Security Advisories](https://github.com/open-webui/open-webui/security)를 통해 비공개로 제보해 주세요. 보안 제보는 GitHub를 통해서만 접수합니다.
+
+### 스타 기록
+
+
+
+
+
+
+
+
+
+#### 라이선스
+
+Open WebUI 브랜드 유지를 요구하는 Open WebUI License가 적용된 코드와, 각각 원래 라이선스가 적용되는 이전 기여분을 포함합니다. 조건과 이력은 [LICENSE](./LICENSE)와 [LICENSE_HISTORY](./LICENSE_HISTORY)를 참고하세요.
+
+[엔터프라이즈](https://docs.openwebui.com/enterprise) · [채용](https://careers.openwebui.com/) · [후원](https://github.com/sponsors/open-webui)
+
+제작: [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.md b/README.md
index 17b816309d..65d7ac7945 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,31 @@
-# Open WebUI 👋
+Open WebUI
+
+Open WebUI is a home for AI : an extensible, easy-to-use, self-hosted platform built to run entirely offline. Connect local models through Ollama or use OpenAI-compatible APIs for local and cloud models.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)


@@ -8,247 +35,85 @@


[](https://discord.gg/5rJgQTnV4s)
-[](https://github.com/sponsors/open-webui)
+[](https://github.com/sponsors/open-webui)
-Open WebUI is **a home for AI**, a self-hosted AI platform that's **[extensible](https://docs.openwebui.com/features/extensibility/plugin/)**, **[feature-rich](https://docs.openwebui.com/features/)**, user-friendly, and built to run **[entirely offline](https://openwebui.com/sovereign-ai)**. With support for **Ollama** and **OpenAI-compatible APIs**, it gives you a powerful, provider-agnostic interface for both local and cloud-based models.
+[Explore Open WebUI →](https://docs.openwebui.com/)
-Passionate about open-source AI? [Join our team →](https://careers.openwebui.com/)
+### Installation
-
+#### Python
-> [!TIP]
-> **Looking for an [Enterprise Plan](https://docs.openwebui.com/enterprise)?** – **[Speak with Our Sales Team Today!](https://docs.openwebui.com/enterprise)**
-
-For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
-
-## Key Features of Open WebUI ⭐
-
-- 🚀 **Effortless Setup**: Install seamlessly via pip, uv, Docker, or Kubernetes (kubectl, kustomize, or helm), with `:ollama` and `:cuda` tagged images available for container deployments.
-
-- 🤝 **Broad Model & API Integration**: Connect any OpenAI-compatible API alongside local Ollama models. Point the API URL at **LMStudio, GroqCloud, Mistral, OpenRouter, vLLM, and more** to mix and match providers freely.
-
-- 🔐 **Granular RBAC & User Groups**: Administrators define detailed roles, groups, and permissions, giving each user exactly the access they need. Secure by default, with tailored experiences per group.
-
-- 🧩 **Plugin Support**: Extend Open WebUI with **Filters**, **Actions**, **Pipes**, **Tools**, and **Skills**. Connect external services through **MCP**, **MCPO**, and **OpenAPI tool servers**. Build custom integrations, rate limits, approval flows, data connections, and more.
-
-- 🤖 **Models & Agents**: Wrap any base model with custom instructions, tools, and knowledge to build specialized agents. Supports dynamic variables, per-user/group access control, and community preset imports via [Open WebUI Community](https://openwebui.com/).
-
-- ⚡ **Agentic Execution with [Open Terminal](https://github.com/open-webui/open-terminal)**: Give your agents a terminal and filesystem to carry out multi-step tasks. Let them analyze data, run scripts, fix errors, and produce files directly in chat. Scale to teams with **[Terminals (Enterprise)](https://github.com/open-webui/terminals)** for per-user isolated environments, resource limits, and automatic lifecycle management.
-
-- 📝 **Notes**: A dedicated workspace for content outside conversations. Draft with a rich editor, use AI to rewrite selected text, and attach notes to any chat for full-context injection.
-
-- 📢 **Channels**: Real-time shared spaces where your team and AI models collaborate in one timeline. Tag models to draft or critique, with threads, reactions, pins, and access control.
-
-- 🧠 **Persistent Memory**: The AI remembers facts about you across conversations, carrying context from one chat to the next.
-
-- ✅ **Live Workflow & Message Flow**: Watch the AI build and work through checklists in real time. Queue messages while the AI is still responding; they send automatically when it's ready.
-
-- 📅 **Calendar & AI Scheduling**: Built-in personal and shared calendars with month/week/day views, recurring events, color coding, attendees, and reminders. Models manage your schedule conversationally through native function calling.
-
-- ⏱️ **Automations**: Schedule prompts to run on recurring schedules, with runs surfaced on your calendar and each completed run linking back to the chat it produced.
-
-- 📱 **Responsive Design & PWA**: Seamless experience across desktop, laptop, and mobile, with a Progressive Web App for native app-like feel and offline access on localhost.
-
-- ✒️🔢 **Full Markdown and LaTeX Support**: Comprehensive Markdown and LaTeX capabilities for enriched interaction.
-
-- 🎤📹 **Hands-Free Voice/Video Call**: Integrated voice and video calls with multiple Speech-to-Text providers (Local Whisper, OpenAI, Deepgram, Azure) and Text-to-Speech engines (Azure, ElevenLabs, OpenAI, Transformers, WebAPI).
-
-- 💾 **Persistent Artifact Storage**: Built-in key-value storage API for artifacts, enabling journals, trackers, leaderboards, and collaborative tools with personal and shared data scopes.
-
-- 📚 **Local RAG Integration**: Retrieval Augmented Generation backed by 9 vector databases and multiple content-extraction engines (Tika, Docling, Document Intelligence, Mistral OCR, PaddleOCR-vl, external loaders). Supports hybrid search (BM25 + vector) with reranking and full-context mode. Load documents into chat or pull them from your library with the `#` command.
-
-- 🔍 **Web Search for RAG**: Search the web through dozens of providers including `SearXNG`, `Google PSE`, `Brave Search`, `Kagi`, `Mojeek`, `Tavily`, `Perplexity`, `Firecrawl`, `serpstack`, `serper`, `Serply`, `DuckDuckGo`, `SearchApi`, `SerpApi`, `Bing`, `Jina`, `Exa`, `Sougou`, `Azure AI Search`, and `Ollama Cloud`, injecting results directly into the conversation.
-
-- 🌐 **Web Browsing Capability**: Pull websites into chat with the `#` command followed by a URL, or let the model fetch them on its own when needed.
-
-- 🎨 **Image Generation & Editing**: Create and edit images with multiple engines including OpenAI DALL·E, Gemini, ComfyUI (local), and AUTOMATIC1111 (local), supporting both generation and prompt-based editing.
-
-- ⚙️ **Multi-Model Conversations**: Engage several models at once, harnessing their individual strengths in parallel for the best possible responses.
-
-- 📊 **Usage Analytics & Model Evaluation**: Admin dashboards track message volume, token consumption, and cost across users and models. Evaluate models with a built-in arena, A/B testing, and ELO-based leaderboards.
-
-- 🗄️ **Flexible Database & Storage**: Choose SQLite (with optional encryption) or PostgreSQL, and store files locally or on S3, Google Cloud Storage, or Azure Blob Storage.
-
-- 🧬 **Advanced Vector Database Support**: Pick from 9 vector databases: ChromaDB, PGVector, Qdrant, Milvus, Elasticsearch, OpenSearch, Pinecone, S3Vector, and Oracle 23ai.
-
-- 🪪 **Enterprise Authentication & Provisioning**: Full LDAP/Active Directory integration, SSO via trusted headers and OAuth providers, and SCIM 2.0 automated provisioning for identity providers like Okta, Azure AD, and Google Workspace.
-
-- ☁️ **Cloud-Native File Integration**: Native Google Drive and OneDrive/SharePoint file picking for seamless document import from enterprise cloud storage.
-
-- 🔭 **Production Observability**: Built-in OpenTelemetry support for traces, metrics, and logs, plugging into your existing monitoring stack.
-
-- ⚖️ **Horizontal Scalability**: Redis-backed session management and WebSocket support for multi-worker, multi-node deployments behind load balancers.
-
-- 🌐🌍 **Multilingual Support**: Use Open WebUI in your preferred language with i18n support. We're actively seeking contributors to expand language coverage!
-
-- 🌟 **Continuous Updates**: We're committed to improving Open WebUI with regular updates, fixes, and new features.
-
-- 🛡️ **Transparent Security Process**: Security reports are triaged, fixed, and published as open advisories through a documented responsible-disclosure process. See our [Security Policy](https://github.com/open-webui/open-webui/security).
-
-Want to learn more about Open WebUI's features? Check out our [Open WebUI documentation](https://docs.openwebui.com/features) for a comprehensive overview!
-
-## The Open WebUI Ecosystem 🌐
-
-Open WebUI is the core, surrounded by companion apps and infrastructure that extend what your AI can do, where it can reach, and how you run it:
-
-- 💻 **Open WebUI Computer** ([open-webui/computer](https://github.com/open-webui/computer)): A standalone, mobile-first computer and coding agent that runs on the machine you own. Files, terminal, and git in a browser tab, reachable from your phone. Connect it into Open WebUI as a model, or reach it from Telegram, WhatsApp, and more.
-
-- ⚡ **Open Terminal** and **Terminals (Enterprise)** ([open-webui/open-terminal](https://github.com/open-webui/open-terminal) & [open-webui/terminals](https://github.com/open-webui/terminals)): A self-hosted computing environment that plugs into Open WebUI, giving the AI a place to write code, run it, read output, fix errors, and iterate inside the chat. Terminals gives you per-user isolated containers with separate credentials, resource limits, and network rules. Automatic lifecycle management on Docker or Kubernetes.
-
-- 🔄 **oikb** ([open-webui/oikb](https://github.com/open-webui/oikb)): Feed your Knowledge Bases from 45+ sources (GitHub, Confluence, ServiceNow, Salesforce, Jira, Slack, SharePoint, Notion, and more), keeping the tools your team already uses continuously in sync.
-
-- 🖥️ **Native Desktop App** ([open-webui/desktop](https://github.com/open-webui/desktop)): Run Open WebUI as a native app on macOS, Windows, and Linux. System-wide Spotlight chat bar with screenshot capture, push-to-talk voice, and optional fully-local inference via a built-in llama.cpp engine.
-
-Want to learn more? Check out our [Open WebUI documentation](https://docs.openwebui.com) for more details!
-
----
-
-We are incredibly grateful for the generous support of our sponsors. Their contributions help us to maintain and improve our project, ensuring we can continue to deliver quality work to our community. Thank you!
-
-## How to Install 🚀
-
-### Installation via Python pip 🐍
-
-Open WebUI can be installed using pip, the Python package installer. Before proceeding, ensure you're using **Python 3.12** to avoid compatibility issues.
-
-1. **Install Open WebUI**:
- Open your terminal and run the following command to install Open WebUI:
-
- ```bash
- pip install open-webui
- ```
-
-2. **Running Open WebUI**:
- After installation, you can start Open WebUI by executing:
-
- ```bash
- open-webui serve
- ```
-
-This will start the Open WebUI server, which you can access at [http://localhost:8080](http://localhost:8080)
-
-### Quick Start with Docker 🐳
-
-> [!NOTE]
-> Please note that for certain Docker environments, additional configurations might be needed. If you encounter any connection issues, our detailed guide on [Open WebUI Documentation](https://docs.openwebui.com/) is ready to assist you.
-
-> [!WARNING]
-> When using Docker to install Open WebUI, make sure to include the `-v open-webui:/app/backend/data` in your Docker command. This step is crucial as it ensures your database is properly mounted and prevents any loss of data.
-
-> [!TIP]
-> If you wish to utilize Open WebUI with Ollama included or CUDA acceleration, we recommend utilizing our official images tagged with either `:cuda` or `:ollama`. To enable CUDA, you must install the [Nvidia CUDA container toolkit](https://docs.nvidia.com/dgx/nvidia-container-runtime-upgrade/) on your Linux/WSL system.
-
-### Installation with Default Configuration
-
-- **If Ollama is on your computer**, use this command:
-
- ```bash
- docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
- ```
-
-- **If Ollama is on a Different Server**, use this command:
-
- To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
-
- ```bash
- docker run -d -p 3000:8080 -e OLLAMA_BASE_URL=https://example.com -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
- ```
-
-- **To run Open WebUI with Nvidia GPU support**, use this command:
-
- ```bash
- docker run -d -p 3000:8080 --gpus all --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:cuda
- ```
-
-### Installation for OpenAI API Usage Only
-
-- **If you're only using OpenAI API**, use this command:
-
- ```bash
- docker run -d -p 3000:8080 -e OPENAI_API_KEY=your_secret_key -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
- ```
-
-### Installing Open WebUI with Bundled Ollama Support
-
-This installation method uses a single container image that bundles Open WebUI with Ollama, allowing for a streamlined setup via a single command. Choose the appropriate command based on your hardware setup:
-
-- **With GPU Support**:
- Utilize GPU resources by running the following command:
-
- ```bash
- docker run -d -p 3000:8080 --gpus=all -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
- ```
-
-- **For CPU Only**:
- If you're not using a GPU, use this command instead:
-
- ```bash
- docker run -d -p 3000:8080 -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
- ```
-
-Both commands facilitate a built-in, hassle-free installation of both Open WebUI and Ollama, ensuring that you can get everything up and running swiftly.
-
-After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
-
-### Other Installation Methods
-
-We offer various installation alternatives, including non-Docker native installation methods, Docker Compose, Kustomize, and Helm. Visit our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/) or join our [Discord community](https://discord.gg/5rJgQTnV4s) for comprehensive guidance.
-
-### Troubleshooting
-
-Encountering connection issues? Our [Open WebUI Documentation](https://docs.openwebui.com/troubleshooting/) has got you covered. For further assistance and to join our vibrant community, visit the [Open WebUI Discord](https://discord.gg/5rJgQTnV4s).
-
-#### Open WebUI: Server Connection Error
-
-If you're experiencing connection issues, it’s often due to the WebUI docker container not being able to reach the Ollama server at 127.0.0.1:11434 (host.docker.internal:11434) inside the container . Use the `--network=host` flag in your docker command to resolve this. Note that the port changes from 3000 to 8080, resulting in the link: `http://localhost:8080`.
-
-**Example Docker Command**:
+Requires Python 3.12.
```bash
-docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_BASE_URL=http://127.0.0.1:11434 --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+pip install open-webui
+open-webui serve
```
-### Keeping Your Docker Installation Up-to-Date
+Then open [http://localhost:8080](http://localhost:8080).
-Check our Updating Guide available in our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/updating).
-
-### Using the Dev Branch 🌙
-
-> [!WARNING]
-> The `:dev` branch contains the latest unstable features and changes. Use it at your own risk as it may have bugs or incomplete features.
-
-If you want to try out the latest bleeding-edge features and are okay with occasional instability, you can use the `:dev` tag like this:
+#### Docker
```bash
-docker run -d -p 3000:8080 -v open-webui:/app/backend/data --name open-webui --add-host=host.docker.internal:host-gateway --restart always ghcr.io/open-webui/open-webui:dev
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
-### Offline Mode
+Then open [http://localhost:3000](http://localhost:3000).
-If you are running Open WebUI in an offline environment, you can set the `HF_HUB_OFFLINE` environment variable to `1` to prevent attempts to download models from the internet.
+| Image tag | Includes |
+| --- | --- |
+| `:main` | Standard image with local AI dependencies |
+| `:slim` | Lightweight image using external services for embeddings, document extraction, and voice |
+| `:cuda` | Open WebUI with CUDA acceleration |
+| `:ollama` | Open WebUI bundled with Ollama |
+| `:dev` | Latest development build |
-```bash
-export HF_HUB_OFFLINE=1
-```
+Add these options to `docker run` before the image name as needed:
-## What's Next? 🌟
+| Option | Purpose |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Connect to Ollama on another server |
+| `-e OPENAI_API_KEY=your_secret_key` | Set your OpenAI API key |
+| `-e HF_HUB_OFFLINE=1` | Disable Hugging Face model downloads for offline use |
+| `--gpus all` | Enable Nvidia GPU access for `:cuda` or `:ollama`; requires the Nvidia Container Toolkit |
-Discover upcoming features on our roadmap in the [Open WebUI Documentation](https://docs.openwebui.com/roadmap/).
+See the [Docker installation guide](https://docs.openwebui.com/getting-started/quick-start/) for setup instructions and configuration options.
-## License 📜
+#### Desktop App
-This project contains code under multiple licenses. The current codebase includes components licensed under the Open WebUI License with an additional requirement to preserve the "Open WebUI" branding, as well as prior contributions under their respective original licenses. For a detailed record of license changes and the applicable terms for each section of the code, please refer to [LICENSE_HISTORY](./LICENSE_HISTORY). For complete and updated licensing details, please see the [LICENSE](./LICENSE) and [LICENSE_HISTORY](./LICENSE_HISTORY) files.
+[Download the native desktop app](https://github.com/open-webui/desktop) for macOS, Windows, and Linux.
-## Support 💬
+[Read the docs →](https://docs.openwebui.com/getting-started/)
-If you have any questions, suggestions, or need assistance, please open an issue or join our
-[Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
+### Ecosystem
-## Security 🛡️
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): The action layer that turns Open WebUI into a full agent harness, with enterprise orchestration for per-user workspaces.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Mirror folders, repos, buckets, and wikis into Open WebUI Knowledge Bases with incremental sync.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Your computer in any browser: files, editor, terminal, git, and optional AI agents, running on your real machine.
-If you believe you've found a security vulnerability, or something that shouldn't be disclosed publicly, please [reach out confidentially through our responsible disclosure program on GitHub](https://github.com/open-webui/open-webui/security). We accept reports only through GitHub, not through any other platform. Thank you for helping us keep Open WebUI secure!
+See the [ecosystem documentation](https://docs.openwebui.com/ecosystem/) for details.
-## Star History
+### Troubleshooting and Updates
+
+See the [troubleshooting guide](https://docs.openwebui.com/troubleshooting/) for connection issues and the [updating guide](https://docs.openwebui.com/getting-started/updating) to update your installation.
+
+### Documentation
+
+See the [docs](https://docs.openwebui.com/) for configuration and usage, and the [roadmap](https://docs.openwebui.com/roadmap/) for planned work.
+
+For Docker Compose, Kubernetes, and other setups, see the [installation docs](https://docs.openwebui.com/getting-started/).
+
+### Support
+
+[Open an issue](https://github.com/open-webui/open-webui/issues) or [start a discussion](https://github.com/open-webui/open-webui/discussions).
+
+Find us on [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI), and [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Security
+
+Report vulnerabilities privately through [GitHub security advisories](https://github.com/open-webui/open-webui/security). Security reports are accepted only through GitHub.
+
+### Star History
@@ -258,6 +123,10 @@ If you believe you've found a security vulnerability, or something that shouldn'
----
+#### License
-Created by [Timothy Jaeryang Baek](https://github.com/tjbck) - Let's make Open WebUI even more amazing together! 💪
+Includes code under the Open WebUI License, which requires preserving the Open WebUI branding, and prior contributions under their original licenses. See [LICENSE](./LICENSE) and [LICENSE_HISTORY](./LICENSE_HISTORY) for terms and history.
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Careers](https://careers.openwebui.com/) · [Sponsor](https://github.com/sponsors/open-webui)
+
+Created by [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.no.md b/README.no.md
new file mode 100644
index 0000000000..7162e8e15f
--- /dev/null
+++ b/README.no.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI er et hjem for KI : en utvidbar og brukervennlig plattform du drifter selv, bygget for å kjøre helt uten nettilgang. Koble til lokale modeller via Ollama, eller bruk OpenAI-kompatible API-er for lokale og skybaserte modeller.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Utforsk Open WebUI →](https://docs.openwebui.com/)
+
+### Installasjon
+
+#### Python
+
+Krever Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Åpne deretter [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Åpne deretter [http://localhost:3000](http://localhost:3000).
+
+| Image-tagg | Innhold |
+| --- | --- |
+| `:main` | Standardimage med avhengigheter for lokal KI |
+| `:slim` | Lettvektsimage med eksterne tjenester for embeddings, dokumentuttrekk og tale |
+| `:cuda` | Open WebUI med CUDA-akselerasjon |
+| `:ollama` | Open WebUI med Ollama inkludert |
+| `:dev` | Nyeste utviklingsbygg |
+
+Legg til disse valgene i `docker run` før image-navnet etter behov:
+
+| Valg | Formål |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Koble til Ollama på en annen server |
+| `-e OPENAI_API_KEY=your_secret_key` | Angi OpenAI-API-nøkkelen din |
+| `-e HF_HUB_OFFLINE=1` | Deaktiver nedlasting av Hugging Face-modeller for bruk uten nettilgang |
+| `--gpus all` | Aktiver tilgang til Nvidia-GPU for `:cuda` eller `:ollama`; krever Nvidia Container Toolkit |
+
+Se [installasjonsveiledningen for Docker](https://docs.openwebui.com/getting-started/quick-start/) for oppsett og konfigurasjonsvalg.
+
+#### Skrivebordsapp
+
+[Last ned den native skrivebordsappen](https://github.com/open-webui/desktop) for macOS, Windows og Linux.
+
+[Les dokumentasjonen →](https://docs.openwebui.com/getting-started/)
+
+### Økosystem
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Utførelseslaget som gjør Open WebUI til et komplett agentmiljø, med enterprise-orkestrering av egne arbeidsområder for hver bruker.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Speil mapper, kodearkiver, bøtter og wikier til Open WebUI Knowledge Bases med inkrementell synkronisering.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Datamaskinen din i enhver nettleser: filer, editor, terminal, Git og valgfrie KI-agenter, som kjører på din egen maskin.
+
+Se [økosystemets dokumentasjon](https://docs.openwebui.com/ecosystem/) for detaljer.
+
+### Feilsøking og oppdateringer
+
+Se [feilsøkingsveiledningen](https://docs.openwebui.com/troubleshooting/) ved tilkoblingsproblemer og [oppdateringsveiledningen](https://docs.openwebui.com/getting-started/updating) for å oppdatere installasjonen.
+
+### Dokumentasjon
+
+Se [dokumentasjonen](https://docs.openwebui.com/) for konfigurasjon og bruk, og [veikartet](https://docs.openwebui.com/roadmap/) for planlagt arbeid.
+
+For Docker Compose, Kubernetes og andre oppsett, se [installasjonsdokumentasjonen](https://docs.openwebui.com/getting-started/).
+
+### Hjelp
+
+[Opprett en sak](https://github.com/open-webui/open-webui/issues) eller [start en diskusjon](https://github.com/open-webui/open-webui/discussions).
+
+Du finner oss på [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) og [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Sikkerhet
+
+Rapporter sårbarheter privat via [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sikkerhetsrapporter mottas kun via GitHub.
+
+### Stjernehistorikk
+
+
+
+
+
+
+
+
+
+#### Lisens
+
+Inneholder kode under Open WebUI License, som krever at Open WebUI-merkevaren beholdes, samt tidligere bidrag under sine opprinnelige lisenser. Se [LICENSE](./LICENSE) og [LICENSE_HISTORY](./LICENSE_HISTORY) for vilkår og historikk.
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Karriere](https://careers.openwebui.com/) · [Støtt prosjektet](https://github.com/sponsors/open-webui)
+
+Laget av [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.pl.md b/README.pl.md
new file mode 100644
index 0000000000..e97ef12a5a
--- /dev/null
+++ b/README.pl.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI to dom dla AI : rozszerzalna, łatwa w obsłudze platforma do samodzielnego hostowania, zaprojektowana do pracy całkowicie offline. Podłącz lokalne modele przez Ollama lub korzystaj z API zgodnych z OpenAI dla modeli lokalnych i chmurowych.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Poznaj Open WebUI →](https://docs.openwebui.com/)
+
+### Instalacja
+
+#### Python
+
+Wymaga Pythona 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Następnie otwórz [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Następnie otwórz [http://localhost:3000](http://localhost:3000).
+
+| Tag obrazu | Zawartość |
+| --- | --- |
+| `:main` | Standardowy obraz z zależnościami dla lokalnej AI |
+| `:slim` | Lekki obraz korzystający z usług zewnętrznych do osadzeń, ekstrakcji dokumentów i obsługi głosu |
+| `:cuda` | Open WebUI z akceleracją CUDA |
+| `:ollama` | Open WebUI z dołączonym Ollama |
+| `:dev` | Najnowsza kompilacja rozwojowa |
+
+W razie potrzeby dodaj te opcje do `docker run` przed nazwą obrazu:
+
+| Opcja | Zastosowanie |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Połączenie z Ollama na innym serwerze |
+| `-e OPENAI_API_KEY=your_secret_key` | Ustawienie klucza API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Wyłączenie pobierania modeli Hugging Face do pracy offline |
+| `--gpus all` | Włączenie dostępu do GPU Nvidia dla `:cuda` lub `:ollama`; wymaga Nvidia Container Toolkit |
+
+Instrukcje i opcje konfiguracji znajdziesz w [przewodniku instalacji przez Docker](https://docs.openwebui.com/getting-started/quick-start/).
+
+#### Aplikacja desktopowa
+
+[Pobierz natywną aplikację desktopową](https://github.com/open-webui/desktop) dla macOS, Windows i Linux.
+
+[Przeczytaj dokumentację →](https://docs.openwebui.com/getting-started/)
+
+### Ekosystem
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Warstwa wykonawcza, która zmienia Open WebUI w kompletne środowisko agentowe, z orkiestracją klasy enterprise dla osobnych przestrzeni roboczych użytkowników.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Synchronizuj przyrostowo foldery, repozytoria, zasobniki i wiki z bazami wiedzy Open WebUI.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Twój komputer w dowolnej przeglądarce: pliki, edytor, terminal, Git i opcjonalni agenci AI, działający na twojej własnej maszynie.
+
+Szczegóły znajdziesz w [dokumentacji ekosystemu](https://docs.openwebui.com/ecosystem/).
+
+### Rozwiązywanie problemów i aktualizacje
+
+W razie problemów z połączeniem skorzystaj z [poradnika rozwiązywania problemów](https://docs.openwebui.com/troubleshooting/), a aby zaktualizować instalację — z [poradnika aktualizacji](https://docs.openwebui.com/getting-started/updating).
+
+### Dokumentacja
+
+Informacje o konfiguracji i użytkowaniu znajdziesz w [dokumentacji](https://docs.openwebui.com/), a planowane prace w [planie rozwoju](https://docs.openwebui.com/roadmap/).
+
+Informacje o Docker Compose, Kubernetes i innych sposobach instalacji znajdziesz w [dokumentacji instalacji](https://docs.openwebui.com/getting-started/).
+
+### Pomoc
+
+[Utwórz zgłoszenie](https://github.com/open-webui/open-webui/issues) lub [rozpocznij dyskusję](https://github.com/open-webui/open-webui/discussions).
+
+Znajdziesz nas na [Reddicie](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) i [Discordzie](https://discord.gg/5rJgQTnV4s).
+
+### Bezpieczeństwo
+
+Zgłaszaj luki poufnie przez [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Zgłoszenia dotyczące bezpieczeństwa przyjmujemy wyłącznie przez GitHub.
+
+### Historia gwiazdek
+
+
+
+
+
+
+
+
+
+#### Licencja
+
+Zawiera kod na licencji Open WebUI License, która wymaga zachowania oznaczeń marki Open WebUI, oraz wcześniejsze wkłady na ich oryginalnych licencjach. Warunki i historię znajdziesz w [LICENSE](./LICENSE) i [LICENSE_HISTORY](./LICENSE_HISTORY).
+
+[Enterprise](https://docs.openwebui.com/enterprise) · [Kariera](https://careers.openwebui.com/) · [Wesprzyj](https://github.com/sponsors/open-webui)
+
+Autor: [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.ru.md b/README.ru.md
new file mode 100644
index 0000000000..79d5f86932
--- /dev/null
+++ b/README.ru.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI — это дом для ИИ : расширяемая и удобная платформа для самостоятельного размещения, способная работать полностью офлайн. Подключайте локальные модели через Ollama или используйте совместимые с OpenAI API для локальных и облачных моделей.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Знакомство с Open WebUI →](https://docs.openwebui.com/)
+
+### Установка
+
+#### Python
+
+Требуется Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Затем откройте [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Затем откройте [http://localhost:3000](http://localhost:3000).
+
+| Тег образа | Содержимое |
+| --- | --- |
+| `:main` | Стандартный образ с зависимостями для локального ИИ |
+| `:slim` | Облегчённый образ с внешними сервисами для эмбеддингов, извлечения данных из документов и обработки речи |
+| `:cuda` | Open WebUI с ускорением CUDA |
+| `:ollama` | Open WebUI со встроенным Ollama |
+| `:dev` | Последняя сборка для разработки |
+
+При необходимости добавьте эти параметры в `docker run` перед именем образа:
+
+| Параметр | Назначение |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Подключение к Ollama на другом сервере |
+| `-e OPENAI_API_KEY=your_secret_key` | Установка ключа API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Отключение загрузки моделей Hugging Face для работы офлайн |
+| `--gpus all` | Доступ к GPU Nvidia для `:cuda` или `:ollama`; требуется Nvidia Container Toolkit |
+
+Инструкции и параметры настройки приведены в [руководстве по установке через Docker](https://docs.openwebui.com/getting-started/quick-start/).
+
+#### Приложение для компьютера
+
+[Скачайте нативное приложение](https://github.com/open-webui/desktop) для macOS, Windows и Linux.
+
+[Читать документацию →](https://docs.openwebui.com/getting-started/)
+
+### Экосистема
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Слой выполнения действий, который превращает Open WebUI в полноценную среду для агентов, с корпоративной оркестрацией отдельных рабочих пространств пользователей.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Зеркалирование папок, репозиториев, бакетов и вики в базы знаний Open WebUI с инкрементальной синхронизацией.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Ваш компьютер в любом браузере: файлы, редактор, терминал, Git и необязательные ИИ-агенты, работающие на вашей реальной машине.
+
+Подробнее — в [документации экосистемы](https://docs.openwebui.com/ecosystem/).
+
+### Устранение неполадок и обновления
+
+При проблемах с подключением обратитесь к [руководству по устранению неполадок](https://docs.openwebui.com/troubleshooting/), а для обновления установки — к [руководству по обновлению](https://docs.openwebui.com/getting-started/updating).
+
+### Документация
+
+Настройка и использование описаны в [документации](https://docs.openwebui.com/), а запланированные работы — в [дорожной карте](https://docs.openwebui.com/roadmap/).
+
+Для Docker Compose, Kubernetes и других вариантов установки см. [документацию по установке](https://docs.openwebui.com/getting-started/).
+
+### Поддержка
+
+[Создайте issue](https://github.com/open-webui/open-webui/issues) или [начните обсуждение](https://github.com/open-webui/open-webui/discussions).
+
+Мы есть на [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) и [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Безопасность
+
+Сообщайте об уязвимостях конфиденциально через [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Сообщения о безопасности принимаются только через GitHub.
+
+### История звёзд
+
+
+
+
+
+
+
+
+
+#### Лицензия
+
+Включает код под Open WebUI License, которая требует сохранения брендинга Open WebUI, а также предыдущие вклады под их исходными лицензиями. Условия и история приведены в [LICENSE](./LICENSE) и [LICENSE_HISTORY](./LICENSE_HISTORY).
+
+[Для организаций](https://docs.openwebui.com/enterprise) · [Карьера](https://careers.openwebui.com/) · [Поддержать проект](https://github.com/sponsors/open-webui)
+
+Автор: [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.th.md b/README.th.md
new file mode 100644
index 0000000000..aa69df7ec6
--- /dev/null
+++ b/README.th.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI คือ บ้านสำหรับ AI : แพลตฟอร์มที่โฮสต์เองได้ ขยายความสามารถได้ ใช้งานง่าย และออกแบบให้ทำงานแบบออฟไลน์ได้ทั้งหมด เชื่อมต่อโมเดลภายในเครื่องผ่าน Ollama หรือใช้ API ที่เข้ากันได้กับ OpenAI สำหรับโมเดลภายในเครื่องและบนคลาวด์
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[สำรวจ Open WebUI →](https://docs.openwebui.com/)
+
+### การติดตั้ง
+
+#### Python
+
+ต้องใช้ Python 3.12
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+จากนั้นเปิด [http://localhost:8080](http://localhost:8080)
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+จากนั้นเปิด [http://localhost:3000](http://localhost:3000)
+
+| แท็กอิมเมจ | สิ่งที่มีให้ |
+| --- | --- |
+| `:main` | อิมเมจมาตรฐานพร้อมแพ็กเกจที่จำเป็นสำหรับ AI ภายในเครื่อง |
+| `:slim` | อิมเมจขนาดเล็กที่ใช้บริการภายนอกสำหรับ embeddings การสกัดข้อมูลจากเอกสาร และเสียง |
+| `:cuda` | Open WebUI พร้อมการเร่งความเร็วด้วย CUDA |
+| `:ollama` | Open WebUI ที่รวม Ollama มาให้ |
+| `:dev` | บิลด์สำหรับการพัฒนาล่าสุด |
+
+เพิ่มตัวเลือกเหล่านี้ใน `docker run` ก่อนชื่ออิมเมจได้ตามต้องการ:
+
+| ตัวเลือก | จุดประสงค์ |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | เชื่อมต่อกับ Ollama บนเซิร์ฟเวอร์อื่น |
+| `-e OPENAI_API_KEY=your_secret_key` | กำหนดคีย์ API ของ OpenAI |
+| `-e HF_HUB_OFFLINE=1` | ปิดการดาวน์โหลดโมเดลจาก Hugging Face สำหรับการใช้งานออฟไลน์ |
+| `--gpus all` | เปิดใช้ GPU Nvidia สำหรับ `:cuda` หรือ `:ollama` โดยต้องมี Nvidia Container Toolkit |
+
+ดูขั้นตอนการติดตั้งและตัวเลือกการตั้งค่าใน[คู่มือการติดตั้งด้วย Docker](https://docs.openwebui.com/getting-started/quick-start/)
+
+#### แอปเดสก์ท็อป
+
+[ดาวน์โหลดแอปเดสก์ท็อปเนทีฟ](https://github.com/open-webui/desktop)สำหรับ macOS, Windows และ Linux
+
+[อ่านเอกสาร →](https://docs.openwebui.com/getting-started/)
+
+### ระบบนิเวศ
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): ชั้นการทำงานที่ทำให้ Open WebUI เป็นสภาพแวดล้อมเอเจนต์ที่ครบถ้วน พร้อมระบบจัดการพื้นที่ทำงานแยกตามผู้ใช้ในระดับองค์กร
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): ทำสำเนาโฟลเดอร์ รีโพซิทอรี บักเก็ต และวิกิลงในฐานความรู้ Open WebUI ด้วยการซิงก์เฉพาะส่วนที่เปลี่ยนแปลง
+- [Open WebUI Computer](https://github.com/open-webui/computer): คอมพิวเตอร์ของคุณในทุกเบราว์เซอร์: ไฟล์ ตัวแก้ไข เทอร์มินัล Git และเอเจนต์ AI ที่เลือกใช้ได้ ทั้งหมดทำงานบนเครื่องจริงของคุณ
+
+ดูรายละเอียดใน[เอกสารระบบนิเวศ](https://docs.openwebui.com/ecosystem/)
+
+### การแก้ไขปัญหาและการอัปเดต
+
+ดู[คู่มือแก้ไขปัญหา](https://docs.openwebui.com/troubleshooting/)สำหรับปัญหาการเชื่อมต่อ และ[คู่มืออัปเดต](https://docs.openwebui.com/getting-started/updating)เพื่ออัปเดตการติดตั้งของคุณ
+
+### เอกสาร
+
+ดู[เอกสาร](https://docs.openwebui.com/)สำหรับการตั้งค่าและการใช้งาน และ[แผนการพัฒนา](https://docs.openwebui.com/roadmap/)สำหรับงานที่วางแผนไว้
+
+สำหรับ Docker Compose, Kubernetes และการติดตั้งแบบอื่น ๆ ดู[เอกสารการติดตั้ง](https://docs.openwebui.com/getting-started/)
+
+### การช่วยเหลือ
+
+[เปิด issue](https://github.com/open-webui/open-webui/issues) หรือ[เริ่มการสนทนา](https://github.com/open-webui/open-webui/discussions)
+
+พบเราได้ที่ [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) และ [Discord](https://discord.gg/5rJgQTnV4s)
+
+### ความปลอดภัย
+
+รายงานช่องโหว่แบบเป็นส่วนตัวผ่าน [GitHub Security Advisories](https://github.com/open-webui/open-webui/security) โดยรับรายงานด้านความปลอดภัยผ่าน GitHub เท่านั้น
+
+### ประวัติจำนวนดาว
+
+
+
+
+
+
+
+
+
+#### สัญญาอนุญาต
+
+มีโค้ดภายใต้ Open WebUI License ซึ่งกำหนดให้คงแบรนด์ Open WebUI ไว้ รวมถึงผลงานที่มีผู้ร่วมพัฒนาก่อนหน้านี้ภายใต้สัญญาอนุญาตเดิมของแต่ละส่วน ดูเงื่อนไขและประวัติได้ที่ [LICENSE](./LICENSE) และ [LICENSE_HISTORY](./LICENSE_HISTORY)
+
+[องค์กร](https://docs.openwebui.com/enterprise) · [ร่วมงานกับเรา](https://careers.openwebui.com/) · [สนับสนุนโครงการ](https://github.com/sponsors/open-webui)
+
+สร้างโดย [Timothy Jaeryang Baek](https://github.com/tjbck)
diff --git a/README.tr.md b/README.tr.md
new file mode 100644
index 0000000000..b6c166e389
--- /dev/null
+++ b/README.tr.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI, yapay zekâ için bir yuva dır: tamamen çevrimdışı çalışmak üzere tasarlanmış, genişletilebilir, kullanımı kolay ve kendi sunucunuzda barındırabileceğiniz bir platform. Yerel modellere Ollama üzerinden bağlanın veya yerel ve bulut modelleri için OpenAI uyumlu API’leri kullanın.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Open WebUI’ı keşfedin →](https://docs.openwebui.com/)
+
+### Kurulum
+
+#### Python
+
+Python 3.12 gerektirir.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Ardından [http://localhost:8080](http://localhost:8080) adresini açın.
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Ardından [http://localhost:3000](http://localhost:3000) adresini açın.
+
+| İmaj etiketi | İçerik |
+| --- | --- |
+| `:main` | Yerel yapay zekâ bağımlılıklarını içeren standart imaj |
+| `:slim` | Gömme vektörleri, belge çıkarımı ve ses için harici hizmetler kullanan hafif imaj |
+| `:cuda` | CUDA hızlandırmalı Open WebUI |
+| `:ollama` | Ollama ile birlikte gelen Open WebUI |
+| `:dev` | En son geliştirme derlemesi |
+
+Gerektiğinde bu seçenekleri `docker run` komutunda imaj adından önce ekleyin:
+
+| Seçenek | Amaç |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Başka bir sunucudaki Ollama’ya bağlanma |
+| `-e OPENAI_API_KEY=your_secret_key` | OpenAI API anahtarınızı ayarlama |
+| `-e HF_HUB_OFFLINE=1` | Çevrimdışı kullanım için Hugging Face model indirmelerini devre dışı bırakma |
+| `--gpus all` | `:cuda` veya `:ollama` için Nvidia GPU erişimini etkinleştirme; Nvidia Container Toolkit gerektirir |
+
+Kurulum adımları ve yapılandırma seçenekleri için [Docker kurulum kılavuzuna](https://docs.openwebui.com/getting-started/quick-start/) bakın.
+
+#### Masaüstü uygulaması
+
+macOS, Windows ve Linux için [yerel masaüstü uygulamasını indirin](https://github.com/open-webui/desktop).
+
+[Belgeleri okuyun →](https://docs.openwebui.com/getting-started/)
+
+### Ekosistem
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI’ı eksiksiz bir ajan çalışma ortamına dönüştüren yürütme katmanı; kullanıcıya özel çalışma alanları için kurumsal orkestrasyon sunar.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Klasörleri, depoları, nesne depolama kovalarını ve vikileri artımlı eşitleme ile Open WebUI bilgi tabanlarına yansıtın.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Bilgisayarınız her tarayıcıda: dosyalar, düzenleyici, terminal, Git ve isteğe bağlı yapay zekâ ajanları kendi gerçek makinenizde çalışır.
+
+Ayrıntılar için [ekosistem belgelerine](https://docs.openwebui.com/ecosystem/) bakın.
+
+### Sorun giderme ve güncellemeler
+
+Bağlantı sorunları için [sorun giderme kılavuzuna](https://docs.openwebui.com/troubleshooting/), kurulumunuzu güncellemek için [güncelleme kılavuzuna](https://docs.openwebui.com/getting-started/updating) bakın.
+
+### Belgeler
+
+Yapılandırma ve kullanım için [belgelere](https://docs.openwebui.com/), planlanan çalışmalar için [yol haritasına](https://docs.openwebui.com/roadmap/) bakın.
+
+Docker Compose, Kubernetes ve diğer kurulumlar için [kurulum belgelerine](https://docs.openwebui.com/getting-started/) bakın.
+
+### Destek
+
+[Bir issue açın](https://github.com/open-webui/open-webui/issues) veya [tartışma başlatın](https://github.com/open-webui/open-webui/discussions).
+
+Bizi [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) ve [Discord](https://discord.gg/5rJgQTnV4s) üzerinde bulabilirsiniz.
+
+### Güvenlik
+
+Güvenlik açıklarını [GitHub Security Advisories](https://github.com/open-webui/open-webui/security) üzerinden gizli olarak bildirin. Güvenlik bildirimleri yalnızca GitHub üzerinden kabul edilir.
+
+### Yıldız geçmişi
+
+
+
+
+
+
+
+
+
+#### Lisans
+
+Open WebUI markasının korunmasını gerektiren Open WebUI License kapsamındaki kodu ve kendi özgün lisanslarına tabi önceki katkıları içerir. Koşullar ve geçmiş için [LICENSE](./LICENSE) ve [LICENSE_HISTORY](./LICENSE_HISTORY) dosyalarına bakın.
+
+[Kurumsal](https://docs.openwebui.com/enterprise) · [Kariyer](https://careers.openwebui.com/) · [Sponsor olun](https://github.com/sponsors/open-webui)
+
+Geliştiren: [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.uk.md b/README.uk.md
new file mode 100644
index 0000000000..0df42addb3
--- /dev/null
+++ b/README.uk.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI — це дім для ШІ : розширювана й зручна платформа для самостійного розгортання, здатна працювати повністю офлайн. Підключайте локальні моделі через Ollama або використовуйте сумісні з OpenAI API для локальних і хмарних моделей.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Дізнатися про Open WebUI →](https://docs.openwebui.com/)
+
+### Встановлення
+
+#### Python
+
+Потрібен Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Потім відкрийте [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Потім відкрийте [http://localhost:3000](http://localhost:3000).
+
+| Тег образу | Вміст |
+| --- | --- |
+| `:main` | Стандартний образ із залежностями для локального ШІ |
+| `:slim` | Полегшений образ із зовнішніми сервісами для ембедингів, видобування даних із документів і обробки мовлення |
+| `:cuda` | Open WebUI з прискоренням CUDA |
+| `:ollama` | Open WebUI із вбудованим Ollama |
+| `:dev` | Найновіша збірка для розробки |
+
+За потреби додайте ці параметри до `docker run` перед назвою образу:
+
+| Параметр | Призначення |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Підключення до Ollama на іншому сервері |
+| `-e OPENAI_API_KEY=your_secret_key` | Встановлення ключа API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Вимкнення завантаження моделей Hugging Face для роботи офлайн |
+| `--gpus all` | Доступ до GPU Nvidia для `:cuda` або `:ollama`; потрібен Nvidia Container Toolkit |
+
+Інструкції та параметри налаштування наведено в [посібнику зі встановлення через Docker](https://docs.openwebui.com/getting-started/quick-start/).
+
+#### Настільний застосунок
+
+[Завантажте нативний настільний застосунок](https://github.com/open-webui/desktop) для macOS, Windows і Linux.
+
+[Читати документацію →](https://docs.openwebui.com/getting-started/)
+
+### Екосистема
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Шар виконання дій, який перетворює Open WebUI на повноцінне середовище для агентів, із корпоративною оркестрацією окремих робочих просторів користувачів.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Дзеркальне копіювання папок, репозиторіїв, бакетів і вікі до баз знань Open WebUI з інкрементальною синхронізацією.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Ваш комп’ютер у будь-якому браузері: файли, редактор, термінал, Git і необов’язкові ШІ-агенти, що працюють на вашій реальній машині.
+
+Докладніше — у [документації екосистеми](https://docs.openwebui.com/ecosystem/).
+
+### Усунення несправностей та оновлення
+
+У разі проблем із підключенням дивіться [посібник з усунення несправностей](https://docs.openwebui.com/troubleshooting/), а для оновлення інсталяції — [посібник з оновлення](https://docs.openwebui.com/getting-started/updating).
+
+### Документація
+
+Налаштування й використання описано в [документації](https://docs.openwebui.com/), а заплановані роботи — у [дорожній карті](https://docs.openwebui.com/roadmap/).
+
+Для Docker Compose, Kubernetes та інших способів встановлення дивіться [документацію зі встановлення](https://docs.openwebui.com/getting-started/).
+
+### Підтримка
+
+[Створіть issue](https://github.com/open-webui/open-webui/issues) або [розпочніть обговорення](https://github.com/open-webui/open-webui/discussions).
+
+Знайдіть нас на [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) і [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Безпека
+
+Повідомляйте про вразливості конфіденційно через [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Повідомлення про безпеку приймаються лише через GitHub.
+
+### Історія зірок
+
+
+
+
+
+
+
+
+
+#### Ліцензія
+
+Містить код під Open WebUI License, яка вимагає збереження брендингу Open WebUI, а також попередні внески під їхніми початковими ліцензіями. Умови й історію наведено в [LICENSE](./LICENSE) та [LICENSE_HISTORY](./LICENSE_HISTORY).
+
+[Для організацій](https://docs.openwebui.com/enterprise) · [Кар’єра](https://careers.openwebui.com/) · [Підтримати проєкт](https://github.com/sponsors/open-webui)
+
+Автор: [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.vi.md b/README.vi.md
new file mode 100644
index 0000000000..727296c15f
--- /dev/null
+++ b/README.vi.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI là ngôi nhà dành cho AI : một nền tảng tự lưu trữ, dễ mở rộng, dễ sử dụng và được thiết kế để hoạt động hoàn toàn ngoại tuyến. Kết nối mô hình cục bộ qua Ollama hoặc dùng API tương thích với OpenAI cho các mô hình cục bộ và trên đám mây.
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[Khám phá Open WebUI →](https://docs.openwebui.com/)
+
+### Cài đặt
+
+#### Python
+
+Yêu cầu Python 3.12.
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+Sau đó mở [http://localhost:8080](http://localhost:8080).
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+Sau đó mở [http://localhost:3000](http://localhost:3000).
+
+| Thẻ image | Nội dung |
+| --- | --- |
+| `:main` | Image tiêu chuẩn với các thư viện phụ thuộc cho AI cục bộ |
+| `:slim` | Image gọn nhẹ dùng dịch vụ bên ngoài cho embedding, trích xuất tài liệu và giọng nói |
+| `:cuda` | Open WebUI với tăng tốc CUDA |
+| `:ollama` | Open WebUI tích hợp sẵn Ollama |
+| `:dev` | Bản dựng phát triển mới nhất |
+
+Thêm các tùy chọn sau vào `docker run` trước tên image khi cần:
+
+| Tùy chọn | Mục đích |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Kết nối đến Ollama trên máy chủ khác |
+| `-e OPENAI_API_KEY=your_secret_key` | Thiết lập khóa API OpenAI |
+| `-e HF_HUB_OFFLINE=1` | Tắt tải mô hình Hugging Face để sử dụng ngoại tuyến |
+| `--gpus all` | Bật quyền truy cập GPU Nvidia cho `:cuda` hoặc `:ollama`; yêu cầu Nvidia Container Toolkit |
+
+Xem [hướng dẫn cài đặt Docker](https://docs.openwebui.com/getting-started/quick-start/) để biết các bước thiết lập và tùy chọn cấu hình.
+
+#### Ứng dụng máy tính
+
+[Tải ứng dụng máy tính gốc](https://github.com/open-webui/desktop) cho macOS, Windows và Linux.
+
+[Đọc tài liệu →](https://docs.openwebui.com/getting-started/)
+
+### Hệ sinh thái
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Lớp thực thi biến Open WebUI thành môi trường tác tử hoàn chỉnh, với khả năng điều phối cấp doanh nghiệp cho không gian làm việc riêng của từng người dùng.
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Đồng bộ các thư mục, kho mã, bucket và wiki vào cơ sở tri thức Open WebUI theo kiểu gia tăng.
+- [Open WebUI Computer](https://github.com/open-webui/computer): Máy tính của bạn trong bất kỳ trình duyệt nào: tệp, trình soạn thảo, terminal, Git và các tác tử AI tùy chọn đều chạy trên máy thật của bạn.
+
+Xem [tài liệu hệ sinh thái](https://docs.openwebui.com/ecosystem/) để biết chi tiết.
+
+### Khắc phục sự cố và cập nhật
+
+Xem [hướng dẫn khắc phục sự cố](https://docs.openwebui.com/troubleshooting/) khi gặp vấn đề kết nối và [hướng dẫn cập nhật](https://docs.openwebui.com/getting-started/updating) để cập nhật bản cài đặt.
+
+### Tài liệu
+
+Xem [tài liệu](https://docs.openwebui.com/) để biết cách cấu hình và sử dụng, cùng [lộ trình](https://docs.openwebui.com/roadmap/) cho các công việc dự kiến.
+
+Với Docker Compose, Kubernetes và các cách thiết lập khác, xem [tài liệu cài đặt](https://docs.openwebui.com/getting-started/).
+
+### Hỗ trợ
+
+[Tạo issue](https://github.com/open-webui/open-webui/issues) hoặc [bắt đầu thảo luận](https://github.com/open-webui/open-webui/discussions).
+
+Tìm chúng tôi trên [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) và [Discord](https://discord.gg/5rJgQTnV4s).
+
+### Bảo mật
+
+Báo cáo lỗ hổng một cách riêng tư qua [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Báo cáo bảo mật chỉ được tiếp nhận qua GitHub.
+
+### Lịch sử sao
+
+
+
+
+
+
+
+
+
+#### Giấy phép
+
+Bao gồm mã theo Open WebUI License, yêu cầu giữ nguyên thương hiệu Open WebUI, và các đóng góp trước đây theo giấy phép gốc tương ứng. Xem [LICENSE](./LICENSE) và [LICENSE_HISTORY](./LICENSE_HISTORY) để biết điều khoản và lịch sử.
+
+[Doanh nghiệp](https://docs.openwebui.com/enterprise) · [Tuyển dụng](https://careers.openwebui.com/) · [Tài trợ](https://github.com/sponsors/open-webui)
+
+Được tạo bởi [Timothy Jaeryang Baek](https://github.com/tjbck).
diff --git a/README.zh.md b/README.zh.md
new file mode 100644
index 0000000000..6bae944544
--- /dev/null
+++ b/README.zh.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI 是 AI 的家 :一个可扩展、易于使用的自托管平台,支持完全离线运行。通过 Ollama 连接本地模型,或使用兼容 OpenAI 的 API 连接本地和云端模型。
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[探索 Open WebUI →](https://docs.openwebui.com/)
+
+### 安装
+
+#### Python
+
+需要 Python 3.12。
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+然后打开 [http://localhost:8080](http://localhost:8080)。
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+然后打开 [http://localhost:3000](http://localhost:3000)。
+
+| 镜像标签 | 内容 |
+| --- | --- |
+| `:main` | 包含本地 AI 依赖的标准镜像 |
+| `:slim` | 轻量镜像,通过外部服务处理嵌入、文档提取和语音 |
+| `:cuda` | 支持 CUDA 加速的 Open WebUI |
+| `:ollama` | 内置 Ollama 的 Open WebUI |
+| `:dev` | 最新开发版本 |
+
+根据需要,在 `docker run` 的镜像名称前添加以下选项:
+
+| 选项 | 用途 |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 连接另一台服务器上的 Ollama |
+| `-e OPENAI_API_KEY=your_secret_key` | 设置 OpenAI API 密钥 |
+| `-e HF_HUB_OFFLINE=1` | 禁用 Hugging Face 模型下载,以便离线使用 |
+| `--gpus all` | 为 `:cuda` 或 `:ollama` 启用 Nvidia GPU 访问;需要 Nvidia Container Toolkit |
+
+安装步骤和配置选项请参阅 [Docker 安装指南](https://docs.openwebui.com/getting-started/quick-start/)。
+
+#### 桌面应用
+
+[下载原生桌面应用](https://github.com/open-webui/desktop),支持 macOS、Windows 和 Linux。
+
+[阅读文档 →](https://docs.openwebui.com/getting-started/)
+
+### 生态系统
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): 为 Open WebUI 提供执行能力,使其成为完整的智能体运行框架,并通过企业级编排为每位用户管理独立工作空间。
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): 通过增量同步,将文件夹、代码仓库、存储桶和 Wiki 镜像到 Open WebUI 知识库。
+- [Open WebUI Computer](https://github.com/open-webui/computer): 在任意浏览器中使用你的电脑:文件、编辑器、终端、Git 和可选的 AI 智能体,均在你的真实机器上运行。
+
+详情请参阅[生态系统文档](https://docs.openwebui.com/ecosystem/)。
+
+### 故障排查与更新
+
+连接问题请参阅[故障排查指南](https://docs.openwebui.com/troubleshooting/),更新安装请参阅[更新指南](https://docs.openwebui.com/getting-started/updating)。
+
+### 文档
+
+配置和使用方法请参阅[文档](https://docs.openwebui.com/),计划中的工作请参阅[路线图](https://docs.openwebui.com/roadmap/)。
+
+Docker Compose、Kubernetes 及其他部署方式请参阅[安装文档](https://docs.openwebui.com/getting-started/)。
+
+### 支持
+
+[提交 Issue](https://github.com/open-webui/open-webui/issues) 或[发起讨论](https://github.com/open-webui/open-webui/discussions)。
+
+也可以在 [Reddit](https://www.reddit.com/r/OpenWebUI/)、[X](https://x.com/OpenWebUI) 和 [Discord](https://discord.gg/5rJgQTnV4s) 找到我们。
+
+### 安全
+
+请通过 [GitHub 安全公告](https://github.com/open-webui/open-webui/security)私下报告漏洞。安全报告仅通过 GitHub 接收。
+
+### Star 历史
+
+
+
+
+
+
+
+
+
+#### 许可证
+
+包含采用 Open WebUI License 的代码,该许可证要求保留 Open WebUI 品牌标识;此前的贡献仍适用各自的原始许可证。条款和历史请参阅 [LICENSE](./LICENSE) 和 [LICENSE_HISTORY](./LICENSE_HISTORY)。
+
+[企业版](https://docs.openwebui.com/enterprise) · [招聘](https://careers.openwebui.com/) · [赞助](https://github.com/sponsors/open-webui)
+
+由 [Timothy Jaeryang Baek](https://github.com/tjbck) 创建。
diff --git a/README.zht.md b/README.zht.md
new file mode 100644
index 0000000000..7b4574c856
--- /dev/null
+++ b/README.zht.md
@@ -0,0 +1,132 @@
+Open WebUI
+
+Open WebUI 是 AI 的家 :一個可擴充、易於使用的自架平台,支援完全離線執行。透過 Ollama 連接本機模型,或使用相容於 OpenAI 的 API 連接本機和雲端模型。
+
+[English](README.md) |
+[简体中文](README.zh.md) |
+[繁體中文](README.zht.md) |
+[한국어](README.ko.md) |
+[Deutsch](README.de.md) |
+[Español](README.es.md) |
+[Français](README.fr.md) |
+[Italiano](README.it.md) |
+[Dansk](README.da.md) |
+[日本語](README.ja.md) |
+[Polski](README.pl.md) |
+[Русский](README.ru.md) |
+[Bosanski](README.bs.md) |
+[العربية](README.ar.md) |
+[Norsk](README.no.md) |
+[Português (Brasil)](README.br.md) |
+[ไทย](README.th.md) |
+[Türkçe](README.tr.md) |
+[Українська](README.uk.md) |
+[বাংলা](README.bn.md) |
+[Ελληνικά](README.gr.md) |
+[Tiếng Việt](README.vi.md)
+
+[](https://docs.openwebui.com/)
+
+
+
+
+
+
+
+
+[](https://discord.gg/5rJgQTnV4s)
+[](https://github.com/sponsors/open-webui)
+
+[探索 Open WebUI →](https://docs.openwebui.com/)
+
+### 安裝
+
+#### Python
+
+需要 Python 3.12。
+
+```bash
+pip install open-webui
+open-webui serve
+```
+
+接著開啟 [http://localhost:8080](http://localhost:8080)。
+
+#### Docker
+
+```bash
+docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
+```
+
+接著開啟 [http://localhost:3000](http://localhost:3000)。
+
+| 映像標籤 | 內容 |
+| --- | --- |
+| `:main` | 包含本機 AI 相依套件的標準映像 |
+| `:slim` | 輕量映像,透過外部服務處理嵌入、文件擷取與語音 |
+| `:cuda` | 支援 CUDA 加速的 Open WebUI |
+| `:ollama` | 內建 Ollama 的 Open WebUI |
+| `:dev` | 最新開發版本 |
+
+視需要在 `docker run` 的映像名稱前加入以下選項:
+
+| 選項 | 用途 |
+| --- | --- |
+| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 連接另一台伺服器上的 Ollama |
+| `-e OPENAI_API_KEY=your_secret_key` | 設定 OpenAI API 金鑰 |
+| `-e HF_HUB_OFFLINE=1` | 停用 Hugging Face 模型下載,以便離線使用 |
+| `--gpus all` | 為 `:cuda` 或 `:ollama` 啟用 Nvidia GPU 存取;需要 Nvidia Container Toolkit |
+
+安裝步驟與設定選項請參閱 [Docker 安裝指南](https://docs.openwebui.com/getting-started/quick-start/)。
+
+#### 桌面應用程式
+
+[下載原生桌面應用程式](https://github.com/open-webui/desktop),支援 macOS、Windows 和 Linux。
+
+[閱讀文件 →](https://docs.openwebui.com/getting-started/)
+
+### 生態系統
+
+- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): 為 Open WebUI 提供執行能力,使其成為完整的代理執行框架,並透過企業級協調管理每位使用者的獨立工作區。
+- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): 透過增量同步,將資料夾、程式碼儲存庫、儲存桶和 Wiki 鏡像同步至 Open WebUI 知識庫。
+- [Open WebUI Computer](https://github.com/open-webui/computer): 在任何瀏覽器中使用你的電腦:檔案、編輯器、終端機、Git 與選用的 AI 代理,皆在你的實際機器上執行。
+
+詳情請參閱[生態系統文件](https://docs.openwebui.com/ecosystem/)。
+
+### 疑難排解與更新
+
+連線問題請參閱[疑難排解指南](https://docs.openwebui.com/troubleshooting/),更新安裝請參閱[更新指南](https://docs.openwebui.com/getting-started/updating)。
+
+### 文件
+
+設定與使用方式請參閱[文件](https://docs.openwebui.com/),規劃中的工作請參閱[路線圖](https://docs.openwebui.com/roadmap/)。
+
+Docker Compose、Kubernetes 與其他部署方式請參閱[安裝文件](https://docs.openwebui.com/getting-started/)。
+
+### 支援
+
+[提交 Issue](https://github.com/open-webui/open-webui/issues) 或[發起討論](https://github.com/open-webui/open-webui/discussions)。
+
+也可以在 [Reddit](https://www.reddit.com/r/OpenWebUI/)、[X](https://x.com/OpenWebUI) 和 [Discord](https://discord.gg/5rJgQTnV4s) 找到我們。
+
+### 安全性
+
+請透過 [GitHub 安全公告](https://github.com/open-webui/open-webui/security)私下通報漏洞。安全性通報僅透過 GitHub 接收。
+
+### Star 歷史
+
+
+
+
+
+
+
+
+
+#### 授權
+
+包含採用 Open WebUI License 的程式碼,該授權要求保留 Open WebUI 品牌標示;先前的貢獻仍適用各自的原始授權。條款與歷史請參閱 [LICENSE](./LICENSE) 和 [LICENSE_HISTORY](./LICENSE_HISTORY)。
+
+[企業版](https://docs.openwebui.com/enterprise) · [徵才](https://careers.openwebui.com/) · [贊助](https://github.com/sponsors/open-webui)
+
+由 [Timothy Jaeryang Baek](https://github.com/tjbck) 建立。
diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py
index fc9c5543b7..3e98856ec4 100644
--- a/backend/open_webui/config.py
+++ b/backend/open_webui/config.py
@@ -57,9 +57,7 @@ class EndpointFilter(logging.Filter):
logging.getLogger('uvicorn.access').addFilter(EndpointFilter())
-####################################
# Initialization
-####################################
def run_migrations():
@@ -92,9 +90,7 @@ async def import_legacy_config_json():
os.rename(f'{DATA_DIR}/config.json', f'{DATA_DIR}/old_config.json')
-####################################
# Static DIR
-####################################
STATIC_DIR = Path(os.getenv('STATIC_DIR', OPEN_WEBUI_DIR / 'static')).resolve()
STATIC_SOURCE_DIR = FRONTEND_BUILD_DIR / 'static'
@@ -151,7 +147,7 @@ if frontend_loader.exists():
logging.error(f'An error occurred: {e}')
-# --- Storage Provider ---
+# Storage provider
STORAGE_PROVIDER = os.getenv('STORAGE_PROVIDER', 'local') # defaults to local, s3
STORAGE_LOCAL_CACHE = os.getenv('STORAGE_LOCAL_CACHE', 'true').lower() == 'true'
@@ -173,25 +169,19 @@ AZURE_STORAGE_ENDPOINT = os.getenv('AZURE_STORAGE_ENDPOINT', None)
AZURE_STORAGE_CONTAINER_NAME = os.getenv('AZURE_STORAGE_CONTAINER_NAME', None)
AZURE_STORAGE_KEY = os.getenv('AZURE_STORAGE_KEY', None)
-####################################
# File Upload DIR
-####################################
UPLOAD_DIR = DATA_DIR / 'uploads'
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
-####################################
# Cache DIR
-####################################
CACHE_DIR = DATA_DIR / 'cache'
CACHE_DIR.mkdir(parents=True, exist_ok=True)
-####################################
# CUSTOM_NAME (Legacy)
-####################################
# LICENSE covers this legacy Open WebUI branding path.
# Do not alter, remove, obscure, or replace it except as LICENSE permits:
@@ -229,16 +219,12 @@ if CUSTOM_NAME:
pass
-####################################
-# DIRECT CONNECTIONS
-####################################
+# Direct connections
ENABLE_DIRECT_CONNECTIONS = os.getenv('ENABLE_DIRECT_CONNECTIONS', 'False').lower() == 'true'
ENABLE_DIRECT_INTEGRATIONS = os.getenv('ENABLE_DIRECT_INTEGRATIONS', 'False').lower() == 'true'
-####################################
# OLLAMA_BASE_URL
-####################################
ENABLE_OLLAMA_API = os.getenv('ENABLE_OLLAMA_API', 'True').lower() == 'true'
@@ -246,7 +232,7 @@ OLLAMA_API_BASE_URL = os.getenv('OLLAMA_API_BASE_URL', 'http://localhost:11434/a
OLLAMA_BASE_URL = os.getenv('OLLAMA_BASE_URL', '')
if OLLAMA_BASE_URL:
- # Remove trailing slash
+ # Trim the trailing slash; the next path will bring its own.
OLLAMA_BASE_URL = OLLAMA_BASE_URL[:-1] if OLLAMA_BASE_URL.endswith('/') else OLLAMA_BASE_URL
@@ -317,9 +303,7 @@ if _ollama_api_configs:
except (JSONCodec.JSONDecodeError, TypeError):
log.warning('OLLAMA_API_CONFIGS is not valid JSON, ignoring')
-####################################
# OPENAI_API
-####################################
ENABLE_OPENAI_API = os.getenv('ENABLE_OPENAI_API', 'True').lower() == 'true'
@@ -373,16 +357,12 @@ except Exception:
OPENAI_API_BASE_URL = 'https://api.openai.com/v1'
-####################################
-# MODELS
-####################################
+# Models
ENABLE_BASE_MODELS_CACHE = os.getenv('ENABLE_BASE_MODELS_CACHE', 'False').lower() == 'true'
-####################################
# TOOL_SERVERS
-####################################
try:
tool_server_connections = JSONCodec.loads(os.getenv('TOOL_SERVER_CONNECTIONS', '[]'))
@@ -395,9 +375,7 @@ TOOL_SERVER_CONNECTIONS = tool_server_connections
OAUTH_CLIENT_TIMEOUT = os.getenv('OAUTH_CLIENT_TIMEOUT', '')
-####################################
# TERMINAL_SERVER
-####################################
terminal_server_connections = JSONCodec.loads(os.getenv('TERMINAL_SERVER_CONNECTIONS', '[]'))
@@ -408,9 +386,7 @@ try:
except Exception:
TERMINAL_PROXY_HEADERS = {}
-####################################
# Code Interpreter
-####################################
ENABLE_CODE_EXECUTION = os.getenv('ENABLE_CODE_EXECUTION', 'True').lower() == 'true'
@@ -502,9 +478,7 @@ CODE_INTERPRETER_PYODIDE_PROMPT = """
- Use `import os; os.listdir('/mnt/uploads')` to discover available files."""
-####################################
# Vector Database
-####################################
VECTOR_DB = os.getenv('VECTOR_DB', 'pgvector' if USE_SLIM else 'chroma')
@@ -841,9 +815,7 @@ VALKEY_HNSW_M = int(os.getenv('VALKEY_HNSW_M', '16'))
VALKEY_HNSW_EF_CONSTRUCTION = int(os.getenv('VALKEY_HNSW_EF_CONSTRUCTION', '200'))
VALKEY_HNSW_EF_RUNTIME = int(os.getenv('VALKEY_HNSW_EF_RUNTIME', '10'))
-####################################
# Information Retrieval (RAG)
-####################################
# If configured, Google Drive will be available as an upload option.
@@ -996,6 +968,17 @@ ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS = (
RAG_FULL_CONTEXT = os.getenv('RAG_FULL_CONTEXT', 'False').lower() == 'true'
RAG_FILE_MAX_COUNT = int(os.getenv('RAG_FILE_MAX_COUNT')) if os.getenv('RAG_FILE_MAX_COUNT') else None
+KNOWLEDGE_MAX_UPLOAD_COUNT = (
+ int(os.getenv('KNOWLEDGE_MAX_UPLOAD_COUNT')) if os.getenv('KNOWLEDGE_MAX_UPLOAD_COUNT') else None
+)
+KNOWLEDGE_MAX_FILE_COUNT = int(os.getenv('KNOWLEDGE_MAX_FILE_COUNT')) if os.getenv('KNOWLEDGE_MAX_FILE_COUNT') else None
+KNOWLEDGE_MAX_FILE_SIZE = int(os.getenv('KNOWLEDGE_MAX_FILE_SIZE')) if os.getenv('KNOWLEDGE_MAX_FILE_SIZE') else None
+if KNOWLEDGE_MAX_UPLOAD_COUNT is not None and KNOWLEDGE_MAX_UPLOAD_COUNT <= 0:
+ raise ValueError('KNOWLEDGE_MAX_UPLOAD_COUNT must be a positive integer or unset')
+if KNOWLEDGE_MAX_FILE_COUNT is not None and KNOWLEDGE_MAX_FILE_COUNT <= 0:
+ raise ValueError('KNOWLEDGE_MAX_FILE_COUNT must be a positive integer or unset')
+if KNOWLEDGE_MAX_FILE_SIZE is not None and KNOWLEDGE_MAX_FILE_SIZE <= 0:
+ raise ValueError('KNOWLEDGE_MAX_FILE_SIZE must be a positive integer or unset')
RAG_FILE_MAX_SIZE = int(os.getenv('RAG_FILE_MAX_SIZE')) if os.getenv('RAG_FILE_MAX_SIZE') else None
@@ -1171,9 +1154,7 @@ YOUTUBE_LOADER_LANGUAGE = os.getenv('YOUTUBE_LOADER_LANGUAGE', 'en').split(',')
YOUTUBE_LOADER_PROXY_URL = os.getenv('YOUTUBE_LOADER_PROXY_URL', '')
-####################################
# Web Search
-####################################
ENABLE_WEB_SEARCH = os.getenv('ENABLE_WEB_SEARCH', 'False').lower() == 'true'
@@ -1363,9 +1344,7 @@ except JSONCodec.JSONDecodeError:
LINKUP_SEARCH_PARAMS = linkup_search_params
-####################################
# Images
-####################################
ENABLE_IMAGE_GENERATION = os.getenv('ENABLE_IMAGE_GENERATION', '').lower() == 'true'
@@ -1573,9 +1552,7 @@ except JSONCodec.JSONDecodeError:
IMAGES_EDIT_COMFYUI_WORKFLOW_NODES = images_edit_comfyui_workflow_nodes
-####################################
# Audio
-####################################
# Transcription
WHISPER_MODEL = os.getenv('WHISPER_MODEL', 'base')
@@ -1691,9 +1668,7 @@ AUDIO_TTS_MISTRAL_API_KEY = os.getenv('AUDIO_TTS_MISTRAL_API_KEY', '')
AUDIO_TTS_MISTRAL_API_BASE_URL = os.getenv('AUDIO_TTS_MISTRAL_API_BASE_URL', 'https://api.mistral.ai/v1')
-####################################
-# WEBUI
-####################################
+# WebUI
WEBUI_URL = os.getenv('WEBUI_URL', '')
@@ -1944,6 +1919,8 @@ USER_PERMISSIONS_CHAT_MULTIPLE_MODELS = os.getenv('USER_PERMISSIONS_CHAT_MULTIPL
USER_PERMISSIONS_CHAT_TEMPORARY = os.getenv('USER_PERMISSIONS_CHAT_TEMPORARY', 'True').lower() == 'true'
+USER_PERMISSIONS_CHAT_SIDE_CHAT = os.getenv('USER_PERMISSIONS_CHAT_SIDE_CHAT', 'False').lower() == 'true'
+
USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED = (
os.getenv('USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED', 'False').lower() == 'true'
)
@@ -2049,6 +2026,7 @@ DEFAULT_USER_PERMISSIONS = {
'call': USER_PERMISSIONS_CHAT_CALL,
'multiple_models': USER_PERMISSIONS_CHAT_MULTIPLE_MODELS,
'temporary': USER_PERMISSIONS_CHAT_TEMPORARY,
+ 'side_chat': USER_PERMISSIONS_CHAT_SIDE_CHAT,
'temporary_enforced': USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED,
},
'features': {
@@ -2103,10 +2081,15 @@ ENABLE_AUTOMATIONS = os.getenv('ENABLE_AUTOMATIONS', 'True').lower() == 'true'
ENABLE_SUBAGENTS = os.getenv('ENABLE_SUBAGENTS', 'False').lower() == 'true'
SUBAGENTS_BACKGROUND_ENABLED = os.getenv('SUBAGENTS_BACKGROUND_ENABLED', 'False').lower() == 'true'
-SUBAGENTS_MAX_CONCURRENT = int(os.getenv('SUBAGENTS_MAX_CONCURRENT', '20'))
-SUBAGENTS_MAX_ASYNC = int(os.getenv('SUBAGENTS_MAX_ASYNC', '20'))
-SUBAGENTS_MAX_ITERATIONS = int(os.getenv('SUBAGENTS_MAX_ITERATIONS', '30'))
-SUBAGENTS_MAX_OUTPUT = int(os.getenv('SUBAGENTS_MAX_OUTPUT', '30000'))
+# Leave empty for unlimited.
+SUBAGENTS_MAX_CONCURRENT = os.getenv('SUBAGENTS_MAX_CONCURRENT', '')
+SUBAGENTS_MAX_CONCURRENT = int(SUBAGENTS_MAX_CONCURRENT) if SUBAGENTS_MAX_CONCURRENT else None
+SUBAGENTS_MAX_ASYNC = os.getenv('SUBAGENTS_MAX_ASYNC', '')
+SUBAGENTS_MAX_ASYNC = int(SUBAGENTS_MAX_ASYNC) if SUBAGENTS_MAX_ASYNC else None
+SUBAGENTS_MAX_ITERATIONS = os.getenv('SUBAGENTS_MAX_ITERATIONS', '')
+SUBAGENTS_MAX_ITERATIONS = int(SUBAGENTS_MAX_ITERATIONS) if SUBAGENTS_MAX_ITERATIONS else None
+SUBAGENTS_MAX_OUTPUT = os.getenv('SUBAGENTS_MAX_OUTPUT', '')
+SUBAGENTS_MAX_OUTPUT = int(SUBAGENTS_MAX_OUTPUT) if SUBAGENTS_MAX_OUTPUT else None
SUBAGENTS_SYSTEM_PROMPT = os.getenv('SUBAGENTS_SYSTEM_PROMPT', '')
AUTOMATION_MAX_COUNT = os.getenv('AUTOMATION_MAX_COUNT', '')
@@ -2115,6 +2098,9 @@ AUTOMATION_MIN_INTERVAL = os.getenv('AUTOMATION_MIN_INTERVAL', '')
AUTOMATION_AUTH_TOKEN_EXPIRES_IN = os.getenv('AUTOMATION_AUTH_TOKEN_EXPIRES_IN', '1h')
+ENABLE_COMMENTS = os.getenv('ENABLE_COMMENTS', 'False').lower() == 'true'
+ENABLE_NOTIFICATIONS = os.getenv('ENABLE_NOTIFICATIONS', 'True').lower() == 'true'
+
ENABLE_NOTES = os.getenv('ENABLE_NOTES', 'True').lower() == 'true'
ENABLE_USER_STATUS = os.getenv('ENABLE_USER_STATUS', 'True').lower() == 'true'
@@ -2240,9 +2226,7 @@ SHOW_ADMIN_DETAILS = os.getenv('SHOW_ADMIN_DETAILS', 'true').lower() == 'true'
ADMIN_EMAIL = os.getenv('ADMIN_EMAIL', None)
-####################################
-# TASKS
-####################################
+# Tasks
TASK_MODEL = os.getenv('TASK_MODEL', '')
@@ -2546,9 +2530,7 @@ Your task is to synthesize these responses into a single, high-quality response.
Responses from models: {{responses}}"""
-####################################
# Auth
-####################################
ENABLE_API_KEYS = os.getenv('ENABLE_API_KEYS', 'False').lower() == 'true'
@@ -2574,9 +2556,7 @@ if JWT_EXPIRES_IN == '-1':
' See: https://docs.openwebui.com/reference/env-configuration\n'
)
-####################################
# OAuth config
-####################################
# Master switch for OAuth/OIDC sign-in. Defaults to enabled so existing
# deployments that already have a provider configured keep working; admins can
@@ -2736,35 +2716,42 @@ if _oauth_authorize_params:
log.warning('OAUTH_AUTHORIZE_PARAMS is not valid JSON, ignoring')
-def oauth_client_kwargs(scope: str, **kwargs):
+def oauth_client_kwargs(scope: str, timeout: int | str | None, code_challenge_method: str | None, **kwargs):
client_kwargs = {
'scope': scope,
**kwargs,
- **({'timeout': int(OAUTH_TIMEOUT)} if OAUTH_TIMEOUT else {}),
+ **({'timeout': int(timeout)} if timeout else {}),
}
- if OAUTH_CODE_CHALLENGE_METHOD == 'S256':
+ if code_challenge_method == 'S256':
client_kwargs['code_challenge_method'] = 'S256'
- elif OAUTH_CODE_CHALLENGE_METHOD:
- raise Exception(
- 'Code challenge methods other than "%s" not supported. Given: "%s"' % ('S256', OAUTH_CODE_CHALLENGE_METHOD)
+ elif code_challenge_method:
+ raise ValueError(
+ 'Code challenge methods other than "%s" not supported. Given: "%s"' % ('S256', code_challenge_method)
)
return client_kwargs
-def load_oauth_providers():
+async def load_oauth_providers():
+ config = await Config.get_namespace('oauth')
+ oauth_timeout = config.get('oauth.timeout')
+ oauth_code_challenge_method = config.get('oauth.code_challenge_method')
OAUTH_PROVIDERS.clear()
- if GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
+ google_client_id = config.get('oauth.google.client_id')
+ google_client_secret = config.get('oauth.google.client_secret')
+ if google_client_id and google_client_secret:
def google_oauth_register(oauth: OAuth):
client = oauth.register(
name='google',
- client_id=GOOGLE_CLIENT_ID,
- client_secret=GOOGLE_CLIENT_SECRET,
+ client_id=google_client_id,
+ client_secret=google_client_secret,
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
- client_kwargs=oauth_client_kwargs(GOOGLE_OAUTH_SCOPE),
- redirect_uri=GOOGLE_REDIRECT_URI,
+ client_kwargs=oauth_client_kwargs(
+ config.get('oauth.google.scope'), oauth_timeout, oauth_code_challenge_method
+ ),
+ redirect_uri=config.get('oauth.google.redirect_uri'),
**({'authorize_params': GOOGLE_OAUTH_AUTHORIZE_PARAMS} if GOOGLE_OAUTH_AUTHORIZE_PARAMS else {}),
)
return client
@@ -2773,37 +2760,47 @@ def load_oauth_providers():
'register': google_oauth_register,
}
- if MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET and MICROSOFT_CLIENT_TENANT_ID:
+ microsoft_client_id = config.get('oauth.microsoft.client_id')
+ microsoft_client_secret = config.get('oauth.microsoft.client_secret')
+ microsoft_client_tenant_id = config.get('oauth.microsoft.tenant_id')
+ microsoft_client_login_base_url = config.get('oauth.microsoft.login_base_url')
+ if microsoft_client_id and microsoft_client_secret and microsoft_client_tenant_id:
def microsoft_oauth_register(oauth: OAuth):
client = oauth.register(
name='microsoft',
- client_id=MICROSOFT_CLIENT_ID,
- client_secret=MICROSOFT_CLIENT_SECRET,
- server_metadata_url=f'{MICROSOFT_CLIENT_LOGIN_BASE_URL}/{MICROSOFT_CLIENT_TENANT_ID}/v2.0/.well-known/openid-configuration?appid={MICROSOFT_CLIENT_ID}',
- client_kwargs=oauth_client_kwargs(MICROSOFT_OAUTH_SCOPE),
- redirect_uri=MICROSOFT_REDIRECT_URI,
+ client_id=microsoft_client_id,
+ client_secret=microsoft_client_secret,
+ server_metadata_url=f'{microsoft_client_login_base_url}/{microsoft_client_tenant_id}/v2.0/.well-known/openid-configuration?appid={microsoft_client_id}',
+ client_kwargs=oauth_client_kwargs(
+ config.get('oauth.microsoft.scope'), oauth_timeout, oauth_code_challenge_method
+ ),
+ redirect_uri=config.get('oauth.microsoft.redirect_uri'),
)
return client
OAUTH_PROVIDERS['microsoft'] = {
- 'picture_url': MICROSOFT_CLIENT_PICTURE_URL,
+ 'picture_url': config.get('oauth.microsoft.picture_url'),
'register': microsoft_oauth_register,
}
- if GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET:
+ github_client_id = config.get('oauth.github.client_id')
+ github_client_secret = config.get('oauth.github.client_secret')
+ if github_client_id and github_client_secret:
def github_oauth_register(oauth: OAuth):
client = oauth.register(
name='github',
- client_id=GITHUB_CLIENT_ID,
- client_secret=GITHUB_CLIENT_SECRET,
+ client_id=github_client_id,
+ client_secret=github_client_secret,
access_token_url='https://github.com/login/oauth/access_token',
authorize_url='https://github.com/login/oauth/authorize',
api_base_url='https://api.github.com',
userinfo_endpoint='https://api.github.com/user',
- client_kwargs=oauth_client_kwargs(GITHUB_CLIENT_SCOPE),
- redirect_uri=GITHUB_CLIENT_REDIRECT_URI,
+ client_kwargs=oauth_client_kwargs(
+ config.get('oauth.github.scope'), oauth_timeout, oauth_code_challenge_method
+ ),
+ redirect_uri=config.get('oauth.github.redirect_uri'),
)
return client
@@ -2812,47 +2809,55 @@ def load_oauth_providers():
'sub_claim': 'id',
}
- if OAUTH_CLIENT_ID and (OAUTH_CLIENT_SECRET or OAUTH_CODE_CHALLENGE_METHOD) and OPENID_PROVIDER_URL:
+ oauth_client_id = config.get('oauth.client_id')
+ oauth_client_secret = config.get('oauth.client_secret')
+ openid_provider_url = config.get('oauth.provider_url')
+ oauth_token_endpoint_auth_method = config.get('oauth.token_endpoint_auth_method')
+ if oauth_client_id and (oauth_client_secret or oauth_code_challenge_method) and openid_provider_url:
def oidc_oauth_register(oauth: OAuth):
client = oauth.register(
name='oidc',
- client_id=OAUTH_CLIENT_ID,
- client_secret=OAUTH_CLIENT_SECRET,
- server_metadata_url=OPENID_PROVIDER_URL,
+ client_id=oauth_client_id,
+ client_secret=oauth_client_secret,
+ server_metadata_url=openid_provider_url,
client_kwargs=oauth_client_kwargs(
- OAUTH_SCOPES,
+ config.get('oauth.scopes'),
+ oauth_timeout,
+ oauth_code_challenge_method,
**(
- {'token_endpoint_auth_method': OAUTH_TOKEN_ENDPOINT_AUTH_METHOD}
- if OAUTH_TOKEN_ENDPOINT_AUTH_METHOD
+ {'token_endpoint_auth_method': oauth_token_endpoint_auth_method}
+ if oauth_token_endpoint_auth_method
else {}
),
),
- redirect_uri=OPENID_REDIRECT_URI,
+ redirect_uri=config.get('oauth.redirect_uri'),
)
return client
OAUTH_PROVIDERS['oidc'] = {
- 'name': OAUTH_PROVIDER_NAME,
+ 'name': config.get('oauth.provider_name'),
'register': oidc_oauth_register,
}
- if FEISHU_CLIENT_ID and FEISHU_CLIENT_SECRET:
+ feishu_client_id = config.get('oauth.feishu.client_id')
+ feishu_client_secret = config.get('oauth.feishu.client_secret')
+ if feishu_client_id and feishu_client_secret:
def feishu_oauth_register(oauth: OAuth):
client = oauth.register(
name='feishu',
- client_id=FEISHU_CLIENT_ID,
- client_secret=FEISHU_CLIENT_SECRET,
+ client_id=feishu_client_id,
+ client_secret=feishu_client_secret,
access_token_url='https://open.feishu.cn/open-apis/authen/v2/oauth/token',
authorize_url='https://accounts.feishu.cn/open-apis/authen/v1/authorize',
api_base_url='https://open.feishu.cn/open-apis',
userinfo_endpoint='https://open.feishu.cn/open-apis/authen/v1/user_info',
client_kwargs={
- 'scope': FEISHU_OAUTH_SCOPE,
- **({'timeout': int(OAUTH_TIMEOUT)} if OAUTH_TIMEOUT else {}),
+ 'scope': config.get('oauth.feishu.scope'),
+ **({'timeout': int(oauth_timeout)} if oauth_timeout else {}),
},
- redirect_uri=FEISHU_REDIRECT_URI,
+ redirect_uri=config.get('oauth.feishu.redirect_uri'),
)
return client
@@ -2862,16 +2867,16 @@ def load_oauth_providers():
}
configured_providers = []
- if GOOGLE_CLIENT_ID:
+ if google_client_id:
configured_providers.append('Google')
- if MICROSOFT_CLIENT_ID:
+ if microsoft_client_id:
configured_providers.append('Microsoft')
- if GITHUB_CLIENT_ID:
+ if github_client_id:
configured_providers.append('GitHub')
- if FEISHU_CLIENT_ID:
+ if feishu_client_id:
configured_providers.append('Feishu')
- if configured_providers and not OPENID_PROVIDER_URL and not OPENID_END_SESSION_ENDPOINT:
+ if configured_providers and not openid_provider_url and not config.get('oauth.end_session_endpoint'):
provider_list = ', '.join(configured_providers)
log.warning(
f'⚠️ OAuth providers configured ({provider_list}) but OPENID_PROVIDER_URL not set - logout will not work!'
@@ -2882,11 +2887,7 @@ def load_oauth_providers():
)
-load_oauth_providers()
-
-####################################
# LDAP
-####################################
ENABLE_LDAP = os.getenv('ENABLE_LDAP', 'false').lower() == 'true'
@@ -3013,6 +3014,9 @@ DEFAULT_CONFIG = {
'rag.enable_hybrid_search_enriched_texts': ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS,
'rag.full_context': RAG_FULL_CONTEXT,
'rag.file.max_count': RAG_FILE_MAX_COUNT,
+ 'knowledge.max_upload_count': KNOWLEDGE_MAX_UPLOAD_COUNT,
+ 'knowledge.max_file_count': KNOWLEDGE_MAX_FILE_COUNT,
+ 'knowledge.max_file_size': KNOWLEDGE_MAX_FILE_SIZE,
'rag.file.max_size': RAG_FILE_MAX_SIZE,
'file.image_compression_width': FILE_IMAGE_COMPRESSION_WIDTH,
'file.image_compression_height': FILE_IMAGE_COMPRESSION_HEIGHT,
@@ -3242,6 +3246,8 @@ DEFAULT_CONFIG = {
'automations.min_interval': AUTOMATION_MIN_INTERVAL,
'automations.auth_token_expires_in': AUTOMATION_AUTH_TOKEN_EXPIRES_IN,
'notes.enable': ENABLE_NOTES,
+ 'comments.enable': ENABLE_COMMENTS,
+ 'notifications.enable': ENABLE_NOTIFICATIONS,
'users.enable_status': ENABLE_USER_STATUS,
'evaluation.arena.enable': ENABLE_EVALUATION_ARENA_MODELS,
'evaluation.arena.models': EVALUATION_ARENA_MODELS,
diff --git a/backend/open_webui/env.py b/backend/open_webui/env.py
index 0e2797c3af..b672fe0483 100644
--- a/backend/open_webui/env.py
+++ b/backend/open_webui/env.py
@@ -18,9 +18,7 @@ import markdown
from bs4 import BeautifulSoup
from cryptography.hazmat.primitives import serialization
-####################################
# Load .env file
-####################################
# Use .resolve() to get the canonical path, removing any '..' or '.' components
ENV_FILE_PATH = Path(__file__).resolve()
@@ -72,9 +70,7 @@ if not USE_SLIM and sys.platform == 'darwin' and DEVICE_TYPE == 'cpu':
# Torch MPS inference is not thread-safe and a concurrent call kills the whole process.
MPS_INFERENCE_LOCK = threading.Lock() if DEVICE_TYPE == 'mps' else nullcontext()
-####################################
-# LOGGING
-####################################
+# Logging
_LEVEL_MAP = {
'DEBUG': 'debug',
@@ -132,9 +128,7 @@ if _cuda_error:
SRC_LOG_LEVELS = {} # Legacy variable, do not remove
-####################################
# ENV (dev,test,prod)
-####################################
ENV = os.getenv('ENV', 'dev')
@@ -221,9 +215,7 @@ for version in soup.find_all('h2'):
CHANGELOG = changelog_json
-####################################
-# DATA/FRONTEND BUILD DIR
-####################################
+# Data/frontend build dir
DATA_DIR = Path(os.getenv('DATA_DIR', BACKEND_DIR / 'data')).resolve()
@@ -256,9 +248,7 @@ FRONTEND_BUILD_DIR = Path(os.getenv('FRONTEND_BUILD_DIR', BASE_DIR / 'build')).r
if FROM_INIT_PY:
FRONTEND_BUILD_DIR = Path(os.getenv('FRONTEND_BUILD_DIR', OPEN_WEBUI_DIR / 'frontend')).resolve()
-####################################
# Database
-####################################
# Check if the file exists
if os.path.exists(f'{DATA_DIR}/ollama.db'):
@@ -374,9 +364,7 @@ RAG_SYSTEM_CONTEXT = os.getenv('RAG_SYSTEM_CONTEXT', 'False').lower() == 'true'
# Empty by default: chunk metadata also holds internal bookkeeping (file hashes, collection names, scores).
RAG_SOURCE_METADATA_KEYS = [key.strip() for key in os.getenv('RAG_SOURCE_METADATA_KEYS', '').split(',') if key.strip()]
-####################################
-# REDIS
-####################################
+# Redis
REDIS_URL = os.getenv('REDIS_URL', '')
REDIS_CLUSTER = os.getenv('REDIS_CLUSTER', 'False').lower() == 'true'
@@ -454,9 +442,7 @@ else:
except Exception:
REDIS_RECONNECT_DELAY = None
-####################################
# Uvicorn
-####################################
try:
UVICORN_WORKERS = max(int(os.getenv('UVICORN_WORKERS', '1')), 1)
@@ -466,9 +452,7 @@ except (ValueError, TypeError):
# tiny delta-stream frames make per-frame websocket compression CPU-bound, allow opting out (true/false)
UVICORN_WS_PER_MESSAGE_DEFLATE = os.getenv('UVICORN_WS_PER_MESSAGE_DEFLATE', 'True').lower() == 'true'
-####################################
-# WEBSOCKET SUPPORT
-####################################
+# Websocket support
ENABLE_WEBSOCKET_SUPPORT = os.getenv('ENABLE_WEBSOCKET_SUPPORT', 'True').lower() == 'true'
@@ -728,9 +712,7 @@ except (ValueError, TypeError):
MCP_INITIALIZE_TIMEOUT = 10
-####################################
# AIOHTTP Connection Pool
-####################################
AIOHTTP_POOL_CONNECTIONS = os.getenv('AIOHTTP_POOL_CONNECTIONS', '')
if AIOHTTP_POOL_CONNECTIONS == '':
@@ -778,18 +760,14 @@ else:
RAG_EMBEDDING_TIMEOUT = None
-####################################
# Auth
-####################################
WEBUI_AUTH = os.getenv('WEBUI_AUTH', 'True').lower() == 'true'
ENABLE_INITIAL_ADMIN_SIGNUP = os.getenv('ENABLE_INITIAL_ADMIN_SIGNUP', 'False').lower() == 'true'
ENABLE_SIGNUP_PASSWORD_CONFIRMATION = os.getenv('ENABLE_SIGNUP_PASSWORD_CONFIRMATION', 'False').lower() == 'true'
-####################################
# Secret key & cookies
-####################################
# WEBUI_JWT_SECRET_KEY is deprecated; use WEBUI_SECRET_KEY instead.
# No hardcoded fallback by design: the supported start scripts set/auto-generate it; unset is rejected below.
@@ -823,9 +801,7 @@ if WEBUI_AUTH and WEBUI_SECRET_KEY == '':
ENABLE_COMPRESSION_MIDDLEWARE = os.getenv('ENABLE_COMPRESSION_MIDDLEWARE', 'True').lower() == 'true'
-####################################
# Admin Account Runtime Creation
-####################################
# Optional env vars for creating an admin account on startup
# Useful for headless/automated deployments
@@ -907,9 +883,7 @@ ENABLE_OPENAI_API_PASSTHROUGH = os.getenv('ENABLE_OPENAI_API_PASSTHROUGH', 'Fals
WEBUI_AUTH_SIGNOUT_REDIRECT_URL = os.getenv('WEBUI_AUTH_SIGNOUT_REDIRECT_URL', None)
-####################################
# OAUTH Configuration
-####################################
ENABLE_OAUTH_EMAIL_FALLBACK = os.getenv('ENABLE_OAUTH_EMAIL_FALLBACK', 'False').lower() == 'true'
ENABLE_OAUTH_ID_TOKEN_COOKIE = os.getenv('ENABLE_OAUTH_ID_TOKEN_COOKIE', 'True').lower() == 'true'
@@ -944,9 +918,7 @@ OAUTH_TOKEN_EXCHANGE_TRUSTED_CLIENT_IDS = [
# Requires Redis for JWT revocation.
ENABLE_OAUTH_BACKCHANNEL_LOGOUT = os.getenv('ENABLE_OAUTH_BACKCHANNEL_LOGOUT', 'False').lower() == 'true'
-####################################
# SCIM Configuration
-####################################
ENABLE_SCIM = os.getenv('ENABLE_SCIM', os.getenv('SCIM_ENABLED', 'False')).lower() == 'true'
SCIM_TOKEN = os.getenv('SCIM_TOKEN', '')
@@ -959,9 +931,7 @@ if ENABLE_SCIM and not SCIM_AUTH_PROVIDER:
'to enable externalId storage.'
)
-####################################
# LICENSE_KEY
-####################################
LICENSE_KEY = os.getenv('LICENSE_KEY', '')
@@ -984,9 +954,7 @@ if LICENSE_PUBLIC_KEY:
)
-####################################
# WEBUI Identity
-####################################
# LICENSE covers this Open WebUI branding surface, including name, logo,
# visual, textual, symbolic identifiers, metadata, and surrounding UI.
@@ -1004,9 +972,7 @@ WEBUI_FAVICON_URL = 'https://openwebui.com/favicon.png'
WEBUI_BUILD_HASH = os.getenv('WEBUI_BUILD_HASH', 'dev-build')
TRUSTED_SIGNATURE_KEY = os.getenv('TRUSTED_SIGNATURE_KEY', '')
-####################################
# Feature flags
-####################################
SAFE_MODE = os.getenv('SAFE_MODE', 'False').lower() == 'true'
ENABLE_EASTER_EGGS = os.getenv('ENABLE_EASTER_EGGS', 'True').lower() == 'true'
@@ -1028,9 +994,7 @@ PROFILE_IMAGE_ALLOWED_MIME_TYPES = frozenset(
_profile_image_max_data_uri_size = os.getenv('PROFILE_IMAGE_MAX_DATA_URI_SIZE', '').strip()
PROFILE_IMAGE_MAX_DATA_URI_SIZE = int(_profile_image_max_data_uri_size) if _profile_image_max_data_uri_size else None
-####################################
# Forward Headers
-####################################
ENABLE_FORWARD_USER_INFO_HEADERS = os.getenv('ENABLE_FORWARD_USER_INFO_HEADERS', 'False').lower() == 'true'
@@ -1053,9 +1017,7 @@ try:
except ValueError:
FORWARD_USER_INFO_HEADER_JWT_EXPIRES_SECONDS = 300
-####################################
# Progressive Web App
-####################################
# LICENSE covers this install-time Open WebUI branding surface, including
# names, logos, manifests, metadata, and surrounding UI.
@@ -1063,18 +1025,14 @@ except ValueError:
# https://docs.openwebui.com/license.
EXTERNAL_PWA_MANIFEST_URL = os.getenv('EXTERNAL_PWA_MANIFEST_URL', None)
-####################################
-# GROUP DEFAULTS
-####################################
+# Group defaults
# Controls the default "Who can share to this group" setting for new groups.
# Env var values: "true" (anyone), "false" (no one), "members" (only group members).
_default_group_share = os.getenv('DEFAULT_GROUP_SHARE_PERMISSION', 'members').strip().lower()
DEFAULT_GROUP_SHARE_PERMISSION = 'members' if _default_group_share == 'members' else _default_group_share == 'true'
-####################################
-# MODELS
-####################################
+# Models
ENABLE_CUSTOM_MODEL_FALLBACK = os.getenv('ENABLE_CUSTOM_MODEL_FALLBACK', 'False').lower() == 'true'
@@ -1088,9 +1046,7 @@ else:
MODELS_CACHE_TTL = 1
-####################################
-# CHAT
-####################################
+# Chat
ENABLE_CHAT_RESPONSE_BASE64_IMAGE_URL_CONVERSION = (
os.getenv('ENABLE_CHAT_RESPONSE_BASE64_IMAGE_URL_CONVERSION', 'False').lower() == 'true'
@@ -1128,16 +1084,16 @@ else:
# The old CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES name is accepted as a fallback.
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = os.getenv(
'CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS',
- os.getenv('CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES', '256'),
+ os.getenv('CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES', '1024'),
)
if CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS == '':
- CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 256
+ CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 1024
else:
try:
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = int(CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS)
except Exception:
- CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 256
+ CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 1024
# -1 means unlimited (no cap).
if CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS == -1:
@@ -1162,9 +1118,7 @@ else:
CHAT_STREAM_RESPONSE_CHUNK_MAX_BUFFER_SIZE = None
-####################################
-# SENTENCE TRANSFORMERS
-####################################
+# Sentence transformers
SENTENCE_TRANSFORMERS_BACKEND = os.getenv('SENTENCE_TRANSFORMERS_BACKEND', '')
@@ -1203,9 +1157,7 @@ SENTENCE_TRANSFORMERS_CROSS_ENCODER_SIGMOID_ACTIVATION_FUNCTION = (
os.getenv('SENTENCE_TRANSFORMERS_CROSS_ENCODER_SIGMOID_ACTIVATION_FUNCTION', 'True').lower() == 'true'
)
-####################################
-# KNOWLEDGE TOOLS
-####################################
+# Knowledge tools
def _int_env(name: str, default: int) -> int:
@@ -1225,9 +1177,7 @@ KNOWLEDGE_GREP_MAX_MATCHES = _int_env('KNOWLEDGE_GREP_MAX_MATCHES', 50)
VIEW_FILE_MAX_CHARS = _int_env('VIEW_FILE_MAX_CHARS', 100_000)
VIEW_FILE_DEFAULT_MAX_CHARS = _int_env('VIEW_FILE_DEFAULT_MAX_CHARS', 10_000)
-####################################
-# TOOLS/FUNCTIONS PIP OPTIONS
-####################################
+# Tools/functions pip options
ENABLE_PLUGINS = os.getenv('ENABLE_PLUGINS', 'True').lower() == 'true'
# Deployment controls: the master switch always overrides all feature switches.
@@ -1243,9 +1193,7 @@ PIP_OPTIONS = os.getenv('PIP_OPTIONS', '').split()
PIP_PACKAGE_INDEX_OPTIONS = os.getenv('PIP_PACKAGE_INDEX_OPTIONS', '').split()
-####################################
# OFFLINE_MODE
-####################################
ENABLE_VERSION_UPDATE_CHECK = os.getenv('ENABLE_VERSION_UPDATE_CHECK', 'true').lower() == 'true'
OFFLINE_MODE = os.getenv('OFFLINE_MODE', 'false').lower() == 'true'
@@ -1254,15 +1202,11 @@ if OFFLINE_MODE:
os.environ['HF_HUB_OFFLINE'] = '1'
ENABLE_VERSION_UPDATE_CHECK = False
-####################################
# Pyodide file persistence
-####################################
ENABLE_PYODIDE_FILE_PERSISTENCE = os.getenv('ENABLE_PYODIDE_FILE_PERSISTENCE', 'false').lower() == 'true'
-####################################
# Audit logging
-####################################
ENABLE_AUDIT_STDOUT = os.getenv('ENABLE_AUDIT_STDOUT', 'False').lower() == 'true'
@@ -1306,9 +1250,7 @@ AUDIT_INCLUDED_PATHS = [
ENABLE_AUDIT_GET_REQUESTS = os.getenv('ENABLE_AUDIT_GET_REQUESTS', 'False').lower() == 'true'
-####################################
-# OPENTELEMETRY
-####################################
+# OpenTelemetry
ENABLE_OTEL = os.getenv('ENABLE_OTEL', 'False').lower() == 'true'
ENABLE_OTEL_TRACES = os.getenv('ENABLE_OTEL_TRACES', 'False').lower() == 'true'
diff --git a/backend/open_webui/events.py b/backend/open_webui/events.py
index b5373f386b..071f23dec2 100644
--- a/backend/open_webui/events.py
+++ b/backend/open_webui/events.py
@@ -5,9 +5,9 @@ import inspect
import logging
import time
import uuid
-from types import SimpleNamespace
from typing import Any
+from fastapi import Request
from pydantic import BaseModel, ConfigDict, Field, model_validator
from open_webui.env import ENABLE_FUNCTIONS, VERSION
@@ -43,6 +43,13 @@ class EventDefinition(BaseModel):
class EventDefinitions(BaseModel):
model_config = ConfigDict(frozen=True)
+ COMMENT_CREATED: EventDefinition = EventDefinition(
+ name='comment.created', description='A resource comment or reply was created.', message='Comment created'
+ )
+ COMMENT_UPDATED: EventDefinition = EventDefinition(
+ name='comment.updated', description='A resource comment was edited.', message='Comment updated'
+ )
+
SYSTEM_STARTUP_STARTED: EventDefinition = EventDefinition(
name='system.startup.started', description='Application startup began.', message='Startup started'
)
@@ -540,6 +547,12 @@ class EventDefinitions(BaseModel):
TOOL_UPDATED: EventDefinition = EventDefinition(
name='tool.updated', description='A tool was updated.', message='Tool updated'
)
+ TOOL_ENABLED: EventDefinition = EventDefinition(
+ name='tool.enabled', description='A tool was enabled.', message='Tool enabled'
+ )
+ TOOL_DISABLED: EventDefinition = EventDefinition(
+ name='tool.disabled', description='A tool was disabled.', message='Tool disabled'
+ )
TOOL_DELETED: EventDefinition = EventDefinition(
name='tool.deleted', description='A tool was deleted.', message='Tool deleted'
)
@@ -704,7 +717,6 @@ NOTIFICATION_EVENTS = (
EVENTS.CHAT_FAILED.name,
EVENTS.CHANNEL_MESSAGE.name,
EVENTS.CALENDAR_ALERT.name,
- EVENTS.RETRIEVAL_CONTENT_PROCESS_FAILED.name,
EVENTS.AUTOMATION_RUN_FAILED.name,
)
@@ -1027,7 +1039,7 @@ def event_name(event: EventDefinition | str) -> str:
def build_event(
- request_or_app: Any,
+ request: Request | None,
event: EventDefinition | str,
*,
actor: Any | None = None,
@@ -1036,9 +1048,10 @@ def build_event(
source: str = 'api',
data: dict | None = None,
message: str | None = None,
+ event_id: str | None = None,
) -> Event:
event_name_value = event_name(event)
- app = getattr(request_or_app, 'app', request_or_app)
+ app = request.app if request is not None else None
parts = event_name_value.split('.')
resource = '.'.join(parts[:-1])
instance_id = getattr(getattr(app, 'state', None), 'instance_id', None)
@@ -1050,7 +1063,7 @@ def build_event(
return Event(
schema=VERSION,
- id=str(uuid.uuid4()),
+ id=event_id or str(uuid.uuid4()),
event=event_name_value,
resource=resource,
operation=parts[-1],
@@ -1101,8 +1114,8 @@ def schedule_webhook_dispatch(app: Any, event: Event) -> None:
class WebhookEventSink:
- async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
- schedule_webhook_dispatch(app, event)
+ async def handle_event(self, request: Request, event: Event) -> None:
+ schedule_webhook_dispatch(request.app, event)
def schedule_notification_dispatch(app: Any, event: Event) -> None:
@@ -1115,13 +1128,13 @@ def schedule_notification_dispatch(app: Any, event: Event) -> None:
class NotificationEventSink:
- async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
+ async def handle_event(self, request: Request, event: Event) -> None:
if event.event in NOTIFICATION_EVENTS:
- schedule_notification_dispatch(app, event)
+ schedule_notification_dispatch(request.app, event)
class SocketSessionEventSink:
- async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
+ async def handle_event(self, request: Request, event: Event) -> None:
from open_webui.socket.main import refresh_chat_access
if event.event in {
@@ -1156,7 +1169,7 @@ class SocketSessionEventSink:
async def dispatch_event_functions(
- app: Any, event: Event, request: Any | None = None, extra_function_ids: list[str] | None = None
+ request: Request, event: Event, extra_function_ids: list[str] | None = None
) -> None:
if not ENABLE_FUNCTIONS:
return
@@ -1164,7 +1177,6 @@ async def dispatch_event_functions(
from open_webui.models.functions import Functions
from open_webui.utils.plugin import get_function_module_from_cache
- context = request or SimpleNamespace(app=app)
event_payload = event.model_dump()
try:
@@ -1181,7 +1193,7 @@ async def dispatch_event_functions(
for function in event_functions:
try:
- function_module, _, _ = await get_function_module_from_cache(context, function.id, function=function)
+ function_module, _, _ = await get_function_module_from_cache(request, function.id, function=function)
handler = getattr(function_module, 'event', None)
if not handler:
continue
@@ -1198,7 +1210,7 @@ async def dispatch_event_functions(
'__event__': event,
'__event_id__': event.id,
'__event_name__': event.event,
- '__app__': app,
+ '__app__': request.app,
'__request__': request,
}
params = {key: value for key, value in extra_params.items() if accepts_kwargs or key in sig.parameters}
@@ -1211,24 +1223,32 @@ async def dispatch_event_functions(
log.exception('Event function failed for %s', function.id)
-def schedule_event_function_dispatch(app: Any, event: Event, request: Any | None = None) -> None:
+def schedule_event_function_dispatch(request: Request, event: Event) -> None:
try:
- asyncio.create_task(dispatch_event_functions(app, event, request))
+ asyncio.create_task(dispatch_event_functions(request, event))
except RuntimeError:
log.exception('Event functions could not be scheduled for %s', event.event)
class EventFunctionSink:
- async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
- schedule_event_function_dispatch(app, event, request)
+ async def handle_event(self, request: Request, event: Event) -> None:
+ schedule_event_function_dispatch(request, event)
EVENT_SINKS = [SocketSessionEventSink(), EventFunctionSink(), WebhookEventSink(), NotificationEventSink()]
+async def _dispatch_event(request, event_payload):
+ for sink in EVENT_SINKS:
+ try:
+ await sink.handle_event(request, event_payload)
+ except Exception:
+ log.exception('Event sink failed for %s', event_payload.event)
+
+
async def publish_event(
- request_or_app: Any,
- event: EventDefinition | str,
+ request: Request,
+ event: EventDefinition | str | Event,
*,
actor: Any | None = None,
subject_id: Any | None = None,
@@ -1237,28 +1257,26 @@ async def publish_event(
data: dict | None = None,
message: str | None = None,
) -> None:
- app = getattr(request_or_app, 'app', request_or_app)
- request = request_or_app if hasattr(request_or_app, 'app') else None
- event_payload = build_event(
- request_or_app,
- event,
- actor=actor,
- subject_id=subject_id,
- subject_type=subject_type,
- source=source,
- data=data,
- message=message,
+ """Deliver an event through the existing sinks. Call after committing source changes."""
+ event_payload = (
+ event
+ if isinstance(event, Event)
+ else build_event(
+ request,
+ event,
+ actor=actor,
+ subject_id=subject_id,
+ subject_type=subject_type,
+ source=source,
+ data=data,
+ message=message,
+ )
)
-
- for sink in EVENT_SINKS:
- try:
- await sink.handle_event(app, event_payload, request=request)
- except Exception:
- log.exception('Event sink failed for %s', event_payload.event)
+ await _dispatch_event(request, event_payload)
async def publish_model_provider_request_failed(
- request_or_app: Any,
+ request: Request,
*,
actor: Any | None,
provider: str,
@@ -1319,7 +1337,7 @@ async def publish_model_provider_request_failed(
data['upstream_message'] = error
await publish_event(
- request_or_app,
+ request,
EVENTS.MODEL_PROVIDER_REQUEST_FAILED,
actor=actor,
subject_id=requested_model,
diff --git a/backend/open_webui/functions.py b/backend/open_webui/functions.py
index 20601fee7e..c08d5b69d1 100644
--- a/backend/open_webui/functions.py
+++ b/backend/open_webui/functions.py
@@ -31,9 +31,9 @@ from open_webui.utils.access_control import check_model_access
from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.misc import (
add_or_update_system_message,
+ chat_completion_chunk_template,
+ chat_completion_message_template,
get_last_user_message,
- openai_chat_chunk_message_template,
- openai_chat_completion_message_template,
prepend_to_first_user_message_content,
)
from open_webui.utils.oauth import get_system_oauth_token
@@ -184,7 +184,7 @@ async def generate_function_chat_completion(request, form_data, user, models: di
if line.startswith('data:'):
return f'{line}\n\n'
else:
- line = openai_chat_chunk_message_template(form_data['model'], line)
+ line = chat_completion_chunk_template(form_data['model'], line)
return f'data: {JSONCodec.dumps(line)}\n\n'
def get_pipe_id(form_data: dict) -> str:
@@ -304,7 +304,7 @@ async def generate_function_chat_completion(request, form_data, user, models: di
return
if isinstance(res, str):
- message = openai_chat_chunk_message_template(form_data['model'], res)
+ message = chat_completion_chunk_template(form_data['model'], res)
yield f'data: {JSONCodec.dumps(message)}\n\n'
if isinstance(res, Iterator):
@@ -315,7 +315,7 @@ async def generate_function_chat_completion(request, form_data, user, models: di
async for line in res:
yield process_line(form_data, line)
- finish_message = openai_chat_chunk_message_template(form_data['model'], '')
+ finish_message = chat_completion_chunk_template(form_data['model'], '')
finish_message['choices'][0]['finish_reason'] = 'stop'
yield f'data: {JSONCodec.dumps(finish_message)}\n\n'
yield 'data: [DONE]'
@@ -335,4 +335,4 @@ async def generate_function_chat_completion(request, form_data, user, models: di
return res.model_dump()
message = await get_message_content(res)
- return openai_chat_completion_message_template(form_data['model'], message)
+ return chat_completion_message_template(form_data['model'], message)
diff --git a/backend/open_webui/internal/db.py b/backend/open_webui/internal/db.py
index 7433f1cd5f..25768d057d 100644
--- a/backend/open_webui/internal/db.py
+++ b/backend/open_webui/internal/db.py
@@ -43,17 +43,7 @@ from typing_extensions import Self
log = logging.getLogger(__name__)
-# ── SSL URL normalization (used by sync engine & Alembic migrations) ─
-#
-# psycopg2 (sync) needs ``sslmode=`` in the connection string (it does
-# not recognise the bare ``ssl=`` key that some ORMs emit). The helpers
-# below strip all SSL-related query params, normalise them, and
-# reattach them in the canonical libpq form.
-#
-# The **async** engine now uses psycopg (v3), which speaks libpq
-# natively, so it needs no translation at all — the DATABASE_URL is
-# passed through as-is.
-# ─────────────────────────────────────────────────────────────────────
+# Normalize SSL query parameters for sync psycopg2 and Alembic; async psycopg uses the URL unchanged.
def _pop_first(params: dict[str, list[str]], key: str) -> str | None:
@@ -281,10 +271,8 @@ def _create_async_engine(*args, **kwargs):
return create_async_engine(*args, **_json_codec_kwargs(kwargs))
-# ============================================================
-# SYNC ENGINE (used only for: startup migrations, config loading,
+# Sync engine (used only for: startup migrations, config loading,
# Alembic, peewee migration, health checks)
-# ============================================================
# Handle SQLCipher URLs
if SQLALCHEMY_DATABASE_URL.startswith('sqlite+sqlcipher://'):
@@ -443,9 +431,7 @@ def get_session():
get_db = contextmanager(get_session)
-# ============================================================
-# ASYNC ENGINE (used for ALL runtime database operations)
-# ============================================================
+# Async engine (used for all runtime database operations)
# psycopg (v3) speaks libpq natively — the full DATABASE_URL is passed
# through as-is. SSL params, ``options``, ``target_session_attrs``, etc.
diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py
index a1abf80e79..25ff758870 100644
--- a/backend/open_webui/main.py
+++ b/backend/open_webui/main.py
@@ -22,7 +22,6 @@ from fastapi import (
applications,
status,
)
-from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
@@ -158,6 +157,7 @@ from open_webui.routers import (
calendar,
channels,
chats,
+ comments,
configs,
evaluations,
files,
@@ -208,6 +208,7 @@ from open_webui.socket.main import (
from open_webui.tasks import (
cleanup_task,
create_task,
+ get_response_streams_by_chat_id,
has_active_tasks,
list_task_ids_by_item_id,
list_tasks,
@@ -220,7 +221,7 @@ from open_webui.utils import logger
from open_webui.utils.access_control import has_permission
from open_webui.utils.access_control.folders import has_folder_write_access
from open_webui.utils.actions import chat_action as chat_action_handler
-from open_webui.utils.asgi_middleware import AppHTTPMiddleware
+from open_webui.utils.asgi_middleware import AppHTTPMiddleware, BrowserCORSMiddleware
from open_webui.utils.audit import AuditLevel, AuditLoggingMiddleware
from open_webui.utils.auth import (
create_admin_user,
@@ -232,7 +233,9 @@ from open_webui.utils.auth import (
is_valid_token,
)
from open_webui.utils.chat import (
+ register_temporary_chat_session,
chat_completed as chat_completed_handler,
+ get_temporary_chat,
)
from open_webui.utils.chat import (
generate_chat_completion as chat_completion_handler,
@@ -386,12 +389,24 @@ async def lifespan(app: FastAPI):
await import_legacy_config_json()
await seed_registered_defaults()
+ await app.state.oauth_manager.initialize()
from open_webui.utils.mfa import validate_mfa_configuration
await validate_mfa_configuration()
await initialize_runtime_config(app)
await migrate_legacy_webhook_config()
- await publish_event(app, EVENTS.SYSTEM_STARTUP_STARTED, source='system')
+ request = Request(
+ {
+ 'type': 'http',
+ 'method': 'GET',
+ 'path': '/internal',
+ 'query_string': b'',
+ 'headers': [],
+ 'scheme': 'http',
+ 'app': app,
+ }
+ )
+ await publish_event(request, EVENTS.SYSTEM_STARTUP_STARTED, source='system')
license_task = None
if LICENSE_KEY:
@@ -502,11 +517,11 @@ async def lifespan(app: FastAPI):
log.warning(f'License data retrieval failed during startup: {e}')
app.state.startup_complete = True
- await publish_event(app, EVENTS.SYSTEM_STARTUP_COMPLETED, source='system')
+ await publish_event(request, EVENTS.SYSTEM_STARTUP_COMPLETED, source='system')
yield
- await publish_event(app, EVENTS.SYSTEM_SHUTDOWN_STARTED, source='system')
+ await publish_event(request, EVENTS.SYSTEM_SHUTDOWN_STARTED, source='system')
await app_connections.close()
# Shutdown: clean up shared resources
@@ -528,7 +543,7 @@ async def lifespan(app: FastAPI):
app.state.periodic_session_pool_cleanup.cancel()
app.state.scheduler_worker_loop.cancel()
- await publish_event(app, EVENTS.SYSTEM_SHUTDOWN_COMPLETED, source='system')
+ await publish_event(request, EVENTS.SYSTEM_SHUTDOWN_COMPLETED, source='system')
# ENABLE_ORJSON: orjson for request-body parsing and JSONResponse bodies;
@@ -576,11 +591,7 @@ app.state.USER_COUNT = None
app.state.EXTERNAL_PWA_MANIFEST_URL = EXTERNAL_PWA_MANIFEST_URL
-########################################
-#
-# OPENTELEMETRY
-#
-########################################
+# OpenTelemetry
if ENABLE_OTEL:
from open_webui.utils.telemetry.setup import setup as setup_opentelemetry
@@ -588,69 +599,34 @@ if ENABLE_OTEL:
setup_opentelemetry(app=app, db_engine=engine)
-########################################
-#
-# OLLAMA
-#
-########################################
+# Ollama
app.state.OLLAMA_MODELS = {}
-########################################
-#
-# OPENAI
-#
-########################################
+# OpenAI
app.state.OPENAI_MODELS = {}
-########################################
-#
-# TOOL SERVERS
-#
-########################################
+# Tool servers
app.state.TOOL_SERVERS = []
-########################################
-#
-# TERMINAL SERVER
-#
-########################################
+# Terminal server
app.state.TERMINAL_SERVERS = []
-########################################
-#
-# DIRECT CONNECTIONS
-#
-########################################
-
-
-########################################
-#
# SCIM
-#
-########################################
app.state.ENABLE_SCIM = ENABLE_SCIM
app.state.SCIM_TOKEN = SCIM_TOKEN
-########################################
-#
-# MODELS
-#
-########################################
+# Models
app.state.BASE_MODELS = []
-########################################
-#
-# WEBUI
-#
-########################################
+# WebUI
async def initialize_runtime_config(app: FastAPI):
@@ -785,25 +761,7 @@ async def initialize_runtime_config(app: FastAPI):
)
-########################################
-#
-# CODE EXECUTION
-#
-########################################
-
-
-########################################
-#
-# IMAGES
-#
-########################################
-
-
-########################################
-#
-# AUDIO
-#
-########################################
+# Audio
app.state.faster_whisper_model = None
@@ -811,18 +769,7 @@ app.state.speech_synthesiser = None
app.state.speech_speaker_embeddings_dataset = None
-########################################
-#
-# TASKS
-#
-########################################
-
-
-########################################
-#
-# WEBUI
-#
-########################################
+# WebUI
app.state.MODELS = MODELS
@@ -850,19 +797,13 @@ if ENABLE_COMPRESSION_MIDDLEWARE:
app.add_middleware(CompressMiddleware)
-# All HTTP middlewares below are pure-ASGI implementations. The previous
-# `BaseHTTPMiddleware` / `@app.middleware('http')` versions wrapped the
-# downstream app in an anyio task group whose cancel scope cancelled
-# in-flight DB calls (and any other awaits) on client disconnect /
-# response completion — which surfaced as noisy SQLAlchemy
-# `terminate_force_close` tracebacks under aiosqlite and as random
-# CancelledError storms across the request path. See
-# `open_webui.utils.asgi_middleware` for the rationale.
+# Use pure ASGI middleware to avoid BaseHTTPMiddleware cancellation of in-flight DB work.
+# See open_webui.utils.asgi_middleware for the disconnect and cleanup rationale.
app.add_middleware(AppHTTPMiddleware)
app.add_middleware(
- CORSMiddleware,
+ BrowserCORSMiddleware,
allow_origins=CORS_ALLOW_ORIGIN,
allow_credentials=True,
allow_methods=['*'],
@@ -894,6 +835,7 @@ app.include_router(users.router, prefix='/api/v1/users', tags=['users'])
app.include_router(apps.router, prefix='/api/v1/apps', tags=['apps'])
app.include_router(channels.router, prefix='/api/v1/channels', tags=['channels'])
app.include_router(chats.router, prefix='/api/v1/chats', tags=['chats'])
+app.include_router(comments.router, prefix='/api/v1/comments', tags=['comments'])
app.include_router(notes.router, prefix='/api/v1/notes', tags=['notes'])
app.include_router(search.router, prefix='/api/v1/search', tags=['search'])
@@ -923,11 +865,7 @@ if ENABLE_SCIM:
app.include_router(scim.router, prefix='/api/v1/scim/v2', tags=['scim'])
-##################################
-#
# Chat Endpoints
-#
-##################################
@app.get('/api/models')
@@ -935,7 +873,7 @@ if ENABLE_SCIM:
async def get_models(request: Request, refresh: bool = False, user=Depends(get_verified_user)):
all_models = await get_all_models(request, refresh=refresh, user=user)
- # Filter out filter pipelines
+ # Keep filter pipelines off the model menu; they work backstage.
models = [
model for model in all_models if not ('pipeline' in model and model['pipeline'].get('type', None) == 'filter')
]
@@ -952,7 +890,7 @@ async def get_models(request: Request, refresh: bool = False, user=Depends(get_v
info = model.get('info') if isinstance(model.get('info'), dict) else {}
meta = info.get('meta') if isinstance(info.get('meta'), dict) else {}
- # Remove profile image URL to reduce payload size
+ # Leave profile images out; this model list is traveling light.
meta.pop('profile_image_url', None)
if 'tags' in meta:
@@ -964,7 +902,7 @@ async def get_models(request: Request, refresh: bool = False, user=Depends(get_v
model_order_list = await Config.get('ui.model_order_list')
if model_order_list:
model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
- # Sort models by order list priority, with fallback for those not in the list
+ # Configured models get the front seats; the rest line up by name.
models.sort(
key=lambda model: (
model_order_dict.get(model.get('id', ''), float('inf')),
@@ -1009,7 +947,7 @@ async def unload_model(request: Request, form_data: ModelUnloadForm, user=Depend
break
model_id = model_info.base_model_id
- # --- Ollama provider ---
+ # Ollama provider
if model_id in ollama_models:
ollama_config = await Config.get_many('ollama.base_urls', 'ollama.api_configs')
ollama_base_urls = ollama_config.get('ollama.base_urls') or []
@@ -1055,7 +993,7 @@ async def unload_model(request: Request, form_data: ModelUnloadForm, user=Depend
)
return {'status': True}
- # --- OpenAI-compatible providers ---
+ # OpenAI-compatible providers
if model_id in openai_models:
openai_config = await Config.get_many('openai.api_configs', 'openai.api_base_urls', 'openai.api_keys')
openai_api_configs = openai_config.get('openai.api_configs') or {}
@@ -1102,9 +1040,7 @@ async def unload_model(request: Request, form_data: ModelUnloadForm, user=Depend
raise HTTPException(status_code=404, detail=f'Model "{model_id}" not found')
-##################################
# Embeddings
-##################################
@app.post('/api/embeddings')
@@ -1364,6 +1300,18 @@ async def chat_completion(
if is_new_chat:
metadata['chat_id'] = str(uuid4())
+ if is_temporary_chat_id(metadata.get('chat_id')):
+ session_id = metadata.get('session_id')
+ if not isinstance(session_id, str) or not await register_temporary_chat_session(
+ request.app.state.redis,
+ metadata['chat_id'],
+ user.id,
+ session_id,
+ get_user_id_from_session_pool(session_id),
+ create=True,
+ ):
+ raise HTTPException(status_code=404, detail='Temporary chat expired or unavailable')
+
initial_title_generation = None
if is_new_chat and tasks and TASKS.TITLE_GENERATION in tasks:
initial_title_generation = tasks.pop(TASKS.TITLE_GENERATION)
@@ -1963,18 +1911,14 @@ async def resolve_chat_message_tool_call(
app.state.CHAT_COMPLETION_HANDLER = chat_completion
-##################################
-#
# Anthropic Messages API Compatible Endpoint
-#
-##################################
from open_webui.utils.anthropic import (
- convert_anthropic_to_openai_payload,
- convert_openai_to_anthropic_response,
+ convert_anthropic_payload_to_chat_completions,
+ convert_chat_completions_response_to_anthropic,
+ convert_chat_completions_stream_to_anthropic,
is_anthropic_messages_passthrough,
- openai_stream_to_anthropic_stream,
)
@@ -2096,17 +2040,19 @@ async def generate_messages(
return await passthrough_anthropic_messages(request, form_data, user)
passthrough_params = api_config.get('passthrough_params') or []
- # Convert Anthropic payload to OpenAI format
- openai_payload = convert_anthropic_to_openai_payload(form_data, passthrough_params)
+ # Translate Anthropic into OpenAI before sending it through the house plumbing.
+ openai_payload = convert_anthropic_payload_to_chat_completions(form_data, passthrough_params)
# Route through the existing chat_completion handler
response = await chat_completion(request, openai_payload, user)
- # Convert response back to Anthropic format
+ # Translate back to Anthropic; the caller ordered that dialect.
if isinstance(response, StreamingResponse):
# Streaming response: wrap the generator to convert SSE format
return StreamingResponse(
- openai_stream_to_anthropic_stream(response.body_iterator, model=requested_model, input_tokens=input_tokens),
+ convert_chat_completions_stream_to_anthropic(
+ response.body_iterator, model=requested_model, input_tokens=input_tokens
+ ),
media_type='text/event-stream',
headers={
'Cache-Control': 'no-cache',
@@ -2114,7 +2060,9 @@ async def generate_messages(
},
)
elif isinstance(response, dict):
- return convert_openai_to_anthropic_response(response, model=requested_model, input_tokens=input_tokens)
+ return convert_chat_completions_response_to_anthropic(
+ response, model=requested_model, input_tokens=input_tokens
+ )
else:
# Passthrough for error responses (JSONResponse, PlainTextResponse, etc.)
return response
@@ -2195,7 +2143,8 @@ async def list_tasks_endpoint(request: Request, user=Depends(get_admin_user)):
async def list_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=Depends(get_verified_user)):
socket_id = get_temporary_chat_session_id(chat_id)
if socket_id:
- owner_id = get_user_id_from_session_pool(socket_id)
+ owner = await get_temporary_chat(request.app.state.redis, chat_id)
+ owner_id = owner['user_id'] if owner else get_user_id_from_session_pool(socket_id)
if owner_id != user.id and not (user.role == 'admin' and ENABLE_ADMIN_CHAT_ACCESS):
return {'task_ids': []}
else:
@@ -2212,12 +2161,31 @@ async def list_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=De
return {'task_ids': task_ids}
+@app.post('/api/tasks/chat/{chat_id:path}/resume')
+async def resume_temporary_chat(request: Request, chat_id: str, form_data: dict, user=Depends(get_verified_user)):
+ session_id = form_data.get('session_id')
+ if not isinstance(session_id, str) or not await register_temporary_chat_session(
+ request.app.state.redis,
+ chat_id,
+ user.id,
+ session_id,
+ get_user_id_from_session_pool(session_id),
+ create=True,
+ ):
+ raise HTTPException(status_code=404, detail='Temporary chat expired or unavailable')
+ return {
+ 'task_ids': await list_task_ids_by_item_id(request.app.state.redis, chat_id),
+ 'streams': await get_response_streams_by_chat_id(request.app.state.redis, chat_id),
+ }
+
+
@app.post('/api/tasks/chat/{chat_id:path}/stop')
async def stop_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=Depends(get_verified_user)):
socket_id = get_temporary_chat_session_id(chat_id)
chat = None
if socket_id:
- owner_id = get_user_id_from_session_pool(socket_id)
+ owner = await get_temporary_chat(request.app.state.redis, chat_id)
+ owner_id = owner['user_id'] if owner else get_user_id_from_session_pool(socket_id)
if owner_id != user.id and not (user.role == 'admin' and ENABLE_ADMIN_CHAT_ACCESS):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
else:
@@ -2275,15 +2243,12 @@ async def stop_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=De
if event_emitter:
await event_emitter({'type': 'chat:completion', 'data': {'done': True, 'output': output}})
await event_emitter({'type': 'chat:tasks:cancel'})
+ await event_emitter({'type': 'chat:active', 'data': {'active': False}})
return result
-##################################
-#
# Config Endpoints
-#
-##################################
@app.get('/api/config')
@@ -2355,6 +2320,8 @@ async def get_app_config(request: Request):
'calendar.enable',
'automations.enable',
'notes.enable',
+ 'comments.enable',
+ 'notifications.enable',
'chat.context_compaction.enable',
'chat.tool_permissions.enable',
'web.search.enable',
@@ -2420,7 +2387,7 @@ async def get_app_config(request: Request):
},
'features': {
'slim': USE_SLIM,
- # --- Public: required by login/signup page pre-auth ---
+ # Public: required by login/signup page pre-auth
'auth': WEBUI_AUTH,
'auth_trusted_header': bool(WEBUI_AUTH_TRUSTED_EMAIL_HEADER),
'enable_signup_password_confirmation': ENABLE_SIGNUP_PASSWORD_CONFIRMATION,
@@ -2433,7 +2400,7 @@ async def get_app_config(request: Request):
if WEBSOCKET_HEARTBEAT_INTERVAL is not None
else {}
),
- # --- Authenticated: only consumed by logged-in frontend ---
+ # Authenticated: only consumed by logged-in frontend
**(
{
'enable_api_keys': config.get('auth.enable_api_keys'),
@@ -2462,6 +2429,8 @@ async def get_app_config(request: Request):
'enable_calendar': config.get('calendar.enable'),
'enable_automations': config.get('automations.enable'),
'enable_notes': config.get('notes.enable'),
+ 'enable_comments': config.get('comments.enable'),
+ 'enable_notifications': config.get('notifications.enable'),
'enable_context_compaction': config.get('chat.context_compaction.enable'),
'enable_tool_permissions': config.get('chat.tool_permissions.enable'),
'enable_web_search': config.get('web.search.enable'),
@@ -2617,7 +2586,7 @@ async def get_event_webhooks_api(user=Depends(get_admin_user)):
@app.post('/api/events/webhooks')
-async def create_event_webhook(form_data: EventWebhookForm, user=Depends(get_admin_user)):
+async def create_event_webhook(request: Request, form_data: EventWebhookForm, user=Depends(get_admin_user)):
try:
webhook = await upsert_event_webhook(
{
@@ -2632,7 +2601,7 @@ async def create_event_webhook(form_data: EventWebhookForm, user=Depends(get_adm
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
await publish_event(
- app,
+ request,
EVENTS.CONFIG_WEBHOOK_UPDATED,
actor=user,
subject_id=webhook['id'],
@@ -2648,7 +2617,9 @@ async def create_event_webhook(form_data: EventWebhookForm, user=Depends(get_adm
@app.put('/api/events/webhooks/{webhook_id}')
-async def update_event_webhook(webhook_id: str, form_data: EventWebhookUpdateForm, user=Depends(get_admin_user)):
+async def update_event_webhook(
+ request: Request, webhook_id: str, form_data: EventWebhookUpdateForm, user=Depends(get_admin_user)
+):
webhooks = await get_event_webhooks()
existing = next((webhook for webhook in webhooks if webhook.get('id') == webhook_id), None)
if not existing:
@@ -2666,7 +2637,7 @@ async def update_event_webhook(webhook_id: str, form_data: EventWebhookUpdateFor
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
await publish_event(
- app,
+ request,
EVENTS.CONFIG_WEBHOOK_UPDATED,
actor=user,
subject_id=webhook_id,
@@ -2682,13 +2653,13 @@ async def update_event_webhook(webhook_id: str, form_data: EventWebhookUpdateFor
@app.delete('/api/events/webhooks/{webhook_id}')
-async def delete_event_webhook_api(webhook_id: str, user=Depends(get_admin_user)):
+async def delete_event_webhook_api(request: Request, webhook_id: str, user=Depends(get_admin_user)):
deleted = await delete_event_webhook(webhook_id)
if not deleted:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Webhook not found')
await publish_event(
- app,
+ request,
EVENTS.CONFIG_WEBHOOK_UPDATED,
actor=user,
subject_id=webhook_id,
@@ -2758,7 +2729,7 @@ async def get_current_usage(user=Depends(get_verified_user)):
raise HTTPException(status_code=500, detail='Internal Server Error')
-# --- OAuth Login & Callback ---
+# OAuth login & callback
try:
@@ -2974,9 +2945,7 @@ async def oauth_login_callback(
return await oauth_manager.handle_callback(request, provider, response, db=db)
-############################
# OIDC Back-Channel Logout
-############################
@app.post('/oauth/backchannel-logout')
@@ -3137,7 +3106,7 @@ async def check_db_health():
return {'status': True}
-# --- static assets & files ---
+# Static assets & files
# Windows registry entries can override these with text/plain, which breaks module and wasm loading
mimetypes.add_type('text/javascript', '.js')
mimetypes.add_type('text/javascript', '.mjs')
diff --git a/backend/open_webui/migrations/env.py b/backend/open_webui/migrations/env.py
index 0ddfc609ee..c6e385d74d 100644
--- a/backend/open_webui/migrations/env.py
+++ b/backend/open_webui/migrations/env.py
@@ -14,6 +14,8 @@ from open_webui.models.auths import Auth
from open_webui.models.calendar import Calendar, CalendarEvent, CalendarEventAttendee # noqa: F401
from open_webui.models.chat_messages import ChatMessage # noqa: F401
from open_webui.models.chats import Chat # noqa: F401
+from open_webui.models.comments import Comment, CommentReaction # noqa: F401
+from open_webui.models.notifications import Notification # noqa: F401
from sqlalchemy import create_engine, engine_from_config, inspect, pool
alembic_config = alembic.context.config
diff --git a/backend/open_webui/migrations/util.py b/backend/open_webui/migrations/util.py
index 1c55faf0e9..05407a4358 100644
--- a/backend/open_webui/migrations/util.py
+++ b/backend/open_webui/migrations/util.py
@@ -6,7 +6,7 @@ from alembic import op # noqa: E402 — alembic runtime context
from sqlalchemy import inspect # metadata inspection
-# --- database helper functions ---
+# Database helper functions
def get_existing_tables() -> set[str]:
"""Return table names already present in the database."""
conn = op.get_bind()
diff --git a/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py b/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py
index ff6fe65118..8b571dccea 100644
--- a/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py
+++ b/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py
@@ -22,7 +22,7 @@ def upgrade() -> None:
inspector = sa.inspect(op.get_bind())
existing_tables = set(inspector.get_table_names())
- # ── Create oauth_session table (idempotent) ───────────────────────
+ # Create oauth_session table (idempotent)
if 'oauth_session' not in existing_tables:
op.create_table(
'oauth_session',
diff --git a/backend/open_webui/migrations/versions/6f8c2a91d4e7_add_tool_is_active.py b/backend/open_webui/migrations/versions/6f8c2a91d4e7_add_tool_is_active.py
new file mode 100644
index 0000000000..470cf20e30
--- /dev/null
+++ b/backend/open_webui/migrations/versions/6f8c2a91d4e7_add_tool_is_active.py
@@ -0,0 +1,21 @@
+"""Add a persistent enabled state to tools.
+
+Revision ID: 6f8c2a91d4e7
+Revises: c41f8d9e2a10
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = '6f8c2a91d4e7'
+down_revision = 'c41f8d9e2a10'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.add_column('tool', sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.true()))
+
+
+def downgrade():
+ op.drop_column('tool', 'is_active')
diff --git a/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py b/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py
index ca75fff7d1..e55f591890 100644
--- a/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py
+++ b/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py
@@ -178,7 +178,7 @@ _INITIAL_TABLES: list[tuple[str, list[sa.Column], list]] = [
]
-# --- migration execution ---
+# Migration execution
def upgrade() -> None: # deploy initial schema tables
existing_tables = set(get_existing_tables())
for name, columns, constraints in _INITIAL_TABLES:
@@ -186,7 +186,7 @@ def upgrade() -> None: # deploy initial schema tables
op.create_table(name, *columns, *constraints)
-# --- rollback function ---
+# Rollback function
def downgrade() -> None: # rollback initial schema tables
for table_name, _, _ in reversed(_INITIAL_TABLES):
op.drop_table(table_name)
diff --git a/backend/open_webui/migrations/versions/af906e964978_add_feedback_table.py b/backend/open_webui/migrations/versions/af906e964978_add_feedback_table.py
index 65dcf6f5f9..1f3d6685ba 100644
--- a/backend/open_webui/migrations/versions/af906e964978_add_feedback_table.py
+++ b/backend/open_webui/migrations/versions/af906e964978_add_feedback_table.py
@@ -22,7 +22,7 @@ def upgrade():
existing_tables = set(inspector.get_table_names())
if 'feedback' not in existing_tables:
- # ### Create feedback table ###
+ # Create feedback table
op.create_table(
'feedback',
sa.Column('id', sa.Text(), primary_key=True), # Unique identifier for each feedback (TEXT type)
@@ -42,5 +42,5 @@ def upgrade():
def downgrade():
- # ### Drop feedback table ###
+ # Drop feedback table
op.drop_table('feedback')
diff --git a/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py b/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py
index 1de7af315f..fbb9f8f2c9 100644
--- a/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py
+++ b/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py
@@ -20,7 +20,7 @@ down_revision: Union[str, None] = '2f1211949ecc'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
-# ── Ad-hoc table references for Core DML ─────────────────────────────────
+# Ad-hoc table references for Core DML
# These are lightweight table() / column() references used only inside this
# migration for SELECT / UPDATE / INSERT — they do NOT create or alter
# anything on disk.
@@ -143,7 +143,7 @@ def upgrade() -> None:
existing_tables = set(inspector.get_table_names())
user_columns = {c['name'] for c in inspector.get_columns('user')}
- # ── Add new columns (idempotent) ──────────────────────────────────
+ # Add new columns (idempotent)
for col_name, col_type in [
('profile_banner_image_url', sa.Text()),
('timezone', sa.String()),
@@ -164,7 +164,7 @@ def upgrade() -> None:
if isinstance(user_col_types.get('settings'), sa.Text):
_convert_column_to_json('user', 'settings')
- # ── Create api_key table (idempotent) ─────────────────────────────
+ # Create api_key table (idempotent)
if 'api_key' not in existing_tables:
op.create_table(
'api_key',
@@ -178,7 +178,7 @@ def upgrade() -> None:
sa.Column('updated_at', sa.BigInteger(), nullable=False),
)
- # ── Migrate oauth_sub → oauth JSON (only if old column still exists)
+ # Migrate oauth_sub → OAuth JSON (only if old column still exists)
if 'oauth_sub' in user_columns:
rows = conn.execute(sa.select(_user.c.id, _user.c.oauth_sub).where(_user.c.oauth_sub.is_not(None))).fetchall()
@@ -187,7 +187,7 @@ def upgrade() -> None:
provider, sub = oauth_sub.split('@', 1) if '@' in oauth_sub else ('oidc', oauth_sub)
conn.execute(sa.update(_user).where(_user.c.id == uid).values(oauth={provider: {'sub': sub}}))
- # ── Migrate api_key column → api_key table (only if old column still exists)
+ # Migrate api_key column → api_key table (only if old column still exists)
if 'api_key' in user_columns:
rows = conn.execute(sa.select(_user.c.id, _user.c.api_key).where(_user.c.api_key.is_not(None))).fetchall()
now = int(time.time())
@@ -204,7 +204,7 @@ def upgrade() -> None:
)
)
- # ── Drop legacy columns (idempotent) ──────────────────────────────
+ # Drop legacy columns (idempotent)
cols_to_drop = {'api_key', 'oauth_sub'} & user_columns
if cols_to_drop:
if conn.dialect.name == 'sqlite':
@@ -235,7 +235,7 @@ def downgrade() -> None:
op.drop_column('user', 'oauth')
- # --- Restore api_key field ---
+ # Restore api_key field
op.add_column('user', sa.Column('api_key', sa.String(), nullable=True))
keys = conn.execute(sa.select(_api_key.c.user_id, _api_key.c.key)).fetchall()
diff --git a/backend/open_webui/migrations/versions/c0fbf31ca0db_update_file_table.py b/backend/open_webui/migrations/versions/c0fbf31ca0db_update_file_table.py
index 75eada2d3f..7d42a649b5 100644
--- a/backend/open_webui/migrations/versions/c0fbf31ca0db_update_file_table.py
+++ b/backend/open_webui/migrations/versions/c0fbf31ca0db_update_file_table.py
@@ -23,7 +23,7 @@ def upgrade():
inspector = sa.inspect(conn)
file_cols = {c['name'] for c in inspector.get_columns('file')}
- # ### commands auto generated by Alembic - please adjust! ###
+ # Commands auto generated by alembic - please adjust!
if 'hash' not in file_cols:
op.add_column('file', sa.Column('hash', sa.Text(), nullable=True))
if 'data' not in file_cols:
@@ -33,7 +33,7 @@ def upgrade():
def downgrade():
- # ### commands auto generated by Alembic - please adjust! ###
+ # Commands auto generated by alembic - please adjust!
op.drop_column('file', 'updated_at')
op.drop_column('file', 'data')
op.drop_column('file', 'hash')
diff --git a/backend/open_webui/migrations/versions/c41f8d9e2a10_add_resource_comments.py b/backend/open_webui/migrations/versions/c41f8d9e2a10_add_resource_comments.py
new file mode 100644
index 0000000000..b178580abd
--- /dev/null
+++ b/backend/open_webui/migrations/versions/c41f8d9e2a10_add_resource_comments.py
@@ -0,0 +1,50 @@
+"""Add resource comments and reactions.
+
+Revision ID: c41f8d9e2a10
+Revises: 0bd252b206fb
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = 'c41f8d9e2a10'
+down_revision = '0bd252b206fb'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_table(
+ 'comment',
+ sa.Column('id', sa.Text(), primary_key=True),
+ sa.Column('user_id', sa.Text(), nullable=True),
+ sa.Column('resource_type', sa.Text(), nullable=False),
+ sa.Column('resource_id', sa.Text(), nullable=False),
+ sa.Column('parent_id', sa.Text(), nullable=True),
+ sa.Column('reply_to_id', sa.Text(), nullable=True),
+ sa.Column('content', sa.Text(), nullable=False),
+ sa.Column('target_type', sa.Text(), nullable=True),
+ sa.Column('target_id', sa.Text(), nullable=True),
+ sa.Column('meta', sa.JSON(), nullable=True),
+ sa.Column('created_at', sa.BigInteger(), nullable=False),
+ sa.Column('updated_at', sa.BigInteger(), nullable=False),
+ sa.Column('deleted_at', sa.BigInteger(), nullable=True),
+ )
+ op.create_index('ix_comment_resource', 'comment', ['resource_type', 'resource_id', 'parent_id', 'created_at', 'id'])
+ op.create_index('ix_comment_parent', 'comment', ['parent_id', 'created_at', 'id'])
+ op.create_index('ix_comment_target', 'comment', ['resource_type', 'resource_id', 'target_type', 'target_id'])
+ op.create_table(
+ 'comment_reaction',
+ sa.Column('id', sa.Text(), primary_key=True),
+ sa.Column('user_id', sa.Text(), nullable=False),
+ sa.Column('comment_id', sa.Text(), nullable=False),
+ sa.Column('name', sa.Text(), nullable=False),
+ sa.Column('created_at', sa.BigInteger(), nullable=False),
+ sa.UniqueConstraint('comment_id', 'user_id', 'name', name='uq_comment_reaction'),
+ )
+ op.create_index('ix_comment_reaction_comment_id', 'comment_reaction', ['comment_id'])
+
+
+def downgrade():
+ op.drop_table('comment_reaction')
+ op.drop_table('comment')
diff --git a/backend/open_webui/migrations/versions/e42c8f710a36_add_notification_inbox.py b/backend/open_webui/migrations/versions/e42c8f710a36_add_notification_inbox.py
new file mode 100644
index 0000000000..f5f455a5fa
--- /dev/null
+++ b/backend/open_webui/migrations/versions/e42c8f710a36_add_notification_inbox.py
@@ -0,0 +1,52 @@
+"""Add persistent general inbox notifications.
+
+Revision ID: e42c8f710a36
+Revises: 6f8c2a91d4e7
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = 'e42c8f710a36'
+down_revision = '6f8c2a91d4e7'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_table(
+ 'notification',
+ sa.Column('id', sa.Text(), primary_key=True),
+ sa.Column('user_id', sa.Text(), nullable=False),
+ sa.Column('event_type', sa.Text(), nullable=False),
+ sa.Column('event_key', sa.Text(), nullable=False),
+ sa.Column('actor_type', sa.Text(), nullable=False),
+ sa.Column('actor_id', sa.Text(), nullable=True),
+ sa.Column('resource_type', sa.Text(), nullable=True),
+ sa.Column('resource_id', sa.Text(), nullable=True),
+ sa.Column('object_type', sa.Text(), nullable=True),
+ sa.Column('object_id', sa.Text(), nullable=True),
+ sa.Column('data', sa.JSON(), nullable=False),
+ sa.Column('seen_at', sa.BigInteger(), nullable=True),
+ sa.Column('read_at', sa.BigInteger(), nullable=True),
+ sa.Column('created_at', sa.BigInteger(), nullable=False),
+ sa.Column('updated_at', sa.BigInteger(), nullable=False),
+ sa.UniqueConstraint('user_id', 'event_key', name='uq_notification_occurrence'),
+ sa.CheckConstraint('(resource_type IS NULL) = (resource_id IS NULL)', name='ck_notification_resource'),
+ sa.CheckConstraint('(object_type IS NULL) = (object_id IS NULL)', name='ck_notification_object'),
+ sa.CheckConstraint("actor_type IN ('user', 'system')", name='ck_notification_actor'),
+ )
+ op.create_index('ix_notification_user_created', 'notification', ['user_id', 'created_at', 'id'])
+ op.create_index(
+ 'ix_notification_unseen',
+ 'notification',
+ ['user_id', 'created_at', 'id'],
+ sqlite_where=sa.text('seen_at IS NULL'),
+ postgresql_where=sa.text('seen_at IS NULL'),
+ )
+ op.create_index('ix_notification_resource', 'notification', ['resource_type', 'resource_id'])
+ op.create_index('ix_notification_object', 'notification', ['object_type', 'object_id'])
+
+
+def downgrade():
+ op.drop_table('notification')
diff --git a/backend/open_webui/models/access_grants.py b/backend/open_webui/models/access_grants.py
index b9c2221f7a..36bf633d03 100644
--- a/backend/open_webui/models/access_grants.py
+++ b/backend/open_webui/models/access_grants.py
@@ -17,9 +17,7 @@ PRINCIPAL_TYPE_USER = 'user'
WILDCARD_PRINCIPAL_ID = '*'
-####################
# AccessGrant DB Schema
-####################
class AccessGrant(Base):
@@ -75,9 +73,7 @@ class AccessGrantResponse(BaseModel):
)
-####################
# Conversion utilities
-####################
def access_control_to_grants(
@@ -318,9 +314,7 @@ def grants_to_access_control(grants: list) -> Optional[dict]:
return result
-####################
# Table Operations
-####################
class AccessGrantsTable:
@@ -582,47 +576,17 @@ class AccessGrantsTable:
- There's a grant for any of the user's groups with the requested permission
"""
async with get_async_db_context(db) as db:
- # Build conditions for matching grants
- conditions = [
- # Public access
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == '*',
- ),
- # Direct user access
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == user_id,
- ),
- ]
-
- # Group access
if user_group_ids is None:
from open_webui.models.groups import Groups
user_groups = await Groups.get_groups_by_member_id(user_id, db=db, include_inherited=True)
user_group_ids = {group.id for group in user_groups}
- if user_group_ids:
- conditions.append(
- and_(
- AccessGrant.principal_type == 'group',
- AccessGrant.principal_id.in_(user_group_ids),
- )
+ return bool(
+ await db.scalar(
+ select(self.has_grant_expression(user_id, resource_type, resource_id, permission, user_group_ids))
)
-
- result = await db.execute(
- select(AccessGrant)
- .filter(
- AccessGrant.resource_type == resource_type,
- AccessGrant.resource_id == resource_id,
- AccessGrant.permission == permission,
- or_(*conditions),
- )
- .limit(1)
)
- grant = result.scalars().first()
- return grant is not None
async def get_accessible_resource_ids(
self,
@@ -766,122 +730,55 @@ class AccessGrantsTable:
user_ids = await self.get_user_ids_by_access_grants(access_grants, permission, db=db)
return previous_user_ids - user_ids
+ def has_grant_expression(self, user_id, resource_type, resource_id, permission='read', user_group_ids=()):
+ """SQL grant check for one resource or a correlated resource column; ownership is separate."""
+ return (
+ select(AccessGrant.id)
+ .where(
+ AccessGrant.resource_type == resource_type,
+ AccessGrant.resource_id == resource_id,
+ AccessGrant.permission == permission,
+ or_(
+ and_(
+ AccessGrant.principal_type == 'user',
+ AccessGrant.principal_id.in_(['*', user_id] if user_id else ['*']),
+ ),
+ and_(AccessGrant.principal_type == 'group', AccessGrant.principal_id.in_(user_group_ids or ())),
+ ),
+ )
+ .correlate_except(AccessGrant)
+ .exists()
+ )
+
def has_permission_filter(
self,
- db,
query,
DocumentModel,
filter: dict,
resource_type: str,
permission: str = 'read',
+ *,
+ db,
):
- """
- Apply access control filtering to a SQLAlchemy query by JOINing with access_grant.
-
- This replaces the old JSON-column-based filtering with a proper relational JOIN.
-
- Note: This method builds SQLAlchemy expressions and does NOT perform I/O itself,
- so it remains synchronous. The caller is responsible for executing the query
- asynchronously with `await db.execute(...)`.
- """
+ """Apply owner-or-grant filtering without loading resources or duplicating rows."""
+ if permission == 'read_only':
+ return self._has_read_only_permission_filter(query, DocumentModel, filter, resource_type, db=db)
group_ids = filter.get('group_ids', [])
user_id = filter.get('user_id')
-
- if permission == 'read_only':
- return self._has_read_only_permission_filter(db, query, DocumentModel, filter, resource_type)
-
- # Build principal conditions
- principal_conditions = []
-
- if group_ids or user_id:
- # Public access: user:* read
- principal_conditions.append(
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == '*',
- )
- )
-
- if user_id:
- # Owner always has access
- principal_conditions.append(DocumentModel.user_id == user_id)
-
- # Direct user grant
- principal_conditions.append(
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == user_id,
- )
- )
-
- if group_ids:
- # Group grants
- principal_conditions.append(
- and_(
- AccessGrant.principal_type == 'group',
- AccessGrant.principal_id.in_(group_ids),
- )
- )
-
- if not principal_conditions:
+ if not group_ids and not user_id:
return query
-
- # LEFT JOIN access_grant and filter
- # We use a subquery approach to avoid duplicates from multiple matching grants
- from sqlalchemy import exists as sa_exists
-
- grant_exists = (
- select(AccessGrant.id)
- .where(
- AccessGrant.resource_type == resource_type,
- AccessGrant.resource_id == DocumentModel.id,
- AccessGrant.permission == permission,
- or_(
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == '*',
- ),
- *(
- [
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == user_id,
- )
- ]
- if user_id
- else []
- ),
- *(
- [
- and_(
- AccessGrant.principal_type == 'group',
- AccessGrant.principal_id.in_(group_ids),
- )
- ]
- if group_ids
- else []
- ),
- ),
- )
- .correlate(DocumentModel)
- .exists()
- )
-
- # Owner OR has a matching grant
- owner_or_grant = [grant_exists]
+ allowed = self.has_grant_expression(user_id, resource_type, DocumentModel.id, permission, group_ids)
if user_id:
- owner_or_grant.append(DocumentModel.user_id == user_id)
-
- query = query.filter(or_(*owner_or_grant))
- return query
+ allowed = or_(DocumentModel.user_id == user_id, allowed)
+ return query.filter(allowed)
def _has_read_only_permission_filter(
self,
- db,
query,
DocumentModel,
filter: dict,
resource_type: str,
+ db,
):
"""
Filter for items where user has read BUT NOT write access.
@@ -895,81 +792,8 @@ class AccessGrantsTable:
group_ids = filter.get('group_ids', [])
user_id = filter.get('user_id')
- from sqlalchemy import exists as sa_exists
-
- read_grant_exists = (
- select(AccessGrant.id)
- .where(
- AccessGrant.resource_type == resource_type,
- AccessGrant.resource_id == DocumentModel.id,
- AccessGrant.permission == 'read',
- or_(
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == '*',
- ),
- *(
- [
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == user_id,
- )
- ]
- if user_id
- else []
- ),
- *(
- [
- and_(
- AccessGrant.principal_type == 'group',
- AccessGrant.principal_id.in_(group_ids),
- )
- ]
- if group_ids
- else []
- ),
- ),
- )
- .correlate(DocumentModel)
- .exists()
- )
-
- write_grant_exists = (
- select(AccessGrant.id)
- .where(
- AccessGrant.resource_type == resource_type,
- AccessGrant.resource_id == DocumentModel.id,
- AccessGrant.permission == 'write',
- or_(
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == '*',
- ),
- *(
- [
- and_(
- AccessGrant.principal_type == 'user',
- AccessGrant.principal_id == user_id,
- )
- ]
- if user_id
- else []
- ),
- *(
- [
- and_(
- AccessGrant.principal_type == 'group',
- AccessGrant.principal_id.in_(group_ids),
- )
- ]
- if group_ids
- else []
- ),
- ),
- )
- .correlate(DocumentModel)
- .exists()
- )
+ read_grant_exists = self.has_grant_expression(user_id, resource_type, DocumentModel.id, 'read', group_ids)
+ write_grant_exists = self.has_grant_expression(user_id, resource_type, DocumentModel.id, 'write', group_ids)
conditions = [read_grant_exists, ~write_grant_exists]
diff --git a/backend/open_webui/models/apps.py b/backend/open_webui/models/apps.py
index 2501d4de46..0433e48ce4 100644
--- a/backend/open_webui/models/apps.py
+++ b/backend/open_webui/models/apps.py
@@ -205,9 +205,7 @@ class AppInteractionForm(StrictModel):
action_id: str = Field(min_length=1, max_length=100)
-####################
# Forms
-####################
class AppManifestForm(StrictModel):
@@ -244,9 +242,7 @@ class AppConnectionForm(StrictModel):
api_key: SecretStr | None = Field(default=None, min_length=1, max_length=4096)
-####################
# Responses
-####################
class AppResponse(BaseModel):
diff --git a/backend/open_webui/models/auths.py b/backend/open_webui/models/auths.py
index f5350cc737..0ee67d73e4 100644
--- a/backend/open_webui/models/auths.py
+++ b/backend/open_webui/models/auths.py
@@ -207,7 +207,7 @@ class AddUserForm(SignupForm):
role: str | None = 'pending'
-# --- data-access layer ---
+# Data-access layer
class AuthsTable:
@@ -393,7 +393,7 @@ class AuthsTable:
await session.commit()
await Users.update_user_by_id(user_id, {'email': email}, db=session)
return True
- # --- password modification ---
+ # Password modification
async def update_user_password_by_id(
self,
diff --git a/backend/open_webui/models/automations.py b/backend/open_webui/models/automations.py
index 0aab02e5f6..7f5707d78a 100644
--- a/backend/open_webui/models/automations.py
+++ b/backend/open_webui/models/automations.py
@@ -3,6 +3,7 @@ import time
from typing import Literal, Optional
from uuid import uuid4
+from open_webui.models.notifications import emit_changes
from open_webui.internal.db import Base, get_async_db_context
from open_webui.utils.misc import json_text_variants
from pydantic import BaseModel, ConfigDict
@@ -12,9 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-####################
# Automation DB Schema
-####################
class Automation(Base):
@@ -55,9 +54,7 @@ class AutomationRun(Base):
)
-####################
# Pydantic Models
-####################
class AutomationTerminalConfig(BaseModel):
@@ -124,9 +121,7 @@ class AutomationListResponse(BaseModel):
total: int
-####################
-# AutomationTable
-####################
+# Automation Table
class AutomationTable:
@@ -291,8 +286,12 @@ class AutomationTable:
row = await db.get(Automation, id)
if not row:
return False
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(resource_type='automation', resource_ids=[id], db=db)
await db.delete(row)
await db.commit()
+ await emit_changes(recipients)
return True
async def claim_due(self, now_ns: int, limit: int = 10, db: Optional[AsyncSession] = None) -> list[AutomationModel]:
@@ -349,9 +348,7 @@ class AutomationTable:
return [AutomationModel.model_validate(r) for r in claimed]
-####################
-# AutomationRunTable
-####################
+# Automation Run Table
class AutomationRunTable:
@@ -361,6 +358,9 @@ class AutomationRunTable:
status: str,
chat_id: Optional[str] = None,
error: Optional[str] = None,
+ *,
+ request=None,
+ event_actor=None,
db: Optional[AsyncSession] = None,
) -> AutomationRunModel:
async with get_async_db_context(db) as db:
@@ -373,7 +373,37 @@ class AutomationRunTable:
created_at=int(time.time_ns()),
)
db.add(row)
+ await db.flush()
+ event = None
+ recipients = set()
+ if status == 'error':
+ from open_webui.events import EVENTS, build_event, publish_event
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+
+ automation = await db.get(Automation, automation_id)
+ if automation:
+ event = build_event(
+ request,
+ EVENTS.AUTOMATION_RUN_FAILED,
+ actor=event_actor,
+ subject_id=automation_id,
+ event_id=f'automation-run:{row.id}',
+ data={
+ 'run_id': row.id,
+ 'name': automation.name,
+ 'error': error,
+ 'user_id': automation.user_id,
+ 'message': f'{automation.name}: {error}',
+ **({'chat_id': chat_id} if chat_id else {}),
+ },
+ )
+ recipients = await consume_event(event, db=db)
await db.commit()
+ if event is not None:
+ await emit_changes(recipients)
+ if request is not None:
+ await publish_event(request, event)
return AutomationRunModel.model_validate(row)
async def get_latest(self, automation_id: str, db: Optional[AsyncSession] = None) -> Optional[AutomationRunModel]:
@@ -434,8 +464,16 @@ class AutomationRunTable:
async def delete_by_automation(self, automation_id: str, db: Optional[AsyncSession] = None) -> int:
async with get_async_db_context(db) as db:
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(
+ object_type='automation_run',
+ object_ids=select(AutomationRun.id).where(AutomationRun.automation_id == automation_id),
+ db=db,
+ )
result = await db.execute(delete(AutomationRun).filter_by(automation_id=automation_id))
await db.commit()
+ await emit_changes(recipients)
return result.rowcount
async def get_runs_by_user_range(
diff --git a/backend/open_webui/models/calendar.py b/backend/open_webui/models/calendar.py
index a7489e925f..7bcd393ebc 100644
--- a/backend/open_webui/models/calendar.py
+++ b/backend/open_webui/models/calendar.py
@@ -3,6 +3,7 @@ import time
from typing import Optional
from uuid import uuid4
+from open_webui.models.notifications import emit_changes
from open_webui.constants import ERROR_MESSAGES
from open_webui.internal.db import Base, get_async_db_context
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
@@ -30,9 +31,7 @@ log = logging.getLogger(__name__)
MIN_CALENDAR_RRULE_INTERVAL_SECONDS = 24 * 60 * 60
-####################
# Calendar DB Schema
-####################
class Calendar(Base):
@@ -97,9 +96,7 @@ class CalendarEventAttendee(Base):
)
-####################
# Pydantic Models
-####################
class CalendarModel(BaseModel):
@@ -158,9 +155,7 @@ class CalendarEventAttendeeModel(BaseModel):
updated_at: int
-####################
# Forms
-####################
class CalendarForm(BaseModel):
@@ -227,9 +222,7 @@ class RSVPForm(BaseModel):
status: str # 'accepted' | 'declined' | 'tentative' | 'pending'
-####################
# Response Models
-####################
class CalendarEventUserResponse(CalendarEventModel):
@@ -241,9 +234,7 @@ class CalendarEventListResponse(BaseModel):
total: int
-####################
# Table Operations
-####################
class CalendarTable:
@@ -408,8 +399,12 @@ class CalendarTable:
await db.execute(delete(CalendarEvent).filter(CalendarEvent.calendar_id == id))
# Delete calendar
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(resource_type='calendar', resource_ids=[id], db=db)
await db.execute(delete(Calendar).filter(Calendar.id == id))
await db.commit()
+ await emit_changes(recipients)
# Revoke access grants in a separate transaction to avoid
# write-lock contention on SQLite when session sharing is off.
@@ -772,8 +767,12 @@ class CalendarEventTable:
try:
async with get_async_db_context(db) as db:
await db.execute(delete(CalendarEventAttendee).filter(CalendarEventAttendee.event_id == id))
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(object_type='calendar_event', object_ids=[id], db=db)
await db.execute(delete(CalendarEvent).filter(CalendarEvent.id == id))
await db.commit()
+ await emit_changes(recipients)
return True
except Exception:
return False
diff --git a/backend/open_webui/models/channels.py b/backend/open_webui/models/channels.py
index 1876f41c03..1f0d15f47b 100644
--- a/backend/open_webui/models/channels.py
+++ b/backend/open_webui/models/channels.py
@@ -3,6 +3,7 @@ import time
import uuid
from typing import Optional
+from open_webui.models.notifications import emit_changes
from open_webui.internal.db import Base, JSONField, get_async_db_context
from open_webui.models.access_grants import (
AccessGrantModel,
@@ -33,9 +34,7 @@ from sqlalchemy import (
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.asyncio import AsyncSession
-####################
# Channel DB Schema
-####################
class Channel(Base):
@@ -225,9 +224,7 @@ class ChannelWebhookModel(BaseModel):
updated_at: int # timestamp in epoch (time_ns)
-####################
# Forms
-####################
class ChannelResponse(ChannelModel):
@@ -793,7 +790,7 @@ class ChannelTable:
allowed_channels = []
for channel in channels:
- # --- Case A: group or dm => user must be an active member ---
+ # Case a: group or dm => user must be an active member
if channel.type in ['group', 'dm']:
result = await db.execute(
select(ChannelMember)
@@ -809,7 +806,7 @@ class ChannelTable:
allowed_channels.append(await self._to_channel_model(channel, db=db))
continue
- # --- Case B: standard channel => rely on ACL permissions ---
+ # Case b: standard channel => rely on acl permissions
stmt = select(Channel).filter(Channel.id == channel.id)
stmt = self._has_permission(
@@ -963,13 +960,15 @@ class ChannelTable:
async def delete_channel_by_id(self, id: str, db: Optional[AsyncSession] = None) -> bool:
async with get_async_db_context(db) as db:
await AccessGrants.revoke_all_access('channel', id, db=db)
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(resource_type='channel', resource_ids=[id], db=db)
await db.execute(delete(Channel).filter(Channel.id == id))
await db.commit()
+ await emit_changes(recipients)
return True
- ####################
# Webhook Methods
- ####################
async def insert_webhook(
self,
diff --git a/backend/open_webui/models/chat_messages.py b/backend/open_webui/models/chat_messages.py
index d7ed13223c..352e819930 100644
--- a/backend/open_webui/models/chat_messages.py
+++ b/backend/open_webui/models/chat_messages.py
@@ -10,7 +10,7 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from open_webui.internal.db import Base, get_async_db_context
from open_webui.utils.response import normalize_usage
-from open_webui.utils.session_records import normalize_tool_output, recorded_timestamp
+from open_webui.utils.session_records import has_pending_tool_approval, normalize_tool_output, recorded_timestamp
from pydantic import BaseModel, ConfigDict
from sqlalchemy import (
JSON,
@@ -32,9 +32,7 @@ from sqlalchemy import (
)
from sqlalchemy.ext.asyncio import AsyncSession
-####################
# Helpers
-####################
def _normalize_timestamp(timestamp: Optional[int]) -> float:
@@ -43,11 +41,11 @@ def _normalize_timestamp(timestamp: Optional[int]) -> float:
if timestamp is None:
return now
- # Convert milliseconds to seconds if needed
+ # Treat values above the seconds-range cutoff as milliseconds.
if timestamp > 10_000_000_000:
timestamp = timestamp / 1000
- # Validate: must be after 2020 and not in the future (with 1 day tolerance)
+ # Accept timestamps from 2020-01-01 through one day ahead of now, inclusive.
min_valid = 1577836800 # 2020-01-01 00:00:00 UTC
max_valid = now + 86400 # 1 day in the future (clock skew tolerance)
@@ -157,9 +155,7 @@ def _extract_tool_names(value: Any) -> list[str]:
return names
-####################
# ChatMessage DB Schema
-####################
class ChatMessage(Base):
@@ -210,9 +206,7 @@ class ChatMessage(Base):
)
-####################
# Pydantic Models
-####################
class ChatMessageModel(BaseModel):
@@ -239,9 +233,7 @@ class ChatMessageModel(BaseModel):
updated_at: int
-####################
# Table Operations
-####################
class ChatMessageTable:
@@ -364,6 +356,20 @@ class ChatMessageTable:
message = await db.get(ChatMessage, id)
return ChatMessageModel.model_validate(message) if message else None
+ async def get_chat_ids_with_pending_approval(
+ self, chat_ids: list[str], db: AsyncSession | None = None
+ ) -> set[str]:
+ if not chat_ids:
+ return set()
+ async with get_async_db_context(db) as db:
+ result = await db.execute(
+ select(ChatMessage.chat_id, ChatMessage.output)
+ .where(ChatMessage.chat_id.in_(chat_ids))
+ .where(ChatMessage.role == 'assistant')
+ .where(ChatMessage.done.is_(False))
+ )
+ return {chat_id for chat_id, output in result.all() if has_pending_tool_approval(output)}
+
async def has_unfinished_assistant_by_chat_id(
self,
chat_id: str,
diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py
index 3391c000eb..57f44331e3 100644
--- a/backend/open_webui/models/chats.py
+++ b/backend/open_webui/models/chats.py
@@ -11,7 +11,9 @@ import uuid
from typing import Any, Literal
# local imports
+from open_webui.models.notifications import emit_changes
from open_webui.env import ENABLE_ADMIN_CHAT_ACCESS
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, JSONField, get_async_db, get_async_db_context
from open_webui.models.access_grants import AccessGrants
from open_webui.models.automations import AutomationRun
@@ -295,9 +297,7 @@ class ChatFileModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
-####################
# Forms
-####################
class ChatForm(BaseModel):
@@ -356,6 +356,7 @@ class ChatTitleIdResponse(BaseModel):
last_read_at: int | None = None
snippet: str | None = None
active: bool = False
+ pending_approval: bool = False
archived: bool = False
@@ -2814,8 +2815,10 @@ class ChatTable:
async with get_async_db_context(db) as session:
await session.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None))
await session.execute(delete(ChatMessage).filter_by(chat_id=id))
+ recipients = await delete_resource_comments('chat', select(Chat.id).filter_by(id=id), db=session)
await session.execute(delete(Chat).filter_by(id=id))
await session.commit()
+ await emit_changes(recipients)
return True and await self.delete_shared_chat_by_chat_id(id, db=session)
except Exception:
@@ -2826,8 +2829,12 @@ class ChatTable:
async with get_async_db_context(db) as session:
await session.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None))
await session.execute(delete(ChatMessage).filter_by(chat_id=id))
+ recipients = await delete_resource_comments(
+ 'chat', select(Chat.id).filter_by(id=id, user_id=user_id), db=session
+ )
await session.execute(delete(Chat).filter_by(id=id, user_id=user_id))
await session.commit()
+ await emit_changes(recipients)
return True and await self.delete_shared_chat_by_chat_id(id, db=session)
except Exception:
@@ -2847,8 +2854,12 @@ class ChatTable:
await session.execute(
delete(ChatMessage).filter(ChatMessage.chat_id.in_(select(Chat.id).filter_by(user_id=user_id)))
)
+ recipients = await delete_resource_comments(
+ 'chat', select(Chat.id).filter_by(user_id=user_id), db=session
+ )
await session.execute(delete(Chat).filter_by(user_id=user_id))
await session.commit()
+ await emit_changes(recipients)
return True
except Exception:
@@ -2866,9 +2877,16 @@ class ChatTable:
update(AutomationRun).filter(AutomationRun.chat_id.in_(chat_ids_stmt)).values(chat_id=None)
)
await session.execute(delete(ChatMessage).filter(ChatMessage.chat_id.in_(chat_ids_stmt)))
+ recipients = await delete_resource_comments('chat', chat_ids_stmt, db=session)
await session.execute(delete(SharedChatTable).filter(SharedChatTable.chat_id.in_(chat_ids_stmt)))
+ recipients.update(
+ await delete_resource_comments(
+ 'chat', select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id), db=session
+ )
+ )
await session.execute(delete(Chat).filter_by(user_id=user_id, folder_id=folder_id))
await session.commit()
+ await emit_changes(recipients)
return True
except Exception:
diff --git a/backend/open_webui/models/comments.py b/backend/open_webui/models/comments.py
new file mode 100644
index 0000000000..cf866295db
--- /dev/null
+++ b/backend/open_webui/models/comments.py
@@ -0,0 +1,160 @@
+"""Resource discussions. All operations use the caller's transaction."""
+
+from typing import Literal
+from uuid import UUID
+
+from open_webui.internal.db import Base
+from open_webui.models.users import User
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+from sqlalchemy import JSON, BigInteger, Column, Index, Text, UniqueConstraint, case, delete, func, select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+
+ResourceType = Literal['model', 'knowledge', 'prompt', 'skill', 'tool', 'note', 'chat']
+
+
+class Comment(Base):
+ __tablename__ = 'comment'
+ id = Column(Text, primary_key=True)
+ user_id = Column(Text, nullable=True)
+ resource_type = Column(Text, nullable=False)
+ resource_id = Column(Text, nullable=False)
+ parent_id = Column(Text, nullable=True)
+ reply_to_id = Column(Text, nullable=True)
+ content = Column(Text, nullable=False)
+ target_type = Column(Text, nullable=True)
+ target_id = Column(Text, nullable=True)
+ meta = Column(JSON, nullable=True)
+ created_at = Column(BigInteger, nullable=False)
+ updated_at = Column(BigInteger, nullable=False)
+ deleted_at = Column(BigInteger, nullable=True)
+ __table_args__ = (
+ Index('ix_comment_resource', 'resource_type', 'resource_id', 'parent_id', 'created_at', 'id'),
+ Index('ix_comment_parent', 'parent_id', 'created_at', 'id'),
+ Index('ix_comment_target', 'resource_type', 'resource_id', 'target_type', 'target_id'),
+ )
+
+
+class CommentReaction(Base):
+ __tablename__ = 'comment_reaction'
+ id = Column(Text, primary_key=True)
+ user_id = Column(Text, nullable=False)
+ comment_id = Column(Text, nullable=False, index=True)
+ name = Column(Text, nullable=False)
+ created_at = Column(BigInteger, nullable=False)
+ __table_args__ = (UniqueConstraint('comment_id', 'user_id', 'name', name='uq_comment_reaction'),)
+
+
+class CommentAnchor(BaseModel):
+ model_config = ConfigDict(extra='forbid')
+ quote: str = Field(min_length=1, max_length=10000)
+ prefix: str = Field(default='', max_length=64)
+ suffix: str = Field(default='', max_length=64)
+ start: int = Field(ge=0)
+ end: int = Field(ge=1)
+ surface_id: str = Field(max_length=256)
+ source: str = Field(pattern=r'^[0-9a-f]{64}$')
+ content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
+
+
+class CommentContentForm(BaseModel):
+ model_config = ConfigDict(extra='forbid')
+ content: str = Field(min_length=1, max_length=20000)
+
+ @field_validator('content')
+ @classmethod
+ def nonempty(cls, value):
+ if not value.strip():
+ raise ValueError('Comment cannot be empty')
+ return value
+
+
+class CommentForm(CommentContentForm):
+ temp_id: UUID | None = None
+ resource_type: ResourceType
+ resource_id: str = Field(min_length=1, max_length=512)
+ target_type: Literal['note_page', 'chat_message'] | None = None
+ target_id: str | None = Field(default=None, max_length=256)
+ anchor: CommentAnchor | None = None
+
+
+class CommentReplyForm(CommentContentForm):
+ temp_id: UUID | None = None
+ reply_to_id: str | None = None
+
+
+class CommentUpdateForm(CommentContentForm):
+ etag: str = Field(pattern=r'^\d{1,20}$')
+
+
+async def comment_responses(db: AsyncSession, comments: list[Comment], user, owner_id: str) -> list[dict]:
+ if not comments:
+ return []
+ ids = [c.id for c in comments]
+ authors = {
+ u.id: {'id': u.id, 'name': u.name, 'profile_image_url': u.profile_image_url}
+ for u in (await db.scalars(select(User).where(User.id.in_({c.user_id for c in comments if c.user_id})))).all()
+ }
+ counts = {
+ parent_id: (count, latest)
+ for parent_id, count, latest in (
+ await db.execute(
+ select(Comment.parent_id, func.count(), func.max(Comment.created_at))
+ .where(Comment.parent_id.in_(ids))
+ .group_by(Comment.parent_id)
+ )
+ ).all()
+ }
+ reactions = {}
+ for comment_id, name, count, mine in (
+ await db.execute(
+ select(
+ CommentReaction.comment_id,
+ CommentReaction.name,
+ func.count(),
+ func.max(
+ # CASE is portable across PostgreSQL and SQLite (boolean MAX isn't).
+ case((CommentReaction.user_id == user.id, 1), else_=0)
+ ),
+ )
+ .where(CommentReaction.comment_id.in_(ids))
+ .group_by(CommentReaction.comment_id, CommentReaction.name)
+ )
+ ).all():
+ reactions.setdefault(comment_id, []).append({'name': name, 'count': count, 'reacted': bool(mine)})
+ return [
+ {
+ **{c.name: getattr(comment, c.name) for c in Comment.__table__.columns},
+ 'etag': str(comment.updated_at),
+ 'user': authors.get(comment.user_id),
+ 'reply_count': counts.get(comment.id, (0, None))[0],
+ 'latest_reply_at': counts.get(comment.id, (0, None))[1],
+ 'reactions': reactions.get(comment.id, []),
+ 'can_edit': not comment.deleted_at and comment.user_id == user.id,
+ 'can_delete': not comment.deleted_at
+ and (comment.user_id == user.id or owner_id == user.id or user.role == 'admin'),
+ }
+ for comment in comments
+ ]
+
+
+async def delete_resource_comments(resource_type: str, resource_ids, db: AsyncSession):
+ """Lock resources before cleanup so concurrent comment creation cannot leave orphans."""
+ from open_webui.utils.comments import resource_models
+
+ model = resource_models()[resource_type]
+ ids = list((await db.scalars(select(model.id).where(model.id.in_(resource_ids)).with_for_update())).all())
+ if not ids:
+ return set()
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(resource_type=resource_type, resource_ids=ids, db=db)
+ comment_ids = select(Comment.id).where(Comment.resource_type == resource_type, Comment.resource_id.in_(ids))
+ await db.execute(delete(CommentReaction).where(CommentReaction.comment_id.in_(comment_ids)))
+ await db.execute(delete(Comment).where(Comment.resource_type == resource_type, Comment.resource_id.in_(ids)))
+ return recipients
+
+
+async def cleanup_comments_for_deleted_user(db: AsyncSession, user_id: str):
+ """Remove reactions and clear authorship, preserving comment text and threads."""
+ await db.execute(delete(CommentReaction).where(CommentReaction.user_id == user_id))
+ await db.execute(update(Comment).where(Comment.user_id == user_id).values(user_id=None))
diff --git a/backend/open_webui/models/config.py b/backend/open_webui/models/config.py
index f298b889d6..f6de0a488b 100644
--- a/backend/open_webui/models/config.py
+++ b/backend/open_webui/models/config.py
@@ -98,7 +98,7 @@ def _json_value(value: Any) -> Any:
return jsonable_encoder(value)
-# ── Model ────────────────────────────────────────────────────────────────────
+# Model
class Config(Base):
@@ -114,7 +114,7 @@ class Config(Base):
PERSISTENT_ENABLED: ClassVar[bool] = True
OAUTH_PERSISTENT_ENABLED: ClassVar[bool] = False
- # ── Class methods ────────────────────────────────────────
+ # Class methods
@classmethod
def configure(
diff --git a/backend/open_webui/models/feedbacks.py b/backend/open_webui/models/feedbacks.py
index ca1fe39b38..6bdeb7c06a 100644
--- a/backend/open_webui/models/feedbacks.py
+++ b/backend/open_webui/models/feedbacks.py
@@ -12,9 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-####################
# Feedback DB Schema
-####################
class Feedback(Base):
@@ -44,9 +42,7 @@ class FeedbackModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
-####################
# Forms
-####################
class FeedbackResponse(BaseModel):
diff --git a/backend/open_webui/models/files.py b/backend/open_webui/models/files.py
index d1f61c7cc7..f2eaab3b1a 100644
--- a/backend/open_webui/models/files.py
+++ b/backend/open_webui/models/files.py
@@ -48,7 +48,7 @@ class FileModel(BaseModel):
updated_at: int | None # timestamp in epoch
-# --- metadata structures ---
+# Metadata structures
class FileMeta(BaseModel):
name: str | None = None
content_type: str | None = None
diff --git a/backend/open_webui/models/folders.py b/backend/open_webui/models/folders.py
index 828119440d..7973c9efed 100644
--- a/backend/open_webui/models/folders.py
+++ b/backend/open_webui/models/folders.py
@@ -12,11 +12,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-####################
# Folder DB Schema
# Let every room in this house shelter someone who needs it,
# and let no chamber stand empty while there is want.
-####################
class Folder(Base):
@@ -78,9 +76,7 @@ class SharedFolderResponse(BaseModel):
updated_at: int
-####################
# Forms
-####################
class FolderForm(BaseModel):
diff --git a/backend/open_webui/models/functions.py b/backend/open_webui/models/functions.py
index a06f2bac17..522def658a 100644
--- a/backend/open_webui/models/functions.py
+++ b/backend/open_webui/models/functions.py
@@ -59,7 +59,7 @@ class FunctionModel(BaseModel):
model_config = ConfigDict(from_attributes=True) # allows ORM model binding
-# --- form / schema definitions ---
+# Form / schema definitions
class FunctionWithValvesModel(BaseModel):
version_id: str | None = None
id: str
@@ -77,9 +77,7 @@ class FunctionWithValvesModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
-####################
# Forms
-####################
class FunctionResponse(BaseModel):
diff --git a/backend/open_webui/models/groups.py b/backend/open_webui/models/groups.py
index 7d477f1836..2552b3c6e7 100644
--- a/backend/open_webui/models/groups.py
+++ b/backend/open_webui/models/groups.py
@@ -30,11 +30,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-####################
# UserGroup DB Schema
-# Let none who belong to this house be turned away,
-# and let the covenant hold for every member.
-####################
class Group(Base):
@@ -102,9 +98,7 @@ class GroupMemberModel(BaseModel):
updated_at: Optional[int] = None # timestamp in epoch
-####################
# Forms
-####################
class GroupResponse(GroupModel):
diff --git a/backend/open_webui/models/knowledge.py b/backend/open_webui/models/knowledge.py
index b053344bc9..de3297d6af 100644
--- a/backend/open_webui/models/knowledge.py
+++ b/backend/open_webui/models/knowledge.py
@@ -3,9 +3,12 @@ import time
import uuid
from typing import Optional
+from open_webui.models.notifications import emit_changes
from open_webui.config import RAG_FILE_CONTENT_SEARCH_MAX_CHARS
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, JSONField, get_async_db_context
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
+from open_webui.models.config import Config
from open_webui.models.files import (
File,
FileMetadataResponse,
@@ -38,11 +41,9 @@ log = logging.getLogger(__name__)
# Columns the knowledge base list may be ordered by; anything else falls back to the default.
KNOWLEDGE_SORTABLE_FIELDS = {'name', 'created_at', 'updated_at'}
-####################
# Knowledge DB Schema
# Let what was gathered here outlast the one who gathered it,
# and still teach when the builder is gone.
-####################
class Knowledge(Base):
@@ -146,9 +147,7 @@ class KnowledgeDirectoryForm(BaseModel):
parent_id: Optional[str] = None
-####################
# Forms
-####################
class KnowledgeUserModel(KnowledgeModel):
user: Optional[UserResponse] = None
file_count: int | None = None
@@ -162,10 +161,16 @@ class KnowledgeUserResponse(KnowledgeUserModel):
pass
+class KnowledgeMeta(BaseModel):
+ max_file_count: int | None = Field(default=None, gt=0)
+ max_file_size: int | None = Field(default=None, gt=0)
+
+
class KnowledgeForm(BaseModel):
name: str
description: str
access_grants: Optional[list[dict]] = None
+ meta: KnowledgeMeta | None = None
class FileUserResponse(FileModelResponse):
@@ -209,7 +214,8 @@ class KnowledgeTable:
async with get_async_db_context(db) as db:
knowledge = KnowledgeModel(
**{
- **form_data.model_dump(exclude={'access_grants'}),
+ **form_data.model_dump(exclude={'access_grants', 'meta'}),
+ 'meta': form_data.meta.model_dump() if form_data.meta else None,
'id': str(uuid.uuid4()),
'user_id': user_id,
'created_at': int(time.time()),
@@ -544,12 +550,12 @@ class KnowledgeTable:
.filter(KnowledgeFile.knowledge_id == knowledge_id)
)
- # Filter by directory_id (None = root level)
+ # Omit directory_id to include all directories; supply it to restrict the listing.
directory_id = filter.get('directory_id') if filter else None
if directory_id:
stmt = stmt.filter(KnowledgeFile.directory_id == directory_id)
elif filter and 'directory_id' in filter:
- # Explicit None = root level only
+ # A supplied but falsy directory_id selects root-level files only.
stmt = stmt.filter(KnowledgeFile.directory_id.is_(None))
# Default sort: updated_at descending
@@ -671,6 +677,37 @@ class KnowledgeTable:
except Exception:
return []
+ async def get_file_limits(self, meta: dict | None) -> dict[str, int | None]:
+ local = meta or {}
+ counts = [
+ int(value) for value in (await Config.get('knowledge.max_file_count'), local.get('max_file_count')) if value
+ ]
+ sizes = [
+ int(value) for value in (await Config.get('knowledge.max_file_size'), local.get('max_file_size')) if value
+ ]
+ return {'max_file_count': min(counts, default=None), 'max_file_size': min(sizes, default=None)}
+
+ async def get_file_count_by_id(
+ self,
+ knowledge_id: str,
+ include_pending: bool = False,
+ exclude_file_ids: list[str] | None = None,
+ db: Optional[AsyncSession] = None,
+ ) -> int:
+ async with get_async_db_context(db) as db:
+ linked = select(KnowledgeFile.file_id.label('file_id')).where(KnowledgeFile.knowledge_id == knowledge_id)
+ if include_pending:
+ pending = select(File.id.label('file_id')).where(
+ File.meta['data']['knowledge_id'].as_string() == knowledge_id,
+ File.data['status'].as_string().in_(['pending', 'processing']),
+ )
+ linked = linked.union(pending)
+ files = linked.subquery()
+ stmt = select(func.count()).select_from(files)
+ if exclude_file_ids:
+ stmt = stmt.where(files.c.file_id.notin_(exclude_file_ids))
+ return (await db.execute(stmt)).scalar_one()
+
async def add_file_to_knowledge_by_id(
self,
knowledge_id: str,
@@ -679,7 +716,27 @@ class KnowledgeTable:
directory_id: Optional[str] = None,
db: Optional[AsyncSession] = None,
) -> Optional[KnowledgeFileModel]:
+ global_limit = await Config.get('knowledge.max_file_count')
async with get_async_db_context(db) as db:
+ # Read the local limit under the same write lock as count + insert.
+ await db.execute(
+ update(Knowledge).where(Knowledge.id == knowledge_id).values(updated_at=Knowledge.updated_at)
+ )
+ meta = await db.scalar(select(Knowledge.meta).where(Knowledge.id == knowledge_id))
+ local_limit = (meta or {}).get('max_file_count')
+ limit = min((int(value) for value in (global_limit, local_limit) if value), default=None)
+ if limit is not None:
+ existing = await db.scalar(select(KnowledgeFile).filter_by(knowledge_id=knowledge_id, file_id=file_id))
+ if existing:
+ await db.commit()
+ # Preserve duplicate-insert semantics; callers must not release another request's slot.
+ return None
+ count = await db.scalar(
+ select(func.count()).select_from(KnowledgeFile).where(KnowledgeFile.knowledge_id == knowledge_id)
+ )
+ if count >= int(limit):
+ await db.rollback()
+ raise ValueError(f'Knowledge base file limit exceeded ({limit} files maximum).')
knowledge_file = KnowledgeFileModel(
**{
'id': str(uuid.uuid4()),
@@ -702,6 +759,7 @@ class KnowledgeTable:
else:
return None
except Exception:
+ await db.rollback()
return None
async def has_file(self, knowledge_id: str, file_id: str, db: Optional[AsyncSession] = None) -> bool:
@@ -758,11 +816,15 @@ class KnowledgeTable:
) -> Optional[KnowledgeModel]:
try:
async with get_async_db_context(db) as db:
+ values = form_data.model_dump(exclude={'access_grants', 'meta'})
+ if form_data.meta is not None:
+ meta = await db.scalar(select(Knowledge.meta).where(Knowledge.id == id)) or {}
+ values['meta'] = {**meta, **form_data.meta.model_dump(exclude_unset=True)}
await db.execute(
update(Knowledge)
.filter_by(id=id)
.values(
- **form_data.model_dump(exclude={'access_grants'}),
+ **values,
updated_at=int(time.time()),
)
)
@@ -795,8 +857,10 @@ class KnowledgeTable:
try:
async with get_async_db_context(db) as db:
await AccessGrants.revoke_all_access('knowledge', id, db=db)
+ recipients = await delete_resource_comments('knowledge', [id], db=db)
await db.execute(delete(Knowledge).filter_by(id=id))
await db.commit()
+ await emit_changes(recipients)
return True
except Exception:
return False
@@ -808,14 +872,16 @@ class KnowledgeTable:
knowledge_ids = [row[0] for row in result.all()]
for knowledge_id in knowledge_ids:
await AccessGrants.revoke_all_access('knowledge', knowledge_id, db=db)
+ recipients = await delete_resource_comments('knowledge', knowledge_ids, db=db)
await db.execute(delete(Knowledge))
await db.commit()
+ await emit_changes(recipients)
return True
except Exception:
return False
- # ── Directory CRUD ────────────────────────────────────────────────
+ # Directory CRUD
async def create_directory(
self,
diff --git a/backend/open_webui/models/messages.py b/backend/open_webui/models/messages.py
index b6e04bb973..0ba78c2eb2 100644
--- a/backend/open_webui/models/messages.py
+++ b/backend/open_webui/models/messages.py
@@ -2,6 +2,7 @@ import time
import uuid
from typing import Optional
+from open_webui.models.notifications import emit_changes
from open_webui.internal.db import Base, JSONField, get_async_db_context
from open_webui.models.channels import ChannelMember, Channels
from open_webui.models.tags import Tag, TagModel, Tags
@@ -11,9 +12,7 @@ from sqlalchemy import JSON, BigInteger, Boolean, Column, String, Text, and_, de
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.sql import exists
-####################
# Message DB Schema
-####################
class MessageReaction(Base):
@@ -88,9 +87,7 @@ class MessageModel(BaseModel):
return str(self.updated_at)
-####################
# Forms
-####################
class MessageForm(BaseModel):
@@ -156,6 +153,10 @@ class MessageTable:
form_data: MessageForm,
channel_id: str,
user_id: str,
+ *,
+ request=None,
+ event_actor=None,
+ event_source='api',
db: Optional[AsyncSession] = None,
) -> Optional[MessageModel]:
async with get_async_db_context(db) as db:
@@ -185,8 +186,25 @@ class MessageTable:
db.add(result)
from open_webui.utils.apps import publish_app_message_event
+ from open_webui.events import EVENTS, build_event, publish_event
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+ await db.flush()
+ event = build_event(
+ request,
+ EVENTS.MESSAGE_CREATED,
+ actor=event_actor or {'id': user_id},
+ subject_id=result.id,
+ source=event_source,
+ data={'channel_id': channel_id, 'content_preview': result.content[:300]},
+ event_id=f'message:{result.id}:created',
+ )
+ recipients = await consume_event(event, db=db)
await db.commit()
+ await emit_changes(recipients)
+ if request is not None:
+ await publish_event(request, event)
await db.refresh(result)
await publish_app_message_event(result, 'channel.message.created')
return MessageModel.model_validate(result) if result else None
@@ -209,7 +227,21 @@ class MessageTable:
updated_at=now,
)
db.add(message)
+ from open_webui.events import EVENTS, build_event
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+
+ await db.flush()
+ event = build_event(
+ None,
+ EVENTS.MESSAGE_CREATED,
+ subject_id=message.id,
+ actor={'id': app_id, 'type': 'app'},
+ event_id=f'message:{message.id}:created',
+ )
+ recipients = await consume_event(event, db=db)
await db.commit()
+ await emit_changes(recipients)
from open_webui.utils.apps import publish_app_message_event
await publish_app_message_event(message, 'channel.message.created')
@@ -703,8 +735,14 @@ class MessageTable:
from open_webui.utils.apps import publish_app_message_event
messages = (await db.scalars(select(Message).filter_by(parent_id=id))).all()
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(
+ object_type='message', object_ids=select(Message.id).where(Message.parent_id == id), db=db
+ )
await db.execute(delete(Message).filter_by(parent_id=id))
await db.commit()
+ await emit_changes(recipients)
for message in messages:
await publish_app_message_event(message, 'channel.message.deleted')
return True
@@ -714,12 +752,16 @@ class MessageTable:
from open_webui.utils.apps import publish_app_message_event
message = await db.get(Message, id)
+ from open_webui.models.notifications import delete_notifications
+
+ recipients = await delete_notifications(object_type='message', object_ids=[id], db=db)
await db.execute(delete(Message).filter_by(id=id))
# Delete all reactions to this message
await db.execute(delete(MessageReaction).filter_by(message_id=id))
await db.commit()
+ await emit_changes(recipients)
if message:
await publish_app_message_event(message, 'channel.message.deleted')
return True
diff --git a/backend/open_webui/models/models.py b/backend/open_webui/models/models.py
index 91c0e85461..3ceae31be0 100755
--- a/backend/open_webui/models/models.py
+++ b/backend/open_webui/models/models.py
@@ -7,6 +7,8 @@ from copy import deepcopy
from typing import Annotated, Any, Literal
from fastapi import HTTPException
+from open_webui.models.notifications import emit_changes
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, JSONField, get_async_db_context
from open_webui.models.access_grants import AccessGrant, AccessGrantModel, AccessGrants
from open_webui.models.groups import Groups
@@ -65,7 +67,7 @@ def strip_extracted_content_from_model_knowledge(knowledge: Any) -> Any:
return sanitized
-# --- Models DB Schema ---
+# Models DB schema
ModelControlKey = Annotated[str, Field(pattern=re.compile(r'^(?!(?:constructor|prototype)\Z)[a-zA-Z][a-zA-Z0-9_-]*\Z'))]
@@ -108,6 +110,10 @@ class ModelVoice(BaseModel):
voice: str | None = Field(default=None, min_length=1, max_length=200, pattern=r'^\S+$')
+class ModelSubagents(BaseModel):
+ model_ids: list[str] = Field(default_factory=list)
+
+
class ModelAvatarAnimation(BaseModel):
model_config = ConfigDict(extra='forbid')
file_id: str = Field(pattern=r'^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$')
@@ -149,6 +155,7 @@ class ModelMeta(BaseModel):
i18n: dict[str, Any] | None = None
capabilities: dict | None = None
knowledge: list[Any] | None = None
+ subagents: ModelSubagents | None = None
voice: ModelVoice | None = None
voice_avatar: ModelVoiceAvatar | None = None
@@ -714,17 +721,20 @@ class ModelsTable:
return None
async def _delete_models(self, session, ids):
+ recipients = await delete_resource_comments('model', ids, db=session)
await session.execute(
delete(AccessGrant).where(AccessGrant.resource_type == 'model', AccessGrant.resource_id.in_(ids))
)
await session.execute(delete(ModelHistory).where(ModelHistory.model_id.in_(ids)))
await session.execute(delete(Model).where(Model.id.in_(ids)))
+ return recipients
async def delete_model_by_id(self, id: str, db: AsyncSession | None = None) -> bool:
async with get_async_db_context(db) as session:
try:
- await self._delete_models(session, [id])
+ recipients = await self._delete_models(session, [id])
await session.commit()
+ await emit_changes(recipients)
return True
except Exception:
await session.rollback()
@@ -734,8 +744,9 @@ class ModelsTable:
async with get_async_db_context(db) as session:
try:
ids = (await session.execute(select(Model.id))).scalars().all()
- await self._delete_models(session, ids)
+ recipients = await self._delete_models(session, ids)
await session.commit()
+ await emit_changes(recipients)
return True
except Exception:
await session.rollback()
@@ -752,8 +763,9 @@ class ModelsTable:
# Imported version IDs are never local history identities.
form = ModelForm(**model.model_dump())
written.append(await self._write_model(session, form, user_id, existing.get(model.id)))
- await self._delete_models(session, existing.keys() - {model.id for model in models})
+ recipients = await self._delete_models(session, existing.keys() - {model.id for model in models})
await session.commit()
+ await emit_changes(recipients)
return [await self._written_model(session, model) for model in written]
except Exception:
await session.rollback()
diff --git a/backend/open_webui/models/notes.py b/backend/open_webui/models/notes.py
index b73457646e..53c87d2e8e 100644
--- a/backend/open_webui/models/notes.py
+++ b/backend/open_webui/models/notes.py
@@ -8,6 +8,8 @@ from typing import Literal, Optional
import markdown
from bs4 import BeautifulSoup
+from open_webui.models.notifications import emit_changes
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, get_async_db_context
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
from open_webui.models.groups import Groups
@@ -384,9 +386,7 @@ def matching_page(data: dict, query: str = '') -> dict:
return pages[0]
-####################
# Note DB Schema
-####################
class Note(Base):
@@ -460,9 +460,7 @@ class PinnedNote(Base):
created_at = Column(BigInteger, nullable=False)
-####################
# Forms
-####################
class NoteForm(BaseModel):
@@ -842,9 +840,11 @@ class NoteTable:
try:
async with get_async_db_context(db) as db:
await AccessGrants.revoke_all_access('note', id, db=db)
+ recipients = await delete_resource_comments('note', [id], db=db)
await db.execute(delete(PinnedNote).filter(PinnedNote.note_id == id))
await db.execute(delete(Note).filter(Note.id == id))
await db.commit()
+ await emit_changes(recipients)
return True
except Exception:
return False
diff --git a/backend/open_webui/models/notifications.py b/backend/open_webui/models/notifications.py
new file mode 100644
index 0000000000..80f5f83066
--- /dev/null
+++ b/backend/open_webui/models/notifications.py
@@ -0,0 +1,162 @@
+"""Persistent, per-recipient inbox activity. Writers never commit the caller's transaction."""
+
+import logging
+import time
+from uuid import uuid4
+
+from open_webui.internal.db import Base
+from pydantic import BaseModel, ConfigDict, Field
+from sqlalchemy import JSON, BigInteger, CheckConstraint, Column, Index, Text, UniqueConstraint, delete, update
+
+log = logging.getLogger(__name__)
+
+
+class Notification(Base):
+ __tablename__ = 'notification'
+ id = Column(Text, primary_key=True)
+ user_id = Column(Text, nullable=False)
+ event_type = Column(Text, nullable=False)
+ event_key = Column(Text, nullable=False)
+ actor_type = Column(Text, nullable=False)
+ actor_id = Column(Text, nullable=True)
+ resource_type = Column(Text, nullable=True)
+ resource_id = Column(Text, nullable=True)
+ object_type = Column(Text, nullable=True)
+ object_id = Column(Text, nullable=True)
+ data = Column(JSON, nullable=False)
+ seen_at = Column(BigInteger, nullable=True)
+ read_at = Column(BigInteger, nullable=True)
+ created_at = Column(BigInteger, nullable=False)
+ updated_at = Column(BigInteger, nullable=False)
+ __table_args__ = (
+ UniqueConstraint('user_id', 'event_key', name='uq_notification_occurrence'),
+ CheckConstraint('(resource_type IS NULL) = (resource_id IS NULL)', name='ck_notification_resource'),
+ CheckConstraint('(object_type IS NULL) = (object_id IS NULL)', name='ck_notification_object'),
+ CheckConstraint("actor_type IN ('user', 'system')", name='ck_notification_actor'),
+ Index('ix_notification_user_created', 'user_id', 'created_at', 'id'),
+ Index(
+ 'ix_notification_unseen',
+ 'user_id',
+ 'created_at',
+ 'id',
+ sqlite_where=seen_at.is_(None),
+ postgresql_where=seen_at.is_(None),
+ ),
+ Index('ix_notification_resource', 'resource_type', 'resource_id'),
+ Index('ix_notification_object', 'object_type', 'object_id'),
+ )
+
+
+class NotificationData(BaseModel):
+ model_config = ConfigDict(extra='forbid')
+
+
+class ReminderData(NotificationData):
+ start_at: int
+
+
+class SystemData(NotificationData):
+ message: str = Field(min_length=1, max_length=2000)
+
+
+DATA_TYPES = {
+ 'comment.created': NotificationData,
+ 'comment.replied': NotificationData,
+ 'comment.mentioned': NotificationData,
+ 'channel.mentioned': NotificationData,
+ 'channel.replied': NotificationData,
+ 'calendar.alert': ReminderData,
+ 'automation.run_failed': NotificationData,
+ 'system.announcement': SystemData,
+}
+
+
+async def emit_changes(user_ids):
+ from open_webui.socket.main import sio
+
+ for user_id in user_ids:
+ try:
+ await sio.emit('notifications:changed', {}, room=f'user:{user_id}')
+ except Exception:
+ log.exception('Could not broadcast inbox change for %s', user_id)
+
+
+async def insert_notifications(
+ *,
+ recipients,
+ event_key,
+ actor_id=None,
+ resource_type=None,
+ resource_id=None,
+ object_type=None,
+ object_id=None,
+ data=None,
+ db,
+):
+ """recipients maps user IDs to event types; the producer chooses the strongest reason."""
+ from open_webui.models.config import Config
+ from open_webui.utils.inbox import validate_source, eligible_recipients
+
+ if not recipients or not await Config.get('notifications.enable'):
+ return set()
+ if not event_key or len(event_key) > 512:
+ raise ValueError('Invalid notification occurrence')
+ payloads = {kind: DATA_TYPES[kind].model_validate(data or {}).model_dump() for kind in set(recipients.values())}
+ for event_type in payloads:
+ await validate_source(event_type, resource_type, resource_id, object_type, object_id, db=db)
+ recipients = await eligible_recipients(recipients, resource_type, resource_id, actor_id, db=db)
+ if not recipients:
+ return set()
+ dialect = db.get_bind().dialect.name
+ if dialect == 'postgresql':
+ from sqlalchemy.dialects.postgresql import insert
+ elif dialect == 'sqlite':
+ from sqlalchemy.dialects.sqlite import insert
+ else:
+ raise ValueError('Inbox requires SQLite or PostgreSQL')
+ try:
+ now = time.time_ns()
+ result = await db.execute(
+ insert(Notification)
+ .on_conflict_do_nothing(index_elements=['user_id', 'event_key'])
+ .returning(Notification.user_id),
+ [
+ dict(
+ id=str(uuid4()),
+ user_id=user_id,
+ event_type=event_type,
+ event_key=event_key,
+ actor_type='user' if actor_id else 'system',
+ actor_id=actor_id,
+ resource_type=resource_type,
+ resource_id=resource_id,
+ object_type=object_type,
+ object_id=object_id,
+ data=payloads[event_type],
+ created_at=now,
+ updated_at=now,
+ )
+ for user_id, event_type in recipients.items()
+ ],
+ )
+ return set(result.scalars().all())
+ except Exception:
+ log.exception('Inbox insertion failed for occurrence %s', event_key)
+ raise
+
+
+async def delete_notifications(*, resource_type=None, resource_ids=None, object_type=None, object_ids=None, db):
+ condition = (
+ (Notification.resource_type == resource_type) & Notification.resource_id.in_(resource_ids)
+ if resource_type
+ else (Notification.object_type == object_type) & Notification.object_id.in_(object_ids)
+ )
+ recipients = (
+ (await db.execute(delete(Notification).where(condition).returning(Notification.user_id))).scalars().all()
+ )
+ return set(recipients)
+
+
+async def delete_user_notifications(user_id, db):
+ await db.execute(delete(Notification).where(Notification.user_id == user_id))
+ await db.execute(update(Notification).where(Notification.actor_id == user_id).values(actor_id=None))
diff --git a/backend/open_webui/models/oauth_sessions.py b/backend/open_webui/models/oauth_sessions.py
index 25a50ced55..13d5d773a9 100644
--- a/backend/open_webui/models/oauth_sessions.py
+++ b/backend/open_webui/models/oauth_sessions.py
@@ -15,9 +15,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-####################
-# DB MODEL
-####################
+# DB model
class OAuthSession(Base):
@@ -51,9 +49,7 @@ class OAuthSessionModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
-####################
# Forms
-####################
class OAuthSessionResponse(BaseModel):
diff --git a/backend/open_webui/models/prompt_history.py b/backend/open_webui/models/prompt_history.py
index 78c3330b4a..60dcb74145 100644
--- a/backend/open_webui/models/prompt_history.py
+++ b/backend/open_webui/models/prompt_history.py
@@ -11,9 +11,7 @@ from pydantic import BaseModel, ConfigDict
from sqlalchemy import JSON, BigInteger, Column, Index, Text, delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
-####################
# PromptHistory DB Schema
-####################
class PromptHistory(Base):
diff --git a/backend/open_webui/models/prompts.py b/backend/open_webui/models/prompts.py
index 2c50b74d7e..d7252d665e 100644
--- a/backend/open_webui/models/prompts.py
+++ b/backend/open_webui/models/prompts.py
@@ -9,6 +9,8 @@ from typing import Optional
log = logging.getLogger(__name__)
+from open_webui.models.notifications import emit_changes
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, JSONField, get_async_db_context
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
from open_webui.models.groups import Groups
@@ -57,9 +59,8 @@ class PromptModel(BaseModel):
model_config = ConfigDict(from_attributes=True) # allows ORM model binding
-# --- form / schema definitions ---
+# Form / schema definitions
# Forms
-####################
class PromptUserResponse(PromptModel):
@@ -194,7 +195,7 @@ class PromptsTable:
if match is None:
return
return await self._to_prompt_model(match, db=session)
- # --- context manager always returns above ---
+ # Context manager always returns above
return
async def get_prompts(self, db: AsyncSession | None = None) -> list[PromptUserResponse]:
@@ -644,8 +645,10 @@ class PromptsTable:
await PromptHistories.delete_history_by_prompt_id(prompt.id, db=session)
await AccessGrants.revoke_all_access('prompt', prompt.id, db=session)
+ recipients = await delete_resource_comments('prompt', [prompt.id], db=session)
await session.delete(prompt)
await session.commit()
+ await emit_changes(recipients)
return True
return False
except Exception:
@@ -661,8 +664,10 @@ class PromptsTable:
await PromptHistories.delete_history_by_prompt_id(prompt.id, db=session)
await AccessGrants.revoke_all_access('prompt', prompt.id, db=session)
+ recipients = await delete_resource_comments('prompt', [prompt.id], db=session)
await session.delete(prompt)
await session.commit()
+ await emit_changes(recipients)
return True
return False
except Exception as err:
diff --git a/backend/open_webui/models/shared_chats.py b/backend/open_webui/models/shared_chats.py
index 8959d6c771..cd88eef241 100644
--- a/backend/open_webui/models/shared_chats.py
+++ b/backend/open_webui/models/shared_chats.py
@@ -17,9 +17,7 @@ class ShareChatForm(BaseModel):
share_mode: ChatShareMode = None
-####################
# SharedChat DB Schema
-####################
class SharedChat(Base):
@@ -59,9 +57,7 @@ class SharedChatResponse(BaseModel):
created_at: int
-####################
# Table Operations
-####################
class SharedChatsTable:
diff --git a/backend/open_webui/models/skills.py b/backend/open_webui/models/skills.py
index ffe58336e2..9a3f17952f 100644
--- a/backend/open_webui/models/skills.py
+++ b/backend/open_webui/models/skills.py
@@ -3,6 +3,8 @@ import time
from typing import Optional
from fastapi import HTTPException
+from open_webui.models.notifications import emit_changes
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, get_async_db_context
from open_webui.models.access_grants import AccessGrant, AccessGrantModel, AccessGrants
from open_webui.models.groups import Groups
@@ -16,9 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-####################
# Skills DB Schema
-####################
class Skill(Base):
@@ -61,9 +61,7 @@ class SkillModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
-####################
# Forms
-####################
class SkillUserModel(SkillModel):
@@ -499,10 +497,12 @@ class SkillsTable:
async def delete_skill_by_id(self, id: str, db: Optional[AsyncSession] = None) -> bool:
try:
async with get_async_db_context(db) as db:
+ recipients = await delete_resource_comments('skill', [id], db=db)
await db.execute(delete(AccessGrant).filter_by(resource_type='skill', resource_id=id))
await db.execute(delete(SkillHistory).filter_by(skill_id=id))
await db.execute(delete(Skill).filter_by(id=id))
await db.commit()
+ await emit_changes(recipients)
return True
except Exception:
diff --git a/backend/open_webui/models/tags.py b/backend/open_webui/models/tags.py
index 9f24d274bb..2db4d0c8af 100644
--- a/backend/open_webui/models/tags.py
+++ b/backend/open_webui/models/tags.py
@@ -39,9 +39,8 @@ class TagModel(BaseModel):
model_config = ConfigDict(from_attributes=True) # allows ORM model binding
-# --- tag schema forms ---
+# Tag schema forms
# Forms
-####################
class TagChatIdForm(BaseModel):
diff --git a/backend/open_webui/models/tools.py b/backend/open_webui/models/tools.py
index 73ed8f0991..289420c8d9 100644
--- a/backend/open_webui/models/tools.py
+++ b/backend/open_webui/models/tools.py
@@ -8,6 +8,8 @@ import time
from fastapi import HTTPException
# local imports
+from open_webui.models.notifications import emit_changes
+from open_webui.models.comments import delete_resource_comments
from open_webui.internal.db import Base, JSONField, get_async_db_context
from open_webui.models.access_grants import AccessGrant, AccessGrantModel, AccessGrants
from open_webui.models.groups import Groups
@@ -15,7 +17,7 @@ from open_webui.models.tool_history import ToolHistories, ToolHistory, tool_snap
from open_webui.models.users import UserResponse, Users
from open_webui.utils.valves import decrypt_valves, encrypt_valves, validate_valves
from pydantic import BaseModel, ConfigDict, Field
-from sqlalchemy import BigInteger, Column, String, Text, delete, select, update
+from sqlalchemy import BigInteger, Boolean, Column, String, Text, delete, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
@@ -32,6 +34,7 @@ class Tool(Base): # database table definition
specs = Column(JSONField) # OpenAPI-style function specs
meta = Column(JSONField) # description, manifest, etc.
valves = Column(JSONField) # admin-configurable runtime parameters
+ is_active = Column(Boolean, nullable=False, default=True, server_default=true())
updated_at = Column(BigInteger, nullable=False) # modification timestamp
created_at = Column(BigInteger, index=True) # creation timestamp
@@ -54,6 +57,7 @@ class ToolModel(BaseModel):
content: str | None = None
specs: list[dict]
meta: ToolMeta
+ is_active: bool = True
access_grants: list[AccessGrantModel] = Field(default_factory=list)
updated_at: int # timestamp in epoch
@@ -62,9 +66,8 @@ class ToolModel(BaseModel):
model_config = ConfigDict(from_attributes=True) # enables ORM mapping
-# --- tool request forms ---
+# Tool request forms
# Forms
-####################
class ToolUserModel(ToolModel):
@@ -77,6 +80,7 @@ class ToolResponse(BaseModel):
user_id: str | None = None # may be null for legacy/malformed records
name: str
meta: ToolMeta
+ is_active: bool = True
access_grants: list[AccessGrantModel] = Field(default_factory=list)
updated_at: int # timestamp in epoch
created_at: int # timestamp in epoch
@@ -215,6 +219,26 @@ class ToolsTable:
for tool in tools
}
+ async def is_tool_active(self, id: str, db: AsyncSession | None = None) -> bool:
+ async with get_async_db_context(db) as session:
+ return (await session.scalar(select(Tool.is_active).where(Tool.id == id))) is True
+
+ async def toggle_tool_by_id(self, id: str, db: AsyncSession | None = None) -> ToolModel | None:
+ async with get_async_db_context(db) as session:
+ try:
+ tool = await self._lock_tool(session, id)
+ if tool is None:
+ return None
+ tool.is_active = not tool.is_active
+ tool.updated_at = int(time.time())
+ await session.flush()
+ result = await self._to_tool_model(tool, db=session)
+ await session.commit()
+ return result
+ except Exception:
+ await session.rollback()
+ raise
+
async def get_tools(
self,
defer_content: bool = False,
@@ -222,6 +246,7 @@ class ToolsTable:
user_id: str | None = None,
user_group_ids: set[str] | None = None,
permission: str = 'read',
+ active_only: bool = False,
) -> list[ToolUserModel]:
async with get_async_db_context(db) as db:
# Skip Tool.content (plugin source, potentially large) via a
@@ -234,6 +259,7 @@ class ToolsTable:
Tool.name,
Tool.specs,
Tool.meta,
+ Tool.is_active,
Tool.updated_at,
Tool.created_at,
)
@@ -241,6 +267,9 @@ class ToolsTable:
else select(Tool)
).order_by(Tool.updated_at.desc())
+ if active_only:
+ stmt = stmt.where(Tool.is_active.is_(True))
+
if user_id is not None:
if user_group_ids is None:
user_group_ids = {
@@ -396,11 +425,13 @@ class ToolsTable:
async def delete_tool_by_id(self, id, db=None):
async with get_async_db_context(db) as session:
try:
+ recipients = await delete_resource_comments('tool', [id], db=session)
await self._lock_tool(session, id)
await session.execute(delete(AccessGrant).filter_by(resource_type='tool', resource_id=id))
await session.execute(delete(ToolHistory).filter_by(tool_id=id))
await session.execute(delete(Tool).filter_by(id=id))
await session.commit()
+ await emit_changes(recipients)
return True
except Exception:
await session.rollback()
diff --git a/backend/open_webui/models/users.py b/backend/open_webui/models/users.py
index 0aa6a6f167..28c0f49415 100644
--- a/backend/open_webui/models/users.py
+++ b/backend/open_webui/models/users.py
@@ -35,11 +35,9 @@ from sqlalchemy import (
)
from sqlalchemy.ext.asyncio import AsyncSession
-####################
# User DB Schema
-# Hallowed be the columns defined here, for they hold the
-# daily bread of every session. Let none go hungry.
-####################
+# Let every name entrusted to these records find its place,
+# and let no one be forgotten among the many.
class InterfaceTitleSettings(BaseModel):
@@ -217,7 +215,7 @@ class UserModel(BaseModel):
)
# validation schema logic
- # --- model validators ---
+ # Model validators
@model_validator(mode='after')
def _ensure_profile_image(self) -> 'UserModel':
"""Assign a generated avatar when no profile image is provided."""
@@ -262,9 +260,7 @@ class ApiKeyModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
-####################
# Forms
-####################
class UpdateProfileForm(BaseModel):
@@ -410,7 +406,7 @@ class UsersTable:
return user if result else None
# database read methods
- # --- read / lookup operations ---
+ # Read / lookup operations
async def get_user_by_id(
self,
id: str,
@@ -448,10 +444,10 @@ class UsersTable:
if match is None:
return
return UserModel.model_validate(match)
- # --- context manager above always returns ---
+ # Context manager above always returns
return
- # --- oauth & integrations ---
+ # OAuth & integrations
async def get_user_by_oauth_sub(
self,
provider: str,
@@ -858,6 +854,12 @@ class UsersTable:
deleted_chats = await Chats.delete_chats_by_user_id(id, db=session)
if not deleted_chats:
return False # chats deletion failed
+ from open_webui.models.comments import cleanup_comments_for_deleted_user
+
+ await cleanup_comments_for_deleted_user(session, id)
+ from open_webui.models.notifications import delete_user_notifications
+
+ await delete_user_notifications(id, db=session)
await session.execute(delete(User).where(User.id == id))
await session.commit()
return True
diff --git a/backend/open_webui/retrieval/loaders/main.py b/backend/open_webui/retrieval/loaders/main.py
index 971b124a9e..6e1f9fc047 100644
--- a/backend/open_webui/retrieval/loaders/main.py
+++ b/backend/open_webui/retrieval/loaders/main.py
@@ -94,15 +94,6 @@ known_source_ext = [
'svg',
]
-known_archive_ext = {'docx', 'epub', 'odt', 'pptx', 'xlsx'}
-known_archive_content_types = {
- 'application/epub+zip',
- 'application/vnd.oasis.opendocument.text',
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
-}
-
class ExcelLoader:
"""Fallback Excel loader using pandas when unstructured is not installed."""
@@ -538,7 +529,7 @@ class Loader:
def _get_loader(self, filename: str, file_content_type: str, file_path: str):
file_ext = filename.split('.')[-1].lower()
- if file_ext in known_archive_ext or file_content_type in known_archive_content_types:
+ if zipfile.is_zipfile(file_path):
max_file_size = self.config['rag.file.max_size']
try:
max_file_size_bytes = int(max_file_size) * 1024 * 1024 if max_file_size else 100 * 1024 * 1024
diff --git a/backend/open_webui/retrieval/loaders/mistral.py b/backend/open_webui/retrieval/loaders/mistral.py
index a5dbebfff1..efa973f8e8 100644
--- a/backend/open_webui/retrieval/loaders/mistral.py
+++ b/backend/open_webui/retrieval/loaders/mistral.py
@@ -65,7 +65,7 @@ class MistralLoader:
self.params = params or {}
self.user = user
- # PERFORMANCE OPTIMIZATION: Differentiated timeouts for different operations
+ # Use separate timeouts for different operations.
# This prevents long-running OCR operations from affecting quick operations
# and improves user experience by failing fast on operations that should be quick
self.upload_timeout = min(timeout, 120) # Cap upload at 2 minutes - prevents hanging on large files
@@ -73,12 +73,12 @@ class MistralLoader:
self.ocr_timeout = timeout # OCR can take the full timeout - this is the heavy operation
self.cleanup_timeout = 30 # Cleanup should be quick - don't hang on file deletion
- # PERFORMANCE OPTIMIZATION: Pre-compute file info to avoid repeated filesystem calls
+ # Precompute file info to avoid repeated filesystem calls.
# This avoids multiple os.path.basename() and os.path.getsize() calls during processing
self.file_name = os.path.basename(file_path)
self.file_size = os.path.getsize(file_path)
- # ENHANCEMENT: Added User-Agent for better API tracking and debugging
+ # Include User-Agent for API tracking and debugging.
self.headers = {
'Authorization': f'Bearer {self.api_key}',
'User-Agent': 'OpenWebUI-MistralLoader/2.0', # Helps API provider track usage
@@ -161,7 +161,7 @@ class MistralLoader:
if attempt == self.max_retries - 1 or not self._is_retryable_error(e):
raise
- # PERFORMANCE OPTIMIZATION: Exponential backoff with cap
+ # Cap exponential backoff between retries.
# Prevents overwhelming the server while ensuring reasonable retry delays
wait_time = min((2**attempt) + 0.5, 30) # Cap at 30 seconds
log.warning(
@@ -182,7 +182,7 @@ class MistralLoader:
url = f'{self.base_url}/files'
def upload_request():
- # MEMORY OPTIMIZATION: Use context manager to minimize file handle lifetime
+ # Limit the file handle's lifetime with a context manager.
# This ensures the file is closed immediately after reading, reducing memory usage
with open(self.file_path, 'rb') as f:
files = {'file': (self.file_name, f, 'application/pdf')}
diff --git a/backend/open_webui/retrieval/models/colbert.py b/backend/open_webui/retrieval/models/colbert.py
index b388974701..98d63a69d7 100644
--- a/backend/open_webui/retrieval/models/colbert.py
+++ b/backend/open_webui/retrieval/models/colbert.py
@@ -34,10 +34,7 @@ class ColBERT(BaseReranker):
DOCKER = kwargs.get('env') == 'docker'
if DOCKER:
- # This is a workaround for the issue with the docker container
- # where the torch extension is not loaded properly
- # and the following error is thrown:
- # /root/.cache/torch_extensions/py312_cpu/segmented_maxsim_cpp/segmented_maxsim_cpp.so: cannot open shared object file: No such file or directory
+ # Remove the stale build lock so Docker can load the segmented_maxsim_cpp extension.
lock_file = '/root/.cache/torch_extensions/py312_cpu/segmented_maxsim_cpp/lock'
if os.path.exists(lock_file):
diff --git a/backend/open_webui/retrieval/utils.py b/backend/open_webui/retrieval/utils.py
index 24963eafcd..a6ea444e82 100644
--- a/backend/open_webui/retrieval/utils.py
+++ b/backend/open_webui/retrieval/utils.py
@@ -243,12 +243,7 @@ def _get_content_from_url_sync(request, url: str, config: dict):
# Validate URL before making any request (blocks private IPs, non-HTTP, filter list)
validate_url(url)
- # YouTube URLs (including youtu.be short links) should go straight to
- # YoutubeLoader, which uses youtube-transcript-api and never needs the
- # HTTP response body. Probing the URL first is harmful for short URLs:
- # youtu.be returns a 303 redirect with Content-Type: application/binary
- # when allow_redirects=False, causing the binary-content path to run
- # and produce empty docs → HTTP 400.
+ # Send YouTube URLs directly to YoutubeLoader; probing youtu.be can misclassify its 303 as binary.
if is_youtube_url(url):
loader = get_loader(request, url, config)
docs = loader.load()
@@ -814,11 +809,7 @@ async def query_collection_with_hybrid_search(
if native_task_results and all(result is not None for result in native_task_results):
return merge_and_sort_query_results(native_task_results, k=k)
- # Fetch every collection's contents once up front so the
- # per-query/per-document loop below can reuse them. Each fetch
- # offloads to a worker thread, so run them concurrently with
- # `asyncio.gather` instead of awaiting them serially — otherwise
- # latency scales linearly with `len(collection_names)`.
+ # Fetch collections concurrently once, then reuse the results across queries and documents.
log.debug(
'query_collection_with_hybrid_search: prefetching %d collections',
len(collection_names),
diff --git a/backend/open_webui/retrieval/vector/dbs/valkey.py b/backend/open_webui/retrieval/vector/dbs/valkey.py
index c315a0a5fb..b96507c3ec 100644
--- a/backend/open_webui/retrieval/vector/dbs/valkey.py
+++ b/backend/open_webui/retrieval/vector/dbs/valkey.py
@@ -237,7 +237,7 @@ class ValkeyClient(VectorDBBase):
except Exception:
pass
- # ----- version checks ----------------------------------------------------
+ # Version checks
@staticmethod
def _parse_semver(version_str: str) -> tuple[int, int, int] | None:
diff --git a/backend/open_webui/routers/analytics.py b/backend/open_webui/routers/analytics.py
index e455bb596f..6d0f2dd15f 100644
--- a/backend/open_webui/routers/analytics.py
+++ b/backend/open_webui/routers/analytics.py
@@ -20,9 +20,7 @@ log = logging.getLogger(__name__)
router = APIRouter()
-####################
# Response Models
-####################
class ModelAnalyticsEntry(BaseModel):
@@ -51,9 +49,7 @@ class UserAnalyticsResponse(BaseModel):
total: int
-####################
# Endpoints
-####################
@router.get('/models', response_model=ModelAnalyticsResponse)
@@ -283,9 +279,7 @@ async def get_token_usage(
)
-####################
# Model Chats Browser
-####################
class ModelChatEntry(BaseModel):
@@ -344,9 +338,7 @@ async def get_model_chats(
)
-####################
# Model Overview
-####################
class HistoryEntry(BaseModel):
@@ -446,9 +438,7 @@ async def get_model_overview(
return ModelOverviewResponse(history=history, tags=tags)
-####################
# Session Explorer
-####################
def require_session_access(user=Depends(get_admin_user)):
diff --git a/backend/open_webui/routers/apps.py b/backend/open_webui/routers/apps.py
index beb2bb0f82..528b7dd261 100644
--- a/backend/open_webui/routers/apps.py
+++ b/backend/open_webui/routers/apps.py
@@ -38,9 +38,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
router = APIRouter()
-############################
-# GetApps
-############################
+# Get Apps
@router.get('', response_model=list[AppResponse])
@@ -57,9 +55,7 @@ async def get_apps(user=Depends(get_verified_user), db: AsyncSession = Depends(g
]
-############################
-# PreviewAppManifest
-############################
+# Preview App Manifest
@router.post('/manifest/preview', response_model=Manifest)
@@ -96,9 +92,7 @@ async def preview_app_manifest(
) from None
-############################
-# CreateNewApp
-############################
+# Create New App
@router.post('', response_model=AppResponse)
@@ -140,9 +134,7 @@ async def create_new_app(
return get_app_response(app)
-############################
-# GetAppDetailsById
-############################
+# Get App Details By Id
@router.get('/{app_id}', response_model=AppAccessResponse)
@@ -164,9 +156,7 @@ async def get_app_details_by_id(
return result
-############################
-# UpdateAppById
-############################
+# Update App By Id
@router.patch('/{app_id}', response_model=AppResponse)
@@ -207,9 +197,7 @@ async def update_app_by_id(
return get_app_response(app)
-############################
-# ConnectAppById
-############################
+# Connect App By Id
@router.post('/{app_id}/connect', response_model=AppResponse)
@@ -245,9 +233,7 @@ async def connect_app_by_id(
return {**get_app_response(app), 'connection_status': 'connected'}
-############################
-# UninstallAppById
-############################
+# Uninstall App By Id
@router.delete('/{app_id}', response_model=AppResponse)
@@ -257,9 +243,7 @@ async def uninstall_app_by_id(app_id: str, user=Depends(get_admin_user), db: Asy
return get_app_response(app)
-############################
-# CreateAppInteraction
-############################
+# Create App Interaction
@router.post('/{app_id}/interactions')
diff --git a/backend/open_webui/routers/audio/__init__.py b/backend/open_webui/routers/audio/__init__.py
index fda9e11854..8f86d77e5f 100644
--- a/backend/open_webui/routers/audio/__init__.py
+++ b/backend/open_webui/routers/audio/__init__.py
@@ -72,7 +72,7 @@ log = logging.getLogger(__name__)
router = APIRouter()
router.include_router(realtime.router)
-# --- Constants ---
+# Constants
MAX_FILE_SIZE_MB: int = 20
MAX_FILE_SIZE: int = MAX_FILE_SIZE_MB * 1024 * 1024
diff --git a/backend/open_webui/routers/audio/realtime.py b/backend/open_webui/routers/audio/realtime.py
index c9c506eb34..5243cabad5 100644
--- a/backend/open_webui/routers/audio/realtime.py
+++ b/backend/open_webui/routers/audio/realtime.py
@@ -493,7 +493,15 @@ async def realtime_call(ws: WebSocket):
if event == {'type': 'bridge.ping'}:
await ws.send_json({'type': 'bridge.pong'})
continue
- command = protocol.command(event)
+ try:
+ command = protocol.command(event)
+ except (ValueError, TypeError):
+ if not isinstance(event, dict) or event.get('type') != 'conversation.item.truncate':
+ raise
+ await ws.send_json(
+ {'type': 'bridge.error', 'message': 'Invalid audio truncation request', 'fatal': False}
+ )
+ continue
if event['type'] == 'bridge.result':
protocol.requested.add(f'result:{event["call_id"]}')
for item in command if isinstance(command, list) else [command]:
diff --git a/backend/open_webui/routers/auths.py b/backend/open_webui/routers/auths.py
index d9b0d01d52..318d2dc786 100644
--- a/backend/open_webui/routers/auths.py
+++ b/backend/open_webui/routers/auths.py
@@ -19,6 +19,7 @@ from ldap3.utils.dn import parse_dn
from open_webui.config import (
ENABLE_PASSWORD_AUTH,
OAUTH_PROVIDERS,
+ oauth_client_kwargs,
)
from open_webui.constants import ERROR_MESSAGES
from open_webui.env import (
@@ -90,8 +91,8 @@ router = APIRouter(route_class=MfaRoute)
log = logging.getLogger(__name__)
-# Forgive us our failed attempts, as we forgive those
-# who exceed their allotted rate against this gate.
+# Let patience meet those who stumble at the gate,
+# and let those within rest safely through the night.
signin_rate_limiter = RateLimiter(limit=5 * 3, window=60 * 3)
# Best-effort throttle only: there is no caller identity before the provider answers,
# and deployments may derive request.client from proxy headers.
@@ -128,6 +129,8 @@ ADMIN_CONFIG_KEYS = {
'AUTOMATION_MIN_INTERVAL': 'automations.min_interval',
'ENABLE_AUTOMATIONS': 'automations.enable',
'ENABLE_CHANNELS': 'channels.enable',
+ 'ENABLE_COMMENTS': 'comments.enable',
+ 'ENABLE_NOTIFICATIONS': 'notifications.enable',
'ENABLE_ENCRYPTED_CHANNELS': 'channels.encryption.enable',
'ENABLE_APPS': 'apps.enable',
'CHANNEL_MODEL_RESPONSE_MODE': 'channels.model_response_mode',
@@ -240,9 +243,7 @@ async def get_session_user(
return response_data
-############################
# Update Profile
-############################
@router.post('/update/profile', response_model=UserProfileImageResponse)
@@ -273,9 +274,7 @@ async def update_profile(
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
-############################
# Update Timezone
-############################
class UpdateTimezoneForm(BaseModel):
@@ -307,9 +306,7 @@ async def update_timezone(
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
-############################
# Update Password
-############################
@router.post('/update/password', response_model=bool)
@@ -404,9 +401,7 @@ def extract_group_cn_from_dn(group_dn: str) -> str | None:
return None
-############################
# LDAP Authentication
-############################
@router.post('/ldap', response_model=SigninResult)
async def ldap_auth(
request: Request,
@@ -655,9 +650,7 @@ async def ldap_auth(
raise HTTPException(400, detail='LDAP authentication failed.')
-############################
-# SignIn
-############################
+# Sign In
@router.post('/signin', response_model=SigninResult)
@@ -788,9 +781,7 @@ async def signin(
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
-############################
-# SignUp
-############################
+# Sign Up
async def signup_handler(
@@ -1014,9 +1005,7 @@ async def signout(request: Request, response: Response, db: AsyncSession = Depen
return JSONResponse(status_code=200, content={'status': True}, headers=response.headers)
-############################
# OAuth Session Management
-############################
@router.delete('/oauth/sessions/{provider:path}', response_model=bool)
@@ -1048,9 +1037,7 @@ async def delete_oauth_session_by_provider(
return True
-############################
-# AddUser
-############################
+# Add User
@router.post('/add', response_model=AddUserResponse, response_model_exclude_none=True)
@@ -1123,9 +1110,7 @@ async def add_user(
raise HTTPException(500, detail='An internal error occurred while adding the user.')
-############################
-# GetAdminDetails
-############################
+# Get Admin Details
@router.get('/admin/details')
@@ -1156,9 +1141,7 @@ async def get_admin_details(
raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
-############################
-# ToggleSignUp
-############################
+# Toggle Sign Up
@router.get('/admin/config')
@@ -1188,6 +1171,8 @@ class AdminConfig(MfaConfigForm):
AUTOMATION_MIN_INTERVAL: int | str | None = None
ENABLE_AUTOMATIONS: bool
ENABLE_CHANNELS: bool
+ ENABLE_COMMENTS: bool = False
+ ENABLE_NOTIFICATIONS: bool = True
ENABLE_ENCRYPTED_CHANNELS: bool = False
ENABLE_APPS: bool = False
CHANNEL_MODEL_RESPONSE_MODE: str = 'thread'
@@ -1241,6 +1226,10 @@ async def update_admin_config(request: Request, form_data: AdminConfig, user=Dep
updates.pop('ui.enable_login_form', None)
if 'ENABLE_ENCRYPTED_CHANNELS' not in form_data.model_fields_set:
updates.pop('channels.encryption.enable', None)
+ if 'ENABLE_COMMENTS' not in form_data.model_fields_set:
+ updates.pop('comments.enable', None)
+ if 'ENABLE_NOTIFICATIONS' not in form_data.model_fields_set:
+ updates.pop('notifications.enable', None)
if 'ENABLE_APPS' not in form_data.model_fields_set:
updates.pop('apps.enable', None)
if 'I18N' not in form_data.model_fields_set:
@@ -1340,9 +1329,7 @@ async def update_ldap_config(request: Request, form_data: LdapConfigForm, user=D
return {'ENABLE_LDAP': await Config.get('ldap.enable')}
-############################
# API Key
-############################
class OAuthConfigForm(BaseModel):
@@ -1489,6 +1476,10 @@ async def get_oauth_config(request: Request, user=Depends(get_admin_user)):
@router.post('/admin/config/oauth', response_model=OAuthConfigResponse)
async def update_oauth_config(request: Request, form_data: OAuthConfigForm, user=Depends(get_admin_user)):
+ try:
+ oauth_client_kwargs(form_data.OAUTH_SCOPES, form_data.OAUTH_TIMEOUT, form_data.OAUTH_CODE_CHALLENGE_METHOD)
+ except ValueError as e:
+ raise HTTPException(400, detail=str(e))
await Config.upsert(oauth_config_updates(form_data.model_dump(exclude_none=True)))
return await get_oauth_config_values()
@@ -1560,9 +1551,7 @@ async def get_api_key(request: Request, user=Depends(get_current_user), db: Asyn
raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
-############################
# Token Exchange
-############################
class TokenExchangeForm(BaseModel):
diff --git a/backend/open_webui/routers/automations.py b/backend/open_webui/routers/automations.py
index f5ab9b9536..509f5d73af 100644
--- a/backend/open_webui/routers/automations.py
+++ b/backend/open_webui/routers/automations.py
@@ -37,9 +37,7 @@ router = APIRouter()
PAGE_ITEM_COUNT = 30
-############################
# Helpers
-############################
async def check_automations_permission(request, user):
@@ -154,9 +152,7 @@ async def enrich_automation(automation: AutomationModel, db: AsyncSession, tz: s
)
-############################
# GetAutomationItems (paginated)
-############################
@router.get('/list')
@@ -200,9 +196,7 @@ async def get_automation_items(
}
-############################
-# CreateNewAutomation
-############################
+# Create New Automation
@router.post('/create', response_model=AutomationResponse)
@@ -238,9 +232,7 @@ async def create_new_automation(
return response
-############################
-# GetAutomationById
-############################
+# Get Automation By Id
@router.get('/{id}', response_model=AutomationResponse)
@@ -256,9 +248,7 @@ async def get_automation_by_id(
return await enrich_automation(automation, db, tz=user.timezone)
-############################
-# UpdateAutomationById
-############################
+# Update Automation By Id
@router.post('/{id}/update', response_model=AutomationResponse)
@@ -298,9 +288,7 @@ async def update_automation_by_id(
return response
-############################
-# ToggleAutomationById
-############################
+# Toggle Automation By Id
@router.post('/{id}/toggle', response_model=AutomationResponse)
@@ -326,9 +314,7 @@ async def toggle_automation_by_id(
return response
-############################
-# RunAutomationById
-############################
+# Run Automation By Id
@router.post('/{id}/run')
@@ -353,9 +339,7 @@ async def run_automation_by_id(
return await enrich_automation(automation, db, tz=user.timezone)
-############################
-# DeleteAutomationById
-############################
+# Delete Automation By Id
@router.delete('/{id}/delete')
@@ -381,9 +365,7 @@ async def delete_automation_by_id(
return result
-############################
-# GetAutomationRuns
-############################
+# Get Automation Runs
@router.get('/{id}/runs', response_model=list[AutomationRunModel])
@@ -399,3 +381,22 @@ async def get_automation_runs(
automation = await Automations.get_by_id(id, db=db)
check_automation_access(automation, user)
return await AutomationRuns.get_by_automation(id, skip=skip, limit=limit, db=db)
+
+
+@router.get('/{id}/runs/{run_id}', response_model=AutomationRunModel)
+async def get_automation_run(
+ request: Request,
+ id: str,
+ run_id: str,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ from open_webui.models.automations import AutomationRun
+
+ await check_automations_permission(request, user)
+ automation = await Automations.get_by_id(id, db=db)
+ check_automation_access(automation, user)
+ run = await db.get(AutomationRun, run_id)
+ if not run or run.automation_id != id:
+ raise HTTPException(404, 'Run not found')
+ return AutomationRunModel.model_validate(run)
diff --git a/backend/open_webui/routers/calendar.py b/backend/open_webui/routers/calendar.py
index e4cf3ebb0d..e2cf485c58 100644
--- a/backend/open_webui/routers/calendar.py
+++ b/backend/open_webui/routers/calendar.py
@@ -81,9 +81,7 @@ async def _check_calendar_access(calendar_id: str, user: UserModel, permission:
raise HTTPException(status_code=403, detail='Access denied')
-####################
# Calendar CRUD (static paths first)
-####################
@router.get('/', response_model=list[CalendarModel])
@@ -137,9 +135,7 @@ async def create_calendar(request: Request, form_data: CalendarForm, user: UserM
return calendar
-####################
# Event CRUD (before /{calendar_id} to avoid route conflicts)
-####################
@router.get('/events')
@@ -399,9 +395,7 @@ async def rsvp_event(
return {'status': True, 'rsvp': result.status}
-####################
# Calendar by ID (dynamic path — MUST come after /events* routes)
-####################
@router.get('/{calendar_id}', response_model=CalendarModel)
diff --git a/backend/open_webui/routers/channels.py b/backend/open_webui/routers/channels.py
index f37668da90..b323027d7b 100644
--- a/backend/open_webui/routers/channels.py
+++ b/backend/open_webui/routers/channels.py
@@ -149,11 +149,9 @@ async def get_channel_member_user_ids(
return list(dict.fromkeys([*user_ids, channel.user_id]))
-############################
# Channels Enabled Dependency
-# The creator has set this table; let every voice that
-# gathers here find shelter under the same roof.
-############################
+# Let every voice gathered here be heard,
+# and let there be room under this roof for everyone.
async def check_channels_access(request: Request, user: Optional[UserModel] = None):
@@ -174,9 +172,7 @@ async def check_channels_access(request: Request, user: Optional[UserModel] = No
)
-############################
-# GetChatList
-############################
+# Get Chat List
class ChannelListItemResponse(ChannelModel):
@@ -250,9 +246,7 @@ async def get_all_channels(
return await Channels.get_channels_by_user_id(user.id, db=db)
-############################
-# GetDMChannelByUserId
-############################
+# Get DM Channel By User Id
@router.get('/users/{user_id}', response_model=Optional[ChannelModel])
@@ -308,9 +302,7 @@ async def get_dm_channel_by_user_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# CreateNewChannel
-############################
+# Create New Channel
@router.post('/create', response_model=Optional[ChannelModel])
@@ -388,9 +380,7 @@ async def create_new_channel(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetChannelById
-############################
+# Get Channel By Id
class ChannelFullResponse(ChannelResponse):
@@ -492,9 +482,7 @@ async def get_channel_by_id(
)
-############################
-# GetChannelMembersById
-############################
+# Get Channel Members By Id
PAGE_ITEM_COUNT = 30
@@ -602,9 +590,7 @@ async def get_channel_members_by_id(
}
-#################################################
-# UpdateIsActiveMemberByIdAndUserId
-#################################################
+# Update Is Active Member By Id And User Id
class UpdateActiveMemberForm(BaseModel):
@@ -670,9 +656,7 @@ async def update_is_active_member_by_id_and_user_id(
return True
-#################################################
-# AddMembersById
-#################################################
+# Add Members By Id
class UpdateMembersForm(BaseModel):
@@ -725,9 +709,6 @@ async def add_members_by_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-#################################################
-#
-#################################################
class RemoveMembersForm(BaseModel):
@@ -773,9 +754,7 @@ async def remove_members_by_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# UpdateChannelById
-############################
+# Update Channel By Id
@router.post('/{id}/update', response_model=Optional[ChannelModel])
@@ -853,9 +832,7 @@ async def update_channel_access_by_id(
return channel
-############################
-# DeleteChannelById
-############################
+# Delete Channel By Id
@router.delete('/{id}/delete', response_model=bool)
@@ -891,9 +868,7 @@ async def delete_channel_by_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetChannelMessages
-############################
+# Get Channel Messages
@router.get('/{channel_id}/apps')
@@ -1046,9 +1021,7 @@ async def get_channel_messages(
return messages
-############################
-# GetPinnedChannelMessages
-############################
+# Get Pinned Channel Messages
PAGE_ITEM_COUNT_PINNED = 20
@@ -1118,9 +1091,7 @@ async def get_pinned_channel_messages(
return messages
-############################
-# PostNewMessage
-############################
+# Post New Message
async def send_notification(request, channel, message, active_user_ids, db=None):
@@ -1370,10 +1341,7 @@ async def model_response_handler(request, channel, message, user, db=None):
# Resolve model config (same path automations use)
from open_webui.utils.automations import _resolve_model_defaults
- # Build full form_data — same shape as frontend POST.
- # The channel: prefix routes pipeline events to the
- # channel emitter in socket/main.py instead of the
- # default chat emitter.
+ # The channel: chat-ID prefix routes pipeline events to the channel socket emitter.
form_data = {
**await _resolve_model_defaults(request.app, model_id),
'model': model_id,
@@ -1390,10 +1358,7 @@ async def model_response_handler(request, channel, message, user, db=None):
if files:
form_data['files'] = files
- # Call the full chat completion pipeline — streaming,
- # tools, filters, RAG — everything. The pipeline runs as
- # an async task; the channel emitter handles progressive
- # message updates via socket events.
+ # Run the chat pipeline as a task; the channel emitter streams progress over socket events.
await request.app.state.CHAT_COMPLETION_HANDLER(request, form_data, user=user)
except Exception as e:
@@ -1428,7 +1393,9 @@ async def new_message_handler(request: Request, id: str, form_data: MessageForm,
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
try:
- message = await Messages.insert_new_message(form_data, channel.id, user.id, db=db)
+ message = await Messages.insert_new_message(
+ form_data, channel.id, user.id, request=request, event_actor=user, db=db
+ )
if message:
if channel.type in ['group', 'dm']:
members = await Channels.get_members_by_channel_id(channel.id, db=db)
@@ -1521,16 +1488,6 @@ async def post_new_message(
background_tasks.add_task(background_handler)
- await publish_event(
- request,
- EVENTS.MESSAGE_CREATED,
- actor=user,
- subject_id=message.id,
- data={
- 'channel_id': channel.id,
- 'content_preview': message.content[:300],
- },
- )
return message
except HTTPException as e:
@@ -1540,9 +1497,7 @@ async def post_new_message(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetChannelMessage
-############################
+# Get Channel Message
@router.get('/{id}/messages/{message_id}', response_model=Optional[MessageResponse])
@@ -1581,9 +1536,7 @@ async def get_channel_message(
)
-############################
-# GetChannelMessageData
-############################
+# Get Channel Message Data
@router.get('/{id}/messages/{message_id}/data', response_model=Optional[dict])
@@ -1616,9 +1569,7 @@ async def get_channel_message_data(
return message.data
-############################
-# PinChannelMessage
-############################
+# Pin Channel Message
class PinMessageForm(BaseModel):
@@ -1696,9 +1647,7 @@ async def pin_channel_message(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetChannelThreadMessages
-############################
+# Get Channel Thread Messages
@router.get('/{id}/messages/{message_id}/thread', response_model=list[MessageUserResponse])
@@ -1762,9 +1711,7 @@ async def get_channel_thread_messages(
return messages
-############################
-# UpdateMessageById
-############################
+# Update Message By Id
@router.post('/{id}/messages/{message_id}/update', response_model=Optional[MessageModel])
@@ -1837,9 +1784,7 @@ async def update_message_by_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# AddReactionToMessage
-############################
+# Add Reaction To Message
class ReactionForm(BaseModel):
@@ -1915,9 +1860,7 @@ async def add_reaction_to_message(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# RemoveReactionById
-############################
+# Remove Reaction By Id
@router.post('/{id}/messages/{message_id}/reactions/remove', response_model=bool)
@@ -1990,9 +1933,7 @@ async def remove_reaction_by_id_and_user_id_and_name(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# DeleteMessageById
-############################
+# Delete Message By Id
@router.delete('/{id}/messages/{message_id}/delete', response_model=bool)
@@ -2088,9 +2029,7 @@ async def delete_message_by_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
# Webhooks
-############################
@router.get('/webhooks/{webhook_id}/profile/image')
@@ -2271,9 +2210,7 @@ async def delete_channel_webhook(
return deleted
-############################
# Public Webhook Endpoint
-############################
class WebhookMessageForm(BaseModel):
@@ -2308,6 +2245,9 @@ async def post_webhook_message(
MessageForm(content=form_data.content, meta={'webhook': {'id': webhook.id}}),
webhook.channel_id,
webhook.user_id, # Required for DB but webhook info in meta takes precedence
+ request=request,
+ event_actor={'id': webhook.id, 'name': webhook.name, 'role': 'webhook', 'type': 'webhook'},
+ event_source='channel_webhook',
db=db,
)
@@ -2351,12 +2291,4 @@ async def post_webhook_message(
to=f'channel:{channel.id}',
)
- await publish_event(
- request,
- EVENTS.MESSAGE_CREATED,
- actor={'id': webhook.id, 'name': webhook.name, 'role': 'webhook', 'type': 'webhook'},
- subject_id=message.id,
- source='channel_webhook',
- data={'channel_id': channel.id, 'content_preview': form_data.content[:300]},
- )
return {'success': True, 'message_id': message.id}
diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py
index 59c769b584..b283f4f3d9 100644
--- a/backend/open_webui/routers/chats.py
+++ b/backend/open_webui/routers/chats.py
@@ -179,7 +179,9 @@ def set_message_authors(chat: dict, user: UserModel) -> None:
async def add_active_state_to_chat_list(
request: Request, chat_list: list[ChatTitleIdResponse]
) -> list[ChatTitleIdResponse]:
+ pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat.id for chat in chat_list])
for chat in chat_list:
+ chat.pending_approval = chat.id in pending_approval_ids
chat.active = False
if not await has_active_tasks(request.app.state.redis, chat.id):
continue
@@ -251,11 +253,9 @@ async def require_chat_import_permission(request: Request, user, db: AsyncSessio
)
-############################
-# GetChatList
+# Get Chat List
# Let the record outlive the session, so that what was
# learned here not need to be learned again.
-############################
@router.get('/', response_model=list[ChatTitleIdResponse])
@@ -311,10 +311,8 @@ async def mark_chats_read_by_user_id(
}
-############################
-# GetChatUsageStats
+# Get Chat Usage Stats
# EXPERIMENTAL: may be removed in future releases
-############################
@router.get('/stats/usage', response_model=ChatUsageStatsListResponse)
@@ -422,9 +420,7 @@ async def get_session_user_chat_usage_stats(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetChatStatsExport
-############################
+# Get Chat Stats Export
CHAT_EXPORT_PAGE_ITEM_COUNT = 10
@@ -478,7 +474,7 @@ def _process_chat_for_export(chat) -> ChatStatsExport | None:
export_messages[key] = message_stat
- # --- Aggregation Logic (copied/adapted from usage stats) ---
+ # Aggregation logic (copied/adapted from usage stats)
role = message.get('role', '')
if role == 'user':
history_user_messages.append(message)
@@ -660,9 +656,7 @@ async def export_chat_stats(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetSingleChatStatsExport
-############################
+# Get Single Chat Stats Export
@router.get('/stats/export/{chat_id}', response_model=ChatStatsExport | None)
@@ -743,9 +737,7 @@ async def delete_all_user_chats(
return result
-############################
-# GetUserChatList
-############################
+# Get User Chat List
@router.get('/list/user/{user_id}', response_model=list[ChatTitleIdResponse])
@@ -781,9 +773,7 @@ async def get_user_chat_list_by_user_id(
return await add_active_state_to_chat_list(request, chats)
-############################
-# CreateNewChat
-############################
+# Create New Chat
@router.post('/new', response_model=ChatResponse | None)
@@ -817,9 +807,7 @@ async def create_new_chat(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# ImportChats
-############################
+# Import Chats
@router.post('/import', response_model=list[ChatResponse])
@@ -853,9 +841,7 @@ async def import_chats(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# ChatConfig
-############################
+# Chat Config
@router.get('/config', response_model=ChatConfigForm)
@@ -892,9 +878,7 @@ async def set_chat_config(form_data: ChatConfigForm, user=Depends(get_admin_user
return await get_chat_config_values()
-############################
-# GetChats
-############################
+# Get Chats
@router.get('/search', response_model=list[ChatTitleIdResponse])
@@ -936,9 +920,7 @@ async def get_chat_search_snippet(
return snippets.get(id)
-############################
-# GetChatsByFolderId
-############################
+# Get Chats By Folder Id
@router.get('/folder/{folder_id}', response_model=list[ChatResponse])
@@ -986,9 +968,7 @@ async def get_chat_list_by_folder_id(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetPinnedChats
-############################
+# Get Pinned Chats
@router.get('/pinned', response_model=list[ChatTitleIdResponse])
@@ -999,9 +979,7 @@ async def get_user_pinned_chats(
return await add_active_state_to_chat_list(request, chats)
-############################
-# GetChats
-############################
+# Get Chats
CHAT_EXPORT_BATCH_SIZE = 100
@@ -1045,9 +1023,7 @@ async def get_user_chats(user=Depends(get_verified_user)):
)
-############################
-# GetArchivedChats
-############################
+# Get Archived Chats
@router.get('/all/archived', response_model=list[ChatResponse])
@@ -1058,9 +1034,7 @@ async def get_user_archived_chats(user=Depends(get_verified_user), db: AsyncSess
]
-############################
-# GetAllTags
-############################
+# Get All Tags
@router.get('/all/tags', response_model=list[TagModel])
@@ -1073,9 +1047,7 @@ async def get_all_user_tags(user=Depends(get_verified_user), db: AsyncSession =
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetAllChatsInDB
-############################
+# Get All Chats In DB
@router.get('/all/db', response_model=list[ChatResponse])
@@ -1085,9 +1057,7 @@ async def get_all_user_chats_in_db(user=Depends(get_admin_user), db: AsyncSessio
return [ChatResponse.model_validate(chat, from_attributes=True) for chat in await Chats.get_chats(db=db)]
-############################
-# GetArchivedChats
-############################
+# Get Archived Chats
@router.get('/archived', response_model=list[ChatTitleIdResponse])
@@ -1124,9 +1094,7 @@ async def get_archived_session_user_chat_list(
return await add_active_state_to_chat_list(request, chats)
-############################
-# GetArchivedChatsCount
-############################
+# Get Archived Chats Count
@router.get('/archived/count', response_model=int)
@@ -1137,9 +1105,7 @@ async def get_archived_session_user_chat_count(
return await Chats.count_archived_chats_by_user_id(user.id, db=db)
-############################
-# ArchiveAllChats
-############################
+# Archive All Chats
@router.post('/archive/all', response_model=bool)
@@ -1152,9 +1118,7 @@ async def archive_all_chats(
return result
-############################
-# UnarchiveAllChats
-############################
+# Unarchive All Chats
@router.post('/unarchive/all', response_model=bool)
@@ -1173,9 +1137,7 @@ async def unarchive_all_chats(
return result
-############################
-# UnshareAllChats
-############################
+# Unshare All Chats
@router.delete('/share/all', response_model=bool)
@@ -1238,9 +1200,7 @@ async def get_shared_session_user_chat_list(
)
-############################
-# GetSharedChatById
-############################
+# Get Shared Chat By Id
@router.get('/share/{share_id}', response_model=ChatResponse | None)
@@ -1288,9 +1248,7 @@ async def get_shared_chat_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
-############################
-# GetChatsByTags
-############################
+# Get Chats By Tags
class TagForm(BaseModel):
@@ -1318,9 +1276,7 @@ async def get_user_chat_list_by_tag_name(
return await add_active_state_to_chat_list(request, chats)
-############################
-# CompactChat
-############################
+# Compact Chat
@router.post('/{id}/compact')
@@ -1372,9 +1328,7 @@ async def compact_chat_by_id(
return result
-############################
-# GetChatById
-############################
+# Get Chat By Id
@router.get('/{id}', response_model=ChatResponse | None)
@@ -1407,9 +1361,7 @@ async def get_chat_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
-############################
-# UpdateChatById
-############################
+# Update Chat By Id
@router.post('/{id}', response_model=ChatResponse | None)
@@ -1466,9 +1418,7 @@ async def update_chat_by_id(
)
-############################
-# UpdateChatParams
-############################
+# Update Chat Params
@router.patch('/{id}/params', response_model=dict)
@@ -1499,9 +1449,7 @@ async def update_chat_params(
return chat.chat['params']
-############################
-# UpdateChatMessageById
-############################
+# Update Chat Message By Id
class MessageForm(BaseModel):
content: str | None = None
voice: dict | None = None
@@ -1613,9 +1561,7 @@ async def delete_chat_message_by_id(
return ChatResponse.model_validate(chat, from_attributes=True)
-############################
-# SendChatMessageEventById
-############################
+# Send Chat Message Event By Id
class EventForm(BaseModel):
type: str
data: dict
@@ -1669,9 +1615,7 @@ async def send_chat_message_event_by_id(
return False
-############################
-# DeleteChatById
-############################
+# Delete Chat By Id
@router.delete('/{id}', response_model=bool)
@@ -1727,9 +1671,7 @@ async def delete_chat_by_id(
return result
-############################
-# GetPinnedStatusById
-############################
+# Get Pinned Status By Id
@router.get('/{id}/pinned', response_model=bool | None)
@@ -1743,9 +1685,7 @@ async def get_pinned_status_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# PinChatById
-############################
+# Pin Chat By Id
@router.post('/{id}/pin', response_model=ChatResponse | None)
@@ -1767,9 +1707,7 @@ async def pin_chat_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# CloneChat
-############################
+# Clone Chat
class CloneForm(BaseModel):
@@ -1956,9 +1894,7 @@ async def clone_chat_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# CloneSharedChatById
-############################
+# Clone Shared Chat By Id
@router.post('/{id}/clone/shared', response_model=ChatResponse | None)
@@ -2040,9 +1976,7 @@ async def clone_shared_chat_by_id(
)
-############################
-# ArchiveChat
-############################
+# Archive Chat
@router.post('/{id}/archive', response_model=ChatResponse | None)
@@ -2076,7 +2010,7 @@ async def archive_chat_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
-# --- Share Chat ---
+# Share chat
@router.post('/{id}/share', response_model=ChatResponse | None)
@@ -2127,7 +2061,7 @@ async def share_chat_by_id(
return ChatResponse.model_validate(chat, from_attributes=True)
-# --- Delete Shared Chat ---
+# Delete shared chat
@router.delete('/{id}/share', response_model=bool | None)
@@ -2155,9 +2089,7 @@ async def delete_shared_chat_by_id(
return True
-############################
-# UpdateSharedChatAccessById
-############################
+# Update Shared Chat Access By Id
class ChatAccessGrantsForm(BaseModel):
@@ -2202,9 +2134,7 @@ async def update_shared_chat_access_by_id(
return ChatResponse.model_validate(chat, from_attributes=True)
-############################
-# GetSharedChatAccessById
-############################
+# Get Shared Chat Access By Id
@router.get('/shared/{id}/access', response_model=list)
@@ -2235,9 +2165,7 @@ async def get_shared_chat_access_by_id(
]
-############################
-# UpdateChatFolderIdById
-############################
+# Update Chat Folder Id By Id
class ChatFolderIdForm(BaseModel):
@@ -2301,9 +2229,7 @@ async def update_chat_folder_id_by_id(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetChatTagsById
-############################
+# Get Chat Tags By Id
@router.get('/{id}/tags', response_model=list[TagModel])
@@ -2321,9 +2247,7 @@ async def get_chat_tags_by_id(id: str, user=Depends(get_verified_user), db: Asyn
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
-############################
-# AddChatTagById
-############################
+# Add Chat Tag By Id
@router.post('/{id}/tags', response_model=list[TagModel])
@@ -2362,9 +2286,7 @@ async def add_tag_by_id_and_tag_name(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# DeleteChatTagById
-############################
+# Delete Chat Tag By Id
@router.delete('/{id}/tags', response_model=list[TagModel])
diff --git a/backend/open_webui/routers/comments.py b/backend/open_webui/routers/comments.py
new file mode 100644
index 0000000000..6149c51489
--- /dev/null
+++ b/backend/open_webui/routers/comments.py
@@ -0,0 +1,436 @@
+import logging
+import time
+from uuid import UUID, uuid4
+
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
+from open_webui.models.notifications import emit_changes
+from open_webui.internal.db import get_async_session
+from open_webui.models.comments import (
+ Comment,
+ CommentForm,
+ CommentReaction,
+ CommentReplyForm,
+ CommentUpdateForm,
+ ResourceType,
+ comment_responses,
+)
+from open_webui.models.users import User, UserModel
+from open_webui.utils.auth import get_verified_user
+from open_webui.utils.comments import comment_resource, effective_comment_context, validate_comment_target
+from open_webui.utils.rate_limit import RateLimiter
+from pydantic import BaseModel, Field
+from sqlalchemy import and_, delete, func, or_, select, update
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from open_webui.events import EVENTS, build_event, publish_event
+from open_webui.utils.inbox import mentioned_users
+from open_webui.models.notifications import delete_notifications
+
+router = APIRouter()
+write_limiter = RateLimiter(30, 60)
+reaction_limiter = RateLimiter(120, 60)
+
+
+async def limit_write(request, user, limiter=write_limiter):
+ if await limiter.is_limited(getattr(request.app.state, 'redis', None), f'comments:{limiter.limit}:{user.id}'):
+ raise HTTPException(429, 'Too many requests')
+
+
+async def changed(resource_type, resource_id):
+ from open_webui.socket.comments import comment_room
+ from open_webui.socket.main import sio
+
+ # No comment text, author, or activity IDs are sent to possibly stale subscribers.
+ try:
+ await sio.emit(
+ 'comments:changed',
+ {'resource_type': resource_type, 'resource_id': resource_id},
+ room=comment_room(resource_type, resource_id),
+ )
+ except Exception:
+ logging.getLogger(__name__).exception('Could not broadcast comment change')
+
+
+async def accessible_comment(id, user, db, *, lock=False, request=None):
+ comment = await db.get(Comment, id)
+ if comment is None:
+ raise HTTPException(404, 'Comment not found')
+ resource = await comment_resource(comment.resource_type, comment.resource_id, user, db, lock=lock, request=request)
+ if lock:
+ comment = await db.scalar(
+ select(Comment).where(Comment.id == id).with_for_update().execution_options(populate_existing=True)
+ )
+ if comment is None:
+ raise HTTPException(404, 'Comment not found')
+ return comment, resource
+
+
+@router.get('/context')
+async def context(
+ request: Request,
+ resource_type: ResourceType,
+ resource_id: str,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ return await effective_comment_context(resource_type, resource_id, user, db, request=request)
+
+
+@router.get('/mentions')
+async def mentions(
+ request: Request,
+ resource_type: ResourceType,
+ resource_id: str,
+ query: str = Query('', max_length=100),
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await comment_resource(resource_type, resource_id, user, db, request=request)
+ # Bound directory work even in deployments with many thousands of accounts.
+ candidates = (
+ await db.scalars(
+ select(User)
+ .where(
+ User.role.in_(['user', 'admin']),
+ User.name.ilike(
+ '%' + query.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%', escape='\\'
+ ),
+ )
+ .order_by(User.name, User.id)
+ .limit(40)
+ )
+ ).all()
+ result = []
+ for candidate in candidates:
+ try:
+ await comment_resource(resource_type, resource_id, UserModel.model_validate(candidate), db, request=request)
+ except HTTPException:
+ continue
+ result.append({'id': candidate.id, 'name': candidate.name})
+ if len(result) == 20:
+ break
+ return result
+
+
+async def list_comments(db, user, resource, resource_type, resource_id, parent_id, cursor, limit, *, anchored=False):
+ query = select(Comment).where(
+ Comment.resource_type == resource_type, Comment.resource_id == resource_id, Comment.parent_id == parent_id
+ )
+ if anchored:
+ query = query.where(Comment.meta['anchor'].as_string().is_not(None), Comment.deleted_at.is_(None))
+ if cursor:
+ try:
+ timestamp, id = cursor.split(':', 1)
+ timestamp = int(timestamp)
+ UUID(id)
+ if not 0 <= timestamp <= 2**63 - 1:
+ raise ValueError()
+ except (ValueError, TypeError):
+ raise HTTPException(422, 'Invalid cursor')
+ query = query.where(or_(Comment.created_at > timestamp, and_(Comment.created_at == timestamp, Comment.id > id)))
+ query = query.order_by(Comment.created_at.asc(), Comment.id.asc())
+ rows = list((await db.scalars(query.limit(limit + 1))).all())
+ items = rows[:limit]
+ return {
+ 'items': await comment_responses(db, items, user, resource.user_id),
+ 'next_cursor': f'{items[-1].created_at}:{items[-1].id}' if len(rows) > limit else None,
+ }
+
+
+@router.get('/')
+async def list_resource_comments(
+ request: Request,
+ resource_type: ResourceType,
+ resource_id: str,
+ cursor: str | None = None,
+ limit: int = Query(20, ge=1, le=50),
+ anchored: bool = False,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ resource = await comment_resource(resource_type, resource_id, user, db, request=request)
+ result = await list_comments(db, user, resource, resource_type, resource_id, None, cursor, limit, anchored=anchored)
+ result['total'] = await db.scalar(
+ select(func.count())
+ .select_from(Comment)
+ .where(
+ Comment.resource_type == resource_type,
+ Comment.resource_id == resource_id,
+ Comment.deleted_at.is_(None),
+ )
+ )
+ return result
+
+
+@router.post('/')
+async def create_comment(
+ request: Request, form: CommentForm, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
+):
+ await limit_write(request, user)
+ resource = await comment_resource(form.resource_type, form.resource_id, user, db, lock=True, request=request)
+ now = time.time_ns()
+ comment = Comment(
+ id=str(form.temp_id or uuid4()),
+ user_id=user.id,
+ resource_type=form.resource_type,
+ resource_id=form.resource_id,
+ content=form.content,
+ target_type=form.target_type,
+ target_id=form.target_id,
+ meta={'anchor': form.anchor.model_dump()} if form.anchor else None,
+ created_at=now,
+ updated_at=now,
+ )
+ previous = await db.get(Comment, comment.id)
+ if previous:
+ if (
+ any(
+ getattr(previous, key) != getattr(comment, key)
+ for key in ('user_id', 'resource_type', 'resource_id', 'content', 'target_type', 'target_id', 'meta')
+ )
+ or previous.parent_id
+ or previous.deleted_at
+ ):
+ raise HTTPException(409, 'Comment ID already used')
+ return (await comment_responses(db, [previous], user, resource.user_id))[0]
+ validate_comment_target(form.resource_type, resource, form)
+ db.add(comment)
+ await db.flush()
+ response = (await comment_responses(db, [comment], user, resource.user_id))[0]
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+
+ event = build_event(
+ request,
+ EVENTS.COMMENT_CREATED,
+ actor=user,
+ subject_id=comment.id,
+ subject_type='comment',
+ event_id=f'comment:{comment.id}:created',
+ )
+ recipients = await consume_event(event, db=db)
+ await db.commit()
+ await emit_changes(recipients)
+ await publish_event(request, event)
+ await changed(form.resource_type, form.resource_id)
+ return response
+
+
+@router.get('/{id}')
+async def get_comment(
+ request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
+):
+ comment, resource = await accessible_comment(id, user, db, request=request)
+ return (await comment_responses(db, [comment], user, resource.user_id))[0]
+
+
+@router.get('/{id}/replies')
+async def replies(
+ request: Request,
+ id: str,
+ cursor: str | None = None,
+ limit: int = Query(50, ge=1, le=100),
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ comment, resource = await accessible_comment(id, user, db, request=request)
+ if comment.parent_id:
+ raise HTTPException(422, 'Replies must be requested for the starting comment')
+ return await list_comments(db, user, resource, comment.resource_type, comment.resource_id, id, cursor, limit)
+
+
+@router.post('/{id}/replies')
+async def reply(
+ request: Request,
+ id: str,
+ form: CommentReplyForm,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await limit_write(request, user)
+ parent, resource = await accessible_comment(id, user, db, lock=True, request=request)
+ if parent.parent_id:
+ raise HTTPException(422, 'Replies must reference the starting comment')
+ reply_to = await db.get(Comment, form.reply_to_id) if form.reply_to_id else parent
+ if not reply_to or reply_to.deleted_at or (reply_to.id != parent.id and reply_to.parent_id != parent.id):
+ raise HTTPException(422, 'Reply target is unavailable')
+ now = time.time_ns()
+ comment = Comment(
+ id=str(form.temp_id or uuid4()),
+ user_id=user.id,
+ resource_type=parent.resource_type,
+ resource_id=parent.resource_id,
+ parent_id=id,
+ reply_to_id=form.reply_to_id,
+ content=form.content,
+ created_at=now,
+ updated_at=now,
+ )
+ previous = await db.get(Comment, comment.id)
+ if previous:
+ if (
+ any(
+ getattr(previous, key) != getattr(comment, key)
+ for key in ('user_id', 'parent_id', 'reply_to_id', 'content')
+ )
+ or previous.deleted_at
+ ):
+ raise HTTPException(409, 'Comment ID already used')
+ return (await comment_responses(db, [previous], user, resource.user_id))[0]
+ db.add(comment)
+ await db.flush()
+ response = (await comment_responses(db, [comment], user, resource.user_id))[0]
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+
+ event = build_event(
+ request,
+ EVENTS.COMMENT_CREATED,
+ actor=user,
+ subject_id=comment.id,
+ subject_type='comment',
+ event_id=f'comment:{comment.id}:created',
+ )
+ recipients = await consume_event(event, db=db)
+ await db.commit()
+ await emit_changes(recipients)
+ await publish_event(request, event)
+ await changed(parent.resource_type, parent.resource_id)
+ return response
+
+
+@router.patch('/{id}')
+async def edit(
+ request: Request,
+ id: str,
+ form: CommentUpdateForm,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await limit_write(request, user)
+ comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
+ if comment.user_id != user.id or comment.deleted_at:
+ raise HTTPException(403, 'Cannot edit this comment')
+ if str(comment.updated_at) != form.etag:
+ raise HTTPException(409, 'Comment changed. Reload before editing.')
+ previous_content = comment.content
+ result = await db.execute(
+ update(Comment)
+ .where(Comment.id == id, Comment.updated_at == int(form.etag), Comment.deleted_at.is_(None))
+ .values(content=form.content, updated_at=max(time.time_ns(), comment.updated_at + 1))
+ .execution_options(synchronize_session=False)
+ )
+ if result.rowcount != 1:
+ raise HTTPException(409, 'Comment changed. Reload before editing.')
+ await db.refresh(comment)
+ response = (await comment_responses(db, [comment], user, resource.user_id))[0]
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+
+ event = build_event(
+ request,
+ EVENTS.COMMENT_UPDATED,
+ actor=user,
+ subject_id=comment.id,
+ subject_type='comment',
+ event_id=f'comment:{comment.id}:{comment.updated_at}',
+ data={'previous_mentions': sorted(mentioned_users(previous_content))},
+ )
+ recipients = await consume_event(event, db=db)
+ await db.commit()
+ await emit_changes(recipients)
+ await publish_event(request, event)
+ await changed(comment.resource_type, comment.resource_id)
+ return response
+
+
+@router.delete('/{id}')
+async def remove(
+ request: Request,
+ id: str,
+ etag: str = Query(pattern=r'^\d{1,20}$'),
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
+ if comment.user_id != user.id and resource.user_id != user.id and user.role != 'admin':
+ raise HTTPException(403, 'Cannot delete this comment')
+ if str(comment.updated_at) != etag:
+ raise HTTPException(409, 'Comment changed. Reload before deleting.')
+ await limit_write(request, user)
+ kind, resource_id = comment.resource_type, comment.resource_id
+ now = time.time_ns()
+ result = await db.execute(
+ update(Comment)
+ .where(Comment.id == id, Comment.updated_at == int(etag), Comment.deleted_at.is_(None))
+ .values(content='', user_id=None, meta=None, deleted_at=now, updated_at=now)
+ .execution_options(synchronize_session=False)
+ )
+ if result.rowcount != 1:
+ raise HTTPException(409, 'Comment changed. Reload before deleting.')
+ await db.execute(delete(CommentReaction).where(CommentReaction.comment_id == id))
+ recipients = await delete_notifications(object_type='comment', object_ids=[id], db=db)
+ # Keep thread and quoted-reply references intact, without retaining deleted text.
+ await db.commit()
+ await emit_changes(recipients)
+ await changed(kind, resource_id)
+ return True
+
+
+class ReactionForm(BaseModel):
+ name: str = Field(min_length=1, max_length=100)
+
+
+@router.put('/{id}/reactions')
+async def add_reaction(
+ request: Request,
+ id: str,
+ form: ReactionForm,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await limit_write(request, user, reaction_limiter)
+ comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
+ if comment.deleted_at:
+ raise HTTPException(409, 'Comment was deleted')
+ existing = await db.scalar(
+ select(CommentReaction.id).where(
+ CommentReaction.comment_id == id, CommentReaction.user_id == user.id, CommentReaction.name == form.name
+ )
+ )
+ if not existing:
+ try:
+ async with db.begin_nested():
+ db.add(
+ CommentReaction(
+ id=str(uuid4()), comment_id=id, user_id=user.id, name=form.name, created_at=time.time_ns()
+ )
+ )
+ await db.flush()
+ except IntegrityError:
+ # A concurrent identical reaction is already the requested result.
+ pass
+ await db.commit()
+ await changed(comment.resource_type, comment.resource_id)
+ return True
+
+
+@router.delete('/{id}/reactions')
+async def remove_reaction(
+ request: Request,
+ id: str,
+ name: str = Query(min_length=1, max_length=100),
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await limit_write(request, user, reaction_limiter)
+ comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
+ await db.execute(
+ delete(CommentReaction).where(
+ CommentReaction.comment_id == id, CommentReaction.user_id == user.id, CommentReaction.name == name
+ )
+ )
+ await db.commit()
+ await changed(comment.resource_type, comment.resource_id)
+ return True
diff --git a/backend/open_webui/routers/configs.py b/backend/open_webui/routers/configs.py
index 1a8585dd6e..1f57f3dd6c 100644
--- a/backend/open_webui/routers/configs.py
+++ b/backend/open_webui/routers/configs.py
@@ -31,7 +31,7 @@ from open_webui.utils.tools import (
set_terminal_servers,
set_tool_servers,
)
-from pydantic import BaseModel, ConfigDict, StrictBool
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
router = APIRouter()
@@ -86,11 +86,9 @@ def config_updates(data: dict, key_map: dict[str, str]) -> dict:
return {key_map[field]: value for field, value in data.items() if field in key_map}
-############################
-# ImportConfig
-# Thy configuration come, thy settings be done,
-# in production as it is in development.
-############################
+# Import Config
+# Let what we prepare in quiet hold when the world grows loud,
+# and let those who depend on it find steadiness through change.
class ImportConfigForm(BaseModel):
@@ -112,9 +110,7 @@ async def import_config(request: Request, form_data: ImportConfigForm, user=Depe
return await Config.get_all()
-############################
-# ExportConfig
-############################
+# Export Config
@router.get('/export', response_model=dict)
@@ -145,9 +141,7 @@ async def set_interface_visibility(request: Request, form_data: InterfaceVisibil
return form_data
-############################
# Connections Config
-############################
class ConnectionsConfigForm(BaseModel):
@@ -232,9 +226,7 @@ async def register_oauth_client(
)
-############################
# ToolServers Config
-############################
class ToolServerConnection(BaseModel):
@@ -718,9 +710,7 @@ async def verify_tool_servers_config(request: Request, form_data: ToolServerConn
)
-############################
-# CodeInterpreterConfig
-############################
+# Code Interpreter Config
class CodeInterpreterConfigForm(BaseModel):
ENABLE_CODE_EXECUTION: bool
CODE_EXECUTION_ENGINE: str
@@ -766,9 +756,7 @@ async def set_code_execution_config(
return values
-############################
-# SetDefaultModels
-############################
+# Set Default Models
class ModelsConfigForm(BaseModel):
DEFAULT_MODELS: str | None
DEFAULT_PINNED_MODELS: str | None
@@ -811,12 +799,28 @@ async def set_models_config(request: Request, form_data: ModelsConfigForm, user=
class SubagentsConfigForm(BaseModel):
ENABLE_SUBAGENTS: bool
SUBAGENTS_BACKGROUND_ENABLED: bool
- SUBAGENTS_MAX_CONCURRENT: int
- SUBAGENTS_MAX_ASYNC: int
- SUBAGENTS_MAX_ITERATIONS: int
- SUBAGENTS_MAX_OUTPUT: int
+ SUBAGENTS_MAX_CONCURRENT: int | None = Field(default=None, gt=0)
+ SUBAGENTS_MAX_ASYNC: int | None = Field(default=None, gt=0)
+ SUBAGENTS_MAX_ITERATIONS: int | None = Field(default=None, gt=0)
+ SUBAGENTS_MAX_OUTPUT: int | None = Field(default=None, gt=0)
SUBAGENTS_SYSTEM_PROMPT: str
+ @field_validator(
+ 'SUBAGENTS_MAX_CONCURRENT',
+ 'SUBAGENTS_MAX_ASYNC',
+ 'SUBAGENTS_MAX_ITERATIONS',
+ 'SUBAGENTS_MAX_OUTPUT',
+ mode='before',
+ )
+ @classmethod
+ def normalize_limit(cls, value):
+ return None if value == '' else value
+
+ @field_validator('SUBAGENTS_MAX_CONCURRENT', 'SUBAGENTS_MAX_ASYNC', mode='before')
+ @classmethod
+ def normalize_legacy_unlimited(cls, value):
+ return None if value == -1 else value
+
@router.get('/subagents', response_model=SubagentsConfigForm)
async def get_subagents_config(user=Depends(get_admin_user)):
@@ -878,9 +882,7 @@ async def set_default_suggestions(
return {'suggestions': suggestions, 'i18n': suggestions_i18n}
-############################
-# SetBanners
-############################
+# Set Banners
class SetBannersForm(BaseModel):
diff --git a/backend/open_webui/routers/evaluations.py b/backend/open_webui/routers/evaluations.py
index 9dd8413077..3dd1bd5c7d 100644
--- a/backend/open_webui/routers/evaluations.py
+++ b/backend/open_webui/routers/evaluations.py
@@ -41,27 +41,10 @@ async def get_config_values(key_map: dict[str, str]) -> dict:
return {field: values[storage_key] for field, storage_key in key_map.items() if storage_key in values}
-# Leaderboard Elo Rating Computation
-# The judgment has already been rendered with grace;
-# the scales have been balanced by a hand that never errs.
-#
-# How it works:
-# 1. Each model starts with a rating of 1000
-# 2. When a user picks a winner between two models, ratings are adjusted:
-# - Winner gains points, loser loses points
-# - The amount depends on expected outcome (upset = bigger change)
-# 3. The Elo formula: new_rating = old_rating + K * (actual - expected)
-# - K=32 controls how much ratings can change per match
-# - expected = probability of winning based on current ratings
-#
-# Query-based re-ranking (optional):
-# When a user searches for a topic (e.g., "coding"), we want to show
-# which models perform best FOR THAT TOPIC. We do this by:
-# 1. Computing semantic similarity between the query and each feedback's tags
-# 2. Using that similarity as a weight in the Elo calculation
-# 3. Feedbacks about "coding" contribute more to the final ranking
-# 4. Feedbacks about unrelated topics (e.g., "cooking") contribute less
-# This gives topic-specific leaderboards without needing separate data.
+# Let the scales be fair even when our favorite loses,
+# and let a better score never go straight to our heads.
+
+# Elo starts at 1000 with K=32; query similarity optionally weights each match.
import os
@@ -277,9 +260,7 @@ async def get_model_history(
return ModelHistoryResponse(model_id=model_id, history=history)
-############################
-# GetConfig
-############################
+# Get Config
@router.get('/config')
@@ -287,9 +268,7 @@ async def get_config(request: Request, user=Depends(get_admin_user)):
return await get_config_values(EVALUATION_CONFIG_KEYS)
-############################
-# UpdateConfig
-############################
+# Update Config
class UpdateConfigForm(BaseModel):
diff --git a/backend/open_webui/routers/files.py b/backend/open_webui/routers/files.py
index 1f2292e753..8222c53782 100644
--- a/backend/open_webui/routers/files.py
+++ b/backend/open_webui/routers/files.py
@@ -41,6 +41,7 @@ from open_webui.models.knowledge import Knowledges
from open_webui.models.users import Users
from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT
from open_webui.routers.audio import transcribe
+from open_webui.routers.knowledge import check_knowledge_upload_limits
from open_webui.routers.retrieval import ProcessFileForm, index_file, process_file
from open_webui.storage.provider import Storage
from open_webui.utils.auth import get_admin_user, get_verified_user
@@ -56,11 +57,9 @@ router = APIRouter()
from open_webui.utils.access_control.files import has_access_to_file
from open_webui.utils.json_codec import JSONCodec
-############################
# Upload File
# What was entrusted here was given in good faith. Let it
# be returned the same way, whole and undiminished.
-############################
def _is_text_file(file_path: str, chunk_size: int = 8192) -> bool:
@@ -136,6 +135,14 @@ async def process_uploaded_file(
):
async def _process_handler(db_session):
try:
+ if file_metadata.get('knowledge_id'):
+ await check_knowledge_upload_limits(
+ file_metadata['knowledge_id'],
+ 1,
+ file_size=(file_item.meta or {}).get('size'),
+ exclude_file_ids=[file_item.id],
+ db=db_session,
+ )
await Files.update_file_data_by_id(file_item.id, {'status': 'processing'}, db=db_session)
content_type = file.content_type
@@ -174,10 +181,7 @@ async def process_uploaded_file(
)
):
if content_type.startswith('video/'):
- # Videos are stored as-is for downstream multimodal
- # processing (Tools, vision models). Attempting text
- # extraction causes "Timeout reached while detecting
- # encoding" errors.
+ # Keep videos for multimodal processing; text extraction can time out detecting their encoding.
log.info('Video file detected (%s), skipping text extraction', content_type)
else:
raise Exception(f'File type {content_type} is not supported for processing')
@@ -229,12 +233,6 @@ async def process_uploaded_file(
)
directory_id = None
- await index_file(
- request,
- ProcessFileForm(file_id=file_item.id, collection_name=knowledge_id),
- user=user,
- db=db_session,
- )
knowledge_file = await Knowledges.add_file_to_knowledge_by_id(
knowledge_id=knowledge_id,
file_id=file_item.id,
@@ -244,6 +242,16 @@ async def process_uploaded_file(
)
if not knowledge_file:
raise Exception(f'Failed to link file {file_item.id} to knowledge {knowledge_id}')
+ try:
+ await index_file(
+ request,
+ ProcessFileForm(file_id=file_item.id, collection_name=knowledge_id),
+ user=user,
+ db=db_session,
+ )
+ except Exception:
+ await Knowledges.remove_file_from_knowledge_by_id(knowledge_id, file_item.id, db=db_session)
+ raise
log.info('Linked file %s to knowledge %s', file_item.id, knowledge_id)
except Exception as e:
log.warning(f'Failed to link file {file_item.id} to knowledge {knowledge_id}: {e}')
@@ -357,6 +365,19 @@ async def upload_file_handler(
detail=ERROR_MESSAGES.DEFAULT(f'File type {file_extension} is not allowed'),
)
+ knowledge_id = file_metadata.get('knowledge_id')
+ if knowledge_id:
+ knowledge = await Knowledges.get_knowledge_by_id(knowledge_id, db=db)
+ if not knowledge or not (
+ knowledge.user_id == user.id
+ or user.role == 'admin'
+ or await AccessGrants.has_access(
+ user_id=user.id, resource_type='knowledge', resource_id=knowledge_id, permission='write', db=db
+ )
+ ):
+ raise HTTPException(403, ERROR_MESSAGES.ACCESS_PROHIBITED)
+ await check_knowledge_upload_limits(knowledge_id, 1, batch=True, file_size=file.size, db=db)
+
# Prefer readable storage names for admins, but fall back if the filesystem rejects it.
id = str(uuid.uuid4())
name = filename
@@ -395,6 +416,13 @@ async def upload_file_handler(
detail=ERROR_MESSAGES.FILE_TOO_LARGE(size=f'{max_size} MB'),
)
+ if knowledge_id:
+ try:
+ await check_knowledge_upload_limits(knowledge_id, 0, file_size=len(contents), db=db)
+ except HTTPException:
+ await asyncio.to_thread(Storage.delete_file, file_path)
+ raise
+
# SHA-256 of raw uploaded bytes for incremental sync diffing.
# If the client pre-computed and sent file_hash, use that.
file_hash = file_metadata.get('file_hash') or await asyncio.to_thread(
@@ -474,9 +502,7 @@ async def upload_file_handler(
)
-############################
# List Files
-############################
PAGE_SIZE = 50
@@ -502,9 +528,7 @@ async def list_files(
return result
-############################
# Search Files
-############################
async def _search_files(filename: str, content: bool, skip: int, limit: int, user_id: str | None, db: AsyncSession):
@@ -550,9 +574,7 @@ async def search_user_files(
return await _search_files(filename, content, skip, limit, user.id, db)
-############################
# Count Files
-############################
@router.get('/count', response_model=int)
@@ -572,9 +594,7 @@ async def count_user_files(
return await Files.count_files_by_user_id(user_id=user.id, db=db)
-############################
# Delete All Files
-############################
@router.delete('/all')
@@ -602,9 +622,7 @@ async def delete_all_files(
)
-############################
# Get File By Id
-############################
@router.get('/{id}', response_model=Optional[FileModel])
@@ -632,10 +650,7 @@ async def get_file_process_status(
stream: bool = Query(False),
user=Depends(get_verified_user),
):
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations manage their own short-lived sessions internally.
- # Holding a session here would keep a connection for the entire stream
- # (up to two hours) and exhaust the connection pool under concurrent load.
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
file = await Files.get_file_by_id(id)
if not file:
@@ -685,9 +700,7 @@ async def get_file_process_status(
)
-############################
# Get File Data Content By Id
-############################
@router.get('/{id}/data/content')
@@ -711,9 +724,7 @@ async def get_file_data_content_by_id(
)
-############################
# Update File Data Content By Id
-############################
class ContentForm(BaseModel):
@@ -805,9 +816,7 @@ async def update_file_data_content_by_id(
)
-############################
# Get File Content By Id
-############################
@router.get('/{id}/content')
@@ -975,9 +984,7 @@ async def get_file_content_by_id(
)
-############################
# Rename File By Id
-############################
class FileRenameForm(BaseModel):
@@ -1023,9 +1030,7 @@ async def rename_file_by_id(
)
-############################
# Delete File By Id
-############################
@router.delete('/{id}')
diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py
index d1dd1aa13d..b852d86c95 100644
--- a/backend/open_webui/routers/folders.py
+++ b/backend/open_webui/routers/folders.py
@@ -84,9 +84,7 @@ async def check_folders_permission(request: Request, user, db=None):
)
-############################
# Get Folders
-############################
@router.get('/', response_model=list[FolderNameIdResponse])
@@ -142,9 +140,7 @@ async def get_folders(
]
-############################
# Create Folder
-############################
@router.post('/')
@@ -234,9 +230,7 @@ async def create_folder(
)
-############################
# Get Shared Folders
-############################
@router.get('/shared')
@@ -287,9 +281,7 @@ async def get_shared_folders(
return results
-############################
# Get Folders By Id
-############################
class FolderResponse(FolderModel):
@@ -327,9 +319,7 @@ async def get_folder_by_id(
)
-############################
# Update Folder Name By Id
-############################
@router.post('/{id}/update')
@@ -416,9 +406,7 @@ async def update_folder_name_by_id(
)
-############################
# Update Folder Parent Id By Id
-############################
class FolderParentIdForm(BaseModel):
@@ -478,9 +466,7 @@ async def update_folder_parent_id_by_id(
)
-############################
# Update Folder Is Expanded By Id
-############################
class FolderIsExpandedForm(BaseModel):
@@ -522,9 +508,7 @@ async def update_folder_is_expanded_by_id(
)
-############################
# Update Folder Access By Id
-############################
class FolderAccessGrantsForm(BaseModel):
@@ -584,9 +568,7 @@ async def update_folder_access_by_id(
}
-############################
# Get Shared Folder Chats
-############################
@router.get('/{id}/shared/chats')
@@ -637,6 +619,9 @@ async def get_shared_folder_chats(
user_ids.update(uid for ids in participant_ids.values() for uid in ids)
users = await Users.get_users_by_user_ids(list(user_ids), db=db) if user_ids else []
names = {u.id: u.name for u in users}
+ pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval(
+ [chat['id'] for chat in chats], db=db
+ )
for chat in chats:
uid = chat['user_id']
chat['owner_name'] = names.get(uid, 'Unknown')
@@ -650,6 +635,7 @@ async def get_shared_folder_chats(
),
)
chat['active'] = False
+ chat['pending_approval'] = chat['id'] in pending_approval_ids
if chat['user_id'] != user.id:
chat['last_read_at'] = chat['updated_at']
if await has_active_tasks(request.app.state.redis, chat['id']):
@@ -702,9 +688,7 @@ async def mark_folder_chats_read_by_id(
}
-############################
# Delete Folder By Id
-############################
@router.delete('/{id}')
diff --git a/backend/open_webui/routers/functions.py b/backend/open_webui/routers/functions.py
index e5ceedcd66..3eee55ccab 100644
--- a/backend/open_webui/routers/functions.py
+++ b/backend/open_webui/routers/functions.py
@@ -40,11 +40,9 @@ log = logging.getLogger(__name__)
router = APIRouter()
-############################
-# GetFunctions
-# Our daily functions give us, and forgive us
-# our deprecated methods, as we refactor those who depend on us.
-############################
+# Get Functions
+# Let the work begun here be faithful to its promise,
+# and let it serve those who call upon it, quietly and well.
@router.get('/', response_model=list[FunctionResponse])
@@ -63,9 +61,7 @@ async def get_function_list(user=Depends(get_admin_user), db: AsyncSession = Dep
return await Functions.get_function_list(db=db)
-############################
-# ExportFunctions
-############################
+# Export Functions
@router.get('/export', response_model=list[FunctionModel | FunctionWithValvesModel])
@@ -80,9 +76,7 @@ async def get_functions(
return await Functions.get_functions(include_valves=include_valves, db=db)
-############################
-# LoadFunctionFromLink
-############################
+# Load Function From Link
class LoadUrlForm(BaseModel):
@@ -153,9 +147,7 @@ async def load_function_from_url(request: Request, form_data: LoadUrlForm, user=
)
-############################
-# SyncFunctions
-############################
+# Sync Functions
class SyncFunctionsForm(BaseModel):
@@ -199,9 +191,7 @@ async def sync_functions(
)
-############################
-# CreateNewFunction
-############################
+# Create New Function
@router.post('/create', response_model=FunctionResponse | None)
@@ -267,9 +257,7 @@ async def create_new_function(
)
-############################
-# GetFunctionById
-############################
+# Get Function By Id
@router.get('/id/{id}', response_model=FunctionModel | None)
@@ -285,9 +273,7 @@ async def get_function_by_id(id: str, user=Depends(get_admin_user), db: AsyncSes
)
-############################
-# ToggleFunctionById
-############################
+# Toggle Function By Id
@router.post('/id/{id}/toggle', response_model=FunctionModel | None)
@@ -308,9 +294,8 @@ async def toggle_function_by_id(
data={'type': function.type, 'name': function.name},
)
await dispatch_event_functions(
- request.app,
+ request,
lifecycle_event,
- request=request,
extra_function_ids=[function.id] if not function.is_active else None,
)
schedule_webhook_dispatch(request.app, lifecycle_event)
@@ -339,9 +324,7 @@ async def toggle_function_by_id(
)
-############################
-# ToggleGlobalById
-############################
+# Toggle Global By Id
@router.post('/id/{id}/toggle/global', response_model=FunctionModel | None)
@@ -376,9 +359,7 @@ async def toggle_global_by_id(
)
-############################
-# UpdateFunctionById
-############################
+# Update Function By Id
@router.post('/id/{id}/update', response_model=FunctionModel | None)
@@ -434,9 +415,7 @@ async def _update_function(request, id, form_data, user, db, version_id=None):
)
-############################
-# DeleteFunctionById
-############################
+# Delete Function By Id
@router.delete('/id/{id}/delete', response_model=bool)
@@ -463,9 +442,7 @@ async def delete_function_by_id(
return result
-############################
-# GetFunctionValves
-############################
+# Get Function Valves
@router.get('/id/{id}/valves', response_model=dict | None)
@@ -489,9 +466,7 @@ async def get_function_valves_by_id(
)
-############################
-# GetFunctionValvesSpec
-############################
+# Get Function Valves Spec
@router.get('/id/{id}/valves/spec', response_model=dict | None)
@@ -519,9 +494,7 @@ async def get_function_valves_spec_by_id(
)
-############################
-# UpdateFunctionValves
-############################
+# Update Function Valves
@router.post('/id/{id}/valves/update', response_model=dict | None)
@@ -571,9 +544,7 @@ async def update_function_valves_by_id(
)
-############################
-# FunctionUserValves
-############################
+# Function User Valves
@router.get('/id/{id}/valves/user', response_model=dict | None)
diff --git a/backend/open_webui/routers/groups.py b/backend/open_webui/routers/groups.py
index 5cbb8840bd..f387806381 100755
--- a/backend/open_webui/routers/groups.py
+++ b/backend/open_webui/routers/groups.py
@@ -40,9 +40,7 @@ log = logging.getLogger(__name__)
router = APIRouter()
-############################
-# GetFunctions
-############################
+# Get Functions
@router.get('/', response_model=list[GroupResponse])
@@ -64,9 +62,7 @@ async def get_groups(
return groups
-############################
-# CreateNewGroup
-############################
+# Create New Group
@router.post('/create', response_model=Optional[GroupResponse])
@@ -107,9 +103,7 @@ async def create_new_group(
)
-############################
-# GetGroupById
-############################
+# Get Group By Id
@router.get('/id/{id}', response_model=Optional[GroupResponse])
@@ -142,9 +136,7 @@ async def get_group_info_by_id(id: str, user=Depends(get_verified_user), db: Asy
)
-############################
-# ExportGroupById
-############################
+# Export Group By Id
class GroupExportResponse(GroupResponse):
@@ -168,9 +160,7 @@ async def export_group_by_id(id: str, user=Depends(get_admin_user), db: AsyncSes
)
-############################
-# GetUsersInGroupById
-############################
+# Get Users In Group By Id
@router.post('/id/{id}/users', response_model=list[UserInfoResponse])
@@ -186,9 +176,7 @@ async def get_users_in_group(id: str, user=Depends(get_admin_user), db: AsyncSes
)
-############################
-# UpdateGroupById
-############################
+# Update Group By Id
@router.post('/id/{id}/update', response_model=Optional[GroupResponse])
@@ -231,9 +219,7 @@ async def update_group_by_id(
)
-############################
-# AddUserToGroupByUserIdAndGroupId
-############################
+# Add User To Group By User Id And Group Id
@router.post('/id/{id}/users/add', response_model=Optional[GroupResponse])
@@ -317,9 +303,7 @@ async def remove_users_from_group(
)
-############################
-# DeleteGroupById
-############################
+# Delete Group By Id
@router.delete('/id/{id}/delete', response_model=bool)
@@ -363,9 +347,7 @@ async def delete_group_by_id(
)
-############################
-# PreviewGroupAccess
-############################
+# Preview Group Access
@router.get('/id/{id}/preview')
diff --git a/backend/open_webui/routers/knowledge.py b/backend/open_webui/routers/knowledge.py
index 6b13b798cd..c083e4e477 100644
--- a/backend/open_webui/routers/knowledge.py
+++ b/backend/open_webui/routers/knowledge.py
@@ -44,18 +44,16 @@ from open_webui.routers.retrieval import (
from open_webui.storage.provider import Storage
from open_webui.utils.access_control import filter_allowed_access_grants, has_permission, validate_access_grants
from open_webui.utils.access_control.files import has_access_to_file
-from open_webui.utils.auth import get_admin_user, get_verified_user
+from open_webui.utils.auth import get_admin_user, get_verified_user, get_verified_user_by_id
from open_webui.utils.json_codec import JSONCodec
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
router = APIRouter()
-############################
# getKnowledgeBases
-############################
PAGE_ITEM_COUNT = 30
@@ -79,9 +77,7 @@ async def delete_file_resource(file: FileModel, db: AsyncSession) -> bool:
return result
-############################
# Knowledge Base Embedding
-############################
# Knowledge that sits unread serves no one. Let what is
# stored here find the ones who need it.
@@ -311,9 +307,7 @@ async def search_knowledge_files(
return await Knowledges.search_knowledge_files(filter=filter, skip=skip, limit=limit, db=db)
-############################
-# CreateNewKnowledge
-############################
+# Create New Knowledge
@router.post('/create', response_model=KnowledgeResponse | None)
@@ -322,10 +316,7 @@ async def create_new_knowledge(
form_data: KnowledgeForm,
user=Depends(get_verified_user),
):
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (has_permission, filter_allowed_access_grants, insert_new_knowledge) manage their own sessions.
- # This prevents holding a connection during embed_knowledge_base_metadata()
- # which makes external embedding API calls (1-5+ seconds).
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
if user.role != 'admin' and not await has_permission(
user.id, 'workspace.knowledge', await Config.get('user.permissions')
):
@@ -367,9 +358,7 @@ async def create_new_knowledge(
)
-############################
-# ReindexKnowledgeFiles
-############################
+# Reindex Knowledge Files
@router.post('/reindex', response_model=bool)
@@ -462,9 +451,7 @@ async def reindex_knowledge_files(
return True
-############################
-# ReindexKnowledgeBases
-############################
+# Reindex Knowledge Bases
@router.post('/metadata/reindex', response_model=dict)
@@ -495,9 +482,7 @@ async def reindex_knowledge_base_metadata_embeddings(
return {'total': len(knowledge_bases), 'success': success_count}
-############################
# External Knowledge Sources
-############################
class ExternalKnowledgeSourceForm(BaseModel):
@@ -1079,9 +1064,7 @@ async def update_external_knowledge_source(
return updated
-############################
-# GetKnowledgeById
-############################
+# Get Knowledge By Id
class KnowledgeFilesResponse(KnowledgeResponse):
@@ -1131,9 +1114,7 @@ async def get_knowledge_by_id(id: str, user=Depends(get_verified_user), db: Asyn
)
-############################
-# UpdateKnowledgeById
-############################
+# Update Knowledge By Id
@router.post('/{id}/update', response_model=KnowledgeFilesResponse | None)
@@ -1143,10 +1124,7 @@ async def update_knowledge_by_id(
form_data: KnowledgeForm,
user=Depends(get_verified_user),
):
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations manage their own short-lived sessions internally.
- # This prevents holding a connection during embed_knowledge_base_metadata()
- # which makes external embedding API calls (1-5+ seconds).
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
knowledge = await Knowledges.get_knowledge_by_id(id=id)
if not knowledge:
raise HTTPException(
@@ -1169,6 +1147,12 @@ async def update_knowledge_by_id(
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
+ if form_data.meta is not None:
+ if knowledge.user_id != user.id and user.role != 'admin':
+ raise HTTPException(403, ERROR_MESSAGES.ACCESS_PROHIBITED)
+ if is_external_knowledge(knowledge):
+ external_knowledge_error()
+
knowledge = await Knowledges.update_knowledge_by_id(id=id, form_data=form_data)
if knowledge:
# Re-embed knowledge base for semantic search
@@ -1197,9 +1181,7 @@ async def update_knowledge_by_id(
)
-############################
-# UpdateKnowledgeAccessById
-############################
+# Update Knowledge Access By Id
class KnowledgeAccessGrantsForm(BaseModel):
@@ -1261,9 +1243,7 @@ async def update_knowledge_access_by_id(
return response
-############################
-# GetPendingKnowledgeFiles
-############################
+# Get Pending Knowledge Files
@router.get('/{id}/files/pending')
@@ -1283,10 +1263,7 @@ async def get_pending_knowledge_files(
When ``stream=true``, returns an SSE stream that polls every 3 seconds
and emits the current pending file list. Closes when no files remain.
"""
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations manage their own short-lived sessions internally.
- # Holding a session here would keep a connection for the entire stream
- # (up to an hour) and exhaust the connection pool under concurrent load.
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
knowledge = await Knowledges.get_knowledge_by_id(id=id)
if not knowledge:
raise HTTPException(
@@ -1322,15 +1299,29 @@ async def get_pending_knowledge_files(
break
await asyncio.sleep(3)
+ # Access can be revoked while the stream is open.
+ refreshed_user = await get_verified_user_by_id(user.id)
+ if not refreshed_user:
+ break
+ if not (
+ refreshed_user.role == 'admin'
+ or knowledge.user_id == refreshed_user.id
+ or await AccessGrants.has_access(
+ user_id=refreshed_user.id,
+ resource_type='knowledge',
+ resource_id=knowledge_id,
+ permission='read',
+ )
+ ):
+ break
+
return StreamingResponse(
event_stream(id),
media_type='text/event-stream',
)
-############################
-# GetKnowledgeFilesById
-############################
+# Get Knowledge Files By Id
@router.get('/{id}/files', response_model=KnowledgeFileListResponse)
@@ -1397,9 +1388,66 @@ async def get_knowledge_files_by_id(
return await Knowledges.search_files_by_id(id, user.id, filter=filter, skip=skip, limit=limit, db=db)
-############################
-# AddFileToKnowledge
-############################
+# Add File To Knowledge
+
+
+async def check_knowledge_upload_limits(
+ knowledge_id: str,
+ count: int,
+ *,
+ batch: bool = False,
+ file_size: int | None = None,
+ exclude_file_ids: list[str] | None = None,
+ db=None,
+) -> None:
+ if batch:
+ batch_limit = await Config.get('knowledge.max_upload_count')
+ if batch_limit is not None and count > int(batch_limit):
+ raise HTTPException(400, f'You can only upload a maximum of {batch_limit} file(s) per batch.')
+
+ knowledge = await Knowledges.get_knowledge_by_id(knowledge_id, db=db)
+ if not knowledge:
+ raise HTTPException(404, ERROR_MESSAGES.NOT_FOUND)
+ limits = await Knowledges.get_file_limits(knowledge.meta)
+
+ if file_size is not None:
+ for max_size in (await Config.get('rag.file.max_size'), limits['max_file_size']):
+ if max_size and file_size > int(max_size) * 1024 * 1024:
+ raise HTTPException(413, ERROR_MESSAGES.FILE_TOO_LARGE(size=f'{max_size} MB'))
+
+ limit = limits['max_file_count']
+ if limit is not None and count > 0:
+ current_count = await Knowledges.get_file_count_by_id(
+ knowledge_id, include_pending=True, exclude_file_ids=exclude_file_ids, db=db
+ )
+ if current_count + count > int(limit):
+ raise HTTPException(400, f'Knowledge base file limit exceeded ({limit} files maximum).')
+
+
+class KnowledgeUploadValidationForm(BaseModel):
+ count: int = Field(ge=0)
+ file_size: int | None = Field(default=None, ge=0)
+ removed_file_ids: list[str] = Field(default_factory=list)
+
+
+@router.post('/{id}/files/validate')
+async def validate_knowledge_upload(
+ id: str,
+ form_data: KnowledgeUploadValidationForm,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await _verify_knowledge_write_access(id, user, db)
+ # This is a preflight only. Actual additions recheck capacity without removal credits.
+ await check_knowledge_upload_limits(
+ id,
+ form_data.count,
+ batch=True,
+ file_size=form_data.file_size,
+ exclude_file_ids=form_data.removed_file_ids,
+ db=db,
+ )
+ return {'status': True}
class KnowledgeFileIdForm(BaseModel):
@@ -1462,24 +1510,34 @@ async def add_file_to_knowledge_by_id(
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
- # Add content to the vector database
+ already_linked = await Knowledges.has_file(knowledge_id=id, file_id=form_data.file_id, db=db)
+ if not already_linked:
+ await check_knowledge_upload_limits(
+ id, 1, batch=True, file_size=(file.meta or {}).get('size', 0), exclude_file_ids=[form_data.file_id], db=db
+ )
+
+ linked = None
try:
+ # Claim capacity atomically before indexing into the knowledge collection.
+ if not already_linked:
+ linked = await Knowledges.add_file_to_knowledge_by_id(
+ knowledge_id=id,
+ file_id=form_data.file_id,
+ user_id=user.id,
+ directory_id=form_data.directory_id,
+ db=db,
+ )
+ if not linked:
+ raise ValueError(f'Failed to link file {form_data.file_id} to knowledge {id}')
await process_file(
request,
ProcessFileForm(file_id=form_data.file_id, collection_name=id),
user=user,
db=db,
)
-
- # Add file to knowledge base
- await Knowledges.add_file_to_knowledge_by_id(
- knowledge_id=id,
- file_id=form_data.file_id,
- user_id=user.id,
- directory_id=form_data.directory_id,
- db=db,
- )
except Exception as e:
+ if linked:
+ await Knowledges.remove_file_from_knowledge_by_id(id, form_data.file_id, db=db)
log.debug(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -1590,9 +1648,7 @@ async def update_file_from_knowledge_by_id(
)
-############################
-# RemoveFileFromKnowledge
-############################
+# Remove File From Knowledge
@router.post('/{id}/file/remove', response_model=KnowledgeFilesResponse | None)
@@ -1679,9 +1735,7 @@ async def remove_file_from_knowledge_by_id(
)
-############################
-# DeleteKnowledgeById
-############################
+# Delete Knowledge By Id
@router.delete('/{id}/delete', response_model=bool)
@@ -1769,9 +1823,7 @@ async def delete_knowledge_by_id(
return result
-############################
-# ResetKnowledgeById
-############################
+# Reset Knowledge By Id
@router.post('/{id}/reset', response_model=KnowledgeResponse | None)
@@ -1831,9 +1883,7 @@ async def reset_knowledge_by_id(
return knowledge
-############################
-# SyncKnowledgeDiff
-############################
+# Sync Knowledge Diff
class FileManifestEntry(BaseModel):
@@ -1870,7 +1920,7 @@ async def sync_knowledge_diff(
"""
await _verify_knowledge_write_access(id, user, db)
- # ── Index existing state ──
+ # Index existing state
existing_directories = await Knowledges.get_all_directories(id, db=db)
# Build directory path lookups
@@ -1911,7 +1961,7 @@ async def sync_knowledge_diff(
'checksum': stored_checksum,
}
- # ── Diff files ──
+ # Diff files
added: list[dict] = []
modified: list[dict] = []
deleted: list[dict] = []
@@ -1943,7 +1993,19 @@ async def sync_knowledge_diff(
if key not in manifest_keys:
deleted.append({'file_id': file_info['file_id'], 'filename': key[1]})
- # ── Diff directories ──
+ changed_keys = {(entry['path'], entry['filename']) for entry in added + modified}
+ await check_knowledge_upload_limits(
+ id,
+ len(added) + len(modified),
+ file_size=max(
+ (entry.size for entry in form_data.manifest if (entry.path, entry.filename) in changed_keys), default=0
+ ),
+ batch=True,
+ exclude_file_ids=[entry['file_id'] for entry in deleted] + [entry['stale_file_id'] for entry in modified],
+ db=db,
+ )
+
+ # Diff directories
required_directory_paths: set[str] = set()
for entry in form_data.manifest:
if entry.path:
@@ -1967,9 +2029,7 @@ async def sync_knowledge_diff(
)
-############################
-# SyncKnowledgeCleanup
-############################
+# Sync Knowledge Cleanup
class SyncCleanupForm(BaseModel):
@@ -1990,7 +2050,7 @@ async def sync_knowledge_cleanup(
"""
await _verify_knowledge_write_access(id, user, db)
- # ── Remove deleted files ──
+ # Remove deleted files
for file_id in form_data.file_ids:
file = await Files.get_file_by_id(file_id, db=db)
if not file:
@@ -2017,7 +2077,7 @@ async def sync_knowledge_cleanup(
):
await delete_file_resource(file, db)
- # ── Remove orphaned directories (children before parents) ──
+ # Remove orphaned directories (children before parents)
for dir_id in reversed(form_data.dir_ids):
# Only delete directories that belong to this knowledge base.
directory = await Knowledges.get_directory_by_id(dir_id, db=db)
@@ -2028,9 +2088,7 @@ async def sync_knowledge_cleanup(
return {'status': True}
-############################
-# AddFilesToKnowledge
-############################
+# Add Files To Knowledge
@router.post('/{id}/files/batch/add', response_model=KnowledgeFilesResponse | None)
@@ -2069,6 +2127,10 @@ async def add_files_to_knowledge_batch(
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
+ batch_limit = await Config.get('knowledge.max_upload_count')
+ if batch_limit is not None and len(form_data) > int(batch_limit):
+ raise HTTPException(400, f'You can only upload a maximum of {batch_limit} file(s) per batch.')
+
for directory_id in {form.directory_id for form in form_data if form.directory_id}:
await _verify_directory_in_knowledge(id, directory_id, db, detail='Target directory not found.')
@@ -2112,8 +2174,29 @@ async def add_files_to_knowledge_batch(
new_file_ids = {form.file_id for form in new_entries}
files = [f for f in files if f.id in new_file_ids]
- # Process files
+ await check_knowledge_upload_limits(
+ id,
+ len(files),
+ file_size=max(((file.meta or {}).get('size', 0) or 0 for file in files), default=0),
+ exclude_file_ids=list(new_file_ids),
+ db=db,
+ )
+
+ # Claim slots before embedding; release them if processing fails.
+ reserved_ids = []
+ dir_map = {form.file_id: form.directory_id for form in new_entries}
try:
+ for file in files:
+ linked = await Knowledges.add_file_to_knowledge_by_id(
+ knowledge_id=id,
+ file_id=file.id,
+ user_id=user.id,
+ directory_id=dir_map.get(file.id),
+ db=db,
+ )
+ if not linked:
+ raise ValueError(f'Failed to link file {file.id} to knowledge {id}')
+ reserved_ids.append(file.id)
result = await process_files_batch(
request=request,
form_data=BatchProcessFilesForm(files=files, collection_name=id),
@@ -2121,20 +2204,14 @@ async def add_files_to_knowledge_batch(
db=db,
)
except Exception as e:
+ for file_id in reserved_ids:
+ await Knowledges.remove_file_from_knowledge_by_id(id, file_id, db=db)
log.error(f'add_files_to_knowledge_batch: Exception occurred: {e}', exc_info=True)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
- # Only add files that were successfully processed
successful_file_ids = [r.file_id for r in result.results if r.status == 'completed']
- dir_map = {form.file_id: form.directory_id for form in new_entries}
- for file_id in successful_file_ids:
- await Knowledges.add_file_to_knowledge_by_id(
- knowledge_id=id,
- file_id=file_id,
- user_id=user.id,
- directory_id=dir_map.get(file_id),
- db=db,
- )
+ for file_id in set(reserved_ids) - set(successful_file_ids):
+ await Knowledges.remove_file_from_knowledge_by_id(id, file_id, db=db)
# If there were any errors, include them in the response
if result.errors:
@@ -2154,9 +2231,7 @@ async def add_files_to_knowledge_batch(
)
-############################
-# ExportKnowledgeById
-############################
+# Export Knowledge By Id
@router.get('/{id}/export')
@@ -2202,9 +2277,7 @@ async def export_knowledge_by_id(id: str, user=Depends(get_admin_user), db: Asyn
)
-############################
# Directory endpoints
-############################
class KnowledgeDirectoryCreateForm(BaseModel):
diff --git a/backend/open_webui/routers/memories.py b/backend/open_webui/routers/memories.py
index b4d1c346b4..dc25625864 100644
--- a/backend/open_webui/routers/memories.py
+++ b/backend/open_webui/routers/memories.py
@@ -45,11 +45,9 @@ async def check_memories_permission(user):
)
-############################
-# GetMemories
+# Get Memories
# Let what is remembered here spare someone the cost
# of learning it twice.
-############################
@router.get('/', response_model=list[MemoryModel])
@@ -63,9 +61,7 @@ async def get_memories(
return await Memories.get_memories_by_user_id(user.id, db=db)
-############################
-# AddMemory
-############################
+# Add Memory
class AddMemoryForm(BaseModel):
@@ -316,9 +312,7 @@ async def update_memories(
return response
-############################
-# QueryMemory
-############################
+# Query Memory
class QueryMemoryForm(BaseModel):
@@ -332,10 +326,7 @@ async def query_memory(
form_data: QueryMemoryForm,
user=Depends(get_verified_user),
):
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (get_memories_by_user_id) manage their own short-lived sessions.
- # This prevents holding a connection during EMBEDDING_FUNCTION()
- # which makes external embedding API calls (1-5+ seconds).
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
await check_memories_permission(user)
memories = await Memories.get_memories_by_user_id(user.id)
@@ -352,12 +343,7 @@ async def query_memory(
limit=form_data.k,
)
- # Filter results by relevance threshold to avoid returning unrelated
- # memories. Vector similarity search always returns the top-K nearest
- # neighbours even when they are completely irrelevant; applying the
- # same RELEVANCE_THRESHOLD used by RAG ensures only genuinely matching
- # memories are surfaced (distances are normalised to 0→1, higher is
- # better).
+ # Apply the RAG relevance threshold; top-K results can include unrelated memories.
relevance_threshold = await Config.get('rag.relevance_threshold', 0.0)
if results and relevance_threshold > 0.0 and results.distances and results.distances[0]:
from open_webui.retrieval.vector.main import SearchResult
@@ -442,9 +428,7 @@ async def read_memory_path(
}
-############################
-# ReindexMemoryVectorDB
-############################
+# Reindex Memory Vector DB
@router.post('/reindex')
async def reindex_memories_from_vector_db(
request: Request,
@@ -506,9 +490,7 @@ async def reset_memory_from_vector_db(
return True
-############################
-# DeleteMemoriesByUserId
-############################
+# Delete Memories By User Id
@router.delete('/delete/user', response_model=bool)
@@ -538,9 +520,7 @@ async def delete_memory_by_user_id(
return False
-############################
-# UpdateMemoryById
-############################
+# Update Memory By Id
@router.post('/{memory_id}/update', response_model=MemoryModel | None)
@@ -550,10 +530,7 @@ async def update_memory_by_id(
form_data: MemoryUpdateModel,
user=Depends(get_verified_user),
):
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (update_memory_by_id_and_user_id) manage their own
- # short-lived sessions. This prevents holding a connection during
- # EMBEDDING_FUNCTION() which makes external API calls (1-5+ seconds).
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
await check_memories_permission(user)
content = clean_memory_content(form_data.content) if form_data.content is not None else None
@@ -602,9 +579,7 @@ async def update_memory_by_id(
return memory
-############################
-# DeleteMemoryById
-############################
+# Delete Memory By Id
@router.delete('/{memory_id}', response_model=bool)
diff --git a/backend/open_webui/routers/models.py b/backend/open_webui/routers/models.py
index f9e7ed74dc..91558b0c04 100644
--- a/backend/open_webui/routers/models.py
+++ b/backend/open_webui/routers/models.py
@@ -214,11 +214,7 @@ async def _verify_knowledge_file_access(
)
-###########################
-# GetModels
-# Let each model here be judged by what it does and not
-# by what it claims. The house deserves honest servants.
-###########################
+# Get Models
PAGE_ITEM_COUNT = 30
@@ -302,9 +298,7 @@ async def get_models(
)
-###########################
-# GetBaseModels
-###########################
+# Get Base Models
@router.get('/all', response_model=list[ModelResponse])
@@ -327,9 +321,7 @@ async def get_base_models(
return await Models.get_base_models(tag=tag, db=db)
-###########################
-# GetModelTags
-###########################
+# Get Model Tags
@router.get('/tags', response_model=list[str])
@@ -342,9 +334,7 @@ async def get_model_tags(user=Depends(get_verified_user), db: AsyncSession = Dep
return sorted(tags)
-############################
-# CreateNewModel
-############################
+# Create New Model
@router.post('/create', response_model=ModelModel | None)
@@ -436,9 +426,7 @@ async def create_new_model(
return model_response(model)
-############################
-# ExportModels
-############################
+# Export Models
class ModelExportResponse(ModelModel):
@@ -496,9 +484,7 @@ async def export_models(
return exported
-############################
-# ImportModels
-############################
+# Import Models
class ModelsImportForm(BaseModel):
@@ -737,9 +723,7 @@ async def import_models(
raise HTTPException(status_code=500, detail=str(e))
-############################
-# SyncModels
-############################
+# Sync Models
class SyncModelsForm(BaseModel):
@@ -776,9 +760,7 @@ async def sync_models(
return models
-###########################
-# GetModelById
-###########################
+# Get Model By Id
class ModelIdForm(BaseModel):
@@ -835,9 +817,7 @@ async def get_model_by_id(id: str, user=Depends(get_verified_user), db: AsyncSes
)
-###########################
-# GetModelById
-###########################
+# Get Model By Id
async def authorized_model_history(id, user, db):
@@ -1084,9 +1064,7 @@ async def get_model_profile_image(
)
-############################
-# ToggleModelById
-############################
+# Toggle Model By Id
@router.post('/model/toggle', response_model=ModelResponse | None)
@@ -1135,9 +1113,7 @@ async def toggle_model_by_id(
)
-############################
-# UpdateModelById
-############################
+# Update Model By Id
@router.post('/model/update', response_model=ModelModel | None)
@@ -1212,9 +1188,7 @@ async def update_model_by_id(
return model_response(model)
-############################
-# UpdateModelAccessById
-############################
+# Update Model Access By Id
class ModelAccessGrantsForm(BaseModel):
@@ -1294,9 +1268,7 @@ async def update_model_access_by_id(
return model_response(model)
-############################
-# DeleteModelById
-############################
+# Delete Model By Id
@router.post('/model/delete', response_model=bool)
diff --git a/backend/open_webui/routers/notes.py b/backend/open_webui/routers/notes.py
index 04a447e96c..f0438425b5 100644
--- a/backend/open_webui/routers/notes.py
+++ b/backend/open_webui/routers/notes.py
@@ -95,9 +95,7 @@ async def leave_note_rooms_for_revoked_users(
await leave_room_for_users(room, user_ids)
-############################
-# GetNotes
-############################
+# Get Notes
class NoteItemResponse(BaseModel):
@@ -148,9 +146,7 @@ async def get_notes(
]
-############################
-# GetPinnedNotes
-############################
+# Get Pinned Notes
@router.get('/pinned', response_model=list[NoteItemResponse])
@@ -229,9 +225,7 @@ async def search_notes(
return result
-############################
-# CreateNewNote
-############################
+# Create New Note
@router.post('/create', response_model=Optional[NoteModel])
@@ -270,9 +264,7 @@ async def create_new_note(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
-############################
-# GetNoteById
-############################
+# Get Note By Id
class NoteResponse(NoteModel):
@@ -521,9 +513,7 @@ async def create_note_chat_by_id(
return chat
-############################
-# UpdateNoteById
-############################
+# Update Note By Id
@router.post('/{id}/update', response_model=Optional[NoteModel])
@@ -609,9 +599,7 @@ async def update_note_pages(
return await update_note_by_id(request, id, NoteUpdateForm(page_operation=form_data), user, db)
-############################
-# UpdateNoteAccessById
-############################
+# Update Note Access By Id
class NoteAccessGrantsForm(BaseModel):
@@ -667,9 +655,7 @@ async def update_note_access_by_id(
return note
-############################
-# PinNoteById
-############################
+# Pin Note By Id
@router.post('/{id}/pin', response_model=Optional[NoteModel])
@@ -710,9 +696,7 @@ async def pin_note_by_id(
return note
-############################
-# DeleteNoteById
-############################
+# Delete Note By Id
@router.delete('/{id}/delete', response_model=bool)
diff --git a/backend/open_webui/routers/notifications.py b/backend/open_webui/routers/notifications.py
index 6cc098392f..894e29c9c5 100644
--- a/backend/open_webui/routers/notifications.py
+++ b/backend/open_webui/routers/notifications.py
@@ -1,8 +1,16 @@
from __future__ import annotations
from typing import Any
+import logging
+import time
+from uuid import UUID
-from fastapi import APIRouter, Depends, HTTPException, Request, status
+from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
+from sqlalchemy import and_, func, or_, select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+from open_webui.internal.db import get_async_session
+from open_webui.models.notifications import Notification, emit_changes
+from open_webui.utils.inbox import hydrate, visible_clause
from pydantic import BaseModel
from open_webui.constants import ERROR_MESSAGES
@@ -21,6 +29,121 @@ from open_webui.utils.notifications import (
router = APIRouter()
+log = logging.getLogger(__name__)
+
+
+async def _check_notifications_enabled():
+ if not await Config.get('notifications.enable'):
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
+
+
+async def inbox_page(user, cursor=None, limit=20, clause=None, *, db):
+ started = time.monotonic()
+ if clause is None:
+ clause = await visible_clause(user, db=db)
+ query = select(Notification).where(clause)
+ if cursor:
+ try:
+ timestamp, id = cursor.split(':', 1)
+ timestamp = int(timestamp)
+ UUID(id)
+ if not 0 <= timestamp <= 2**63 - 1:
+ raise ValueError()
+ except (ValueError, TypeError):
+ raise HTTPException(422, 'Invalid inbox cursor')
+ query = query.where(
+ or_(Notification.created_at < timestamp, and_(Notification.created_at == timestamp, Notification.id < id))
+ )
+ rows = (
+ await db.scalars(query.order_by(Notification.created_at.desc(), Notification.id.desc()).limit(limit + 1))
+ ).all()
+ more = len(rows) > limit
+ rows = rows[:limit]
+ result = {
+ 'items': await hydrate(rows, db=db),
+ 'next_cursor': f'{rows[-1].created_at}:{rows[-1].id}' if more else None,
+ }
+ log.debug('Inbox page loaded in %.3fs', time.monotonic() - started)
+ return result
+
+
+@router.get('/inbox')
+async def get_inbox(
+ cursor: str | None = Query(None, max_length=100),
+ limit: int = Query(20, ge=1, le=50),
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ await _check_notifications_enabled()
+ return await inbox_page(user, cursor, limit, db=db)
+
+
+@router.get('/inbox/count')
+async def get_inbox_count(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
+ await _check_notifications_enabled()
+ started = time.monotonic()
+ clause = await visible_clause(user, db=db)
+ count = await db.scalar(
+ select(func.count()).select_from(Notification).where(clause, Notification.seen_at.is_(None))
+ )
+ log.debug('Inbox count loaded in %.3fs', time.monotonic() - started)
+ return {'count': count}
+
+
+@router.post('/inbox/open')
+async def open_inbox(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
+ await _check_notifications_enabled()
+ clause = await visible_clause(user, db=db)
+ now = time.time_ns()
+ # A single UPDATE acknowledges only rows visible to this statement. A late
+ # commit with an older created_at must remain unseen (no timestamp watermark).
+ result = await db.execute(
+ update(Notification)
+ .where(clause, Notification.seen_at.is_(None))
+ .values(seen_at=now, updated_at=now)
+ .returning(Notification.id)
+ .execution_options(synchronize_session=False)
+ )
+ # SQLite reports rowcount=-1 for UPDATEs containing the recursive folder CTE.
+ acknowledged = len(result.scalars().all())
+ await db.commit()
+ await emit_changes({user.id})
+ page = await inbox_page(user, clause=clause, db=db)
+ for item in page['items']:
+ item['is_new'] = item['seen_at'] == str(now) or item['seen_at'] is None
+ page.update(
+ acknowledged_count=acknowledged,
+ acknowledged_at=str(now),
+ count=await db.scalar(
+ select(func.count()).select_from(Notification).where(clause, Notification.seen_at.is_(None))
+ ),
+ )
+ return page
+
+
+@router.patch('/inbox/{id}')
+async def read_inbox_item(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
+ await _check_notifications_enabled()
+ clause = await visible_clause(user, db=db)
+ now = time.time_ns()
+ row = await db.scalar(
+ update(Notification)
+ .where(clause, Notification.id == id)
+ .values(
+ seen_at=func.coalesce(Notification.seen_at, now),
+ read_at=func.coalesce(Notification.read_at, now),
+ updated_at=now,
+ )
+ .returning(Notification)
+ .execution_options(populate_existing=True)
+ )
+ if not row:
+ raise HTTPException(404, 'Notification not found')
+ response = (await hydrate([row], db=db))[0]
+ await db.commit()
+ await emit_changes({user.id})
+ return response
+
class NotificationTargetForm(BaseModel):
id: str | None = None
diff --git a/backend/open_webui/routers/ollama.py b/backend/open_webui/routers/ollama.py
index 2d2b0fe397..40c4fd6b59 100644
--- a/backend/open_webui/routers/ollama.py
+++ b/backend/open_webui/routers/ollama.py
@@ -189,11 +189,7 @@ def get_api_key(idx, url, configs):
return configs.get(str(idx), configs.get(base_url, {})).get('key', None) # Legacy support
-##########################################
-#
# API routes
-#
-##########################################
router = APIRouter()
@@ -1138,10 +1134,7 @@ async def generate_chat_completion(
if not await Config.get('ollama.enable'):
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
- # This prevents holding a connection during the entire LLM call (30-60+ seconds),
- # which would exhaust the connection pool under concurrent load.
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
# bypass_filter and bypass_system_prompt are read from request.state to prevent
# external clients from setting them via query parameter. Only internal
@@ -1254,10 +1247,7 @@ async def generate_openai_completion(
user=Depends(get_verified_user), # noqa: B008
):
"""Forward a text completion request via the OpenAI-compatible proxy."""
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
- # This prevents holding a connection during the entire LLM call (30-60+ seconds),
- # which would exhaust the connection pool under concurrent load.
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
metadata = form_data.pop('metadata', None)
try:
@@ -1359,10 +1349,7 @@ async def generate_openai_chat_completion(
user=Depends(get_verified_user), # noqa: B008
):
"""Forward a chat completion request via the OpenAI-compatible proxy."""
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
- # This prevents holding a connection during the entire LLM call (30-60+ seconds),
- # which would exhaust the connection pool under concurrent load.
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
metadata = form_data.pop('metadata', None)
try:
diff --git a/backend/open_webui/routers/openai.py b/backend/open_webui/routers/openai.py
index 55b06eb42a..6e1229ed7b 100644
--- a/backend/open_webui/routers/openai.py
+++ b/backend/open_webui/routers/openai.py
@@ -4,6 +4,7 @@ import asyncio
import hashlib
import logging
import re
+import time
from typing import Optional
from urllib.parse import quote, urlparse
@@ -48,6 +49,7 @@ from open_webui.utils.payload import (
apply_model_params_to_body_openai,
apply_system_prompt_to_body,
)
+from open_webui.utils.response import convert_responses_usage_to_chat_completions, get_responses_finish_reason
from open_webui.utils.session_pool import (
cleanup_response,
get_client_timeout,
@@ -60,13 +62,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
-##########################################
-#
# Utility functions
# Let the responses returned through this gate be worth
# the question that summoned them.
-#
-##########################################
# Headers that become stale after aiohttp auto-decompresses the upstream
# response body. Forwarding them verbatim causes desktop / programmatic
@@ -150,11 +148,7 @@ def openai_reasoning_model_handler(payload):
return payload
-##########################################
-#
# API routes
-#
-##########################################
router = APIRouter()
@@ -1363,12 +1357,15 @@ def convert_responses_result(response: dict) -> dict:
output_items = response.get('output', [])
content = ''
+ refusal = ''
tool_calls = []
for item in output_items:
if item.get('type') == 'message':
for part in item.get('content', []):
if part.get('type') == 'output_text':
content += part.get('text', '')
+ elif part.get('type') == 'refusal':
+ refusal += part.get('refusal', '')
elif item.get('type') == 'function_call':
arguments = item.get('arguments', '{}')
if not isinstance(arguments, str):
@@ -1387,6 +1384,7 @@ def convert_responses_result(response: dict) -> dict:
return {
'id': response.get('id', ''),
'object': 'chat.completion',
+ 'created': response.get('created_at') or int(time.time()),
'model': response.get('model', ''),
'choices': [
{
@@ -1394,12 +1392,13 @@ def convert_responses_result(response: dict) -> dict:
'message': {
'role': 'assistant',
'content': content,
+ **({'refusal': refusal} if refusal else {}),
**({'tool_calls': tool_calls} if tool_calls else {}),
},
- 'finish_reason': 'tool_calls' if tool_calls else 'stop',
+ 'finish_reason': get_responses_finish_reason(response, bool(tool_calls)),
}
],
- 'usage': response.get('usage', {}),
+ 'usage': convert_responses_usage_to_chat_completions(response.get('usage')) or None,
}
@@ -1412,10 +1411,7 @@ async def generate_chat_completion(
if not await Config.get('openai.enable'):
raise HTTPException(status_code=503, detail='OpenAI API is disabled')
- # NOTE: We intentionally do NOT use Depends(get_async_session) here.
- # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
- # This prevents holding a connection during the entire LLM call (30-60+ seconds),
- # which would exhaust the connection pool under concurrent load.
+ # Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
# bypass_filter and bypass_system_prompt are read from request.state to prevent
# external clients from setting them via query parameter. Only internal
diff --git a/backend/open_webui/routers/pipelines.py b/backend/open_webui/routers/pipelines.py
index 753c9fc77f..1fe70a1dba 100644
--- a/backend/open_webui/routers/pipelines.py
+++ b/backend/open_webui/routers/pipelines.py
@@ -29,13 +29,9 @@ from starlette.responses import FileResponse
log = logging.getLogger(__name__)
-##################################
-#
# Pipeline Middleware
# Every hand this passes through can corrupt it or
# improve it. Let each stage leave it better than it found.
-#
-##################################
def get_sorted_filters(model_id, models):
@@ -192,11 +188,7 @@ async def process_pipeline_outlet_filter(request, payload, user, models):
return payload
-##################################
-#
# Pipelines Endpoints
-#
-##################################
router = APIRouter()
diff --git a/backend/open_webui/routers/prompts.py b/backend/open_webui/routers/prompts.py
index 28b1e7b685..fb8fdc0f9a 100644
--- a/backend/open_webui/routers/prompts.py
+++ b/backend/open_webui/routers/prompts.py
@@ -44,11 +44,9 @@ router = APIRouter()
PAGE_ITEM_COUNT = 30
-############################
-# GetPrompts
+# Get Prompts
# The hardest part is knowing what to ask. Let the right
# question already be here when it is needed.
-############################
@router.get('/', response_model=list[PromptModel])
@@ -135,9 +133,7 @@ async def get_prompt_list(
)
-############################
-# CreateNewPrompt
-############################
+# Create New Prompt
@router.post('/create', response_model=PromptModel | None)
@@ -197,9 +193,7 @@ async def create_new_prompt(
)
-############################
-# GetPromptById
-############################
+# Get Prompt By Id
@router.get('/id/{prompt_id}', response_model=PromptAccessResponse | None)
@@ -241,9 +235,7 @@ async def get_prompt_by_id(
)
-############################
-# UpdatePromptById
-############################
+# Update Prompt By Id
@router.post('/id/{prompt_id}/update', response_model=PromptModel | None)
@@ -307,9 +299,7 @@ async def update_prompt_by_id(
)
-############################
-# UpdatePromptMetadata
-############################
+# Update Prompt Metadata
@router.post('/id/{prompt_id}/update/meta', response_model=PromptModel | None)
@@ -421,9 +411,7 @@ async def set_prompt_version(
)
-############################
-# UpdatePromptAccessById
-############################
+# Update Prompt Access By Id
class PromptAccessGrantsForm(BaseModel):
@@ -482,9 +470,7 @@ async def update_prompt_access_by_id(
return updated_prompt
-############################
-# TogglePromptActiveById
-############################
+# Toggle Prompt Active By Id
@router.post('/id/{prompt_id}/toggle', response_model=PromptModel | None)
@@ -535,9 +521,7 @@ async def toggle_prompt_active(
)
-############################
-# DeletePromptById
-############################
+# Delete Prompt By Id
@router.delete('/id/{prompt_id}/delete', response_model=bool)
@@ -583,9 +567,7 @@ async def delete_prompt_by_id(
return result
-############################
# Prompt History Endpoints
-############################
@router.get('/id/{prompt_id}/history', response_model=list[PromptHistoryResponse])
diff --git a/backend/open_webui/routers/retrieval.py b/backend/open_webui/routers/retrieval.py
index d2a6857c06..072a3d2df1 100644
--- a/backend/open_webui/routers/retrieval.py
+++ b/backend/open_webui/routers/retrieval.py
@@ -135,13 +135,9 @@ log = logging.getLogger(__name__)
TIKTOKEN_DISALLOWED_SPECIAL = ()
-##########################################
-#
# Utility functions
-# Give us this day our relevant chunks, and lead us
-# not into hallucination, but deliver us from noise.
-#
-##########################################
+# Let us find what is true among the many voices,
+# and let us not mistake the loudest answer for the wisest.
def get_ef(
@@ -240,11 +236,7 @@ def get_rf(
return rf
-##########################################
-#
# API routes
-#
-##########################################
RETRIEVAL_CONFIG_KEYS = {
@@ -305,6 +297,9 @@ RETRIEVAL_CONFIG_KEYS = {
'FILE_IMAGE_COMPRESSION_HEIGHT': 'file.image_compression_height',
'FILE_IMAGE_COMPRESSION_WIDTH': 'file.image_compression_width',
'FILE_MAX_COUNT': 'rag.file.max_count',
+ 'KNOWLEDGE_MAX_UPLOAD_COUNT': 'knowledge.max_upload_count',
+ 'KNOWLEDGE_MAX_FILE_COUNT': 'knowledge.max_file_count',
+ 'KNOWLEDGE_MAX_FILE_SIZE': 'knowledge.max_file_size',
'FILE_MAX_SIZE': 'rag.file.max_size',
'FIRECRAWL_API_BASE_URL': 'web.loader.firecrawl_api_url',
'FIRECRAWL_API_KEY': 'web.loader.firecrawl_api_key',
@@ -684,6 +679,9 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)):
# File upload settings
'FILE_MAX_SIZE': config['rag.file.max_size'],
'FILE_MAX_COUNT': config['rag.file.max_count'],
+ 'KNOWLEDGE_MAX_UPLOAD_COUNT': config['knowledge.max_upload_count'],
+ 'KNOWLEDGE_MAX_FILE_COUNT': config['knowledge.max_file_count'],
+ 'KNOWLEDGE_MAX_FILE_SIZE': config['knowledge.max_file_size'],
'FILE_IMAGE_COMPRESSION_WIDTH': config['file.image_compression_width'],
'FILE_IMAGE_COMPRESSION_HEIGHT': config['file.image_compression_height'],
'ALLOWED_FILE_EXTENSIONS': config['rag.file.allowed_extensions'],
@@ -935,6 +933,9 @@ class ConfigForm(BaseModel):
# File upload settings
FILE_MAX_SIZE: Union[int, str | None] = None
FILE_MAX_COUNT: Union[int, str | None] = None
+ KNOWLEDGE_MAX_UPLOAD_COUNT: Union[int, str | None] = None
+ KNOWLEDGE_MAX_FILE_COUNT: Union[int, str | None] = None
+ KNOWLEDGE_MAX_FILE_SIZE: Union[int, str | None] = None
FILE_IMAGE_COMPRESSION_WIDTH: Union[int, str | None] = None
FILE_IMAGE_COMPRESSION_HEIGHT: Union[int, str | None] = None
ALLOWED_FILE_EXTENSIONS: list[str] | None = None
@@ -998,10 +999,35 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
}
if form_data.RAG_TOKENIZER_MODEL is not None:
updates['rag.tokenizer_model'] = form_data.RAG_TOKENIZER_MODEL.strip()
- for field in ('FILE_MAX_SIZE', 'FILE_MAX_COUNT', 'FILE_IMAGE_COMPRESSION_WIDTH', 'FILE_IMAGE_COMPRESSION_HEIGHT'):
+ for field in (
+ 'FILE_MAX_SIZE',
+ 'FILE_MAX_COUNT',
+ 'KNOWLEDGE_MAX_UPLOAD_COUNT',
+ 'KNOWLEDGE_MAX_FILE_COUNT',
+ 'KNOWLEDGE_MAX_FILE_SIZE',
+ 'FILE_IMAGE_COMPRESSION_WIDTH',
+ 'FILE_IMAGE_COMPRESSION_HEIGHT',
+ ):
if getattr(form_data, field) == '':
updates[RETRIEVAL_CONFIG_KEYS[field]] = None
+ for field, label in (
+ ('KNOWLEDGE_MAX_UPLOAD_COUNT', 'Knowledge batch upload limit'),
+ ('KNOWLEDGE_MAX_FILE_COUNT', 'Knowledge file count limit'),
+ ('KNOWLEDGE_MAX_FILE_SIZE', 'Knowledge file size limit'),
+ ):
+ value = getattr(form_data, field)
+ if field in form_data.model_fields_set and value is None:
+ updates[RETRIEVAL_CONFIG_KEYS[field]] = None
+ if value not in (None, ''):
+ try:
+ value = int(value)
+ if value <= 0:
+ raise ValueError
+ except (TypeError, ValueError):
+ raise HTTPException(400, f'{label} must be a positive integer.')
+ updates[RETRIEVAL_CONFIG_KEYS[field]] = value
+
# Unload the previous internal reranker before applying its new settings.
if config['rag.reranking_engine'] == '':
request.app.state.rf = None
@@ -1116,6 +1142,9 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
# File upload settings
'FILE_MAX_SIZE': config['rag.file.max_size'],
'FILE_MAX_COUNT': config['rag.file.max_count'],
+ 'KNOWLEDGE_MAX_UPLOAD_COUNT': config['knowledge.max_upload_count'],
+ 'KNOWLEDGE_MAX_FILE_COUNT': config['knowledge.max_file_count'],
+ 'KNOWLEDGE_MAX_FILE_SIZE': config['knowledge.max_file_size'],
'FILE_IMAGE_COMPRESSION_WIDTH': config['file.image_compression_width'],
'FILE_IMAGE_COMPRESSION_HEIGHT': config['file.image_compression_height'],
'ALLOWED_FILE_EXTENSIONS': config['rag.file.allowed_extensions'],
@@ -1206,11 +1235,7 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
}
-####################################
-#
# Document process and retrieval
-#
-####################################
def can_merge_chunks(a: Document, b: Document) -> bool:
@@ -2927,11 +2952,7 @@ async def query_collection_handler(
)
-####################################
-#
# Vector DB operations
-#
-####################################
class DeleteForm(BaseModel):
@@ -2969,13 +2990,7 @@ async def delete_entries_from_collection(
detail=ERROR_MESSAGES.DEFAULT('File has no hash; cannot delete vector entries by hash.'),
)
- # Pre-existing bug: this used `metadata=` which is not a
- # parameter on `VectorDBBase.delete` nor on any backend
- # implementation, so the call always raised TypeError that
- # was silently swallowed by the surrounding `except
- # Exception` and the endpoint reported `{'status': False}`
- # for every request. Use `filter` to actually do what the
- # endpoint name promises.
+ # Vector deletion accepts filter, not metadata; passing the wrong keyword raises TypeError.
await ASYNC_VECTOR_DB_CLIENT.delete(
collection_name=form_data.collection_name,
filter={'hash': hash},
diff --git a/backend/open_webui/routers/search.py b/backend/open_webui/routers/search.py
index 2b50ddd2b7..02eac5515a 100644
--- a/backend/open_webui/routers/search.py
+++ b/backend/open_webui/routers/search.py
@@ -339,7 +339,7 @@ async def search_workspace( # noqa: C901 — keep permission scoping and source
.exists()
)
stmt = AccessGrants.has_permission_filter(
- db, select(Note, pinned, note_shared), Note, {'user_id': user.id, 'group_ids': groups}, 'note', 'read'
+ select(Note, pinned, note_shared), Note, {'user_id': user.id, 'group_ids': groups}, 'note', 'read', db=db
)
stmt = stmt.where(sharing_filter(Note.user_id))
stmt = apply_match(
diff --git a/backend/open_webui/routers/skills.py b/backend/open_webui/routers/skills.py
index d8ffb87f1d..aaefd49df6 100644
--- a/backend/open_webui/routers/skills.py
+++ b/backend/open_webui/routers/skills.py
@@ -48,9 +48,7 @@ PAGE_ITEM_COUNT = 30
router = APIRouter()
-############################
-# GetSkills
-############################
+# Get Skills
@router.get('/', response_model=list[SkillUserResponse])
@@ -72,9 +70,7 @@ async def get_skills(
return skills
-############################
-# GetSkillList
-############################
+# Get Skill List
@router.get('/list', response_model=SkillAccessListResponse)
@@ -134,9 +130,7 @@ async def get_skill_list(
)
-############################
-# ExportSkills
-############################
+# Export Skills
async def authorized_skill(id, user, permission='read', db=None):
@@ -211,9 +205,7 @@ async def export_skills(
raise HTTPException(400, str(error))
-############################
-# CreateNewSkill
-############################
+# Create New Skill
@router.post('/create', response_model=Optional[SkillResponse])
@@ -290,9 +282,7 @@ async def create_new_skill(
)
-############################
-# GetSkillById
-############################
+# Get Skill By Id
@router.get('/id/{id}', response_model=Optional[SkillDetailResponse])
@@ -337,9 +327,7 @@ async def get_skill_by_id(id: str, user=Depends(get_verified_user), db: AsyncSes
)
-############################
-# UpdateSkillById
-############################
+# Update Skill By Id
@router.post('/id/{id}/update', response_model=Optional[SkillModel])
@@ -403,9 +391,7 @@ async def update_skill_by_id(
)
-############################
-# UpdateSkillAccessById
-############################
+# Update Skill Access By Id
class SkillAccessGrantsForm(BaseModel):
@@ -464,9 +450,7 @@ async def update_skill_access_by_id(
return skill
-############################
-# ToggleSkillById
-############################
+# Toggle Skill By Id
@router.post('/id/{id}/toggle', response_model=Optional[SkillModel])
@@ -517,9 +501,7 @@ async def toggle_skill_by_id(
)
-############################
-# DeleteSkillById
-############################
+# Delete Skill By Id
@router.delete('/id/{id}/delete', response_model=bool)
diff --git a/backend/open_webui/routers/tasks.py b/backend/open_webui/routers/tasks.py
index 921809a12f..75943a8764 100644
--- a/backend/open_webui/routers/tasks.py
+++ b/backend/open_webui/routers/tasks.py
@@ -99,11 +99,7 @@ async def get_task_model_generation_config(default_model_id: str, models) -> tup
)
-##################################
-#
# Task Endpoints
-#
-##################################
@router.get('/config')
diff --git a/backend/open_webui/routers/terminals.py b/backend/open_webui/routers/terminals.py
index d084710568..55149dd104 100644
--- a/backend/open_webui/routers/terminals.py
+++ b/backend/open_webui/routers/terminals.py
@@ -6,12 +6,16 @@ Routes:
"""
import asyncio
+import json
import logging
+import re
+from contextlib import suppress
+from html import escape
import posixpath
-from urllib.parse import unquote
+from urllib.parse import quote, unquote, urljoin, urlsplit
import aiohttp
-from fastapi import APIRouter, Depends, Request, Response, WebSocket
+from fastapi import APIRouter, Depends, HTTPException, Request, Response, WebSocket
from fastapi.responses import JSONResponse, StreamingResponse
from open_webui.config import TERMINAL_PROXY_HEADERS
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, ENABLE_TOOL_SERVERS
@@ -20,6 +24,7 @@ from open_webui.models.config import Config
from open_webui.models.groups import Groups
from open_webui.utils.access_control import has_connection_access
from open_webui.utils.auth import get_verified_user, get_verified_user_by_token
+from open_webui.utils.browser import browser_access, browser_ticket
from open_webui.utils.headers import bearer_auth_header, normalize_bearer_token
from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.terminals import (
@@ -40,7 +45,7 @@ log = logging.getLogger(__name__)
router = APIRouter()
-STREAMING_CONTENT_TYPES = ('application/octet-stream', 'image/', 'application/pdf')
+STREAMING_CONTENT_TYPES = ('application/octet-stream', 'image/', 'application/pdf', 'text/event-stream')
ADMIN_API_PATHS = ('api/v1/policies', 'api/v1/status', 'api/v1/terminals')
# Drop the upstream's server and date: uvicorn adds its own and forwarding both duplicates them.
STRIPPED_RESPONSE_HEADERS = frozenset(
@@ -48,6 +53,78 @@ STRIPPED_RESPONSE_HEADERS = frozenset(
)
+def _port_browser_html(body: bytes, prefix: str, port: int) -> bytes:
+ """Keep port links inside the proxy and report navigation from sandboxed frames."""
+ config = json.dumps({'prefix': prefix, 'origin': f'http://localhost:{port}'}).replace(
+ '<', '\\u003c'
+ )
+ script = r"""
+(() => {
+ const config = __CONFIG__;
+ const remote = (value = location.href) => {
+ const url = new URL(value, location.href);
+ return url.pathname.startsWith(config.prefix)
+ ? config.origin + '/' + url.pathname.slice(config.prefix.length) + url.search + url.hash
+ : url.href;
+ };
+ const destination = value => new URL(value, remote());
+ const proxy = value => {
+ const url = destination(value);
+ return url.origin === config.origin ? config.prefix + url.pathname.slice(1) + url.search + url.hash : url.href;
+ };
+ const report = () => parent.postMessage({type: 'terminal-browser-state', url: remote(), title: document.title}, '*');
+ for (const method of ['pushState', 'replaceState']) {
+ const original = history[method].bind(history);
+ history[method] = (state, title, value) => {
+ try { const result = original(state, title, value == null ? value : proxy(value)); queueMicrotask(report); return result; }
+ catch (error) {
+ if (error.name !== 'SecurityError' || value == null) throw error;
+ parent.postMessage({type: 'terminal-browser-navigate', url: destination(value).href, replace: method === 'replaceState'}, '*');
+ }
+ };
+ }
+ addEventListener('popstate', report);
+ addEventListener('hashchange', report);
+ document.addEventListener('click', event => {
+ const link = event.target.closest?.('a[href]');
+ if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || link.hasAttribute('download')) return;
+ const url = destination(remote(link.href));
+ if (!/^https?:$/.test(url.protocol)) return;
+ event.preventDefault();
+ parent.postMessage({type: 'terminal-browser-navigate', url: url.href}, '*');
+ }, true);
+ document.addEventListener('submit', event => {
+ const form = event.target;
+ if (form instanceof HTMLFormElement) form.action = proxy(form.getAttribute('action') || remote());
+ }, true);
+ const nativeFetch = window.fetch.bind(window);
+ window.fetch = (input, init) => nativeFetch(input instanceof Request ? new Request(proxy(input.url), input) : proxy(input), init);
+ const nativeOpen = XMLHttpRequest.prototype.open;
+ XMLHttpRequest.prototype.open = function(method, url, ...rest) { return nativeOpen.call(this, method, proxy(url), ...rest); };
+ addEventListener('DOMContentLoaded', () => {
+ new MutationObserver(report).observe(document.querySelector('title') || document.head || document.documentElement, {childList:true,subtree:true,characterData:true});
+ report();
+ });
+ report();
+})();
+""".replace('__CONFIG__', config)
+ html = body.decode('utf-8', errors='replace')
+ # Root-relative assets otherwise resolve against WebUI instead of the port.
+ html = re.sub(
+ r"""(\b(?:href|src|action)\s*=\s*["'])/(?!/)""",
+ lambda match: match[1] + escape(prefix, quote=True),
+ html,
+ flags=re.I,
+ )
+ bridge = ''
+ head = re.search(r']*>', html, re.I)
+ if head:
+ html = html[:head.end()] + bridge + html[head.end():]
+ else:
+ html = bridge + html
+ return html.encode('utf-8')
+
+
def _sanitize_proxy_path(path: str) -> str | None:
"""Sanitize a proxy path to prevent directory traversal / SSRF.
@@ -84,6 +161,112 @@ def _sanitize_proxy_path(path: str) -> str | None:
return cleaned
+@router.api_route(
+ '/{server_id}/browser/view/{sid}/{ticket}/{path:path}',
+ methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
+)
+async def browser_http(request: Request, server_id: str, sid: str, ticket: str, path: str):
+ user, data = await browser_access(server_id, sid, ticket)
+ request.state.browser_auth = data['relay']
+ request.scope['path_params']['chat_id'] = data.get('chat', '')
+ return await proxy_terminal(server_id, f'browser/view/{sid}/{data["capability"]}/{path}', request, user)
+
+
+async def relay_from_browser(ws, upstream):
+ while True:
+ msg = await ws.receive()
+ if msg['type'] == 'websocket.disconnect':
+ return
+ if msg.get('bytes') is not None:
+ await upstream.send_bytes(msg['bytes'])
+ elif msg.get('text') is not None:
+ await upstream.send_str(msg['text'])
+
+
+async def relay_to_browser(ws, upstream):
+ async for msg in upstream:
+ if msg.type == aiohttp.WSMsgType.TEXT:
+ await ws.send_text(msg.data)
+ elif msg.type == aiohttp.WSMsgType.BINARY:
+ await ws.send_bytes(msg.data)
+ else:
+ return
+
+
+async def watch_access(server_id, sid, ticket):
+ while True:
+ await asyncio.sleep(10)
+ current_user, _ = await browser_access(server_id, sid, ticket)
+ latest = await Config.get('terminal_server.connections', []) or []
+ current = next((c for c in latest if c.get('id') == server_id), None)
+ if (
+ not current
+ or not current.get('enabled', True)
+ or not ENABLE_TOOL_SERVERS
+ or not await has_connection_access(current_user, current)
+ or not terminal_context_available(current, 'chat')
+ ):
+ return
+
+
+@router.websocket('/{server_id}/browser/view/{sid}/{ticket}/{kind}')
+async def browser_ws(ws: WebSocket, server_id: str, sid: str, ticket: str, kind: str):
+ try:
+ user, data = await browser_access(server_id, sid, ticket)
+ connections = await Config.get('terminal_server.connections', []) or []
+ connection = next((c for c in connections if c.get('id') == server_id), None)
+ if (
+ kind not in ('ws', 'stream', 'vnc')
+ or not ENABLE_TOOL_SERVERS
+ or not connection
+ or not connection.get('enabled', True)
+ or not await has_connection_access(user, connection)
+ or not terminal_context_available(connection, 'chat')
+ ):
+ raise HTTPException(403, 'Browser access denied')
+ chat = data.get('chat', '')
+ context = terminal_context_id(connection, {'chat_id': chat}, 'chat')
+ if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context:
+ raise HTTPException(403, 'Saved chat required')
+ except HTTPException:
+ await ws.close(code=4001)
+ return
+ await ws.accept()
+ base = get_terminal_server_url(connection).replace('https://', 'wss://').replace('http://', 'ws://')
+ url = f'{base}/browser/view/{sid}/{quote(data["capability"], safe="")}/{kind}'
+ headers = {'X-User-Id': user.id, 'X-Session-Id': chat}
+ if context:
+ headers[TERMINAL_CONTEXT_HEADER] = context
+ if data['relay'].get('authorization'):
+ headers['Authorization'] = data['relay']['authorization']
+ tasks = []
+ try:
+ async with aiohttp.ClientSession(cookies=data['relay'].get('cookies', {}), trust_env=True) as client:
+ async with client.ws_connect(
+ url,
+ headers=headers,
+ ssl=AIOHTTP_CLIENT_SESSION_SSL,
+ max_msg_size=16 * 1024 * 1024,
+ ) as upstream:
+
+ tasks = [
+ asyncio.create_task(relay_from_browser(ws, upstream)),
+ asyncio.create_task(relay_to_browser(ws, upstream)),
+ asyncio.create_task(watch_access(server_id, sid, ticket)),
+ ]
+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+ except aiohttp.WSServerHandshakeError as exc:
+ await ws.close(code=4004 if exc.status in (401, 403, 404) else 1011)
+ except Exception as exc:
+ log.debug('Browser relay disconnected: %s', type(exc).__name__)
+ finally:
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ with suppress(Exception):
+ await ws.close(code=1011)
+
+
@router.get('/')
async def list_terminal_servers(request: Request, user=Depends(get_verified_user)):
"""Return terminal servers the authenticated user has access to."""
@@ -172,7 +355,12 @@ async def proxy_terminal(
cookies = getattr(request, 'cookies', {}) if connection.get('forward_cookies', False) else {}
auth_type = connection.get('auth_type', 'bearer')
- if auth_type == 'bearer':
+ browser_auth = getattr(request.state, 'browser_auth', None)
+ if browser_auth is not None:
+ cookies = browser_auth.get('cookies', {})
+ if browser_auth.get('authorization'):
+ headers['Authorization'] = browser_auth['authorization']
+ elif auth_type == 'bearer':
headers.update(bearer_auth_header(connection.get('key', '')))
elif auth_type == 'session':
headers.update(bearer_auth_header(request.state.token.credentials))
@@ -191,6 +379,11 @@ async def proxy_terminal(
headers.update(bearer_auth_header(oauth_token.get('access_token', '')))
# auth_type == "none": no Authorization header
+ if browser_auth is not None:
+ for name in ('accept', 'origin', 'access-control-request-method', 'access-control-request-headers', 'last-event-id', 'range'):
+ if value := request.headers.get(name):
+ headers[name] = value
+
content_type = request.headers.get('content-type')
if content_type:
headers['Content-Type'] = content_type
@@ -222,6 +415,29 @@ async def proxy_terminal(
if TERMINAL_PROXY_HEADERS:
filtered_headers.update(TERMINAL_PROXY_HEADERS)
+ port_match = re.match(r'^proxy/(\d+)/', safe_path)
+ port_prefix = None
+ if port_match:
+ port_prefix = request.url.path[
+ :request.url.path.index('/proxy/') + len(port_match[0]) + 1
+ ]
+ location = upstream_response.headers.get('location')
+ if location:
+ remote_origin = f'http://localhost:{port_match[1]}'
+ destination = urlsplit(
+ urljoin(f'{remote_origin}/{safe_path[len(port_match[0]):]}', location)
+ )
+ if destination.netloc == urlsplit(remote_origin).netloc:
+ filtered_headers = {
+ key: value for key, value in filtered_headers.items()
+ if key.lower() != 'location'
+ }
+ filtered_headers['Location'] = (
+ port_prefix + destination.path.lstrip('/')
+ + (f'?{destination.query}' if destination.query else '')
+ + (f'#{destination.fragment}' if destination.fragment else '')
+ )
+
# Stream binary responses directly
if any(t in upstream_content_type for t in STREAMING_CONTENT_TYPES):
@@ -238,6 +454,13 @@ async def proxy_terminal(
# Buffer text/JSON responses
response_body = await upstream_response.read()
+ if safe_path.startswith('browser/sessions') and upstream_response.status < 300 and request.method in ('GET', 'POST', 'PATCH'):
+ browser_session = json.loads(response_body)
+ if isinstance(browser_session, dict) and browser_session.get('id') and browser_session.get('token'):
+ browser_session['token'] = browser_ticket(server_id, user.id, session_id or '', browser_session, headers, cookies)
+ response_body = json.dumps(browser_session).encode()
+ if port_prefix and 'text/html' in upstream_content_type:
+ response_body = _port_browser_html(response_body, port_prefix, int(port_match[1]))
status_code = upstream_response.status
await upstream_response.release()
await session.close()
@@ -257,9 +480,7 @@ async def proxy_terminal(
return JSONResponse({'error': f'Terminal proxy error: {error}'}, status_code=502)
-# ---------------------------------------------------------------------------
# WebSocket proxy for interactive terminal sessions
-# ---------------------------------------------------------------------------
async def _resolve_authenticated_connection(ws: WebSocket, server_id: str):
@@ -331,13 +552,45 @@ async def _resolve_terminal_access(ws: WebSocket, server_id: str, token: str):
return user, connection
+@router.websocket('/{server_id}/events')
+async def ws_events(ws: WebSocket, server_id: str):
+ await _proxy_terminal_websocket(ws, server_id)
+
+
+@router.websocket('/{server_id}/desktop/stream')
+async def desktop_ws(ws: WebSocket, server_id: str):
+ await _proxy_terminal_websocket(ws, server_id, stream_path='desktop/stream')
+
+
+@router.websocket('/{server_id}/desktop/audio')
+async def desktop_audio_ws(ws: WebSocket, server_id: str):
+ await _proxy_terminal_websocket(ws, server_id, stream_path='desktop/audio')
+
+
+@router.websocket('/{server_id}/execute')
+async def ws_processes(ws: WebSocket, server_id: str):
+ await _proxy_terminal_websocket(ws, server_id, stream_path='execute')
+
+
+@router.websocket('/{server_id}/execute/{process_id}/status')
+async def ws_process_output(ws: WebSocket, server_id: str, process_id: str):
+ from urllib.parse import quote
+ await _proxy_terminal_websocket(ws, server_id,
+ stream_path=f'execute/{quote(process_id, safe="")}/status')
+
+
@router.websocket('/{server_id}/api/terminals/{session_id}')
-async def ws_terminal(
+async def ws_terminal(ws: WebSocket, server_id: str, session_id: str):
+ await _proxy_terminal_websocket(ws, server_id, session_id)
+
+
+async def _proxy_terminal_websocket(
ws: WebSocket,
server_id: str,
- session_id: str,
+ session_id: str | None = None,
+ stream_path: str = 'events',
):
- """Proxy an interactive WebSocket terminal session to a terminal server.
+ """Proxy terminal sessions and filesystem notifications to a terminal server.
Uses first-message auth: the client sends ``{"type": "auth", "token": ""}``
as its first message. The proxy validates the JWT, then connects to the
@@ -361,6 +614,10 @@ async def ws_terminal(
upstream_params = {}
# For orchestrator-backed servers, pass user_id
upstream_params['user_id'] = user.id
+ if stream_path.startswith('execute/'):
+ for key in ('offset', 'tail'):
+ if key in ws.query_params:
+ upstream_params[key] = ws.query_params[key]
context_id = terminal_context_id(connection, {'chat_id': chat_id}, 'chat')
upstream_headers = {'X-User-Id': user.id, 'X-Session-Id': chat_id}
if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context_id:
@@ -373,13 +630,15 @@ async def ws_terminal(
# Encode session_id as an opaque path segment so it cannot smuggle '?'/'#'/'&' (at any
# decode depth) and inject an attacker-chosen user_id ahead of the one appended below.
- safe_session_id = urllib.parse.quote(session_id, safe='')
-
- upstream_url = f'{ws_base}/api/terminals/{safe_session_id}'
+ upstream_path = (
+ f'api/terminals/{urllib.parse.quote(session_id, safe="")}'
+ if session_id is not None else stream_path
+ )
+ upstream_url = f'{ws_base}/{upstream_path}'
if upstream_params:
upstream_url += f'?{urllib.parse.urlencode(upstream_params)}'
- app = ws.scope.get('app')
+ request = Request({**ws.scope, 'type': 'http', 'method': 'GET'})
opened = False
session = aiohttp.ClientSession()
try:
@@ -400,15 +659,16 @@ async def ws_terminal(
else:
await upstream.send_str(_json.dumps({'type': 'auth', 'token': ''}))
- await publish_event(
- app,
- EVENTS.TERMINAL_SESSION_OPENED,
- actor=user,
- subject_id=session_id,
- subject_type='terminal.session',
- data={'server_id': server_id},
- )
- opened = True
+ if session_id is not None:
+ await publish_event(
+ request,
+ EVENTS.TERMINAL_SESSION_OPENED,
+ actor=user,
+ subject_id=session_id,
+ subject_type='terminal.session',
+ data={'server_id': server_id},
+ )
+ opened = True
async def _client_to_upstream():
"""Forward client → upstream."""
@@ -437,6 +697,9 @@ async def ws_terminal(
aiohttp.WSMsgType.ERROR,
):
break
+ if session_id is None:
+ code = upstream.close_code or 1011
+ await ws.close(code=1011 if code in (1005, 1006, 1015) else code)
except Exception:
pass
@@ -466,11 +729,18 @@ async def ws_terminal(
await asyncio.gather(*tasks, return_exceptions=True)
except Exception as e:
log.exception('Terminal WebSocket proxy error: %s', e)
+ if session_id is None:
+ status = getattr(e, 'status', None)
+ code = {401: 4001, 403: 4003, 404: 4004}.get(status, 1011)
+ try:
+ await ws.close(code=code)
+ except Exception:
+ pass
finally:
await session.close()
if opened:
await publish_event(
- app,
+ request,
EVENTS.TERMINAL_SESSION_CLOSED,
actor=user,
subject_id=session_id,
diff --git a/backend/open_webui/routers/tools.py b/backend/open_webui/routers/tools.py
index 4176eaca97..0c46cdda18 100644
--- a/backend/open_webui/routers/tools.py
+++ b/backend/open_webui/routers/tools.py
@@ -5,11 +5,11 @@ import logging
import re
import time
from pathlib import Path
-from typing import Optional
+from typing import Literal, Optional
import aiohttp
from fastapi import APIRouter, Depends, HTTPException, Request, status
-from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL, CACHE_DIR
+from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL, CACHE_DIR, IFRAME_CSP
from open_webui.constants import ERROR_MESSAGES
from open_webui.env import (
AIOHTTP_CLIENT_SESSION_SSL,
@@ -39,6 +39,8 @@ from open_webui.utils.access_control import (
validate_access_grants,
)
from open_webui.utils.auth import get_admin_user, get_verified_user
+from open_webui.utils.mcp.apps import app_csp, ui_resource_uri, verify_app_binding
+from open_webui.utils.mcp.client import tool_visible_to
from open_webui.utils.misc import is_string_allowed
from open_webui.utils.plugin import (
get_tool_contents_cache,
@@ -51,7 +53,7 @@ from open_webui.utils.plugin import (
)
from open_webui.utils.tools import connect_mcp_server, get_tool_servers
from open_webui.utils.tools import get_tool_specs as get_local_tool_specs
-from pydantic import BaseModel, HttpUrl
+from pydantic import BaseModel, ConfigDict, Field, HttpUrl, model_validator
from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
@@ -68,11 +70,9 @@ async def get_tool_module(request, tool_id, load_from_db=True):
return tool_module
-############################
-# GetTools
+# Get Tools
# The danger is not in having tools, but in reaching
# for the wrong one. Let the choice here be deliberate.
-############################
@router.get('/', response_model=list[ToolUserResponse])
@@ -95,6 +95,7 @@ async def get_tools(
tools_cache = get_tools_cache(request)
for tool in await Tools.get_tools(
defer_content=True,
+ active_only=True,
db=db,
user_id=None if bypass_access_control else user.id,
user_group_ids=user_group_ids,
@@ -239,9 +240,86 @@ async def get_tool_specs(request: Request, id: str, user=Depends(get_verified_us
raise HTTPException(status_code=502, detail='Unable to load tools')
-############################
-# GetToolList
-############################
+# Get Tool List
+
+
+class MCPAppRPCForm(BaseModel):
+ model_config = ConfigDict(extra='forbid')
+ tool_name: str
+ binding: str = Field(min_length=64, max_length=64, pattern='^[a-f0-9]{64}$')
+ method: Literal['tools/call', 'resources/read', 'resources/list', 'ui/resource']
+ params: dict
+
+ @model_validator(mode='after')
+ def validate_params(self):
+ params = self.params
+ keys = {
+ 'tools/call': {'name', 'arguments'},
+ 'resources/read': {'uri'},
+ 'resources/list': {'cursor'},
+ 'ui/resource': set(),
+ }
+ if params.keys() - keys[self.method]:
+ raise ValueError('Invalid app request parameters')
+ if self.method == 'tools/call' and (
+ not isinstance(params.get('name'), str) or not isinstance(params.get('arguments', {}), dict)
+ ):
+ raise ValueError('Invalid tool call')
+ if self.method == 'resources/read' and not isinstance(params.get('uri'), str):
+ raise ValueError('Invalid resource URI')
+ if (
+ self.method == 'resources/list'
+ and params.get('cursor') is not None
+ and not isinstance(params['cursor'], str)
+ ):
+ raise ValueError('Invalid resource cursor')
+ return self
+
+
+@router.post('/id/{id}/mcp/app/rpc')
+async def mcp_app_rpc(request: Request, id: str, form_data: MCPAppRPCForm, user=Depends(get_verified_user)):
+ server_id = id.removeprefix('server:mcp:')
+ if not id.startswith('server:mcp:') or not verify_app_binding(server_id, form_data.tool_name, form_data.binding):
+ raise HTTPException(status_code=403, detail='Invalid app binding. Run the tool again.')
+ params = form_data.params
+
+ try:
+ async with asyncio.timeout(60):
+ connection = await connect_mcp_server(request, server_id, user, {})
+ if connection is None:
+ raise HTTPException(status_code=404, detail='Tool not found')
+ client, _ = connection
+ try:
+ origin = client.tool_definitions.get(form_data.tool_name)
+ if not origin or not ui_resource_uri(origin) or not tool_visible_to(origin, 'model'):
+ raise HTTPException(status_code=403, detail='App tool is unavailable')
+ if form_data.method == 'ui/resource':
+ document, ui = await client.read_ui_resource(ui_resource_uri(origin))
+ return {
+ 'html': document,
+ 'ui': ui,
+ 'tool': origin,
+ 'csp': app_csp(ui),
+ 'additional_csp': IFRAME_CSP,
+ }
+ if form_data.method == 'tools/call':
+ target = client.tool_definitions.get(params['name'])
+ if not target or not tool_visible_to(target, 'app'):
+ raise HTTPException(status_code=403, detail='Tool is unavailable to this app')
+ return await client.call_tool_raw(params['name'], params.get('arguments', {}))
+ if form_data.method == 'resources/read':
+ return await client.read_resource(params['uri'])
+ result = await client.client.list_resources(cursor=params.get('cursor'))
+ return result.model_dump(mode='json', by_alias=True, exclude_none=True)
+ finally:
+ await client.disconnect()
+ except HTTPException:
+ raise
+ except TimeoutError:
+ raise HTTPException(status_code=504, detail='MCP app request timed out')
+ except Exception as error:
+ log.warning('MCP app request failed: %s', type(error).__name__)
+ raise HTTPException(status_code=502, detail='MCP app request failed')
@router.get('/list', response_model=list[ToolAccessResponse])
@@ -285,9 +363,39 @@ async def get_tool_list(user=Depends(get_verified_user), db: AsyncSession = Depe
return result
-############################
-# LoadFunctionFromLink
-############################
+@router.post('/id/{id}/toggle', response_model=ToolResponse)
+async def toggle_tool_by_id(
+ request: Request,
+ id: str,
+ user=Depends(get_verified_user),
+ db: AsyncSession = Depends(get_async_session),
+):
+ tool = await Tools.get_tool_by_id(id, db=db)
+ if tool is None:
+ raise HTTPException(status_code=404, detail=ERROR_MESSAGES.NOT_FOUND)
+ if not (
+ (user.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL)
+ or tool.user_id == user.id
+ or await AccessGrants.has_access(
+ user_id=user.id, resource_type='tool', resource_id=id, permission='write', db=db
+ )
+ ):
+ raise HTTPException(status_code=403, detail=ERROR_MESSAGES.UNAUTHORIZED)
+
+ tool = await Tools.toggle_tool_by_id(id, db=db)
+ if tool is None:
+ raise HTTPException(status_code=404, detail=ERROR_MESSAGES.NOT_FOUND)
+ await publish_event(
+ request,
+ EVENTS.TOOL_ENABLED if tool.is_active else EVENTS.TOOL_DISABLED,
+ actor=user,
+ subject_id=tool.id,
+ data={'name': tool.name},
+ )
+ return tool
+
+
+# Load Function From Link
class LoadUrlForm(BaseModel):
@@ -358,9 +466,7 @@ async def load_tool_from_url(request: Request, form_data: LoadUrlForm, user=Depe
)
-############################
-# ExportTools
-############################
+# Export Tools
@router.get('/export', response_model=list[ToolModel])
@@ -388,9 +494,7 @@ async def export_tools(
)
-############################
-# CreateNewTools
-############################
+# Create New Tools
@router.post('/create', response_model=ToolResponse | None)
@@ -477,9 +581,7 @@ async def create_new_tools(
)
-############################
-# GetToolsById
-############################
+# Get Tools By Id
@router.get('/id/{id}', response_model=ToolAccessResponse | None)
@@ -526,9 +628,7 @@ async def get_tools_by_id(id: str, user=Depends(get_verified_user), db: AsyncSes
)
-############################
-# UpdateToolsById
-############################
+# Update Tools By Id
@router.post('/id/{id}/update', response_model=ToolModel | None)
@@ -622,9 +722,7 @@ async def _update_tool(request, id, form_data, user, db, version_id=None):
)
-############################
-# UpdateToolAccessById
-############################
+# Update Tool Access By Id
class ToolAccessGrantsForm(BaseModel):
@@ -683,9 +781,7 @@ async def update_tool_access_by_id(
return tools
-############################
-# DeleteToolsById
-############################
+# Delete Tools By Id
@router.delete('/id/{id}/delete', response_model=bool)
@@ -735,9 +831,7 @@ async def delete_tools_by_id(
return result
-############################
-# GetToolValves
-############################
+# Get Tool Valves
@router.get('/id/{id}/valves', response_model=dict | None)
@@ -777,9 +871,7 @@ async def get_tools_valves_by_id(
)
-############################
-# GetToolValvesSpec
-############################
+# Get Tool Valves Spec
@router.get('/id/{id}/valves/spec', response_model=dict | None)
@@ -823,9 +915,7 @@ async def get_tools_valves_spec_by_id(
return None
-############################
-# UpdateToolValves
-############################
+# Update Tool Valves
@router.post('/id/{id}/valves/update', response_model=dict | None)
@@ -888,9 +978,7 @@ async def update_tools_valves_by_id(
)
-############################
-# ToolUserValves
-############################
+# Tool User Valves
@router.get('/id/{id}/valves/user', response_model=dict | None)
diff --git a/backend/open_webui/routers/users.py b/backend/open_webui/routers/users.py
index 4c3c5bf7e6..7b5f41c980 100644
--- a/backend/open_webui/routers/users.py
+++ b/backend/open_webui/routers/users.py
@@ -72,11 +72,7 @@ def merge_user_ui_settings(defaults: dict, settings: dict) -> dict:
return merged
-############################
-# GetUsers
-# A house is only as strong as its care for the least of
-# its members. Let none here be counted without being served.
-############################
+# Get Users
PAGE_ITEM_COUNT = 30
@@ -164,9 +160,7 @@ async def search_users(
)
-############################
# User Groups
-############################
@router.get('/groups')
@@ -176,9 +170,7 @@ async def get_user_groups(
return await user_groups_response(user.id, include_inherited, db)
-############################
# User Permissions
-############################
@router.get('/permissions')
@@ -192,9 +184,7 @@ async def get_user_permissisions(
return user_permissions
-############################
# User Default Permissions
-############################
class WorkspacePermissions(BaseModel):
models: bool = False
knowledge: bool = False
@@ -259,6 +249,7 @@ class ChatPermissions(BaseModel):
call: bool = True
multiple_models: bool = True
temporary: bool = True
+ side_chat: bool = False
temporary_enforced: bool = False
@@ -434,6 +425,12 @@ async def get_default_user_permissions(request: Request, user=Depends(get_admin_
async def update_default_user_permissions(request: Request, form_data: UserPermissions, user=Depends(get_admin_user)):
user_permissions = form_data.model_dump(by_alias=True)
await Config.upsert({'user.permissions': user_permissions})
+ from open_webui.socket.main import sio
+
+ try:
+ await sio.emit('access:updated', {})
+ except Exception:
+ log.exception('Unable to refresh default user permissions')
await publish_event(
request,
EVENTS.USER_PERMISSIONS_UPDATED,
@@ -458,9 +455,7 @@ async def get_default_user_permissions_defaults(user=Depends(get_admin_user)):
}
-############################
-# GetUserSettingsBySessionUser
-############################
+# Get User Settings By Session User
@router.get('/user/settings', response_model=UserSettings | None)
@@ -483,9 +478,7 @@ async def get_user_settings_by_session_user(
return UserSettings.model_validate(user_settings)
-############################
-# UpdateUserSettingsBySessionUser
-############################
+# Update User Settings By Session User
@router.post('/user/settings/update', response_model=UserSettings)
@@ -561,9 +554,7 @@ async def update_user_settings_by_session_user(
)
-############################
-# GetUserStatusBySessionUser
-############################
+# Get User Status By Session User
@router.get('/user/status')
@@ -580,9 +571,7 @@ async def get_user_status_by_session_user(
return user
-############################
-# UpdateUserStatusBySessionUser
-############################
+# Update User Status By Session User
@router.post('/user/status/update')
@@ -613,9 +602,7 @@ async def update_user_status_by_session_user(
)
-############################
-# GetUserInfoBySessionUser
-############################
+# Get User Info By Session User
@router.get('/user/info', response_model=dict | None)
@@ -632,9 +619,7 @@ class UserVariablesResponse(BaseModel):
variables: dict[str, str] = Field(default_factory=dict)
-############################
-# GetUserVariablesBySessionUser
-############################
+# Get User Variables By Session User
@router.get('/user/variables', response_model=UserVariablesResponse)
@@ -642,9 +627,7 @@ async def get_user_variables_by_session_user(user=Depends(get_verified_user)):
return UserVariablesResponse(variables=normalize_user_variables(user.variables))
-############################
-# UpdateUserVariablesBySessionUser
-############################
+# Update User Variables By Session User
@router.post('/user/variables/update', response_model=UserVariablesResponse)
@@ -670,9 +653,7 @@ async def update_user_variables_by_session_user(
return UserVariablesResponse(variables=variables)
-############################
-# UpdateUserInfoBySessionUser
-############################
+# Update User Info By Session User
@router.post('/user/info/update', response_model=dict | None)
@@ -697,9 +678,7 @@ async def update_user_info_by_session_user( # PATCH-style merge
return updated.info
-############################
-# GetUserUsageBySessionUser
-############################
+# Get User Usage By Session User
@router.get('/usage', response_model=UserUsageResponse)
@@ -776,9 +755,7 @@ async def get_user_usage_by_session_user(
)
-############################
-# GetUserById
-############################
+# Get User By Id
class UserActiveResponse(UserStatus):
@@ -845,9 +822,7 @@ async def get_user_oauth_sessions_by_id(
)
-############################
-# GetUserProfileImageById
-############################
+# Get User Profile Image By Id
@router.get('/{user_id}/profile/image')
@@ -892,9 +867,7 @@ async def get_user_profile_image_by_id(user_id: str, user=Depends(get_verified_u
)
-############################
-# GetUserActiveStatusById
-############################
+# Get User Active Status By Id
@router.get('/{user_id}/active', response_model=dict)
@@ -906,9 +879,7 @@ async def get_user_active_status_by_id(
}
-############################
-# UpdateUserById
-############################
+# Update User By Id
@router.post('/{user_id}/sessions/revoke', response_model=bool)
@@ -1114,9 +1085,7 @@ async def update_user_by_id(
)
-############################
-# DeleteUserById
-############################
+# Delete User By Id
@router.delete('/{user_id}', response_model=bool)
@@ -1164,9 +1133,7 @@ async def delete_user_by_id(
)
-############################
-# GetUserGroupsById
-############################
+# Get User Groups By Id
@router.get('/{user_id}/groups')
@@ -1179,9 +1146,7 @@ async def get_user_groups_by_id(
return await user_groups_response(user_id, include_inherited, db)
-############################
-# GetUserPreview
-############################
+# Get User Preview
@router.get('/{user_id}/preview')
diff --git a/backend/open_webui/socket/comments.py b/backend/open_webui/socket/comments.py
new file mode 100644
index 0000000000..8722820d2c
--- /dev/null
+++ b/backend/open_webui/socket/comments.py
@@ -0,0 +1,84 @@
+"""Small, authorized subscriptions on the existing Socket.IO server."""
+
+import hashlib
+
+from fastapi import HTTPException
+from open_webui.internal.db import get_async_db_context
+from open_webui.models.users import Users
+from open_webui.utils.comments import comment_resource
+from starlette.requests import HTTPConnection
+
+
+def comment_room(resource_type, resource_id):
+ return 'comments:' + hashlib.sha256(f'{resource_type}:{resource_id}'.encode()).hexdigest()
+
+
+def comment_connection(sio, sid):
+ scope = (sio.get_environ(sid) or {}).get('asgi.scope') or {}
+ return HTTPConnection(scope) if scope.get('app') else None
+
+
+def register_comment_events(sio, get_socket_session_user):
+ @sio.on('comments:join')
+ async def join(sid, data):
+ session_user = await get_socket_session_user(sid)
+ if not session_user or not isinstance(data, dict):
+ return {'error': 'Unauthorized'}
+ kind, id = data.get('resource_type'), data.get('resource_id')
+ if not isinstance(kind, str) or not isinstance(id, str) or len(id) > 512:
+ return {'error': 'Invalid resource'}
+ user = await Users.get_user_by_id(session_user['id'])
+ if not user:
+ return {'error': 'Unauthorized'}
+ try:
+ async with get_async_db_context() as db:
+ await comment_resource(kind, id, user, db, request=comment_connection(sio, sid))
+ except HTTPException:
+ return {'error': 'Resource unavailable'}
+ session = await sio.get_session(sid)
+ subscription = data.get('subscription_id', 'default')
+ if not isinstance(subscription, str) or len(subscription) > 100:
+ return {'error': 'Invalid subscription'}
+ subscriptions = session.setdefault('comments_resources', {})
+ if subscription not in subscriptions and len(subscriptions) >= 10:
+ return {'error': 'Too many comment panels'}
+ previous = subscriptions.get(subscription)
+ subscriptions[subscription] = [kind, id]
+ if previous and previous not in subscriptions.values():
+ await sio.leave_room(sid, comment_room(*previous))
+ await sio.save_session(sid, session)
+ await sio.enter_room(sid, comment_room(kind, id))
+ return {'ok': True}
+
+ @sio.on('comments:leave')
+ async def leave(sid, data=None):
+ session = await sio.get_session(sid)
+ subscriptions = session.get('comments_resources', {})
+ subscription = data.get('subscription_id', 'default') if isinstance(data, dict) else 'default'
+ if not isinstance(subscription, str):
+ return
+ resource = subscriptions.pop(subscription, None)
+ if resource and resource not in subscriptions.values():
+ await sio.leave_room(sid, comment_room(*resource))
+ await sio.save_session(sid, session)
+
+
+async def revalidate_comment_subscription(sio, sid, session_user):
+ session = await sio.get_session(sid)
+ subscriptions = session.get('comments_resources', {})
+ if not subscriptions:
+ return
+ user = await Users.get_user_by_id(session_user['id'])
+ for resource in set(tuple(value) for value in subscriptions.values()):
+ try:
+ if not user:
+ raise HTTPException(403)
+ async with get_async_db_context() as db:
+ await comment_resource(*resource, user, db, request=comment_connection(sio, sid))
+ except HTTPException:
+ await sio.leave_room(sid, comment_room(*resource))
+ session['comments_resources'] = {
+ key: value for key, value in session['comments_resources'].items() if tuple(value) != resource
+ }
+ await sio.save_session(sid, session)
+ await sio.emit('comments:unavailable', {'resource_type': resource[0], 'resource_id': resource[1]}, to=sid)
diff --git a/backend/open_webui/socket/main.py b/backend/open_webui/socket/main.py
index 1338308fb6..ea9ea1de9b 100644
--- a/backend/open_webui/socket/main.py
+++ b/backend/open_webui/socket/main.py
@@ -37,6 +37,7 @@ from open_webui.env import (
)
from open_webui.models.access_grants import AccessGrants
from open_webui.models.channels import Channels
+from open_webui.models.chat_messages import ChatMessages
from open_webui.models.chats import Chats
from open_webui.models.config import Config
from open_webui.models.folders import Folders
@@ -56,12 +57,13 @@ from open_webui.tasks import (
from open_webui.utils.access_control import has_permission
from open_webui.utils.access_control.files import has_access_to_note_files
from open_webui.utils.auth import get_verified_user_by_token
-from open_webui.utils.chat_id import is_saved_chat_id
+from open_webui.utils.chat_id import is_saved_chat_id, is_temporary_chat_id
from open_webui.utils.json_codec import SOCKETIO_JSON, JSONCodec, dumps_bytes
from open_webui.utils.misc import get_output_text
from open_webui.utils.redis import (
build_sentinel_kwargs,
build_sentinel_url,
+ get_redis_client,
get_redis_connection,
get_sentinels_from_env,
)
@@ -76,7 +78,7 @@ log = logging.getLogger(__name__)
# cause, and let every message find the room it was meant for.
REDIS = None
-# Configure CORS for Socket.IO
+# Socket.IO expects a wildcard string rather than a one-item wildcard list.
SOCKETIO_CORS_ORIGINS = '*' if CORS_ALLOW_ORIGIN == ['*'] else CORS_ALLOW_ORIGIN
# Large notes outgrow the 1 MB default; match uvicorn's 16 MiB websocket limit
@@ -463,7 +465,14 @@ async def periodic_socket_authentication():
await asyncio.sleep(30)
await encryption.sweep()
for sid in tuple(LOCAL_AUTHENTICATED_SIDS):
- await get_socket_session_user(sid)
+ session_user = await get_socket_session_user(sid)
+ if session_user:
+ from open_webui.socket.comments import revalidate_comment_subscription
+
+ try:
+ await revalidate_comment_subscription(sio, sid, session_user)
+ except Exception:
+ log.exception('Could not revalidate comment subscription')
async def get_socket_session_user(sid: str, *, wait_for_disconnect: bool = True) -> dict | None:
@@ -1594,6 +1603,10 @@ async def _make_channel_emitter(request_info):
async def get_event_emitter(request_info, update_db=True):
+ from open_webui.utils.chat import get_temporary_chat
+
+ redis = get_redis_client(async_mode=True) if is_temporary_chat_id(request_info.get('chat_id')) else None
+
# Channel mode: route pipeline output to channel message updates
if (request_info.get('chat_id') or '').startswith('channel:'):
return await _make_channel_emitter(request_info)
@@ -1612,7 +1625,19 @@ async def get_event_emitter(request_info, update_db=True):
if internal and event_data.get('type') == 'notification':
return
+ if event_data.get('type') == 'chat:active' and is_saved_chat_id(chat_id):
+ pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat_id])
+ event_data = {
+ **event_data,
+ 'data': {**(event_data.get('data') or {}), 'pending_approval': chat_id in pending_approval_ids},
+ }
+
room = f'user:{user_id}'
+ if is_temporary_chat_id(chat_id):
+ owner = await get_temporary_chat(redis, chat_id)
+ room = owner['session_id'] if owner and owner['user_id'] == user_id else request_info.get('session_id')
+ if not room or get_user_id_from_session_pool(room) != user_id:
+ return
if event_data.get('type') != 'chat:messages':
await sio.emit(
'events',
@@ -1784,8 +1809,18 @@ def get_user_chat_session_id(user_id: str, chat_id: str) -> str | None:
async def get_event_call(request_info):
+ from open_webui.utils.chat import get_temporary_chat
+
+ redis = get_redis_client(async_mode=True) if is_temporary_chat_id(request_info.get('chat_id')) else None
+
async def __event_caller__(event_data):
session_id = request_info['session_id']
+ if is_temporary_chat_id(request_info['chat_id']):
+ owner = await get_temporary_chat(redis, request_info['chat_id'])
+ if owner and owner['user_id'] == request_info['user_id']:
+ session_id = request_info['session_id'] = owner['session_id']
+ if 'session_id' in (event_data.get('data') or {}):
+ event_data = {**event_data, 'data': {**event_data['data'], 'session_id': session_id}}
# session_id is client-supplied; only the requesting user's own live session may be targeted.
session = SESSION_POOL.get(session_id)
@@ -1817,7 +1852,7 @@ async def get_event_call(request_info):
can_resume = (
is_input_request
and 'session_id' not in (event_data.get('data') or {})
- and is_saved_chat_id(request_info['chat_id'])
+ and (is_saved_chat_id(request_info['chat_id']) or is_temporary_chat_id(request_info['chat_id']))
)
try:
async with asyncio.timeout(timeout):
@@ -1852,9 +1887,19 @@ async def get_event_call(request_info):
async with asyncio.timeout(60):
while True:
# Redis session scans are synchronous; keep them off the event loop.
- next_session_id = await asyncio.to_thread(
- get_user_chat_session_id, request_info['user_id'], request_info['chat_id']
- )
+ if is_temporary_chat_id(request_info['chat_id']):
+ owner = await get_temporary_chat(redis, request_info['chat_id'])
+ next_session_id = (
+ owner['session_id']
+ if owner and owner['user_id'] == request_info['user_id']
+ else None
+ )
+ if get_user_id_from_session_pool(next_session_id) != request_info['user_id']:
+ next_session_id = None
+ else:
+ next_session_id = await asyncio.to_thread(
+ get_user_chat_session_id, request_info['user_id'], request_info['chat_id']
+ )
if next_session_id is not None:
session_id = request_info['session_id'] = next_session_id
break
@@ -1883,3 +1928,8 @@ async def get_event_call(request_info):
get_event_caller = get_event_call
+
+
+from open_webui.socket.comments import register_comment_events
+
+register_comment_events(sio, get_socket_session_user)
diff --git a/backend/open_webui/static/apple-touch-icon.png b/backend/open_webui/static/apple-touch-icon.png
index 9807373436..946f476262 100644
Binary files a/backend/open_webui/static/apple-touch-icon.png and b/backend/open_webui/static/apple-touch-icon.png differ
diff --git a/backend/open_webui/static/favicon-96x96.png b/backend/open_webui/static/favicon-96x96.png
index 2ebdffebe5..efe2c2e6e1 100644
Binary files a/backend/open_webui/static/favicon-96x96.png and b/backend/open_webui/static/favicon-96x96.png differ
diff --git a/backend/open_webui/static/favicon.ico b/backend/open_webui/static/favicon.ico
index b819d42f96..1f03d71bb6 100644
Binary files a/backend/open_webui/static/favicon.ico and b/backend/open_webui/static/favicon.ico differ
diff --git a/backend/open_webui/static/favicon.svg b/backend/open_webui/static/favicon.svg
index 0aa909745a..5f200b4bf8 100644
--- a/backend/open_webui/static/favicon.svg
+++ b/backend/open_webui/static/favicon.svg
@@ -1,3 +1 @@
-
\ No newline at end of file
+
diff --git a/backend/open_webui/static/logo.png b/backend/open_webui/static/logo.png
index a652a5fb87..9da2acbd2f 100644
Binary files a/backend/open_webui/static/logo.png and b/backend/open_webui/static/logo.png differ
diff --git a/backend/open_webui/static/web-app-manifest-192x192.png b/backend/open_webui/static/web-app-manifest-192x192.png
index fbd2eab6e2..696b3ee62c 100644
Binary files a/backend/open_webui/static/web-app-manifest-192x192.png and b/backend/open_webui/static/web-app-manifest-192x192.png differ
diff --git a/backend/open_webui/static/web-app-manifest-512x512.png b/backend/open_webui/static/web-app-manifest-512x512.png
index afebe2cd08..e99e8a04a4 100644
Binary files a/backend/open_webui/static/web-app-manifest-512x512.png and b/backend/open_webui/static/web-app-manifest-512x512.png differ
diff --git a/backend/open_webui/tasks.py b/backend/open_webui/tasks.py
index 94b247badb..53781438ea 100644
--- a/backend/open_webui/tasks.py
+++ b/backend/open_webui/tasks.py
@@ -84,9 +84,7 @@ async def redis_task_heartbeat(app):
log.exception('Redis task heartbeat failed')
-### ------------------------------
-### REDIS-ENABLED HANDLERS
-### ------------------------------
+# Redis-enabled handlers
async def redis_save_task(redis: Redis, task_id: str, item_id: str | None):
@@ -166,11 +164,11 @@ async def create_task(redis, coroutine, id=None, task_id=None):
task_id = task_id or str(uuid4()) # Generate a unique ID for the task
task = asyncio.create_task(coroutine) # Create the task
- # Add a done callback for cleanup
+ # Give the task a checkout routine before handing it the keys.
task.add_done_callback(lambda t: asyncio.create_task(cleanup_task(redis, task_id, id)))
tasks[task_id] = task
- # If an ID is provided, associate the task with that ID
+ # File this task under its item ID, if it came with a return address.
if id:
if item_tasks.get(id):
item_tasks[id].append(task_id)
diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py
index 9e43578208..1704b9d4d1 100644
--- a/backend/open_webui/tools/builtin.py
+++ b/backend/open_webui/tools/builtin.py
@@ -124,9 +124,7 @@ async def _has_read_access_to_file(
)
-# =============================================================================
-# TIME UTILITIES
-# =============================================================================
+# Time utilities
async def notify(
@@ -226,7 +224,7 @@ async def calculate_timestamp(
total_days = days_ago + (weeks_ago * 7)
adjusted = now - datetime.timedelta(days=total_days)
- # Handle months and years separately (variable length)
+ # Months and years need calendar arithmetic; February refuses to be 30 days.
if months_ago > 0 or years_ago > 0:
adjusted = adjusted - relativedelta(months=months_ago, years=years_ago)
@@ -287,9 +285,7 @@ async def calculate_timestamp(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# WEB SEARCH TOOLS
-# =============================================================================
+# Web search tools
async def search_web(
@@ -363,9 +359,7 @@ async def fetch_url(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# IMAGE GENERATION TOOLS
-# =============================================================================
+# Image generation tools
async def generate_image(
@@ -535,9 +529,7 @@ async def edit_image(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# USER INPUT TOOLS
-# =============================================================================
+# User input tools
async def ask_user(
@@ -652,9 +644,7 @@ async def ask_user(
return JSONCodec.dumps({'status': 'error', 'error': str(e)}, ensure_ascii=False)
-# =============================================================================
-# CODE INTERPRETER TOOLS
-# =============================================================================
+# Code interpreter tools
async def execute_code(
@@ -819,9 +809,7 @@ async def execute_code(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# MEMORY TOOLS
-# =============================================================================
+# Memory tools
async def list_memory_paths(
@@ -1146,9 +1134,7 @@ async def list_memories(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# NOTES TOOLS
-# =============================================================================
+# Notes tools
async def search_notes(
@@ -1634,9 +1620,7 @@ async def replace_note_content(
return JSONCodec.dumps({'error': str(e), 'code': 'unexpected_error'})
-# =============================================================================
-# CHATS TOOLS
-# =============================================================================
+# Chats tools
async def search_chats(
@@ -1750,7 +1734,7 @@ async def view_chat(
history = chat.chat.get('history', {})
msg_dict = history.get('messages', {})
- # Build message chain from currentId
+ # Follow parent links from currentId; conversations have family trees too.
current_id = history.get('currentId')
visited = set()
@@ -1784,9 +1768,7 @@ async def view_chat(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# SUB-AGENT TOOL
-# =============================================================================
+# Sub-agent tool
async def delegate_task(
@@ -1794,6 +1776,7 @@ async def delegate_task(
context: str = '',
file_ids: list[str] | None = None,
background: bool = False,
+ model_id: str | None = None,
__request__: Request = None,
__user__: dict = None,
__metadata__: dict = None,
@@ -1801,13 +1784,14 @@ async def delegate_task(
__message_id__: str = None,
) -> str:
"""
- Delegate focused work to a parallel sub-agent using the current model and tools.
+ Delegate focused work to a parallel sub-agent using the current tools.
:param task: The specific task for the sub-agent to complete
:param context: Relevant context, decisions, or file paths for the task
:param file_ids: Attached file IDs the sub-agent needs. Use this for images or files;
do not put file IDs only in context.
:param background: Return immediately and continue this chat when the sub-agent finishes
+ :param model_id: ID of an available sub-agent model. Omit to use the current model
:return: Foreground result text, or a JSON dispatch handle for background work
"""
if __request__ is None:
@@ -1822,6 +1806,7 @@ async def delegate_task(
context,
background,
file_ids=file_ids,
+ model_id=model_id,
request=__request__,
user_data=__user__ or {},
metadata=__metadata__ or {},
@@ -1867,9 +1852,7 @@ async def timer(
)
-# =============================================================================
-# CHANNELS TOOLS
-# =============================================================================
+# Channels tools
async def search_channels(
@@ -2109,7 +2092,7 @@ async def view_channel_thread(
# Build the response
messages = []
- # Add parent message first
+ # Parent message first; the replies need something to reply to.
messages.append(
{
'id': parent_message.id,
@@ -2121,7 +2104,7 @@ async def view_channel_thread(
}
)
- # Add thread replies (reverse to get chronological order)
+ # Reverse the replies into chronological order; spoilers go at the end.
for reply in reversed(thread_replies):
messages.append(
{
@@ -2150,9 +2133,7 @@ async def view_channel_thread(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# KNOWLEDGE BASE TOOLS
-# =============================================================================
+# Knowledge base tools
async def list_knowledge_bases(
@@ -3664,9 +3645,7 @@ async def query_knowledge_bases(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# SKILLS TOOLS
-# =============================================================================
+# Skills tools
async def view_skill(
@@ -3888,6 +3867,47 @@ async def grep_skill_files(
return result
+async def create_tool(
+ id: str,
+ name: str,
+ description: str,
+ content: str,
+ __request__: Request = None,
+ __user__: dict = None,
+) -> str:
+ """Create a private Python tool in the workspace.
+ Source must define a Tools class with public methods, type hints, and descriptive docstrings.
+ Use Valves or UserValves for credentials; do not embed secrets. Saving executes the Python module on the server.
+
+ :param id: Unique lowercase Python identifier for the toolkit.
+ :param name: Display name.
+ :param description: Short description of what the tool does.
+ :param content: Complete Python source, without Markdown fences.
+ """
+ try:
+ from types import SimpleNamespace
+
+ from open_webui.models.tools import ToolForm
+ from open_webui.routers.tools import create_new_tools
+ from open_webui.utils.access_control import has_permission
+
+ if __request__ is None or not __user__:
+ raise ValueError('Request and user context required')
+ if __user__.get('role') != 'admin' and not await has_permission(
+ __user__['id'], 'workspace.tools', await Config.get('user.permissions')
+ ):
+ raise ValueError('Tool authoring permission required')
+ result = await create_new_tools(
+ __request__,
+ ToolForm(id=id, name=name, content=content, meta={'description': description}, access_grants=[]),
+ SimpleNamespace(**__user__),
+ None,
+ )
+ return JSONCodec.dumps({'id': result.id, 'url': '/workspace/tools/edit?id=' + result.id})
+ except Exception as error:
+ return JSONCodec.dumps({'error': getattr(error, 'detail', str(error))})
+
+
async def create_skill(
id: str,
name: str,
@@ -3999,9 +4019,7 @@ async def update_skill_files(
return JSONCodec.dumps({'error': detail})
-# =============================================================================
-# TOOL SEARCH
-# =============================================================================
+# Tool search
async def search_tools(
@@ -4031,9 +4049,7 @@ async def search_tools(
return JSONCodec.dumps({'tools': [candidates[name] for name in matches]})
-# =============================================================================
-# TASK MANAGEMENT TOOLS
-# =============================================================================
+# Task management tools
from typing import Literal
@@ -4176,9 +4192,7 @@ async def update_task(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# AUTOMATION TOOLS
-# =============================================================================
+# Automation tools
async def _validate_owned_automation_folder(user_id: str, folder_id: Optional[str]) -> Optional[str]:
@@ -4571,9 +4585,7 @@ async def delete_automation(
return JSONCodec.dumps({'error': str(e)})
-# =============================================================================
-# CALENDAR TOOLS
-# =============================================================================
+# Calendar tools
MAX_CALENDAR_RANGE_END_NS = 2**63 - 1
diff --git a/backend/open_webui/tools/knowledge_fs.py b/backend/open_webui/tools/knowledge_fs.py
index 0ab071f24a..5bc73396d9 100644
--- a/backend/open_webui/tools/knowledge_fs.py
+++ b/backend/open_webui/tools/knowledge_fs.py
@@ -62,9 +62,7 @@ def match_budget():
_active_budget.reset(token)
-# =============================================================================
-# SHARED REGEX UTILITIES — also used by builtin.py grep_knowledge_files
-# =============================================================================
+# Shared regex utilities — also used by builtin.py grep_knowledge_files
def is_regex_pattern(pattern: str) -> bool:
@@ -173,9 +171,7 @@ def build_matcher(pattern: str, case_insensitive: bool = False, use_regex: bool
return (lambda line: sp in (line.lower() if case_insensitive else line)), None
-# =============================================================================
-# COMMAND PARSING
-# =============================================================================
+# Command parsing
def _parse_pipeline(command: str) -> list[list[str]]:
@@ -248,9 +244,7 @@ def _extract_numeric_flag(tokens: list[str]) -> tuple[Optional[int], list[str]]:
return num, remaining
-# =============================================================================
-# DIRECTORY TREE & PATH RESOLUTION
-# =============================================================================
+# Directory tree & path resolution
async def _build_directory_tree(knowledge_id: str) -> dict:
@@ -344,9 +338,7 @@ def _get_files_under_dir(tree: dict, dir_id: str) -> list[dict]:
return [f for f in tree['files'] if f['directory_id'] in target_ids]
-# =============================================================================
-# FILE RESOLUTION & ACCESS CONTROL
-# =============================================================================
+# File resolution & access control
async def _get_accessible_kb_ids(
@@ -573,9 +565,7 @@ async def _get_file_content(file_id: str) -> str | None:
return None
-# =============================================================================
-# COMMAND HANDLERS
-# =============================================================================
+# Command handlers
async def _kb_ls(args: list[str], flags: set[str], user: dict, model_knowledge: list[dict] | None) -> str:
@@ -1063,9 +1053,7 @@ async def _kb_sed(
return result
-# =============================================================================
-# PIPE EXECUTOR
-# =============================================================================
+# Pipe executor
async def _kb_tree(args: list[str], flags: set[str], user: dict, model_knowledge: list[dict] | None) -> str:
@@ -1177,9 +1165,7 @@ async def _execute_pipeline(
return piped_input or ''
-# =============================================================================
-# ENTRY POINT
-# =============================================================================
+# Entry point
async def kb_exec(
diff --git a/backend/open_webui/utils/anthropic.py b/backend/open_webui/utils/anthropic.py
index bd2cea2e61..5f1498c0f1 100644
--- a/backend/open_webui/utils/anthropic.py
+++ b/backend/open_webui/utils/anthropic.py
@@ -101,11 +101,7 @@ async def get_anthropic_models(url: str, key: str, user: UserModel = None) -> di
return {'object': 'list', 'data': all_models}
-##############################
-#
# Anthropic Messages API Conversion Utilities
-#
-##############################
def _copy_cache_control(source: dict, target: dict) -> dict:
@@ -118,7 +114,7 @@ def _has_cache_control(blocks: list) -> bool:
return any(isinstance(block, dict) and 'cache_control' in block for block in blocks)
-def _finalize_openai_content(blocks: list) -> str | list:
+def _finalize_chat_completions_content(blocks: list) -> str | list:
if not blocks:
return ''
@@ -135,7 +131,7 @@ def is_anthropic_messages_passthrough(url: str, api_config: dict | None = None)
return is_anthropic_url(url or '') or provider == 'litellm'
-def convert_anthropic_to_openai_payload(
+def convert_anthropic_payload_to_chat_completions(
anthropic_payload: dict, passthrough_params: list[str] | str | None = None
) -> dict:
"""
@@ -174,7 +170,7 @@ def convert_anthropic_to_openai_payload(
)
elif isinstance(block, str):
openai_content.append({'type': 'text', 'text': block})
- messages.append({'role': 'system', 'content': _finalize_openai_content(openai_content)})
+ messages.append({'role': 'system', 'content': _finalize_chat_completions_content(openai_content)})
# Convert messages
for msg in anthropic_payload.get('messages', []):
@@ -366,13 +362,13 @@ def convert_anthropic_to_openai_payload(
# Assistant message with tool calls
msg_dict = {'role': role}
if openai_content:
- msg_dict['content'] = _finalize_openai_content(openai_content)
+ msg_dict['content'] = _finalize_chat_completions_content(openai_content)
else:
msg_dict['content'] = ''
msg_dict['tool_calls'] = tool_calls
messages.append(msg_dict)
elif openai_content or role == 'assistant':
- messages.append({'role': role, 'content': _finalize_openai_content(openai_content)})
+ messages.append({'role': role, 'content': _finalize_chat_completions_content(openai_content)})
else:
messages.append({'role': role, 'content': str(content) if content else ''})
@@ -469,7 +465,7 @@ def convert_anthropic_to_openai_payload(
return openai_payload
-def convert_openai_to_anthropic_response(
+def convert_chat_completions_response_to_anthropic(
openai_response: dict, model: str = '', input_tokens: int | None = None
) -> dict:
"""
@@ -592,7 +588,9 @@ def convert_openai_to_anthropic_response(
}
-async def openai_stream_to_anthropic_stream(openai_stream_generator, model: str = '', input_tokens: int | None = None):
+async def convert_chat_completions_stream_to_anthropic(
+ openai_stream_generator, model: str = '', input_tokens: int | None = None
+):
"""
Convert an OpenAI SSE streaming response to Anthropic Messages SSE format.
@@ -752,7 +750,7 @@ async def openai_stream_to_anthropic_stream(openai_stream_generator, model: str
}
yield f'event: content_block_delta\ndata: {JSONCodec.dumps(block_delta)}\n\n'.encode()
- # --- Handle text content ---
+ # Handle text content
# Anthropic expects text blocks before tool blocks, so skip
# text deltas once any tool call has started.
content = delta.get('content')
@@ -782,7 +780,7 @@ async def openai_stream_to_anthropic_stream(openai_stream_generator, model: str
}
yield f'event: content_block_delta\ndata: {JSONCodec.dumps(block_delta)}\n\n'.encode()
- # --- Handle tool calls ---
+ # Handle tool calls
# Some providers put tool_calls on the final message object
# instead of the delta; fall back to that when needed.
tool_calls = delta.get('tool_calls') or []
@@ -903,7 +901,7 @@ async def openai_stream_to_anthropic_stream(openai_stream_generator, model: str
except (JSONCodec.JSONDecodeError, ValueError):
pass
- # --- Handle finish reason ---
+ # Handle finish reason
if finish_reason is not None:
stop_reason_map = {
'stop': 'end_turn',
diff --git a/backend/open_webui/utils/asgi_middleware.py b/backend/open_webui/utils/asgi_middleware.py
index 2d9f4e190e..58caa4cd60 100644
--- a/backend/open_webui/utils/asgi_middleware.py
+++ b/backend/open_webui/utils/asgi_middleware.py
@@ -42,12 +42,22 @@ from open_webui.internal.db import ScopedSession
from open_webui.utils.auth import get_http_authorization_cred
from open_webui.utils.security_headers import set_security_headers
from starlette.datastructures import MutableHeaders
+from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.types import ASGIApp, Message, Receive, Scope, Send
log = logging.getLogger(__name__)
+class BrowserCORSMiddleware(CORSMiddleware):
+ async def __call__(self, scope, receive, send):
+ # Sandboxed pages have an opaque origin; capability routes handle their own CORS.
+ if re.match(r'^/api/v1/terminals/[^/]+/browser/view/', scope.get('path', '')):
+ await self.app(scope, receive, send)
+ else:
+ await super().__call__(scope, receive, send)
+
+
class AppHTTPMiddleware:
"""Open WebUI's pure-ASGI HTTP middleware.
diff --git a/backend/open_webui/utils/auth.py b/backend/open_webui/utils/auth.py
index 44d0c8c460..1363601508 100644
--- a/backend/open_webui/utils/auth.py
+++ b/backend/open_webui/utils/auth.py
@@ -48,9 +48,7 @@ SESSION_SECRET = WEBUI_SECRET_KEY
ALGORITHM = 'HS256'
PASSWORD_BCRYPT_MAX_BYTES = 72
-##############
# Auth Utils
-##############
def verify_signature(payload: str, signature: str) -> bool:
@@ -222,9 +220,8 @@ async def verify_password(plain_password: str, hashed_password: str) -> bool:
return False
-# Let the one who signed this token be remembered at every gate,
-# and may the claims therein honor the creator long after
-# the session has closed.
+# Let this token open only the doors it should,
+# and have the good manners to expire before overstaying its welcome.
def create_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
payload = data.copy()
@@ -391,10 +388,7 @@ async def get_current_user(
response: Response,
background_tasks: BackgroundTasks,
auth_token: HTTPAuthorizationCredentials = Depends(bearer_security),
- # NOTE: We intentionally do NOT use Depends(get_session) here.
- # Sessions are managed internally with short-lived context managers.
- # This ensures connections are released immediately after auth queries,
- # not held for the entire request duration (e.g., during 30+ second LLM calls).
+ # Use short-lived auth sessions so streaming requests do not retain DB connections.
):
token = None
diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py
index 292e435083..3250b38614 100644
--- a/backend/open_webui/utils/automations.py
+++ b/backend/open_webui/utils/automations.py
@@ -27,7 +27,7 @@ from uuid import uuid4
from fastapi import Request
from fastapi.security import HTTPAuthorizationCredentials
from open_webui.constants import ERROR_MESSAGES
-from open_webui.events import EVENTS, publish_event
+from open_webui.events import EVENTS, build_event, publish_event
from open_webui.internal.db import get_async_db
from open_webui.models.automations import AutomationModel, AutomationRuns, Automations
from open_webui.models.chats import ChatForm, Chats
@@ -56,9 +56,7 @@ TIMER_POLL_INTERVAL = int(os.getenv('TIMER_POLL_INTERVAL', '1'))
CALENDAR_ALERT_LOOKAHEAD_MINUTES = int(os.getenv('CALENDAR_ALERT_LOOKAHEAD_MINUTES', '10'))
-############################
# Worker Loop
-############################
# Keep the old name as an alias so any stale imports still work.
@@ -87,7 +85,7 @@ async def scheduler_worker_loop(app) -> None:
while True:
try:
now = time.monotonic()
- # ── Timers ──
+ # Timers
try:
from open_webui.utils.timers import claim_due_timers, execute_due_timer
@@ -102,7 +100,7 @@ async def scheduler_worker_loop(app) -> None:
# Jitter to spread automation/calendar load across instances; timers keep a tight poll.
next_scheduler_poll = now + SCHEDULER_POLL_INTERVAL + random.uniform(0, 2)
- # ── Automations ──
+ # Automations
if await Config.get('automations.enable'):
try:
async with get_async_db() as db:
@@ -114,7 +112,7 @@ async def scheduler_worker_loop(app) -> None:
except Exception:
log.exception('Scheduler: automation error')
- # ── Calendar Alerts ──
+ # Calendar alerts
if await Config.get('calendar.enable'):
try:
await _check_calendar_alerts(app)
@@ -127,9 +125,7 @@ async def scheduler_worker_loop(app) -> None:
await asyncio.sleep(max(1, TIMER_POLL_INTERVAL))
-##########################
# Execute
-####################
def _build_request(
@@ -340,9 +336,9 @@ async def _execute_channel_automation(
room=f'user:{automation.user_id}',
)
- await _record_run(automation.id, 'success', chat_id=f'channel:{channel.id}')
+ await _record_run(request, automation.id, 'success', chat_id=f'channel:{channel.id}')
await publish_event(
- app,
+ request,
EVENTS.AUTOMATION_RUN_COMPLETED,
actor=user,
subject_id=automation.id,
@@ -358,16 +354,11 @@ async def execute_automation(app, automation: AutomationModel) -> None:
(filters, model params, knowledge/RAG, tools, DB saves, webhooks).
"""
chat = None
+ request = _build_request(app)
try:
user = await Users.get_user_by_id(automation.user_id)
if not user:
- await _record_run(automation.id, 'error', error='User not found')
- await publish_event(
- app,
- EVENTS.AUTOMATION_RUN_FAILED,
- subject_id=automation.id,
- data={'name': automation.name, 'error': 'User not found'},
- )
+ await _record_run(request, automation.id, 'error', error='User not found')
return
# Re-gate the rehydrated owner: a demoted/deactivated or de-permissioned owner must not run.
@@ -378,14 +369,7 @@ async def execute_automation(app, automation: AutomationModel) -> None:
and not await has_permission(user.id, 'features.automations', await Config.get('user.permissions'))
):
error = 'Owner no longer permitted to run automations'
- await _record_run(automation.id, 'error', error=error)
- await publish_event(
- app,
- EVENTS.AUTOMATION_RUN_FAILED,
- actor=user,
- subject_id=automation.id,
- data={'name': automation.name, 'error': error, 'message': f'{automation.name}: {error}'},
- )
+ await _record_run(request, automation.id, 'error', error=error, actor=user)
return
prompt = await prompt_template(automation.data['prompt'], user)
@@ -464,14 +448,7 @@ async def execute_automation(app, automation: AutomationModel) -> None:
if not chat:
error = 'Failed to create chat'
- await _record_run(automation.id, 'error', error=error)
- await publish_event(
- app,
- EVENTS.AUTOMATION_RUN_FAILED,
- actor=user,
- subject_id=automation.id,
- data={'name': automation.name, 'error': error, 'message': f'{automation.name}: {error}'},
- )
+ await _record_run(request, automation.id, 'error', error=error, actor=user)
return
# Notify frontend to refresh chat list
@@ -542,9 +519,9 @@ async def execute_automation(app, automation: AutomationModel) -> None:
room=f'user:{automation.user_id}',
)
- await _record_run(automation.id, 'success', chat_id=chat.id)
+ await _record_run(request, automation.id, 'success', chat_id=chat.id)
await publish_event(
- app,
+ request,
EVENTS.AUTOMATION_RUN_COMPLETED,
actor=user,
subject_id=automation.id,
@@ -554,26 +531,12 @@ async def execute_automation(app, automation: AutomationModel) -> None:
except (Exception, asyncio.CancelledError) as e:
log.exception(f'Automation {automation.id} failed')
error = 'Automation reply was cancelled' if isinstance(e, asyncio.CancelledError) else str(e)[:4000]
- await _record_run(automation.id, 'error', chat_id=chat.id if chat else None, error=error)
- await publish_event(
- app,
- EVENTS.AUTOMATION_RUN_FAILED,
- subject_id=automation.id,
- data={
- 'name': automation.name,
- 'error': error,
- 'user_id': automation.user_id,
- 'message': f'{automation.name}: {error}',
- **({'chat_id': chat.id} if chat else {}),
- },
- )
+ await _record_run(request, automation.id, 'error', chat_id=chat.id if chat else None, error=error)
if isinstance(e, asyncio.CancelledError):
raise
-####################
# Internals
-####################
async def _check_calendar_alerts(app) -> None:
@@ -582,7 +545,7 @@ async def _check_calendar_alerts(app) -> None:
De-duplication is DB-backed via meta.alerted_at — survives restarts
and works across multiple instances.
"""
- from open_webui.models.calendar import CalendarEvents, CalendarEventUpdateForm
+ from open_webui.models.calendar import CalendarEvents
from open_webui.socket.main import sio
now_ns = int(time.time_ns())
@@ -597,6 +560,7 @@ async def _check_calendar_alerts(app) -> None:
if not upcoming:
return
+ request = _build_request(app)
for event, user_tz in upcoming:
# Skip if already alerted for this start time
if event.meta and event.meta.get('alerted_at') == event.start_at:
@@ -615,6 +579,45 @@ async def _check_calendar_alerts(app) -> None:
'location': event.location or '',
}
+ from open_webui.models.calendar import CalendarEvent
+ from sqlalchemy import select
+
+ async with get_async_db() as db:
+ current = await db.scalar(select(CalendarEvent).where(CalendarEvent.id == event.id).with_for_update())
+ if (
+ not current
+ or current.is_cancelled
+ or current.start_at != event.start_at
+ or (current.meta or {}).get('alerted_at') == event.start_at
+ ):
+ continue
+ time_str = f'in {minutes_until} min' if minutes_until > 0 else 'now'
+ from open_webui.utils.inbox import consume_event
+ from open_webui.models.notifications import emit_changes
+
+ alert_event = build_event(
+ request,
+ EVENTS.CALENDAR_ALERT,
+ subject_id=event.id,
+ subject_type='calendar.event',
+ source='scheduler',
+ message=event.title,
+ event_id=f'calendar:{event.id}:{event.start_at}',
+ data={
+ **alert_data,
+ 'user_id': event.user_id,
+ 'starts_in': time_str,
+ 'start_at': event.start_at,
+ 'message': f'{event.title}: starting {time_str}',
+ },
+ )
+ current.meta = {**(current.meta or {}), 'alerted_at': event.start_at}
+ current.updated_at = time.time_ns()
+ recipients = await consume_event(alert_event, db=db)
+ await db.commit()
+ await emit_changes(recipients)
+ await publish_event(request, alert_event)
+
await sio.emit(
'events',
{
@@ -626,42 +629,17 @@ async def _check_calendar_alerts(app) -> None:
room=f'user:{event.user_id}',
)
- # Mark as alerted in DB so it survives restarts / multi-instance
- try:
- await CalendarEvents.update_event_by_id(
- event.id,
- CalendarEventUpdateForm(meta={'alerted_at': event.start_at}),
- )
- except Exception:
- log.debug('Failed to mark event %s as alerted', event.id, exc_info=True)
-
- # Send target notification if user has one configured
- try:
- time_str = f'in {minutes_until} min' if minutes_until > 0 else 'now'
- await publish_event(
- app,
- EVENTS.CALENDAR_ALERT,
- subject_id=event.id,
- subject_type='calendar.event',
- source='scheduler',
- data={
- **alert_data,
- 'user_id': event.user_id,
- 'starts_in': time_str,
- 'message': f'{event.title}: starting {time_str}',
- },
- message=event.title,
- )
- except Exception:
- log.debug('Failed to send notification for calendar alert %s', event.id, exc_info=True)
-
async def _record_run(
+ request: Request,
automation_id: str,
status: str,
chat_id: str = None,
error: str = None,
+ actor=None,
):
"""Insert a run record into automation_run."""
async with get_async_db() as db:
- await AutomationRuns.insert(automation_id, status, chat_id=chat_id, error=error, db=db)
+ await AutomationRuns.insert(
+ automation_id, status, chat_id=chat_id, error=error, request=request, event_actor=actor, db=db
+ )
diff --git a/backend/open_webui/utils/browser.py b/backend/open_webui/utils/browser.py
new file mode 100644
index 0000000000..2bc3ebf3d7
--- /dev/null
+++ b/backend/open_webui/utils/browser.py
@@ -0,0 +1,42 @@
+from fastapi import HTTPException
+from open_webui.utils.auth import create_token, decode_token, get_verified_user_by_id
+
+
+def browser_ticket(server_id, user_id, chat_id, session, headers=None, cookies=None):
+ from open_webui.utils.oauth import encrypt_data
+
+ relay = encrypt_data(
+ {
+ 'authorization': (headers or {}).get('Authorization'),
+ 'cookies': cookies or {},
+ }
+ )
+ return create_token(
+ {
+ 'purpose': 'terminal-browser',
+ 'server': server_id,
+ 'user': user_id,
+ 'chat': chat_id,
+ 'session': session['id'],
+ 'capability': session['token'],
+ 'relay': relay,
+ },
+ )
+
+
+async def browser_access(server_id, sid, ticket):
+ data = decode_token(ticket)
+ if (
+ not data
+ or data.get('purpose') != 'terminal-browser'
+ or data.get('server') != server_id
+ or data.get('session') != sid
+ ):
+ raise HTTPException(401, 'Browser session expired')
+ user = await get_verified_user_by_id(data.get('user'))
+ if user is None:
+ raise HTTPException(401, 'Browser session expired')
+ from open_webui.utils.oauth import decrypt_data
+
+ data['relay'] = decrypt_data(data['relay'])
+ return user, data
diff --git a/backend/open_webui/utils/chat.py b/backend/open_webui/utils/chat.py
index c97985dde4..f34556df6f 100644
--- a/backend/open_webui/utils/chat.py
+++ b/backend/open_webui/utils/chat.py
@@ -1,4 +1,5 @@
import asyncio
+import json
import logging
import random
import sys
@@ -8,7 +9,7 @@ from typing import Any, Optional
from aiocache import cached
from fastapi import HTTPException, Request, status
-from open_webui.env import BYPASS_MODEL_ACCESS_CONTROL, GLOBAL_LOG_LEVEL
+from open_webui.env import BYPASS_MODEL_ACCESS_CONTROL, GLOBAL_LOG_LEVEL, REDIS_KEY_PREFIX
from open_webui.functions import generate_function_chat_completion
from open_webui.models.models import Models
from open_webui.models.users import UserModel
@@ -27,16 +28,17 @@ from open_webui.socket.main import (
get_event_call,
get_event_emitter,
)
+from open_webui.utils.chat_id import get_temporary_chat_session_id
from open_webui.utils.filter import (
get_filter_functions,
process_filter_functions,
)
from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.models import check_model_access, get_all_models
-from open_webui.utils.payload import apply_system_prompt_to_body, convert_payload_openai_to_ollama
+from open_webui.utils.payload import apply_system_prompt_to_body, convert_chat_completions_payload_to_ollama
from open_webui.utils.response import (
- convert_response_ollama_to_openai,
- convert_streaming_response_ollama_to_openai,
+ convert_ollama_response_to_chat_completions,
+ convert_ollama_stream_to_chat_completions,
)
from starlette.responses import JSONResponse, Response, StreamingResponse
@@ -44,6 +46,64 @@ logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
log = logging.getLogger(__name__)
+TEMPORARY_CHAT_TTL = 24 * 60 * 60
+_temporary_chat_owners: dict[str, tuple[float, dict]] = {}
+
+
+def _temporary_chat_key(chat_id):
+ return f'{REDIS_KEY_PREFIX}:chat:{chat_id}:session'
+
+
+async def get_temporary_chat(redis, chat_id):
+ if redis is not None:
+ value = await redis.get(_temporary_chat_key(chat_id))
+ return json.loads(value) if value else None
+ expiry, owner = _temporary_chat_owners.get(chat_id, (0, None))
+ if expiry <= time.monotonic():
+ _temporary_chat_owners.pop(chat_id, None)
+ return None
+ return owner
+
+
+async def register_temporary_chat_session(redis, chat_id, user_id, session_id, session_owner, *, create=False):
+ """Only an authenticated live socket can create or reattach its user's chat."""
+ origin = get_temporary_chat_session_id(chat_id)
+ if not origin or not session_id or session_owner != user_id:
+ return False
+ owner = await get_temporary_chat(redis, chat_id)
+ if owner is None:
+ if not create or origin != session_id:
+ return False
+ elif owner['user_id'] != user_id:
+ return False
+
+ value = {'user_id': user_id, 'session_id': session_id}
+ if redis is not None:
+ encoded = json.dumps(value, sort_keys=True)
+ if owner is None:
+ return bool(
+ await redis.set(_temporary_chat_key(chat_id), encoded, nx=True, ex=TEMPORARY_CHAT_TTL)
+ ) or await register_temporary_chat_session(redis, chat_id, user_id, session_id, session_owner)
+ # An expired/replaced record must not be overwritten after the ownership check.
+ return bool(
+ await redis.eval(
+ "if redis.call('get', KEYS[1]) ~= ARGV[1] then return 0 end "
+ "redis.call('set', KEYS[1], ARGV[2], 'EX', ARGV[3]); return 1",
+ 1,
+ _temporary_chat_key(chat_id),
+ json.dumps(owner, sort_keys=True),
+ encoded,
+ TEMPORARY_CHAT_TTL,
+ )
+ )
+ now = time.monotonic()
+ for key, (expiry, _) in list(_temporary_chat_owners.items()):
+ if expiry <= now:
+ _temporary_chat_owners.pop(key, None)
+ _temporary_chat_owners[chat_id] = (now + TEMPORARY_CHAT_TTL, value)
+ return True
+
+
# When the question has been asked, let silence not be the
# answer. But if the answer must wait, let it come honest.
async def generate_direct_chat_completion(
@@ -290,7 +350,7 @@ async def generate_chat_completion(
request.state.bypass_system_prompt = True
# Using /ollama/api/chat endpoint
- form_data = convert_payload_openai_to_ollama(form_data)
+ form_data = convert_chat_completions_payload_to_ollama(form_data)
response = await generate_ollama_chat_completion(
request=request,
form_data=form_data,
@@ -299,12 +359,12 @@ async def generate_chat_completion(
if form_data.get('stream'):
response.headers['content-type'] = 'text/event-stream'
return StreamingResponse(
- convert_streaming_response_ollama_to_openai(response),
+ convert_ollama_stream_to_chat_completions(response),
headers=dict(response.headers),
background=response.background,
)
else:
- return convert_response_ollama_to_openai(response)
+ return convert_ollama_response_to_chat_completions(response)
else:
return await generate_openai_chat_completion(
request=request,
diff --git a/backend/open_webui/utils/chat_id.py b/backend/open_webui/utils/chat_id.py
index 47b5e61174..c745a35512 100644
--- a/backend/open_webui/utils/chat_id.py
+++ b/backend/open_webui/utils/chat_id.py
@@ -1,5 +1,4 @@
-from typing import Optional
-
+from uuid import UUID
TEMPORARY_CHAT_ID_PREFIX = 'temporary:'
LEGACY_TEMPORARY_CHAT_ID_PREFIX = 'local:' # Legacy temporary chat prefix.
@@ -12,16 +11,26 @@ TEMPORARY_CHAT_ID_PREFIXES = (
NON_SAVED_CHAT_ID_PREFIXES = (*TEMPORARY_CHAT_ID_PREFIXES, CHANNEL_CHAT_ID_PREFIX)
-def is_saved_chat_id(chat_id: Optional[str]) -> bool:
+def is_saved_chat_id(chat_id: str | None) -> bool:
return bool(chat_id) and not chat_id.startswith(NON_SAVED_CHAT_ID_PREFIXES)
-def is_temporary_chat_id(chat_id: Optional[str]) -> bool:
+def is_temporary_chat_id(chat_id: str | None) -> bool:
return bool(chat_id) and chat_id.startswith(TEMPORARY_CHAT_ID_PREFIXES)
-def get_temporary_chat_session_id(chat_id: str) -> Optional[str]:
+def get_temporary_chat_session_id(chat_id: str) -> str | None:
for prefix in TEMPORARY_CHAT_ID_PREFIXES:
if chat_id.startswith(prefix):
- return chat_id.removeprefix(prefix)
+ value = chat_id.removeprefix(prefix)
+ session_id, separator, conversation_id = value.partition(':')
+ if not session_id:
+ return None
+ if separator:
+ try:
+ if str(UUID(conversation_id)) != conversation_id:
+ return None
+ except ValueError:
+ return None
+ return session_id
return None
diff --git a/backend/open_webui/utils/comments.py b/backend/open_webui/utils/comments.py
new file mode 100644
index 0000000000..924f853982
--- /dev/null
+++ b/backend/open_webui/utils/comments.py
@@ -0,0 +1,160 @@
+"""Access and optional source context for comments; never returns resource contents."""
+
+import hashlib
+from types import SimpleNamespace
+
+from fastapi import HTTPException
+from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
+from open_webui.models.access_grants import AccessGrants
+from open_webui.models.config import Config
+from open_webui.utils.access_control import has_permission
+from sqlalchemy import select
+
+
+def resource_models():
+ from open_webui.models.chats import Chat
+ from open_webui.models.knowledge import Knowledge
+ from open_webui.models.models import Model
+ from open_webui.models.notes import Note
+ from open_webui.models.prompts import Prompt
+ from open_webui.models.skills import Skill
+ from open_webui.models.tools import Tool
+
+ return dict(
+ model=Model,
+ knowledge=Knowledge,
+ prompt=Prompt,
+ skill=Skill,
+ tool=Tool,
+ note=Note,
+ chat=Chat,
+ )
+
+
+async def provider_comment_resource(resource_id, user, request):
+ # Unconfigured provider models are visible only to admins, as in the catalog.
+ if user.role != 'admin' or request is None:
+ raise HTTPException(404, 'Resource not found')
+ providers = getattr(request.app.state, 'BASE_MODELS', [])
+ if not providers:
+ from open_webui.utils.models import get_all_models
+
+ await get_all_models(request, user=user)
+ providers = getattr(request.app.state, 'BASE_MODELS', [])
+ provider = next((item for item in providers if item.get('id') == resource_id), None)
+ if provider is None:
+ raise HTTPException(404, 'Resource not found')
+ return SimpleNamespace(id=resource_id, name=provider.get('name') or resource_id, user_id=None)
+
+
+async def comment_resource(resource_type, resource_id, user, db, *, lock=False, request=None):
+ if not await Config.get('comments.enable'):
+ raise HTTPException(403, 'Comments are disabled')
+ model = resource_models().get(resource_type)
+ if model is None or user.role not in {'user', 'admin'}:
+ raise HTTPException(404, 'Resource not found')
+ query = select(model).where(model.id == resource_id)
+ resource = await db.scalar(query.with_for_update() if lock else query)
+ if resource is None:
+ if resource_type == 'model':
+ return await provider_comment_resource(resource_id, user, request)
+ raise HTTPException(404, 'Resource not found')
+ allowed = resource.user_id == user.id
+ if resource_type == 'chat':
+ from open_webui.models.chats import Chats
+
+ allowed = await Chats.get_accessible_chat_by_id(resource_id, user, db=db, chat=resource) is not None
+ else:
+ if resource_type == 'note':
+ if not await Config.get('notes.enable') or (
+ user.role != 'admin'
+ and not await has_permission(user.id, 'features.notes', await Config.get('user.permissions'), db=db)
+ ):
+ raise HTTPException(404, 'Resource not found')
+ allowed = (
+ allowed
+ or (user.role == 'admin' and (resource_type == 'note' or BYPASS_ADMIN_ACCESS_CONTROL))
+ or await AccessGrants.has_access(user.id, resource_type, resource_id, 'read', db=db)
+ )
+ if not allowed:
+ raise HTTPException(404, 'Resource not found')
+ return resource
+
+
+async def effective_comment_context(resource_type, resource_id, user, db, *, request=None):
+ resource = await comment_resource(resource_type, resource_id, user, db, request=request)
+ return {
+ 'resource_type': resource_type,
+ 'resource_id': resource_id,
+ 'title': getattr(resource, 'title', None) or getattr(resource, 'name', None) or resource_id,
+ }
+
+
+def note_comment_text(content):
+ def text(node):
+ if not isinstance(node, dict):
+ return ''
+ if node.get('type') == 'text':
+ return node.get('text', '')
+ return ''.join(text(child) for child in node.get('content', []))
+
+ return text(content['json']) if isinstance(content.get('json'), dict) else content.get('md') or ''
+
+
+def validate_comment_target(resource_type, resource, form):
+ if bool(form.target_type) != bool(form.target_id) or (form.anchor and not form.target_id):
+ raise HTTPException(422, 'A selection requires a target')
+ if not form.target_id:
+ return
+ if resource_type == 'note' and form.target_type == 'note_page':
+ from open_webui.models.notes import normalize_pages
+
+ target = next((p for p in normalize_pages(resource.data)['pages'] if p['id'] == form.target_id), None)
+ elif resource_type == 'chat' and form.target_type == 'chat_message':
+ target = (resource.chat.get('history', {}).get('messages') or {}).get(form.target_id)
+ if target and target.get('role') == 'assistant' and target.get('done') is False:
+ raise HTTPException(409, 'Wait for the message to finish')
+ else:
+ target = None
+ if target is None:
+ raise HTTPException(404, 'Comment target not found')
+ if form.anchor and (
+ form.anchor.end <= form.anchor.start or form.anchor.end - form.anchor.start != len(form.anchor.quote)
+ ):
+ raise HTTPException(422, 'Invalid text selection')
+
+ if form.anchor:
+ source = comment_anchor_source(resource_type, target, form)
+ if not isinstance(source, str) or hashlib.sha256(source.encode()).hexdigest() != form.anchor.content_hash:
+ raise HTTPException(409, 'Content changed. Select the passage again or leave a general comment.')
+
+
+def comment_anchor_source(resource_type, target, form):
+ if resource_type == 'note':
+ if form.anchor.surface_id != form.target_id:
+ raise HTTPException(422, 'Invalid page selection')
+ source = note_comment_text(target.get('content') or {})
+ elif form.anchor.surface_id == 'content':
+ source = target.get('content') or ''
+ else:
+ matches = [
+ item
+ for index, item in enumerate(target.get('output') or [])
+ if form.anchor.surface_id
+ == (item.get('id') or f'{"message" if item.get("type") == "message" else "output"}-{index}')
+ and item.get('type')
+ not in {
+ 'reasoning',
+ 'function_call',
+ 'open_webui:code_interpreter',
+ 'web_search_call',
+ 'file_search_call',
+ 'computer_call',
+ }
+ ]
+ if len(matches) != 1:
+ raise HTTPException(409, 'Message output changed. Select the passage again.')
+ source = ''.join(
+ part.get('text', '') for part in matches[0].get('content', []) if isinstance(part.get('text'), str)
+ )
+ return source
diff --git a/backend/open_webui/utils/filter.py b/backend/open_webui/utils/filter.py
index 3bc5346b1d..bc7fac1f26 100644
--- a/backend/open_webui/utils/filter.py
+++ b/backend/open_webui/utils/filter.py
@@ -207,8 +207,8 @@ async def process_filter_function(
return form_data, valves_by_id, skip_files
-# Grant these filters the discernment to pass what serves
-# and refuse what harms, for every soul in the house.
+# Let these filters pass what helps and catch what harms,
+# and spare us the bug report that explains the difference.
async def process_filter_functions(
request,
filter_context,
diff --git a/backend/open_webui/utils/inbox.py b/backend/open_webui/utils/inbox.py
new file mode 100644
index 0000000000..da55d9755b
--- /dev/null
+++ b/backend/open_webui/utils/inbox.py
@@ -0,0 +1,451 @@
+"""Resource-aware producers and reads for the general inbox."""
+
+from collections import defaultdict
+
+from sqlalchemy import and_, false, or_, select, true
+from sqlalchemy.orm import load_only
+
+from open_webui.models.notifications import Notification, insert_notifications
+
+
+def source_models():
+ from open_webui.utils.comments import resource_models
+ from open_webui.models.automations import Automation, AutomationRun
+ from open_webui.models.calendar import Calendar, CalendarEvent
+ from open_webui.models.channels import Channel
+ from open_webui.models.comments import Comment
+ from open_webui.models.messages import Message
+
+ return {
+ **resource_models(),
+ 'automation': Automation,
+ 'automation_run': AutomationRun,
+ 'calendar': Calendar,
+ 'calendar_event': CalendarEvent,
+ 'channel': Channel,
+ 'comment': Comment,
+ 'message': Message,
+ }
+
+
+async def validate_source(event_type, resource_type, resource_id, object_type, object_id, db):
+ if event_type == 'system.announcement':
+ if any((resource_type, resource_id, object_type, object_id)):
+ raise ValueError('System announcements cannot attach resources')
+ return
+ models = source_models()
+ if (
+ not all((resource_type, resource_id, object_type, object_id))
+ or resource_type not in models
+ or object_type not in models
+ ):
+ raise ValueError('Incomplete notification source')
+ obj = await db.get(models[object_type], object_id)
+ if obj is None:
+ raise ValueError('Notification object does not exist')
+ valid = False
+ if event_type.startswith('comment.'):
+ valid = (
+ object_type == 'comment'
+ and not obj.deleted_at
+ and (obj.resource_type, obj.resource_id) == (resource_type, resource_id)
+ )
+ elif event_type.startswith('channel.'):
+ valid = object_type == 'message' and resource_type == 'channel' and obj.channel_id == resource_id
+ elif event_type == 'automation.run_failed':
+ valid = (
+ object_type == 'automation_run'
+ and resource_type == 'automation'
+ and obj.automation_id == resource_id
+ and obj.status == 'error'
+ )
+ elif event_type == 'calendar.alert':
+ valid = (
+ object_type == 'calendar_event'
+ and resource_type == 'calendar'
+ and obj.calendar_id == resource_id
+ and not obj.is_cancelled
+ )
+ if not valid:
+ raise ValueError('Notification object does not belong to resource')
+
+
+async def resource_queries(user, db):
+ """One set of indexed permission subqueries, shared by listing, counts and writes."""
+ from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
+ from open_webui.env import ENABLE_ADMIN_CHAT_ACCESS
+ from open_webui.models.access_grants import AccessGrants
+ from open_webui.models.channels import ChannelMember
+ from open_webui.models.config import Config
+ from open_webui.models.folders import Folder
+ from open_webui.models.groups import Groups
+ from open_webui.models.shared_chats import SharedChat
+ from open_webui.utils.access_control import has_permission
+
+ if user.role not in {'user', 'admin'}:
+ return {}
+ groups = [g.id for g in await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)]
+ config = await Config.get_many(
+ 'comments.enable',
+ 'notes.enable',
+ 'channels.enable',
+ 'calendar.enable',
+ 'automations.enable',
+ 'user.permissions',
+ )
+ admin = user.role == 'admin'
+
+ def grant(kind, column):
+ return AccessGrants.has_grant_expression(user.id, kind, column, user_group_ids=groups)
+
+ async def enabled(feature):
+ return config.get(f'{feature}.enable') and (
+ admin or await has_permission(user.id, f'features.{feature}', config.get('user.permissions'), db=db)
+ )
+
+ models = source_models()
+ queries = {}
+ for kind in ('model', 'knowledge', 'prompt', 'skill', 'tool', 'note'):
+ if not config.get('comments.enable') or (kind == 'note' and not await enabled('notes')):
+ continue
+ model = models[kind]
+ allowed = (
+ true()
+ if admin and (kind == 'note' or BYPASS_ADMIN_ACCESS_CONTROL)
+ else or_(model.user_id == user.id, grant(kind, model.id))
+ )
+ queries[kind] = select(model.id).where(allowed)
+ if config.get('comments.enable'):
+ chat = models['chat']
+ # UNION (not UNION ALL) terminates even if legacy folder data contains a cycle.
+ folders = (
+ select(Folder.id)
+ .where(or_(Folder.user_id == user.id, grant('folder', Folder.id)))
+ .cte('inbox_folders', recursive=True)
+ )
+ folders = folders.union(select(Folder.id).join(folders, Folder.parent_id == folders.c.id))
+ shared = select(SharedChat.chat_id).where(
+ SharedChat.chat['share_mode'].as_string() == 'continue', grant('shared_chat', SharedChat.chat_id)
+ )
+ queries['chat'] = select(chat.id).where(
+ or_(
+ chat.user_id == user.id,
+ true() if admin and ENABLE_ADMIN_CHAT_ACCESS else false(),
+ and_(true() if admin else false(), chat.meta['internal'].as_boolean().is_(True)),
+ chat.id.in_(shared),
+ chat.folder_id.in_(select(folders.c.id)),
+ )
+ )
+ if await enabled('channels'):
+ channel = models['channel']
+ member = (
+ select(ChannelMember.id)
+ .where(
+ ChannelMember.channel_id == channel.id,
+ ChannelMember.user_id == user.id,
+ ChannelMember.is_active.is_(True),
+ )
+ .exists()
+ )
+ queries['channel'] = select(channel.id).where(
+ channel.deleted_at.is_(None),
+ or_(
+ and_(channel.type.in_(['group', 'dm']), member),
+ and_(
+ or_(channel.type.is_(None), channel.type.not_in(['group', 'dm'])),
+ true() if admin else grant('channel', channel.id),
+ ),
+ ),
+ )
+ if await enabled('calendar'):
+ model = models['calendar']
+ queries['calendar'] = select(model.id).where(
+ true() if admin else or_(model.user_id == user.id, grant('calendar', model.id))
+ )
+ if await enabled('automations'):
+ model = models['automation']
+ queries['automation'] = select(model.id).where(model.user_id == user.id)
+ return queries
+
+
+async def eligible_recipients(recipients, resource_type, resource_id, actor_id, db):
+ from open_webui.models.users import User, UserModel
+
+ users = (await db.scalars(select(User).where(User.id.in_(recipients), User.role.in_(['user', 'admin'])))).all()
+ eligible = {}
+ for row in users:
+ kind = recipients[row.id]
+ if row.id == actor_id and kind.startswith(('comment.', 'channel.')):
+ continue
+ if resource_type is not None:
+ queries = await resource_queries(UserModel.model_validate(row), db=db)
+ query = queries.get(resource_type)
+ if query is None or not await db.scalar(
+ select(query.where(source_models()[resource_type].id == resource_id).exists())
+ ):
+ continue
+ eligible[row.id] = kind
+ return eligible
+
+
+async def visible_clause(user, db):
+ queries = await resource_queries(user, db=db)
+ models = source_models()
+ resources = or_(
+ *[
+ and_(Notification.resource_type == kind, Notification.resource_id.in_(query))
+ for kind, query in queries.items()
+ ]
+ )
+ objects = []
+ for kind, parent_column, events in (
+ ('comment', 'resource_id', ['comment.created', 'comment.replied', 'comment.mentioned']),
+ ('message', 'channel_id', ['channel.mentioned', 'channel.replied']),
+ ('automation_run', 'automation_id', ['automation.run_failed']),
+ ('calendar_event', 'calendar_id', ['calendar.alert']),
+ ):
+ model = models[kind]
+ conditions = [model.id == Notification.object_id, getattr(model, parent_column) == Notification.resource_id]
+ if kind == 'comment':
+ conditions += [model.resource_type == Notification.resource_type, model.deleted_at.is_(None)]
+ if kind == 'calendar_event':
+ conditions.append(model.is_cancelled.is_(False))
+ objects.append(
+ and_(
+ Notification.event_type.in_(events),
+ Notification.object_type == kind,
+ select(model.id).where(*conditions).exists(),
+ )
+ )
+ return (
+ and_(
+ Notification.user_id == user.id,
+ or_(
+ and_(
+ Notification.event_type == 'system.announcement',
+ Notification.resource_type.is_(None),
+ Notification.object_type.is_(None),
+ ),
+ and_(resources, or_(*objects)),
+ ),
+ )
+ if user.role in {'user', 'admin'}
+ else false()
+ )
+
+
+async def hydrate(rows, db):
+ """Fetch each actor/resource/object type once, never once per notification."""
+ from open_webui.models.users import User
+ from open_webui.utils.channels import replace_mentions
+
+ models = source_models()
+ ids = defaultdict(set)
+ for row in rows:
+ if row.resource_type:
+ ids[row.resource_type].add(row.resource_id)
+ if row.object_type:
+ ids[row.object_type].add(row.object_id)
+ objects = {}
+ for kind, values in ids.items():
+ model = models[kind]
+ fields = ['id', 'title', 'name']
+ if kind in {'comment', 'message'}:
+ fields += ['content', 'target_type', 'target_id', 'parent_id']
+ columns = [getattr(model, field) for field in fields if hasattr(model, field)]
+ objects[kind] = {
+ obj.id: obj
+ for obj in (await db.scalars(select(model).options(load_only(*columns)).where(model.id.in_(values)))).all()
+ }
+ actors = {
+ u.id: {'id': u.id, 'name': u.name}
+ for u in (
+ await db.scalars(
+ select(User)
+ .options(load_only(User.id, User.name))
+ .where(User.id.in_({r.actor_id for r in rows if r.actor_id}))
+ )
+ ).all()
+ }
+ result = []
+ for row in rows:
+ resource = objects.get(row.resource_type, {}).get(row.resource_id)
+ obj = objects.get(row.object_type, {}).get(row.object_id)
+ title = (
+ getattr(resource, 'title', None)
+ or getattr(resource, 'name', None)
+ or ''
+ )
+ preview = (
+ replace_mentions(getattr(obj, 'content', '') or '')[:300]
+ if row.object_type in {'comment', 'message'}
+ else ''
+ )
+ data = dict(row.data or {})
+ if row.object_type == 'comment':
+ data.update(target_type=obj.target_type, target_id=obj.target_id, parent_id=obj.parent_id)
+ elif row.object_type == 'message':
+ data['parent_id'] = obj.parent_id
+ elif row.object_type == 'calendar_event':
+ title = obj.title
+ result.append(
+ {
+ **{c.name: getattr(row, c.name) for c in Notification.__table__.columns},
+ 'actor': actors.get(row.actor_id),
+ 'title': title,
+ 'preview': preview,
+ 'data': data,
+ # Epoch nanoseconds must not become imprecise JavaScript cursor values.
+ 'created_at': str(row.created_at),
+ 'updated_at': str(row.updated_at),
+ 'seen_at': str(row.seen_at) if row.seen_at is not None else None,
+ 'read_at': str(row.read_at) if row.read_at is not None else None,
+ }
+ )
+ return result
+
+
+def mentioned_users(content):
+ from open_webui.utils.channels import extract_mentions
+
+ return {m['id'] for m in extract_mentions(content or '') if m['id_type'] == 'U'}
+
+
+async def comment_notifications(comment, owner_id, *, reply_to=None, previous_mentions=None, event_key=None, db):
+ mentions = mentioned_users(comment.content)
+ recipients = {}
+ if previous_mentions is None:
+ recipients = {
+ id: 'comment.replied' if comment.parent_id else 'comment.created'
+ for id in (owner_id, getattr(reply_to, 'user_id', None))
+ if id
+ }
+ else:
+ mentions -= set(previous_mentions)
+ recipients.update({id: 'comment.mentioned' for id in mentions})
+ return await insert_notifications(
+ recipients=recipients,
+ event_key=event_key
+ or f'comment:{comment.id}:{(comment.updated_at if previous_mentions is not None else "created")}',
+ actor_id=comment.user_id,
+ resource_type=comment.resource_type,
+ resource_id=comment.resource_id,
+ object_type='comment',
+ object_id=comment.id,
+ db=db,
+ )
+
+
+async def channel_notifications(message, *, event_key=None, actor_type='user', db):
+ from open_webui.models.channels import ChannelMember
+ from open_webui.models.messages import Message
+
+ mentions = mentioned_users(message.content)
+ target = (
+ await db.get(Message, message.reply_to_id or message.parent_id)
+ if message.reply_to_id or message.parent_id
+ else None
+ )
+ recipients = (
+ {target.user_id: 'channel.replied'}
+ if target and target.channel_id == message.channel_id and target.user_id
+ else {}
+ )
+ recipients.update({id: 'channel.mentioned' for id in mentions})
+ muted = (
+ await db.scalars(
+ select(ChannelMember.user_id).where(
+ ChannelMember.channel_id == message.channel_id,
+ ChannelMember.user_id.in_(recipients),
+ ChannelMember.is_channel_muted.is_(True),
+ )
+ )
+ ).all()
+ for id in muted:
+ if id not in mentions:
+ recipients.pop(id, None)
+ return await insert_notifications(
+ recipients=recipients,
+ event_key=event_key or f'message:{message.id}:created',
+ actor_id=message.user_id if actor_type == 'user' else None,
+ resource_type='channel',
+ resource_id=message.channel_id,
+ object_type='message',
+ object_id=message.id,
+ db=db,
+ )
+
+
+async def consume_event(event, db):
+ """Transactional inbox consumer; source producers publish facts, not recipients."""
+ from open_webui.events import EVENTS
+ from open_webui.models.config import Config
+
+ if not await Config.get('notifications.enable'):
+ return set()
+
+ subject_id = (event.subject or {}).get('id')
+ models = source_models()
+ if event.event in {EVENTS.COMMENT_CREATED.name, EVENTS.COMMENT_UPDATED.name}:
+ comment = await db.get(models['comment'], subject_id)
+ if not comment or comment.deleted_at:
+ raise ValueError('Comment event references an unavailable comment')
+ resource_model = models[comment.resource_type]
+ owner_id = await db.scalar(select(resource_model.user_id).where(resource_model.id == comment.resource_id))
+ reply_to = (
+ await db.get(models['comment'], comment.reply_to_id or comment.parent_id) if comment.parent_id else None
+ )
+ recipients = await comment_notifications(
+ comment,
+ owner_id,
+ reply_to=reply_to,
+ previous_mentions=event.data.get('previous_mentions', [])
+ if event.event == EVENTS.COMMENT_UPDATED.name
+ else None,
+ event_key=event.id,
+ db=db,
+ )
+ if event.event == EVENTS.COMMENT_UPDATED.name:
+ existing = await db.scalars(
+ select(Notification.user_id)
+ .where(Notification.object_type == 'comment', Notification.object_id == comment.id)
+ .distinct()
+ )
+ recipients.update(existing.all())
+ return recipients
+ elif event.event == EVENTS.MESSAGE_CREATED.name:
+ message = await db.get(models['message'], subject_id)
+ if message and message.channel_id:
+ return await channel_notifications(
+ message, event_key=event.id, actor_type=(event.actor or {}).get('type', 'system'), db=db
+ )
+ elif event.event == EVENTS.AUTOMATION_RUN_FAILED.name:
+ run = await db.get(models['automation_run'], event.data.get('run_id'))
+ automation = await db.get(models['automation'], subject_id)
+ if not run or not automation or run.automation_id != automation.id:
+ raise ValueError('Automation failure event requires its persisted run')
+ return await insert_notifications(
+ recipients={automation.user_id: event.event},
+ event_key=event.id,
+ resource_type='automation',
+ resource_id=automation.id,
+ object_type='automation_run',
+ object_id=run.id,
+ db=db,
+ )
+ elif event.event == EVENTS.CALENDAR_ALERT.name:
+ calendar_event = await db.get(models['calendar_event'], subject_id)
+ if not calendar_event or event.data.get('start_at') != calendar_event.start_at:
+ raise ValueError('Calendar alert must reference the current occurrence')
+ return await insert_notifications(
+ recipients={calendar_event.user_id: event.event},
+ event_key=event.id,
+ resource_type='calendar',
+ resource_id=calendar_event.calendar_id,
+ object_type='calendar_event',
+ object_id=calendar_event.id,
+ data={'start_at': calendar_event.start_at},
+ db=db,
+ )
+
+ return set()
diff --git a/backend/open_webui/utils/mcp/apps.py b/backend/open_webui/utils/mcp/apps.py
new file mode 100644
index 0000000000..6db2eaa701
--- /dev/null
+++ b/backend/open_webui/utils/mcp/apps.py
@@ -0,0 +1,79 @@
+"""MCP app result data and sandbox policy."""
+
+import hmac
+import re
+from dataclasses import dataclass
+
+from open_webui.env import WEBUI_SECRET_KEY
+from open_webui.utils.json_codec import JSONCodec
+
+APP_MIME_TYPE = 'text/html;profile=mcp-app'
+MAX_APP_BYTES = 5 * 1024 * 1024
+_DOMAIN = re.compile(r'(?:https?|wss?)://(?:\*\.)?(?:[a-zA-Z0-9.-]+|\[[a-fA-F0-9:]+\])(?::[0-9]{1,5})?')
+
+
+@dataclass
+class MCPAppResult:
+ embed: dict
+ context: list[dict]
+
+
+def app_binding(server_id: str, tool_name: str) -> str:
+ # Bind callbacks to a server/tool; the endpoint separately authenticates the viewer.
+ if not WEBUI_SECRET_KEY:
+ raise ValueError('A stable WEBUI_SECRET_KEY is required for MCP apps')
+ payload = JSONCodec.dumps([server_id, tool_name], ensure_ascii=True).encode()
+ return hmac.digest(WEBUI_SECRET_KEY.encode(), b'open-webui-mcp-app-v1\n' + payload, 'sha256').hex()
+
+
+def verify_app_binding(server_id: str, tool_name: str, binding: str) -> bool:
+ return bool(WEBUI_SECRET_KEY) and hmac.compare_digest(app_binding(server_id, tool_name), binding)
+
+
+def ui_metadata(value: dict) -> dict:
+ meta = value.get('_meta') or {}
+ ui = meta.get('ui') if isinstance(meta, dict) else None
+ return ui if isinstance(ui, dict) else {}
+
+
+def ui_resource_uri(tool: dict) -> str | None:
+ meta = tool.get('_meta') or {}
+ if not isinstance(meta, dict):
+ return None
+ uri = ui_metadata(tool).get('resourceUri') or meta.get('ui/resourceUri')
+ return uri if isinstance(uri, str) and uri.startswith('ui://') else None
+
+
+def app_csp(ui: dict) -> str:
+ csp = ui.get('csp') or {}
+ if not isinstance(csp, dict):
+ raise ValueError('Invalid app CSP')
+
+ def domains(key):
+ values = csp.get(key, [])
+ if not isinstance(values, list) or any(
+ not isinstance(value, str)
+ or not _DOMAIN.fullmatch(value)
+ or (key != 'connectDomains' and not value.startswith(('https://', 'http://')))
+ for value in values
+ ):
+ raise ValueError('Invalid app CSP domain')
+ return ' '.join(values)
+
+ resources = domains('resourceDomains')
+ deny = "'none'"
+ return '; '.join(
+ [
+ "default-src 'none'",
+ f"script-src 'unsafe-inline' blob: {resources}",
+ f"style-src 'unsafe-inline' {resources}",
+ f'img-src data: blob: {resources}',
+ f'media-src data: blob: {resources}',
+ f'font-src {resources or deny}',
+ f'connect-src {domains("connectDomains") or deny}',
+ f'frame-src {domains("frameDomains") or deny}',
+ f'base-uri {domains("baseUriDomains") or deny}',
+ "object-src 'none'",
+ "form-action 'none'",
+ ]
+ )
diff --git a/backend/open_webui/utils/mcp/client.py b/backend/open_webui/utils/mcp/client.py
index ee644ace2d..596f51b149 100644
--- a/backend/open_webui/utils/mcp/client.py
+++ b/backend/open_webui/utils/mcp/client.py
@@ -1,4 +1,5 @@
import asyncio
+import base64
import logging
import math
from typing import Optional
@@ -7,6 +8,7 @@ from urllib.parse import urlsplit
import httpx2
from jsonschema import Draft202012Validator, FormatChecker
from mcp import Client
+from mcp.client import advertise
from mcp.client.streamable_http import streamable_http_client
from mcp.types import ElicitRequestFormParams, ElicitResult
from open_webui.env import (
@@ -15,6 +17,14 @@ from open_webui.env import (
MCP_INITIALIZE_TIMEOUT,
)
from open_webui.utils.json_codec import JSONCodec
+from open_webui.utils.mcp.apps import (
+ APP_MIME_TYPE,
+ MAX_APP_BYTES,
+ MCPAppResult,
+ app_binding,
+ ui_metadata,
+ ui_resource_uri,
+)
from referencing import Registry
log = logging.getLogger(__name__)
@@ -70,6 +80,7 @@ class MCPClient:
self.event_caller = event_caller
self.server_name = server_name
self.instructions: Optional[str] = None
+ self.tool_definitions: dict[str, dict] = {}
async def elicit(self, context, params):
try:
@@ -127,6 +138,7 @@ class MCPClient:
# later request that does not set its own; the SDK caps the probe itself.
async with Client(
streamable_http_client(url, http_client=http_client),
+ extensions=[advertise('io.modelcontextprotocol/ui', {'mimeTypes': ['text/html;profile=mcp-app']})],
read_timeout_seconds=MCP_INITIALIZE_TIMEOUT,
elicitation_callback=self.elicit if self.event_caller else None,
) as client:
@@ -144,7 +156,7 @@ class MCPClient:
if not connected.done():
connected.set_exception(RuntimeError('MCP client failed to connect.'))
- async def list_tool_specs(self) -> Optional[dict]:
+ async def list_tool_specs(self) -> list[dict]:
if not self.client:
raise RuntimeError('MCP client is not connected.')
@@ -158,7 +170,12 @@ class MCPClient:
break
tool_specs = []
+ self.tool_definitions = {
+ tool.name: tool.model_dump(mode='json', by_alias=True, exclude_none=True) for tool in tools
+ }
for tool in tools:
+ if not tool_visible_to(self.tool_definitions[tool.name], 'model'):
+ continue
name = tool.name
description = tool.description
@@ -170,7 +187,7 @@ class MCPClient:
return tool_specs
- async def call_tool(self, function_name: str, function_args: dict) -> list[dict]:
+ async def call_tool_raw(self, function_name: str, function_args: dict) -> dict:
if not self.client:
raise RuntimeError('MCP client is not connected.')
@@ -183,11 +200,33 @@ class MCPClient:
if not result:
raise Exception('No result returned from MCP tool call.')
- result_dict = result.model_dump(mode='json', by_alias=True)
- result_content = result_dict['content']
+ return result.model_dump(mode='json', by_alias=True, exclude_none=True)
+
+ async def call_tool(self, function_name: str, function_args: dict) -> list[dict] | MCPAppResult:
+ raw = await self.call_tool_raw(function_name, function_args)
+ context = self.normalize_tool_result(raw)
+ tool = self.tool_definitions.get(function_name, {})
+ if not ui_resource_uri(tool):
+ return context
+ return MCPAppResult(
+ embed={
+ 'type': 'mcp_app',
+ 'server_id': self.server_name,
+ 'tool_name': function_name,
+ 'binding': app_binding(self.server_name, function_name),
+ 'arguments': function_args,
+ 'result': raw,
+ },
+ context=context,
+ )
+
+ @staticmethod
+ def normalize_tool_result(result_dict: dict) -> list[dict]:
+ # Keep the raw result intact for the app, including widget-only metadata.
+ result_content = list(result_dict['content'])
texts = [item['text'] for item in result_content if item['type'] == 'text']
- if result.is_error:
+ if result_dict.get('isError'):
raise Exception('\n'.join(texts) or 'MCP tool call returned an error.')
structured_content = result_dict.get('structuredContent')
@@ -227,6 +266,37 @@ class MCPClient:
result_content.append({'type': 'text', 'text': structured_json})
return result_content
+ async def read_ui_resource(self, uri: str) -> tuple[str, dict]:
+ result = await self.read_resource(uri)
+ content = next((item for item in result.get('contents', []) if item.get('uri') == uri), None)
+ if not content or content.get('mimeType') != APP_MIME_TYPE:
+ raise ValueError('Unsupported app resource')
+ document = content.get('text')
+ if document is None and isinstance(content.get('blob'), str):
+ document = base64.b64decode(content['blob'], validate=True).decode('utf-8')
+ if not isinstance(document, str) or not document or len(document.encode('utf-8')) > MAX_APP_BYTES:
+ raise ValueError('Invalid app HTML')
+
+ ui = ui_metadata(content)
+ if not ui:
+ # Some servers put CSP on resources/list rather than resources/read.
+ cursor = None
+ while True:
+ try:
+ listing = await self.client.list_resources(cursor=cursor)
+ except Exception:
+ # Listing is optional; missing policy still gets the restrictive default.
+ break
+ listed = listing.model_dump(mode='json', by_alias=True, exclude_none=True)
+ entry = next((item for item in listed.get('resources', []) if item.get('uri') == uri), None)
+ if entry:
+ ui = ui_metadata(entry)
+ break
+ cursor = listed.get('nextCursor')
+ if not cursor:
+ break
+ return document, ui
+
async def list_resources(self, cursor: Optional[str] = None) -> Optional[dict]:
if not self.client:
raise RuntimeError('MCP client is not connected.')
@@ -235,7 +305,7 @@ class MCPClient:
if not result:
raise Exception('No result returned from MCP list_resources call.')
- result_dict = result.model_dump(by_alias=True)
+ result_dict = result.model_dump(mode='json', by_alias=True, exclude_none=True)
resources = result_dict.get('resources', [])
return resources
@@ -247,7 +317,7 @@ class MCPClient:
result = await self.client.read_resource(uri)
if not result:
raise Exception('No result returned from MCP read_resource call.')
- result_dict = result.model_dump(by_alias=True)
+ result_dict = result.model_dump(mode='json', by_alias=True, exclude_none=True)
return result_dict
@@ -280,3 +350,10 @@ class MCPClient:
async def __aexit__(self, exc_type, exc_value, traceback):
await self.disconnect()
+
+
+def tool_visible_to(tool: dict, visibility: str) -> bool:
+ meta = tool.get('_meta') or {}
+ ui = (meta.get('ui') or {}) if isinstance(meta, dict) else {}
+ allowed = ui.get('visibility', ['model', 'app']) if isinstance(ui, dict) else []
+ return isinstance(allowed, list) and visibility in allowed
diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py
index b61635543b..1db1b76ede 100644
--- a/backend/open_webui/utils/middleware.py
+++ b/backend/open_webui/utils/middleware.py
@@ -103,6 +103,7 @@ from open_webui.utils.filter import (
process_filter_functions,
)
from open_webui.utils.json_codec import JSONCodec, dumps_bytes
+from open_webui.utils.mcp.apps import MCPAppResult
from open_webui.utils.memory import add_memory_context, review_memory_after_turn
from open_webui.utils.misc import (
add_or_update_system_message,
@@ -130,6 +131,7 @@ from open_webui.utils.oauth import get_system_oauth_token
from open_webui.utils.payload import apply_params_to_form_data, apply_system_prompt_to_body, resolve_system_prompt
from open_webui.utils.plugin import load_function_module_by_id
from open_webui.utils.response import (
+ convert_responses_stream_to_chat_completions,
get_response_delta_key,
handle_responses_streaming_event,
merge_usage,
@@ -150,7 +152,7 @@ from open_webui.utils.task import (
rag_template,
tools_function_calling_generation_template,
)
-from open_webui.utils.terminals import upload_files_to_terminal
+from open_webui.utils.terminals import filter_user_terminal_tools, upload_files_to_terminal
from open_webui.utils.tool_approval import complete_tool_call, pending_tool_calls
from open_webui.utils.tool_search import apply_tool_search, resolve_tool_call
from open_webui.utils.tools import (
@@ -273,10 +275,8 @@ async def publish_chat_failed_event(request: Request, user: UserModel, metadata:
)
-# We believe in one maker of all models, seen and unseen,
-# and in the reasoning which proceeds from the architect.
-# We look for the resurrection of dead processes and the
-# inference of the world to come.
+# Let every wandering thought find its closing tag,
+# and let the answer arrive before we forget the question.
DEFAULT_REASONING_TAGS = [
('', ' '),
('', ' '),
@@ -736,6 +736,9 @@ async def process_tool_result(
user=None,
):
tool_result_embeds = []
+ if isinstance(tool_result, MCPAppResult):
+ tool_result_embeds.append(tool_result.embed)
+ tool_result = tool_result.context
EXTERNAL_TOOL_TYPES = ('external', 'action', 'terminal')
# Support (HTMLResponse, result_context) tuples: the optional second
@@ -2431,12 +2434,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
form_data['messages'],
)
else:
- # Native FC: tool docstring can't be dynamic, so inject
- # filesystem context into the system message for pyodide
- # engine. Appending to the system prompt (instead of the
- # user message) keeps it in the stable cached prefix so
- # providers with prefix caching don't re-bill the full
- # conversation on every turn.
+ # Put dynamic Pyodide filesystem context in the system prompt to preserve prefix caching.
if engine != 'jupyter':
form_data['messages'] = add_or_update_system_message(
CODE_INTERPRETER_PYODIDE_PROMPT,
@@ -2627,10 +2625,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
prompt = get_last_user_message(form_data['messages'])
- # Guard against empty user message after skill mention stripping.
- # When a user selects a skill ($skill-name) without typing additional text,
- # the stripped result is an empty string which causes 400 errors on providers
- # that reject empty content blocks (e.g. AWS Bedrock ConverseStream).
+ # Supply fallback text for skill-only messages; some providers reject empty content.
if not prompt or not prompt.strip():
fallback = ', '.join([s.name for s in available_skills] + [s['name'] for s in terminal_skills])
# Attachment-only messages keep their empty text, same as on models without skills.
@@ -2877,61 +2872,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
):
tools_dict[name] = {**tools_dict[name], 'file_tool': tool_dict}
- # Connections can keep shell tools advertised across browser disconnects for prompt caching.
- shell_tools = {
- name: tool
- for name, tool in tools_dict.items()
- if name in {'read_user_terminal', 'send_user_terminal_input'}
- and (tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True)
- }
- selected = {
- name: tool
- for name, tool in shell_tools.items()
- if terminal_id
- and (
- tool.get('tool_id') == f'terminal:{terminal_id}'
- or (tool.get('direct') and tool.get('server', {}).get('url') == terminal_id)
- )
- }
- connected = (
- any(
- tool.get('user_shell_tools') == 'always'
- or (
- tool.get('direct')
- and (tool.get('server', {}).get('config') or {}).get('user_shell_tools') == 'always'
- )
- for tool in selected.values()
- )
- and not metadata.get('automation_id')
- and not metadata.get('internal')
- )
- if (
- selected
- and not connected
- and event_caller
- and metadata.get('session_id')
- and metadata.get('chat_id')
- and not metadata.get('automation_id')
- and not metadata.get('internal')
- ):
- try:
- state = await asyncio.wait_for(
- event_caller(
- {
- 'type': 'request:terminal:state',
- 'data': {'terminal_id': terminal_id, 'session_id': metadata['session_id']},
- }
- ),
- timeout=2,
- )
- connected = isinstance(state, dict) and state.get('connected') is True
- except Exception:
- # Old/disconnected browsers cannot confirm availability; other tools still work.
- pass
-
- for name in shell_tools:
- if not connected or name not in selected:
- tools_dict.pop(name)
+ await filter_user_terminal_tools(request, user, tools_dict, metadata, extra_params)
if tools_dict:
# Always store resolved tools in metadata so downstream consumers
@@ -3387,6 +3328,9 @@ async def pause_for_tool_approval(chat_id: str, message_id: str, output: list[di
},
touch=False,
)
+ event_emitter = await get_event_emitter(metadata, update_db=False)
+ if event_emitter:
+ await event_emitter({'type': 'chat:active', 'data': {'active': True}})
def get_response_data(response):
@@ -4898,11 +4842,7 @@ async def streaming_chat_response_handler(response, ctx):
}
)
- # Merge any metadata (usage, etc.)
- # Strip 'done' — response.completed emits
- # it but we may still need to execute tool
- # calls. The outer middleware manages the
- # actual completion signal.
+ # Merge metadata without 'done'; the outer middleware signals completion after tool calls.
if response_metadata:
if ENABLE_RESPONSES_API_STATEFUL:
response_id = response_metadata.pop('response_id', None)
@@ -5348,13 +5288,7 @@ async def streaming_chat_response_handler(response, ctx):
# closure-cell str += recopies per chunk; append + join once at read is O(n)
content_parts.append(value)
- # Check if we're inside a tag-based block
- # (reasoning, code_interpreter, or solution).
- # If so, append to the existing in-progress
- # item instead of creating a new message —
- # otherwise tag_output_handler re-detects the
- # start tag on every chunk and fragments the
- # output.
+ # Continue the open tag block so its start tag is not re-detected on each chunk.
last_item = output[-1] if output else None
last_item_type = last_item.get('type', '') if last_item else ''
inside_tag_block = (
@@ -6094,12 +6028,7 @@ async def streaming_chat_response_handler(response, ctx):
)
if isinstance(res, StreamingResponse):
- # Save accumulated output and start fresh.
- # Responses API output_index values are relative
- # to the current response — a clean output list
- # keeps indices aligned. The display prefix
- # ensures the UI shows tool history during
- # streaming.
+ # Reset response-relative output indices; keep prior output as the UI history prefix.
prior_output = list(full_output())
# Trim the trailing empty placeholder message
# so it doesn't persist as a ghost item once
@@ -6388,10 +6317,7 @@ async def streaming_chat_response_handler(response, ctx):
except asyncio.CancelledError:
log.warning('Task was cancelled!')
- # Close the response body iterator to trigger cleanup
- # in stream_wrapper's finally block and release the
- # upstream connection. Without this, the async
- # generator is orphaned and may spin in anyio internals.
+ # Close the iterator so stream_wrapper's finally block releases the upstream connection.
if hasattr(response, 'body_iterator') and hasattr(response.body_iterator, 'aclose'):
try:
await asyncio.shield(response.body_iterator.aclose())
@@ -6530,7 +6456,7 @@ async def streaming_chat_response_handler(response, ctx):
log_model_usage(request, user, form_data['model'], current_usage)
return StreamingResponse(
- stream_wrapper(response.body_iterator, events),
+ convert_responses_stream_to_chat_completions(stream_wrapper(response.body_iterator, events)),
headers=dict(response.headers),
background=response.background,
)
diff --git a/backend/open_webui/utils/misc.py b/backend/open_webui/utils/misc.py
index 65739bee56..043d987105 100644
--- a/backend/open_webui/utils/misc.py
+++ b/backend/open_webui/utils/misc.py
@@ -192,7 +192,7 @@ def get_message_list(messages_map, message_id):
:return: List of ordered messages starting from the root to the given message
"""
- # Handle case where messages is None
+ # No history, no archaeology. An empty map gets an empty list.
if not messages_map:
return [] # Return empty list instead of None to prevent iteration errors
@@ -202,7 +202,7 @@ def get_message_list(messages_map, message_id):
if not current_message:
return [] # Return empty list instead of None to prevent iteration errors
- # Reconstruct the chain by following the parentId links
+ # Follow parentId back through the conversation family tree.
message_list = []
visited_message_ids = set()
@@ -775,7 +775,7 @@ def strip_empty_content_blocks(messages: list[dict]) -> list[dict]:
return messages
-def openai_chat_message_template(model: str, message_id: str | None = None):
+def chat_completion_template(model: str, message_id: str | None = None):
return {
'id': message_id if message_id else f'{model}-{str(uuid.uuid4())}',
'created': int(time.time()),
@@ -784,7 +784,7 @@ def openai_chat_message_template(model: str, message_id: str | None = None):
}
-def openai_chat_chunk_message_template(
+def chat_completion_chunk_template(
model: str,
content: str | None = None,
reasoning_content: str | None = None,
@@ -792,7 +792,7 @@ def openai_chat_chunk_message_template(
usage: dict | None = None,
message_id: str | None = None,
) -> dict:
- template = openai_chat_message_template(model, message_id)
+ template = chat_completion_template(model, message_id)
template['object'] = 'chat.completion.chunk'
template['choices'][0]['index'] = 0
@@ -815,14 +815,14 @@ def openai_chat_chunk_message_template(
return template
-def openai_chat_completion_message_template(
+def chat_completion_message_template(
model: str,
message: str | None = None,
reasoning_content: str | None = None,
tool_calls: list[dict] | None = None,
usage: dict | None = None,
) -> dict:
- template = openai_chat_message_template(model)
+ template = chat_completion_template(model)
template['object'] = 'chat.completion'
if message is not None:
template['choices'][0]['message'] = {
@@ -840,25 +840,21 @@ def openai_chat_completion_message_template(
def get_gravatar_url(email):
- # Trim leading and trailing whitespace from
- # an email address and force all characters
- # to lower case
+ # Trim and lowercase the email; the avatar should survive a stuck Shift key.
address = str(email).strip().lower()
- # Create a SHA256 hash of the final string
+ # Hash the normalized email into its Gravatar calling card.
hash_object = hashlib.sha256(address.encode())
hash_hex = hash_object.hexdigest()
- # Grab the actual image URL
+ # Send the hash to Gravatar; the email stays out of the URL.
return f'https://www.gravatar.com/avatar/{hash_hex}?d=mp'
-# Give us each day the data we require, and forgive us our
-# technical debts as we forgive those who commit upstream.
-# Lead the bits not into corruption but deliver them from
-# entropy, for the checksum and the glory are forever.
+# Let what has been entrusted to us be kept whole,
+# and let nothing be lost in the passing from hand to hand.
def calculate_sha256(file_path, chunk_size):
- # Compute SHA-256 hash of a file efficiently in chunks
+ # Read in chunks so large files do not need to fit in memory.
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
@@ -869,9 +865,9 @@ def calculate_sha256(file_path, chunk_size):
def calculate_sha256_string(string):
# Create a new SHA-256 hash object
sha256_hash = hashlib.sha256()
- # Update the hash object with the bytes of the input string
+ # Feed the hash UTF-8 bytes; it does not take strings on faith.
sha256_hash.update(string.encode('utf-8'))
- # Get the hexadecimal representation of the hash
+ # Return the hex fingerprint, now suitable for polite string comparison.
hashed_string = sha256_hash.hexdigest()
return hashed_string
@@ -884,13 +880,13 @@ def validate_email_format(email: str) -> bool:
def sanitize_filename(file_name):
- # Convert to lowercase
+ # Lowercase the filename; shouting does not help us find it.
lower_case_file_name = file_name.lower()
- # Remove special characters using regular expression
+ # Strip punctuation; word characters and whitespace make the guest list.
sanitized_file_name = re.sub(r'[^\w\s]', '', lower_case_file_name)
- # Replace spaces with dashes
+ # Give each whitespace run one dash, regardless of its enthusiasm.
final_file_name = re.sub(r'\s+', '-', sanitized_file_name)
return final_file_name
@@ -1009,7 +1005,7 @@ def extract_folders_after_data_docs(path):
except ValueError:
return []
- # Exclude the filename and accumulate folder names
+ # Collect the folder ancestry; the filename is not invited.
tags = []
folders = parts[index_docs:-1]
@@ -1245,17 +1241,15 @@ def extract_urls(text: str) -> list[str]:
return url_pattern.findall(text)
-# We believe in one architect of all that is seen and served.
-# Should this stream falter, it shall be raised again on the
-# third retry. We look for the uptime of the world to come.
+# Let what falters have another chance,
+# and let the third try be kinder than the first two.
async def cleanup_response(
response: aiohttp.ClientResponse | None,
session: aiohttp.ClientSession | None,
):
if response:
if not response.closed:
- # aiohttp 3.9+ made ClientResponse.close() synchronous (returns None).
- # Older versions returned a coroutine. Handle both gracefully.
+ # Close directly, and await completion if the implementation returns an awaitable.
result = response.close()
if result is not None:
await result
diff --git a/backend/open_webui/utils/models.py b/backend/open_webui/utils/models.py
index d2cd3c3840..40e44f303b 100644
--- a/backend/open_webui/utils/models.py
+++ b/backend/open_webui/utils/models.py
@@ -353,13 +353,7 @@ async def get_all_models(request, refresh: bool = False, user: UserModel = None)
functions_by_id = {f.id: f for f in await Functions.get_functions_by_ids(list(all_function_ids))}
- # Pre-warm the function module cache once per unique function ID.
- # This ensures each function's DB freshness check runs exactly once,
- # not once per (model × function) pair.
- # Only attempt to load functions that actually exist in the local DB;
- # imported/custom model configs may reference tools or filters the user
- # hasn't installed, and trying to load those would cause persistent
- # "Failed to load function module" log spam on every model refresh.
+ # Warm each installed function once, avoiding per-model freshness checks and errors for missing functions.
for function_id, function in functions_by_id.items():
try:
await get_function_module_from_cache(request, function_id, function=function)
diff --git a/backend/open_webui/utils/oauth.py b/backend/open_webui/utils/oauth.py
index ca43d43da9..74abf72196 100644
--- a/backend/open_webui/utils/oauth.py
+++ b/backend/open_webui/utils/oauth.py
@@ -63,6 +63,7 @@ from open_webui.config import (
OAUTH_UPDATE_PICTURE_ON_LOGIN,
OAUTH_USERNAME_CLAIM,
WEBHOOK_URL,
+ load_oauth_providers,
)
from open_webui.constants import ERROR_MESSAGES
from open_webui.env import (
@@ -1382,12 +1383,21 @@ class OAuthManager:
self._clients = {}
self._refresh_locks: dict[str, asyncio.Lock] = {}
- for name, provider_config in OAUTH_PROVIDERS.items():
+ async def initialize(self):
+ # Provider connections are fixed for this worker's lifetime.
+ await load_oauth_providers()
+
+ for name, provider_config in list(OAUTH_PROVIDERS.items()):
if 'register' not in provider_config:
log.error(f'OAuth provider {name} missing register function')
continue
- client = provider_config['register'](self.oauth)
+ try:
+ client = provider_config['register'](self.oauth)
+ except (ValueError, TypeError) as e:
+ log.error('Error registering OAuth provider %s: %s', name, e)
+ OAUTH_PROVIDERS.pop(name)
+ continue
self._clients[name] = client
def get_client(self, provider_name):
diff --git a/backend/open_webui/utils/payload.py b/backend/open_webui/utils/payload.py
index 50db01021f..d033fbfaab 100644
--- a/backend/open_webui/utils/payload.py
+++ b/backend/open_webui/utils/payload.py
@@ -65,7 +65,7 @@ async def resolve_system_prompt(
# What goes out cannot be taken back. Let it be shaped
# well before it leaves this place.
-# inplace function: form_data is modified
+# Mutates form_data in place.
async def apply_system_prompt_to_body(
system: Optional[str],
form_data: dict,
@@ -242,7 +242,7 @@ def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
for key, value in name_differences.items():
if (param := params.get(key, None)) is not None:
- # Copy the parameter to new name then delete it, to prevent Ollama warning of invalid option provided
+ # Move this parameter to the payload root so it is not also sent as a generation option.
params[value] = params[key]
del params[key]
@@ -292,16 +292,16 @@ def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
form_data[key] = value(param)
del params[key]
- # Unlike OpenAI, Ollama does not support params directly in the body
+ # Map the remaining generation parameters into options; root-level parameters were handled above.
form_data['options'] = apply_model_params_to_body(params, (form_data.get('options', {}) or {}), mappings)
return form_data
-def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
+def convert_chat_completions_messages_to_ollama(messages: list[dict]) -> list[dict]:
ollama_messages = []
for message in messages:
- # Initialize the new message structure with the role
+ # New envelope, same speaker: carry the role across first.
new_message = {'role': message['role']}
# Preserve Ollama-native 'thinking' field (used by reasoning models,
@@ -315,12 +315,12 @@ def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
tool_calls = message.get('tool_calls', None)
tool_call_id = message.get('tool_call_id', None)
- # Check if the content is a string (just a simple message)
+ # Plain text without tool calls gets the express lane.
if isinstance(content, str) and not tool_calls:
# If the content is a string, it's pure text
new_message['content'] = content
- # If message is a tool call, add the tool call id to the message
+ # Preserve the tool response's link to the call it answers.
if tool_call_id:
new_message['tool_call_id'] = tool_call_id
@@ -339,7 +339,7 @@ def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
ollama_tool_calls.append(ollama_tool_call)
new_message['tool_calls'] = ollama_tool_calls
- # Put the content to empty string (Ollama requires an empty string for tool calls)
+ # Tool calls get an empty content string; Ollama insists on the blank name tag.
new_message['content'] = ''
else:
@@ -357,7 +357,7 @@ def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
elif item.get('type') == 'image_url':
img_url = item.get('image_url', {}).get('url', '')
if img_url:
- # If the image url starts with data:, it's a base64 image and should be trimmed
+ # Peel the data-URL label off the base64 image before packing it for Ollama.
if img_url.startswith('data:'):
img_url = img_url.split(',')[-1]
images.append(img_url)
@@ -370,13 +370,13 @@ def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
if images:
new_message['images'] = images
- # Append the new formatted message to the result
+ # Add the repacked message to the outgoing mail.
ollama_messages.append(new_message)
return ollama_messages
-def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
+def convert_chat_completions_payload_to_ollama(openai_payload: dict) -> dict:
"""
Converts a payload formatted for OpenAI's API to be compatible with Ollama's API endpoint for chat completions.
@@ -396,7 +396,7 @@ def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
# Mapping basic model and message details
ollama_payload['model'] = openai_payload.get('model')
- ollama_payload['messages'] = convert_messages_openai_to_ollama(openai_payload.get('messages'))
+ ollama_payload['messages'] = convert_chat_completions_messages_to_ollama(openai_payload.get('messages'))
ollama_payload['stream'] = openai_payload.get('stream', False)
if 'tools' in openai_payload:
ollama_payload['tools'] = openai_payload['tools']
@@ -425,7 +425,7 @@ def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
# Ollama's options field can contain parameters that should be at the root level.
for key, value in ollama_root_params.items():
if (param := ollama_options.get(key, None)) is not None:
- # Copy the parameter to new name then delete it, to prevent Ollama warning of invalid option provided
+ # Move this parameter to the payload root so it is not also sent as a generation option.
ollama_payload[key] = value(param)
del ollama_options[key]
@@ -434,8 +434,7 @@ def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
ollama_options['num_predict'] = ollama_options['max_tokens']
del ollama_options['max_tokens']
- # Ollama lacks a "system" prompt option. It has to be provided as a direct parameter, so we copy it down.
- # Comment: Not sure why this is needed, but we'll keep it for compatibility.
+ # Preserve legacy options.system input by moving it to the payload root.
if 'system' in ollama_options:
ollama_payload['system'] = ollama_options['system']
del ollama_options['system']
diff --git a/backend/open_webui/utils/plugin.py b/backend/open_webui/utils/plugin.py
index 281c22375f..7a7bea81a4 100644
--- a/backend/open_webui/utils/plugin.py
+++ b/backend/open_webui/utils/plugin.py
@@ -203,8 +203,8 @@ def replace_imports(content):
return content
-# May the intent of the one who wrote it survive every
-# import and transformation, as a deed survives the generations.
+# Let the care put into this work survive every
+# import and transformation, and serve those who carry it forward.
async def load_tool_module_by_id(tool_id, content=None):
"""Prepare a Tool instance, frontmatter, and Python module without changing the live cache."""
if not ENABLE_TOOLS:
@@ -229,8 +229,7 @@ async def load_tool_module_by_id(tool_id, content=None):
module = types.ModuleType(module_name)
sys.modules[module_name] = module
- # Create a temporary file and use it to define `__file__` so
- # that it works as expected from the module's perspective.
+ # Give the module a real __file__; even dynamically loaded code wants an address.
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.close()
try:
@@ -244,7 +243,7 @@ async def load_tool_module_by_id(tool_id, content=None):
frontmatter = extract_frontmatter(content)
log.info('Loaded module: %s', module.__name__)
- # Create and return the object if the class 'Tools' is found in the module
+ # Look for the Tools class; the toolkit still needs someone to answer the door.
if hasattr(module, 'Tools'):
return module.Tools(), frontmatter, module
else:
@@ -278,8 +277,7 @@ async def load_function_module_by_id(function_id: str, content: str | None = Non
module = types.ModuleType(module_name)
sys.modules[module_name] = module
- # Create a temporary file and use it to define `__file__` so
- # that it works as expected from the module's perspective.
+ # Give the module a real __file__; even dynamically loaded code wants an address.
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.close()
try:
@@ -475,7 +473,7 @@ async def install_tool_and_function_dependencies():
return
function_list = await Functions.get_functions(active_only=True) if ENABLE_FUNCTIONS else []
- tool_list = await Tools.get_tools() if ENABLE_TOOLS else []
+ tool_list = await Tools.get_tools(active_only=True) if ENABLE_TOOLS else []
all_dependencies = ''
try:
diff --git a/backend/open_webui/utils/redis.py b/backend/open_webui/utils/redis.py
index a4f91fc619..e2ad336c3e 100644
--- a/backend/open_webui/utils/redis.py
+++ b/backend/open_webui/utils/redis.py
@@ -113,9 +113,7 @@ def get_redis_client(async_mode: bool = False) -> Any | None:
return None
-# ---------------------------------------------------------------------------
# Sentinel proxy with automatic failover retry
-# ---------------------------------------------------------------------------
class SentinelRedisProxy:
@@ -178,7 +176,7 @@ class SentinelRedisProxy:
exc,
)
- # -- async wrappers -----------------------------------------------------
+ # Async wrappers
def _wrap_async(self, name: str, attr: Any) -> Any:
if inspect.isasyncgenfunction(attr):
@@ -233,7 +231,7 @@ class SentinelRedisProxy:
return wrapper
- # -- sync wrapper -------------------------------------------------------
+ # Sync wrapper
def _wrap_sync(self, name: str) -> Any:
proxy = self
@@ -256,9 +254,7 @@ class SentinelRedisProxy:
return wrapper
-# ---------------------------------------------------------------------------
# Connection factory
-# ---------------------------------------------------------------------------
def _socket_options() -> dict[str, Any]:
diff --git a/backend/open_webui/utils/response.py b/backend/open_webui/utils/response.py
index 3eda90f686..7f9080936e 100644
--- a/backend/open_webui/utils/response.py
+++ b/backend/open_webui/utils/response.py
@@ -1,10 +1,11 @@
+import time
from numbers import Number
from uuid import uuid4
from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.misc import (
- openai_chat_chunk_message_template,
- openai_chat_completion_message_template,
+ chat_completion_chunk_template,
+ chat_completion_message_template,
)
@@ -157,7 +158,7 @@ def update_usage_snapshot(current: dict | None, incoming: dict | None) -> dict:
return result
-def convert_ollama_tool_call_to_openai(tool_calls: list) -> list:
+def convert_ollama_tool_call_to_chat_completions(tool_calls: list) -> list:
openai_tool_calls = []
for tool_call in tool_calls:
function = tool_call.get('function', {})
@@ -174,7 +175,7 @@ def convert_ollama_tool_call_to_openai(tool_calls: list) -> list:
return openai_tool_calls
-def convert_ollama_usage_to_openai(data: dict) -> dict:
+def convert_ollama_usage_to_chat_completions(data: dict) -> dict:
input_tokens = usage_counter(data.get('prompt_eval_count')) or 0
output_tokens = usage_counter(data.get('eval_count')) or 0
total_tokens = input_tokens + output_tokens
@@ -231,7 +232,23 @@ def convert_ollama_usage_to_openai(data: dict) -> dict:
return result
-def convert_response_ollama_to_openai(ollama_response: dict) -> dict:
+def convert_responses_usage_to_chat_completions(usage: dict | None) -> dict:
+ result = normalize_usage(usage)
+ for source, target in (('input_tokens', 'prompt_tokens'), ('output_tokens', 'completion_tokens')):
+ for suffix in ('', '_details'):
+ if source + suffix in result:
+ result[target + suffix] = result[source + suffix]
+ return result
+
+
+def get_responses_finish_reason(response: dict, has_tool_calls: bool = False) -> str:
+ if response.get('status') == 'incomplete':
+ reason = (response.get('incomplete_details') or {}).get('reason')
+ return 'content_filter' if reason == 'content_filter' else 'length'
+ return 'tool_calls' if has_tool_calls else 'stop'
+
+
+def convert_ollama_response_to_chat_completions(ollama_response: dict) -> dict:
model = ollama_response.get('model', 'ollama')
message_content = ollama_response.get('message', {}).get('content', '')
reasoning_content = ollama_response.get('message', {}).get('thinking', None)
@@ -239,21 +256,19 @@ def convert_response_ollama_to_openai(ollama_response: dict) -> dict:
openai_tool_calls = None
if tool_calls:
- openai_tool_calls = convert_ollama_tool_call_to_openai(tool_calls)
+ openai_tool_calls = convert_ollama_tool_call_to_chat_completions(tool_calls)
data = ollama_response
- usage = convert_ollama_usage_to_openai(data)
+ usage = convert_ollama_usage_to_chat_completions(data)
- response = openai_chat_completion_message_template(
- model, message_content, reasoning_content, openai_tool_calls, usage
- )
+ response = chat_completion_message_template(model, message_content, reasoning_content, openai_tool_calls, usage)
if not openai_tool_calls and ollama_response.get('done_reason'):
response['choices'][0]['finish_reason'] = ollama_response['done_reason']
return response
-async def convert_streaming_response_ollama_to_openai(ollama_streaming_response):
+async def convert_ollama_stream_to_chat_completions(ollama_streaming_response):
has_tool_calls = False
# All chunks in a single completion must share the same id (OpenAI spec).
completion_id = f'chatcmpl-{str(uuid4())}'
@@ -269,7 +284,7 @@ async def convert_streaming_response_ollama_to_openai(ollama_streaming_response)
openai_tool_calls = None
if tool_calls:
- openai_tool_calls = convert_ollama_tool_call_to_openai(tool_calls)
+ openai_tool_calls = convert_ollama_tool_call_to_chat_completions(tool_calls)
has_tool_calls = True
done = data.get('done', False)
@@ -277,9 +292,9 @@ async def convert_streaming_response_ollama_to_openai(ollama_streaming_response)
usage = None
if done:
- usage = convert_ollama_usage_to_openai(data)
+ usage = convert_ollama_usage_to_chat_completions(data)
- data = openai_chat_chunk_message_template(
+ data = chat_completion_chunk_template(
model, message_content, reasoning_content, openai_tool_calls, usage, message_id=completion_id
)
@@ -299,6 +314,97 @@ async def convert_streaming_response_ollama_to_openai(ollama_streaming_response)
yield 'data: [DONE]\n\n'
+async def convert_responses_stream_to_chat_completions(body_iterator):
+ """Convert line-framed Responses SSE after internal filters; pass other streams through."""
+ completion_id = f'chatcmpl-{uuid4()}'
+ created = int(time.time())
+ model = ''
+ tool_call_indexes = {}
+ first = True
+ is_responses_stream = False
+ done = False
+ async for line in body_iterator:
+ text = line.decode('utf-8', 'replace') if isinstance(line, bytes) else line
+ if text.startswith('event:') and (
+ is_responses_stream or text.removeprefix('event:').strip().startswith('response.')
+ ):
+ continue
+ if done and text.strip() == 'data: [DONE]':
+ continue
+ try:
+ data = JSONCodec.loads(text.removeprefix('data:').strip()) if text.startswith('data:') else None
+ except JSONCodec.JSONDecodeError:
+ data = None
+ event_type = data.get('type', '') if isinstance(data, dict) else ''
+ if not event_type.startswith('response.') and not (event_type == 'error' and is_responses_stream):
+ yield line
+ continue
+
+ is_responses_stream = True
+ if event_type in ('response.failed', 'error'):
+ error = data.get('response', {}).get('error') if event_type == 'response.failed' else data
+ yield f'data: {JSONCodec.dumps({"error": error})}\n\n'
+ done = True
+ continue
+ if event_type == 'response.created':
+ response = data.get('response', {})
+ completion_id = response.get('id') or completion_id
+ created = response.get('created_at') or created
+ model = response.get('model', '')
+ continue
+
+ delta = {}
+ output_index = data.get('output_index')
+ is_final = event_type in ('response.completed', 'response.incomplete')
+ if event_type == 'response.output_text.delta':
+ delta['content'] = data['delta']
+ elif event_type in ('response.reasoning_text.delta', 'response.reasoning_summary_text.delta'):
+ delta['reasoning_content'] = data['delta']
+ elif event_type == 'response.refusal.delta':
+ delta['refusal'] = data['delta']
+ elif event_type == 'response.output_item.added' and data.get('item', {}).get('type') == 'function_call':
+ item = data['item']
+ tool_call_indexes[output_index] = len(tool_call_indexes)
+ delta['tool_calls'] = [
+ {
+ 'index': tool_call_indexes[output_index],
+ 'id': item.get('call_id', ''),
+ 'type': 'function',
+ 'function': {'name': item.get('name', ''), 'arguments': item.get('arguments', '')},
+ }
+ ]
+ elif event_type == 'response.function_call_arguments.delta':
+ delta['tool_calls'] = [
+ {
+ 'index': tool_call_indexes[output_index],
+ 'function': {'arguments': data['delta']},
+ }
+ ]
+ elif not is_final:
+ continue
+
+ chunk = chat_completion_chunk_template(model, message_id=completion_id)
+ chunk['created'] = created
+ chunk['choices'][0].update(delta=delta, finish_reason=None)
+ if first:
+ delta['role'] = 'assistant'
+ first = False
+ if is_final:
+ response = data.get('response', {})
+ chunk['choices'][0]['finish_reason'] = get_responses_finish_reason(
+ {**response, 'status': event_type.removeprefix('response.')}, bool(tool_call_indexes)
+ )
+ usage = convert_responses_usage_to_chat_completions(response.get('usage'))
+ if usage:
+ chunk['usage'] = usage
+ done = True
+ yield f'data: {JSONCodec.dumps(chunk)}\n\n'
+
+ # Let the wrapped stream finish outlet filters and usage logging before clients disconnect.
+ if done:
+ yield 'data: [DONE]\n\n'
+
+
def convert_embedding_response_ollama_to_openai(response) -> dict:
"""
Convert the response from Ollama embeddings endpoint to the OpenAI-compatible format.
diff --git a/backend/open_webui/utils/session_records.py b/backend/open_webui/utils/session_records.py
index 80af860208..b35574d6ed 100644
--- a/backend/open_webui/utils/session_records.py
+++ b/backend/open_webui/utils/session_records.py
@@ -6,6 +6,21 @@ import re
import time
+def has_pending_tool_approval(output):
+ if not isinstance(output, list):
+ return False
+ items = [item for item in output if isinstance(item, dict)]
+ result_ids = {item.get('call_id') for item in items if item.get('type') == 'function_call_output'}
+ return any(
+ item.get('type') == 'function_call'
+ and (item.get('call_id') or item.get('id'))
+ and (item.get('call_id') or item.get('id')) not in result_ids
+ and item.get('status') in {'pending', 'queued', 'requires_approval'}
+ and item.get('approved') is not True
+ for item in items
+ )
+
+
def recorded_timestamp(value):
try:
value = float(value)
diff --git a/backend/open_webui/utils/subagents.py b/backend/open_webui/utils/subagents.py
index 3389f4729a..9d237d2e0f 100644
--- a/backend/open_webui/utils/subagents.py
+++ b/backend/open_webui/utils/subagents.py
@@ -18,6 +18,7 @@ from open_webui.tasks import create_task, has_active_tasks
from open_webui.utils.auth import VERIFIED_USER_ROLES, create_token
from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.misc import add_or_update_system_message, get_message_list, is_raster_image_content_type
+from open_webui.utils.models import get_filtered_models
from open_webui.utils.tool_search import strip_deferred_tools_manifest
from starlette.datastructures import Headers
@@ -45,6 +46,22 @@ _foreground_semaphore: asyncio.Semaphore | None = None
_parent_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
+async def get_subagent_models(request: Request, user: UserModel, model: dict) -> list[dict]:
+ subagents = (model.get('info', {}).get('meta') or {}).get('subagents') or {}
+ model_ids = subagents.get('model_ids') or []
+ if not model_ids:
+ return []
+ candidates = [model for model_id, model in request.app.state.MODELS.items() if model_id in model_ids]
+ return [
+ {
+ 'id': model['id'],
+ 'name': model.get('name', model['id']),
+ 'description': (model.get('info', {}).get('meta') or {}).get('description') or '',
+ }
+ for model in await get_filtered_models(candidates, user)
+ ]
+
+
async def _build_request(source: Request, user_id: str, *, internal: bool) -> Request:
scope = {
'type': 'http',
@@ -282,6 +299,7 @@ async def delegate(
background: bool,
*,
file_ids: list[str] | None = None,
+ model_id: str | None = None,
request: Request,
user_data: dict,
metadata: dict,
@@ -304,13 +322,21 @@ async def delegate(
'subagents.max_output',
'subagents.system_prompt',
)
- max_concurrent = int(config.get('subagents.max_concurrent') or 20)
- max_async = int(config.get('subagents.max_async') or 20)
- max_iterations = int(config.get('subagents.max_iterations') or 30)
- max_output = int(config.get('subagents.max_output') or 30_000)
- if max_concurrent != -1:
+ max_concurrent = config.get('subagents.max_concurrent')
+ max_concurrent = int(max_concurrent) if max_concurrent else None
+ max_async = config.get('subagents.max_async')
+ max_async = int(max_async) if max_async else None
+ max_iterations = config.get('subagents.max_iterations')
+ max_iterations = int(max_iterations) if max_iterations else None
+ max_output = config.get('subagents.max_output')
+ max_output = int(max_output) if max_output else None
+ if max_concurrent == -1:
+ max_concurrent = None
+ elif max_concurrent is not None:
max_concurrent = max(1, max_concurrent)
- if max_async != -1:
+ if max_async == -1:
+ max_async = None
+ elif max_async is not None:
max_async = max(1, max_async)
if background and not config.get('subagents.background_enabled'):
@@ -343,6 +369,16 @@ async def delegate(
return 'Error: model context is required.'
if run.get('direct'):
return 'Error: sub-agents are unavailable for direct connections.'
+ if model_id:
+ available_models = await get_subagent_models(request, UserModel(**user_data), metadata.get('model') or {})
+ available_ids = [model['id'] for model in available_models]
+ if model_id not in available_ids:
+ return (
+ f'Error: model {model_id} is not available for sub-agents. '
+ f'Available models: {", ".join(available_ids) or "none"}. '
+ 'Omit model_id to use the current model.'
+ )
+ model_id = model_id or run['model_id']
delegated_files = []
if file_ids:
requested_file_ids = {str(file_id) for file_id in file_ids if file_id}
@@ -378,13 +414,13 @@ async def delegate(
foreground_semaphore = None
if background:
async with _background_lock:
- if max_async != -1 and len(_background_active) >= max_async:
+ if max_async is not None and len(_background_active) >= max_async:
return (
f'Error: Async subagent capacity reached ({max_async} running). '
'Wait for one to finish or increase subagents.max_async.'
)
_background_active.add(delegation_id)
- elif max_concurrent != -1:
+ elif max_concurrent is not None:
if _foreground_semaphore is None:
_foreground_semaphore = asyncio.Semaphore(max_concurrent)
foreground_semaphore = _foreground_semaphore
@@ -405,7 +441,7 @@ async def delegate(
'role': 'user',
'content': prompt,
'timestamp': int(time.time()),
- 'models': [run['model_id']],
+ 'models': [model_id],
**({'files': prompt_files} if prompt_files else {}),
}
chat = await Chats.insert_new_chat(
@@ -415,7 +451,7 @@ async def delegate(
chat={
'id': chat_id,
'title': f'Sub-agent: {task[:60]}',
- 'models': [run['model_id']],
+ 'models': [model_id],
'history': {
'currentId': assistant_message_id,
'messages': {
@@ -427,7 +463,7 @@ async def delegate(
'role': 'assistant',
'content': '',
'done': False,
- 'model': run['model_id'],
+ 'model': model_id,
'timestamp': int(time.time()),
},
},
@@ -472,7 +508,7 @@ async def delegate(
str(config.get('subagents.system_prompt') or '').strip() or DEFAULT_SUBAGENT_SYSTEM_PROMPT
)
form_data = {
- 'model': run['model_id'],
+ 'model': model_id,
'params': chat_context.get('params') or {},
'messages': add_or_update_system_message(
subagent_system_prompt,
@@ -523,7 +559,7 @@ async def delegate(
for part in item.get('content') or []
if part.get('type') == 'output_text'
)
- if len(summary) > max_output:
+ if max_output is not None and len(summary) > max_output:
summary = f'{summary[:max_output]}\n\n[output truncated]'
error = message.get('error')
if isinstance(error, dict):
diff --git a/backend/open_webui/utils/task.py b/backend/open_webui/utils/task.py
index 66f596c5c1..3c6bfae69f 100644
--- a/backend/open_webui/utils/task.py
+++ b/backend/open_webui/utils/task.py
@@ -15,9 +15,8 @@ log = logging.getLogger(__name__)
# Let the right tool be given for the work at hand,
# not the one that flatters, but the one that serves.
def get_task_model_id(default_model_id: str, task_model: str, task_model_external: str, models) -> str:
- # Set the task model
task_model_id = default_model_id
- # Check if the user has a custom task model and use that model
+ # Use an available task model override for the local or external connection.
if models.get(task_model_id, {}).get('connection_type') == 'local':
if task_model and task_model in models:
task_model_id = task_model
@@ -73,6 +72,7 @@ async def prompt_template(template: str, user: Optional[Any] = None) -> str:
USER_VARIABLES = {
'name': str(user.get('name')),
'email': str(user.get('email')),
+ 'role': str(user.get('role')),
'location': str(user_info.get('location')),
'bio': str(user.get('bio')),
'gender': str(user.get('gender')),
@@ -84,7 +84,7 @@ async def prompt_template(template: str, user: Optional[Any] = None) -> str:
# Get the current date
current_date = datetime.now()
- # Format the date to YYYY-MM-DD
+ # YYYY-MM-DD: one date format, fewer international incidents.
formatted_date = current_date.strftime('%Y-%m-%d')
formatted_time = current_date.strftime('%I:%M:%S %p')
formatted_weekday = current_date.strftime('%A')
@@ -96,6 +96,7 @@ async def prompt_template(template: str, user: Optional[Any] = None) -> str:
template = template.replace('{{USER_NAME}}', USER_VARIABLES.get('name', 'Unknown'))
template = template.replace('{{USER_EMAIL}}', USER_VARIABLES.get('email', 'Unknown'))
+ template = template.replace('{{USER_ROLE}}', USER_VARIABLES.get('role', 'Unknown'))
template = template.replace('{{USER_BIO}}', USER_VARIABLES.get('bio', 'Unknown'))
template = template.replace('{{USER_GENDER}}', USER_VARIABLES.get('gender', 'Unknown'))
template = template.replace('{{USER_BIRTH_DATE}}', USER_VARIABLES.get('birth_date', 'Unknown'))
diff --git a/backend/open_webui/utils/telemetry/instrumentors.py b/backend/open_webui/utils/telemetry/instrumentors.py
index 3f72339a9d..41b460d725 100644
--- a/backend/open_webui/utils/telemetry/instrumentors.py
+++ b/backend/open_webui/utils/telemetry/instrumentors.py
@@ -63,10 +63,7 @@ def redis_request_hook(span: Span, instance: Union[Redis | RedisCluster], args,
Redis Request Hook
"""
- # In cluster mode, the instance can be of two types:
- # - redis.asyncio.cluster.RedisCluster
- # - redis.cluster.RedisCluster
- # Instead of checking the type, we check if the instance has a nodes_manager attribute.
+ # Detect both sync and async RedisCluster clients by their nodes_manager attribute.
try:
db = ''
if hasattr(instance, 'nodes_manager'):
diff --git a/backend/open_webui/utils/telemetry/metrics.py b/backend/open_webui/utils/telemetry/metrics.py
index e730748489..cd810f9e89 100644
--- a/backend/open_webui/utils/telemetry/metrics.py
+++ b/backend/open_webui/utils/telemetry/metrics.py
@@ -55,17 +55,7 @@ from sqlalchemy.orm import Session
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Sync DB helpers for OTel gauge callbacks
-#
-# The OTel Python SDK calls observable-instrument callbacks *synchronously*
-# from a background collection thread — async callbacks are NOT supported
-# (the SDK does not ``await`` the return value).
-#
-# Rather than bridging into the async event loop, we run plain synchronous
-# SQL queries using the sync engine that is already available at setup time.
-# This avoids any cross-thread / cross-loop concerns entirely.
-# ---------------------------------------------------------------------------
+# OTel gauge callbacks run synchronously on a collection thread, so use the sync DB engine.
def _count_total_users(db_engine: Engine) -> Optional[int]:
@@ -168,10 +158,7 @@ def setup_metrics(app: FastAPI, resource: Resource, db_engine: Engine) -> None:
unit='ms',
)
- # -- Observable gauge callbacks ----------------------------------------
- # These are called synchronously by the OTel SDK from a background
- # collection thread. They use the sync DB engine directly — no async
- # bridging required.
+ # Gauge callbacks use the sync DB engine on OTel's collection thread.
def observe_total_users(
options: metrics.CallbackOptions,
diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py
index fad06c388a..ec9fff01de 100644
--- a/backend/open_webui/utils/terminals.py
+++ b/backend/open_webui/utils/terminals.py
@@ -232,6 +232,58 @@ async def get_terminal_json(
return None
+async def filter_user_terminal_tools(request, user, tools: dict, metadata: dict, extra_params: dict):
+ """Let Open Terminal, which owns the shells, confirm availability for this user and chat."""
+ terminal_id = metadata.get('terminal_id')
+ shell_tools = {
+ name: tool
+ for name, tool in tools.items()
+ if name in {'read_user_terminal', 'send_user_terminal_input'}
+ and (tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True)
+ }
+ selected = {
+ name: tool
+ for name, tool in shell_tools.items()
+ if terminal_id
+ and (
+ tool.get('tool_id') == f'terminal:{terminal_id}'
+ or (tool.get('direct') and tool.get('server', {}).get('url') == terminal_id)
+ )
+ }
+ available = False
+ if selected and not metadata.get('automation_id') and not metadata.get('internal'):
+ available = any(
+ tool.get('user_shell_tools') == 'always'
+ or (tool.get('direct') and (tool.get('server', {}).get('config') or {}).get('user_shell_tools') == 'always')
+ for tool in selected.values()
+ )
+ if not available and metadata.get('chat_id'):
+ try:
+ # This endpoint checks ownership, a live process, and a connected shell.
+ # Its output is discarded; the model must explicitly read the terminal.
+ async with asyncio.timeout(5):
+ state = await get_terminal_json(request, user, metadata, '/api/terminals/user/output', extra_params)
+ available = isinstance(state, dict) and isinstance(state.get('output'), str)
+ except Exception as error:
+ log.debug('User terminal availability check failed (%s)', type(error).__name__)
+
+ for name in shell_tools:
+ if not available or name not in selected:
+ tools.pop(name)
+
+ if available and 'read_user_terminal' in selected:
+ tool = selected['read_user_terminal']
+ tools['read_user_terminal'] = {
+ **tool,
+ 'spec': {
+ **tool['spec'],
+ 'description': tool['spec'].get('description', '')
+ + "\nReads the user's Open WebUI Terminal tab, separate from the Desktop. "
+ 'Use this tool when the user refers to an open terminal tab.',
+ },
+ }
+
+
async def upload_files_to_terminal(request, user, files: list[dict], metadata: dict, extra_params: dict):
"""Copy Open WebUI files to the selected terminal, adding terminal_path or terminal_error to each entry."""
if not metadata.get('terminal_id') or not files:
diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py
index f04b7e07c7..97ef2c8030 100644
--- a/backend/open_webui/utils/tools.py
+++ b/backend/open_webui/utils/tools.py
@@ -7,7 +7,7 @@ import inspect
import logging
import os
import re
-from functools import cache, partial, update_wrapper
+from functools import cache, partial, update_wrapper, wraps
from typing import (
Any,
Awaitable,
@@ -52,6 +52,7 @@ from open_webui.tools.builtin import (
create_automation,
create_calendar_event,
create_tasks,
+ create_tool,
delegate_task,
delete_automation,
delete_calendar_event,
@@ -256,6 +257,11 @@ async def connect_mcp_server(
tool_specs = await client.list_tool_specs()
if function_name_filter_list:
tool_specs = [spec for spec in tool_specs if is_string_allowed(spec['name'], function_name_filter_list)]
+ client.tool_definitions = {
+ name: tool
+ for name, tool in client.tool_definitions.items()
+ if is_string_allowed(name, function_name_filter_list)
+ }
return client, tool_specs
except BaseException:
await client.disconnect()
@@ -334,14 +340,28 @@ async def get_updated_tool_function(function: Callable, extra_params: dict):
__extra_params__ = getattr(function, '__extra_params__', None)
if __function__ is not None and __extra_params__ is not None:
- return await get_async_tool_function_and_apply_extra_params(
+ updated = await get_async_tool_function_and_apply_extra_params(
__function__,
{**__extra_params__, **extra_params},
)
+ tool_id = getattr(function, '__tool_id__', None)
+ return guard_tool_enabled(tool_id, updated) if tool_id is not None else updated
return function
+def guard_tool_enabled(tool_id: str, function: Callable) -> Callable:
+ @wraps(function)
+ async def guarded(*args, **kwargs):
+ # Resolve again at invocation: a chat may have prepared this callable before a toggle.
+ if not await Tools.is_tool_active(tool_id):
+ raise HTTPException(status_code=403, detail='Tool is disabled or no longer available')
+ return await function(*args, **kwargs)
+
+ guarded.__tool_id__ = tool_id
+ return guarded
+
+
async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extra_params: dict) -> dict[str, dict]:
"""Load tools for the given tool_ids, checking access control."""
if not tool_ids:
@@ -368,6 +388,8 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr
for tool_id in tool_ids:
tool = tool_models.get(tool_id)
if tool:
+ if not tool.is_active:
+ continue
# Check access control for local tools
if (
not (user.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL)
@@ -426,6 +448,7 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr
'__user__': __user__,
},
)
+ callable = guard_tool_enabled(tool_id, callable)
# TODO: Support Pydantic models as parameters
if callable.__doc__ and callable.__doc__.strip() != '':
@@ -865,6 +888,12 @@ async def get_builtin_tools(
):
builtin_functions.append(create_skill)
+ if ENABLE_TOOLS and is_builtin_tool_enabled('tools'):
+ if user.get('role') == 'admin' or await has_permission(
+ user.get('id', ''), 'workspace.tools', await Config.get('user.permissions')
+ ):
+ builtin_functions.append(create_tool)
+
# Task management - break down complex work into trackable steps
# Task state is stored on the chats row; local/channel IDs do not have one.
if is_builtin_tool_enabled('tasks') and is_saved_chat_id(metadata.get('chat_id')):
@@ -916,11 +945,22 @@ async def get_builtin_tools(
)
spec = get_builtin_tool_spec(func)
- if func.__name__ == 'delegate_task' and not config.get('subagents.background_enabled'):
+ if func.__name__ == 'delegate_task':
+ from open_webui.utils.subagents import get_subagent_models
+
parameters = spec.get('parameters', {})
- parameters.get('properties', {}).pop('background', None)
- if isinstance(parameters.get('required'), list):
- parameters['required'] = [name for name in parameters['required'] if name != 'background']
+ properties = parameters.get('properties', {})
+ if not config.get('subagents.background_enabled'):
+ properties.pop('background', None)
+ if isinstance(parameters.get('required'), list):
+ parameters['required'] = [name for name in parameters['required'] if name != 'background']
+
+ subagent_models = await get_subagent_models(request, UserModel(**user), model) if user else []
+ if subagent_models:
+ properties['model_id']['enum'] = [model['id'] for model in subagent_models]
+ spec['description'] += f' Available models: {JSONCodec.dumps(subagent_models)}'
+ else:
+ properties.pop('model_id', None)
tools_dict[func.__name__] = {
'tool_id': f'builtin:{func.__name__}',
diff --git a/backend/open_webui/utils/validate.py b/backend/open_webui/utils/validate.py
index 41c7f67b59..f1fcab896c 100644
--- a/backend/open_webui/utils/validate.py
+++ b/backend/open_webui/utils/validate.py
@@ -61,12 +61,12 @@ def validate_image_url(url: str, *, file_only: bool = False) -> str:
return url
raise ValueError('Invalid background image URL: must reference an internal file.')
- # --- Relative paths (exact match + anchored regex only) -----------
+ # Relative paths (exact match + anchored regex only)
if not url or url in _SAFE_STATIC_PATHS or _USER_PROFILE_IMAGE_RE.match(url):
return url
- # --- Absolute URLs -------------------------------------------------
+ # Absolute URLs
# urlparse normalises the scheme to lowercase, giving us
# case-insensitive scheme matching for free.
diff --git a/backend/open_webui/utils/webhook.py b/backend/open_webui/utils/webhook.py
index a2f099af74..fbd7838935 100644
--- a/backend/open_webui/utils/webhook.py
+++ b/backend/open_webui/utils/webhook.py
@@ -40,14 +40,14 @@ async def post_webhook(name: str, url: str, message: str, event_data: dict, desc
try:
payload = {}
- # Slack and Google Chat Webhooks
+ # Slack and Google Chat both order their message under "text".
if 'https://hooks.slack.com' in url or 'https://chat.googleapis.com' in url:
payload['text'] = _event_text(message, description, event_data)
- # Discord Webhooks
+ # Discord calls it "content" and keeps the speech under 2,000 characters.
elif 'https://discord.com/api/webhooks' in url:
content = _event_text(message, description, event_data)
payload['content'] = content if len(content) < 2000 else f'{content[: 2000 - 20]}... (truncated)'
- # Microsoft Teams Webhooks
+ # Teams prefers a MessageCard; apparently the message needs stationery.
elif 'webhook.office.com' in url:
action = event_data.get('action', 'undefined')
user_data = event_data.get('user') or event_data.get('actor') or {}
@@ -79,7 +79,7 @@ async def post_webhook(name: str, url: str, message: str, event_data: dict, desc
}
],
}
- # Default Payload
+ # Everyone else gets the event data without gift wrapping.
else:
payload = event_data
diff --git a/backend/start.sh b/backend/start.sh
index adf521811b..813058ef12 100755
--- a/backend/start.sh
+++ b/backend/start.sh
@@ -1,11 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
-# ---------------------------------------------------------------------------
# Container entry point for Open WebUI.
# Handles secret key generation, optional Ollama/CUDA/Playwright setup,
# HuggingFace Space deployment, and launches the uvicorn server.
-# ---------------------------------------------------------------------------
# Default optional env vars that we test below with bash's `,,` lowercase
# expansion. The two can't be combined inline (`${VAR:-default,,}` makes
@@ -16,7 +14,7 @@ set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
cd "$SCRIPT_DIR" || exit 1
-# ── Playwright browser installation (if configured) ──────────────────────────
+# Playwright browser installation (if configured)
if [[ "${USE_SLIM_DOCKER,,}" != "true" && "${WEB_LOADER_ENGINE,,}" == "playwright" ]]; then
if [[ -z "${PLAYWRIGHT_WS_URL:-}" ]]; then
@@ -26,7 +24,7 @@ if [[ "${USE_SLIM_DOCKER,,}" != "true" && "${WEB_LOADER_ENGINE,,}" == "playwrigh
fi
fi
-# ── Secret key setup ─────────────────────────────────────────────────────────
+# Secret key setup
KEY_FILE="${WEBUI_SECRET_KEY_FILE:-.webui_secret_key}"
WEBUI_SECRET_KEY_LENGTH="${WEBUI_SECRET_KEY_LENGTH:-24}"
@@ -49,21 +47,21 @@ if [[ -z "${WEBUI_SECRET_KEY:-}" && -z "${WEBUI_JWT_SECRET_KEY:-}" ]]; then
WEBUI_SECRET_KEY=$(cat "$KEY_FILE")
fi
-# ── Ollama (bundled Docker image) ────────────────────────────────────────────
+# Ollama (bundled docker image)
if [[ "${USE_OLLAMA_DOCKER,,}" == "true" ]]; then
echo "Starting bundled ollama serve..."
ollama serve &
fi
-# ── CUDA library paths ──────────────────────────────────────────────────────
+# Cuda library paths
if [[ "${USE_CUDA_DOCKER,,}" == "true" ]]; then
echo "CUDA enabled — extending LD_LIBRARY_PATH for torch/cudnn libraries."
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}:/usr/local/lib/python3.12/site-packages/torch/lib:/usr/local/lib/python3.12/site-packages/nvidia/cudnn/lib"
fi
-# ── HuggingFace Space deployment ─────────────────────────────────────────────
+# HuggingFace space deployment
if [[ -n "${SPACE_ID:-}" ]]; then
echo "Configuring for HuggingFace Space deployment..."
@@ -93,7 +91,7 @@ if [[ -n "${SPACE_ID:-}" ]]; then
export WEBUI_URL="${SPACE_HOST}"
fi
-# ── Launch uvicorn ───────────────────────────────────────────────────────────
+# Launch uvicorn
PYTHON_CMD=$(command -v python3 || command -v python)
UVICORN_WORKERS="${UVICORN_WORKERS:-1}"
diff --git a/docker-cleanup.sh b/docker-cleanup.sh
index 5092b31c10..be994d1ec5 100755
--- a/docker-cleanup.sh
+++ b/docker-cleanup.sh
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# ---------------------------------------------------------------------------
# Tear down the compose project and remove all volumes (including data).
-# ---------------------------------------------------------------------------
echo "WARNING: This will stop all containers and delete all volumes (including persistent data)."
read -rp "Are you sure you want to continue? [y/N]: " answer
diff --git a/docker-compose-launcher.sh b/docker-compose-launcher.sh
index 026de313fa..3b5c730144 100755
--- a/docker-compose-launcher.sh
+++ b/docker-compose-launcher.sh
@@ -1,10 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
-# ---------------------------------------------------------------------------
# Interactive docker compose launcher for Open WebUI.
# Supports GPU auto-detection, configurable ports, data mounts, and Playwright.
-# ---------------------------------------------------------------------------
readonly BOLD='\033[1m'
readonly GREEN='\033[1;32m'
@@ -13,7 +11,7 @@ readonly RED='\033[0;31m'
readonly RESET='\033[0m'
readonly CHECK_MARK='\xE2\x9C\x93'
-# ── GPU detection ─────────────────────────────────────────────────────────────
+# Gpu detection
detect_gpu_driver() {
if command -v nvidia-smi &>/dev/null && nvidia-smi &>/dev/null; then
@@ -32,7 +30,7 @@ detect_gpu_driver() {
fi
}
-# ── Argument helpers ──────────────────────────────────────────────────────────
+# Argument helpers
extract_bracket_value() {
local input="$1" fallback="${2:-}"
@@ -66,7 +64,7 @@ Examples:
EOF
}
-# ── Defaults ──────────────────────────────────────────────────────────────────
+# Defaults
enable_gpu=false
enable_api=false
@@ -79,7 +77,7 @@ api_port=11435
webui_port=3000
data_dir=""
-# ── Parse arguments ───────────────────────────────────────────────────────────
+# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
@@ -97,7 +95,7 @@ while [[ $# -gt 0 ]]; do
shift
done
-# ── Drop mode ─────────────────────────────────────────────────────────────────
+# Drop mode
if [[ "$drop_project" == true ]]; then
docker compose down --remove-orphans
@@ -105,7 +103,7 @@ if [[ "$drop_project" == true ]]; then
exit 0
fi
-# ── Build compose command ─────────────────────────────────────────────────────
+# Build compose command
compose_files=("-f" "docker-compose.yaml")
@@ -141,7 +139,7 @@ if [[ "$build_image" == true ]]; then
up_args+=("--build")
fi
-# ── Confirmation ──────────────────────────────────────────────────────────────
+# Confirmation
echo
echo -e "${WHITE}${BOLD}Current Setup:${RESET}"
@@ -161,7 +159,7 @@ if [[ "$headless" != true ]]; then
fi
fi
-# ── Launch ────────────────────────────────────────────────────────────────────
+# Launch
if docker compose "${compose_files[@]}" "${up_args[@]}"; then
echo
diff --git a/docker-ollama.sh b/docker-ollama.sh
index bf9cf6046d..bce39367dd 100755
--- a/docker-ollama.sh
+++ b/docker-ollama.sh
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# ---------------------------------------------------------------------------
# Pull and run the official Ollama container with optional GPU support.
-# ---------------------------------------------------------------------------
readonly CONTAINER="ollama"
readonly HOST_PORT="${OLLAMA_PORT:-11434}"
diff --git a/docker-run.sh b/docker-run.sh
index 527c8d93e2..a794997ba2 100755
--- a/docker-run.sh
+++ b/docker-run.sh
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# ---------------------------------------------------------------------------
# Build and run the Open WebUI Docker container locally.
-# ---------------------------------------------------------------------------
readonly IMAGE="open-webui"
readonly CONTAINER="open-webui"
diff --git a/docker-update-models.sh b/docker-update-models.sh
index 5f21715618..ed4e8c869d 100755
--- a/docker-update-models.sh
+++ b/docker-update-models.sh
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# ---------------------------------------------------------------------------
# Pull the latest version of every model installed in the Ollama container.
-# ---------------------------------------------------------------------------
readonly CONTAINER="${OLLAMA_CONTAINER:-ollama}"
diff --git a/package-lock.json b/package-lock.json
index 3f3d943f76..45cb579aa3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "open-webui",
- "version": "0.12.5",
+ "version": "0.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "open-webui",
- "version": "0.12.5",
+ "version": "0.13.0",
"dependencies": {
"@azure/msal-browser": "^4.5.0",
"@codemirror/lang-javascript": "^6.2.2",
@@ -18,6 +18,8 @@
"@huggingface/transformers": "^3.0.0",
"@joplin/turndown-plugin-gfm": "^1.0.62",
"@mediapipe/tasks-vision": "^0.10.17",
+ "@modelcontextprotocol/ext-apps": "2.0.4",
+ "@novnc/novnc": "^1.7.0",
"@pixiv/three-vrm": "3.5.5",
"@pixiv/three-vrm-animation": "3.5.5",
"@pyscript/core": "^0.4.32",
@@ -127,6 +129,7 @@
"@types/three": "0.186.0",
"@typescript-eslint/eslint-plugin": "^8.31.1",
"@typescript-eslint/parser": "^8.31.1",
+ "@xmldom/xmldom": "^0.8.15",
"cypress": "^13.15.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
@@ -2293,6 +2296,82 @@
"integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
"license": "BSD-2-Clause"
},
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",
+ "integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",
+ "license": "Apache-2.0",
+ "peer": true,
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.4.0",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.8",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/client/node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
+ "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
+ "license": "Apache-2.0",
+ "peer": true,
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/ext-apps": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.4.tgz",
+ "integrity": "sha512-B+PcbuGiaf0e5I3uy4iO5tS3Abo+5w8JvZFzHMzQdq9yVwP836zJkw2+KCGOQ0r4TM1fuQi4JdnbuWjkS4aBvg==",
+ "license": "MIT",
+ "workspaces": [
+ "examples/*"
+ ],
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "@modelcontextprotocol/client": "^2.0.0",
+ "@modelcontextprotocol/core": "^2.0.0",
+ "@modelcontextprotocol/server": "^2.0.0",
+ "react": "^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
+ "zod": "^4.2.0"
+ },
+ "peerDependenciesMeta": {
+ "@modelcontextprotocol/server": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@napi-rs/canvas": {
"version": "0.1.97",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.97.tgz",
@@ -2578,6 +2657,12 @@
"node": ">= 8"
}
},
+ "node_modules/@novnc/novnc": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/@novnc/novnc/-/novnc-1.7.0.tgz",
+ "integrity": "sha512-ucEJOx4T2avIRCleodk7YobZj5O2Ga2AeLfQ69A/yjG9HHba2+PDgwSkN3FttrmG+70ZGx21sElNFouK13RzyA==",
+ "license": "MPL-2.0"
+ },
"node_modules/@parcel/watcher": {
"version": "2.5.6",
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz",
@@ -7000,7 +7085,6 @@
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
@@ -8531,6 +8615,19 @@
"bare-events": "^2.7.0"
}
},
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/eventsource-parser": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-1.1.2.tgz",
@@ -8540,6 +8637,16 @@
"node": ">=14.18"
}
},
+ "node_modules/eventsource/node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/execa": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/execa/-/execa-4.1.0.tgz",
@@ -10078,7 +10185,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
- "dev": true,
"license": "ISC"
},
"node_modules/isomorphic.js": {
@@ -10124,6 +10230,16 @@
"jiti": "lib/jiti-cli.mjs"
}
},
+ "node_modules/jose": {
+ "version": "6.2.14",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.14.tgz",
+ "integrity": "sha512-3JasLuki1NRLQvY4wCoC37KZk4qxoBx2k2aFqLxT84IezqW0bkJKnNtxnZj/Fu1xsQivoc/lytxaRHJoGLjJ1A==",
+ "license": "MIT",
+ "peer": true,
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/js-sha256": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/js-sha256/-/js-sha256-0.10.1.tgz",
@@ -11844,7 +11960,6 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -11957,6 +12072,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
"node_modules/pkg-types": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
@@ -13579,7 +13704,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
@@ -13592,7 +13716,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -16310,7 +16433,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
- "dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
@@ -16679,6 +16801,16 @@
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
"license": "MIT"
},
+ "node_modules/zod": {
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
+ "license": "MIT",
+ "peer": true,
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
"node_modules/zwitch": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
diff --git a/package.json b/package.json
index f0e3149352..cd6a19c3dc 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-webui",
- "version": "0.12.5",
+ "version": "0.13.0",
"private": true,
"scripts": {
"crypto:verify": "node scripts/encryption/artifact.mjs",
@@ -38,6 +38,7 @@
"@types/three": "0.186.0",
"@typescript-eslint/eslint-plugin": "^8.31.1",
"@typescript-eslint/parser": "^8.31.1",
+ "@xmldom/xmldom": "^0.8.15",
"cypress": "^13.15.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
@@ -69,6 +70,8 @@
"@huggingface/transformers": "^3.0.0",
"@joplin/turndown-plugin-gfm": "^1.0.62",
"@mediapipe/tasks-vision": "^0.10.17",
+ "@modelcontextprotocol/ext-apps": "2.0.4",
+ "@novnc/novnc": "^1.7.0",
"@pixiv/three-vrm": "3.5.5",
"@pixiv/three-vrm-animation": "3.5.5",
"@pyscript/core": "^0.4.32",
diff --git a/scripts/generate-sbom.sh b/scripts/generate-sbom.sh
index cffcb08d69..32e8303a22 100755
--- a/scripts/generate-sbom.sh
+++ b/scripts/generate-sbom.sh
@@ -60,14 +60,14 @@ generate() {
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' RETURN
- # --- Python: resolve all transitive deps without installing ---
+ # Python: resolve all transitive deps without installing
dim "Resolving Python transitive deps (uv pip compile)..."
uv pip compile "$ROOT_DIR/backend/requirements.txt" \
--python-version 3.12 \
--quiet \
> "$WORK_DIR/requirements-resolved.txt" 2>/dev/null
- # --- JavaScript: package-lock.json is already fully resolved ---
+ # JavaScript: package-lock.JSON is already fully resolved
if [[ -f "$ROOT_DIR/package-lock.json" ]]; then
cp "$ROOT_DIR/package-lock.json" "$WORK_DIR/package-lock.json"
# Syft needs package.json alongside the lockfile
@@ -76,7 +76,7 @@ generate() {
warn "package-lock.json not found — JS deps will be skipped"
fi
- # --- Scan only the resolved files ---
+ # Scan only the resolved files
dim "Scanning resolved manifests with Syft..."
syft scan "dir:$WORK_DIR" \
--output "cyclonedx-json=$OUTPUT" \
@@ -175,7 +175,7 @@ else:
"
}
-# --- Main ---
+# Main
cd "$ROOT_DIR"
TARGET="${1:-generate}"
diff --git a/src/app.css b/src/app.css
index b7ba3c0155..b5bc3f341c 100644
--- a/src/app.css
+++ b/src/app.css
@@ -103,8 +103,7 @@ textarea {
color-scheme: dark;
}
-textarea::-webkit-resizer,
-textarea::-webkit-scrollbar-corner {
+textarea::-webkit-resizer {
background: transparent;
}
@@ -161,7 +160,11 @@ li p {
display: inline;
}
-::-webkit-scrollbar-thumb {
+:where(html:not(.native-scrollbars)) textarea::-webkit-scrollbar-corner {
+ background: transparent;
+}
+
+:where(html:not(.native-scrollbars), html:not(.native-scrollbars) *)::-webkit-scrollbar-thumb {
--tw-border-opacity: 1;
background-color: rgba(215, 215, 215, 0.6);
border-color: rgba(255, 255, 255, var(--tw-border-opacity));
@@ -170,17 +173,17 @@ li p {
}
/* Dark theme scrollbar styles */
-.dark ::-webkit-scrollbar-thumb {
+:where(html:not(.native-scrollbars)).dark ::-webkit-scrollbar-thumb {
background-color: rgba(67, 67, 67, 0.6); /* Darker color for dark theme */
border-color: rgba(0, 0, 0, var(--tw-border-opacity));
}
-::-webkit-scrollbar {
+:where(html:not(.native-scrollbars), html:not(.native-scrollbars) *)::-webkit-scrollbar {
height: 0.45rem;
width: 0.45rem;
}
-::-webkit-scrollbar-track {
+:where(html:not(.native-scrollbars), html:not(.native-scrollbars) *)::-webkit-scrollbar-track {
background-color: transparent;
border-radius: 9999px;
}
@@ -298,16 +301,17 @@ body > iframe[id^='imermaid-'] {
overflow: hidden !important;
}
-.scrollbar-hidden:active::-webkit-scrollbar-thumb,
-.scrollbar-hidden:focus::-webkit-scrollbar-thumb,
-.scrollbar-hidden:hover::-webkit-scrollbar-thumb {
+:where(html:not(.native-scrollbars)) .scrollbar-hidden:active::-webkit-scrollbar-thumb,
+:where(html:not(.native-scrollbars)) .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
+:where(html:not(.native-scrollbars)) .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
visibility: visible;
}
-.scrollbar-hidden::-webkit-scrollbar-thumb {
+
+:where(html:not(.native-scrollbars)) .scrollbar-hidden::-webkit-scrollbar-thumb {
visibility: hidden;
}
-.scrollbar-hidden::-webkit-scrollbar-corner {
+:where(html:not(.native-scrollbars)) .scrollbar-hidden::-webkit-scrollbar-corner {
display: none;
}
@@ -339,21 +343,22 @@ input[type='number'] {
@apply overflow-y-hidden overflow-x-auto max-w-full;
}
-.katex-display::-webkit-scrollbar {
+:where(html:not(.native-scrollbars)) .katex-display::-webkit-scrollbar {
height: 0.4rem;
width: 0.4rem;
}
-.katex-display:active::-webkit-scrollbar-thumb,
-.katex-display:focus::-webkit-scrollbar-thumb,
-.katex-display:hover::-webkit-scrollbar-thumb {
+:where(html:not(.native-scrollbars)) .katex-display:active::-webkit-scrollbar-thumb,
+:where(html:not(.native-scrollbars)) .katex-display:focus::-webkit-scrollbar-thumb,
+:where(html:not(.native-scrollbars)) .katex-display:hover::-webkit-scrollbar-thumb {
visibility: visible;
}
-.katex-display::-webkit-scrollbar-thumb {
+
+:where(html:not(.native-scrollbars)) .katex-display::-webkit-scrollbar-thumb {
visibility: hidden;
}
-.katex-display::-webkit-scrollbar-corner {
+:where(html:not(.native-scrollbars)) .katex-display::-webkit-scrollbar-corner {
display: none;
}
@@ -362,17 +367,17 @@ input[type='number'] {
width: 100%;
}
-.cm-scroller:active::-webkit-scrollbar-thumb,
-.cm-scroller:focus::-webkit-scrollbar-thumb,
-.cm-scroller:hover::-webkit-scrollbar-thumb {
+:where(html:not(.native-scrollbars)) .cm-scroller:active::-webkit-scrollbar-thumb,
+:where(html:not(.native-scrollbars)) .cm-scroller:focus::-webkit-scrollbar-thumb,
+:where(html:not(.native-scrollbars)) .cm-scroller:hover::-webkit-scrollbar-thumb {
visibility: visible;
}
-.cm-scroller::-webkit-scrollbar-thumb {
+:where(html:not(.native-scrollbars)) .cm-scroller::-webkit-scrollbar-thumb {
visibility: hidden;
}
-.cm-scroller::-webkit-scrollbar-corner {
+:where(html:not(.native-scrollbars)) .cm-scroller::-webkit-scrollbar-corner {
display: none;
}
@@ -660,7 +665,8 @@ html.high-contrast.dark .ProseMirror p.is-editor-empty:first-child::before {
@apply dark:bg-gray-800 bg-gray-50;
}
-.tiptap pre {
+.tiptap pre,
+.tiptap pre.hljs {
border-radius: 0.5rem;
font-family: 'JetBrainsMono', monospace;
margin: 1.5rem 0;
@@ -675,56 +681,12 @@ html.high-contrast.dark .ProseMirror p.is-editor-empty:first-child::before {
@apply font-mono rounded-md text-gray-800 bg-gray-50 dark:text-gray-200 dark:bg-gray-800 mx-0.5;
}
-/* Code styling */
-.hljs-comment,
-.hljs-quote {
- color: #616161;
+:where(html:not(.dark)) .tiptap {
+ @import 'highlight.js/styles/github.css';
}
-.hljs-variable,
-.hljs-template-variable,
-.hljs-attribute,
-.hljs-tag,
-.hljs-regexp,
-.hljs-link,
-.hljs-name,
-.hljs-selector-id,
-.hljs-selector-class {
- color: #f98181;
-}
-
-.hljs-number,
-.hljs-meta,
-.hljs-built_in,
-.hljs-builtin-name,
-.hljs-literal,
-.hljs-type,
-.hljs-params {
- color: #fbbc88;
-}
-
-.hljs-string,
-.hljs-symbol,
-.hljs-bullet {
- color: #b9f18d;
-}
-
-.hljs-title,
-.hljs-section {
- color: #faf594;
-}
-
-.hljs-keyword,
-.hljs-selector-tag {
- color: #70cff8;
-}
-
-.hljs-emphasis {
- font-style: italic;
-}
-
-.hljs-strong {
- font-weight: 700;
+:where(html.dark) .tiptap {
+ @import 'highlight.js/styles/github-dark.css';
}
/* Table styling for tiptap editors */
@@ -757,6 +719,10 @@ html.high-contrast.dark .ProseMirror p.is-editor-empty:first-child::before {
@apply bg-transparent p-0 m-0 text-inherit;
}
+.tippy-box[data-theme~='transparent'] > .tippy-content {
+ padding: 0;
+}
+
/* This gives the remote user caret. The colors are automatically overwritten*/
.ProseMirror-yjs-cursor {
position: relative;
diff --git a/src/app.d.ts b/src/app.d.ts
index 80c9762761..d23728b866 100644
--- a/src/app.d.ts
+++ b/src/app.d.ts
@@ -11,6 +11,10 @@ declare global {
const APP_BUILD_CHANNEL: 'main' | 'dev' | 'unknown';
namespace App {
+ interface PageState {
+ inbox?: boolean;
+ inboxUserId?: string;
+ }
// interface Error {}
// interface Locals {}
// interface PageData {}
diff --git a/src/app.html b/src/app.html
index 28a7135a1b..6797f46469 100644
--- a/src/app.html
+++ b/src/app.html
@@ -47,6 +47,13 @@
-
+
diff --git a/src/lib/components/AddTerminalServerModal.svelte b/src/lib/components/AddTerminalServerModal.svelte
index e8e8aa5b4d..f72796a14c 100644
--- a/src/lib/components/AddTerminalServerModal.svelte
+++ b/src/lib/components/AddTerminalServerModal.svelte
@@ -432,7 +432,11 @@
};
-
+
@@ -648,9 +652,9 @@
-
+
{$i18n.t('Policy ID')}
-
+
-
+
{$i18n.t('Image')}
({$i18n.t('optional')})
-
+
-
+
{$i18n.t('Memory')}
-
+
-
+
{$i18n.t('Storage')}
-
+
-
+
{$i18n.t('Ephemeral')}
{$i18n.t('Persistent')}
@@ -752,6 +760,7 @@
class={`w-full flex-1 text-sm font-mono ${inputClass}`}
type="text"
bind:value={policyStorageSize}
+ aria-label={$i18n.t('Size')}
placeholder="5Gi"
autocomplete="off"
/>
@@ -762,10 +771,10 @@
-
+
{$i18n.t('Idle Timeout')}
({$i18n.t('min')})
-
+