From e5b098c6811bc85dc15a4e4e03f5a684f34f949e Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 22 Nov 2026 23:44:38 +0400 Subject: [PATCH] refac --- backend/open_webui/routers/machines.py | 47 ++++- .../open_webui/utils/machines/bootstrap.sh | 19 +- backend/open_webui/utils/machines/managed.py | 107 ++++++++-- src/lib/apis/machines/index.ts | 35 +++- src/lib/components/AddMachineModal.svelte | 185 ++++++++++++++---- 5 files changed, 330 insertions(+), 63 deletions(-) diff --git a/backend/open_webui/routers/machines.py b/backend/open_webui/routers/machines.py index aa6552d9a6..83e276c1ef 100644 --- a/backend/open_webui/routers/machines.py +++ b/backend/open_webui/routers/machines.py @@ -95,6 +95,9 @@ class CreateForm(Pinned): id: str = Field(pattern=SSH_MACHINE_ID) name: str = Field('', max_length=100) version: str = Field('latest', max_length=20) # 'latest' or an exact Open Terminal version + # 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) class LocalForm(BaseModel): @@ -106,6 +109,13 @@ class LocalForm(BaseModel): class UpgradeForm(BaseModel): version: str | None = Field(None, max_length=20) # omitted: keep the machine's current choice + deps: list[str] | None = Field(None, max_length=16) + packages: list[str] | None = Field(None, max_length=64) + + +class InstallForm(BaseModel): + deps: list[str] = Field(default_factory=list, max_length=16) + packages: list[str] = Field(default_factory=list, max_length=64) class FolderForm(BaseModel): @@ -158,11 +168,21 @@ async def install_key(form: InstallKeyForm, user=Depends(get_admin_user)): async def create_machine(request: Request, form: CreateForm, user=Depends(get_admin_user)): try: version = managed.requested_version(form.version) + managed.install_args(form.deps, form.packages) except MachineError as error: _ssh_fail(error) target = form.model_dump(include={'host', 'port', 'username', 'host_key'}) _ssh_start( - managed.provision(request, form.id, user.id, name=form.name or form.host, target=target, version=version) + managed.provision( + request, + form.id, + user.id, + name=form.name or form.host, + target=target, + version=version, + deps=form.deps, + packages=form.packages, + ) ) return {'id': form.id, 'status': 'installing'} @@ -204,9 +224,32 @@ async def upgrade_machine( try: await managed.get_machine(machine_id) version = managed.requested_version(form.version) if form and form.version is not None else None + managed.install_args(form.deps if form else None, form.packages if form else None) except MachineError as error: _ssh_fail(error) - _ssh_start(managed.provision(request, machine_id, user.id, version=version)) + _ssh_start( + managed.provision( + request, + machine_id, + user.id, + version=version, + deps=form.deps if form else None, + packages=form.packages if form else None, + ) + ) + return {'id': machine_id, 'status': 'installing'} + + +@router.post('/managed/{machine_id}/install') +async def install_machine_packages(request: Request, machine_id: str, form: InstallForm, user=Depends(get_admin_user)): + """Install system packages on the machine through `open-terminal install-deps`. Needs passwordless sudo.""" + try: + await managed.get_machine(machine_id) + if not managed.install_args(form.deps, form.packages): + raise MachineError('Enter what to install.') + except MachineError as error: + _ssh_fail(error) + _ssh_start(managed.install(request, machine_id, user.id, form.deps, form.packages)) return {'id': machine_id, 'status': 'installing'} diff --git a/backend/open_webui/utils/machines/bootstrap.sh b/backend/open_webui/utils/machines/bootstrap.sh index 813a491dcb..a317b06801 100644 --- a/backend/open_webui/utils/machines/bootstrap.sh +++ b/backend/open_webui/utils/machines/bootstrap.sh @@ -1,9 +1,11 @@ # Run by utils/machines/managed.py on stdin, over SSH or on this computer. Tokens (__OPEN_WEBUI_*__) are -# validated before rendering; FOLDER (where sessions start, empty for home) is set on the line above. +# validated before rendering; FOLDER (where sessions start, empty for home) 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__" FOLDER="${FOLDER:-}" +DEPS="${DEPS:-}" VERSION="__OPEN_WEBUI_VERSION__" echo "OPEN_WEBUI:step:detect" @@ -37,6 +39,21 @@ if [ "$VERSION" = latest ] || [ "$INSTALLED" != "$VERSION" ]; then fi echo "OPEN_WEBUI:version:$(cat "$ROOT/version")" +# Optional system packages. A failure here is a warning: the machine +# works without them. stdin is this script, so sudo must not read a password from it. +if [ -n "$DEPS" ]; then + echo "OPEN_WEBUI:step:packages" + if ! "$ROOT/bin/open-terminal" install-deps --help >/dev/null 2>&1; then + echo "OPEN_WEBUI:warning:This Open Terminal version cannot install packages. Upgrade to the latest." + elif "$ROOT/bin/open-terminal" install-deps --yes $DEPS >"$ROOT/packages.log" 2>&1 "$ROOT/api-key" diff --git a/backend/open_webui/utils/machines/managed.py b/backend/open_webui/utils/machines/managed.py index 84702964c2..bc02ac6656 100644 --- a/backend/open_webui/utils/machines/managed.py +++ b/backend/open_webui/utils/machines/managed.py @@ -85,6 +85,16 @@ def clean_folder(value: str | None) -> str: return value +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 [])) + for name in [*deps, *packages]: + # Names only: these become arguments of a command that installs as root on the machine. + if not re.fullmatch(r'[a-z0-9][a-z0-9+.-]*', name): + raise MachineError(f'"{name}" is not a package name.') + return ' '.join([*deps, *(f'--package {name}' for name in packages)]) + + def render(template: str, **values: str) -> str: for name, value in values.items(): if not TOKENS[name].fullmatch(value): @@ -142,10 +152,20 @@ async def open_host(machine: dict): async def run_bootstrap( - host, machine_id: str, api_key: str, on_step, version: str = 'latest', folder: str = '' -) -> tuple[str, str]: - """Install or upgrade Open Terminal and start it. Returns (install root, installed version).""" - script = f'FOLDER={shlex.quote(folder)}\n' + render( + host, + machine_id: str, + api_key: str, + on_step, + version: str = 'latest', + folder: str = '', + install: str = '', +) -> tuple[str, str, str | None]: + """Install or upgrade Open Terminal and start it. Returns (install root, installed version, warning). + + `install` (see install_args) also runs `open-terminal install-deps`. When that fails the + machine is still set up, with a warning. + """ + script = f'FOLDER={shlex.quote(folder)}\nDEPS={shlex.quote(install)}\n' + render( BOOTSTRAP, ID=machine_id, VERSION=requested_version(version), @@ -154,9 +174,10 @@ async def run_bootstrap( API_KEY=api_key, ) proc = await host.start(script) # stdin, not argv: the API key never shows up in `ps` - root, installed, error, tail = None, None, None, deque(maxlen=80) + root, installed, error, warning, tail = None, None, None, None, deque(maxlen=80) try: - async with asyncio.timeout(900): # a cold install downloads Python and the package + # A cold install downloads Python and the package; system packages can be far larger. + async with asyncio.timeout(2700 if install else 900): async for line in proc.lines(): line = line.rstrip('\n') tail.append(line) @@ -171,6 +192,8 @@ async def run_bootstrap( installed = value elif name == 'error': error = value + elif name == 'warning': + warning = value status = await proc.wait() finally: proc.close() @@ -178,7 +201,12 @@ async def run_bootstrap( raise MachineError(error or '\n'.join(tail) or 'Setup failed.') if not host.valid_root(root, machine_id): raise MachineError(f'Unexpected install path: {root}') - return root, installed or '' + if warning: + warning = ( + f'Packages were not installed: {warning}\n' + f'Run this on the machine, then restart it here: {root}/bin/open-terminal install-deps {install}' + ) + return root, installed or '', warning # --------------------------------------------------------------------------- @@ -397,6 +425,17 @@ class MachineClient: # --------------------------------------------------------------------------- +async def emit_step(admin_id: str, machine_id: str, value: str, **extra): + """Tell the admin's browser how far a machine's setup is (`machines:progress`).""" + from open_webui.socket.main import emit_to_users + + await emit_to_users( + 'events', + {'data': {'type': 'machines:progress', 'id': machine_id, 'step': value, **extra}}, + [admin_id], + ) + + async def provision( request, machine_id: str, @@ -407,23 +446,19 @@ async def provision( is_local: bool = False, version: str | None = None, folder: 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, and `folder` is where sessions start. + `version` is 'latest' or an exact Open Terminal version, `folder` is where sessions start, + 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.socket.main import emit_to_users from open_webui.utils.machines import notify_machines_changed from open_webui.utils.tools import set_machines - async def step(value: str, **extra): - await emit_to_users( - 'events', - {'data': {'type': 'machines:progress', 'id': machine_id, 'step': value, **extra}}, - [admin_id], - ) - + step = partial(emit_step, admin_id, machine_id) existing = None with suppress(MachineError): existing = await get_machine(machine_id) @@ -439,6 +474,10 @@ async def provision( folder = current.get('folder') or '' if is_local and not folder: folder = local.default_folder() + if deps is None: + deps = current.get('deps') or [] + if packages is None: + packages = current.get('packages') or [] try: if existing: @@ -447,7 +486,9 @@ async def provision( await step('connect') 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 = await run_bootstrap(host, machine_id, api_key, step, requested, folder) + root, installed, warning = await run_bootstrap( + host, machine_id, api_key, step, requested, folder, install_args(deps, packages) + ) transport = await host.transport(root) entry = existing or { @@ -465,9 +506,12 @@ async def provision( 'folder': folder, 'version': installed, 'requested_version': requested, + 'deps': deps, + 'packages': packages, 'transport': transport, 'status': 'ready', 'error': None, + 'warning': warning, } await save_machine(entry) if not is_local: @@ -477,7 +521,7 @@ async def provision( await tunnels.socket_for(machine_id) await set_machines(request) # load its OpenAPI spec like any other machine await notify_machines_changed([admin_id]) - await step('ready') + await step('ready', message=warning) except Exception as error: log.exception('Provisioning %s failed', machine_id) message = describe(error) @@ -503,6 +547,33 @@ async def set_folder(machine_id: str, folder: str): await update_state(machine_id, folder=folder) +async def install(request, machine_id: str, admin_id: str, deps: list[str], packages: list[str]): + """Run `open-terminal install-deps` on a machine that is already set up, streaming progress to the admin.""" + from open_webui.utils.tools import set_machines + + step = partial(emit_step, admin_id, machine_id) + try: + args = install_args(deps, packages) + machine = await get_machine(machine_id) + binary = f'{state(machine)["root"]}/bin/open-terminal' + await step('packages') + async with await open_host(machine) as host: + try: + # stdin is the script, so sudo must not read a password from it. + output = await host.sh(f'{shlex.quote(binary)} install-deps --yes {args} managedMachineRequest<{ id: string; status: string }>(token, '/ssh', 'POST', form); /** Where sessions on this computer start by default, and whether it is already added. */ @@ -971,13 +981,30 @@ export const installLocalMachine = ( form: { id: string; name?: string; version?: string; folder?: string } ) => managedMachineRequest<{ id: string; status: string }>(token, '/local', 'POST', form); -/** Install the machine's Open Terminal again: `version` is 'latest' or an exact version (omit to keep the current choice). */ -export const upgradeMachine = (token: string, id: string, version?: string) => +/** Install the machine's Open Terminal again: `version` is 'latest' or an exact version. Omitted fields keep the current choice. */ +export const upgradeMachine = ( + token: string, + id: string, + form?: { version?: string; deps?: string[]; packages?: string[] } +) => managedMachineRequest<{ id: string; status: string }>( token, managedPath(id, '/upgrade'), 'POST', - version === undefined ? undefined : { version } + form + ); + +/** Install system packages on the machine now. Progress arrives as `machines:progress` socket events. */ +export const installMachinePackages = ( + token: string, + id: string, + form: { deps: string[]; packages: string[] } +) => + managedMachineRequest<{ id: string; status: string }>( + token, + managedPath(id, '/install'), + 'POST', + form ); /** Change where terminal sessions start, then restart Open Terminal there. */ diff --git a/src/lib/components/AddMachineModal.svelte b/src/lib/components/AddMachineModal.svelte index d752410f8a..136aa3f10e 100644 --- a/src/lib/components/AddMachineModal.svelte +++ b/src/lib/components/AddMachineModal.svelte @@ -21,6 +21,7 @@ getLocalMachineDefaults, getMachineLogs, installLocalMachine, + installMachinePackages, installSSHKey, installSSHMachine, parseSSHUrl, @@ -60,6 +61,13 @@ let showDelete = false; // SSH: an ssh://user@host URL installs Open Terminal on that machine instead of connecting to one. const SSH_STEPS = ['connect', 'detect', 'install', 'configure', 'start', 'health', 'ready']; + // SSH only: what `open-terminal install-deps` adds to the machine, typed as names separated by + // spaces. These are the names it knows itself; any other name is an apt package. + const INSTALL_DEPS = ['desktop', 'browser']; + let toInstall = ''; + // The Install button: only that step runs, and what it reports shows under the field. + let installingPackages = false; + let packagesResult: { text: string; failed: boolean } | null = null; // How Open WebUI logs in the first time to add its own key. Nothing here is stored. let signIn: 'password' | 'key' | 'manual' = 'password'; let password = ''; @@ -97,6 +105,14 @@ $: installingSSH = !managed && !installingLocal && url.trim().toLowerCase().startsWith('ssh://'); $: installing = installingSSH || installingLocal; $: sshTarget = installingSSH ? parseSSHUrl(url) : null; + $: installNames = toInstall.trim().split(/\s+/).filter(Boolean); + $: installForm = { + deps: installNames.filter((name) => INSTALL_DEPS.includes(name)), + packages: installNames.filter((name) => !INSTALL_DEPS.includes(name)) + }; + $: installSteps = installNames.length + ? SSH_STEPS.flatMap((step) => (step === 'install' ? [step, 'packages'] : [step])) + : SSH_STEPS; $: showLocalOption = allowLocal && !connection && localDefaults !== null && !localDefaults.added; $: if (show && !initialized) { url = connection?.url ?? ''; @@ -115,6 +131,7 @@ ? current.requested_version : ''; folder = current?.folder ?? ''; + toInstall = [...(current?.deps ?? []), ...(current?.packages ?? [])].join(' '); target = 'url'; localDefaults = null; if (allowLocal && !connection) { @@ -131,6 +148,8 @@ passphrase = ''; resetSSH(); logs = null; + installingPackages = false; + packagesResult = null; initialized = true; } $: if (!show) { @@ -152,6 +171,8 @@ return $i18n.t('Checking the machine'); case 'install': return $i18n.t('Installing Open Terminal'); + case 'packages': + return $i18n.t('Installing packages'); case 'configure': return $i18n.t('Configuring'); case 'start': @@ -163,7 +184,10 @@ } } // Follow `machines:progress` events for one machine until it is ready or fails. - function follow(machineId: string, onDone: (ok: boolean, message?: string) => void) { + function follow( + machineId: string, + onDone: (ok: boolean, message?: string, output?: string) => void + ) { stopListening?.(); steps = []; running = true; @@ -178,7 +202,8 @@ steps = [...steps.filter((step) => step !== data.step), data.step]; if (data.step === 'ready') { stop(); - onDone(true); + // A message here is a warning: ready, but packages are missing. + onDone(true, data.message, data.output); } }; const stop = () => { @@ -313,7 +338,8 @@ host_key: hostKey!.host_key, id: machine.id, name: name.trim(), - version: openTerminalVersion.trim() || 'latest' + version: openTerminalVersion.trim() || 'latest', + ...installForm }) ); } @@ -356,6 +382,7 @@ config: configuration(), [kind]: {} }); + if (message) toast.warning(message); show = false; } catch (e) { error = e instanceof Error ? e.message : String(e); @@ -373,31 +400,55 @@ const authorizeCommand = (publicKey: string) => `mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo '${publicKey}' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`; // Existing machines Open WebUI installed (SSH or this computer) + // Show what the machine has now: its version, packages, and any warning. + async function refreshManaged() { + const res = await getMachineConnections(localStorage.token).catch(() => null); + const updated = res?.MACHINE_CONNECTIONS?.find((c: any) => c.id === connection.id); + if (updated?.ssh) connection = { ...connection, ssh: updated.ssh }; + if (updated?.local) connection = { ...connection, local: updated.local }; + } const upgrade = () => run(async () => { + installingPackages = false; follow(connection.id, async (ok, message) => { if (!ok) { error = message ?? $i18n.t('Upgrade failed'); return; } - toast.success($i18n.t('Machine upgraded')); - // Show the version that is now installed. - const res = await getMachineConnections(localStorage.token).catch(() => null); - const updated = res?.MACHINE_CONNECTIONS?.find((c: any) => c.id === connection.id); - if (updated?.ssh) connection = { ...connection, ssh: updated.ssh }; - if (updated?.local) connection = { ...connection, local: updated.local }; + if (message) toast.warning(message); + else toast.success($i18n.t('Machine upgraded')); + await refreshManaged(); }); try { - await upgradeMachine( - localStorage.token, - connection.id, - openTerminalVersion.trim() || 'latest' - ); + await upgradeMachine(localStorage.token, connection.id, { + version: openTerminalVersion.trim() || 'latest', + ...(sshMachine ? installForm : {}) + }); } catch (e) { stopListening?.(); throw e; } }); + const installPackages = () => + run(async () => { + installingPackages = true; + packagesResult = null; + follow(connection.id, async (ok, message, output) => { + installingPackages = false; + steps = []; + packagesResult = ok + ? { text: output?.trim() || $i18n.t('Packages installed'), failed: false } + : { text: message ?? $i18n.t('Installation failed'), failed: true }; + if (ok) await refreshManaged(); + }); + try { + await installMachinePackages(localStorage.token, connection.id, installForm); + } catch (e) { + stopListening?.(); + installingPackages = false; + packagesResult = { text: e instanceof Error ? e.message : String(e), failed: true }; + } + }); const restart = () => run(async () => { await restartMachine(localStorage.token, connection.id); @@ -705,10 +756,63 @@ {/if} {#if (installing && sshPhase === 'form') || managed} + {#if installingSSH || sshMachine} +
+ + + + + {#if managed} + + {/if} +
+ {#if installingPackages} +
+ {$i18n.t('Installing packages')} +
+ {:else if packagesResult || managed?.warning} +
{packagesResult?.text ??
+							managed?.warning}
+ {/if} + {/if}
- +
+ + + +
-

{$i18n.t('Where terminal sessions start.')}

- +
+ + + +
-

- {managed - ? $i18n.t('Leave empty for the latest release. Upgrade installs this version.') - : $i18n.t('Leave empty for the latest release.')} -

{#if installingLocal || localMachine}

@@ -747,9 +856,9 @@

{/if} {/if} - {#if sshPhase === 'installing' || running || steps.length} + {#if !installingPackages && (sshPhase === 'installing' || running || steps.length)}
    - {#each SSH_STEPS as step} + {#each installSteps as step} {@const index = steps.indexOf(step)} {@const current = running && index === steps.length - 1}
  1. {$i18n.t('Filesystem')} - -
    - {}} /> -
    -
    + +
    + {}} /> +
    +
    {#if edit}