diff --git a/backend/open_webui/routers/machines.py b/backend/open_webui/routers/machines.py index ca758c37dc..1ebc41dddc 100644 --- a/backend/open_webui/routers/machines.py +++ b/backend/open_webui/routers/machines.py @@ -96,6 +96,7 @@ class CreateForm(Pinned): name: str = Field('', max_length=100) version: str = Field('latest', max_length=20) # 'latest' or an exact Open Terminal version start_dir: str = Field('', max_length=1024) + flags: str = Field('', max_length=1024) # extra flags for `open-terminal run` # For `open-terminal install-deps`: dependency sets it knows by name, and apt packages. Needs passwordless sudo. deps: list[str] = Field(default_factory=list, max_length=16) packages: list[str] = Field(default_factory=list, max_length=64) @@ -106,6 +107,7 @@ class LocalForm(BaseModel): name: str = Field('', max_length=100) version: str = Field('latest', max_length=20) start_dir: str = Field('', max_length=1024) # empty: the project folder Open WebUI picks + flags: str = Field('', max_length=1024) class UpgradeForm(BaseModel): @@ -119,8 +121,9 @@ class InstallForm(BaseModel): packages: list[str] = Field(default_factory=list, max_length=64) -class StartDirForm(BaseModel): +class ConfigureForm(BaseModel): start_dir: str = Field('', max_length=1024) # empty: the default (home over SSH) + flags: str = Field('', max_length=1024) def _ssh_fail(error: BaseException): @@ -171,6 +174,7 @@ async def create_machine(request: Request, form: CreateForm, user=Depends(get_ad version = managed.requested_version(form.version) managed.install_args(form.deps, form.packages) start_dir = managed.clean_start_dir(form.start_dir) or None + flags = managed.clean_flags(form.flags) except MachineError as error: _ssh_fail(error) target = form.model_dump(include={'host', 'port', 'username', 'host_key'}) @@ -183,6 +187,7 @@ async def create_machine(request: Request, form: CreateForm, user=Depends(get_ad target=target, version=version, start_dir=start_dir, + flags=flags, deps=form.deps, packages=form.packages, ) @@ -211,11 +216,19 @@ async def create_local_machine(request: Request, form: LocalForm, user=Depends(g try: version = managed.requested_version(form.version) start_dir = managed.clean_start_dir(form.start_dir) or None + flags = managed.clean_flags(form.flags) except MachineError as error: _ssh_fail(error) _ssh_start( managed.provision( - request, form.id, user.id, name=form.name, is_local=True, version=version, start_dir=start_dir + request, + form.id, + user.id, + name=form.name, + is_local=True, + version=version, + start_dir=start_dir, + flags=flags, ) ) return {'id': form.id, 'status': 'installing'} @@ -258,11 +271,11 @@ async def install_machine_packages(request: Request, machine_id: str, form: Inst return {'id': machine_id, 'status': 'installing'} -@router.post('/managed/{machine_id}/directory') -async def set_machine_start_dir(machine_id: str, form: StartDirForm, user=Depends(get_admin_user)): - """Change where terminal sessions start, then restart Open Terminal there.""" +@router.post('/managed/{machine_id}/configure') +async def configure_machine(machine_id: str, form: ConfigureForm, user=Depends(get_admin_user)): + """Change where terminal sessions start and the Open Terminal flags, then restart Open Terminal with them.""" try: - await managed.set_start_dir(machine_id, form.start_dir) + await managed.configure(machine_id, form.start_dir, form.flags) except Exception as error: _ssh_fail(error) return {'status': True} diff --git a/backend/open_webui/utils/machines/bootstrap.sh b/backend/open_webui/utils/machines/bootstrap.sh index 7a18ec9bc5..cde2e5e02e 100644 --- a/backend/open_webui/utils/machines/bootstrap.sh +++ b/backend/open_webui/utils/machines/bootstrap.sh @@ -1,10 +1,12 @@ # Run by utils/machines/managed.py on stdin, over SSH or on this computer. Tokens (__OPEN_WEBUI_*__) are -# validated before rendering; START_DIR (where sessions start, empty for home) and DEPS (arguments for -# `open-terminal install-deps`, empty for none) are set on the lines above. +# validated before rendering; START_DIR (where sessions start, empty for home), FLAGS (extra, shell-quoted +# `open-terminal run` flags) and DEPS (arguments for `open-terminal install-deps`, empty for none) are set +# on the lines above. # Output lines starting with OPEN_WEBUI: drive the progress UI; everything else is log. set -eu ROOT="${OPEN_WEBUI_MACHINES_DIR:-$HOME/.open-webui}/__OPEN_WEBUI_ID__" START_DIR="${START_DIR:-}" +FLAGS="${FLAGS:-}" DEPS="${DEPS:-}" VERSION="__OPEN_WEBUI_VERSION__" @@ -67,7 +69,8 @@ SOCK="$ROOT/run/api.sock" MATCH="open-terminal run --ipc $SOCK" ours() { ps -ww -eo pid=,args= 2>/dev/null | awk -v m="$MATCH" 'index($0, m) && $2 !~ /(^|\/)awk$/ {print $1}'; } ready() { [ -S "$SOCK" ] && [ -n "$(ours)" ]; } -wait_ready() { i=0; while [ $i -lt 300 ]; do ready && return 0; sleep 0.1; i=$((i+1)); done; return 1; } +PID="" +wait_ready() { i=0; while [ $i -lt 300 ]; do ready && return 0; [ -z "$PID" ] || kill -0 "$PID" 2>/dev/null || return 1; sleep 0.1; i=$((i+1)); done; return 1; } ready && exit 0 i=0 @@ -84,9 +87,11 @@ if [ -z "$(ours)" ]; then # nothing running: launch (a running ser rm -f "$SOCK" START_DIR="$(cat "$ROOT/start_dir" 2>/dev/null || true)" cd "${START_DIR:-$HOME}" 2>/dev/null || cd "$HOME" + eval "set -- $(cat "$ROOT/flags" 2>/dev/null || true)" OPEN_TERMINAL_API_KEY_FILE="$ROOT/api-key" nohup "$ROOT/bin/open-terminal" run \ - --ipc "$SOCK" >>"$ROOT/server.log" 2>&1 "$ROOT/pid" + --ipc "$SOCK" "$@" >>"$ROOT/server.log" 2>&1 "$ROOT/pid" fi wait_ready || { echo "start.sh: server did not come up, see $ROOT/server.log" >&2; tail -20 "$ROOT/server.log" >&2; exit 1; } EOF @@ -111,6 +116,10 @@ if [ "$(cat "$ROOT/start_dir" 2>/dev/null || true)" != "$START_DIR" ]; then printf '%s' "$START_DIR" > "$ROOT/start_dir" "$ROOT/stop.sh" # start.sh below brings it up in the new directory fi +if [ "$(cat "$ROOT/flags" 2>/dev/null || true)" != "$FLAGS" ]; then + printf '%s' "$FLAGS" > "$ROOT/flags" + "$ROOT/stop.sh" # start.sh below brings it up with the new flags +fi echo "OPEN_WEBUI:step:start" "$ROOT/start.sh" diff --git a/backend/open_webui/utils/machines/managed.py b/backend/open_webui/utils/machines/managed.py index 8eb56af8ba..fc46a2d0f3 100644 --- a/backend/open_webui/utils/machines/managed.py +++ b/backend/open_webui/utils/machines/managed.py @@ -85,6 +85,18 @@ def clean_start_dir(value: str | None) -> str: return value +def clean_flags(value: str | None) -> str: + """Extra flags for `open-terminal run`, quoted for the shell. Open WebUI sets the socket and the key itself.""" + try: + flags = shlex.split(value or '') + except ValueError as error: + raise MachineError(f'Could not read the flags: {error}.') from error + for flag in flags: + if flag.split('=')[0] in ('--ipc', '--api-key'): + raise MachineError(f'Open WebUI sets {flag.split("=")[0]} itself.') + return shlex.join(flags) + + def install_args(deps: list[str] | None, packages: list[str] | None) -> str: """Arguments for `open-terminal install-deps`: the dependency sets it knows by name, then apt packages.""" deps, packages = list(dict.fromkeys(deps or [])), list(dict.fromkeys(packages or [])) @@ -158,6 +170,7 @@ async def run_bootstrap( on_step, version: str = 'latest', start_dir: str = '', + flags: str = '', install: str = '', ) -> tuple[str, str, str | None]: """Install or upgrade Open Terminal and start it. Returns (install root, installed version, warning). @@ -165,7 +178,8 @@ async def run_bootstrap( `install` (see install_args) also runs `open-terminal install-deps`. When that fails the machine is still set up, with a warning. """ - script = f'START_DIR={shlex.quote(start_dir)}\nDEPS={shlex.quote(install)}\n' + render( + settings = {'START_DIR': start_dir, 'FLAGS': flags, 'DEPS': install} + script = ''.join(f'{name}={shlex.quote(value)}\n' for name, value in settings.items()) + render( BOOTSTRAP, ID=machine_id, VERSION=requested_version(version), @@ -446,13 +460,14 @@ async def provision( is_local: bool = False, version: str | None = None, start_dir: str | None = None, + flags: str | None = None, deps: list[str] | None = None, packages: list[str] | None = None, ): """Create (target given, or is_local) or upgrade/repair (neither) a machine, streaming progress to the admin. `version` is 'latest' or an exact Open Terminal version, `start_dir` is where sessions start, - and `deps` and `packages` are what `open-terminal install-deps` adds (see install_args). + `flags` are extra `open-terminal run` flags (see clean_flags), and `deps` and `packages` are what `open-terminal install-deps` adds (see install_args). When omitted, the machine keeps what the admin chose last time. """ from open_webui.utils.machines import notify_machines_changed @@ -474,6 +489,8 @@ async def provision( start_dir = current.get('start_dir') or '' if is_local and not start_dir: start_dir = local.default_start_dir() + if flags is None: + flags = current.get('flags') or '' if deps is None: deps = current.get('deps') or [] if packages is None: @@ -487,7 +504,7 @@ async def provision( machine = existing or ({'id': machine_id, 'local': {}} if is_local else {'id': machine_id, 'ssh': target}) async with await open_host(machine) as host: root, installed, warning = await run_bootstrap( - host, machine_id, api_key, step, requested, start_dir, install_args(deps, packages) + host, machine_id, api_key, step, requested, start_dir, flags, install_args(deps, packages) ) transport = await host.transport(root) @@ -504,6 +521,7 @@ async def provision( **({} if is_local else {k: source[k] for k in ('host', 'port', 'username', 'host_key')}), 'root': root, 'start_dir': start_dir, + 'flags': flags, 'version': installed, 'requested_version': requested, 'deps': deps, @@ -530,21 +548,34 @@ async def provision( await step('error', message=message) -async def set_start_dir(machine_id: str, start_dir: str): - """Change where sessions start, then restart Open Terminal there.""" +async def configure(machine_id: str, start_dir: str, flags: str): + """Change where sessions start and the `open-terminal run` flags, then restart Open Terminal with them.""" machine = await get_machine(machine_id) - root = state(machine)['root'] + current = state(machine) start_dir = clean_start_dir(start_dir) or (local.default_start_dir() if kind(machine) == 'local' else '') - q = shlex.quote + flags = clean_flags(flags) + + async def on_step(_): + pass + + # The installed version, so this does not upgrade. Also brings older installs' start.sh up to date. + apply = partial(run_bootstrap, version=current.get('version')) await tunnels.drop(machine_id) async with await open_host(machine) as host: - await host.sh( - f'D={q(start_dir)}\n' - 'if [ -n "$D" ] && [ ! -d "$D" ]; then echo "Start directory not found: $D" >&2; exit 1; fi\n' - f'printf %s "$D" > {q(root + "/start_dir")}\n' - f'{q(root + "/stop.sh")}\n{q(root + "/start.sh")}\n' - ) - await update_state(machine_id, start_dir=start_dir) + try: + await apply(host, machine_id, machine['key'], on_step, start_dir=start_dir, flags=flags) + except MachineError: # a wrong flag keeps Open Terminal from starting: go back to what worked + with suppress(Exception): + await apply( + host, + machine_id, + machine['key'], + on_step, + start_dir=current.get('start_dir') or '', + flags=current.get('flags') or '', + ) + raise + await update_state(machine_id, start_dir=start_dir, flags=flags) async def install(request, machine_id: str, admin_id: str, deps: list[str], packages: list[str]): diff --git a/src/lib/apis/machines/index.ts b/src/lib/apis/machines/index.ts index b4a16ea1f2..636012ab5c 100644 --- a/src/lib/apis/machines/index.ts +++ b/src/lib/apis/machines/index.ts @@ -871,6 +871,7 @@ export type SSHTarget = { host: string; port: number; username: string }; export type ManagedMachineInfo = { root?: string; start_dir?: string; // where terminal sessions start; empty is home + flags?: string; // extra flags for `open-terminal run` version?: string; requested_version?: string; // 'latest' or an exact version deps?: string[]; // installed with the machine by `open-terminal install-deps`, by name @@ -967,6 +968,7 @@ export const installSSHMachine = ( name: string; version?: string; start_dir?: string; + flags?: string; deps?: string[]; packages?: string[]; } @@ -979,7 +981,7 @@ export const getLocalMachineDefaults = (token: string) => /** Install Open Terminal on the computer Open WebUI runs on (experimental). Empty start_dir: the project folder Open WebUI picks. */ export const installLocalMachine = ( token: string, - form: { id: string; name?: string; version?: string; start_dir?: string } + form: { id: string; name?: string; version?: string; start_dir?: string; flags?: string } ) => managedMachineRequest<{ id: string; status: string }>(token, '/local', 'POST', form); /** Install the machine's Open Terminal again: `version` is 'latest' or an exact version. Omitted fields keep the current choice. */ @@ -1009,10 +1011,12 @@ export const installMachinePackages = ( ); /** Change where terminal sessions start, then restart Open Terminal there. */ -export const setMachineStartDir = (token: string, id: string, startDir: string) => - managedMachineRequest<{ status: boolean }>(token, managedPath(id, '/directory'), 'POST', { - start_dir: startDir - }); +export const configureMachine = ( + token: string, + id: string, + form: { start_dir: string; flags: string } +) => + managedMachineRequest<{ status: boolean }>(token, managedPath(id, '/configure'), 'POST', form); export const restartMachine = (token: string, id: string) => managedMachineRequest<{ status: boolean }>(token, managedPath(id, '/restart'), 'POST'); diff --git a/src/lib/components/AddMachineModal.svelte b/src/lib/components/AddMachineModal.svelte index 85016345ea..d37c180f51 100644 --- a/src/lib/components/AddMachineModal.svelte +++ b/src/lib/components/AddMachineModal.svelte @@ -16,6 +16,7 @@ import ExperimentalBadge from '$lib/components/common/ExperimentalBadge.svelte'; import { getMachineConnections, verifyMachineConnection } from '$lib/apis/configs'; import { + configureMachine, createSSHKeypair, formatSSHUrl, getLocalMachineDefaults, @@ -28,7 +29,6 @@ probeSSHMachine, removeMachine, restartMachine, - setMachineStartDir, upgradeMachine, type ManagedMachineInfo, type SSHMachineInfo @@ -76,6 +76,7 @@ // Type when adding: Remote (a URL or ssh://) or Local (the server Open WebUI runs on). let target: 'url' | 'local' = 'url'; let startDir = ''; // where terminal sessions start; empty is the default + let flags = ''; // extra flags for `open-terminal run` let localDefaults: { start_dir: string; added: boolean } | null = null; let passphrase = ''; let keyFileInput: HTMLInputElement; @@ -131,6 +132,7 @@ ? current.requested_version : ''; startDir = current?.start_dir ?? ''; + flags = current?.flags ?? ''; toInstall = [...(current?.deps ?? []), ...(current?.packages ?? [])].join(' '); target = 'url'; localDefaults = null; @@ -247,8 +249,14 @@ busy = true; error = ''; try { - if (managed && startDir.trim() !== (managed.start_dir ?? '')) { - await setMachineStartDir(localStorage.token, connection.id, startDir.trim()); + if ( + managed && + (startDir.trim() !== (managed.start_dir ?? '') || flags.trim() !== (managed.flags ?? '')) + ) { + await configureMachine(localStorage.token, connection.id, { + start_dir: startDir.trim(), + flags: flags.trim() + }); } const result = { ...(connection ?? {}), @@ -340,6 +348,7 @@ name: name.trim(), version: openTerminalVersion.trim() || 'latest', start_dir: startDir.trim(), + flags: flags.trim(), ...installForm }) ); @@ -352,7 +361,8 @@ id: machineId, name: name.trim(), version: openTerminalVersion.trim() || 'latest', - start_dir: startDir.trim() + start_dir: startDir.trim(), + flags: flags.trim() }) ); } @@ -849,6 +859,31 @@ autocomplete="off" /> +
{$i18n.t(