diff --git a/backend/open_webui/utils/machines/__init__.py b/backend/open_webui/utils/machines/__init__.py index 4306b8c24e..b82730dcb3 100644 --- a/backend/open_webui/utils/machines/__init__.py +++ b/backend/open_webui/utils/machines/__init__.py @@ -7,6 +7,7 @@ import ntpath import posixpath from pathlib import Path from urllib.parse import quote, unquote, urlsplit +from uuid import uuid4 import aiohttp @@ -787,6 +788,23 @@ async def upload_files_to_machine(request, user, files: list[dict], metadata: di entry['machine_error'] = 'File saved in Open WebUI, but the selected terminal is unavailable.' +async def save_tool_result_to_machine(request, user, metadata: dict | None, content: str) -> str | None: + """Save a tool's full result where the model's machine tools can read it, and return its path.""" + tools = (metadata or {}).get('tools') or {} + if not any(tool.get('type') == 'terminal' for tool in tools.values()): + return None + try: + # Beside the user's recent folders (src/lib/apis/machines/recentFolders.ts). + home = (await get_machine_json(request, user, metadata, '/files/cwd'))['home'] + path = posixpath.join(home, f'.open-webui/users/{user.id}/outputs/{uuid4().hex}.txt') + body = {'path': path, 'content': content} + result = await get_machine_json(request, user, metadata, '/files/write', method='POST', body=body) + return result['path'] if result else None + except Exception as error: + log.warning('Tool result could not be saved to the machine (%s)', type(error).__name__) + return None + + async def get_machine_file(request, user, metadata: dict, path: str, *, max_bytes: int) -> bytes: """Read a bounded file through the authorized terminal connection.""" import aiohttp diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index bc94a25537..e6a5dffb47 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -164,7 +164,11 @@ from open_webui.utils.task import ( rag_template, tools_function_calling_generation_template, ) -from open_webui.utils.machines import filter_user_terminal_tools, upload_files_to_machine +from open_webui.utils.machines import ( + filter_user_terminal_tools, + save_tool_result_to_machine, + upload_files_to_machine, +) from open_webui.utils.tool_approval import complete_tool_call, pending_tool_calls from open_webui.utils.tool_permissions import ( ToolApprovalRequired, @@ -980,7 +984,13 @@ async def process_tool_result( max_chars = await Config.get('tools.output_max_chars') if max_chars and tool_result and len(tool_result) > max_chars: - tool_result = f'{tool_result[:max_chars]}\n\n[Truncated: {len(tool_result)} characters, limit {max_chars}]' + note = f'Truncated: {len(tool_result)} characters, limit {max_chars}' + # Machine tools read the saved file, so saving their results would only copy it again. + if tool_type != 'terminal': + path = await save_tool_result_to_machine(request, user, metadata, tool_result) + if path: + note += f', full result saved to {path} on the machine' + tool_result = f'{tool_result[:max_chars]}\n\n[{note}]' return tool_result, tool_result_files, tool_result_embeds diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index b3539b84de..a554748705 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -998,7 +998,7 @@ }); }; - const applyChatInputControls = (input: ReturnType) => { + const applyChatInputControls = (input: Partial>) => { selectedToolIds = input.selectedToolIds ?? []; selectedSkillIds = input.selectedSkillIds ?? []; selectedFilterIds = input.selectedFilterIds ?? []; @@ -1257,20 +1257,8 @@ const resetInput = async () => { // Let the $: update finish first, or webSearchActive misses the default-feature writes await tick(); - selectedToolIds = []; - selectedSkillIds = []; - selectedFilterIds = []; pendingOAuthTools = []; - webSearchEnabled = false; - imageGenerationEnabled = false; - codeInterpreterEnabled = false; - selectedImageModelId = ''; - videoGenerationEnabled = false; - selectedVideoModelId = ''; - - if (selectedModelIds.filter((id) => id).length > 0) { - await setDefaults(); - } + applyChatInputControls({}); }; /** Check whether a machine ID references an available machine. */ @@ -2903,11 +2891,8 @@ chatIdProp = id; } else if ($page.params.folderId || $page.url.pathname === '/') { selectedFolder.set($page.data.folder ?? null); - // On a first load the input is on screen before set-up, which resets it; - // what was typed there goes back in. - const typed = preserveTabs ? '' : prompt; - await initNewChat({ preserveTabs, url: $page.url }); - if (typed) messageInput?.setText(typed); + // On a first load the input is on screen before set-up, so what was entered there stays. + await initNewChat({ preserveTabs, preserveInput: !preserveTabs, url: $page.url }); } else if (initialPage) { if (!preserveTabs) await initNewChat(); loading = false; @@ -3073,6 +3058,7 @@ const initNewChat: NonNullable = async ({ preserveTabs = false, + preserveInput = false, temporary, url = initialPage || preserveTabs ? undefined : $page.url } = {}) => { @@ -3227,12 +3213,14 @@ autoScroll = true; + const input = preserveInput ? { prompt, files, controls: getChatInputControls() } : null; // resetInput() must stay last: the selected model's defaults override the draft's selection. prompt = ''; files = []; const chatInputPrompt = (await restoreChatInput(sessionStorage.getItem(getChatInputKey()))) ? prompt : null; + if (input) files = [...input.files, ...files]; if (signal.aborted) return; // Clear the previous chat first, so its id and history don't affect the new chat's defaults. await chatId.set(''); @@ -3263,6 +3251,12 @@ await resetInput(); if (signal.aborted) return; + // No defaults are applied yet, so setDefaults() adds the model's to what was picked. + modelDefaults = getChatInputControls(); + defaultsModelIds = []; + if (input) applyChatInputControls(input.controls); + if (selectedModelIds.some((id) => id)) await setDefaults(true); + if (signal.aborted) return; // A chat opened or a message sent in the meantime keeps its id and history if ($chatId || history.currentId) { loading = false; @@ -3326,7 +3320,7 @@ await tick(); if (signal.aborted) return; // The new-chat input stays mounted through set-up, so set its text either way. - messageInput?.setText(chatInputPrompt ?? ''); + messageInput?.setText(input?.prompt || chatInputPrompt || ''); if (modelSearch) await openModelSelectorWithSearch(modelSearch); // Consume call requests or the acknowledged Tether handoff. diff --git a/src/lib/i18n/locales/en-US/translation.json b/src/lib/i18n/locales/en-US/translation.json index be186d83d4..91d6184460 100644 --- a/src/lib/i18n/locales/en-US/translation.json +++ b/src/lib/i18n/locales/en-US/translation.json @@ -3703,7 +3703,7 @@ "settings.admin.general.skillPreviewMaxChars.description": "Characters shown when instructions exceed the read limit. Cannot exceed that limit. Leave empty to use the default.", "settings.admin.general.skillPreviewMaxChars.label": "Skill Preview Length", "settings.admin.general.title": "General", - "settings.admin.general.toolOutputMaxChars.description": "Maximum characters of a tool result sent to the model. Longer results are cut off. Leave empty for no limit.", + "settings.admin.general.toolOutputMaxChars.description": "Maximum characters of a tool result sent to the model. Longer results are cut off. With a machine connected, results from tools outside it are saved there in full. Leave empty for no limit.", "settings.admin.general.toolOutputMaxChars.label": "Tool Output Limit", "settings.admin.general.translations.addTranslation.label": "Add translation", "settings.admin.general.translations.uiTranslations.label": "UI Translations", diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts index cf052393f6..94ecb6ed22 100644 --- a/src/lib/types/index.ts +++ b/src/lib/types/index.ts @@ -25,6 +25,7 @@ export type AppLayoutContext = { openPageTab?: (tab: { href: string; label: string; inSplit?: boolean }) => void; initNewChat?: (options?: { preserveTabs?: boolean; + preserveInput?: boolean; temporary?: boolean; url?: URL; }) => Promise;