Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions src-tauri/src/crash.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
//! Crash reports. Release builds abort on a panic (Cargo.toml), so the window
//! is simply gone and nothing on screen says why. The panic hook writes what it
//! knows to a file before the abort; the next launch finds it and the page
//! offers to report it (`take_crash_report`, ReportIssueDialog).

use std::path::PathBuf;
use std::sync::OnceLock;

const FILE: &str = "last-crash.json";

/// The app's data directory, once `setup()` knows it. A panic before that
/// writes to the temp directory instead; both are checked on the next launch.
static DIR: OnceLock<PathBuf> = OnceLock::new();

pub fn set_dir(dir: PathBuf) {
let _ = std::fs::create_dir_all(&dir);
let _ = DIR.set(dir);
}

fn fallback_path() -> PathBuf {
std::env::temp_dir().join(format!("stroke-{FILE}"))
}

fn report_path() -> PathBuf {
DIR.get().map(|d| d.join(FILE)).unwrap_or_else(fallback_path)
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
pub struct CrashReport {
pub message: String,
pub location: String,
pub thread: String,
pub version: String,
pub os: String,
/// Seconds since the Unix epoch.
pub at: u64,
pub backtrace: String,
}

fn payload_text(info: &std::panic::PanicHookInfo<'_>) -> String {
let p = info.payload();
p.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| p.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".to_string())
}

/// Install the hook. Call first thing in `run()`. The previous hook still runs
/// (stderr), and after it the process aborts as before, so the operating
/// system's own crash reporter sees the crash too.
pub fn install() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let report = CrashReport {
message: payload_text(info),
location: info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_default(),
thread: std::thread::current().name().unwrap_or("unnamed").to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
os: format!("{} {}", std::env::consts::OS, std::env::consts::ARCH),
at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
backtrace: std::backtrace::Backtrace::force_capture().to_string(),
};
log::error!("panic at {}: {}", report.location, report.message);
if let Ok(json) = serde_json::to_vec_pretty(&report) {
let _ = std::fs::write(report_path(), json);
}
previous(info);
}));
}

