Merge pull request #127 from open-webui/main

0.9.0
This commit is contained in:
Tim Baek authored and GitHub committed 2026-07-11 19:02:18 -05:00
commit b9e00a1a81
70 files changed
+8136 -1817

No files matched your search

+14
View File
@@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.9.0] - 2026-07-11
### Added
- 🌐 **A browser in your workspace.** Open websites and local app previews in their own tabs, with back and forward navigation, mobile views, and display-quality choices.
- 🤖 **More coding agents.** Add Gemini or Pi alongside the coding tools you already use.
- 🔎 **Search inside files.** Find file names and matching text, then jump straight to the right line.
- 💬 **A more useful home screen.** Start a chat, terminal, or browser before opening a workspace, and arrange them side by side.
### Changed
- 🗂️ **Easier chat organization.** Rename chats, copy their saved location, and load more of a workspace's chats without leaving the sidebar.
- ✨ **More control over the view.** Choose a wider layout and decide whether tool details stay expanded.
## [0.8.8] - 2026-07-09
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
# Manifesto
> **TL;DR** We pushed code and went to dinner. Prod broke. Phone in pocket, laptop at home. The fix was on our computer, not in some fresh cloud box. So we built `cptr`: your actual machine, in any browser. Files, terminal, editor, git, running sessions, all of it. Phone, tablet, laptop, whatever. It literally is your computer. Now go outside.
> **TL;DR** We pushed code and went to dinner. Prod broke. Phone in pocket, laptop at home. The fix was on our computer, not in some fresh cloud box. So we built Open WebUI Computer: your actual machine, in any browser. Files, terminal, editor, git, running sessions, all of it. Phone, tablet, laptop, whatever. It literally is your computer. Now go outside.
Your computer is where your work lives.
+5 -5
View File
@@ -1,4 +1,4 @@
# Open WebUI Computer (cptr)
# Open WebUI Computer
![GitHub stars](https://img.shields.io/github/stars/open-webui/computer?style=social)
![GitHub forks](https://img.shields.io/github/forks/open-webui/computer?style=social)
@@ -12,12 +12,12 @@
![Open WebUI Computer Demo](./demo.png)
<sub>See more at [cptr.sh](https://cptr.sh/)</sub>
Open WebUI Computer (`cptr`) runs on your machine and serves your whole computer to any browser: files, terminal, editor, git, running sessions, AI agents, and tools. It literally is your computer.
Use it from your phone, tablet, laptop, another computer, or the machine it's running on. Designed to feel native on every screen. Connect your own AI via API key, plug in a coding agent you already subscribe to, or work directly in the terminal. One tool, full workstation, any device.
> Start here: [Open WebUI Computer docs](https://docs.openwebui.com/ecosystem/computer/)
## Install
```bash
@@ -101,11 +101,11 @@ Bring your own API key (OpenAI, Anthropic, Ollama, or any OpenAI-compatible endp
Use the subscriptions you already pay for as native backends on your own machine. No separate API key needed.
**Codex** · **Claude Code** · **Cursor** · **Grok** · **OpenCode** · **Cline**
**Codex** · **Claude Code** · **Cursor** · **Grok** · **OpenCode** · **Cline** · **Gemini** · **Pi**
Add an agent profile from Settings, pick your models, and it shows up in the model selector like any other provider. Conversations run inside your workspace with full tool access and resume where you left off.
Prefer to run agents yourself? Any terminal agent (Gemini CLI, Kilo Code, Pi, and others) works in the terminal tab the way it always has.
Prefer to run agents yourself? Any terminal agent (Kilo Code, Pi, and others) works in the terminal tab the way it always has.
## Messaging bots
+7 -11
View File
@@ -11,6 +11,7 @@ from cptr.routers import (
auth_router,
automations_router,
bridge_router,
browser_router,
webhook_router,
chat_router,
events_router,
@@ -20,7 +21,6 @@ from cptr.routers import (
images_router,
memory_router,
notifications_router,
proxy_router,
search_router,
skills_router,
state_router,
@@ -84,11 +84,15 @@ async def shutdown():
await cancel_all_async_subagents(reason="shutdown")
except Exception:
pass
# Clean up browser sessions and launched Chrome
# Clean up browser sessions and launched Chrome used by agent tools.
try:
from cptr.utils.browser.session import session_manager
from cptr.utils.browser.launcher import shutdown_browser
from cptr.utils.browser.proxy import manager as browser_proxy_manager
from cptr.utils.browser.viewer import manager as chrome_viewer_manager
await chrome_viewer_manager.close_all()
await browser_proxy_manager.close_all()
await session_manager.close_all()
await shutdown_browser()
except Exception:
@@ -153,14 +157,6 @@ if audit_level != AuditLevel.NONE:
)
# Proxy fallback middleware: intercepts sub-resource requests for proxied
# dev servers (JS modules, CSS, etc.) based on the Referer header chain.
# Added after auth middleware so it wraps outermost (runs before auth),
# since proxied sub-resources don't need cptr auth.
from cptr.utils.proxy_middleware import ProxyFallbackMiddleware
app.add_middleware(ProxyFallbackMiddleware)
# CORS middleware: uses CPTR_CORS_ALLOWED_ORIGINS env var (default "*").
from fastapi.middleware.cors import CORSMiddleware
from cptr.env import CORS_ALLOWED_ORIGINS
@@ -260,6 +256,7 @@ app.include_router(audio_router)
app.include_router(auth_router)
app.include_router(automations_router)
app.include_router(bridge_router)
app.include_router(browser_router)
app.include_router(webhook_router)
app.include_router(chat_router)
app.include_router(events_router)
@@ -269,7 +266,6 @@ app.include_router(git_router)
app.include_router(images_router)
app.include_router(memory_router)
app.include_router(notifications_router)
app.include_router(proxy_router)
app.include_router(search_router)
app.include_router(skills_router)
app.include_router(state_router)
+5 -2
View File
@@ -20,17 +20,20 @@ def cli():
@click.option("--headless", is_flag=True, default=False, help="Don't open browser.")
def run(host: str, port: int, reload: bool, headless: bool):
"""Start the cptr server."""
import os, secrets
import os
import secrets
display_host = "localhost" if host == "0.0.0.0" else host
token = secrets.token_hex(32)
os.environ["CPTR_STARTUP_TOKEN"] = token
os.environ["CPTR_PORT"] = str(port)
url = f"http://{display_host}:{port}/?token={token}"
print(f"\n ➜ {url}\n")
if not headless:
import threading, webbrowser
import threading
import webbrowser
threading.Timer(1.5, lambda: webbrowser.open(url)).start()
uvicorn.run(
+2 -2
View File
@@ -29,8 +29,8 @@
--app-fg: #525252;
--app-fg-muted: color-mix(in oklab, var(--app-fg) 62%, var(--app-bg));
--app-fg-subtle: color-mix(in oklab, var(--app-fg) 48%, var(--app-bg));
--app-border: color-mix(in oklab, var(--app-fg) 10%, transparent);
--app-divider: color-mix(in oklab, var(--app-fg) 8%, transparent);
--app-border: color-mix(in oklab, var(--app-fg) 7%, transparent);
--app-divider: color-mix(in oklab, var(--app-fg) 5%, transparent);
--app-hover: color-mix(in oklab, var(--app-fg) 6%, transparent);
--app-active: color-mix(in oklab, var(--app-fg) 7%, transparent);
--app-ui-font: var(--font-sans);
+9 -1
View File
@@ -60,7 +60,15 @@ export const updateConfig = (config: Record<string, unknown>) =>
// ── Agents ─────────────────────────────────────────────────
export type AgentType = 'codex' | 'claude_code' | 'cursor' | 'grok' | 'opencode' | 'cline';
export type AgentType =
| 'codex'
| 'claude_code'
| 'cursor'
| 'grok'
| 'opencode'
| 'cline'
| 'gemini'
| 'pi';
export type AgentMode = 'auto' | 'enabled' | 'disabled';
export type AgentStatus = 'ready' | 'not_found' | 'missing_dependency' | 'auth_unknown' | 'error';
+91
View File
@@ -0,0 +1,91 @@
import { fetchHandler, fetchJSON } from '$lib/apis';
export interface BrowserSession {
session_id: string;
url: string;
title: string;
mode: 'proxy' | 'chrome';
status: string;
}
export interface BrowserAvailability {
proxy: { available: true };
chrome: {
available: boolean;
reason: string | null;
};
}
export interface PersonalChromeStatus {
status: 'disconnected' | 'connecting' | 'playing' | 'lost' | 'unavailable';
browser: string;
session_count: number;
}
let availabilityPromise: Promise<BrowserAvailability> | undefined;
export const getBrowserAvailability = () =>
(availabilityPromise ??= fetchJSON<BrowserAvailability>('/api/browser/availability'));
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');
return data.session_ids;
};
export const deleteBrowserSession = (sessionId: string) =>
fetchHandler(`/api/browser/sessions/${sessionId}`, { method: 'DELETE' }).catch(() => {});
export const getBrowserSession = (sessionId: string) =>
fetchJSON<BrowserSession>(`/api/browser/sessions/${sessionId}`);
export const updateBrowserSession = (sessionId: string, url: string, title: string) =>
fetchJSON<BrowserSession>(`/api/browser/sessions/${sessionId}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ url, title })
});
export const setBrowserMode = (sessionId: string, mode: 'proxy' | 'chrome', url: string) =>
fetchJSON<BrowserSession>(`/api/browser/sessions/${sessionId}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ mode, url })
});
export const browserFrameUrl = (sessionId: string, rawUrl: string) => {
const normalized = /^https?:\/\//i.test(rawUrl) ? rawUrl : `https://${rawUrl}`;
const url = new URL(normalized);
return `/api/browser/frame/${sessionId}/${url.protocol.slice(0, -1)}/${encodeURIComponent(url.host)}${url.pathname}${url.search}${url.hash}`;
};
export const browserBlankUrl = (sessionId: string) => `/api/browser/sessions/${sessionId}/blank`;
export const clearManagedChromeProfile = () =>
fetchJSON<{ status: string; closed_session_ids: string[] }>('/api/browser/profile', {
method: 'DELETE'
});
export const testBrowserCdp = (url: string) =>
fetchJSON<{ browser: string }>('/api/browser/cdp', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ url })
});
export const getPersonalChrome = () => fetchJSON<PersonalChromeStatus>('/api/browser/personal');
export const connectPersonalChrome = (url: string) =>
fetchJSON<PersonalChromeStatus>('/api/browser/personal', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ url })
});
export const disconnectPersonalChrome = () =>
fetchJSON<PersonalChromeStatus>('/api/browser/personal', { method: 'DELETE' });
+11 -4
View File
@@ -79,14 +79,14 @@ export interface CompactChatResult {
// ── Queries ─────────────────────────────────────────────────
export const getChats = (
workspace: string,
workspace?: string,
limit = 50,
offset = 0,
sortBy: 'title' | 'updated_at' = 'updated_at',
sortDir: 'asc' | 'desc' = 'desc'
) =>
fetchJSON<{ chats: ChatInfo[]; total: number; has_more: boolean }>(
`/api/chats?workspace=${encodeURIComponent(workspace)}&limit=${limit}&offset=${offset}&sort_by=${sortBy}&sort_dir=${sortDir}`
`/api/chats?${workspace ? `workspace=${encodeURIComponent(workspace)}&` : ''}limit=${limit}&offset=${offset}&sort_by=${sortBy}&sort_dir=${sortDir}`
);
export const getChat = (chatId: string, modelId?: string) => {
@@ -97,6 +97,13 @@ export const getChat = (chatId: string, modelId?: string) => {
export const deleteChat = (chatId: string) =>
fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}`, { method: 'DELETE' });
export const updateChatTitle = (chatId: string, title: string) =>
fetchJSON<{ ok: boolean; title: string }>(`/api/chats/${chatId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title })
});
export const forkChat = (chatId: string, messageId?: string | null) =>
fetchJSON<{ ok: boolean; chat_id: string }>(
`/api/chats/${chatId}/fork`,
@@ -108,7 +115,7 @@ export const forkChat = (chatId: string, messageId?: string | null) =>
export const sendMessage = (
content: string,
modelId: string,
workspace: string,
workspace?: string,
chatId?: string,
parentId?: string | null,
params: ChatSendParams = {},
@@ -120,7 +127,7 @@ export const sendMessage = (
jsonBody({
content,
model_id: modelId,
workspace,
...(workspace ? { workspace } : {}),
chat_id: chatId,
parent_id: parentId ?? null,
regeneration_prompt: regenerationPrompt,
+23
View File
@@ -40,3 +40,26 @@ export const searchFiles = (query: string, path: string) =>
fetchJSON(
`/api/workspace/files/search?query=${encodeURIComponent(query)}&path=${encodeURIComponent(path)}`
);
export type ContentMatch = { line: number; column: number; text: string };
export type FileMatch = {
path: string;
relative_path: string;
name: string;
type: 'file' | 'directory';
name_match: boolean;
content_matches: ContentMatch[];
};
export type FileMatches = { results: FileMatch[]; next_offset: number | null };
export const getFileMatches = (
query: string,
path: string,
showHidden: boolean,
offset = 0,
signal?: AbortSignal
) =>
fetchJSON<FileMatches>(
`/api/workspace/files/matches?query=${encodeURIComponent(query)}&path=${encodeURIComponent(path)}&show_hidden=${showHidden}&offset=${offset}`,
{ signal }
);
+5 -2
View File
@@ -45,5 +45,8 @@ export const unifiedSearch = (
return fetchJSON<UnifiedSearchResponse>(`/api/search?${params}`);
};
export const getRecentChats = (limit = 9) =>
fetchJSON<{ chats: ChatSearchResult[] }>(`/api/search/recent?limit=${limit}`);
export const getRecentChats = (limit = 9, workspace?: string) => {
const params = new URLSearchParams({ limit: String(limit) });
if (workspace) params.set('workspace', workspace);
return fetchJSON<{ chats: ChatSearchResult[] }>(`/api/search/recent?${params}`);
};
+4 -2
View File
@@ -21,5 +21,7 @@ export interface SkillInfo {
last_updated_at?: string | null;
}
export const getSkills = (workspace: string) =>
fetchJSON<SkillInfo[]>(`/api/skills?workspace=${encodeURIComponent(workspace)}`);
export const getSkills = (workspace?: string) =>
fetchJSON<SkillInfo[]>(
workspace ? `/api/skills?workspace=${encodeURIComponent(workspace)}` : '/api/skills'
);
+2 -2
View File
@@ -25,8 +25,8 @@ export interface CommandSession {
export const listSessions = () => fetchJSON<TerminalSession[]>('/api/terminal');
export const createSession = (cwd: string) =>
fetchJSON<TerminalSession>('/api/terminal', jsonBody({ cwd }));
export const createSession = (cwd?: string) =>
fetchJSON<TerminalSession>('/api/terminal', jsonBody(cwd ? { cwd } : {}));
export const deleteSession = (sessionId: string) =>
fetchHandler(`/api/terminal/${sessionId}`, { method: 'DELETE' }).catch(() => {});
@@ -48,7 +48,9 @@
cursor: 'agent',
grok: 'grok',
opencode: 'opencode',
cline: 'cline'
cline: 'cline',
gemini: 'gemini',
pi: 'pi'
}[agent];
}
@@ -59,7 +61,9 @@
cursor: 'Cursor',
grok: 'Grok',
opencode: 'OpenCode',
cline: 'Cline'
cline: 'Cline',
gemini: 'Gemini',
pi: 'Pi'
}[agent];
}
</script>
@@ -129,6 +133,8 @@
<option value="grok">Grok</option>
<option value="opencode">OpenCode</option>
<option value="cline">Cline</option>
<option value="gemini">Gemini</option>
<option value="pi">Pi</option>
</select>
</div>
</div>
@@ -112,7 +112,9 @@
cursor: 'agent',
grok: 'grok',
opencode: 'opencode',
cline: 'cline'
cline: 'cline',
gemini: 'gemini',
pi: 'pi'
}[agent];
}
@@ -123,7 +125,9 @@
cursor: 'Cursor',
grok: 'Grok',
opencode: 'OpenCode',
cline: 'Cline'
cline: 'Cline',
gemini: 'Gemini',
pi: 'Pi'
}[agent];
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,431 @@
<script lang="ts">
import { onDestroy, onMount, tick } from 'svelte';
import { tooltip } from '$lib/tooltip';
import {
browserBlankUrl,
browserFrameUrl,
getBrowserSession,
setBrowserMode,
updateBrowserSession
} from '$lib/apis/browser';
import { openBrowserTab, updateTabLabel } from '$lib/stores';
import Icon from './Icon.svelte';
import ChromeBrowser from './ChromeBrowser.svelte';
import DropdownMenu from './DropdownMenu.svelte';
import Spinner from './common/Spinner.svelte';
import { t } from '$lib/i18n';
interface Props {
sessionId: string;
groupId: string;
tabId: string;
initialUrl?: string;
active?: boolean;
onTabUpdate?: (label: string) => void;
onOpenBrowser?: (url?: string) => void;
}
type DeviceMode = 'auto' | 'desktop' | 'mobile';
type MobileViewport = { width: number; height: number };
let {
sessionId,
groupId,
tabId,
initialUrl,
active = true,
onTabUpdate,
onOpenBrowser
}: Props = $props();
let iframeEl: HTMLIFrameElement | undefined = $state();
let chromeEl: ChromeBrowser | undefined = $state();
let frameSrc = $state(browserBlankUrl(sessionId));
let urlInput = $state(initialUrl ?? '');
let title = $state('');
let error = $state('');
let modeError = $state('');
let mode = $state<'proxy' | 'chrome'>('proxy');
let chromeStatus = $state('');
let canGoBack = $state(false);
let canGoForward = $state(false);
let chromeQuality = $state<'low' | 'balanced' | 'crisp' | null>(null);
let chromeDeviceMode = $state<DeviceMode>('auto');
let chromeMobileViewport = $state<MobileViewport | undefined>();
let qualityMenuOpen = $state(false);
let qualityMenuAnchor = $state<HTMLElement>();
function updateLabel(label: string) {
if (!label.trim()) return;
if (onTabUpdate) onTabUpdate(label);
else updateTabLabel(tabId, label);
}
function setChromeQuality(quality: 'low' | 'balanced' | 'crisp') {
chromeEl?.setQuality(quality);
chromeQuality = quality;
qualityMenuOpen = false;
}
function setChromeDeviceMode(nextMode: DeviceMode) {
chromeDeviceMode = nextMode;
chromeEl?.setDeviceMode(nextMode);
}
function setChromeMobileDimension(key: keyof MobileViewport, value: number) {
if (!Number.isFinite(value) || value <= 0) return;
chromeMobileViewport = {
...(chromeMobileViewport ?? { width: 390, height: 844 }),
[key]: Math.round(value)
};
chromeEl?.setMobileViewport(chromeMobileViewport);
}
function setChromeMobileViewport(enabled: boolean) {
chromeMobileViewport = enabled
? (chromeMobileViewport ?? { width: 390, height: 844 })
: undefined;
chromeEl?.setMobileViewport(chromeMobileViewport);
}
function publicUrl(value: string) {
const proxyUrl = new URL(value, location.origin);
if (proxyUrl.pathname === `/api/browser/frame/${sessionId}`)
return proxyUrl.searchParams.get('url') || value;
const marker = `/api/browser/frame/${sessionId}/`;
const index = proxyUrl.pathname.indexOf(marker);
if (index === -1) return value;
const [scheme, encodedHost, ...path] = proxyUrl.pathname
.slice(index + marker.length)
.split('/');
const host = decodeURIComponent(encodedHost || '');
return scheme && host
? `${scheme}://${host}/${path.join('/')}${proxyUrl.search}${proxyUrl.hash}`
: value;
}
function navigate(url = urlInput) {
const value = url.trim();
if (!value) return;
try {
urlInput = new URL(
/^https?:\/\//i.test(publicUrl(value)) ? publicUrl(value) : `https://${publicUrl(value)}`
).href;
if (mode === 'chrome') chromeEl?.navigate(urlInput);
else frameSrc = browserFrameUrl(sessionId, urlInput);
error = '';
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
} catch {
error = $t('browser.invalidUrl');
}
}
function newTabUrl(value: string) {
try {
const canonical = publicUrl(value.trim());
return canonical
? new URL(/^https?:\/\//i.test(canonical) ? canonical : `https://${canonical}`).href
: '';
} catch {
return '';
}
}
function refresh() {
if (mode === 'chrome') chromeEl?.reload();
else iframeEl?.contentWindow?.location.reload();
}
function frameLoaded() {
try {
const current = new URL(iframeEl?.contentWindow?.location.href || '');
const framePrefix = `/api/browser/frame/${sessionId}`;
const blankPath = `/api/browser/sessions/${sessionId}/blank`;
if (
current.origin !== location.origin ||
current.pathname.startsWith(framePrefix) ||
current.pathname === blankPath
)
return;
const upstream = new URL(`${current.pathname}${current.search}${current.hash}`, urlInput)
.href;
urlInput = upstream;
void updateBrowserSession(sessionId, upstream, title).catch(() => {});
iframeEl?.contentWindow?.location.replace(browserFrameUrl(sessionId, upstream));
} catch {
// Cross-origin frames cannot be inspected; the proxy frame is same-origin.
}
}
function receiveMessage(event: MessageEvent) {
if (event.origin !== location.origin || event.source !== iframeEl?.contentWindow) return;
const data = event.data;
if (data?.type === 'cptr-browser-state') {
urlInput = publicUrl(data.url || urlInput);
title = data.title || '';
updateLabel(title);
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
}
if (data?.type === 'cptr-browser-popup' && data.url) {
if (onOpenBrowser) onOpenBrowser(data.url);
else openBrowserTab(groupId, data.url);
}
}
onMount(() => {
window.addEventListener('message', receiveMessage);
void getBrowserSession(sessionId)
.then(async (session) => {
const url = publicUrl(session.url || initialUrl || '');
urlInput = url;
title = session.title;
updateLabel(title);
mode = session.mode || 'proxy';
if (mode === 'chrome') {
const supported =
'VideoDecoder' in window &&
(await VideoDecoder.isConfigSupported({ codec: 'avc1.42E028' })).supported;
if (!supported) {
mode = 'proxy';
modeError = $t('browser.decoderUnavailable');
void setBrowserMode(sessionId, 'proxy', url).catch(() => {});
}
}
if (url && mode === 'proxy') navigate(url);
else if (url && mode === 'chrome' && !session.url) {
await tick();
chromeEl?.navigate(url);
}
})
.catch(() => {});
});
onDestroy(() => window.removeEventListener('message', receiveMessage));
</script>
<div class="flex h-full min-w-0 flex-col overflow-hidden">
<div
class="flex min-w-0 shrink-0 items-center gap-1 border-b border-gray-200 px-1.5 py-[3px] sm:px-2 dark:border-white/6"
>
<button
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:pointer-events-none disabled:opacity-35 dark:hover:bg-white/6 dark:hover:text-gray-300"
disabled={mode === 'chrome' && !canGoBack}
onclick={() =>
mode === 'chrome' ? chromeEl?.back() : iframeEl?.contentWindow?.history.back()}
use:tooltip={$t('settings.back')}
>
<Icon name="chevron-left" size={12} />
</button>
<button
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:pointer-events-none disabled:opacity-35 dark:hover:bg-white/6 dark:hover:text-gray-300"
disabled={mode === 'chrome' && !canGoForward}
onclick={() =>
mode === 'chrome' ? chromeEl?.forward() : iframeEl?.contentWindow?.history.forward()}
use:tooltip={$t('common.forward')}
>
<Icon name="chevron-right" size={12} />
</button>
<button
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-white/6 dark:hover:text-gray-300"
onclick={refresh}
use:tooltip={$t('files.refresh')}
>
<Icon name="refresh" size={12} />
</button>
<div class="relative min-w-0 flex-1">
<input
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"
spellcheck="false"
/>
<a
class="absolute top-1/2 right-1 z-10 grid h-5 w-5 -translate-y-1/2 place-items-center rounded-full text-xs text-gray-500 hover:bg-gray-200/60 dark:hover:bg-white/8"
href={newTabUrl(urlInput) || undefined}
target="_blank"
rel="noopener noreferrer"
aria-label={$t('port.openInNewTab')}
use:tooltip={$t('port.openInNewTab')}>↗</a
>
</div>
{#if mode === 'chrome' && chromeQuality}
<button
bind:this={qualityMenuAnchor}
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-white/6 dark:hover:text-gray-300"
aria-label={$t('admin.browserQuality')}
use:tooltip={$t('admin.browserQuality')}
onclick={() => (qualityMenuOpen = !qualityMenuOpen)}
>
<Icon name="three-dots" size={12} />
</button>
{/if}
</div>
{#if qualityMenuOpen && qualityMenuAnchor}
<DropdownMenu
items={[]}
anchor={qualityMenuAnchor}
align="end"
onclose={() => (qualityMenuOpen = false)}
>
<div class="p-1 text-xs">
{#each [{ value: 'low' as const, label: $t('admin.browserQualityLow') }, { value: 'balanced' as const, label: $t('admin.browserQualityBalanced') }, { value: 'crisp' as const, label: $t('admin.browserQualityCrisp') }] as item}
<button
class="flex h-6 w-full items-center rounded-lg px-2 text-left hover:bg-gray-100 dark:hover:bg-white/8 {chromeQuality ===
item.value
? 'font-medium text-gray-900 dark:text-white'
: 'text-gray-500 dark:text-gray-400'}"
onclick={() => setChromeQuality(item.value)}
>
<span class="flex-1">{item.label}</span>
{#if chromeQuality === item.value}<Icon name="check" size={12} />{/if}
</button>
{/each}
<div class="my-1 h-px bg-gray-200 dark:bg-white/8"></div>
<div class="px-1 pb-1 pt-0.5 text-[0.625rem] text-gray-400 dark:text-gray-600">
{$t('browser.device')}
</div>
<div class="flex gap-1">
{#each [{ value: 'auto' as DeviceMode, label: $t('browser.deviceAuto'), icon: 'monitor' }, { value: 'desktop' as DeviceMode, label: $t('browser.deviceDesktop'), icon: 'monitor' }, { value: 'mobile' as DeviceMode, label: $t('browser.deviceMobile'), icon: 'phone' }] as item}
<button
class="flex h-7 flex-1 items-center justify-center gap-1 rounded-lg px-1.5 text-[0.625rem] transition-colors {chromeDeviceMode ===
item.value
? 'bg-gray-200/50 font-medium text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
onclick={() => setChromeDeviceMode(item.value)}
>
<Icon name={item.icon} size={12} />
{item.label}
</button>
{/each}
</div>
{#if chromeDeviceMode === 'mobile'}
<label
class="mt-1.5 flex items-center justify-between gap-2 px-1 text-[0.625rem] text-gray-500 dark:text-gray-400"
>
<span>{$t('browser.deviceFixedViewport')}</span>
<input
type="checkbox"
checked={Boolean(chromeMobileViewport)}
onchange={(event) => setChromeMobileViewport(event.currentTarget.checked)}
/>
</label>
{#if chromeMobileViewport}
<div
class="mt-1.5 flex items-center gap-1 text-[0.625rem] text-gray-500 dark:text-gray-400"
>
<input
type="number"
min="1"
value={chromeMobileViewport.width}
aria-label={$t('browser.deviceWidth')}
use:tooltip={$t('browser.deviceWidthHint')}
onchange={(event) =>
setChromeMobileDimension('width', event.currentTarget.valueAsNumber)}
class="h-6 min-w-0 rounded-md border border-gray-200 bg-gray-100 px-1 text-center dark:border-white/8 dark:bg-white/6"
/>
<span>×</span>
<input
type="number"
min="1"
value={chromeMobileViewport.height}
aria-label={$t('browser.deviceHeight')}
use:tooltip={$t('browser.deviceHeightHint')}
onchange={(event) =>
setChromeMobileDimension('height', event.currentTarget.valueAsNumber)}
class="h-6 min-w-0 rounded-md border border-gray-200 bg-gray-100 px-1 text-center dark:border-white/8 dark:bg-white/6"
/>
</div>
{/if}
{/if}
</div>
</DropdownMenu>
{/if}
<div class="preview-content">
{#if error}
<div class="preview-error">
<p class="error-title">{error}</p>
<button class="error-retry" onclick={() => navigate()}>{$t('files.retry')}</button>
</div>
{:else if mode === 'chrome'}
<ChromeBrowser
bind:this={chromeEl}
{sessionId}
{active}
onstate={(state) => {
urlInput = state.url || urlInput;
title = state.title || '';
updateLabel(title);
canGoBack = state.can_go_back;
canGoForward = state.can_go_forward;
}}
onstatus={(status, message, nextMode) => {
chromeStatus = status;
if (message) modeError = message;
else if (status === 'playing') modeError = '';
if (nextMode === 'proxy') {
mode = 'proxy';
chromeQuality = null;
if (urlInput) frameSrc = browserFrameUrl(sessionId, urlInput);
}
}}
onquality={(quality) => (chromeQuality = quality)}
ondevicemode={(nextMode, viewport) => {
chromeDeviceMode = nextMode;
chromeMobileViewport = viewport;
}}
/>
{#if chromeStatus === 'reconnecting'}
<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>
{:else if chromeStatus === 'lost'}
<div
class="absolute inset-0 z-10 flex flex-col items-center justify-center gap-1 bg-white/80 px-4 text-center text-xs text-gray-500 dark:bg-black/80 dark:text-gray-400"
>
<span class="font-medium">{$t('browser.connectionLost')}</span>
{#if modeError}<span class="max-w-md opacity-75">{modeError}</span>{/if}
</div>
{/if}
{:else}
<iframe
bind:this={iframeEl}
src={frameSrc}
title={title || $t('bar.newBrowser')}
class="preview-iframe"
onload={frameLoaded}
onerror={() => {
error = $t('port.cannotConnect');
}}
></iframe>
{/if}
</div>
</div>
<style>
@reference "../../app.css";
.preview-content {
flex: 1;
min-height: 0;
position: relative;
}
.preview-iframe {
width: 100%;
height: 100%;
border: 0;
display: block;
background: white;
}
.preview-error {
height: 100%;
display: grid;
place-content: center;
gap: 0.5rem;
text-align: center;
}
.error-retry {
color: var(--color-brand-600);
}
</style>
@@ -0,0 +1,728 @@
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
interface BrowserState {
url: string;
title: string;
can_go_back: boolean;
can_go_forward: boolean;
}
interface Props {
sessionId: string;
active: boolean;
onstate: (state: BrowserState) => void;
onstatus: (status: string, message?: string, mode?: 'proxy') => void;
onquality: (quality: 'low' | 'balanced' | 'crisp' | null) => void;
ondevicemode: (mode: DeviceMode, viewport?: MobileViewport) => void;
}
type DeviceMode = 'auto' | 'desktop' | 'mobile';
type MobileViewport = { width: number; height: number };
interface DeviceProfile {
userAgent: string;
language: string;
maxTouchPoints: number;
screenWidth: number;
screenHeight: number;
devicePixelRatio: number;
orientation: 'portraitPrimary' | 'landscapePrimary';
mobile: boolean;
userAgentMetadata?: Record<string, unknown>;
}
interface UserAgentData {
brands?: Array<{ brand: string; version: string }>;
mobile?: boolean;
platform?: string;
getHighEntropyValues?: (hints: string[]) => Promise<Record<string, unknown>>;
}
interface EditableRegion {
x: number;
y: number;
width: number;
height: number;
}
let { sessionId, active, onstate, onstatus, onquality, ondevicemode }: Props = $props();
let canvas: HTMLCanvasElement;
let container: HTMLDivElement;
let keyboardAntenna: HTMLTextAreaElement;
let socket: WebSocket | undefined;
let decoder: VideoDecoder | undefined;
let audioDecoder: AudioDecoder | undefined;
let audioContext: AudioContext | undefined;
let observer: ResizeObserver | undefined;
let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
let viewportTimer: ReturnType<typeof setTimeout> | undefined;
let reconnectAttempt = 0;
let disposed = false;
let viewport = { width: 0, height: 0 };
let pendingPointer: Record<string, unknown> | undefined;
let pointerFrame = 0;
let hasFrame = false;
let awaitingFrame = true;
let ready = $state(false);
let managed = $state(false);
let mobile = $state(false);
let quality = $state<'low' | 'balanced' | 'crisp'>('balanced');
let deviceMode = $state<DeviceMode>('auto');
let mobileViewport = $state<MobileViewport | undefined>();
let deviceProfile: DeviceProfile | undefined;
let editableRegions = $state<EditableRegion[]>([]);
let lastViewport = '';
let composition = false;
let suppressText = '';
let keepKeyboardFocus = false;
let audioClockOrigin: number | undefined;
let reapplyViewportAfterConfig = true;
const pressedKeys = new Map<string, Record<string, unknown>>();
const touchPoints = new Map<number, Record<string, unknown>>();
const macClient = /Mac|iPhone|iPad/.test(navigator.userAgent);
const keyboardSentinel = '\u200b';
function send(message: Record<string, unknown>) {
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
}
async function collectDeviceProfile(): Promise<DeviceProfile> {
const uaData = (navigator as Navigator & { userAgentData?: UserAgentData }).userAgentData;
let highEntropy: Record<string, unknown> = {};
if (uaData?.getHighEntropyValues) {
try {
highEntropy = await uaData.getHighEntropyValues([
'architecture',
'bitness',
'fullVersionList',
'model',
'platformVersion'
]);
} catch {
// User agent client hints are optional.
}
}
const maxTouchPoints = Math.min(10, Math.max(0, navigator.maxTouchPoints || 0));
const uaMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent);
const mobileProfile =
uaData?.mobile ?? (uaMobile || (/Mac/.test(navigator.userAgent) && maxTouchPoints > 1));
const orientation = screen.orientation?.type?.startsWith('landscape')
? 'landscapePrimary'
: 'portraitPrimary';
const metadata = uaData
? {
brands: uaData.brands || [],
mobile: Boolean(uaData.mobile),
platform: uaData.platform || '',
...highEntropy
}
: undefined;
return {
userAgent: navigator.userAgent,
language: navigator.language,
maxTouchPoints,
screenWidth: screen.width,
screenHeight: screen.height,
devicePixelRatio: window.devicePixelRatio || 1,
orientation,
mobile: mobileProfile,
userAgentMetadata: metadata
};
}
const deviceProfilePromise = collectDeviceProfile().then((profile) => {
deviceProfile = profile;
mobile = profile.mobile;
return profile;
});
function connect() {
if (disposed) return;
ready = false;
lastViewport = '';
reapplyViewportAfterConfig = true;
awaitingFrame = true;
onstatus(hasFrame ? 'playing' : 'reconnecting');
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
socket = new WebSocket(`${scheme}://${location.host}/api/browser/sessions/${sessionId}/stream`);
socket.binaryType = 'arraybuffer';
socket.onopen = () => {
reconnectAttempt = 0;
send({ type: 'visibility', visible: active });
};
socket.onmessage = receive;
socket.onclose = () => {
if (disposed) return;
onstatus('lost', 'Chrome connection lost');
const delays = [1000, 2000, 5000];
reconnectTimer = setTimeout(connect, delays[Math.min(reconnectAttempt++, delays.length - 1)]);
};
}
function receive(event: MessageEvent) {
if (typeof event.data === 'string') {
const message = JSON.parse(event.data);
if (message.type === 'ready') {
ready = true;
managed = message.managed === true;
if (message.quality?.preset in { low: true, balanced: true, crisp: true })
quality = message.quality.preset;
if (message.device_mode in { auto: true, desktop: true, mobile: true })
deviceMode = message.device_mode;
if (
Number.isFinite(message.mobile_viewport?.width) &&
Number.isFinite(message.mobile_viewport?.height)
)
mobileViewport = message.mobile_viewport;
else mobileViewport = undefined;
onquality(managed ? quality : null);
ondevicemode(deviceMode, mobileViewport);
if (active) focusBrowser();
else resize();
}
if (message.type === 'state') onstate(message);
if (message.type === 'status' && (message.status !== 'playing' || hasFrame))
onstatus(message.status, message.message, message.mode);
if (message.type === 'config') configureDecoder(message);
if (message.type === 'audio_config') configureAudio(message);
if (message.type === 'editable_regions' && Array.isArray(message.regions)) {
editableRegions = message.regions.filter(
(region: unknown): region is EditableRegion =>
typeof region === 'object' &&
region !== null &&
Number.isFinite((region as EditableRegion).x) &&
Number.isFinite((region as EditableRegion).y) &&
Number.isFinite((region as EditableRegion).width) &&
Number.isFinite((region as EditableRegion).height)
);
}
if (
message.type === 'quality' &&
message.preset in { low: true, balanced: true, crisp: true }
) {
quality = message.preset;
onquality(quality);
}
return;
}
if (!(event.data instanceof ArrayBuffer) || event.data.byteLength < 14) return;
const view = new DataView(event.data);
const media = view.getUint8(0);
const timestamp = Number(view.getBigUint64(6));
if (media === 1 && decoder?.state === 'configured') {
try {
decoder.decode(
new EncodedVideoChunk({
type: view.getUint8(1) & 1 ? 'key' : 'delta',
timestamp,
data: new Uint8Array(event.data, 14)
})
);
} catch {
send({ type: 'request_keyframe' });
}
} else if (media === 2 && audioDecoder?.state === 'configured') {
try {
audioDecoder.decode(
new EncodedAudioChunk({ type: 'key', timestamp, data: new Uint8Array(event.data, 14) })
);
} catch {
audioClockOrigin = undefined;
}
}
}
function configureDecoder(config: { codec: string; width: number; height: number }) {
decoder?.close();
decoder = new VideoDecoder({
output(frame) {
if (!canvas) return frame.close();
canvas.width = frame.displayWidth;
canvas.height = frame.displayHeight;
canvas.getContext('2d', { alpha: false })?.drawImage(frame, 0, 0);
frame.close();
if (awaitingFrame) {
awaitingFrame = false;
hasFrame = true;
onstatus('playing');
}
},
error() {
send({ type: 'request_keyframe' });
}
});
decoder.configure({ codec: config.codec, optimizeForLatency: true });
if (managed && reapplyViewportAfterConfig) {
reapplyViewportAfterConfig = false;
void sendViewport(true);
}
}
function configureAudio(config: { codec: string; sampleRate: number; numberOfChannels: number }) {
if (!('AudioDecoder' in window)) return;
audioDecoder?.close();
audioClockOrigin = undefined;
audioDecoder = new AudioDecoder({
output(data) {
playAudio(data);
data.close();
},
error() {
audioClockOrigin = undefined;
}
});
try {
audioDecoder.configure({
codec: config.codec,
sampleRate: config.sampleRate,
numberOfChannels: config.numberOfChannels
});
} catch {
audioDecoder.close();
audioDecoder = undefined;
}
}
function unlockAudio() {
if (!('AudioContext' in window)) return;
audioContext ??= new AudioContext();
if (audioContext.state !== 'running') void audioContext.resume();
}
function playAudio(data: AudioData) {
const context = audioContext;
if (!context || context.state !== 'running') return;
const mediaTime = data.timestamp / 1_000_000;
audioClockOrigin ??= context.currentTime + 0.1 - mediaTime;
let start = audioClockOrigin + mediaTime;
if (start < context.currentTime - 0.05) {
audioClockOrigin = context.currentTime + 0.1 - mediaTime;
start = context.currentTime + 0.1;
}
const buffer = context.createBuffer(
data.numberOfChannels,
data.numberOfFrames,
data.sampleRate
);
for (let channel = 0; channel < data.numberOfChannels; channel += 1) {
data.copyTo(buffer.getChannelData(channel), { planeIndex: channel, format: 'f32-planar' });
}
const source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(Math.max(context.currentTime, start));
}
function resize(debounce = false) {
if (!container || !ready) return;
const rect = container.getBoundingClientRect();
const width = Math.round(rect.width);
const height = Math.round(rect.height);
if (width <= 0 || height <= 0) return;
viewport = {
width,
height
};
if (viewportTimer) clearTimeout(viewportTimer);
if (debounce || (isMobileInput() && document.activeElement === keyboardAntenna)) {
viewportTimer = setTimeout(() => void sendViewport(), 150);
} else {
void sendViewport();
}
}
async function sendViewport(force = false) {
const device = deviceProfile || (await deviceProfilePromise);
const key = JSON.stringify([viewport, quality, device, deviceMode, mobileViewport]);
if (!force && key === lastViewport) return;
lastViewport = key;
send({
type: 'viewport',
...viewport,
quality,
device,
device_mode: deviceMode,
mobile_viewport: mobileViewport ?? null,
force
});
}
function modifiers(event: MouseEvent | KeyboardEvent | WheelEvent) {
return (
(event.altKey ? 1 : 0) |
(event.ctrlKey ? 2 : 0) |
(event.metaKey ? 4 : 0) |
(event.shiftKey ? 8 : 0)
);
}
function coordinates(event: MouseEvent | PointerEvent | WheelEvent) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) / rect.width,
y: (event.clientY - rect.top) / rect.height,
normalized: true
};
}
function button(value: number) {
return value === 0 ? 'left' : value === 1 ? 'middle' : value === 2 ? 'right' : 'none';
}
function focusAntenna() {
if (!isMobileInput()) return;
keepKeyboardFocus = true;
resetKeyboardAntenna();
keyboardAntenna?.focus({ preventScroll: true });
unlockAudio();
}
function resetKeyboardAntenna() {
if (!keyboardAntenna) return;
keyboardAntenna.value = keyboardSentinel;
keyboardAntenna.setSelectionRange(keyboardSentinel.length, keyboardSentinel.length);
}
function canvasFocus() {
if (keepKeyboardFocus) focusAntenna();
}
function isEditableTouch(event: PointerEvent) {
if (!isMobileInput()) return false;
const point = coordinates(event);
return editableRegions.some(
(region) =>
point.x >= region.x &&
point.x <= region.x + region.width &&
point.y >= region.y &&
point.y <= region.y + region.height
);
}
function touch(event: PointerEvent, type: 'start' | 'move' | 'end' | 'cancel') {
if (type === 'start') {
event.preventDefault();
unlockAudio();
keepKeyboardFocus = isEditableTouch(event);
if (keepKeyboardFocus) focusAntenna();
canvas.setPointerCapture(event.pointerId);
touchPoints.set(event.pointerId, {
id: event.pointerId,
...coordinates(event),
radiusX: event.width / 2,
radiusY: event.height / 2,
force: event.pressure
});
} else if (type === 'move') {
if (!touchPoints.has(event.pointerId)) return;
touchPoints.set(event.pointerId, {
id: event.pointerId,
...coordinates(event),
radiusX: event.width / 2,
radiusY: event.height / 2,
force: event.pressure
});
} else {
touchPoints.delete(event.pointerId);
}
send({
type: 'touch',
event: type,
...coordinates(event),
points: [...touchPoints.values()],
button: type === 'move' ? 'none' : 'left',
buttons: event.buttons,
click_count: event.detail || 1,
modifiers: modifiers(event)
});
}
function pointer(event: PointerEvent, type: 'move' | 'down' | 'up' | 'cancel') {
if (isMobileInput()) {
touch(event, type === 'down' ? 'start' : type === 'up' ? 'end' : type);
return;
}
if (type === 'cancel') return;
if (type === 'down') {
unlockAudio();
focusBrowser();
canvas.focus();
canvas.setPointerCapture(event.pointerId);
}
const message = {
type: 'pointer',
event: type,
...coordinates(event),
button: type === 'move' ? 'none' : button(event.button),
buttons: event.buttons,
click_count: event.detail || 1,
modifiers: modifiers(event)
};
if (type !== 'move') return send(message);
pendingPointer = message;
if (!pointerFrame) {
pointerFrame = requestAnimationFrame(() => {
if (pendingPointer) send(pendingPointer);
pendingPointer = undefined;
pointerFrame = 0;
});
}
}
function wheel(event: WheelEvent) {
event.preventDefault();
focusBrowser();
send({
type: 'wheel',
...coordinates(event),
delta_x: event.deltaX,
delta_y: event.deltaY,
modifiers: modifiers(event)
});
}
function key(event: KeyboardEvent, type: 'keyDown' | 'keyUp') {
event.preventDefault();
event.stopPropagation();
const message = {
type: 'key',
event: type,
key: event.key,
code: event.code,
unmodified_text: event.key.length === 1 ? event.key : '',
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,
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);
send(message);
}
function mobileKey(key: string, code: string, virtualKey: number) {
for (const event of ['keyDown', 'keyUp']) {
send({
type: 'key',
event,
key,
code,
text: '',
unmodified_text: '',
modifiers: 0,
location: 0,
is_keypad: false,
windows_virtual_key_code: virtualKey
});
}
}
function beforeInput(event: InputEvent) {
if (!isMobileInput() || composition) return;
const text = event.data || '';
if (suppressText && text === suppressText) {
event.preventDefault();
suppressText = '';
resetKeyboardAntenna();
return;
}
switch (event.inputType) {
case 'insertText':
event.preventDefault();
if (text) send({ type: 'text', text });
break;
case 'insertFromPaste':
event.preventDefault();
if (text) send({ type: 'paste', text });
break;
case 'insertLineBreak':
case 'insertParagraph':
event.preventDefault();
mobileKey('Enter', 'Enter', 13);
break;
case 'deleteContentBackward':
event.preventDefault();
mobileKey('Backspace', 'Backspace', 8);
break;
case 'deleteContentForward':
event.preventDefault();
mobileKey('Delete', 'Delete', 46);
break;
default:
return;
}
resetKeyboardAntenna();
}
function releaseKeys() {
for (const message of pressedKeys.values()) send({ ...message, event: 'keyUp', text: '' });
pressedKeys.clear();
}
export function navigate(url: string) {
focusBrowser();
send({ type: 'navigate', url });
}
export function back() {
focusBrowser();
send({ type: 'back' });
}
export function forward() {
focusBrowser();
send({ type: 'forward' });
}
export function reload() {
focusBrowser();
send({ type: 'reload' });
}
export function setQuality(nextQuality: 'low' | 'balanced' | 'crisp') {
quality = nextQuality;
lastViewport = '';
onquality(quality);
resize();
}
export function setDeviceMode(nextMode: DeviceMode) {
deviceMode = nextMode;
lastViewport = '';
ondevicemode(deviceMode, mobileViewport);
resize();
}
export function setMobileViewport(nextViewport?: MobileViewport) {
if (nextViewport && (nextViewport.width <= 0 || nextViewport.height <= 0)) return;
mobileViewport = nextViewport;
lastViewport = '';
ondevicemode(deviceMode, mobileViewport);
resize();
}
function isMobileInput() {
return managed && (deviceMode === 'mobile' || (deviceMode === 'auto' && mobile));
}
function focusBrowser() {
if (!ready) return;
send({ type: 'focus' });
resize();
}
function visualViewportResize() {
resize(true);
}
$effect(() => {
if (socket?.readyState === WebSocket.OPEN && ready) {
send({ type: 'visibility', visible: active });
if (active) focusBrowser();
}
});
onMount(() => {
observer = new ResizeObserver(() => resize());
observer.observe(container);
window.visualViewport?.addEventListener('resize', visualViewportResize);
resetKeyboardAntenna();
connect();
});
onDestroy(() => {
disposed = true;
releaseKeys();
observer?.disconnect();
window.visualViewport?.removeEventListener('resize', visualViewportResize);
if (reconnectTimer) clearTimeout(reconnectTimer);
if (viewportTimer) clearTimeout(viewportTimer);
if (pointerFrame) cancelAnimationFrame(pointerFrame);
socket?.close();
decoder?.close();
audioDecoder?.close();
if (audioContext) void audioContext.close();
});
</script>
<div class="chrome-container" bind:this={container}>
<textarea
bind:this={keyboardAntenna}
class="keyboard-antenna"
aria-label="Remote browser keyboard"
onbeforeinput={beforeInput}
oncompositionstart={() => (composition = true)}
oncompositionupdate={() => {}}
oncompositionend={(event) => {
composition = false;
const text = event.data || '';
if (isMobileInput() && text) {
suppressText = text;
send({ type: 'text', text });
queueMicrotask(() => {
if (suppressText === text) suppressText = '';
});
}
resetKeyboardAntenna();
}}
oninput={() => {
if (!composition) resetKeyboardAntenna();
}}
></textarea>
<canvas
bind:this={canvas}
tabindex={isMobileInput() ? -1 : 0}
onfocus={canvasFocus}
onpointermove={(event) => pointer(event, 'move')}
onpointerdown={(event) => pointer(event, 'down')}
onpointerup={(event) => pointer(event, 'up')}
onpointercancel={(event) => pointer(event, 'cancel')}
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()}
></canvas>
</div>
<style>
.chrome-container,
canvas {
width: 100%;
height: 100%;
display: block;
background: white;
}
.chrome-container {
position: relative;
display: grid;
place-items: center;
}
canvas {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
margin: auto;
outline: none;
object-fit: contain;
touch-action: none;
}
.keyboard-antenna {
position: absolute;
top: 0;
left: 0;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
</style>
@@ -15,7 +15,10 @@
deleteFiles,
moveFile,
uploadFiles as apiUpload,
createEntry
createEntry,
getFileMatches,
type FileMatch,
type ContentMatch
} from '$lib/apis/files';
import { fileIconName } from '$lib/utils/fileIcon';
import Icon from './Icon.svelte';
@@ -44,6 +47,16 @@
let dragExpandTimer: ReturnType<typeof setTimeout> | null = null;
let error = $state<string | null>(null);
let searchQuery = $state('');
let matchResults = $state<FileMatch[] | null>(null);
let matchLoading = $state(false);
let matchLoadingMore = $state(false);
let matchError = $state<string | null>(null);
let matchLoadMoreError = $state(false);
let nextMatchOffset = $state<number | null>(null);
let matchTimer: ReturnType<typeof setTimeout> | null = null;
let matchController: AbortController | null = null;
let matchRequestId = 0;
let searchTargetRequestId = 0;
let dragOverDir = $state<string | null>(null);
let draggedItem = $state<string | null>(null);
let showNewInput = $state<'file' | 'folder' | null>(null);
@@ -80,6 +93,10 @@
let cwd = $derived($activeWorkspace?.fileBrowserCwd ?? $activeWorkspace?.path ?? '/');
let workspacePath = $derived($activeWorkspace?.path ?? '/');
let searchText = $derived(searchQuery.trim());
let isSearching = $derived(Boolean(searchText));
let filenameMatches = $derived(matchResults?.filter((match) => match.name_match) ?? []);
let contentOnlyMatches = $derived(matchResults?.filter((match) => !match.name_match) ?? []);
let gitStatus = $derived(gitStatusStore.status);
let gitRoot = $derived(workspacePath.replace(/\/$/, ''));
@@ -283,6 +300,7 @@
const isNavigation = _prevCwd !== '';
_prevCwd = cwd;
if (isNavigation) {
searchQuery = '';
// Navigated to a new directory: reset tree state
expandedDirs = new Set();
dirContents = new Map();
@@ -300,6 +318,97 @@
}
});
$effect(() => {
const query = searchText;
const hidden = showHidden;
if (matchTimer) clearTimeout(matchTimer);
matchTimer = null;
matchController?.abort();
matchController = null;
matchError = null;
const requestId = ++matchRequestId;
if (!query) {
matchResults = null;
matchLoading = false;
matchLoadingMore = false;
matchLoadMoreError = false;
nextMatchOffset = null;
return;
}
showNewInput = null;
clearSelection();
contextMenu = null;
directoryMenu = null;
addMenuOpen = false;
sortMenuOpen = false;
matchLoading = true;
matchLoadingMore = false;
matchLoadMoreError = false;
nextMatchOffset = null;
matchTimer = setTimeout(async () => {
const controller = new AbortController();
matchController = controller;
try {
const data = await getFileMatches(query, cwd, hidden, 0, controller.signal);
if (requestId === matchRequestId) {
matchResults = data.results;
nextMatchOffset = data.next_offset;
}
} catch (e: any) {
if (e.name !== 'AbortError' && requestId === matchRequestId) {
matchError = e.message || $t('files.failedToSearch');
matchResults = [];
}
} finally {
if (requestId === matchRequestId) matchLoading = false;
}
}, 200);
});
async function loadMoreMatches() {
const offset = nextMatchOffset;
if (offset === null || !isSearching || matchLoading || matchLoadingMore || matchLoadMoreError)
return;
const query = searchText;
const hidden = showHidden;
const requestId = matchRequestId;
matchLoadingMore = true;
const controller = new AbortController();
matchController = controller;
try {
const data = await getFileMatches(query, cwd, hidden, offset, controller.signal);
if (requestId === matchRequestId) {
matchResults = [...(matchResults ?? []), ...data.results];
nextMatchOffset = data.next_offset;
}
} catch (e: any) {
if (e.name !== 'AbortError' && requestId === matchRequestId) {
matchLoadMoreError = true;
}
} finally {
if (requestId === matchRequestId) matchLoadingMore = false;
}
}
function retryMoreMatches() {
matchLoadMoreError = false;
void loadMoreMatches();
}
function loadMoreOnVisible(node: HTMLElement) {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) void loadMoreMatches();
},
{ rootMargin: '160px' }
);
observer.observe(node);
return { destroy: () => observer.disconnect() };
}
// Keep the websocket watch path in sync (separate effect so it doesn't
// re-trigger directory fetches via fsTick feedback loops)
$effect(() => {
@@ -464,9 +573,34 @@
}
function navigateTo(path: string) {
searchQuery = '';
setFileBrowserCwd(path);
}
function parentPath(relativePath: string): string {
const slash = relativePath.lastIndexOf('/');
return slash === -1 ? '' : relativePath.slice(0, slash);
}
function openFileMatch(match: FileMatch) {
if (match.type === 'directory') {
navigateTo(match.path);
return;
}
openFileTab(match.path);
}
function openContentMatch(match: FileMatch, contentMatch: ContentMatch) {
openFileTab(match.path, undefined, {
searchTarget: {
line: contentMatch.line,
column: contentMatch.column,
length: searchText.length,
requestId: ++searchTargetRequestId
}
});
}
// fileIconName imported from $lib/utils/fileIcon
function formatSize(bytes: number | null): string {
@@ -955,9 +1089,9 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex flex-col h-full overflow-hidden relative"
ondragover={onDropzoneOver}
ondragleave={onDropzoneLeave}
ondrop={onDropzoneDrop}
ondragover={(e) => !isSearching && onDropzoneOver(e)}
ondragleave={(e) => !isSearching && onDropzoneLeave(e)}
ondrop={(e) => !isSearching && onDropzoneDrop(e)}
>
<!-- Header: breadcrumb + actions -->
<div
@@ -1002,29 +1136,31 @@
<Icon name="refresh" size={11} />
</button>
<!-- Sort dropdown -->
<button
bind:this={sortBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
sortMenuOpen = !sortMenuOpen;
}}
use:tooltip={$t('files.sort')}
>
<Icon name="sort" size={11} />
</button>
{#if !isSearching}
<!-- Sort dropdown -->
<button
bind:this={sortBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
sortMenuOpen = !sortMenuOpen;
}}
use:tooltip={$t('files.sort')}
>
<Icon name="sort" size={11} />
</button>
<!-- Three-dot menu -->
<button
bind:this={addBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
toggleAddMenu();
}}
use:tooltip={$t('files.actions')}
>
<Icon name="three-dots" size={11} />
</button>
<!-- Three-dot menu -->
<button
bind:this={addBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
toggleAddMenu();
}}
use:tooltip={$t('files.actions')}
>
<Icon name="three-dots" size={11} />
</button>
{/if}
</div>
<!-- Ports -->
@@ -1051,7 +1187,7 @@
<input
type="text"
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white placeholder:text-gray-400"
placeholder={$t('files.filter')}
placeholder={$t('files.searchFilesAndContents')}
bind:value={searchQuery}
/>
{#if searchQuery}
@@ -1064,9 +1200,12 @@
<!-- Sort bar replaced with dropdown in toolbar -->
<!-- File list -->
<div class="flex-1 overflow-y-auto p-1" oncontextmenu={onDirectoryContextMenu}>
<div
class="flex-1 overflow-y-auto p-1"
oncontextmenu={(e) => !isSearching && onDirectoryContextMenu(e)}
>
<!-- New item input -->
{#if showNewInput}
{#if showNewInput && !isSearching}
<div class="flex items-center gap-2 h-7 px-2">
<Icon
name={showNewInput === 'folder' ? 'folder' : 'empty-page'}
@@ -1113,6 +1252,97 @@
onclick={() => fetchDirectory(cwd)}>{$t('files.retry')}</button
>
</div>
{:else if isSearching}
{#if matchLoading}
<div class="flex items-center justify-center py-12">
<Spinner size={16} />
</div>
{:else if matchError}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-red-400">{matchError}</p>
</div>
{:else if !matchResults?.length}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('files.noMatches')}</p>
</div>
{:else}
{#snippet resultRows(matches: FileMatch[])}
{#each matches as match (match.path)}
<button
class="flex items-center gap-2 w-full h-7 px-2 rounded-lg text-left hover:bg-gray-50 dark:hover:bg-white/4 transition-colors duration-75"
onclick={() => openFileMatch(match)}
>
<Icon
name={fileIconName(match.name, match.type)}
size={14}
strokeWidth={1.4}
class="shrink-0 {match.type === 'directory'
? 'text-gray-500 dark:text-gray-400'
: 'text-gray-400 dark:text-gray-500'}"
/>
<span class="min-w-0 flex-1 truncate text-xs text-gray-800 dark:text-gray-200">
{match.name}
{#if parentPath(match.relative_path)}
<span class="ml-1.5 text-[0.6875rem] text-gray-400 dark:text-gray-600"
>{parentPath(match.relative_path)}</span
>
{/if}
</span>
</button>
{#if match.content_matches.length > 0}
{@const preview = match.content_matches[0]}
<button
class="flex items-center gap-2 w-full h-6 pl-8 pr-2 rounded-lg text-left hover:bg-gray-50 dark:hover:bg-white/4 transition-colors duration-75"
onclick={() => openContentMatch(match, preview)}
>
<span
class="w-6 shrink-0 text-right text-[0.625rem] font-mono text-gray-400 dark:text-gray-600"
>{preview.line}</span
>
<span
class="min-w-0 flex-1 truncate text-[0.6875rem] font-mono text-gray-500 dark:text-gray-500"
>{preview.text}</span
>
{#if match.content_matches.length > 1}
<span class="shrink-0 text-[0.625rem] text-gray-400 dark:text-gray-600"
>+{match.content_matches.length - 1}</span
>
{/if}
</button>
{/if}
{/each}
{/snippet}
{#if filenameMatches.length > 0}
<div
class="px-2 pt-1 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600"
>
{$t('files.filenameMatches')}
</div>
{@render resultRows(filenameMatches)}
{/if}
{#if contentOnlyMatches.length > 0}
<div
class="px-2 pt-2 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600"
>
{$t('files.contentMatches')}
</div>
{@render resultRows(contentOnlyMatches)}
{/if}
{#if nextMatchOffset !== null}
<div use:loadMoreOnVisible class="flex h-8 items-center justify-center">
{#if matchLoadingMore}
<Spinner size={12} />
{:else if matchLoadMoreError}
<button
class="text-[0.6875rem] text-gray-400 hover:text-gray-600 dark:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
onclick={retryMoreMatches}>{$t('files.retry')}</button
>
{/if}
</div>
{/if}
{/if}
{:else if visibleEntries.length === 0 && !showNewInput}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-gray-400 dark:text-gray-600">
@@ -1157,7 +1387,7 @@
: null}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<button
class="group flex items-center gap-1 w-full h-7 rounded-lg text-left transition-colors duration-75
class="group flex items-center gap-1 w-full h-7 pr-2 rounded-lg text-left transition-colors duration-75
{isSelected
? 'bg-blue-50 dark:bg-blue-500/10'
: isDragTarget
@@ -1165,7 +1395,6 @@
? 'bg-blue-100 dark:bg-blue-500/20'
: 'bg-blue-50/60 dark:bg-blue-500/8'
: 'hover:bg-gray-100 dark:hover:bg-white/4'}"
style="padding-left: {8 + entry.depth * 16}px; padding-right: 0.5rem;"
onclick={(e) => handleClick(e, entry, i)}
oncontextmenu={(e) => onContextMenu(e, entry)}
draggable="true"
@@ -1178,7 +1407,7 @@
{#if entry.type === 'directory'}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 cursor-pointer"
class="flex h-full shrink-0 cursor-pointer items-center text-gray-400 hover:text-gray-600 dark:text-gray-600 dark:hover:text-gray-400"
role="button"
tabindex="-1"
onclick={(e) => {
@@ -1192,13 +1421,25 @@
}
}}
>
<Icon
name={expandedDirs.has(entry.path) ? 'chevron-down' : 'chevron-right'}
size={10}
/>
<span class="w-2 shrink-0"></span>
{#each Array(entry.depth) as _}
<span class="w-4 shrink-0"></span>
{/each}
<span class="flex w-4 shrink-0 items-center justify-center">
<Icon
name={expandedDirs.has(entry.path) ? 'chevron-down' : 'chevron-right'}
size={10}
/>
</span>
</span>
{:else}
<span class="w-4 shrink-0"></span>
<span class="flex shrink-0">
<span class="w-2 shrink-0"></span>
{#each Array(entry.depth) as _}
<span class="w-4 shrink-0"></span>
{/each}
<span class="w-4 shrink-0"></span>
</span>
{/if}
<span
class="flex items-center justify-center w-4 shrink-0 {entry.type === 'directory'
@@ -1268,7 +1509,7 @@
</div>
<!-- Upload dropzone overlay -->
{#if dropzoneActive}
{#if dropzoneActive && !isSearching}
<div
class="absolute inset-0 bg-blue-500/10 border-2 border-dashed border-blue-400 dark:border-blue-500 rounded-lg flex items-center justify-center z-10 pointer-events-none"
>
@@ -1277,7 +1518,7 @@
{/if}
<!-- Multi-select action bar -->
{#if selectedPaths.size > 0}
{#if selectedPaths.size > 0 && !isSearching}
<div
class="flex items-center justify-between h-8 px-2 border-t border-gray-200 dark:border-white/6 shrink-0 bg-blue-50 dark:bg-blue-500/5"
>
@@ -1,6 +1,13 @@
<script lang="ts">
import { onMount, onDestroy, tick } from 'svelte';
import { clearTabEdit, markTabUnsaved, updateTabFilePath, activeWorkspace } from '$lib/stores';
import {
clearFileSearchTarget,
clearTabEdit,
markTabUnsaved,
updateTabFilePath,
activeWorkspace,
type FileSearchTarget
} from '$lib/stores';
import { get } from 'svelte/store';
import { t } from '$lib/i18n';
import { tooltip } from '$lib/tooltip';
@@ -80,9 +87,10 @@
filePath: string;
tabId: string;
edit?: boolean;
searchTarget?: FileSearchTarget;
}
let { filePath, tabId, edit = false }: Props = $props();
let { filePath, tabId, edit = false, searchTarget }: Props = $props();
interface FileData {
path: string;
@@ -867,6 +875,33 @@
}
let themeObserver: MutationObserver | null = null;
let appliedSearchTarget = 0;
function applySearchTarget() {
if (!view || !searchTarget || appliedSearchTarget === searchTarget.requestId) return;
const target = searchTarget;
const line = view.state.doc.line(Math.min(Math.max(target.line, 1), view.state.doc.lines));
const from = Math.min(line.from + Math.max(target.column - 1, 0), line.to);
const to = Math.min(from + Math.max(target.length, 0), line.to);
view.dispatch({
selection: { anchor: from, head: to },
effects: EditorView.scrollIntoView(from, { y: 'center' })
});
appliedSearchTarget = target.requestId;
clearFileSearchTarget(tabId, target.requestId);
}
$effect(() => {
if (searchTarget && fileData && !fileData.binary) {
if (isMarkdown && markdownMode !== 'raw') switchMarkdownMode('raw');
else if (isJson && jsonViewMode !== 'source') toggleJsonView();
else if ((isHtml || isSvg) && previewMode) togglePreview();
else if (isCsv && !view) {
requestAnimationFrame(() => initEditor(fileData!.content!, fileData!.language));
}
}
applySearchTarget();
});
function initEditor(content: string, language: string | null) {
if (!editorEl) return;
@@ -944,6 +979,7 @@
const state = EditorState.create({ doc: content, extensions });
view = new EditorView({ state, parent: editorEl });
applyGitLineChanges();
applySearchTarget();
// Watch for theme changes and rebuild editor
themeObserver = new MutationObserver(() => {
@@ -9,6 +9,7 @@
reorderTabs,
openUntitledFileTab,
openTerminalTab,
openBrowserTab,
openInSplit,
closeGroup,
moveTabToGroup,
@@ -32,13 +33,44 @@
import { TAB_DRAG_MIME } from '$lib/constants';
interface Props {
group: EditorGroup;
canClose?: boolean;
isPrimary?: boolean;
onTabDragOver?: () => void;
}
group: EditorGroup;
home?: boolean;
canClose?: boolean;
isPrimary?: boolean;
onTabDragOver?: () => void;
onHomeSelect?: (tabId: string) => void;
onHomeClose?: (tabId: string) => void;
onHomeReorder?: (oldIndex: number, newIndex: number) => void;
onHomeMove?: (tabId: string, fromGroupId: string) => void;
onHomeNewChat?: () => void;
onHomeNewTerminal?: () => void;
onHomeNewBrowser?: () => void;
onHomeSplit?: (direction: 'horizontal' | 'vertical') => void;
onHomeCloseGroup?: () => void;
homeSplitDirection?: 'horizontal' | 'vertical';
homeSplitActive?: boolean;
homeActive?: boolean;
}
let { group, canClose = false, isPrimary = false, onTabDragOver }: Props = $props();
let {
group,
home = false,
canClose = false,
isPrimary = false,
onTabDragOver,
onHomeSelect,
onHomeClose,
onHomeReorder,
onHomeMove,
onHomeNewChat,
onHomeNewTerminal,
onHomeNewBrowser,
onHomeSplit,
onHomeCloseGroup,
homeSplitDirection = 'horizontal',
homeSplitActive = false,
homeActive = true
}: Props = $props();
let tabsEl: HTMLDivElement | undefined = $state();
let sortable: Sortable | null = null;
@@ -63,10 +95,12 @@
const displayTabs = $derived((group?.tabs ?? []).filter((t) => t.type !== 'git'));
const isActiveGroup = $derived($activeWorkspace?.activeGroupId === group?.id);
const isActiveGroup = $derived(home ? homeActive : $activeWorkspace?.activeGroupId === group?.id);
function tabIconName(tab: Tab): string {
switch (tab.type) {
case 'home':
return 'spark';
case 'files':
return 'folder';
case 'terminal':
@@ -79,22 +113,27 @@
return 'chat-bubble';
case 'preview':
return 'monitor';
case 'browser':
return 'browser';
default:
return 'page';
}
}
function handleTabClick(tab: Tab) {
if (home) return onHomeSelect?.(tab.id);
setActiveTab(tab.id, group.id);
}
function handleClose(e: Event, tabId: string) {
e.stopPropagation();
if (home) return onHomeClose?.(tabId);
closeTab(tabId, group.id);
}
function handleCloseGroup(e: Event) {
e.stopPropagation();
if (home) return onHomeCloseGroup?.();
closeGroup(group.id);
}
@@ -105,6 +144,7 @@
}
function handlePaneClick() {
if (home) return;
if (!isActiveGroup) {
setActiveGroup(group.id);
}
@@ -161,51 +201,85 @@
e.preventDefault();
e.stopPropagation();
if (payload.groupId === group.id) return; // same group, ignore
moveTabToGroup(payload.tabId, payload.groupId, group.id);
if (home) onHomeMove?.(payload.tabId, payload.groupId);
else moveTabToGroup(payload.tabId, payload.groupId, group.id);
}
const plusMenuItems = $derived([
{
label: $t('bar.newFile'),
icon: 'page',
shortcut: formatChord($keybindings.newFile),
onclick: () => {
openUntitledFileTab(group.id);
}
},
...($chatEnabled
const plusMenuItems = $derived(
home
? [
...($chatEnabled
? [
{
label: $t('bar.newChat'),
icon: 'chat-bubble',
shortcut: formatChord($keybindings.newChat),
onclick: () => onHomeNewChat?.()
}
]
: []),
{
label: $t('bar.newChat'),
icon: 'chat-bubble',
shortcut: formatChord($keybindings.newChat),
onclick: () => {
openChatTab(undefined, group.id);
}
label: $t('bar.newTerminal'),
icon: 'terminal',
shortcut: formatChord($keybindings.newTerminal),
onclick: () => onHomeNewTerminal?.()
},
{
label: $t('bar.newBrowser'),
icon: 'browser',
shortcut: formatChord($keybindings.newBrowser),
onclick: () => onHomeNewBrowser?.()
}
]
: []),
{
label: $t('bar.newTerminal'),
icon: 'terminal',
shortcut: formatChord($keybindings.newTerminal),
onclick: () => {
openTerminalTab(group.id);
}
},
...($voiceMemosEnabled
? [
: [
{
label: $t('bar.voiceMemo'),
icon: 'microphone',
shortcut: formatChord($keybindings.voiceMemo),
label: $t('bar.newFile'),
icon: 'page',
shortcut: formatChord($keybindings.newFile),
onclick: () => {
showVoiceMemo.set(true);
openUntitledFileTab(group.id);
}
}
},
...($chatEnabled
? [
{
label: $t('bar.newChat'),
icon: 'chat-bubble',
shortcut: formatChord($keybindings.newChat),
onclick: () => {
openChatTab(undefined, group.id);
}
}
]
: []),
{
label: $t('bar.newTerminal'),
icon: 'terminal',
shortcut: formatChord($keybindings.newTerminal),
onclick: () => {
openTerminalTab(group.id);
}
},
{
label: $t('bar.newBrowser'),
icon: 'browser',
shortcut: formatChord($keybindings.newBrowser),
onclick: () => openBrowserTab(group.id)
},
...($voiceMemosEnabled
? [
{
label: $t('bar.voiceMemo'),
icon: 'microphone',
shortcut: formatChord($keybindings.voiceMemo),
onclick: () => {
showVoiceMemo.set(true);
}
}
]
: [])
]
: [])
]);
);
const contextMenuItems = $derived.by(() => {
if (!contextMenu) return [];
@@ -230,7 +304,7 @@
items.push({
label: $t('bar.closeTab'),
icon: 'xmark',
onclick: () => closeTab(tab.id, group.id)
onclick: () => (home ? onHomeClose?.(tab.id) : closeTab(tab.id, group.id))
});
}
@@ -238,15 +312,20 @@
});
const splitMenuItems = $derived.by(() => {
const direction = $activeWorkspace?.splitDirection ?? 'horizontal';
const direction = home
? homeSplitDirection
: ($activeWorkspace?.splitDirection ?? 'horizontal');
return [
{
label: $t('bar.splitRight'),
icon: 'split-horizontal',
active: direction === 'horizontal',
onclick: () => {
setSplitDirection('horizontal');
splitCurrentTab('horizontal');
if (home) onHomeSplit?.('horizontal');
else {
setSplitDirection('horizontal');
splitCurrentTab('horizontal');
}
}
},
{
@@ -254,8 +333,11 @@
icon: 'split-vertical',
active: direction === 'vertical',
onclick: () => {
setSplitDirection('vertical');
splitCurrentTab('vertical');
if (home) onHomeSplit?.('vertical');
else {
setSplitDirection('vertical');
splitCurrentTab('vertical');
}
}
}
];
@@ -269,7 +351,7 @@
if (tabsEl) {
sortable = Sortable.create(tabsEl, {
animation: 150,
ghostClass: 'opacity-30',
ghostClass: 'tab-reorder-preview',
dragClass: 'cursor-grabbing',
direction: 'horizontal',
delay: 200,
@@ -283,7 +365,8 @@
},
onEnd: (evt) => {
if (evt.oldIndex != null && evt.newIndex != null && evt.oldIndex !== evt.newIndex) {
reorderTabs(evt.oldIndex, evt.newIndex, group.id);
if (home) onHomeReorder?.(evt.oldIndex, evt.newIndex);
else reorderTabs(evt.oldIndex, evt.newIndex, group.id);
}
}
});
@@ -300,9 +383,7 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex items-center h-9 px-1.5 gap-1 shrink-0 select-none border-b transition-colors duration-100
{dropHighlight
? 'border-blue-400 bg-blue-50 dark:bg-blue-500/5 dark:border-blue-500/40'
: 'border-gray-200 dark:border-white/6'}
{dropHighlight ? 'tab-reorder-drop-preview' : 'border-gray-200 dark:border-white/6'}
{isActiveGroup ? '' : 'opacity-50'}"
onclick={handlePaneClick}
ondragover={handleBarDragOver}
@@ -332,6 +413,7 @@
? 'bg-gray-200/50 text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
data-tab-id={tab.id}
onpointerdown={() => handleTabClick(tab)}
onclick={() => handleTabClick(tab)}
oncontextmenu={(e) => handleContextMenu(e, tab)}
>
@@ -348,6 +430,7 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="flex items-center justify-center w-4 h-4 rounded text-gray-400 hover:bg-gray-200 hover:text-gray-700 dark:hover:bg-white/10 dark:hover:text-white"
onpointerdown={(e) => e.stopPropagation()}
onclick={(e) => handleClose(e, tab.id)}
onkeydown={(e) => {
if (e.key === 'Enter') handleClose(e, tab.id);
@@ -382,7 +465,7 @@
<button
bind:this={splitBtnEl}
class="flex items-center justify-center w-7 h-7 rounded-lg transition-colors duration-100 shrink-0
{$splitActive
{(home ? homeSplitActive : $splitActive)
? 'bg-gray-200/50 text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}"
onclick={() => (showSplitMenu = !showSplitMenu)}
@@ -390,7 +473,7 @@
use:tooltip={$t('a11y.splitEditor')}
>
<Icon
name={$activeWorkspace?.splitDirection === 'vertical'
name={(home ? homeSplitDirection : $activeWorkspace?.splitDirection) === 'vertical'
? 'split-vertical'
: 'split-horizontal'}
size={14}
@@ -437,7 +520,7 @@
/>
{/if}
{#if $showVoiceMemo}
{#if !home && $showVoiceMemo}
<VoiceMemoModal
workspace={$activeWorkspace?.path ?? ''}
directory={$activeWorkspace?.fileBrowserCwd ?? $activeWorkspace?.path ?? ''}
@@ -455,4 +538,16 @@
.group-tabs-row::-webkit-scrollbar {
display: none;
}
.tab-reorder-preview {
background: color-mix(in oklab, var(--app-fg) 6%, transparent) !important;
box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--app-fg) 16%, transparent);
opacity: 1 !important;
}
.tab-reorder-drop-preview {
background: color-mix(in oklab, var(--app-fg) 6%, transparent);
box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--app-fg) 16%, transparent);
border-color: transparent;
}
</style>
@@ -1,383 +0,0 @@
<script lang="ts">
import { tooltip } from '$lib/tooltip';
import Icon from './Icon.svelte';
import { t } from '$lib/i18n';
interface Props {
port: number;
}
let { port }: Props = $props();
let path = $state('');
let urlInput = $state(`localhost:${port}`);
let iframeEl: HTMLIFrameElement | undefined = $state();
let iframeKey = $state(0);
let isLoading = $state(true);
let loadError = $state(false);
// ── Navigation history ──────────────────────────────────────────
let history = $state<string[]>(['']);
let historyIndex = $state(0);
let canGoBack = $derived(historyIndex > 0);
let canGoForward = $derived(historyIndex < history.length - 1);
let proxyPathPrefix = $derived(`/api/proxy/${port}/`);
let proxyUrl = $derived(`/api/proxy/${port}/${path}`);
function makeDisplayUrl(p: string): string {
return `localhost:${port}${p ? '/' + p : ''}`;
}
function syncUrlBar() {
urlInput = makeDisplayUrl(path);
}
function pushHistory(newPath: string) {
if (historyIndex < history.length - 1) {
history = history.slice(0, historyIndex + 1);
}
history = [...history, newPath];
historyIndex = history.length - 1;
}
function goBack() {
if (!canGoBack) return;
historyIndex -= 1;
path = history[historyIndex];
syncUrlBar();
iframeKey += 1;
}
function goForward() {
if (!canGoForward) return;
historyIndex += 1;
path = history[historyIndex];
syncUrlBar();
iframeKey += 1;
}
function refresh() {
isLoading = true;
loadError = false;
iframeKey += 1;
}
function navigateUrl() {
const stripped = urlInput.trim();
const localhostPrefix = `localhost:${port}`;
let newPath = '';
if (stripped.startsWith(localhostPrefix)) {
newPath = stripped.slice(localhostPrefix.length).replace(/^\//, '');
} else if (stripped.startsWith('/') || !stripped.includes(':')) {
newPath = stripped.replace(/^\//, '');
}
if (newPath !== path) {
path = newPath;
pushHistory(path);
}
syncUrlBar();
iframeKey += 1;
}
function onIframeLoad() {
isLoading = false;
if (!iframeEl) return;
try {
const loc = iframeEl.contentWindow?.location;
if (!loc) return;
const iframePath = loc.pathname ?? '';
const iframeSearch = loc.search ?? '';
const iframeHash = loc.hash ?? '';
if (iframePath.startsWith(proxyPathPrefix)) {
const relativePath = iframePath.slice(proxyPathPrefix.length) + iframeSearch + iframeHash;
if (relativePath !== path) {
path = relativePath;
pushHistory(path);
syncUrlBar();
}
}
} catch {
// Cross-origin, can't access
}
}
function openExternal() {
window.open(`http://localhost:${port}/${path}`, '_blank');
}
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Enter') {
e.preventDefault();
navigateUrl();
}
}
</script>
<div class="preview-container">
<!-- Toolbar -->
<div class="preview-toolbar">
<!-- Back -->
<button
class="preview-btn {canGoBack ? '' : 'disabled'}"
onclick={goBack}
disabled={!canGoBack}
use:tooltip={$t('settings.back')}
>
<Icon name="chevron-left" size={12} />
</button>
<!-- Forward -->
<button
class="preview-btn {canGoForward ? '' : 'disabled'}"
onclick={goForward}
disabled={!canGoForward}
use:tooltip={$t('common.forward')}
>
<Icon name="chevron-right" size={12} />
</button>
<!-- Refresh -->
<button class="preview-btn" onclick={refresh} use:tooltip={$t('files.refresh')}>
<Icon name="refresh" size={12} />
</button>
<!-- URL bar -->
<div class="url-bar">
<input
type="text"
class="url-input"
bind:value={urlInput}
onkeydown={onKeydown}
placeholder="localhost:{port}"
spellcheck="false"
/>
</div>
<!-- Open external -->
<button class="preview-btn" onclick={openExternal} use:tooltip={$t('port.openInNewTab')}>
<Icon name="external-link" size={12} />
</button>
</div>
<!-- Loading bar -->
{#if isLoading}
<div class="loading-track">
<div class="loading-bar"></div>
</div>
{/if}
<!-- Content -->
<div class="preview-content">
{#if loadError}
<div class="preview-error">
<p class="error-title">{$t('port.cannotConnect')}</p>
<p class="error-sub">{$t('port.notResponding', { port })}</p>
<button class="error-retry" onclick={refresh}>{$t('files.retry')}</button>
</div>
{:else}
{#key iframeKey}
<iframe
bind:this={iframeEl}
src={proxyUrl}
title={$t('port.previewTitle', { port })}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
class="preview-iframe"
onload={onIframeLoad}
onerror={() => {
loadError = true;
isLoading = false;
}}
></iframe>
{/key}
{/if}
</div>
</div>
<style>
@reference "../../app.css";
.preview-container {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.preview-toolbar {
display: flex;
align-items: center;
gap: 0.25rem;
height: 2rem;
padding: 0 0.375rem;
border-bottom: 1px solid var(--color-gray-200);
flex-shrink: 0;
}
:global(.dark) .preview-toolbar {
border-bottom-color: rgba(255, 255, 255, 0.06);
}
.preview-btn {
display: flex;
align-items: center;
justify-content: center;
width: 1.375rem;
height: 1.375rem;
border-radius: 0.25rem;
color: var(--color-gray-500);
transition: all 0.1s;
flex-shrink: 0;
}
.preview-btn:hover:not(.disabled) {
background: var(--color-gray-100);
color: var(--color-gray-700);
}
:global(.dark) .preview-btn {
color: var(--color-gray-400);
}
:global(.dark) .preview-btn:hover:not(.disabled) {
background: rgba(255, 255, 255, 0.06);
color: var(--color-gray-300);
}
.preview-btn.disabled {
color: var(--color-gray-300);
cursor: default;
}
:global(.dark) .preview-btn.disabled {
color: var(--color-gray-700);
}
.url-bar {
flex: 1;
min-width: 0;
}
.url-input {
width: 100%;
border: 1px solid var(--color-gray-200);
border-radius: 624.9375rem;
padding: 0.1875rem 0.75rem;
font-size: 0.6875rem;
font-family: var(--font-mono);
background: white;
color: var(--color-gray-600);
outline: none;
transition: border-color 0.1s;
}
.url-input:focus {
border-color: oklch(0.65 0.15 250);
box-shadow: 0 0 0 0.125rem oklch(0.65 0.15 250 / 0.15);
}
:global(.dark) .url-input {
background: rgba(255, 255, 255, 0.04);
border-color: rgba(255, 255, 255, 0.08);
color: var(--color-gray-300);
}
:global(.dark) .url-input:focus {
border-color: oklch(0.65 0.15 250);
box-shadow: 0 0 0 0.125rem oklch(0.65 0.15 250 / 0.1);
}
.loading-track {
height: 0.125rem;
background: var(--color-gray-100);
flex-shrink: 0;
overflow: hidden;
}
:global(.dark) .loading-track {
background: rgba(255, 255, 255, 0.04);
}
.loading-bar {
height: 100%;
background: oklch(0.65 0.15 250);
border-radius: 624.9375rem;
animation: loading-bar 1.5s ease-in-out infinite;
}
@keyframes loading-bar {
0% {
width: 0;
margin-left: 0;
}
50% {
width: 60%;
margin-left: 20%;
}
100% {
width: 0;
margin-left: 100%;
}
}
.preview-content {
flex: 1;
overflow: hidden;
position: relative;
}
.preview-iframe {
width: 100%;
height: 100%;
border: none;
background: white;
}
.preview-error {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
gap: 0.375rem;
}
.error-title {
font-size: 0.875rem;
font-weight: 500;
color: var(--color-gray-500);
}
.error-sub {
font-size: 0.75rem;
color: var(--color-gray-400);
font-family: var(--font-mono);
}
.error-retry {
margin-top: 0.5rem;
padding: 0.25rem 0.875rem;
border-radius: 0.375rem;
font-size: 0.75rem;
background: var(--color-gray-100);
color: var(--color-gray-600);
transition: all 0.1s;
}
.error-retry:hover {
background: var(--color-gray-200);
}
:global(.dark) .error-retry {
background: rgba(255, 255, 255, 0.06);
color: var(--color-gray-300);
}
:global(.dark) .error-retry:hover {
background: rgba(255, 255, 255, 0.1);
}
</style>
@@ -58,7 +58,7 @@
async function loadRecents() {
try {
const data = await getRecentChats(9);
const data = await getRecentChats(9, effectiveWorkspace?.path);
recentChats = data.chats;
} catch {
// ignore
@@ -2,7 +2,8 @@
import { toast } from 'svelte-sonner';
import Icon from '../Icon.svelte';
import { t } from '$lib/i18n';
import { textScale, theme, themeConfig } from '$lib/stores';
import { expandToolDetails, textScale, theme, themeConfig, widescreenMode } from '$lib/stores';
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
import type { Theme, ThemeConfig } from '$lib/stores';
import {
normalizeHexColor,
@@ -21,7 +22,9 @@
const resolvedTheme = $derived(resolveThemeMode($theme));
const resolvedConfig = $derived(resolveThemeConfig($theme, $themeConfig));
const hasCustomAppearance = $derived(Boolean($themeConfig || $textScale !== null));
const hasCustomAppearance = $derived(
Boolean($themeConfig || $textScale !== null || $widescreenMode)
);
$effect(() => {
colorDrafts = {
@@ -102,13 +105,15 @@
scaleEnabled = false;
scaleDraft = 1;
textScale.set(null);
widescreenMode.set(false);
}
function exportTheme() {
const payload = {
theme: $theme,
themeConfig: sanitizeThemeConfig($themeConfig),
textScale: $textScale
textScale: $textScale,
widescreenMode: $widescreenMode
};
try {
@@ -155,13 +160,21 @@
typeof parsed?.textScale === 'number' && Number.isFinite(parsed.textScale)
? normalizeTextScale(parsed.textScale)
: undefined;
const importedWidescreenMode =
typeof parsed?.widescreenMode === 'boolean' ? parsed.widescreenMode : undefined;
if (!importedConfig && !importedTheme && importedScale === undefined) {
if (
!importedConfig &&
!importedTheme &&
importedScale === undefined &&
importedWidescreenMode === undefined
) {
throw new Error('empty theme');
}
if (importedTheme) theme.set(importedTheme);
if (importedConfig) themeConfig.set(importedConfig);
if (importedScale !== undefined) textScale.set(importedScale === 1 ? null : importedScale);
if (importedWidescreenMode !== undefined) widescreenMode.set(importedWidescreenMode);
toast.success($t('appearance.imported'));
} catch {
toast.error($t('appearance.importFailed'));
@@ -262,10 +275,20 @@
/>
</label>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
{$t('general.uiScale')}
</h3>
<div class="w-full">
<label class="flex items-center justify-between gap-3 mt-3">
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('appearance.widescreenMode')}</span
>
<ToggleSwitch value={$widescreenMode} onchange={(value) => widescreenMode.set(value)} />
</label>
<label class="flex items-center justify-between gap-3 mt-3">
<span class="text-xs text-gray-600 dark:text-gray-400"
>{$t('appearance.expandToolDetails')}</span
>
<ToggleSwitch value={$expandToolDetails} onchange={(value) => expandToolDetails.set(value)} />
</label>
<div class="w-full mt-5">
<div class="flex items-center gap-2">
<span id="ui-scale-label" class="text-xs text-gray-600 dark:text-gray-400">
{$t('general.uiScale')}
@@ -16,6 +16,7 @@
newFile: $t('keyboard.newFile'),
newTerminal: $t('keyboard.newTerminal'),
newChat: $t('keyboard.newChat'),
newBrowser: $t('keyboard.newBrowser'),
closeTab: $t('keyboard.closeTab'),
nextTab: $t('keyboard.nextTab'),
prevTab: $t('keyboard.prevTab'),
@@ -30,6 +31,7 @@
newFile: $t('keyboard.action.newFile'),
newTerminal: $t('keyboard.action.newTerminal'),
newChat: $t('keyboard.action.newChat'),
newBrowser: $t('keyboard.action.newBrowser'),
closeTab: $t('keyboard.action.closeTab'),
nextTab: $t('keyboard.action.nextTab'),
prevTab: $t('keyboard.action.prevTab'),
@@ -4,7 +4,12 @@
import { workspaceList, removeWorkspace, reorderWorkspaces, sidebarOpen } from '$lib/stores';
import { chatEnabled } from '$lib/stores/chat';
import { socketStore } from '$lib/stores/socket.svelte';
import { deleteChat as apiDeleteChat, getChats, type ChatInfo } from '$lib/apis/chat';
import {
deleteChat as apiDeleteChat,
getChats,
updateChatTitle,
type ChatInfo
} from '$lib/apis/chat';
import { t } from '$lib/i18n';
import { tooltip } from '$lib/tooltip';
import Sortable from 'sortablejs';
@@ -24,9 +29,11 @@
let wsListEl: HTMLDivElement | undefined = $state();
let sortable: Sortable | null = null;
let unbindSocketListener: (() => void) | null = null;
let workspacesExpanded = $state(true);
let expandedWorkspaces = $state<Set<string>>(new Set());
let wsChatsCache = $state<Map<string, ChatInfo[]>>(new Map());
let wsChatsHasMore = $state<Map<string, boolean>>(new Map());
let wsChatsLoading = $state<Set<string>>(new Set());
let currentPath = $derived($page.url.searchParams.get('workspace'));
@@ -41,14 +48,20 @@
expandedWorkspaces = next;
}
async function fetchWorkspaceChats(path: string) {
async function fetchWorkspaceChats(path: string, append = false) {
if (wsChatsLoading.has(path)) return;
wsChatsLoading = new Set([...wsChatsLoading, path]);
try {
const data = await getChats(path, 5, 0, 'updated_at', 'desc');
wsChatsCache = new Map([...wsChatsCache, [path, data.chats || []]]);
const existing = wsChatsCache.get(path) ?? [];
const data = await getChats(path, 5, append ? existing.length : 0, 'updated_at', 'desc');
wsChatsCache = new Map([
...wsChatsCache,
[path, append ? [...existing, ...(data.chats || [])] : data.chats || []]
]);
wsChatsHasMore = new Map([...wsChatsHasMore, [path, data.has_more]]);
} catch {
wsChatsCache = new Map([...wsChatsCache, [path, []]]);
wsChatsHasMore = new Map([...wsChatsHasMore, [path, false]]);
} finally {
const next = new Set(wsChatsLoading);
next.delete(path);
@@ -72,11 +85,6 @@
closeMobileSidebar();
}
function showMoreChats(wsPath: string) {
goto(`/?workspace=${encodeURIComponent(wsPath)}&chatId`);
closeMobileSidebar();
}
function newChat(wsPath: string) {
goto(`/?workspace=${encodeURIComponent(wsPath)}&chatId`);
closeMobileSidebar();
@@ -123,6 +131,30 @@
}
}
async function handleRenameChat() {
if (!chatMenu) return;
const { chatId, wsPath } = chatMenu;
const chat = (wsChatsCache.get(wsPath) ?? []).find((item) => item.id === chatId);
const title = window.prompt($t('files.rename'), chat?.title)?.trim();
if (!title || title === chat?.title) return;
await updateChatTitle(chatId, title);
const chats = wsChatsCache.get(wsPath) ?? [];
wsChatsCache = new Map([
...wsChatsCache,
[wsPath, chats.map((item) => (item.id === chatId ? { ...item, title } : item))]
]);
}
function copyChatPath() {
if (!chatMenu) return;
const { chatId, wsPath } = chatMenu;
const chat = (wsChatsCache.get(wsPath) ?? []).find((item) => item.id === chatId);
if (!chat) return;
navigator.clipboard.writeText(
`${wsPath.replace(/\/$/, '')}/.cptr/chats/${chat.folder ? `${chat.folder}/` : ''}${chat.id}.json`
);
}
const seenChatIds = new Set<string>();
function handleChatEvent(data: {
@@ -137,6 +169,7 @@
if (!data.done && !data.title && !isNew) return;
wsChatsCache = new Map();
wsChatsHasMore = new Map();
for (const path of expandedWorkspaces) fetchWorkspaceChats(path);
}
@@ -172,7 +205,20 @@
</script>
<div class="flex items-center justify-between h-8 pl-3.5 pr-1.5 shrink-0">
<span class="text-xs text-gray-400 dark:text-gray-500">{$t('sidebar.workspaces')}</span>
<button
class="group flex flex-1 h-full items-center gap-1 text-left text-xs text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400 transition-colors duration-100"
onclick={() => (workspacesExpanded = !workspacesExpanded)}
aria-expanded={workspacesExpanded}
aria-controls="workspace-list"
>
<span>{$t('sidebar.workspaces')}</span>
<span
class="flex opacity-0 group-hover:opacity-100 transition-all duration-100"
style="transform: rotate({workspacesExpanded ? '90deg' : '0deg'})"
>
<Icon name="chevron-right" size={11} />
</span>
</button>
<button
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-300 hover:text-gray-500 dark:text-gray-600 dark:hover:text-gray-400 transition-colors duration-100"
onclick={onaddworkspace}
@@ -183,10 +229,16 @@
</button>
</div>
<div bind:this={wsListEl} class="flex-1 overflow-y-auto px-1.5">
<div
id="workspace-list"
bind:this={wsListEl}
class="flex-1 overflow-y-auto px-1.5"
class:invisible={!workspacesExpanded}
>
{#each $workspaceList as ws (ws.path)}
{@const isExpanded = expandedWorkspaces.has(ws.path)}
{@const chats = wsChatsCache.get(ws.path)}
{@const hasMoreChats = wsChatsHasMore.get(ws.path)}
{@const isLoading = wsChatsLoading.has(ws.path)}
<div class="ws-item">
<div
@@ -266,9 +318,15 @@
onmenu={(e) => openChatMenu(e, chat.id, ws.path)}
/>
{/each}
<button class="ws-chat-show-more" onclick={() => showMoreChats(ws.path)}>
{$t('sidebar.showMore')}
</button>
{#if hasMoreChats}
<button
class="ws-chat-show-more"
disabled={isLoading}
onclick={() => fetchWorkspaceChats(ws.path, true)}
>
{$t('sidebar.showMore')}
</button>
{/if}
{/if}
</div>
{/if}
@@ -301,6 +359,16 @@
anchor={chatMenu.anchor}
align="end"
items={[
{
label: $t('files.copyPath'),
icon: 'copy',
onclick: copyChatPath
},
{
label: $t('files.rename'),
icon: 'pencil',
onclick: handleRenameChat
},
{
label: $t('chat.history.delete'),
icon: 'trash',
@@ -347,7 +415,7 @@
}
:global(.dark) .ws-icon-chevron {
color: #6b7280;
color: var(--app-fg-muted);
}
.ws-icon-toggle:hover .ws-icon-folder {
@@ -371,21 +439,13 @@
background: none;
cursor: pointer;
font-size: 0.6875rem;
color: #b0b5be;
color: var(--app-fg-subtle);
text-align: left;
transition: color 0.1s;
}
.ws-chat-show-more:hover {
color: #6b7280;
}
:global(.dark) .ws-chat-show-more {
color: #6b7280;
}
:global(.dark) .ws-chat-show-more:hover {
color: #9ca3af;
color: var(--app-fg);
}
.ws-chat-loading {
@@ -9,6 +9,8 @@
chats: ChatInfo[];
onopen: (id: string) => void;
ondelete: (id: string) => void;
onrename: (id: string) => void;
oncopy?: (id: string) => void;
page?: number;
totalPages?: number;
perPage?: number;
@@ -21,6 +23,8 @@
chats,
onopen,
ondelete,
onrename,
oncopy,
page = 1,
totalPages = 1,
perPage = 10,
@@ -144,6 +148,24 @@
anchor={menuAnchor}
align="end"
items={[
...(oncopy
? [
{
label: $t('files.copyPath'),
icon: 'copy',
onclick: () => {
if (menuChatId) oncopy(menuChatId);
}
}
]
: []),
{
label: $t('files.rename'),
icon: 'pencil',
onclick: () => {
if (menuChatId) onrename(menuChatId);
}
},
{
label: $t('chat.history.delete'),
icon: 'trash',
@@ -160,6 +160,7 @@
}
async function processFiles(files: File[]) {
if (!workspace) return;
for (const file of files) {
const id = Math.random().toString(36).substring(7);
const isImage = file.type.startsWith('image/');
@@ -373,7 +374,6 @@
let slashSkillsRequestId = 0;
async function getCachedSkills(): Promise<SkillMentionAttrs[]> {
if (!workspace) return [];
if (!cachedSkills || cachedSkillsWorkspace !== workspace) {
const data = await getSkills(workspace);
cachedSkills = data.map((s) => ({
@@ -388,7 +388,6 @@
}
async function fetchSkillSuggestions({ query }: { query: string }): Promise<SkillMentionAttrs[]> {
if (!workspace) return [];
try {
const skills = await getCachedSkills();
if (!query) return skills;
@@ -990,7 +989,7 @@
$effect(() => {
const query = slashCommandQuery;
const requestId = ++slashSkillsRequestId;
if (!query.startsWith('/') || /\s/.test(query.slice(1)) || !workspace) {
if (!query.startsWith('/') || /\s/.test(query.slice(1))) {
slashSkillSuggestions = [];
return;
}
@@ -1472,14 +1471,16 @@
onmousedown={(e) => e.stopPropagation()}
>
<div class="ml-0.5 self-end flex items-center gap-1">
<PlusMenu
onfiles={(files) => {
if (files) processFiles(Array.from(files));
}}
oncapture={(file) => {
processFiles([file]);
}}
/>
{#if workspace}
<PlusMenu
onfiles={(files) => {
if (files) processFiles(Array.from(files));
}}
oncapture={(file) => {
processFiles([file]);
}}
/>
{/if}
{#if $planMode}
<button
type="button"
@@ -3,6 +3,7 @@
getChat,
getChats,
deleteChat as apiDeleteChat,
updateChatTitle,
forkChat as apiForkChat,
sendMessage as apiSendMessage,
approveToolCall,
@@ -36,7 +37,8 @@
planMode,
streamingBehavior,
selectedModelId,
requestParams
requestParams,
widescreenMode
} from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import {
@@ -71,11 +73,13 @@
};
interface Props {
workspace: string;
workspace?: string;
chatId?: string;
tabId?: string;
ontabupdate?: (tabId: string, chatId: string, label: string) => void;
onopenchat?: (chatId?: string) => void;
}
let { workspace, chatId: initialChatId, tabId }: Props = $props();
let { workspace = '', chatId: initialChatId, tabId, ontabupdate, onopenchat }: Props = $props();
let inputText = $state('');
let chatId = $state<string | null>(initialChatId ?? null);
@@ -301,7 +305,9 @@
const hasChatContent = $derived(
activePath.some(({ msg }) => msg.role === 'user' && msg.content.trim())
);
const workspaceDisplayName = $derived(getPathDisplayName(workspace, 'workspace'));
const workspaceDisplayName = $derived(
workspace ? getPathDisplayName(workspace, 'workspace') : 'Computer'
);
const displayChatTitle = $derived(chatTitle || firstUserMessageTitle() || workspaceDisplayName);
const runningCommandSessions = $derived(commandSessions.filter((session) => !session.done));
const summaryCount = $derived(runningCommandSessions.length);
@@ -445,6 +451,31 @@
previousChats = previousChats.filter((c) => c.id !== id);
}
async function renameChat(id: string) {
const chat = previousChats.find((c) => c.id === id);
const title = window.prompt($t('files.rename'), chat?.title)?.trim();
if (!title || title === chat?.title) return;
try {
await updateChatTitle(id, title);
previousChats = previousChats.map((c) => (c.id === id ? { ...c, title } : c));
if (chatId === id) {
chatTitle = title;
if (tabId) updateTab(tabId, id, title);
}
} catch (e) {
toast.error(e instanceof Error ? e.message : $t('files.rename'));
}
}
function copyChatPath(id: string) {
if (!workspace) return;
const chat = previousChats.find((c) => c.id === id);
if (!chat) return;
navigator.clipboard.writeText(
`${workspace.replace(/\/$/, '')}/.cptr/chats/${chat.folder ? `${chat.folder}/` : ''}${chat.id}.json`
);
}
// ── Socket listener ─────────────────────────────────────────
let landingRefreshTimer: ReturnType<typeof setTimeout> | null = null;
@@ -493,8 +524,9 @@
return;
}
// Title generated by backend — update tab label
// Title updates also keep open chat tabs in sync.
if (data.title && tabId) {
chatTitle = data.title;
updateTab(tabId, data.chat_id, data.title);
}
@@ -913,7 +945,8 @@
const toastId = toast.loading($t('chat.forking'));
try {
const result = await apiForkChat(chatId, messageId ?? currentMessageId);
openChatTab(result.chat_id);
if (onopenchat) onopenchat(result.chat_id);
else openChatTab(result.chat_id);
toast.success($t('chat.forkDone'), { id: toastId });
} catch (err: any) {
toast.error(err?.message || $t('chat.forkFailed'), { id: toastId });
@@ -950,7 +983,7 @@
async function refreshCommandSessions() {
const currentChatId = chatId;
if (!currentChatId) {
if (!currentChatId || !workspace) {
commandSessions = [];
return;
}
@@ -1178,6 +1211,7 @@
}
function updateTab(tid: string, newChatId: string, label: string) {
if (ontabupdate) return ontabupdate(tid, newChatId, label);
currentWorkspace.update((ws) => {
if (!ws) return ws;
return {
@@ -1558,6 +1592,8 @@
chats={previousChats}
onopen={openChat}
ondelete={deleteChat}
onrename={renameChat}
oncopy={workspace ? copyChatPath : undefined}
page={chatPage}
{totalPages}
perPage={CHATS_PAGE_SIZE}
@@ -1581,7 +1617,11 @@
style="background: var(--app-bg); color: var(--app-fg);"
onscroll={handleMessagesScroll}
>
<div class="max-w-2xl mx-auto px-4 pt-4 pb-16 flex flex-col gap-4">
<div
class="{$widescreenMode
? 'max-w-full'
: 'max-w-2xl'} mx-auto w-full px-4 pt-4 pb-16 flex flex-col gap-4"
>
{#if hasHiddenMessages}
<div bind:this={loadSentinelEl} class="h-1 w-full" aria-hidden="true"></div>
{/if}
@@ -1623,7 +1663,7 @@
<!-- Input area -->
<div class="px-4 py-3" style="background: var(--app-bg);">
<div class="max-w-2xl mx-auto relative">
<div class="{$widescreenMode ? 'max-w-full' : 'max-w-2xl'} mx-auto w-full relative">
{#if !autoScroll && activePath.length > 0}
<div
class="absolute -top-10 left-0 right-0 pr-2 flex justify-end z-30 pointer-events-none"
@@ -2,6 +2,7 @@
import { slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { t } from '$lib/i18n';
import { expandToolDetails } from '$lib/stores';
import ReasoningCollapsible from './ReasoningCollapsible.svelte';
import ToolCallCollapsible from './ToolCallCollapsible.svelte';
@@ -31,7 +32,10 @@
onapprove
}: Props = $props();
let expanded = $state(false);
let expanded = $state($expandToolDetails);
$effect(() => {
expanded = $expandToolDetails;
});
const hasReasoningPending = $derived(
reasoning.some((ri: any) => ri.status === 'in_progress' || ri.status === 'running')
@@ -2,6 +2,7 @@
import { slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { t } from '$lib/i18n';
import { expandToolDetails } from '$lib/stores';
interface Props {
item: any;
@@ -15,7 +16,10 @@
let { item, pairedOutput, done, chatId, messageId, toolLabel, onapprove }: Props = $props();
let expanded = $state(false);
let expanded = $state($expandToolDetails);
$effect(() => {
expanded = $expandToolDetails;
});
const args = $derived(item.arguments || {});
const toolName = $derived(item.name);
@@ -1,5 +1,26 @@
{
"app.tagline": "Dein Computer, von überall.",
"home.greeting.superEarly.0": "Schon früh wach, {{name}}?",
"home.greeting.superEarly.1": "Die ruhigen Stunden passen zu dir, {{name}}.",
"home.greeting.superEarly.2": "Bevor die Welt aufwacht, {{name}}.",
"home.greeting.morning.0": "Guten Morgen, {{name}}.",
"home.greeting.morning.1": "Frischer Start, {{name}}.",
"home.greeting.morning.2": "Erst Kaffee, dann was auch immer kommt, {{name}}.",
"home.greeting.noon.0": "Mittags-Check-in, {{name}}.",
"home.greeting.noon.1": "Zeit zum Durchatmen, {{name}}?",
"home.greeting.noon.2": "Genau richtig, {{name}}.",
"home.greeting.afternoon.0": "Noch dabei, {{name}}.",
"home.greeting.afternoon.1": "Guten Nachmittag, {{name}}.",
"home.greeting.afternoon.2": "Kommst du voran, {{name}}?",
"home.greeting.evening.0": "Guten Abend, {{name}}.",
"home.greeting.evening.1": "Schon Feierabend oder geht's los, {{name}}?",
"home.greeting.evening.2": "Gute Zeit, etwas abzuschließen, {{name}}.",
"home.greeting.night.0": "Nachtschicht, {{name}}?",
"home.greeting.night.1": "Der Tag ist noch nicht vorbei, {{name}}.",
"home.greeting.night.2": "Noch eine Sache, {{name}}?",
"home.greeting.lateNight.0": "Noch wach, {{name}}?",
"home.greeting.lateNight.1": "Die Nachteule ist wieder da, {{name}}.",
"home.greeting.lateNight.2": "Speichere deine Arbeit, {{name}}.",
"auth.createAccountHint": "Erstelle ein Konto, um loszulegen.",
"auth.signInSystemHint": "Melde dich mit deinem Systemkonto an.",
"auth.setup": "Einrichtung",
@@ -33,6 +54,14 @@
"sidebar.showMore": "Mehr anzeigen",
"bar.newFile": "Neue Datei",
"bar.newTerminal": "Neues Terminal",
"bar.newBrowser": "Browser",
"browser.invalidUrl": "Ungültige URL",
"browser.proxy": "Proxy",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "H.264-Videodekodierung ist in diesem Browser nicht verfügbar",
"browser.viewOnly": "Nur ansehen",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "Tab schließen",
"bar.new": "Neu...",
"bar.sidebar": "Seitenleiste",
@@ -354,6 +383,41 @@
"admin.webCcHint": "Beliebiger OpenAI-kompatibler Endpunkt (z. B. Perplexity Sonar, LiteLLM-Proxy)",
"admin.browser": "Browsersteuerung",
"admin.browserTools": "Browser-Tools",
"admin.browserTabDefault": "Standard für Browser-Tabs",
"admin.browserTabDefaultHint": "Standard-Renderer für neue Browser- und Port-Vorschau-Tabs.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "Gibt der KI Zugriff auf einen Webbrowser zum Navigieren, Klicken und Erstellen von Screenshots.",
"admin.browserProvider": "Anbieter",
"admin.browserLocalCdp": "Lokales CDP",
@@ -444,6 +508,7 @@
"keyboard.newFile": "Eine neue leere Datei öffnen",
"keyboard.newTerminal": "Eine neue Terminalsitzung öffnen",
"keyboard.newChat": "Einen neuen KI-Chat starten",
"keyboard.newBrowser": "Einen neuen Browser-Tab öffnen",
"keyboard.closeTab": "Den aktiven Tab schließen",
"keyboard.nextTab": "Zum nächsten Tab wechseln",
"keyboard.prevTab": "Zum vorherigen Tab wechseln",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "Neue Datei",
"keyboard.action.newTerminal": "Neues Terminal",
"keyboard.action.newChat": "Neuer Chat",
"keyboard.action.newBrowser": "Neuer Browser",
"keyboard.action.closeTab": "Tab schließen",
"keyboard.action.nextTab": "Nächster Tab",
"keyboard.action.prevTab": "Vorheriger Tab",
@@ -897,6 +963,8 @@
"appearance.background": "Hintergrund",
"appearance.foreground": "Vordergrund",
"appearance.uiFont": "Oberflächenschrift",
"appearance.widescreenMode": "Breitbildmodus",
"appearance.expandToolDetails": "Aktivitäten immer erweitern",
"appearance.exported": "Design exportiert",
"appearance.exportFailed": "Design konnte nicht exportiert werden",
"appearance.imported": "Design importiert",
+86 -1
View File
@@ -1,5 +1,26 @@
{
"app.tagline": "Your computer, from anywhere.",
"home.greeting.superEarly.0": "Up early, {{name}}?",
"home.greeting.superEarly.1": "The quiet hours suit you, {{name}}.",
"home.greeting.superEarly.2": "Before the world wakes up, {{name}}.",
"home.greeting.morning.0": "Morning, {{name}}.",
"home.greeting.morning.1": "Fresh start, {{name}}.",
"home.greeting.morning.2": "Coffee first, then whatever’s next, {{name}}.",
"home.greeting.noon.0": "Midday check-in, {{name}}.",
"home.greeting.noon.1": "Taking a breather, {{name}}?",
"home.greeting.noon.2": "Right on time, {{name}}.",
"home.greeting.afternoon.0": "Still at it, {{name}}.",
"home.greeting.afternoon.1": "Afternoon, {{name}}.",
"home.greeting.afternoon.2": "Making progress, {{name}}?",
"home.greeting.evening.0": "Evening, {{name}}.",
"home.greeting.evening.1": "Winding down or warming up, {{name}}?",
"home.greeting.evening.2": "A good time to finish something, {{name}}.",
"home.greeting.night.0": "Night shift, {{name}}?",
"home.greeting.night.1": "The day is not over yet, {{name}}.",
"home.greeting.night.2": "One more thing, {{name}}?",
"home.greeting.lateNight.0": "Still here, {{name}}?",
"home.greeting.lateNight.1": "The night owl is back, {{name}}.",
"home.greeting.lateNight.2": "Save your work, {{name}}.",
"auth.createAccountHint": "Create your account to get started.",
"auth.signInSystemHint": "Sign in with your system account.",
"auth.setup": "Setup",
@@ -33,11 +54,20 @@
"sidebar.showMore": "Show more",
"bar.newFile": "New File",
"bar.newTerminal": "New Terminal",
"bar.newBrowser": "Browser",
"browser.invalidUrl": "Invalid URL",
"browser.proxy": "Proxy",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "H.264 video decoding is unavailable in this browser",
"browser.viewOnly": "View only",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "Close tab",
"bar.new": "New...",
"bar.sidebar": "Sidebar",
"bar.toggleSidebar": "Toggle sidebar",
"files.filter": "Filter...",
"files.searchFilesAndContents": "Search filenames and contents...",
"files.refresh": "Refresh",
"files.sort": "Sort",
"files.actions": "Actions",
@@ -48,6 +78,11 @@
"files.fileNamePlaceholder": "File name...",
"files.retry": "Retry",
"files.noMatches": "No matches",
"files.filenameMatches": "Files",
"files.contentMatches": "Contents",
"files.line": "Line {{line}}",
"files.searchTruncated": "Some matches are not shown",
"files.failedToSearch": "Failed to search files",
"files.emptyDirectory": "Empty directory",
"files.dropToUpload": "Drop files to upload",
"files.selected": "{{count}} selected",
@@ -283,7 +318,7 @@
"bar.newChat": "New Chat",
"home.start": "Start",
"home.openFolder": "Open Folder...",
"home.openWorkspace": "Open workspace",
"home.openWorkspace": "Open Workspace",
"home.recent": "Recent",
"home.continue": "Continue",
"home.noWorkspaces": "No workspaces yet",
@@ -356,6 +391,52 @@
"admin.webCcHint": "Use any OpenAI-compatible endpoint (e.g. Perplexity Sonar, LiteLLM proxy)",
"admin.browser": "Browser",
"admin.browserTools": "Browser tools",
"admin.browserTabDefault": "Browser tab default",
"admin.browserTabDefaultHint": "Default renderer for new Browser and Port Preview tabs.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Controls stream bitrate and frame rate without resizing the page.",
"admin.browserQualityHintV2": "Controls stream bitrate and frame rate without resizing the page.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityFrameRate": "Frame rate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"browser.device": "Device",
"browser.deviceAuto": "Auto",
"browser.deviceDesktop": "Desktop",
"browser.deviceMobile": "Mobile",
"browser.deviceFixedViewport": "Use fixed width × height",
"browser.deviceWidth": "Mobile viewport width",
"browser.deviceHeight": "Mobile viewport height",
"browser.deviceWidthHint": "Viewport width in CSS pixels.",
"browser.deviceHeightHint": "Viewport height in CSS pixels.",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "Give the AI access to a web browser for navigating pages, clicking elements, and taking screenshots.",
"admin.browserProvider": "Provider",
"admin.browserLocalCdp": "Local CDP",
@@ -446,6 +527,7 @@
"keyboard.newFile": "Open a new untitled file",
"keyboard.newTerminal": "Open a new terminal session",
"keyboard.newChat": "Start a new AI chat",
"keyboard.newBrowser": "Open a new Browser tab",
"keyboard.closeTab": "Close the active tab",
"keyboard.nextTab": "Switch to the next tab",
"keyboard.prevTab": "Switch to the previous tab",
@@ -764,6 +846,7 @@
"keyboard.action.newFile": "New File",
"keyboard.action.newTerminal": "New Terminal",
"keyboard.action.newChat": "New Chat",
"keyboard.action.newBrowser": "New Browser",
"keyboard.action.closeTab": "Close Tab",
"keyboard.action.nextTab": "Next Tab",
"keyboard.action.prevTab": "Previous Tab",
@@ -909,6 +992,8 @@
"appearance.background": "Background",
"appearance.foreground": "Foreground",
"appearance.uiFont": "UI font",
"appearance.widescreenMode": "Widescreen Mode",
"appearance.expandToolDetails": "Always Expand Activity",
"appearance.exported": "Theme exported",
"appearance.exportFailed": "Failed to export theme",
"appearance.imported": "Theme imported",
@@ -1,5 +1,26 @@
{
"app.tagline": "Tu computadora, desde cualquier lugar.",
"home.greeting.superEarly.0": "Madrugas, {{name}}?",
"home.greeting.superEarly.1": "Las horas tranquilas te sientan bien, {{name}}.",
"home.greeting.superEarly.2": "Antes de que despierte el mundo, {{name}}.",
"home.greeting.morning.0": "Buenos días, {{name}}.",
"home.greeting.morning.1": "Nuevo comienzo, {{name}}.",
"home.greeting.morning.2": "Primero café, luego lo que siga, {{name}}.",
"home.greeting.noon.0": "Control de mediodía, {{name}}.",
"home.greeting.noon.1": "Tomando un respiro, {{name}}?",
"home.greeting.noon.2": "Justo a tiempo, {{name}}.",
"home.greeting.afternoon.0": "Sigues con ello, {{name}}.",
"home.greeting.afternoon.1": "Buenas tardes, {{name}}.",
"home.greeting.afternoon.2": "Haciendo progreso, {{name}}?",
"home.greeting.evening.0": "Buenas noches, {{name}}.",
"home.greeting.evening.1": "Bajando el ritmo o arrancando, {{name}}?",
"home.greeting.evening.2": "Buen momento para terminar algo, {{name}}.",
"home.greeting.night.0": "Turno de noche, {{name}}?",
"home.greeting.night.1": "El día aún no termina, {{name}}.",
"home.greeting.night.2": "Una cosa más, {{name}}?",
"home.greeting.lateNight.0": "Sigues aquí, {{name}}?",
"home.greeting.lateNight.1": "El búho nocturno volvió, {{name}}.",
"home.greeting.lateNight.2": "Guarda tu trabajo, {{name}}.",
"auth.createAccountHint": "Crea tu cuenta para comenzar.",
"auth.signInSystemHint": "Inicia sesión con tu cuenta del sistema.",
"auth.setup": "Configuración",
@@ -33,6 +54,14 @@
"sidebar.showMore": "Mostrar más",
"bar.newFile": "Nuevo archivo",
"bar.newTerminal": "Nueva terminal",
"bar.newBrowser": "Navegador",
"browser.invalidUrl": "URL no válida",
"browser.proxy": "Proxy",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "La decodificación de vídeo H.264 no está disponible en este navegador",
"browser.viewOnly": "Solo lectura",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "Cerrar pestaña",
"bar.new": "Nuevo...",
"bar.sidebar": "Barra lateral",
@@ -354,6 +383,41 @@
"admin.webCcHint": "Cualquier endpoint compatible con OpenAI (ej. Perplexity Sonar, proxy LiteLLM)",
"admin.browser": "Navegador",
"admin.browserTools": "Herramientas del navegador",
"admin.browserTabDefault": "Navegador predeterminado",
"admin.browserTabDefaultHint": "Renderizador predeterminado para nuevas pestañas de Navegador y Vista previa de puerto.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "Dar a la IA acceso a un navegador web para navegar páginas, hacer clic en elementos y tomar capturas de pantalla.",
"admin.browserProvider": "Proveedor",
"admin.browserLocalCdp": "CDP local",
@@ -444,6 +508,7 @@
"keyboard.newFile": "Abrir un archivo nuevo vacío",
"keyboard.newTerminal": "Abrir una nueva sesión de terminal",
"keyboard.newChat": "Iniciar un nuevo chat de IA",
"keyboard.newBrowser": "Abrir una nueva pestaña del navegador",
"keyboard.closeTab": "Cerrar la pestaña activa",
"keyboard.nextTab": "Cambiar a la siguiente pestaña",
"keyboard.prevTab": "Cambiar a la pestaña anterior",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "Nuevo archivo",
"keyboard.action.newTerminal": "Nueva terminal",
"keyboard.action.newChat": "Nuevo chat",
"keyboard.action.newBrowser": "Nuevo navegador",
"keyboard.action.closeTab": "Cerrar pestaña",
"keyboard.action.nextTab": "Siguiente pestaña",
"keyboard.action.prevTab": "Pestaña anterior",
@@ -897,6 +963,8 @@
"appearance.background": "Fondo",
"appearance.foreground": "Primer plano",
"appearance.uiFont": "Fuente de interfaz",
"appearance.widescreenMode": "Modo panorámico",
"appearance.expandToolDetails": "Expandir siempre la actividad",
"appearance.exported": "Tema exportado",
"appearance.exportFailed": "Error al exportar el tema",
"appearance.imported": "Tema importado",
@@ -1,5 +1,26 @@
{
"app.tagline": "Votre ordinateur, où que vous soyez.",
"home.greeting.superEarly.0": "Déjà debout, {{name}} ?",
"home.greeting.superEarly.1": "Les heures calmes te vont bien, {{name}}.",
"home.greeting.superEarly.2": "Avant que le monde se réveille, {{name}}.",
"home.greeting.morning.0": "Bonjour, {{name}}.",
"home.greeting.morning.1": "Nouveau départ, {{name}}.",
"home.greeting.morning.2": "D'abord le café, puis la suite, {{name}}.",
"home.greeting.noon.0": "Point de midi, {{name}}.",
"home.greeting.noon.1": "Une pause, {{name}} ?",
"home.greeting.noon.2": "Pile à l'heure, {{name}}.",
"home.greeting.afternoon.0": "Toujours à l’œuvre, {{name}}.",
"home.greeting.afternoon.1": "Bon après-midi, {{name}}.",
"home.greeting.afternoon.2": "Ça avance, {{name}} ?",
"home.greeting.evening.0": "Bonsoir, {{name}}.",
"home.greeting.evening.1": "On ralentit ou on démarre, {{name}} ?",
"home.greeting.evening.2": "Bon moment pour finir quelque chose, {{name}}.",
"home.greeting.night.0": "Service de nuit, {{name}} ?",
"home.greeting.night.1": "La journée n'est pas finie, {{name}}.",
"home.greeting.night.2": "Encore une chose, {{name}} ?",
"home.greeting.lateNight.0": "Toujours là, {{name}} ?",
"home.greeting.lateNight.1": "Le hibou de nuit est de retour, {{name}}.",
"home.greeting.lateNight.2": "Sauvegarde ton travail, {{name}}.",
"auth.createAccountHint": "Créez votre compte pour commencer.",
"auth.signInSystemHint": "Connectez-vous avec votre compte système.",
"auth.setup": "Configuration",
@@ -33,6 +54,14 @@
"sidebar.showMore": "Afficher plus",
"bar.newFile": "Nouveau fichier",
"bar.newTerminal": "Nouveau terminal",
"bar.newBrowser": "Navigateur",
"browser.invalidUrl": "URL non valide",
"browser.proxy": "Proxy",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "Le décodage vidéo H.264 n’est pas disponible dans ce navigateur",
"browser.viewOnly": "Lecture seule",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "Fermer l'onglet",
"bar.new": "Nouveau...",
"bar.sidebar": "Barre latérale",
@@ -354,6 +383,41 @@
"admin.webCcHint": "Tout endpoint compatible OpenAI (ex. Perplexity Sonar, proxy LiteLLM)",
"admin.browser": "Navigateur",
"admin.browserTools": "Outils du navigateur",
"admin.browserTabDefault": "Navigateur par défaut",
"admin.browserTabDefaultHint": "Moteur par défaut des nouveaux onglets Navigateur et Aperçu de port.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "Donne à l'IA accès à un navigateur web pour naviguer, cliquer et prendre des captures d'écran.",
"admin.browserProvider": "Fournisseur",
"admin.browserLocalCdp": "CDP local",
@@ -444,6 +508,7 @@
"keyboard.newFile": "Ouvrir un nouveau fichier vide",
"keyboard.newTerminal": "Ouvrir une nouvelle session de terminal",
"keyboard.newChat": "Démarrer un nouveau chat IA",
"keyboard.newBrowser": "Ouvrir un nouvel onglet de navigateur",
"keyboard.closeTab": "Fermer l'onglet actif",
"keyboard.nextTab": "Passer à l'onglet suivant",
"keyboard.prevTab": "Passer à l'onglet précédent",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "Nouveau fichier",
"keyboard.action.newTerminal": "Nouveau terminal",
"keyboard.action.newChat": "Nouveau chat",
"keyboard.action.newBrowser": "Nouveau navigateur",
"keyboard.action.closeTab": "Fermer l'onglet",
"keyboard.action.nextTab": "Onglet suivant",
"keyboard.action.prevTab": "Onglet précédent",
@@ -897,6 +963,8 @@
"appearance.background": "Arrière-plan",
"appearance.foreground": "Premier plan",
"appearance.uiFont": "Police de l’interface",
"appearance.widescreenMode": "Mode grand écran",
"appearance.expandToolDetails": "Toujours développer l’activité",
"appearance.exported": "Thème exporté",
"appearance.exportFailed": "Échec de l’export du thème",
"appearance.imported": "Thème importé",
@@ -1,5 +1,26 @@
{
"app.tagline": "どこからでも、あなたのコンピュータへ。",
"home.greeting.superEarly.0": "もう起きてるの、{{name}}さん?",
"home.greeting.superEarly.1": "静かな時間が似合いますね、{{name}}さん。",
"home.greeting.superEarly.2": "世界が目を覚ます前に、{{name}}さん。",
"home.greeting.morning.0": "おはよう、{{name}}さん。",
"home.greeting.morning.1": "新しい一日の始まりですね、{{name}}さん。",
"home.greeting.morning.2": "まずはコーヒー、それからゆっくり、{{name}}さん。",
"home.greeting.noon.0": "お昼のチェックイン、{{name}}さん。",
"home.greeting.noon.1": "ひと休みしますか、{{name}}さん?",
"home.greeting.noon.2": "ちょうどいい時間です、{{name}}さん。",
"home.greeting.afternoon.0": "まだ続いてますね、{{name}}さん。",
"home.greeting.afternoon.1": "こんにちは、{{name}}さん。",
"home.greeting.afternoon.2": "順調ですか、{{name}}さん?",
"home.greeting.evening.0": "こんばんは、{{name}}さん。",
"home.greeting.evening.1": "これからですか、それともひと休み、{{name}}さん?",
"home.greeting.evening.2": "何かを終えるのにいい時間です、{{name}}さん。",
"home.greeting.night.0": "夜の時間ですね、{{name}}さん?",
"home.greeting.night.1": "まだ一日は終わっていません、{{name}}さん。",
"home.greeting.night.2": "あと一つだけ、{{name}}さん?",
"home.greeting.lateNight.0": "まだ起きてますか、{{name}}さん?",
"home.greeting.lateNight.1": "夜型ですね、{{name}}さん。",
"home.greeting.lateNight.2": "保存を忘れずに、{{name}}さん。",
"auth.createAccountHint": "アカウントを作成して始めましょう。",
"auth.signInSystemHint": "システムアカウントでサインインしてください。",
"auth.setup": "セットアップ",
@@ -33,6 +54,14 @@
"sidebar.showMore": "もっと見る",
"bar.newFile": "新規ファイル",
"bar.newTerminal": "新規ターミナル",
"bar.newBrowser": "ブラウザ",
"browser.invalidUrl": "無効なURL",
"browser.proxy": "プロキシ",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "このブラウザーではH.264動画をデコードできません",
"browser.viewOnly": "閲覧のみ",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "タブを閉じる",
"bar.new": "新規...",
"bar.sidebar": "サイドバー",
@@ -354,6 +383,41 @@
"admin.webCcHint": "OpenAI互換エンドポイント(例: Perplexity Sonar、LiteLLMプロキシ)",
"admin.browser": "ブラウザ",
"admin.browserTools": "ブラウザツール",
"admin.browserTabDefault": "ブラウザタブの既定値",
"admin.browserTabDefaultHint": "新しいブラウザとポートプレビュータブの既定のレンダラーです。",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "AIにウェブブラウザへのアクセスを提供し、ページ操作、要素のクリック、スクリーンショットの取得を可能にします。",
"admin.browserProvider": "プロバイダー",
"admin.browserLocalCdp": "ローカルCDP",
@@ -444,6 +508,7 @@
"keyboard.newFile": "新しい空のファイルを開く",
"keyboard.newTerminal": "新しいターミナルセッションを開く",
"keyboard.newChat": "新しいAIチャットを開始",
"keyboard.newBrowser": "新しいブラウザータブを開く",
"keyboard.closeTab": "アクティブなタブを閉じる",
"keyboard.nextTab": "次のタブに切り替える",
"keyboard.prevTab": "前のタブに切り替える",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "新規ファイル",
"keyboard.action.newTerminal": "新規ターミナル",
"keyboard.action.newChat": "新規チャット",
"keyboard.action.newBrowser": "新規ブラウザー",
"keyboard.action.closeTab": "タブを閉じる",
"keyboard.action.nextTab": "次のタブ",
"keyboard.action.prevTab": "前のタブ",
@@ -897,6 +963,8 @@
"appearance.background": "背景",
"appearance.foreground": "前景",
"appearance.uiFont": "UIフォント",
"appearance.widescreenMode": "ワイドスクリーンモード",
"appearance.expandToolDetails": "アクティビティを常に展開",
"appearance.exported": "テーマをエクスポートしました",
"appearance.exportFailed": "テーマのエクスポートに失敗しました",
"appearance.imported": "テーマをインポートしました",
@@ -1,5 +1,26 @@
{
"app.tagline": "어디서든, 당신의 컴퓨터로.",
"home.greeting.superEarly.0": "벌써 일어났어요, {{name}}님?",
"home.greeting.superEarly.1": "조용한 시간이 잘 어울리네요, {{name}}님.",
"home.greeting.superEarly.2": "세상이 깨어나기 전에, {{name}}님.",
"home.greeting.morning.0": "좋은 아침이에요, {{name}}님.",
"home.greeting.morning.1": "새로운 시작이에요, {{name}}님.",
"home.greeting.morning.2": "커피 먼저, 그다음 천천히, {{name}}님.",
"home.greeting.noon.0": "한낮의 체크인, {{name}}님.",
"home.greeting.noon.1": "잠깐 쉬어갈까요, {{name}}님?",
"home.greeting.noon.2": "딱 좋은 시간이네요, {{name}}님.",
"home.greeting.afternoon.0": "계속하고 있네요, {{name}}님.",
"home.greeting.afternoon.1": "좋은 오후예요, {{name}}님.",
"home.greeting.afternoon.2": "잘 풀리고 있나요, {{name}}님?",
"home.greeting.evening.0": "좋은 저녁이에요, {{name}}님.",
"home.greeting.evening.1": "쉬어갈까요, 시작할까요, {{name}}님?",
"home.greeting.evening.2": "무언가 마무리하기 좋은 때예요, {{name}}님.",
"home.greeting.night.0": "밤 시간이에요, {{name}}님?",
"home.greeting.night.1": "아직 하루가 끝나지 않았어요, {{name}}님.",
"home.greeting.night.2": "한 가지만 더, {{name}}님?",
"home.greeting.lateNight.0": "아직 여기 있네요, {{name}}님?",
"home.greeting.lateNight.1": "밤 올빼미군요, {{name}}님.",
"home.greeting.lateNight.2": "저장하는 것 잊지 마세요, {{name}}님.",
"auth.createAccountHint": "계정을 만들어 시작하세요.",
"auth.signInSystemHint": "시스템 계정으로 로그인하세요.",
"auth.setup": "설정",
@@ -33,6 +54,14 @@
"sidebar.showMore": "더 보기",
"bar.newFile": "새 파일",
"bar.newTerminal": "새 터미널",
"bar.newBrowser": "브라우저",
"browser.invalidUrl": "잘못된 URL",
"browser.proxy": "프록시",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "이 브라우저에서는 H.264 비디오 디코딩을 사용할 수 없습니다",
"browser.viewOnly": "보기 전용",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "탭 닫기",
"bar.new": "새로 만들기...",
"bar.sidebar": "사이드바",
@@ -354,6 +383,41 @@
"admin.webCcHint": "OpenAI 호환 엔드포인트 사용 (예: Perplexity Sonar, LiteLLM 프록시)",
"admin.browser": "브라우저",
"admin.browserTools": "브라우저 도구",
"admin.browserTabDefault": "브라우저 탭 기본값",
"admin.browserTabDefaultHint": "새 브라우저 및 포트 미리보기 탭의 기본 렌더러입니다.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "AI에게 웹 브라우저 접근 권한을 부여하여 페이지 탐색, 요소 클릭, 스크린샷 촬영을 가능하게 합니다.",
"admin.browserProvider": "제공자",
"admin.browserLocalCdp": "로컬 CDP",
@@ -444,6 +508,7 @@
"keyboard.newFile": "새 빈 파일 열기",
"keyboard.newTerminal": "새 터미널 세션 열기",
"keyboard.newChat": "새 AI 채팅 시작",
"keyboard.newBrowser": "새 브라우저 탭 열기",
"keyboard.closeTab": "활성 탭 닫기",
"keyboard.nextTab": "다음 탭으로 전환",
"keyboard.prevTab": "이전 탭으로 전환",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "새 파일",
"keyboard.action.newTerminal": "새 터미널",
"keyboard.action.newChat": "새 채팅",
"keyboard.action.newBrowser": "새 브라우저",
"keyboard.action.closeTab": "탭 닫기",
"keyboard.action.nextTab": "다음 탭",
"keyboard.action.prevTab": "이전 탭",
@@ -897,6 +963,8 @@
"appearance.background": "배경",
"appearance.foreground": "전경",
"appearance.uiFont": "UI 글꼴",
"appearance.widescreenMode": "와이드스크린 모드",
"appearance.expandToolDetails": "항상 활동 펼치기",
"appearance.exported": "테마를 내보냈습니다",
"appearance.exportFailed": "테마 내보내기에 실패했습니다",
"appearance.imported": "테마를 가져왔습니다",
@@ -1,5 +1,26 @@
{
"app.tagline": "Seu computador, de qualquer lugar.",
"home.greeting.superEarly.0": "Acordou cedo, {{name}}?",
"home.greeting.superEarly.1": "As horas tranquilas combinam com você, {{name}}.",
"home.greeting.superEarly.2": "Antes de o mundo acordar, {{name}}.",
"home.greeting.morning.0": "Bom dia, {{name}}.",
"home.greeting.morning.1": "Um novo começo, {{name}}.",
"home.greeting.morning.2": "Primeiro o café, depois o que vier, {{name}}.",
"home.greeting.noon.0": "Check-in do meio-dia, {{name}}.",
"home.greeting.noon.1": "Uma pausa, {{name}}?",
"home.greeting.noon.2": "Na hora certa, {{name}}.",
"home.greeting.afternoon.0": "Ainda nessa, {{name}}.",
"home.greeting.afternoon.1": "Boa tarde, {{name}}.",
"home.greeting.afternoon.2": "Está rendendo, {{name}}?",
"home.greeting.evening.0": "Boa noite, {{name}}.",
"home.greeting.evening.1": "Desacelerando ou começando, {{name}}?",
"home.greeting.evening.2": "Boa hora para terminar algo, {{name}}.",
"home.greeting.night.0": "Turno da noite, {{name}}?",
"home.greeting.night.1": "O dia ainda não acabou, {{name}}.",
"home.greeting.night.2": "Só mais uma coisa, {{name}}?",
"home.greeting.lateNight.0": "Ainda por aqui, {{name}}?",
"home.greeting.lateNight.1": "A coruja noturna apareceu, {{name}}.",
"home.greeting.lateNight.2": "Não esqueça de salvar, {{name}}.",
"auth.createAccountHint": "Crie sua conta para começar.",
"auth.signInSystemHint": "Faça login com sua conta do sistema.",
"auth.setup": "Configuração",
@@ -33,6 +54,14 @@
"sidebar.showMore": "Mostrar mais",
"bar.newFile": "Novo arquivo",
"bar.newTerminal": "Novo terminal",
"bar.newBrowser": "Navegador",
"browser.invalidUrl": "URL inválida",
"browser.proxy": "Proxy",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "A decodificação de vídeo H.264 não está disponível neste navegador",
"browser.viewOnly": "Somente visualização",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "Fechar aba",
"bar.new": "Novo...",
"bar.sidebar": "Barra lateral",
@@ -354,6 +383,41 @@
"admin.webCcHint": "Qualquer endpoint compatível com OpenAI (ex. Perplexity Sonar, proxy LiteLLM)",
"admin.browser": "Navegador",
"admin.browserTools": "Ferramentas do navegador",
"admin.browserTabDefault": "Padrão da aba Navegador",
"admin.browserTabDefaultHint": "Renderizador padrão para novas abas de Navegador e Visualização de porta.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "Dar à IA acesso a um navegador web para navegar páginas, clicar em elementos e tirar capturas de tela.",
"admin.browserProvider": "Provedor",
"admin.browserLocalCdp": "CDP local",
@@ -444,6 +508,7 @@
"keyboard.newFile": "Abrir um novo arquivo vazio",
"keyboard.newTerminal": "Abrir uma nova sessão de terminal",
"keyboard.newChat": "Iniciar um novo chat de IA",
"keyboard.newBrowser": "Abrir uma nova aba do navegador",
"keyboard.closeTab": "Fechar a aba ativa",
"keyboard.nextTab": "Mudar para a próxima aba",
"keyboard.prevTab": "Mudar para a aba anterior",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "Novo arquivo",
"keyboard.action.newTerminal": "Novo terminal",
"keyboard.action.newChat": "Novo chat",
"keyboard.action.newBrowser": "Novo navegador",
"keyboard.action.closeTab": "Fechar aba",
"keyboard.action.nextTab": "Próxima aba",
"keyboard.action.prevTab": "Aba anterior",
@@ -897,6 +963,8 @@
"appearance.background": "Plano de fundo",
"appearance.foreground": "Primeiro plano",
"appearance.uiFont": "Fonte da interface",
"appearance.widescreenMode": "Modo tela ampla",
"appearance.expandToolDetails": "Sempre expandir a atividade",
"appearance.exported": "Tema exportado",
"appearance.exportFailed": "Falha ao exportar o tema",
"appearance.imported": "Tema importado",
@@ -1,5 +1,26 @@
{
"app.tagline": "Ваш компьютер, откуда угодно.",
"home.greeting.superEarly.0": "Уже рано встали, {{name}}?",
"home.greeting.superEarly.1": "Тихие часы вам идут, {{name}}.",
"home.greeting.superEarly.2": "Пока мир не проснулся, {{name}}.",
"home.greeting.morning.0": "Доброе утро, {{name}}.",
"home.greeting.morning.1": "Новый старт, {{name}}.",
"home.greeting.morning.2": "Сначала кофе, потом всё остальное, {{name}}.",
"home.greeting.noon.0": "Полуденная проверка, {{name}}.",
"home.greeting.noon.1": "Передохнёте, {{name}}?",
"home.greeting.noon.2": "Как раз вовремя, {{name}}.",
"home.greeting.afternoon.0": "Всё ещё в деле, {{name}}.",
"home.greeting.afternoon.1": "Добрый день, {{name}}.",
"home.greeting.afternoon.2": "Есть прогресс, {{name}}?",
"home.greeting.evening.0": "Добрый вечер, {{name}}.",
"home.greeting.evening.1": "Отдыхаете или начинаете, {{name}}?",
"home.greeting.evening.2": "Хорошее время что-то закончить, {{name}}.",
"home.greeting.night.0": "Ночная смена, {{name}}?",
"home.greeting.night.1": "День ещё не закончился, {{name}}.",
"home.greeting.night.2": "Ещё одно дело, {{name}}?",
"home.greeting.lateNight.0": "Всё ещё здесь, {{name}}?",
"home.greeting.lateNight.1": "Ночная сова снова здесь, {{name}}.",
"home.greeting.lateNight.2": "Не забудьте сохранить, {{name}}.",
"auth.createAccountHint": "Создайте аккаунт, чтобы начать.",
"auth.signInSystemHint": "Войдите с помощью системной учётной записи.",
"auth.setup": "Настройка",
@@ -33,6 +54,14 @@
"sidebar.showMore": "Показать ещё",
"bar.newFile": "Новый файл",
"bar.newTerminal": "Новый терминал",
"bar.newBrowser": "Браузер",
"browser.invalidUrl": "Недопустимый URL",
"browser.proxy": "Прокси",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "Декодирование видео H.264 недоступно в этом браузере",
"browser.viewOnly": "Только просмотр",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "Закрыть вкладку",
"bar.new": "Создать...",
"bar.sidebar": "Боковая панель",
@@ -354,6 +383,41 @@
"admin.webCcHint": "Любой OpenAI-совместимый эндпоинт (напр. Perplexity Sonar, прокси LiteLLM)",
"admin.browser": "Браузер",
"admin.browserTools": "Инструменты браузера",
"admin.browserTabDefault": "Браузер по умолчанию",
"admin.browserTabDefaultHint": "Средство отображения для новых вкладок браузера и предпросмотра порта.",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "Предоставить ИИ доступ к веб-браузеру для навигации по страницам, кликов по элементам и создания скриншотов.",
"admin.browserProvider": "Провайдер",
"admin.browserLocalCdp": "Локальный CDP",
@@ -444,6 +508,7 @@
"keyboard.newFile": "Открыть новый пустой файл",
"keyboard.newTerminal": "Открыть новую сессию терминала",
"keyboard.newChat": "Начать новый ИИ-чат",
"keyboard.newBrowser": "Открыть новую вкладку браузера",
"keyboard.closeTab": "Закрыть активную вкладку",
"keyboard.nextTab": "Перейти к следующей вкладке",
"keyboard.prevTab": "Перейти к предыдущей вкладке",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "Новый файл",
"keyboard.action.newTerminal": "Новый терминал",
"keyboard.action.newChat": "Новый чат",
"keyboard.action.newBrowser": "Новый браузер",
"keyboard.action.closeTab": "Закрыть вкладку",
"keyboard.action.nextTab": "Следующая вкладка",
"keyboard.action.prevTab": "Предыдущая вкладка",
@@ -897,6 +963,8 @@
"appearance.background": "Фон",
"appearance.foreground": "Передний план",
"appearance.uiFont": "Шрифт интерфейса",
"appearance.widescreenMode": "Широкоэкранный режим",
"appearance.expandToolDetails": "Всегда разворачивать действия",
"appearance.exported": "Тема экспортирована",
"appearance.exportFailed": "Не удалось экспортировать тему",
"appearance.imported": "Тема импортирована",
@@ -1,5 +1,26 @@
{
"app.tagline": "随时随地,掌控你的电脑。",
"home.greeting.superEarly.0": "这么早就起来了,{{name}}?",
"home.greeting.superEarly.1": "安静的时光很适合你,{{name}}。",
"home.greeting.superEarly.2": "趁世界还没醒来,{{name}}。",
"home.greeting.morning.0": "早上好,{{name}}。",
"home.greeting.morning.1": "新的开始,{{name}}。",
"home.greeting.morning.2": "先喝咖啡,再做接下来的事,{{name}}。",
"home.greeting.noon.0": "中午好,{{name}}。",
"home.greeting.noon.1": "休息一下吗,{{name}}?",
"home.greeting.noon.2": "正是时候,{{name}}。",
"home.greeting.afternoon.0": "还在忙,{{name}}。",
"home.greeting.afternoon.1": "下午好,{{name}}。",
"home.greeting.afternoon.2": "进展顺利吗,{{name}}?",
"home.greeting.evening.0": "晚上好,{{name}}。",
"home.greeting.evening.1": "是在放松,还是刚开始,{{name}}?",
"home.greeting.evening.2": "是完成一件事的好时候,{{name}}。",
"home.greeting.night.0": "夜间模式,{{name}}?",
"home.greeting.night.1": "这一天还没结束,{{name}}。",
"home.greeting.night.2": "再做一件事,{{name}}?",
"home.greeting.lateNight.0": "还在这里,{{name}}?",
"home.greeting.lateNight.1": "夜猫子来了,{{name}}。",
"home.greeting.lateNight.2": "别忘了保存,{{name}}。",
"auth.createAccountHint": "创建账户以开始使用。",
"auth.signInSystemHint": "使用系统账户登录。",
"auth.setup": "初始设置",
@@ -33,6 +54,14 @@
"sidebar.showMore": "显示更多",
"bar.newFile": "新建文件",
"bar.newTerminal": "新建终端",
"bar.newBrowser": "浏览器",
"browser.invalidUrl": "无效网址",
"browser.proxy": "代理",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "此浏览器不支持 H.264 视频解码",
"browser.viewOnly": "仅查看",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "关闭标签",
"bar.new": "新建...",
"bar.sidebar": "侧边栏",
@@ -354,6 +383,41 @@
"admin.webCcHint": "使用任何 OpenAI 兼容端点(如 Perplexity Sonar、LiteLLM 代理)",
"admin.browser": "浏览器",
"admin.browserTools": "浏览器工具",
"admin.browserTabDefault": "浏览器标签页默认模式",
"admin.browserTabDefaultHint": "新建浏览器和端口预览标签页的默认渲染方式。",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "为AI提供网页浏览器访问权限,用于浏览页面、点击元素和截图。",
"admin.browserProvider": "提供者",
"admin.browserLocalCdp": "本地 CDP",
@@ -444,6 +508,7 @@
"keyboard.newFile": "打开新的空白文件",
"keyboard.newTerminal": "打开新的终端会话",
"keyboard.newChat": "开始新的 AI 聊天",
"keyboard.newBrowser": "打开新的浏览器标签页",
"keyboard.closeTab": "关闭活动标签页",
"keyboard.nextTab": "切换到下一个标签页",
"keyboard.prevTab": "切换到上一个标签页",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "新建文件",
"keyboard.action.newTerminal": "新建终端",
"keyboard.action.newChat": "新建聊天",
"keyboard.action.newBrowser": "新建浏览器",
"keyboard.action.closeTab": "关闭标签页",
"keyboard.action.nextTab": "下一个标签页",
"keyboard.action.prevTab": "上一个标签页",
@@ -897,6 +963,8 @@
"appearance.background": "背景",
"appearance.foreground": "前景",
"appearance.uiFont": "界面字体",
"appearance.widescreenMode": "宽屏模式",
"appearance.expandToolDetails": "始终展开活动",
"appearance.exported": "主题已导出",
"appearance.exportFailed": "主题导出失败",
"appearance.imported": "主题已导入",
@@ -1,5 +1,26 @@
{
"app.tagline": "隨時隨地,掌控你的電腦。",
"home.greeting.superEarly.0": "這麼早就起來了,{{name}}?",
"home.greeting.superEarly.1": "安靜的時光很適合你,{{name}}。",
"home.greeting.superEarly.2": "趁世界還沒醒來,{{name}}。",
"home.greeting.morning.0": "早安,{{name}}。",
"home.greeting.morning.1": "新的開始,{{name}}。",
"home.greeting.morning.2": "先喝咖啡,再做接下來的事,{{name}}。",
"home.greeting.noon.0": "中午好,{{name}}。",
"home.greeting.noon.1": "休息一下嗎,{{name}}?",
"home.greeting.noon.2": "正是時候,{{name}}。",
"home.greeting.afternoon.0": "還在忙,{{name}}。",
"home.greeting.afternoon.1": "午安,{{name}}。",
"home.greeting.afternoon.2": "進展順利嗎,{{name}}?",
"home.greeting.evening.0": "晚安,{{name}}。",
"home.greeting.evening.1": "是在放鬆,還是剛開始,{{name}}?",
"home.greeting.evening.2": "是完成一件事的好時候,{{name}}。",
"home.greeting.night.0": "夜間模式,{{name}}?",
"home.greeting.night.1": "這一天還沒結束,{{name}}。",
"home.greeting.night.2": "再做一件事,{{name}}?",
"home.greeting.lateNight.0": "還在這裡,{{name}}?",
"home.greeting.lateNight.1": "夜貓子來了,{{name}}。",
"home.greeting.lateNight.2": "別忘了儲存,{{name}}。",
"auth.createAccountHint": "建立帳號以開始使用。",
"auth.signInSystemHint": "使用系統帳號登入。",
"auth.setup": "初始設定",
@@ -33,6 +54,14 @@
"sidebar.showMore": "顯示更多",
"bar.newFile": "新增檔案",
"bar.newTerminal": "新增終端機",
"bar.newBrowser": "瀏覽器",
"browser.invalidUrl": "無效網址",
"browser.proxy": "代理",
"browser.chrome": "Chrome",
"browser.decoderUnavailable": "此瀏覽器不支援 H.264 影片解碼",
"browser.viewOnly": "僅檢視",
"browser.starting": "Starting Browser…",
"browser.connectionLost": "Browser connection lost",
"bar.closeTab": "關閉分頁",
"bar.new": "新增...",
"bar.sidebar": "側邊欄",
@@ -354,6 +383,41 @@
"admin.webCcHint": "使用任何 OpenAI 相容端點(如 Perplexity Sonar、LiteLLM 代理)",
"admin.browser": "瀏覽器",
"admin.browserTools": "瀏覽器工具",
"admin.browserTabDefault": "瀏覽器分頁預設模式",
"admin.browserTabDefaultHint": "新建瀏覽器與連接埠預覽分頁的預設轉譯方式。",
"admin.browserTabs": "Browser tabs",
"admin.agentBrowserTools": "Agent browser tools",
"admin.chromeProfile": "Chrome profile",
"admin.managedChrome": "Managed Chrome",
"admin.personalChrome": "Personal Chrome",
"admin.managedChromeHint": "A private Chrome profile managed by Open WebUI Computer.",
"admin.personalChromeHint": "Connect to Chrome through its CDP URL.",
"admin.personalChromeEnableDebugging": "Enable remote debugging",
"admin.personalChromeConnection": "Connection",
"admin.personalChromeConnectionHint": "When Chrome asks what to share, choose the Open WebUI Computer Browser window. Do not choose a tab or your screen.",
"admin.personalChromeKeepRunning": "Keep running",
"admin.personalChromeStopUnused": "Stop when unused",
"admin.personalChromeConnected": "Connected",
"admin.personalChromeDisconnected": "Not connected",
"admin.personalChromeLost": "Connection lost",
"admin.personalChromeConnect": "Connect",
"admin.personalChromeDisconnect": "Disconnect",
"admin.personalChromeTabs": "Browser tabs",
"admin.personalChromeUnavailable": "Could not connect to Chrome",
"admin.managedChromeData": "Browser data",
"admin.managedChromeDataHint": "Clear saved cookies and website sessions.",
"admin.advanced": "Advanced",
"admin.browserQuality": "Streaming quality",
"admin.browserQualityHint": "Capture cap preserves the current viewport aspect ratio.",
"admin.browserQualityMaxHeight": "Max height",
"admin.browserQualityMaxBitrate": "Max bitrate",
"admin.browserQualityAllowDsf2": "Allow DSF 2",
"admin.browserQualityLow": "Low",
"admin.browserQualityBalanced": "Balanced",
"admin.browserQualityCrisp": "Crisp",
"admin.managedChromeClear": "Clear",
"admin.managedChromeClearConfirm": "Clear the managed Chrome profile and close its Browser tabs?",
"admin.managedChromeCleared": "Managed Chrome data cleared",
"admin.browserHint": "為 AI 提供網頁瀏覽器存取權限,用於瀏覽頁面、點擊元素和擷取螢幕截圖。",
"admin.browserProvider": "提供者",
"admin.browserLocalCdp": "本機 CDP",
@@ -444,6 +508,7 @@
"keyboard.newFile": "開啟新的空白檔案",
"keyboard.newTerminal": "開啟新的終端機工作階段",
"keyboard.newChat": "開始新的 AI 聊天",
"keyboard.newBrowser": "開啟新的瀏覽器分頁",
"keyboard.closeTab": "關閉使用中的分頁",
"keyboard.nextTab": "切換到下一個分頁",
"keyboard.prevTab": "切換到上一個分頁",
@@ -752,6 +817,7 @@
"keyboard.action.newFile": "新增檔案",
"keyboard.action.newTerminal": "新增終端機",
"keyboard.action.newChat": "新增聊天",
"keyboard.action.newBrowser": "新增瀏覽器",
"keyboard.action.closeTab": "關閉分頁",
"keyboard.action.nextTab": "下一個分頁",
"keyboard.action.prevTab": "上一個分頁",
@@ -897,6 +963,8 @@
"appearance.background": "背景",
"appearance.foreground": "前景",
"appearance.uiFont": "介面字體",
"appearance.widescreenMode": "寬螢幕模式",
"appearance.expandToolDetails": "一律展開活動",
"appearance.exported": "主題已匯出",
"appearance.exportFailed": "主題匯出失敗",
"appearance.imported": "主題已匯入",
+446 -100
View File
@@ -17,6 +17,7 @@
*/
import { writable, derived, get } from 'svelte/store';
import { toast } from 'svelte-sonner';
import {
getPreferences,
savePreferences,
@@ -25,6 +26,7 @@ import {
saveWorkspaceState
} from '$lib/apis/state';
import { listSessions, createSession, deleteSession } from '$lib/apis/terminal';
import { createBrowserSession, deleteBrowserSession, listBrowserSessions } from '$lib/apis/browser';
import { changeLocale, i18next } from '$lib/i18n';
import { streamingChatTabs } from '$lib/stores/chat';
import { keybindings, loadKeybindings } from '$lib/stores/keybindings';
@@ -42,18 +44,27 @@ export type { AppearancePreferences, Theme, ThemeConfig };
// ── Types ───────────────────────────────────────────────────────
export interface FileSearchTarget {
line: number;
column: number;
length: number;
requestId: number;
}
export interface Tab {
id: string;
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview';
type: 'home' | 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
label: string;
filePath?: string;
edit?: boolean;
path?: string; // generic path (e.g. for chat)
sessionId?: string;
port?: number;
port?: number; // legacy preview port, migrated on load
browserSessionId?: string;
unsaved?: boolean;
permanent?: boolean;
badge?: number;
searchTarget?: FileSearchTarget;
}
export type SplitDirection = 'horizontal' | 'vertical';
@@ -92,6 +103,13 @@ export interface WorkspaceState {
fileBrowserCwd: string;
}
export interface HomeState {
groups: EditorGroup[];
activeGroupId: string;
layout: EditorLayout;
splitDirection: SplitDirection;
}
export type ToolApprovalMode = 'ask' | 'auto' | 'full';
export interface UserPreferences {
@@ -110,6 +128,10 @@ export interface UserPreferences {
showUpdateToast?: boolean; // show version update notifications (default true)
pwa?: PwaPreferences;
textScale?: number | null;
widescreenMode?: boolean;
expandToolDetails?: boolean;
homeGroup?: EditorGroup;
homeState?: HomeState;
}
// ── ID generation ───────────────────────────────────────────────
@@ -169,7 +191,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;
}
@@ -201,14 +227,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 = {
@@ -243,6 +273,18 @@ function normalizeLayout(
/** The workspace currently displayed in THIS browser tab. Null = welcome page. */
export const currentWorkspace = writable<WorkspaceState | null>(null);
export const homeState = writable<HomeState>({
groups: [
{
id: 'home',
tabs: [{ id: 'home', type: 'home', label: 'Home', permanent: true }],
activeTabId: 'home'
}
],
activeGroupId: 'home',
layout: { type: 'group', groupId: 'home' },
splitDirection: 'horizontal'
});
/** List of all workspace summaries for the sidebar. */
export const workspaceList = writable<{ path: string; name: string }[]>([]);
@@ -297,6 +339,8 @@ export const selectedModelId = writable<string>('');
export const pwaPreferences = writable<PwaPreferences>(defaultPwaPreferences);
export const themeConfig = writable<ThemeConfig | null>(null);
export const textScale = writable<number | null>(null);
export const widescreenMode = writable(false);
export const expandToolDetails = writable(false);
/** Saved workspace path order for sidebar drag-reorder. */
export const workspaceOrder = writable<string[]>([]);
@@ -314,6 +358,16 @@ export const activeTab = derived(activeGroup, ($g) =>
$g ? ($g.tabs.find((t) => t.id === $g.activeTabId) ?? null) : null
);
export const activeHomeGroup = derived(
homeState,
($state) =>
$state.groups.find((group) => group.id === $state.activeGroupId) ?? $state.groups[0] ?? null
);
export const activeHomeTab = derived(activeHomeGroup, ($group) =>
$group ? ($group.tabs.find((tab) => tab.id === $group.activeTabId) ?? null) : null
);
export const splitActive = derived(currentWorkspace, ($ws) => ($ws?.groups.length ?? 0) > 1);
// ── Compat aliases for old split-pane API ──────────────────────
@@ -381,7 +435,7 @@ function persistPreferences(): void {
appearance: {
theme: get(theme),
themeConfig: sanitizeThemeConfig(get(themeConfig)),
textScale: get(textScale) ?? undefined
textScale: get(textScale)
},
sidebarOpen: get(sidebarOpen),
sidebarWidth: get(sidebarWidth),
@@ -395,7 +449,10 @@ function persistPreferences(): void {
requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined,
showUpdateToast: get(showUpdateToastPref),
pwa: get(pwaPreferences),
textScale: get(textScale) ?? undefined
textScale: get(textScale),
widescreenMode: get(widescreenMode),
expandToolDetails: get(expandToolDetails),
homeState: get(homeState)
};
savePreferences(prefs as unknown as Record<string, unknown>).catch(() => {});
}, 300);
@@ -408,6 +465,9 @@ function subscribeForPersistence() {
currentWorkspace.subscribe(() => {
if (get(stateLoaded)) persistWorkspace();
});
homeState.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
theme.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
@@ -450,6 +510,12 @@ function subscribeForPersistence() {
textScale.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
widescreenMode.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
expandToolDetails.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
i18next.on('languageChanged', () => {
if (get(stateLoaded)) persistPreferences();
});
@@ -490,6 +556,77 @@ export async function loadPreferences(): Promise<void> {
? (prefs.textScale as number)
: null
);
if (prefs.widescreenMode !== undefined) widescreenMode.set(prefs.widescreenMode as boolean);
if (prefs.expandToolDetails !== undefined)
expandToolDetails.set(prefs.expandToolDetails as boolean);
const savedHomeGroup = prefs.homeGroup as EditorGroup | undefined;
const savedHomeState =
(prefs.homeState as HomeState | undefined) ??
(savedHomeGroup
? {
groups: [savedHomeGroup],
activeGroupId: savedHomeGroup.id,
layout: { type: 'group' as const, groupId: savedHomeGroup.id },
splitDirection: 'horizontal' as const
}
: undefined);
if (savedHomeState && Array.isArray(savedHomeState.groups)) {
const [terminalIds, browserIds] = await Promise.all([
listSessions().catch(() => []),
listBrowserSessions().catch(() => [])
]);
const aliveTerminals = new Set(terminalIds);
const aliveBrowsers = new Set(browserIds);
let groups = savedHomeState.groups
.map((group) => {
const tabs = group.tabs.filter(
(tab) =>
tab.type !== 'terminal' ||
(tab.sessionId !== undefined && aliveTerminals.has(tab.sessionId))
);
const liveTabs = tabs.filter(
(tab) =>
tab.type !== 'browser' ||
(tab.browserSessionId !== undefined && aliveBrowsers.has(tab.browserSessionId))
);
return {
...group,
tabs: liveTabs,
activeTabId: liveTabs.some((tab) => tab.id === group.activeTabId)
? group.activeTabId
: (liveTabs[0]?.id ?? '')
};
})
.filter((group) => group.tabs.length > 0);
if (!groups.length) {
groups = [
{
id: 'home',
tabs: [{ id: 'home', type: 'home', label: 'Home', permanent: true }],
activeTabId: 'home'
}
];
}
if (!groups.some((group) => group.tabs.some((tab) => tab.type === 'home'))) {
groups[0] = {
...groups[0],
tabs: [{ id: 'home', type: 'home', label: 'Home', permanent: true }, ...groups[0].tabs]
};
}
homeState.set({
groups,
activeGroupId: groups.some((group) => group.id === savedHomeState.activeGroupId)
? savedHomeState.activeGroupId
: groups[0].id,
layout: normalizeLayout(
savedHomeState.layout,
groups,
savedHomeState.splitDirection ?? 'horizontal',
0.5
),
splitDirection: savedHomeState.splitDirection ?? 'horizontal'
});
}
const pwaPrefs = prefs.pwa;
if (pwaPrefs)
pwaPreferences.set({
@@ -532,12 +669,43 @@ export async function loadWorkspace(path: string): Promise<void> {
if (wsData && wsData.groups && (wsData.groups as EditorGroup[]).length > 0) {
// Validate terminal sessions are still alive
let aliveSessions: Set<string> = new Set();
let aliveBrowserSessions: Set<string> = new Set();
try {
const sessions = await listSessions();
aliveSessions = new Set(sessions.map((s) => s.session_id));
} catch {}
try {
aliveBrowserSessions = new Set(await listBrowserSessions());
} catch {}
const ws = wsData as unknown as WorkspaceState;
ws.groups = await Promise.all(
ws.groups.map(async (group) => ({
...group,
tabs: (
await Promise.all(
group.tabs.map(async (tab) => {
if (tab.type !== 'preview' || !tab.port) return tab;
try {
const previewUrl = `http://localhost:${tab.port}/`;
const session = await createBrowserSession(previewUrl);
aliveBrowserSessions.add(session.session_id);
const { port, ...browserTab } = tab;
return {
...browserTab,
type: 'browser' as const,
label: `localhost:${port}`,
browserSessionId: session.session_id,
path: previewUrl
};
} catch {
return null;
}
})
)
).filter((tab): tab is Tab => tab !== null)
}))
);
// Remove dead terminal tabs from all groups
const cleanedGroups = ws.groups
@@ -546,6 +714,12 @@ export async function loadWorkspace(path: string): Promise<void> {
if (t.type === 'terminal' && t.sessionId && !aliveSessions.has(t.sessionId)) {
return false;
}
if (
t.type === 'browser' &&
(!t.browserSessionId || !aliveBrowserSessions.has(t.browserSessionId))
) {
return false;
}
return true;
});
const activeStillExists = filteredTabs.some((t: Tab) => t.id === g.activeTabId);
@@ -567,7 +741,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
@@ -769,10 +948,44 @@ export function reorderTabs(oldIndex: number, newIndex: number, groupId?: string
});
}
export function updateTabLabel(tabId: string, label: string): void {
const value = label.trim().slice(0, 120);
if (!value) return;
currentWorkspace.update((workspace) =>
workspace
? {
...workspace,
groups: workspace.groups.map((group) => ({
...group,
tabs: group.tabs.map((tab) => (tab.id === tabId ? { ...tab, label: value } : tab))
}))
}
: workspace
);
}
export function clearFileSearchTarget(tabId: string, requestId: number): void {
currentWorkspace.update((workspace) =>
workspace
? {
...workspace,
groups: workspace.groups.map((group) => ({
...group,
tabs: group.tabs.map((tab) =>
tab.id === tabId && tab.searchTarget?.requestId === requestId
? { ...tab, searchTarget: undefined }
: tab
)
}))
}
: workspace
);
}
export function openFileTab(
filePath: string,
targetGroupId?: string,
options: { edit?: boolean } = {}
options: { edit?: boolean; searchTarget?: FileSearchTarget } = {}
): void {
const ws = get(currentWorkspace);
if (!ws) return;
@@ -784,9 +997,13 @@ export function openFileTab(
// Reuse existing tab within this group
const existing = group.tabs.find((t) => t.type === 'file' && t.filePath === filePath);
if (existing) {
if (options.edit) {
if (options.edit || options.searchTarget) {
updateGroupTabs(gid, (tabs) => ({
tabs: tabs.map((t) => (t.id === existing.id ? { ...t, edit: true } : t)),
tabs: tabs.map((t) =>
t.id === existing.id
? { ...t, ...(options.edit ? { edit: true } : {}), searchTarget: options.searchTarget }
: t
),
activeTabId: existing.id
}));
return;
@@ -801,7 +1018,8 @@ export function openFileTab(
type: 'file',
label: name,
filePath,
edit: options.edit
edit: options.edit,
searchTarget: options.searchTarget
};
updateGroupTabs(gid, (tabs) => ({
@@ -861,7 +1079,7 @@ export async function openTerminalTab(targetGroupId?: string): Promise<void> {
}
}
export function openPreviewTab(port: number, targetGroupId?: string): void {
export async function openPreviewTab(port: number, targetGroupId?: string): Promise<void> {
const ws = get(currentWorkspace);
if (!ws) return;
@@ -870,23 +1088,44 @@ export function openPreviewTab(port: number, targetGroupId?: string): void {
if (!group) return;
// Reuse existing tab within this group
const existing = group.tabs.find((t) => t.type === 'preview' && t.port === port);
const url = `http://localhost:${port}/`;
const existing = group.tabs.find((t) => t.type === 'browser' && t.path === url);
if (existing) {
setActiveTab(existing.id, gid);
return;
}
const newTab: Tab = {
id: nextId(),
type: 'preview',
label: `localhost:${port}`,
port
};
await openBrowserTab(gid, url, `localhost:${port}`);
}
updateGroupTabs(gid, (tabs) => ({
tabs: [...tabs, newTab],
activeTabId: newTab.id
}));
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(url);
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);
toast.error(error instanceof Error ? error.message : 'Failed to open Browser');
closeTab(tabId, gid);
}
}
export function openChatTab(chatId?: string, targetGroupId?: string): void {
@@ -944,6 +1183,9 @@ export function closeTab(tabId: string, groupId?: string): void {
if (tab.type === 'terminal' && tab.sessionId) {
deleteSession(tab.sessionId);
}
if (tab.type === 'browser' && tab.browserSessionId) {
deleteBrowserSession(tab.browserSessionId);
}
// Clean up streaming indicator for closed chat tabs
if (tab.type === 'chat') {
@@ -998,7 +1240,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
};
});
@@ -1025,7 +1267,15 @@ export function setActiveTab(tabId: string, groupId?: string): void {
}
export function setActiveGroup(groupId: string): void {
currentWorkspace.update((ws) => (ws ? { ...ws, activeGroupId: groupId } : ws));
currentWorkspace.update((ws) =>
ws && ws.activeGroupId !== groupId ? { ...ws, activeGroupId: groupId } : ws
);
}
export function setHomeActiveGroup(groupId: string): void {
homeState.update((state) =>
state.activeGroupId === groupId ? state : { ...state, activeGroupId: groupId }
);
}
export function setFileBrowserCwd(cwd: string): void {
@@ -1142,6 +1392,24 @@ export function splitCurrentTab(direction?: SplitDirection): void {
});
}
export function splitHomeTab(direction?: SplitDirection): void {
homeState.update((state) => {
const group = state.groups.find((item) => item.id === state.activeGroupId);
const tab = group?.tabs.find((item) => item.id === group.activeTabId);
if (!group || !tab) return state;
const dir = direction ?? state.splitDirection;
const newTab: Tab = { ...tab, id: nextId(), permanent: false };
const newGroup: EditorGroup = { id: nextId(), tabs: [newTab], activeTabId: newTab.id };
return {
...state,
groups: [...state.groups, newGroup],
activeGroupId: newGroup.id,
layout: splitLayout(state.layout, group.id, newGroup.id, dir),
splitDirection: dir
};
});
}
/** Close an entire editor group */
export function closeGroup(groupId: string): void {
currentWorkspace.update((ws) => {
@@ -1179,42 +1447,136 @@ export function closeGroup(groupId: string): void {
});
}
/** Move a tab from one group to another */
export function moveTabToGroup(tabId: string, fromGroupId: string, toGroupId: string): void {
currentWorkspace.update((ws) => {
if (!ws) return ws;
const fromGroup = ws.groups.find((g) => g.id === fromGroupId);
if (!fromGroup) return ws;
const tab = fromGroup.tabs.find((t) => t.id === tabId);
if (!tab) return ws;
let newGroups = ws.groups.map((g) => {
if (g.id === fromGroupId) {
const newTabs = g.tabs.filter((t) => t.id !== tabId);
const newActiveId = g.activeTabId === tabId ? (newTabs[0]?.id ?? 'files') : g.activeTabId;
return { ...g, tabs: newTabs, activeTabId: newActiveId };
}
if (g.id === toGroupId) {
return { ...g, tabs: [...g.tabs, tab], activeTabId: tab.id };
}
return g;
});
// Remove empty non-primary groups
newGroups = newGroups.filter((g) => g.tabs.length > 0);
if (newGroups.length === 0) newGroups = [createDefaultGroup()];
const sourceGroupStillExists = newGroups.some((g) => g.id === fromGroupId);
const targetGroupStillExists = newGroups.some((g) => g.id === toGroupId);
export function closeHomeGroup(groupId: string): void {
homeState.update((state) => {
if (state.groups.length < 2) return state;
const closingGroup = state.groups.find((group) => group.id === groupId);
const remainingGroups = state.groups.filter((group) => group.id !== groupId);
const targetGroup =
remainingGroups.find((group) => group.id === state.activeGroupId) ?? remainingGroups[0];
if (!closingGroup || !targetGroup) return state;
const existingTabIds = new Set(targetGroup.tabs.map((tab) => tab.id));
const tabs = [
...targetGroup.tabs,
...closingGroup.tabs.filter((tab) => !existingTabIds.has(tab.id))
];
const activeTabId =
state.activeGroupId === groupId && tabs.some((tab) => tab.id === closingGroup.activeTabId)
? closingGroup.activeTabId
: targetGroup.activeTabId;
return {
...ws,
groups: newGroups,
layout: sourceGroupStillExists ? ws.layout : removeLayoutGroup(ws.layout, fromGroupId) ?? ws.layout,
activeGroupId: targetGroupStillExists ? toGroupId : newGroups[0].id
...state,
groups: remainingGroups.map((group) =>
group.id === targetGroup.id ? { ...group, tabs, activeTabId } : group
),
activeGroupId: targetGroup.id,
layout: removeLayoutGroup(state.layout, groupId) ?? { type: 'group', groupId: targetGroup.id }
};
});
}
type SplitEditorState = Pick<
WorkspaceState,
'groups' | 'activeGroupId' | 'layout' | 'splitDirection'
>;
function moveTabToGroupInState<T extends SplitEditorState>(
state: T,
tabId: string,
fromGroupId: string,
toGroupId: string,
allowPermanent: boolean
): T {
const fromGroup = state.groups.find((g) => g.id === fromGroupId);
if (!fromGroup || fromGroupId === toGroupId) return state;
const tab = fromGroup.tabs.find((t) => t.id === tabId);
if (!tab || (!allowPermanent && tab.permanent)) return state;
let newGroups = state.groups.map((g) => {
if (g.id === fromGroupId) {
const newTabs = g.tabs.filter((t) => t.id !== tabId);
const newActiveId = g.activeTabId === tabId ? (newTabs[0]?.id ?? 'files') : g.activeTabId;
return { ...g, tabs: newTabs, activeTabId: newActiveId };
}
if (g.id === toGroupId) {
return { ...g, tabs: [...g.tabs, tab], activeTabId: tab.id };
}
return g;
});
newGroups = newGroups.filter((g) => g.tabs.length > 0);
const sourceGroupStillExists = newGroups.some((g) => g.id === fromGroupId);
const targetGroupStillExists = newGroups.some((g) => g.id === toGroupId);
return {
...state,
groups: newGroups,
layout: sourceGroupStillExists
? state.layout
: (removeLayoutGroup(state.layout, fromGroupId) ?? state.layout),
activeGroupId: targetGroupStillExists ? toGroupId : newGroups[0].id
};
}
/** Move a tab from one group to another */
export function moveTabToGroup(tabId: string, fromGroupId: string, toGroupId: string): void {
currentWorkspace.update((workspace) =>
workspace ? moveTabToGroupInState(workspace, tabId, fromGroupId, toGroupId, true) : workspace
);
}
export function moveHomeTabToGroup(tabId: string, fromGroupId: string, toGroupId: string): void {
homeState.update((state) => moveTabToGroupInState(state, tabId, fromGroupId, toGroupId, true));
}
function moveTabToNewSplitInState<T extends SplitEditorState>(
state: T,
tabId: string,
fromGroupId: string,
targetGroupId: string,
direction: SplitDirection,
placement: 'before' | 'after' = 'after'
): T {
const fromGroup = state.groups.find((g) => g.id === fromGroupId);
if (!fromGroup) return state;
const tab = fromGroup.tabs.find((t) => t.id === tabId);
if (!tab || tab.permanent) return state;
const newGroup: EditorGroup = {
id: nextId(),
tabs: [tab],
activeTabId: tab.id
};
let groups = state.groups.map((g) => {
if (g.id !== fromGroupId) return g;
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
);
groups = groups.filter((g) => g.tabs.length > 0);
groups.push(newGroup);
let layout = state.layout;
if (sourceGroupRemoved) {
layout =
fromGroupId === targetGroupId
? replaceLayoutGroup(layout, fromGroupId, newGroup.id)
: (removeLayoutGroup(layout, fromGroupId) ?? layout);
}
if (!(sourceGroupRemoved && fromGroupId === targetGroupId)) {
layout = splitLayout(layout, targetGroupId, newGroup.id, direction, placement);
}
return {
...state,
groups,
activeGroupId: newGroup.id,
layout,
splitDirection: direction
};
}
export function moveTabToNewSplit(
tabId: string,
fromGroupId: string,
@@ -1222,46 +1584,23 @@ export function moveTabToNewSplit(
direction: SplitDirection,
placement: 'before' | 'after' = 'after'
): void {
currentWorkspace.update((ws) => {
if (!ws) return ws;
const fromGroup = ws.groups.find((g) => g.id === fromGroupId);
if (!fromGroup) return ws;
const tab = fromGroup.tabs.find((t) => t.id === tabId);
if (!tab || tab.permanent) return ws;
currentWorkspace.update((workspace) =>
workspace
? moveTabToNewSplitInState(workspace, tabId, fromGroupId, targetGroupId, direction, placement)
: workspace
);
}
const newGroup: EditorGroup = {
id: nextId(),
tabs: [tab],
activeTabId: tab.id
};
let groups = ws.groups.map((g) => {
if (g.id !== fromGroupId) return g;
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);
groups = groups.filter((g) => g.tabs.length > 0);
groups.push(newGroup);
let layout = ws.layout;
if (sourceGroupRemoved) {
layout =
fromGroupId === targetGroupId
? replaceLayoutGroup(layout, fromGroupId, newGroup.id)
: removeLayoutGroup(layout, fromGroupId) ?? layout;
}
if (!(sourceGroupRemoved && fromGroupId === targetGroupId)) {
layout = splitLayout(layout, targetGroupId, newGroup.id, direction, placement);
}
return {
...ws,
groups,
activeGroupId: newGroup.id,
layout,
splitDirection: direction,
splitRatio: ws.splitRatio ?? 0.5
};
});
export function moveHomeTabToNewSplit(
tabId: string,
fromGroupId: string,
targetGroupId: string,
direction: SplitDirection,
placement: 'before' | 'after' = 'after'
): void {
homeState.update((state) =>
moveTabToNewSplitInState(state, tabId, fromGroupId, targetGroupId, direction, placement)
);
}
export function setSplitDirection(direction: SplitDirection): void {
@@ -1279,6 +1618,13 @@ export function setSplitRatio(splitId: string, ratio: number): void {
);
}
export function setHomeSplitRatio(splitId: string, ratio: number): void {
homeState.update((state) => ({
...state,
layout: updateSplitRatio(state.layout, splitId, ratio)
}));
}
function updateSplitRatio(layout: EditorLayout, splitId: string, ratio: number): EditorLayout {
if (layout.type === 'group') return layout;
if (layout.id === splitId) return { ...layout, ratio: Math.max(0.2, Math.min(0.8, ratio)) };
+39 -3
View File
@@ -14,6 +14,7 @@ import { writable, get } from 'svelte/store';
import {
openUntitledFileTab,
openTerminalTab,
openBrowserTab,
closeTab,
setActiveTab,
activeGroup,
@@ -31,6 +32,7 @@ export const ACTION_IDS = [
'newFile',
'newTerminal',
'newChat',
'newBrowser',
'closeTab',
'nextTab',
'prevTab',
@@ -50,6 +52,7 @@ export const ACTION_LABELS: Record<ActionId, string> = {
newFile: 'New File',
newTerminal: 'New Terminal',
newChat: 'New Chat',
newBrowser: 'New Browser',
closeTab: 'Close Tab',
nextTab: 'Next Tab',
prevTab: 'Previous Tab',
@@ -67,6 +70,7 @@ export const DEFAULT_KEYBINDINGS: Record<ActionId, string> = {
newFile: 'Cmd+N',
newTerminal: 'Ctrl+`',
newChat: 'Cmd+Shift+O',
newBrowser: 'Cmd+Shift+B',
closeTab: 'Cmd+W',
nextTab: 'Cmd+Shift+]',
prevTab: 'Cmd+Shift+[',
@@ -241,20 +245,45 @@ export function executeAction(
toggleVoiceMemo?: () => void;
}
): boolean {
const dispatchHomeAction = (
detail:
| 'newChat'
| 'newTerminal'
| 'newBrowser'
| 'closeTab'
| 'nextTab'
| 'prevTab'
| 'toggleSplit'
) => {
if (typeof window !== 'undefined')
window.dispatchEvent(new CustomEvent('cptr:home-action', { detail }));
};
switch (action) {
case 'newFile':
openUntitledFileTab();
return true;
case 'newTerminal':
openTerminalTab();
if (get(currentWorkspace)) openTerminalTab();
else dispatchHomeAction('newTerminal');
return true;
case 'newChat':
openChatTab();
if (get(currentWorkspace)) openChatTab();
else dispatchHomeAction('newChat');
return true;
case 'newBrowser':
if (get(currentWorkspace)) void openBrowserTab();
else dispatchHomeAction('newBrowser');
return true;
case 'closeTab': {
if (!get(currentWorkspace)) {
dispatchHomeAction('closeTab');
return true;
}
const group = get(activeGroup);
if (!group) return false;
const tab = group.tabs.find((t) => t.id === group.activeTabId);
@@ -266,6 +295,10 @@ export function executeAction(
case 'nextTab':
case 'prevTab': {
if (!get(currentWorkspace)) {
dispatchHomeAction(action);
return true;
}
const g = get(activeGroup);
if (!g || g.tabs.length < 2) return true;
const visibleTabs = g.tabs.filter((t) => t.type !== 'git');
@@ -291,7 +324,10 @@ export function executeAction(
case 'toggleSplit': {
const ws = get(currentWorkspace);
if (!ws) return false;
if (!ws) {
dispatchHomeAction('toggleSplit');
return true;
}
if (get(splitActive)) {
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
if (otherGroup) closeGroup(otherGroup.id);
+2 -5
View File
@@ -4,7 +4,6 @@
import { onMount } from 'svelte';
import { page } from '$app/stores';
import Bar from '$lib/components/Bar.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import Sidebar from '$lib/components/Sidebar.svelte';
import ShortcutBar from '$lib/components/ShortcutBar.svelte';
@@ -17,6 +16,7 @@
import { Toaster, toast } from 'svelte-sonner';
import {
activeTab,
activeHomeTab,
currentWorkspace,
stateLoaded,
initState,
@@ -453,9 +453,6 @@
class="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden"
style="padding-top: env(safe-area-inset-top, 0); padding-bottom: var(--keyboard-inset-bottom, 0);"
>
{#if !$currentWorkspace && $page.url.pathname === '/'}
<Bar />
{/if}
<main class="relative flex-1 min-h-0 overflow-hidden">
{@render children()}
</main>
@@ -464,7 +461,7 @@
<GitBar />
{/if}
{#if $activeTab?.type === 'terminal'}
{#if $activeTab?.type === 'terminal' || (!$currentWorkspace && $activeHomeTab?.type === 'terminal')}
<ShortcutBar />
{/if}
</div>
+604 -188
View File
@@ -17,22 +17,33 @@
appVersion,
showChangelog,
showSearch,
pwaPreferences
pwaPreferences,
homeState,
splitHomeTab,
closeHomeGroup,
setHomeActiveGroup,
moveHomeTabToNewSplit,
moveHomeTabToGroup,
setHomeSplitRatio
} from '$lib/stores';
import type { Tab, EditorGroup, EditorLayout, SplitDirection, WorkspaceState } from '$lib/stores';
import { chatEnabled } from '$lib/stores/chat';
import { t } from '$lib/i18n';
import { session } from '$lib/session';
import { get } from 'svelte/store';
import { toast } from 'svelte-sonner';
import { getWelcome, getWorkspaceState } from '$lib/apis/state';
import { createSession } from '$lib/apis/terminal';
import { createSession, deleteSession } from '$lib/apis/terminal';
import { createBrowserSession, deleteBrowserSession } from '$lib/apis/browser';
import { createEntry, writeFile, uploadFiles as uploadFilesApi } from '$lib/apis/files';
import { getChats, type ChatInfo } from '$lib/apis/chat';
import { getChat, getChats, type ChatInfo } from '$lib/apis/chat';
import { deleteSharePayload, getSharePayload } from '$lib/intents/payloadStore';
import type { LaunchIntent, ShareBehavior, SharePayload } from '$lib/intents/types';
import FileBrowser from '$lib/components/FileBrowser.svelte';
import FileEditor from '$lib/components/FileEditor.svelte';
import GitView from '$lib/components/GitView.svelte';
import Terminal from '$lib/components/Terminal.svelte';
import PortPreview from '$lib/components/PortPreview.svelte';
import BrowserPreview from '$lib/components/BrowserPreview.svelte';
import ChatPanel from '$lib/components/chat/ChatPanel.svelte';
import DirectoryPicker from '$lib/components/DirectoryPicker.svelte';
import GroupTabBar from '$lib/components/GroupTabBar.svelte';
@@ -46,6 +57,157 @@
let pendingIntent = $state<LaunchIntent | null>(null);
let folderPickerIntent = $state<LaunchIntent | null>(null);
let folderPickerWorkspace = $state<string | null>(null);
const welcomeName = $derived($session?.display_name || $session?.username);
const greetingTime = $derived.by(() => {
const hour = new Date().getHours();
if (hour < 5) return 'lateNight';
if (hour < 7) return 'superEarly';
if (hour < 11) return 'morning';
if (hour < 13) return 'noon';
if (hour < 17) return 'afternoon';
if (hour < 21) return 'evening';
return 'night';
});
const greetingVariant = $derived(new Date().getDate() % 3);
const greetingNameMarker = '\uE000';
const activeHomeGroup = $derived(
$homeState.groups.find((group) => group.id === $homeState.activeGroupId) ?? $homeState.groups[0]
);
function updateHomeTabs(
groupId: string,
update: (tabs: Tab[]) => { tabs: Tab[]; activeTabId: string }
) {
homeState.update((state) => ({
...state,
activeGroupId: groupId,
groups: state.groups.map((group) =>
group.id === groupId ? { ...group, ...update(group.tabs) } : group
)
}));
}
function reorderHomeTabs(groupId: string, oldIndex: number, newIndex: number) {
const group = $homeState.groups.find((item) => item.id === groupId);
if (!group) return;
const tabs = [...group.tabs];
const [tab] = tabs.splice(oldIndex, 1);
if (!tab) return;
tabs.splice(newIndex, 0, tab);
updateHomeTabs(groupId, () => ({ tabs, activeTabId: group.activeTabId }));
}
function cycleHomeTab(direction: 1 | -1) {
const group = activeHomeGroup;
if (!group || group.tabs.length < 2) return;
const currentIndex = group.tabs.findIndex((tab) => tab.id === group.activeTabId);
if (currentIndex === -1) return;
const nextIndex = (currentIndex + direction + group.tabs.length) % group.tabs.length;
updateHomeTabs(group.id, (tabs) => ({ tabs, activeTabId: tabs[nextIndex].id }));
}
function toggleHomeSplit() {
if ($homeState.groups.length > 1) {
const group = $homeState.groups.find((item) => item.id !== $homeState.activeGroupId);
if (group) closeHomeGroup(group.id);
} else {
splitHomeTab();
}
}
function openHomeChat(chatId?: string, groupId = $homeState.activeGroupId) {
const group = $homeState.groups.find((item) => item.id === groupId);
if (!group) return;
const existing = group.tabs.find(
(tab) =>
tab.type === 'chat' &&
(chatId
? tab.path === chatId
: tab.path?.startsWith('new-') || tab.path?.startsWith('pending-'))
);
if (existing) {
updateHomeTabs(groupId, (tabs) => ({ tabs, activeTabId: existing.id }));
return;
}
const tab: Tab = {
id: `home-${Date.now()}`,
type: 'chat',
label: chatId ? 'Chat' : 'New Chat',
path: chatId || `new-${Date.now()}`
};
updateHomeTabs(groupId, (tabs) => ({ tabs: [...tabs, tab], activeTabId: tab.id }));
}
async function openHomeTerminal(groupId = $homeState.activeGroupId) {
try {
const session = await createSession();
const tab: Tab = {
id: `home-${Date.now()}`,
type: 'terminal',
label: 'Terminal',
sessionId: session.session_id
};
updateHomeTabs(groupId, (tabs) => ({ tabs: [...tabs, tab], activeTabId: tab.id }));
} catch (error) {
console.error('Failed to create Home terminal:', error);
}
}
async function openHomeBrowser(url?: string, groupId = $homeState.activeGroupId) {
try {
const session = await createBrowserSession(url);
const tab: Tab = {
id: `home-${Date.now()}`,
type: 'browser',
label: 'Browser',
path: url,
browserSessionId: session.session_id
};
updateHomeTabs(groupId, (tabs) => ({ tabs: [...tabs, tab], activeTabId: tab.id }));
} catch (error) {
console.error('Failed to create Home browser:', error);
toast.error(error instanceof Error ? error.message : 'Failed to open Browser');
}
}
function closeHomeTab(tabId: string, groupId = $homeState.activeGroupId) {
const group = $homeState.groups.find((item) => item.id === groupId);
if (!group) return;
const index = group.tabs.findIndex((tab) => tab.id === tabId);
const tab = group.tabs[index];
if (!tab || tab.permanent) return;
if (tab.type === 'terminal' && tab.sessionId) deleteSession(tab.sessionId);
if (tab.type === 'browser' && tab.browserSessionId) deleteBrowserSession(tab.browserSessionId);
const tabs = group.tabs.filter((item) => item.id !== tabId);
const activeTabId =
group.activeTabId === tabId
? (tabs[Math.max(0, index - 1)]?.id ?? 'home')
: group.activeTabId;
updateHomeTabs(groupId, () => ({ tabs, activeTabId }));
if (!tabs.length) closeHomeGroup(groupId);
}
function updateHomeChatTab(
tabId: string,
chatId: string,
label: string,
groupId = $homeState.activeGroupId
) {
const group = $homeState.groups.find((item) => item.id === groupId);
if (!group) return;
updateHomeTabs(groupId, (tabs) => ({
tabs: tabs.map((tab) => (tab.id === tabId ? { ...tab, path: chatId, label } : tab)),
activeTabId: group.activeTabId
}));
}
function updateHomeBrowserTab(tabId: string, label: string, groupId = $homeState.activeGroupId) {
const group = $homeState.groups.find((item) => item.id === groupId);
if (!group) return;
updateHomeTabs(groupId, (tabs) => ({
tabs: tabs.map((tab) => (tab.id === tabId ? { ...tab, label } : tab)),
activeTabId: group.activeTabId
}));
}
const INTENT_URL_KEYS = [
'intent',
'chatId',
@@ -187,16 +349,33 @@
await createNote(targetWorkspace!);
break;
case 'newChat':
openChatTab();
if (targetWorkspace) openChatTab();
else openHomeChat();
break;
case 'newTerminal':
await openTerminalTab();
if (targetWorkspace) await openTerminalTab();
else await openHomeTerminal();
break;
case 'search':
showSearch.set(true);
break;
case 'openChat':
openChatTab(intent.chatId ?? undefined);
if (targetWorkspace) {
openChatTab(intent.chatId ?? undefined);
} else if (intent.chatId) {
const chat = await getChat(intent.chatId).catch(() => null);
const chatWorkspace = chat?.chat.meta?.workspace;
if (typeof chatWorkspace === 'string' && chatWorkspace) {
addWorkspace(chatWorkspace);
await goto(
`/?workspace=${encodeURIComponent(chatWorkspace)}&chatId=${encodeURIComponent(intent.chatId)}`
);
} else {
openHomeChat(intent.chatId);
}
} else {
openHomeChat();
}
break;
case 'openFile':
if (intent.filePath) openFileTab(intent.filePath);
@@ -214,7 +393,7 @@
}
function intentNeedsExplicitWorkspace(kind: LaunchIntent['kind']): boolean {
return !['openWorkspace', 'search'].includes(kind);
return ['newNote', 'openFile', 'openDir', 'share', 'importFiles'].includes(kind);
}
async function createNote(workspacePath: string, content = '') {
@@ -367,6 +546,54 @@
});
});
$effect(() => {
if (typeof window === 'undefined') return;
const handleHomeAction = (event: Event) => {
if ($currentWorkspace) return;
switch (
(
event as CustomEvent<
| 'newChat'
| 'newTerminal'
| 'newBrowser'
| 'closeTab'
| 'nextTab'
| 'prevTab'
| 'toggleSplit'
>
).detail
) {
case 'newChat':
openHomeChat();
break;
case 'newBrowser':
void openHomeBrowser();
break;
case 'closeTab':
if (
activeHomeGroup &&
!activeHomeGroup.tabs.find((tab) => tab.id === activeHomeGroup.activeTabId)?.permanent
) {
closeHomeTab(activeHomeGroup.activeTabId, activeHomeGroup.id);
}
break;
case 'nextTab':
cycleHomeTab(1);
break;
case 'prevTab':
cycleHomeTab(-1);
break;
case 'toggleSplit':
toggleHomeSplit();
break;
default:
void openHomeTerminal();
}
};
window.addEventListener('cptr:home-action', handleHomeAction);
return () => window.removeEventListener('cptr:home-action', handleHomeAction);
});
// Welcome page data
let welcomeData = $state<{
hostname: string;
@@ -465,11 +692,11 @@
): WorkspaceResume {
const tabs = (state.groups ?? []).flatMap((group) => group.tabs ?? []);
const previewPorts = tabs
.filter((tab) => tab.type === 'preview' && tab.port)
.map((tab) => tab.port!)
.filter((tab) => tab.type === 'browser' && /^localhost:\d+$/.test(tab.label))
.map((tab) => Number(tab.label.slice('localhost:'.length)))
.filter((port, index, all) => all.indexOf(port) === index);
const activeLabels = tabs
.filter((tab) => !tab.permanent && ['terminal', 'chat', 'preview', 'file'].includes(tab.type))
.filter((tab) => !tab.permanent && ['terminal', 'chat', 'browser', 'file'].includes(tab.type))
.slice(0, 3)
.map((tab) => tab.label);
@@ -588,10 +815,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);
}
@@ -605,7 +839,8 @@
} else {
ratio = (e.clientY - rect.top) / rect.height;
}
setSplitRatio(resizingSplit.splitId, ratio);
if ($currentWorkspace) setSplitRatio(resizingSplit.splitId, ratio);
else setHomeSplitRatio(resizingSplit.splitId, ratio);
}
function handleDividerPointerUp() {
@@ -723,7 +958,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;
}
}
@@ -749,162 +987,301 @@
const direction: SplitDirection =
zone === 'left' || zone === 'right' ? 'horizontal' : 'vertical';
const placement = zone === 'left' || zone === 'top' ? 'before' : 'after';
moveTabToNewSplit(payload.tabId, payload.groupId, targetGroupId, direction, placement);
if ($currentWorkspace) {
moveTabToNewSplit(payload.tabId, payload.groupId, targetGroupId, direction, placement);
} else {
moveHomeTabToNewSplit(payload.tabId, payload.groupId, targetGroupId, direction, placement);
}
dragOverZone = null;
}
</script>
{#if !$currentWorkspace}
<div class="flex h-full items-center justify-center overflow-y-auto p-6">
<div class="w-full max-w-md">
<div class="mb-5">
<div class="flex items-baseline gap-2">
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white">
Computer
</h1>
{#if $appVersion}
<button
onclick={() => showChangelog.set(true)}
class="cursor-pointer font-mono text-[0.6875rem] text-gray-400 hover:text-gray-500 hover:underline dark:text-gray-600 dark:hover:text-gray-400"
>
v{$appVersion}
</button>
{/if}
</div>
{#if welcomeData?.hostname}
<p class="mt-0.5 font-mono text-xs text-gray-400 dark:text-gray-600">
{welcomeData.hostname}
</p>
{#snippet renderHomePane(homePane: EditorGroup)}
{@const homeTab =
homePane.tabs.find((tab) => tab.id === homePane.activeTabId) ?? homePane.tabs[0]}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="split-pane"
onpointerdown={() => setHomeActiveGroup(homePane.id)}
onfocusin={() => setHomeActiveGroup(homePane.id)}
ondragover={(event) => handlePaneDragOver(event, homePane.id)}
ondragleave={(event) => handlePaneDragLeave(event, homePane.id)}
ondrop={(event) => handlePaneDrop(event, homePane.id)}
>
<GroupTabBar
group={homePane}
home
isPrimary={homePane.id === $homeState.groups[0]?.id}
canClose={$homeState.groups.length > 1}
homeActive={homePane.id === $homeState.activeGroupId}
homeSplitActive={$homeState.groups.length > 1}
homeSplitDirection={$homeState.splitDirection}
onHomeSelect={(tabId) =>
updateHomeTabs(homePane.id, (tabs) => ({ tabs, activeTabId: tabId }))}
onHomeClose={(tabId) => closeHomeTab(tabId, homePane.id)}
onHomeReorder={(oldIndex, newIndex) => reorderHomeTabs(homePane.id, oldIndex, newIndex)}
onHomeMove={(tabId, fromGroupId) => moveHomeTabToGroup(tabId, fromGroupId, homePane.id)}
onHomeNewChat={() => openHomeChat(undefined, homePane.id)}
onHomeNewTerminal={() => openHomeTerminal(homePane.id)}
onHomeNewBrowser={() => openHomeBrowser(undefined, homePane.id)}
onHomeSplit={(direction) => {
setHomeActiveGroup(homePane.id);
splitHomeTab(direction);
}}
onHomeCloseGroup={() => closeHomeGroup(homePane.id)}
onTabDragOver={() => {
if (dragOverZone?.groupId === homePane.id) dragOverZone = null;
}}
/>
<div class="pane-content">
{#if homeTab?.type === 'home'}
<div class="h-full overflow-y-auto px-6">
<div class="mx-auto flex min-h-full w-full max-w-md flex-col justify-center py-6">
<div class="mb-5">
<div class="flex items-baseline gap-2">
<h1 class="text-lg font-medium tracking-tight text-gray-900 dark:text-white">
{#if welcomeName}
{@const greeting = $t(`home.greeting.${greetingTime}.${greetingVariant}`, {
name: greetingNameMarker
})}
{@const [beforeName, afterName] = greeting.split(greetingNameMarker)}
{beforeName}<span class="capitalize">{welcomeName}</span>{afterName}
{:else}
Computer
{/if}
</h1>
</div>
<div
class="mt-0.5 flex items-baseline gap-2 font-mono text-xs text-gray-400 dark:text-gray-600"
>
{#if welcomeData?.hostname}
<span class="text-[0.6875rem]">{welcomeData.hostname}</span>
{/if}
{#if $appVersion}
<button
onclick={() => showChangelog.set(true)}
class="cursor-pointer text-[0.6875rem] hover:text-gray-500 hover:underline dark:hover:text-gray-400"
>
v{$appVersion}
</button>
{/if}
</div>
</div>
<div class="mb-5">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
{$t('home.start')}
</h2>
<button
class="text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
onclick={() => (showPicker = true)}
>
{$t('home.openWorkspace')}
</button>
{#if $chatEnabled}
<button
class="mt-1.5 block text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
onclick={() => openHomeChat(undefined, homePane.id)}
>
{$t('bar.newChat')}
</button>
{/if}
</div>
{#if continuation}
<div class="mb-5">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
{$t('home.continue')}
</h2>
<button
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
onclick={() => quickOpen(continuation.path)}
>
<span class="flex min-w-0 items-baseline gap-2">
<span
class="truncate text-[0.8125rem] text-gray-800 group-hover:text-gray-950 dark:text-gray-200 dark:group-hover:text-white"
>
{continuation.name}
</span>
<span
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{shortenPath(continuation.path)}
</span>
</span>
{#if continueSignals.length}
<span
class="mt-0.5 block truncate font-mono text-[0.625rem] text-gray-400 dark:text-gray-600"
>
{continueSignals.join(' ')}
</span>
{:else if continueResume?.activeLabels.length}
<span
class="mt-0.5 block truncate text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{continueResume.activeLabels.join(' · ')}
</span>
{/if}
</button>
</div>
{/if}
{#if recent.length}
<div class="mb-5">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
{$t('home.recent')}
</h2>
<div class="flex flex-col">
{#each recent as item}
{@const resume = workspaceResumes.get(item.path)}
{@const signals = resumeSignals(resume)}
<button
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
onclick={() => quickOpen(item.path)}
>
<span class="flex min-w-0 items-baseline gap-2">
<span
class="truncate text-[0.8125rem] text-gray-700 group-hover:text-gray-900 dark:text-gray-300 dark:group-hover:text-white"
>
{item.name}
</span>
<span
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{shortenPath(item.path)}
</span>
</span>
{#if signals.length}
<span
class="mt-0.5 block truncate font-mono text-[0.625rem] text-gray-400 dark:text-gray-600"
>
{signals.join(' ')}
</span>
{:else if resume?.activeLabels.length}
<span
class="mt-0.5 block truncate text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{resume.activeLabels.join(' · ')}
</span>
{/if}
</button>
{/each}
</div>
</div>
{:else if !continuation}
<div class="mb-5">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
{$t('home.recent')}
</h2>
<button
class="text-[0.8125rem] text-gray-500 transition-colors duration-100 hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
onclick={() => (showPicker = true)}
>
{$t('home.noWorkspaces')}
</button>
</div>
{/if}
{#if nearby.length && !welcomeData?.recent?.length}
<div>
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
{$t('home.folders')}
</h2>
<div class="flex flex-col">
{#each nearby as item}
<button
class="flex min-w-0 items-center gap-2 py-1.5 text-left text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
onclick={() => quickOpen(item.path)}
>
<Icon
name="folder"
size={14}
strokeWidth={1.3}
class="shrink-0 text-gray-400 dark:text-gray-600"
/>
<span class="truncate">{item.name}</span>
<span
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{shortenPath(item.path)}
</span>
</button>
{/each}
</div>
</div>
{/if}
</div>
</div>
{:else if homeTab?.type === 'chat'}
<ChatPanel
chatId={homeTab.path?.startsWith('new-') || homeTab.path?.startsWith('pending-')
? undefined
: homeTab.path}
tabId={homeTab.id}
ontabupdate={(tabId, chatId, label) =>
updateHomeChatTab(tabId, chatId, label, homePane.id)}
onopenchat={(chatId) => openHomeChat(chatId, homePane.id)}
/>
{:else if homeTab?.type === 'terminal' && homeTab.sessionId}
<Terminal sessionId={homeTab.sessionId} />
{:else if homeTab?.type === 'browser' && homeTab.browserSessionId}
<BrowserPreview
sessionId={homeTab.browserSessionId}
groupId={homePane.id}
tabId={homeTab.id}
initialUrl={homeTab.path}
onTabUpdate={(label) => updateHomeBrowserTab(homeTab.id, label, homePane.id)}
onOpenBrowser={(url) => openHomeBrowser(url, homePane.id)}
/>
{/if}
</div>
<div class="mb-6">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.start')}</h2>
<button
class="text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
onclick={() => (showPicker = true)}
>
{$t('home.openWorkspace')}
</button>
</div>
{#if continuation}
<div class="mb-6">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.continue')}</h2>
<button
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
onclick={() => quickOpen(continuation.path)}
>
<span class="flex min-w-0 items-baseline gap-2">
<span
class="truncate text-[0.8125rem] text-gray-800 group-hover:text-gray-950 dark:text-gray-200 dark:group-hover:text-white"
>
{continuation.name}
</span>
<span class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600">
{shortenPath(continuation.path)}
</span>
</span>
{#if continueSignals.length}
<span
class="mt-0.5 block truncate font-mono text-[0.625rem] text-gray-400 dark:text-gray-600"
>
{continueSignals.join(' ')}
</span>
{:else if continueResume?.activeLabels.length}
<span class="mt-0.5 block truncate text-[0.6875rem] text-gray-400 dark:text-gray-600">
{continueResume.activeLabels.join(' · ')}
</span>
{/if}
</button>
</div>
{/if}
{#if recent.length}
<div class="mb-6">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.recent')}</h2>
<div class="flex flex-col">
{#each recent as item}
{@const resume = workspaceResumes.get(item.path)}
{@const signals = resumeSignals(resume)}
<button
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
onclick={() => quickOpen(item.path)}
>
<span class="flex min-w-0 items-baseline gap-2">
<span
class="truncate text-[0.8125rem] text-gray-700 group-hover:text-gray-900 dark:text-gray-300 dark:group-hover:text-white"
>
{item.name}
</span>
<span
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{shortenPath(item.path)}
</span>
</span>
{#if signals.length}
<span
class="mt-0.5 block truncate font-mono text-[0.625rem] text-gray-400 dark:text-gray-600"
>
{signals.join(' ')}
</span>
{:else if resume?.activeLabels.length}
<span
class="mt-0.5 block truncate text-[0.6875rem] text-gray-400 dark:text-gray-600"
>
{resume.activeLabels.join(' · ')}
</span>
{/if}
</button>
{/each}
</div>
</div>
{:else if !continuation}
<div class="mb-6">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.recent')}</h2>
<button
class="text-[0.8125rem] text-gray-500 transition-colors duration-100 hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
onclick={() => (showPicker = true)}
>
{$t('home.noWorkspaces')}
</button>
</div>
{/if}
{#if nearby.length && !welcomeData?.recent?.length}
<div>
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.folders')}</h2>
<div class="flex flex-col">
{#each nearby as item}
<button
class="flex min-w-0 items-center gap-2 py-1.5 text-left text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
onclick={() => quickOpen(item.path)}
>
<Icon
name="folder"
size={14}
strokeWidth={1.3}
class="shrink-0 text-gray-400 dark:text-gray-600"
/>
<span class="truncate">{item.name}</span>
<span class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600">
{shortenPath(item.path)}
</span>
</button>
{/each}
</div>
</div>
{#if dragOverZone?.groupId === homePane.id}
<div class={`split-drop-zone split-drop-${dragOverZone.zone}`}></div>
{/if}
</div>
{/snippet}
{#snippet renderHomeLayout(node: EditorLayout)}
{#if node.type === 'group'}
{@const group = $homeState.groups.find((item) => item.id === node.groupId)}
{#if group}{@render renderHomePane(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-child" style={`flex: ${node.ratio} 1 0%;`}>
{@render renderHomeLayout(node.first)}
</div>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="split-divider"
class:split-divider-h={node.direction === 'horizontal'}
class:split-divider-v={node.direction === 'vertical'}
onpointerdown={(event) => handleDividerPointerDown(event, node)}
onpointermove={handleDividerPointerMove}
onpointerup={handleDividerPointerUp}
onpointercancel={handleDividerPointerUp}
></div>
<div class="split-branch-child" style={`flex: ${1 - node.ratio} 1 0%;`}>
{@render renderHomeLayout(node.second)}
</div>
</div>
{/if}
{/snippet}
<div class="split-container" class:is-dragging={resizingSplit !== null} role="presentation">
{#if isWideScreen}
{@render renderHomeLayout($homeState.layout)}
{:else if activeHomeGroup}
{@render renderHomePane(activeHomeGroup)}
{/if}
</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 +1295,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>
@@ -944,7 +1325,8 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="split-pane"
onclick={() => setActiveGroup(group.id)}
onpointerdown={() => setActiveGroup(group.id)}
onfocusin={() => setActiveGroup(group.id)}
ondragover={(event) => handlePaneDragOver(event, group.id)}
ondragleave={(event) => handlePaneDragLeave(event, group.id)}
ondrop={(event) => handlePaneDrop(event, group.id)}
@@ -958,34 +1340,64 @@
}}
/>
<div class="pane-content">
{#if $gitReviewOpen && group.id === allGroups[0]?.id}
<GitView />
{:else}
{#each group.tabs.filter((tab) => tab.type === 'file' && tab.filePath) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<FileEditor filePath={tab.filePath!} tabId={tab.id} edit={tab.edit === true} />
</div>
{/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} />
</div>
{/each}
{#each group.tabs.filter((tab) => tab.type === 'terminal' && tab.sessionId) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<Terminal sessionId={tab.sessionId!} />
</div>
{/each}
{#each group.tabs.filter((tab) => tab.type === 'preview' && tab.port) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<PortPreview port={tab.port!} />
</div>
{/each}
{#if !groupTab || groupTab.type === 'files'}
{#each group.tabs.filter((tab) => tab.type === 'files') as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<FileBrowser />
{:else if groupTab.type === 'terminal' && !groupTab.sessionId}
<div class="flex items-center justify-center h-full"><Spinner size={20} /></div>
{/if}
</div>
{/each}
{#each group.tabs.filter((tab) => tab.type === 'file' && tab.filePath) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<FileEditor
filePath={tab.filePath!}
tabId={tab.id}
edit={tab.edit === true}
searchTarget={tab.searchTarget}
/>
</div>
{/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}
/>
</div>
{/each}
{#each group.tabs.filter((tab) => tab.type === 'terminal' && tab.sessionId) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<Terminal sessionId={tab.sessionId!} />
</div>
{/each}
{#each group.tabs.filter((tab) => tab.type === 'browser' && tab.browserSessionId) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<BrowserPreview
sessionId={tab.browserSessionId!}
groupId={group.id}
tabId={tab.id}
initialUrl={tab.path}
active={tab.id === group.activeTabId && group.id === activeGroup?.id}
/>
</div>
{/each}
{#if !groupTab}
<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('browser.starting')}</span>
</div>
{/if}
{#if $gitReviewOpen && group.id === allGroups[0]?.id}
<div class="persisted-tab git-review-tab">
<GitView />
</div>
{/if}
</div>
{#if dragOverZone?.groupId === group.id}
@@ -1193,4 +1605,8 @@
z-index: 0;
pointer-events: none;
}
.git-review-tab {
z-index: 2;
}
</style>
@@ -0,0 +1,5 @@
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Open WebUI Computer Browser</title></head>
<body><script src="/browser-encoder.js"></script></body>
</html>
+223
View File
@@ -0,0 +1,223 @@
(() => {
const params = new URLSearchParams(location.hash.slice(1));
const windowCapture = params.get('window') === '1';
const audioEnabled = params.get('audio') === '1';
let socket;
let encoder;
let audioEncoder;
let reader;
let audioReader;
let videoTrack;
let paused = true;
let forceKeyframe = true;
let sequence = 0;
let audioSequence = 0;
let lastKeyframe = 0;
let started = false;
let configured = '';
let resolveInitialQuality;
const initialQuality = new Promise(resolve => { resolveInitialQuality = resolve; });
let quality = { bitrate: 12_000_000, frame_rate: 30, max_height: 1080 };
let lastEncodedTimestamp = -Infinity;
function sendError(error) {
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'error', message: error?.message || String(error) }));
}
}
function normalizedQuality(value) {
const bitrate = Math.max(1_000_000, Math.min(12_000_000, Number(value?.bitrate) || 12_000_000));
const frameRate = Math.max(1, Math.min(60, Number(value?.frame_rate ?? value?.fps) || 30));
const maxHeight = Math.max(240, Math.min(2160, Number(value?.max_height) || 1080));
return { bitrate: Math.round(bitrate), frame_rate: Math.round(frameRate), max_height: Math.round(maxHeight) };
}
function receiveControl(event) {
if (typeof event.data !== 'string') return;
const message = JSON.parse(event.data);
if (message.type === 'pause') paused = true;
if (message.type === 'resume') { paused = false; forceKeyframe = true; }
if (message.type === 'keyframe') forceKeyframe = true;
if (message.type === 'resize') forceKeyframe = true;
if (message.type === 'quality') {
quality = normalizedQuality(message);
resolveInitialQuality?.();
resolveInitialQuality = undefined;
configured = '';
forceKeyframe = true;
lastEncodedTimestamp = -Infinity;
}
}
function crop(frame) {
if (!windowCapture) return { x: 0, y: 0, width: frame.codedWidth, height: frame.codedHeight };
const scaleX = frame.codedWidth / Math.max(1, outerWidth);
const scaleY = frame.codedHeight / Math.max(1, outerHeight);
const width = Math.max(2, Math.min(frame.codedWidth, Math.floor(innerWidth * scaleX / 2) * 2));
const height = Math.max(2, Math.min(frame.codedHeight, Math.floor(innerHeight * scaleY / 2) * 2));
return {
x: Math.max(0, Math.floor((frame.codedWidth - width) / 2)),
y: Math.max(0, frame.codedHeight - height),
width,
height
};
}
async function configure(width, height) {
const key = `${width}x${height}:${quality.bitrate}:${quality.frame_rate}`;
if (configured === key) return;
const config = {
codec: 'avc1.42E028',
width,
height,
bitrate: quality.bitrate,
framerate: quality.frame_rate,
hardwareAcceleration: 'prefer-hardware',
latencyMode: 'realtime',
avc: { format: 'annexb' }
};
const support = await VideoEncoder.isConfigSupported(config);
if (!support.supported) throw new Error(`H.264 WebCodecs encoding is unavailable at ${width}×${height}; lower Admin > Web > Streaming quality > Advanced > Max height`);
if (encoder) {
try { await encoder.flush(); } catch {}
encoder.close();
}
encoder = new VideoEncoder({
error: sendError,
output(chunk) {
if (socket.readyState !== WebSocket.OPEN) return;
const payload = new ArrayBuffer(14 + chunk.byteLength);
const view = new DataView(payload);
view.setUint8(0, 1);
view.setUint8(1, chunk.type === 'key' ? 1 : 0);
view.setUint32(2, sequence++);
view.setBigUint64(6, BigInt(Math.max(0, chunk.timestamp)));
chunk.copyTo(new Uint8Array(payload, 14));
socket.send(payload);
}
});
encoder.configure(config);
configured = key;
socket.send(JSON.stringify({ type: 'config', codec: config.codec, width, height }));
forceKeyframe = true;
}
async function startAudio(stream) {
const track = stream.getAudioTracks()[0];
if (!track || !window.AudioEncoder) return;
const settings = track.getSettings();
const config = {
codec: 'opus',
sampleRate: settings.sampleRate || 48000,
numberOfChannels: settings.channelCount || 1,
bitrate: (settings.channelCount || 1) > 1 ? 128000 : 64000
};
const support = await AudioEncoder.isConfigSupported(config);
if (!support.supported) return;
audioEncoder = new AudioEncoder({
error() {},
output(chunk) {
if (!paused && socket.readyState === WebSocket.OPEN) {
const payload = new ArrayBuffer(14 + chunk.byteLength);
const view = new DataView(payload);
view.setUint8(0, 2);
view.setUint8(1, 0);
view.setUint32(2, audioSequence++);
view.setBigUint64(6, BigInt(Math.max(0, chunk.timestamp)));
chunk.copyTo(new Uint8Array(payload, 14));
socket.send(payload);
}
}
});
audioEncoder.configure(config);
socket.send(JSON.stringify({ type: 'audio_config', codec: config.codec, sampleRate: config.sampleRate, numberOfChannels: config.numberOfChannels }));
audioReader = new MediaStreamTrackProcessor({ track }).readable.getReader();
while (true) {
const next = await audioReader.read();
if (next.done || !next.value) break;
if (!paused && audioEncoder.encodeQueueSize <= 8) audioEncoder.encode(next.value);
next.value.close();
}
}
window.startCapture = async () => {
if (started) return;
started = true;
try {
socket = new WebSocket(`${params.get('ws')}?token=${encodeURIComponent(params.get('token') || '')}`);
socket.binaryType = 'arraybuffer';
socket.addEventListener('message', receiveControl);
const opened = new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', reject, { once: true });
});
await opened;
if (!window.VideoEncoder || !window.MediaStreamTrackProcessor) {
throw new Error('This Chrome version does not support WebCodecs tab encoding');
}
await Promise.race([initialQuality, new Promise(resolve => setTimeout(resolve, 250))]);
const stream = await navigator.mediaDevices.getDisplayMedia({
audio: audioEnabled ? { suppressLocalAudioPlayback: true } : false,
video: {
...(windowCapture ? { displaySurface: 'window' } : {}),
height: { ideal: quality.max_height, max: quality.max_height },
frameRate: { ideal: quality.frame_rate, max: quality.frame_rate }
},
preferCurrentTab: false,
...(windowCapture ? { selfBrowserSurface: 'include', surfaceSwitching: 'exclude' } : {})
});
videoTrack = stream.getVideoTracks()[0];
await videoTrack.applyConstraints({
height: { ideal: quality.max_height, max: quality.max_height },
frameRate: { ideal: quality.frame_rate, max: quality.frame_rate }
}).catch(() => {});
if (windowCapture && videoTrack.getSettings().displaySurface !== 'window') {
videoTrack.stop();
throw new Error('Select the Open WebUI Computer Browser window');
}
reader = new MediaStreamTrackProcessor({ track: videoTrack }).readable.getReader();
const first = await reader.read();
if (first.done || !first.value) throw new Error('Chrome tab capture returned no video');
let rect = crop(first.value);
await configure(rect.width, rect.height);
if (audioEnabled) void startAudio(stream);
let frame = first.value;
while (frame) {
const nextRect = crop(frame);
if (nextRect.width !== rect.width || nextRect.height !== rect.height) rect = nextRect;
const frameInterval = 1_000_000 / quality.frame_rate;
if (
!paused &&
encoder.encodeQueueSize <= 2 &&
(forceKeyframe || frame.timestamp - lastEncodedTimestamp >= frameInterval)
) {
const now = performance.now();
const keyFrame = forceKeyframe || now - lastKeyframe >= 2000;
const encoded = windowCapture
? new VideoFrame(frame, { visibleRect: rect, displayWidth: rect.width, displayHeight: rect.height })
: frame;
await configure(rect.width, rect.height);
encoder.encode(encoded, { keyFrame });
lastEncodedTimestamp = frame.timestamp;
if (encoded !== frame) encoded.close();
if (keyFrame) { forceKeyframe = false; lastKeyframe = now; }
}
frame.close();
const next = await reader.read();
frame = next.done ? null : next.value;
}
} catch (error) {
sendError(error);
throw error;
}
};
addEventListener('beforeunload', () => {
reader?.cancel();
audioReader?.cancel();
encoder?.close();
audioEncoder?.close();
});
})();
+142
View File
@@ -0,0 +1,142 @@
(() => {
const config = window.__cptrBrowser;
if (!config) return;
const prefix = `/api/browser/frame/${config.session}`;
const api = `/api/browser/sessions/${config.session}`;
const nativeFetch = window.fetch.bind(window);
const nativeWebSocket = window.WebSocket;
function remoteUrl(value = location.href) {
const url = new URL(value, location.href);
if (url.pathname === prefix) return url.searchParams.get('url') || config.url;
if (!url.pathname.startsWith(`${prefix}/`)) return config.url;
const [scheme, encodedHost, ...path] = url.pathname.slice(prefix.length + 1).split('/');
if (!scheme || !encodedHost) return config.url;
return `${scheme}://${decodeURIComponent(encodedHost)}/${path.join('/')}${url.search}${url.hash}`;
}
function proxyUrl(value, base = remoteUrl()) {
try {
const current = new URL(value, location.href);
if (current.pathname.startsWith(`${prefix}/`)) return `${current.pathname}${current.search}${current.hash}`;
const url = new URL(value, base);
if (!/^https?:$/.test(url.protocol)) return value;
return `${prefix}/${url.protocol.slice(0, -1)}/${encodeURIComponent(url.host)}${url.pathname}${url.search}${url.hash}`;
} catch {
return value;
}
}
function report() {
parent.postMessage({ type: 'cptr-browser-state', url: remoteUrl(), title: document.title }, location.origin);
}
const originalPushState = history.pushState.bind(history);
const originalReplaceState = history.replaceState.bind(history);
history.pushState = (state, title, url) => {
const result = originalPushState(state, title, url ? proxyUrl(url) : url);
queueMicrotask(report);
return result;
};
history.replaceState = (state, title, url) => {
const result = originalReplaceState(state, title, url ? proxyUrl(url) : url);
queueMicrotask(report);
return result;
};
addEventListener('popstate', report);
new MutationObserver(report).observe(document.querySelector('title') || document.head, {
childList: true,
subtree: true,
characterData: true
});
window.fetch = (input, init) => {
if (input instanceof Request) return nativeFetch(new Request(proxyUrl(input.url), input), init);
return nativeFetch(proxyUrl(input), init);
};
const open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, ...rest) {
return open.call(this, method, proxyUrl(url), ...rest);
};
window.WebSocket = function ProxyWebSocket(url, protocols) {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
const native = new nativeWebSocket(`${scheme}://${location.host}${api}/ws`);
const proxy = new EventTarget();
let state = 0;
let protocol = '';
Object.defineProperties(proxy, {
url: { value: String(url) },
readyState: { get: () => state },
protocol: { get: () => protocol },
binaryType: { get: () => native.binaryType, set: (value) => { native.binaryType = value; } },
onopen: { get: () => proxy._onopen, set: (value) => { proxy._onopen = value; } },
onmessage: { get: () => proxy._onmessage, set: (value) => { proxy._onmessage = value; } },
onclose: { get: () => proxy._onclose, set: (value) => { proxy._onclose = value; } },
onerror: { get: () => proxy._onerror, set: (value) => { proxy._onerror = value; } }
});
const emit = (type, event) => {
proxy.dispatchEvent(event);
proxy[`_on${type}`]?.call(proxy, event);
};
native.addEventListener('open', () => native.send(JSON.stringify({ url: new URL(url, remoteUrl()).href, protocols })));
native.addEventListener('message', (event) => {
if (typeof event.data === 'string') {
try {
const control = JSON.parse(event.data);
if (control.type === 'open') {
state = 1; protocol = control.protocol || ''; emit('open', new Event('open')); return;
}
} catch {}
}
emit('message', new MessageEvent('message', { data: event.data }));
});
native.addEventListener('close', (event) => { state = 3; emit('close', event); });
native.addEventListener('error', (event) => emit('error', event));
proxy.send = (data) => {
if (state !== 1) throw new DOMException('WebSocket is not open', 'InvalidStateError');
native.send(data);
};
proxy.close = (code, reason) => { state = 2; native.close(code, reason); };
return proxy;
};
window.WebSocket.prototype = nativeWebSocket.prototype;
const NativeEventSource = window.EventSource;
if (NativeEventSource) {
window.EventSource = function ProxyEventSource(url, options) {
return new NativeEventSource(proxyUrl(url), options);
};
window.EventSource.prototype = NativeEventSource.prototype;
}
document.addEventListener('click', (event) => {
const link = event.target.closest?.('a[href]');
if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const url = new URL(link.getAttribute('href'), remoteUrl());
if (!/^https?:$/.test(url.protocol)) return;
event.preventDefault();
if (link.target && link.target !== '_self') {
parent.postMessage({ type: 'cptr-browser-popup', url: url.href }, location.origin);
} else {
location.assign(proxyUrl(url.href));
}
}, true);
document.addEventListener('submit', (event) => {
const form = event.target;
if (!(form instanceof HTMLFormElement)) return;
const url = new URL(form.getAttribute('action') || remoteUrl(), remoteUrl());
if (/^https?:$/.test(url.protocol)) form.action = proxyUrl(url.href);
}, true);
const nativeOpen = window.open.bind(window);
window.open = (url, target, features) => {
if (url) parent.postMessage({ type: 'cptr-browser-popup', url: new URL(url, remoteUrl()).href }, location.origin);
return target === '_blank' ? null : nativeOpen(proxyUrl(url || remoteUrl()), target, features);
};
report();
})();
+2 -2
View File
@@ -6,6 +6,7 @@ from cptr.routers.auth import router as auth_router
from cptr.routers.automations import router as automations_router
from cptr.routers.bridge import router as bridge_router
from cptr.routers.bridge import webhook_router
from cptr.routers.browser import router as browser_router
from cptr.routers.chat import router as chat_router
from cptr.routers.gateway import router as gateway_router
from cptr.routers.events import router as events_router
@@ -14,7 +15,6 @@ from cptr.routers.git import router as git_router
from cptr.routers.images import router as images_router
from cptr.routers.memory import router as memory_router
from cptr.routers.notifications import router as notifications_router
from cptr.routers.proxy import router as proxy_router
from cptr.routers.search import router as search_router
from cptr.routers.skills import router as skills_router
from cptr.routers.state import router as state_router
@@ -27,6 +27,7 @@ __all__ = [
"auth_router",
"automations_router",
"bridge_router",
"browser_router",
"webhook_router",
"chat_router",
"events_router",
@@ -36,7 +37,6 @@ __all__ = [
"images_router",
"memory_router",
"notifications_router",
"proxy_router",
"search_router",
"skills_router",
"state_router",
+527
View File
@@ -0,0 +1,527 @@
"""Same-origin HTTP/WebSocket proxy backing Browser editor tabs."""
from __future__ import annotations
import asyncio
import json
import logging
from collections.abc import AsyncIterator
from pathlib import Path
from urllib.parse import urljoin, urlsplit, urlunsplit
import httpx
import websockets
from fastapi import APIRouter, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from cptr.routers.auth import COOKIE_NAME
from cptr.routers.admin import require_admin
from cptr.models import Config
from cptr.utils.browser.proxy import (
manager,
rewrite_css,
rewrite_html,
rewrite_javascript,
target_url,
)
from cptr.utils.browser.viewer import (
CDPConnection,
local_origin,
manager as chrome_viewer_manager,
resolve_cdp_endpoint,
)
from cptr.utils.config import AuthResult, check_access
router = APIRouter(prefix="/api/browser", tags=["browser"])
logger = logging.getLogger(__name__)
_HOP_BY_HOP = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
}
_SKIP_REQUEST_HEADERS = _HOP_BY_HOP | {
"accept-encoding",
"host",
"cookie",
"authorization",
"content-length",
}
_SKIP_RESPONSE_HEADERS = _HOP_BY_HOP | {
"content-encoding",
"content-length",
"content-security-policy",
"set-cookie",
"x-frame-options",
}
def _owner(auth: AuthResult) -> str:
return auth.user_id or auth.username or "default"
def _auth(request: Request) -> AuthResult:
auth = getattr(request.state, "auth", None)
if auth is None:
raise HTTPException(status_code=401, detail="not authenticated")
return auth
def _headers(request: Request, upstream_url: str) -> dict[str, str]:
headers = {
key: value
for key, value in request.headers.items()
if key.lower() not in _SKIP_REQUEST_HEADERS and not key.lower().startswith("x-cptr-")
}
parsed = urlsplit(upstream_url)
headers["host"] = parsed.netloc
# The proxy rewrites HTML and CSS after httpx has decoded it. Do not negotiate
# encodings a downstream browser supports but this process may not decode.
headers["accept-encoding"] = "gzip, deflate"
referer = request.headers.get("referer")
if referer and "/api/browser/frame/" in referer:
headers["referer"] = upstream_url
if request.headers.get("origin"):
headers["origin"] = f"{parsed.scheme}://{parsed.netloc}"
return headers
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
}
headers["x-cptr-browser-url"] = str(upstream.url)
return headers
def _session_payload(session) -> dict[str, object]:
return {
"session_id": session.session_id,
"url": session.url,
"title": session.title,
"mode": session.mode,
"status": session.status,
}
async def _stream_response(upstream: httpx.Response) -> AsyncIterator[bytes]:
try:
async for chunk in upstream.aiter_bytes():
yield chunk
finally:
await upstream.aclose()
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")
try:
upstream_url = target_url(url)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
body = await request.body() if request.method not in {"GET", "HEAD"} else None
upstream = None
candidates = [upstream_url]
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, ""))
)
for candidate in candidates:
try:
upstream = await client.send(
client.build_request(
request.method, candidate, headers=_headers(request, candidate), content=body
),
stream=True,
)
break
except httpx.ConnectError:
continue
if upstream is None:
raise HTTPException(status_code=502, detail=f"Cannot connect to {parsed.netloc}")
content_type = upstream.headers.get("content-type", "")
headers = _response_headers(upstream)
if content_type.startswith("text/event-stream"):
return StreamingResponse(
_stream_response(upstream),
status_code=upstream.status_code,
headers=headers,
media_type=content_type,
)
content = await upstream.aread()
await upstream.aclose()
if "text/html" in content_type or "application/xhtml" in content_type:
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, "")
)
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")
content = rewrite_html(text, final_url, session_id, final_url).encode("utf-8")
headers.pop("content-type", None)
content_type = "text/html; charset=utf-8"
elif "text/css" in content_type:
text = content.decode(upstream.encoding or "utf-8", errors="replace")
content = rewrite_css(text, upstream_url, session_id).encode("utf-8")
headers.pop("content-type", None)
content_type = "text/css; charset=utf-8"
elif parsed.hostname in {"localhost", "127.0.0.1", "::1"} and (
"javascript" in content_type or "ecmascript" in content_type
):
text = content.decode(upstream.encoding or "utf-8", errors="replace")
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
)
async def _proxy(request: Request, session_id: str, url: str) -> Response:
return await proxy_browser_request(request, session_id, url, _owner(_auth(request)))
@router.get("/availability")
async def browser_availability(request: Request):
_auth(request)
return chrome_viewer_manager.availability(await _chrome_cdp_url())
async def _chrome_cdp_url() -> str:
if await Config.get("browser.tab_chrome_source") != "personal":
return ""
return str(await Config.get("browser.cdp_url") or "").strip()
async def _personal_keep_alive() -> bool:
return await Config.get("browser.personal_keep_alive") is not False
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:
payload = await request.json()
except Exception:
payload = {}
explicit_mode = isinstance(payload, dict) and "mode" in payload
mode = (
payload.get("mode")
if explicit_mode
else "chrome"
if await Config.get("browser.tab_default_mode") == "chrome"
else "proxy"
)
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)
auth = _auth(request)
session = await manager.create(_owner(auth))
if initial_url:
await manager.update(session.session_id, session.owner, url=initial_url)
if mode == "chrome":
try:
cdp_url = await _chrome_cdp_url()
if cdp_url:
if auth.role != "admin":
raise RuntimeError("Personal Chrome is available to administrators only")
await chrome_viewer_manager.attach_personal(
session, local_origin(str(request.base_url)), cdp_url
)
else:
await chrome_viewer_manager.start(session, local_origin(str(request.base_url)))
session.mode = "chrome"
except Exception as exc:
logger.warning("Managed Chrome startup failed: %s", exc)
await manager.close(session.session_id, session.owner)
raise HTTPException(status_code=409, detail=str(exc)) from exc
return _session_payload(session)
@router.get("/runtime.js", response_class=FileResponse)
async def browser_runtime():
path = Path(__file__).parents[1] / "frontend" / "build" / "browser-runtime.js"
return FileResponse(path, media_type="text/javascript", headers={"cache-control": "no-store"})
@router.get("/sessions")
async def list_sessions(request: Request):
return {"session_ids": manager.ids(_owner(_auth(request)))}
@router.delete("/sessions/{session_id}")
async def close_session(session_id: str, request: Request):
owner = _owner(_auth(request))
if not await chrome_viewer_manager.detach_personal(
session_id, owner, await _personal_keep_alive()
):
await chrome_viewer_manager.stop(session_id, owner)
if not await manager.close(session_id, owner):
raise HTTPException(status_code=404, detail="Browser tab not found")
return {"status": "closed"}
@router.get("/sessions/{session_id}")
async def get_session(session_id: str, request: Request):
session = manager.session(session_id, _owner(_auth(request)))
if session is None:
raise HTTPException(status_code=404, detail="Browser tab expired")
return _session_payload(session)
@router.patch("/sessions/{session_id}")
async def update_session(session_id: str, request: Request):
payload = await request.json()
owner = _owner(_auth(request))
existing = manager.session(session_id, owner)
if existing is None:
raise HTTPException(status_code=404, detail="Browser tab expired")
url = str(payload["url"]) if "url" in payload else None
title = str(payload["title"])[:512] if "title" in payload else None
if url:
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise HTTPException(status_code=400, detail="Invalid Browser URL")
session = await manager.update(session_id, owner, url=url, title=title)
if session is None:
raise HTTPException(status_code=404, detail="Browser tab expired")
requested_mode = payload.get("mode")
if requested_mode is not None and requested_mode not in {"proxy", "chrome"}:
raise HTTPException(status_code=400, detail="Invalid Browser mode")
if requested_mode == "chrome" and session.mode != "chrome":
session.status = "connecting"
try:
cdp_url = await _chrome_cdp_url()
if cdp_url:
if _auth(request).role != "admin":
raise RuntimeError("Personal Chrome is available to administrators only")
await chrome_viewer_manager.attach_personal(
session, local_origin(str(request.base_url)), cdp_url
)
else:
await chrome_viewer_manager.start(session, local_origin(str(request.base_url)))
except Exception as exc:
logger.warning("Managed Chrome startup failed: %s", exc)
session.status = "ready"
raise HTTPException(status_code=409, detail=str(exc)) from exc
session.mode = "chrome"
session.status = "playing"
elif requested_mode == "proxy" and session.mode == "chrome":
if not await chrome_viewer_manager.detach_personal(
session_id, owner, await _personal_keep_alive()
):
await chrome_viewer_manager.stop(session_id, owner)
session.mode = "proxy"
session.status = "ready"
return _session_payload(session)
@router.delete("/profile")
async def clear_managed_chrome_profile(request: Request):
owner = _owner(require_admin(request))
session_ids = await chrome_viewer_manager.clear_managed_profile(owner)
for session_id in session_ids:
await manager.close(session_id, owner)
return {"status": "cleared", "closed_session_ids": session_ids}
@router.post("/cdp")
async def test_chrome_cdp(request: Request):
require_admin(request)
url = str((await request.json()).get("url", "")).strip().rstrip("/")
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise HTTPException(status_code=400, detail="Invalid CDP URL")
connection = None
try:
connection = await CDPConnection.connect(await resolve_cdp_endpoint(url))
version = await connection.send("Browser.getVersion")
except Exception as exc:
raise HTTPException(status_code=409, detail="Could not connect to Chrome") from exc
finally:
if connection:
await connection.close()
return {"browser": str(version.get("product", "Chrome"))}
@router.get("/personal")
async def personal_chrome_status(request: Request):
return chrome_viewer_manager.personal_status(_owner(require_admin(request)))
@router.post("/personal")
async def connect_personal_chrome(request: Request):
owner = _owner(require_admin(request))
try:
payload = await request.json()
except Exception:
payload = {}
cdp_url = str(payload.get("url") or await Config.get("browser.cdp_url") or "").strip()
try:
await chrome_viewer_manager.connect_personal(
owner, local_origin(str(request.base_url)), cdp_url
)
except Exception as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return chrome_viewer_manager.personal_status(owner)
@router.delete("/personal")
async def disconnect_personal_chrome(request: Request):
owner = _owner(require_admin(request))
await chrome_viewer_manager.disconnect_personal(owner)
return chrome_viewer_manager.personal_status(owner)
@router.get("/sessions/{session_id}/blank")
async def blank(session_id: str, request: Request):
if manager.session(session_id, _owner(_auth(request))) is None:
raise HTTPException(status_code=404, detail="Browser tab expired")
return HTMLResponse("<!doctype html><title>Browser</title>")
@router.api_route(
"/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))
session = manager.session(session_id, owner)
if session is None or not session.origin:
raise HTTPException(status_code=404, detail="Browser tab expired")
url = urljoin(session.origin + "/", path.lstrip("/"))
if request.url.query:
url += f"?{request.url.query}"
return await proxy_browser_request(request, session_id, url, owner)
@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)
@router.api_route(
"/frame/{session_id}/{scheme}/{host}/{path:path}",
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, "")),
)
@router.api_route(
"/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, "")))
@router.websocket("/sessions/{session_id}/ws")
async def proxy_websocket(websocket: WebSocket, session_id: str):
client_host = websocket.client.host if websocket.client else "127.0.0.1"
auth = check_access(client_host, websocket.cookies.get(COOKIE_NAME))
owner = _owner(auth) if auth else ""
if not auth or manager.session(session_id, owner) is None:
await websocket.close(code=4001, reason="unauthorized")
return
await websocket.accept()
try:
open_message = await asyncio.wait_for(websocket.receive_json(), timeout=10)
target = str(open_message.get("url", ""))
parsed = urlsplit(target)
if parsed.scheme not in {"ws", "wss"}:
await websocket.close(code=4000, reason="invalid websocket URL")
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)
)
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 ""})
async def to_upstream() -> None:
while True:
message = await websocket.receive()
if message.get("text") is not None:
await upstream.send(message["text"])
elif message.get("bytes") is not None:
await upstream.send(message["bytes"])
else:
break
async def to_client() -> None:
async for message in upstream:
if isinstance(message, bytes):
await websocket.send_bytes(message)
else:
await websocket.send_text(message)
done, pending = await asyncio.wait(
(asyncio.create_task(to_upstream()), asyncio.create_task(to_client())),
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
for task in done:
task.result()
await upstream.close()
except (WebSocketDisconnect, asyncio.TimeoutError, json.JSONDecodeError):
pass
except Exception:
await websocket.close(code=1011, reason="Browser WebSocket failed")
@router.websocket("/sessions/{session_id}/stream")
async def chrome_viewer_stream(websocket: WebSocket, session_id: str):
client_host = websocket.client.host if websocket.client else "127.0.0.1"
token = websocket.cookies.get(COOKIE_NAME) or websocket.query_params.get("token")
auth = check_access(client_host, token)
owner = _owner(auth) if auth else ""
session = manager.session(session_id, owner) if auth else None
viewer = chrome_viewer_manager.viewer_for(session_id)
if not session or session.mode != "chrome" or not viewer:
await websocket.close(code=4004, reason="Chrome Browser session not found")
return
await chrome_viewer_manager.viewer_socket(websocket, viewer, session_id)
@router.websocket("/sessions/{session_id}/encoder")
async def chrome_encoder_stream(websocket: WebSocket, session_id: str):
await chrome_viewer_manager.encoder_socket(
websocket, session_id, websocket.query_params.get("token", "")
)
+58 -28
View File
@@ -6,7 +6,6 @@ import asyncio
from copy import deepcopy
import json
import logging
from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query, Request
@@ -16,6 +15,7 @@ from cptr.models import Chat, ChatMessage, Config
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
from cptr.utils.crypto import decrypt_key
from cptr.utils.workspace import ensure_cptr_gitignored
from cptr.utils.chat_export import chat_directory
log = logging.getLogger(__name__)
@@ -34,25 +34,26 @@ def _get_user(request: Request) -> str:
return auth.user_id
# ── List chats for a workspace ──────────────────────────────
# ── List chats for a workspace or Home ──────────────────────
@router.get("")
async def list_chats(
request: Request,
workspace: str = Query(..., description="Workspace root path"),
workspace: str | None = Query(None, description="Workspace root path; omit for Home chats"),
limit: int = Query(50, ge=1, le=200, description="Max chats to return"),
offset: int = Query(0, ge=0, description="Number of chats to skip"),
sort_by: str = Query("updated_at", description="Sort field: 'title' or 'updated_at'"),
sort_dir: str = Query("desc", description="Sort direction: 'asc' or 'desc'"),
):
"""List chats for a workspace by scanning .cptr/chats/ for JSON files.
"""List chats by scanning the workspace or global chat directory.
Returns chat metadata with relative folder paths for sidebar display.
Supports pagination via limit/offset and sorting via sort_by/sort_dir.
"""
user_id = _get_user(request)
chats_dir = Path(workspace) / ".cptr" / "chats"
chats_dir = chat_directory(workspace)
if not chats_dir.exists():
return {"chats": [], "total": 0, "has_more": False}
@@ -497,6 +498,29 @@ async def _get_latest_usage_checkpoint(
# ── Delete a chat ───────────────────────────────────────────
class UpdateChatRequest(BaseModel):
title: str
@router.patch("/{chat_id}")
async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request):
"""Rename a chat."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
if not chat or chat.user_id != user_id:
raise HTTPException(404, "chat not found")
title = body.title.strip()
if not title:
raise HTTPException(422, "title cannot be empty")
await Chat.update_title(chat_id, title, now_ms())
from cptr.socket.main import emit_to_user
await emit_to_user(user_id, {"chat_id": chat_id, "title": title})
return {"ok": True, "title": title}
@router.delete("/{chat_id}")
async def delete_chat(chat_id: str, request: Request):
"""Delete a chat and all its messages."""
@@ -506,10 +530,9 @@ async def delete_chat(chat_id: str, request: Request):
raise HTTPException(404, "chat not found")
# Remove the workspace chat file.
workspace = chat.meta.get("workspace", "") if chat.meta else ""
if workspace:
chat_file = Path(workspace) / ".cptr" / "chats" / f"{chat_id}.json"
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
workspace = chat.meta.get("workspace") if chat.meta else None
chat_file = chat_directory(workspace) / f"{chat_id}.json"
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
await Chat.delete(chat_id)
return {"ok": True}
@@ -533,7 +556,9 @@ async def fork_chat(chat_id: str, request: Request, body: ForkChatRequest | None
if not messages:
raise HTTPException(400, "chat has no messages to fork")
message_by_id = {message.id: message for message in messages}
source_message_id = (body.message_id if body else None) or chat.current_message_id or messages[-1].id
source_message_id = (
(body.message_id if body else None) or chat.current_message_id or messages[-1].id
)
source_message = message_by_id.get(source_message_id)
if not source_message:
raise HTTPException(404, "message not found")
@@ -594,7 +619,7 @@ async def fork_chat(chat_id: str, request: Request, body: ForkChatRequest | None
class SendMessageRequest(BaseModel):
content: str = ""
model_id: str
workspace: str
workspace: Optional[str] = None
chat_id: Optional[str] = None
parent_id: Optional[str] = None
regeneration_prompt: Optional[str] = None
@@ -613,11 +638,18 @@ async def send_message(body: SendMessageRequest, request: Request):
"""
user_id = _get_user(request)
from cptr.utils.model_targets import AgentModelTarget, resolve_model_target
target = await resolve_model_target(body.model_id, request.app.state)
# Create or fetch chat
if body.chat_id:
chat = await Chat.get_by_id(body.chat_id)
if not chat or chat.user_id != user_id:
raise HTTPException(404, "chat not found")
workspace = (chat.meta or {}).get("workspace") or None
if not workspace and isinstance(target, AgentModelTarget):
raise HTTPException(400, "Home chats require an API model")
# Sync params into chat meta
if chat.meta is None:
chat.meta = {}
@@ -626,28 +658,27 @@ async def send_message(body: SendMessageRequest, request: Request):
chat.meta["last_model"] = body.model_id
await Chat.update_meta(chat.id, chat.meta)
else:
workspace = body.workspace or None
if not workspace and isinstance(target, AgentModelTarget):
raise HTTPException(400, "Home chats require an API model")
title = body.content[:50].strip() or "New Chat"
meta = {
"params": body.params,
"last_model": body.model_id,
}
if workspace:
meta["workspace"] = workspace
chat = await Chat.create(
user_id=user_id,
title=title,
meta={
"workspace": body.workspace,
"params": body.params,
"last_model": body.model_id,
},
meta=meta,
created_at=now_ms(),
)
# Ensure .cptr/chats/ dir exists
chats_dir = Path(body.workspace) / ".cptr" / "chats"
chats_dir = chat_directory(workspace)
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
# Auto-add .cptr to .gitignore if this is a git repo
await asyncio.to_thread(ensure_cptr_gitignored, body.workspace)
# Resolve selected model to either an API connection or an agent profile.
from cptr.utils.model_targets import resolve_model_target
target = await resolve_model_target(body.model_id, request.app.state)
if workspace:
await asyncio.to_thread(ensure_cptr_gitignored, workspace)
from cptr.utils.chat_task import (
get_pending_input_lock,
@@ -705,8 +736,7 @@ async def send_message(body: SendMessageRequest, request: Request):
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
if queued_msg:
workspace = (chat.meta or {}).get("workspace", body.workspace)
await process_pending_chat_inputs(chat.id, user_id, workspace)
await process_pending_chat_inputs(chat.id, user_id, workspace or "")
return {"chat_id": chat.id, "message_id": queued_msg.id, "queued": True}
if not assistant_msg:
@@ -721,7 +751,7 @@ async def send_message(body: SendMessageRequest, request: Request):
message_id=assistant_msg.id,
chat_id=chat.id,
user_id=user_id,
workspace=body.workspace,
workspace=workspace or "",
regeneration_prompt=body.regeneration_prompt,
target=target,
)
-286
View File
@@ -1,286 +0,0 @@
"""Reverse proxy to localhost services.
Proxies HTTP requests and WebSocket connections to 127.0.0.1:{port}
so that dev servers started in terminal sessions are accessible
from any device through the cptr UI.
The proxy path cache (shared with proxy_middleware) tracks which
request paths belong to which ports, enabling sub-resource loading
without URL rewriting.
"""
from __future__ import annotations
import asyncio
import logging
import re
import time
import httpx
from fastapi import APIRouter, Request, Response, WebSocket, WebSocketDisconnect
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/proxy", tags=["proxy"])
# ── Shared async HTTP client ────────────────────────────────────
_client: httpx.AsyncClient | None = None
def _get_client() -> httpx.AsyncClient:
global _client
if _client is None or _client.is_closed:
_client = httpx.AsyncClient(
timeout=httpx.Timeout(30.0, connect=5.0),
follow_redirects=False,
limits=httpx.Limits(max_connections=50),
)
return _client
# ── Path → port cache (used by both proxy router and middleware) ──
# Maps request paths to (port, timestamp). Populated when requests
# flow through /api/proxy/{port}/... and also by the middleware when
# it proxies sub-resources based on Referer.
proxy_path_cache: dict[str, tuple[int, float]] = {}
CACHE_TTL = 300 # seconds
def cache_path(path: str, port: int) -> None:
"""Associate a request path with a proxy port."""
proxy_path_cache[path] = (port, time.time())
# Lazy eviction: prune stale entries when cache gets large
if len(proxy_path_cache) > 2000:
now = time.time()
stale = [k for k, (_, ts) in proxy_path_cache.items() if now - ts > CACHE_TTL]
for k in stale:
proxy_path_cache.pop(k, None)
def resolve_cached_port(path: str) -> int | None:
"""Look up a port for a previously-proxied path."""
entry = proxy_path_cache.get(path)
if entry is None:
return None
port, ts = entry
if time.time() - ts > CACHE_TTL:
proxy_path_cache.pop(path, None)
return None
return port
# ── Headers ────────────────────────────────────────────────────
_HOP_BY_HOP = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
}
_SKIP_REQUEST_HEADERS = {
"host",
"connection",
"accept-encoding",
}
def _build_request_headers(request: Request, port: int) -> dict[str, str]:
"""Build headers to forward to the upstream server."""
headers = {}
for key, value in request.headers.items():
if key.lower() not in _SKIP_REQUEST_HEADERS:
headers[key] = value
headers["host"] = f"127.0.0.1:{port}"
return headers
def _build_response_headers(upstream_headers: httpx.Headers) -> dict[str, str]:
"""Build headers to return to the client, stripping hop-by-hop and frame blockers."""
headers = {}
for key, value in upstream_headers.items():
if key.lower() not in _HOP_BY_HOP:
headers[key] = value
# Remove X-Frame-Options so iframe embedding works
headers.pop("x-frame-options", None)
headers.pop("X-Frame-Options", None)
# Remove frame-ancestors from CSP
csp = headers.get("content-security-policy", "")
if "frame-ancestors" in csp:
parts = [p.strip() for p in csp.split(";") if "frame-ancestors" not in p]
if parts:
headers["content-security-policy"] = "; ".join(parts)
else:
headers.pop("content-security-policy", None)
# Drop content-length (we might not change the body, but the framework
# will set it correctly)
headers.pop("content-length", None)
headers.pop("Content-Length", None)
return headers
# ── Core proxy function (reused by middleware) ──────────────────
async def proxy_http_request(port: int, path: str, request: Request) -> Response:
"""Proxy an HTTP request to localhost:{port}/{path}.
This is the shared implementation used by both the explicit
/api/proxy/{port}/{path} route and the fallback middleware.
"""
if port < 1 or port > 65535:
return Response(content="Invalid port", status_code=400)
# Build target URL
target_url = f"http://127.0.0.1:{port}/{path}"
query = str(request.url.query) if request.url.query else ""
if query:
target_url += f"?{query}"
headers = _build_request_headers(request, port)
body = await request.body() if request.method not in ("GET", "HEAD") else None
client = _get_client()
# Try IPv4, fall back to IPv6
upstream: httpx.Response | None = None
for host in ("127.0.0.1", "[::1]"):
url = target_url if host == "127.0.0.1" else target_url.replace("127.0.0.1", "[::1]")
try:
upstream = await client.request(
method=request.method,
url=url,
headers=headers,
content=body,
follow_redirects=False,
)
break
except httpx.ConnectError:
continue
except httpx.TimeoutException:
return Response(
content=f"Timeout connecting to localhost:{port}",
status_code=504,
media_type="text/plain",
)
except Exception as e:
logger.error(f"Proxy error for port {port}: {e}")
return Response(content=f"Proxy error: {e}", status_code=502, media_type="text/plain")
if upstream is None:
return Response(
content=f"Cannot connect to localhost:{port}", status_code=502, media_type="text/plain"
)
response_headers = _build_response_headers(upstream.headers)
return Response(
content=upstream.content,
status_code=upstream.status_code,
headers=response_headers,
media_type=upstream.headers.get("content-type"),
)
# ── HTTP proxy route ────────────────────────────────────────────
@router.api_route(
"/{port}/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]
)
async def proxy_route(port: int, path: str, request: Request) -> Response:
"""Proxy an HTTP request to localhost:{port}/{path}."""
# Cache this path so the middleware can resolve sub-resources
cache_path(f"/api/proxy/{port}/{path}", port)
return await proxy_http_request(port, path, request)
# ── WebSocket proxy route ──────────────────────────────────────
@router.websocket("/{port}/ws-proxy")
@router.websocket("/{port}/ws-proxy/{path:path}")
async def proxy_websocket(websocket: WebSocket, port: int, path: str = ""):
"""Proxy a WebSocket connection to localhost:{port}/{path}.
Used for things like Vite HMR. Relays frames bidirectionally.
"""
if port < 1 or port > 65535:
await websocket.close(code=4000, reason="Invalid port")
return
await websocket.accept()
# Build upstream WS URL -- try IPv6 if IPv4 fails
query = str(websocket.url.query) if websocket.url.query else ""
qs = f"?{query}" if query else ""
upstream_ws = None
for host in ("127.0.0.1", "[::1]"):
ws_url = f"ws://{host}:{port}/{path}{qs}"
try:
import websockets
upstream_ws = await asyncio.wait_for(
websockets.connect(ws_url, additional_headers={"host": f"127.0.0.1:{port}"}),
timeout=5.0,
)
break
except Exception:
continue
if upstream_ws is None:
await websocket.close(code=4002, reason=f"Cannot connect to localhost:{port}")
return
async def client_to_upstream():
"""Relay messages from client WebSocket to upstream."""
try:
while True:
data = await websocket.receive()
if "text" in data:
await upstream_ws.send(data["text"])
elif "bytes" in data:
await upstream_ws.send(data["bytes"])
else:
break
except (WebSocketDisconnect, Exception):
pass
async def upstream_to_client():
"""Relay messages from upstream WebSocket to client."""
try:
async for msg in upstream_ws:
if isinstance(msg, str):
await websocket.send_text(msg)
elif isinstance(msg, bytes):
await websocket.send_bytes(msg)
except Exception:
pass
try:
done, pending = await asyncio.wait(
[asyncio.create_task(client_to_upstream()), asyncio.create_task(upstream_to_client())],
return_when=asyncio.FIRST_COMPLETED,
)
for t in pending:
t.cancel()
finally:
try:
await upstream_ws.close()
except Exception:
pass
try:
await websocket.close()
except Exception:
pass
+8 -2
View File
@@ -107,8 +107,9 @@ async def unified_search(
async def recent_chats(
request: Request,
limit: int = Query(9, ge=1, le=20),
workspace: Optional[str] = Query(None, description="Scope to one workspace path"),
):
"""Return most recent chats across all workspaces (for empty-query state)."""
"""Return most recent chats, optionally scoped to one workspace."""
user_id = _get_user(request)
from sqlalchemy import select
@@ -119,7 +120,12 @@ async def recent_chats(
select(Chat).where(Chat.user_id == user_id).order_by(Chat.updated_at.desc())
)
rows = list(result.scalars().all())
rows = [c for c in rows if not (c.meta or {}).get("subagent")][:limit]
rows = [
c
for c in rows
if not (c.meta or {}).get("subagent")
and (workspace is None or (c.meta or {}).get("workspace") == workspace)
][:limit]
return {
"chats": [
+3 -1
View File
@@ -30,7 +30,9 @@ class SkillResponse(BaseModel):
@router.get("", response_model=list[SkillResponse])
async def list_skills(workspace: str = Query(..., description="Workspace path")):
async def list_skills(
workspace: str = Query("", description="Workspace path; omit for global skills"),
):
"""List available skills (frontmatter only) for the $ mention picker."""
from cptr.models import Config
from cptr.utils.skills import discover_skills
+231 -1
View File
@@ -8,7 +8,9 @@ single-user model. Not safe for shared or public instances. See README.md.
from __future__ import annotations
import asyncio
import os
import json
import shutil
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
@@ -306,6 +308,7 @@ async def write_file(req: WriteFileRequest):
SEARCH_IGNORE_DIRS = {
".cptr",
".git",
"node_modules",
"__pycache__",
@@ -323,6 +326,233 @@ SEARCH_IGNORE_DIRS = {
".DS_Store",
}
MATCH_PAGE_SIZE = 100
MAX_CONTENT_MATCHES_PER_FILE = 3
MAX_CONTENT_SEARCH_FILE_SIZE = 1 * 1024 * 1024
class ContentMatch(BaseModel):
line: int
column: int
text: str
class FileMatch(BaseModel):
path: str
relative_path: str
name: str
type: str # "file" | "directory"
name_match: bool
content_matches: list[ContentMatch]
class FileMatches(BaseModel):
results: list[FileMatch]
next_offset: int | None = None
def _is_search_ignored(name: str) -> bool:
return name in SEARCH_IGNORE_DIRS or name.endswith(".egg-info")
def _walk_match_entries(root: Path, show_hidden: bool):
"""Yield visible files and directories without following symlinks."""
try:
entries = sorted(root.iterdir(), key=lambda item: item.name.lower())
except (OSError, PermissionError):
return
for item in entries:
if _is_search_ignored(item.name) or (not show_hidden and item.name.startswith(".")):
continue
try:
if item.is_symlink():
yield item, "file"
elif item.is_dir():
yield item, "directory"
yield from _walk_match_entries(item, show_hidden)
elif item.is_file():
yield item, "file"
except (OSError, PermissionError):
continue
def _match_column(text: str, query_lower: str) -> int | None:
index = text.lower().find(query_lower)
if index < 0:
return None
# CodeMirror measures columns in UTF-16 code units.
return len(text[:index].encode("utf-16-le")) // 2 + 1
def _content_match(text: str, line: int, query_lower: str) -> ContentMatch | None:
text = text.rstrip("\r\n")
column = _match_column(text, query_lower)
return ContentMatch(line=line, column=column, text=text) if column is not None else None
def _content_matches_with_rg(
root: Path, query: str, query_lower: str, show_hidden: bool, files: set[Path]
) -> tuple[dict[Path, list[ContentMatch]], bool] | None:
rg = shutil.which("rg")
if not rg:
return None
args = [
rg,
"--json",
"--no-messages",
"--fixed-strings",
"--ignore-case",
"--line-number",
"--column",
"--max-count",
str(MAX_CONTENT_MATCHES_PER_FILE + 1),
"--no-ignore",
]
if show_hidden:
args.append("--hidden")
for ignored in SEARCH_IGNORE_DIRS:
pattern = f"!{ignored}" if ignored == ".DS_Store" else f"!{ignored}/**"
args.extend(("--glob", pattern))
args.extend(("--", query, str(root)))
try:
completed = subprocess.run(args, capture_output=True, text=True, check=False)
except OSError:
return None
if completed.returncode not in (0, 1):
return None
matches: dict[Path, list[ContentMatch]] = {}
truncated = False
for raw in completed.stdout.splitlines():
try:
message = json.loads(raw)
except json.JSONDecodeError:
continue
if message.get("type") != "match":
continue
data = message["data"]
path = Path(data["path"]["text"]).resolve()
if path not in files:
continue
line_matches = matches.setdefault(path, [])
if len(line_matches) >= MAX_CONTENT_MATCHES_PER_FILE:
truncated = True
continue
match = _content_match(data["lines"]["text"], data["line_number"], query_lower)
if match:
line_matches.append(match)
return matches, truncated
def _content_matches_with_python(
files: set[Path], query_lower: str
) -> tuple[dict[Path, list[ContentMatch]], bool]:
matches: dict[Path, list[ContentMatch]] = {}
truncated = False
for path in files:
try:
if path.stat().st_size > MAX_CONTENT_SEARCH_FILE_SIZE:
continue
with path.open("rb") as source:
if b"\0" in source.read(8192):
continue
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
except (OSError, PermissionError):
continue
for number, text in enumerate(lines, start=1):
match = _content_match(text, number, query_lower)
if not match:
continue
file_matches = matches.setdefault(path, [])
if len(file_matches) >= MAX_CONTENT_MATCHES_PER_FILE:
truncated = True
break
file_matches.append(match)
return matches, truncated
def find_file_matches(
root: Path,
query: str,
show_hidden: bool = False,
offset: int = 0,
limit: int = MATCH_PAGE_SIZE,
) -> FileMatches:
"""Find filename/path and literal text matches below a browser directory."""
query = query.strip()
query_lower = query.lower()
entries = list(_walk_match_entries(root, show_hidden))
files = {path.resolve() for path, kind in entries if kind == "file" and not path.is_symlink()}
content_result = _content_matches_with_rg(root, query, query_lower, show_hidden, files)
content_matches, _ = (
content_result if content_result is not None else _content_matches_with_python(files, query_lower)
)
matches: list[tuple[int, int, FileMatch]] = []
for path, kind in entries:
relative_path = path.relative_to(root).as_posix()
name_lower = path.name.lower()
relative_lower = relative_path.lower()
if name_lower == query_lower:
score = 0
elif name_lower.startswith(query_lower):
score = 1
elif query_lower in name_lower:
score = 2
elif query_lower in relative_lower:
score = 3
else:
score = 4
path_content_matches = content_matches.get(path.resolve(), []) if kind == "file" else []
name_match = score < 4
if not name_match and not path_content_matches:
continue
matches.append(
(
score,
len(relative_path),
FileMatch(
path=str(path),
relative_path=relative_path,
name=path.name,
type=kind,
name_match=name_match,
content_matches=path_content_matches,
),
)
)
matches.sort(key=lambda item: (item[0], item[1], item[2].relative_path.lower()))
next_offset = offset + limit if offset + limit < len(matches) else None
return FileMatches(
results=[item[2] for item in matches[offset : offset + limit]],
next_offset=next_offset,
)
@router.get("/matches", response_model=FileMatches)
async def file_matches(
query: str = Query(..., description="Literal text to match"),
path: str = Query(..., description="Root path to search"),
show_hidden: bool = Query(False, description="Include dotfiles and dot-directories"),
offset: int = Query(0, ge=0, description="Result offset"),
limit: int = Query(MATCH_PAGE_SIZE, ge=1, le=MATCH_PAGE_SIZE, description="Page size"),
):
"""Return filename/path and content matches below a directory."""
if not query.strip():
raise HTTPException(status_code=400, detail="Query must not be blank")
root = Path(path).resolve()
if not root.exists() or not root.is_dir():
raise HTTPException(status_code=404, detail=f"Path not found: {path}")
return await asyncio.to_thread(find_file_matches, root, query, show_hidden, offset, limit)
class SearchResult(BaseModel):
path: str
+51 -2
View File
@@ -159,7 +159,7 @@ async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
return AgentDetection("ready", command, version, None, models)
if profile.get("agent") == "cline":
models = await _probe_cline_models(command, profile)
models = await _probe_acp_models(command, profile)
if not models:
return AgentDetection(
"auth_unknown",
@@ -170,6 +170,30 @@ async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
)
return AgentDetection("ready", command, version, None, models)
if profile.get("agent") == "gemini":
models = await _probe_acp_models(command, profile)
if not models:
return AgentDetection(
"auth_unknown",
command,
version,
"Could not discover Gemini models. Check Gemini CLI login or add models manually.",
[],
)
return AgentDetection("ready", command, version, None, models)
if profile.get("agent") == "pi":
models = await _probe_pi_models(command, profile)
if not models:
return AgentDetection(
"auth_unknown",
command,
version,
"Could not discover Pi models. Check Pi provider configuration.",
[],
)
return AgentDetection("ready", command, version, None, models)
return AgentDetection("error", command, version, "Unknown agent")
@@ -235,6 +259,31 @@ async def _probe_codex_models(command: str, profile: dict[str, Any]) -> list[str
await client.close()
async def _probe_pi_models(command: str, profile: dict[str, Any]) -> list[str] | None:
from cptr.utils.agents.pi import PiRpcClient
env = os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
client = PiRpcClient(command, os.getcwd(), env)
try:
await asyncio.wait_for(client.start(), timeout=5)
response = await asyncio.wait_for(client.request("get_available_models"), timeout=5)
data = response.get("data") if isinstance(response.get("data"), dict) else {}
models = []
for item in data.get("models", []):
if not isinstance(item, dict):
continue
provider, model = item.get("provider"), item.get("id")
if isinstance(provider, str) and provider and isinstance(model, str) and model:
models.append(f"{provider}/{model}")
return models or None
except Exception:
return None
finally:
await client.close()
async def _probe_cursor_about(command: str, profile: dict[str, Any]) -> dict[str, Any]:
env = os.environ.copy()
if profile.get("home"):
@@ -399,7 +448,7 @@ async def _probe_opencode_models(command: str, profile: dict[str, Any]) -> list[
await proc.wait()
async def _probe_cline_models(command: str, profile: dict[str, Any]) -> list[str] | None:
async def _probe_acp_models(command: str, profile: dict[str, Any]) -> list[str] | None:
from cptr.utils.agents.acp import AcpClient, acp_models_from_setup
env = os.environ.copy()
+1
View File
@@ -30,6 +30,7 @@ class AgentToolOutputDelta:
call_id: str
delta: str
stream_kind: str = "tool_output"
replace: bool = False
@dataclass
+24 -2
View File
@@ -80,10 +80,30 @@ DEFAULT_AGENT_PROFILES: list[dict[str, Any]] = [
"models": [],
"default_model": "",
},
{
"id": "gemini",
"agent": "gemini",
"name": "Gemini",
"mode": "auto",
"command": "gemini",
"home": None,
"models": [],
"default_model": "",
},
{
"id": "pi",
"agent": "pi",
"name": "Pi",
"mode": "auto",
"command": "pi",
"home": None,
"models": [],
"default_model": "",
},
]
_PROFILE_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
_VALID_AGENTS = {"codex", "claude_code", "cursor", "grok", "opencode", "cline"}
_VALID_AGENTS = {"codex", "claude_code", "cursor", "grok", "opencode", "cline", "gemini", "pi"}
_VALID_MODES = {"auto", "enabled", "disabled"}
_VALID_CODEX_APPROVAL = {"ask", "auto", "full"}
_VALID_CODEX_SANDBOX = {"read-only", "workspace-write", "danger-full-access"}
@@ -103,6 +123,8 @@ _AGENT_DEFAULTS: dict[str, dict[str, str]] = {
"grok": {"name": "Grok", "command": "grok", "model": ""},
"opencode": {"name": "OpenCode", "command": "opencode", "model": ""},
"cline": {"name": "Cline", "command": "cline", "model": ""},
"gemini": {"name": "Gemini", "command": "gemini", "model": ""},
"pi": {"name": "Pi", "command": "pi", "model": ""},
}
@@ -119,7 +141,7 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
agent = str(profile.get("agent") or "").strip()
if agent not in _VALID_AGENTS:
raise HTTPException(
400, "agent must be codex, claude_code, cursor, grok, opencode, or cline"
400, "agent must be codex, claude_code, cursor, grok, opencode, cline, gemini, or pi"
)
defaults = _AGENT_DEFAULTS[agent]
+322
View File
@@ -0,0 +1,322 @@
"""Pi coding-agent adapter using Pi's public JSONL RPC mode."""
from __future__ import annotations
import asyncio
import codecs
import collections
import json
import os
from contextlib import suppress
from typing import Any, AsyncIterator
from cptr.utils.agents.attachments import PreparedAgentAttachments
from cptr.utils.agents.events import (
AgentDone,
AgentError,
AgentEvent,
AgentReasoningDelta,
AgentTextDelta,
AgentToolOutputDelta,
AgentToolUpdate,
)
def _content_text(value: Any) -> str:
if not isinstance(value, dict) or not isinstance(value.get("content"), list):
return ""
return "\n".join(
item["text"]
for item in value["content"]
if isinstance(item, dict)
and item.get("type") == "text"
and isinstance(item.get("text"), str)
)
def _tool_name(name: str) -> str:
return "run_command" if name == "bash" else "agent_tool"
def _message_text(messages: list[dict[str, Any]], system_prompt: str, resumed: bool) -> str:
source = messages
if resumed:
source = [
next((message for message in reversed(messages) if message.get("role") == "user"), {})
]
parts = []
if system_prompt and not resumed:
parts.append(f"[system]\n{system_prompt}")
for message in source:
content = message.get("content", "")
if isinstance(content, list):
content = "\n".join(
str(block.get("text") or "") for block in content if isinstance(block, dict)
)
if content:
parts.append(f"[{message.get('role', 'user')}]\n{content}")
return "\n\n".join(parts)
def translate_event(event: dict[str, Any]) -> AgentEvent | None:
event_type = event.get("type")
if event_type == "message_update":
delta = event.get("assistantMessageEvent")
if not isinstance(delta, dict):
return None
text = delta.get("delta")
if not isinstance(text, str) or not text:
return None
if delta.get("type") == "thinking_delta":
return AgentReasoningDelta(text)
if delta.get("type") == "text_delta":
return AgentTextDelta(text)
elif event_type == "tool_execution_start":
call_id = event.get("toolCallId")
if not isinstance(call_id, str) or not call_id:
return None
raw_name = str(event.get("toolName") or "agent_tool")
args = event.get("args") if isinstance(event.get("args"), dict) else {}
arguments = {"command": args.get("command")} if raw_name == "bash" else {"input": args}
return AgentToolUpdate(call_id, "in_progress", _tool_name(raw_name), arguments)
elif event_type == "tool_execution_end":
call_id = event.get("toolCallId")
if not isinstance(call_id, str) or not call_id:
return None
return AgentToolUpdate(
call_id,
"failed" if event.get("isError") else "completed",
_tool_name(str(event.get("toolName") or "agent_tool")),
output=_content_text(event.get("result")),
)
return None
def tool_output_delta(event: dict[str, Any], sent: dict[str, str]) -> AgentToolOutputDelta | None:
"""Convert Pi's accumulated partial result into cptr's append/replace event."""
call_id = event.get("toolCallId")
if not isinstance(call_id, str) or not call_id:
return None
full = _content_text(event.get("partialResult"))
previous = sent.get(call_id, "")
replace = not full.startswith(previous)
delta = full if replace else full[len(previous) :]
sent[call_id] = full
if not delta and not replace:
return None
return AgentToolOutputDelta(
call_id,
delta,
"command_output"
if _tool_name(str(event.get("toolName") or "")) == "run_command"
else "tool_output",
replace,
)
class PiRpcClient:
"""Small stdio client for ``pi --mode rpc``."""
def __init__(self, command: str, cwd: str, env: dict[str, str], model: str = "") -> None:
self.command = command
self.cwd = cwd
self.env = env
self.model = model
self.proc: asyncio.subprocess.Process | None = None
self.reader_task: asyncio.Task[None] | None = None
self.stderr_task: asyncio.Task[None] | None = None
self.events: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
self.pending: dict[str, asyncio.Future[dict[str, Any]]] = {}
self.stderr_tail: collections.deque[str] = collections.deque(maxlen=20)
self._next_id = 0
async def start(self) -> None:
args = ["--mode", "rpc"]
if self.model and self.model != "default":
args.extend(["--model", self.model])
self.proc = await asyncio.create_subprocess_exec(
self.command,
*args,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd or os.getcwd(),
env=self.env,
)
self.reader_task = asyncio.create_task(self._read_stdout())
self.stderr_task = asyncio.create_task(self._read_stderr())
async def close(self) -> None:
if self.proc and self.proc.returncode is None:
self.proc.terminate()
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.proc.wait(), timeout=3)
if self.proc.returncode is None:
self.proc.kill()
await self.proc.wait()
for task in (self.reader_task, self.stderr_task):
if task and not task.done():
task.cancel()
with suppress(asyncio.CancelledError):
await task
self._fail_pending("Pi RPC client closed")
async def request(self, command: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
self._next_id += 1
request_id = str(self._next_id)
future: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()
self.pending[request_id] = future
await self._send({"type": command, "id": request_id, **(params or {})})
response = await asyncio.wait_for(future, timeout=30)
if not response.get("success"):
raise RuntimeError(str(response.get("error") or f"Pi {command} failed"))
return response
async def cancel_extension_dialog(self, event: dict[str, Any]) -> bool:
request_id = event.get("id")
if event.get("method") not in {"select", "confirm", "input", "editor"} or not isinstance(
request_id, str
):
return False
await self._send({"type": "extension_ui_response", "id": request_id, "cancelled": True})
return True
async def _send(self, payload: dict[str, Any]) -> None:
if not self.proc or not self.proc.stdin:
raise RuntimeError("Pi RPC process is not running")
self.proc.stdin.write(json.dumps(payload, ensure_ascii=False).encode() + b"\n")
await self.proc.stdin.drain()
async def _read_stdout(self) -> None:
assert self.proc and self.proc.stdout
decoder = codecs.getincrementaldecoder("utf-8")("replace")
buffer = ""
error = None
try:
while chunk := await self.proc.stdout.read(8192):
buffer += decoder.decode(chunk)
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
if line.rstrip("\r").strip():
await self._route(json.loads(line.rstrip("\r")))
buffer += decoder.decode(b"", final=True)
if buffer.strip():
raise RuntimeError("Pi RPC ended mid-record")
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - report malformed RPC output to the chat.
error = str(exc)
finally:
message = f"Pi RPC transport error: {error}" if error else "Pi RPC process exited"
self._fail_pending(message)
await self.events.put({"type": "process_exited", "message": message})
async def _route(self, message: dict[str, Any]) -> None:
request_id = message.get("id")
if message.get("type") == "response" and isinstance(request_id, str):
future = self.pending.pop(request_id, None)
if future and not future.done():
future.set_result(message)
return
await self.events.put(message)
async def _read_stderr(self) -> None:
assert self.proc and self.proc.stderr
while line := await self.proc.stderr.readline():
self.stderr_tail.append(line.decode(errors="replace").rstrip())
def _fail_pending(self, message: str) -> None:
for future in self.pending.values():
if not future.done():
future.set_exception(RuntimeError(message))
self.pending.clear()
def error_detail(self, message: str) -> str:
return (
f"{message}: {' | '.join(list(self.stderr_tail)[-3:])}" if self.stderr_tail else message
)
async def run_pi_agent(
*,
profile: dict[str, Any],
model: str,
workspace: str,
messages: list[dict[str, Any]],
system_prompt: str,
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
client = PiRpcClient(str(profile.get("command") or "pi"), workspace, env, model)
session_file = (resume_state or {}).get("session_file")
resumed = isinstance(session_file, str) and bool(session_file)
try:
await client.start()
if resumed:
await client.request("switch_session", {"sessionPath": session_file})
images = [
{"type": "image", "data": image.base64, "mimeType": image.mime_type}
for image in attachments.images
]
await client.request(
"prompt",
{
"message": _message_text(messages, system_prompt, resumed),
**({"images": images} if images else {}),
},
)
sent: dict[str, str] = {}
while True:
event = await asyncio.wait_for(client.events.get(), timeout=120)
if event.get("type") == "process_exited":
yield AgentError(client.error_detail(str(event.get("message") or "Pi exited")))
return
if event.get("type") == "extension_ui_request" and await client.cancel_extension_dialog(
event
):
yield AgentError(
"Pi extension requested interactive UI, which Computer does not support."
)
return
if event.get("type") == "tool_execution_update":
output = tool_output_delta(event, sent)
if output:
yield output
continue
translated = translate_event(event)
if translated:
yield translated
if event.get("type") == "agent_settled":
stats = await client.request("get_session_stats")
state = await client.request("get_state")
state_data = state.get("data") if isinstance(state.get("data"), dict) else {}
stat_data = stats.get("data") if isinstance(stats.get("data"), dict) else {}
tokens = (
stat_data.get("tokens") if isinstance(stat_data.get("tokens"), dict) else None
)
session = state_data.get("sessionFile")
yield AgentDone(
usage=tokens,
resume_state={"session_file": session}
if isinstance(session, str) and session
else None,
)
return
if event.get("type") == "extension_error":
yield AgentError(f"Pi extension error: {event.get('error') or 'unknown error'}")
return
except asyncio.CancelledError:
with suppress(Exception):
await asyncio.wait_for(client.request("abort"), timeout=2)
raise
except Exception as exc: # noqa: BLE001 - surfaced in chat.
yield AgentError(client.error_detail(str(exc)))
finally:
await client.close()
+22 -5
View File
@@ -32,16 +32,26 @@ _CHROME_PATHS_LINUX = [
"microsoft-edge",
]
_CHROME_PATHS_WINDOWS = [
("PROGRAMFILES", "Google/Chrome/Application/chrome.exe"),
("PROGRAMFILES(X86)", "Google/Chrome/Application/chrome.exe"),
("LOCALAPPDATA", "Google/Chrome/Application/chrome.exe"),
("PROGRAMFILES", "Microsoft/Edge/Application/msedge.exe"),
("PROGRAMFILES(X86)", "Microsoft/Edge/Application/msedge.exe"),
("LOCALAPPDATA", "BraveSoftware/Brave-Browser/Application/brave.exe"),
]
# Track launched process so we can kill it on shutdown
_launched_process: asyncio.subprocess.Process | None = None
_user_data_dir: str | None = None
def _find_chrome() -> str | None:
"""Find a Chrome/Chromium binary on this system."""
def find_browser() -> str | None:
"""Find a compatible Chrome-family browser without launching it."""
import platform
if platform.system() == "Darwin":
system = platform.system()
if system == "Darwin":
for path in _CHROME_PATHS_MACOS:
if Path(path).exists():
return path
@@ -50,8 +60,15 @@ def _find_chrome() -> str | None:
found = shutil.which(name)
if found:
return found
elif system == "Windows":
for env_name, suffix in _CHROME_PATHS_WINDOWS:
root = os.environ.get(env_name)
if root and (candidate := Path(root) / suffix).exists():
return str(candidate)
for name in ("chrome", "msedge", "brave"):
if found := shutil.which(name):
return found
else:
# Linux / other
for name in _CHROME_PATHS_LINUX:
found = shutil.which(name)
if found:
@@ -96,7 +113,7 @@ async def ensure_browser(port: int = 9222) -> str:
return base_url
# 2. Find Chrome binary
chrome_path = _find_chrome()
chrome_path = find_browser()
if not chrome_path:
raise RuntimeError(
"No Chrome or Chromium found. Install Google Chrome, Chromium, or Brave, "
+266
View File
@@ -0,0 +1,266 @@
"""In-memory sessions and response rewriting for the Browser proxy tab."""
from __future__ import annotations
import asyncio
import html
import re
import uuid
from dataclasses import dataclass, field
from html.parser import HTMLParser
from urllib.parse import quote, urljoin, urlsplit, urlunsplit
import httpx
_URL_ATTRIBUTES = {
"action",
"background",
"cite",
"data",
"formaction",
"href",
"poster",
"src",
}
_SKIP_SCHEMES = ("data:", "javascript:", "mailto:", "tel:", "about:", "blob:")
@dataclass
class BrowserSession:
session_id: str
owner: str
url: str = ""
title: str = ""
origin: str = ""
mode: str = "proxy"
status: str = "ready"
device_profile: dict = field(default_factory=dict)
device_mode: str = "auto"
mobile_viewport: tuple[int, int] | None = None
quality_preset: str = "balanced"
resolved_quality: dict = field(default_factory=dict)
@dataclass
class BrowserProfile:
client: httpx.AsyncClient
class BrowserProxyManager:
"""Owns ephemeral Browser tab sessions and per-user upstream cookie jars."""
def __init__(self) -> None:
self._sessions: dict[str, BrowserSession] = {}
self._profiles: dict[str, BrowserProfile] = {}
self._lock = asyncio.Lock()
async def create(self, owner: str) -> BrowserSession:
session = BrowserSession(uuid.uuid4().hex, owner)
async with self._lock:
self._sessions[session.session_id] = session
self._profile(owner)
return session
async def close(self, session_id: str, owner: str) -> bool:
async with self._lock:
session = self._sessions.get(session_id)
if not session or session.owner != owner:
return False
self._sessions.pop(session_id, None)
return True
def ids(self, owner: str) -> list[str]:
return [
session_id for session_id, session in self._sessions.items() if session.owner == owner
]
def session(self, session_id: str, owner: str) -> BrowserSession | None:
session = self._sessions.get(session_id)
return session if session and session.owner == owner else None
async def update(
self, session_id: str, owner: str, *, url: str | None = None, title: str | None = None
) -> BrowserSession | None:
async with self._lock:
session = self.session(session_id, owner)
if session is None:
return None
if url is not None:
session.url = url
parsed = urlsplit(url)
session.origin = (
f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else ""
)
if title is not None:
session.title = title
return session
def client(self, session_id: str, owner: str) -> httpx.AsyncClient | None:
session = self.session(session_id, owner)
return self._profile(session.owner).client if session else None
def _profile(self, owner: str) -> BrowserProfile:
profile = self._profiles.get(owner)
if profile is None:
profile = BrowserProfile(
httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(60.0, connect=10.0),
limits=httpx.Limits(max_connections=30),
)
)
self._profiles[owner] = profile
return profile
async def close_all(self) -> None:
clients = [profile.client for profile in self._profiles.values()]
self._sessions.clear()
self._profiles.clear()
await asyncio.gather(*(client.aclose() for client in clients), return_exceptions=True)
def proxy_path(session_id: str, url: str) -> str:
"""Return the same-origin URL used by the Browser iframe for an upstream URL."""
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("Only HTTP(S) URLs can be opened in Browser")
host = quote(parsed.netloc, safe=":[]")
path = quote(parsed.path or "/", safe="/%:@!$&'()*+,;=-._~")
query = f"?{parsed.query}" if parsed.query else ""
fragment = f"#{parsed.fragment}" if parsed.fragment else ""
return f"/api/browser/frame/{session_id}/{parsed.scheme}/{host}{path}{query}{fragment}"
def target_url(url: str) -> str:
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("Only HTTP(S) URLs can be opened in Browser")
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or "/", parsed.query, ""))
def resource_path(session_id: str, url: str) -> str:
parsed = urlsplit(url)
path = parsed.path or "/"
return f"/api/browser/resources/{session_id}{path}" + (
f"?{parsed.query}" if parsed.query else ""
)
def rewrite_url(value: str, base_url: str, session_id: str) -> str:
value = value.strip()
if not value or value.startswith("#") or value.lower().startswith(_SKIP_SCHEMES):
return value
try:
url = urljoin(base_url, value)
return proxy_path(session_id, url)
except ValueError:
return value
def _rewrite_srcset(value: str, base_url: str, session_id: str) -> str:
parts = []
for item in value.split(","):
url, *descriptor = item.strip().split(maxsplit=1)
parts.append(" ".join([rewrite_url(url, base_url, session_id), *descriptor]))
return ", ".join(parts)
class _HtmlRewriter(HTMLParser):
def __init__(self, base_url: str, session_id: str) -> None:
super().__init__(convert_charrefs=False)
self.base_url = base_url
self.session_id = session_id
self.output: list[str] = []
def handle_decl(self, decl: str) -> None:
self.output.append(f"<!{decl}>")
def handle_comment(self, data: str) -> None:
self.output.append(f"<!--{data}-->")
def handle_data(self, data: str) -> None:
self.output.append(data)
def handle_entityref(self, name: str) -> None:
self.output.append(f"&{name};")
def handle_charref(self, name: str) -> None:
self.output.append(f"&#{name};")
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self._tag(tag, attrs, close=True)
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self._tag(tag, attrs, close=False)
def _tag(self, tag: str, attrs: list[tuple[str, str | None]], close: bool) -> None:
rewritten: list[tuple[str, str | None]] = []
for key, value in attrs:
lower = key.lower()
if lower == "integrity":
continue
if value and lower in _URL_ATTRIBUTES:
value = rewrite_url(value, self.base_url, self.session_id)
elif value and lower == "srcset":
value = _rewrite_srcset(value, self.base_url, self.session_id)
elif tag.lower() == "meta" and lower == "content":
value = re.sub(
r"(?i)(url\s*=\s*)([^;]+)",
lambda match: (
match.group(1)
+ rewrite_url(match.group(2).strip(), self.base_url, self.session_id)
),
value,
)
rewritten.append((key, value))
attrs_text = "".join(
f" {key}" if value is None else f' {key}="{html.escape(value, quote=True)}"'
for key, value in rewritten
)
self.output.append(f"<{tag}{attrs_text}{' /' if close else ''}>")
def handle_endtag(self, tag: str) -> None:
self.output.append(f"</{tag}>")
def rewrite_html(content: str, base_url: str, session_id: str, final_url: str) -> str:
parser = _HtmlRewriter(base_url, session_id)
parser.feed(content)
parser.close()
runtime = (
f"<script>window.__cptrBrowser={{session:{session_id!r},url:{final_url!r}}};</script>"
'<script src="/api/browser/runtime.js"></script>'
)
rendered = "".join(parser.output)
if urlsplit(final_url).hostname in {"localhost", "127.0.0.1", "::1"}:
rendered = rewrite_javascript(rendered, final_url, session_id)
if re.search(r"<head(?:\s[^>]*)?>", rendered, re.I):
return re.sub(r"(<head(?:\s[^>]*)?>)", r"\1" + runtime, rendered, count=1, flags=re.I)
return runtime + rendered
def rewrite_css(content: str, base_url: str, session_id: str) -> str:
def replace_url(match: re.Match[str]) -> str:
quote, value = match.group(1), match.group(2)
return f"url({quote}{rewrite_url(value, base_url, session_id)}{quote})"
content = re.sub(r"url\(\s*(['\"]?)([^'\")]+)\1\s*\)", replace_url, content, flags=re.I)
return re.sub(
r"(@import\s+(?:url\()?['\"])([^'\"]+)",
lambda match: match.group(1) + rewrite_url(match.group(2), base_url, session_id),
content,
flags=re.I,
)
def rewrite_javascript(content: str, base_url: str, session_id: str) -> str:
"""Rewrite root-relative ES module imports used by local dev servers."""
return re.sub(
r"((?:from\s*|import\s*\(\s*|import\s*)['\"])(/[^'\"]+)",
lambda match: match.group(1) + rewrite_url(match.group(2), base_url, session_id),
content,
)
manager = BrowserProxyManager()
File diff suppressed because it is too large. Load diff
+8 -4
View File
@@ -11,20 +11,24 @@ import json
import logging
from pathlib import Path
from cptr.env import DATA_DIR
from cptr.models import Chat, ChatMessage
logger = logging.getLogger(__name__)
def chat_directory(workspace: str | None) -> Path:
"""Return the portable chat directory for a workspace or Home."""
return Path(workspace) / ".cptr" / "chats" if workspace else DATA_DIR / "chats"
async def export_chat_to_file(chat_id: str) -> None:
"""Regenerate .cptr/chats/{id}.json from the DB."""
chat = await Chat.get_by_id(chat_id)
if not chat:
return
workspace = (chat.meta or {}).get("workspace", "")
if not workspace:
return
workspace = (chat.meta or {}).get("workspace")
messages = await ChatMessage.get_all_by_chat(chat_id)
@@ -70,7 +74,7 @@ async def export_chat_to_file(chat_id: str) -> None:
}
def _write():
chats_dir = Path(workspace) / ".cptr" / "chats"
chats_dir = chat_directory(workspace)
chats_dir.mkdir(parents=True, exist_ok=True)
target = chats_dir / f"{chat_id}.json"
target.write_text(json.dumps(chat_data, indent=2, ensure_ascii=False))
+11 -2
View File
@@ -626,6 +626,12 @@ async def generate_chat_title(
if not title:
return
# Do not overwrite a title manually set while this request was running.
chat = await Chat.get_by_id(chat_id)
fallback = user_content[:50].strip() or "New Chat"
if not chat or chat.title != fallback:
return
# Persist and notify
await Chat.update_title(chat_id, title, now_ms())
await emit_to_user(user_id, {"chat_id": chat_id, "title": title})
@@ -1459,6 +1465,7 @@ async def run_chat_task(
from cptr.utils.agents.cursor import run_cursor_agent
from cptr.utils.agents.grok import run_grok_agent
from cptr.utils.agents.opencode import run_opencode_agent
from cptr.utils.agents.pi import run_pi_agent
chat_obj = await Chat.get_by_id(chat_id)
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
@@ -1517,6 +1524,8 @@ async def run_chat_task(
"grok": run_grok_agent,
"opencode": run_opencode_agent,
"cline": run_cline_agent,
"gemini": run_cline_agent,
"pi": run_pi_agent,
}
runner = runners.get(agent_target.agent)
if runner is None:
@@ -1692,7 +1701,7 @@ async def run_chat_task(
"call_id": event.call_id,
"native_agent": True,
"output": _append_capped_output(
str(existing_output.get("output") or ""),
"" if event.replace else str(existing_output.get("output") or ""),
event.delta,
max_chars,
),
@@ -1791,7 +1800,7 @@ async def run_chat_task(
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
if regeneration_prompt:
messages.append({"role": "user", "content": regeneration_prompt})
tools = await get_tool_list(builtin_tools=builtin_tools)
tools = await get_tool_list(builtin_tools=builtin_tools, workspace=workspace)
if not skill_authoring_allowed:
tools = [t for t in tools if t["name"] != "manage_skill"]
+1 -1
View File
@@ -24,7 +24,7 @@ class ApiModelTarget:
class AgentModelTarget:
kind: Literal["agent"]
profile_id: str
agent: Literal["codex", "claude_code", "cursor", "grok", "opencode", "cline"]
agent: Literal["codex", "claude_code", "cursor", "grok", "opencode", "cline", "gemini", "pi"]
model: str
full_model_id: str
config: dict[str, Any]
+19 -10
View File
@@ -34,6 +34,14 @@ DEFAULT_SYSTEM_PROMPT = (
"\nFiles:\n{{FILE_TREE}}"
)
HOME_SYSTEM_PROMPT = (
"You are Computer (cptr), a helpful assistant in the user's computer interface. "
"This is a general chat with no workspace open. Use the available tools directly and "
"ask the user to open a workspace for project files or commands."
"\n\n{{MEMORY}}"
"\n\n{{SKILLS}}"
)
def _get_file_tree(workspace: str, max_entries: int = 200) -> str:
"""Generate a compact file tree listing for the workspace."""
@@ -215,11 +223,11 @@ def _build_template_variables(
skills_enabled: bool = True,
) -> dict[str, str]:
"""Build the dict of template variable values for the current context."""
ws_path = Path(workspace)
ws_path = Path(workspace) if workspace else None
os_name = platform.system().replace("Darwin", "macOS")
shell = os.environ.get("SHELL") or os.environ.get("COMSPEC") or ""
instructions = _load_instruction_files(workspace)
instructions = _load_instruction_files(workspace) if workspace else ""
if instructions:
instructions_block = (
f"<instructions>\n{instructions}\n</instructions>"
@@ -233,13 +241,13 @@ def _build_template_variables(
skills_block = build_catalog_xml(discover_skills(workspace)) if skills_enabled else ""
return {
"WORKSPACE_NAME": ws_path.name if ws_path.is_dir() else "",
"WORKSPACE_PATH": str(ws_path),
"FILE_TREE": _get_file_tree(workspace),
"WORKSPACE_NAME": ws_path.name if ws_path and ws_path.is_dir() else "",
"WORKSPACE_PATH": str(ws_path) if ws_path else "",
"FILE_TREE": _get_file_tree(workspace) if workspace else "",
"INSTRUCTIONS": instructions_block,
"MEMORY": memory,
"SKILLS": skills_block,
"CPTR_CONTEXT": _format_cptr_context(workspace, model),
"CPTR_CONTEXT": _format_cptr_context(workspace, model) if workspace else "",
"RUNTIME_ENV": _runtime_label(),
"HOSTNAME": _safe_hostname(),
"OS": os_name,
@@ -271,9 +279,10 @@ async def load_system_prompt(
"""
template = None
ws_prompt = Path(workspace) / ".cptr" / "system.md"
if ws_prompt.is_file():
template = ws_prompt.read_text(errors="replace").strip()
if workspace:
ws_prompt = Path(workspace) / ".cptr" / "system.md"
if ws_prompt.is_file():
template = ws_prompt.read_text(errors="replace").strip()
if template is None:
try:
@@ -294,7 +303,7 @@ async def load_system_prompt(
logger.debug("[system_prompt] Failed to load from config", exc_info=True)
if template is None:
template = DEFAULT_SYSTEM_PROMPT
template = DEFAULT_SYSTEM_PROMPT if workspace else HOME_SYSTEM_PROMPT
memory = ""
if user_id:
-233
View File
@@ -1,233 +0,0 @@
"""Proxy fallback middleware.
Intercepts requests for sub-resources of proxied dev servers.
When a page is loaded through /api/proxy/{port}/, its sub-resources
(JS modules, CSS, images) use absolute paths like /@vite/client or
/node_modules/... which resolve against the cptr origin. This
middleware detects those requests via the Referer header and a
path-to-port cache, then proxies them to the correct local port.
The cache chain works like this:
1. /api/proxy/5174/ loads HTML with <script src="/@vite/client">
2. Browser requests /@vite/client with Referer containing /api/proxy/5174/
3. Middleware extracts port 5174, proxies, caches /@vite/client -> 5174
4. /@vite/client imports /node_modules/foo
5. Referer is /@vite/client, middleware looks up cache -> port 5174
6. Chain continues indefinitely
"""
from __future__ import annotations
import logging
import re
from urllib.parse import urlparse
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp, Receive, Scope, Send
logger = logging.getLogger(__name__)
# Regex to extract port from a proxy Referer URL
_PROXY_PORT_RE = re.compile(r"/api/proxy/(\d+)/")
# Paths that should never be intercepted by the proxy middleware
_PASSTHROUGH_PREFIXES = (
"/api/",
"/_app/",
"/socket.io/",
"/favicon",
)
def _extract_port_from_referer(referer: str) -> int | None:
"""Extract the proxy port from a Referer like /api/proxy/5174/..."""
m = _PROXY_PORT_RE.search(referer)
return int(m.group(1)) if m else None
class ProxyFallbackMiddleware:
"""ASGI middleware that intercepts sub-resource requests for proxied dev servers."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket"):
await self.app(scope, receive, send)
return
path: str = scope.get("path", "")
# Never intercept known cptr paths
if any(path.startswith(prefix) for prefix in _PASSTHROUGH_PREFIXES):
await self.app(scope, receive, send)
return
# Try to resolve a proxy port for this request
port = self._resolve_port(scope)
if port is None:
await self.app(scope, receive, send)
return
# Auth check: this middleware runs before the auth middleware (outermost),
# so we must verify the session ourselves to prevent unauthenticated SSRF.
if not self._is_authenticated(scope):
# Not authenticated — fall through to the normal app (which will
# either serve a page or return 401 via the auth middleware).
await self.app(scope, receive, send)
return
if scope["type"] == "http":
await self._proxy_http(scope, receive, send, port, path)
elif scope["type"] == "websocket":
await self._proxy_websocket(scope, receive, send, port, path)
@staticmethod
def _is_authenticated(scope: Scope) -> bool:
"""Check if the request carries a valid cptr session cookie."""
from cptr.utils.config import check_access
headers = dict(scope.get("headers", []))
cookie_header = (headers.get(b"cookie") or b"").decode("latin-1", errors="replace")
token = None
for part in cookie_header.split(";"):
part = part.strip()
if part.startswith("cptr_session="):
token = part.split("=", 1)[1]
break
if not token:
return False
client = scope.get("client")
client_host = client[0] if client else "127.0.0.1"
return check_access(client_host=client_host, jwt_token=token) is not None
def _resolve_port(self, scope: Scope) -> int | None:
"""Determine which proxy port this request belongs to."""
from cptr.routers.proxy import resolve_cached_port
path: str = scope.get("path", "")
# 1. Check the path cache (handles chained imports)
cached = resolve_cached_port(path)
if cached is not None:
return cached
# 2. Check Referer header
headers = dict(scope.get("headers", []))
referer_bytes = headers.get(b"referer", b"")
if referer_bytes:
referer = referer_bytes.decode("latin-1", errors="replace")
# Direct: Referer is /api/proxy/{port}/...
port = _extract_port_from_referer(referer)
if port:
return port
# Indirect: Referer is a previously-cached path
try:
ref_path = urlparse(referer).path
except Exception:
ref_path = ""
if ref_path:
cached = resolve_cached_port(ref_path)
if cached is not None:
return cached
return None
async def _proxy_http(
self, scope: Scope, receive: Receive, send: Send, port: int, path: str
) -> None:
"""Proxy an HTTP request through the shared proxy function."""
from cptr.routers.proxy import proxy_http_request, cache_path
# Cache this path for future chained requests
cache_path(path, port)
request = Request(scope, receive)
response = await proxy_http_request(port, path.lstrip("/"), request)
await response(scope, receive, send)
async def _proxy_websocket(
self, scope: Scope, receive: Receive, send: Send, port: int, path: str
) -> None:
"""Proxy a WebSocket connection to the dev server.
This handles the case where Vite HMR or similar tools try to
connect a WebSocket to the page origin (e.g. ws://remote:8000/)
instead of through /api/proxy/{port}/ws-proxy/.
"""
import asyncio
from starlette.websockets import WebSocket
websocket = WebSocket(scope, receive, send)
await websocket.accept()
# Build query string
qs_bytes = scope.get("query_string", b"")
qs = f"?{qs_bytes.decode()}" if qs_bytes else ""
upstream_ws = None
for host in ("127.0.0.1", "[::1]"):
ws_url = f"ws://{host}:{port}{path}{qs}"
try:
import websockets
upstream_ws = await asyncio.wait_for(
websockets.connect(ws_url, additional_headers={"host": f"127.0.0.1:{port}"}),
timeout=5.0,
)
break
except Exception:
continue
if upstream_ws is None:
await websocket.close(code=4002, reason=f"Cannot connect to localhost:{port}")
return
async def client_to_upstream():
try:
while True:
data = await websocket.receive()
if "text" in data:
await upstream_ws.send(data["text"])
elif "bytes" in data:
await upstream_ws.send(data["bytes"])
else:
break
except Exception:
pass
async def upstream_to_client():
try:
async for msg in upstream_ws:
if isinstance(msg, str):
await websocket.send_text(msg)
elif isinstance(msg, bytes):
await websocket.send_bytes(msg)
except Exception:
pass
try:
done, pending = await asyncio.wait(
[
asyncio.create_task(client_to_upstream()),
asyncio.create_task(upstream_to_client()),
],
return_when=asyncio.FIRST_COMPLETED,
)
for t in pending:
t.cancel()
finally:
try:
await upstream_ws.close()
except Exception:
pass
try:
await websocket.close()
except Exception:
pass
+15 -1
View File
@@ -2533,6 +2533,16 @@ BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = {
"notifications": ("notify",),
}
GLOBAL_CHAT_DISABLED_TOOLS = {
*BUILTIN_TOOL_GROUPS["files"],
*BUILTIN_TOOL_GROUPS["terminal"],
*BUILTIN_TOOL_GROUPS["browser"],
*BUILTIN_TOOL_GROUPS["automations"],
*BUILTIN_TOOL_GROUPS["images"],
*BUILTIN_TOOL_GROUPS["subagents"],
"manage_skill",
}
def disabled_builtin_tool_names(builtin_tools: dict | None) -> set[str]:
"""Return builtin tool names disabled by group config."""
@@ -2851,7 +2861,7 @@ def _without_background_param(schema: dict) -> dict:
return schema
async def get_tool_list(builtin_tools: dict | None = None) -> list[dict]:
async def get_tool_list(builtin_tools: dict | None = None, workspace: str = "") -> list[dict]:
"""Return tool schemas for the LLM.
Automatically includes browser tools when browser.enabled is true,
@@ -2898,6 +2908,8 @@ async def get_tool_list(builtin_tools: dict | None = None) -> list[dict]:
pass
disabled_tools = disabled_builtin_tool_names(builtin_tools)
if not workspace:
disabled_tools |= GLOBAL_CHAT_DISABLED_TOOLS
if disabled_tools:
tools = {name: tool for name, tool in tools.items() if name not in disabled_tools}
@@ -2920,6 +2932,8 @@ async def execute_tool(name: str, args: dict, __context__: dict) -> str:
"""Execute a tool by name, injecting execution context."""
info = ALL_TOOLS.get(name)
if info:
if not __context__.get("workspace") and name in GLOBAL_CHAT_DISABLED_TOOLS:
return f"Error: tool requires an open workspace: {name}"
if not is_builtin_tool_enabled(name, __context__.get("builtin_tools")):
return f"Error: tool disabled: {name}"
fn = info["fn"]
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.8.8"
version = "0.9.0"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
Generated
+1 -1
View File
@@ -284,7 +284,7 @@ wheels = [
[[package]]
name = "cptr"
version = "0.8.8"
version = "0.9.0"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },