From cbeb8e3630cafd7ef6fd28b552bf7114729f21b9 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 29 Oct 2026 18:42:37 +0900 Subject: [PATCH 001/160] refac --- src/lib/components/notes/NotePanel.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/components/notes/NotePanel.svelte b/src/lib/components/notes/NotePanel.svelte index c232b5b175..4cd9b31336 100644 --- a/src/lib/components/notes/NotePanel.svelte +++ b/src/lib/components/notes/NotePanel.svelte @@ -21,7 +21,7 @@ }; onMount(() => { - mediaQuery = window.matchMedia('(min-width: 1000px)'); + mediaQuery = window.matchMedia('(min-width: 768px)'); mediaQuery.addEventListener('change', handleMediaQuery); handleMediaQuery(mediaQuery); }); From eed4c1f693b7744f1875c9517127492b80cebd09 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 29 Oct 2026 18:44:38 +0900 Subject: [PATCH 002/160] refac --- static/pyodide/pyodide-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/static/pyodide/pyodide-lock.json b/static/pyodide/pyodide-lock.json index 2bf53cbc19..947abfffea 100644 --- a/static/pyodide/pyodide-lock.json +++ b/static/pyodide/pyodide-lock.json @@ -5238,10 +5238,10 @@ }, "xlsxwriter": { "name": "xlsxwriter", - "version": "3.3.0", - "file_name": "xlsxwriter-3.3.0-py3-none-any.whl", + "version": "3.3.1", + "file_name": "xlsxwriter-3.3.1-py3-none-any.whl", "install_dir": "site", - "sha256": "5f04772d43281da5109af66f39b65153359a203e896847c416476e709b024469", + "sha256": "8e2c89e59d733fe59e112317218c64fbbc276d90a8c144ebd6f7fa15e7ab184a", "package_type": "package", "imports": [ "xlsxwriter" From c5981aaea6b25bb9b9601e62b9ff75da33aaaf4e Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 29 Oct 2026 18:46:35 +0900 Subject: [PATCH 003/160] refac --- src/lib/components/channel/Channel.svelte | 3 ++- src/lib/components/chat/ChatControls.svelte | 2 +- src/lib/components/chat/Controls/Controls.svelte | 5 ++++- src/lib/components/chat/MessageInput/TerminalMenu.svelte | 5 +++-- src/lib/components/layout/SearchModal.svelte | 6 ++++-- src/lib/components/layout/Sidebar.svelte | 1 - 6 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/lib/components/channel/Channel.svelte b/src/lib/components/channel/Channel.svelte index a5bccf4aaa..8237d5858d 100644 --- a/src/lib/components/channel/Channel.svelte +++ b/src/lib/components/channel/Channel.svelte @@ -373,7 +373,7 @@ $socket?.on('events:channel', channelEventHandler); - mediaQuery = window.matchMedia('(min-width: 1024px)'); + mediaQuery = window.matchMedia('(min-width: 768px)'); mediaQuery.addEventListener('change', handleMediaQuery); handleMediaQuery(mediaQuery); @@ -553,6 +553,7 @@ bind:width={threadPanelWidth} minWidth={320} maxWidth={640} + minSiblingWidth={360} className="h-full" >
diff --git a/src/lib/components/chat/ChatControls.svelte b/src/lib/components/chat/ChatControls.svelte index e8e5ea5375..77b0c3bc4d 100644 --- a/src/lib/components/chat/ChatControls.svelte +++ b/src/lib/components/chat/ChatControls.svelte @@ -347,7 +347,7 @@ -
+
{ const newId = $selectedTerminalId === terminal.url ? null : terminal.url; selectedTerminalId.set(newId); - if (newId && window.matchMedia('(min-width: 1024px)').matches) { + if (newId && !$mobile) { showControls.set($settings?.showFilesOnTerminalSelect ?? true); } @@ -92,7 +93,7 @@ const selectSystem = async (terminal: (typeof systemTerminals)[0]) => { const newId = $selectedTerminalId === terminal.id ? null : terminal.id; selectedTerminalId.set(newId); - if (newId && window.matchMedia('(min-width: 1024px)').matches) { + if (newId && !$mobile) { showControls.set($settings?.showFilesOnTerminalSelect ?? true); } diff --git a/src/lib/components/layout/SearchModal.svelte b/src/lib/components/layout/SearchModal.svelte index a1b86153c3..b2e16c4825 100644 --- a/src/lib/components/layout/SearchModal.svelte +++ b/src/lib/components/layout/SearchModal.svelte @@ -88,9 +88,11 @@ const quietButton = 'focus-ring flex h-[1.6875rem] shrink-0 items-center justify-center gap-1 rounded-lg px-1.5 text-[0.6875rem] font-normal text-gray-500 hover:bg-gray-50/60 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-gray-800/60 dark:hover:text-gray-200'; $: if (show && typeof window !== 'undefined') { + const savedPreview = localStorage.getItem('searchPreview'); preview = - window.matchMedia('(min-width: 1024px)').matches && - localStorage.getItem('searchPreview') !== 'false'; + savedPreview === null + ? window.matchMedia('(min-width: 768px)').matches + : savedPreview === 'true'; } $: schedule(show, query, kind, sharing, scope); diff --git a/src/lib/components/layout/Sidebar.svelte b/src/lib/components/layout/Sidebar.svelte index 3ddd1ae054..4e0cbe36fb 100644 --- a/src/lib/components/layout/Sidebar.svelte +++ b/src/lib/components/layout/Sidebar.svelte @@ -104,7 +104,6 @@ import MoreHorizontalIcon from './Sidebar/icons/MoreHorizontal.svelte'; import MobileSwipePanel from '../common/MobileSwipePanel.svelte'; - const BREAKPOINT = 768; const DEFAULT_PINNED_ITEMS = ['notes', 'workspace']; let scrollTop = 0; From d58af14c0ce50bc16f290560bf3d2521dd85e65c Mon Sep 17 00:00:00 2001 From: Classic298 <27028174+Classic298@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:18:14 +0100 Subject: [PATCH 004/160] Merge pull request #33377 from Classic298/fix-chat-load-controller-renewal fix: Controls file removals and shared-chat Regenerate break in a new chat --- src/lib/components/chat/Chat.svelte | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 438c173eb9..fb6317698e 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -950,7 +950,7 @@ }; const initEmbeddedDraft = async () => { - chatLoadController.abort(); + startChatLoad(); modelDefaults = null; terminalContext = null; clearTimeout(saveControlsTimer); @@ -2619,7 +2619,7 @@ }; const initNewChat = async () => { - chatLoadController.abort(); + startChatLoad(); modelDefaults = null; clearTimeout(saveControlsTimer); await saveControls(); From 93f4440a384341438e0da2fa8e41f3d310ce9837 Mon Sep 17 00:00:00 2001 From: joaoback <156559121+joaoback@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:58:51 -0300 Subject: [PATCH 005/160] i18n: add pt-BR translations for newly added UI items and consistency pass (#33379) New **pt-BR** translations for items introduced in the latest releases, plus a consistency/quality pass across existing strings (grammar, tone, capitalization, pluralization). Placeholders and hotkeys preserved. No logic changes. --- src/lib/i18n/locales/pt-BR/translation.json | 292 ++++++++++---------- 1 file changed, 146 insertions(+), 146 deletions(-) diff --git a/src/lib/i18n/locales/pt-BR/translation.json b/src/lib/i18n/locales/pt-BR/translation.json index bb4d27e248..63502cd92d 100644 --- a/src/lib/i18n/locales/pt-BR/translation.json +++ b/src/lib/i18n/locales/pt-BR/translation.json @@ -1,6 +1,6 @@ { - "- usage not recorded": "", - "- usage not recorded · * partial usage": "", + "- usage not recorded": "- uso não registrado", + "- usage not recorded · * partial usage": "- uso não registrado · * uso parcial", "-1 for no limit, or a positive integer for a specific limit": "-1 para nenhum limite ou um inteiro positivo para um limite específico", "(latest)": "(mais recente)", "(leave blank for to use commercial endpoint)": "(deixe em branco para usar o endpoint comercial)", @@ -81,7 +81,7 @@ "{{NAMES}} reacted with {{REACTION}}": "{{NAMES}} reagiram com {{REACTION}}", "{{page}} / {{totalPages}} ({{rows}} rows)": "{{page}} / {{totalPages}} ({{rows}} linhas)", "{{percent}}% full": "{{percent}}% cheio", - "{{tokens}} tokens": "", + "{{tokens}} tokens": "{{tokens}} tokens", "{{user}}'s Chats": "Chats de {{user}}", "{{webUIName}} Backend Required": "Backend {{webUIName}} necessário", "* (all domains)": "* (todos os domínios)", @@ -111,7 +111,7 @@ "A collaboration channel where people join as members": "Um canal de colaboração onde as pessoas se juntam como membros.", "A discussion channel where access is controlled by groups and permissions": "Um canal de discussão onde o acesso é controlado por grupos e permissões.", "A new version (v{{LATEST_VERSION}}) is now available.": "Uma nova versão (v{{LATEST_VERSION}}) está disponível.", - "A page changed elsewhere. Your previous text is available to download.": "", + "A page changed elsewhere. Your previous text is available to download.": "Uma página foi alterada em outro lugar. Seu texto anterior está disponível para baixar.", "A private conversation between you and selected users": "Uma conversa privada entre você e usuários selecionados.", "a user": "um usuário", "about the Roman Empire": "sobre o Império Romano", @@ -166,14 +166,14 @@ "Add Members": "Adicionar membros", "Add Memory": "Adicionar Memória", "Add option": "Adicionar opção", - "Add page": "", + "Add page": "Adicionar página", "Add parameter": "Adicionar parâmetro", "Add prompt": "Adicionar prompt", "Add prompt suggestion": "Adicionar sugestão de prompt", "Add Reaction": "Adicionar reação", "Add skills in the Skills workspace.": "Adicione skills no espaço de trabalho de Skills.", - "Add subpage": "", - "Add subpage to {{title}}": "", + "Add subpage": "Adicionar subpágina", + "Add subpage to {{title}}": "Adicionar subpágina em {{title}}", "Add tag": "Adicionar tag", "Add Tag": "Adicionar Tag", "Add tags to organize models and make them easier to find.": "Adicione tags para organizar os modelos e facilitar a localização.", @@ -214,7 +214,7 @@ "All models are now visible": "Todos os modelos estão agora visíveis", "All models deleted successfully": "Todos os modelos foram excluídos com sucesso", "All rights reserved.": "Todos os direitos reservados.", - "All sessions": "", + "All sessions": "Todas as sessões", "All sessions revoked": "Todas as sessões foram revogadas", "All shared chats have been unshared.": "Todos os chats compartilhados foram descompartilhados.", "All Sources": "Todas as Origens", @@ -261,7 +261,7 @@ "Amazing": "Incrível", "an assistant": "um assistente", "Analytics": "Análises", - "Analytics view": "", + "Analytics view": "Visualização das análises", "Analyzed": "Analisado", "Analyzing...": "Analisando...", "and": "e", @@ -338,7 +338,7 @@ "Attach reusable instructions and resources for specific tasks.": "Anexe instruções e recursos reutilizáveis para tarefas específicas.", "Attach Webpage": "Anexar Página Web", "Attention to detail": "Atenção aos detalhes", - "Audio": "", + "Audio": "Áudio", "Audio playback failed": "Falha na reprodução do áudio", "Audio player": "Reprodutor de áudio", "August": "Agosto", @@ -402,7 +402,7 @@ "before": "antes", "Being lazy": "Foi preguiçoso", "Binary file — text comparison is unavailable.": "Arquivo binário — a comparação de texto não está disponível.", - "Binary file. Download to open.": "", + "Binary file. Download to open.": "Arquivo binário. Baixe para abrir.", "Bing": "Bing", "Bold": "Negrito", "Boosting or penalizing specific tokens for constrained responses. Bias values will be clamped between -100 and 100 (inclusive). (Default: none)": "Aumentar ou penalizar tokens específicos para respostas restritas. Os valores de viés serão fixados entre -100 e 100 (inclusive). (Padrão: nenhum)", @@ -418,8 +418,8 @@ "by {{name}}": "por {{name}}", "By {{name}}": "Por {{name}}", "By supporting the project through sponsorship or an enterprise license, you help us stay independent, ship new features faster, improve stability, and grow Open WebUI for the long haul.": "Ao apoiar o projeto por meio de patrocínio ou de uma licença empresarial, você nos ajuda a manter a independência, lançar novos recursos mais rapidamente, melhorar a estabilidade e desenvolver o Open WebUI a longo prazo.", - "Cache read": "", - "Cache write": "", + "Cache read": "Leitura de cache", + "Cache write": "Gravação de cache", "Calendar": "Calendário", "Calendar created": "Calendário criado", "Calendar deleted": "Calendário excluído", @@ -434,7 +434,7 @@ "Camera": "Câmera", "Cancel": "Cancelar", "Cancel download of {{model}}": "Cancelar download de {{model}}", - "Cancelled": "", + "Cancelled": "Cancelado", "Cannot create an empty note.": "Não é possível criar uma nota vazia.", "Cannot delete the production version": "Não é possível excluir a versão de produção.", "Capture": "Capturar", @@ -490,7 +490,7 @@ "Checking for updates...": "Verificando atualizações...", "Choose a date range to compare": "Escolha um intervalo de datas para comparar", "Choose a model before saving...": "Escolha um modelo antes de salvar...", - "Choose a parent page. Subpages move with this page.": "", + "Choose a parent page. Subpages move with this page.": "Escolha uma página-mãe. As subpáginas são movidas junto com esta página.", "Choose a valid start and end date.": "Escolha datas de início e de término válidas.", "Choose a VRM file, up to 25 MiB.": "Escolha um arquivo VRM de até 25 MiB.", "Choose a VRMA file, up to 10 MiB.": "Escolha um arquivo VRMA de até 10 MiB.", @@ -546,9 +546,9 @@ "Close feedback": "Fechar feedback", "Close modal": "Fechar modal", "Close Modal": "Fechar Modal", - "Close pages": "", + "Close pages": "Fechar páginas", "Close search": "Fechar pesquisa", - "Close session details": "", + "Close session details": "Fechar detalhes da sessão", "Close Sidebar": "Fechar barra lateral", "Close terminal": "Fechar terminal", "cloud": "cloud", @@ -557,7 +557,7 @@ "Code Editor": "Editor de código", "Code execution": "Execução de código", "Code formatted successfully": "Código formatado com sucesso", - "Code interpreter": "", + "Code interpreter": "Intérprete de código", "Code Interpreter": "Intérprete de código", "Codes match": "Os códigos coincidem", "Collaboration channel where people join as members": "Canal de colaboração onde as pessoas se juntam como membros.", @@ -598,8 +598,8 @@ "Comparing with knowledge base...": "Comparando com a base de conhecimento...", "Comparison options": "Opções de comparação", "Comparison reached its time limit; some changes are grouped together.": "A comparação atingiu o limite de tempo; algumas alterações foram agrupadas.", - "complete": "", - "Completed": "", + "complete": "completas", + "Completed": "Concluído", "Completions": "Completions", "Compress uploaded images before sending or storage.": "Comprima as imagens enviadas antes do envio ou armazenamento.", "Computing checksums ({{count}} files)_one": "Calculando checksums ({{count}} arquivo)", @@ -648,7 +648,7 @@ "Context compaction failed": "Falha na compactação de contexto", "Context compaction is disabled": "A compactação de contexto está desativada", "Context usage": "Uso de contexto", - "Context window": "", + "Context window": "Janela de contexto", "Continue": "Continuar", "Continue Response": "Continuar Resposta", "Continue with {{provider}}": "Continuar com {{provider}}", @@ -678,12 +678,12 @@ "Copy link": "Copiar link", "Copy Link": "Copiar Link", "Copy original to clipboard": "Copiar original para a área de transferência", - "Copy page link": "", + "Copy page link": "Copiar link da página", "Copy Path": "Copiar caminho", "Copy Prompt": "Copiar prompt", "Copy proposed revision to clipboard": "Copiar revisão proposta para a área de transferência", "Copy Share Link": "Copiar link de compartilhamento", - "Copy this key now. It will not be shown here again after you close this dialog.": "", + "Copy this key now. It will not be shown here again after you close this dialog.": "Copie esta chave agora. Ela não será exibida novamente depois que você fechar esta janela.", "Copy to clipboard": "Copiar para a área de transferência", "Copy Token": "Copiar Token", "Copy URL": "Copiar URL", @@ -705,7 +705,7 @@ "Could not update {{count}} chats. They remain selected so you can try again._other": "Não foi possível atualizar {{count}} chats. Eles continuam selecionados para que você possa tentar novamente.", "Could you start by asking me about instances when I procrastinate the most and then give me some suggestions to overcome it?": "Você poderia começar me perguntando em quais situações eu mais procrastino e, em seguida, me dar algumas sugestões para superar isso?", "Couldn't find your language?": "Não encontrou seu idioma?", - "Count": "", + "Count": "Qtd.", "CPU": "CPU", "Create": "Criar", "Create a knowledge base": "Criar uma Base de Conhecimento", @@ -790,7 +790,7 @@ "Default to segmented retrieval for focused and relevant content extraction, this is recommended for most cases.": "Use a recuperação segmentada como padrão para extração de conteúdo focado e relevante; isso é recomendado para a maioria dos casos.", "Default webhook": "Webhook padrão", "Delete": "Excluir", - "Delete \"{{title}}\"? This cannot be undone.": "", + "Delete \"{{title}}\"? This cannot be undone.": "Excluir \"{{title}}\"? Esta ação não pode ser desfeita.", "Delete {{count}} chats?_one": "Excluir {{count}} chat?", "Delete {{count}} chats?_many": "Excluir {{count}} chats?", "Delete {{count}} chats?_other": "Excluir {{count}} chats?", @@ -822,13 +822,13 @@ "Delete message?": "Excluir mensagem?", "Delete Model": "Excluir modelo", "Delete note?": "Excluir nota?", - "Delete page": "", - "Delete page?": "", + "Delete page": "Excluir página", + "Delete page?": "Excluir página?", "Delete prompt?": "Excluir prompt?", - "Delete selected": "", - "Delete selected files?": "", + "Delete selected": "Excluir selecionados", + "Delete selected files?": "Excluir os arquivos selecionados?", "Delete skill?": "Excluir skill?", - "Delete this file or folder?": "", + "Delete this file or folder?": "Excluir este arquivo ou pasta?", "delete this link": "Excluir este link", "Delete tool?": "Excluir ferramenta?", "Delete User": "Excluir Usuário", @@ -877,7 +877,7 @@ "Discard changes": "Descartar alterações", "Discard comparison changes?": "Descartar as alterações da comparação?", "Discard unsaved changes?": "Descartar alterações não salvas?", - "Discard unsaved skill changes?": "", + "Discard unsaved skill changes?": "Descartar as alterações não salvas da skill?", "Disconnect OAuth": "Desconectar OAuth", "Disconnected": "Desconectado", "Discover a function": "Descubra uma função", @@ -921,7 +921,7 @@ "Download CSV Template": "Baixar Modelo CSV", "Download failed": "Download falhou", "Download Model": "Baixar Modelo", - "Download page": "", + "Download page": "Baixar página", "Download recovery codes": "Baixar códigos de recuperação", "Downloading \"{{name}}\"": "Baixando \"{{name}}\"", "Downloading \"{{searchValue}}\"": "Baixando \"{{searchValue}}\"", @@ -990,12 +990,12 @@ "ElevenLabs": "ElevenLabs", "Email": "Email", "Embedded content": "Conteúdo incorporado", - "Embeddings": "", + "Embeddings": "Embeddings", "Emoji": "Emoji", "Emoji graphics provided by": "Gráficos de emoji fornecidos por", "Emojis": "Emojis", "Empty": "Vazio", - "Empty folders are saved when they contain files.": "", + "Empty folders are saved when they contain files.": "Pastas vazias só são salvas quando tiverem arquivos.", "Empty message": "Mensagem vazia", "Enable": "Ativar", "Enable All": "Ativar tudo", @@ -1015,7 +1015,7 @@ "End call": "Encerrar chamada", "End date": "Data de término", "End Tag": "Tag final", - "End time": "", + "End time": "Hora de término", "Endpoint": "Endpoint", "Enforce Temporary Chat": "Aplicar chat temporário", "Enhance": "Melhorar", @@ -1185,7 +1185,7 @@ "Error uploading file: {{error}}": "Erro ao carregar o arquivo: {{error}}", "Error: A model with the ID '{{modelId}}' already exists. Please select a different ID to proceed.": "Erro: Já existe um modelo com o ID '{{modelId}}'. Selecione um ID diferente para prosseguir.", "Error: Model ID cannot be empty. Please enter a valid ID to proceed.": "Erro: O ID do modelo não pode estar vazio. Insira um ID válido para prosseguir.", - "Errors": "", + "Errors": "Erros", "Evaluations": "Avaliações", "Event": "Evento", "Event created": "Evento criado", @@ -1214,7 +1214,7 @@ "Exclude": "Excluir", "Execute code for analysis": "Executar código para análise", "Executing {{NAME}}...": "Executando {{NAME}}...", - "Execution timeline": "", + "Execution timeline": "Linha do tempo de execução", "Expand": "Expandir", "Expand {{name}}": "Expandir {{name}}", "Expand input": "Expandir entrada", @@ -1344,7 +1344,7 @@ "File renamed.": "Arquivo renomeado.", "File saved": "Arquivo salvo", "File size should not exceed {{maxSize}} MB.": "Arquivo não pode exceder {{maxSize}} MB.", - "File updated on disk. Your local changes are preserved.": "", + "File updated on disk. Your local changes are preserved.": "Arquivo atualizado no disco. Suas alterações locais foram preservadas.", "File uploaded successfully": "Arquivo carregado com sucesso", "Filename": "Nome do arquivo", "Filename matches": "Correspondências de nome de arquivo", @@ -1358,7 +1358,7 @@ "Filter is now globally enabled": "O filtro está agora ativado globalmente", "Filters": "Filtros", "Fingerprint spoofing detected: Unable to use initials as avatar. Defaulting to default profile image.": "Falsificação de impressão digital detectada: Não foi possível usar as iniciais como avatar. Usando a imagem de perfil padrão.", - "First to last saved message, including idle time": "", + "First to last saved message, including idle time": "Da primeira à última mensagem salva, incluindo o tempo ocioso", "Focus Chat Input": "Focar no Campo de Entrada do Chat", "Folder": "Pasta", "Folder Background Image": "Imagem de fundo da pasta", @@ -1475,8 +1475,8 @@ "Hide from Sidebar": "Ocultar da barra lateral", "Hide Hidden Files": "Ocultar Arquivos Ocultos", "Hide Model": "Ocultar modelo", - "Hide preview": "", - "Hide sub-agents": "", + "Hide preview": "Ocultar pré-visualização", + "Hide sub-agents": "Ocultar subagentes", "Hide whitespace": "Ocultar espaços em branco", "High": "Alto", "History": "Histórico", @@ -1516,7 +1516,7 @@ "Import": "Importar", "Import action": "Ação de importação", "Import CSV": "Importar CSV", - "Import folder": "", + "Import folder": "Importar pasta", "Import from URL": "Importar do link", "Import JSON": "Importar JSON", "Import Models": "Importar Modelos", @@ -1530,7 +1530,7 @@ "Imported automations successfully": "Automações importadas com sucesso", "Imported notes successfully": "Notas importadas com sucesso", "Importing...": "Importando...", - "In progress": "", + "In progress": "Em andamento", "Inactive": "Inativo", "Include": "Incluir", "Include the current directory in tool instructions.": "Inclua o diretório atual nas instruções das ferramentas.", @@ -1551,7 +1551,7 @@ "Input Tokens": "Tokens de Entrada", "Input Transcription Model": "Modelo de Transcrição de Entrada", "Input Variables": "Variáveis de entrada", - "Inputs": "", + "Inputs": "Entradas", "Insert into note": "Inserir na nota", "Instructions": "Instruções", "Integrations": "Integrações", @@ -1572,9 +1572,9 @@ "Invalid value": "Valor inválido", "is typing...": "está digitando...", "Italic": "Itálico", - "items without recorded durations": "", - "items without recorded start/end times": "", - "Its subpages will be kept and moved up one level.": "", + "items without recorded durations": "itens sem duração registrada", + "items without recorded start/end times": "itens sem horários de início/fim registrados", + "Its subpages will be kept and moved up one level.": "As subpáginas dela serão mantidas e subirão um nível.", "January": "Janeiro", "Join": "Entrar", "Join encrypted chat": "Entrar no chat criptografado", @@ -1590,7 +1590,7 @@ "Keep both": "Manter ambos", "Keep both versions in the proposed revision, original first.": "Mantém as duas versões na revisão proposta, com o original primeiro.", "Keep current webhook URL": "Manter a URL atual do webhook", - "Keep editing": "", + "Keep editing": "Continuar editando", "Keep in Sidebar": "Manter na barra lateral", "Keep tools listed even while your shell is closed.": "Mantenha as ferramentas listadas mesmo com o shell fechado.", "Key": "Chave", @@ -1618,7 +1618,7 @@ "Last 30 days": "Últimos 30 dias", "Last 7 days": "Últimos 7 dias", "Last 90 days": "Últimos 90 dias", - "Last active": "", + "Last active": "Última atividade", "Last Active": "Última Atividade", "Last Modified": "Última Modificação", "Last reply": "Última resposta", @@ -1677,9 +1677,9 @@ "Loading more results": "Carregando mais resultados", "Loading policy...": "Carregando política...", "Loading release notes...": "Carregando notas da versão...", - "Loading sessions": "", + "Loading sessions": "Carregando sessões", "Loading tools...": "Carregando ferramentas...", - "Loading trace": "", + "Loading trace": "Carregando rastreamento", "Loading...": "Carregando...", "local": "local", "Local": "Local", @@ -1713,7 +1713,7 @@ "Matching tabs: {{count}}_one": "Aba correspondente: {{count}}", "Matching tabs: {{count}}_many": "Abas correspondentes: {{count}}", "Matching tabs: {{count}}_other": "Abas correspondentes: {{count}}", - "Max output": "", + "Max output": "Saída máxima", "Max Snippets": "Máximo de Trechos", "Max tokens to retrieve (1024-32768, default 8192)": "Máximo de tokens para recuperar (1024-32768, padrão 8192)", "Maximum extra snippets returned per result. Set to 0 to disable them.": "Número máximo de trechos adicionais retornados por resultado. Defina como 0 para desativá-los.", @@ -1758,7 +1758,7 @@ "MinerU API Key required for Cloud API mode.": "Chave de API MinerU necessária para o modo Cloud API.", "Mistral OCR": "Mistral OCR", "Mistral OCR API Key required.": "Chave de API do Mistral OCR necessária.", - "Mistral OCR Parameters": "", + "Mistral OCR Parameters": "Parâmetros do Mistral OCR", "MistralAI": "MistralAI", "Mo_day_of_week": "Seg", "Model": "Modelo", @@ -1825,11 +1825,11 @@ "More options": "Mais opções", "More Options": "Mais opções", "Move": "Mover", - "Move down": "", - "Move page": "", - "Move page…": "", + "Move down": "Mover para baixo", + "Move page": "Mover página", + "Move page…": "Mover página…", "Move to top level": "Mover para o nível superior", - "Move up": "", + "Move up": "Mover para cima", "Moved {{name}}": "{{name}} movido", "Multi-factor authentication": "Autenticação multifator", "Multipart Upload": "Upload multipart", @@ -1875,8 +1875,8 @@ "Next month": "Próximo mês", "Next page": "Próxima página", "Next run": "Próxima execução", - "Next sessions": "", - "Next trace items": "", + "Next sessions": "Próximas sessões", + "Next trace items": "Próximos itens do rastreamento", "Next version": "Próxima versão", "No": "Não", "No access grants. Private to you.": "Nenhuma concessão de acesso. Privado para você.", @@ -1929,11 +1929,11 @@ "No knowledge found": "Nenhum conhecimento encontrado", "No limit": "Sem limite", "No matches": "Nenhuma correspondência", - "No matches found": "", + "No matches found": "Nenhum resultado encontrado", "No matching scopes.": "Nenhum escopo correspondente.", "No model data": "Nenhum dado de modelo", "No model IDs": "Nenhum ID de modelo", - "No model recorded": "", + "No model recorded": "Nenhum modelo registrado", "No model usage found": "Nenhum uso de modelo encontrado", "No models accessible": "Nenhum modelo acessível", "No models available": "Nenhum modelo disponível", @@ -1954,11 +1954,11 @@ "No results": "Nenhum resultado encontrado", "No results found": "Nenhum resultado encontrado", "No runs yet": "Nenhuma execução ainda", - "No saved items match this filter.": "", + "No saved items match this filter.": "Nenhum item salvo corresponde a este filtro.", "No scopes requested.": "Nenhum escopo solicitado.", "No search query generated": "Nenhuma consulta de pesquisa gerada", "No servers detected": "Nenhum servidor detectado", - "No sessions match these filters.": "", + "No sessions match these filters.": "Nenhuma sessão corresponde a estes filtros.", "No skills found": "Nenhuma skill encontrada", "No source available": "Nenhuma fonte disponível", "No sources found": "Nenhuma fonte encontrada", @@ -1978,12 +1978,12 @@ "No webhooks yet": "Ainda não há webhooks", "Node Ids": "IDs dos nós", "None": "Nenhum", - "None reported": "", + "None reported": "Nenhum informado", "Not configured": "Não configurado", "Not factually correct": "Não está factualmente correto", "Not helpful": "Não é útil", - "Not logged": "", - "Not provided": "", + "Not logged": "Não registrado", + "Not provided": "Não informado", "Not Registered": "Não registrado", "Not scheduled": "Não agendado", "Note": "Nota", @@ -1992,7 +1992,7 @@ "Notes": "Notas", "Notes Public Sharing": "Compartilhamento Público das Notas", "Notes Sharing": "Compartilhamento de notas", - "Nothing here yet": "", + "Nothing here yet": "Nada aqui ainda", "Nothing to compact": "Nada para compactar", "Notifications": "Notificações", "November": "Novembro", @@ -2015,7 +2015,7 @@ "Omit": "Omitir", "On": "Ligado", "Once": "Uma vez", - "One session per chat. Counts cover the selected date range; span includes idle time.": "", + "One session per chat. Counts cover the selected date range; span includes idle time.": "Uma sessão por chat. As contagens cobrem o intervalo de datas selecionado; a duração inclui o tempo ocioso.", "Only active during Voice Mode.": "Ativo somente durante o Modo de Voz.", "Only active when \"Paste Large Text as File\" setting is toggled on.": "Ativo somente quando a configuração \"Colar texto grande como arquivo\" estiver ativada.", "Only active when a tool call is waiting for approval.": "Ativo somente quando uma chamada de ferramenta está aguardando aprovação.", @@ -2039,7 +2039,7 @@ "Oops! You're using an unsupported method (frontend only). Please serve the WebUI from the backend.": "Ops! Você está usando um método não suportado (somente frontend). Por favor, sirva a WebUI a partir do backend.", "Open": "Abrir", "Open automation": "Abrir automação", - "Open chat": "", + "Open chat": "Abrir chat", "Open create menu": "Abrir menu Criar", "Open file": "Abrir arquivo", "Open Folder": "Abrir Pasta", @@ -2084,7 +2084,7 @@ "Output": "Saída", "OUTPUT": "SAÍDA", "Output Tokens": "Tokens de Saída", - "Outputs": "", + "Outputs": "Saídas", "Overcome procrastination": "Vencer a procrastinação", "Override generation settings such as temperature, token limits, and sampling. Unmodified settings use the provider defaults.": "Substitua configurações de geração como temperatura, limites de tokens e amostragem. As configurações não modificadas usam os padrões do provedor.", "Overview": "Visão Geral", @@ -2092,19 +2092,19 @@ "PaddleOCR-vl API URL required.": "URL da API PaddleOCR-vl é obrigatória.", "page": "página", "Page": "Página", - "Page {{number}}": "", - "Page menu": "", - "Page title": "", - "Pages": "", + "Page {{number}}": "Página {{number}}", + "Page menu": "Menu da página", + "Page title": "Título da página", + "Pages": "Páginas", "Paragraphs": "Parágrafos", "parameter": "parâmetro", "Parameter": "Parâmetro", "Parameters": "Parâmetros", "Parent group": "Grupo pai", "Parent message not found": "Mensagem pai não encontrada", - "Parent page": "", + "Parent page": "Página-mãe", "Parent permissions are inherited. Disabling a local permission does not revoke inherited access.": "As permissões do grupo pai são herdadas. Desativar uma permissão local não revoga o acesso herdado.", - "Partial usage": "", + "Partial usage": "Uso parcial", "Participants": "Participantes", "Participate in community leaderboards and evaluations! Syncing aggregated usage stats helps drive research and improvements to Open WebUI. Your privacy is paramount: no message content is ever shared.": "Participe dos rankings e avaliações da comunidade! A sincronização de estatísticas de uso agregadas ajuda a impulsionar pesquisas e melhorias no Open WebUI. Sua privacidade é fundamental: nenhum conteúdo de mensagem é compartilhado.", "Passthrough params": "Parâmetros de repasse", @@ -2129,12 +2129,12 @@ "Permissions reset to defaults": "Permissões redefinidas para os padrões", "Persistent": "Persistente", "Personal": "Pessoal", - "Personal chat": "", - "Personal note": "", + "Personal chat": "Chat pessoal", + "Personal note": "Nota pessoal", "Pin": "Fixar", "Pin to Sidebar": "Fixar na barra lateral", "Pinned": "Fixado", - "Pinned & recent": "", + "Pinned & recent": "Fixados e recentes", "Pinned Messages": "Mensagens fixadas", "Pipe": "Pipe", "Pipeline deleted successfully": "Pipeline excluído com sucesso", @@ -2196,8 +2196,8 @@ "Previous message": "Mensagem anterior", "Previous month": "Mês anterior", "Previous page": "Página anterior", - "Previous sessions": "", - "Previous trace items": "", + "Previous sessions": "Sessões anteriores", + "Previous trace items": "Itens anteriores do rastreamento", "Previous version": "Versão anterior", "Private": "Privado", "Private conversation between selected users": "Conversa privada entre usuários selecionados", @@ -2219,8 +2219,8 @@ "Prompts Sharing": "Compartilhamento de Prompts", "Proposed revision": "Revisão proposta", "Provider": "Provedor", - "Provider context": "", - "Provider details": "", + "Provider context": "Contexto do provedor", + "Provider details": "Detalhes do provedor", "Public": "Público", "Public key": "Chave pública", "Pull \"{{searchValue}}\" from Ollama.com": "Obter \"{{searchValue}}\" de Ollama.com", @@ -2249,7 +2249,7 @@ "Realtime": "Realtime", "Realtime Voice": "Voz em Tempo Real (Realtime)", "Reason": "Razão", - "Reasoning": "", + "Reasoning": "Raciocínio", "Reasoning text...": "Texto de raciocínio...", "Rebuild knowledge file, knowledge search, and memory vectors using the current embedding model.": "Reconstrua o arquivo de conhecimento, a pesquisa de conhecimento e os vetores de memória usando o modelo de embedding atual.", "Receives matching events across the instance, including system/config events and events associated with any user.": "Recebe eventos correspondentes em toda a instância, incluindo eventos de sistema/configuração e eventos associados a qualquer usuário.", @@ -2261,10 +2261,10 @@ "Reconnected": "Reconectado", "Record": "Gravar", "Record voice": "Gravar voz", - "Recorded duration": "", - "Recorded sequence": "", - "Recorded tokens": "", - "Recorded tokens by response": "", + "Recorded duration": "Duração registrada", + "Recorded sequence": "Sequência registrada", + "Recorded tokens": "Tokens registrados", + "Recorded tokens by response": "Tokens registrados por resposta", "Recover your authenticator": "Recuperar seu autenticador", "Recovery code": "Código de recuperação", "Redirecting you to Open WebUI Community": "Redirecionando você para a Comunidade Open WebUI", @@ -2289,12 +2289,12 @@ "Registration failed": "O registro falhou", "Registration successful": "Registro realizado com sucesso", "Reindex Embedding Data": "Reindexar Dados de Embedding", - "Rejected": "", + "Rejected": "Rejeitado", "Release Notes": "Notas de Lançamento", "Releases": "Lançamentos", "Relevance": "Relevância", - "Reload": "", - "Reload latest": "", + "Reload": "Recarregar", + "Reload latest": "Carregar a versão mais recente", "Reload preview": "Recarregar pré-visualização", "Remember Dismissal": "Lembrar da dispensa", "Reminder": "Lembrete", @@ -2318,7 +2318,7 @@ "Removing {{count}} stale files..._many": "Removendo {{count}} arquivos obsoletos...", "Removing {{count}} stale files..._other": "Removendo {{count}} arquivos obsoletos...", "Rename": "Renomear", - "Rename page": "", + "Rename page": "Renomear página", "Renamed to {{name}}": "Renomeado para {{name}}", "Rendered preview": "Pré-visualização renderizada", "Reorder": "Reordenar", @@ -2331,7 +2331,7 @@ "Reply in Thread": "Responder no tópico", "Reply to thread...": "Responder ao tópico...", "Replying to {{NAME}}": "Respondendo para {{NAME}}", - "Reported by the provider.": "", + "Reported by the provider.": "Informado pelo provedor.", "Requested scopes": "Escopos solicitados", "Require an authenticator for all users": "Exigir autenticador para todos os usuários", "required": "obrigatório", @@ -2350,17 +2350,17 @@ "Resolved": "Resolvido", "Response": "Resposta", "Response complete": "Resposta concluída", - "Response duration": "", - "Response errors": "", + "Response duration": "Duração da resposta", + "Response errors": "Erros de resposta", "Response notifications cannot be activated as the website permissions have been denied. Please visit your browser settings to grant the necessary access.": "Notificações de resposta não podem ser ativadas pois as permissões do site foram negadas. Por favor, visite as configurações do seu navegador para conceder o acesso necessário.", "Responses": "Respostas", - "responses with recorded usage": "", + "responses with recorded usage": "respostas com uso registrado", "Restart": "Reiniciar", "Restricted": "Restrito", "Result": "Resultado", "RESULT": "RESULTADO", "Result preview": "Pré-visualização do resultado", - "Results": "", + "Results": "Resultados", "Retrieved {{count}} sources": "{{count}} fontes recuperadas", "Retrieved {{count}} sources_one": "{{count}} fonte recuperada", "Retrieved {{count}} sources_many": "{{count}} fontes recuperadas", @@ -2375,8 +2375,8 @@ "Revised": "Revisado", "Rewrite the selected text.": "Reescreva o texto selecionado.", "Role": "Função", - "Rotate": "", - "Rotate API Key?": "", + "Rotate": "Rotacionar", + "Rotate API Key?": "Rotacionar a Chave API?", "RTL": "Direita para Esquerda", "Run": "Executar", "Run AI on your own terms. Connect any model, extend with code, and protect what matters without compromise. Your models, your data, your machine, wherever you open it.": "Execute IA do seu jeito. Conecte qualquer modelo, amplie com código e proteja o que importa sem abrir mão de nada. Seus modelos, seus dados e sua máquina, onde quer que você os acesse.", @@ -2398,15 +2398,15 @@ "Save and send": "Salvar e enviar", "Save As Copy": "Salvar Como Cópia", "Save Chat": "Salvar Chat", - "Save draft as copy": "", - "Save local changes": "", + "Save draft as copy": "Salvar rascunho como cópia", + "Save local changes": "Salvar alterações locais", "Save the connection to keep the OAuth details. Keep the Connection ID unchanged.": "Salve a conexão para manter os dados do OAuth. Não altere o ID da Conexão.", "Save your changes before continuing?": "Salvar suas alterações antes de continuar?", "Save your recovery codes": "Salve seus códigos de recuperação", "Saved": "Salvo", - "Saved execution sequence": "", - "Saved item": "", - "Saved order only; spacing does not represent elapsed time.": "", + "Saved execution sequence": "Sequência de execução salva", + "Saved item": "Item salvo", + "Saved order only; spacing does not represent elapsed time.": "Apenas a ordem salva; o espaçamento não representa o tempo decorrido.", "Saving approves the updated app identity and selected scopes.": "Salvar aprova a identidade atualizada do app e os escopos selecionados.", "Saving...": "Salvando...", "Scan the QR code, then enter the six-digit code from your authenticator app.": "Escaneie o QR code e, em seguida, digite o código de seis dígitos do seu aplicativo autenticador.", @@ -2452,8 +2452,8 @@ "Search Prompts": "Pesquisar Prompts", "Search results": "Resultados da pesquisa", "Search scopes": "Pesquisar escopos", - "Search sessions": "", - "Search sessions, users or folders": "", + "Search sessions": "Pesquisar sessões", + "Search sessions, users or folders": "Pesquisar sessões, usuários ou pastas", "Search skills": "Pesquisar skills", "Search Skills": "Pesquisar Skills", "Search the internet": "Pesquisar na Internet", @@ -2475,7 +2475,7 @@ "Select {{filename}}": "Selecionar {{filename}}", "Select {{modelName}} model": "Selecionar modelo {{modelName}}", "Select {{name}}": "Selecionar {{name}}", - "Select a bar to jump to its saved responses. Grouped bars sum consecutive responses.": "", + "Select a bar to jump to its saved responses. Grouped bars sum consecutive responses.": "Selecione uma barra para ir às respostas salvas dela. Barras agrupadas somam respostas consecutivas.", "Select a base model": "Selecione um modelo base", "Select a conversation to preview": "Selecione uma conversa para visualizar", "Select a engine": "Selecione um motor", @@ -2489,7 +2489,7 @@ "Select a model to isolate it.": "Selecione um modelo para isolá-lo.", "Select a pipeline": "Selecione um pipeline", "Select a pipeline url": "Selecione uma URL de pipeline", - "Select a range to filter sessions. Partial usage is included.": "", + "Select a range to filter sessions. Partial usage is included.": "Selecione uma faixa para filtrar as sessões. O uso parcial está incluído.", "Select a reranking model engine": "Selecione um mecanismo de modelo de reclassificação", "Select a role": "Selecione uma função", "Select a theme": "Selecione um tema", @@ -2511,7 +2511,7 @@ "Select for Compare": "Selecionar para Comparar", "Select how to split message text for TTS requests": "Selecione como dividir o texto da mensagem para solicitações TTS", "Select Knowledge": "Selecionar Conhecimento", - "Select less text (maximum 16 KiB).": "", + "Select less text (maximum 16 KiB).": "Selecione menos texto (máximo de 16 KiB).", "Select loaded files": "Selecionar arquivos carregados", "Select Method": "Selecione o método", "Select model": "Selecione o modelo", @@ -2545,13 +2545,13 @@ "Service Account": "Conta de Serviço", "Services": "Serviços", "Session": "Sessão", - "Session details": "", + "Session details": "Detalhes da sessão", "Session expired. Please sign in again.": "Sessão expirada. Por favor, faça login novamente.", - "Session options": "", - "Session summary": "", - "Session visualization": "", - "Sessions": "", - "Sessions by recorded token usage": "", + "Session options": "Opções da sessão", + "Session summary": "Resumo das sessões", + "Session visualization": "Visualização da sessão", + "Sessions": "Sessões", + "Sessions by recorded token usage": "Sessões por uso de tokens registrado", "Set a local zoom level for the app interface.": "Defina um nível de zoom local para a interface do aplicativo.", "Set as default": "Definir como padrão", "Set as Pinned Model": "Definir como modelo fixado", @@ -2857,14 +2857,14 @@ "settings.admin.documents.embeddingBatchSize.label": "Tamanho do Lote de Embedding", "settings.admin.documents.embeddingConcurrentRequests.description": "Número máximo de solicitações simultâneas de embedding. Defina como 0 para não limitar.", "settings.admin.documents.embeddingConcurrentRequests.label": "Solicitações Simultâneas de Embedding", - "settings.admin.documents.embeddingContentPrefix.description": "", - "settings.admin.documents.embeddingContentPrefix.label": "", + "settings.admin.documents.embeddingContentPrefix.description": "Adicionado antes do conteúdo ao gerar o embedding. Inclua os espaços finais necessários. Reindexe os dados existentes após alterar isso.", + "settings.admin.documents.embeddingContentPrefix.label": "Prefixo do conteúdo", "settings.admin.documents.embeddingModel.description": "Modelo usado para gerar embeddings. Reindexe o conhecimento após alterá-lo.", "settings.admin.documents.embeddingModel.label": "Modelo de Embedding", "settings.admin.documents.embeddingModelEngine.description": "Provedor usado para gerar embeddings de documentos.", "settings.admin.documents.embeddingModelEngine.label": "Motor do Modelo de Embedding", - "settings.admin.documents.embeddingQueryPrefix.description": "", - "settings.admin.documents.embeddingQueryPrefix.label": "", + "settings.admin.documents.embeddingQueryPrefix.description": "Adicionado antes das consultas de pesquisa ao gerar o embedding. Inclua os espaços finais necessários.", + "settings.admin.documents.embeddingQueryPrefix.label": "Prefixo da consulta", "settings.admin.documents.endpoint.description": "Endpoint do Document Intelligence usado para análise.", "settings.admin.documents.endpoint.label": "Endpoint", "settings.admin.documents.enrichHybridSearchText.description": "Adicione nomes de arquivos, títulos, seções e trechos para melhorar a recuperação lexical.", @@ -2904,8 +2904,8 @@ "settings.admin.documents.mistralOcrApiBaseUrl.label": "URL Base da API", "settings.admin.documents.mistralOcrApiKey.description": "Chave de API enviada ao Mistral OCR.", "settings.admin.documents.mistralOcrApiKey.label": "Chave API", - "settings.admin.documents.mistralOcrParams.description": "", - "settings.admin.documents.mistralOcrParams.label": "", + "settings.admin.documents.mistralOcrParams.description": "Parâmetros adicionais da solicitação ao Mistral OCR em formato JSON, como o modelo.", + "settings.admin.documents.mistralOcrParams.label": "Parâmetros", "settings.admin.documents.ollamakey.description": "Chave de API opcional para solicitações ao Ollama.", "settings.admin.documents.ollamakey.label": "Chave API", "settings.admin.documents.ollamaurl.description": "Endpoint do Ollama usado para embeddings.", @@ -3707,10 +3707,10 @@ "Share to Open WebUI Community": "Compartilhar com a Comunidade Open WebUI", "Share your background and interests": "Fale sobre você e seus interesses", "Shared": "Compartilhado", - "Shared chat": "", + "Shared chat": "Chat compartilhado", "Shared Chats": "Chats compartilhados", - "Shared note": "", - "Shared snapshot": "", + "Shared note": "Nota compartilhada", + "Shared snapshot": "Cópia compartilhada", "Shared with you": "Compartilhado com você", "Sharing mode": "Modo de compartilhamento", "Sharing Permissions": "Permissões de compartilhamento", @@ -3736,7 +3736,7 @@ "Show Model": "Mostrar modelo", "Show more": "Exibir mais", "Show or switch the current model.": "Mostre ou troque o modelo atual.", - "Show preview": "", + "Show preview": "Mostrar pré-visualização", "Show Shortcuts": "Mostrar Atalhos", "Show the floating quick-action toolbar in chat.": "Mostre a barra de ferramentas flutuante de ações rápidas no chat.", "Show your support!": "Mostre seu apoio!", @@ -3791,7 +3791,7 @@ "Sort": "Ordenar", "Sort by": "Ordenar por", "Source": "Fonte", - "Span": "", + "Span": "Duração", "Speaking": "Falando", "Specific users or groups": "Usuários ou grupos específicos", "Speech recognition error: {{error}}": "Erro de reconhecimento de fala: {{error}}", @@ -3807,8 +3807,8 @@ "Start of the channel": "Início do canal", "Start Tag": "Tag inicial", "Start the chat to use this terminal.": "Inicie o chat para usar este terminal.", - "Start time": "", - "Start/end times not recorded; bars compare durations only.": "", + "Start time": "Hora de início", + "Start/end times not recorded; bars compare durations only.": "Horários de início/fim não registrados; as barras comparam apenas as durações.", "Starting in {{count}} minutes_one": "Começando em {{count}} minuto", "Starting in {{count}} minutes_many": "Começando em {{count}} minutos", "Starting in {{count}} minutes_other": "Começando em {{count}} minutos", @@ -3832,7 +3832,7 @@ "Streamable HTTP": "HTTP com streaming", "Strikethrough": "Tachado", "Su_day_of_week": "Dom", - "Sub-agent": "", + "Sub-agent": "Subagente", "Submit": "Enviar", "Submit answers": "Enviar respostas", "Submit question": "Enviar pergunta", @@ -3847,7 +3847,7 @@ "Sun": "Dom", "Support": "Suporte", "Support this plugin:": "Apoie este plugin:", - "Supported parameters": "", + "Supported parameters": "Parâmetros suportados", "Swap": "Inverter", "Swap sides": "Inverter lados", "Switch camera": "Alternar câmera", @@ -3899,7 +3899,7 @@ "Test succeeded.": "Teste bem-sucedido.", "Test the source before creating it.": "Teste a fonte antes de criá-la.", "Test the source before saving it.": "Teste a fonte antes de salvá-la.", - "Text": "", + "Text": "Texto", "Text only": "Somente texto", "Th_day_of_week": "Qui", "Thanks for your feedback!": "Obrigado pelo seu comentário!", @@ -3936,9 +3936,9 @@ "This option controls how long the model will stay loaded into memory following the request (default: 5m)": "Esta opção controla por quanto tempo o modelo permanecerá carregado na memória após a solicitação (padrão: 5m)", "This option controls how many tokens are preserved when refreshing the context. For example, if set to 2, the last 2 tokens of the conversation context will be retained. Preserving context can help maintain the continuity of a conversation, but it may reduce the ability to respond to new topics.": "Esta opção controla quantos tokens são preservados ao atualizar o contexto. Por exemplo, se definido como 2, os últimos 2 tokens do contexto da conversa serão mantidos. Preservar o contexto pode ajudar a manter a continuidade de uma conversa, mas pode reduzir a capacidade de responder a novos tópicos.", "This option sets the maximum number of tokens the model can generate in its response. Increasing this limit allows the model to provide longer answers, but it may also increase the likelihood of unhelpful or irrelevant content being generated.": "Esta opção define o número máximo de tokens que o modelo pode gerar em sua resposta. Aumentar esse limite permite que o modelo forneça respostas mais longas, mas também pode aumentar a probabilidade de geração de conteúdo inútil ou irrelevante.", - "This page no longer exists": "", + "This page no longer exists": "Esta página não existe mais", "This response was generated by \"{{model}}\"": "Esta resposta foi gerada por \"{{model}}\"", - "This skill has a newer version. Your draft is preserved.": "", + "This skill has a newer version. Your draft is preserved.": "Esta skill tem uma versão mais recente. Seu rascunho foi preservado.", "This template contains multiple context placeholders ([context] or {{CONTEXT}}). Context will be injected at each occurrence.": "Este template contém múltiplos marcadores de contexto ([context] ou {{CONTEXT}}). O contexto será injetado em cada ocorrência.", "This user will need to sign in again on every device. API keys remain active.": "Este usuário precisará entrar novamente em todos os dispositivos. As chaves de API permanecem ativas.", "This will delete": "Isso vai excluir", @@ -3947,7 +3947,7 @@ "This will delete the cached model and cannot be undone.": "Isso excluirá o modelo em cache e não pode ser desfeito.", "This will permanently delete the calendar \"{{name}}\" and all its events. This action cannot be undone.": "Esta ação excluirá permanentemente o calendário \"{{name}}\" e todos os seus eventos. Esta ação não pode ser desfeita.", "This will remove all files and directories from this knowledge base. This action cannot be undone.": "Isso removerá todos os arquivos e diretórios desta base de conhecimento. Esta ação não pode ser desfeita.", - "This will replace the current API key. Integrations using the old key will stop working.": "", + "This will replace the current API key. Integrations using the old key will stop working.": "Isso substituirá a chave API atual. As integrações que usam a chave antiga deixarão de funcionar.", "This will reset the saved settings for this base model to their defaults. The model will remain available.": "Isso redefinirá as configurações salvas deste modelo base para os valores padrão. O modelo continuará disponível.", "This will revoke the current API key.": "Isso revogará a chave de API atual.", "Thorough explanation": "Explicação detalhada", @@ -3965,8 +3965,8 @@ "Tika Server URL required.": "URL do servidor Tika necessária.", "Tiktoken": "Tiktoken", "Time": "Tempo", - "Time from first timed operation on this page.": "", - "Timeline": "", + "Time from first timed operation on this page.": "Tempo desde a primeira operação cronometrada nesta página.", + "Timeline": "Linha do tempo", "Timeout": "Tempo limite", "Timer": "Temporizador", "Title": "Título", @@ -3993,7 +3993,7 @@ "Toggle details": "Alternar detalhes", "Toggle Dictation": "Alternar Ditado", "Toggle Mute": "Alternar Mudo", - "Toggle pages": "", + "Toggle pages": "Mostrar/ocultar páginas", "Toggle Sidebar": "Alternar barra lateral", "Toggle status history": "Alternar histórico de status", "Toggle temporary chat for this new chat.": "Alterne o chat temporário para este novo chat.", @@ -4002,12 +4002,12 @@ "Token activity": "Atividade de tokens", "Token counts are estimates and may not reflect actual API usage": "A contagem de tokens é uma estimativa e pode não refletir o uso real da API.", "Token share": "% dos tokens", - "Token usage not recorded": "", + "Token usage not recorded": "Uso de tokens não registrado", "tokens": "tokens", "Tokens": "Tokens", "Too verbose": "Muito detalhado", "tool": "ferramenta", - "Tool call": "", + "Tool call": "Chamada de ferramenta", "Tool created successfully": "Ferramenta criada com sucesso", "Tool deleted successfully": "Ferramenta excluída com sucesso", "Tool Description": "Descrição da ferramenta", @@ -4017,7 +4017,7 @@ "Tool Menu": "Menu de ferramentas", "Tool Name": "Nome da ferramenta", "Tool Permissions": "Permissões de Ferramentas", - "Tool result": "", + "Tool result": "Resultado da ferramenta", "Tool Servers": "Servidores de ferramentas", "Tool updated successfully": "Ferramenta atualizada com sucesso", "Tools": "Ferramentas", @@ -4027,11 +4027,11 @@ "Tools Public Sharing": "Compartilhamento Público de Ferramentas", "Tools Sharing": "Compartilhamento de Ferramentas", "Top": "Top", - "Top level": "", + "Top level": "Nível principal", "Total": "Total", "Total chats": "Total de chats", "Total Tokens": "Total de Tokens", - "Trace filter": "", + "Trace filter": "Filtro do rastreamento", "Transformers": "Transformers", "Translation": "Tradução", "Translation key": "Chave de tradução", @@ -4054,8 +4054,8 @@ "Ultra-fast": "Ultrarrápido", "Unable to copy link": "Não foi possível copiar o link", "Unable to load analytics. Please try again.": "Não foi possível carregar as análises. Tente novamente.", - "Unable to load session.": "", - "Unable to load sessions.": "", + "Unable to load session.": "Não foi possível carregar a sessão.", + "Unable to load sessions.": "Não foi possível carregar as sessões.", "Unable to load tools": "Não foi possível carregar as ferramentas", "Unarchive": "Desarquivar", "Unarchive Chat": "Desarquivar Chat", @@ -4091,7 +4091,7 @@ "Unsupported input format": "Formato de entrada não suportado", "Untagged": "Sem tag", "Untitled": "Sem título", - "Untitled chat": "", + "Untitled chat": "Chat sem título", "Update": "Atualizar", "Update All Models": "Atualizar Todos os Modelos", "Update and Copy Link": "Atualizar e Copiar Link", @@ -4195,7 +4195,7 @@ "Version {{selectedVersion}} of {{totalVersions}}": "Versão {{selectedVersion}} de {{totalVersions}}", "Version deleted": "Versão excluída", "Vertical Layout": "Layout Vertical", - "Video": "", + "Video": "Vídeo", "Video player": "Reprodutor de vídeo", "View": "Visualizar", "View channel": "Ver canal", From 8650cd2dd526566b325d9f939419cf91b61f674b Mon Sep 17 00:00:00 2001 From: Classic298 <27028174+Classic298@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:09:02 +0100 Subject: [PATCH 006/160] feat: generate a title when renaming a chat from the top bar (#33382) Renaming a chat from the top bar had no way to generate a title, while the sidebar rename has a sparkle button for it. The rename field in the top bar now has the same button: it generates a title from the conversation and saves it right away, like the sidebar does. If you switch chats while the title is generating, it still goes to the original chat and does not show up on the one you switched to. --- src/lib/components/chat/Navbar.svelte | 51 +++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/src/lib/components/chat/Navbar.svelte b/src/lib/components/chat/Navbar.svelte index 67b54148d3..5be6010847 100644 --- a/src/lib/components/chat/Navbar.svelte +++ b/src/lib/components/chat/Navbar.svelte @@ -37,8 +37,12 @@ import ChatPlus from '../icons/ChatPlus.svelte'; import ChatCheck from '../icons/ChatCheck.svelte'; import Knobs from '../icons/Knobs.svelte'; + import Sparkles from '$lib/components/layout/Sidebar/icons/Sparkles.svelte'; import { isTemporaryChatId } from '$lib/utils/chatId'; + import { createMessagesList } from '$lib/utils'; + import { generateTitle } from '$lib/apis'; import { updateChatById } from '$lib/apis/chats'; + import { getOutputText } from './Messages/structuredOutput'; import { refreshChatList, refreshFolderChatLists } from '$lib/stores/chatList'; import ChatParticipants from '$lib/components/common/ChatParticipants.svelte'; @@ -75,6 +79,7 @@ let confirmEdit = false; let chatTitle = ''; let chatTitleInput: HTMLInputElement; + let generating = false; const renameHandler = async () => { chatTitle = title || chat?.chat?.title || ''; @@ -88,7 +93,8 @@ }; const editChatTitle = async () => { - if (!confirmEdit) return; + // Disabling the field to generate a title blurs it, which would save the empty field + if (!confirmEdit || generating) return; confirmEdit = false; const newTitle = chatTitle.trim(); @@ -106,10 +112,34 @@ ); if (!res) return; - _chatTitle.set(newTitle); + if (chat.id === $chatId) { + _chatTitle.set(newTitle); + } await refreshChatList(localStorage.token, { refreshPinned: true }); await refreshFolderChatLists(); }; + + const generateTitleHandler = async () => { + generating = true; + chatTitle = ''; + + const messages = createMessagesList(history, history.currentId).map((message) => ({ + role: message.role, + content: getOutputText(message.output) || message.content || '' + })); + const model = chat.chat.models.find((modelId: string) => modelId) ?? ''; + + const generatedTitle = await generateTitle(localStorage.token, model, messages).catch( + (error) => { + toast.error(`${error}`); + return null; + } + ); + generating = false; + + chatTitle = generatedTitle || title; + await editChatTitle(); + }; @@ -170,6 +200,8 @@ bind:value={chatTitle} class="min-w-0 flex-1 bg-transparent py-1 text-[0.9375rem] font-normal text-gray-700 outline-hidden dark:text-gray-300" aria-label={$i18n.t('Title')} + placeholder={generating ? $i18n.t('Generating...') : ''} + disabled={generating} on:keydown={(e) => { if (e.isComposing || e.keyCode === 229) return; @@ -183,6 +215,21 @@ }} on:blur={editChatTitle} /> + + + + {:else}

Date: Thu, 29 Oct 2026 20:51:10 +0100 Subject: [PATCH 007/160] feat: raise the default tool-call iteration limit per response to 1024 (#33384) With native function calling, each model turn that calls tools counts as one iteration, and a single response was stopped with "Tool-call limit reached (256 iterations)." after 256 of them. The CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS environment variable now defaults to 1024, also when it is set empty or to something that is not a number, and the error shows the new number. A model stuck calling tools in a loop now runs up to 1024 iterations before it is stopped; setting the variable to 256 keeps the old limit, and -1 still means no limit. --- backend/open_webui/env.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/open_webui/env.py b/backend/open_webui/env.py index 0e2797c3af..14e882ca42 100644 --- a/backend/open_webui/env.py +++ b/backend/open_webui/env.py @@ -1128,16 +1128,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: From 7618df3f53a8db2ad5352a789c88673a736b07a4 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 30 Oct 2026 07:08:28 +0900 Subject: [PATCH 008/160] refac --- backend/open_webui/config.py | 8 + backend/open_webui/models/knowledge.py | 68 +++++++- backend/open_webui/routers/files.py | 45 +++++- backend/open_webui/routers/knowledge.py | 150 +++++++++++++++--- backend/open_webui/routers/retrieval.py | 33 +++- src/lib/apis/knowledge/index.ts | 34 +++- .../admin/Settings/Documents.svelte | 33 ++++ src/lib/components/workspace/Knowledge.svelte | 4 +- .../workspace/Knowledge/KnowledgeBase.svelte | 137 +++++++++++++++- ...edgeBase.svelte => KnowledgeEditor.svelte} | 142 +++++++++++++---- src/lib/i18n/locales/en-US/translation.json | 13 +- 11 files changed, 588 insertions(+), 79 deletions(-) rename src/lib/components/workspace/Knowledge/{CreateKnowledgeBase.svelte => KnowledgeEditor.svelte} (52%) diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index fc9c5543b7..baf1ea4594 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -996,6 +996,12 @@ 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_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_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 @@ -3013,6 +3019,8 @@ 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_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, diff --git a/backend/open_webui/models/knowledge.py b/backend/open_webui/models/knowledge.py index b053344bc9..8e52cea70d 100644 --- a/backend/open_webui/models/knowledge.py +++ b/backend/open_webui/models/knowledge.py @@ -6,6 +6,7 @@ from typing import Optional from open_webui.config import RAG_FILE_CONTENT_SEARCH_MAX_CHARS 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, @@ -162,10 +163,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 +216,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()), @@ -671,6 +679,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 +718,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 +761,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 +818,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()), ) ) diff --git a/backend/open_webui/routers/files.py b/backend/open_webui/routers/files.py index 1f2292e753..f583b38880 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 @@ -136,6 +137,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 @@ -229,12 +238,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 +247,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 +370,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 +421,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( diff --git a/backend/open_webui/routers/knowledge.py b/backend/open_webui/routers/knowledge.py index 6b13b798cd..7b6e88feec 100644 --- a/backend/open_webui/routers/knowledge.py +++ b/backend/open_webui/routers/knowledge.py @@ -46,7 +46,7 @@ from open_webui.utils.access_control import filter_allowed_access_grants, has_pe 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.json_codec import JSONCodec -from pydantic import BaseModel +from pydantic import BaseModel, Field from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) @@ -1169,6 +1169,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 @@ -1402,6 +1408,65 @@ async def get_knowledge_files_by_id( ############################ +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('rag.file.max_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): file_id: str directory_id: Optional[str] = None @@ -1462,24 +1527,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, @@ -1943,6 +2018,18 @@ async def sync_knowledge_diff( if key not in manifest_keys: deleted.append({'file_id': file_info['file_id'], 'filename': key[1]}) + 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: @@ -2069,6 +2156,10 @@ async def add_files_to_knowledge_batch( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) + batch_limit = await Config.get('rag.file.max_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 +2203,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 +2233,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: diff --git a/backend/open_webui/routers/retrieval.py b/backend/open_webui/routers/retrieval.py index d2a6857c06..69005a3b22 100644 --- a/backend/open_webui/routers/retrieval.py +++ b/backend/open_webui/routers/retrieval.py @@ -305,6 +305,8 @@ 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_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 +686,8 @@ 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_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 +939,8 @@ class ConfigForm(BaseModel): # File upload settings FILE_MAX_SIZE: Union[int, str | None] = None FILE_MAX_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 +1004,33 @@ 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_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_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 +1145,8 @@ 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_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'], diff --git a/src/lib/apis/knowledge/index.ts b/src/lib/apis/knowledge/index.ts index d3a1780e9a..c6835ff208 100644 --- a/src/lib/apis/knowledge/index.ts +++ b/src/lib/apis/knowledge/index.ts @@ -1,10 +1,35 @@ import { WEBUI_API_BASE_URL } from '$lib/constants'; +type KnowledgeMeta = { + max_file_count: number | null; + max_file_size: number | null; +}; + +export const validateKnowledgeUpload = async ( + token: string, + id: string, + count: number, + removedFileIds: string[] = [], + fileSize?: number +) => { + const res = await fetch(`${WEBUI_API_BASE_URL}/knowledge/${id}/files/validate`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + }, + body: JSON.stringify({ count, removed_file_ids: removedFileIds, file_size: fileSize }) + }); + if (!res.ok) throw (await res.json()).detail; + return res.json(); +}; + export const createNewKnowledge = async ( token: string, name: string, description: string, - accessGrants: object[] + accessGrants: object[], + meta?: KnowledgeMeta ) => { let error = null; @@ -18,7 +43,8 @@ export const createNewKnowledge = async ( body: JSON.stringify({ name: name, description: description, - access_grants: accessGrants + access_grants: accessGrants, + meta: meta }) }) .then(async (res) => { @@ -605,6 +631,7 @@ export const streamPendingKnowledgeFiles = async (token: string, id: string) => }; type KnowledgeUpdateForm = { + meta?: KnowledgeMeta; name?: string; description?: string; data?: object; @@ -623,7 +650,8 @@ export const updateKnowledgeById = async (token: string, id: string, form: Knowl body: JSON.stringify({ name: form?.name ? form.name : undefined, description: form?.description ? form.description : undefined, - data: form?.data ? form.data : undefined + data: form?.data ? form.data : undefined, + meta: form.meta }) }) .then(async (res) => { diff --git a/src/lib/components/admin/Settings/Documents.svelte b/src/lib/components/admin/Settings/Documents.svelte index 9ac3656611..9d5678e1a3 100644 --- a/src/lib/components/admin/Settings/Documents.svelte +++ b/src/lib/components/admin/Settings/Documents.svelte @@ -282,6 +282,8 @@ // can distinguish "clear this field" from "don't change this field" FILE_MAX_SIZE: RAGConfig.FILE_MAX_SIZE ?? '', FILE_MAX_COUNT: RAGConfig.FILE_MAX_COUNT ?? '', + KNOWLEDGE_MAX_FILE_COUNT: RAGConfig.KNOWLEDGE_MAX_FILE_COUNT ?? '', + KNOWLEDGE_MAX_FILE_SIZE: RAGConfig.KNOWLEDGE_MAX_FILE_SIZE ?? '', FILE_IMAGE_COMPRESSION_WIDTH: RAGConfig.FILE_IMAGE_COMPRESSION_WIDTH ?? '', FILE_IMAGE_COMPRESSION_HEIGHT: RAGConfig.FILE_IMAGE_COMPRESSION_HEIGHT ?? '', ALLOWED_FILE_EXTENSIONS: RAGConfig.ALLOWED_FILE_EXTENSIONS.split(',') @@ -1591,6 +1593,37 @@

+
+ + + + + + +
+
- { closeCreateModal(); diff --git a/src/lib/components/workspace/Knowledge/KnowledgeBase.svelte b/src/lib/components/workspace/Knowledge/KnowledgeBase.svelte index c7a1edaf15..850ce952bb 100644 --- a/src/lib/components/workspace/Knowledge/KnowledgeBase.svelte +++ b/src/lib/components/workspace/Knowledge/KnowledgeBase.svelte @@ -3,6 +3,7 @@ import { v4 as uuidv4 } from 'uuid'; import { onMount, getContext, onDestroy } from 'svelte'; + import KnowledgeEditor from './KnowledgeEditor.svelte'; import KnowledgeBrowser from './KnowledgeBase/Browser.svelte'; import type { Writable } from 'svelte/store'; import type { i18n as i18nType } from 'i18next'; @@ -16,6 +17,7 @@ import { uploadFile } from '$lib/apis/files'; import { addFileToKnowledgeById, + validateKnowledgeUpload, getKnowledgeById, resetKnowledgeById, updateKnowledgeById, @@ -31,6 +33,11 @@ import { computeFileHash } from '$lib/utils/hash'; import Spinner from '$lib/components/common/Spinner.svelte'; + import Modal from '$lib/components/common/Modal.svelte'; + import Dropdown from '$lib/components/common/Dropdown.svelte'; + import DropdownMenu from '$lib/components/common/DropdownMenu.svelte'; + import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte'; + import Cog6 from '$lib/components/icons/Cog6.svelte'; import AddTextContentModal from './KnowledgeBase/AddTextContentModal.svelte'; @@ -51,12 +58,14 @@ let showAccessControlModal = false; let savedAccessGrants = []; let showResetConfirm = false; + let showSettings = false; type DirectoryFileEntry = { path: string; filename: string; file: File }; type DirectoryManifestEntry = DirectoryFileEntry & { checksum: string; size: number }; type Knowledge = { id: string; + user_id: string; name: string; description: string; data: { @@ -125,6 +134,35 @@ return file; }; + const validateUpload = async ( + count: number, + removedFileIds: string[] = [], + fileSize?: number + ) => { + if (!knowledge) return false; + if (count === 0) return true; + const maxCount = $config?.file?.max_count; + if (maxCount != null && count > maxCount) { + toast.error( + $i18n.t('You can only upload a maximum of {{maxCount}} file(s) per batch.', { maxCount }) + ); + return false; + } + try { + await validateKnowledgeUpload( + localStorage.token, + knowledge.id, + count, + removedFileIds, + fileSize + ); + return true; + } catch (error) { + toast.error(`${error}`); + return false; + } + }; + const uploadWeb = async (urls) => { const targetDirectoryId = currentDirectoryId; if (!knowledge) { @@ -135,6 +173,7 @@ if (!Array.isArray(urls)) { urls = [urls]; } + if (!(await validateUpload(urls.length))) return; const newFileItems = urls.map((url) => ({ type: 'file', @@ -331,6 +370,14 @@ // Rows go up front because each upload waits until its file is processed. const uploadFiles = async (files: File[]) => { + if ( + !(await validateUpload( + files.length, + [], + files.reduce((size, file) => Math.max(size, file.size), 0) + )) + ) + return; const uploads: { file: File; fileItem: { itemId: string; directory_id: string | null } }[] = []; for (const file of files) { const fileItem = createFileItem(file); @@ -529,6 +576,14 @@ const uploadDirectoryEntries = async (entries: DirectoryFileEntry[]) => { if (!knowledge) return; + if ( + !(await validateUpload( + entries.length, + [], + entries.reduce((size, entry) => Math.max(size, entry.file.size), 0) + )) + ) + return; const targetDirectoryId = currentDirectoryId; const targetPath = breadcrumbs.map((crumb) => crumb.name).join('/'); const getDirectoryUploadPath = (path: string) => @@ -603,6 +658,7 @@ ...diff.deleted.map((d: any) => d.file_id), ...diff.modified.map((m: any) => m.stale_file_id) ]; + if (!(await validateUpload(diff.added.length + diff.modified.length, staleFileIds))) return; if (staleFileIds.length > 0 || diff.rmdir.length > 0) { syncing = $i18n.t('Removing {{count}} stale files...', { count: staleFileIds.length }); @@ -779,6 +835,18 @@ } } + // A mixed drop is one batch, even though its upload paths differ. + if ( + !(await validateUpload( + looseFiles.length + directoryEntries.length, + [], + directoryEntries.reduce( + (size, entry) => Math.max(size, entry.file.size), + looseFiles.reduce((size, file) => Math.max(size, file.size), 0) + ) + )) + ) + return; await uploadFiles(looseFiles); if (directoryEntries.length > 0) { @@ -908,13 +976,45 @@ on:click={() => goto('/workspace/knowledge')} >{$i18n.t('Back')} - - {#if knowledge.write_access}{#if $user?.permissions?.sharing?.knowledge || $user?.role === 'admin'} { - savedAccessGrants = structuredClone(knowledge.access_grants ?? []); - showAccessControlModal = true; - }} - />{/if}{:else}{$i18n.t('Read Only')}{/if} +
+ {#if knowledge.write_access} + {#if $user?.permissions?.sharing?.knowledge || $user?.role === 'admin'} + { + savedAccessGrants = structuredClone(knowledge.access_grants ?? []); + showAccessControlModal = true; + }} + /> + {/if} + {:else} + {$i18n.t('Read Only')} + {/if} + {#if !isExternalKnowledge && (knowledge.user_id === $user?.id || $user?.role === 'admin')} + + +
+ + + +
+
+ {/if} +
{/if}
+ + {#if knowledge} + { + showSettings = false; + }} + onSaved={(saved) => { + if (!knowledge) return; + knowledge = { + ...knowledge, + name: saved.name, + description: saved.description, + meta: saved.meta + }; + showSettings = false; + }} + /> + {/if} + + void | Promise} */ export let onBack = () => goto('/workspace/knowledge'); - /** @type {(knowledge: { id: string }) => void | Promise} */ - export let onCreated = (knowledge) => goto(`/workspace/knowledge/${knowledge.id}`); + /** @type {(knowledge: { id: string; name: string; description: string; meta?: any; access_grants?: any[] }) => void | Promise} */ + export let onSaved = (knowledge) => goto(`/workspace/knowledge/${knowledge.id}`); let loading = false; - let name = ''; - let description = ''; + let name = knowledge?.name ?? ''; + let description = knowledge?.description ?? ''; /** @type {{ id?: string; principal_type: 'user' | 'group'; principal_id: string; permission: 'read' | 'write' }[]} */ let accessGrants = []; + let showAdvanced = false; + /** @type {number | undefined} */ + let maxFileCount = knowledge?.meta?.max_file_count || undefined; + /** @type {number | undefined} */ + let maxFileSize = knowledge?.meta?.max_file_size || undefined; const submitHandler = async () => { - loading = true; - + if (loading) return; if (name.trim() === '' || description.trim() === '') { toast.error($i18n.t('Please fill in all fields.')); - name = ''; - description = ''; - loading = false; return; } - const res = await createNewKnowledge(localStorage.token, name, description, accessGrants).catch( - (e) => { - toast.error(`${e}`); + loading = true; + const meta = { + max_file_count: maxFileCount ?? null, + max_file_size: maxFileSize ?? null + }; + try { + const res = + edit && knowledge + ? await updateKnowledgeById(localStorage.token, knowledge.id, { + name, + description, + meta + }) + : await createNewKnowledge(localStorage.token, name, description, accessGrants, meta); + if (res) { + toast.success($i18n.t(edit ? 'Saved' : 'Knowledge created successfully.')); + await onSaved(res); } - ); - - if (res) { - toast.success($i18n.t('Knowledge created successfully.')); - await onCreated(res); + } catch (error) { + toast.error(`${error}`); + } finally { + loading = false; } - - loading = false; };
{#if modal}
-

{$i18n.t('Create a knowledge base')}

+

+ {$i18n.t(edit ? 'Settings' : 'Create a knowledge base')} +

-
- -
+ {#if !edit} +
+ +
+ {/if} + + + + {#if showAdvanced} +
+
+
+ + +

{$i18n.t('Maximum total files.')}

+
+
+ + +

{$i18n.t('Maximum size per file.')}

+
+
+

+ {$i18n.t('Global limits always apply.')} +

+
+ {/if}
{#if modal} @@ -177,7 +249,7 @@ type="submit" disabled={loading} > -
{$i18n.t('Create Knowledge')}
+
{$i18n.t(edit ? 'Save' : 'Create Knowledge')}
{#if loading}
diff --git a/src/lib/i18n/locales/en-US/translation.json b/src/lib/i18n/locales/en-US/translation.json index 3e444dc8db..1147a9d29e 100644 --- a/src/lib/i18n/locales/en-US/translation.json +++ b/src/lib/i18n/locales/en-US/translation.json @@ -1,4 +1,11 @@ { + "Maximum total files.": "", + "Maximum size per file.": "", + "File count limit": "", + "File size limit (MB)": "", + "Use global setting": "", + "Global limits always apply.": "", + "You can only upload a maximum of {{maxCount}} file(s) per batch.": "", "- usage not recorded": "- usage not recorded", "- usage not recorded · * partial usage": "- usage not recorded · * partial usage", "-1 for no limit, or a positive integer for a specific limit": "", @@ -2870,8 +2877,12 @@ "settings.admin.documents.imageCompressionWidth.label": "Image Compression Width", "settings.admin.documents.markdownHeaderTextSplitter.description": "Split documents by markdown headers before character or token splitting.", "settings.admin.documents.markdownHeaderTextSplitter.label": "Markdown Header Text Splitter", - "settings.admin.documents.maxUploadCount.description": "Maximum number of files that can be used at once in chat.", + "settings.admin.documents.maxUploadCount.description": "Maximum number of files that can be used at once in chat or uploaded in one knowledge base batch.", "settings.admin.documents.maxUploadCount.label": "Max Upload Count", + "settings.admin.documents.knowledgeMaxSize.label": "Knowledge File Size Limit", + "settings.admin.documents.knowledgeMaxSize.description": "Maximum file size in MB per knowledge base. Leave empty for no limit.", + "settings.admin.documents.knowledgeMaxCount.label": "Knowledge File Count Limit", + "settings.admin.documents.knowledgeMaxCount.description": "Maximum total files per knowledge base. Leave empty for no limit.", "settings.admin.documents.maxUploadSize.description": "Maximum file size in MB. Leave empty for unlimited.", "settings.admin.documents.maxUploadSize.label": "Max Upload Size", "settings.admin.documents.mineruApiKey.description": "API key used for MinerU cloud mode.", From 5c4fb61d862b011cf9efda6b2289de637ba8d6bb Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 30 Oct 2026 07:15:50 +0900 Subject: [PATCH 009/160] refac --- backend/open_webui/config.py | 6 ++++++ backend/open_webui/routers/knowledge.py | 4 ++-- backend/open_webui/routers/retrieval.py | 6 ++++++ .../components/admin/Settings/Documents.svelte | 16 ++++++++++++++++ .../workspace/Knowledge/KnowledgeBase.svelte | 7 ------- src/lib/i18n/locales/en-US/translation.json | 4 +++- 6 files changed, 33 insertions(+), 10 deletions(-) diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index baf1ea4594..9c44a90994 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -996,8 +996,13 @@ 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: @@ -3019,6 +3024,7 @@ 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, diff --git a/backend/open_webui/routers/knowledge.py b/backend/open_webui/routers/knowledge.py index 7b6e88feec..08487bea6e 100644 --- a/backend/open_webui/routers/knowledge.py +++ b/backend/open_webui/routers/knowledge.py @@ -1418,7 +1418,7 @@ async def check_knowledge_upload_limits( db=None, ) -> None: if batch: - batch_limit = await Config.get('rag.file.max_count') + 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.') @@ -2156,7 +2156,7 @@ async def add_files_to_knowledge_batch( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) - batch_limit = await Config.get('rag.file.max_count') + 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.') diff --git a/backend/open_webui/routers/retrieval.py b/backend/open_webui/routers/retrieval.py index 69005a3b22..fe1db69ace 100644 --- a/backend/open_webui/routers/retrieval.py +++ b/backend/open_webui/routers/retrieval.py @@ -305,6 +305,7 @@ 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', @@ -686,6 +687,7 @@ 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'], @@ -939,6 +941,7 @@ 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 @@ -1007,6 +1010,7 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend 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', @@ -1016,6 +1020,7 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend 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'), ): @@ -1145,6 +1150,7 @@ 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'], diff --git a/src/lib/components/admin/Settings/Documents.svelte b/src/lib/components/admin/Settings/Documents.svelte index 9d5678e1a3..3f8405ab4a 100644 --- a/src/lib/components/admin/Settings/Documents.svelte +++ b/src/lib/components/admin/Settings/Documents.svelte @@ -282,6 +282,7 @@ // can distinguish "clear this field" from "don't change this field" FILE_MAX_SIZE: RAGConfig.FILE_MAX_SIZE ?? '', FILE_MAX_COUNT: RAGConfig.FILE_MAX_COUNT ?? '', + KNOWLEDGE_MAX_UPLOAD_COUNT: RAGConfig.KNOWLEDGE_MAX_UPLOAD_COUNT ?? '', KNOWLEDGE_MAX_FILE_COUNT: RAGConfig.KNOWLEDGE_MAX_FILE_COUNT ?? '', KNOWLEDGE_MAX_FILE_SIZE: RAGConfig.KNOWLEDGE_MAX_FILE_SIZE ?? '', FILE_IMAGE_COMPRESSION_WIDTH: RAGConfig.FILE_IMAGE_COMPRESSION_WIDTH ?? '', @@ -1593,6 +1594,21 @@
+ + + +
{ if (!knowledge) return false; if (count === 0) return true; - const maxCount = $config?.file?.max_count; - if (maxCount != null && count > maxCount) { - toast.error( - $i18n.t('You can only upload a maximum of {{maxCount}} file(s) per batch.', { maxCount }) - ); - return false; - } try { await validateKnowledgeUpload( localStorage.token, diff --git a/src/lib/i18n/locales/en-US/translation.json b/src/lib/i18n/locales/en-US/translation.json index 1147a9d29e..879509c1e3 100644 --- a/src/lib/i18n/locales/en-US/translation.json +++ b/src/lib/i18n/locales/en-US/translation.json @@ -2877,8 +2877,10 @@ "settings.admin.documents.imageCompressionWidth.label": "Image Compression Width", "settings.admin.documents.markdownHeaderTextSplitter.description": "Split documents by markdown headers before character or token splitting.", "settings.admin.documents.markdownHeaderTextSplitter.label": "Markdown Header Text Splitter", - "settings.admin.documents.maxUploadCount.description": "Maximum number of files that can be used at once in chat or uploaded in one knowledge base batch.", + "settings.admin.documents.maxUploadCount.description": "Maximum number of files that can be used at once in chat.", "settings.admin.documents.maxUploadCount.label": "Max Upload Count", + "settings.admin.documents.knowledgeMaxUploadCount.label": "Knowledge Batch Upload Limit", + "settings.admin.documents.knowledgeMaxUploadCount.description": "Maximum files per upload batch. Leave empty for no limit.", "settings.admin.documents.knowledgeMaxSize.label": "Knowledge File Size Limit", "settings.admin.documents.knowledgeMaxSize.description": "Maximum file size in MB per knowledge base. Leave empty for no limit.", "settings.admin.documents.knowledgeMaxCount.label": "Knowledge File Count Limit", From 0e0ba872a4d3e70c4e19e5c62b05fd7187b917f3 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 30 Oct 2026 07:50:55 +0900 Subject: [PATCH 010/160] refac --- backend/open_webui/routers/tools.py | 87 ++++++- backend/open_webui/utils/mcp/apps.py | 79 ++++++ backend/open_webui/utils/mcp/client.py | 91 ++++++- backend/open_webui/utils/middleware.py | 4 + backend/open_webui/utils/tools.py | 5 + package-lock.json | 136 ++++++++++- package.json | 1 + .../components/chat/Messages/MCPApp.svelte | 225 ++++++++++++++++++ .../Markdown/ConsecutiveDetailsGroup.svelte | 23 +- .../chat/Messages/ResponseMessage.svelte | 19 +- .../components/common/ToolCallDisplay.svelte | 21 +- 11 files changed, 651 insertions(+), 40 deletions(-) create mode 100644 backend/open_webui/utils/mcp/apps.py create mode 100644 src/lib/components/chat/Messages/MCPApp.svelte diff --git a/backend/open_webui/routers/tools.py b/backend/open_webui/routers/tools.py index 4176eaca97..b75ea7b4c7 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__) @@ -244,6 +246,85 @@ async def get_tool_specs(request: Request, id: str, user=Depends(get_verified_us ############################ +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]) async def get_tool_list(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): if not ENABLE_TOOLS: 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..a20d53e1bb 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -104,6 +104,7 @@ from open_webui.utils.filter import ( ) from open_webui.utils.json_codec import JSONCodec, dumps_bytes from open_webui.utils.memory import add_memory_context, review_memory_after_turn +from open_webui.utils.mcp.apps import MCPAppResult from open_webui.utils.misc import ( add_or_update_system_message, add_or_update_user_message, @@ -736,6 +737,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 diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index f04b7e07c7..5f3886c6cd 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -256,6 +256,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() diff --git a/package-lock.json b/package-lock.json index 3f3d943f76..d793425a27 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "@huggingface/transformers": "^3.0.0", "@joplin/turndown-plugin-gfm": "^1.0.62", "@mediapipe/tasks-vision": "^0.10.17", + "@modelcontextprotocol/ext-apps": "2.0.4", "@pixiv/three-vrm": "3.5.5", "@pixiv/three-vrm-animation": "3.5.5", "@pyscript/core": "^0.4.32", @@ -2293,6 +2294,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", @@ -7000,7 +7077,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 +8607,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 +8629,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 +10177,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 +10222,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 +11952,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 +12064,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 +13696,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 +13708,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 +16425,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 +16793,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..2ecea9eb8e 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "@huggingface/transformers": "^3.0.0", "@joplin/turndown-plugin-gfm": "^1.0.62", "@mediapipe/tasks-vision": "^0.10.17", + "@modelcontextprotocol/ext-apps": "2.0.4", "@pixiv/three-vrm": "3.5.5", "@pixiv/three-vrm-animation": "3.5.5", "@pyscript/core": "^0.4.32", diff --git a/src/lib/components/chat/Messages/MCPApp.svelte b/src/lib/components/chat/Messages/MCPApp.svelte new file mode 100644 index 0000000000..89c8bc4eca --- /dev/null +++ b/src/lib/components/chat/Messages/MCPApp.svelte @@ -0,0 +1,225 @@ + + + + +
+ {#if status}

{$i18n.t(status)}

{/if} + + {#if link}{$i18n.t('Open link')}{/if} +
+{#if showConfirmation} + confirmCall?.(true)} + on:cancel={() => confirmCall?.(false)} + > +
{confirmationText}
+
+{/if} diff --git a/src/lib/components/chat/Messages/Markdown/ConsecutiveDetailsGroup.svelte b/src/lib/components/chat/Messages/Markdown/ConsecutiveDetailsGroup.svelte index fe3b2ce4b5..62d8534034 100644 --- a/src/lib/components/chat/Messages/Markdown/ConsecutiveDetailsGroup.svelte +++ b/src/lib/components/chat/Messages/Markdown/ConsecutiveDetailsGroup.svelte @@ -13,6 +13,7 @@ import CheckCircle from '$lib/components/icons/CheckCircle.svelte'; import XMark from '$lib/components/icons/XMark.svelte'; import FullHeightIframe from '$lib/components/common/FullHeightIframe.svelte'; + import MCPApp, { type MCPAppEmbed } from '$lib/components/chat/Messages/MCPApp.svelte'; import { settings } from '$lib/stores'; @@ -127,7 +128,7 @@ $: allEmbeds = (() => { if (!allowEmbeds) return []; - const result: Array<{ name: string; embed: string; args: string }> = []; + const result: Array<{ name: string; embed: string | MCPAppEmbed; args: string }> = []; for (const t of tokens) { if (t?.attributes?.type !== 'tool_calls') continue; const raw = decode(t.attributes?.embeds ?? ''); @@ -313,14 +314,18 @@ {#if allEmbeds.length > 0} {#each allEmbeds as embedItem, idx}
- + {#if typeof embedItem.embed === 'object' && embedItem.embed?.type === 'mcp_app'} + {#key embedItem.embed}{/key} + {:else if typeof embedItem.embed === 'string'} + + {/if}
{/each} {/if} diff --git a/src/lib/components/chat/Messages/ResponseMessage.svelte b/src/lib/components/chat/Messages/ResponseMessage.svelte index d8a83d94e1..91bfa70cb4 100644 --- a/src/lib/components/chat/Messages/ResponseMessage.svelte +++ b/src/lib/components/chat/Messages/ResponseMessage.svelte @@ -72,6 +72,7 @@ import RegenerateMenu from './ResponseMessage/RegenerateMenu.svelte'; import StatusHistory from './ResponseMessage/StatusHistory.svelte'; import FullHeightIframe from '$lib/components/common/FullHeightIframe.svelte'; + import MCPApp from '$lib/components/chat/Messages/MCPApp.svelte'; import OutputEditView from './OutputEditView.svelte'; import { getOutputText, replaceOutputMessageText, type OutputItem } from './structuredOutput'; @@ -759,13 +760,17 @@ > {#each message.embeds as embed, idx}
- + {#if typeof embed === 'object' && embed?.type === 'mcp_app'} + {#key embed}{/key} + {:else if typeof embed === 'string'} + + {/if}
{/each}
diff --git a/src/lib/components/common/ToolCallDisplay.svelte b/src/lib/components/common/ToolCallDisplay.svelte index 3849397018..6d2470cc94 100644 --- a/src/lib/components/common/ToolCallDisplay.svelte +++ b/src/lib/components/common/ToolCallDisplay.svelte @@ -18,6 +18,7 @@ import XMark from '../icons/XMark.svelte'; import Image from './Image.svelte'; import FullHeightIframe from './FullHeightIframe.svelte'; + import MCPApp from '$lib/components/chat/Messages/MCPApp.svelte'; import { settings } from '$lib/stores'; export let id: string = ''; @@ -182,14 +183,18 @@
{#each embeds as embed, idx}
- + {#if typeof embed === 'object' && embed?.type === 'mcp_app'} + {#key embed}{/key} + {:else if typeof embed === 'string'} + + {/if}
{/each}
From 4ab90a6c1ff9526640e73ad37e67e88e693e2172 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 30 Oct 2026 07:55:43 +0900 Subject: [PATCH 011/160] refac --- .../components/chat/Messages/MCPApp.svelte | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/lib/components/chat/Messages/MCPApp.svelte b/src/lib/components/chat/Messages/MCPApp.svelte index 89c8bc4eca..66268bd7a3 100644 --- a/src/lib/components/chat/Messages/MCPApp.svelte +++ b/src/lib/components/chat/Messages/MCPApp.svelte @@ -16,6 +16,7 @@ import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge'; import { WEBUI_API_BASE_URL, WEBUI_VERSION } from '$lib/constants'; import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte'; + import Spinner from '$lib/components/common/Spinner.svelte'; import { injectCsp } from '$lib/utils/csp'; export let app: MCPAppEmbed; @@ -25,7 +26,7 @@ let bridge: AppBridge | undefined; let initialized = false; let closing = false; - let status = 'Loading widget…'; + let status = ''; let link = ''; let showConfirmation = false; let confirmationText = ''; @@ -34,7 +35,7 @@ let loadTimeout: ReturnType; async function rpc(method: string, params: object, signal?: AbortSignal) { - if (closing) throw new Error('Widget closed'); + if (closing) throw new Error('App closed'); const response = await fetch( `${WEBUI_API_BASE_URL}/tools/id/${encodeURIComponent(`server:mcp:${app.server_id}`)}/mcp/app/rpc`, { @@ -54,9 +55,7 @@ if (!response.ok) { const error = await response.json().catch(() => null); throw new Error( - typeof error?.detail === 'string' - ? error.detail - : `Widget request failed (${response.status})` + typeof error?.detail === 'string' ? error.detail : `App request failed (${response.status})` ); } return response.json(); @@ -138,7 +137,7 @@ void bridge!.sendToolResult(app.result); }; bridge.onerror = () => { - status = 'Widget communication failed'; + status = 'App communication failed'; }; observer = new ResizeObserver(() => { if (initialized) @@ -186,7 +185,7 @@ onMount(() => { loadTimeout = setTimeout(() => { - status = 'Widget did not initialize'; + status = 'App did not initialize'; stop(); }, 30000); void start().catch((error) => { @@ -199,12 +198,22 @@ onDestroy(stop); -
- {#if status}

{$i18n.t(status)}

{/if} +
+ {#if status} +

{$i18n.t(status)}

+ {:else if !initialized && !closing} +
+ +
+ {/if} {/key} + {:else}
+ {$i18n.t('Enter a URL to browse.')} +
{/if} +
+
diff --git a/src/lib/components/chat/ChatControls/Embeds.svelte b/src/lib/components/chat/ChatTabs/Embeds.svelte similarity index 100% rename from src/lib/components/chat/ChatControls/Embeds.svelte rename to src/lib/components/chat/ChatTabs/Embeds.svelte diff --git a/src/lib/components/chat/ChatControls/UntitledFile.svelte b/src/lib/components/chat/ChatTabs/UntitledFile.svelte similarity index 100% rename from src/lib/components/chat/ChatControls/UntitledFile.svelte rename to src/lib/components/chat/ChatTabs/UntitledFile.svelte diff --git a/src/lib/components/chat/ChatControls/tabs.ts b/src/lib/components/chat/ChatTabs/tabs.ts similarity index 97% rename from src/lib/components/chat/ChatControls/tabs.ts rename to src/lib/components/chat/ChatTabs/tabs.ts index ad9c56fd31..b35746c157 100644 --- a/src/lib/components/chat/ChatControls/tabs.ts +++ b/src/lib/components/chat/ChatTabs/tabs.ts @@ -5,6 +5,7 @@ export type PanelTabKind = | 'files' | 'file' | 'terminal' + | 'browser' | 'artifacts' | 'preview' | 'voice' @@ -19,6 +20,7 @@ export type PanelTab = { dirty?: boolean; untitled?: boolean; connection?: TerminalConnection; + browserBaseUrl?: string; context?: TerminalContext | null; }; export type PanelTabs = { tabs: PanelTab[]; activeId: string; history: string[] }; diff --git a/src/lib/components/chat/FileNav.svelte b/src/lib/components/chat/FileNav.svelte index 7437e9d186..813c88daef 100644 --- a/src/lib/components/chat/FileNav.svelte +++ b/src/lib/components/chat/FileNav.svelte @@ -16,7 +16,6 @@ } from '$lib/stores'; import { getCwd, - getTerminalConfig, getFileMatches, listFiles, readFile, @@ -54,7 +53,7 @@ import FileTypeIcon from './FileNav/FileTypeIcon.svelte'; import BulkActionBar from './FileNav/BulkActionBar.svelte'; import PortList from './FileNav/PortList.svelte'; - import PortPreview from './FileNav/PortPreview.svelte'; + import Browser from './ChatTabs/Browser.svelte'; import TerminalDock from './TerminalDock.svelte'; // Directory and preview state belong to this tab, including its terminal connection. @@ -74,6 +73,7 @@ export let showTerminalDock = true; export let onOpenFile: ((path: string, page?: number | null) => void) | null = null; export let onBrowseDirectory: ((path: string) => void) | null = null; + export let onOpenPort: ((port: number, baseUrl: string) => void) | null = null; $: effectiveTerminalId = terminalId ?? $selectedTerminalId; export let chatId: string | null = null; @@ -268,12 +268,12 @@ await tick(); }; - // ── Terminal panel state ──────────────────────────────────────────── + // ── Sessions panel state ──────────────────────────────────────────── let terminalExpanded = false; + let hasSessions = false; let terminalHeight = 200; // px, default when expanded let isDraggingHandle = false; let containerEl: HTMLElement; - let terminalEnabled = true; type ComparisonFile = { name: string; path: string; size?: number }; let pinnedComparison: ComparisonFile | null = null; let comparison: { @@ -359,6 +359,15 @@ let loadingDirs: Set = new Set(); let directoryMenu: { x: number; y: number } | null = null; let searchQuery = ''; + let showSearch = false; + let searchInput: HTMLInputElement; + const toggleSearch = async () => { + showSearch = !showSearch; + if (!showSearch) searchQuery = ''; + await tick(); + if (showSearch) searchInput?.focus(); + else containerEl?.querySelector('[data-file-search-toggle]')?.focus(); + }; let matchResults: TerminalFileMatch[] | null = null; let matchLoading = false; let matchLoadingMore = false; @@ -694,12 +703,6 @@ entries = []; resetTreeState(); (async () => { - if (terminalChanged) { - const config = await getTerminalConfig(terminal.url, terminal.key); - if (disposed) return; - terminalEnabled = config?.features?.terminal !== false; - } - savedPath = applyCwd(await getCwd(terminal.url, terminal.key, chatId ?? undefined)); loadDir(savedPath); })(); @@ -1916,10 +1919,6 @@ loading = true; void (async () => { - // Discover server features on initial mount - const config = await getTerminalConfig(terminal.url, terminal.key); - terminalEnabled = config?.features?.terminal !== false; - const serverCwd = await getCwd(terminal.url, terminal.key, chatId ?? undefined); if (disposed) return; const serverPath = applyCwd(serverCwd); @@ -2100,6 +2099,8 @@ breadcrumbs={buildBreadcrumbs(currentPath)} {selectedFile} {loading} + {showSearch} + onToggleSearch={toggleSearch} writable={currentWritable} canGoBack={!initialFile && canGoBack} canGoForward={!initialFile && canGoForward} @@ -2132,7 +2133,7 @@ {#if (isMarkdown || isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null && !editing}
{/if} - - {#if terminalEnabled && showTerminalDock} -
+ + {#if showTerminalDock} +
{#if terminalExpanded} @@ -2741,6 +2757,7 @@ void = () => {}; export let onRefresh: () => void = () => {}; + export let showSearch = false; + export let onToggleSearch: (() => void) | null = null; export let onNewFolder: () => void = () => {}; export let onNewFile: () => void = () => {}; export let onUploadFiles: (files: File[]) => void = () => {}; @@ -65,7 +67,7 @@
+ {#if onToggleSearch} + + + + {/if} - - - - - - - - - - - - - -
- -
- - - - - - - - - - -
- - - {#if isLoading} -
-
-
- {/if} - - -
- {#if overlay} -
- {/if} - {#key iframeKey} - {/key} - {:else}
- {$i18n.t('Enter a URL to browse.')} + {:else}
+
+
+ + {$i18n.t('Browser')} +
+ {#if connection} +
+ navigate(`http://localhost:${event.detail}/`)} + /> +
+ {/if} +
{/if}
diff --git a/src/lib/components/chat/FileNav.svelte b/src/lib/components/chat/FileNav.svelte index 813c88daef..471983f104 100644 --- a/src/lib/components/chat/FileNav.svelte +++ b/src/lib/components/chat/FileNav.svelte @@ -52,8 +52,6 @@ import Icon from './FileNav/Icon.svelte'; import FileTypeIcon from './FileNav/FileTypeIcon.svelte'; import BulkActionBar from './FileNav/BulkActionBar.svelte'; - import PortList from './FileNav/PortList.svelte'; - import Browser from './ChatTabs/Browser.svelte'; import TerminalDock from './TerminalDock.svelte'; // Directory and preview state belong to this tab, including its terminal connection. @@ -73,7 +71,6 @@ export let showTerminalDock = true; export let onOpenFile: ((path: string, page?: number | null) => void) | null = null; export let onBrowseDirectory: ((path: string) => void) | null = null; - export let onOpenPort: ((port: number, baseUrl: string) => void) | null = null; $: effectiveTerminalId = terminalId ?? $selectedTerminalId; export let chatId: string | null = null; @@ -233,10 +230,6 @@ return structuredClone(openedFile); }; - $: if (previewPort !== null && openedFile) { - openedFile = null; - if (terminalContext) terminalContext = { ...terminalContext, file: null }; - } $: { (selectedFile, effectiveTerminalId, chatId); fileAsk = null; @@ -555,7 +548,6 @@ // ── File preview state ─────────────────────────────────────────────── let selectedFile: string | null = null; let selectedFileWritable = true; - let previewPort: number | null = null; let fileContent: string | null = null; let fileImageUrl: string | null = null; let fileVideoUrl: string | null = null; @@ -681,7 +673,6 @@ comparison = null; pinnedComparison = null; } - if (chatChanged || terminalChanged || !terminal) previewPort = null; if (mounted && terminal) { if (chatChanged && chatId && !oldChatId) { @@ -795,13 +786,12 @@ terminal: { url: string; key: string } | null, path: string, hiddenVisible: boolean, - activeFile: string | null, - activePort: number | null + activeFile: string | null ) => { clearMatchRequest(); matchRequestId += 1; const requestId = matchRequestId; - if (!query || !terminal || activeFile || activePort !== null) { + if (!query || !terminal || activeFile) { resetMatches(); return; } @@ -841,14 +831,7 @@ }, 200); }; - $: queueFileSearch( - searchText, - selectedTerminal, - currentPath, - showHidden, - selectedFile, - previewPort - ); + $: queueFileSearch(searchText, selectedTerminal, currentPath, showHidden, selectedFile); const loadMoreMatches = async () => { const offset = nextMatchOffset; @@ -1018,7 +1001,6 @@ error = null; selectedFile = null; selectedFileWritable = true; - previewPort = null; clearFilePreview(); clearSelection(); currentPath = directory; @@ -2094,249 +2076,247 @@
{/if} - {#if previewPort === null} - { - if (selectedFile) { - const fileName = selectedFile.split('/').pop() ?? ''; - openEntry({ name: fileName, type: 'file', size: 0 }); - } else { - refreshBrowser(); - } - }} - onNewFolder={startNewFolder} - onNewFile={startNewFile} - onUploadFiles={handleUploadFiles} - onUploadFolder={() => openUploadPicker(true)} - onDownloadDir={() => downloadFile(currentPath)} - onMove={handleMovePaths} - onSort={toggleSort} - onToggleHidden={toggleHidden} - > - {#if (isMarkdown || isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null && !editing} - + { + if (selectedFile) { + const fileName = selectedFile.split('/').pop() ?? ''; + openEntry({ name: fileName, type: 'file', size: 0 }); + } else { + refreshBrowser(); + } + }} + onNewFolder={startNewFolder} + onNewFile={startNewFile} + onUploadFiles={handleUploadFiles} + onUploadFolder={() => openUploadPicker(true)} + onDownloadDir={() => downloadFile(currentPath)} + onMove={handleMovePaths} + onSort={toggleSort} + onToggleHidden={toggleHidden} + > + {#if (isMarkdown || isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null && !editing} + + + + {/if} + {#if isTextFile} + {#if isHtml && showRaw} + - {/if} - {#if isTextFile} - {#if isHtml && showRaw} - - - - {:else if isHtml} - - {:else if isMarkdown && showRaw} - - - - {:else if isMarkdown} - - {:else if isCode} - - - - {:else if editing} - - - - - - - {:else} - - - - {/if} - {/if} - - {#if fileContent !== null} - + {:else if isHtml} + + {:else if isMarkdown && showRaw} + + + + {:else if isMarkdown} + + {:else if isCode} + + + + {:else if editing} + + + + + + {:else} + + {/if} - + {/if} + + {#if fileContent !== null} + - - - - {#if !selectedFile && showSearch} -
- - { - if (event.key === 'Escape') { - event.preventDefault(); - event.stopPropagation(); - void toggleSearch(); + on:click={async () => { + if (await copyToClipboard(fileContent ?? '')) { + toast.success($i18n.t('Copied to clipboard')); } }} - /> - {#if searchQuery} - - {/if} -
- {/if} - - {#if pinnedComparison} -
- - {$i18n.t('Comparing with {{name}}', { name: pinnedComparison.name })} - - -
+ + +
{/if} + + + +
- - {#if selectedCount > 0 && !isSearching} - { - if (canCompare) - openComparison([ - comparisonFile(comparisonEntries[0]), - comparisonFile(comparisonEntries[1]) - ]); + {#if !selectedFile && showSearch} +
+ + { + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + void toggleSearch(); + } }} - canDelete={selectedEntriesWritable} - onDelete={() => { - deleteTarget = { path: '__bulk__', name: `${selectedCount} items` }; - showDeleteConfirm = true; - }} - onDownload={bulkDownload} - onSelectAll={selectAll} - onClear={clearSelection} /> - {/if} + {#if searchQuery} + + {/if} +
+ {/if} + + {#if pinnedComparison} +
+ + {$i18n.t('Comparing with {{name}}', { name: pinnedComparison.name })} + + +
+ {/if} + + + {#if selectedCount > 0 && !isSearching} + { + if (canCompare) + openComparison([ + comparisonFile(comparisonEntries[0]), + comparisonFile(comparisonEntries[1]) + ]); + }} + canDelete={selectedEntriesWritable} + onDelete={() => { + deleteTarget = { path: '__bulk__', name: `${selectedCount} items` }; + showDeleteConfirm = true; + }} + onDownload={bulkDownload} + onSelectAll={selectAll} + onClear={clearSelection} + /> {/if} {#if diskChanged}
0) clearSelection(); }} on:contextmenu={(e) => { - if (comparison || selectedFile || previewPort !== null || isSearching) return; + if (comparison || selectedFile || isSearching) return; if ((e.target as HTMLElement)?.closest('[data-file-row]')) return; e.preventDefault(); directoryMenu = { x: e.clientX, y: e.clientY }; }} > - {#if previewPort !== null} - { - previewPort = null; - }} - /> - {:else if selectedFile !== null} + {#if selectedFile !== null} {#if supportsComments(selectedFile) && selectedTerminal} {#key `${selectedTerminal.url}|${selectedTerminal.key}|${chatId}|${selectedFile}|${commentGeneration}`} - - {#if selectedTerminal && !selectedFile && previewPort === null && !isSearching} -
- {#key JSON.stringify([chatId, selectedTerminal.url])} - { - if (onOpenPort) { - onOpenPort(e.detail, previewBaseUrl); - return; - } - selectedFile = null; - clearFilePreview(); - previewPort = e.detail; - }} - /> - {/key} -
- {/if} - {#if showTerminalDock}
('i18n'); const dispatch = createEventDispatcher<{ previewPort: number }>(); export let baseUrl: string; + export let active = true; export let previewBaseUrl: string | null = null; export let apiKey: string; export let chatId: string | null = null; let ports: ListeningPort[] = []; - let expanded = false; let loading = false; let pollTimer: ReturnType | null = null; @@ -46,41 +46,34 @@ window.open(url, '_blank', 'noopener,noreferrer'); }; - // Start polling when baseUrl is available - $: if (baseUrl) { + // Only discover ports while the browser start view is visible. + $: if (baseUrl && active) { startPolling(); - } + } else stopPolling(); onDestroy(() => { stopPolling(); }); -
+
- +
- {#if expanded} -
- {#if ports.length === 0} -
- {$i18n.t('No servers detected')} -
- {:else} - {#each ports as port} -
+ {#if ports.length === 0} +
+ {$i18n.t('No servers detected')} +
+ {:else} + {#each ports as port} +
+ + + - - - -
- {/each} - {/if} -
- {/if} + +
+ {/each} + {/if} +
From 3e50233b13f48fdd7c0871c03ff966f09879b0c6 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 1 Nov 2026 21:46:47 +0900 Subject: [PATCH 119/160] refac --- src/lib/components/chat/ChatTabs/Browser.svelte | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/components/chat/ChatTabs/Browser.svelte b/src/lib/components/chat/ChatTabs/Browser.svelte index 3b37d02e14..6251131ed0 100644 --- a/src/lib/components/chat/ChatTabs/Browser.svelte +++ b/src/lib/components/chat/ChatTabs/Browser.svelte @@ -196,14 +196,14 @@ : ''} allow-forms allow-popups allow-modals allow-downloads" on:load={loaded} >{/key} - {:else}
+ {:else}
{$i18n.t('Browser')}
{#if connection} -
+
Date: Sun, 1 Nov 2026 22:26:40 +0900 Subject: [PATCH 120/160] refac --- src/lib/apis/terminal/git.ts | 94 ++ src/lib/components/chat/ChatTabs.svelte | 22 + .../components/chat/ChatTabs/GitBar.svelte | 993 ++++++++++++++++++ .../components/chat/ChatTabs/GitDiff.svelte | 132 +++ .../chat/ChatTabs/GitPullRequests.svelte | 506 +++++++++ 5 files changed, 1747 insertions(+) create mode 100644 src/lib/apis/terminal/git.ts create mode 100644 src/lib/components/chat/ChatTabs/GitBar.svelte create mode 100644 src/lib/components/chat/ChatTabs/GitDiff.svelte create mode 100644 src/lib/components/chat/ChatTabs/GitPullRequests.svelte diff --git a/src/lib/apis/terminal/git.ts b/src/lib/apis/terminal/git.ts new file mode 100644 index 0000000000..a7ae504b25 --- /dev/null +++ b/src/lib/apis/terminal/git.ts @@ -0,0 +1,94 @@ +import { get } from 'svelte/store'; +import { config } from '$lib/stores'; +import type { TerminalConnection } from './index'; + +export type GitFile = { + path: string; + original_path?: string; + status: string; + staged: boolean; + unstaged: boolean; + additions: number; + deletions: number; + binary?: boolean; +}; +export type GitStatus = { + is_repo: boolean; + root?: string; + branch: string; + head?: string; + upstream?: string; + ahead: number; + behind: number; + files: GitFile[]; +}; +export type GitCommit = { + hash: string; + short_hash: string; + author: string; + date: string; + message: string; +}; +export type GitBranch = { name: string; current: boolean; upstream: string; is_local?: boolean }; + +export async function gitRequest( + connection: TerminalConnection, + chatId: string | null, + directory: string, + operation: string, + params: Record = {}, + body?: Record, + method = body ? 'POST' : 'GET' +): Promise { + if (!get(config)?.features?.enable_tool_servers) throw new Error('Tool servers are disabled'); + const query = new URLSearchParams({ root: directory, ...params }); + const response = await fetch(`${connection.baseUrl}/git/${operation}?${query}`, { + method, + headers: { + Authorization: `Bearer ${connection.key.trim()}`, + ...(chatId ? { 'X-Session-Id': chatId } : {}), + ...(body ? { 'Content-Type': 'application/json' } : {}) + }, + ...(body ? { body: JSON.stringify({ root: directory, ...body }) } : {}) + }); + if (!response.ok) { + const error = await response.json().catch(() => null); + throw new Error( + typeof error?.detail === 'string' ? error.detail : `Git request failed (${response.status})` + ); + } + return response.json(); +} + +export function gitAction( + connection: TerminalConnection, + chatId: string | null, + directory: string, + action: string, + fields: Record +) { + let operation = action; + let method = 'POST'; + let body: Record = { ...fields }; + if (['stage', 'unstage', 'discard'].includes(action)) body = { files: fields.paths }; + if (action === 'branch') body = { name: fields.branch }; + if (action === 'worktree') { + operation = 'worktrees'; + body = { branch: fields.branch, path: fields.target }; + } + if (action === 'publish') { + operation = 'push'; + body = { set_upstream: true }; + } + if (action === 'rename_branch') { + operation = 'branch'; + method = 'PATCH'; + body = { old_name: fields.branch, new_name: fields.target }; + } + if (action === 'delete_branch') { + operation = 'branch'; + method = 'DELETE'; + body = { name: fields.branch }; + } + return gitRequest(connection, chatId, directory, operation, {}, body, method); +} diff --git a/src/lib/components/chat/ChatTabs.svelte b/src/lib/components/chat/ChatTabs.svelte index 9ecf6416c6..4403aff7aa 100644 --- a/src/lib/components/chat/ChatTabs.svelte +++ b/src/lib/components/chat/ChatTabs.svelte @@ -54,6 +54,7 @@ import Drawer from '../common/Drawer.svelte'; import MobileSwipePanel from '../common/MobileSwipePanel.svelte'; import ResizableSidePanel from '../common/ResizableSidePanel.svelte'; + import GitBar from './ChatTabs/GitBar.svelte'; import Artifacts from './Artifacts.svelte'; import Embeds from './ChatTabs/Embeds.svelte'; import FileNav from './FileNav.svelte'; @@ -159,6 +160,16 @@ $: activeTabId = tabs.activeId; $: activeTab = tabs.tabs.find((tab) => tab.id === tabs.activeId); $: terminalContext = fileContexts[tabs.activeId] ?? activeTab?.context ?? null; + $: gitConnection = + mounted && + tabs.tabs.length > 0 && + (tabs.tabs.find((tab) => tab.id === tabs.activeId)?.connection ?? + resolveTerminalConnection( + tabs.tabs.find((tab) => tab.id === tabs.activeId)?.terminalId ?? $selectedTerminalId, + $terminalServers ?? [], + directTerminals, + localStorage.token ?? '' + )); $: if (activeTabId && panelTarget) { const id = activeTabId; void tick().then(() => @@ -289,6 +300,7 @@ tabs = removeTab(tabs, id); delete dirtyFiles[id]; delete fileContexts[id]; + if (!tabs.tabs.length) showTabs.set(false); await tick(); document.getElementById(domId(tabs.activeId))?.focus(); } finally { @@ -886,6 +898,16 @@ {$i18n.t('Open a tab using the + menu.')}
{/if}
+ {#if gitConnection} + openFile(path, gitConnection.selector)} + onOpenDirectory={(path) => openFiles(gitConnection.selector, path)} + /> + {/if}
{#if !largeScreen} diff --git a/src/lib/components/chat/ChatTabs/GitBar.svelte b/src/lib/components/chat/ChatTabs/GitBar.svelte new file mode 100644 index 0000000000..58ed7c06f8 --- /dev/null +++ b/src/lib/components/chat/ChatTabs/GitBar.svelte @@ -0,0 +1,993 @@ + + +{#if status?.is_repo} +
+ {#if expanded} + + {/if} +
+ + +
+ +
+ +
+ +
+ {#each branches.filter((branch) => branch.name + .toLowerCase() + .includes(branchSearch.toLowerCase())) as branch} +
+ + + +
+ + {#if branch.is_local !== false}{/if} + + {#if branch.is_local !== false && !branch.current}{/if} + +
+
+
+ {/each} +
+ {#if creatingBranch}
act('branch', { branch: newBranch })} + > + + + {:else}
+ +
{/if} +
+
+
+ + +
+ +
+ +
+
+ {#each worktrees.filter((tree) => `${tree.branch} ${tree.path}` + .toLowerCase() + .includes(worktreeSearch.toLowerCase())) as tree}{/each} +
+ {#if creatingWorktree}
+ act('worktree', { branch: worktreeBranch, target: worktreePath })} + > + +
+ +
+
+ {:else}
+ +
{/if} +
+
+
+ + + +
+ {#if error}{/if} + {#if expanded} +
+
+ {#each ['changes', 'history', ...(prCapabilities?.available ? ['pull requests'] : [])] as section}{/each} +
+ + +
+
+ +
+ {$i18n.t('Display')} +
+ {#each ['unified', 'split'] as mode}{/each} +
+
+
+
+ {#if view === 'pull requests' && connection && status.root} + {#key status.root} { + void refresh(true); + }} + />{/key} + {:else} +
+
+ {#if view === 'changes'} + {#if status.files.length} + + {/if} +
+ {#each status.files as file (file.path)} +
+ + + {#if file.binary}{file.status === 'untracked' ? 'U' : file.status[0].toUpperCase()}{:else}{/if} + + +
+ + + {#if file.staged}{/if} + {#if file.unstaged}{/if} + {#if file.unstaged && file.status !== 'untracked'}{/if} + +
+
+
+ {/each} + {#if !status.files.length}
+ {$i18n.t('No changes')} +
{/if} +
+
+ act('commit', { + message: [summary.trim(), description.trim()].filter(Boolean).join('\n\n') + })} + > +
+ + +
+ +
+ {:else} +
+ {#each commits as commit, index}
+ +
+ {#if index === 0}{/if} +
+
{/each} + {#if !commits.length}
+ {$i18n.t('No commits yet')} +
{/if} +
+ {/if} +
+
+ {#if selected || selectedCommit} +
+ {selected?.path ?? + `${selectedCommit?.short_hash} · ${selectedCommit?.message}`} + {#if selected}{/if} +
+
+ {#if loadingDiff}

+ {$i18n.t('Loading...')} +

{:else if diff}{:else}
+ {$i18n.t('No text changes')} +
{/if} +
+ {:else}
+ {$i18n.t( + view === 'history' + ? 'Select a commit to view changes' + : 'Select a file to view changes' + )} +
{/if} +
+
+ {/if} +
+ {/if} +
+{/if} + + { + if (discardFile) void act('discard', { paths: paths([discardFile]) }); + }} +/> + + { + if (actionBranch) + void act('rename_branch', { branch: actionBranch.name, target: event.detail }); + }} +/> + { + if (actionBranch) void act('delete_branch', { branch: actionBranch.name }); + }} +/> + act('uncommit')} +/> + + diff --git a/src/lib/components/chat/ChatTabs/GitDiff.svelte b/src/lib/components/chat/ChatTabs/GitDiff.svelte new file mode 100644 index 0000000000..994de35de0 --- /dev/null +++ b/src/lib/components/chat/ChatTabs/GitDiff.svelte @@ -0,0 +1,132 @@ + + +{#snippet text(line: VersionDiffLine | null)} + {#if line}{#each line.segments as segment}{segment.text}{/each}{#if line.noNewline} + ↵{/if}{:else}{' '}{/if} +{/snippet} + +{#snippet cell(line: VersionDiffLine | null)} +
+ {@render text(line)} +
+{/snippet} + +
+ {#each files as file} + {#if files.length > 1}
+ {file.path} +
{/if} + {#each file.hunks as hunk, index} +
+ {file.headers[index]} +
+ {#each hunk.rows as row} + {#if !(hideWhitespace && row.before?.type === 'deletion' && row.after?.type === 'addition' && row.before.content.replace(/\s/g, '') === row.after.content.replace(/\s/g, ''))} + {#if mode === 'split'}
+ {@render cell(row.before)}{@render cell(row.after)} +
+ {:else if row.before?.type === 'context'}{@render cell(row.before)} + {:else}{#if row.before}{@render cell(row.before)}{/if}{#if row.after}{@render cell( + row.after + )}{/if}{/if} + {/if} + {/each} + {/each} + {/each} +
+ + diff --git a/src/lib/components/chat/ChatTabs/GitPullRequests.svelte b/src/lib/components/chat/ChatTabs/GitPullRequests.svelte new file mode 100644 index 0000000000..3a830932c1 --- /dev/null +++ b/src/lib/components/chat/ChatTabs/GitPullRequests.svelte @@ -0,0 +1,506 @@ + + +
+
+
+
+ {#each ['open', 'closed', 'all'] as option}{/each} +
+
+
+ +
+ +
+
+ {#if error && !selected && !creating && !editing}{/if} +
+ {#if loading}

+ {$i18n.t('Loading...')} +

{:else}{#each prs.filter((pr) => `${pr.number} ${pr.title}` + .toLowerCase() + .includes(search.toLowerCase())) as pr}{/each}{#if !prs.length}

+ {$i18n.t('No pull requests')} +

{/if}{/if} +
+
+
+
+ {#if selected || creating || editing}{/if} + {#if selected}#{selected.number} {selected.title} +
+ + + + {#if selected.state === 'OPEN'}{#if selected.isDraft}{/if}{:else if selected.state === 'CLOSED'}{/if} + {$i18n.t('Open in GitHub')} + +
{/if} +
+ {#if error}{/if} + {#if creating || editing} +
mutate(editing ? 'edit' : 'create')} + > + + + {#if creating}
+ +
+ {/if} + +
+ {:else if selected} +
+ {#each ['summary', 'code', 'checks', 'activity'] as tab}{/each} +
+
+ {#if loading}

{$i18n.t('Loading...')}

+ {:else if view === 'code'} + {:else if view === 'summary'}
+
+ {$i18n.t('Author')}{selected.author?.login ?? 'unknown'} + {$i18n.t('Status')}{selected.isDraft ? $i18n.t('Draft') : selected.state}{selected.reviewDecision + ? ` · ${selected.reviewDecision}` + : ''} + {$i18n.t('Reviewers')}{selected.reviewRequests + ?.map((person) => person.login || person.name) + .join(', ') || $i18n.t('none')} + {$i18n.t('Assignees')}{selected.assignees?.map((person) => person.login || person.name).join(', ') || + $i18n.t('none')} + {$i18n.t('Labels')}{selected.labels?.map((label) => label.name).join(', ') || $i18n.t('none')} + {$i18n.t('Merge')}{selected.mergeable ?? 'unknown'} +
+
+
+ {$i18n.t('Description')} +
+
+ {selected.body || $i18n.t('No description')} +
+
+
+ {#if selected.state === 'OPEN'} + {#if selected.isDraft}{/if} + {#each ['squash', 'merge', 'rebase'] as method}{/each} + + {:else if selected.state === 'CLOSED'}{/if} +
+
+ {:else if view === 'checks'}
+ {#each selected.statusCheckRollup ?? [] as check}
+ {check.name ?? check.context}{check.conclusion || check.status || check.state} +
{/each}{#if !selected.statusCheckRollup?.length}

+ {$i18n.t('No checks')} +

{/if} +
+ {:else}
+ {#each [...(selected.comments ?? []), ...(selected.reviews ?? [])] as item}
+

+ {item.author?.login}{'state' in item ? ` · ${item.state}` : ''} +

+

{item.body}

+
{/each} +
+ {#if selected.state === 'OPEN'}{/if} +
+
{/if} +
+ {:else}
+ {$i18n.t('Select a pull request')} +
{/if} +
+
+ + mutate(pendingAction)} +/> + + From 3e24a08f8ec8472dcbbc46e7e39ab35aaa4a6f4f Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 1 Nov 2026 22:41:22 +0900 Subject: [PATCH 121/160] refac --- src/lib/apis/terminal/git.ts | 28 ++- src/lib/components/chat/ChatTabs.svelte | 1 + .../components/chat/ChatTabs/GitBar.svelte | 196 +++++++++++------- .../components/chat/ChatTabs/GitDiff.svelte | 59 +++++- .../chat/ChatTabs/GitPullRequests.svelte | 16 +- 5 files changed, 211 insertions(+), 89 deletions(-) diff --git a/src/lib/apis/terminal/git.ts b/src/lib/apis/terminal/git.ts index a7ae504b25..e8b62e50fd 100644 --- a/src/lib/apis/terminal/git.ts +++ b/src/lib/apis/terminal/git.ts @@ -18,6 +18,7 @@ export type GitStatus = { branch: string; head?: string; upstream?: string; + remote_url?: string; ahead: number; behind: number; files: GitFile[]; @@ -31,6 +32,22 @@ export type GitCommit = { }; export type GitBranch = { name: string; current: boolean; upstream: string; is_local?: boolean }; +export function gitRemoteWebUrl(remote = ''): string { + const scp = remote.match(/^[^/@:\s]+@([^/:\s]+):(.+)$/); + try { + const url = new URL(scp ? `https://${scp[1]}/${scp[2]}` : remote); + if (url.protocol === 'ssh:') { + return new URL(`https://${url.hostname}${url.pathname.replace(/\.git\/?$/, '')}`).href; + } + if (!['http:', 'https:'].includes(url.protocol)) return ''; + url.username = url.password = url.search = url.hash = ''; + url.pathname = url.pathname.replace(/\.git\/?$/, ''); + return url.href; + } catch { + return ''; + } +} + export async function gitRequest( connection: TerminalConnection, chatId: string | null, @@ -53,8 +70,17 @@ export async function gitRequest( }); if (!response.ok) { const error = await response.json().catch(() => null); + if (response.status === 404 && error?.detail === 'Not Found') { + throw new Error( + 'Git support is unavailable on this connection. Update and restart Open Terminal.' + ); + } throw new Error( - typeof error?.detail === 'string' ? error.detail : `Git request failed (${response.status})` + typeof error?.detail === 'string' + ? error.detail + : typeof error?.error === 'string' + ? error.error + : `Git request failed (${response.status})` ); } return response.json(); diff --git a/src/lib/components/chat/ChatTabs.svelte b/src/lib/components/chat/ChatTabs.svelte index 4403aff7aa..be0e1c5928 100644 --- a/src/lib/components/chat/ChatTabs.svelte +++ b/src/lib/components/chat/ChatTabs.svelte @@ -684,6 +684,7 @@ class:hidden={!$showTabs || !panelTarget} use:placePanel={$showTabs ? panelTarget : null} class="h-full w-full min-h-0 flex flex-col" + style:--chat-tabs-dark-background={largeScreen ? 'var(--color-gray-900)' : 'var(--color-gray-850)'} id="controls-container" >
diff --git a/src/lib/components/chat/ChatTabs/GitBar.svelte b/src/lib/components/chat/ChatTabs/GitBar.svelte index 58ed7c06f8..4f4a934b6a 100644 --- a/src/lib/components/chat/ChatTabs/GitBar.svelte +++ b/src/lib/components/chat/ChatTabs/GitBar.svelte @@ -4,6 +4,7 @@ import { gitRequest, gitAction, + gitRemoteWebUrl, type GitStatus, type GitFile, type GitCommit, @@ -11,6 +12,7 @@ } from '$lib/apis/terminal/git'; import Icon from '../FileNav/Icon.svelte'; import GitDiff from './GitDiff.svelte'; + import { parseDiffRows } from '../Messages/diff'; import Dropdown from '../../common/Dropdown.svelte'; import DropdownMenu from '../../common/DropdownMenu.svelte'; import ConfirmDialog from '../../common/ConfirmDialog.svelte'; @@ -34,6 +36,14 @@ let selected: { path: string; staged: boolean; untracked: boolean } | null = null; let selectedCommit: GitCommit | null = null; let diff = ''; + $: diffStats = parseDiffRows(diff).reduce( + (counts, row) => { + if (row.type === 'addition') counts.additions++; + if (row.type === 'deletion') counts.deletions++; + return counts; + }, + { additions: 0, deletions: 0 } + ); let commits: GitCommit[] = []; let branches: GitBranch[] = []; let branchSearch = ''; @@ -54,6 +64,7 @@ let summary = ''; let description = ''; let error = ''; + let detectionError = ''; let busy = false; let loadingDiff = false; let confirmDiscard = false; @@ -76,6 +87,16 @@ $: additions = status?.files.reduce((sum, file) => sum + file.additions, 0) ?? 0; $: deletions = status?.files.reduce((sum, file) => sum + file.deletions, 0) ?? 0; $: branchLabel = status?.branch === '(detached)' ? status.head?.slice(0, 7) : status?.branch; + $: remoteWebUrl = gitRemoteWebUrl(status?.remote_url); + $: remoteHost = remoteWebUrl ? new URL(remoteWebUrl).hostname : ''; + $: remotePlatform = + remoteHost === 'github.com' + ? 'GitHub' + : remoteHost.includes('gitlab') + ? 'GitLab' + : remoteHost === 'bitbucket.org' + ? 'Bitbucket' + : remoteHost; $: syncAction = !status?.upstream ? 'publish' : status.behind > 0 @@ -110,6 +131,7 @@ const task = gitRequest(connection, chatId, directory, 'status') .then((next) => { if (current !== generation) return; + detectionError = ''; if (status?.root && status.root !== next.root) resetSelection(); status = next.is_repo ? next : null; if (next.root && next.root !== prRoot) { @@ -131,8 +153,11 @@ ) resetSelection(); }) - .catch(() => { - if (current === generation) status = null; + .catch((reason) => { + if (current === generation) { + status = null; + detectionError = String(reason instanceof Error ? reason.message : reason); + } }) .finally(() => { if (current === generation) pending = null; @@ -155,6 +180,7 @@ pending = null; status = null; error = ''; + detectionError = ''; expanded = false; showBranches = showWorktrees = @@ -278,9 +304,6 @@ files.flatMap((file) => [file.path, ...(file.original_path ? [file.original_path] : [])]) ) ]; - const openFile = () => { - if (selected && status?.root) onOpenFile(`${status.root}/${selected.path}`); - }; const toggle = () => { expanded = !expanded; if (expanded) { @@ -343,14 +366,14 @@ }} >
{/if} -
+
@@ -454,12 +477,12 @@ @@ -545,22 +568,18 @@ >{/if} + + + -
{#if error}{/if} {#if expanded}
{#each ['changes', 'history', ...(prCapabilities?.available ? ['pull requests'] : [])] as section}{/each}
+ {#if remoteWebUrl} + + + + {/if}
act(allStaged ? 'unstage' : 'stage', { paths: paths(status?.files ?? []) })} > - {/if} - {file.path.split('/').pop()} { + if (status?.root) + onOpenFile(`${status.root.replace(/\/$/, '')}/${file.path}`); + }}>{file.path.split('/').pop()} - + +
{#if file.binary}{/if}
act('commit', { message: [summary.trim(), description.trim()].filter(Boolean).join('\n\n') @@ -789,7 +827,7 @@ bind:value={summary} />