From 88f743c95ba5cd2e89248b5f3e47076da11fe09c Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 18 Jun 2026 11:46:41 +0200 Subject: [PATCH] refac --- .../lib/components/ConnectionMonitor.svelte | 61 +++++++++++++++ cptr/frontend/src/lib/components/Icon.svelte | 13 ++++ .../lib/components/Settings/General.svelte | 1 - .../src/lib/components/Terminal.svelte | 77 +++++++++++++++++++ .../components/chat/AssistantMessage.svelte | 28 +++++++ .../src/lib/components/chat/ChatInput.svelte | 21 +++++ .../src/lib/components/chat/ChatPanel.svelte | 4 +- cptr/frontend/src/lib/i18n/locales/en.json | 14 +++- cptr/frontend/src/lib/stores.ts | 40 ++++++++++ cptr/frontend/src/lib/stores/audio.ts | 44 ++++++++++- cptr/frontend/src/routes/+layout.svelte | 2 + 11 files changed, 301 insertions(+), 4 deletions(-) create mode 100644 cptr/frontend/src/lib/components/ConnectionMonitor.svelte diff --git a/cptr/frontend/src/lib/components/ConnectionMonitor.svelte b/cptr/frontend/src/lib/components/ConnectionMonitor.svelte new file mode 100644 index 0000000..5deb31d --- /dev/null +++ b/cptr/frontend/src/lib/components/ConnectionMonitor.svelte @@ -0,0 +1,61 @@ + diff --git a/cptr/frontend/src/lib/components/Icon.svelte b/cptr/frontend/src/lib/components/Icon.svelte index 7825f2d..45ddb37 100644 --- a/cptr/frontend/src/lib/components/Icon.svelte +++ b/cptr/frontend/src/lib/components/Icon.svelte @@ -380,5 +380,18 @@ {:else if name === 'stop'} + {:else if name === 'share'} + + + + + + {:else if name === 'wifi-off'} + + + + + + {/if} diff --git a/cptr/frontend/src/lib/components/Settings/General.svelte b/cptr/frontend/src/lib/components/Settings/General.svelte index 6634def..42bbc78 100644 --- a/cptr/frontend/src/lib/components/Settings/General.svelte +++ b/cptr/frontend/src/lib/components/Settings/General.svelte @@ -48,7 +48,6 @@ async function toggleNotifications() { if (!$notificationsEnabled) { - // Enabling: request permission if ('Notification' in window) { const permission = await Notification.requestPermission(); if (permission === 'granted') { diff --git a/cptr/frontend/src/lib/components/Terminal.svelte b/cptr/frontend/src/lib/components/Terminal.svelte index bfe7322..bb41314 100644 --- a/cptr/frontend/src/lib/components/Terminal.svelte +++ b/cptr/frontend/src/lib/components/Terminal.svelte @@ -51,6 +51,64 @@ let lastSentCols = 0; let lastSentRows = 0; + // ── Wake Lock ───────────────────────────────────────────── + // Keeps the screen alive during terminal sessions so long-running + // commands (npm install, docker build) don't cause screen dimming. + let wakeLock: WakeLockSentinel | null = null; + + async function acquireWakeLock() { + if (wakeLock || destroyed) return; + try { + if ('wakeLock' in navigator) { + wakeLock = await navigator.wakeLock.request('screen'); + wakeLock.addEventListener('release', () => { wakeLock = null; }); + } + } catch { + // Wake lock request can fail if document is hidden or permission denied + } + } + + function releaseWakeLock() { + wakeLock?.release().catch(() => {}); + wakeLock = null; + } + + // Re-acquire wake lock when tab becomes visible again + function handleVisibilityChange() { + if (document.visibilityState === 'visible' && !destroyed) { + acquireWakeLock(); + } + } + + // ── Haptic Feedback ────────────────────────────────────── + // Short vibration on command completion: when PTY output pauses + // after sustained activity. Useful for "build finished" when + // phone is in pocket. + let lastOutputTime = 0; + let outputActive = false; + let hapticTimer: ReturnType | null = null; + const HAPTIC_PAUSE_MS = 800; // output must pause this long to trigger + + function trackOutputForHaptics() { + const now = Date.now(); + if (now - lastOutputTime > 2000) { + // Fresh burst of output after a gap - mark as active + outputActive = true; + } + lastOutputTime = now; + + // Reset pause timer + if (hapticTimer) clearTimeout(hapticTimer); + hapticTimer = setTimeout(() => { + if (outputActive && document.hidden) { + // Output was flowing, paused, and user isn't looking - vibrate + if ('vibrate' in navigator) navigator.vibrate(15); + } + outputActive = false; + hapticTimer = null; + }, HAPTIC_PAUSE_MS); + } + function getWsUrl(sid: string): string { const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; return `${proto}//${window.location.host}/api/terminal/${sid}/ws`; @@ -132,6 +190,17 @@ onMount(() => { if (!containerEl) return; + // ── Virtual Keyboard API ──────────────────────────────── + // In overlay mode the keyboard covers content instead of resizing + // the viewport, which avoids jarring layout shifts in the terminal. + if ('virtualKeyboard' in navigator) { + (navigator as any).virtualKeyboard.overlaysContent = true; + } + + // Acquire wake lock to keep screen on during terminal session + acquireWakeLock(); + document.addEventListener('visibilitychange', handleVisibilityChange); + term = new Terminal({ cursorBlink: true, cursorStyle: 'bar', @@ -323,6 +392,11 @@ document.removeEventListener('touchstart', onTouchStart); document.removeEventListener('touchmove', onTouchMove); document.removeEventListener('touchend', onTouchEnd); + document.removeEventListener('visibilitychange', handleVisibilityChange); + // Reset virtual keyboard mode so other views aren't affected + if ('virtualKeyboard' in navigator) { + (navigator as any).virtualKeyboard.overlaysContent = false; + } }; }); @@ -352,6 +426,7 @@ // binaryType='arraybuffer' guarantees ArrayBuffer; write // directly with a Uint8Array view (zero-copy wrapper) term?.write(new Uint8Array(event.data as ArrayBuffer)); + trackOutputForHaptics(); }; ws.onclose = (e) => { @@ -377,7 +452,9 @@ destroyed = true; if (resizeTimeout) clearTimeout(resizeTimeout); if (reconnectTimer) clearTimeout(reconnectTimer); + if (hapticTimer) clearTimeout(hapticTimer); resizeObserver?.disconnect(); + releaseWakeLock(); ws?.close(); term?.dispose(); }); diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index 63918c3..ec9694b 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -118,6 +118,18 @@ }, 1500); } + function shareContent() { + const text = + (output || []) + .filter((i: any) => i.type === 'message') + .flatMap((i: any) => i.content || []) + .map((c: any) => c.text) + .join('') || content; + if ('share' in navigator) { + navigator.share({ text }).catch(() => {}); + } + } + /** Shorten a file path to just the basename for compact display */ function shortPath(p: string | undefined): string { if (!p) return '?'; @@ -625,6 +637,22 @@ {/if} {/if} + {#if done && 'share' in navigator} + + {/if} {/if} {/if} diff --git a/cptr/frontend/src/lib/components/chat/ChatInput.svelte b/cptr/frontend/src/lib/components/chat/ChatInput.svelte index 7b8a1c9..4e045a8 100644 --- a/cptr/frontend/src/lib/components/chat/ChatInput.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatInput.svelte @@ -34,6 +34,24 @@ import Spinner from '$lib/components/common/Spinner.svelte'; import { t } from '$lib/i18n'; + // Keep screen awake during voice mode conversations + let voiceWakeLock: WakeLockSentinel | null = null; + + async function acquireVoiceWakeLock() { + if (voiceWakeLock) return; + try { + if ('wakeLock' in navigator) { + voiceWakeLock = await navigator.wakeLock.request('screen'); + voiceWakeLock.addEventListener('release', () => { voiceWakeLock = null; }); + } + } catch {} + } + + function releaseVoiceWakeLock() { + voiceWakeLock?.release().catch(() => {}); + voiceWakeLock = null; + } + interface Props { inputText: string; selectedModel: string; @@ -517,6 +535,7 @@ onDestroy(() => { stopVoiceRecognition(); if (voiceRestartTimer) clearTimeout(voiceRestartTimer); + releaseVoiceWakeLock(); destroyPopup(); destroySkillPopup(); editor?.destroy(); @@ -810,10 +829,12 @@ voiceModeEnabled.set(next); if (next) { void unlockTtsAudioPlayback(); + void acquireVoiceWakeLock(); voiceWaitingForResponse = false; voiceSawStreaming = false; startVoiceRecognition(); } else { + releaseVoiceWakeLock(); voiceWaitingForResponse = false; voiceSawStreaming = false; stopVoiceRecognition(); diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index cdad286..91e0207 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -78,6 +78,7 @@ let autoScroll = $state(true); let cancelledMessageId: string | null = null; let loading = $state(!!initialChatId); + let chatTitle = ''; let ttsQueue: string[] = []; let ttsBuffer = ''; let ttsInsideCodeFence = false; @@ -273,6 +274,7 @@ currentMessageId = data.chat.current_message_id; // Update tab label with the real title from the DB if (tabId && data.chat.title) { + chatTitle = data.chat.title; updateTab(tabId, id, data.chat.title); } } finally { @@ -1225,7 +1227,7 @@ if (generation !== ttsGeneration) break; if (ttsObjectUrl) URL.revokeObjectURL(ttsObjectUrl); ttsObjectUrl = URL.createObjectURL(blob); - ttsAudio = setTtsAudioPlaybackSource(ttsObjectUrl) ?? new Audio(ttsObjectUrl); + ttsAudio = setTtsAudioPlaybackSource(ttsObjectUrl, chatTitle) ?? new Audio(ttsObjectUrl); await new Promise((resolve, reject) => { const audio = ttsAudio!; audio.onended = () => resolve(); diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index 16e9aec..475e48a 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -801,5 +801,17 @@ "onboarding.suggestion3": "What files are here?", "onboarding.suggestion4": "Help me write tests", "onboarding.connectAiNudge": "Connect an AI provider to start chatting.", - "onboarding.goToConnections": "Settings → Connections" + "onboarding.goToConnections": "Settings → Connections", + + "pwa.reconnecting": "Reconnecting", + "pwa.reconnectingTo": "Reconnecting to {{hostname}}", + "chat.share": "Share", + + "general.storage": "Storage", + "general.cacheUsage": "Cache usage", + "general.persistentStorage": "Persistent storage", + "general.persistentYes": "Active", + "general.persistentNo": "Not granted", + "general.clearCache": "Clear cache", + "general.cacheCleared": "Cache cleared" } diff --git a/cptr/frontend/src/lib/stores.ts b/cptr/frontend/src/lib/stores.ts index 787be49..250b2d9 100644 --- a/cptr/frontend/src/lib/stores.ts +++ b/cptr/frontend/src/lib/stores.ts @@ -493,6 +493,46 @@ if (typeof window !== 'undefined') { }); } +// ── Cross-tab state sync (BroadcastChannel) ───────────────────── +// Syncs theme and locale changes between browser tabs / PWA windows +// so the user doesn't see divergent state. + +if (typeof BroadcastChannel !== 'undefined') { + const channel = new BroadcastChannel('cptr-sync'); + + let _syncingFromBroadcast = false; + + channel.onmessage = (e: MessageEvent) => { + const { type, value } = e.data || {}; + _syncingFromBroadcast = true; + try { + if (type === 'theme' && value) { + theme.set(value); + } else if (type === 'locale' && value) { + changeLocale(value); + } + } finally { + _syncingFromBroadcast = false; + } + }; + + theme.subscribe((t) => { + if (!_syncingFromBroadcast) { + channel.postMessage({ type: 'theme', value: t }); + } + }); + + // Locale changes are broadcast from changeLocale() calls; + // subscribe to i18next language changes. + if (i18next) { + i18next.on('languageChanged', (lng: string) => { + if (!_syncingFromBroadcast) { + channel.postMessage({ type: 'locale', value: lng }); + } + }); + } +} + // ── Workspace actions ─────────────────────────────────────────── /** diff --git a/cptr/frontend/src/lib/stores/audio.ts b/cptr/frontend/src/lib/stores/audio.ts index 6840acd..bbf7267 100644 --- a/cptr/frontend/src/lib/stores/audio.ts +++ b/cptr/frontend/src/lib/stores/audio.ts @@ -60,7 +60,7 @@ export function getTtsAudioElement(): HTMLAudioElement | null { return ttsAudioElement; } -export function setTtsAudioPlaybackSource(src: string): HTMLAudioElement | null { +export function setTtsAudioPlaybackSource(src: string, title?: string): HTMLAudioElement | null { const audio = getTtsAudioElement(); if (!audio) return null; ttsAudioUseToken += 1; @@ -69,9 +69,51 @@ export function setTtsAudioPlaybackSource(src: string): HTMLAudioElement | null audio.muted = false; audio.playbackRate = currentTtsPlaybackSpeed; audio.src = src; + + // Shows playback controls on lock screen (Android) and + // Control Center (iOS) while TTS is playing. + if ('mediaSession' in navigator) { + navigator.mediaSession.metadata = new MediaMetadata({ + title: title || 'cptr', + artist: 'cptr', + artwork: [ + { src: '/icon-192.png', sizes: '192x192', type: 'image/png' }, + { src: '/icon-512.png', sizes: '512x512', type: 'image/png' } + ] + }); + navigator.mediaSession.setActionHandler('play', () => { + audio.play().catch(() => {}); + }); + navigator.mediaSession.setActionHandler('pause', () => { + audio.pause(); + }); + navigator.mediaSession.setActionHandler('stop', () => { + audio.pause(); + audio.currentTime = 0; + clearMediaSession(); + }); + + // Clear media session when playback ends naturally + const currentToken = ttsAudioUseToken; + audio.addEventListener('ended', function onEnd() { + audio.removeEventListener('ended', onEnd); + if (ttsAudioUseToken === currentToken) clearMediaSession(); + }); + } + return audio; } +/** Clear media session metadata and handlers. */ +export function clearMediaSession() { + if ('mediaSession' in navigator) { + navigator.mediaSession.metadata = null; + navigator.mediaSession.setActionHandler('play', null); + navigator.mediaSession.setActionHandler('pause', null); + navigator.mediaSession.setActionHandler('stop', null); + } +} + export async function unlockTtsAudioPlayback() { if (typeof window === 'undefined') return; diff --git a/cptr/frontend/src/routes/+layout.svelte b/cptr/frontend/src/routes/+layout.svelte index 72dd8d7..e10c0d7 100644 --- a/cptr/frontend/src/routes/+layout.svelte +++ b/cptr/frontend/src/routes/+layout.svelte @@ -14,6 +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 { activeTab, @@ -371,6 +372,7 @@ {/if} +