/// The report the last run left behind, if it crashed. Reading it deletes it,
/// so it is offered once.
#[tauri::command]
pub fn take_crash_report() -> Option<CrashReport> {
let mut found = None;
for path in [report_path(), fallback_path()] {
if let Ok(bytes) = std::fs::read(&path) {
let _ = std::fs::remove_file(&path);
if found.is_none() {
found = serde_json::from_slice::<CrashReport>(&bytes).ok();
}
}
}
found
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_report_round_trips_and_is_taken_once() {
let dir = std::env::temp_dir().join(format!("stroke-crash-test-{}", std::process::id()));
set_dir(dir.clone());
let r = CrashReport {
message: "boom".into(),
location: "src/x.rs:1".into(),
thread: "main".into(),
version: "1.0.0".into(),
os: "linux x86_64".into(),
at: 1,
backtrace: String::new(),
};
std::fs::write(report_path(), serde_json::to_vec(&r).unwrap()).unwrap();
assert_eq!(take_crash_report(), Some(r));
assert_eq!(take_crash_report(), None);
let _ = std::fs::remove_dir_all(dir);
}
}
7 changes: 6 additions & 1 deletion src-tauri/src/db/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,12 @@ pub fn close_in_background(conn: ActiveConnection) {
// seconds. Nothing downstream needs the drain to finish - the state slot
// is already empty - so never make connect/switch wait on it. The timeout
// caps the drain; after that the OS cleans up the sockets.
tokio::spawn(async move {
//
// tauri's runtime, not tokio::spawn: this is also called from sync
// commands (park_connection, resume_connection, close_parked), which run
// outside any Tokio context. tokio::spawn panics there, and with
// panic = "abort" that closed the whole app on a Labs switch or disconnect.
tauri::async_runtime::spawn(async move {
let timeout = std::time::Duration::from_secs(3);
match conn {
ActiveConnection::Postgres(p) => {
Expand Down
17 changes: 17 additions & 0 deletions src-tauri/src/db/parked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,20 @@ pub fn set_active_conn_key(state: Db<'_>, key: Option<String>) -> Result<(), Str
*state.active_key.lock().map_err(|e| e.to_string())? = key.filter(|k| !k.is_empty());
Ok(())
}

#[cfg(test)]
mod tests {
use super::super::connection::ActiveConnection;
use super::*;

/// park/resume/close_parked are sync commands: they run on a thread with
/// no Tokio runtime. Closing a pool there used to call tokio::spawn, which
/// panics outside a runtime, and release builds abort on a panic: turning
/// Labs off or disconnecting closed the app.
#[test]
fn closing_a_pool_outside_a_runtime_does_not_panic() {
let pool = tauri::async_runtime::block_on(sqlx::SqlitePool::connect("sqlite::memory:")).unwrap();
let handle = std::thread::spawn(move || close_in_background(ActiveConnection::Sqlite(pool)));
handle.join().expect("close_in_background panicked outside a runtime");
}
}
5 changes: 5 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod cloudflare;
mod commands;
mod connection_store;
mod copilot;
mod crash;
mod db;
mod docker;
mod launch;
Expand Down Expand Up @@ -409,6 +410,8 @@ fn unlock_macos_webview_frame_rate(window: &tauri::WebviewWindow) {

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// First, so a panic anywhere after this leaves a report (see crash.rs).
crash::install();
// One TLS crypto provider for the whole process. Two are compiled in
// (ring, which every driver used so far, and aws-lc-rs from tiberius 0.13),
// and with both rustls has no default: any client built without naming one
Expand Down Expand Up @@ -501,6 +504,7 @@ pub fn run() {
// driver refreshing an expired Cloudflare token mid-session.
cloudflare::set_app_handle(app.handle().clone());
if let Ok(dir) = app.path().app_data_dir() {
crash::set_dir(dir.clone());
db::connection::set_data_dir(dir);
}
db::connection::register_active_conn(std::sync::Arc::clone(&db_conn_for_setup));
Expand Down Expand Up @@ -651,6 +655,7 @@ pub fn run() {
Ok(())
})
.invoke_handler(tauri::generate_handler![
crash::take_crash_report,
plugins::plugins_list,
plugins::plugins_read_source,
plugins::plugins_install,
Expand Down
9 changes: 8 additions & 1 deletion src/lib/components/ReportIssueDialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
initialBody = "",
/** Verbatim technical detail (stack trace, …) appended as a code block. */
details = "",
/** The dialog's title; a crash found at launch says what happened instead. */
heading = "Report an issue",
/** A line above the form, e.g. what the crash report holds. */
lead = "",
} = $props();

/** @type {'bug'|'crash'|'feature'} */
Expand Down Expand Up @@ -128,13 +132,16 @@
<Dialog.Root bind:open>
<Dialog.Content class="w-[min(32rem,calc(100vw-2rem))] gap-0 p-0">
<Dialog.Header class="gap-1 px-6 pt-6 pe-12">
<Dialog.Title class="text-ui-lg">Report an issue</Dialog.Title>
<Dialog.Title class="text-ui-lg">{heading}</Dialog.Title>
<Dialog.Description class="text-ui-xs">
Opens a GitHub issue with this filled in, plus Stroke <span class="font-mono tabular-nums">v{appVersion}</span> on {platform || "this computer"}{details ? " and the error details" : ""}.
</Dialog.Description>
</Dialog.Header>

<div class="flex flex-col gap-5 px-6 pt-5 pb-6">
{#if lead}
<p class="text-ui-sm text-muted-foreground">{lead}</p>
{/if}
<!-- Kind: a segmented control, one choice, no icons. -->
<div role="radiogroup" aria-label="Kind of report" class="grid grid-cols-3 gap-0.5 rounded-lg bg-muted/40 p-0.5">
{#each TYPES as t (t.id)}
Expand Down
36 changes: 36 additions & 0 deletions src/lib/components/StatusBar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@
onswitchd1database = /** @type {(db: { databaseId: string, name: string }) => void} */ ((_db) => {}),
onswitchproviderdb = /** @type {(db: { provider: string, dbRef: string, name: string }) => void} */ ((_db) => {}),
onswitchconnection = /** @type {(conn: import('$lib/stores/connections.js').SavedConnection) => void} */ ((_c) => {}),
/** Labs, several databases open: all of them, the one in front marked. Empty otherwise. */
openDatabases = /** @type {{ key: string, label: string, current: boolean }[]} */ ([]),
/** Bring an open database to the front. */
onopendatabase = /** @type {(key: string) => void} */ ((_k) => {}),
/** Labs: the database being opened while the one on screen stays up. */
switchingTo = '',
oncheckupdate = /** @type {() => void} */ (() => {}),
onopenmodelsettings = /** @type {() => void} */ (() => {}),
aiMode = false,
Expand Down Expand Up @@ -719,6 +725,36 @@
</div>
{/if}

<!-- Labs, several databases open: every one of them, the one in front
marked. Clicking one brings it forward; its tabs are already in the
tab bar. While one opens, this says so and the page stays as it is. -->
{#if switchingTo}
{@render sep()}
<span role="status" class="flex h-7 min-w-0 shrink-0 items-center gap-1.5 px-2 text-ui-xs text-muted-foreground">
<Icon name="loader-2" class="size-3.5 shrink-0 animate-spin" />
Opening <span class="max-w-[8rem] truncate text-foreground">{switchingTo}</span>
</span>
{:else if openDatabases.length}
{@render sep()}
<div role="group" aria-label="Open databases" class="flex min-w-0 items-center gap-0.5 @max-[48rem]/sb:hidden">
{#each openDatabases as db (db.key)}
<button
type="button"
class={cn(
'flex h-6 min-w-0 max-w-[9rem] items-center gap-1.5 rounded-md px-2 text-ui-2xs transition-colors duration-100',
db.current ? 'bg-sidebar-accent text-foreground' : 'text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground',
)}
aria-current={db.current ? 'true' : undefined}
title={db.current ? `${db.label}: open now` : `Switch to ${db.label}`}
onclick={() => { if (!db.current) onopendatabase(db.key) }}
>
<span aria-hidden="true" class={cn('size-1.5 shrink-0 rounded-full', db.current ? 'bg-success' : 'bg-muted-foreground/40')}></span>
<span class="truncate">{db.label}</span>
</button>
{/each}
</div>
{/if}

<!-- Read-only is a fact about this connection, so it sits with it and says
so in words; it used to be an orange lock among the tool icons. -->
{#if connection}
Expand Down
Loading
Loading