From a5058fa562e72cd2e31f2579225cc7b75e9d0603 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 22 Nov 2026 20:43:18 +0400 Subject: [PATCH] refac --- backend/open_webui/models/chat_messages.py | 20 +++++++++++++++ backend/open_webui/models/chats.py | 11 ++++++++ backend/open_webui/utils/agents/session.py | 5 +++- backend/open_webui/utils/machines/__init__.py | 25 ++++++++++++------- backend/open_webui/utils/mcp/client.py | 8 +++++- backend/open_webui/utils/tools.py | 16 ++++++------ 6 files changed, 67 insertions(+), 18 deletions(-) diff --git a/backend/open_webui/models/chat_messages.py b/backend/open_webui/models/chat_messages.py index 149a5f1733..9b3ca457ca 100644 --- a/backend/open_webui/models/chat_messages.py +++ b/backend/open_webui/models/chat_messages.py @@ -479,6 +479,26 @@ class ChatMessageTable: return messages_map + async def get_message_parents_map_by_chat_id( + self, chat_id: str, db: Optional[AsyncSession] = None + ) -> Optional[dict]: + """Like ``get_messages_map_by_chat_id``, with only each message's ``parentId`` and ``meta``.""" + async with get_async_db_context(db) as db: + result = await db.execute( + select(ChatMessage.id, ChatMessage.parent_id, ChatMessage.meta).filter_by(chat_id=chat_id) + ) + rows = result.all() + + if not rows: + return None + + prefix = f'{chat_id}-' + prefix_len = len(prefix) + return { + (row_id[prefix_len:] if row_id.startswith(prefix) else row_id): {'parentId': parent_id, 'meta': meta} + for row_id, parent_id, meta in rows + } + async def get_messages_by_user_id( self, user_id: str, diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index 84e9d7f8bb..5988d756da 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -2012,6 +2012,17 @@ class ChatTable: except Exception: return None + async def get_chat_without_history_by_id(self, id: str) -> tuple[str, str, dict, str | None, str | None] | None: + """Return (id, user_id, meta, folder_id, current_message_id) for a chat, without its history.""" + try: + async with get_async_db_context() as session: + result = await session.execute( + select(Chat.id, Chat.user_id, Chat.meta, Chat.folder_id, Chat.current_message_id).filter_by(id=id) + ) + return result.first() + except Exception: + return None + async def get_chat_by_share_id(self, id: str, db: AsyncSession | None = None) -> ChatModel | None: """Look up a shared chat snapshot by its share token.""" from open_webui.models.shared_chats import SharedChats diff --git a/backend/open_webui/utils/agents/session.py b/backend/open_webui/utils/agents/session.py index 6102c8a939..71415f7f19 100644 --- a/backend/open_webui/utils/agents/session.py +++ b/backend/open_webui/utils/agents/session.py @@ -5,6 +5,7 @@ import re from urllib.parse import quote from open_webui.utils.machines import machine_id_of, normalize_machine_id +from open_webui.models.chat_messages import ChatMessages from open_webui.models.chats import ChatModel, Chats from open_webui.utils.auth import decode_token @@ -77,7 +78,9 @@ async def get_session(chat, message_id=None): ) if not message_id: return None - messages = await Chats.get_messages_map_by_chat_id(chat.id) or {} + messages = await ChatMessages.get_message_parents_map_by_chat_id(chat.id) + if not messages or Chats.get_unresolved_parent_ids(messages): + messages = await Chats.get_messages_map_by_chat_id(chat.id) or {} return _find(chat, messages, message_id)[0] diff --git a/backend/open_webui/utils/machines/__init__.py b/backend/open_webui/utils/machines/__init__.py index 378effdfb7..9663f9b0a5 100644 --- a/backend/open_webui/utils/machines/__init__.py +++ b/backend/open_webui/utils/machines/__init__.py @@ -383,19 +383,23 @@ async def find_machine_connection(user, machine_id, metadata=None, request=None) instance_user = user chat_id = metadata.get('chat_id') if chat_id and is_saved_chat_id(chat_id): - chat = await Chats.get_accessible_chat_by_id(chat_id, user, permission='write') - if chat is None: - other = await Chats.get_chat_by_id(chat_id) - if other is None or not await has_machine_write_access(user, machine_id): + chat = await Chats.get_chat_without_history_by_id(chat_id) + if chat is None or not await Chats.has_chat_access(chat_id, user, permission='write', chat=chat): + if chat is None or not await has_machine_write_access(user, machine_id): raise HTTPException(403, 'Chat access denied') - return await find_instance_user_connection(other.user_id) - if chat.meta.get('internal') is True and chat.meta.get('type') == 'subagent': + return await find_instance_user_connection(chat.user_id) + chat_meta = chat.meta or {} + if chat_meta.get('internal') is True and chat_meta.get('type') == 'subagent': # A sub-agent shares the instance and files of its parent chat. - metadata['chat_id'] = chat.meta.get('parent_chat_id') + metadata['chat_id'] = chat_meta.get('parent_chat_id') return await find_machine_connection(user, machine_id, metadata, request=request) from open_webui.utils.agents.session import get_session, model_id - shared_session = await get_session(chat) + # Without a current message id only the full chat knows where the history ends. + session_chat = chat if chat.current_message_id else await Chats.get_chat_by_id(chat_id) + if session_chat is None: + raise HTTPException(403, 'Chat access denied') + shared_session = await get_session(session_chat) if shared_session and shared_session['machine_id'] != machine_id: shared_session = None if shared_session: @@ -429,7 +433,10 @@ async def find_machine_connection(user, machine_id, metadata=None, request=None) scope = (template.get('data') or {}).get('scope') if chat and not shared_session: - stored = machine_id_of(chat.chat) + full_chat = await Chats.get_chat_by_id(chat_id) + if full_chat is None: + raise HTTPException(403, 'Chat access denied') + stored = machine_id_of(full_chat.chat) if chat.user_id != user.id and stored != machine_id: raise HTTPException(403, 'Use the machine selected by the chat owner') if stored and stored != machine_id: diff --git a/backend/open_webui/utils/mcp/client.py b/backend/open_webui/utils/mcp/client.py index 4392995e76..82ee0d4074 100644 --- a/backend/open_webui/utils/mcp/client.py +++ b/backend/open_webui/utils/mcp/client.py @@ -52,7 +52,11 @@ def create_httpx_client(headers=None, auth=None): class OAuthTokenAuth(httpx2.Auth): - """Resolve current credentials per request and recover from concurrent token rotation.""" + """Resolve current credentials per request and recover from a rejected token. + + On a 401, pick up a token another request already rotated in, or else force + one refresh. A failed refresh drops the stored session so the user can sign in again. + """ requires_request_body = True @@ -69,6 +73,8 @@ class OAuthTokenAuth(httpx2.Auth): if response.status_code == 401: headers = httpx2.Headers(await self.get_headers()) + if headers.get('Authorization') == authorization: + headers = httpx2.Headers(await self.get_headers(refresh=True)) if headers.get('Authorization') and headers['Authorization'] != authorization: request.headers.update(headers) yield request diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index 3cb2970e6f..4c3aaba7e4 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -148,6 +148,7 @@ async def build_tool_server_headers( user, server_id: str = '', metadata: dict | None = None, + refresh: bool = False, ) -> tuple[dict, dict]: """Build auth headers and cookies for a tool server connection. @@ -177,7 +178,7 @@ async def build_tool_server_headers( oauth_server_id = splits[-1] if len(splits) > 1 else server_id connection_type = connection.get('type', 'openapi') oauth_token = await request.app.state.oauth_client_manager.get_oauth_token( - user.id, f'{connection_type}:{oauth_server_id}' + user.id, f'{connection_type}:{oauth_server_id}', force_refresh=refresh ) if oauth_token: headers.update(bearer_auth_header(oauth_token.get('access_token', ''))) @@ -253,18 +254,19 @@ async def connect_mcp_server( metadata = extra_params.get('__metadata__', {}) - async def get_headers(): + async def get_headers(refresh=False): headers, _ = await build_tool_server_headers( - mcp_server_connection, request, user, server_id=server_id, metadata=metadata + mcp_server_connection, request, user, server_id=server_id, metadata=metadata, refresh=refresh ) return headers - auth = OAuthTokenAuth(get_headers) if mcp_server_connection.get('auth_type') == 'system_oauth' else None - headers = {} if auth else await get_headers() - - if mcp_server_connection.get('auth_type') in ('oauth_2.1', 'oauth_2.1_static') and not headers.get('Authorization'): + auth_type = mcp_server_connection.get('auth_type') + if auth_type in ('oauth_2.1', 'oauth_2.1_static') and not (await get_headers()).get('Authorization'): raise HTTPException(status_code=401, detail='Auth required') + auth = OAuthTokenAuth(get_headers) if auth_type in ('system_oauth', 'oauth_2.1', 'oauth_2.1_static') else None + headers = {} if auth else await get_headers() + client = MCPClient( event_caller=extra_params.get('__event_call__') if metadata.get('session_id') else None, server_name=server_id,