mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add useKeepAlive hook
This commit is contained in:
2 files changed
+218
No files matched your search
@@ -7,6 +7,7 @@ import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useJSRuntime } from '@/hooks/useJSRuntime';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { copyDirectory, copyFile } from '@/lib/copyFiles';
|
||||
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
|
||||
import { bytesToHex } from 'nostr-tools/utils';
|
||||
@@ -37,6 +38,20 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
const { fs: browserFS } = useFS();
|
||||
const { runtime } = useJSRuntime();
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: isLoading || isBuildLoading || isDeployLoading,
|
||||
title: 'Shakespeare',
|
||||
artist: `Working on ${projectName}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.ico',
|
||||
sizes: '32x32',
|
||||
type: 'image/x-icon'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
const addMessage = (message: AIMessage) => {
|
||||
setMessages((prev) => {
|
||||
const messageMap = new Map(prev.map(m => [m.id, m])).set(message.id, message);
|
||||
@@ -56,6 +71,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
if (isBuildLoading) return;
|
||||
|
||||
setIsBuildLoading(true);
|
||||
updateMetadata('Shakespeare', `Building ${projectName}...`);
|
||||
try {
|
||||
console.log('Running build for project:', projectId);
|
||||
const runtimeFS = await runtime.fs();
|
||||
@@ -112,6 +128,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
if (isDeployLoading) return;
|
||||
|
||||
setIsDeployLoading(true);
|
||||
updateMetadata('Shakespeare', `Deploying ${projectName}...`);
|
||||
try {
|
||||
const runtimeFS = await runtime.fs();
|
||||
|
||||
@@ -216,6 +233,15 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
onStepFinish(stepResult) {
|
||||
console.log(stepResult);
|
||||
addMessages(stepResult.response.messages);
|
||||
|
||||
// Update media session with current step info
|
||||
const lastMessage = stepResult.response.messages[stepResult.response.messages.length - 1];
|
||||
if (lastMessage?.role === 'tool') {
|
||||
const toolName = lastMessage.content?.[0]?.toolName;
|
||||
if (toolName) {
|
||||
updateMetadata('Shakespeare', `Working on ${projectName} - ${toolName}`);
|
||||
}
|
||||
}
|
||||
},
|
||||
tools: {
|
||||
git_commit: new GitCommitTool(browserFS, cwd),
|
||||
@@ -272,6 +298,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
|
||||
try {
|
||||
const aiMessages: AIMessage[] = [...messages, userMessage];
|
||||
updateMetadata('Shakespeare', `Processing your request for ${projectName}...`);
|
||||
|
||||
await createAIChat(projectId, aiMessages);
|
||||
} catch (error) {
|
||||
@@ -294,6 +321,12 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
}
|
||||
};
|
||||
|
||||
// Handle first user interaction to enable audio context
|
||||
const handleFirstInteraction = () => {
|
||||
// This will be handled automatically by the useKeepAlive hook
|
||||
// when isLoading becomes true after user interaction
|
||||
};
|
||||
|
||||
if (!isConfigured) {
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
@@ -360,6 +393,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
size="sm"
|
||||
className="gap-1 sm:gap-2 hover:bg-primary/10 hover:border-primary/20"
|
||||
onClick={runBuild}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={isBuildLoading || isDeployLoading}
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
@@ -376,6 +410,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
size="sm"
|
||||
className="gap-1 sm:gap-2 hover:bg-accent/10 hover:border-accent/20"
|
||||
onClick={runDeploy}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={isDeployLoading || isBuildLoading}
|
||||
>
|
||||
{isDeployLoading ? (
|
||||
@@ -447,12 +482,14 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={handleFirstInteraction}
|
||||
placeholder="Ask me to add features, edit files, or build your project..."
|
||||
className="min-h-[60px] resize-none"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={!input.trim() || isLoading}
|
||||
className="self-end"
|
||||
size="icon"
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useEffect, useRef, useCallback } from 'react';
|
||||
|
||||
interface UseKeepAliveOptions {
|
||||
/** Whether to enable keep-alive functionality */
|
||||
enabled: boolean;
|
||||
/** Title to show in media session */
|
||||
title: string;
|
||||
/** Artist to show in media session */
|
||||
artist: string;
|
||||
/** Artwork to show in media session */
|
||||
artwork?: MediaImage[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to keep the tab alive using a silent sine wave and Media Session API.
|
||||
* This prevents the browser from throttling the tab when the user locks their phone
|
||||
* or navigates away, allowing AI processing to continue in the background.
|
||||
*/
|
||||
export function useKeepAlive({
|
||||
enabled,
|
||||
title,
|
||||
artist,
|
||||
artwork = []
|
||||
}: UseKeepAliveOptions) {
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const oscillatorRef = useRef<OscillatorNode | null>(null);
|
||||
const gainNodeRef = useRef<GainNode | null>(null);
|
||||
const isActiveRef = useRef(false);
|
||||
|
||||
const startKeepAlive = useCallback(async () => {
|
||||
if (isActiveRef.current || !enabled) return;
|
||||
|
||||
try {
|
||||
// Create audio context
|
||||
const AudioContextClass = window.AudioContext || (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||
if (!AudioContextClass) {
|
||||
throw new Error('AudioContext not supported');
|
||||
}
|
||||
audioContextRef.current = new AudioContextClass();
|
||||
const audioContext = audioContextRef.current;
|
||||
|
||||
// Resume audio context if suspended (required for user interaction)
|
||||
if (audioContext.state === 'suspended') {
|
||||
await audioContext.resume();
|
||||
}
|
||||
|
||||
// Create oscillator for silent sine wave
|
||||
oscillatorRef.current = audioContext.createOscillator();
|
||||
gainNodeRef.current = audioContext.createGain();
|
||||
|
||||
const oscillator = oscillatorRef.current;
|
||||
const gainNode = gainNodeRef.current;
|
||||
|
||||
// Configure oscillator
|
||||
oscillator.type = 'sine';
|
||||
oscillator.frequency.setValueAtTime(20000, audioContext.currentTime); // 20kHz - above human hearing range
|
||||
|
||||
// Set volume to nearly silent but not completely muted
|
||||
gainNode.gain.setValueAtTime(0.001, audioContext.currentTime);
|
||||
|
||||
// Connect nodes
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(audioContext.destination);
|
||||
|
||||
// Start oscillator
|
||||
oscillator.start();
|
||||
|
||||
// Set up Media Session API
|
||||
if ('mediaSession' in navigator) {
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title,
|
||||
artist,
|
||||
artwork
|
||||
});
|
||||
|
||||
// Set playback state
|
||||
navigator.mediaSession.playbackState = 'playing';
|
||||
|
||||
// Handle media session actions
|
||||
navigator.mediaSession.setActionHandler('play', () => {
|
||||
// Already playing, do nothing
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('pause', () => {
|
||||
stopKeepAlive();
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('stop', () => {
|
||||
stopKeepAlive();
|
||||
});
|
||||
}
|
||||
|
||||
isActiveRef.current = true;
|
||||
console.log('Keep-alive started with silent audio and media session');
|
||||
} catch (error) {
|
||||
console.error('Failed to start keep-alive:', error);
|
||||
}
|
||||
}, [enabled, title, artist, artwork]);
|
||||
|
||||
const stopKeepAlive = useCallback(() => {
|
||||
if (!isActiveRef.current) return;
|
||||
|
||||
try {
|
||||
// Stop oscillator
|
||||
if (oscillatorRef.current) {
|
||||
oscillatorRef.current.stop();
|
||||
oscillatorRef.current.disconnect();
|
||||
oscillatorRef.current = null;
|
||||
}
|
||||
|
||||
// Disconnect gain node
|
||||
if (gainNodeRef.current) {
|
||||
gainNodeRef.current.disconnect();
|
||||
gainNodeRef.current = null;
|
||||
}
|
||||
|
||||
// Close audio context
|
||||
if (audioContextRef.current) {
|
||||
audioContextRef.current.close();
|
||||
audioContextRef.current = null;
|
||||
}
|
||||
|
||||
// Clear media session
|
||||
if ('mediaSession' in navigator) {
|
||||
navigator.mediaSession.metadata = null;
|
||||
navigator.mediaSession.playbackState = 'none';
|
||||
|
||||
// Clear action handlers
|
||||
navigator.mediaSession.setActionHandler('play', null);
|
||||
navigator.mediaSession.setActionHandler('pause', null);
|
||||
navigator.mediaSession.setActionHandler('stop', null);
|
||||
}
|
||||
|
||||
isActiveRef.current = false;
|
||||
console.log('Keep-alive stopped');
|
||||
} catch (error) {
|
||||
console.error('Failed to stop keep-alive:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const updateMetadata = useCallback((newTitle: string, newArtist?: string) => {
|
||||
if (!isActiveRef.current || !('mediaSession' in navigator)) return;
|
||||
|
||||
try {
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: newTitle,
|
||||
artist: newArtist || artist,
|
||||
artwork
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to update media session metadata:', error);
|
||||
}
|
||||
}, [artist, artwork]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopKeepAlive();
|
||||
};
|
||||
}, [stopKeepAlive]);
|
||||
|
||||
// Handle enabled state changes
|
||||
useEffect(() => {
|
||||
if (enabled && !isActiveRef.current) {
|
||||
// Small delay to ensure user interaction has occurred
|
||||
const timer = setTimeout(() => {
|
||||
startKeepAlive();
|
||||
}, 100);
|
||||
return () => clearTimeout(timer);
|
||||
} else if (!enabled && isActiveRef.current) {
|
||||
stopKeepAlive();
|
||||
}
|
||||
}, [enabled, startKeepAlive, stopKeepAlive]);
|
||||
|
||||
return {
|
||||
isActive: isActiveRef.current,
|
||||
startKeepAlive,
|
||||
stopKeepAlive,
|
||||
updateMetadata
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user