mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-16 09:41:23 +00:00
refac
This commit is contained in:
parent
2e55c36564
commit
c4c10aa255
5 changed files with 145 additions and 34 deletions
|
|
@ -431,13 +431,22 @@ async def _resolve_terminal_access(ws: WebSocket, server_id: str, token: str):
|
|||
return user, connection
|
||||
|
||||
|
||||
@router.websocket('/{server_id}/files/events')
|
||||
async def ws_file_events(ws: WebSocket, server_id: str):
|
||||
await _proxy_terminal_websocket(ws, server_id)
|
||||
|
||||
|
||||
@router.websocket('/{server_id}/api/terminals/{session_id}')
|
||||
async def ws_terminal(
|
||||
async def ws_terminal(ws: WebSocket, server_id: str, session_id: str):
|
||||
await _proxy_terminal_websocket(ws, server_id, session_id)
|
||||
|
||||
|
||||
async def _proxy_terminal_websocket(
|
||||
ws: WebSocket,
|
||||
server_id: str,
|
||||
session_id: str,
|
||||
session_id: str | None = None,
|
||||
):
|
||||
"""Proxy an interactive WebSocket terminal session to a terminal server.
|
||||
"""Proxy terminal sessions and filesystem notifications to a terminal server.
|
||||
|
||||
Uses first-message auth: the client sends ``{"type": "auth", "token": "<jwt>"}``
|
||||
as its first message. The proxy validates the JWT, then connects to the
|
||||
|
|
@ -473,9 +482,11 @@ async def ws_terminal(
|
|||
|
||||
# Encode session_id as an opaque path segment so it cannot smuggle '?'/'#'/'&' (at any
|
||||
# decode depth) and inject an attacker-chosen user_id ahead of the one appended below.
|
||||
safe_session_id = urllib.parse.quote(session_id, safe='')
|
||||
|
||||
upstream_url = f'{ws_base}/api/terminals/{safe_session_id}'
|
||||
upstream_path = (
|
||||
f'api/terminals/{urllib.parse.quote(session_id, safe="")}'
|
||||
if session_id is not None else 'files/events'
|
||||
)
|
||||
upstream_url = f'{ws_base}/{upstream_path}'
|
||||
if upstream_params:
|
||||
upstream_url += f'?{urllib.parse.urlencode(upstream_params)}'
|
||||
|
||||
|
|
@ -500,15 +511,16 @@ async def ws_terminal(
|
|||
else:
|
||||
await upstream.send_str(_json.dumps({'type': 'auth', 'token': ''}))
|
||||
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.TERMINAL_SESSION_OPENED,
|
||||
actor=user,
|
||||
subject_id=session_id,
|
||||
subject_type='terminal.session',
|
||||
data={'server_id': server_id},
|
||||
)
|
||||
opened = True
|
||||
if session_id is not None:
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.TERMINAL_SESSION_OPENED,
|
||||
actor=user,
|
||||
subject_id=session_id,
|
||||
subject_type='terminal.session',
|
||||
data={'server_id': server_id},
|
||||
)
|
||||
opened = True
|
||||
|
||||
async def _client_to_upstream():
|
||||
"""Forward client → upstream."""
|
||||
|
|
@ -537,6 +549,8 @@ async def ws_terminal(
|
|||
aiohttp.WSMsgType.ERROR,
|
||||
):
|
||||
break
|
||||
if session_id is None and upstream.close_code and 4000 <= upstream.close_code < 5000:
|
||||
await ws.close(code=upstream.close_code)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
|
|
|||
52
src/lib/apis/terminal/events.ts
Normal file
52
src/lib/apis/terminal/events.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import type { TerminalConnection } from './index';
|
||||
|
||||
export function watchTerminalFiles(
|
||||
connection: TerminalConnection,
|
||||
chatId: string | null,
|
||||
directory: string,
|
||||
onChange: () => void,
|
||||
onError: (message: string) => void
|
||||
) {
|
||||
let stopped = false;
|
||||
let socket: WebSocket;
|
||||
let retry: ReturnType<typeof setTimeout>;
|
||||
let retryDelay = 1000;
|
||||
const connect = () => {
|
||||
const url = new URL(`${connection.baseUrl.replace(/\/$/, '')}/files/events`, location.href);
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
socket = new WebSocket(url);
|
||||
socket.onopen = () => {
|
||||
socket.send(
|
||||
JSON.stringify({ type: 'auth', token: connection.key.trim(), chat_id: chatId ?? '' })
|
||||
);
|
||||
socket.send(JSON.stringify({ type: 'subscribe', path: directory }));
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
if (stopped) return;
|
||||
try {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.type === 'ready') {
|
||||
retryDelay = 1000;
|
||||
onError('');
|
||||
onChange();
|
||||
} else if (message.type === 'change') onChange();
|
||||
} catch {
|
||||
/* Ignore frames that are not filesystem notifications. */
|
||||
}
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
if (stopped) return;
|
||||
onError('Live updates unavailable');
|
||||
if (event.code >= 4000 && event.code < 5000) return;
|
||||
retry = setTimeout(connect, retryDelay);
|
||||
retryDelay = Math.min(retryDelay * 2, 30000);
|
||||
};
|
||||
};
|
||||
connect();
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearTimeout(retry);
|
||||
socket.onopen = socket.onmessage = socket.onclose = null;
|
||||
socket.close();
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
<script lang="ts">
|
||||
import { getContext, onDestroy, onMount } from 'svelte';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import { watchTerminalFiles } from '$lib/apis/terminal/events';
|
||||
import {
|
||||
gitRequest,
|
||||
gitAction,
|
||||
|
|
@ -77,7 +78,8 @@
|
|||
let context = '';
|
||||
let generation = 0;
|
||||
let diffGeneration = 0;
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
let stopWatching: (() => void) | undefined;
|
||||
let watchError = '';
|
||||
let pending: Promise<void> | null = null;
|
||||
let syncAction: 'publish' | 'pull' | 'push' | 'fetch';
|
||||
$: staged = status?.files.filter((file) => file.staged) ?? [];
|
||||
|
|
@ -173,7 +175,9 @@
|
|||
loadingDiff = false;
|
||||
};
|
||||
const configure = (key: string, enabled: boolean) => {
|
||||
clearInterval(timer);
|
||||
stopWatching?.();
|
||||
stopWatching = undefined;
|
||||
watchError = '';
|
||||
if (key !== context) {
|
||||
context = key;
|
||||
++generation;
|
||||
|
|
@ -196,11 +200,22 @@
|
|||
view = 'changes';
|
||||
resetSelection();
|
||||
}
|
||||
if (enabled) {
|
||||
if (enabled && connection) {
|
||||
void refresh();
|
||||
timer = setInterval(() => {
|
||||
if (!busy) void refresh();
|
||||
}, 5000);
|
||||
const current = generation;
|
||||
stopWatching = watchTerminalFiles(
|
||||
connection,
|
||||
chatId,
|
||||
directory,
|
||||
async () => {
|
||||
// An event arriving during a status request must refresh after that request.
|
||||
await pending;
|
||||
if (current === generation) await refresh();
|
||||
},
|
||||
(message) => {
|
||||
watchError = message;
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
$: configure(JSON.stringify([connection, chatId, directory]), mounted && active);
|
||||
|
|
@ -322,13 +337,13 @@
|
|||
onDestroy(() => {
|
||||
++generation;
|
||||
++diffGeneration;
|
||||
clearInterval(timer);
|
||||
stopWatching?.();
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if status?.is_repo}
|
||||
<section
|
||||
class="git-panel relative shrink-0 border-t border-gray-200 dark:border-white/6"
|
||||
class="git-panel relative shrink-0 border-t border-gray-100/50 dark:border-white/2"
|
||||
aria-label={$i18n.t('Git')}
|
||||
>
|
||||
{#if expanded}
|
||||
|
|
@ -338,7 +353,7 @@
|
|||
aria-orientation="horizontal"
|
||||
aria-valuenow={height}
|
||||
tabindex="0"
|
||||
class="absolute inset-x-0 -top-[0.1875rem] h-[0.375rem] z-20 cursor-row-resize touch-none hover:bg-gray-200/50 dark:hover:bg-white/8"
|
||||
class="absolute inset-x-0 -top-px h-px z-20 cursor-row-resize touch-none border-t border-transparent hover:border-gray-200 dark:hover:border-gray-800 transition"
|
||||
on:pointerdown={(event) => {
|
||||
event.preventDefault();
|
||||
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
||||
|
|
@ -364,7 +379,9 @@
|
|||
);
|
||||
}
|
||||
}}
|
||||
></div>
|
||||
>
|
||||
<span class="absolute inset-x-0 -top-1.5 -bottom-1.5 bg-transparent"></span>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex min-w-0 items-center h-7 pl-3 pr-1 text-gray-400 dark:text-gray-600">
|
||||
<Dropdown side="top" maxHeight="15rem" bind:show={showBranches} onOpenChange={loadBranches}>
|
||||
|
|
@ -573,7 +590,9 @@
|
|||
{#if status.behind}<span>↓{status.behind}</span>{/if}
|
||||
</span>
|
||||
{/if}
|
||||
<Tooltip content={$i18n.t(syncLabel)}>
|
||||
<Tooltip
|
||||
content={[$i18n.t(syncLabel), ...(watchError ? [$i18n.t(watchError)] : [])].join('\n')}
|
||||
>
|
||||
<button
|
||||
class="flex shrink-0 items-center justify-center h-6 w-6 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
aria-label={$i18n.t(syncLabel)}
|
||||
|
|
@ -967,7 +986,7 @@
|
|||
</section>
|
||||
{:else if detectionError}
|
||||
<div
|
||||
class="flex h-7 shrink-0 items-center gap-1.5 border-t border-gray-200 dark:border-white/6 px-3 text-[0.6875rem] text-gray-500 dark:text-gray-400"
|
||||
class="flex h-7 shrink-0 items-center gap-1.5 border-t border-gray-100/50 dark:border-white/2 px-3 text-[0.6875rem] text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
<Icon name="git-branch" size={12} />
|
||||
<Tooltip content={detectionError} className="min-w-0 flex-1"
|
||||
|
|
|
|||
|
|
@ -143,10 +143,28 @@
|
|||
.removed .prefix {
|
||||
color: var(--color-red-500);
|
||||
}
|
||||
.line-text span:not(.changed) {
|
||||
.git-diff:not(.split) .added {
|
||||
box-shadow: inset 0.1875rem 0 0 #22c55e;
|
||||
}
|
||||
:global(.dark) .git-diff:not(.split) .added {
|
||||
box-shadow: inset 0.1875rem 0 0 #4ade80;
|
||||
}
|
||||
.git-diff:not(.split) .removed {
|
||||
background-image: repeating-linear-gradient(
|
||||
-45deg,
|
||||
#ef4444 0,
|
||||
#ef4444 1px,
|
||||
transparent 1px,
|
||||
transparent 0.1875rem
|
||||
);
|
||||
background-position: left top;
|
||||
background-repeat: repeat-y;
|
||||
background-size: 0.1875rem 0.1875rem;
|
||||
}
|
||||
.line-text span {
|
||||
color: var(--diff-token-light, inherit);
|
||||
}
|
||||
:global(.dark) .line-text span:not(.changed) {
|
||||
:global(.dark) .line-text span {
|
||||
color: var(--diff-token-dark, inherit);
|
||||
}
|
||||
.changed {
|
||||
|
|
@ -154,12 +172,20 @@
|
|||
-webkit-box-decoration-break: clone;
|
||||
}
|
||||
.added .changed {
|
||||
background: rgba(21, 128, 61, 0.85);
|
||||
color: #fff;
|
||||
background: rgba(22, 163, 74, 0.38);
|
||||
box-shadow: inset 0 -0.125rem 0 rgba(21, 128, 61, 0.42);
|
||||
}
|
||||
.removed .changed {
|
||||
background: rgba(185, 28, 28, 0.85);
|
||||
color: #fff;
|
||||
background: rgba(220, 38, 38, 0.32);
|
||||
box-shadow: inset 0 -0.125rem 0 rgba(185, 28, 28, 0.38);
|
||||
}
|
||||
:global(.dark) .added .changed {
|
||||
background: rgba(34, 197, 94, 0.42);
|
||||
box-shadow: inset 0 -0.125rem 0 rgba(134, 239, 172, 0.5);
|
||||
}
|
||||
:global(.dark) .removed .changed {
|
||||
background: rgba(248, 113, 113, 0.4);
|
||||
box-shadow: inset 0 -0.125rem 0 rgba(252, 165, 165, 0.48);
|
||||
}
|
||||
:global(.dark) .git-diff {
|
||||
color: var(--color-gray-400);
|
||||
|
|
|
|||
|
|
@ -162,7 +162,7 @@
|
|||
{/if}
|
||||
</div>
|
||||
{#if selectedFile && fileSize !== undefined}
|
||||
<span class="shrink-0 text-[0.6875rem] text-gray-400">{formatFileSize(fileSize)}</span>
|
||||
<span class="shrink-0 me-1 text-[0.6875rem] text-gray-400/75">{formatFileSize(fileSize)}</span>
|
||||
{/if}
|
||||
{#if selectedFile && (gitFile || gitDiffOpen)}
|
||||
<Tooltip content={gitDiffOpen ? $i18n.t('Hide diff') : $i18n.t('Show diff')}>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue