mirror of
https://github.com/jamiepine/voicebox.git
synced 2026-10-03 00:55:14 -07:00
Implement server management enhancements with window close handling
- Introduced a checkbox in the ConnectionForm to allow users to keep the server running when the app closes. - Added a setupWindowCloseHandler function to manage server shutdown based on user preference. - Updated App component to integrate the new window close handling logic. - Created a reusable Checkbox component for better UI consistency. - Modified serverStore to include state management for the new setting.
This commit is contained in:
+17
-7
@@ -7,7 +7,7 @@ import { ModelManagement } from '@/components/ServerSettings/ModelManagement';
|
|||||||
import { Toaster } from '@/components/ui/toaster';
|
import { Toaster } from '@/components/ui/toaster';
|
||||||
import { ProfileList } from '@/components/VoiceProfiles/ProfileList';
|
import { ProfileList } from '@/components/VoiceProfiles/ProfileList';
|
||||||
import { Sidebar } from '@/components/Sidebar';
|
import { Sidebar } from '@/components/Sidebar';
|
||||||
import { isTauri, startServer, stopServer } from '@/lib/tauri';
|
import { isTauri, startServer, setupWindowCloseHandler } from '@/lib/tauri';
|
||||||
|
|
||||||
// Track if server is starting to prevent duplicate starts
|
// Track if server is starting to prevent duplicate starts
|
||||||
let serverStarting = false;
|
let serverStarting = false;
|
||||||
@@ -16,9 +16,19 @@ function App() {
|
|||||||
const [activeTab, setActiveTab] = useState('profiles');
|
const [activeTab, setActiveTab] = useState('profiles');
|
||||||
const [serverReady, setServerReady] = useState(false);
|
const [serverReady, setServerReady] = useState(false);
|
||||||
|
|
||||||
// Auto-start server when running in Tauri
|
// Setup window close handler and auto-start server when running in Tauri
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isTauri() || serverStarting) {
|
if (!isTauri()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup window close handler to check setting and stop server if needed
|
||||||
|
setupWindowCloseHandler().catch((error) => {
|
||||||
|
console.error('Failed to setup window close handler:', error);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Auto-start server
|
||||||
|
if (serverStarting) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,13 +46,13 @@ function App() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Cleanup: stop server on actual unmount (not StrictMode remount)
|
// Cleanup: stop server on actual unmount (not StrictMode remount)
|
||||||
|
// Note: Window close is handled separately in Tauri Rust code
|
||||||
return () => {
|
return () => {
|
||||||
// In production builds, we want to stop the server on unmount
|
|
||||||
// In dev mode, React StrictMode causes remounts, so we skip cleanup
|
// In dev mode, React StrictMode causes remounts, so we skip cleanup
|
||||||
|
// In production, window close event handles server shutdown based on setting
|
||||||
if (import.meta.env?.PROD) {
|
if (import.meta.env?.PROD) {
|
||||||
stopServer().catch((error) => {
|
// Only stop if setting says to stop (handled by window close event)
|
||||||
console.error('Failed to stop server on cleanup:', error);
|
// This cleanup is mainly for React remounts in dev mode
|
||||||
});
|
|
||||||
serverStarting = false;
|
serverStarting = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@/components/ui/form';
|
} from '@/components/ui/form';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import { useToast } from '@/components/ui/use-toast';
|
import { useToast } from '@/components/ui/use-toast';
|
||||||
import { useServerStore } from '@/stores/serverStore';
|
import { useServerStore } from '@/stores/serverStore';
|
||||||
|
|
||||||
@@ -25,6 +26,8 @@ type ConnectionFormValues = z.infer<typeof connectionSchema>;
|
|||||||
export function ConnectionForm() {
|
export function ConnectionForm() {
|
||||||
const serverUrl = useServerStore((state) => state.serverUrl);
|
const serverUrl = useServerStore((state) => state.serverUrl);
|
||||||
const setServerUrl = useServerStore((state) => state.setServerUrl);
|
const setServerUrl = useServerStore((state) => state.setServerUrl);
|
||||||
|
const keepServerRunningOnClose = useServerStore((state) => state.keepServerRunningOnClose);
|
||||||
|
const setKeepServerRunningOnClose = useServerStore((state) => state.setKeepServerRunningOnClose);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
const form = useForm<ConnectionFormValues>({
|
const form = useForm<ConnectionFormValues>({
|
||||||
@@ -68,6 +71,36 @@ export function ConnectionForm() {
|
|||||||
<Button type="submit">Update Connection</Button>
|
<Button type="submit">Update Connection</Button>
|
||||||
</form>
|
</form>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
|
<div className="mt-6 pt-6 border-t">
|
||||||
|
<div className="flex items-start space-x-3">
|
||||||
|
<Checkbox
|
||||||
|
id="keepServerRunning"
|
||||||
|
checked={keepServerRunningOnClose}
|
||||||
|
onCheckedChange={(checked: boolean) => {
|
||||||
|
setKeepServerRunningOnClose(checked);
|
||||||
|
toast({
|
||||||
|
title: 'Setting updated',
|
||||||
|
description: checked
|
||||||
|
? 'Server will continue running when app closes'
|
||||||
|
: 'Server will stop when app closes',
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<label
|
||||||
|
htmlFor="keepServerRunning"
|
||||||
|
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||||
|
>
|
||||||
|
Keep server running when app closes
|
||||||
|
</label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
When enabled, the server will continue running in the background after closing the app.
|
||||||
|
Disabled by default.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { cn } from '@/lib/utils/cn';
|
||||||
|
|
||||||
|
export interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||||
|
onCheckedChange?: (checked: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
|
||||||
|
({ className, onCheckedChange, ...props }, ref) => {
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
if (onCheckedChange) {
|
||||||
|
onCheckedChange(e.target.checked);
|
||||||
|
}
|
||||||
|
// Call original onChange if provided
|
||||||
|
if (props.onChange) {
|
||||||
|
props.onChange(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className={cn(
|
||||||
|
'h-4 w-4 rounded border-gray-300 text-primary focus:ring-2 focus:ring-primary focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
ref={ref}
|
||||||
|
onChange={handleChange}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Checkbox.displayName = 'Checkbox';
|
||||||
|
|
||||||
|
export { Checkbox };
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { listen, emit } from '@tauri-apps/api/event';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if running in Tauri environment
|
* Check if running in Tauri environment
|
||||||
@@ -45,3 +46,35 @@ export async function stopServer(): Promise<void> {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Setup window close handler to check setting and stop server if needed
|
||||||
|
*/
|
||||||
|
export async function setupWindowCloseHandler(): Promise<void> {
|
||||||
|
if (!isTauri()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Listen for window close request from Rust
|
||||||
|
await listen<null>('window-close-requested', async () => {
|
||||||
|
// Import store here to avoid circular dependency
|
||||||
|
const { useServerStore } = await import('@/stores/serverStore');
|
||||||
|
const keepRunning = useServerStore.getState().keepServerRunningOnClose;
|
||||||
|
|
||||||
|
if (!keepRunning) {
|
||||||
|
// Stop server before closing
|
||||||
|
try {
|
||||||
|
await stopServer();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to stop server on close:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emit event back to Rust to allow close
|
||||||
|
await emit('window-close-allowed');
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to setup window close handler:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ interface ServerStore {
|
|||||||
|
|
||||||
mode: 'local' | 'remote';
|
mode: 'local' | 'remote';
|
||||||
setMode: (mode: 'local' | 'remote') => void;
|
setMode: (mode: 'local' | 'remote') => void;
|
||||||
|
|
||||||
|
keepServerRunningOnClose: boolean;
|
||||||
|
setKeepServerRunningOnClose: (keepRunning: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useServerStore = create<ServerStore>()(
|
export const useServerStore = create<ServerStore>()(
|
||||||
@@ -23,6 +26,10 @@ export const useServerStore = create<ServerStore>()(
|
|||||||
|
|
||||||
mode: 'local',
|
mode: 'local',
|
||||||
setMode: (mode) => set({ mode }),
|
setMode: (mode) => set({ mode }),
|
||||||
|
|
||||||
|
keepServerRunningOnClose: false,
|
||||||
|
setKeepServerRunningOnClose: (keepRunning) =>
|
||||||
|
set({ keepServerRunningOnClose: keepRunning }),
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
name: 'voicebox-server',
|
name: 'voicebox-server',
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use tauri::{command, State, Manager};
|
use tauri::{command, State, Manager, WindowEvent, Emitter, Listener};
|
||||||
use tauri_plugin_shell::ShellExt;
|
use tauri_plugin_shell::ShellExt;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
struct ServerState {
|
struct ServerState {
|
||||||
child: Mutex<Option<tauri_plugin_shell::process::CommandChild>>,
|
child: Mutex<Option<tauri_plugin_shell::process::CommandChild>>,
|
||||||
@@ -132,6 +133,50 @@ pub fn run() {
|
|||||||
child: Mutex::new(None),
|
child: Mutex::new(None),
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![start_server, stop_server])
|
.invoke_handler(tauri::generate_handler![start_server, stop_server])
|
||||||
|
.on_window_event(|window, event| {
|
||||||
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
// Prevent automatic close
|
||||||
|
api.prevent_close();
|
||||||
|
|
||||||
|
// Emit event to frontend to check setting and stop server if needed
|
||||||
|
let app_handle = window.app_handle();
|
||||||
|
|
||||||
|
if let Err(e) = app_handle.emit("window-close-requested", ()) {
|
||||||
|
eprintln!("Failed to emit window-close-requested event: {}", e);
|
||||||
|
// If event emission fails, allow close anyway
|
||||||
|
window.close().ok();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up listener for frontend response
|
||||||
|
let window_for_close = window.clone();
|
||||||
|
let (tx, mut rx) = mpsc::unbounded_channel::<()>();
|
||||||
|
|
||||||
|
// Listen for response from frontend using window's listen method
|
||||||
|
let listener_id = window.listen("window-close-allowed", move |_| {
|
||||||
|
// Frontend has checked setting and stopped server if needed
|
||||||
|
// Signal that we can close
|
||||||
|
let _ = tx.send(());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for frontend response or timeout
|
||||||
|
tokio::spawn(async move {
|
||||||
|
tokio::select! {
|
||||||
|
_ = rx.recv() => {
|
||||||
|
// Frontend responded, close window
|
||||||
|
window_for_close.close().ok();
|
||||||
|
}
|
||||||
|
_ = tokio::time::sleep(tokio::time::Duration::from_secs(5)) => {
|
||||||
|
// Timeout - close anyway
|
||||||
|
eprintln!("Window close timeout, closing anyway");
|
||||||
|
window_for_close.close().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Clean up listener
|
||||||
|
window_for_close.unlisten(listener_id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
.setup(|_app| {
|
.setup(|_app| {
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user