mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 22:11:29 -05:00
refac
This commit is contained in:
1 parent
c186284484
commit
622e1daff2
5 files changed
+152
-44
No files matched your search
@@ -11,6 +11,7 @@
|
||||
import { openBrowserTab, updateTabLabel } from '$lib/stores';
|
||||
import Icon from './Icon.svelte';
|
||||
import ChromeBrowser from './ChromeBrowser.svelte';
|
||||
import Spinner from './common/Spinner.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
@@ -132,6 +133,8 @@
|
||||
updateTabLabel(tabId, title);
|
||||
mode = session.mode || 'proxy';
|
||||
if (mode === 'chrome') {
|
||||
chromeStatus = 'connecting';
|
||||
loading = true;
|
||||
const supported =
|
||||
'VideoDecoder' in window &&
|
||||
(await VideoDecoder.isConfigSupported({ codec: 'avc1.42E028' })).supported;
|
||||
@@ -179,7 +182,7 @@
|
||||
</button>
|
||||
<div class="relative min-w-0 flex-1">
|
||||
<input
|
||||
class="h-7 w-full min-w-0 rounded-full border border-transparent bg-gray-100 py-1 pr-8 pl-3 text-left text-xs font-medium text-gray-700 outline-none transition-colors focus:border-gray-300 focus:bg-white sm:px-8 sm:text-center dark:bg-white/8 dark:text-gray-300 dark:focus:border-white/12 dark:focus:bg-white/11"
|
||||
class="h-7 w-full min-w-0 rounded-full bg-transparent py-1 pr-8 pl-3 text-left text-xs font-medium text-gray-700 outline-none transition-colors hover:bg-gray-100/60 focus:bg-gray-100 sm:px-8 sm:text-center dark:text-gray-300 dark:hover:bg-white/5 dark:focus:bg-white/8"
|
||||
bind:value={urlInput}
|
||||
onkeydown={(event) => event.key === 'Enter' && navigate()}
|
||||
placeholder="https://example.com"
|
||||
@@ -214,18 +217,26 @@
|
||||
updateTabLabel(tabId, title);
|
||||
canGoBack = state.can_go_back;
|
||||
canGoForward = state.can_go_forward;
|
||||
loading = false;
|
||||
}}
|
||||
onstatus={(status, message, nextMode) => {
|
||||
chromeStatus = status;
|
||||
loading = status === 'connecting';
|
||||
if (message) modeError = message;
|
||||
else if (status === 'playing' || status === 'view_only') modeError = '';
|
||||
if (nextMode === 'proxy') {
|
||||
mode = 'proxy';
|
||||
if (urlInput) frameSrc = browserFrameUrl(sessionId, urlInput);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{#if chromeStatus === 'connecting'}
|
||||
<div
|
||||
class="pointer-events-none absolute inset-0 z-10 flex items-center justify-center gap-2 bg-white/80 text-xs text-gray-500 dark:bg-black/80 dark:text-gray-400"
|
||||
>
|
||||
<Spinner size={14} />
|
||||
<span>{$t('common.loading')}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if chromeStatus === 'view_only'}<div class="status-pill">{$t('browser.viewOnly')}</div>{/if}
|
||||
{:else}
|
||||
<iframe
|
||||
|
||||
@@ -27,6 +27,9 @@
|
||||
let viewport = { width: 1280, height: 720 };
|
||||
let pendingPointer: Record<string, unknown> | undefined;
|
||||
let pointerFrame = 0;
|
||||
let controller = false;
|
||||
let hasFrame = false;
|
||||
const pressedKeys = new Map<string, Record<string, unknown>>();
|
||||
|
||||
function send(message: Record<string, unknown>) {
|
||||
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
|
||||
@@ -34,6 +37,7 @@
|
||||
|
||||
function connect() {
|
||||
if (disposed) return;
|
||||
hasFrame = false;
|
||||
onstatus('connecting');
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
socket = new WebSocket(`${scheme}://${location.host}/api/browser/sessions/${sessionId}/stream`);
|
||||
@@ -55,9 +59,10 @@
|
||||
function receive(event: MessageEvent) {
|
||||
if (typeof event.data === 'string') {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.type === 'ready') onstatus(message.controller ? 'playing' : 'view_only');
|
||||
if (message.type === 'ready') controller = message.controller === true;
|
||||
if (message.type === 'state') onstate(message);
|
||||
if (message.type === 'status') onstatus(message.status, message.message, message.mode);
|
||||
if (message.type === 'status' && (message.status !== 'playing' || hasFrame))
|
||||
onstatus(message.status, message.message, message.mode);
|
||||
if (message.type === 'config') configureDecoder(message);
|
||||
return;
|
||||
}
|
||||
@@ -86,6 +91,10 @@
|
||||
canvas.height = frame.displayHeight;
|
||||
canvas.getContext('2d', { alpha: false })?.drawImage(frame, 0, 0);
|
||||
frame.close();
|
||||
if (!hasFrame) {
|
||||
hasFrame = true;
|
||||
onstatus(controller ? 'playing' : 'view_only');
|
||||
}
|
||||
},
|
||||
error() {
|
||||
send({ type: 'request_keyframe' });
|
||||
@@ -164,14 +173,34 @@
|
||||
|
||||
function key(event: KeyboardEvent, type: 'keyDown' | 'keyUp') {
|
||||
event.preventDefault();
|
||||
send({
|
||||
event.stopPropagation();
|
||||
const message = {
|
||||
type: 'key',
|
||||
event: type,
|
||||
key: event.key,
|
||||
code: event.code,
|
||||
text: type === 'keyDown' && event.key.length === 1 ? event.key : '',
|
||||
modifiers: modifiers(event)
|
||||
});
|
||||
text:
|
||||
type === 'keyDown' &&
|
||||
event.key.length === 1 &&
|
||||
!event.altKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
? event.key
|
||||
: '',
|
||||
modifiers: modifiers(event),
|
||||
auto_repeat: event.repeat,
|
||||
location: event.location,
|
||||
is_keypad: event.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD,
|
||||
windows_virtual_key_code: event.keyCode
|
||||
};
|
||||
if (type === 'keyDown') pressedKeys.set(event.code, message);
|
||||
else pressedKeys.delete(event.code);
|
||||
send(message);
|
||||
}
|
||||
|
||||
function releaseKeys() {
|
||||
for (const message of pressedKeys.values()) send({ ...message, event: 'keyUp', text: '' });
|
||||
pressedKeys.clear();
|
||||
}
|
||||
|
||||
export function navigate(url: string) {
|
||||
@@ -202,6 +231,7 @@
|
||||
|
||||
onDestroy(() => {
|
||||
disposed = true;
|
||||
releaseKeys();
|
||||
observer?.disconnect();
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
if (pointerFrame) cancelAnimationFrame(pointerFrame);
|
||||
@@ -220,8 +250,10 @@
|
||||
onwheel={wheel}
|
||||
onkeydown={(event) => key(event, 'keyDown')}
|
||||
onkeyup={(event) => key(event, 'keyUp')}
|
||||
onblur={releaseKeys}
|
||||
onpaste={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
send({ type: 'paste', text: event.clipboardData?.getData('text/plain') || '' });
|
||||
}}
|
||||
oncontextmenu={(event) => event.preventDefault()}
|
||||
|
||||
@@ -171,7 +171,11 @@ function splitLayout(
|
||||
};
|
||||
}
|
||||
|
||||
function replaceLayoutGroup(layout: EditorLayout, groupId: string, replacementId: string): EditorLayout {
|
||||
function replaceLayoutGroup(
|
||||
layout: EditorLayout,
|
||||
groupId: string,
|
||||
replacementId: string
|
||||
): EditorLayout {
|
||||
if (layout.type === 'group') {
|
||||
return layout.groupId === groupId ? { type: 'group', groupId: replacementId } : layout;
|
||||
}
|
||||
@@ -203,14 +207,18 @@ function isEditorLayout(value: unknown): value is EditorLayout {
|
||||
return node.type === 'group'
|
||||
? typeof node.groupId === 'string'
|
||||
: node.type === 'split' &&
|
||||
typeof node.id === 'string' &&
|
||||
(node.direction === 'horizontal' || node.direction === 'vertical') &&
|
||||
typeof node.ratio === 'number' &&
|
||||
isEditorLayout(node.first) &&
|
||||
isEditorLayout(node.second);
|
||||
typeof node.id === 'string' &&
|
||||
(node.direction === 'horizontal' || node.direction === 'vertical') &&
|
||||
typeof node.ratio === 'number' &&
|
||||
isEditorLayout(node.first) &&
|
||||
isEditorLayout(node.second);
|
||||
}
|
||||
|
||||
function createLayout(groups: EditorGroup[], direction: SplitDirection, ratio: number): EditorLayout {
|
||||
function createLayout(
|
||||
groups: EditorGroup[],
|
||||
direction: SplitDirection,
|
||||
ratio: number
|
||||
): EditorLayout {
|
||||
let layout: EditorLayout = { type: 'group', groupId: groups[0].id };
|
||||
for (const group of groups.slice(1)) {
|
||||
layout = {
|
||||
@@ -605,7 +613,12 @@ export async function loadWorkspace(path: string): Promise<void> {
|
||||
path: canonicalWorkspacePath,
|
||||
groups,
|
||||
activeGroupId,
|
||||
layout: normalizeLayout(ws.layout, groups, ws.splitDirection ?? 'horizontal', ws.splitRatio ?? 0.5),
|
||||
layout: normalizeLayout(
|
||||
ws.layout,
|
||||
groups,
|
||||
ws.splitDirection ?? 'horizontal',
|
||||
ws.splitRatio ?? 0.5
|
||||
),
|
||||
splitDirection: ws.splitDirection ?? 'horizontal',
|
||||
splitRatio: ws.splitRatio ?? 0.5,
|
||||
fileBrowserCwd: ws.fileBrowserCwd ?? canonicalWorkspacePath
|
||||
@@ -934,23 +947,32 @@ export async function openPreviewTab(port: number, targetGroupId?: string): Prom
|
||||
await openBrowserTab(gid, url, `localhost:${port}`);
|
||||
}
|
||||
|
||||
export async function openBrowserTab(targetGroupId?: string, url?: string, label = 'Browser'): Promise<void> {
|
||||
export async function openBrowserTab(
|
||||
targetGroupId?: string,
|
||||
url?: string,
|
||||
label = 'Browser'
|
||||
): Promise<void> {
|
||||
const ws = get(currentWorkspace);
|
||||
if (!ws) return;
|
||||
const gid = targetGroupId ?? ws.activeGroupId;
|
||||
if (!ws.groups.some((group) => group.id === gid)) return;
|
||||
const tabId = nextId();
|
||||
const pendingTab: Tab = { id: tabId, type: 'browser', label, path: url };
|
||||
updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, pendingTab], activeTabId: tabId }));
|
||||
try {
|
||||
const session = await createBrowserSession();
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'browser',
|
||||
label,
|
||||
browserSessionId: session.session_id,
|
||||
path: url
|
||||
};
|
||||
updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id }));
|
||||
let attached = false;
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: tabs.map((tab) => {
|
||||
if (tab.id !== tabId) return tab;
|
||||
attached = true;
|
||||
return { ...tab, browserSessionId: session.session_id };
|
||||
})
|
||||
}));
|
||||
if (!attached) deleteBrowserSession(session.session_id);
|
||||
} catch (error) {
|
||||
console.error('Failed to create browser session:', error);
|
||||
closeTab(tabId, gid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1066,7 +1088,7 @@ export function closeTab(tabId: string, groupId?: string): void {
|
||||
groups: newGroups,
|
||||
layout: closedGroupStillExists
|
||||
? ws.layout
|
||||
: removeLayoutGroup(ws.layout, gid) ?? { type: 'group', groupId: newGroups[0].id },
|
||||
: (removeLayoutGroup(ws.layout, gid) ?? { type: 'group', groupId: newGroups[0].id }),
|
||||
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id
|
||||
};
|
||||
});
|
||||
@@ -1277,7 +1299,9 @@ export function moveTabToGroup(tabId: string, fromGroupId: string, toGroupId: st
|
||||
return {
|
||||
...ws,
|
||||
groups: newGroups,
|
||||
layout: sourceGroupStillExists ? ws.layout : removeLayoutGroup(ws.layout, fromGroupId) ?? ws.layout,
|
||||
layout: sourceGroupStillExists
|
||||
? ws.layout
|
||||
: (removeLayoutGroup(ws.layout, fromGroupId) ?? ws.layout),
|
||||
activeGroupId: targetGroupStillExists ? toGroupId : newGroups[0].id
|
||||
};
|
||||
});
|
||||
@@ -1307,7 +1331,9 @@ export function moveTabToNewSplit(
|
||||
const tabs = g.tabs.filter((t) => t.id !== tabId);
|
||||
return { ...g, tabs, activeTabId: tabs[0]?.id ?? '' };
|
||||
});
|
||||
const sourceGroupRemoved = groups.some((group) => group.id === fromGroupId && group.tabs.length === 0);
|
||||
const sourceGroupRemoved = groups.some(
|
||||
(group) => group.id === fromGroupId && group.tabs.length === 0
|
||||
);
|
||||
groups = groups.filter((g) => g.tabs.length > 0);
|
||||
groups.push(newGroup);
|
||||
let layout = ws.layout;
|
||||
@@ -1315,7 +1341,7 @@ export function moveTabToNewSplit(
|
||||
layout =
|
||||
fromGroupId === targetGroupId
|
||||
? replaceLayoutGroup(layout, fromGroupId, newGroup.id)
|
||||
: removeLayoutGroup(layout, fromGroupId) ?? layout;
|
||||
: (removeLayoutGroup(layout, fromGroupId) ?? layout);
|
||||
}
|
||||
if (!(sourceGroupRemoved && fromGroupId === targetGroupId)) {
|
||||
layout = splitLayout(layout, targetGroupId, newGroup.id, direction, placement);
|
||||
|
||||
@@ -588,10 +588,17 @@
|
||||
element: HTMLElement;
|
||||
} | null>(null);
|
||||
|
||||
function handleDividerPointerDown(e: PointerEvent, split: Extract<EditorLayout, { type: 'split' }>) {
|
||||
function handleDividerPointerDown(
|
||||
e: PointerEvent,
|
||||
split: Extract<EditorLayout, { type: 'split' }>
|
||||
) {
|
||||
e.preventDefault();
|
||||
const divider = e.currentTarget as HTMLElement;
|
||||
resizingSplit = { splitId: split.id, direction: split.direction, element: divider.parentElement! };
|
||||
resizingSplit = {
|
||||
splitId: split.id,
|
||||
direction: split.direction,
|
||||
element: divider.parentElement!
|
||||
};
|
||||
divider.setPointerCapture(e.pointerId);
|
||||
}
|
||||
|
||||
@@ -723,7 +730,10 @@
|
||||
}
|
||||
|
||||
function handlePaneDragLeave(e: DragEvent, groupId: string) {
|
||||
if (!(e.currentTarget as HTMLElement).contains(e.relatedTarget as Node) && dragOverZone?.groupId === groupId) {
|
||||
if (
|
||||
!(e.currentTarget as HTMLElement).contains(e.relatedTarget as Node) &&
|
||||
dragOverZone?.groupId === groupId
|
||||
) {
|
||||
dragOverZone = null;
|
||||
}
|
||||
}
|
||||
@@ -900,11 +910,7 @@
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Editor groups layout -->
|
||||
<div
|
||||
class="split-container"
|
||||
class:is-dragging={resizingSplit !== null}
|
||||
role="presentation"
|
||||
>
|
||||
<div class="split-container" class:is-dragging={resizingSplit !== null} role="presentation">
|
||||
{#if isWideScreen && layout}
|
||||
{@render renderLayout(layout)}
|
||||
{:else if activeGroup}
|
||||
@@ -918,7 +924,11 @@
|
||||
{@const group = allGroups.find((item) => item.id === node.groupId)}
|
||||
{#if group}{@render renderPane(group)}{/if}
|
||||
{:else}
|
||||
<div class="split-branch" class:split-branch-horizontal={node.direction === 'horizontal'} class:split-branch-vertical={node.direction === 'vertical'}>
|
||||
<div
|
||||
class="split-branch"
|
||||
class:split-branch-horizontal={node.direction === 'horizontal'}
|
||||
class:split-branch-vertical={node.direction === 'vertical'}
|
||||
>
|
||||
<div class="split-branch-child" style={`flex: ${node.ratio} 1 0%;`}>
|
||||
{@render renderLayout(node.first)}
|
||||
</div>
|
||||
@@ -968,7 +978,13 @@
|
||||
{/each}
|
||||
{#each group.tabs.filter((tab) => tab.type === 'chat') as tab (tab.id)}
|
||||
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
|
||||
<ChatPanel workspace={$currentWorkspace!.path} chatId={tab.path?.startsWith('new-') || tab.path?.startsWith('pending-') ? undefined : tab.path} tabId={tab.id} />
|
||||
<ChatPanel
|
||||
workspace={$currentWorkspace!.path}
|
||||
chatId={tab.path?.startsWith('new-') || tab.path?.startsWith('pending-')
|
||||
? undefined
|
||||
: tab.path}
|
||||
tabId={tab.id}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
{#each group.tabs.filter((tab) => tab.type === 'terminal' && tab.sessionId) as tab (tab.id)}
|
||||
@@ -991,6 +1007,13 @@
|
||||
<FileBrowser />
|
||||
{:else if groupTab.type === 'terminal' && !groupTab.sessionId}
|
||||
<div class="flex items-center justify-center h-full"><Spinner size={20} /></div>
|
||||
{:else if groupTab.type === 'browser' && !groupTab.browserSessionId}
|
||||
<div
|
||||
class="flex h-full items-center justify-center gap-2 text-xs text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
<Spinner size={16} />
|
||||
<span>{$t('common.loading')}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -298,7 +298,8 @@ class ChromeViewerManager:
|
||||
try:
|
||||
for _ in range(30):
|
||||
ready = await controller_cdp.send(
|
||||
"Runtime.evaluate", {"expression": "typeof window.startCapture === 'function'"}
|
||||
"Runtime.evaluate",
|
||||
{"expression": "typeof window.startCapture === 'function'"},
|
||||
)
|
||||
if ready.get("result", {}).get("value") is True:
|
||||
break
|
||||
@@ -338,7 +339,11 @@ class ChromeViewerManager:
|
||||
with contextlib.suppress(Exception):
|
||||
await viewer.target_cdp.send("Page.handleJavaScriptDialog", {"accept": True})
|
||||
|
||||
for method in ("Page.frameNavigated", "Page.navigatedWithinDocument", "Page.loadEventFired"):
|
||||
for method in (
|
||||
"Page.frameNavigated",
|
||||
"Page.navigatedWithinDocument",
|
||||
"Page.loadEventFired",
|
||||
):
|
||||
viewer.target_cdp.on(method, refresh)
|
||||
viewer.target_cdp.on("Page.javascriptDialogOpening", dialog)
|
||||
|
||||
@@ -412,7 +417,8 @@ class ChromeViewerManager:
|
||||
viewer.encoder = None
|
||||
viewer.session.status = "lost"
|
||||
await self._broadcast_json(
|
||||
viewer, {"type": "status", "status": "lost", "message": "Chrome encoder disconnected"}
|
||||
viewer,
|
||||
{"type": "status", "status": "lost", "message": "Chrome encoder disconnected"},
|
||||
)
|
||||
if self.viewers.get(session_id) is viewer:
|
||||
asyncio.create_task(self._restart_encoder(viewer))
|
||||
@@ -563,14 +569,24 @@ class ChromeViewerManager:
|
||||
elif kind == "wheel":
|
||||
await self._wheel(viewer, data)
|
||||
elif kind == "key":
|
||||
event = str(data.get("event", ""))
|
||||
if event not in {"keyDown", "keyUp", "char"}:
|
||||
return
|
||||
text = str(data.get("text", ""))
|
||||
await viewer.target_cdp.send(
|
||||
"Input.dispatchKeyEvent",
|
||||
{
|
||||
"type": str(data.get("event", "keyDown")),
|
||||
"type": "rawKeyDown" if event == "keyDown" and not text else event,
|
||||
"key": str(data.get("key", "")),
|
||||
"code": str(data.get("code", "")),
|
||||
"text": str(data.get("text", "")),
|
||||
"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)))
|
||||
),
|
||||
},
|
||||
)
|
||||
elif kind == "paste":
|
||||
|
||||
Reference in new issue
Block a user