Spaces:
Running
Running
File size: 13,953 Bytes
94004a2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | /**
* First-run bootstrap splash.
*
* Two data sources drive this UI:
* 1. `bootstrap_status` Tauri command (polled every 1 s) — coarse stage.
* 2. `bootstrap-log` + `bootstrap-progress` Tauri events — live stdout
* from `uv sync`, ffmpeg byte counts, etc. The log panel shows the
* last N lines so users can see *something* happening during the 5–10
* min dependency install.
*/
import { useEffect, useRef, useState } from 'react';
import './BootstrapSplash.css';
// Vite injects package.json version at build time.
const APP_VERSION = __APP_VERSION__ || '0.0.0';
const STAGE_LABEL = {
checking: 'Checking environment…',
downloading_uv: 'Downloading uv (Python package manager)…',
creating_venv: 'Creating Python virtual environment…',
installing_deps: 'Installing dependencies — first run, 5–10 min.',
starting_backend: 'Starting backend…',
ready: 'Ready',
failed: 'Setup failed',
};
const STEPS = [
'checking',
'downloading_uv',
'creating_venv',
'installing_deps',
'starting_backend',
];
const MAX_LOG_LINES = 200;
/** Scan logs + error message for known failure patterns and return actionable hints. */
function detectHints(message, logs) {
const hints = [];
const all = (message || '') + '\n' + logs.map(l => l.line).join('\n');
if (/README\.md/i.test(all)) hints.push('README.md was missing from the bundle. This is now auto-fixed — retry should work.');
if (/uv.*download|uv.*install/i.test(all) && /timeout|connection/i.test(all)) hints.push('Network timeout downloading uv. Check your internet connection or try the China mirror.');
if (/uv sync failed/i.test(all)) hints.push('Dependency install failed. "Clean & Retry" will delete the cached venv and start fresh.');
if (/hatchling|build_editable/i.test(all)) hints.push('Python build backend error. "Clean & Retry" removes the broken venv so it rebuilds from scratch.');
if (/ffmpeg/i.test(all) && /download|timeout/i.test(all)) hints.push('ffmpeg download failed. This is non-fatal — retry or install ffmpeg manually.');
if (/port.*in use|address.*in use/i.test(all)) hints.push('Port 3900 is already in use. Close other instances of OmniVoice or apps using that port.');
if (/no error output/i.test(all)) hints.push('Backend crashed silently. "Clean & Retry" often fixes corrupt venv issues.');
if (hints.length === 0) hints.push('Try "Retry" first. If it fails again, "Clean & Retry" will rebuild the environment from scratch.');
return hints;
}
function formatBytes(n) {
if (!n || n < 0) return '';
const units = ['B', 'KB', 'MB', 'GB'];
let i = 0;
let v = n;
while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
}
export function BootstrapSplash({ stage, message }) {
const label = STAGE_LABEL[stage] || stage;
const stepIndex = Math.max(0, STEPS.indexOf(stage));
const isFailed = stage === 'failed';
const [logs, setLogs] = useState([]);
const [logsOpen, setLogsOpen] = useState(true);
const [copied, setCopied] = useState(false);
const [progress, setProgress] = useState(null);
const [region, setRegionState] = useState('auto');
const [retrying, setRetrying] = useState(false);
const logRef = useRef(null);
const handleRetry = async () => {
if (retrying) return;
setRetrying(true);
try {
const { invoke } = await import('@tauri-apps/api/core');
setLogs([]);
await invoke('retry_bootstrap');
} catch (e) { console.error('retry failed', e); }
finally { setRetrying(false); }
};
const handleCleanRetry = async () => {
if (retrying) return;
if (!confirm('This will delete the cached Python environment and re-download all dependencies (~5-10 min). Continue?')) return;
setRetrying(true);
try {
const { invoke } = await import('@tauri-apps/api/core');
setLogs([]);
await invoke('clean_and_retry_bootstrap');
} catch (e) { console.error('clean retry failed', e); }
finally { setRetrying(false); }
};
// Load persisted region on mount.
useEffect(() => {
if (typeof window === 'undefined' || !('__TAURI_INTERNALS__' in window)) return;
(async () => {
try {
const { invoke } = await import('@tauri-apps/api/core');
const r = await invoke('get_region');
if (r) setRegionState(r);
} catch { /* older build without region support */ }
})();
}, []);
const handleRegionChange = async (newRegion) => {
setRegionState(newRegion);
try {
const { invoke } = await import('@tauri-apps/api/core');
await invoke('set_region', { region: newRegion });
} catch { /* silent */ }
};
// Subscribe to live log + progress events from the Rust bootstrap.
// Also backfill any logs emitted before the webview finished loading.
useEffect(() => {
if (typeof window === 'undefined') return;
if (!('__TAURI_INTERNALS__' in window)) return;
let unlistenLog = null;
let unlistenProgress = null;
let cancelled = false;
(async () => {
try {
const { listen } = await import('@tauri-apps/api/event');
const { invoke } = await import('@tauri-apps/api/core');
if (cancelled) return;
// Backfill: fetch all log lines buffered on the Rust side before
// the webview was ready to receive events.
try {
const buffered = await invoke('get_bootstrap_logs');
if (!cancelled && Array.isArray(buffered) && buffered.length > 0) {
setLogs(buffered.map(({ stage: s, line }) => ({
stage: s, line, t: Date.now(),
})));
}
} catch { /* command may not exist in older builds */ }
// Subscribe to live events for anything new from here on.
unlistenLog = await listen('bootstrap-log', (e) => {
const { stage: s, line } = e.payload || {};
if (!line) return;
setLogs((prev) => {
// Deduplicate against backfill by checking the last few lines.
const lastFew = prev.slice(-5);
if (lastFew.some(l => l.stage === s && l.line === line)) return prev;
const next = prev.concat([{ stage: s, line, t: Date.now() }]);
return next.length > MAX_LOG_LINES
? next.slice(next.length - MAX_LOG_LINES)
: next;
});
});
unlistenProgress = await listen('bootstrap-progress', (e) => {
setProgress(e.payload || null);
});
} catch {
/* not in Tauri or listen unavailable — silent */
}
})();
return () => {
cancelled = true;
if (unlistenLog) unlistenLog();
if (unlistenProgress) unlistenProgress();
};
}, []);
// Auto-scroll the log panel to the latest line whenever it opens or
// new lines arrive.
useEffect(() => {
if (logsOpen && logRef.current) {
logRef.current.scrollTop = logRef.current.scrollHeight;
}
}, [logs, logsOpen]);
// Auto-expand logs on failure so users can see + copy the full output.
// Also expand on failure (in case user collapsed manually).
useEffect(() => {
if (isFailed) setLogsOpen(true);
}, [isFailed]);
const handleCopyLogs = () => {
const logText = logs.length === 0
? 'No log output captured.'
: logs.map(l => `[${l.stage}] ${l.line}`).join('\n');
const full = isFailed && message
? `ERROR: ${message}\n\n--- Bootstrap Logs ---\n${logText}`
: logText;
navigator.clipboard.writeText(full).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}).catch(() => {});
};
const stageProgress = progress && progress.stage === stage ? progress : null;
const pctFromBytes = stageProgress?.percent != null ? stageProgress.percent : null;
return (
<div className="bootstrap-splash">
<div className="bootstrap-splash__card">
<div className="bootstrap-splash__title-row">
<h1>OmniVoice Studio</h1>
<span className="bootstrap-splash__version">v{APP_VERSION}</span>
<div className="bootstrap-splash__region">
<select
className="bootstrap-splash__region-select"
value={region}
onChange={(e) => handleRegionChange(e.target.value)}
>
<option value="auto">🌐 Auto-detect</option>
<option value="global">🌐 Global (direct)</option>
<option value="china">🇨🇳 China (mirror)</option>
<option value="russia">🇷🇺 Russia (mirror)</option>
<option value="restricted">🌍 Restricted (mirror)</option>
</select>
</div>
</div>
<p className="bootstrap-splash__status">{label}</p>
{isFailed ? (
<>
<pre className="bootstrap-splash__error">{message || 'Unknown error'}</pre>
<div className="bootstrap-splash__hints">
<strong>💡 What to try:</strong>
<ul>
{detectHints(message, logs).map((h, i) => <li key={i}>{h}</li>)}
</ul>
</div>
<div className="bootstrap-splash__actions">
<button className="bootstrap-splash__retry-btn" onClick={handleRetry} disabled={retrying}>
{retrying ? '⏳ Retrying…' : '🔄 Retry'}
</button>
<button className="bootstrap-splash__retry-btn bootstrap-splash__retry-btn--danger" onClick={handleCleanRetry} disabled={retrying}>
🧹 Clean & Retry
</button>
</div>
</>
) : (
<>
<div className="bootstrap-splash__bar">
<div
className="bootstrap-splash__bar-fill"
style={{ width: `${((stepIndex + 1) / STEPS.length) * 100}%` }}
/>
</div>
{stageProgress && (
<div className="bootstrap-splash__sub-progress">
<div className="bootstrap-splash__sub-bar">
<div
className="bootstrap-splash__sub-bar-fill"
style={{ width: `${pctFromBytes ?? 0}%` }}
/>
</div>
<span className="bootstrap-splash__sub-label">
{formatBytes(stageProgress.bytes_done)}
{stageProgress.bytes_total > 0
? ` / ${formatBytes(stageProgress.bytes_total)}`
: ''}
{pctFromBytes != null ? ` (${pctFromBytes}%)` : ''}
</span>
</div>
)}
<ol className="bootstrap-splash__steps">
{STEPS.map((s, i) => (
<li
key={s}
className={
i < stepIndex ? 'done' :
i === stepIndex ? 'active' :
'pending'
}
>
{STAGE_LABEL[s]}
</li>
))}
</ol>
</>
)}
{/* Live log panel — always visible so users see what's happening */}
<div className="bootstrap-splash__log-header">
<button
type="button"
className="bootstrap-splash__log-toggle"
onClick={() => setLogsOpen((v) => !v)}
>
{logsOpen ? '▾ Hide logs' : '▸ Show logs'}
</button>
<span className="bootstrap-splash__log-count">
{logs.length > 0 && `${logs.length} lines`}
</span>
<button
type="button"
className="bootstrap-splash__copy-btn"
onClick={handleCopyLogs}
>
{copied ? '✓ Copied!' : '📋 Copy'}
</button>
</div>
{logsOpen && (
<pre className="bootstrap-splash__logs" ref={logRef}>
{logs.length === 0
? 'Waiting for output…'
: logs.map((l, i) => `[${l.stage}] ${l.line}`).join('\n')}
</pre>
)}
</div>
</div>
);
}
/**
* Hook: polls the Rust `bootstrap_status` command every pollMs ms. Returns
* the current stage (string) + message. In a non-Tauri context (dev web),
* returns 'ready' immediately so the splash never mounts.
*/
export function useBootstrapStage(pollMs = 1000) {
const [state, setState] = useState({ stage: 'checking', message: null });
useEffect(() => {
if (typeof window === 'undefined') { setState({ stage: 'ready', message: null }); return; }
if (!('__TAURI_INTERNALS__' in window)) { setState({ stage: 'ready', message: null }); return; }
if (import.meta.env.DEV) { setState({ stage: 'ready', message: null }); return; }
let cancelled = false;
let timer = null;
const invoke = async () => {
try {
const { invoke: tauriInvoke } = await import('@tauri-apps/api/core');
return tauriInvoke;
} catch {
return null;
}
};
(async () => {
const tauriInvoke = await invoke();
if (!tauriInvoke) { setState({ stage: 'ready', message: null }); return; }
const tick = async () => {
if (cancelled) return;
try {
const res = await tauriInvoke('bootstrap_status');
if (cancelled) return;
// Rust returns { stage: 'ready' } or { stage: 'failed', message: '…' } etc.
setState({ stage: res.stage || 'ready', message: res.message || null });
if (res.stage !== 'ready' && res.stage !== 'failed') {
timer = setTimeout(tick, pollMs);
}
} catch {
setState({ stage: 'ready', message: null });
}
};
tick();
})();
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [pollMs]);
return state;
}
|