Compare commits

..

2 Commits

Author SHA1 Message Date
NimBold ba77883e92 test(startup): trace delayed Windows crash (#37)
- Issue #37: record native startup milestones and main-window events in packaged smoke runs.\n- Keep the trace limited to FIRELINK_SMOKE_TEST so production behavior is unchanged.\n\nRefs #37.
2026-08-27 19:58:27 +03:30
NimBold 3fbe26ddf7 test(startup): collect Windows crash diagnostics (#37)
- Issue #37: include packaged stdout, stderr, and matching Windows Application events when the stability smoke fails.\n- Keep the diagnostic scoped to the smoke harness so no product behavior changes.\n\nRefs #37.
2026-08-27 19:29:51 +03:30
3 changed files with 231 additions and 10 deletions
+45 -1
View File
@@ -37,6 +37,7 @@ const child = spawn(executable, [], {
});
let stderr = '';
let stdout = '';
let spawnError = null;
let readyPort = null;
let childExit = null;
@@ -55,7 +56,9 @@ child.on('exit', (code, signal) => {
child.stderr.on('data', data => {
stderr += data.toString();
});
child.stdout.on('data', () => {});
child.stdout.on('data', data => {
stdout += data.toString();
});
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
@@ -187,6 +190,45 @@ if ($visible.Count -gt 0) {
}
}
function windowsCrashDiagnostics() {
if (process.platform !== 'win32') {
return '';
}
const script = `
$start = (Get-Date).AddMinutes(-15)
$events = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; StartTime = $start } -ErrorAction SilentlyContinue |
Where-Object {
$_.ProviderName -in @('Application Error', 'Windows Error Reporting') -and
$_.Message -match '(?i)firelink'
} |
Select-Object -First 8)
foreach ($event in $events) {
Write-Output ("EVENT " + $event.TimeCreated.ToString('o') + " " + $event.ProviderName + " ID=" + $event.Id)
Write-Output $event.Message
}
`;
try {
return execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
}).trim();
} catch {
return '';
}
}
function startupDiagnostics() {
const sections = [];
if (stdout.trim()) sections.push(`Firelink stdout:\n${stdout.slice(-6000)}`);
if (stderr.trim()) sections.push(`Firelink stderr:\n${stderr.slice(-6000)}`);
const crashEvents = windowsCrashDiagnostics();
if (crashEvents) sections.push(`Windows application events:\n${crashEvents.slice(-12000)}`);
return sections.join('\n\n');
}
function waitForChildExit(timeoutMs) {
if (childExit) {
return Promise.resolve(true);
@@ -396,6 +438,8 @@ try {
console.log(`Packaged Firelink smoke passed on 127.0.0.1:${readyPort} with ${stabilityMs}ms stability`);
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
const diagnostics = startupDiagnostics();
if (diagnostics) console.error(`\nStartup diagnostics:\n${diagnostics}`);
process.exitCode = 1;
} finally {
if (!await terminateChild()) {
+63 -6
View File
@@ -3662,6 +3662,22 @@ struct MainWindowRestoreState {
startup_complete: AtomicBool,
}
fn startup_trace(marker: &str) {
if std::env::var_os("FIRELINK_SMOKE_TEST").is_some() {
eprintln!("[firelink-startup] {marker}");
}
}
static STARTUP_WINDOW_EVENT_COUNT: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
fn startup_trace_window_event(label: &str) {
let count = STARTUP_WINDOW_EVENT_COUNT.fetch_add(1, Ordering::Relaxed);
if count < 64 {
startup_trace(label);
}
}
#[cfg(target_os = "macos")]
const MAIN_WINDOW_MINIMIZE_MENU_ID: &str = "main_window_minimize";
@@ -18200,12 +18216,9 @@ fn toggle_log_pause(caller: tauri::WebviewWindow, pause: bool) -> Result<(), Str
}
#[tauri::command]
fn is_log_paused() -> bool {
// This read is needed during renderer bootstrap, including by standalone
// Properties windows. Avoid extracting a WebviewWindow here: on Windows,
// WebView2 can invoke the command while its host is still initializing.
// Mutating logging commands remain restricted to the main window below.
LOG_PAUSED.load(std::sync::atomic::Ordering::Relaxed)
fn is_log_paused(caller: tauri::WebviewWindow) -> bool {
properties_window::ensure_main_window(&caller).is_ok()
&& LOG_PAUSED.load(std::sync::atomic::Ordering::Relaxed)
}
#[tauri::command]
@@ -18262,10 +18275,12 @@ pub fn run() {
.plugin(tauri_plugin_deep_link::init())
.manage(Aria2DaemonGuard::new())
.setup(move |app| {
startup_trace("setup:begin");
let storage_layout = crate::storage::StorageLayout::resolve(
app.handle(),
setup_storage_mode.clone(),
)?;
startup_trace("setup:storage");
let main_window_config = app
.config()
.app
@@ -18283,6 +18298,7 @@ pub fn run() {
main_window_builder =
main_window_builder.data_directory(storage_layout.webview_dir().to_path_buf());
}
startup_trace("setup:window-builder");
let mut sys = sysinfo::System::new_all();
sys.refresh_all();
@@ -18296,6 +18312,7 @@ pub fn run() {
log::info!("==========================");
build_main_tray(app.handle())
.map_err(|error| format!("failed to create tray menu: {error}"))?;
startup_trace("setup:tray");
#[cfg(target_os = "macos")]
{
use tauri::menu::{MenuItem, WINDOW_SUBMENU_ID};
@@ -18348,6 +18365,7 @@ pub fn run() {
// malformed or interrupted transaction cannot reach a missing
// Tauri state entry at startup.
app.manage(database);
startup_trace("setup:database");
if let Err(error) = recover_torrent_move_journals(
app.handle(),
&*app.state::<crate::db::DbState>(),
@@ -18361,6 +18379,7 @@ pub fn run() {
) {
log::warn!("Download replacement recovery did not complete: {error}");
}
startup_trace("setup:recovery");
// Establish Firelink-owned Aria2 routing-table paths after the
// existing data-root initializer has created the selected storage
// directory, but before the daemon launcher is scheduled. A
@@ -18422,6 +18441,7 @@ pub fn run() {
log::warn!("could not identify retained torrent metadata: {error}");
}
}
startup_trace("setup:torrent-cache");
let initial_pairing_token = {
// Generate a temporary session token for the extension server on startup.
// The frontend will hydrate the real token via IPC once it mounts,
@@ -18518,10 +18538,12 @@ pub fn run() {
scheduler_settings: Arc::clone(&scheduler_settings),
queue_manager,
});
startup_trace("setup:app-state");
if let Err(error) = power_manager.activate() {
log::error!("power: failed to activate backend power management: {error}");
}
startup_trace("setup:power");
// Build the window only after all command state is registered. This
// prevents the frontend from racing startup and invoking IPC before
@@ -18553,10 +18575,23 @@ pub fn run() {
main_window_builder = main_window_builder
.inner_size(startup_size.width as f64, startup_size.height as f64)
.prevent_overflow();
#[cfg(target_os = "windows")]
{
// Wry installs its parent WM_SETFOCUS handler while WebView2
// is still being initialized. Keep the host hidden and
// non-activatable until RunEvent::Ready so Windows cannot
// re-enter that handler during native construction.
main_window_builder = main_window_builder
.visible(false)
.focused(false)
.focusable(false);
}
main_window_builder
.build()
.map_err(|error| format!("failed to create main window: {error}"))?;
startup_trace("setup:window-built");
restore_pending_main_window(app.handle());
startup_trace("setup:pending-window-restored");
#[cfg(any(target_os = "windows", target_os = "linux"))]
dispatch_opened_torrent_paths(
@@ -18577,7 +18612,9 @@ pub fn run() {
Ok(None) => {}
Err(error) => eprintln!("Failed to read startup deep link: {error}"),
}
startup_trace("setup:deep-link");
crate::scheduler::spawn_scheduler(app.handle().clone(), scheduler_settings);
startup_trace("setup:scheduler");
let global_speed_limit = persisted_settings
.as_ref()
@@ -18620,10 +18657,12 @@ pub fn run() {
let aria2_secret_clone = aria2_secret.clone();
let app_handle_bg = app.handle().clone();
tauri::async_runtime::spawn(async move {
startup_trace("aria2-task:begin");
let mut ws_port = 6800;
match resolve_bundled_binary_path(&app_handle_bg, "aria2c") {
Ok(binary_path) => {
startup_trace("aria2-task:binary");
let mut success = false;
let mut attempted_rpc_port = false;
let mut startup_failure = None;
@@ -18717,6 +18756,7 @@ pub fn run() {
match cmd.spawn() {
Ok(mut child) => {
startup_trace("aria2-task:spawned");
// Give it a moment to fail if port is in use
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
if let Ok(Some(status)) = child.try_wait() {
@@ -18806,6 +18846,7 @@ pub fn run() {
attempt_port,
async_dns_supported
);
startup_trace("aria2-task:ready");
ready = true;
break;
}
@@ -18858,8 +18899,10 @@ pub fn run() {
ws_retries = 0;
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
startup_trace("aria2-task:websocket-attempt");
let ws_url = format!("ws://127.0.0.1:{}/jsonrpc", ws_port);
if let Ok((ws_stream, _)) = tokio_tungstenite::connect_async(&ws_url).await {
startup_trace("aria2-task:websocket-connected");
ws_retries = 0; // reset on success
if let Ok(mut startup_error) = app_handle_bg
.state::<Aria2DaemonGuard>()
@@ -18873,6 +18916,7 @@ pub fn run() {
}
}
reconcile_aria2_downloads(&app_handle_bg).await;
startup_trace("aria2-task:reconciled");
use futures_util::StreamExt;
let (_, mut read) = ws_stream.split();
while let Some(msg) = read.next().await {
@@ -18999,6 +19043,7 @@ pub fn run() {
let poll_secret = aria2_secret.clone();
let poll_mgr = Arc::clone(&queue_manager_poll);
tauri::async_runtime::spawn(async move {
startup_trace("poller:begin");
let mut interval = tokio::time::interval(std::time::Duration::from_millis(1000));
let mut observations: HashMap<String, Aria2ConnectionObservation> = HashMap::new();
let mut missing_gid_recovery_at: HashMap<String, Instant> = HashMap::new();
@@ -19010,6 +19055,7 @@ pub fn run() {
let mut relocation_checks = HashSet::new();
loop {
interval.tick().await;
startup_trace("poller:tick");
// Terminal cleanup removes a download's GID mapping. Do
// not retain one observation per historical download for
// the lifetime of the poller.
@@ -19057,9 +19103,11 @@ pub fn run() {
.unwrap_or_else(|| "none".to_string()),
active_poll_started.elapsed().as_millis()
);
startup_trace("poller:rpc-failed");
continue;
}
};
startup_trace("poller:rpc-ok");
if let Some(active_arr) = active_list.as_array() {
let mut seen_ids = HashSet::new();
let mut seen_gids = HashSet::new();
@@ -19739,6 +19787,7 @@ pub fn run() {
let ext_app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
startup_trace("extension-task:begin");
while let Err(error) = extension_server::start_server(
ext_app_handle.clone(),
server_pairing_token.clone(),
@@ -19751,6 +19800,7 @@ pub fn run() {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
}
});
startup_trace("setup:tasks-started");
Ok(())
})
.plugin(
@@ -19797,6 +19847,9 @@ pub fn run() {
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_clipboard_manager::init())
.on_window_event(|window, event| {
if window.label() == "main" {
startup_trace_window_event("window-event:main");
}
if properties_window::is_properties_window_label(window.label()) {
let resize = match event {
tauri::WindowEvent::Resized(size) => {
@@ -19889,9 +19942,13 @@ pub fn run() {
.expect("error while building tauri application")
.run(|app_handle, event| match event {
tauri::RunEvent::Ready => {
startup_trace("run-event:ready-begin");
mark_main_window_startup_complete(app_handle);
#[cfg(target_os = "windows")]
reveal_main_window(app_handle);
#[cfg(not(target_os = "windows"))]
restore_pending_main_window(app_handle);
startup_trace("run-event:ready-end");
}
#[cfg(target_os = "macos")]
tauri::RunEvent::Opened { urls } => {
+123 -3
View File
@@ -1,8 +1,128 @@
import { initLogger } from "./utils/logger";
import { StrictMode, type ComponentType } from "react";
import { createRoot } from "react-dom/client";
import "@fontsource-variable/inter/wght.css";
import "@fontsource-variable/noto-sans-hebrew/wght.css";
import "@fontsource-variable/noto-sans-sc/wght.css";
import "@fontsource-variable/outfit/wght.css";
import "@fontsource-variable/roboto/wght.css";
import "@fontsource-variable/vazirmatn/wght.css";
import "./index.css";
import { i18nReady } from "./i18n";
import { ErrorBoundary } from "./components/ErrorBoundary";
import { ToastProvider } from "./contexts/ToastContext";
import { error as logError, warn as logWarn, initLogger } from "./utils/logger";
import { getCurrentWindow } from '@tauri-apps/api/window';
import { invokeCommand as invoke } from './ipc';
const isPropertiesWindow = getCurrentWindow().label.startsWith('properties-');
void initLogger();
const serializeConsoleArguments = (values: unknown[]) => values.map(value => {
if (value instanceof Error) return `${value.name}: ${value.message}\n${value.stack || ''}`;
if (typeof value === 'string') return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}).join(' ');
const redactConsoleMessage = (message: string) => message
.replace(/(authorization|cookie|password|token|secret)\s*[:=]\s*([^\s,;]+)/gi, '$1=[redacted]')
.replace(/(https?:\/\/[^\s?]+)\?[^\s]+/g, '$1?[redacted]');
const originalConsoleError = console.error.bind(console);
const originalConsoleWarn = console.warn.bind(console);
console.error = (...values: unknown[]) => {
originalConsoleError(...values);
void logError(redactConsoleMessage(serializeConsoleArguments(values))).catch(() => undefined);
};
console.warn = (...values: unknown[]) => {
originalConsoleWarn(...values);
void logWarn(redactConsoleMessage(serializeConsoleArguments(values))).catch(() => undefined);
};
const rootElement = document.getElementById("root");
if (rootElement) {
rootElement.textContent = "Firelink startup control";
const renderRoot = (RootComponent: ComponentType) => {
if (!rootElement) return;
createRoot(rootElement).render(
<StrictMode>
<ErrorBoundary>
<ToastProvider>
<RootComponent />
</ToastProvider>
</ErrorBoundary>
</StrictMode>,
);
};
const PropertiesStartupFailure = () => (
<main className="properties-window-shell flex h-screen min-h-0 flex-col items-center justify-center gap-4 bg-main-bg p-6 text-text-primary">
<p role="alert">Download Properties could not be loaded.</p>
<button
type="button"
className="app-button app-button-primary px-3 text-xs"
onClick={() => {
void getCurrentWindow().close().catch(error => {
console.error('[PropertiesStartupFailure] close failed', error);
});
}}
>
Close
</button>
</main>
);
const renderMainApp = async () => {
if (!rootElement) return;
// Keep the child entrypoint isolated from the main application module. App
// imports the persistent Zustand stores, whose module initialization issues
// main-window-only IPC commands. Loading it in a Properties child creates a
// second persistence owner and can race the bridge handshake.
const RootComponent = (await import('./App')).default;
renderRoot(RootComponent);
};
const renderPropertiesApp = async () => {
if (!rootElement) return;
try {
// Properties starts with the synchronous English catalog and changes locale
// after its first paint. Waiting for a lazy locale chunk here delays the
// loading shell and makes native window startup visible to the user.
const RootComponent = (await import('./components/PropertiesWindowApp')).PropertiesWindowApp;
renderRoot(RootComponent);
} catch (error) {
// A failed lazy chunk must not leave the native window hidden forever. Show
// a styled, closable failure state and use the same caller-validated native
// reveal command as the normal child path.
console.error('Failed to initialize the Properties window:', error);
renderRoot(PropertiesStartupFailure);
const fallbackSessionId = crypto.randomUUID();
void invoke('properties_window_send_ready', { sessionId: fallbackSessionId })
.then(() => invoke('properties_window_reveal', { sessionId: fallbackSessionId }))
.catch(revealError => {
console.error('Failed to reveal the Properties startup error:', revealError);
});
}
};
if (isPropertiesWindow) {
void renderPropertiesApp();
} else {
void i18nReady.then(renderMainApp).catch(error => {
console.error('Failed to initialize localization:', error);
void renderMainApp();
});
}
// Prevent the webview's default context menu ("Reload", etc.) on right-click.
// Individual components that provide custom context menus call preventDefault()
// in their own onContextMenu handlers, which fires before this document-level
// listener and is unaffected.
document.addEventListener('contextmenu', (e) => {
e.preventDefault();
});