This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-19 19:13:33 +04:00
1 parent 6e5f3fda3e
commit 8fb2bf35ad
30 files changed
+708 -235

No files matched your search

+113
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import logging
import time
import uuid
import aiohttp
from fastapi import APIRouter, Depends, HTTPException, Request
@@ -20,6 +21,13 @@ from open_webui.routers.images import (
from open_webui.utils.access_control import has_permission
from open_webui.utils.auth import get_admin_user, get_verified_user
from open_webui.utils.headers import get_headers_and_cookies
from open_webui.utils.images.comfyui import (
ComfyUICreateVideoForm,
ComfyUIWorkflow,
comfyui_create_video,
comfyui_upload_image,
)
from open_webui.utils.json_codec import JSONCodec
from open_webui.utils.session_pool import get_session
from open_webui.utils.videos.connections import (
VIDEO_CONNECTIONS_CONFIG_KEY,
@@ -214,6 +222,7 @@ async def video_generations(
Video models take minutes, so the provider runs each request as a job: create it with
``POST /videos``, check ``GET /videos/{id}`` until it is done, then download ``/videos/{id}/content``.
OpenAI's API (which LiteLLM follows) takes a multipart form; OpenRouter's takes JSON.
ComfyUI connections run the admin's workflow instead (see ``comfyui_video_generations``).
"""
connection, model = await resolve_video_model(request, user, form_data.model, strict=strict)
connection_config = connection.get('config') or {}
@@ -221,6 +230,9 @@ async def video_generations(
size = form_data.size or connection_config.get('size')
metadata = metadata or {}
if connection['type'] == 'comfyui':
return await comfyui_video_generations(request, connection, model, form_data, seconds, size, metadata, user)
try:
headers, cookies = await get_headers_and_cookies(
request, connection['url'], connection['key'], connection_config, metadata, user=user
@@ -321,3 +333,104 @@ async def video_generations(
log.exception(f'Video generation failed: {e}')
error = e.message if isinstance(e, aiohttp.ClientResponseError) else e
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))
COMFYUI_DEFAULT_FPS = 24
def get_comfyui_video_length(seconds: int, fps: float) -> int:
"""Frames for a video of *seconds* at *fps*. Video models want 8n+1 frames (Wan 4n+1, LTX-Video 8n+1),
so the count is rounded to the nearest such length."""
return max(round(seconds * fps / 8), 1) * 8 + 1
def get_comfyui_workflow_fps(connection_config: dict) -> float | None:
"""The frame rate the workflow's mapped fps node already has, if any."""
workflow = JSONCodec.loads(connection_config['workflow'])
for node in connection_config.get('nodes') or []:
if node.get('type') != 'fps':
continue
for node_id in node.get('node_ids') or []:
value = ((workflow.get(node_id) or {}).get('inputs') or {}).get(node.get('key') or 'fps')
if isinstance(value, (int, float)) and value > 0:
return value
return None
async def comfyui_video_generations(
request: Request,
connection: dict,
model: str,
form_data: CreateVideoForm,
seconds: int | None,
size: str | None,
metadata: dict,
user,
):
"""Run the connection's ComfyUI video workflow and save each video it makes as a file.
The request's prompt, size, length, frame rate and starting frame go into the workflow nodes the admin
mapped; anything left out keeps the workflow's own value.
"""
connection_config = connection.get('config') or {}
if not connection_config.get('workflow'):
raise HTTPException(
status_code=400, detail=ERROR_MESSAGES.DEFAULT('This ComfyUI connection has no video workflow')
)
try:
width, height = (int(value) for value in size.split('x')) if size and size != 'auto' else (None, None)
except ValueError:
raise HTTPException(
status_code=400, detail=ERROR_MESSAGES.DEFAULT(f'Invalid video size: {size} (e.g. 1280x720)')
)
# Frames are counted at the admin's frame rate, else the one the workflow saves at.
fps = connection_config.get('fps') or get_comfyui_workflow_fps(connection_config) or COMFYUI_DEFAULT_FPS
try:
image = None
if form_data.image:
image_file_item = get_image_file_item(await load_url_image(form_data.image, user))
res = await comfyui_upload_image(image_file_item, connection['url'], connection['key'])
image = res.get('name') or image_file_item[1][0]
payload = ComfyUICreateVideoForm(
workflow=ComfyUIWorkflow(
workflow=connection_config['workflow'],
nodes=connection_config.get('nodes') or [],
),
prompt=form_data.prompt,
image=image,
width=width,
height=height,
length=get_comfyui_video_length(seconds, fps) if seconds else None,
fps=fps if connection_config.get('fps') else None,
)
videos = await comfyui_create_video(
model,
payload,
str(uuid.uuid4()),
connection['url'],
connection['key'],
timeout=VIDEO_GENERATION_TIMEOUT,
)
files = []
for video_data, content_type in videos:
_, video_file = await upload_image(
request,
video_data,
content_type,
{'model': model, 'prompt': form_data.prompt, **metadata},
user,
name='generated-video',
)
files.append(video_file)
return files
except HTTPException:
raise
except Exception as e:
log.exception(f'Video generation failed: {e}')
error = e.message if isinstance(e, aiohttp.ClientResponseError) else e
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))
+143 -42
View File
@@ -1,4 +1,6 @@
import asyncio
import logging
import mimetypes
import random
import urllib.parse
from typing import Optional
@@ -66,13 +68,12 @@ async def get_history(prompt_id, base_url, api_key):
return await r.json()
async def _ws_get_images(ws, workflow, client_id, base_url, api_key):
"""Queue a prompt and wait on *ws* for ComfyUI to finish executing it.
async def _ws_run_prompt(ws, workflow, client_id, base_url, api_key) -> dict:
"""Queue a prompt, wait on *ws* for ComfyUI to finish executing it, and return its history entry.
Returns a dict of ``{'data': [{'url': ...}, ...]}``.
Raises when the workflow failed.
"""
prompt_id = (await queue_prompt(workflow, client_id, base_url, api_key))['prompt_id']
output_images = []
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
@@ -93,6 +94,16 @@ async def _ws_get_images(ws, workflow, client_id, base_url, api_key):
raise Exception(
f'ComfyUI {error.get("node_type", "workflow")} failed: {error.get("exception_message", "").strip()}'
)
return history
async def _ws_get_images(ws, workflow, client_id, base_url, api_key):
"""Queue a prompt and wait on *ws* for ComfyUI to finish executing it.
Returns a dict of ``{'data': [{'url': ...}, ...]}``.
"""
history = await _ws_run_prompt(ws, workflow, client_id, base_url, api_key)
output_images = []
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
@@ -154,46 +165,48 @@ class ComfyUICreateImageForm(BaseModel):
seed: Optional[int] = None
# Node types filled from the request field of the same name, with the input key used when none is set.
WORKFLOW_NODE_INPUT_KEYS = {
'prompt': 'text',
'negative_prompt': 'text',
'width': 'width',
'height': 'height',
'n': 'batch_size',
'steps': 'steps',
'length': 'length',
'fps': 'fps',
}
def _apply_workflow_nodes(workflow, nodes, model, payload):
"""Mutate *workflow* dict in-place based on typed node definitions."""
"""Mutate *workflow* dict in-place based on typed node definitions.
A value the request leaves out (None) keeps the one already in the workflow.
"""
def set_input(node, value, default_key=None):
if value is None:
return
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key or default_key] = value
for node in nodes:
if node.type:
if node.type == 'model':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key] = model
elif node.type == 'prompt':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key if node.key else 'text'] = payload.prompt
elif node.type == 'negative_prompt':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key if node.key else 'text'] = payload.negative_prompt
elif node.type == 'image':
if isinstance(payload.image, list):
for idx, node_id in enumerate(node.node_ids):
if idx < len(payload.image):
workflow[node_id]['inputs'][node.key] = payload.image[idx]
else:
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key] = payload.image
elif node.type == 'width':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key if node.key else 'width'] = payload.width
elif node.type == 'height':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key if node.key else 'height'] = payload.height
elif node.type == 'n':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key if node.key else 'batch_size'] = payload.n
elif node.type == 'steps':
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key if node.key else 'steps'] = payload.steps
elif node.type == 'seed':
seed = payload.seed if payload.seed else random.randint(0, 1125899906842624)
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key] = seed
else:
for node_id in node.node_ids:
workflow[node_id]['inputs'][node.key] = node.value
if not node.type:
set_input(node, node.value)
elif node.type == 'model':
# No model (a connection without model IDs) runs the one the workflow sets.
set_input(node, model or None)
elif node.type == 'image':
image = getattr(payload, 'image', None)
if isinstance(image, list):
for node_id, value in zip(node.node_ids, image):
workflow[node_id]['inputs'][node.key] = value
else:
set_input(node, image)
elif node.type == 'seed':
set_input(node, getattr(payload, 'seed', None) or random.randint(0, 1125899906842624))
elif node.type in WORKFLOW_NODE_INPUT_KEYS:
set_input(node, getattr(payload, node.type, None), WORKFLOW_NODE_INPUT_KEYS[node.type])
async def comfyui_create_image(model: str, payload: ComfyUICreateImageForm, client_id, base_url, api_key):
@@ -263,3 +276,91 @@ async def comfyui_edit_image(model: str, payload: ComfyUIEditImageForm, client_i
return None
return images
class ComfyUICreateVideoForm(BaseModel):
workflow: ComfyUIWorkflow
prompt: str
negative_prompt: Optional[str] = None
image: Optional[str] = None # starting frame, as a file name uploaded to ComfyUI
width: Optional[int] = None
height: Optional[int] = None
length: Optional[int] = None # in frames
fps: Optional[float] = None
steps: Optional[int] = None
seed: Optional[int] = None
VIDEO_EXTENSIONS = ('.mp4', '.webm', '.mkv', '.mov', '.gif', '.webp')
def get_video_outputs(history: dict) -> list[dict]:
"""The video files a finished prompt saved, as ``{filename, subfolder, type}`` entries.
ComfyUI's SaveVideo and SaveWEBM list them under ``images`` (marked ``animated``), and
VideoHelperSuite's Video Combine under ``gifs``. Inputs a workflow loaded (LoadVideo) are left out.
"""
outputs = []
for node_output in (history.get('outputs') or {}).values():
for key in ('images', 'gifs', 'videos'):
for entry in node_output.get(key) or []:
if (
isinstance(entry, dict)
and entry.get('filename', '').lower().endswith(VIDEO_EXTENSIONS)
and entry.get('type') != 'input'
):
outputs.append(entry)
# Prefer saved files over the temporary previews some nodes also write.
saved = [entry for entry in outputs if entry.get('type') == 'output']
return saved or outputs
async def get_video(entry: dict, base_url: str, api_key: str) -> tuple[bytes, str]:
"""Download a video ComfyUI saved, with its content type."""
data = {'filename': entry['filename'], 'subfolder': entry.get('subfolder', ''), 'type': entry.get('type', 'output')}
headers = {**default_headers}
if api_key:
headers['Authorization'] = f'Bearer {api_key}'
session = await get_session()
async with session.get(
f'{base_url}/view?{urllib.parse.urlencode(data)}', headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL
) as r:
r.raise_for_status()
content_type = r.headers.get('content-type', '').split(';')[0]
if not content_type.startswith(('video/', 'image/')):
content_type = mimetypes.guess_type(entry['filename'])[0] or 'video/mp4'
return await r.read(), content_type
async def comfyui_create_video(
model: str, payload: ComfyUICreateVideoForm, client_id, base_url, api_key, timeout: float
) -> list[tuple[bytes, str]]:
"""Run a video workflow and return each video it saved, as ``(data, content_type)``.
Raises when the workflow fails, saves no video, or is not done within *timeout* seconds.
"""
ws_url = base_url.replace('http://', 'ws://').replace('https://', 'wss://')
workflow = JSONCodec.loads(payload.workflow.workflow)
_apply_workflow_nodes(workflow, payload.workflow.nodes, model, payload)
log.debug('Workflow: %s', workflow)
headers = {'Authorization': f'Bearer {api_key}'} if api_key else {}
session = await get_session()
try:
async with asyncio.timeout(timeout):
async with session.ws_connect(
f'{ws_url}/ws?clientId={client_id}',
headers=headers,
ssl=AIOHTTP_CLIENT_SESSION_SSL,
) as ws:
history = await _ws_run_prompt(ws, workflow, client_id, base_url, api_key)
except TimeoutError:
raise Exception(f'The video was not ready after {int(timeout)} seconds')
outputs = get_video_outputs(history)
if not outputs:
raise Exception('The ComfyUI workflow saved no video. Add a Save Video node to it.')
return [await get_video(entry, base_url, api_key) for entry in outputs]
+29 -5
View File
@@ -1,7 +1,8 @@
"""Video connections: the configured backends that built-in video generation runs on.
A connection is one OpenAI compatible server with a video API (``/videos``), such as LiteLLM,
OpenAI or OpenRouter, with the video models it exposes. Users pick a model by its reference,
OpenAI or OpenRouter, or a ComfyUI server running the admin's video workflow, with the video models it
exposes. Users pick a model by its reference,
``{connection_id}:{model_id}``, and only see models their access grants allow.
"""
@@ -24,6 +25,8 @@ from open_webui.utils.images.connections import (
IMAGE_CONNECTION_AUTH_TYPES,
_json_object,
_size,
_workflow,
_workflow_nodes,
get_image_model_ref,
get_openai_connection_models,
get_requested_model,
@@ -35,7 +38,7 @@ log = logging.getLogger(__name__)
VIDEO_CONNECTIONS_CONFIG_KEY = 'videos.connections'
VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY = 'video_generation.default_model'
VIDEO_CONNECTION_TYPES = ('openai',)
VIDEO_CONNECTION_TYPES = ('openai', 'comfyui')
VIDEO_CONNECTION_AUTH_TYPES = IMAGE_CONNECTION_AUTH_TYPES
# Like chat model connections: '' is the OpenAI video API (OpenAI, LiteLLM); OpenRouter has its own.
@@ -71,8 +74,10 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]:
auth_type = str(config.get('auth_type') or 'bearer')
if auth_type not in VIDEO_CONNECTION_AUTH_TYPES:
raise ValueError(f'Unsupported auth type: {auth_type}')
if connection_type != 'openai' and auth_type not in ('none', 'bearer'):
raise ValueError(f'{connection_type} connections support no auth or a key')
provider = str(config.get('provider') or '')
provider = str(config.get('provider') or '') if connection_type == 'openai' else ''
if provider not in VIDEO_CONNECTION_PROVIDERS:
raise ValueError(f'Unsupported video provider: {provider}')
@@ -84,6 +89,14 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]:
else:
seconds = None
fps = config.get('fps')
if fps not in (None, ''):
fps = float(fps)
if fps <= 0:
raise ValueError('Frame rate must be a positive number of frames per second (e.g. 24)')
else:
fps = None
return {
'id': connection_id,
'name': str(connection.get('name') or '').strip() or connection_type,
@@ -101,6 +114,9 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]:
'seconds': seconds,
'api_version': str(config.get('api_version') or ''),
'params': _json_object(config.get('params'), 'additional parameters'),
'workflow': _workflow(config.get('workflow'), 'ComfyUI workflow'),
'nodes': _workflow_nodes(config.get('nodes')),
'fps': fps,
},
}
@@ -108,7 +124,12 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]:
async def get_video_connection_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]:
"""The models a connection serves, with video models marked (``video``). OpenRouter lists its video
models on their own at ``/videos/models``; other servers list everything at ``/models``, and LiteLLM
marks which ones make video."""
marks which ones make video. ComfyUI offers the models its workflow's model node can load."""
if connection.get('type') == 'comfyui':
from open_webui.routers.images import get_comfyui_connection_models
return [{**model, 'video': True} for model in await get_comfyui_connection_models(connection)]
if get_video_connection_provider(connection) != 'openrouter':
return await get_openai_connection_models(request, connection, user)
@@ -157,7 +178,8 @@ async def get_synced_video_models(request: Request, connection: dict, user: User
async def get_video_models(request: Request, user: UserModel, *, bypass_access: bool = False) -> list[dict]:
"""Video models the user may use, across enabled connections. Each carries its connection for internal use.
A connection without model IDs offers every video model the server labels (LiteLLM), else its default model.
A connection without model IDs offers every video model the server labels (LiteLLM), else its default
model, or for ComfyUI the model its workflow sets.
"""
connections = await Config.get(VIDEO_CONNECTIONS_CONFIG_KEY) or []
user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)}
@@ -172,6 +194,8 @@ async def get_video_models(request: Request, user: UserModel, *, bypass_access:
if config.get('model_ids'):
entries = [{'id': model_id} for model_id in config['model_ids']]
elif connection.get('type') == 'comfyui':
entries = [{'id': ''}]
else:
entries = await get_synced_video_models(request, connection, user)
+4 -4
View File
@@ -321,8 +321,8 @@
bind:show
>
<div>
<div class=" flex justify-between dark:text-gray-100 px-5 pt-4 pb-1.5">
<h1 class="text-lg font-medium self-center font-primary">
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 pb-1.5">
<h1 class="text-sm font-medium self-center">
{#if edit}
{$i18n.t('Edit Connection')}
{:else}
@@ -336,7 +336,7 @@
show = false;
}}
>
<XMark className={'size-5'} />
<XMark className={'size-4'} />
</button>
</div>
@@ -349,7 +349,7 @@
submitHandler();
}}
>
<div class="px-1">
<div>
<div class="flex gap-2">
<div class="flex w-full justify-between items-center">
<div class=" text-xs text-gray-500">{$i18n.t('Connection Type')}</div>
@@ -118,19 +118,19 @@
size="sm"
ariaLabel={$i18n.t(edit ? 'Edit Terminal Connection' : 'Add Terminal Connection')}
>
<div class="flex items-center justify-between px-5 pb-2 pt-4 dark:text-gray-100">
<h2 class="font-primary text-lg font-medium">
<div class="flex items-center justify-between px-4 pb-2 pt-3 dark:text-gray-100">
<h2 class="text-sm font-medium">
{$i18n.t(edit ? 'Edit Terminal Connection' : 'Add Terminal Connection')}
</h2>
<button
type="button"
class="shrink-0 self-center"
on:click={() => (show = false)}
aria-label={$i18n.t('Close')}><XMark className="size-5" /></button
aria-label={$i18n.t('Close')}><XMark className="size-4" /></button
>
</div>
<form
class="space-y-2 px-5 pb-4 text-gray-900 dark:text-gray-100"
class="space-y-2 px-4 pb-4 text-gray-900 dark:text-gray-100"
on:submit|preventDefault={save}
>
{#if error}<p role="alert" class="text-sm text-gray-700 dark:text-gray-300">{error}</p>{/if}
+3 -3
View File
@@ -499,8 +499,8 @@
bind:show
>
<div>
<div class=" flex justify-between dark:text-gray-100 px-5 pt-4 pb-2">
<h1 class=" text-lg font-medium self-center font-primary">
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 pb-2">
<h1 class="text-sm font-medium self-center">
{#if edit}
{$i18n.t('Edit Connection')}
{:else}
@@ -555,7 +555,7 @@
submitHandler();
}}
>
<div class="px-1">
<div>
<div class="flex gap-2 mb-1.5">
<div class="flex w-full justify-between items-center">
<div class=" text-xs text-gray-500">{$i18n.t('Type')}</div>
+2 -2
View File
@@ -91,13 +91,13 @@
>
<div class="flex max-h-[58vh] flex-col">
<div
class="flex shrink-0 items-start justify-between gap-4 px-4 pb-2.5 pt-3.5 dark:text-white text-black"
class="flex shrink-0 items-start justify-between gap-4 px-4 pb-2.5 pt-3 dark:text-white text-black"
>
<div class="min-w-0">
<!-- LICENSE covers this Open WebUI release identifier.
Do not alter, remove, obscure, or replace it except as LICENSE permits:
https://docs.openwebui.com/license. -->
<h2 class="m-0 truncate text-base font-normal">
<h2 class="text-sm font-medium m-0 truncate">
{$i18n.t("What's New in")}
{$WEBUI_NAME}
</h2>
@@ -220,8 +220,8 @@
size="sm"
bind:show
>
<div class="flex justify-between dark:text-gray-100 px-5 pt-4 pb-2">
<h1 class="text-lg font-medium self-center font-primary">
<div class="flex justify-between dark:text-gray-100 px-4 pt-3 pb-2">
<h1 class="text-sm font-medium self-center">
{showScopes
? scopeMode === 'requested'
? $i18n.t('Requested scopes')
@@ -236,11 +236,11 @@
class="self-center"
on:click={() => {
show = false;
}}><XMark className="size-5" /></button
}}><XMark className="size-4" /></button
>
</div>
{#if showScopes}
<div class="px-5 pb-4 text-sm dark:text-gray-200">
<div class="px-4 pb-4 text-sm dark:text-gray-200">
<p class="mb-3 text-xs text-gray-500 dark:text-gray-400">
{scopeMode === 'requested'
? $i18n.t('Enter the scopes requested by the app.')
@@ -313,7 +313,7 @@
</div>
</div>
{:else}
<form class="px-5 pb-4 text-sm dark:text-gray-200" on:submit|preventDefault={submit}>
<form class="px-4 pb-4 text-sm dark:text-gray-200" on:submit|preventDefault={submit}>
{#if loading}<div class="flex justify-center py-4"><Spinner className="size-5" /></div>
{:else}
{#if !manifest}<AdminSettingField
@@ -163,8 +163,8 @@
bind:show
>
<div>
<div class=" flex justify-between dark:text-gray-100 px-5 pt-4 pb-2">
<div class=" text-lg font-medium self-center font-primary">
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 pb-2">
<div class="text-sm font-medium self-center">
{#if edit}
{$i18n.t('Edit Arena Model')}
{:else}
@@ -178,7 +178,7 @@
show = false;
}}
>
<XMark className={'size-5'} />
<XMark className={'size-4'} />
</button>
</div>
@@ -190,7 +190,7 @@
submitHandler();
}}
>
<div class="px-1">
<div>
<div class="flex justify-end mb-3">
<LanguageModeSelect
bind:value={locale}
@@ -14,6 +14,7 @@
export let workflow = '';
export let nodes: WorkflowNode[] = [];
export let requiredTypes: string[] = ['prompt'];
export let requiredNote = '';
const inputClass =
'w-full bg-transparent text-sm outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700';
@@ -51,18 +52,17 @@
</div>
<div class="flex items-center gap-2 shrink-0">
{#if workflow}
<button
class="text-xs text-gray-500 transition-colors hover:text-gray-900 hover:underline dark:hover:text-white"
type="button"
aria-label={$i18n.t('settings.admin.images.editWorkflowJsonContent.label')}
on:click={() => {
showEditor = true;
}}
>
{$i18n.t('Edit')}
</button>
{/if}
<!-- Always available, so a workflow can be pasted in as well as uploaded. -->
<button
class="text-xs text-gray-500 transition-colors hover:text-gray-900 hover:underline dark:hover:text-white"
type="button"
aria-label={$i18n.t('settings.admin.images.editWorkflowJsonContent.label')}
on:click={() => {
showEditor = true;
}}
>
{$i18n.t('Edit')}
</button>
<Tooltip content={$i18n.t('settings.admin.images.clickHereToUploadAWorkflowJsonFile.label')}>
<button
@@ -83,7 +83,9 @@
bind:show={showEditor}
value={workflow}
lang="json"
onChange={(value) => {
title={label}
description={$i18n.t('Paste or edit a workflow exported as API format from ComfyUI.')}
onChange={(value: string) => {
workflow = value;
}}
/>
@@ -128,7 +130,7 @@
</div>
<div class="mt-1 text-xs text-gray-400 dark:text-gray-500">
{$i18n.t('*Prompt node ID(s) are required for image generation')}
{requiredNote || $i18n.t('*Prompt node ID(s) are required for image generation')}
</div>
{/if}
</div>
@@ -318,8 +318,8 @@
bind:show
>
<div>
<div class=" flex justify-between dark:text-gray-100 px-5 pt-4 pb-1.5">
<h1 class="text-lg font-medium self-center font-primary">
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 pb-1.5">
<h1 class="text-sm font-medium self-center">
{#if edit}
{$i18n.t('Edit Connection')}
{:else}
@@ -333,7 +333,7 @@
show = false;
}}
>
<XMark className={'size-5'} />
<XMark className={'size-4'} />
</button>
</div>
@@ -346,7 +346,7 @@
submitHandler();
}}
>
<div class="px-1">
<div>
<div class="flex flex-row justify-between items-center w-full">
<label for="image-connection-type-select" class="text-xs text-gray-500"
>{$i18n.t('Connection Type')}</label
@@ -203,16 +203,16 @@
size="sm"
bind:show
>
<div class="px-5 pb-5 pt-4 dark:text-gray-200">
<div class="px-4 pb-4 pt-3 dark:text-gray-200">
<div class="mb-3 flex items-center justify-between gap-3">
<div class="font-primary text-lg font-medium">
<div class="text-sm font-medium">
{editingKey ? $i18n.t('Edit control') : $i18n.t('Add control')}
</div>
<button
type="button"
class={actionClass}
aria-label={$i18n.t('Close')}
on:click={() => (show = false)}><XMark className="size-5" /></button
on:click={() => (show = false)}><XMark className="size-4" /></button
>
</div>
<form class="space-y-2.5" on:submit|preventDefault|stopPropagation={apply}>
@@ -17,6 +17,10 @@
import Textarea from '$lib/components/common/Textarea.svelte';
import AccessButton from '$lib/components/common/AccessButton.svelte';
import AccessControlModal from '$lib/components/workspace/common/AccessControlModal.svelte';
import ComfyUIWorkflow from '$lib/components/admin/Settings/Images/ComfyUIWorkflow.svelte';
type ConnectionType = 'openai' | 'comfyui';
type WorkflowNode = { type: string; key: string; node_ids: string };
export let onSubmit: Function = () => {};
export let onDelete: Function = () => {};
@@ -26,6 +30,21 @@
export let connection: any = null;
// Input keys of the usual nodes in a Wan, LTX-Video or HunyuanVideo workflow.
const VIDEO_WORKFLOW_NODES: WorkflowNode[] = [
{ type: 'prompt', key: 'text', node_ids: '' },
{ type: 'negative_prompt', key: 'text', node_ids: '' },
{ type: 'model', key: 'unet_name', node_ids: '' },
{ type: 'image', key: 'image', node_ids: '' },
{ type: 'width', key: 'width', node_ids: '' },
{ type: 'height', key: 'height', node_ids: '' },
{ type: 'length', key: 'length', node_ids: '' },
{ type: 'fps', key: 'fps', node_ids: '' },
{ type: 'steps', key: 'steps', node_ids: '' },
{ type: 'seed', key: 'seed', node_ids: '' }
];
let connectionType: ConnectionType = 'openai';
let name = '';
let url = '';
let key = '';
@@ -43,6 +62,9 @@
let provider = '';
let params = '';
let headers = '';
let fps = '';
let workflow = '';
let nodes: WorkflowNode[] = [];
let loading = false;
let showDeleteConfirmDialog = false;
@@ -54,6 +76,35 @@
const selectClass =
'bg-transparent pr-5 outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700';
$: typeLabel = {
openai: $i18n.t('OpenAI compatible'),
comfyui: $i18n.t('ComfyUI')
}[connectionType];
// Only OpenAI compatible connections authenticate the way chat model connections do.
$: if (connectionType !== 'openai' && !['none', 'bearer'].includes(auth_type)) {
auth_type = 'bearer';
}
const mapNodes = (defaults: WorkflowNode[], saved: any[] = []) =>
defaults.map((node) => {
const match = saved.find((n) => n.type === node.type) ?? node;
return {
type: match.type,
key: match.key,
node_ids: Array.isArray(match.node_ids) ? match.node_ids.join(',') : (match.node_ids ?? '')
};
});
const toNodeConfig = (workflowNodes: WorkflowNode[]) =>
workflowNodes.map((node) => ({
...node,
node_ids: node.node_ids
.split(',')
.map((id) => id.trim())
.filter(Boolean)
}));
const formatJSON = (value: any) => {
if (!value) return '';
if (typeof value === 'object') {
@@ -85,6 +136,21 @@
toast.error($i18n.t('Enter Video Length in seconds (e.g. 8)'));
return false;
}
if (connectionType === 'comfyui') {
if (!workflow.trim()) {
toast.error($i18n.t('Upload a ComfyUI workflow to generate videos'));
return false;
}
if (!isJSONObject(workflow)) {
toast.error($i18n.t('Invalid JSON format for ComfyUI Workflow.'));
return false;
}
if (fps !== '' && !(Number(fps) > 0)) {
showAdvanced = true;
toast.error($i18n.t('Enter Frame Rate in frames per second (e.g. 24)'));
return false;
}
}
if (headers.trim() && !isJSONObject(headers)) {
showAdvanced = true;
toast.error($i18n.t('Headers must be a valid JSON object'));
@@ -100,10 +166,10 @@
const buildConnection = () => ({
...(connection?.id ? { id: connection.id } : {}),
name: name.trim() || $i18n.t('OpenAI compatible'),
type: 'openai',
name: name.trim() || typeLabel,
type: connectionType,
url,
key,
key: connectionType !== 'openai' && auth_type === 'none' ? '' : key,
config: {
enable,
model_ids: modelIds,
@@ -111,10 +177,13 @@
size: size.trim(),
seconds: seconds === '' ? null : Number(seconds),
api_version: apiVersion.trim(),
provider,
provider: connectionType === 'openai' ? provider : '',
auth_type,
headers: headers.trim() ? JSON.parse(headers) : {},
params: params.trim() ? JSON.parse(params) : {}
headers: connectionType === 'openai' && headers.trim() ? JSON.parse(headers) : {},
params: connectionType === 'openai' && params.trim() ? JSON.parse(params) : {},
workflow: connectionType === 'comfyui' ? workflow.trim() : '',
nodes: connectionType === 'comfyui' ? toNodeConfig(nodes) : [],
fps: connectionType === 'comfyui' && fps !== '' ? Number(fps) : null
}
});
@@ -183,6 +252,7 @@
showAdvanced = false;
modelId = '';
connectionType = connection?.type ?? 'openai';
name = connection?.name ?? '';
url = connection?.url ?? '';
key = connection?.key ?? '';
@@ -197,6 +267,9 @@
provider = config.provider ?? '';
params = formatJSON(config.params);
headers = formatJSON(config.headers);
fps = config.fps === null || config.fps === undefined ? '' : `${config.fps}`;
workflow = formatJSON(config.workflow);
nodes = mapNodes(VIDEO_WORKFLOW_NODES, config.nodes ?? []);
};
$: if (show) {
@@ -214,8 +287,8 @@
bind:show
>
<div>
<div class=" flex justify-between dark:text-gray-100 px-5 pt-4 pb-1.5">
<h1 class="text-lg font-medium self-center font-primary">
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 pb-1.5">
<h1 class="text-sm font-medium self-center">
{#if edit}
{$i18n.t('Edit Connection')}
{:else}
@@ -229,7 +302,7 @@
show = false;
}}
>
<XMark className={'size-5'} />
<XMark className={'size-4'} />
</button>
</div>
@@ -242,7 +315,27 @@
submitHandler();
}}
>
<div class="px-1">
<div>
<div class="flex flex-row justify-between items-center w-full mb-2">
<label for="video-connection-type-select" class="text-xs text-gray-500"
>{$i18n.t('Connection Type')}</label
>
<div>
<select
id="video-connection-type-select"
bind:value={connectionType}
on:change={() => {
availableModelIds = [];
}}
class="text-xs text-gray-700 dark:text-gray-300 bg-transparent pr-5 outline-hidden"
>
<option value="openai">{$i18n.t('OpenAI compatible')}</option>
<option value="comfyui">{$i18n.t('ComfyUI')}</option>
</select>
</div>
</div>
<div class="flex gap-2">
<div class="flex flex-col w-full">
<label for="video-connection-name" class="mb-0.5 text-xs text-gray-500"
@@ -274,9 +367,11 @@
class={`w-full text-sm ${inputClass}`}
type="text"
bind:value={url}
placeholder={$i18n.t('API Base URL')}
placeholder={connectionType === 'comfyui'
? 'http://localhost:8188'
: $i18n.t('API Base URL')}
autocomplete="off"
list="video-connection-openai-urls"
list={connectionType === 'openai' ? 'video-connection-openai-urls' : undefined}
required
/>
@@ -337,9 +432,11 @@
>
<option value="none">{$i18n.t('None')}</option>
<option value="bearer">{$i18n.t('Bearer')}</option>
<option value="session">{$i18n.t('Session')}</option>
<option value="system_oauth">{$i18n.t('OAuth')}</option>
<option value="microsoft_entra_id">{$i18n.t('Entra ID')}</option>
{#if connectionType === 'openai'}
<option value="session">{$i18n.t('Session')}</option>
<option value="system_oauth">{$i18n.t('OAuth')}</option>
<option value="microsoft_entra_id">{$i18n.t('Entra ID')}</option>
{/if}
</select>
</div>
@@ -404,10 +501,14 @@
</ul>
{:else}
<div class={`text-gray-500 text-xs text-center py-2 px-10`}>
{$i18n.t(
'Leave empty to include all video models from "{{url}}/models" endpoint, or the server\'s default model if it does not mark which models make videos',
{ url }
)}
{#if connectionType === 'comfyui'}
{$i18n.t('Leave empty to use the model set in the workflow')}
{:else}
{$i18n.t(
'Leave empty to include all video models from "{{url}}/models" endpoint, or the server\'s default model if it does not mark which models make videos',
{ url }
)}
{/if}
</div>
{/if}
</div>
@@ -450,6 +551,22 @@
</div>
</div>
{#if connectionType === 'comfyui'}
<ComfyUIWorkflow
id="video-connection-workflow"
label={$i18n.t('Video Workflow')}
description={$i18n.t(
'Upload a workflow.json file exported as API format from ComfyUI. It must save its result with a Save Video node.'
)}
bind:workflow
bind:nodes
requiredTypes={['prompt']}
requiredNote={$i18n.t(
'*Prompt node ID(s) are required. Length is set in frames; the image node takes the starting frame.'
)}
/>
{/if}
<div class="flex items-center justify-between">
<button
type="button"
@@ -511,84 +628,102 @@
</div>
</div>
<div class="flex flex-row justify-between items-center w-full mt-2">
<label for="video-connection-provider" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Provider')}</label
>
<div>
<select
id="video-connection-provider"
bind:value={provider}
class="text-xs text-gray-700 dark:text-gray-300 bg-transparent pr-5 outline-hidden"
>
<option value="">{$i18n.t('Default')}</option>
<option value="openrouter">{$i18n.t('OpenRouter')}</option>
</select>
</div>
</div>
{#if provider !== 'openrouter' && !url.includes('openrouter.ai')}
{#if connectionType === 'comfyui'}
<div class="flex gap-2 mt-2">
<div class="flex flex-col w-full">
<label for="video-connection-api-version" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('API Version')}</label
<label for="video-connection-fps" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Frame Rate')}</label
>
<input
id="video-connection-api-version"
id="video-connection-fps"
class={`w-full text-sm ${inputClass}`}
type="text"
bind:value={apiVersion}
placeholder={$i18n.t('API Version')}
bind:value={fps}
placeholder={$i18n.t("Leave empty to use the workflow's frame rate")}
autocomplete="off"
/>
</div>
</div>
{/if}
<div class="flex gap-2 mt-2">
<div class="flex flex-col w-full">
<label for="video-connection-headers" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Headers')}</label
{:else}
<div class="flex flex-row justify-between items-center w-full mt-2">
<label for="video-connection-provider" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Provider')}</label
>
<div class="flex-1">
<Tooltip
content={$i18n.t(
'Enter additional headers in JSON format (e.g. {"X-Custom-Header": "value"}'
)}
<div>
<select
id="video-connection-provider"
bind:value={provider}
class="text-xs text-gray-700 dark:text-gray-300 bg-transparent pr-5 outline-hidden"
>
<option value="">{$i18n.t('Default')}</option>
<option value="openrouter">{$i18n.t('OpenRouter')}</option>
</select>
</div>
</div>
{#if provider !== 'openrouter' && !url.includes('openrouter.ai')}
<div class="flex gap-2 mt-2">
<div class="flex flex-col w-full">
<label for="video-connection-api-version" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('API Version')}</label
>
<input
id="video-connection-api-version"
class={`w-full text-sm ${inputClass}`}
type="text"
bind:value={apiVersion}
placeholder={$i18n.t('API Version')}
autocomplete="off"
/>
</div>
</div>
{/if}
<div class="flex gap-2 mt-2">
<div class="flex flex-col w-full">
<label for="video-connection-headers" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Headers')}</label
>
<div class="flex-1">
<Tooltip
content={$i18n.t(
'Enter additional headers in JSON format (e.g. {"X-Custom-Header": "value"}'
)}
>
<Textarea
id="video-connection-headers"
className="w-full text-sm outline-hidden"
bind:value={headers}
placeholder={$i18n.t('Enter additional headers in JSON format')}
required={false}
minSize={30}
/>
</Tooltip>
</div>
</div>
</div>
<div class="flex gap-2 mt-2">
<div class="flex flex-col w-full">
<label for="video-connection-params" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Additional Parameters')}</label
>
<div class="flex-1">
<Textarea
id="video-connection-headers"
id="video-connection-params"
className="w-full text-sm outline-hidden"
bind:value={headers}
placeholder={$i18n.t('Enter additional headers in JSON format')}
bind:value={params}
placeholder={$i18n.t('Enter additional parameters in JSON format')}
required={false}
minSize={30}
/>
</Tooltip>
</div>
</div>
</div>
</div>
<div class="flex gap-2 mt-2">
<div class="flex flex-col w-full">
<label for="video-connection-params" class="mb-0.5 text-xs text-gray-500"
>{$i18n.t('Additional Parameters')}</label
>
<div class="flex-1">
<Textarea
id="video-connection-params"
className="w-full text-sm outline-hidden"
bind:value={params}
placeholder={$i18n.t('Enter additional parameters in JSON format')}
required={false}
minSize={30}
/>
</div>
</div>
</div>
{/if}
{/if}
</div>
@@ -66,7 +66,7 @@
<div>
<!-- Header -->
<div class="flex justify-between items-center dark:text-gray-100 px-4 pt-3 pb-1">
<h3 class="text-base font-normal">{calendar ? $i18n.t('Edit') : $i18n.t('New Calendar')}</h3>
<h3 class="text-sm font-medium">{calendar ? $i18n.t('Edit') : $i18n.t('New Calendar')}</h3>
<button
class="self-center shrink-0 ml-2"
aria-label={$i18n.t('Close')}
@@ -103,7 +103,7 @@
>
<div class="flex max-h-[calc(100dvh-3rem)] flex-col">
<div class="flex shrink-0 justify-between dark:text-gray-100 px-4 pt-3 mb-1">
<div class="self-center text-base">
<div class="text-sm font-medium self-center">
<div class="flex items-center gap-0.5 shrink-0">
{#if channel?.type === 'dm'}
<div class=" text-left self-center overflow-hidden w-full line-clamp-1 flex-1">
@@ -88,7 +88,7 @@
<Modal ariaLabel={$i18n.t('Add Members')} size="sm" bind:show>
<div>
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 mb-1">
<div class="self-center text-base">
<div class="text-sm font-medium self-center">
<div class="flex items-center gap-0.5 shrink-0">
{$i18n.t('Add Members')}
</div>
@@ -329,7 +329,7 @@
<Modal bind:show={showParticipants} size="sm" ariaLabel={$i18n.t('Participants')}>
<div class="flex items-center justify-between px-4 pt-3 mb-1 dark:text-gray-100">
<h2 class="text-base font-normal">{$i18n.t('Participants')}</h2>
<h2 class="text-sm font-medium">{$i18n.t('Participants')}</h2>
<button
type="button"
aria-label={$i18n.t('Close')}
@@ -70,7 +70,7 @@
<Modal ariaLabel={$i18n.t('Pinned Messages')} size="sm" bind:show>
<div>
<div class=" flex justify-between dark:text-gray-100 px-4 pt-3 mb-1">
<div class="self-center text-base">
<div class="text-sm font-medium self-center">
<div class="flex items-center gap-0.5 shrink-0">
{$i18n.t('Pinned Messages')}
</div>
@@ -101,7 +101,7 @@
<div>
<div class="flex justify-between dark:text-gray-100 px-4 pt-3 mb-1">
<div class="flex w-full justify-between items-center mr-3">
<div class="self-center text-base flex gap-1.5 items-center">
<div class="text-sm font-medium self-center flex gap-1.5 items-center">
<div>{$i18n.t('Webhooks')}</div>
<span class="text-sm text-gray-500">{webhooks.length}</span>
</div>
@@ -53,8 +53,8 @@
<Modal ariaLabel={edit ? $i18n.t('Edit Memory') : $i18n.t('Add Memory')} bind:show size="sm">
<div>
<div class=" flex justify-between dark:text-gray-300 px-5 pt-4 pb-2">
<div class=" text-lg font-medium self-center">
<div class=" flex justify-between dark:text-gray-300 px-4 pt-3 pb-2">
<div class="text-sm font-medium self-center">
{#if edit}
{$i18n.t('Edit Memory')}
{:else}
@@ -62,14 +62,14 @@
{/if}
</div>
<button aria-label={$i18n.t('Close')} class="self-center" on:click={() => (show = false)}>
<XMark className={'size-5'} />
<XMark className={'size-4'} />
</button>
</div>
<div class="flex flex-col md:flex-row w-full px-4 pb-4 md:space-x-4 dark:text-gray-200">
<div class=" flex flex-col w-full sm:flex-row sm:justify-center sm:space-x-6">
<form class="flex flex-col w-full" on:submit|preventDefault={submitHandler}>
<div class="px-1">
<div>
<div class="flex w-full justify-between items-center mb-1.5">
<div class="text-xs text-gray-500">{$i18n.t('Type')}</div>
@@ -331,8 +331,8 @@
>
<div class="w-full">
{#if completed}
<div class="px-5.5 py-5">
<div class="mb-1 text-xl font-normal">{$i18n.t('Sync Complete!')}</div>
<div class="px-4 py-4">
<div class="text-sm font-medium mb-1">{$i18n.t('Sync Complete!')}</div>
<div class="mb-3 text-xs text-gray-500">
{$i18n.t('Your usage stats have been successfully synced.')}
</div>
@@ -349,8 +349,8 @@
</div>
</div>
{:else if error}
<div class="px-5.5 py-5">
<div class="mb-1 text-xl font-normal">{$i18n.t('Sync Failed')}</div>
<div class="px-4 py-4">
<div class="text-sm font-medium mb-1">{$i18n.t('Sync Failed')}</div>
<div class="mb-3 text-xs text-gray-500">
{errorMessage || $i18n.t('There was an error syncing your stats. Please try again.')}
</div>
+3 -3
View File
@@ -38,11 +38,11 @@
</div>
{#if selectedSkills.length > 0}
<div class=" flex justify-between dark:text-gray-300 px-5 pb-1">
<div class=" text-base font-normal self-center">{$i18n.t('Skills')}</div>
<div class=" flex justify-between dark:text-gray-300 px-4 pb-1">
<div class="text-xs text-gray-500 self-center">{$i18n.t('Skills')}</div>
</div>
<div class="px-5 pb-5 w-full flex flex-col justify-center">
<div class="px-4 pb-4 w-full flex flex-col justify-center">
<div class=" text-sm dark:text-gray-300 mb-1">
{#each selectedSkills as skill}
<Collapsible buttonClassName="w-full mb-0.5">
@@ -82,8 +82,8 @@
{#if selectedTools.length > 0}
{#if selectedToolServers.length > 0}
<div class=" flex justify-between dark:text-gray-300 px-5 pb-1">
<div class=" text-base font-normal self-center">{$i18n.t('Tools')}</div>
<div class=" flex justify-between dark:text-gray-300 px-4 pb-1">
<div class="text-xs text-gray-500 self-center">{$i18n.t('Tools')}</div>
</div>
{/if}
@@ -179,11 +179,11 @@
{/if}
{#if selectedToolServers.length > 0}
<div class=" flex justify-between dark:text-gray-300 px-5 pb-0.5">
<div class=" text-base font-normal self-center">{$i18n.t('Tool Servers')}</div>
<div class=" flex justify-between dark:text-gray-300 px-4 pb-0.5">
<div class="text-xs text-gray-500 self-center">{$i18n.t('Tool Servers')}</div>
</div>
<div class="px-5 pb-5 w-full flex flex-col justify-center">
<div class="px-4 pb-4 w-full flex flex-col justify-center">
<div class=" text-xs text-gray-600 dark:text-gray-300 mb-2">
<!-- LICENSE covers this Open WebUI wordmark.
Do not alter, remove, obscure, or replace it except as LICENSE permits:
+7 -2
View File
@@ -317,8 +317,13 @@ print("${endTag}")
if (!readOnly) onSave();
}
// Format code when Ctrl + Shift + F is pressed
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'f') {
// Format Python code when Ctrl + Shift + F is pressed (the formatter is Black)
if (
lang === 'python' &&
(e.ctrlKey || e.metaKey) &&
e.shiftKey &&
e.key.toLowerCase() === 'f'
) {
e.preventDefault();
await formatPythonCodeHandler();
}
+126 -33
View File
@@ -1,65 +1,158 @@
<script lang="ts">
import { onMount, getContext } from 'svelte';
import { getContext, untrack } from 'svelte';
import CodeEditor from './CodeEditor.svelte';
import Drawer from './Drawer.svelte';
import Modal from './Modal.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
const i18n: any = getContext('i18n');
let {
show = $bindable(),
value = $bindable(),
show = $bindable(false),
value = '',
lang = 'python',
onChange = () => {},
title = '',
description = '',
onChange = (_value: string) => {},
onSave = () => {}
}: {
show?: boolean;
value?: string;
lang?: string;
title?: string;
description?: string;
onChange?: (value: string) => void;
onSave?: () => void;
} = $props();
let boilerplate = ``;
let codeEditor = $state(null);
let _content = $state(value);
// Edits stay in a draft until saved, so closing (or Escape) discards them.
let draft = $state('');
$effect(() => {
if (_content !== undefined && _content !== null) {
value = _content;
if (show) {
draft = untrack(() => value) ?? '';
}
});
const jsonError = $derived.by(() => {
if (lang !== 'json' || !draft.trim()) return '';
try {
JSON.parse(draft);
return '';
} catch (e) {
return e instanceof Error ? e.message : `${e}`;
}
});
const format = () => {
if (lang !== 'json' || !draft.trim() || jsonError) return;
draft = JSON.stringify(JSON.parse(draft), null, 2);
};
const save = () => {
if (jsonError) return;
onChange(draft);
onSave();
show = false;
};
</script>
<Drawer bind:show className="h-full" zIndexClass="z-99999" ariaLabel={$i18n.t('Code Editor')}>
<div class="flex h-full flex-col">
<div
class=" sticky top-0 z-30 flex justify-between bg-white px-4.5 pt-3 pb-3 dark:bg-gray-900 dark:text-gray-100"
>
<div class=" self-center text-lg font-normal">
{$i18n.t('Code Editor')}
<Modal bind:show size="lg" ariaLabel={title || $i18n.t('Code Editor')}>
<div class="flex h-[min(80dvh,46rem)] flex-col dark:text-gray-200">
<div class="flex items-start justify-between gap-4 px-4 pt-3 pb-2">
<div class="min-w-0">
<h1 class="text-sm font-medium text-gray-900 dark:text-gray-100">
{title || $i18n.t('Code Editor')}
</h1>
{#if description}
<div class="text-xs text-gray-500 line-clamp-1">{description}</div>
{/if}
</div>
<button
class="self-center"
class="shrink-0 self-start mt-0.5"
type="button"
aria-label={$i18n.t('Close')}
onclick={() => {
show = false;
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="h-5 w-5"
>
<path
d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
/>
</svg>
<XMark className="size-4" />
</button>
</div>
<div
class="flex h-full w-full flex-1 flex-col md:flex-row md:space-x-4 dark:text-gray-200 overflow-y-auto"
class="code-editor-modal mx-4 min-h-0 flex-1 overflow-hidden rounded-2xl border border-gray-100/80 bg-gray-50/60 py-1 dark:border-gray-850 dark:bg-gray-950/40"
>
<div class=" flex h-full w-full flex-col sm:flex-row sm:justify-center sm:space-x-6">
<CodeEditor bind:this={codeEditor} {value} {boilerplate} {lang} {onChange} {onSave} />
<CodeEditor
value={draft}
{lang}
ariaLabel={title || $i18n.t('Code Editor')}
className="text-xs"
onChange={(content: string) => {
draft = content;
}}
onSave={save}
/>
</div>
<div class="flex items-center justify-between gap-3 px-4 pt-3 pb-4">
<div class="min-w-0 flex items-center gap-3 text-xs">
{#if lang === 'json'}
<button
class="shrink-0 text-gray-500 transition hover:text-gray-900 hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed dark:hover:text-white"
type="button"
disabled={!draft.trim() || !!jsonError}
onclick={format}
>
{$i18n.t('Format')}
</button>
{/if}
{#if jsonError}
<div class="truncate text-red-500 dark:text-red-400" title={jsonError}>
{$i18n.t('Invalid JSON')}: {jsonError}
</div>
{/if}
</div>
<div class="flex shrink-0 items-center gap-2">
<button
class="px-1 py-1.5 text-xs text-gray-500 transition hover:text-gray-700 hover:underline dark:text-gray-400 dark:hover:text-gray-200"
type="button"
onclick={() => {
show = false;
}}
>
{$i18n.t('Cancel')}
</button>
<button
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-gray-900 px-2.5 text-xs font-normal text-white transition hover:bg-black disabled:cursor-not-allowed disabled:opacity-60 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"
type="button"
disabled={!!jsonError}
onclick={save}
>
{$i18n.t('Save')}
</button>
</div>
</div>
</div>
</Drawer>
</Modal>
<style>
/* Sit on the panel instead of the editor's own white/black (or One Dark) background. */
.code-editor-modal :global(.cm-editor),
.code-editor-modal :global(.cm-gutters) {
background-color: transparent !important;
}
.code-editor-modal :global(.cm-gutters) {
color: var(--color-gray-400);
}
.code-editor-modal :global(.cm-activeLine),
.code-editor-modal :global(.cm-activeLineGutter) {
background-color: color-mix(in oklab, currentColor 4%, transparent) !important;
}
</style>
@@ -255,11 +255,11 @@
</script>
<Modal ariaLabel={item?.name ?? $i18n.t('File')} bind:show size="lg">
<div class=" px-4.5 py-3.5 w-full flex flex-col justify-center dark:text-gray-400">
<div class=" px-4 py-3 w-full flex flex-col justify-center dark:text-gray-400">
<div class=" pb-2">
<div class="flex items-start justify-between">
<div>
<div class=" font-normal text-lg dark:text-gray-100">
<div class="text-sm font-medium dark:text-gray-100">
<a
href={item?.type === 'file'
? item?.url?.startsWith('http')
+2 -2
View File
@@ -26,9 +26,9 @@
<Drawer bind:show ariaLabel={$i18n.t('Input')}>
<div class="flex h-full min-h-screen flex-col" {oninput}>
<div
class=" sticky top-0 z-30 flex justify-between bg-white px-4.5 pt-3 pb-3 dark:bg-gray-900 dark:text-gray-100"
class=" sticky top-0 z-30 flex justify-between bg-white px-4 pt-3 pb-2 dark:bg-gray-900 dark:text-gray-100"
>
<div class=" self-center text-lg">
<div class="text-sm font-medium self-center">
{$i18n.t('Input')}
</div>
<button
@@ -32,7 +32,7 @@
<div>
<!-- Header -->
<div class="flex justify-between items-center dark:text-gray-100 px-4 pt-3 pb-1">
<h3 class="text-base font-normal">{$i18n.t('New Directory')}</h3>
<h3 class="text-sm font-medium">{$i18n.t('New Directory')}</h3>
<button
class="self-center shrink-0 ml-2"
aria-label={$i18n.t('Close')}
@@ -73,8 +73,8 @@
<div class="w-full max-h-full">
{#if modal}
<div class="flex justify-between items-center dark:text-gray-100 px-5 pt-4 pb-2">
<h3 class="text-base font-normal">
<div class="flex justify-between items-center dark:text-gray-100 px-4 pt-3 pb-2">
<h3 class="text-sm font-medium">
{$i18n.t(edit ? 'Settings' : 'Create a knowledge base')}
</h3>
<button
@@ -85,7 +85,7 @@
onBack();
}}
>
<XMark className="size-5" />
<XMark className="size-4" />
</button>
</div>
{:else}
@@ -114,7 +114,7 @@
{/if}
<form
class="flex flex-col {modal ? 'px-5 pb-3' : 'max-w-lg mx-auto mt-10 mb-10'}"
class="flex flex-col {modal ? 'px-4 pb-3' : 'max-w-lg mx-auto mt-10 mb-10'}"
on:submit|preventDefault={() => {
submitHandler();
}}
@@ -45,9 +45,9 @@
</button>
<Modal ariaLabel={$i18n.t('Avatar setup')} bind:show size="sm">
<div class="p-5 text-gray-900 dark:text-gray-100">
<div class="p-4 text-gray-900 dark:text-gray-100">
<div class="flex items-center justify-between gap-3">
<h2 class="text-base font-medium">{$i18n.t('Avatar setup')}</h2>
<h2 class="text-sm font-medium">{$i18n.t('Avatar setup')}</h2>
<button
type="button"
class="py-1 rounded-lg text-gray-500 hover:text-gray-900 dark:hover:text-gray-100 px-0"