This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-18 11:46:41 +02:00
1 parent c152eac632
commit 88f743c95b
11 files changed
+301 -4

No files matched your search

@@ -0,0 +1,61 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { t } from '$lib/i18n';
let isOnline = $state(true);
let toastId: string | number | undefined;
let healthTimer: ReturnType<typeof setInterval> | null = null;
function showOffline() {
if (!isOnline) return;
isOnline = false;
toastId = toast.error($t('pwa.reconnecting'), { duration: Infinity });
startPolling();
}
function showOnline() {
if (isOnline) return;
isOnline = true;
if (toastId) toast.dismiss(toastId);
toastId = undefined;
stopPolling();
}
function checkHealth() {
fetch('/api/health', { method: 'HEAD', cache: 'no-store' })
.then((res) => {
if (res.ok) showOnline();
})
.catch(() => {});
}
function startPolling() {
stopPolling();
healthTimer = setInterval(checkHealth, 5000);
}
function stopPolling() {
if (healthTimer) {
clearInterval(healthTimer);
healthTimer = null;
}
}
onMount(() => {
// Only react to browser offline/online events.
// Don't probe on mount; if we loaded, we're online.
window.addEventListener('offline', showOffline);
window.addEventListener('online', () => {
// Browser says online, verify with a real request
checkHealth();
});
return () => {
window.removeEventListener('offline', showOffline);
window.removeEventListener('online', checkHealth);
stopPolling();
if (toastId) toast.dismiss(toastId);
};
});
</script>
@@ -380,5 +380,18 @@
<path d="M18.5 6.5C20.0645 7.86634 21 9.82395 21 12C21 14.176 20.0645 16.1337 18.5 17.5" />
{:else if name === 'stop'}
<rect x="6" y="6" width="12" height="12" rx="1" fill="currentColor" />
{:else if name === 'share'}
<path d="M18 22C19.6569 22 21 20.6569 21 19C21 17.3431 19.6569 16 18 16C16.3431 16 15 17.3431 15 19C15 20.6569 16.3431 22 18 22Z" />
<path d="M18 8C19.6569 8 21 6.65685 21 5C21 3.34315 19.6569 2 18 2C16.3431 2 15 3.34315 15 5C15 6.65685 16.3431 8 18 8Z" />
<path d="M6 15C7.65685 15 9 13.6569 9 12C9 10.3431 7.65685 9 6 9C4.34315 9 3 10.3431 3 12C3 13.6569 4.34315 15 6 15Z" />
<path d="M15.5 6.5L8.5 10.5" />
<path d="M8.5 13.5L15.5 17.5" />
{:else if name === 'wifi-off'}
<path d="M1 1L23 23" />
<path d="M16.72 11.06C17.8106 11.5469 18.8104 12.2174 19.67 13.05" />
<path d="M5 12.55C6.97 10.6 9.47 9.48 12 9.48C12.9 9.48 13.8 9.62 14.65 9.87" />
<path d="M8.53 16.11C9.5 15.14 10.7 14.56 12 14.56C12.7 14.56 13.38 14.71 14 15" />
<path d="M2 8.82C5.23 5.72 8.5 4 12 4C13.72 4 15.4 4.4 16.97 5.15" />
<circle cx="12" cy="20" r="1" fill="currentColor" />
{/if}
</svg>
@@ -48,7 +48,6 @@
async function toggleNotifications() {
if (!$notificationsEnabled) {
// Enabling: request permission
if ('Notification' in window) {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
@@ -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<typeof setTimeout> | 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();
});
@@ -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}
</div>
{/if}
{#if done && 'share' in navigator}
<button
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
onclick={shareContent}
aria-label={$t('chat.share')}
>
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M12 4v12M12 4l-4 4M12 4l4 4"
/></svg
>
</button>
{/if}
</div>
{/if}
{/if}
@@ -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();
@@ -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<void>((resolve, reject) => {
const audio = ttsAudio!;
audio.onended = () => resolve();
+13 -1
View File
@@ -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"
}
+40
View File
@@ -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 ───────────────────────────────────────────
/**
+43 -1
View File
@@ -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;
+2
View File
@@ -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 @@
</div>
{/if}
<ConnectionMonitor />
<Toaster
position="top-right"
theme="system"