diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py
index 749e198127..72dd8422a7 100644
--- a/backend/open_webui/tools/builtin.py
+++ b/backend/open_webui/tools/builtin.py
@@ -69,6 +69,7 @@ from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.notifications import notify_target
from open_webui.utils.sanitize import sanitize_code
from open_webui.utils.skill_files import SkillFile, SkillFileOperation, skill_content_page, skill_overview
+from open_webui.utils.terminals import upload_files_to_terminal
log = logging.getLogger(__name__)
@@ -375,6 +376,8 @@ async def generate_image(
__event_emitter__: callable = None,
__chat_id__: str = None,
__message_id__: str = None,
+ __metadata__: dict = None,
+ __event_call__: callable = None,
) -> str:
"""
Generate an image based on a text prompt.
@@ -382,7 +385,7 @@ async def generate_image(
:param prompt: A detailed description of the image to generate
:param size: Optional output size in WIDTHxHEIGHT pixels (e.g. "1536x1024"), supported by the configured image model.
Omit to use the configured default.
- :return: Confirmation that the image was generated, or an error message
+ :return: Image URLs and, when a terminal is selected, terminal_path for display_file or further processing.
"""
if __request__ is None:
return JSONCodec.dumps({'error': 'Request context not available'})
@@ -401,6 +404,10 @@ async def generate_image(
user=user,
)
+ await upload_files_to_terminal(
+ __request__, user, images, __metadata__ or {}, {'__event_call__': __event_call__}
+ )
+
# Prepare file entries for the images
image_files = [{'type': 'image', **img} for img in images]
@@ -428,7 +435,10 @@ async def generate_image(
return JSONCodec.dumps(
{
'status': 'success',
- 'message': 'The image has been successfully generated and is already visible to the user in the chat. You do not need to display or embed the image again - just acknowledge that it has been created.',
+ 'message': (
+ 'The image is already visible in chat. Use terminal_path with terminal tools or '
+ 'display_file when available to continue the requested task.'
+ ),
'images': images,
},
ensure_ascii=False,
@@ -449,6 +459,8 @@ async def edit_image(
__event_emitter__: callable = None,
__chat_id__: str = None,
__message_id__: str = None,
+ __metadata__: dict = None,
+ __event_call__: callable = None,
) -> str:
"""
Transform one or more existing images according to a text prompt.
@@ -458,7 +470,7 @@ async def edit_image(
:param image_urls: Source image URLs to modify or use as composition inputs
:param size: Optional output size in WIDTHxHEIGHT pixels (e.g. "1536x1024"), supported by the configured image model.
Omit to use the configured default.
- :return: Confirmation that the images were edited, or an error message
+ :return: Image URLs and, when a terminal is selected, terminal_path for display_file or further processing.
"""
if __request__ is None:
return JSONCodec.dumps({'error': 'Request context not available'})
@@ -477,6 +489,10 @@ async def edit_image(
user=user,
)
+ await upload_files_to_terminal(
+ __request__, user, images, __metadata__ or {}, {'__event_call__': __event_call__}
+ )
+
# Prepare file entries for the images
image_files = [{'type': 'image', **img} for img in images]
@@ -504,7 +520,10 @@ async def edit_image(
return JSONCodec.dumps(
{
'status': 'success',
- 'message': 'The edited image has been successfully generated and is already visible to the user in the chat. You do not need to display or embed the image again - just acknowledge that it has been created.',
+ 'message': (
+ 'The edited image is already visible in chat. Use terminal_path with terminal tools or '
+ 'display_file when available to continue the requested task.'
+ ),
'images': images,
},
ensure_ascii=False,
diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py
index c851bb6063..8a4e2ba902 100644
--- a/backend/open_webui/utils/middleware.py
+++ b/backend/open_webui/utils/middleware.py
@@ -151,6 +151,7 @@ from open_webui.utils.task import (
rag_template,
tools_function_calling_generation_template,
)
+from open_webui.utils.terminals import upload_files_to_terminal
from open_webui.utils.tool_approval import complete_tool_call, pending_tool_calls
from open_webui.utils.tool_search import apply_tool_search, resolve_tool_call
from open_webui.utils.tools import (
@@ -1496,6 +1497,7 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
'message_id': metadata.get('message_id', None),
**({'channel_id': chat_id.removeprefix('channel:')} if is_channel_chat else {'chat_id': chat_id}),
}
+ terminal_metadata = {**metadata, 'terminal_id': form_data.get('terminal_id')}
if not is_saved_chat_id(chat_id):
message_list = form_data.get('messages', [])
@@ -1544,6 +1546,7 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
metadata=image_metadata,
user=user,
)
+ await upload_files_to_terminal(request, user, images, terminal_metadata, extra_params)
await __event_emitter__(
{
@@ -1567,7 +1570,10 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
}
)
- system_message_content = 'The requested image has been edited and created and is now being shown to the user. Let them know that it has been generated.'
+ system_message_content = (
+ 'The edited images are shown in chat. Use terminal_path with terminal tools or '
+ f'display_file when available. Images: {JSONCodec.dumps(images)}'
+ )
except Exception as e:
log.debug(e)
@@ -1652,6 +1658,7 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
metadata=image_metadata,
user=user,
)
+ await upload_files_to_terminal(request, user, images, terminal_metadata, extra_params)
await __event_emitter__(
{
@@ -1675,7 +1682,10 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
}
)
- system_message_content = 'The requested image has been created by the system successfully and is now being shown to the user. Let the user know that the image they requested has been generated and is now shown in the chat.'
+ system_message_content = (
+ 'The generated images are shown in chat. Use terminal_path with terminal tools or '
+ f'display_file when available. Images: {JSONCodec.dumps(images)}'
+ )
except Exception as e:
log.debug(e)
diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py
index 1bb2369629..af0970bccf 100644
--- a/backend/open_webui/utils/terminals.py
+++ b/backend/open_webui/utils/terminals.py
@@ -5,6 +5,7 @@ import hashlib
import logging
import ntpath
import posixpath
+from pathlib import Path
from urllib.parse import quote
from open_webui.env import ENABLE_TOOL_SERVERS
@@ -129,9 +130,13 @@ def terminal_chat_uploads(connection: dict) -> str:
return value if value in TERMINAL_CHAT_UPLOAD_MODES else 'default'
-async def get_terminal_json(request, user, metadata: dict, path: str, extra_params: dict | None = None):
- """Read from an admin terminal on the backend or a personal terminal in its browser."""
- if not ENABLE_TOOL_SERVERS:
+async def get_terminal_json(
+ request, user, metadata: dict, path: str, extra_params: dict | None = None, *, file: dict | None = None
+):
+ """Read JSON or upload a file through an admin terminal or a personal terminal's browser."""
+ metadata = metadata or {}
+ terminal_id = metadata.get('terminal_id')
+ if not ENABLE_TOOL_SERVERS or not terminal_id:
return None
import aiohttp
@@ -142,11 +147,6 @@ async def get_terminal_json(request, user, metadata: dict, path: str, extra_para
from open_webui.utils.access_control import has_connection_access
from open_webui.utils.tools import build_tool_server_headers
- metadata = metadata or {}
- terminal_id = metadata.get('terminal_id')
- if not terminal_id:
- return None
-
user_model = user if isinstance(user, UserModel) else UserModel(**user)
connections = await Config.get('terminal_server.connections', []) or []
connection = next((item for item in connections if item.get('id') == terminal_id), None)
@@ -179,29 +179,80 @@ async def get_terminal_json(request, user, metadata: dict, path: str, extra_para
headers['X-Session-Id'] = metadata['chat_id']
if context_id:
headers[TERMINAL_CONTEXT_HEADER] = context_id
+ body = None
+ if file:
+ from open_webui.models.files import Files
+ from open_webui.storage.provider import Storage
+
+ source = await Files.get_file_by_id(file['id'])
+ if not source or source.user_id != user_model.id or not source.path:
+ return None
+ local_path = await asyncio.to_thread(Storage.get_file, source.path)
+ body = aiohttp.FormData()
+ body.add_field(
+ 'file',
+ await asyncio.to_thread(Path(local_path).read_bytes),
+ filename=file['name'],
+ content_type=(source.meta or {}).get('content_type') or 'application/octet-stream',
+ )
+ headers = {key: value for key, value in headers.items() if key.lower() != 'content-type'}
timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA)
async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
- async with session.get(
+ async with session.request(
+ 'POST' if file else 'GET',
f'{get_terminal_server_url(connection)}{path}',
headers=headers,
cookies=cookies,
+ data=body,
ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
allow_redirects=False,
) as response:
- return await response.json() if response.status == 200 else None
+ return await response.json() if 200 <= response.status < 300 else None
event_caller = (extra_params or {}).get('__event_call__')
if event_caller:
result = await event_caller(
{
'type': 'request:terminal',
- 'data': {'terminal_id': terminal_id, 'path': path, 'session_id': metadata.get('session_id')},
+ 'data': {
+ 'terminal_id': terminal_id,
+ 'path': path,
+ 'session_id': metadata.get('session_id'),
+ **({'file': file} if file else {}),
+ },
}
)
return result.get('data') if isinstance(result, dict) else None
return None
+async def upload_files_to_terminal(request, user, files: list[dict], metadata: dict, extra_params: dict):
+ """Copy Open WebUI files to the selected terminal, adding terminal_path or terminal_error to each entry."""
+ if not metadata.get('terminal_id') or not files:
+ return
+ try:
+ cwd = await get_terminal_json(request, user, metadata, '/files/cwd', extra_params)
+ directory = cwd.get('cwd') if isinstance(cwd, dict) else None
+ if not directory:
+ raise ValueError('Terminal working directory unavailable')
+ path = f'/files/upload?directory={quote(directory, safe="")}'
+ for entry in files:
+ try:
+ # The file ID keeps separate files from overwriting one another.
+ file = {'id': entry['id'], 'name': f'{entry["id"]}{Path(entry["name"]).suffix}'}
+ result = await get_terminal_json(request, user, metadata, path, extra_params, file=file)
+ if not isinstance(result, dict) or not isinstance(result.get('path'), str) or not result['path']:
+ raise ValueError('Terminal upload failed')
+ entry['terminal_path'] = result['path']
+ except Exception as error:
+ log.warning('File terminal upload failed (%s)', type(error).__name__)
+ entry['terminal_error'] = 'File saved in Open WebUI, but upload to the selected terminal failed.'
+ except Exception as error:
+ log.warning('File terminal unavailable (%s)', type(error).__name__)
+ for entry in files:
+ entry['terminal_error'] = 'File saved in Open WebUI, but the selected terminal is unavailable.'
+
+
async def get_terminal_agents_md(request, user, metadata: dict, extra_params: dict | None = None) -> str | None:
"""Load the selected terminal user's home AGENTS.md afresh for this turn."""
try:
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 0acb691cc1..99c4a5252b 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -41,7 +41,7 @@
desktopEvent
} from '$lib/stores';
import { refreshChatList } from '$lib/stores/chatList';
- import { getFileContentById } from '$lib/apis/files';
+ import { getFileBlobById, getFileContentById } from '$lib/apis/files';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { beforeNavigate } from '$app/navigation';
@@ -672,11 +672,20 @@
const connection = resolveTerminalConnection(
data.terminal_id,
[],
- $config?.features?.enable_direct_integrations ? ($settings?.terminalServers ?? []) : [],
+ $config?.features?.enable_direct_integrations
+ ? ($settings?.terminalServers ?? []).filter((server) => server.enabled)
+ : [],
localStorage.token
);
if (!connection) throw new Error('Terminal Not Found');
- const result = await terminalRequest(connection, event.chat_id, data.path);
+ let options = {};
+ if (data.file) {
+ const blob = await getFileBlobById(localStorage.token, data.file.id);
+ const body = new FormData();
+ body.append('file', blob, data.file.name);
+ options = { method: 'POST', body };
+ }
+ const result = await terminalRequest(connection, event.chat_id, data.path, options);
cb?.({ data: result });
} catch (error) {
cb?.({ error: `${error}` });