From ea922ecd38d73c89611f0890dc46189238a0f432 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 18 Jun 2026 14:40:05 +0200 Subject: [PATCH] refac --- cptr/app.py | 103 ++++- .../lib/components/ConnectionMonitor.svelte | 58 --- .../src/lib/components/DirectoryPicker.svelte | 361 +++++++++--------- .../src/lib/components/FileEditor.svelte | 18 +- cptr/frontend/src/lib/components/Icon.svelte | 5 + .../src/lib/components/Settings/PWA.svelte | 96 +++++ .../src/lib/components/SettingsModal.svelte | 5 + .../src/lib/components/WorkspacePicker.svelte | 106 +++++ .../src/lib/components/chat/ChatPanel.svelte | 10 + cptr/frontend/src/lib/i18n/locales/en.json | 26 +- cptr/frontend/src/lib/intents/payloadStore.ts | 41 ++ cptr/frontend/src/lib/intents/types.ts | 57 +++ cptr/frontend/src/lib/stores.ts | 50 ++- cptr/frontend/src/routes/+layout.svelte | 96 ++++- cptr/frontend/src/routes/+page.svelte | 349 +++++++++++++++-- cptr/frontend/src/service-worker.ts | 136 +++++++ cptr/frontend/static/manifest.json | 101 ++++- cptr/frontend/static/offline.html | 84 ++++ cptr/frontend/svelte.config.js | 3 + cptr/routers/workspace.py | 17 +- 20 files changed, 1444 insertions(+), 278 deletions(-) delete mode 100644 cptr/frontend/src/lib/components/ConnectionMonitor.svelte create mode 100644 cptr/frontend/src/lib/components/Settings/PWA.svelte create mode 100644 cptr/frontend/src/lib/components/WorkspacePicker.svelte create mode 100644 cptr/frontend/src/lib/intents/payloadStore.ts create mode 100644 cptr/frontend/src/lib/intents/types.ts create mode 100644 cptr/frontend/src/service-worker.ts create mode 100644 cptr/frontend/static/offline.html diff --git a/cptr/app.py b/cptr/app.py index 3a0ce42..4e41655 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -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": [], } diff --git a/cptr/frontend/src/lib/components/ConnectionMonitor.svelte b/cptr/frontend/src/lib/components/ConnectionMonitor.svelte deleted file mode 100644 index 49464f8..0000000 --- a/cptr/frontend/src/lib/components/ConnectionMonitor.svelte +++ /dev/null @@ -1,58 +0,0 @@ - diff --git a/cptr/frontend/src/lib/components/DirectoryPicker.svelte b/cptr/frontend/src/lib/components/DirectoryPicker.svelte index 46c52e5..619aedc 100644 --- a/cptr/frontend/src/lib/components/DirectoryPicker.svelte +++ b/cptr/frontend/src/lib/components/DirectoryPicker.svelte @@ -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([]); @@ -25,6 +29,8 @@ let error = $state(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([]); @@ -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; + } - -
{}} + - -
e.stopPropagation()} - onkeydown={() => {}} - > - -
- {#if history.length > 0} - - {/if} + +
+ {#if history.length > 0} + + {/if} - {#if editingPath} -
- { - requestAnimationFrame(() => { - if (editingPath) cancelEditing(); - }); - }} - spellcheck="false" - autocomplete="off" - placeholder={$t('directory.typePath')} - /> - {#if pathValid === 'checking'} - - {:else if pathValid === 'valid'} - - {:else if pathValid === 'invalid'} - + {#if editingPath} +
+ { + requestAnimationFrame(() => { + if (editingPath) cancelEditing(); + }); + }} + spellcheck="false" + autocomplete="off" + placeholder={$t('directory.typePath')} + /> + {#if pathValid === 'checking'} + + {:else if pathValid === 'valid'} + + {:else if pathValid === 'invalid'} + + {/if} + {#if tabHint} + {tabHint} + {/if} + TAB +
+ {:else} + +
{ + if (e.key === 'Enter') startEditing(); + }} + > + {#each breadcrumbs as seg, i (seg.path)} + {#if i > 1}/{/if} + {#if i === breadcrumbs.length - 1} + {seg.name} + {:else} + + { + e.stopPropagation(); + navigateToPath(seg.path); + }} + onkeydown={() => {}}>{seg.name} {/if} - {#if tabHint} - {tabHint} - {/if} - TAB -
- {:else} - -
{ - if (e.key === 'Enter') startEditing(); + {/each} + + + +
+ {/if} + + +
+ + +
+ {#if loading} +
+ +
+ {:else if error} +
+

{error}

+ +
+ {:else if filteredDirs.length === 0} +
+

{$t('directory.noSubdirectories')}

+
+ {:else} + {#each filteredDirs as dir, i (dir.name)} +
- {/if} - - -
- - -
- {#if loading} -
- -
- {:else if error} -
-

{error}

- -
- {:else if filteredDirs.length === 0} -
-

{$t('directory.noSubdirectories')}

-
- {:else} - {#each filteredDirs as dir, i (dir.name)} - - {/each} - {/if} -
- - -
- {currentPath} - - -
+ + {dir.name} + + + {/each} + {/if}
-
+ + +
+ {currentPath} + + +
+
+ +{#if actionsMenuOpen && actionsBtnEl} + toggleHidden() + } + ]} + onclose={() => (actionsMenuOpen = false)} + /> +{/if} diff --git a/cptr/frontend/src/lib/components/FileEditor.svelte b/cptr/frontend/src/lib/components/FileEditor.svelte index 6d85c3c..edf40a7 100644 --- a/cptr/frontend/src/lib/components/FileEditor.svelte +++ b/cptr/frontend/src/lib/components/FileEditor.svelte @@ -1,6 +1,11 @@ + +
+
+

{tr('pwa.settingsTitle')}

+ +

{tr('pwa.shareBehavior')}

+ + +

{tr('pwa.fileImports')}

+ + {#if $pwaPreferences.importDestination === 'configuredFolder'} + + updatePref('importFolder', (e.currentTarget as HTMLInputElement).value || undefined)} + /> + {/if} + +

{tr('pwa.resetTitle')}

+ +

+ {tr('pwa.resetDesc')} +

+
+
diff --git a/cptr/frontend/src/lib/components/SettingsModal.svelte b/cptr/frontend/src/lib/components/SettingsModal.svelte index 03b9b9c..78b78c9 100644 --- a/cptr/frontend/src/lib/components/SettingsModal.svelte +++ b/cptr/frontend/src/lib/components/SettingsModal.svelte @@ -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 @@
{#if activeTab === 'general'} + {:else if activeTab === 'pwa'} + {:else if activeTab === 'keyboard'} {:else if activeTab === 'account'} diff --git a/cptr/frontend/src/lib/components/WorkspacePicker.svelte b/cptr/frontend/src/lib/components/WorkspacePicker.svelte new file mode 100644 index 0000000..eed7635 --- /dev/null +++ b/cptr/frontend/src/lib/components/WorkspacePicker.svelte @@ -0,0 +1,106 @@ + + + + + +
+
+

{title}

+
+
+ + {#if needsShareBehavior} +
+ + +
+ {/if} + +
+ {#if workspaces.length} + {#each workspaces as ws, i (ws.path)} + + {/each} + {:else} +
+

{$t('pwa.noWorkspaces')}

+
+ {/if} +
+ +
+ +
+
diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index 91e0207..dfbb3c4 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -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. diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index 475e48a..090c843 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -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", diff --git a/cptr/frontend/src/lib/intents/payloadStore.ts b/cptr/frontend/src/lib/intents/payloadStore.ts new file mode 100644 index 0000000..ec517e4 --- /dev/null +++ b/cptr/frontend/src/lib/intents/payloadStore.ts @@ -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 { + 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 { + 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 { + 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(); + }); +} diff --git a/cptr/frontend/src/lib/intents/types.ts b/cptr/frontend/src/lib/intents/types.ts new file mode 100644 index 0000000..e04d914 --- /dev/null +++ b/cptr/frontend/src/lib/intents/types.ts @@ -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' +}; diff --git a/cptr/frontend/src/lib/stores.ts b/cptr/frontend/src/lib/stores.ts index 250b2d9..cd43ede 100644 --- a/cptr/frontend/src/lib/stores.ts +++ b/cptr/frontend/src/lib/stores.ts @@ -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; // 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('queue'); export const selectedModelId = writable(''); +export const pwaPreferences = writable(defaultPwaPreferences); /** Saved workspace path order for sidebar drag-reorder. */ export const workspaceOrder = writable([]); @@ -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).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 { if (prefs.selectedModelId) selectedModelId.set(prefs.selectedModelId as string); if (prefs.requestParams) requestParams.set(prefs.requestParams as Record); 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) */ diff --git a/cptr/frontend/src/routes/+layout.svelte b/cptr/frontend/src/routes/+layout.svelte index e10c0d7..e2d920b 100644 --- a/cptr/frontend/src/routes/+layout.svelte +++ b/cptr/frontend/src/routes/+layout.svelte @@ -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 @@
{/if} - (null); + let folderPickerIntent = $state(null); + let folderPickerWorkspace = $state(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(null); + type LaunchQueueWindow = Window & { + __cptrLaunchQueueBound?: boolean; + launchQueue?: { + setConsumer: (consumer: (params: { files?: { getFile: () => Promise }[] }) => 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}
- - {#if showPicker} - (showPicker = false)} /> - {/if} {:else}
{#each group.tabs.filter((t) => t.type === 'file' && t.filePath) as tab (tab.id)}
- +
{/each} @@ -463,13 +720,13 @@ {#each group.tabs.filter((t) => t.type === 'terminal' && t.sessionId) as tab (tab.id)}
- +
{/each} {#each group.tabs.filter((t) => t.type === 'preview' && t.port) as tab (tab.id)}
- +
{/each} @@ -497,6 +754,26 @@
{/if} +{#if pendingIntent} + (pendingIntent = null)} + /> +{/if} + +{#if showPicker} + { + showPicker = false; + folderPickerIntent = null; + folderPickerWorkspace = null; + }} + onselect={folderPickerIntent ? handlePickedImportFolder : undefined} + /> +{/if} + + + +
+

Computer is unreachable

+

Reconnect and refresh before continuing.

+
+ +
+
+ + diff --git a/cptr/frontend/svelte.config.js b/cptr/frontend/svelte.config.js index b3b69af..fd81bf8 100644 --- a/cptr/frontend/svelte.config.js +++ b/cptr/frontend/svelte.config.js @@ -12,6 +12,9 @@ const config = { }), paths: { relative: false + }, + serviceWorker: { + register: false } } }; diff --git a/cptr/routers/workspace.py b/cptr/routers/workspace.py index 7bfbec5..60e5ea4 100644 --- a/cptr/routers/workspace.py +++ b/cptr/routers/workspace.py @@ -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