diff --git a/src-tauri/src/crash.rs b/src-tauri/src/crash.rs new file mode 100644 index 00000000..f3347c9d --- /dev/null +++ b/src-tauri/src/crash.rs @@ -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 = 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::().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 { + 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::(&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); + } +} diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index a58e12ea..2ce51837 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -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) => { diff --git a/src-tauri/src/db/parked.rs b/src-tauri/src/db/parked.rs index 0238cb31..6c84f0ff 100644 --- a/src-tauri/src/db/parked.rs +++ b/src-tauri/src/db/parked.rs @@ -78,3 +78,20 @@ pub fn set_active_conn_key(state: Db<'_>, key: Option) -> 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"); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b29a7c37..51b08425 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -18,6 +18,7 @@ mod cloudflare; mod commands; mod connection_store; mod copilot; +mod crash; mod db; mod docker; mod launch; @@ -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 @@ -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)); @@ -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, diff --git a/src/lib/components/ReportIssueDialog.svelte b/src/lib/components/ReportIssueDialog.svelte index 744eedbc..c97ed0e1 100644 --- a/src/lib/components/ReportIssueDialog.svelte +++ b/src/lib/components/ReportIssueDialog.svelte @@ -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'} */ @@ -128,13 +132,16 @@ - Report an issue + {heading} Opens a GitHub issue with this filled in, plus Stroke v{appVersion} on {platform || "this computer"}{details ? " and the error details" : ""}.
+ {#if lead} +

{lead}

+ {/if}
{#each TYPES as t (t.id)} diff --git a/src/lib/components/StatusBar.svelte b/src/lib/components/StatusBar.svelte index 894e7e63..8dac8043 100644 --- a/src/lib/components/StatusBar.svelte +++ b/src/lib/components/StatusBar.svelte @@ -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, @@ -719,6 +725,36 @@
{/if} + + {#if switchingTo} + {@render sep()} + + + Opening {switchingTo} + + {:else if openDatabases.length} + {@render sep()} +
+ {#each openDatabases as db (db.key)} + + {/each} +
+ {/if} + {#if connection} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index affcba64..33d7c06f 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -105,6 +105,7 @@ import InsiderDialog from './InsiderDialog.svelte' import AboutDialog from './AboutDialog.svelte' import ReportIssueDialog from './ReportIssueDialog.svelte' + import { crashReportFields } from '$lib/crash-report.js' import UpdateDialog from './UpdateDialog.svelte' import StatusBar from './StatusBar.svelte' import QueryLogConsole from './QueryLogConsole.svelte' @@ -621,6 +622,35 @@ let showInsiderModal = $state(false) let showAboutModal = $state(false) let showReportIssueDialog = $state(false) + /** + * The last run crashed (src-tauri/src/crash.rs left a report): offered once, + * as a prefilled crash report, shortly after launch. + * @type {{ title: string, body: string, details: string } | null} + */ + let crashReport = $state(null) + let crashReportShown = false + onMount(() => { + const t = setTimeout(() => { + void import('@tauri-apps/api/core') + .then(({ invoke }) => invoke('take_crash_report')) + .then((r) => { + const c = /** @type {{ message: string, location: string, thread: string, version: string, os: string, at: number, backtrace: string } | null} */ (r) + if (!c) return + crashReport = crashReportFields(c) + crashReportShown = true + showReportIssueDialog = true + }) + .catch(() => {}) + }, 1200) + return () => clearTimeout(t) + }) + $effect(() => { + // Closed: later reports from the menu start blank again. + if (!showReportIssueDialog && crashReportShown) { + crashReportShown = false + crashReport = null + } + }) /** My shares (share links made on this account). */ let showMyShares = $state(false) let showDisconnectDialog = $state(false) @@ -7676,14 +7706,10 @@ let rowSearch = $state('') flushSqlTabs() _sqlTabsRestoredFor = '' tabs = [] - _liveRowsByTab.clear() - _tabRowsMru = [] - _loadSeqByTab.clear() - fetchingTabIds.clear() - _sqlQueryIdByTab.clear() - for (const id of [..._sqlViewsByTab.keys()]) forgetSqlResult(id) - _sqlRowsByTab.clear() - _autoRefreshByTab.clear() + // Labs: the tabs kept for the other open databases keep their rows and + // results. Wiping them handed a resumed grid the proxied copy of its rows + // (slow to scroll) and dropped every kept SQL result. + forgetTabCaches(keptTabIds()) _autoRefreshTick += 1 _busyJobs.clear() _busyTick += 1 @@ -8319,6 +8345,20 @@ let rowSearch = $state('') // Remember where the user was so reconnecting restores this schema. if (!forget && persistConnectionId && activeSchema) setLastSchema(persistConnectionId, activeSchema) recordActivity({ type: 'disconnect', title: `Disconnected from ${connection?.name ?? 'database'}`, success: true }) + // Labs, other databases still open: close this one and go to the one used + // last, the way closing a window leaves the others up. + const here = sessionKey(connection) + sessionOrder = sessionOrder.filter((k) => k !== here) + const next = [..._sessions].filter(([k]) => k !== here).at(-1) + if (next && multiConnection()) { + const left = connection?.name ?? connection?.database ?? 'database' + setConnRoute('') + try { await disconnectPostgres() } catch { /* ignore */ } + if (await resumeKept(next[0], next[1], null)) { + toast.success(`Disconnected from ${left}`, { description: `Now on ${next[1].label}.` }) + return + } + } setWasDisconnected(true) setConnRoute('') try { await disconnectPostgres() } catch { /* ignore */ } @@ -8440,6 +8480,8 @@ let rowSearch = $state('') const _sessions = new Map() /** Bumped on every change to _sessions, so the tab bar re-reads it. */ let sessionsTick = $state(0) + /** Labs: the database being opened while the one on screen stays up ('' when none). */ + let switchingTo = $state('') /** Databases in the order they were first opened: the tab bar groups by it, so tabs don't jump around on a switch. */ let sessionOrder = $state(/** @type {string[]} */ ([])) const multiConnection = () => loadSettings().multiConnection === true @@ -8454,6 +8496,28 @@ let rowSearch = $state('') if (key && !sessionOrder.includes(key)) sessionOrder = [...sessionOrder, key] } + /** Every tab id kept for another open database. */ + function keptTabIds() { + /** @type {Set} */ + const ids = new Set() + for (const s of _sessions.values()) for (const t of s.tabs) ids.add(t.id) + return ids + } + + /** Drop the per-tab row and result caches, except for the tabs in `keep`. @param {Set} keep */ + function forgetTabCaches(keep) { + /** @param {Map | Set} m */ + const prune = (m) => { for (const id of [...m.keys()]) if (!keep.has(id)) m.delete(id) } + prune(_liveRowsByTab) + _tabRowsMru = _tabRowsMru.filter((id) => keep.has(id)) + prune(_loadSeqByTab) + prune(fetchingTabIds) + prune(_sqlQueryIdByTab) + for (const id of [..._sqlViewsByTab.keys()]) if (!keep.has(id)) forgetSqlResult(id) + prune(_sqlRowsByTab) + prune(_autoRefreshByTab) + } + /** Put the open connection's tabs (and its sidebar) aside under its key. */ function keepSession() { if (!connection) return @@ -8468,7 +8532,11 @@ let rowSearch = $state('') label: sessionLabel(connection), // The tab on screen keeps its rows, so coming back to it is instant; // the others refetch when shown, so a kept database costs little. - tabs: tabs.map((t) => (t.kind === 'table' && t.state && t.id !== activeTabId ? { ...t, state: { ...t.state, rows: [], evicted: true } } : t)), + tabs: tabs.map((t) => { + if (!(t.kind === 'table' && t.state && t.id !== activeTabId)) return t + _liveRowsByTab.delete(t.id) + return { ...t, state: { ...t.state, rows: [], selected: new Set(), windowedHead: false, windowedLoaded: [], windowCount: 0, loadingRows: false, evicted: true } } + }), activeTabId, activeSchema, activeTable, @@ -8574,8 +8642,9 @@ let rowSearch = $state('') /** * Labs: one tab bar for every open database. This database's tabs and the - * kept ones, grouped in the order the databases were opened, each labelled - * with its database once more than one is open. + * kept ones, grouped in the order the databases were opened. A group after + * the first starts with a divider; which database a tab belongs to is in its + * tooltip and in the status bar (openDatabases), not on the tab. */ const barTabs = $derived.by(() => { void sessionsTick @@ -8589,16 +8658,36 @@ let rowSearch = $state('') /** @type {any[]} */ const out = [] for (const k of order) { - if (k === here) out.push(...own.map((t) => ({ ...t, connLabel: label }))) - else { - const s = _sessions.get(k) - if (!s) continue - for (const t of s.tabs) if (t.kind !== 'welcome' && t.kind !== 'ai') out.push({ ...t, connLabel: s.label, foreign: true }) - } + const group = k === here + ? own.map((t) => ({ ...t, connLabel: label })) + : (_sessions.get(k)?.tabs ?? []).filter((t) => t.kind !== 'welcome' && t.kind !== 'ai').map((t) => ({ ...t, connLabel: _sessions.get(k)?.label, foreign: true })) + if (group.length && out.length) group[0] = { ...group[0], groupStart: true } + out.push(...group) } return out }) + /** Labs: the databases open now, in tab-bar order, for the status bar. */ + const openDatabases = $derived.by(() => { + void sessionsTick + if (!connection || _sessions.size === 0) return [] + const here = sessionKey(connection) + const order = sessionOrder.includes(here) ? sessionOrder : [...sessionOrder, here] + /** @type {{ key: string, label: string, current: boolean }[]} */ + const out = [] + for (const k of order) { + if (k === here) out.push({ key: k, label: sessionLabel(connection), current: true }) + else if (_sessions.has(k)) out.push({ key: k, label: /** @type {KeptSession} */ (_sessions.get(k)).label, current: false }) + } + return out.length > 1 ? out : [] + }) + + /** Status bar: bring an open database to the front. @param {string} key */ + function openKeptDatabase(key) { + const s = _sessions.get(key) + if (s) void handleSwitchDatabase(s.conn) + } + /** * @param {import('$lib/stores/connections.js').SavedConnection} conn * @param {{ focusTab?: string | null }} [opts] Labs: the tab to land on @@ -8607,62 +8696,58 @@ let rowSearch = $state('') // A deliberate switch is the other half of "PIN to open or reconnect". // Resolves true immediately unless a PIN is set with the connect prompt on. if (!(await requireUnlock('Unlock to connect to a database'))) return + if (switchingTo) return // Disconnect current before connecting to the new one to avoid the race // where set_conn(None) could fire after connect_* sets the new connection. const previous = connection const multi = multiConnection() + /** Labs: the database left stays open and on screen until the new one is ready. */ + let kept = '' if (multi && keepable(previous)) { if (previous && sessionKey(previous) === sessionKey(conn)) { // Already here: just the tab. if (opts.focusTab) void activateTab(opts.focusTab) return } + kept = sessionKey(previous) keepSession() await liveStop().catch(() => {}) const { invoke } = await import('@tauri-apps/api/core') - await invoke('park_connection', { key: sessionKey(previous) }).catch(() => disconnectPostgres().catch(() => {})) + const parked = await invoke('park_connection', { key: kept }).then(() => true).catch(() => false) + if (!parked) { + kept = '' + await disconnectPostgres().catch(() => {}) + } else { + // What is on screen keeps working while the next database opens: its + // calls name its pool, which now waits in the parked list. + setConnRoute(kept) + } // A database kept open comes back in place: no teardown, no overlay, // no welcome screen in between (that was the flicker). const key = sessionKey(conn) - const kept = keepable(conn) ? _sessions.get(key) : undefined - if (kept) { - const resumed = await invoke('resume_connection', { key }).then(Boolean).catch(() => false) - if (resumed) { - setConnRoute(key) - _sessions.delete(key) - noteSession(key) - sessionsTick++ - await resumeSession(conn, kept, opts.focusTab ?? null) - sidebarShowTables() - return - } - } + const session = keepable(conn) ? _sessions.get(key) : undefined + if (session && (await resumeKept(key, session, opts.focusTab ?? null))) return } else { await disconnectPostgres().catch(() => {}) } - connection = null - clearConnectionState() // Labs: a kept pool for this database comes back at once, no overlay. let resumed = false if (multi && keepable(conn)) { const { invoke } = await import('@tauri-apps/api/core') resumed = await invoke('resume_connection', { key: sessionKey(conn) }).then(Boolean).catch(() => false) } - // Connect to the chosen saved connection - if (!resumed) beginConnectOverlay(conn.name ?? conn.database ?? conn.host ?? '') + if (kept) { + // The page stays as it is; the status bar says what is opening. + switchingTo = conn.name ?? conn.database ?? conn.host ?? '' + } else { + connection = null + clearConnectionState() + if (!resumed) beginConnectOverlay(conn.name ?? conn.database ?? conn.host ?? '') + } try { - try { - if (!resumed) await connectByType(conn) - } catch (e) { - // Provider credentials revoked or rotated in the provider's console: - // mint fresh ones once, the same recovery the connect dialog does. - const { AUTH_FAILURE, providerBuildConnection, providerToSaved } = await import('$lib/providers.js') - if (!(conn.provider && conn.providerRef && AUTH_FAILURE.test(String(e)))) throw e - const fresh = await providerBuildConnection(conn.provider, conn.providerRef) - if (fresh.needs_password) throw e - conn = { ...providerToSaved({ ...fresh, providerRef: conn.providerRef }, { provider: conn.provider, saved: [conn], readOnly: conn.readOnly, newId: newConnectionId }), id: conn.id, name: conn.name } - await connectByType(conn) - } + if (!resumed) conn = await connectWithRecovery(conn) + if (kept) clearConnectionState() + switchingTo = '' await onConnected(conn, conn.id) if (multi && keepable(conn)) { // Name the new front pool, so calls routed to it (and to the kept @@ -8682,18 +8767,23 @@ let rowSearch = $state('') // at any more, and the Databases tab is a switcher, not a destination. sidebarShowTables() } catch (e) { + switchingTo = '' // Say why, then put the user back where they were instead of leaving // them disconnected behind a dialog with no message in it. toast.error(`Could not connect to ${conn.name ?? conn.database ?? conn.host ?? 'the database'}`, { description: String(e) }) + const back = kept ? _sessions.get(kept) : undefined + if (back && (await resumeKept(kept, back, null))) return let restored = false if (previous) { try { + if (kept) clearConnectionState() await connectByType(previous) await onConnected(previous, previous.id) restored = true } catch { /* fall through to the dialog */ } } if (!restored) { + connection = null error = String(e) showConnectionModal = true } @@ -8702,6 +8792,45 @@ let rowSearch = $state('') } } + /** + * Labs: bring a kept database to the front, in place. False when its pool + * is gone (closed by the cap, or its connection edited): connect instead. + * @param {string} key @param {KeptSession} session @param {string | null} focusTab + */ + async function resumeKept(key, session, focusTab) { + const { invoke } = await import('@tauri-apps/api/core') + const ok = await invoke('resume_connection', { key }).then(Boolean).catch(() => false) + if (!ok) return false + setConnRoute(key) + _sessions.delete(key) + noteSession(key) + sessionsTick++ + await resumeSession(session.conn, session, focusTab) + sidebarShowTables() + return true + } + + /** + * Connect, and when a provider's credentials were revoked or rotated in its + * console, mint fresh ones once: the same recovery the connect dialog does. + * Returns the connection as connected (fresh credentials included). + * @param {any} conn + */ + async function connectWithRecovery(conn) { + try { + await connectByType(conn) + return conn + } catch (e) { + const { AUTH_FAILURE, providerBuildConnection, providerToSaved } = await import('$lib/providers.js') + if (!(conn.provider && conn.providerRef && AUTH_FAILURE.test(String(e)))) throw e + const fresh = await providerBuildConnection(conn.provider, conn.providerRef) + if (fresh.needs_password) throw e + const next = { ...providerToSaved({ ...fresh, providerRef: conn.providerRef }, { provider: conn.provider, saved: [conn], readOnly: conn.readOnly, newId: newConnectionId }), id: conn.id, name: conn.name } + await connectByType(next) + return next + } + } + // ── Silent auto-reconnect ────────────────────────────────────────────────── // Heals a dropped connection IN PLACE - rebuilds the backend pool for the // CURRENT connection config, with no UI teardown, no full-screen overlay, and @@ -9656,7 +9785,15 @@ let rowSearch = $state('') (showReportIssueDialog = true)} /> - + @@ -10219,11 +10356,13 @@ let rowSearch = $state('') {#snippet groupPane(/** @type {import('$lib/pane-layout.js').GroupNode} */ group, /** @type {boolean} */ isFocused)} {#if tabBarVisible && !tabsInTitle} + tabsById.get(id)).filter(Boolean)} + tabs={paneCount <= 1 && barTabs.some((t) => t.foreign) ? barTabs : group.tabIds.map((id) => tabsById.get(id)).filter(Boolean)} activeTabId={group.activeTabId} - onselect={(id) => void focusTabInGroup(group.id, id)} - onclose={(id) => void closeTabInGroup(group.id, id)} + onselect={(id) => (tabs.some((t) => t.id === id) ? void focusTabInGroup(group.id, id) : void activateForeignTab(id))} + onclose={(id) => (tabs.some((t) => t.id === id) ? void closeTabInGroup(group.id, id) : closeForeignTab(id))} oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} @@ -10233,7 +10372,7 @@ let rowSearch = $state('') canreopenclosed={closedTabStack.length > 0} onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} - ondragtabstart={(id) => beginTabDrag(id)} + ondragtabstart={(id) => { if (tabs.some((t) => t.id === id)) beginTabDrag(id) }} ondragtabmove={(x, y) => moveTabDrag(x, y)} ondragtabend={() => endTabDrag()} /> @@ -11524,6 +11663,9 @@ let rowSearch = $state('') {liveNative} ontogglelive={() => { liveEnabled = !liveEnabled }} onswitchconnection={handleSwitchDatabase} + {openDatabases} + onopendatabase={openKeptDatabase} + {switchingTo} {mcpRunning} latencyMs={dbLatencyMs} {offline} diff --git a/src/lib/components/TabBar.svelte b/src/lib/components/TabBar.svelte index 275c3175..99ae90ac 100644 --- a/src/lib/components/TabBar.svelte +++ b/src/lib/components/TabBar.svelte @@ -178,6 +178,10 @@ {@const tabIconName = tabIcon(tab)} {@const active = tab.id === activeTabId} + + {#if tab.groupStart} + + {/if} {#snippet child({ props: ctxProps })} @@ -204,7 +208,7 @@ type="button" role="tab" aria-selected={active} - title={tabDisplayTitle(tab)} + title={tab.connLabel ? `${tabDisplayTitle(tab)} · ${tab.connLabel}` : tabDisplayTitle(tab)} class={cn( 'flex min-w-0 flex-1 items-center gap-2 pl-2.5 text-left text-ui-xs leading-none transition-colors duration-100', // Every tab keeps the close button's slot, shown or not, so a @@ -217,11 +221,6 @@ onclick={() => { if (_suppressTabClick) { _suppressTabClick = false; return } onselect(tab.id) }} > - - {#if tab.connLabel} - {tab.connLabel} - {/if} {tabDisplayTitle(tab)} diff --git a/src/lib/crash-report.js b/src/lib/crash-report.js new file mode 100644 index 00000000..4166dd21 --- /dev/null +++ b/src/lib/crash-report.js @@ -0,0 +1,25 @@ +/** + * A crash report left by the last run (src-tauri/src/crash.rs), as the fields + * of a GitHub issue. Only what the panic hook recorded goes in: the message, + * where it happened, the version and the platform. The backtrace is trimmed to + * Stroke's own frames when there are any, and capped, since a URL carries it. + * + * @param {{ message: string, location: string, thread: string, version: string, os: string, at: number, backtrace: string }} c + */ +export function crashReportFields(c) { + const when = c.at ? new Date(c.at * 1000).toISOString().replace('T', ' ').slice(0, 19) + ' UTC' : 'unknown' + const frames = String(c.backtrace || '').split('\n') + const ours = frames.filter((l) => /\bapp(_lib)?::|src[\\/]/.test(l)) + const trace = (ours.length ? ours : frames).join('\n').slice(0, 2500) + const short = String(c.message || 'panic').split('\n')[0].slice(0, 90) + return { + title: `Crash: ${short}`, + body: 'Stroke closed by itself. What I was doing just before:\n\n', + details: [ + `${c.message}`, + `at ${c.location || 'unknown location'} (thread ${c.thread || 'unnamed'})`, + `Stroke ${c.version} on ${c.os}, ${when}`, + trace ? `\n${trace}` : '', + ].join('\n').trim(), + } +} diff --git a/src/lib/crash-report.test.js b/src/lib/crash-report.test.js new file mode 100644 index 00000000..7b8c0719 --- /dev/null +++ b/src/lib/crash-report.test.js @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { crashReportFields } from './crash-report.js' + +describe('crashReportFields', () => { + const base = { message: 'there is no reactor running', location: 'src/db/connection.rs:567', thread: 'main', version: '2.16.2', os: 'macos aarch64', at: 1763251200, backtrace: '' } + + it('titles the issue with the first line of the panic', () => { + expect(crashReportFields({ ...base, message: 'boom\nmore' }).title).toBe('Crash: boom') + }) + + it('puts the message, place, version and platform in the details', () => { + const d = crashReportFields(base).details + expect(d).toContain('there is no reactor running') + expect(d).toContain('src/db/connection.rs:567') + expect(d).toContain('Stroke 2.16.2 on macos aarch64') + }) + + it("keeps only Stroke's own frames when the backtrace has them", () => { + const backtrace = ['0: std::panicking::begin', '1: app_lib::db::parked::close_parked', '2: tao::event_loop::run'].join('\n') + const d = crashReportFields({ ...base, backtrace }).details + expect(d).toContain('app_lib::db::parked::close_parked') + expect(d).not.toContain('tao::event_loop') + }) +})