mirror of
https://github.com/open-webui/computer.git
synced 2026-11-26 07:11:02 -05:00
refac
This commit is contained in:
1 parent
28064c17d2
commit
9c47e65420
24 files changed
+924
-455
No files matched your search
@@ -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) => {
|
||||
@@ -115,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 = {},
|
||||
@@ -127,7 +127,7 @@ export const sendMessage = (
|
||||
jsonBody({
|
||||
content,
|
||||
model_id: modelId,
|
||||
workspace,
|
||||
...(workspace ? { workspace } : {}),
|
||||
chat_id: chatId,
|
||||
parent_id: parentId ?? null,
|
||||
regeneration_prompt: regenerationPrompt,
|
||||
|
||||
@@ -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'
|
||||
);
|
||||
@@ -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(() => {});
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
type PersonalChromeStatus
|
||||
} from '$lib/apis/browser';
|
||||
import { t } from '$lib/i18n';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Collapsible from '$lib/components/Collapsible.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
@@ -52,13 +53,11 @@
|
||||
let browserUseBaseUrl = $state('https://api.browser-use.com');
|
||||
let browserQualityDefault = $state<'low' | 'balanced' | 'crisp'>('balanced');
|
||||
let browserQualityProfiles = $state({
|
||||
low: { max_height: 720, bitrate: 3000000, device_scale_factor: 1 },
|
||||
balanced: { max_height: 1080, bitrate: 6000000, device_scale_factor: 1 },
|
||||
crisp: { max_height: 1080, bitrate: 12000000, device_scale_factor: 2 }
|
||||
low: { bitrate: 3000000, frame_rate: 15 },
|
||||
balanced: { bitrate: 6000000, frame_rate: 24 },
|
||||
crisp: { bitrate: 12000000, frame_rate: 30 }
|
||||
});
|
||||
let browserQualityMaxResolution = $state(1080);
|
||||
let browserQualityMaxBitrate = $state(12000000);
|
||||
let browserQualityAllowDsf2 = $state(true);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
@@ -109,18 +108,14 @@
|
||||
if (profile && typeof profile === 'object') {
|
||||
const value = profile as Record<string, unknown>;
|
||||
browserQualityProfiles[name] = {
|
||||
max_height:
|
||||
Number(value.max_height ?? value.resolution) ||
|
||||
browserQualityProfiles[name].max_height,
|
||||
bitrate: Number(value.bitrate) || browserQualityProfiles[name].bitrate,
|
||||
device_scale_factor: Number(value.device_scale_factor) === 2 ? 2 : 1
|
||||
frame_rate:
|
||||
Number(value.frame_rate ?? value.fps) || browserQualityProfiles[name].frame_rate
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
browserQualityMaxResolution = Number(config['browser.quality.max_resolution']) || 1080;
|
||||
browserQualityMaxBitrate = Number(config['browser.quality.max_bitrate']) || 12000000;
|
||||
browserQualityAllowDsf2 = config['browser.quality.allow_dsf2'] !== false;
|
||||
} catch {
|
||||
toast.error($t('admin.failedToLoadConfig'));
|
||||
}
|
||||
@@ -163,9 +158,7 @@
|
||||
'browser.browser_use_base_url': browserUseBaseUrl,
|
||||
'browser.quality.default': browserQualityDefault,
|
||||
'browser.quality.profiles': browserQualityProfiles,
|
||||
'browser.quality.max_resolution': browserQualityMaxResolution,
|
||||
'browser.quality.max_bitrate': browserQualityMaxBitrate,
|
||||
'browser.quality.allow_dsf2': browserQualityAllowDsf2
|
||||
'browser.quality.max_bitrate': browserQualityMaxBitrate
|
||||
};
|
||||
await updateConfig(cfg);
|
||||
if (
|
||||
@@ -516,7 +509,7 @@
|
||||
>{$t('admin.browserQuality')}</span
|
||||
>
|
||||
<p class="text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('admin.browserQualityHint')}
|
||||
{$t('admin.browserQualityHintV2')}
|
||||
</p>
|
||||
</div>
|
||||
<select
|
||||
@@ -534,51 +527,32 @@
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<span class="text-xs capitalize text-gray-600 dark:text-gray-400">{name}</span>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<input
|
||||
type="number"
|
||||
min="240"
|
||||
max="1080"
|
||||
aria-label={`${name} ${$t('admin.browserQualityMaxHeight')}`}
|
||||
bind:value={
|
||||
browserQualityProfiles[name as 'low' | 'balanced' | 'crisp'].max_height
|
||||
}
|
||||
class="h-7 w-16 rounded-lg border border-gray-200 bg-gray-100 px-2 text-xs text-gray-700 outline-none dark:border-white/8 dark:bg-white/6 dark:text-gray-300"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
min="1000000"
|
||||
max="12000000"
|
||||
step="1000000"
|
||||
aria-label={`${name} ${$t('admin.browserQualityMaxBitrate')}`}
|
||||
use:tooltip={$t('admin.browserQualityMaxBitrate')}
|
||||
bind:value={
|
||||
browserQualityProfiles[name as 'low' | 'balanced' | 'crisp'].bitrate
|
||||
}
|
||||
class="h-7 w-20 rounded-lg border border-gray-200 bg-gray-100 px-2 text-xs text-gray-700 outline-none dark:border-white/8 dark:bg-white/6 dark:text-gray-300"
|
||||
/>
|
||||
<select
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="60"
|
||||
aria-label={`${name} ${$t('admin.browserQualityFrameRate')}`}
|
||||
use:tooltip={$t('admin.browserQualityFrameRate')}
|
||||
bind:value={
|
||||
browserQualityProfiles[name as 'low' | 'balanced' | 'crisp']
|
||||
.device_scale_factor
|
||||
browserQualityProfiles[name as 'low' | 'balanced' | 'crisp'].frame_rate
|
||||
}
|
||||
aria-label={`${name} DSF`}
|
||||
class="bg-transparent text-xs text-gray-600 dark:text-gray-400 outline-none cursor-pointer"
|
||||
><option value={1}>1x</option><option value={2}>2x</option></select
|
||||
>
|
||||
class="h-7 w-14 rounded-lg border border-gray-200 bg-gray-100 px-2 text-xs text-gray-700 outline-none dark:border-white/8 dark:bg-white/6 dark:text-gray-300"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('admin.browserQualityMaxHeight')}</span
|
||||
>
|
||||
<input
|
||||
type="number"
|
||||
min="240"
|
||||
max="1080"
|
||||
bind:value={browserQualityMaxResolution}
|
||||
class="h-7 w-20 rounded-lg border border-gray-200 bg-gray-100 px-2 text-xs text-gray-700 outline-none dark:border-white/8 dark:bg-white/6 dark:text-gray-300"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('admin.browserQualityMaxBitrate')}</span
|
||||
@@ -592,15 +566,6 @@
|
||||
class="h-7 w-24 rounded-lg border border-gray-200 bg-gray-100 px-2 text-xs text-gray-700 outline-none dark:border-white/8 dark:bg-white/6 dark:text-gray-300"
|
||||
/>
|
||||
</div>
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('admin.browserQualityAllowDsf2')}</span
|
||||
>
|
||||
<ToggleSwitch
|
||||
value={browserQualityAllowDsf2}
|
||||
onchange={(value) => (browserQualityAllowDsf2 = value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</Collapsible>
|
||||
{:else}
|
||||
|
||||
@@ -21,9 +21,22 @@
|
||||
tabId: string;
|
||||
initialUrl?: string;
|
||||
active?: boolean;
|
||||
onTabUpdate?: (label: string) => void;
|
||||
onOpenBrowser?: (url?: string) => void;
|
||||
}
|
||||
|
||||
let { sessionId, groupId, tabId, initialUrl, active = true }: Props = $props();
|
||||
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));
|
||||
@@ -36,34 +49,32 @@
|
||||
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>({ width: 390, height: 844 });
|
||||
let qualityMenuOpen = $state(false);
|
||||
let qualityMenuAnchor = $state<HTMLElement>();
|
||||
|
||||
function updateLabel(label: string) {
|
||||
if (onTabUpdate) onTabUpdate(label);
|
||||
else updateTabLabel(tabId, label);
|
||||
}
|
||||
|
||||
function setChromeQuality(quality: 'low' | 'balanced' | 'crisp') {
|
||||
chromeEl?.setQuality(quality);
|
||||
chromeQuality = quality;
|
||||
qualityMenuOpen = false;
|
||||
}
|
||||
|
||||
const qualityMenuItems = $derived([
|
||||
{
|
||||
label: $t('admin.browserQualityLow'),
|
||||
onclick: () => setChromeQuality('low'),
|
||||
active: chromeQuality === 'low',
|
||||
check: true
|
||||
},
|
||||
{
|
||||
label: $t('admin.browserQualityBalanced'),
|
||||
onclick: () => setChromeQuality('balanced'),
|
||||
active: chromeQuality === 'balanced',
|
||||
check: true
|
||||
},
|
||||
{
|
||||
label: $t('admin.browserQualityCrisp'),
|
||||
onclick: () => setChromeQuality('crisp'),
|
||||
active: chromeQuality === 'crisp',
|
||||
check: true
|
||||
}
|
||||
]);
|
||||
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, [key]: Math.round(value) };
|
||||
chromeEl?.setMobileViewport(chromeMobileViewport);
|
||||
}
|
||||
|
||||
function publicUrl(value: string) {
|
||||
const proxyUrl = new URL(value, location.origin);
|
||||
@@ -141,10 +152,13 @@
|
||||
if (data?.type === 'cptr-browser-state') {
|
||||
urlInput = publicUrl(data.url || urlInput);
|
||||
title = data.title || '';
|
||||
updateTabLabel(tabId, title);
|
||||
updateLabel(title);
|
||||
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
|
||||
}
|
||||
if (data?.type === 'cptr-browser-popup' && data.url) openBrowserTab(groupId, data.url);
|
||||
if (data?.type === 'cptr-browser-popup' && data.url) {
|
||||
if (onOpenBrowser) onOpenBrowser(data.url);
|
||||
else openBrowserTab(groupId, data.url);
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
@@ -154,7 +168,7 @@
|
||||
const url = publicUrl(session.url || initialUrl || '');
|
||||
urlInput = url;
|
||||
title = session.title;
|
||||
updateTabLabel(tabId, title);
|
||||
updateLabel(title);
|
||||
mode = session.mode || 'proxy';
|
||||
if (mode === 'chrome') {
|
||||
const supported =
|
||||
@@ -237,11 +251,71 @@
|
||||
</div>
|
||||
{#if qualityMenuOpen && qualityMenuAnchor}
|
||||
<DropdownMenu
|
||||
items={qualityMenuItems}
|
||||
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'}
|
||||
<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}
|
||||
</div>
|
||||
</DropdownMenu>
|
||||
{/if}
|
||||
<div class="preview-content">
|
||||
{#if error}
|
||||
@@ -257,7 +331,7 @@
|
||||
onstate={(state) => {
|
||||
urlInput = state.url || urlInput;
|
||||
title = state.title || '';
|
||||
updateTabLabel(tabId, title);
|
||||
updateLabel(title);
|
||||
canGoBack = state.can_go_back;
|
||||
canGoForward = state.can_go_forward;
|
||||
}}
|
||||
@@ -272,6 +346,10 @@
|
||||
}
|
||||
}}
|
||||
onquality={(quality) => (chromeQuality = quality)}
|
||||
ondevicemode={(nextMode, viewport) => {
|
||||
chromeDeviceMode = nextMode;
|
||||
chromeMobileViewport = viewport;
|
||||
}}
|
||||
/>
|
||||
{#if chromeStatus === 'reconnecting'}
|
||||
<div
|
||||
|
||||
@@ -14,8 +14,12 @@
|
||||
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;
|
||||
@@ -42,7 +46,7 @@
|
||||
height: number;
|
||||
}
|
||||
|
||||
let { sessionId, active, onstate, onstatus, onquality }: Props = $props();
|
||||
let { sessionId, active, onstate, onstatus, onquality, ondevicemode }: Props = $props();
|
||||
let canvas: HTMLCanvasElement;
|
||||
let container: HTMLDivElement;
|
||||
let keyboardAntenna: HTMLTextAreaElement;
|
||||
@@ -64,6 +68,8 @@
|
||||
let managed = $state(false);
|
||||
let mobile = $state(false);
|
||||
let quality = $state<'low' | 'balanced' | 'crisp'>('balanced');
|
||||
let deviceMode = $state<DeviceMode>('auto');
|
||||
let mobileViewport = $state<MobileViewport>({ width: 390, height: 844 });
|
||||
let deviceProfile: DeviceProfile | undefined;
|
||||
let editableRegions = $state<EditableRegion[]>([]);
|
||||
let lastViewport = '';
|
||||
@@ -160,7 +166,15 @@
|
||||
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;
|
||||
onquality(managed ? quality : null);
|
||||
ondevicemode(deviceMode, mobileViewport);
|
||||
if (active) focusBrowser();
|
||||
else resize();
|
||||
}
|
||||
@@ -310,10 +324,17 @@
|
||||
|
||||
async function sendViewport() {
|
||||
const device = deviceProfile || (await deviceProfilePromise);
|
||||
const key = JSON.stringify([viewport, quality, device]);
|
||||
const key = JSON.stringify([viewport, quality, device, deviceMode, mobileViewport]);
|
||||
if (key === lastViewport) return;
|
||||
lastViewport = key;
|
||||
send({ type: 'viewport', ...viewport, quality, device });
|
||||
send({
|
||||
type: 'viewport',
|
||||
...viewport,
|
||||
quality,
|
||||
device,
|
||||
device_mode: deviceMode,
|
||||
mobile_viewport: mobileViewport
|
||||
});
|
||||
}
|
||||
|
||||
function modifiers(event: MouseEvent | KeyboardEvent | WheelEvent) {
|
||||
@@ -561,6 +582,19 @@
|
||||
onquality(quality);
|
||||
resize();
|
||||
}
|
||||
export function setDeviceMode(nextMode: DeviceMode) {
|
||||
deviceMode = nextMode;
|
||||
lastViewport = '';
|
||||
ondevicemode(deviceMode, mobileViewport);
|
||||
resize();
|
||||
}
|
||||
export function setMobileViewport(nextViewport: MobileViewport) {
|
||||
if (nextViewport.width <= 0 || nextViewport.height <= 0) return;
|
||||
mobileViewport = nextViewport;
|
||||
lastViewport = '';
|
||||
ondevicemode(deviceMode, mobileViewport);
|
||||
resize();
|
||||
}
|
||||
function focusBrowser() {
|
||||
if (!ready) return;
|
||||
send({ type: 'focus' });
|
||||
@@ -655,10 +689,17 @@
|
||||
}
|
||||
.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: fill;
|
||||
object-fit: contain;
|
||||
touch-action: none;
|
||||
}
|
||||
.keyboard-antenna {
|
||||
|
||||
@@ -34,12 +34,29 @@
|
||||
|
||||
interface Props {
|
||||
group: EditorGroup;
|
||||
home?: boolean;
|
||||
canClose?: boolean;
|
||||
isPrimary?: boolean;
|
||||
onTabDragOver?: () => void;
|
||||
onHomeSelect?: (tabId: string) => void;
|
||||
onHomeClose?: (tabId: string) => void;
|
||||
onHomeNewChat?: () => void;
|
||||
onHomeNewTerminal?: () => void;
|
||||
onHomeNewBrowser?: () => void;
|
||||
}
|
||||
|
||||
let { group, canClose = false, isPrimary = false, onTabDragOver }: Props = $props();
|
||||
let {
|
||||
group,
|
||||
home = false,
|
||||
canClose = false,
|
||||
isPrimary = false,
|
||||
onTabDragOver,
|
||||
onHomeSelect,
|
||||
onHomeClose,
|
||||
onHomeNewChat,
|
||||
onHomeNewTerminal,
|
||||
onHomeNewBrowser
|
||||
}: Props = $props();
|
||||
|
||||
let tabsEl: HTMLDivElement | undefined = $state();
|
||||
let sortable: Sortable | null = null;
|
||||
@@ -64,10 +81,12 @@
|
||||
|
||||
const displayTabs = $derived((group?.tabs ?? []).filter((t) => t.type !== 'git'));
|
||||
|
||||
const isActiveGroup = $derived($activeWorkspace?.activeGroupId === group?.id);
|
||||
const isActiveGroup = $derived(home || $activeWorkspace?.activeGroupId === group?.id);
|
||||
|
||||
function tabIconName(tab: Tab): string {
|
||||
switch (tab.type) {
|
||||
case 'home':
|
||||
return 'spark';
|
||||
case 'files':
|
||||
return 'folder';
|
||||
case 'terminal':
|
||||
@@ -88,11 +107,13 @@
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -102,12 +123,14 @@
|
||||
}
|
||||
|
||||
function handleContextMenu(e: MouseEvent, tab: Tab) {
|
||||
if (home) return;
|
||||
if (!isWideScreen) return;
|
||||
e.preventDefault();
|
||||
contextMenu = { tab, x: e.clientX, y: e.clientY };
|
||||
}
|
||||
|
||||
function handlePaneClick() {
|
||||
if (home) return;
|
||||
if (!isActiveGroup) {
|
||||
setActiveGroup(group.id);
|
||||
}
|
||||
@@ -143,6 +166,7 @@
|
||||
}
|
||||
|
||||
function handleBarDragOver(e: DragEvent) {
|
||||
if (home) return;
|
||||
// Only accept tab drags (not file uploads)
|
||||
if (!e.dataTransfer || !hasTabDrag(e.dataTransfer)) return;
|
||||
e.preventDefault();
|
||||
@@ -157,6 +181,7 @@
|
||||
}
|
||||
|
||||
function handleBarDrop(e: DragEvent) {
|
||||
if (home) return;
|
||||
dropHighlight = false;
|
||||
if (!e.dataTransfer) return;
|
||||
const payload = readTabDragPayload(e.dataTransfer);
|
||||
@@ -167,54 +192,81 @@
|
||||
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);
|
||||
}
|
||||
},
|
||||
{
|
||||
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),
|
||||
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 [];
|
||||
@@ -239,7 +291,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))
|
||||
});
|
||||
}
|
||||
|
||||
@@ -275,7 +327,7 @@
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (tabsEl) {
|
||||
if (tabsEl && !home) {
|
||||
sortable = Sortable.create(tabsEl, {
|
||||
animation: 150,
|
||||
ghostClass: 'tab-reorder-preview',
|
||||
@@ -387,7 +439,7 @@
|
||||
<!-- Right-side controls -->
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<!-- Split button (wide screens) -->
|
||||
{#if isWideScreen}
|
||||
{#if isWideScreen && !home}
|
||||
<button
|
||||
bind:this={splitBtnEl}
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg transition-colors duration-100 shrink-0
|
||||
@@ -446,7 +498,7 @@
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if $showVoiceMemo}
|
||||
{#if !home && $showVoiceMemo}
|
||||
<VoiceMemoModal
|
||||
workspace={$activeWorkspace?.path ?? ''}
|
||||
directory={$activeWorkspace?.fileBrowserCwd ?? $activeWorkspace?.path ?? ''}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
onopen: (id: string) => void;
|
||||
ondelete: (id: string) => void;
|
||||
onrename: (id: string) => void;
|
||||
oncopy: (id: string) => void;
|
||||
oncopy?: (id: string) => void;
|
||||
page?: number;
|
||||
totalPages?: number;
|
||||
perPage?: number;
|
||||
@@ -148,13 +148,17 @@
|
||||
anchor={menuAnchor}
|
||||
align="end"
|
||||
items={[
|
||||
{
|
||||
label: $t('files.copyPath'),
|
||||
icon: 'copy',
|
||||
onclick: () => {
|
||||
if (menuChatId) oncopy(menuChatId);
|
||||
}
|
||||
},
|
||||
...(oncopy
|
||||
? [
|
||||
{
|
||||
label: $t('files.copyPath'),
|
||||
icon: 'copy',
|
||||
onclick: () => {
|
||||
if (menuChatId) oncopy(menuChatId);
|
||||
}
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: $t('files.rename'),
|
||||
icon: 'pencil',
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -73,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);
|
||||
@@ -303,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);
|
||||
@@ -464,6 +468,7 @@
|
||||
}
|
||||
|
||||
function copyChatPath(id: string) {
|
||||
if (!workspace) return;
|
||||
const chat = previousChats.find((c) => c.id === id);
|
||||
if (!chat) return;
|
||||
navigator.clipboard.writeText(
|
||||
@@ -940,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 });
|
||||
@@ -977,7 +983,7 @@
|
||||
|
||||
async function refreshCommandSessions() {
|
||||
const currentChatId = chatId;
|
||||
if (!currentChatId) {
|
||||
if (!currentChatId || !workspace) {
|
||||
commandSessions = [];
|
||||
return;
|
||||
}
|
||||
@@ -1205,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 {
|
||||
@@ -1586,7 +1593,7 @@
|
||||
onopen={openChat}
|
||||
ondelete={deleteChat}
|
||||
onrename={renameChat}
|
||||
oncopy={copyChatPath}
|
||||
oncopy={workspace ? copyChatPath : undefined}
|
||||
page={chatPage}
|
||||
{totalPages}
|
||||
perPage={CHATS_PAGE_SIZE}
|
||||
|
||||
@@ -389,13 +389,23 @@
|
||||
"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.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.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",
|
||||
|
||||
@@ -45,7 +45,7 @@ export type { AppearancePreferences, Theme, ThemeConfig };
|
||||
|
||||
export interface Tab {
|
||||
id: string;
|
||||
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
|
||||
type: 'home' | 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
|
||||
label: string;
|
||||
filePath?: string;
|
||||
edit?: boolean;
|
||||
|
||||
@@ -245,21 +245,29 @@ export function executeAction(
|
||||
toggleVoiceMemo?: () => void;
|
||||
}
|
||||
): boolean {
|
||||
const dispatchHomeAction = (detail: 'newChat' | 'newTerminal' | 'newBrowser') => {
|
||||
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':
|
||||
void openBrowserTab();
|
||||
if (get(currentWorkspace)) void openBrowserTab();
|
||||
else dispatchHomeAction('newBrowser');
|
||||
return true;
|
||||
|
||||
case 'closeTab': {
|
||||
|
||||
@@ -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';
|
||||
@@ -453,9 +452,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>
|
||||
|
||||
@@ -20,12 +20,14 @@
|
||||
pwaPreferences
|
||||
} 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 { get } from 'svelte/store';
|
||||
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';
|
||||
@@ -46,6 +48,99 @@
|
||||
let pendingIntent = $state<LaunchIntent | null>(null);
|
||||
let folderPickerIntent = $state<LaunchIntent | null>(null);
|
||||
let folderPickerWorkspace = $state<string | null>(null);
|
||||
let homeGroup = $state<EditorGroup>({
|
||||
id: 'home',
|
||||
tabs: [{ id: 'home', type: 'home', label: 'Home', permanent: true }],
|
||||
activeTabId: 'home'
|
||||
});
|
||||
const activeHomeTab = $derived(
|
||||
homeGroup.tabs.find((tab) => tab.id === homeGroup.activeTabId) ?? homeGroup.tabs[0]
|
||||
);
|
||||
|
||||
function updateHomeTabs(update: (tabs: Tab[]) => { tabs: Tab[]; activeTabId: string }) {
|
||||
const next = update(homeGroup.tabs);
|
||||
homeGroup = { ...homeGroup, ...next };
|
||||
}
|
||||
|
||||
function openHomeChat(chatId?: string) {
|
||||
const existing = homeGroup.tabs.find(
|
||||
(tab) =>
|
||||
tab.type === 'chat' &&
|
||||
(chatId
|
||||
? tab.path === chatId
|
||||
: tab.path?.startsWith('new-') || tab.path?.startsWith('pending-'))
|
||||
);
|
||||
if (existing) {
|
||||
homeGroup = { ...homeGroup, activeTabId: existing.id };
|
||||
return;
|
||||
}
|
||||
const tab: Tab = {
|
||||
id: `home-${Date.now()}`,
|
||||
type: 'chat',
|
||||
label: chatId ? 'Chat' : 'New Chat',
|
||||
path: chatId || `new-${Date.now()}`
|
||||
};
|
||||
updateHomeTabs((tabs) => ({ tabs: [...tabs, tab], activeTabId: tab.id }));
|
||||
}
|
||||
|
||||
async function openHomeTerminal() {
|
||||
try {
|
||||
const session = await createSession();
|
||||
const tab: Tab = {
|
||||
id: `home-${Date.now()}`,
|
||||
type: 'terminal',
|
||||
label: 'Terminal',
|
||||
sessionId: session.session_id
|
||||
};
|
||||
updateHomeTabs((tabs) => ({ tabs: [...tabs, tab], activeTabId: tab.id }));
|
||||
} catch (error) {
|
||||
console.error('Failed to create Home terminal:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function openHomeBrowser(url?: string) {
|
||||
try {
|
||||
const session = await createBrowserSession(url);
|
||||
const tab: Tab = {
|
||||
id: `home-${Date.now()}`,
|
||||
type: 'browser',
|
||||
label: 'Browser',
|
||||
path: url,
|
||||
browserSessionId: session.session_id
|
||||
};
|
||||
updateHomeTabs((tabs) => ({ tabs: [...tabs, tab], activeTabId: tab.id }));
|
||||
} catch (error) {
|
||||
console.error('Failed to create Home browser:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function closeHomeTab(tabId: string) {
|
||||
const index = homeGroup.tabs.findIndex((tab) => tab.id === tabId);
|
||||
const tab = homeGroup.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 = homeGroup.tabs.filter((item) => item.id !== tabId);
|
||||
const activeTabId =
|
||||
homeGroup.activeTabId === tabId
|
||||
? (tabs[Math.max(0, index - 1)]?.id ?? 'home')
|
||||
: homeGroup.activeTabId;
|
||||
homeGroup = { ...homeGroup, tabs, activeTabId };
|
||||
}
|
||||
|
||||
function updateHomeChatTab(tabId: string, chatId: string, label: string) {
|
||||
updateHomeTabs((tabs) => ({
|
||||
tabs: tabs.map((tab) => (tab.id === tabId ? { ...tab, path: chatId, label } : tab)),
|
||||
activeTabId: homeGroup.activeTabId
|
||||
}));
|
||||
}
|
||||
|
||||
function updateHomeBrowserTab(tabId: string, label: string) {
|
||||
updateHomeTabs((tabs) => ({
|
||||
tabs: tabs.map((tab) => (tab.id === tabId ? { ...tab, label } : tab)),
|
||||
activeTabId: homeGroup.activeTabId
|
||||
}));
|
||||
}
|
||||
const INTENT_URL_KEYS = [
|
||||
'intent',
|
||||
'chatId',
|
||||
@@ -187,16 +282,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 +326,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 +479,25 @@
|
||||
});
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const handleHomeAction = (event: Event) => {
|
||||
if ($currentWorkspace) return;
|
||||
switch ((event as CustomEvent<'newChat' | 'newTerminal' | 'newBrowser'>).detail) {
|
||||
case 'newChat':
|
||||
openHomeChat();
|
||||
break;
|
||||
case 'newBrowser':
|
||||
void openHomeBrowser();
|
||||
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;
|
||||
@@ -765,146 +896,197 @@
|
||||
</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>
|
||||
{/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"
|
||||
<div class="flex h-full flex-col">
|
||||
<GroupTabBar
|
||||
group={homeGroup}
|
||||
home
|
||||
isPrimary
|
||||
onHomeSelect={(tabId) => (homeGroup = { ...homeGroup, activeTabId: tabId })}
|
||||
onHomeClose={closeHomeTab}
|
||||
onHomeNewChat={openHomeChat}
|
||||
onHomeNewTerminal={openHomeTerminal}
|
||||
onHomeNewBrowser={openHomeBrowser}
|
||||
/>
|
||||
<div class="min-h-0 flex-1">
|
||||
{#if activeHomeTab?.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-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"
|
||||
>
|
||||
{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>
|
||||
v{$appVersion}
|
||||
</button>
|
||||
{/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}
|
||||
</div>
|
||||
{#if welcomeData?.hostname}
|
||||
<p class="mt-0.5 font-mono text-xs text-gray-400 dark:text-gray-600">
|
||||
{welcomeData.hostname}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#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}
|
||||
<div class="mb-6">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.start')}</h2>
|
||||
<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)}
|
||||
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)}
|
||||
>
|
||||
<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>
|
||||
{$t('home.openWorkspace')}
|
||||
</button>
|
||||
{/each}
|
||||
{#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()}
|
||||
>
|
||||
{$t('bar.newChat')}
|
||||
</button>
|
||||
{/if}
|
||||
</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}
|
||||
</div>
|
||||
</div>
|
||||
{:else if activeHomeTab?.type === 'chat'}
|
||||
<ChatPanel
|
||||
chatId={activeHomeTab.path?.startsWith('new-') ||
|
||||
activeHomeTab.path?.startsWith('pending-')
|
||||
? undefined
|
||||
: activeHomeTab.path}
|
||||
tabId={activeHomeTab.id}
|
||||
ontabupdate={updateHomeChatTab}
|
||||
onopenchat={openHomeChat}
|
||||
/>
|
||||
{:else if activeHomeTab?.type === 'terminal' && activeHomeTab.sessionId}
|
||||
<Terminal sessionId={activeHomeTab.sessionId} />
|
||||
{:else if activeHomeTab?.type === 'browser' && activeHomeTab.browserSessionId}
|
||||
<BrowserPreview
|
||||
sessionId={activeHomeTab.browserSessionId}
|
||||
groupId="home"
|
||||
tabId={activeHomeTab.id}
|
||||
initialUrl={activeHomeTab.path}
|
||||
onTabUpdate={(label) => updateHomeBrowserTab(activeHomeTab.id, label)}
|
||||
onOpenBrowser={openHomeBrowser}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
let configured = '';
|
||||
let resolveInitialQuality;
|
||||
const initialQuality = new Promise(resolve => { resolveInitialQuality = resolve; });
|
||||
let quality = { max_height: 1080, bitrate: 12_000_000, device_scale_factor: 1 };
|
||||
let quality = { bitrate: 12_000_000, frame_rate: 30 };
|
||||
let lastEncodedTimestamp = -Infinity;
|
||||
|
||||
function sendError(error) {
|
||||
if (socket?.readyState === WebSocket.OPEN) {
|
||||
@@ -26,23 +27,9 @@
|
||||
}
|
||||
|
||||
function normalizedQuality(value) {
|
||||
const maxHeight = Math.max(240, Math.min(1080, Number(value?.max_height) || 1080));
|
||||
const bitrate = Math.max(1_000_000, Math.min(12_000_000, Number(value?.bitrate) || 12_000_000));
|
||||
return { max_height: Math.round(maxHeight), bitrate: Math.round(bitrate), device_scale_factor: value?.device_scale_factor === 2 ? 2 : 1 };
|
||||
}
|
||||
|
||||
async function applyQuality() {
|
||||
if (!videoTrack) return;
|
||||
try {
|
||||
await videoTrack.applyConstraints({
|
||||
height: { ideal: quality.max_height, max: quality.max_height },
|
||||
frameRate: { ideal: 30, max: 30 }
|
||||
});
|
||||
configured = '';
|
||||
forceKeyframe = true;
|
||||
} catch {
|
||||
// Keep the last live capture constraints if a browser rejects a dynamic resize.
|
||||
}
|
||||
const frameRate = Math.max(1, Math.min(60, Number(value?.frame_rate ?? value?.fps) || 30));
|
||||
return { bitrate: Math.round(bitrate), frame_rate: Math.round(frameRate) };
|
||||
}
|
||||
|
||||
function receiveControl(event) {
|
||||
@@ -56,7 +43,9 @@
|
||||
quality = normalizedQuality(message);
|
||||
resolveInitialQuality?.();
|
||||
resolveInitialQuality = undefined;
|
||||
void applyQuality();
|
||||
configured = '';
|
||||
forceKeyframe = true;
|
||||
lastEncodedTimestamp = -Infinity;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,21 +64,24 @@
|
||||
}
|
||||
|
||||
async function configure(width, height) {
|
||||
const key = `${width}x${height}:${quality.bitrate}`;
|
||||
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: 30,
|
||||
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}`);
|
||||
encoder?.close();
|
||||
if (encoder) {
|
||||
try { await encoder.flush(); } catch {}
|
||||
encoder.close();
|
||||
}
|
||||
encoder = new VideoEncoder({
|
||||
error: sendError,
|
||||
output(chunk) {
|
||||
@@ -167,9 +159,7 @@
|
||||
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: 30, max: 30 }
|
||||
...(windowCapture ? { displaySurface: 'window' } : {})
|
||||
},
|
||||
preferCurrentTab: false,
|
||||
...(windowCapture ? { selfBrowserSurface: 'include', surfaceSwitching: 'exclude' } : {})
|
||||
@@ -179,7 +169,6 @@
|
||||
videoTrack.stop();
|
||||
throw new Error('Select the Open WebUI Computer Browser window');
|
||||
}
|
||||
await applyQuality();
|
||||
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');
|
||||
@@ -192,7 +181,12 @@
|
||||
while (frame) {
|
||||
const nextRect = crop(frame);
|
||||
if (nextRect.width !== rect.width || nextRect.height !== rect.height) rect = nextRect;
|
||||
if (!paused && encoder.encodeQueueSize <= 2) {
|
||||
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
|
||||
@@ -200,6 +194,7 @@
|
||||
: 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; }
|
||||
}
|
||||
|
||||
+32
-27
@@ -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}
|
||||
@@ -529,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}
|
||||
@@ -619,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
|
||||
@@ -638,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 = {}
|
||||
@@ -651,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,
|
||||
@@ -730,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:
|
||||
@@ -746,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,
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -36,6 +36,8 @@ class BrowserSession:
|
||||
mode: str = "proxy"
|
||||
status: str = "ready"
|
||||
device_profile: dict = field(default_factory=dict)
|
||||
device_mode: str = "auto"
|
||||
mobile_viewport: tuple[int, int] = (390, 844)
|
||||
quality_preset: str = "balanced"
|
||||
resolved_quality: dict = field(default_factory=dict)
|
||||
|
||||
@@ -69,7 +71,9 @@ class BrowserProxyManager:
|
||||
return True
|
||||
|
||||
def ids(self, owner: str) -> list[str]:
|
||||
return [session_id for session_id, session in self._sessions.items() if session.owner == owner]
|
||||
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)
|
||||
@@ -85,7 +89,9 @@ class BrowserProxyManager:
|
||||
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 ""
|
||||
session.origin = (
|
||||
f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else ""
|
||||
)
|
||||
if title is not None:
|
||||
session.title = title
|
||||
return session
|
||||
@@ -136,7 +142,9 @@ def target_url(url: str) -> str:
|
||||
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 "")
|
||||
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:
|
||||
@@ -199,8 +207,10 @@ class _HtmlRewriter(HTMLParser):
|
||||
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),
|
||||
lambda match: (
|
||||
match.group(1)
|
||||
+ rewrite_url(match.group(2).strip(), self.base_url, self.session_id)
|
||||
),
|
||||
value,
|
||||
)
|
||||
rewritten.append((key, value))
|
||||
@@ -219,7 +229,7 @@ def rewrite_html(content: str, base_url: str, session_id: str, final_url: str) -
|
||||
parser.feed(content)
|
||||
parser.close()
|
||||
runtime = (
|
||||
f'<script>window.__cptrBrowser={{session:{session_id!r},url:{final_url!r}}};</script>'
|
||||
f"<script>window.__cptrBrowser={{session:{session_id!r},url:{final_url!r}}};</script>"
|
||||
'<script src="/api/browser/runtime.js"></script>'
|
||||
)
|
||||
rendered = "".join(parser.output)
|
||||
|
||||
+153
-69
@@ -7,6 +7,7 @@ import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
@@ -32,9 +33,9 @@ EventHandler = Callable[[dict[str, Any]], Awaitable[None]]
|
||||
|
||||
QUALITY_PRESETS = ("low", "balanced", "crisp")
|
||||
DEFAULT_QUALITY_PROFILES = {
|
||||
"low": {"max_height": 720, "bitrate": 3_000_000, "device_scale_factor": 1},
|
||||
"balanced": {"max_height": 1080, "bitrate": 6_000_000, "device_scale_factor": 1},
|
||||
"crisp": {"max_height": 1080, "bitrate": 12_000_000, "device_scale_factor": 2},
|
||||
"low": {"bitrate": 3_000_000, "frame_rate": 15},
|
||||
"balanced": {"bitrate": 6_000_000, "frame_rate": 24},
|
||||
"crisp": {"bitrate": 12_000_000, "frame_rate": 30},
|
||||
}
|
||||
|
||||
|
||||
@@ -52,51 +53,37 @@ def _number(value: object, default: float, minimum: float, maximum: float) -> fl
|
||||
return default
|
||||
|
||||
|
||||
async def _quality_settings() -> tuple[str, dict[str, dict[str, int]], int, int, bool]:
|
||||
async def _quality_settings() -> tuple[str, dict[str, dict[str, int]], int]:
|
||||
configured = await Config.get("browser.quality.profiles")
|
||||
profiles: dict[str, dict[str, int]] = {}
|
||||
for name, fallback in DEFAULT_QUALITY_PROFILES.items():
|
||||
value = configured.get(name) if isinstance(configured, dict) else None
|
||||
value = value if isinstance(value, dict) else {}
|
||||
profiles[name] = {
|
||||
"max_height": _integer(
|
||||
value.get("max_height", value.get("resolution")), fallback["max_height"], 240, 1080
|
||||
),
|
||||
"bitrate": _integer(value.get("bitrate"), fallback["bitrate"], 1_000_000, 12_000_000),
|
||||
"device_scale_factor": 2
|
||||
if _integer(value.get("device_scale_factor"), fallback["device_scale_factor"], 1, 2)
|
||||
== 2
|
||||
else 1,
|
||||
"frame_rate": _integer(
|
||||
value.get("frame_rate", value.get("fps")), fallback["frame_rate"], 1, 60
|
||||
),
|
||||
}
|
||||
default = await Config.get("browser.quality.default")
|
||||
default = default if default in QUALITY_PRESETS else "balanced"
|
||||
max_resolution = _integer(await Config.get("browser.quality.max_resolution"), 1080, 240, 1080)
|
||||
max_bitrate = _integer(
|
||||
await Config.get("browser.quality.max_bitrate"), 12_000_000, 1_000_000, 12_000_000
|
||||
)
|
||||
return (
|
||||
default,
|
||||
profiles,
|
||||
max_resolution,
|
||||
max_bitrate,
|
||||
await Config.get("browser.quality.allow_dsf2") is not False,
|
||||
)
|
||||
return default, profiles, max_bitrate
|
||||
|
||||
|
||||
def _resolve_quality(
|
||||
preset: object,
|
||||
profiles: dict[str, dict[str, int]],
|
||||
max_resolution: int,
|
||||
max_bitrate: int,
|
||||
allow_dsf2: bool,
|
||||
default: str,
|
||||
) -> tuple[str, dict[str, int]]:
|
||||
name = preset if preset in QUALITY_PRESETS else default
|
||||
value = profiles[name]
|
||||
return name, {
|
||||
"max_height": min(value["max_height"], max_resolution),
|
||||
"bitrate": min(value["bitrate"], max_bitrate),
|
||||
"device_scale_factor": 2 if allow_dsf2 and value["device_scale_factor"] == 2 else 1,
|
||||
"frame_rate": value["frame_rate"],
|
||||
}
|
||||
|
||||
|
||||
@@ -119,6 +106,41 @@ def _device_profile(data: object) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _mobile_user_agent(desktop_user_agent: str) -> str:
|
||||
version = re.search(r"Chrome/([\d.]+)", desktop_user_agent)
|
||||
chrome = version.group(1) if version else "120.0.0.0"
|
||||
return (
|
||||
"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 "
|
||||
f"(KHTML, like Gecko) Chrome/{chrome} Mobile Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
def _effective_device_profile(
|
||||
profile: dict[str, Any], mode: str, mobile_viewport: tuple[int, int], desktop_user_agent: str
|
||||
) -> tuple[dict[str, Any], tuple[int, int]]:
|
||||
if mode == "desktop":
|
||||
return {
|
||||
**profile,
|
||||
"user_agent": desktop_user_agent or profile["user_agent"],
|
||||
"max_touch_points": 0,
|
||||
"mobile": False,
|
||||
"user_agent_metadata": None,
|
||||
}, mobile_viewport
|
||||
if mode == "mobile":
|
||||
width, height = mobile_viewport
|
||||
return {
|
||||
**profile,
|
||||
"user_agent": _mobile_user_agent(desktop_user_agent),
|
||||
"max_touch_points": 5,
|
||||
"screen_width": width,
|
||||
"screen_height": height,
|
||||
"orientation": "landscapePrimary" if width > height else "portraitPrimary",
|
||||
"mobile": True,
|
||||
"user_agent_metadata": {"mobile": True, "platform": "Android"},
|
||||
}, mobile_viewport
|
||||
return profile, mobile_viewport
|
||||
|
||||
|
||||
def _user_agent_metadata(value: object) -> dict[str, Any] | None:
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
@@ -351,6 +373,7 @@ class ChromeHost:
|
||||
profile: Path | None
|
||||
browser_cdp: CDPConnection
|
||||
source: str = "managed"
|
||||
user_agent: str = ""
|
||||
start_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
||||
|
||||
async def create_target(
|
||||
@@ -411,13 +434,14 @@ class ChromeViewer:
|
||||
keyframe: bytes | None = None
|
||||
peers: set[ViewerPeer] = field(default_factory=set)
|
||||
controller: ViewerPeer | None = None
|
||||
viewport: tuple[int, int] = (1280, 720)
|
||||
target_viewport: tuple[float, float] = (1280, 720)
|
||||
viewport: tuple[int, int] = (0, 0)
|
||||
target_viewport: tuple[float, float] = (0, 0)
|
||||
viewport_initialized: bool = False
|
||||
restart_attempted: bool = False
|
||||
initial_navigation_pending: bool = True
|
||||
quality_default: str = "balanced"
|
||||
quality_profiles: dict[str, dict[str, int]] = field(default_factory=dict)
|
||||
quality_limits: tuple[int, int, bool] = (1080, 12_000_000, True)
|
||||
max_bitrate: int = 12_000_000
|
||||
personal: bool = False
|
||||
|
||||
|
||||
@@ -482,7 +506,16 @@ class ChromeViewerManager:
|
||||
if source:
|
||||
browser_ws_url = await resolve_cdp_endpoint(source)
|
||||
browser_cdp = await CDPConnection.connect(browser_ws_url)
|
||||
host = ChromeHost(owner, "", None, None, browser_cdp, "external")
|
||||
version = await browser_cdp.send("Browser.getVersion")
|
||||
host = ChromeHost(
|
||||
owner,
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
browser_cdp,
|
||||
"external",
|
||||
str(version.get("userAgent", "")),
|
||||
)
|
||||
self.hosts[key] = host
|
||||
return host
|
||||
browser_path = find_browser()
|
||||
@@ -501,7 +534,6 @@ class ChromeViewerManager:
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--disable-background-networking",
|
||||
"--window-size=1280,800",
|
||||
f"--auto-select-tab-capture-source-by-title={CAPTURE_TITLE}",
|
||||
"about:blank",
|
||||
]
|
||||
@@ -539,6 +571,7 @@ class ChromeViewerManager:
|
||||
process,
|
||||
profile,
|
||||
browser_cdp,
|
||||
user_agent=str(version.get("User-Agent", version.get("userAgent", ""))),
|
||||
)
|
||||
self.hosts[key] = host
|
||||
return host
|
||||
@@ -548,9 +581,9 @@ class ChromeViewerManager:
|
||||
return self.viewers[session.session_id]
|
||||
host = await self._host(session.owner, cdp_url)
|
||||
async with host.start_lock:
|
||||
default, profiles, max_resolution, max_bitrate, allow_dsf2 = await _quality_settings()
|
||||
default, profiles, max_bitrate = await _quality_settings()
|
||||
preset, quality = _resolve_quality(
|
||||
session.quality_preset, profiles, max_resolution, max_bitrate, allow_dsf2, default
|
||||
session.quality_preset, profiles, max_bitrate, default
|
||||
)
|
||||
session.quality_preset = preset
|
||||
session.resolved_quality = quality
|
||||
@@ -572,15 +605,6 @@ class ChromeViewerManager:
|
||||
""",
|
||||
},
|
||||
)
|
||||
await target_cdp.send(
|
||||
"Emulation.setDeviceMetricsOverride",
|
||||
{
|
||||
"width": 1280,
|
||||
"height": 720,
|
||||
"deviceScaleFactor": quality["device_scale_factor"],
|
||||
"mobile": False,
|
||||
},
|
||||
)
|
||||
token = secrets.token_urlsafe(32)
|
||||
base = local_origin(origin)
|
||||
ws_scheme = "wss" if base.startswith("https:") else "ws"
|
||||
@@ -597,7 +621,7 @@ class ChromeViewerManager:
|
||||
)
|
||||
viewer.quality_default = default
|
||||
viewer.quality_profiles = profiles
|
||||
viewer.quality_limits = (max_resolution, max_bitrate, allow_dsf2)
|
||||
viewer.max_bitrate = max_bitrate
|
||||
self.viewers[session.session_id] = viewer
|
||||
self._wire_events(viewer)
|
||||
try:
|
||||
@@ -730,7 +754,9 @@ class ChromeViewerManager:
|
||||
return tab
|
||||
|
||||
def viewer_for(self, session_id: str) -> ChromeViewer | PersonalTab | None:
|
||||
return self.viewers.get(session_id) or (self.personal.tabs.get(session_id) if self.personal else None)
|
||||
return self.viewers.get(session_id) or (
|
||||
self.personal.tabs.get(session_id) if self.personal else None
|
||||
)
|
||||
|
||||
async def detach_personal(self, session_id: str, owner: str, keep_alive: bool) -> bool:
|
||||
if not self.personal or self.personal.owner != owner:
|
||||
@@ -863,7 +889,9 @@ class ChromeViewerManager:
|
||||
]
|
||||
if normalized != viewer.editable_regions:
|
||||
viewer.editable_regions = normalized
|
||||
await self._broadcast_json(viewer, {"type": "editable_regions", "regions": normalized})
|
||||
await self._broadcast_json(
|
||||
viewer, {"type": "editable_regions", "regions": normalized}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -890,7 +918,14 @@ class ChromeViewerManager:
|
||||
if data.get("type") == "config":
|
||||
viewer.config = data
|
||||
viewer.keyframe = None
|
||||
await self._broadcast_json(viewer, data)
|
||||
if viewer.viewport_initialized:
|
||||
for peer in tuple(viewer.peers):
|
||||
while not peer.queue.empty():
|
||||
with contextlib.suppress(asyncio.QueueEmpty):
|
||||
peer.queue.get_nowait()
|
||||
peer.waiting_keyframe = True
|
||||
with contextlib.suppress(asyncio.QueueFull):
|
||||
peer.queue.put_nowait(data)
|
||||
elif data.get("type") == "audio_config":
|
||||
viewer.audio_config = data
|
||||
await self._broadcast_json(viewer, data)
|
||||
@@ -945,9 +980,7 @@ class ChromeViewerManager:
|
||||
if tab := personal.tabs.get(personal.active_session_id):
|
||||
await self._broadcast_json(tab, data)
|
||||
elif data.get("type") == "error":
|
||||
personal.encoder_error = str(
|
||||
data.get("message", "Chrome encoder failed")
|
||||
)
|
||||
personal.encoder_error = str(data.get("message", "Chrome encoder failed"))
|
||||
personal.first_keyframe.set()
|
||||
elif message.get("bytes") is not None:
|
||||
frame = message["bytes"]
|
||||
@@ -1066,6 +1099,13 @@ class ChromeViewerManager:
|
||||
}
|
||||
if not viewer.personal
|
||||
else None,
|
||||
"device_mode": viewer.session.device_mode if not viewer.personal else None,
|
||||
"mobile_viewport": {
|
||||
"width": viewer.session.mobile_viewport[0],
|
||||
"height": viewer.session.mobile_viewport[1],
|
||||
}
|
||||
if not viewer.personal
|
||||
else None,
|
||||
}
|
||||
)
|
||||
config = (
|
||||
@@ -1073,14 +1113,16 @@ class ChromeViewerManager:
|
||||
if viewer.personal and self.personal
|
||||
else viewer.config
|
||||
)
|
||||
if config:
|
||||
await peer.queue.put(config)
|
||||
if not viewer.personal and viewer.audio_config:
|
||||
await peer.queue.put(viewer.audio_config)
|
||||
if viewer.keyframe:
|
||||
await peer.queue.put(viewer.keyframe)
|
||||
if viewer.personal or viewer.viewport_initialized:
|
||||
if config:
|
||||
await peer.queue.put(config)
|
||||
if not viewer.personal and viewer.audio_config:
|
||||
await peer.queue.put(viewer.audio_config)
|
||||
if viewer.keyframe:
|
||||
await peer.queue.put(viewer.keyframe)
|
||||
await self._refresh_state(viewer)
|
||||
await self._request_keyframe(viewer)
|
||||
if viewer.personal or viewer.viewport_initialized:
|
||||
await self._request_keyframe(viewer)
|
||||
|
||||
async def write() -> None:
|
||||
while True:
|
||||
@@ -1129,8 +1171,12 @@ class ChromeViewerManager:
|
||||
if viewer.controller is not peer:
|
||||
return
|
||||
if kind == "viewport":
|
||||
width = max(320, min(1920, int(data.get("width", 1280))))
|
||||
height = max(240, min(1080, int(data.get("height", 720))))
|
||||
try:
|
||||
width, height = int(data.get("width")), int(data.get("height"))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if width <= 0 or height <= 0:
|
||||
return
|
||||
if viewer.personal:
|
||||
viewer.viewport = (width, height)
|
||||
if self.personal and self.personal.active_session_id == viewer.session.session_id:
|
||||
@@ -1213,21 +1259,43 @@ class ChromeViewerManager:
|
||||
async def _apply_managed_viewport(
|
||||
self, viewer: ChromeViewer, data: dict[str, Any], width: int, height: int
|
||||
) -> None:
|
||||
profile = _device_profile(data.get("device"))
|
||||
max_resolution, max_bitrate, allow_dsf2 = viewer.quality_limits
|
||||
requested_profile = _device_profile(data.get("device"))
|
||||
mode = str(data.get("device_mode", viewer.session.device_mode))
|
||||
mode = mode if mode in {"auto", "desktop", "mobile"} else "auto"
|
||||
requested_mobile_viewport = data.get("mobile_viewport")
|
||||
current_mobile_viewport = viewer.session.mobile_viewport
|
||||
if isinstance(requested_mobile_viewport, dict):
|
||||
try:
|
||||
mobile_viewport = (
|
||||
int(requested_mobile_viewport.get("width")),
|
||||
int(requested_mobile_viewport.get("height")),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
mobile_viewport = current_mobile_viewport
|
||||
if mobile_viewport[0] <= 0 or mobile_viewport[1] <= 0:
|
||||
mobile_viewport = current_mobile_viewport
|
||||
else:
|
||||
mobile_viewport = current_mobile_viewport
|
||||
profile, _ = _effective_device_profile(
|
||||
requested_profile, mode, mobile_viewport, viewer.host.user_agent
|
||||
)
|
||||
layout_viewport = mobile_viewport if mode == "mobile" else (width, height)
|
||||
preset, quality = _resolve_quality(
|
||||
data.get("quality"),
|
||||
viewer.quality_profiles,
|
||||
max_resolution,
|
||||
max_bitrate,
|
||||
allow_dsf2,
|
||||
viewer.max_bitrate,
|
||||
viewer.quality_default,
|
||||
)
|
||||
profile_changed = profile != viewer.session.device_profile
|
||||
quality_changed = quality != viewer.session.resolved_quality
|
||||
viewport_changed = viewer.viewport != (width, height)
|
||||
viewer.viewport = (width, height)
|
||||
device_changed = (
|
||||
mode != viewer.session.device_mode or mobile_viewport != viewer.session.mobile_viewport
|
||||
)
|
||||
viewport_changed = viewer.viewport != layout_viewport
|
||||
viewer.viewport = layout_viewport
|
||||
viewer.session.device_profile = profile
|
||||
viewer.session.device_mode = mode
|
||||
viewer.session.mobile_viewport = mobile_viewport
|
||||
viewer.session.quality_preset = preset
|
||||
viewer.session.resolved_quality = quality
|
||||
|
||||
@@ -1247,13 +1315,13 @@ class ChromeViewerManager:
|
||||
"maxTouchPoints": profile["max_touch_points"],
|
||||
},
|
||||
)
|
||||
if profile_changed or quality_changed or viewport_changed:
|
||||
if profile_changed or device_changed or viewport_changed:
|
||||
await viewer.target_cdp.send(
|
||||
"Emulation.setDeviceMetricsOverride",
|
||||
{
|
||||
"width": width,
|
||||
"height": height,
|
||||
"deviceScaleFactor": quality["device_scale_factor"],
|
||||
"width": layout_viewport[0],
|
||||
"height": layout_viewport[1],
|
||||
"deviceScaleFactor": profile["device_scale_factor"],
|
||||
"mobile": profile["mobile"],
|
||||
"screenWidth": profile["screen_width"],
|
||||
"screenHeight": profile["screen_height"],
|
||||
@@ -1266,17 +1334,29 @@ class ChromeViewerManager:
|
||||
metrics = await viewer.target_cdp.send("Page.getLayoutMetrics")
|
||||
visual = metrics.get("cssVisualViewport", {})
|
||||
viewer.target_viewport = (
|
||||
float(visual.get("clientWidth", width)),
|
||||
float(visual.get("clientHeight", height)),
|
||||
float(visual.get("clientWidth", layout_viewport[0])),
|
||||
float(visual.get("clientHeight", layout_viewport[1])),
|
||||
)
|
||||
if quality_changed:
|
||||
await self._send_encoder(viewer, {"type": "quality", **quality})
|
||||
await self._broadcast_json(viewer, {"type": "quality", "preset": preset, **quality})
|
||||
if viewer.initial_navigation_pending:
|
||||
viewer.initial_navigation_pending = False
|
||||
viewer.viewport_initialized = True
|
||||
for peer in tuple(viewer.peers):
|
||||
while not peer.queue.empty():
|
||||
with contextlib.suppress(asyncio.QueueEmpty):
|
||||
peer.queue.get_nowait()
|
||||
peer.waiting_keyframe = True
|
||||
if viewer.config:
|
||||
with contextlib.suppress(asyncio.QueueFull):
|
||||
peer.queue.put_nowait(viewer.config)
|
||||
await viewer.target_cdp.send(
|
||||
"Page.navigate", {"url": viewer.session.url or "about:blank"}
|
||||
)
|
||||
await self._request_keyframe(viewer)
|
||||
elif device_changed and viewer.session.url:
|
||||
await viewer.target_cdp.send("Page.reload")
|
||||
|
||||
async def _focus_personal(self, tab: PersonalTab, peer: ViewerPeer | None = None) -> None:
|
||||
async with self.lock:
|
||||
@@ -1463,7 +1543,11 @@ class ChromeViewerManager:
|
||||
and any(peer.visible for tab in self.personal.tabs.values() for peer in tab.peers)
|
||||
)
|
||||
await self._send_personal({"type": "resume" if visible_personal else "pause"})
|
||||
if visible and self.personal and self.personal.active_session_id == viewer.session.session_id:
|
||||
if (
|
||||
visible
|
||||
and self.personal
|
||||
and self.personal.active_session_id == viewer.session.session_id
|
||||
):
|
||||
await self._send_personal({"type": "keyframe"})
|
||||
return
|
||||
await self._send_encoder(
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -1800,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"]
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+15
-1
@@ -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"]
|
||||
|
||||
Reference in new issue
Block a user