mirror of
https://github.com/open-webui/computer.git
synced 2026-11-24 22:37:40 -05:00
refac
This commit is contained in:
1 parent
622e1daff2
commit
4181e685ff
6 files changed
+119
-62
No files matched your search
@@ -22,8 +22,12 @@ let availabilityPromise: Promise<BrowserAvailability> | undefined;
|
||||
export const getBrowserAvailability = () =>
|
||||
(availabilityPromise ??= fetchJSON<BrowserAvailability>('/api/browser/availability'));
|
||||
|
||||
export const createBrowserSession = () =>
|
||||
fetchJSON<BrowserSession>('/api/browser/sessions', { method: 'POST' });
|
||||
export const createBrowserSession = (url?: string) =>
|
||||
fetchJSON<BrowserSession>('/api/browser/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ url })
|
||||
});
|
||||
|
||||
export const listBrowserSessions = async () => {
|
||||
const data = await fetchJSON<{ session_ids: string[] }>('/api/browser/sessions');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import { onDestroy, onMount, tick } from 'svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import {
|
||||
browserBlankUrl,
|
||||
@@ -28,7 +28,6 @@
|
||||
let frameSrc = $state(browserBlankUrl(sessionId));
|
||||
let urlInput = $state(initialUrl ?? '');
|
||||
let title = $state('');
|
||||
let loading = $state(false);
|
||||
let error = $state('');
|
||||
let modeError = $state('');
|
||||
let mode = $state<'proxy' | 'chrome'>('proxy');
|
||||
@@ -61,7 +60,6 @@
|
||||
).href;
|
||||
if (mode === 'chrome') chromeEl?.navigate(urlInput);
|
||||
else frameSrc = browserFrameUrl(sessionId, urlInput);
|
||||
loading = true;
|
||||
error = '';
|
||||
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
|
||||
} catch {
|
||||
@@ -81,13 +79,11 @@
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
loading = true;
|
||||
if (mode === 'chrome') chromeEl?.reload();
|
||||
else iframeEl?.contentWindow?.location.reload();
|
||||
}
|
||||
|
||||
function frameLoaded() {
|
||||
loading = false;
|
||||
try {
|
||||
const current = new URL(iframeEl?.contentWindow?.location.href || '');
|
||||
const framePrefix = `/api/browser/frame/${sessionId}`;
|
||||
@@ -102,7 +98,6 @@
|
||||
const upstream = new URL(`${current.pathname}${current.search}${current.hash}`, urlInput)
|
||||
.href;
|
||||
urlInput = upstream;
|
||||
loading = true;
|
||||
void updateBrowserSession(sessionId, upstream, title).catch(() => {});
|
||||
iframeEl?.contentWindow?.location.replace(browserFrameUrl(sessionId, upstream));
|
||||
} catch {
|
||||
@@ -117,7 +112,6 @@
|
||||
urlInput = publicUrl(data.url || urlInput);
|
||||
title = data.title || '';
|
||||
updateTabLabel(tabId, title);
|
||||
loading = false;
|
||||
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
|
||||
}
|
||||
if (data?.type === 'cptr-browser-popup' && data.url) openBrowserTab(groupId, data.url);
|
||||
@@ -134,7 +128,6 @@
|
||||
mode = session.mode || 'proxy';
|
||||
if (mode === 'chrome') {
|
||||
chromeStatus = 'connecting';
|
||||
loading = true;
|
||||
const supported =
|
||||
'VideoDecoder' in window &&
|
||||
(await VideoDecoder.isConfigSupported({ codec: 'avc1.42E028' })).supported;
|
||||
@@ -145,6 +138,10 @@
|
||||
}
|
||||
}
|
||||
if (url && mode === 'proxy') navigate(url);
|
||||
else if (url && mode === 'chrome' && !session.url) {
|
||||
await tick();
|
||||
chromeEl?.navigate(url);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
@@ -199,7 +196,6 @@
|
||||
</div>
|
||||
</div>
|
||||
{#if modeError}<div class="mode-error" title={modeError}>{modeError}</div>{/if}
|
||||
{#if loading}<div class="loading-track"><div class="loading-bar"></div></div>{/if}
|
||||
<div class="preview-content">
|
||||
{#if error}
|
||||
<div class="preview-error">
|
||||
@@ -220,7 +216,6 @@
|
||||
}}
|
||||
onstatus={(status, message, nextMode) => {
|
||||
chromeStatus = status;
|
||||
loading = status === 'connecting';
|
||||
if (message) modeError = message;
|
||||
else if (status === 'playing' || status === 'view_only') modeError = '';
|
||||
if (nextMode === 'proxy') {
|
||||
@@ -247,7 +242,6 @@
|
||||
onload={frameLoaded}
|
||||
onerror={() => {
|
||||
error = $t('port.cannotConnect');
|
||||
loading = false;
|
||||
}}
|
||||
></iframe>
|
||||
{/if}
|
||||
@@ -287,17 +281,6 @@
|
||||
display: block;
|
||||
background: white;
|
||||
}
|
||||
.loading-track {
|
||||
height: 2px;
|
||||
overflow: hidden;
|
||||
background: var(--color-gray-100);
|
||||
}
|
||||
.loading-bar {
|
||||
height: 100%;
|
||||
width: 35%;
|
||||
background: var(--color-brand-500);
|
||||
animation: browser-loading 1s ease-in-out infinite;
|
||||
}
|
||||
.preview-error {
|
||||
height: 100%;
|
||||
display: grid;
|
||||
@@ -308,12 +291,4 @@
|
||||
.error-retry {
|
||||
color: var(--color-brand-600);
|
||||
}
|
||||
@keyframes browser-loading {
|
||||
from {
|
||||
transform: translateX(-120%);
|
||||
}
|
||||
to {
|
||||
transform: translateX(320%);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -30,6 +30,7 @@
|
||||
let controller = false;
|
||||
let hasFrame = false;
|
||||
const pressedKeys = new Map<string, Record<string, unknown>>();
|
||||
const macClient = /Mac|iPhone|iPad/.test(navigator.userAgent);
|
||||
|
||||
function send(message: Record<string, unknown>) {
|
||||
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
|
||||
@@ -179,6 +180,7 @@
|
||||
event: type,
|
||||
key: event.key,
|
||||
code: event.code,
|
||||
unmodified_text: event.key.length === 1 ? event.key : '',
|
||||
text:
|
||||
type === 'keyDown' &&
|
||||
event.key.length === 1 &&
|
||||
@@ -191,7 +193,9 @@
|
||||
auto_repeat: event.repeat,
|
||||
location: event.location,
|
||||
is_keypad: event.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD,
|
||||
windows_virtual_key_code: event.keyCode
|
||||
windows_virtual_key_code: event.keyCode,
|
||||
primary_modifier: macClient ? event.metaKey : event.ctrlKey,
|
||||
primary_modifier_key: event.key === (macClient ? 'Meta' : 'Control')
|
||||
};
|
||||
if (type === 'keyDown') pressedKeys.set(event.code, message);
|
||||
else pressedKeys.delete(event.code);
|
||||
|
||||
@@ -560,7 +560,8 @@ export async function loadWorkspace(path: string): Promise<void> {
|
||||
group.tabs.map(async (tab) => {
|
||||
if (tab.type !== 'preview' || !tab.port) return tab;
|
||||
try {
|
||||
const session = await createBrowserSession();
|
||||
const previewUrl = `http://localhost:${tab.port}/`;
|
||||
const session = await createBrowserSession(previewUrl);
|
||||
aliveBrowserSessions.add(session.session_id);
|
||||
const { port, ...browserTab } = tab;
|
||||
return {
|
||||
@@ -568,7 +569,7 @@ export async function loadWorkspace(path: string): Promise<void> {
|
||||
type: 'browser' as const,
|
||||
label: `localhost:${port}`,
|
||||
browserSessionId: session.session_id,
|
||||
path: `http://127.0.0.1:${port}/`
|
||||
path: previewUrl
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -937,7 +938,7 @@ export async function openPreviewTab(port: number, targetGroupId?: string): Prom
|
||||
if (!group) return;
|
||||
|
||||
// Reuse existing tab within this group
|
||||
const url = `http://127.0.0.1:${port}/`;
|
||||
const url = `http://localhost:${port}/`;
|
||||
const existing = group.tabs.find((t) => t.type === 'browser' && t.path === url);
|
||||
if (existing) {
|
||||
setActiveTab(existing.id, gid);
|
||||
@@ -960,7 +961,7 @@ export async function openBrowserTab(
|
||||
const pendingTab: Tab = { id: tabId, type: 'browser', label, path: url };
|
||||
updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, pendingTab], activeTabId: tabId }));
|
||||
try {
|
||||
const session = await createBrowserSession();
|
||||
const session = await createBrowserSession(url);
|
||||
let attached = false;
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: tabs.map((tab) => {
|
||||
|
||||
+53
-12
@@ -15,7 +15,13 @@ from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
||||
|
||||
from cptr.routers.auth import COOKIE_NAME
|
||||
from cptr.models import Config
|
||||
from cptr.utils.browser.proxy import manager, rewrite_css, rewrite_html, rewrite_javascript, target_url
|
||||
from cptr.utils.browser.proxy import (
|
||||
manager,
|
||||
rewrite_css,
|
||||
rewrite_html,
|
||||
rewrite_javascript,
|
||||
target_url,
|
||||
)
|
||||
from cptr.utils.browser.viewer import local_origin, manager as chrome_viewer_manager
|
||||
from cptr.utils.config import AuthResult, check_access
|
||||
|
||||
@@ -79,7 +85,9 @@ def _headers(request: Request, upstream_url: str) -> dict[str, str]:
|
||||
|
||||
def _response_headers(upstream: httpx.Response) -> dict[str, str]:
|
||||
headers = {
|
||||
key: value for key, value in upstream.headers.items() if key.lower() not in _SKIP_RESPONSE_HEADERS
|
||||
key: value
|
||||
for key, value in upstream.headers.items()
|
||||
if key.lower() not in _SKIP_RESPONSE_HEADERS
|
||||
}
|
||||
headers["x-cptr-browser-url"] = str(upstream.url)
|
||||
return headers
|
||||
@@ -107,7 +115,9 @@ async def _stream_response(upstream: httpx.Response) -> AsyncIterator[bytes]:
|
||||
await upstream.aclose()
|
||||
|
||||
|
||||
async def proxy_browser_request(request: Request, session_id: str, url: str, owner: str) -> Response:
|
||||
async def proxy_browser_request(
|
||||
request: Request, session_id: str, url: str, owner: str
|
||||
) -> Response:
|
||||
client = manager.client(session_id, owner)
|
||||
if client is None:
|
||||
raise HTTPException(status_code=404, detail="Browser tab expired")
|
||||
@@ -122,11 +132,15 @@ async def proxy_browser_request(request: Request, session_id: str, url: str, own
|
||||
parsed = urlsplit(upstream_url)
|
||||
if parsed.hostname == "127.0.0.1":
|
||||
port = f":{parsed.port}" if parsed.port else ""
|
||||
candidates.append(urlunsplit((parsed.scheme, f"[::1]{port}", parsed.path, parsed.query, "")))
|
||||
candidates.append(
|
||||
urlunsplit((parsed.scheme, f"[::1]{port}", parsed.path, parsed.query, ""))
|
||||
)
|
||||
for candidate in candidates:
|
||||
try:
|
||||
upstream = await client.send(
|
||||
client.build_request(request.method, candidate, headers=_headers(request, candidate), content=body),
|
||||
client.build_request(
|
||||
request.method, candidate, headers=_headers(request, candidate), content=body
|
||||
),
|
||||
stream=True,
|
||||
)
|
||||
break
|
||||
@@ -151,7 +165,9 @@ async def proxy_browser_request(request: Request, session_id: str, url: str, own
|
||||
final_url = str(upstream.url)
|
||||
if parsed.hostname == "127.0.0.1" and urlsplit(final_url).hostname == "::1":
|
||||
redirected = urlsplit(final_url)
|
||||
final_url = urlunsplit((parsed.scheme, parsed.netloc, redirected.path, redirected.query, ""))
|
||||
final_url = urlunsplit(
|
||||
(parsed.scheme, parsed.netloc, redirected.path, redirected.query, "")
|
||||
)
|
||||
if f"/api/browser/frame/{session_id}/" not in urlsplit(final_url).path:
|
||||
await manager.update(session_id, owner, url=final_url)
|
||||
text = content.decode(upstream.encoding or "utf-8", errors="replace")
|
||||
@@ -170,7 +186,9 @@ async def proxy_browser_request(request: Request, session_id: str, url: str, own
|
||||
content = rewrite_javascript(text, upstream_url, session_id).encode("utf-8")
|
||||
headers.pop("content-type", None)
|
||||
content_type = "text/javascript; charset=utf-8"
|
||||
return Response(content=content, status_code=upstream.status_code, headers=headers, media_type=content_type)
|
||||
return Response(
|
||||
content=content, status_code=upstream.status_code, headers=headers, media_type=content_type
|
||||
)
|
||||
|
||||
|
||||
async def _proxy(request: Request, session_id: str, url: str) -> Response:
|
||||
@@ -183,6 +201,16 @@ async def browser_availability(request: Request):
|
||||
return chrome_viewer_manager.availability()
|
||||
|
||||
|
||||
def _initial_url(value: object) -> str:
|
||||
url = str(value or "").strip()
|
||||
if not url:
|
||||
return ""
|
||||
parsed = urlsplit(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise HTTPException(status_code=400, detail="Invalid Browser URL")
|
||||
return url
|
||||
|
||||
|
||||
@router.post("/sessions")
|
||||
async def create_session(request: Request):
|
||||
try:
|
||||
@@ -197,7 +225,10 @@ async def create_session(request: Request):
|
||||
)
|
||||
if mode not in {"proxy", "chrome"}:
|
||||
raise HTTPException(status_code=400, detail="Invalid Browser mode")
|
||||
initial_url = _initial_url(payload.get("url") if isinstance(payload, dict) else None)
|
||||
session = await manager.create(_owner(_auth(request)))
|
||||
if initial_url:
|
||||
await manager.update(session.session_id, session.owner, url=initial_url)
|
||||
if mode == "chrome":
|
||||
try:
|
||||
await chrome_viewer_manager.start(session, local_origin(str(request.base_url)))
|
||||
@@ -281,7 +312,8 @@ async def blank(session_id: str, request: Request):
|
||||
|
||||
|
||||
@router.api_route(
|
||||
"/resources/{session_id}/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
||||
"/resources/{session_id}/{path:path}",
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
|
||||
)
|
||||
async def proxy_resource(session_id: str, path: str, request: Request):
|
||||
owner = _owner(_auth(request))
|
||||
@@ -294,7 +326,9 @@ async def proxy_resource(session_id: str, path: str, request: Request):
|
||||
return await proxy_browser_request(request, session_id, url, owner)
|
||||
|
||||
|
||||
@router.api_route("/frame/{session_id}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
|
||||
@router.api_route(
|
||||
"/frame/{session_id}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
||||
)
|
||||
async def proxy_frame(session_id: str, url: str, request: Request):
|
||||
return await _proxy(request, session_id, url)
|
||||
|
||||
@@ -304,11 +338,16 @@ async def proxy_frame(session_id: str, url: str, request: Request):
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
|
||||
)
|
||||
async def legacy_proxy_frame(session_id: str, scheme: str, host: str, path: str, request: Request):
|
||||
return await _proxy(request, session_id, urlunsplit((scheme, host, "/" + path.lstrip("/"), request.url.query, "")))
|
||||
return await _proxy(
|
||||
request,
|
||||
session_id,
|
||||
urlunsplit((scheme, host, "/" + path.lstrip("/"), request.url.query, "")),
|
||||
)
|
||||
|
||||
|
||||
@router.api_route(
|
||||
"/frame/{session_id}/{scheme}/{host}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
||||
"/frame/{session_id}/{scheme}/{host}",
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
|
||||
)
|
||||
async def legacy_proxy_frame_root(session_id: str, scheme: str, host: str, request: Request):
|
||||
return await _proxy(request, session_id, urlunsplit((scheme, host, "/", request.url.query, "")))
|
||||
@@ -332,7 +371,9 @@ async def proxy_websocket(websocket: WebSocket, session_id: str):
|
||||
return
|
||||
client = manager.client(session_id, owner)
|
||||
assert client is not None
|
||||
prepared = client.build_request("GET", target.replace("ws:", "http:", 1).replace("wss:", "https:", 1))
|
||||
prepared = client.build_request(
|
||||
"GET", target.replace("ws:", "http:", 1).replace("wss:", "https:", 1)
|
||||
)
|
||||
headers = {"cookie": prepared.headers["cookie"]} if "cookie" in prepared.headers else None
|
||||
upstream = await websockets.connect(target, additional_headers=headers)
|
||||
await websocket.send_json({"type": "open", "protocol": upstream.subprotocol or ""})
|
||||
|
||||
@@ -9,6 +9,7 @@ import os
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
@@ -27,6 +28,23 @@ CAPTURE_TITLE = "cptr Chrome capture source"
|
||||
EventHandler = Callable[[dict[str, Any]], Awaitable[None]]
|
||||
|
||||
|
||||
def _target_modifiers(modifiers: int, primary: bool) -> int:
|
||||
if not primary:
|
||||
return modifiers
|
||||
return (modifiers & ~6) | (4 if sys.platform == "darwin" else 2)
|
||||
|
||||
|
||||
def _target_key(
|
||||
key: str, code: str, virtual_key: int, location: int, primary: bool
|
||||
) -> tuple[str, str, int]:
|
||||
if not primary:
|
||||
return key, code, virtual_key
|
||||
target = "Meta" if sys.platform == "darwin" else "Control"
|
||||
side = "Right" if location == 2 else "Left"
|
||||
virtual_key = (92 if side == "Right" else 91) if target == "Meta" else 17
|
||||
return target, f"{target}{side}", virtual_key
|
||||
|
||||
|
||||
def browser_name(path: str) -> str:
|
||||
name = Path(path).name.lower()
|
||||
if "brave" in name:
|
||||
@@ -573,21 +591,35 @@ class ChromeViewerManager:
|
||||
if event not in {"keyDown", "keyUp", "char"}:
|
||||
return
|
||||
text = str(data.get("text", ""))
|
||||
key = str(data.get("key", ""))
|
||||
code = str(data.get("code", ""))
|
||||
location = max(0, min(3, int(data.get("location", 0))))
|
||||
virtual_key = max(0, min(65535, int(data.get("windows_virtual_key_code", 0))))
|
||||
key, code, virtual_key = _target_key(
|
||||
key,
|
||||
code,
|
||||
virtual_key,
|
||||
location,
|
||||
bool(data.get("primary_modifier_key", False)),
|
||||
)
|
||||
modifiers = _target_modifiers(
|
||||
int(data.get("modifiers", 0)), bool(data.get("primary_modifier", False))
|
||||
)
|
||||
params: dict[str, Any] = {
|
||||
"type": "rawKeyDown" if event == "keyDown" and not text else event,
|
||||
"key": key,
|
||||
"code": code,
|
||||
"text": text,
|
||||
"unmodifiedText": str(data.get("unmodified_text", "")),
|
||||
"modifiers": modifiers,
|
||||
"autoRepeat": bool(data.get("auto_repeat", False)),
|
||||
"location": location,
|
||||
"isKeypad": bool(data.get("is_keypad", False)),
|
||||
"windowsVirtualKeyCode": virtual_key,
|
||||
}
|
||||
await viewer.target_cdp.send(
|
||||
"Input.dispatchKeyEvent",
|
||||
{
|
||||
"type": "rawKeyDown" if event == "keyDown" and not text else event,
|
||||
"key": str(data.get("key", "")),
|
||||
"code": str(data.get("code", "")),
|
||||
"text": text,
|
||||
"modifiers": int(data.get("modifiers", 0)),
|
||||
"autoRepeat": bool(data.get("auto_repeat", False)),
|
||||
"location": max(0, min(3, int(data.get("location", 0)))),
|
||||
"isKeypad": bool(data.get("is_keypad", False)),
|
||||
"windowsVirtualKeyCode": max(
|
||||
0, min(65535, int(data.get("windows_virtual_key_code", 0)))
|
||||
),
|
||||
},
|
||||
params,
|
||||
)
|
||||
elif kind == "paste":
|
||||
await viewer.target_cdp.send("Input.insertText", {"text": str(data.get("text", ""))})
|
||||
|
||||
Reference in new issue
Block a user