mirror of
https://github.com/open-webui/computer.git
synced 2026-11-20 21:41:54 +03:00
refac
This commit is contained in:
+102
-1
@@ -353,7 +353,108 @@ async def pwa_manifest():
|
||||
"categories": ["developer", "productivity", "utilities"],
|
||||
"launch_handler": {"client_mode": ["navigate-existing", "auto"]},
|
||||
"handle_links": "preferred",
|
||||
"note_taking": {"new_note_url": "/?action=newFile"},
|
||||
"note_taking": {"new_note_url": "/?intent=newNote"},
|
||||
"shortcuts": [
|
||||
{
|
||||
"name": "New Chat",
|
||||
"short_name": "Chat",
|
||||
"url": "/?intent=newChat",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}],
|
||||
},
|
||||
{
|
||||
"name": "Open Workspace",
|
||||
"short_name": "Workspace",
|
||||
"url": "/?intent=openWorkspace",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}],
|
||||
},
|
||||
{
|
||||
"name": "New Note",
|
||||
"short_name": "Note",
|
||||
"url": "/?intent=newNote",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}],
|
||||
},
|
||||
{
|
||||
"name": "New Terminal",
|
||||
"short_name": "Terminal",
|
||||
"url": "/?intent=newTerminal",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}],
|
||||
},
|
||||
{
|
||||
"name": "Search",
|
||||
"short_name": "Search",
|
||||
"url": "/?intent=search",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}],
|
||||
},
|
||||
],
|
||||
"share_target": {
|
||||
"action": "/?intent=share",
|
||||
"method": "POST",
|
||||
"enctype": "multipart/form-data",
|
||||
"params": {
|
||||
"title": "title",
|
||||
"text": "text",
|
||||
"url": "url",
|
||||
"files": [
|
||||
{
|
||||
"name": "files",
|
||||
"accept": [
|
||||
"text/*",
|
||||
"application/pdf",
|
||||
"image/*",
|
||||
".md",
|
||||
".py",
|
||||
".js",
|
||||
".ts",
|
||||
".tsx",
|
||||
".jsx",
|
||||
".svelte",
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
".toml",
|
||||
".rs",
|
||||
".go",
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
"file_handlers": [
|
||||
{
|
||||
"action": "/?intent=importFiles",
|
||||
"accept": {
|
||||
"text/*": [
|
||||
".txt",
|
||||
".md",
|
||||
".py",
|
||||
".js",
|
||||
".ts",
|
||||
".tsx",
|
||||
".jsx",
|
||||
".svelte",
|
||||
".css",
|
||||
".html",
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
".toml",
|
||||
".rs",
|
||||
".go",
|
||||
".java",
|
||||
".c",
|
||||
".cpp",
|
||||
".h",
|
||||
".hpp",
|
||||
".sh",
|
||||
],
|
||||
"application/pdf": [".pdf"],
|
||||
"image/*": [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"],
|
||||
},
|
||||
}
|
||||
],
|
||||
"protocol_handlers": [
|
||||
{"protocol": "web+cptr", "url": "/?intent=%s"},
|
||||
],
|
||||
"prefer_related_applications": False,
|
||||
"related_applications": [],
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { t } from '$lib/i18n';
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
|
||||
let isOnline = $state(true);
|
||||
let toastId: string | number | undefined;
|
||||
let hasSeenSocketConnection = $state(false);
|
||||
|
||||
function showOffline() {
|
||||
if (!isOnline) return;
|
||||
isOnline = false;
|
||||
toastId = toast.error($t('pwa.reconnecting'), { duration: Infinity });
|
||||
}
|
||||
|
||||
function showOnline() {
|
||||
if (isOnline) return;
|
||||
isOnline = true;
|
||||
if (toastId) toast.dismiss(toastId);
|
||||
toastId = undefined;
|
||||
}
|
||||
|
||||
function handleOnline() {
|
||||
if (socketStore.connected) {
|
||||
showOnline();
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const socket = socketStore.getSocket();
|
||||
const connected = socketStore.connected;
|
||||
|
||||
if (!socket) {
|
||||
hasSeenSocketConnection = false;
|
||||
showOnline();
|
||||
return;
|
||||
}
|
||||
|
||||
if (connected) {
|
||||
hasSeenSocketConnection = true;
|
||||
showOnline();
|
||||
} else if (hasSeenSocketConnection) {
|
||||
showOffline();
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
window.addEventListener('offline', showOffline);
|
||||
window.addEventListener('online', handleOnline);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('offline', showOffline);
|
||||
window.removeEventListener('online', handleOnline);
|
||||
if (toastId) toast.dismiss(toastId);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
@@ -4,11 +4,15 @@
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
import { listDir } from '$lib/apis/files';
|
||||
import Icon from './Icon.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
onselect?: (path: string) => void;
|
||||
}
|
||||
|
||||
interface DirEntry {
|
||||
@@ -17,7 +21,7 @@
|
||||
modified: string | null;
|
||||
}
|
||||
|
||||
let { onclose }: Props = $props();
|
||||
let { onclose, onselect }: Props = $props();
|
||||
|
||||
let currentPath = $state('~');
|
||||
let directories = $state<DirEntry[]>([]);
|
||||
@@ -25,6 +29,8 @@
|
||||
let error = $state<string | null>(null);
|
||||
let selectedIndex = $state(-1);
|
||||
let showHidden = $state(false);
|
||||
let actionsMenuOpen = $state(false);
|
||||
let actionsBtnEl: HTMLButtonElement | undefined = $state();
|
||||
let listEl: HTMLDivElement | undefined = $state();
|
||||
let history = $state<string[]>([]);
|
||||
|
||||
@@ -111,6 +117,11 @@
|
||||
}
|
||||
|
||||
function selectCurrent() {
|
||||
if (onselect) {
|
||||
onselect(currentPath);
|
||||
onclose();
|
||||
return;
|
||||
}
|
||||
addWorkspace(currentPath);
|
||||
goto(`/?workspace=${encodeURIComponent(currentPath)}`);
|
||||
onclose();
|
||||
@@ -268,183 +279,191 @@
|
||||
const parts = currentPath.split('/').filter(Boolean);
|
||||
return parts.length > 0 ? parts[parts.length - 1] : '/';
|
||||
});
|
||||
|
||||
function toggleHidden() {
|
||||
showHidden = !showHidden;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center"
|
||||
onmousedown={onclose}
|
||||
onkeydown={() => {}}
|
||||
<Modal
|
||||
{onclose}
|
||||
class="w-full max-w-[560px] mx-4 max-md:mx-0 max-md:rounded-none max-h-[480px] max-md:max-h-dvh flex flex-col mb-[6vh] max-md:mb-0"
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="w-full max-w-[560px] bg-white dark:bg-[#111] dark:border dark:border-white/8 rounded-3xl max-md:rounded-none overflow-hidden shadow-2xl flex flex-col"
|
||||
style="max-height: min(520px, 85vh);"
|
||||
onmousedown={(e) => e.stopPropagation()}
|
||||
onkeydown={() => {}}
|
||||
>
|
||||
<!-- Path bar -->
|
||||
<div
|
||||
class="flex items-center gap-2 px-4 h-11 border-b border-gray-200 dark:border-white/6 shrink-0"
|
||||
>
|
||||
{#if history.length > 0}
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={goBack}
|
||||
aria-label={$t('directory.goBack')}
|
||||
>
|
||||
<Icon name="chevron-left" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
<!-- Path bar -->
|
||||
<div class="flex items-center px-3.5 py-3 gap-2 shrink-0">
|
||||
{#if history.length > 0}
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={goBack}
|
||||
aria-label={$t('directory.goBack')}
|
||||
>
|
||||
<Icon name="chevron-left" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if editingPath}
|
||||
<div class="flex items-center gap-2 flex-1 min-w-0">
|
||||
<input
|
||||
bind:this={pathInputEl}
|
||||
bind:value={pathInputValue}
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white font-mono placeholder:text-gray-400"
|
||||
oninput={onPathInput}
|
||||
onkeydown={handlePathKeydown}
|
||||
onblur={() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (editingPath) cancelEditing();
|
||||
});
|
||||
}}
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
placeholder={$t('directory.typePath')}
|
||||
/>
|
||||
{#if pathValid === 'checking'}
|
||||
<Spinner size={12} />
|
||||
{:else if pathValid === 'valid'}
|
||||
<span class="text-green-500 shrink-0 flex"><Icon name="check" size={12} /></span>
|
||||
{:else if pathValid === 'invalid'}
|
||||
<span class="text-red-400 shrink-0 flex"><Icon name="xmark" size={12} /></span>
|
||||
{#if editingPath}
|
||||
<div class="flex items-center gap-2 flex-1 min-w-0">
|
||||
<input
|
||||
bind:this={pathInputEl}
|
||||
bind:value={pathInputValue}
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white font-mono placeholder:text-gray-400"
|
||||
oninput={onPathInput}
|
||||
onkeydown={handlePathKeydown}
|
||||
onblur={() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (editingPath) cancelEditing();
|
||||
});
|
||||
}}
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
placeholder={$t('directory.typePath')}
|
||||
/>
|
||||
{#if pathValid === 'checking'}
|
||||
<Spinner size={12} />
|
||||
{:else if pathValid === 'valid'}
|
||||
<span class="text-green-500 shrink-0 flex"><Icon name="check" size={12} /></span>
|
||||
{:else if pathValid === 'invalid'}
|
||||
<span class="text-red-400 shrink-0 flex"><Icon name="xmark" size={12} /></span>
|
||||
{/if}
|
||||
{#if tabHint}
|
||||
<span class="text-[10px] text-gray-400 whitespace-nowrap shrink-0">{tabHint}</span>
|
||||
{/if}
|
||||
<span
|
||||
class="text-[10px] font-mono font-medium px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/6 text-gray-400 shrink-0"
|
||||
>TAB</span
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="group flex items-center gap-0.5 flex-1 min-w-0 cursor-text px-1 -mx-1"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={startEditing}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter') startEditing();
|
||||
}}
|
||||
>
|
||||
{#each breadcrumbs as seg, i (seg.path)}
|
||||
{#if i > 1}<span class="text-gray-300 dark:text-gray-600 text-[11px] font-mono">/</span
|
||||
>{/if}
|
||||
{#if i === breadcrumbs.length - 1}
|
||||
<span
|
||||
class="text-[11px] font-mono font-medium text-gray-900 dark:text-white whitespace-nowrap overflow-hidden text-ellipsis"
|
||||
>{seg.name}</span
|
||||
>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="text-[11px] font-mono text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 whitespace-nowrap shrink-0 cursor-pointer px-0.5 transition-colors duration-75"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigateToPath(seg.path);
|
||||
}}
|
||||
onkeydown={() => {}}>{seg.name}</span
|
||||
>
|
||||
{/if}
|
||||
{#if tabHint}
|
||||
<span class="text-[10px] text-gray-400 whitespace-nowrap shrink-0">{tabHint}</span>
|
||||
{/if}
|
||||
<span
|
||||
class="text-[10px] font-mono font-medium px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/6 text-gray-400 shrink-0"
|
||||
>TAB</span
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="group flex items-center gap-0.5 flex-1 min-w-0 cursor-text rounded-md px-1 -mx-1 transition-colors duration-100 hover:bg-gray-50 dark:hover:bg-white/4"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={startEditing}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter') startEditing();
|
||||
{/each}
|
||||
<span
|
||||
class="ml-1 text-gray-300 dark:text-gray-700 opacity-0 group-hover:opacity-100 transition-opacity duration-150 shrink-0 flex items-center"
|
||||
>
|
||||
<Icon name="pencil" size={10} />
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<button
|
||||
bind:this={actionsBtnEl}
|
||||
class="flex items-center justify-center w-6 h-6 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-200/70 dark:hover:bg-white/8 transition-colors duration-100 shrink-0"
|
||||
onclick={() => {
|
||||
actionsMenuOpen = !actionsMenuOpen;
|
||||
}}
|
||||
use:tooltip={$t('files.actions')}
|
||||
aria-label={$t('files.actions')}
|
||||
>
|
||||
<Icon name="three-dots" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Directory listing -->
|
||||
<div bind:this={listEl} class="overflow-y-auto px-1.5 pb-1.5 flex-1 min-h-0">
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-8">
|
||||
<Spinner size={16} />
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="flex flex-col items-center justify-center gap-2 py-8 text-center">
|
||||
<p class="text-xs text-red-400">{error}</p>
|
||||
<button
|
||||
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-100"
|
||||
onclick={() => fetchDirectories(currentPath)}>{$t('directory.retry')}</button
|
||||
>
|
||||
</div>
|
||||
{:else if filteredDirs.length === 0}
|
||||
<div class="flex flex-col items-center justify-center py-8">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('directory.noSubdirectories')}</p>
|
||||
</div>
|
||||
{:else}
|
||||
{#each filteredDirs as dir, i (dir.name)}
|
||||
<button
|
||||
data-index={i}
|
||||
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-left transition-colors duration-75
|
||||
{i === selectedIndex
|
||||
? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}"
|
||||
onclick={() => navigateTo(dir.name)}
|
||||
ondblclick={(e) => {
|
||||
e.stopPropagation();
|
||||
const fullPath = currentPath === '/' ? `/${dir.name}` : `${currentPath}/${dir.name}`;
|
||||
addWorkspace(fullPath);
|
||||
goto(`/?workspace=${encodeURIComponent(fullPath)}`);
|
||||
onclose();
|
||||
}}
|
||||
onmouseenter={() => {
|
||||
selectedIndex = i;
|
||||
}}
|
||||
>
|
||||
{#each breadcrumbs as seg, i (seg.path)}
|
||||
{#if i > 1}<span class="text-gray-300 dark:text-gray-600 text-[11px] font-mono">/</span
|
||||
>{/if}
|
||||
{#if i === breadcrumbs.length - 1}
|
||||
<span
|
||||
class="text-[11px] font-mono font-medium text-gray-900 dark:text-white whitespace-nowrap overflow-hidden text-ellipsis"
|
||||
>{seg.name}</span
|
||||
>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="text-[11px] font-mono text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 whitespace-nowrap shrink-0 cursor-pointer rounded px-0.5 hover:bg-gray-200 dark:hover:bg-white/8 transition-colors duration-75"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigateToPath(seg.path);
|
||||
}}
|
||||
onkeydown={() => {}}>{seg.name}</span
|
||||
>
|
||||
{/if}
|
||||
{/each}
|
||||
<span
|
||||
class="ml-1 text-gray-300 dark:text-gray-700 opacity-0 group-hover:opacity-100 transition-opacity duration-150 shrink-0 flex items-center"
|
||||
>
|
||||
<Icon name="pencil" size={10} />
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="flex items-center gap-1.5 cursor-pointer select-none shrink-0">
|
||||
<input type="checkbox" bind:checked={showHidden} class="w-3 h-3 rounded accent-gray-500" />
|
||||
<span class="text-[10px] text-gray-400">{$t('directory.hidden')}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Directory listing -->
|
||||
<div bind:this={listEl} class="flex-1 overflow-y-auto p-1 min-h-0">
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-8">
|
||||
<Spinner size={16} />
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="flex flex-col items-center justify-center gap-2 py-8 text-center">
|
||||
<p class="text-xs text-red-400">{error}</p>
|
||||
<button
|
||||
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-100"
|
||||
onclick={() => fetchDirectories(currentPath)}>{$t('directory.retry')}</button
|
||||
>
|
||||
</div>
|
||||
{:else if filteredDirs.length === 0}
|
||||
<div class="flex flex-col items-center justify-center py-8">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('directory.noSubdirectories')}</p>
|
||||
</div>
|
||||
{:else}
|
||||
{#each filteredDirs as dir, i (dir.name)}
|
||||
<button
|
||||
data-index={i}
|
||||
class="flex items-center gap-2 w-full h-7 px-2 rounded-lg text-left transition-colors duration-75
|
||||
{i === selectedIndex
|
||||
? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}"
|
||||
onclick={() => navigateTo(dir.name)}
|
||||
ondblclick={(e) => {
|
||||
e.stopPropagation();
|
||||
const fullPath = currentPath === '/' ? `/${dir.name}` : `${currentPath}/${dir.name}`;
|
||||
addWorkspace(fullPath);
|
||||
goto(`/?workspace=${encodeURIComponent(fullPath)}`);
|
||||
onclose();
|
||||
}}
|
||||
onmouseenter={() => {
|
||||
selectedIndex = i;
|
||||
}}
|
||||
>
|
||||
<Icon name="folder" size={14} class="shrink-0 text-gray-400" />
|
||||
<span class="flex-1 truncate text-xs">{dir.name}</span>
|
||||
<Icon
|
||||
name="chevron-right"
|
||||
size={12}
|
||||
class="shrink-0 text-gray-300 dark:text-gray-700"
|
||||
/>
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div
|
||||
class="flex items-center gap-2 px-3 py-2 border-t border-gray-200 dark:border-white/6 shrink-0"
|
||||
>
|
||||
<span
|
||||
class="flex-1 text-[11px] text-gray-400 dark:text-gray-600 font-mono truncate min-w-0"
|
||||
title={currentPath}>{currentPath}</span
|
||||
>
|
||||
<button
|
||||
class="text-xs font-medium text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1.5 rounded-lg transition-colors duration-100 shrink-0"
|
||||
onclick={onclose}>{$t('directory.cancel')}</button
|
||||
>
|
||||
<button
|
||||
class="text-xs font-medium text-white dark:text-black bg-gray-900 dark:bg-white hover:bg-gray-800 dark:hover:bg-gray-200 px-3 py-1.5 rounded-lg transition-colors duration-100 shrink-0"
|
||||
onclick={selectCurrent}>{$t('directory.open', { name: currentFolderName })}</button
|
||||
>
|
||||
</div>
|
||||
<Icon name="folder" size={14} class="shrink-0 text-gray-400" />
|
||||
<span class="flex-1 truncate text-xs">{dir.name}</span>
|
||||
<Icon name="chevron-right" size={12} class="shrink-0 text-gray-300 dark:text-gray-700" />
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="flex items-center gap-2 px-3.5 pb-3 pt-1 shrink-0">
|
||||
<span
|
||||
class="flex-1 text-[11px] text-gray-400 dark:text-gray-600 font-mono truncate min-w-0"
|
||||
title={currentPath}>{currentPath}</span
|
||||
>
|
||||
<button
|
||||
class="text-xs font-medium text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1.5 rounded-lg transition-colors duration-100 shrink-0"
|
||||
onclick={onclose}>{$t('directory.cancel')}</button
|
||||
>
|
||||
<button
|
||||
class="text-xs font-medium text-white dark:text-black bg-gray-900 dark:bg-white hover:bg-gray-800 dark:hover:bg-gray-200 px-3 py-1.5 rounded-lg transition-colors duration-100 shrink-0"
|
||||
onclick={selectCurrent}>{$t('directory.open', { name: currentFolderName })}</button
|
||||
>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{#if actionsMenuOpen && actionsBtnEl}
|
||||
<DropdownMenu
|
||||
anchor={actionsBtnEl}
|
||||
align="end"
|
||||
items={[
|
||||
{
|
||||
label: showHidden ? $t('files.hideHidden') : $t('files.showHidden'),
|
||||
icon: 'eye',
|
||||
onclick: () => toggleHidden()
|
||||
}
|
||||
]}
|
||||
onclose={() => (actionsMenuOpen = false)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { markTabUnsaved, updateTabFilePath, activeWorkspace } from '$lib/stores';
|
||||
import {
|
||||
clearTabEdit,
|
||||
markTabUnsaved,
|
||||
updateTabFilePath,
|
||||
activeWorkspace
|
||||
} from '$lib/stores';
|
||||
import { get } from 'svelte/store';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { readFile, writeFile } from '$lib/apis/files';
|
||||
@@ -61,9 +66,10 @@
|
||||
interface Props {
|
||||
filePath: string;
|
||||
tabId: string;
|
||||
edit?: boolean;
|
||||
}
|
||||
|
||||
let { filePath, tabId }: Props = $props();
|
||||
let { filePath, tabId, edit = false }: Props = $props();
|
||||
|
||||
interface FileData {
|
||||
path: string;
|
||||
@@ -122,6 +128,7 @@
|
||||
// Markdown mode: preview (read-only), editor (WYSIWYG), raw (CodeMirror source)
|
||||
type MarkdownMode = 'preview' | 'editor' | 'raw';
|
||||
let markdownMode = $state<MarkdownMode>('preview');
|
||||
let openedInEdit = $state(false);
|
||||
|
||||
// Rich text editor, lazy loaded
|
||||
let RichTextEditor: typeof RichTextEditorType | null = $state(null);
|
||||
@@ -334,6 +341,13 @@
|
||||
if (fileData && !fileData.binary && fileData.content !== null) {
|
||||
if (isMarkdown) {
|
||||
// Preview handled by MarkdownRenderer component
|
||||
if (edit && !openedInEdit) {
|
||||
openedInEdit = true;
|
||||
clearTabEdit(tabId);
|
||||
requestAnimationFrame(() => {
|
||||
enterEditMode();
|
||||
});
|
||||
}
|
||||
} else if (isJson) {
|
||||
try {
|
||||
jsonData = JSON.parse(fileData.content);
|
||||
|
||||
@@ -161,6 +161,11 @@
|
||||
<path d="M1 17H23" />
|
||||
<path d="M12 17V20" />
|
||||
<path d="M9 20H15" />
|
||||
{:else if name === 'phone'}
|
||||
<path
|
||||
d="M8 2.6C8 2.26863 8.26863 2 8.6 2H15.4C15.7314 2 16 2.26863 16 2.6V21.4C16 21.7314 15.7314 22 15.4 22H8.6C8.26863 22 8 21.7314 8 21.4V2.6Z"
|
||||
/>
|
||||
<path d="M11 18.5H13" />
|
||||
{:else if name === 'chevron-left'}
|
||||
<path d="M15 6L9 12L15 18" />
|
||||
{:else if name === 'check'}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<script lang="ts">
|
||||
import { pwaPreferences } from '$lib/stores';
|
||||
import { i18next } from '$lib/i18n';
|
||||
import type { PwaPreferences } from '$lib/intents/types';
|
||||
|
||||
const tr = (key: string, opts?: Record<string, unknown>) => i18next.t(key, opts) as string;
|
||||
|
||||
function updatePref<K extends keyof PwaPreferences>(key: K, value: PwaPreferences[K]) {
|
||||
pwaPreferences.set({ ...$pwaPreferences, [key]: value });
|
||||
}
|
||||
|
||||
function updateShareBehavior(e: Event) {
|
||||
updatePref(
|
||||
'shareBehavior',
|
||||
(e.currentTarget as HTMLSelectElement).value as PwaPreferences['shareBehavior']
|
||||
);
|
||||
}
|
||||
|
||||
function updateImportDestination(e: Event) {
|
||||
updatePref(
|
||||
'importDestination',
|
||||
(e.currentTarget as HTMLSelectElement).value as PwaPreferences['importDestination']
|
||||
);
|
||||
}
|
||||
|
||||
let resetting = $state(false);
|
||||
|
||||
async function resetPwa() {
|
||||
resetting = true;
|
||||
|
||||
try {
|
||||
if ('serviceWorker' in navigator) {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map((registration) => registration.unregister()));
|
||||
}
|
||||
|
||||
if ('caches' in window) {
|
||||
const keys = await caches.keys();
|
||||
await Promise.all(
|
||||
keys.filter((key) => key.startsWith('cptr-')).map((key) => caches.delete(key))
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover pr-1.5 -mr-1.5">
|
||||
<h2 class="text-sm text-gray-900 dark:text-white mb-4">{tr('pwa.settingsTitle')}</h2>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">{tr('pwa.shareBehavior')}</h3>
|
||||
<select
|
||||
class="w-full max-w-[200px] bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-1 cursor-pointer"
|
||||
value={$pwaPreferences.shareBehavior}
|
||||
onchange={updateShareBehavior}
|
||||
>
|
||||
<option value="ask">{tr('pwa.shareAsk')}</option>
|
||||
<option value="chatDraft">{tr('pwa.shareChatDraft')}</option>
|
||||
<option value="noteFile">{tr('pwa.shareNoteFile')}</option>
|
||||
</select>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{tr('pwa.fileImports')}</h3>
|
||||
<select
|
||||
class="w-full max-w-[200px] bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-1 cursor-pointer"
|
||||
value={$pwaPreferences.importDestination}
|
||||
onchange={updateImportDestination}
|
||||
>
|
||||
<option value="workspaceRoot">{tr('pwa.workspaceRoot')}</option>
|
||||
<option value="askFolder">{tr('pwa.askFolder')}</option>
|
||||
<option value="configuredFolder">{tr('pwa.configuredFolder')}</option>
|
||||
</select>
|
||||
{#if $pwaPreferences.importDestination === 'configuredFolder'}
|
||||
<input
|
||||
class="mt-2 w-full h-8 bg-gray-100 dark:bg-white/6 rounded-lg px-2 text-[13px] text-gray-700 dark:text-gray-300 outline-none"
|
||||
placeholder={tr('pwa.importFolderPlaceholder')}
|
||||
value={$pwaPreferences.importFolder ?? ''}
|
||||
oninput={(e) =>
|
||||
updatePref('importFolder', (e.currentTarget as HTMLInputElement).value || undefined)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{tr('pwa.resetTitle')}</h3>
|
||||
<button
|
||||
class="text-[13px] text-gray-500 dark:text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors disabled:opacity-40 disabled:pointer-events-none"
|
||||
onclick={resetPwa}
|
||||
disabled={resetting}
|
||||
>
|
||||
{resetting ? tr('pwa.resetting') : tr('pwa.reset')}
|
||||
</button>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
|
||||
{tr('pwa.resetDesc')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2,6 +2,7 @@
|
||||
import Icon from './Icon.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
import General from './Settings/General.svelte';
|
||||
import PWA from './Settings/PWA.svelte';
|
||||
import Account from './Settings/Account.svelte';
|
||||
import Keyboard from './Settings/Keyboard.svelte';
|
||||
import About from './Settings/About.svelte';
|
||||
@@ -19,6 +20,7 @@
|
||||
|
||||
type Tab =
|
||||
| 'general'
|
||||
| 'pwa'
|
||||
| 'keyboard'
|
||||
| 'account'
|
||||
| 'about'
|
||||
@@ -47,6 +49,7 @@
|
||||
{ id: 'general', label: $t('settings.general'), icon: 'settings' },
|
||||
{ id: 'keyboard', label: $t('settings.keyboard'), icon: 'terminal' },
|
||||
{ id: 'account', label: $t('settings.account'), icon: 'user' },
|
||||
{ id: 'pwa', label: 'PWA', icon: 'phone' },
|
||||
{ id: 'about', label: $t('settings.about'), icon: 'info' }
|
||||
]);
|
||||
|
||||
@@ -118,6 +121,8 @@
|
||||
<div class="flex-1 overflow-y-auto min-h-0 p-4 md:px-5">
|
||||
{#if activeTab === 'general'}
|
||||
<General />
|
||||
{:else if activeTab === 'pwa'}
|
||||
<PWA />
|
||||
{:else if activeTab === 'keyboard'}
|
||||
<Keyboard />
|
||||
{:else if activeTab === 'account'}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<script lang="ts">
|
||||
import Modal from './Modal.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import type { LaunchIntent, ShareBehavior } from '$lib/intents/types';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
intent: LaunchIntent;
|
||||
workspaces: { path: string; name: string }[];
|
||||
onchoose: (path: string, behavior?: ShareBehavior) => void;
|
||||
oncancel: () => void;
|
||||
}
|
||||
|
||||
let { intent, workspaces, onchoose, oncancel }: Props = $props();
|
||||
let behavior = $state<ShareBehavior>('noteFile');
|
||||
let selectedIndex = $state(0);
|
||||
|
||||
const title = $derived($t('intent.chooseWorkspace'));
|
||||
|
||||
const needsShareBehavior = $derived(
|
||||
intent.kind === 'share' && (!intent.shareBehavior || intent.shareBehavior === 'ask')
|
||||
);
|
||||
|
||||
function chooseWorkspace(ws: { path: string; name: string }) {
|
||||
onchoose(ws.path, needsShareBehavior ? behavior : undefined);
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (!workspaces.length) return;
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.min(selectedIndex + 1, workspaces.length - 1);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.max(selectedIndex - 1, 0);
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
chooseWorkspace(workspaces[selectedIndex]);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<Modal
|
||||
onclose={oncancel}
|
||||
class="w-full max-w-[560px] mx-4 max-md:mx-0 max-md:rounded-none max-h-[480px] max-md:max-h-dvh flex flex-col mb-[6vh] max-md:mb-0"
|
||||
>
|
||||
<div class="flex items-center px-3.5 py-3 gap-2">
|
||||
<div class="flex-1 min-w-0">
|
||||
<h2 class="text-sm text-gray-900 dark:text-white truncate">{title}</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if needsShareBehavior}
|
||||
<div class="flex items-center gap-3 px-3.5 pb-2">
|
||||
<label class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0" for="share-behavior">
|
||||
{$t('pwa.shareBehavior')}
|
||||
</label>
|
||||
<select
|
||||
id="share-behavior"
|
||||
bind:value={behavior}
|
||||
class="flex-1 min-w-0 bg-transparent text-xs text-gray-700 dark:text-gray-300 outline-none cursor-pointer"
|
||||
>
|
||||
<option value="chatDraft">{$t('pwa.shareChatDraft')}</option>
|
||||
<option value="noteFile">{$t('pwa.shareNoteFile')}</option>
|
||||
</select>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="overflow-y-auto px-1.5 pb-1.5 flex-1 min-h-0">
|
||||
{#if workspaces.length}
|
||||
{#each workspaces as ws, i (ws.path)}
|
||||
<button
|
||||
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-left transition-colors duration-75
|
||||
{i === selectedIndex
|
||||
? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}"
|
||||
onclick={() => chooseWorkspace(ws)}
|
||||
onmouseenter={() => (selectedIndex = i)}
|
||||
>
|
||||
<Icon name="folder" size={14} class="shrink-0 text-gray-400" />
|
||||
<span class="text-xs shrink-0 truncate max-w-[34%]">{ws.name}</span>
|
||||
<span
|
||||
class="text-[11px] text-gray-400 overflow-hidden text-ellipsis whitespace-nowrap font-mono"
|
||||
>
|
||||
{ws.path}
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
{:else}
|
||||
<div class="flex flex-col items-center justify-center gap-3 py-10 text-center">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('pwa.noWorkspaces')}</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-2 px-3.5 pb-3 pt-1 shrink-0">
|
||||
<button
|
||||
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1.5 rounded-lg transition-colors duration-100 shrink-0"
|
||||
onclick={oncancel}
|
||||
>
|
||||
{$t('pwa.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -100,6 +100,16 @@
|
||||
const TTS_AUDIO_CACHE_LIMIT_BYTES = 20 * 1024 * 1024;
|
||||
const TTS_MAX_PREFETCH = 2;
|
||||
|
||||
onMount(() => {
|
||||
if (initialChatId || typeof sessionStorage === 'undefined') return;
|
||||
const key = `cptr:intent:chatDraft:${workspace}`;
|
||||
const draft = sessionStorage.getItem(key);
|
||||
if (draft) {
|
||||
inputText = draft;
|
||||
sessionStorage.removeItem(key);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Windowed rendering ──────────────────────────────────────
|
||||
// Only render the last N turns to keep the DOM light for long chats.
|
||||
// A "turn" is a user+assistant message pair, so 6 turns = 12 messages.
|
||||
|
||||
@@ -91,6 +91,30 @@
|
||||
|
||||
"settings.back": "Back",
|
||||
"settings.general": "General",
|
||||
"pwa.settingsTitle": "Progressive Web App",
|
||||
"intent.chooseWorkspace": "Workspace",
|
||||
"intent.newNote": "Note",
|
||||
"intent.newChat": "Chat",
|
||||
"intent.newTerminal": "Terminal",
|
||||
"intent.share": "Share",
|
||||
"intent.importFiles": "Import files",
|
||||
"pwa.cancel": "Cancel",
|
||||
"pwa.noWorkspaces": "No workspaces available.",
|
||||
"pwa.shareBehavior": "Shared content",
|
||||
"pwa.shareAsk": "Ask every time",
|
||||
"pwa.shareChatDraft": "Chat draft",
|
||||
"pwa.shareNoteFile": "Note file",
|
||||
"pwa.fileImports": "File imports",
|
||||
"pwa.workspaceRoot": "Workspace root",
|
||||
"pwa.askFolder": "Ask for folder",
|
||||
"pwa.configuredFolder": "Configured folder",
|
||||
"pwa.importFolderPlaceholder": "Folder path or workspace-relative folder",
|
||||
"pwa.resetTitle": "Troubleshooting",
|
||||
"pwa.reset": "Reset PWA",
|
||||
"pwa.resetting": "Resetting...",
|
||||
"pwa.resetDesc": "Unregisters the service worker and clears the cached app shell. Your data stays.",
|
||||
"pwa.unreachable": "Computer is unreachable",
|
||||
"pwa.connectionRestored": "Connection restored",
|
||||
"settings.account": "Account",
|
||||
"settings.about": "About",
|
||||
"settings.save": "Save",
|
||||
@@ -803,8 +827,6 @@
|
||||
"onboarding.connectAiNudge": "Connect an AI provider to start chatting.",
|
||||
"onboarding.goToConnections": "Settings → Connections",
|
||||
|
||||
"pwa.reconnecting": "Reconnecting",
|
||||
"pwa.reconnectingTo": "Reconnecting to {{hostname}}",
|
||||
"chat.share": "Share",
|
||||
|
||||
"general.storage": "Storage",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { SharePayload } from './types';
|
||||
|
||||
const DB_NAME = 'cptr-shares';
|
||||
const DB_VERSION = 1;
|
||||
const SHARE_STORE = 'share-payloads';
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onupgradeneeded = () => {
|
||||
const db = req.result;
|
||||
if (!db.objectStoreNames.contains(SHARE_STORE)) db.createObjectStore(SHARE_STORE);
|
||||
};
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSharePayload(id: string): Promise<SharePayload | null> {
|
||||
if (typeof indexedDB === 'undefined') return null;
|
||||
const db = await openDb();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(SHARE_STORE, 'readonly');
|
||||
const req = tx.objectStore(SHARE_STORE).get(id);
|
||||
req.onsuccess = () => resolve((req.result as SharePayload | undefined) ?? null);
|
||||
req.onerror = () => reject(req.error);
|
||||
tx.oncomplete = () => db.close();
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteSharePayload(id: string): Promise<void> {
|
||||
if (typeof indexedDB === 'undefined') return;
|
||||
const db = await openDb();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(SHARE_STORE, 'readwrite');
|
||||
const req = tx.objectStore(SHARE_STORE).delete(id);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
tx.oncomplete = () => db.close();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
export type LaunchIntentKind =
|
||||
| 'newNote'
|
||||
| 'newChat'
|
||||
| 'newTerminal'
|
||||
| 'openWorkspace'
|
||||
| 'search'
|
||||
| 'openChat'
|
||||
| 'openFile'
|
||||
| 'openDir'
|
||||
| 'share'
|
||||
| 'importFiles';
|
||||
|
||||
export type ShareBehavior = 'ask' | 'chatDraft' | 'noteFile';
|
||||
export type ImportDestination = 'workspaceRoot' | 'askFolder' | 'configuredFolder';
|
||||
|
||||
export interface PwaPreferences {
|
||||
shareBehavior: ShareBehavior;
|
||||
importDestination: ImportDestination;
|
||||
importFolder?: string;
|
||||
}
|
||||
|
||||
export interface ShareFilePayload {
|
||||
name: string;
|
||||
type: string;
|
||||
lastModified?: number;
|
||||
file: File;
|
||||
}
|
||||
|
||||
export interface SharePayload {
|
||||
id?: string;
|
||||
title?: string;
|
||||
text?: string;
|
||||
url?: string;
|
||||
files?: ShareFilePayload[];
|
||||
}
|
||||
|
||||
export interface FileImportPayload {
|
||||
files: File[];
|
||||
}
|
||||
|
||||
export interface LaunchIntent {
|
||||
kind: LaunchIntentKind;
|
||||
workspace?: string;
|
||||
chatId?: string | null;
|
||||
filePath?: string;
|
||||
dirPath?: string;
|
||||
targetDir?: string;
|
||||
payloadId?: string;
|
||||
shareBehavior?: ShareBehavior;
|
||||
share?: SharePayload;
|
||||
importFiles?: FileImportPayload;
|
||||
}
|
||||
|
||||
export const defaultPwaPreferences: PwaPreferences = {
|
||||
shareBehavior: 'ask',
|
||||
importDestination: 'workspaceRoot'
|
||||
};
|
||||
@@ -28,6 +28,7 @@ import { listSessions, createSession, deleteSession } from '$lib/apis/terminal';
|
||||
import { changeLocale, i18next } from '$lib/i18n';
|
||||
import { streamingChatTabs } from '$lib/stores/chat';
|
||||
import { keybindings, loadKeybindings } from '$lib/stores/keybindings';
|
||||
import { defaultPwaPreferences, type PwaPreferences } from '$lib/intents/types';
|
||||
|
||||
// ── Types ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -36,6 +37,7 @@ export interface Tab {
|
||||
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview';
|
||||
label: string;
|
||||
filePath?: string;
|
||||
edit?: boolean;
|
||||
path?: string; // generic path (e.g. for chat)
|
||||
sessionId?: string;
|
||||
port?: number;
|
||||
@@ -78,6 +80,7 @@ export interface UserPreferences {
|
||||
selectedModelId?: string; // last selected chat model, synced across browsers
|
||||
requestParams?: Record<string, unknown>; // arbitrary params merged into API request body
|
||||
showUpdateToast?: boolean; // show version update notifications (default true)
|
||||
pwa?: PwaPreferences;
|
||||
}
|
||||
|
||||
export type Theme = 'dark' | 'light' | 'system';
|
||||
@@ -170,6 +173,7 @@ export const isGitRepo = writable(false);
|
||||
export type StreamingBehavior = 'queue' | 'interrupt';
|
||||
export const streamingBehavior = writable<StreamingBehavior>('queue');
|
||||
export const selectedModelId = writable<string>('');
|
||||
export const pwaPreferences = writable<PwaPreferences>(defaultPwaPreferences);
|
||||
|
||||
/** Saved workspace path order for sidebar drag-reorder. */
|
||||
export const workspaceOrder = writable<string[]>([]);
|
||||
@@ -305,7 +309,8 @@ function persistPreferences(): void {
|
||||
version: get(lastSeenVersion),
|
||||
selectedModelId: get(selectedModelId) || undefined,
|
||||
requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined,
|
||||
showUpdateToast: get(showUpdateToastPref)
|
||||
showUpdateToast: get(showUpdateToastPref),
|
||||
pwa: get(pwaPreferences)
|
||||
};
|
||||
savePreferences(prefs as unknown as Record<string, unknown>).catch(() => {});
|
||||
}, 300);
|
||||
@@ -351,6 +356,9 @@ function subscribeForPersistence() {
|
||||
showUpdateToastPref.subscribe(() => {
|
||||
if (get(stateLoaded)) persistPreferences();
|
||||
});
|
||||
pwaPreferences.subscribe(() => {
|
||||
if (get(stateLoaded)) persistPreferences();
|
||||
});
|
||||
i18next.on('languageChanged', () => {
|
||||
if (get(stateLoaded)) persistPreferences();
|
||||
});
|
||||
@@ -379,6 +387,12 @@ export async function loadPreferences(): Promise<void> {
|
||||
if (prefs.selectedModelId) selectedModelId.set(prefs.selectedModelId as string);
|
||||
if (prefs.requestParams) requestParams.set(prefs.requestParams as Record<string, unknown>);
|
||||
if (prefs.showUpdateToast !== undefined) showUpdateToastPref.set(prefs.showUpdateToast as boolean);
|
||||
const pwaPrefs = prefs.pwa;
|
||||
if (pwaPrefs)
|
||||
pwaPreferences.set({
|
||||
...defaultPwaPreferences,
|
||||
...(pwaPrefs as PwaPreferences)
|
||||
});
|
||||
} catch {
|
||||
// First run, no preferences yet
|
||||
}
|
||||
@@ -627,7 +641,11 @@ export function reorderTabs(oldIndex: number, newIndex: number, groupId?: string
|
||||
});
|
||||
}
|
||||
|
||||
export function openFileTab(filePath: string, targetGroupId?: string): void {
|
||||
export function openFileTab(
|
||||
filePath: string,
|
||||
targetGroupId?: string,
|
||||
options: { edit?: boolean } = {}
|
||||
): void {
|
||||
const ws = get(currentWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
@@ -638,6 +656,13 @@ export function openFileTab(filePath: string, targetGroupId?: string): void {
|
||||
// Reuse existing tab within this group
|
||||
const existing = group.tabs.find((t) => t.type === 'file' && t.filePath === filePath);
|
||||
if (existing) {
|
||||
if (options.edit) {
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: tabs.map((t) => (t.id === existing.id ? { ...t, edit: true } : t)),
|
||||
activeTabId: existing.id
|
||||
}));
|
||||
return;
|
||||
}
|
||||
setActiveTab(existing.id, gid);
|
||||
return;
|
||||
}
|
||||
@@ -647,7 +672,8 @@ export function openFileTab(filePath: string, targetGroupId?: string): void {
|
||||
id: nextId(),
|
||||
type: 'file',
|
||||
label: name,
|
||||
filePath
|
||||
filePath,
|
||||
edit: options.edit
|
||||
};
|
||||
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
@@ -903,6 +929,24 @@ export function updateTabFilePath(tabId: string, newPath: string): void {
|
||||
});
|
||||
}
|
||||
|
||||
export function clearTabEdit(tabId: string): void {
|
||||
currentWorkspace.update((ws) => {
|
||||
if (!ws) return ws;
|
||||
return {
|
||||
...ws,
|
||||
groups: ws.groups.map((g) => ({
|
||||
...g,
|
||||
tabs: g.tabs.map((t) => {
|
||||
if (t.id !== tabId || !t.edit) return t;
|
||||
const next = { ...t };
|
||||
delete next.edit;
|
||||
return next;
|
||||
})
|
||||
}))
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── Split / Editor Group actions ────────────────────────────────
|
||||
|
||||
/** Open a file in a new split group (creates the group if needed) */
|
||||
|
||||
@@ -14,8 +14,7 @@
|
||||
import AuthScreen from '$lib/components/AuthScreen.svelte';
|
||||
import ChangelogModal from '$lib/components/ChangelogModal.svelte';
|
||||
import UpdateToast from '$lib/components/UpdateToast.svelte';
|
||||
import ConnectionMonitor from '$lib/components/ConnectionMonitor.svelte';
|
||||
import { Toaster } from 'svelte-sonner';
|
||||
import { Toaster, toast } from 'svelte-sonner';
|
||||
import {
|
||||
activeTab,
|
||||
currentWorkspace,
|
||||
@@ -50,6 +49,9 @@
|
||||
let showSettings = $state(false);
|
||||
let showUpdateToast = $state(false);
|
||||
let showSetup = $state(false);
|
||||
let connectionToast: string | number | undefined;
|
||||
let applyingServiceWorkerUpdate = false;
|
||||
const BROWSER_SW_CLEANUP_RELOAD = 'cptr:pwa:browser-sw-cleanup-reload';
|
||||
|
||||
// Auth state
|
||||
type AuthState = 'checking' | 'needs_setup' | 'needs_login' | 'authenticated';
|
||||
@@ -95,12 +97,23 @@
|
||||
// iOS may fire 'scroll' instead of 'resize' when keyboard opens.
|
||||
vv?.addEventListener('resize', syncKeyboardInset);
|
||||
vv?.addEventListener('scroll', syncKeyboardInset);
|
||||
|
||||
if (isInstalledPwa()) {
|
||||
registerServiceWorker().catch(() => {});
|
||||
} else {
|
||||
cleanBrowserServiceWorker().catch(() => {});
|
||||
}
|
||||
window.addEventListener('offline', showOfflineToast);
|
||||
window.addEventListener('online', showOnlineToast);
|
||||
|
||||
return () => {
|
||||
clearInterval(healthCheck);
|
||||
document.documentElement.style.removeProperty('--keyboard-inset-bottom');
|
||||
window.removeEventListener('resize', syncKeyboardInset);
|
||||
vv?.removeEventListener('resize', syncKeyboardInset);
|
||||
vv?.removeEventListener('scroll', syncKeyboardInset);
|
||||
window.removeEventListener('offline', showOfflineToast);
|
||||
window.removeEventListener('online', showOnlineToast);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -233,6 +246,84 @@
|
||||
}
|
||||
}
|
||||
|
||||
function isInstalledPwa() {
|
||||
const nav = navigator as Navigator & { standalone?: boolean };
|
||||
return (
|
||||
nav.standalone === true ||
|
||||
window.matchMedia('(display-mode: standalone)').matches ||
|
||||
window.matchMedia('(display-mode: window-controls-overlay)').matches
|
||||
);
|
||||
}
|
||||
|
||||
function showOfflineToast() {
|
||||
if (connectionToast) return;
|
||||
connectionToast = toast.error($t('pwa.unreachable'), { duration: Infinity });
|
||||
}
|
||||
|
||||
function showOnlineToast() {
|
||||
if (connectionToast) toast.dismiss(connectionToast);
|
||||
connectionToast = undefined;
|
||||
toast.success($t('pwa.connectionRestored'));
|
||||
}
|
||||
|
||||
async function clearCptrCaches() {
|
||||
if (!('caches' in window)) return;
|
||||
const keys = await caches.keys();
|
||||
await Promise.all(keys.filter((key) => key.startsWith('cptr-')).map((key) => caches.delete(key)));
|
||||
}
|
||||
|
||||
function isCptrWorker(registration: ServiceWorkerRegistration) {
|
||||
const script =
|
||||
registration.active?.scriptURL ||
|
||||
registration.waiting?.scriptURL ||
|
||||
registration.installing?.scriptURL ||
|
||||
'';
|
||||
return script.endsWith('/service-worker.js');
|
||||
}
|
||||
|
||||
async function cleanBrowserServiceWorker() {
|
||||
if (!('serviceWorker' in navigator)) return;
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
const cptrRegistrations = registrations.filter(isCptrWorker);
|
||||
if (!cptrRegistrations.length) {
|
||||
sessionStorage.removeItem(BROWSER_SW_CLEANUP_RELOAD);
|
||||
return;
|
||||
}
|
||||
|
||||
const hadController = !!navigator.serviceWorker.controller;
|
||||
await Promise.all(cptrRegistrations.map((registration) => registration.unregister()));
|
||||
await clearCptrCaches();
|
||||
if (hadController && !sessionStorage.getItem(BROWSER_SW_CLEANUP_RELOAD)) {
|
||||
sessionStorage.setItem(BROWSER_SW_CLEANUP_RELOAD, '1');
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
async function registerServiceWorker() {
|
||||
if (!('serviceWorker' in navigator)) return;
|
||||
const registration = await navigator.serviceWorker.register('/service-worker.js');
|
||||
if (registration.waiting && navigator.serviceWorker.controller) {
|
||||
applyServiceWorkerUpdate(registration);
|
||||
}
|
||||
registration.addEventListener('updatefound', () => {
|
||||
const worker = registration.installing;
|
||||
if (!worker) return;
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state === 'installed' && navigator.serviceWorker.controller) {
|
||||
applyServiceWorkerUpdate(registration);
|
||||
}
|
||||
});
|
||||
});
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
if (applyingServiceWorkerUpdate) window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
function applyServiceWorkerUpdate(registration: ServiceWorkerRegistration) {
|
||||
applyingServiceWorkerUpdate = true;
|
||||
registration.waiting?.postMessage({ type: 'SKIP_WAITING' });
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
const action = matchKeybinding(e);
|
||||
if (!action) return;
|
||||
@@ -372,7 +463,6 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<ConnectionMonitor />
|
||||
<Toaster
|
||||
position="top-right"
|
||||
theme="system"
|
||||
|
||||
@@ -3,29 +3,31 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import {
|
||||
currentWorkspace,
|
||||
activeTab,
|
||||
workspaceList,
|
||||
addWorkspace,
|
||||
loadWorkspace,
|
||||
gitReviewOpen,
|
||||
setActiveGroup,
|
||||
setSplitRatio,
|
||||
moveTabToGroup,
|
||||
openInSplit,
|
||||
openTabInSplit,
|
||||
setSplitDirection,
|
||||
openChatTab,
|
||||
openFileTab,
|
||||
openTerminalTab,
|
||||
setFileBrowserCwd,
|
||||
appVersion,
|
||||
showChangelog
|
||||
showChangelog,
|
||||
showSearch,
|
||||
pwaPreferences
|
||||
} from '$lib/stores';
|
||||
import { splitActive } from '$lib/stores';
|
||||
import type { Tab, EditorGroup, WorkspaceState } from '$lib/stores';
|
||||
import type { Tab, EditorGroup } from '$lib/stores';
|
||||
import { t } from '$lib/i18n';
|
||||
import { get } from 'svelte/store';
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
import { createSession } from '$lib/apis/terminal';
|
||||
import { createEntry, writeFile, uploadFiles as uploadFilesApi } from '$lib/apis/files';
|
||||
import { deleteSharePayload, getSharePayload } from '$lib/intents/payloadStore';
|
||||
import type { LaunchIntent, ShareBehavior, SharePayload } from '$lib/intents/types';
|
||||
import FileBrowser from '$lib/components/FileBrowser.svelte';
|
||||
import FileEditor from '$lib/components/FileEditor.svelte';
|
||||
import GitView from '$lib/components/GitView.svelte';
|
||||
@@ -35,10 +37,26 @@
|
||||
import DirectoryPicker from '$lib/components/DirectoryPicker.svelte';
|
||||
import GroupTabBar from '$lib/components/GroupTabBar.svelte';
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import WorkspacePicker from '$lib/components/WorkspacePicker.svelte';
|
||||
import SystemInfo from '$lib/components/SystemInfo.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
|
||||
let showPicker = $state(false);
|
||||
let pendingIntent = $state<LaunchIntent | null>(null);
|
||||
let folderPickerIntent = $state<LaunchIntent | null>(null);
|
||||
let folderPickerWorkspace = $state<string | null>(null);
|
||||
const INTENT_URL_KEYS = [
|
||||
'intent',
|
||||
'chatId',
|
||||
'file',
|
||||
'dir',
|
||||
'targetDir',
|
||||
'payload',
|
||||
'shareBehavior',
|
||||
'title',
|
||||
'text',
|
||||
'url'
|
||||
];
|
||||
|
||||
// ── URL-driven workspace loading ───────────────────────────────
|
||||
// The workspace path comes from the URL query param: ?workspace=/path/to/dir
|
||||
@@ -46,36 +64,253 @@
|
||||
// Intent params (chatId, file, dir) are processed AFTER loading.
|
||||
|
||||
let lastLoadedPath = $state<string | null>(null);
|
||||
type LaunchQueueWindow = Window & {
|
||||
__cptrLaunchQueueBound?: boolean;
|
||||
launchQueue?: {
|
||||
setConsumer: (consumer: (params: { files?: { getFile: () => Promise<File> }[] }) => void) => void;
|
||||
};
|
||||
};
|
||||
|
||||
function processIntentParams() {
|
||||
function urlIntent(url: URL): LaunchIntent | null {
|
||||
const protocol = webCptrIntent(url.searchParams.get('intent'));
|
||||
const params = protocol?.params ?? url.searchParams;
|
||||
const intent = protocol?.intent ?? url.searchParams.get('intent');
|
||||
const workspace = params.get('workspace') || undefined;
|
||||
const chatId = params.get('chatId');
|
||||
const filePath = params.get('file');
|
||||
const dirPath = params.get('dir');
|
||||
|
||||
if (intent === 'newNote') return { kind: 'newNote', workspace };
|
||||
if (intent === 'newChat') return { kind: 'newChat', workspace };
|
||||
if (intent === 'newTerminal') return { kind: 'newTerminal', workspace };
|
||||
if (intent === 'openWorkspace') return { kind: 'openWorkspace' };
|
||||
if (intent === 'search') return { kind: 'search', workspace };
|
||||
if (intent === 'importFiles') {
|
||||
return { kind: 'importFiles', workspace, targetDir: params.get('targetDir') || undefined };
|
||||
}
|
||||
if (intent === 'share') {
|
||||
return {
|
||||
kind: 'share',
|
||||
workspace,
|
||||
payloadId: params.get('payload') || undefined,
|
||||
targetDir: params.get('targetDir') || undefined,
|
||||
shareBehavior: (params.get('shareBehavior') || undefined) as ShareBehavior | undefined,
|
||||
share: {
|
||||
title: params.get('title') || undefined,
|
||||
text: params.get('text') || undefined,
|
||||
url: params.get('url') || undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
if (chatId !== null) return { kind: 'openChat', workspace, chatId: chatId || null };
|
||||
if (filePath) return { kind: 'openFile', workspace, filePath };
|
||||
if (dirPath) return { kind: 'openDir', workspace, dirPath };
|
||||
return null;
|
||||
}
|
||||
|
||||
function webCptrIntent(raw: string | null): { intent: string | null; params: URLSearchParams } | null {
|
||||
if (!raw) return null;
|
||||
let decoded = raw;
|
||||
try {
|
||||
decoded = decodeURIComponent(raw);
|
||||
} catch {}
|
||||
if (!decoded.startsWith('web+cptr:')) return null;
|
||||
try {
|
||||
const parsed = new URL(decoded);
|
||||
return {
|
||||
intent:
|
||||
parsed.searchParams.get('intent') ||
|
||||
parsed.hostname ||
|
||||
parsed.pathname.replace(/^\/+/, '') ||
|
||||
null,
|
||||
params: parsed.searchParams
|
||||
};
|
||||
} catch {
|
||||
const rest = decoded.replace(/^web\+cptr:(\/\/)?/, '');
|
||||
const [intentPart, query = ''] = rest.split('?');
|
||||
return { intent: intentPart.replace(/^\/+/, '') || null, params: new URLSearchParams(query) };
|
||||
}
|
||||
}
|
||||
|
||||
function clearIntentUrl(url: URL): string {
|
||||
const next = new URL(url);
|
||||
for (const key of INTENT_URL_KEYS) next.searchParams.delete(key);
|
||||
return next.pathname + next.search;
|
||||
}
|
||||
|
||||
function noteBaseName(now = new Date()): string {
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `note-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(
|
||||
now.getHours()
|
||||
)}${pad(now.getMinutes())}`;
|
||||
}
|
||||
|
||||
function shareMarkdown(payload: SharePayload): string {
|
||||
const lines: string[] = [];
|
||||
if (payload.title) lines.push(`# ${payload.title.trim()}`, '');
|
||||
if (payload.text) lines.push(payload.text.trim(), '');
|
||||
if (payload.url) lines.push(payload.url.trim(), '');
|
||||
if (payload.files?.length) {
|
||||
lines.push('Files:', ...payload.files.map((file) => `- ${file.name}`), '');
|
||||
}
|
||||
return lines.join('\n').trimEnd() + '\n';
|
||||
}
|
||||
|
||||
async function processIntentParams() {
|
||||
const url = new URL($page.url);
|
||||
const chatId = url.searchParams.get('chatId');
|
||||
const filePath = url.searchParams.get('file');
|
||||
const dirPath = url.searchParams.get('dir');
|
||||
const parsed = urlIntent(url);
|
||||
if (parsed) history.replaceState(history.state, '', clearIntentUrl(url));
|
||||
if (!parsed) return;
|
||||
await handleIntent(parsed);
|
||||
}
|
||||
|
||||
let dirty = false;
|
||||
if (url.searchParams.has('chatId')) {
|
||||
if (chatId) {
|
||||
openChatTab(chatId);
|
||||
} else {
|
||||
async function handleIntent(intent: LaunchIntent) {
|
||||
if (intent.kind === 'openWorkspace') {
|
||||
showPicker = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const targetWorkspace = intent.workspace;
|
||||
const needsWorkspace = intentNeedsExplicitWorkspace(intent.kind);
|
||||
if (needsWorkspace && !targetWorkspace) {
|
||||
pendingIntent = intent;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (intent.kind) {
|
||||
case 'newNote':
|
||||
await createNote(targetWorkspace!);
|
||||
break;
|
||||
case 'newChat':
|
||||
openChatTab();
|
||||
break;
|
||||
case 'newTerminal':
|
||||
await openTerminalTab();
|
||||
break;
|
||||
case 'search':
|
||||
showSearch.set(true);
|
||||
break;
|
||||
case 'openChat':
|
||||
openChatTab(intent.chatId ?? undefined);
|
||||
break;
|
||||
case 'openFile':
|
||||
if (intent.filePath) openFileTab(intent.filePath);
|
||||
break;
|
||||
case 'openDir':
|
||||
if (intent.dirPath) setFileBrowserCwd(intent.dirPath);
|
||||
break;
|
||||
case 'share':
|
||||
await handleShareIntent(intent, targetWorkspace!);
|
||||
break;
|
||||
case 'importFiles':
|
||||
await importIntentFiles(intent, targetWorkspace!);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function intentNeedsExplicitWorkspace(kind: LaunchIntent['kind']): boolean {
|
||||
return !['openWorkspace', 'search'].includes(kind);
|
||||
}
|
||||
|
||||
async function createNote(workspacePath: string, content = '') {
|
||||
if (get(currentWorkspace)?.path !== workspacePath) {
|
||||
await loadWorkspace(workspacePath);
|
||||
}
|
||||
|
||||
const base = noteBaseName();
|
||||
for (let i = 1; i < 100; i += 1) {
|
||||
const suffix = i === 1 ? '' : `-${i}`;
|
||||
const path = `${workspacePath}/${base}${suffix}.md`;
|
||||
try {
|
||||
await createEntry(path, 'file');
|
||||
if (content) await writeFile(path, content);
|
||||
openFileTab(path, undefined, { edit: true });
|
||||
return path;
|
||||
} catch (e: any) {
|
||||
if (e?.status !== 409) throw e;
|
||||
}
|
||||
url.searchParams.delete('chatId');
|
||||
dirty = true;
|
||||
}
|
||||
if (filePath) {
|
||||
openFileTab(filePath);
|
||||
url.searchParams.delete('file');
|
||||
dirty = true;
|
||||
throw new Error('Could not create note');
|
||||
}
|
||||
|
||||
async function handleShareIntent(intent: LaunchIntent, workspacePath: string) {
|
||||
const behavior = intent.shareBehavior ?? get(pwaPreferences).shareBehavior;
|
||||
if (behavior === 'ask') {
|
||||
pendingIntent = intent;
|
||||
return;
|
||||
}
|
||||
if (dirPath) {
|
||||
setFileBrowserCwd(dirPath);
|
||||
url.searchParams.delete('dir');
|
||||
dirty = true;
|
||||
|
||||
let share = intent.share;
|
||||
if (intent.payloadId) {
|
||||
share = (await getSharePayload(intent.payloadId)) ?? share;
|
||||
await deleteSharePayload(intent.payloadId).catch(() => {});
|
||||
}
|
||||
if (dirty) {
|
||||
history.replaceState(history.state, '', url.pathname + url.search);
|
||||
if (!share) return;
|
||||
|
||||
if (behavior === 'chatDraft') {
|
||||
sessionStorage.setItem(`cptr:intent:chatDraft:${workspacePath}`, shareMarkdown(share));
|
||||
openChatTab();
|
||||
return;
|
||||
}
|
||||
await createNote(workspacePath, shareMarkdown(share));
|
||||
}
|
||||
|
||||
async function importIntentFiles(intent: LaunchIntent, workspacePath: string) {
|
||||
const files = intent.importFiles?.files;
|
||||
if (!files?.length) return;
|
||||
const prefs = get(pwaPreferences);
|
||||
if (prefs.importDestination === 'askFolder' && !intent.targetDir) {
|
||||
folderPickerIntent = intent;
|
||||
folderPickerWorkspace = workspacePath;
|
||||
showPicker = true;
|
||||
return;
|
||||
}
|
||||
const directory = resolveImportDirectory(workspacePath, intent.targetDir);
|
||||
for (const file of files) {
|
||||
const form = new FormData();
|
||||
form.append('file', file, file.name);
|
||||
form.append('directory', directory);
|
||||
await uploadFilesApi(directory, form);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveImportDirectory(workspacePath: string, targetDir?: string): string {
|
||||
if (targetDir) return targetDir;
|
||||
const prefs = get(pwaPreferences);
|
||||
if (prefs.importDestination !== 'configuredFolder' || !prefs.importFolder?.trim()) {
|
||||
return workspacePath;
|
||||
}
|
||||
const folder = prefs.importFolder.trim();
|
||||
if (folder.startsWith('/')) return folder;
|
||||
return `${workspacePath}/${folder.replace(/^\/+/, '')}`;
|
||||
}
|
||||
|
||||
async function chooseIntentWorkspace(path: string, behavior?: ShareBehavior) {
|
||||
if (!pendingIntent) return;
|
||||
addWorkspace(path);
|
||||
const intent: LaunchIntent = {
|
||||
...pendingIntent,
|
||||
workspace: path,
|
||||
shareBehavior: behavior ?? pendingIntent.shareBehavior
|
||||
};
|
||||
pendingIntent = null;
|
||||
const params = new URLSearchParams({ workspace: path });
|
||||
await goto(`/?${params.toString()}`, { replaceState: true });
|
||||
if (get(currentWorkspace)?.path !== path) await loadWorkspace(path);
|
||||
await handleIntent(intent);
|
||||
}
|
||||
|
||||
function handlePickedImportFolder(path: string) {
|
||||
if (!folderPickerIntent || !folderPickerWorkspace) return;
|
||||
const intent: LaunchIntent = {
|
||||
...folderPickerIntent,
|
||||
workspace: folderPickerWorkspace,
|
||||
targetDir: path
|
||||
};
|
||||
folderPickerIntent = null;
|
||||
folderPickerWorkspace = null;
|
||||
showPicker = false;
|
||||
void handleIntent(intent);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
@@ -90,9 +325,28 @@
|
||||
} else if (!wsPath) {
|
||||
lastLoadedPath = null;
|
||||
currentWorkspace.set(null);
|
||||
processIntentParams();
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const w = window as LaunchQueueWindow;
|
||||
if (!w.launchQueue || w.__cptrLaunchQueueBound) return;
|
||||
w.__cptrLaunchQueueBound = true;
|
||||
w.launchQueue.setConsumer(async (launchParams) => {
|
||||
const handles = launchParams.files ?? [];
|
||||
if (!handles.length) return;
|
||||
const files: File[] = [];
|
||||
for (const handle of handles) {
|
||||
try {
|
||||
files.push(await handle.getFile());
|
||||
} catch {}
|
||||
}
|
||||
if (files.length) await handleIntent({ kind: 'importFiles', importFiles: { files } });
|
||||
});
|
||||
});
|
||||
|
||||
// Welcome page data
|
||||
let welcomeData = $state<{
|
||||
hostname: string;
|
||||
@@ -123,7 +377,7 @@
|
||||
if (!$currentWorkspace) {
|
||||
getWelcome()
|
||||
.then((data) => {
|
||||
welcomeData = data;
|
||||
welcomeData = data as typeof welcomeData;
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
@@ -166,7 +420,10 @@
|
||||
|
||||
function quickOpen(path: string) {
|
||||
addWorkspace(path);
|
||||
goto(`/?workspace=${encodeURIComponent(path)}`);
|
||||
// Carry forward any pending intent params through workspace selection
|
||||
const params = new URLSearchParams($page.url.searchParams);
|
||||
params.set('workspace', path);
|
||||
goto(`/?${params.toString()}`);
|
||||
}
|
||||
|
||||
function shortenPath(path: string): string {
|
||||
@@ -388,10 +645,6 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showPicker}
|
||||
<DirectoryPicker onclose={() => (showPicker = false)} />
|
||||
{/if}
|
||||
{:else}
|
||||
<!-- Editor groups layout -->
|
||||
<div
|
||||
@@ -445,7 +698,11 @@
|
||||
<!-- Persist all tab instances so state survives tab switches (like VS Code) -->
|
||||
{#each group.tabs.filter((t) => t.type === 'file' && t.filePath) as tab (tab.id)}
|
||||
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
|
||||
<FileEditor filePath={tab.filePath} tabId={tab.id} />
|
||||
<FileEditor
|
||||
filePath={tab.filePath!}
|
||||
tabId={tab.id}
|
||||
edit={tab.edit === true}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
@@ -463,13 +720,13 @@
|
||||
|
||||
{#each group.tabs.filter((t) => t.type === 'terminal' && t.sessionId) as tab (tab.id)}
|
||||
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
|
||||
<Terminal sessionId={tab.sessionId} />
|
||||
<Terminal sessionId={tab.sessionId!} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#each group.tabs.filter((t) => t.type === 'preview' && t.port) as tab (tab.id)}
|
||||
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
|
||||
<PortPreview port={tab.port} />
|
||||
<PortPreview port={tab.port!} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
@@ -497,6 +754,26 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if pendingIntent}
|
||||
<WorkspacePicker
|
||||
intent={pendingIntent}
|
||||
workspaces={$workspaceList}
|
||||
onchoose={chooseIntentWorkspace}
|
||||
oncancel={() => (pendingIntent = null)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if showPicker}
|
||||
<DirectoryPicker
|
||||
onclose={() => {
|
||||
showPicker = false;
|
||||
folderPickerIntent = null;
|
||||
folderPickerWorkspace = null;
|
||||
}}
|
||||
onselect={folderPickerIntent ? handlePickedImportFolder : undefined}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../app.css";
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/// <reference types="@sveltejs/kit" />
|
||||
/// <reference lib="webworker" />
|
||||
|
||||
import { build, files, version } from '$service-worker';
|
||||
|
||||
const sw = self as unknown as ServiceWorkerGlobalScope;
|
||||
const CACHE = `cptr-${version}`;
|
||||
const ASSETS = [...new Set([...build, ...files, '/manifest.json'])].filter(
|
||||
(path) => !path.includes('sql-wasm.wasm')
|
||||
);
|
||||
const DB_NAME = 'cptr-shares';
|
||||
const DB_VERSION = 1;
|
||||
const SHARE_STORE = 'share-payloads';
|
||||
|
||||
sw.addEventListener('install', (event) => {
|
||||
event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(ASSETS)));
|
||||
});
|
||||
|
||||
sw.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
(async () => {
|
||||
for (const key of await caches.keys()) {
|
||||
if (key.startsWith('cptr-') && key !== CACHE) await caches.delete(key);
|
||||
}
|
||||
await sw.clients.claim();
|
||||
})()
|
||||
);
|
||||
});
|
||||
|
||||
sw.addEventListener('message', (event) => {
|
||||
if (event.data?.type === 'SKIP_WAITING') sw.skipWaiting();
|
||||
});
|
||||
|
||||
sw.addEventListener('fetch', (event) => {
|
||||
const url = new URL(event.request.url);
|
||||
if (event.request.method === 'POST' && url.searchParams.get('intent') === 'share') {
|
||||
event.respondWith(handleShareTarget(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.request.method !== 'GET') return;
|
||||
if (isLiveBackendPath(url.pathname)) return;
|
||||
|
||||
if (event.request.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
(async () => {
|
||||
try {
|
||||
return await fetch(event.request);
|
||||
} catch {
|
||||
return (
|
||||
(await caches.match('/offline.html')) ??
|
||||
new Response('Computer is unreachable', { status: 503 })
|
||||
);
|
||||
}
|
||||
})()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
(async () => {
|
||||
const cached = await caches.match(event.request);
|
||||
if (cached) return cached;
|
||||
const response = await fetch(event.request);
|
||||
if (response.ok && isStaticAsset(url.pathname)) {
|
||||
const cache = await caches.open(CACHE);
|
||||
cache.put(event.request, response.clone());
|
||||
}
|
||||
return response;
|
||||
})()
|
||||
);
|
||||
});
|
||||
|
||||
async function handleShareTarget(request: Request): Promise<Response> {
|
||||
const form = await request.formData();
|
||||
const id = crypto.randomUUID();
|
||||
const files = form
|
||||
.getAll('files')
|
||||
.filter((item): item is File => item instanceof File)
|
||||
.map((file) => ({
|
||||
name: file.name,
|
||||
type: file.type,
|
||||
lastModified: file.lastModified,
|
||||
file
|
||||
}));
|
||||
|
||||
await putSharePayload(id, {
|
||||
id,
|
||||
title: stringValue(form.get('title')),
|
||||
text: stringValue(form.get('text')),
|
||||
url: stringValue(form.get('url')),
|
||||
files
|
||||
});
|
||||
|
||||
return Response.redirect(`/?intent=share&payload=${encodeURIComponent(id)}`, 303);
|
||||
}
|
||||
|
||||
function stringValue(value: FormDataEntryValue | null): string | undefined {
|
||||
return typeof value === 'string' && value.trim() ? value : undefined;
|
||||
}
|
||||
|
||||
function isLiveBackendPath(pathname: string): boolean {
|
||||
return (
|
||||
pathname.startsWith('/api/') ||
|
||||
pathname.startsWith('/socket.io/') ||
|
||||
pathname.startsWith('/v1/') ||
|
||||
pathname.startsWith('/workspace/files/')
|
||||
);
|
||||
}
|
||||
|
||||
function isStaticAsset(pathname: string): boolean {
|
||||
return pathname.startsWith('/_app/') || pathname.startsWith('/icon-') || pathname.includes('.');
|
||||
}
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onupgradeneeded = () => {
|
||||
const db = req.result;
|
||||
if (!db.objectStoreNames.contains(SHARE_STORE)) db.createObjectStore(SHARE_STORE);
|
||||
};
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
}
|
||||
|
||||
async function putSharePayload(id: string, payload: unknown): Promise<void> {
|
||||
const db = await openDb();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(SHARE_STORE, 'readwrite');
|
||||
const req = tx.objectStore(SHARE_STORE).put(payload, id);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
tx.oncomplete = () => db.close();
|
||||
});
|
||||
}
|
||||
@@ -31,7 +31,106 @@
|
||||
"categories": ["developer", "productivity", "utilities"],
|
||||
"launch_handler": {"client_mode": ["navigate-existing", "auto"]},
|
||||
"handle_links": "preferred",
|
||||
"note_taking": {"new_note_url": "/?action=newFile"},
|
||||
"note_taking": {"new_note_url": "/?intent=newNote"},
|
||||
"shortcuts": [
|
||||
{
|
||||
"name": "New Chat",
|
||||
"short_name": "Chat",
|
||||
"url": "/?intent=newChat",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}]
|
||||
},
|
||||
{
|
||||
"name": "Open Workspace",
|
||||
"short_name": "Workspace",
|
||||
"url": "/?intent=openWorkspace",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}]
|
||||
},
|
||||
{
|
||||
"name": "New Note",
|
||||
"short_name": "Note",
|
||||
"url": "/?intent=newNote",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}]
|
||||
},
|
||||
{
|
||||
"name": "New Terminal",
|
||||
"short_name": "Terminal",
|
||||
"url": "/?intent=newTerminal",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}]
|
||||
},
|
||||
{
|
||||
"name": "Search",
|
||||
"short_name": "Search",
|
||||
"url": "/?intent=search",
|
||||
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}]
|
||||
}
|
||||
],
|
||||
"share_target": {
|
||||
"action": "/?intent=share",
|
||||
"method": "POST",
|
||||
"enctype": "multipart/form-data",
|
||||
"params": {
|
||||
"title": "title",
|
||||
"text": "text",
|
||||
"url": "url",
|
||||
"files": [
|
||||
{
|
||||
"name": "files",
|
||||
"accept": [
|
||||
"text/*",
|
||||
"application/pdf",
|
||||
"image/*",
|
||||
".md",
|
||||
".py",
|
||||
".js",
|
||||
".ts",
|
||||
".tsx",
|
||||
".jsx",
|
||||
".svelte",
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
".toml",
|
||||
".rs",
|
||||
".go"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"file_handlers": [
|
||||
{
|
||||
"action": "/?intent=importFiles",
|
||||
"accept": {
|
||||
"text/*": [
|
||||
".txt",
|
||||
".md",
|
||||
".py",
|
||||
".js",
|
||||
".ts",
|
||||
".tsx",
|
||||
".jsx",
|
||||
".svelte",
|
||||
".css",
|
||||
".html",
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
".toml",
|
||||
".rs",
|
||||
".go",
|
||||
".java",
|
||||
".c",
|
||||
".cpp",
|
||||
".h",
|
||||
".hpp",
|
||||
".sh"
|
||||
],
|
||||
"application/pdf": [".pdf"],
|
||||
"image/*": [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"protocol_handlers": [{"protocol": "web+cptr", "url": "/?intent=%s"}],
|
||||
"prefer_related_applications": false,
|
||||
"related_applications": []
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>cptr unreachable</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
font-family:
|
||||
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
background: #fff;
|
||||
color: #111827;
|
||||
}
|
||||
main {
|
||||
width: min(448px, 100%);
|
||||
}
|
||||
h1 {
|
||||
font-size: 18px;
|
||||
line-height: 1.4;
|
||||
font-weight: 400;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
p {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: #9ca3af;
|
||||
margin: -8px 0 12px;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
button {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
color: #4b5563;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover {
|
||||
color: #111827;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background: #000;
|
||||
color: #fff;
|
||||
}
|
||||
p {
|
||||
color: #4b5563;
|
||||
}
|
||||
button {
|
||||
color: #9ca3af;
|
||||
}
|
||||
button:hover {
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Computer is unreachable</h1>
|
||||
<p>Reconnect and refresh before continuing.</p>
|
||||
<div class="actions">
|
||||
<button onclick="location.reload()">Refresh</button>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -12,6 +12,9 @@ const config = {
|
||||
}),
|
||||
paths: {
|
||||
relative: false
|
||||
},
|
||||
serviceWorker: {
|
||||
register: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -519,7 +519,7 @@ async def upload_file(
|
||||
if not target_dir.is_dir():
|
||||
raise HTTPException(status_code=400, detail=f"Not a directory: {directory}")
|
||||
|
||||
target = target_dir / file.filename
|
||||
target = _unique_child_path(target_dir, file.filename or "file")
|
||||
try:
|
||||
content = await file.read()
|
||||
await asyncio.to_thread(target.write_bytes, content)
|
||||
@@ -529,6 +529,21 @@ async def upload_file(
|
||||
return {"status": "uploaded", "path": str(target), "size": len(content)}
|
||||
|
||||
|
||||
def _unique_child_path(directory: Path, filename: str) -> Path:
|
||||
"""Return a non-existing child path by appending -2, -3, ... on collisions."""
|
||||
safe_name = Path(filename).name or "file"
|
||||
target = directory / safe_name
|
||||
if not target.exists():
|
||||
return target
|
||||
stem = target.stem
|
||||
suffix = target.suffix
|
||||
for i in range(2, 10_000):
|
||||
candidate = directory / f"{stem}-{i}{suffix}"
|
||||
if not candidate.exists():
|
||||
return candidate
|
||||
raise HTTPException(status_code=409, detail=f"Could not find available name for: {filename}")
|
||||
|
||||
|
||||
# ── File viewing (inline) ────────────────────────────────────────
|
||||
|
||||
import mimetypes
|
||||
|
||||
Reference in New Issue
Block a user