From 06221a8a9b538aad34baf794a85d44d7f96ad498 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 14:45:59 +0545 Subject: [PATCH 001/317] fix: Windows title bar, connection saving, theme lag, What's new and terminal install bar (#141) - Windows/Linux title bar is 40px with full-height, square caption buttons flush with the window edge (red behind close), as on Windows. - --app-statusbar-h follows the status bar's h-8, so zooming in no longer slides the connection page's footer over it. - The connection page saves a connection once it connects, not before: failed attempts no longer land in the list or sync. A provider page (TiDB Cloud, Neon, D1...) connects by picking a database; its footer Connect and Save are disabled instead of dialling 127.0.0.1. - previewTheme pauses transitions like applySettings, and the terminal and ERD recolour once per frame: stepping through the theme picker no longer fades ~750 controls per step. - Command palette: no footer shadow over the list, a shorter fade. - Ctrl+Alt+T opens the theme picker (theme.pick, rebindable). - What's new: one lead feature with the only filled button, the rest as a list with text actions, release notes folded behind "Show all N changes". Shorter highlight titles so none truncate. - Terminal: a bar above the built-in prompt says the client isn't installed and offers Install (or How to install), replacing the floating pill that covered output. --- .changeset/windows-smoke-2.md | 14 ++ src/lib/components/AppLockScreen.svelte | 2 +- src/lib/components/CommandPalette.svelte | 6 +- src/lib/components/ConnectionModal.svelte | 32 ++- src/lib/components/ErdCanvas.svelte | 7 +- src/lib/components/SignInScreen.svelte | 2 +- src/lib/components/StudioShell.svelte | 17 +- src/lib/components/TerminalPage.svelte | 85 +++++--- src/lib/components/TitleBar.svelte | 7 +- src/lib/components/TrialExpiredScreen.svelte | 2 +- src/lib/components/WhatsNewDialog.svelte | 206 +++++++++++-------- src/lib/components/WindowControls.svelte | 22 +- src/lib/shortcuts.js | 1 + src/lib/stores/settings.js | 4 + src/lib/whats-new.js | 22 +- 15 files changed, 270 insertions(+), 159 deletions(-) create mode 100644 .changeset/windows-smoke-2.md diff --git a/.changeset/windows-smoke-2.md b/.changeset/windows-smoke-2.md new file mode 100644 index 00000000..2244cf56 --- /dev/null +++ b/.changeset/windows-smoke-2.md @@ -0,0 +1,14 @@ +### Bug Fixes +- Windows and Linux: a 40px title bar with Windows-style minimize, maximize and close buttons +- Zooming in no longer pushes the connection page's footer over the status bar +- A failed connection is no longer saved or synced; it is saved once it connects +- TiDB Cloud and other providers: Connect waits for a database to be picked instead of dialling 127.0.0.1 +- Switching or previewing themes repaints at once, without the lag on Windows and Linux +- The command palette's footer no longer casts a heavy shadow over the list + +### New Features +- Ctrl+Alt+T (Cmd+Alt+T) opens the theme picker +- The terminal says when a client isn't installed in a bar above the prompt, with Install or How to install + +### Changes +- What's new leads with one feature, lists the rest, and folds the full release notes diff --git a/src/lib/components/AppLockScreen.svelte b/src/lib/components/AppLockScreen.svelte index c41978a7..f65aa3c7 100644 --- a/src/lib/components/AppLockScreen.svelte +++ b/src/lib/components/AppLockScreen.svelte @@ -57,7 +57,7 @@
{/if} + + {#if aiTabEverOpened && $appAiInTab} +
+ + {#await import('./AiChat.svelte')}{:then { default: AiChat }} + void handleAiWriteSql(sql)} + onopenmodelsettings={() => (showAiModelSettings = true)} + onopendiagramspage={openDiagramsTab} + onschemadirty={reloadAfterAiDdl} + /> + {/await} + +
+ {/if} + {#if logsEverOpened}
} */ +export const aiChatList = writable({ connectionId: '', chats: [], activeId: null, busyId: null, live: false }) + +/** A request the mounted AiChat has not taken yet. @type {import('svelte/store').Writable} */ +export const aiChatPending = writable(null) + +/** @param {Partial} patch */ +export function publishChatList(patch) { + aiChatList.update((s) => ({ ...s, ...patch })) +} + +/** @param {ChatRequest} req */ +export function requestChat(req) { + aiChatPending.set(req) +} + +/** The waiting request, cleared. */ +export function takeChatRequest() { + const req = get(aiChatPending) + if (req) aiChatPending.set(null) + return req +} diff --git a/src/lib/stores/conversations.js b/src/lib/stores/conversations.js index d2b7d37f..d8e6b0a5 100644 --- a/src/lib/stores/conversations.js +++ b/src/lib/stores/conversations.js @@ -9,6 +9,7 @@ const STORE = STORES.conversations * createdAt: number * updatedAt: number * schema: string + * database?: string - the database it last worked in (chats follow the connection) * connectionId: string * items: unknown[] * apiHistory: unknown[] @@ -21,7 +22,8 @@ function getDb() { } /** - * @param {string} [connectionId] when provided, only return conversations for that connection + * @param {string | ((key: string) => boolean)} [connectionId] when provided, only return + * conversations for that connection: its key, or a test on the stored key (lib/ai-chat-key.js) * @param {'chat' | 'sidebar'} [source] when 'sidebar', return only sidebar chats; otherwise * return full-chat conversations (excludes sidebar) so the two surfaces stay separate. * @returns {Promise} sorted newest first @@ -29,7 +31,8 @@ function getDb() { export async function listConversations(connectionId, source) { const db = await getDb() const all = await db.getAll(STORE) - let filtered = connectionId ? all.filter((c) => c.connectionId === connectionId) : all + const belongs = typeof connectionId === 'function' ? connectionId : (/** @type {string} */ k) => k === connectionId + let filtered = connectionId ? all.filter((c) => belongs(c.connectionId)) : all filtered = source === 'sidebar' ? filtered.filter((c) => c.source === 'sidebar') : filtered.filter((c) => c.source !== 'sidebar') @@ -75,6 +78,7 @@ export async function deleteConversation(id) { * @param {string} [connectionId] * @param {'chat' | 'sidebar'} [source] */ +/** @param {string | ((key: string) => boolean)} [connectionId] @param {'chat' | 'sidebar'} [source] */ export async function clearConversations(connectionId, source) { const list = await listConversations(connectionId, source) const db = await getDb() diff --git a/src/lib/stores/settings.js b/src/lib/stores/settings.js index 8a040ff6..7462f6d8 100644 --- a/src/lib/stores/settings.js +++ b/src/lib/stores/settings.js @@ -107,7 +107,7 @@ const markQualifyDefaultApplied = () => { /** @typedef {'claude' | 'geist' | 'serif' | 'apple' | 'inter' | 'mono' | 'fira' | 'plex' | 'space' | 'source'} FontId */ /** @typedef {'regular' | 'light' | 'bold'} IconStyleId */ /** @typedef {'lucide' | 'hugeicons' | 'phosphor'} IconSetId */ -/** @typedef {{ theme: ThemeId, zoom: number, font: FontId, iconStyle: IconStyleId, iconSet: IconSetId, tableStyle: TableStyleId, jsonTheme: JsonThemeId, editorTheme: import('$lib/themes/editor-themes.js').EditorThemeId, mcpAutoStart: boolean, launchAtLogin: boolean, autoUpdate: boolean, autoReconnectOnStartup: boolean, previewDmlBeforeApply: boolean, defaultDataView: string, paginationMode: string, maxQueryHistory: number, connectTimeoutMs: number, socketTimeoutMs: number, maxAllowedPacket: number, sessionTimezone: string, vimMode: boolean, cmdkAiEnabled: boolean, liveModeEnabled: boolean, sidebarStyle: SidebarStyleId, lazyWideColumns: boolean, nullSortOrder: string, agentChatFontSize: number, agentCodeFontSize: number, agentThinkingStyle: string, agentShowQueryCards: boolean, agentWebAccess: boolean, tableTextAlign: string, telemetry: boolean, jsonWordWrap: boolean, nativeScroll: boolean, rowSpacing: RowSpacingId, motion: MotionId, zebraRows: boolean, showRowNumbers: boolean, showMenuBar: boolean, numberGrouping: boolean, imagePreview: boolean, openUrlsOnClick: boolean, highlightActiveRow: boolean, fkAutoExpandJson: boolean, gridFontSize: number, autoSaveQueries: boolean, streamResults: boolean, sqlUndo: boolean, sidebarComments: boolean, sidebarRememberGroups: boolean, sqlFormat: import('$lib/sql-format-options.js').SqlFormatOptions, sqlEditor: import('$lib/sql-editor-options.js').SqlEditorOptions }} AppSettings */ +/** @typedef {{ theme: ThemeId, zoom: number, font: FontId, iconStyle: IconStyleId, iconSet: IconSetId, tableStyle: TableStyleId, jsonTheme: JsonThemeId, editorTheme: import('$lib/themes/editor-themes.js').EditorThemeId, mcpAutoStart: boolean, launchAtLogin: boolean, autoUpdate: boolean, autoReconnectOnStartup: boolean, previewDmlBeforeApply: boolean, defaultDataView: string, paginationMode: string, maxQueryHistory: number, connectTimeoutMs: number, socketTimeoutMs: number, maxAllowedPacket: number, sessionTimezone: string, vimMode: boolean, cmdkAiEnabled: boolean, liveModeEnabled: boolean, sidebarStyle: SidebarStyleId, aiInTab: boolean, lazyWideColumns: boolean, nullSortOrder: string, agentChatFontSize: number, agentCodeFontSize: number, agentThinkingStyle: string, agentShowQueryCards: boolean, agentWebAccess: boolean, tableTextAlign: string, telemetry: boolean, jsonWordWrap: boolean, nativeScroll: boolean, rowSpacing: RowSpacingId, motion: MotionId, zebraRows: boolean, showRowNumbers: boolean, showMenuBar: boolean, numberGrouping: boolean, imagePreview: boolean, openUrlsOnClick: boolean, highlightActiveRow: boolean, fkAutoExpandJson: boolean, gridFontSize: number, autoSaveQueries: boolean, streamResults: boolean, sqlUndo: boolean, sidebarComments: boolean, sidebarRememberGroups: boolean, sqlFormat: import('$lib/sql-format-options.js').SqlFormatOptions, sqlEditor: import('$lib/sql-editor-options.js').SqlEditorOptions }} AppSettings */ /** * UI type scale in design pixels: `[step, font-size, line-height?]`, matching @@ -600,6 +600,9 @@ export const DEFAULT_SETTINGS = { // Beta: 'tree' swaps the sidebar's Tables / Objects / Databases tabs for one // explorer tree (connection > database > schema > groups > objects > columns). sidebarStyle: 'classic', + // Beta: AI chat opens as a tab beside your tables, its chats listed in the + // sidebar, instead of taking over the whole window. + aiInTab: false, // On by default. A column averaging half a megabyte a row is fetched as a // size, and its value is loaded per cell on demand - the difference between a // table opening in a second and in eleven. Off restores the old behaviour: @@ -714,6 +717,9 @@ export const appLiveMode = writable(false) /** Reactive: which sidebar style is showing - the tab strip, or the Tree (beta). */ export const appSidebarStyle = writable(/** @type {SidebarStyleId} */ ('classic')) +/** Reactive: AI chat opens as a tab, chats in the sidebar (beta), instead of AI mode. */ +export const appAiInTab = writable(false) + /** Whether the agent transcript shows a card per executed query. */ export const appAgentQueryCards = writable(true) @@ -952,6 +958,7 @@ export function loadSettings() { const sidebarRememberGroups = parsed.sidebarRememberGroups !== false const liveModeEnabled = parsed.liveModeEnabled === true const sidebarStyle = parsed.sidebarStyle === 'tree' ? 'tree' : 'classic' + const aiInTab = parsed.aiInTab === true const lazyWideColumns = parsed.lazyWideColumns !== false const nullSortOrder = NULL_SORT_IDS.includes(parsed.nullSortOrder) ? parsed.nullSortOrder : DEFAULT_NULL_SORT const agentChatFontSize = migrateAgentFont(parsed.agentChatFontSize, LEGACY_AGENT_CHAT_FONT, DEFAULT_AGENT_CHAT_FONT) @@ -960,7 +967,7 @@ export function loadSettings() { const agentShowQueryCards = parsed.agentShowQueryCards !== false const agentWebAccess = parsed.agentWebAccess === true const tableTextAlign = TABLE_ALIGN_IDS.includes(parsed.tableTextAlign) ? parsed.tableTextAlign : DEFAULT_TABLE_ALIGN - _settingsCache = { theme, zoom, font, iconStyle, iconSet, tableStyle, jsonTheme, editorTheme, mcpAutoStart, launchAtLogin, autoUpdate, autoReconnectOnStartup, previewDmlBeforeApply, defaultDataView, paginationMode, maxQueryHistory, connectTimeoutMs, socketTimeoutMs, maxAllowedPacket, sessionTimezone, vimMode, cmdkAiEnabled, liveModeEnabled, sidebarStyle, lazyWideColumns, nullSortOrder, agentChatFontSize, agentCodeFontSize, agentThinkingStyle, agentShowQueryCards, agentWebAccess, tableTextAlign, telemetry, jsonWordWrap, nativeScroll, rowSpacing, motion, zebraRows, showRowNumbers, showMenuBar, numberGrouping, imagePreview, openUrlsOnClick, highlightActiveRow, fkAutoExpandJson, gridFontSize, autoSaveQueries, streamResults, sqlUndo, sidebarComments, sidebarRememberGroups, sqlFormat, sqlEditor } + _settingsCache = { theme, zoom, font, iconStyle, iconSet, tableStyle, jsonTheme, editorTheme, mcpAutoStart, launchAtLogin, autoUpdate, autoReconnectOnStartup, previewDmlBeforeApply, defaultDataView, paginationMode, maxQueryHistory, connectTimeoutMs, socketTimeoutMs, maxAllowedPacket, sessionTimezone, vimMode, cmdkAiEnabled, liveModeEnabled, sidebarStyle, aiInTab, lazyWideColumns, nullSortOrder, agentChatFontSize, agentCodeFontSize, agentThinkingStyle, agentShowQueryCards, agentWebAccess, tableTextAlign, telemetry, jsonWordWrap, nativeScroll, rowSpacing, motion, zebraRows, showRowNumbers, showMenuBar, numberGrouping, imagePreview, openUrlsOnClick, highlightActiveRow, fkAutoExpandJson, gridFontSize, autoSaveQueries, streamResults, sqlUndo, sidebarComments, sidebarRememberGroups, sqlFormat, sqlEditor } if (fontMigrated) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(_settingsCache)) } catch {} } @@ -1249,6 +1256,7 @@ function applySettingsNow(settings, root, theme, zoom, dark) { setStore(appSidebarRememberGroups, settings.sidebarRememberGroups !== false) setStore(appLiveMode, settings.liveModeEnabled === true) setStore(appSidebarStyle, settings.sidebarStyle === 'tree' ? 'tree' : 'classic') + setStore(appAiInTab, settings.aiInTab === true) setStore(appAgentQueryCards, settings.agentShowQueryCards !== false) setStore(appAgentWebAccess, settings.agentWebAccess === true) setStore(appTableAlign, TABLE_ALIGN_IDS.includes(settings.tableTextAlign) ? settings.tableTextAlign : DEFAULT_TABLE_ALIGN) From 7013c1acef25e692d561c93bdd1503bdab0210dc Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:35:32 +0545 Subject: [PATCH 018/317] fix(providers): no auto-connect, wait for a new database, searchable region picker (#153) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drop the one-database auto-pick: picking is the user's. - pick({ fresh }) after a create probes the database (SELECT 1 / PING over execute_sql_on_connection, ~40s, stops on an auth failure) before handing it over, so Prisma's first 'Failed to connect to upstream database' never reaches the connect. The trigger reads 'Starting …' meanwhile. - Region and organization use SearchableMenu (search past 6 items). - Password field with an inline copy button. --- .changeset/provider-panel.md | 5 + src/lib/components/ProviderConnect.svelte | 64 +++++++---- .../components/ProviderCreateDatabase.svelte | 103 ++++++++++++------ 3 files changed, 116 insertions(+), 56 deletions(-) create mode 100644 .changeset/provider-panel.md diff --git a/.changeset/provider-panel.md b/.changeset/provider-panel.md new file mode 100644 index 00000000..1a1e5910 --- /dev/null +++ b/.changeset/provider-panel.md @@ -0,0 +1,5 @@ +### Bug Fixes +- Provider panel: an account with one database no longer connects to it unasked; you pick it +- A database just created on Prisma Postgres (or any provider) is connected once it takes connections, instead of failing with "Failed to connect to upstream database" the first time +- Region and organization in "New database" are searchable, like the database list +- The generated password shows in one field with its copy button inside it diff --git a/src/lib/components/ProviderConnect.svelte b/src/lib/components/ProviderConnect.svelte index e5bed70f..7fd22b43 100644 --- a/src/lib/components/ProviderConnect.svelte +++ b/src/lib/components/ProviderConnect.svelte @@ -1,8 +1,3 @@ - - + +{#snippet picker(/** @type {{ items: any[], current: string | null | undefined, currentName: string, noun: string, labelledby: string, onpick: (v: string) => void }} */ p)} + p.onpick(it.value)} + > + {#snippet trigger(props)} + + {/snippet} + {#snippet item(it)} + {it.label} + {#if it.value === p.current}{/if} + {/snippet} + +{/snippet} + {#if step === 'form'}
1}
{options?.scope_label || 'Organization'} - - - {scopeName || 'Select…'} - - - {#each options?.scopes ?? [] as s (s.id)} - {s.name} - {/each} - - + {@render picker({ + items: (options?.scopes ?? []).map((s) => ({ value: s.id, label: s.name, keywords: [s.name, s.id] })), + current: scope, + currentName: scopeName, + noun: (options?.scope_label || 'organization').toLowerCase(), + labelledby: `${uid}-scope`, + onpick: changeScope, + })}
{/if} {#if needsRegion || loadingOptions}
{options?.region_label || 'Region'} - v && (region = v)}> - - {#if loadingOptions} - - - {:else} - {regionName || 'Select…'} - {/if} - - - {#each options?.regions ?? [] as r (r.id)} - {r.name} - {/each} - - + {@render picker({ + items: (options?.regions ?? []).map((r) => ({ value: r.id, label: r.name, keywords: [r.name, r.id] })), + current: region, + currentName: regionName, + noun: (options?.region_label || 'region').toLowerCase(), + labelledby: `${uid}-region`, + onpick: (/** @type {string} */ v) => v && (region = v), + })}
{/if}
@@ -268,18 +296,25 @@ {#if password}
Database password -
+ +
{password} - + class="min-w-0 flex-1 truncate font-mono text-ui-xs tabular-nums text-foreground select-all" + >{password} + {copied ? 'Password copied' : ''}

- Generated for you. {providerName} won't show it again; Stroke saves it with this connection. Copy it if you'll connect from somewhere else. + {providerName} won't show it again. Stroke saves it with the connection.

{/if} From 7834f24d0caa48309566f6102fe0a7061109d485 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:35:37 +0545 Subject: [PATCH 019/317] =?UTF-8?q?feat(docker):=20launch=20catalog=20of?= =?UTF-8?q?=2018=20database=20images=20from=20=E2=8C=98K=20(#154)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - docker.rs: TEMPLATES (image, env, command, credentials, readiness) and docker_templates; docker_run_db takes a template id, picks a free host port, waits per engine (SELECT 1 for Postgres/MySQL protocols, a log line (count) for Redis/Mongo/CouchDB/Cassandra/SQL Server/Oracle, an HTTP answer for ClickHouse/DynamoDB Local/libSQL), and returns the saved-connection object for that engine. - Palette Docker page: Running containers, then the catalog by group, with DbIcon marks; the modal starts the chosen image at once. - db-icons: simple-icons marks for MongoDB, Cassandra, CouchDB, Oracle, DynamoDB, Firestore, and Timescale. --- .changeset/docker-catalog.md | 4 + src-tauri/src/docker.rs | 388 +++++++++++--------- src-tauri/src/lib.rs | 1 + src/lib/api.js | 9 + src/lib/components/CommandPalette.svelte | 75 ++-- src/lib/components/DockerLaunchModal.svelte | 201 +++++----- src/lib/components/StudioShell.svelte | 22 +- src/lib/db-icons.js | 13 +- 8 files changed, 394 insertions(+), 319 deletions(-) create mode 100644 .changeset/docker-catalog.md diff --git a/.changeset/docker-catalog.md b/.changeset/docker-catalog.md new file mode 100644 index 00000000..30bdc695 --- /dev/null +++ b/.changeset/docker-catalog.md @@ -0,0 +1,4 @@ +### Features +- ⌘K → Docker starts any of 18 databases in one step, each with its brand icon: PostgreSQL 17 and 16, pgvector, PostGIS, TimescaleDB, MySQL, MariaDB, SQL Server, Oracle Free, CockroachDB, MongoDB, Redis, Valkey, CouchDB, DynamoDB Local, Cassandra, ClickHouse and a libSQL server. It picks a free port, waits until the database takes connections, and opens it +- ⌘K → Docker lists the database containers already running, to open in one step +- Real brand marks for MongoDB, Cassandra, CouchDB, Oracle, DynamoDB and Firestore diff --git a/src-tauri/src/docker.rs b/src-tauri/src/docker.rs index 2b016635..141aa7b9 100644 --- a/src-tauri/src/docker.rs +++ b/src-tauri/src/docker.rs @@ -3,6 +3,7 @@ use std::process::Stdio; use tauri::Emitter; use tokio::io::AsyncBufReadExt; use tokio::process::Command as Cmd; +use serde_json::Value; /// `docker …`, with no console window on Windows. The container scan runs on the /// connection screen, so a bare spawn flashed a cmd.exe window at app start. @@ -16,63 +17,12 @@ fn docker() -> Cmd { // TCP-open ≠ database-ready. MySQL/Postgres accept TCP connections seconds before // they finish initialization. We retry actual SQL pings to confirm readiness. -async fn wait_mysql_ready(host_port: u16, password: &str) -> bool { - let url = format!( - "mysql://root:{password}@127.0.0.1:{host_port}/mysql?ssl-mode=disabled" - ); - for _ in 0..60u32 { - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - if let Ok(pool) = sqlx::mysql::MySqlPoolOptions::new() - .max_connections(1) - .acquire_timeout(std::time::Duration::from_secs(2)) - .connect(&url) - .await - { - let ok = sqlx::query("SELECT 1").execute(&pool).await.is_ok(); - pool.close().await; - if ok { return true; } - } - } - false -} - -async fn wait_postgres_ready(host_port: u16, password: &str) -> bool { - let url = format!( - "postgres://postgres:{password}@127.0.0.1:{host_port}/postgres?sslmode=disable" - ); - for _ in 0..60u32 { - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - if let Ok(pool) = sqlx::postgres::PgPoolOptions::new() - .max_connections(1) - .acquire_timeout(std::time::Duration::from_secs(2)) - .connect(&url) - .await - { - let ok = sqlx::query("SELECT 1").execute(&pool).await.is_ok(); - pool.close().await; - if ok { return true; } - } - } - false -} - #[derive(serde::Serialize, Clone)] pub struct DockerLog { pub line: String, pub kind: String, } -#[derive(serde::Serialize, Clone)] -pub struct DockerConnInfo { - pub db_type: String, - pub host: String, - pub port: u16, - pub user: String, - pub password: String, - pub database: String, - pub name: String, -} - fn emit_log(app: &tauri::AppHandle, event: &str, line: &str, kind: &str) { let _ = app.emit( event, @@ -114,153 +64,239 @@ pub async fn docker_check() -> Result { Ok(if v.is_empty() { "ok".to_string() } else { v }) } +// ── The launch catalog ──────────────────────────────────────────────────────── +// Every engine Stroke can open, as a container it can start with one click: the +// image, how to start it, the credentials it starts with, and how to tell it is +// ready. The palette lists these (docker_templates) and docker_run_db launches +// one, returning a connection the app opens as it is. + +/// How to tell a fresh container is ready for a client. +#[derive(Clone, Copy)] +enum Ready { + /// `SELECT 1` over the Postgres protocol (Postgres, CockroachDB). + Postgres, + /// `SELECT 1` over the MySQL protocol (MySQL, MariaDB). + Mysql, + /// This line in the container's log, at least this many times (MongoDB + /// prints it once for its setup run and again for the real server). + Log(&'static str, usize), + /// Any HTTP answer at this path. Not a bare TCP connect: Docker's port + /// proxy accepts those before anything listens inside the container. + Http(&'static str), +} + +struct Template { + id: &'static str, + label: &'static str, + /// Stroke engine id: the connection type, and the palette's icon. + engine: &'static str, + /// Icon when it isn't the engine's own (pgvector shows Postgres anyway). + icon: &'static str, + group: &'static str, + image: &'static str, + note: &'static str, + /// Port inside the container. + port: u16, + /// Preferred host port; the next free one is used when it is taken. + host_port: u16, + env: &'static [&'static str], + /// Arguments after the image (the container's command). + cmd: &'static [&'static str], + user: &'static str, + password: &'static str, + database: &'static str, + ready: Ready, + /// Seconds to wait for `ready`; Oracle and SQL Server start slowly. + wait_secs: u64, +} + +const PG_ENV: &[&str] = &["POSTGRES_PASSWORD=postgres", "POSTGRES_USER=postgres", "POSTGRES_DB=postgres"]; + +const TEMPLATES: &[Template] = &[ + Template { id: "postgres", label: "PostgreSQL 17", engine: "postgres", icon: "postgres", group: "Relational", image: "postgres:17-alpine", note: "", port: 5432, host_port: 5433, env: PG_ENV, cmd: &[], user: "postgres", password: "postgres", database: "postgres", ready: Ready::Postgres, wait_secs: 90 }, + Template { id: "postgres16", label: "PostgreSQL 16", engine: "postgres", icon: "postgres", group: "Relational", image: "postgres:16-alpine", note: "", port: 5432, host_port: 5434, env: PG_ENV, cmd: &[], user: "postgres", password: "postgres", database: "postgres", ready: Ready::Postgres, wait_secs: 90 }, + Template { id: "pgvector", label: "PostgreSQL + pgvector", engine: "postgres", icon: "postgres", group: "Relational", image: "pgvector/pgvector:pg17", note: "Vector search", port: 5432, host_port: 5435, env: PG_ENV, cmd: &[], user: "postgres", password: "postgres", database: "postgres", ready: Ready::Postgres, wait_secs: 90 }, + Template { id: "postgis", label: "PostGIS", engine: "postgres", icon: "postgres", group: "Relational", image: "postgis/postgis:17-3.5", note: "Geospatial", port: 5432, host_port: 5436, env: PG_ENV, cmd: &[], user: "postgres", password: "postgres", database: "postgres", ready: Ready::Postgres, wait_secs: 120 }, + Template { id: "timescale", label: "TimescaleDB", engine: "postgres", icon: "timescale", group: "Relational", image: "timescale/timescaledb:latest-pg17", note: "Time series", port: 5432, host_port: 5437, env: PG_ENV, cmd: &[], user: "postgres", password: "postgres", database: "postgres", ready: Ready::Postgres, wait_secs: 120 }, + // MySQL 8.4 defaults to caching_sha2_password, which needs TLS or an RSA + // exchange; native passwords let the driver connect over loopback. + Template { id: "mysql", label: "MySQL 8.4", engine: "mysql", icon: "mysql", group: "Relational", image: "mysql:8.4", note: "", port: 3306, host_port: 3307, env: &["MYSQL_ROOT_PASSWORD=mysql", "MYSQL_DATABASE=app"], cmd: &["--mysql-native-password=ON"], user: "root", password: "mysql", database: "app", ready: Ready::Mysql, wait_secs: 120 }, + Template { id: "mariadb", label: "MariaDB 11", engine: "mariadb", icon: "mariadb", group: "Relational", image: "mariadb:11", note: "", port: 3306, host_port: 3308, env: &["MARIADB_ROOT_PASSWORD=mariadb", "MARIADB_DATABASE=app"], cmd: &[], user: "root", password: "mariadb", database: "app", ready: Ready::Mysql, wait_secs: 120 }, + Template { id: "mssql", label: "SQL Server 2022", engine: "mssql", icon: "mssql", group: "Relational", image: "mcr.microsoft.com/mssql/server:2022-latest", note: "x86-64 only", port: 1433, host_port: 1434, env: &["ACCEPT_EULA=Y", "MSSQL_SA_PASSWORD=Stroke_Passw0rd!"], cmd: &[], user: "sa", password: "Stroke_Passw0rd!", database: "master", ready: Ready::Log("SQL Server is now ready for client connections", 1), wait_secs: 180 }, + Template { id: "oracle", label: "Oracle Database Free", engine: "oracle", icon: "oracle", group: "Relational", image: "gvenzl/oracle-free:slim", note: "Needs Instant Client", port: 1521, host_port: 1521, env: &["ORACLE_PASSWORD=oracle", "APP_USER=app", "APP_USER_PASSWORD=app"], cmd: &[], user: "app", password: "app", database: "FREEPDB1", ready: Ready::Log("DATABASE IS READY TO USE!", 1), wait_secs: 300 }, + Template { id: "cockroachdb", label: "CockroachDB", engine: "cockroachdb", icon: "cockroachdb", group: "Relational", image: "cockroachdb/cockroach:latest", note: "Single node", port: 26257, host_port: 26257, env: &[], cmd: &["start-single-node", "--insecure"], user: "root", password: "", database: "defaultdb", ready: Ready::Postgres, wait_secs: 120 }, + Template { id: "mongodb", label: "MongoDB 8", engine: "mongodb", icon: "mongodb", group: "Document and key-value", image: "mongo:8", note: "", port: 27017, host_port: 27018, env: &["MONGO_INITDB_ROOT_USERNAME=mongo", "MONGO_INITDB_ROOT_PASSWORD=mongo"], cmd: &[], user: "mongo", password: "mongo", database: "app", ready: Ready::Log("Waiting for connections", 2), wait_secs: 90 }, + Template { id: "redis", label: "Redis 7", engine: "redis", icon: "redis", group: "Document and key-value", image: "redis:7-alpine", note: "", port: 6379, host_port: 6380, env: &[], cmd: &[], user: "", password: "", database: "", ready: Ready::Log("Ready to accept connections", 1), wait_secs: 60 }, + Template { id: "valkey", label: "Valkey 8", engine: "valkey", icon: "valkey", group: "Document and key-value", image: "valkey/valkey:8-alpine", note: "", port: 6379, host_port: 6381, env: &[], cmd: &[], user: "", password: "", database: "", ready: Ready::Log("Ready to accept connections", 1), wait_secs: 60 }, + Template { id: "couchdb", label: "CouchDB 3", engine: "couchdb", icon: "couchdb", group: "Document and key-value", image: "couchdb:3", note: "", port: 5984, host_port: 5985, env: &["COUCHDB_USER=admin", "COUCHDB_PASSWORD=couchdb"], cmd: &[], user: "admin", password: "couchdb", database: "", ready: Ready::Log("Apache CouchDB has started", 1), wait_secs: 90 }, + Template { id: "dynamodb", label: "DynamoDB Local", engine: "dynamodb", icon: "dynamodb", group: "Document and key-value", image: "amazon/dynamodb-local:latest", note: "", port: 8000, host_port: 8001, env: &[], cmd: &[], user: "", password: "", database: "", ready: Ready::Http("/"), wait_secs: 60 }, + Template { id: "cassandra", label: "Cassandra 5", engine: "cassandra", icon: "cassandra", group: "Document and key-value", image: "cassandra:5", note: "Starts in about a minute", port: 9042, host_port: 9043, env: &[], cmd: &[], user: "", password: "", database: "", ready: Ready::Log("Starting listening for CQL clients", 1), wait_secs: 240 }, + Template { id: "clickhouse", label: "ClickHouse", engine: "clickhouse", icon: "clickhouse", group: "Analytics", image: "clickhouse/clickhouse-server:latest", note: "", port: 8123, host_port: 8124, env: &["CLICKHOUSE_USER=default", "CLICKHOUSE_PASSWORD=clickhouse", "CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1"], cmd: &[], user: "default", password: "clickhouse", database: "default", ready: Ready::Http("/ping"), wait_secs: 90 }, + Template { id: "libsql", label: "libSQL server", engine: "libsql", icon: "turso", group: "Analytics", image: "ghcr.io/tursodatabase/libsql-server:latest", note: "Turso, self-hosted", port: 8080, host_port: 8081, env: &[], cmd: &[], user: "", password: "", database: "", ready: Ready::Http("/health"), wait_secs: 60 }, +]; + +/// What the palette lists for one launchable image. +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DockerTemplate { + pub id: &'static str, + pub label: &'static str, + pub engine: &'static str, + pub icon: &'static str, + pub group: &'static str, + pub image: &'static str, + pub note: &'static str, + pub port: u16, +} + #[tauri::command] -pub async fn docker_run_db( - app: tauri::AppHandle, - db_type: String, - event_id: String, -) -> Result { - let evt = format!("docker-log:{event_id}"); +pub fn docker_templates() -> Vec { + TEMPLATES + .iter() + .map(|t| DockerTemplate { id: t.id, label: t.label, engine: t.engine, icon: t.icon, group: t.group, image: t.image, note: t.note, port: t.host_port }) + .collect() +} - let (image, host_port, cont_port): (&str, u16, u16) = match db_type.as_str() { - "postgres" => ("postgres:17-alpine", 5433, 5432), - "mysql" => ("mysql:8.4", 3307, 3306), - other => return Err(format!("Unsupported database type: {other}")), - }; +/// The preferred port if nothing listens there, else the next free one. +fn free_port(preferred: u16) -> u16 { + let free = |p: u16| std::net::TcpListener::bind(("127.0.0.1", p)).is_ok(); + (preferred..preferred.saturating_add(100)).find(|p| free(*p)).unwrap_or_else(|| { + std::net::TcpListener::bind(("127.0.0.1", 0)).and_then(|l| l.local_addr()).map(|a| a.port()).unwrap_or(preferred) + }) +} - let (user, password, database): (&str, &str, &str) = match db_type.as_str() { - "postgres" => ("postgres", "postgres", "postgres"), - "mysql" => ("root", "mysql", "mysql"), - _ => unreachable!(), - }; +/// The saved-connection object the app opens for a launched template. +fn connection_for(t: &Template, port: u16) -> Value { + let host = "127.0.0.1"; + let name = format!("Docker {} (:{port})", t.label); + match t.engine { + "mongodb" => serde_json::json!({ "type": "mongodb", "name": name, "uri": format!("mongodb://{}:{}@{host}:{port}/?authSource=admin", t.user, t.password), "database": t.database }), + "redis" | "valkey" => serde_json::json!({ "type": t.engine, "name": name, "host": host, "port": port, "db": 0 }), + "couchdb" => serde_json::json!({ "type": "couchdb", "name": name, "url": format!("http://{host}:{port}"), "user": t.user, "password": t.password }), + "dynamodb" => serde_json::json!({ "type": "dynamodb", "name": name, "region": "us-east-1", "endpoint": format!("http://{host}:{port}"), "accessKeyId": "local", "secretAccessKey": "local" }), + "cassandra" => serde_json::json!({ "type": "cassandra", "name": name, "hosts": format!("{host}:{port}") }), + "libsql" => serde_json::json!({ "type": "libsql", "name": name, "url": format!("http://{host}:{port}") }), + "oracle" => serde_json::json!({ "type": "oracle", "name": name, "host": host, "port": port, "serviceName": t.database, "user": t.user, "password": t.password }), + "mssql" => serde_json::json!({ "type": "mssql", "name": name, "host": host, "port": port, "user": t.user, "password": t.password, "database": t.database, "trustCert": true }), + _ => serde_json::json!({ "type": t.engine, "name": name, "host": host, "port": port, "user": t.user, "password": t.password, "database": t.database, "ssl": false }), + } +} - let ts = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - let container_name = format!("stroke-{db_type}-{ts}"); - let port_map = format!("{host_port}:{cont_port}"); +async fn wait_ready(t: &Template, container: &str, port: u16) -> bool { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(t.wait_secs); + while std::time::Instant::now() < deadline { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + let ok = match t.ready { + Ready::Postgres => { + let url = format!("postgres://{}:{}@127.0.0.1:{port}/{}?sslmode=disable", t.user, t.password, t.database); + match sqlx::postgres::PgPoolOptions::new().max_connections(1).acquire_timeout(std::time::Duration::from_secs(2)).connect(&url).await { + Ok(pool) => { + let ok = sqlx::query("SELECT 1").execute(&pool).await.is_ok(); + pool.close().await; + ok + } + Err(_) => false, + } + } + Ready::Mysql => { + let url = format!("mysql://{}:{}@127.0.0.1:{port}/{}?ssl-mode=disabled", t.user, t.password, t.database); + match sqlx::mysql::MySqlPoolOptions::new().max_connections(1).acquire_timeout(std::time::Duration::from_secs(2)).connect(&url).await { + Ok(pool) => { + let ok = sqlx::query("SELECT 1").execute(&pool).await.is_ok(); + pool.close().await; + ok + } + Err(_) => false, + } + } + Ready::Http(path) => { + let url = format!("http://127.0.0.1:{port}{path}"); + let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(2)).build(); + match client { + Ok(c) => c.get(&url).send().await.is_ok(), + Err(_) => false, + } + } + Ready::Log(line, times) => { + let logs = docker().args(["logs", container]).output().await; + logs.is_ok_and(|o| { + let all = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr)); + all.matches(line).count() >= times + }) + } + }; + if ok { + return true; + } + } + false +} - // ── Pull ────────────────────────────────────────────────────────────────── - emit_log(&app, &evt, &format!("Pulling {image}…"), "info"); +/// Pull and run one catalog image, wait until it takes connections, and +/// return the connection to open. `db_type` is a template id (`postgres`, +/// `mongodb`, ...); logs stream as `docker-log:{event_id}`. +#[tauri::command] +pub async fn docker_run_db(app: tauri::AppHandle, db_type: String, event_id: String) -> Result { + let evt = format!("docker-log:{event_id}"); + let t = TEMPLATES + .iter() + .find(|t| t.id == db_type) + .ok_or_else(|| format!("No Docker image for {db_type}"))?; + let host_port = free_port(t.host_port); + if host_port != t.host_port { + emit_log(&app, &evt, &format!("Port {} is taken, using {host_port}.", t.host_port), "info"); + } + let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let container_name = format!("stroke-{}-{ts}", t.id); + // ── Pull ────────────────────────────────────────────────────────────────── + emit_log(&app, &evt, &format!("Pulling {}…", t.image), "info"); let mut pull_child = docker() - .args(["pull", image]) + .args(["pull", t.image]) .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() .map_err(|e| format!("Failed to start docker pull: {e}"))?; - if let Some(stderr) = pull_child.stderr.take() { let mut lines = tokio::io::BufReader::new(stderr).lines(); while let Ok(Some(line)) = lines.next_line().await { - let t = line.trim(); - if !t.is_empty() { - emit_log(&app, &evt, t, "info"); + let line = line.trim(); + if !line.is_empty() { + emit_log(&app, &evt, line, "info"); } } } - let pull_status = pull_child.wait().await.map_err(|e| e.to_string())?; if !pull_status.success() { - return Err(format!( - "docker pull {image} failed. Check your internet connection." - )); + return Err(format!("docker pull {} failed. Check your internet connection, or whether the image runs on this machine ({}).", t.image, std::env::consts::ARCH)); } - emit_log(&app, &evt, "Image ready. Starting container…", "info"); // ── Run ─────────────────────────────────────────────────────────────────── let mut run_cmd = docker(); - run_cmd - .arg("run") - .arg("-d") - .arg("--name") - .arg(&container_name) - .arg("-p") - .arg(&port_map); - - match db_type.as_str() { - "postgres" => { - run_cmd - .arg("-e") - .arg("POSTGRES_PASSWORD=postgres") - .arg("-e") - .arg("POSTGRES_USER=postgres") - .arg("-e") - .arg("POSTGRES_DB=postgres"); - } - "mysql" => { - run_cmd - .arg("-e") - .arg("MYSQL_ROOT_PASSWORD=mysql") - .arg("-e") - .arg("MYSQL_DATABASE=mysql") - // MySQL 8.4 uses caching_sha2_password by default which requires SSL or - // RSA key exchange. Enable mysql_native_password so sqlx can connect - // without TLS on loopback connections. - .arg("--mysql-native-password=ON"); - } - _ => {} + run_cmd.args(["run", "-d", "--name", &container_name, "-p", &format!("{host_port}:{}", t.port)]); + for e in t.env { + run_cmd.args(["-e", e]); } - run_cmd.arg(image); - - let run_out = run_cmd - .output() - .await - .map_err(|e| format!("Failed to launch container: {e}"))?; - + run_cmd.arg(t.image).args(t.cmd); + let run_out = run_cmd.output().await.map_err(|e| format!("Failed to launch container: {e}"))?; if !run_out.status.success() { let err = String::from_utf8_lossy(&run_out.stderr); - let msg = if err.contains("port is already allocated") - || err.contains("address already in use") - { + return Err(if err.contains("port is already allocated") || err.contains("address already in use") { format!("Port {host_port} is already in use. Stop the existing service and try again.") } else { format!("Container failed to start: {err}") - }; - return Err(msg); + }); } - let cid = String::from_utf8_lossy(&run_out.stdout).trim().to_string(); - let short = &cid[..cid.len().min(12)]; - emit_log(&app, &evt, &format!("Container {short} started."), "info"); - emit_log( - &app, - &evt, - "Waiting for database to accept connections…", - "info", - ); + emit_log(&app, &evt, &format!("Container {} started on port {host_port}.", &cid[..cid.len().min(12)]), "info"); + emit_log(&app, &evt, "Waiting for the database to accept connections…", "info"); - let ready = match db_type.as_str() { - "mysql" => wait_mysql_ready(host_port, password).await, - "postgres" => wait_postgres_ready(host_port, password).await, - _ => false, - }; - - if !ready { - return Err(format!( - "Database did not become ready within 60s. Container: {container_name}" - )); + if !wait_ready(t, &container_name, host_port).await { + return Err(format!("{} did not become ready within {}s. Container: {container_name} (docker logs {container_name})", t.label, t.wait_secs)); } - emit_log(&app, &evt, "Database is ready.", "info"); - - let label = if db_type == "postgres" { - "PostgreSQL" - } else { - "MySQL" - }; - - Ok(DockerConnInfo { - db_type, - host: "127.0.0.1".to_string(), - port: host_port, - user: user.to_string(), - password: password.to_string(), - database: database.to_string(), - name: format!("Docker {label} (:{host_port})"), - }) + Ok(connection_for(t, host_port)) } // ── Databases already running in Docker ─────────────────────────────────────── @@ -270,7 +306,6 @@ pub async fn docker_run_db( // running containers and hands back ready-to-open connections. use serde::Serialize; -use serde_json::Value; #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] @@ -683,3 +718,28 @@ mod action_tests { docker_container_action("stroke-test-mysql".into(), "restart".into()).await.unwrap(); } } + +#[cfg(test)] +mod catalog_tests { + use super::*; + + #[test] + fn template_ids_are_unique_and_connections_name_their_engine() { + let mut ids: Vec<&str> = TEMPLATES.iter().map(|t| t.id).collect(); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), TEMPLATES.len()); + for t in TEMPLATES { + let c = connection_for(t, 4000); + assert_eq!(c["type"], t.engine, "{}", t.id); + assert!(c["name"].as_str().unwrap().contains(":4000"), "{}", t.id); + } + } + + #[test] + fn free_port_skips_a_taken_one() { + let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = taken.local_addr().unwrap().port(); + assert_ne!(free_port(port), port); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 52237693..d9cd9845 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -802,6 +802,7 @@ pub fn run() { omniroute::omniroute_running, docker::docker_check, docker::docker_run_db, + docker::docker_templates, docker::scan_docker_databases, docker::docker_container_action, db::local_scan::scan_local_studios, diff --git a/src/lib/api.js b/src/lib/api.js index fd1b2cc1..ad521cdf 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -1049,6 +1049,15 @@ export async function scanLocalStudios() { return inv('scan_local_studios') } +/** + * What the Docker launcher can start: one row per image, grouped by kind. + * @typedef {{ id: string, label: string, engine: string, icon: string, group: string, image: string, note: string, port: number }} DockerTemplate + * @returns {Promise} + */ +export async function dockerTemplates() { + return inv('docker_templates') +} + /** * Database containers running in Docker, with the credentials they were started * with - read from the container's own environment, so nothing has to be typed. diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index 3ef60e1b..6a71bd65 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -8,7 +8,8 @@ import { aiSettings, isAiConfigured } from '$lib/stores/ai-settings.js' import { pinEnabled, lockNow } from '$lib/stores/app-lock.js' import { appCmdkAi, appThemeId, appSidebarStyle, previewTheme, endThemePreview, updateSettings } from '$lib/stores/settings.js' - import { executeSql } from '$lib/api.js' + import { executeSql, dockerTemplates, scanDockerDatabases } from '$lib/api.js' + import DbIcon from './DbIcon.svelte' import { themesByGroup, getThemeDefinition } from '$lib/themes/registry.js' import ThemeSwatchStrip from './ThemeSwatchStrip.svelte' @@ -86,6 +87,8 @@ onreadonlytoggle = () => {}, /** @param {'postgres'|'mysql'} dbType */ ondockerlaunch = (dbType) => {}, + /** Open a database already running in Docker. @type {(conn: Record) => void} */ + onopendocker = () => {}, /** @param {import('$lib/stores/connections.js').SavedConnection} conn */ onswitchdatabase = (conn) => {}, /** @type {import('$lib/stores/query-history.js').QueryHistoryEntry[]} */ @@ -120,6 +123,23 @@ /** Value of the highlighted command row (bound to the palette). */ let highlighted = $state('') + + // ── Docker page: the launch catalog and what is already running ────────── + /** @type {import('$lib/api.js').DockerTemplate[]} */ + let dockerTpls = $state([]) + /** @type {import('$lib/api.js').DockerDatabase[]} */ + let dockerRunning = $state([]) + $effect(() => { + if (page !== 'docker') return + if (!dockerTpls.length) dockerTemplates().then((t) => (dockerTpls = t)).catch(() => {}) + scanDockerDatabases().then((d) => (dockerRunning = d.filter((x) => !x.reason))).catch(() => {}) + }) + const dockerGroups = $derived.by(() => { + /** @type {Map} */ + const m = new Map() + for (const t of dockerTpls) m.set(t.group, [...(m.get(t.group) ?? []), t]) + return [...m] + }) /** The theme in effect when the page opened; null when no preview is live. */ let themeOrigin = $state(/** @type {ThemeId | null} */ (null)) /** Off until the page has highlighted the current theme, so the first row is never flashed. */ @@ -1045,8 +1065,8 @@ - navigate('docker')}> - + navigate('docker')}> + Docker @@ -1123,24 +1143,37 @@ {:else if page === 'docker'} - - run(() => ondockerlaunch('postgres'))} - > - - PostgreSQL container - :5433 - - run(() => ondockerlaunch('mysql'))} - > - - MySQL container - :3307 - - + {#if dockerRunning.length} + + {#each dockerRunning as d (d.containerId)} + run(() => onopendocker({ id: `docker-${d.name}`, type: d.engine, name: d.name, host: d.host, port: d.port, user: d.user, password: d.password, database: d.database }))} + > + + {d.name} + {d.target} + + {/each} + + {/if} + {#each dockerGroups as [group, items] (group)} + + {#each items as t (t.id)} + run(() => ondockerlaunch(t.id))} + > + + {t.label}{#if t.note}{t.note}{/if} + {t.image} + + {/each} + + {/each} + {#if !dockerTpls.length} +
Loading images…
+ {/if} {:else if page === 'connections'} diff --git a/src/lib/components/DockerLaunchModal.svelte b/src/lib/components/DockerLaunchModal.svelte index 638943b5..5b21aa4e 100644 --- a/src/lib/components/DockerLaunchModal.svelte +++ b/src/lib/components/DockerLaunchModal.svelte @@ -1,191 +1,162 @@ - + - - Docker Database + {#if current} + {current.label} + {:else} + Start a database in Docker + {/if} - Pull and run a database container, then connect instantly. + {#if current?.image}{current.image}{:else}Pulls the image, starts it, and connects when it is ready.{/if} {#if phase === 'pick'} -
- {#each DB_OPTIONS as opt (opt.type)} - +
+ {#each groups as [group, items] (group)} +
+

{group}

+ {#each items as t (t.id)} + + {/each} +
{/each} -

- Requires Docker Desktop to be installed and running -

+ {#if !templates.length} +

Loading images…

+ {/if}
{:else if phase === 'running'}
- - Pulling and starting {selectedDb === 'postgres' ? 'PostgreSQL' : 'MySQL'}… + + {logs.at(-1) ?? 'Checking Docker…'}
{#each logs as line, i (i)}
{line}
{/each} - {#if logs.length === 0} - Waiting for output… - {/if}
-
- - {:else if phase === 'done' && connInfo} -
-
- - Container is running and ready -
-
-
- host{connInfo.host}:{connInfo.port} - user{connInfo.user} - pass{connInfo.password} - db{connInfo.database} -
-
- +

The first start downloads the image; later starts take seconds.

{:else if phase === 'error'}
- - {errorMsg} + + {errorMsg} +
+
+ + {#if current}{/if}
-
{/if} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index d9448dbd..68ffae5b 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -7802,26 +7802,21 @@ let rowSearch = $state('') } /** @param {{ db_type: string, host: string, port: number, user: string, password: string, database: string, name: string }} info */ + /** + * A container the Docker launcher started: save it and open it. The backend + * returns the saved-connection shape for its engine (Postgres, MongoDB, + * Redis, Oracle, ...). + * @param {Record} info + */ async function handleDockerConnect(info) { - const conn = /** @type {import('$lib/stores/connections.js').SavedConnection} */ ({ - id: crypto.randomUUID(), - type: info.db_type === 'mysql' ? 'mysql' : 'postgres', - name: info.name, - host: info.host, - port: info.port, - user: info.user, - password: info.password, - database: info.database, - ssl: false, - }) + const conn = /** @type {import('$lib/stores/connections.js').SavedConnection} */ ({ id: crypto.randomUUID(), ...info }) upsertConnection(conn) await disconnectPostgres().catch(() => {}) connection = null clearConnectionState() beginConnectOverlay(conn.name ?? '') try { - if (conn.type === 'mysql' || conn.type === 'mariadb') await connectMysql(conn) - else await connectPostgres(conn) + await connectByType(conn) await onConnected(conn, conn.id) showDockerModal = false } catch (e) { @@ -8979,6 +8974,7 @@ let rowSearch = $state('') onopenreport={() => (showReportIssueDialog = true)} oncheckupdate={() => void updateDialog?.checkNow()} ondockerlaunch={(dbType) => { commandOpen = false; dockerInitialDb = dbType; showDockerModal = true }} + onopendocker={(c) => { commandOpen = false; void handleDockerConnect(c) }} onswitchdatabase={handleSwitchDatabase} {queryHistory} {savedQueries} diff --git a/src/lib/db-icons.js b/src/lib/db-icons.js index b5540444..b44ebf09 100644 --- a/src/lib/db-icons.js +++ b/src/lib/db-icons.js @@ -11,6 +11,7 @@ export const BRAND_MARKS = { mysql: { d: 'M116.948 97.807c-6.863-.187-12.104.452-16.585 2.341-1.273.537-3.305.552-3.513 2.147.7.733.809 1.829 1.365 2.731 1.07 1.73 2.876 4.052 4.488 5.268 1.762 1.33 3.577 2.751 5.465 3.902 3.358 2.047 7.107 3.217 10.34 5.268 1.906 1.21 3.799 2.733 5.658 4.097.92.675 1.537 1.724 2.732 2.147v-.194c-.628-.8-.79-1.898-1.366-2.733l-2.537-2.537c-2.48-3.292-5.629-6.184-8.976-8.585-2.669-1.916-8.642-4.504-9.755-7.609l-.195-.195c1.892-.214 4.107-.898 5.854-1.367 2.934-.786 5.556-.583 8.585-1.365l4.097-1.171v-.78c-1.531-1.571-2.623-3.651-4.292-5.073-4.37-3.72-9.138-7.437-14.048-10.537-2.724-1.718-6.089-2.835-8.976-4.292-.971-.491-2.677-.746-3.318-1.562-1.517-1.932-2.342-4.382-3.511-6.633-2.449-4.717-4.854-9.868-7.024-14.831-1.48-3.384-2.447-6.72-4.293-9.756-8.86-14.567-18.396-23.358-33.169-32-3.144-1.838-6.929-2.563-10.929-3.513-2.145-.129-4.292-.26-6.438-.391-1.311-.546-2.673-2.149-3.902-2.927C17.811 4.565 5.257-2.16 1.633 6.682c-2.289 5.581 3.421 11.025 5.462 13.854 1.434 1.982 3.269 4.207 4.293 6.438.674 1.467.79 2.938 1.367 4.489 1.417 3.822 2.652 7.98 4.487 11.511.927 1.788 1.949 3.67 3.122 5.268.718.981 1.951 1.413 2.145 2.927-1.204 1.686-1.273 4.304-1.95 6.44-3.05 9.615-1.899 21.567 2.537 28.683 1.36 2.186 4.567 6.871 8.975 5.073 3.856-1.57 2.995-6.438 4.098-10.732.249-.973.096-1.689.585-2.341v.195l3.513 7.024c2.6 4.187 7.212 8.562 11.122 11.514 2.027 1.531 3.623 4.177 6.244 5.073v-.196h-.195c-.508-.791-1.303-1.119-1.951-1.755-1.527-1.497-3.225-3.358-4.487-5.073-3.556-4.827-6.698-10.11-9.561-15.609-1.368-2.627-2.557-5.523-3.709-8.196-.444-1.03-.438-2.589-1.364-3.122-1.263 1.958-3.122 3.542-4.098 5.854-1.561 3.696-1.762 8.204-2.341 12.878-.342.122-.19.038-.391.194-2.718-.655-3.672-3.452-4.683-5.853-2.554-6.07-3.029-15.842-.781-22.829.582-1.809 3.21-7.501 2.146-9.172-.508-1.666-2.184-2.63-3.121-3.903-1.161-1.574-2.319-3.646-3.124-5.464-2.09-4.731-3.066-10.044-5.267-14.828-1.053-2.287-2.832-4.602-4.293-6.634-1.617-2.253-3.429-3.912-4.683-6.635-.446-.968-1.051-2.518-.391-3.513.21-.671.508-.951 1.171-1.17 1.132-.873 4.284.29 5.462.779 3.129 1.3 5.741 2.538 8.392 4.294 1.271.844 2.559 2.475 4.097 2.927h1.756c2.747.631 5.824.195 8.391.975 4.536 1.378 8.601 3.523 12.292 5.854 11.246 7.102 20.442 17.21 26.732 29.269 1.012 1.942 1.45 3.794 2.341 5.854 1.798 4.153 4.063 8.426 5.852 12.488 1.786 4.052 3.526 8.141 6.05 11.513 1.327 1.772 6.451 2.723 8.781 3.708 1.632.689 4.307 1.409 5.854 2.34 2.953 1.782 5.815 3.903 8.586 5.855 1.383.975 5.64 3.116 5.852 4.879zM29.729 23.466c-1.431-.027-2.443.156-3.513.389v.195h.195c.683 1.402 1.888 2.306 2.731 3.513.65 1.367 1.301 2.732 1.952 4.097l.194-.193c1.209-.853 1.762-2.214 1.755-4.294-.484-.509-.555-1.147-.975-1.755-.556-.811-1.635-1.272-2.339-1.952z', vb: '0 0 128 128', hex: '#00618A' }, mariadb: { d: 'M23.157 4.412c-.676.284-.79.31-1.673.372-.65.045-.757.057-1.212.209-.75.246-1.395.75-2.02 1.59-.296.398-1.249 1.913-1.249 1.988 0 .057-.65.998-.915 1.32-.574.713-1.08 1.079-2.14 1.59-.77.36-1.224.524-4.102 1.477-1.073.353-2.133.738-2.367.864-.852.449-1.515 1.036-2.203 1.938-1.003 1.32-.972 1.313-3.042.947a12.264 12.264 0 00-.675-.063c-.644-.05-1.023.044-1.332.334L0 17.193l.177.088c.094.05.353.234.561.398.215.17.461.347.55.391.088.044.17.088.183.101.012.013-.089.17-.228.353-.435.581-.593.871-.574 1.048.019.164.032.17.43.17.517-.006.826-.056 1.261-.208.65-.233 2.058-.94 2.784-1.4.776-.5 1.717-.998 1.956-1.042.082-.02.354-.07.594-.114.58-.107 1.464-.095 2.587.05.108.013.373.045.6.064.227.025.43.057.454.076.026.012.474.037.998.056.934.026 1.104.007 1.3-.189.126-.133.385-.631.498-.985.209-.643.417-.921.366-.492-.113.966-.322 1.692-.713 2.411-.259.499-.663 1.092-.934 1.395-.322.347-.315.36.088.315.619-.063 1.471-.397 2.096-.82.827-.562 1.647-1.691 2.19-3.03.107-.27.22-.22.183.083-.013.094-.038.315-.057.498l-.031.328.353-.202c.833-.48 1.414-1.262 2.127-2.884.227-.518.877-2.922 1.073-3.976a9.64 9.64 0 01.271-1.042c.127-.429.196-.555.48-.858.183-.19.625-.555.978-.808.72-.505.953-.75 1.187-1.205.208-.417.284-1.13.132-1.357-.132-.202-.284-.196-.763.006Z', hex: '#003545' }, cockroachdb: { d: 'M17.645 16.155a13.013 13.013 0 0 0-4.479-13.287 11.617 11.617 0 0 1 5.815-1.546c.774 0 1.545.075 2.304.226l.32-1.282A13.092 13.092 0 0 0 18.98 0 12.93 12.93 0 0 0 12 2.03 12.933 12.933 0 0 0 5.021 0C4.139 0 3.26.089 2.396.266l.319 1.282a11.83 11.83 0 0 1 2.306-.226 11.64 11.64 0 0 1 5.817 1.544 13.01 13.01 0 0 0 .792 20.877l.375.257.373-.257c2.624-1.801 4.5-4.5 5.27-7.588zm-6.305 5.7A11.687 11.687 0 0 1 7.825 9.519a13.08 13.08 0 0 0 2.457 2.977 3.202 3.202 0 0 1 1.058 2.383zm.661-9.657a11.717 11.717 0 0 1-2.343-2.315 3.23 3.23 0 0 1 0-3.912 11.67 11.67 0 0 1 2.347-2.333c.9.671 1.697 1.468 2.37 2.366a3.197 3.197 0 0 1 0 3.832 11.816 11.816 0 0 1-2.374 2.362zm.659 9.657v-6.976a3.202 3.202 0 0 1 1.06-2.383 13.026 13.026 0 0 0 2.455-2.977 11.694 11.694 0 0 1-3.515 12.336Z', hex: '#6933FF' }, + timescale: { d: 'M5.537.763c-1.167.7-2.21 1.582-3.08 2.61L3.79 4.836a10.422 10.422 0 013.627-2.881zm13.028.085l-1.991 1.12a10.381 10.381 0 013.762 3.07l1.18-1.654a12.371 12.371 0 00-2.95-2.536zm-6.564.752a9.788 9.788 0 00-4.131.91l.59 1.011a8.542 8.542 0 013.541-.762c1.261 0 2.457.274 3.534.76l.59-1.012a9.81 9.81 0 00-4.124-.907zM11.4 3.535l-.55 6.626h.003l-.002.04c.003.111.013.216.033.318.01.112.043.227.097.342.114.289.298.505.516.607.05.04.105.075.158.111a.98.98 0 01.033.02v.004l6.68 3.596.348-.476-6.058-4.6c-.007 0-.01-.005-.014-.008L12 3.535zm1.423.052c.19.234.361.523.502.855 3.155.604 5.54 3.325 5.54 6.596 0 .877-.176 1.712-.484 2.48a3.7 3.7 0 01.52.76 7.314 7.314 0 00.754-3.24c0-3.868-2.99-7.05-6.832-7.45zm-2.284.095c-3.527.667-6.19 3.708-6.19 7.356 0 2.584 1.335 4.863 3.367 6.21a9.84 9.84 0 01.295-.743c-1.74-1.219-2.874-3.214-2.874-5.467 0-3.054 2.082-5.632 4.932-6.45.128-.351.289-.656.47-.906zm9.15 1.675l-.801.893a8.101 8.101 0 011.551 4.777c0 2.916-1.542 5.481-3.872 6.952.104.388.188.792.251 1.209 2.87-1.632 4.802-4.677 4.802-8.16a9.224 9.224 0 00-1.93-5.67zm-15.38.007a9.25 9.25 0 00-1.93 5.665c0 3.507 1.954 6.567 4.858 8.19.063-.418.144-.822.248-1.206-2.36-1.468-3.923-4.045-3.923-6.984 0-1.777.573-3.422 1.549-4.772zm9.314.043c.044.203.08.416.107.64a5.332 5.332 0 013.213 2.912l.577-.148a5.942 5.942 0 00-3.897-3.404zm-3.816.187a5.939 5.939 0 00-3.319 3.198l.58.148A5.324 5.324 0 019.73 6.257c.017-.227.04-.45.077-.663zM6.733 9.672l-.62.63.315.614 1.727.618.942-.618-.312-.923zm10.615 0l-2.048.321-.315.923.942.618 1.73-.618.315-.614zM6.1 11.869A5.824 5.824 0 008.42 15.7c.1-.17.204-.335.315-.493a5.252 5.252 0 01-2.038-3.34zm11.206 0c-.03.18-.071.355-.118.529.174.138.338.272.493.41.097-.302.174-.617.22-.94zm-15.679.217L0 14.158c.966 3.661 3.638 6.65 7.132 8.111a9.399 9.399 0 01-.05-1.031c0-.375.017-.747.05-1.111-3.024-1.563-5.166-4.544-5.505-8.041zm20.707.055c-.352 3.45-2.464 6.394-5.441 7.957.033.374.05.755.053 1.136 0 .377-.017.71-.05 1.005 3.506-1.488 6.175-4.522 7.104-8.223zm-6.544 2.617a5.31 5.31 0 01-.486.42c.11.158.218.322.318.493.265-.2.513-.42.74-.66a10.61 10.61 0 01-.572-.253zm1.502.559a6.9 6.9 0 01-1.25 1.156c.106.236.207.485.294.741a7.667 7.667 0 001.857-1.772 3.554 3.554 0 01-.9-.125zm-2.988.63l-2.303.913-2.307-.91-.587 1.435 2.448.946c-.134.46-.568.798-1.08.798-.034 0-.07-.004-.104-.007l-.5.686c.188.063.39.096.6.096.621 0 1.17-.289 1.52-.738a1.924 1.924 0 002.183.62l-.49-.67a1.122 1.122 0 01-1.26-.805l2.47-.926zm1.156 4.775c-1.09.377-2.256.58-3.476.58-1.17 0-2.29-.186-3.34-.534.231.88.59 1.654 1.05 2.262.743.134 1.509.207 2.294.207.835 0 1.65-.082 2.437-.236.453-.61.807-1.39 1.035-2.28z', hex: '#FDB515' }, sqlite: { d: 'M21.678.521c-1.032-.92-2.28-.55-3.513.544a8.71 8.71 0 0 0-.547.535c-2.109 2.237-4.066 6.38-4.674 9.544.237.48.422 1.093.544 1.561a13.044 13.044 0 0 1 .164.703s-.019-.071-.096-.296l-.05-.146a1.689 1.689 0 0 0-.033-.08c-.138-.32-.518-.995-.686-1.289-.143.423-.27.818-.376 1.176.484.884.778 2.4.778 2.4s-.025-.099-.147-.442c-.107-.303-.644-1.244-.772-1.464-.217.804-.304 1.346-.226 1.478.152.256.296.698.422 1.186.286 1.1.485 2.44.485 2.44l.017.224a22.41 22.41 0 0 0 .056 2.748c.095 1.146.273 2.13.5 2.657l.155-.084c-.334-1.038-.47-2.399-.41-3.967.09-2.398.642-5.29 1.661-8.304 1.723-4.55 4.113-8.201 6.3-9.945-1.993 1.8-4.692 7.63-5.5 9.788-.904 2.416-1.545 4.684-1.931 6.857.666-2.037 2.821-2.912 2.821-2.912s1.057-1.304 2.292-3.166c-.74.169-1.955.458-2.362.629-.6.251-.762.337-.762.337s1.945-1.184 3.613-1.72C21.695 7.9 24.195 2.767 21.678.521m-18.573.543A1.842 1.842 0 0 0 1.27 2.9v16.608a1.84 1.84 0 0 0 1.835 1.834h9.418a22.953 22.953 0 0 1-.052-2.707c-.006-.062-.011-.141-.016-.2a27.01 27.01 0 0 0-.473-2.378c-.121-.47-.275-.898-.369-1.057-.116-.197-.098-.31-.097-.432 0-.12.015-.245.037-.386a9.98 9.98 0 0 1 .234-1.045l.217-.028c-.017-.035-.014-.065-.031-.097l-.041-.381a32.8 32.8 0 0 1 .382-1.194l.2-.019c-.008-.016-.01-.038-.018-.053l-.043-.316c.63-3.28 2.587-7.443 4.8-9.791.066-.069.133-.128.198-.194Z', hex: '#003B57' }, clickhouse: { d: 'M21.333 10H24v4h-2.667ZM16 1.335h2.667v21.33H16Zm-5.333 0h2.666v21.33h-2.666ZM0 22.665V1.335h2.667v21.33zm5.333-21.33H8v21.33H5.333Z', hex: '#FFCC01' }, duckdb: { d: 'M12 0C5.363 0 0 5.363 0 12s5.363 12 12 12 12-5.363 12-12S18.637 0 12 0zM9.502 7.03a4.974 4.974 0 0 1 4.97 4.97 4.974 4.974 0 0 1-4.97 4.97A4.974 4.974 0 0 1 4.532 12a4.974 4.974 0 0 1 4.97-4.97zm6.563 3.183h2.351c.98 0 1.787.782 1.787 1.762s-.807 1.789-1.787 1.789h-2.351v-3.551z', hex: '#FFF000' }, @@ -33,12 +34,12 @@ export const BRAND_MARKS = { mssql: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#CC2927' }, redis: { d: 'M22.71 13.145c-1.66 2.092-3.452 4.483-7.038 4.483-3.203 0-4.397-2.825-4.48-5.12.701 1.484 2.073 2.685 4.214 2.63 4.117-.133 6.94-3.852 6.94-7.239 0-4.05-3.022-6.972-8.268-6.972-3.752 0-8.4 1.428-11.455 3.685C2.59 6.937 3.885 9.958 4.35 9.626c2.648-1.904 4.748-3.13 6.784-3.744C8.12 9.244.886 17.05 0 18.425c.1 1.261 1.66 4.648 2.424 4.648.232 0 .431-.133.664-.365a100.49 100.49 0 0 0 5.54-6.765c.222 3.104 1.748 6.898 6.014 6.898 3.819 0 7.604-2.756 9.33-8.965.2-.764-.73-1.361-1.261-.73zm-4.349-5.013c0 1.959-1.926 2.922-3.685 2.922-.941 0-1.664-.247-2.235-.568 1.051-1.592 2.092-3.225 3.21-4.973 1.972.334 2.71 1.43 2.71 2.619z', hex: '#FF4438' }, // Generic cylinders in each brand's color; no third-party artwork is bundled. - dynamodb: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#4053D6' }, - mongodb: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#47A248' }, - couchdb: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#E42528' }, - cassandra: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#1287B1' }, - firestore: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#FFA000' }, - oracle: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#C74634' }, + dynamodb: { d: 'M16.606 20.705v-2.371c-1.263 1.082-3.884 1.795-7.066 1.795-3.184 0-5.805-.714-7.068-1.797v2.369c0 1.168 2.903 2.47 7.068 2.47 4.16 0 7.06-1.3 7.066-2.466zm.001-6.765l.817-.005v.005c0 .517-.258.998-.75 1.441.601.54.75 1.071.75 1.449a1661.7 1661.7 0 0 0 0 3.87c0 1.881-3.389 3.3-7.884 3.3-4.471 0-7.846-1.404-7.88-3.27a583.119 583.119 0 0 1-.003-3.909c.001-.375.15-.9.745-1.437-.592-.538-.743-1.062-.746-1.435v-3.892c.002-.377.153-.903.747-1.438-.593-.54-.744-1.062-.747-1.435 0-1.357-.002-2.735.002-3.897C1.674 1.412 5.056 0 9.54 0c2.159 0 4.233.356 5.689.974l-.315.766c-1.36-.58-3.319-.91-5.374-.91-4.165 0-7.067 1.3-7.067 2.47 0 1.168 2.902 2.47 7.067 2.47.115 0 .222 0 .334-.005l.033.828c-.122.006-.245.006-.367.006-3.184 0-5.805-.714-7.068-1.798v2.38c.005.45.45.843.821 1.093 1.116.736 3.114 1.239 5.34 1.342l-.037.829c-2.254-.105-4.23-.59-5.5-1.332-.318.245-.623.573-.623.952 0 1.168 2.902 2.47 7.067 2.47.411 0 .812-.014 1.203-.042l.06.826c-.41.03-.833.045-1.263.045-3.184 0-5.805-.713-7.068-1.797v2.368c.005.462.449.855.821 1.104 1.275.842 3.67 1.366 6.247 1.366h.182v.83H9.54c-2.62 0-4.99-.507-6.444-1.359-.317.245-.623.574-.623.954 0 1.168 2.902 2.47 7.067 2.47 4.159 0 7.058-1.298 7.066-2.465v-.007c0-.377-.303-.705-.62-.948a5.732 5.732 0 0 1-.662.336l-.316-.764c.3-.128.56-.266.776-.412.376-.254.823-.651.823-1.1zm4.377-6.915h-2.717a.406.406 0 0 1-.332-.173.42.42 0 0 1-.055-.375l1.204-3.597h-5.403l-2.583 4.974h2.623c.128 0 .248.06.325.164a.418.418 0 0 1 .069.36l-2.249 8.365zm1.249-.128l-10.89 11.608a.408.408 0 0 1-.498.075.418.418 0 0 1-.192-.471l2.534-9.426h-2.766a.407.407 0 0 1-.349-.2.418.418 0 0 1-.012-.407l3.014-5.804a.408.408 0 0 1 .36-.222h6.22c.132 0 .256.065.332.174a.422.422 0 0 1 .055.374l-1.204 3.598h3.1c.164 0 .31.099.375.251a.422.422 0 0 1-.08.45zM3.085 20.723a8.107 8.107 0 0 0 1.72.72l.233-.794a7.32 7.32 0 0 1-1.546-.645zm1.72-5.984l.233-.795a7.262 7.262 0 0 1-1.546-.646l-.407.72a8.051 8.051 0 0 0 1.72.72zm-1.72-7.427l.407-.719c.418.244.939.462 1.546.646l-.232.794a8.046 8.046 0 0 1-1.72-.72Z', hex: '#4053D6' }, + mongodb: { d: 'M17.193 9.555c-1.264-5.58-4.252-7.414-4.573-8.115-.28-.394-.53-.954-.735-1.44-.036.495-.055.685-.523 1.184-.723.566-4.438 3.682-4.74 10.02-.282 5.912 4.27 9.435 4.888 9.884l.07.05A73.49 73.49 0 0111.91 24h.481c.114-1.032.284-2.056.51-3.07.417-.296.604-.463.85-.693a11.342 11.342 0 003.639-8.464c.01-.814-.103-1.662-.197-2.218zm-5.336 8.195s0-8.291.275-8.29c.213 0 .49 10.695.49 10.695-.381-.045-.765-1.76-.765-2.405z', hex: '#47A248' }, + couchdb: { d: 'M19.5 14.625c0 .995-.524 1.482-1.5 1.5H6c-.976-.018-1.5-.505-1.5-1.5s.524-1.482 1.5-1.5h12c.976.018 1.5.505 1.5 1.5m-1.5 2.25H6c-.976.018-1.5.505-1.5 1.5s.524 1.482 1.5 1.5h12c.976-.018 1.5-.505 1.5-1.5s-.524-1.482-1.5-1.5m3.75-8.248v-.001c-.976.017-1.5.504-1.5 1.499v8.25c0 .995.524 1.482 1.5 1.5v-.002c1.464-.052 2.25-1.514 2.25-4.498v-3.75c0-1.99-.786-2.964-2.25-2.998m-19.5-.001C.786 8.662 0 9.637 0 11.626v3.75c0 2.984.786 4.446 2.25 4.498v.001c.976-.017 1.5-.504 1.5-1.499v-8.25c0-.995-.524-1.482-1.5-1.5m19.5-.75c0-2.486-1.31-3.705-3.75-3.748v-.002H6v.002c-2.44.043-3.75 1.262-3.75 3.748v.001c1.464.026 2.25.757 2.25 2.249s.786 2.223 2.25 2.249v.001h10.5v-.001c1.464-.026 2.25-.757 2.25-2.249s.786-2.223 2.25-2.249z', hex: '#E42528' }, + cassandra: { d: 'M10.374 10.53a3.102 3.102 0 0 1-.428-.222l.555.143c0 .02-.01.036-.01.055l-.117.025zm-.283 1.506-.315.253.852-1.079-1.078.391c.002.017.009.033.009.05a.57.57 0 0 1-.184.42c.102.217.228.424.375.616a3.2 3.2 0 0 1 .34-.651zm.717-2.347-.652-.82a.427.427 0 0 1-.506.162c-.054.073-.083.162-.13.24l1.258.463c.011-.015.019-.031.03-.045zm-1.666.444c-.07.314-.087.637-.05.956a.566.566 0 0 1 .451.475l.946-.606c-.067-.022-.126-.06-.191-.088l-1.119-.08.64-.14a3.186 3.186 0 0 1-.668-.554l-.01.037zM20.1 11.648c-.164.202.833 1.022.833 1.022s-1.654-1.022-2.234-.72c-.278.144.574.811 1.175 1.242-.428-.274-.982-.571-1.175-.408-.328.277 1.565 2.549 1.565 2.549s-2.145-2.322-2.36-2.209c-.214.114.593 1.224.593 1.224s-1.06-1.16-1.35-.959c-.29.202 1.514 3.218 1.514 3.218s-1.956-3.091-2.763-2.574c1.268 2.782.795 3.18.795 3.18s-.162-2.839-1.742-2.764c-.795.038.379 2.12.379 2.12s-1.08-1.902-1.8-1.864c1.326 2.51.854 3.53.854 3.53s.219-2.143-1.58-3.336c.682.606-.427 3.336-.427 3.336s.976-4.023-.719-3.256c-.268.121-.019 2.007-.019 2.007s-.34-2.158-.851-2.045c-.298.066-1.893 2.99-1.893 2.99s1.306-3.16.908-3.027c-.29.096-.833 1.4-.833 1.4s.265-1.287 0-1.363c-.264-.075-1.74 1.363-1.74 1.363s1.097-1.287.908-1.552c-.287-.402-.623-.42-1.022-.265-.581.226-1.363 1.287-1.363 1.287s.78-1.074.643-1.476c-.219-.647-2.46 1.249-2.46 1.249s1.325-1.25 1.022-1.514c-.303-.265-1.947-.183-2.46-.185-1.515-.004-2.039-.36-2.498-.724 1.987.997 3.803-.151 6.094.494l.21.06c-1.3-.558-2.144-1.378-2.226-2.354-.036-.416.074-.827.297-1.222.619-.4 1.29-.773 2.06-1.095a4 4 0 0 0-.064.698c0 2.44 2.203 4.417 4.92 4.417s4.92-1.977 4.92-4.417c0-.45-.083-.881-.223-1.29 1.431.404 2.45.968 3.132 1.335.022.092.045.184.053.279.024.274-.018.547-.11.814.095-.147.198-.288.28-.445.367-.997 1.855.227 1.855.227s-1.085-.454-1.06-.24c.026.215 1.628.96 1.628.96s-1.45-.455-1.362-.114c.088.34 1.817 1.703 1.817 1.703s-1.956-1.489-2.12-1.287zm-7.268 2.65.042-.008-.06.01zM9.256 9.753c.12.13.26.234.396.343l.927-.029-1.064-.788c-.093.154-.195.303-.26.474Zm10.62 3.44c.3.215.54.373.54.373s-.24-.181-.54-.374zM7.507 8.617c-.14.229-.214.492-.215.76a3.99 3.99 0 0 0 2.358 3.64c0-.005.002-.01.003-.014a3.19 3.19 0 0 1-.58-.788c-.648.099-.926-.794-.336-1.08a3.174 3.174 0 0 1 .138-1.388 3.162 3.162 0 0 1-.52-1.36c-.296.07-.579.147-.848.23Zm1.488.82c.108-.24.243-.46.402-.661a.435.435 0 0 1 .568-.557c.077-.059.166-.099.248-.15a16.17 16.17 0 0 0-1.727.284c.114.388.272.76.509 1.084Zm2.285 3.928c1.4 0 2.633-.723 3.344-1.816a3.399 3.399 0 0 0-1.265-.539l-.297-.023.916.9-1.197-.467.704 1.078-1.074-.832-.012.006.347 1.278-.596-1.134-.098 1.33-.401-1.326-.472 1.261.114-1.359c-.006-.002-.01-.006-.015-.008l-.814 1.154.286-1.067c-.34.322-.605.713-.781 1.146.095.102.197.198.303.29.322.083.66.128 1.008.128zm10.145-4.434c.971-.567 1.716-1.955 1.716-1.955s-1.893 1.955-3.205 1.665c1.186-.934 1.766-2.549 1.766-2.549s-1.506 2.325-2.448 2.423c1.086-.959 1.54-2.322 1.54-2.322s-1.237 1.817-2.196 1.944c1.287-1.161 1.338-1.893 1.338-1.893s-1.781 2.302-2.499 1.943c.858-.934 1.439-2.12 1.439-2.12s-1.489 2.019-1.893 1.69c-.277-.05.454-.958.454-.958s-.908.807-1.16.606c.454-.278 1.236-1.64 1.236-1.64S16 7.505 15.621 7.304l.731-1.483s-.73 1.483-1.715 1.23c.454-.58.63-1.112.63-1.112s-.756 1.213-1.69.885c-.22-.077.273-.635.273-.635s-.626.61-1.055.534c-.43-.076.025-.858.025-.858s-.757 1.186-.908 1.136c-.152-.05.075-.833.075-.833s-.555.908-.858.858c-.302-.05 0-.934 0-.934s-.328.984-.58.909c-.252-.076-.303-.656-.303-.656s-.068.788-.429.858c-2.725.53-5.728 1.69-9.489 5.45C3.887 10.738 5.3 7.91 11.962 7.659c5.044-.191 7.399 2.137 8.177 2.17C22.51 9.93 24 7.633 24 7.633s-1.489 1.716-2.574 1.3zm-7.74.872-.608.464v.001l.054.003a3.35 3.35 0 0 0 .554-.468zm1.583-.426c0-.536-.237-.929-.594-1.217a3.178 3.178 0 0 1-.165.825.393.393 0 0 1-.328.681c-.154.233-.34.445-.549.63l.661.034-.995.237c-.025.018-.045.041-.07.058a3.194 3.194 0 0 1 1.536.691c.32-.574.504-1.235.504-1.94zM10.99 7.996a3.5 3.5 0 0 0-.785.46.427.427 0 0 1-.013.357l.885.643.023-.016-.36-1.262.627 1.12c.018-.006.04-.006.058-.011l-.02-1.251.398 1.163.477-1.15.016 1.268c.004.001.007.005.012.007l.713-1.005-.363 1.218.009.01 1.04-.69-.759 1.05.002.005.95-.34c.012-.016.028-.029.041-.045a.395.395 0 0 1 .394-.632 3.43 3.43 0 0 0 .27-.784 13.99 13.99 0 0 0-2.798-.168c-.286.011-.55.033-.817.053Z', hex: '#1287B1' }, + firestore: { d: 'M19.455 8.369c-.538-.748-1.778-2.285-3.681-4.569-.826-.991-1.535-1.832-1.884-2.245a146 146 0 0 0-.488-.576l-.207-.245-.113-.133-.022-.032-.01-.005L12.57 0l-.609.488c-1.555 1.246-2.828 2.851-3.681 4.64-.523 1.064-.864 2.105-1.043 3.176-.047.241-.088.489-.121.738-.209-.017-.421-.028-.632-.033-.018-.001-.035-.002-.059-.003a7.46 7.46 0 0 0-2.28.274l-.317.089-.163.286c-.765 1.342-1.198 2.869-1.252 4.416-.07 2.01.477 3.954 1.583 5.625 1.082 1.633 2.61 2.882 4.42 3.611l.236.095.071.025.003-.001a9.59 9.59 0 0 0 2.941.568q.171.006.342.006c1.273 0 2.513-.249 3.69-.742l.008.004.313-.145a9.63 9.63 0 0 0 3.927-3.335c1.01-1.49 1.577-3.234 1.641-5.042.075-2.161-.643-4.304-2.133-6.371m-7.083 6.695c.328 1.244.264 2.44-.191 3.558-1.135-1.12-1.967-2.352-2.475-3.665-.543-1.404-.87-2.74-.974-3.975.48.157.922.366 1.315.622 1.132.737 1.914 1.902 2.325 3.461zm.207 6.022c.482.368.99.712 1.513 1.028-.771.21-1.565.302-2.369.273a8 8 0 0 1-.373-.022c.458-.394.869-.823 1.228-1.279zm1.347-6.431c-.516-1.957-1.527-3.437-3.002-4.398-.647-.421-1.385-.741-2.194-.95.011-.134.026-.268.043-.4.014-.113.03-.216.046-.313.133-.689.332-1.37.589-2.025.099-.25.206-.499.321-.74l.004-.008c.177-.358.376-.719.61-1.105l.092-.152-.003-.001c.544-.851 1.197-1.627 1.942-2.311l.288.341c.672.796 1.304 1.548 1.878 2.237 1.291 1.549 2.966 3.583 3.612 4.48 1.277 1.771 1.893 3.579 1.83 5.375-.049 1.395-.461 2.755-1.195 3.933-.694 1.116-1.661 2.05-2.8 2.708-.636-.318-1.559-.839-2.539-1.599.79-1.575.952-3.28.479-5.072zm-2.575 5.397c-.725.939-1.587 1.55-2.09 1.856-.081-.029-.163-.06-.243-.093l-.065-.026c-1.49-.616-2.747-1.656-3.635-3.01-.907-1.384-1.356-2.993-1.298-4.653.041-1.19.338-2.327.882-3.379.316-.07.638-.114.96-.131l.084-.002c.162-.003.324-.003.478 0 .227.011.454.035.677.07.073 1.513.445 3.145 1.105 4.852.637 1.644 1.694 3.162 3.144 4.515z', hex: '#FFA000' }, + oracle: { d: 'M16.412 4.412h-8.82a7.588 7.588 0 0 0-.008 15.176h8.828a7.588 7.588 0 0 0 0-15.176zm-.193 12.502H7.786a4.915 4.915 0 0 1 0-9.828h8.433a4.914 4.914 0 1 1 0 9.828z', hex: '#C74634' }, valkey: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#6983FF' }, } From b6e21468b9159d9cfd5280796803a3441038b6cc Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:35:42 +0545 Subject: [PATCH 020/317] feat(connect): paste any connection string (#155) cleanPastedConnection strips .env wrappers and quotes; detectConnectionUri drops ORM driver suffixes, converts libpq and ADO.NET key/value strings to URLs, adds valkey/couchdb/cassandra/mysqlx/pg aliases and HTTP endpoints (Turso, ClickHouse, CouchDB by host or port), and TiDB Cloud, Upstash, Nile and Railway hosts. Redis and libSQL now go through their own parsers (they were parsed as Postgres). New parseCouchUri and parseCassandraUri fill those forms. --- .changeset/paste-any-connection.md | 5 + src/lib/components/ConnectionModal.svelte | 27 +++- src/lib/connection-uri.js | 167 +++++++++++++++++++++- src/lib/connection-uri.test.js | 45 ++++++ 4 files changed, 235 insertions(+), 9 deletions(-) create mode 100644 .changeset/paste-any-connection.md diff --git a/.changeset/paste-any-connection.md b/.changeset/paste-any-connection.md new file mode 100644 index 00000000..753877cc --- /dev/null +++ b/.changeset/paste-any-connection.md @@ -0,0 +1,5 @@ +### Features +- Paste any connection string to connect: whole .env lines (DATABASE_URL="…"), SQLAlchemy/ORM URLs (postgresql+psycopg2://), libpq key/value (host=… dbname=…), ADO.NET SQL Server strings (Server=…;Database=…;), valkey://, couchdb://, cassandra://, mysqlx://, Turso https:// and ClickHouse http:// endpoints, and TiDB Cloud, Upstash, Nile and Railway hosts + +### Bug Fixes +- A pasted redis:// or libsql:// URL fills the Redis or LibSQL form correctly instead of being read as a Postgres URL diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 8d444598..4a4dab1c 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -661,7 +661,7 @@ // A string for another engine switches the engine too - refusing it and // making the user go and change the dropdown first would be pedantry. if (hit && hit.type !== dbType && !DISABLED_TABS.has(hit.type)) switchDriver(hit.type); - const ok = applyConnectionUriFrom(raw, hit?.uriType ?? uriTypeFor(dbType)); + const ok = applyConnectionUriFrom(hit?.uri ?? raw, hit?.uriType ?? uriTypeFor(dbType)); if (ok) { importUri = ""; // Left open would mean an empty bar sitting over the fields it just @@ -726,7 +726,7 @@ if (!raw) return; const hit = detectConnectionUri(raw); if (!hit) { - quickHint = "That does not look like a connection string. Try postgres://…, mysql://…, or a path to a .db file."; + quickHint = "That does not look like a connection string. Paste a URL (postgres://, mysql://, sqlserver://, oracle://, mongodb://, redis://, libsql://, …), a .env line, host=… dbname=…, or a path to a .db file."; return; } if (DISABLED_TABS.has(hit.type)) { @@ -744,7 +744,9 @@ const known = ALL_DRIVERS.find((d) => d.id === hit.provider); quickHint = `Recognised a ${known?.label ?? PROVIDER_LABELS[hit.provider] ?? hit.provider} endpoint.`; } - const ok = applyConnectionUriFrom(raw, hit.uriType); + // `hit.uri`: the string with its .env wrapper or driver suffix taken off, + // or a key/value string turned into a URL. + const ok = applyConnectionUriFrom(hit.uri ?? raw, hit.uriType); if (!ok && !quickHint) quickHint = "Could not read that string."; quickUri = ""; // Used. Coming back to the picker should not hand it over again. @@ -1448,6 +1450,25 @@ uriHint = "Fields updated from URL"; return true; } + // CouchDB: the server URL, the login in its own fields. + if ("couch" in parsed) { + couchUrl = parsed.url; + if (parsed.user) user = parsed.user; + if (parsed.password) password = parsed.password; + flashFields(["user", "password"]); + uriHint = "Fields updated from URL"; + return true; + } + // Cassandra / ScyllaDB: contact points, login, keyspace. + if ("cql" in parsed) { + cqlHosts = parsed.hosts; + cqlKeyspace = parsed.keyspace; + if (parsed.user) user = parsed.user; + if (parsed.password) password = parsed.password; + flashFields(["user", "password"]); + uriHint = "Fields updated from URL"; + return true; + } // Oracle: host + service or SID, or a descriptor kept whole. if ("oracle" in parsed) { host = parsed.host || host; diff --git a/src/lib/connection-uri.js b/src/lib/connection-uri.js index 4af768eb..0242de13 100644 --- a/src/lib/connection-uri.js +++ b/src/lib/connection-uri.js @@ -328,6 +328,8 @@ export function parseOracleUri(uri) { * @returns {ParsedPostgresUri | ParsedSqliteUri | Record | { error: string } | null} */ export function parseConnectionUri(type, uri) { + if (type === 'couchdb') return parseCouchUri(uri) + if (type === 'cassandra') return parseCassandraUri(uri) if (type === 'sqlite') return parseSqliteUri(uri) if (type === 'mysql') return parseMysqlUri(uri) if (type === 'mssql') return parseMssqlUri(uri) @@ -356,11 +358,95 @@ export function parseConnectionUri(type, uri) { * @returns {{ type: string, provider?: string, uriType: 'postgres'|'sqlite'|'mysql'|'mssql'|'clickhouse'|'oracle' } | null} */ export function detectConnectionUri(uri) { - const s = unquotePath(String(uri ?? '')) + const s = cleanPastedConnection(String(uri ?? '')) if (!s) return null + const hit = detectClean(s) + if (!hit) return null + // `uri`: the string to hand the parser, when it isn't what was pasted - the + // .env wrapper, driver suffix or key/value form turned into a plain URL. + const plain = hit.uri ?? s + const { uri: _drop, ...rest } = hit + return plain !== String(uri ?? '').trim() ? { ...rest, uri: plain } : rest +} + +/** + * What people paste is rarely just the URL: a `.env` line (`DATABASE_URL="…"`, + * `export REDIS_URL=…`), a quoted value, a trailing semicolon. Keep the value. + * @param {string} raw + */ +export function cleanPastedConnection(raw) { + let s = String(raw ?? '').trim() + s = s.replace(/^export\s+/i, '') + // KEY=value or KEY: value, when the key is an identifier and the value + // starts like a connection string (not `host=… dbname=…` key/value text). + const kv = /^([A-Za-z_][A-Za-z0-9_]*)\s*[=:]\s*(.+)$/s.exec(s) + if (kv && /^["'`]?[a-z][a-z0-9+.-]*:\/\//i.test(kv[2].trim())) s = kv[2].trim() + s = s.replace(/;\s*$/, '').trim() + return unquotePath(s) +} + +/** + * A libpq key/value string (`host=db port=5432 dbname=app user=me`) as a URL. + * @param {string} s + */ +function libpqToUrl(s) { + /** @type {Record} */ + const o = {} + for (const m of s.matchAll(/(\w+)\s*=\s*('(?:[^'\\]|\\.)*'|\S+)/g)) o[m[1].toLowerCase()] = m[2].replace(/^'|'$/g, '').replace(/\\(.)/g, '$1') + if (!o.host && !o.dbname) return null + const enc = encodeURIComponent + const auth = o.user ? `${enc(o.user)}${o.password ? `:${enc(o.password)}` : ''}@` : '' + const q = o.sslmode ? `?sslmode=${enc(o.sslmode)}` : '' + return `postgresql://${auth}${o.host || 'localhost'}${o.port ? `:${o.port}` : ''}/${enc(o.dbname || '')}${q}` +} - const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(s)?.[1]?.toLowerCase() ?? '' +/** + * An ADO.NET string (`Server=tcp:host,1433;Database=app;User Id=sa;Password=…;`) + * in the semicolon form the SQL Server parser reads. + * @param {string} s + */ +function adoNetToUrl(s) { + /** @type {Record} */ + const o = {} + for (const part of s.split(';')) { + const i = part.indexOf('=') + if (i > 0) o[part.slice(0, i).trim().toLowerCase().replace(/\s+/g, ' ')] = part.slice(i + 1).trim() + } + const server = o.server ?? o['data source'] ?? o.address ?? o.addr + if (!server) return null + const [hostPart, portPart] = server.replace(/^tcp:/i, '').split(',') + const user = o['user id'] ?? o.uid ?? o.user ?? '' + const password = o.password ?? o.pwd ?? '' + const db = o.database ?? o['initial catalog'] ?? '' + const params = [db && `database=${db}`, user && `user=${user}`, password && `password=${password}`, + o.encrypt && `encrypt=${o.encrypt}`, o.trustservercertificate && `trustServerCertificate=${o.trustservercertificate}`].filter(Boolean) + return `sqlserver://${hostPart.trim()}${portPart ? `:${portPart.trim()}` : ''};${params.join(';')}` +} + +/** @param {string} s @returns {{ type: string, provider?: string, uriType: string, uri?: string } | null} */ +function detectClean(s) { + // Key/value forms first: no scheme to go by. + if (!/^[a-z][a-z0-9+.-]*:/i.test(s) || /^(server|data source)\s*=/i.test(s)) { + if (/(^|;)\s*(server|data source|address)\s*=/i.test(s) && s.includes(';')) { + const url = adoNetToUrl(s) + if (url) return { type: 'mssql', uriType: 'mssql', uri: url } + } + if (/\b(host|dbname)\s*=/i.test(s) && !s.includes(';')) { + const url = libpqToUrl(s) + if (url) return { type: 'postgres', uriType: 'postgres', uri: url } + } + } + + let scheme = /^([a-z][a-z0-9+.-]*):/i.exec(s)?.[1]?.toLowerCase() ?? '' + // SQLAlchemy / ORM driver suffixes: `postgresql+psycopg2://`, `mysql+pymysql://`. + // Not `mongodb+srv` (a real scheme) or `prisma+postgres` (a provider's). + if (scheme.includes('+') && scheme !== 'mongodb+srv' && scheme !== 'prisma+postgres') { + const base = scheme.split('+')[0] + const inner = detectClean(base + s.slice(scheme.length)) + return inner ? { ...inner, uri: inner.uri ?? base + s.slice(scheme.length) } : null + } const host = hostOf(s) + const port = Number(/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?[^/:?#]+:(\d+)/i.exec(s)?.[1] ?? 0) // Providers first: a Neon or Supabase string is a Postgres string, and saying // so lets the caller offer the account flow rather than a bare host/port form. @@ -375,8 +461,20 @@ export function detectConnectionUri(uri) { if (/\.psdb\.cloud$/i.test(host) || /\.planetscale\.(com|sh)$/i.test(host)) { return { type: 'mysql', provider: 'planetscale', uriType: 'mysql' } } - if (/\.turso\.io$/i.test(host)) return { type: 'libsql', provider: 'turso', uriType: 'postgres' } + if (/\.turso\.io$/i.test(host)) return { type: 'libsql', provider: 'turso', uriType: 'libsql' } + if (/\.tidbcloud\.com$/i.test(host)) return { type: 'mysql', provider: 'tidb', uriType: 'mysql' } + if (/\.upstash\.io$/i.test(host) && /^rediss?$/.test(scheme)) return { type: 'redis', provider: 'upstash', uriType: 'redis' } + if (/\.thenile\.dev$/i.test(host)) return { type: 'postgres', provider: 'nile', uriType: 'postgres' } + if (/\.(rlwy\.net|railway\.app|railway\.internal)$/i.test(host)) { + const inner = detectByScheme(scheme, s, host, port) + if (inner) return { ...inner, provider: 'railway' } + } } + return detectByScheme(scheme, s, host, port) +} + +/** @param {string} scheme @param {string} s @param {string} host @param {number} port */ +function detectByScheme(scheme, s, host, port) { switch (scheme) { case 'postgres': @@ -385,7 +483,8 @@ export function detectConnectionUri(uri) { case 'cockroachdb': return { type: 'cockroachdb', uriType: 'postgres' } case 'mysql': - return { type: 'mysql', uriType: 'mysql' } + case 'mysqlx': + return { type: 'mysql', uriType: 'mysql', uri: scheme === 'mysqlx' ? 'mysql' + s.slice(6) : undefined } case 'mariadb': return { type: 'mariadb', uriType: 'mysql' } case 'sqlserver': @@ -399,11 +498,35 @@ export function detectConnectionUri(uri) { case 'mongodb': case 'mongodb+srv': return { type: 'mongodb', uriType: 'mongodb' } + case 'postgis': + case 'timescale': + case 'pgsql': + case 'pg': + return { type: 'postgres', uriType: 'postgres', uri: 'postgresql' + s.slice(scheme.length) } case 'redis': case 'rediss': - return { type: 'redis', uriType: 'postgres' } + return { type: 'redis', uriType: 'redis' } + case 'valkey': + case 'valkeys': + return { type: 'valkey', uriType: 'redis', uri: (scheme === 'valkeys' ? 'rediss' : 'redis') + s.slice(scheme.length) } case 'libsql': - return { type: 'libsql', uriType: 'postgres' } + return { type: 'libsql', uriType: 'libsql' } + case 'couchdb': + case 'couchdbs': + return { type: 'couchdb', uriType: 'couchdb', uri: (scheme === 'couchdbs' ? 'https' : 'http') + s.slice(scheme.length) } + case 'cassandra': + case 'scylla': + case 'cql': + return { type: 'cassandra', uriType: 'cassandra' } + case 'http': + case 'https': + case 'ws': + case 'wss': + // An HTTP endpoint says what it is by its host or its port. + if (/\.turso\.io$/i.test(host) || scheme.startsWith('ws')) return { type: 'libsql', uriType: 'libsql' } + if (/clickhouse/i.test(host) || port === 8123 || port === 8443) return { type: 'clickhouse', uriType: 'clickhouse' } + if (/couch|cloudant/i.test(host) || port === 5984) return { type: 'couchdb', uriType: 'couchdb' } + return null case 'duckdb': return { type: 'duckdb', uriType: 'sqlite' } case 'sqlite': @@ -501,3 +624,35 @@ export function parseLibsqlUri(uri) { // `toString()` re-appends a bare `?` once the params are gone. return { url: url.toString().replace(/\?$/, ''), authToken: token } } + +/** + * CouchDB's server URL, with the login moved to its own fields. + * @param {string} uri + * @returns {{ couch: true, url: string, user: string, password: string } | { error: string } | null} + */ +export function parseCouchUri(uri) { + const t = uri.trim().replace(/^couchdbs:/i, 'https:').replace(/^couchdb:/i, 'http:') + if (!t) return null + let u + try { + u = new URL(escapeUserinfo(t)) + } catch { + return { error: 'Could not read that CouchDB URL' } + } + const user = decodePart(u.username) + const password = decodePart(u.password) + u.username = '' + u.password = '' + return { couch: true, url: u.toString().replace(/\/$/, ''), user, password } +} + +/** + * `cassandra://user:pass@h1:9042,h2:9042/keyspace` into the CQL form's fields. + * @param {string} uri + * @returns {{ cql: true, hosts: string, user: string, password: string, keyspace: string } | { error: string } | null} + */ +export function parseCassandraUri(uri) { + const m = /^[a-z]+:\/\/(?:([^:@/]*)(?::([^@/]*))?@)?([^/?#]+)(?:\/([^?#]*))?/i.exec(uri.trim()) + if (!m) return { error: 'Expected cassandra://host:9042/keyspace' } + return { cql: true, user: decodePart(m[1] ?? ''), password: decodePart(m[2] ?? ''), hosts: m[3], keyspace: decodePart(m[4] ?? '') } +} diff --git a/src/lib/connection-uri.test.js b/src/lib/connection-uri.test.js index 846ea4f9..4510ca74 100644 --- a/src/lib/connection-uri.test.js +++ b/src/lib/connection-uri.test.js @@ -242,3 +242,48 @@ describe('Oracle connection strings', () => { expect(detectConnectionUri('jdbc:oracle:thin:@//h:1521/svc')).toEqual({ type: 'oracle', uriType: 'oracle' }) }) }) + +describe('detectConnectionUri: everything people paste', () => { + const d = (s) => detectConnectionUri(s) + it('takes the value out of a .env line', () => { + expect(d('DATABASE_URL="postgresql://u:p@db:5432/app"')).toMatchObject({ type: 'postgres', uri: 'postgresql://u:p@db:5432/app' }) + expect(d("export REDIS_URL='rediss://:pw@x.upstash.io:6379'")).toMatchObject({ type: 'redis', provider: 'upstash', uriType: 'redis' }) + }) + it('drops ORM driver suffixes', () => { + expect(d('postgresql+psycopg2://u:p@h/db')).toMatchObject({ type: 'postgres', uri: 'postgresql://u:p@h/db' }) + expect(d('mysql+pymysql://u:p@h/db')).toMatchObject({ type: 'mysql', uri: 'mysql://u:p@h/db' }) + expect(d('mongodb+srv://u:p@c.mongodb.net/app')).toMatchObject({ type: 'mongodb' }) + }) + it('parses Redis, Valkey and libSQL with their own parsers, not Postgres', () => { + expect(d('redis://:pw@h:6379/2')).toMatchObject({ type: 'redis', uriType: 'redis' }) + expect(d('valkey://h:6379')).toMatchObject({ type: 'valkey', uriType: 'redis', uri: 'redis://h:6379' }) + expect(d('libsql://db-org.turso.io?authToken=x')).toMatchObject({ type: 'libsql', uriType: 'libsql' }) + expect(d('https://db-org.turso.io')).toMatchObject({ type: 'libsql' }) + }) + it('reads key/value strings', () => { + const pg = d("host=db.example.com port=5433 dbname=shop user=me password='p w' sslmode=require") + expect(pg).toMatchObject({ type: 'postgres' }) + expect(parseConnectionUri('postgres', pg.uri)).toMatchObject({ host: 'db.example.com', port: '5433', database: 'shop', user: 'me', password: 'p w' }) + const ms = d('Server=tcp:sql.example.com,1433;Database=app;User Id=sa;Password=Secret1!;Encrypt=True;') + expect(ms).toMatchObject({ type: 'mssql' }) + expect(parseConnectionUri('mssql', ms.uri)).toMatchObject({ host: 'sql.example.com', port: '1433', database: 'app', user: 'sa', password: 'Secret1!' }) + }) + it('knows the NoSQL and HTTP endpoints', () => { + expect(d('couchdb://admin:pw@localhost:5984')).toMatchObject({ type: 'couchdb' }) + expect(parseConnectionUri('couchdb', 'http://admin:pw@localhost:5984')).toEqual({ couch: true, url: 'http://localhost:5984', user: 'admin', password: 'pw' }) + expect(d('cassandra://u:p@h1:9042,h2:9042/shop')).toMatchObject({ type: 'cassandra' }) + expect(parseConnectionUri('cassandra', 'cassandra://u:p@h1:9042,h2:9042/shop')).toEqual({ cql: true, user: 'u', password: 'p', hosts: 'h1:9042,h2:9042', keyspace: 'shop' }) + expect(d('http://localhost:8123')).toMatchObject({ type: 'clickhouse' }) + expect(d('https://example.com')).toBeNull() + }) + it('recognises cloud hosts', () => { + expect(d('mysql://u:p@gateway01.ap-northeast-1.prod.aws.tidbcloud.com:4000/test')).toMatchObject({ type: 'mysql', provider: 'tidb' }) + expect(d('postgres://u:p@eu-central-1.db.thenile.dev/db')).toMatchObject({ provider: 'nile' }) + expect(d('postgresql://u:p@monorail.proxy.rlwy.net:5432/railway')).toMatchObject({ type: 'postgres', provider: 'railway' }) + expect(d('jdbc:sqlserver://h:1433;databaseName=x')).toMatchObject({ type: 'mssql' }) + expect(d('jdbc:oracle:thin:@//h:1521/FREEPDB1')).toMatchObject({ type: 'oracle' }) + }) + it('still says no to junk', () => { + expect(d('adsf')).toBeNull() + }) +}) From ea87d66f84db4fa8a3c853a304135314071c7a75 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:35:47 +0545 Subject: [PATCH 021/317] fix(connect): title row for the panel's buttons; full-width layout (#156) The show-connections toggle and Close were absolutely positioned (top-3, left-[88px]) and drifted off the traffic lights' line. They now sit in a title row: 52pt with the 92px lights inset on macOS, 40px elsewhere, which is also the drag region. The step header, the picker, the form and the footer drop the centred max-w-3xl/44rem column for a left-aligned max-w-6xl at px-10. --- .changeset/connect-screen-layout.md | 3 + src/lib/components/ConnectionModal.svelte | 69 ++++++++++++----------- 2 files changed, 40 insertions(+), 32 deletions(-) create mode 100644 .changeset/connect-screen-layout.md diff --git a/.changeset/connect-screen-layout.md b/.changeset/connect-screen-layout.md new file mode 100644 index 00000000..ac4cea0d --- /dev/null +++ b/.changeset/connect-screen-layout.md @@ -0,0 +1,3 @@ +### Bug Fixes +- Connection screen: the show-connections and close buttons sit in a title row on the traffic lights' line on macOS (and in a 40px row on Windows and Linux), instead of floating at an offset +- Connection screen uses the window's width, left-aligned with the connections list, instead of a narrow centred column diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 4a4dab1c..06dcf6e2 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -3535,25 +3535,41 @@
- {#if !railOpen} - + +
+ {#if !railOpen} + + {/if} + + - {/if} +
@@ -3580,12 +3596,12 @@
{#if step === "pick"} -
+

@@ -3729,7 +3745,7 @@ starts somewhere neither of them does. One leading edge. --> -
+
-
+
-
-
+
+
- {#snippet secLabel(/** @type {string} */ text)} {#if !searching} +

{text}

-
{/if} {/snippet} @@ -1566,15 +1573,35 @@ {#if show($t('settings.aiModels'), $t('settings.aiModels.desc'))} {@render actionRow($t('settings.aiModels'), $t('settings.aiModels.desc'), $t('settings.btn.configure'), openModelConfiguration)} {/if} +{/snippet} + +{#snippet accountContent()} {@render secLabel($t('settings.sec.account'))} - {#if show('Account', 'Sign in with GitHub or Google, plan, devices, sign out')} {/if} {#if show($t('settings.license'), $t('settings.license.desc'))} {@render actionRow($t('settings.license'), $t('settings.license.desc'), $t('settings.btn.manage'), () => { open = false; onopenlicense(); }, planBadge)} {/if} + {#if show('Sync', 'End-to-end encrypted sync of connections, workspaces and settings across your devices')} + {#if $isSignedIn} +
+ +
+ {:else} + {@render secLabel('Sync')} +
+
+

Sync your connections

+

Sign in to keep connections, workspaces and settings on all your devices. They are encrypted on this device with a passphrase only you know, so no one else can read them, Stroke included.

+
+ +
+ {/if} + {/if} {/snippet} {#snippet aboutContent()} @@ -1595,8 +1622,7 @@ {/if} {#if !searching} -

{$t('settings.sec.keyboard')}

-
+

{$t('settings.sec.keyboard')}

{#if bindingFor('theme.next')}{@render shortcut(bindingFor('theme.next'), $t('settings.kbd.cycleTheme'))}{/if} {#if bindingFor('theme.prev')}{@render shortcut(bindingFor('theme.prev'), $t('settings.kbd.prevTheme'))}{/if} diff --git a/src/lib/i18n.js b/src/lib/i18n.js index 3ead232e..80c43729 100644 --- a/src/lib/i18n.js +++ b/src/lib/i18n.js @@ -57,6 +57,7 @@ const DICT = { 'settings.nav.appearance': 'Appearance', 'settings.nav.agent': 'Agent', 'settings.nav.integrations': 'Integrations', + 'settings.nav.account': 'Account & Sync', 'settings.nav.keybindings': 'Keybindings', 'settings.nav.about': 'About', 'settings.sec.dataView': 'Data view', @@ -214,6 +215,7 @@ const DICT = { 'settings.nav.appearance': 'Apariencia', 'settings.nav.agent': 'Agente', 'settings.nav.integrations': 'Integraciones', + 'settings.nav.account': 'Cuenta y sincronización', 'settings.nav.keybindings': 'Atajos de teclado', 'settings.nav.about': 'Acerca de', 'settings.sec.dataView': 'Vista de datos', @@ -368,6 +370,7 @@ const DICT = { 'settings.nav.database': 'Base de données', 'settings.nav.appearance': 'Apparence', 'settings.nav.integrations': 'Intégrations', + 'settings.nav.account': 'Compte et synchro', 'settings.nav.keybindings': 'Raccourcis clavier', 'settings.nav.about': 'À propos', 'settings.sec.dataView': 'Vue de données', @@ -522,6 +525,7 @@ const DICT = { 'settings.nav.database': 'Datenbank', 'settings.nav.appearance': 'Darstellung', 'settings.nav.integrations': 'Integrationen', + 'settings.nav.account': 'Konto & Sync', 'settings.nav.keybindings': 'Tastenkürzel', 'settings.nav.about': 'Info', 'settings.sec.dataView': 'Datenansicht', diff --git a/src/lib/stores/account.js b/src/lib/stores/account.js index 5ad3b761..80210b1b 100644 --- a/src/lib/stores/account.js +++ b/src/lib/stores/account.js @@ -256,8 +256,8 @@ async function maybePromptKeyHolder() { return } const { toast } = await import('$lib/components/ui/sonner/toast.svelte.js') - toast.info('Stroke now has accounts', { - description: 'Sign in to sync your connections; your license comes with you.', + toast.info('Sign in to sync your connections', { + description: 'Your connections, workspaces and settings, on every device, end-to-end encrypted: no one else can read them, Stroke included. Your license comes with you.', duration: 20000, action: { label: 'Sign in', onClick: () => void signInWithToast() }, }) From 577edca285f6cff0967cc1884c385ba48dacfcfe Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:36:14 +0545 Subject: [PATCH 025/317] fix(license): seat-limit message points at removing a device or asking for more (#158) --- .changeset/seat-limit-message.md | 2 ++ src-tauri/src/commands.rs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 .changeset/seat-limit-message.md diff --git a/.changeset/seat-limit-message.md b/.changeset/seat-limit-message.md new file mode 100644 index 00000000..ace3cf3d --- /dev/null +++ b/.changeset/seat-limit-message.md @@ -0,0 +1,2 @@ +### Bug Fixes +- When a license is on all the devices it covers, the message says where to free one or ask for more devices (stroke.click/app) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index b891d38f..abfe730d 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1798,7 +1798,7 @@ pub async fn activate_license( Err(e) => { // Convert server error codes to user-friendly messages let msg = match e.as_str() { - "seat_limit_exceeded" => "Seat limit reached. Deactivate another device first.", + "seat_limit_exceeded" => "This license is on all the devices it covers. Remove one at stroke.click/app, or ask for more devices there (\"Need more devices?\").", "revoked" => "This license key has been revoked.", "expired" => "This license key has expired.", "not_found" => "License key not found.", From b364058aed9b9bd353321b47df9cb6ce5ddfd640 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:36:18 +0545 Subject: [PATCH 026/317] fix(scroll): Shift + wheel scrolls sideways in every scroll area (#159) lib/shift-wheel.js: while Shift is held (the non-passive listener is only attached then), a vertical wheel the page did not already handle scrolls the nearest overflow-x auto/scroll ancestor under the pointer. Whether the webview converts Shift+wheel itself depends on OS, webview and mouse. DataTable: over the FK sub-view the grid never takes Shift+wheel; it used to scroll the grid behind the panel whenever the panel did not overflow. --- .changeset/shift-wheel.md | 3 ++ src/App.svelte | 3 ++ src/lib/components/DataTable.svelte | 11 +++-- src/lib/shift-wheel.js | 73 +++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 .changeset/shift-wheel.md create mode 100644 src/lib/shift-wheel.js diff --git a/.changeset/shift-wheel.md b/.changeset/shift-wheel.md new file mode 100644 index 00000000..f3bdc282 --- /dev/null +++ b/.changeset/shift-wheel.md @@ -0,0 +1,3 @@ +### Bug Fixes +- Shift + mouse wheel scrolls sideways everywhere: the related-rows panel, query results, settings and every other wide area, not only the data grid +- Shift + wheel over the related-rows panel no longer scrolls the grid behind it diff --git a/src/App.svelte b/src/App.svelte index d2178f04..54fcfbb7 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -12,11 +12,14 @@ import { loadSettings, applySettings, installZoomShortcuts } from '$lib/stores/settings.js' import { installPlatformClass } from '$lib/platform.js' import { installClipboardBridge } from '$lib/clipboard.js' + import { installShiftWheel } from '$lib/shift-wheel.js' onMount(async () => { installPlatformClass() applySettings(loadSettings()) installZoomShortcuts() + // Shift + wheel scrolls sideways in every scroll area, whatever the webview does. + installShiftWheel() // Route clipboard through Tauri's native plugin so copy works in the WKWebview // (navigator.clipboard is denied there, incl. Monaco's internal copy). void installClipboardBridge() diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index c55b1cdc..bdaf21f8 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -7620,9 +7620,14 @@ import FilterX from "@lucide/svelte/icons/filter-x"; const { dx, dy } = wheelPixels(e, el.clientWidth) const delta = dy || dx // shift + vertical wheel IS horizontal movement if (!delta) return - if (inner && inner !== el && inner.scrollWidth > inner.clientWidth) { - e.preventDefault() - inner.scrollLeft += delta + // Over the panel the grid behind it never moves: scrolling something + // you can't see was what Shift+wheel did there whenever the panel + // itself was not wider than its box. + if (inner && inner !== el) { + if (inner.scrollWidth > inner.clientWidth) { + e.preventDefault() + inner.scrollLeft += delta + } return } e.preventDefault() diff --git a/src/lib/shift-wheel.js b/src/lib/shift-wheel.js new file mode 100644 index 00000000..cb11da09 --- /dev/null +++ b/src/lib/shift-wheel.js @@ -0,0 +1,73 @@ +/** + * Shift + wheel scrolls sideways, everywhere. + * + * Whether a webview turns a vertical wheel with Shift held into horizontal + * scrolling depends on the OS, the webview and the mouse, so a wide result, + * the related-rows panel or a settings table could only be scrolled sideways by + * dragging its scrollbar. This does the conversion when nothing else did: the + * nearest element under the pointer that can scroll sideways moves. + * + * The listener is non-passive (it has to preventDefault), and a non-passive + * wheel listener puts the main thread in front of every wheel tick. So it is + * attached only while Shift is held, the way the grid gates its own. + */ + +/** A "line" of wheel delta (deltaMode 1). */ +const LINE_PX = 16 + +/** + * The element to move: the nearest ancestor of `target` that overflows + * sideways and lets the user scroll it (overflow-x auto or scroll). + * @param {EventTarget | null} target + * @returns {HTMLElement | null} + */ +export function horizontalScroller(target) { + let el = target instanceof Element ? target : null + while (el && el !== document.documentElement) { + if (el instanceof HTMLElement && el.scrollWidth > el.clientWidth + 1) { + const ox = getComputedStyle(el).overflowX + if (ox === 'auto' || ox === 'scroll') return el + } + el = el.parentElement + } + return null +} + +/** @param {WheelEvent} e */ +function onWheel(e) { + // Something already handled it (the data grid has its own Shift handling), + // or the device already sent sideways movement. + if (e.defaultPrevented || !e.shiftKey || e.ctrlKey || e.metaKey || e.deltaX !== 0 || e.deltaY === 0) return + const el = horizontalScroller(e.target) + if (!el) return + const scale = e.deltaMode === 1 ? LINE_PX : e.deltaMode === 2 ? el.clientWidth : 1 + e.preventDefault() + el.scrollLeft += e.deltaY * scale +} + +let attached = false +function attach() { + if (attached) return + attached = true + window.addEventListener('wheel', onWheel, { passive: false }) +} +function detach() { + if (!attached) return + attached = false + window.removeEventListener('wheel', onWheel) +} + +/** Install once at startup. Returns the uninstaller. */ +export function installShiftWheel() { + /** @param {KeyboardEvent} e */ + const onKey = (e) => (e.shiftKey ? attach() : detach()) + window.addEventListener('keydown', onKey, true) + window.addEventListener('keyup', onKey, true) + window.addEventListener('blur', detach) + return () => { + detach() + window.removeEventListener('keydown', onKey, true) + window.removeEventListener('keyup', onKey, true) + window.removeEventListener('blur', detach) + } +} From 80e51415f272b0b09c2c92131be7e9071044486e Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:36:23 +0545 Subject: [PATCH 027/317] fix(ai): watchdog for local-agent tool calls that never answer (#160) A step whose MCP call never returned (four schema reads against a slow TiDB) spun forever with 'Working for 30s'. While steps are running and no agent event has arrived for 30s, the status line names what it is waiting on; at 3 minutes the stuck steps are marked failed, the agent is interrupted and the turn ends with the reason. --- .changeset/ai-stalled-tools.md | 2 ++ src/lib/components/AiChat.svelte | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 .changeset/ai-stalled-tools.md diff --git a/.changeset/ai-stalled-tools.md b/.changeset/ai-stalled-tools.md new file mode 100644 index 00000000..cca70d53 --- /dev/null +++ b/.changeset/ai-stalled-tools.md @@ -0,0 +1,2 @@ +### Bug Fixes +- AI chat with a local agent no longer spins forever when a tool never answers: after 30 seconds it says which step it is waiting on, and after 3 minutes it stops the agent and ends the turn with the reason diff --git a/src/lib/components/AiChat.svelte b/src/lib/components/AiChat.svelte index 71a41b6f..a8670e08 100644 --- a/src/lib/components/AiChat.svelte +++ b/src/lib/components/AiChat.svelte @@ -2738,7 +2738,36 @@ }; await new Promise((resolve, reject) => { + // A tool that never answers (the database stalls, or the MCP server + // stops responding) used to leave the steps spinning forever with no + // word about why. Say which step it is waiting on after 30s; after 3 + // minutes interrupt the agent and end the turn with the reason. + let lastEventAt = Date.now(); + const runningSteps = () => [...tools.entries()].filter(([id, t]) => + items.some((i) => i.id === t.workId && i.kind === "work" && /** @type {any} */ (i).steps.some((/** @type {WorkStep} */ s) => s.id === String(id) && s.status === "running"))); + const watchdog = setInterval(() => { + const quiet = Date.now() - lastEventAt; + const waiting = runningSteps(); + if (!waiting.length) return; + const what = waiting.length === 1 ? (waiting[0][1].detail || waiting[0][1].name.replace(/_/g, " ")) : `${waiting.length} steps`; + if (quiet >= 180_000) { + for (const [id, t] of waiting) { + patchWork(t.workId, (w) => ({ + ...w, + steps: w.steps.map((/** @type {WorkStep} */ st) => (st.id === String(id) ? { ...st, status: "error", error: "No answer in 3 minutes." } : st)), + })); + } + void agentInterrupt(key).catch(() => {}); + error = `No answer from ${what} in 3 minutes. The database may be busy or unreachable; check Logs, then try again.`; + closeText(); + closeWork(); + settle(null); + } else if (quiet >= 30_000) { + aiStatusHint = `Still waiting on ${what}… Stop ends it.`; + } + }, 5_000); const settle = (/** @type {Error | null} */ err) => { + clearInterval(watchdog); agentOnEvent = null; agentSettle = null; if (err) reject(err); @@ -2746,6 +2775,8 @@ }; agentSettle = () => settle(null); agentOnEvent = (ev) => { + lastEventAt = Date.now(); + if (aiStatusHint.startsWith("Still waiting on")) aiStatusHint = ""; if (disowned()) return settle(null); if (ev.Text) { aiStatusHint = ""; From 88954ab91e07ed7c46568d33fbec2fb6886a24cc Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:36:28 +0545 Subject: [PATCH 028/317] style(dialogs): Create database, Report an issue and About on one frame (#161) Header (title + one-line description, close in the corner), body with 8px gaps inside a group and 24px between groups, and a bordered footer with one primary button, ghost for the rest - the What's new dialog's frame. - Create database: no icon tile or asterisk; 'Name' with a sentence hint; advanced options as a quiet disclosure naming what is inside; inline error; ghost Cancel. - Report an issue: segmented kind control without icons; version and OS in the description instead of an 'Auto-included' box; Copy and View issues as ghost buttons, Open on GitHub the one primary. - About: logo, name and build in a header row; plan and licensee as a key-value list; 'Deactivate on this computer' as a small ghost action. --- .changeset/dialog-design.md | 2 + src/lib/components/AboutDialog.svelte | 118 +++++------- .../components/CreateDatabaseDialog.svelte | 72 +++----- src/lib/components/ReportIssueDialog.svelte | 173 ++++++------------ 4 files changed, 122 insertions(+), 243 deletions(-) create mode 100644 .changeset/dialog-design.md diff --git a/.changeset/dialog-design.md b/.changeset/dialog-design.md new file mode 100644 index 00000000..2dddfb8d --- /dev/null +++ b/.changeset/dialog-design.md @@ -0,0 +1,2 @@ +### Improvements +- Create database, Report an issue and About share one calm dialog frame: a title with one line under it, the content, and a ruled footer with a single filled action. Decorative icon tiles, boxed rows and the full-width Deactivate bar are gone; Report an issue picks its kind from a segmented control diff --git a/src/lib/components/AboutDialog.svelte b/src/lib/components/AboutDialog.svelte index cfac4944..845d7114 100644 --- a/src/lib/components/AboutDialog.svelte +++ b/src/lib/components/AboutDialog.svelte @@ -6,7 +6,6 @@ import Logo from './Logo.svelte' import ShieldCheck from '@lucide/svelte/icons/shield-check' import Clock from '@lucide/svelte/icons/clock' - import AlertTriangle from '@lucide/svelte/icons/alert-triangle' import KeyRound from '@lucide/svelte/icons/key-round' import LogOut from '@lucide/svelte/icons/log-out' import ExternalLink from '@lucide/svelte/icons/external-link' @@ -46,25 +45,17 @@ - -
-
- -
-
-

Stroke

-

Database management, reimagined

- - v{appVersion} - + +
+ +
+ Stroke +

v{appVersion}

- -
- -
+
{#if !$licenseStatus} @@ -75,57 +66,41 @@ {:else if isValid} -
-
-
- -
- Pro license active -
-
-
- Email - {$licenseStatus.email} -
-
- Plan - {$licenseStatus.plan ?? 'Pro'} -
-
- Expires - - {$licenseStatus.expires_at - ? new Date($licenseStatus.expires_at * 1000).toLocaleDateString() - : 'Lifetime'} - -
-
- -
+ +
+
Plan
+
+
+
Licensed to
+
{$licenseStatus.email}
+
+ {:else if isTrial}
-
-
- -
- Free trial -
+ + {$licenseStatus.days_remaining}d left @@ -152,14 +127,9 @@ {:else}
-
-
- -
-
-

No active license

-

Free features only

-
+
+

No active license

+

Free features only.

{#if showActivate} { showActivate = false; open = false }} /> @@ -183,11 +153,11 @@
-
+
@@ -196,7 +166,7 @@ href="https://github.com/stroke-app/stroke" target="_blank" rel="noopener noreferrer" - class="inline-flex items-center gap-1 text-ui-3xs text-muted-foreground transition-colors hover:text-foreground" + class="inline-flex items-center gap-1.5 text-ui-2xs text-muted-foreground transition-colors hover:text-foreground" >
-
- -
-
- Create database -

- {engineLabel} · on this server -

-
-
- - - - - -
- + +
+
+ -

- Letters, digits, underscores · max 63 characters +

+ Letters, digits and underscores, up to 63 characters.

@@ -169,21 +155,16 @@ type="button" aria-expanded={showAdvanced} aria-controls="cdb-advanced" - class="flex w-full items-center gap-1.5 rounded-md py-1.5 text-left text-ui-xs text-muted-foreground transition-colors hover:text-foreground" + class="-mb-3 flex w-fit items-center gap-1.5 rounded-md text-left text-ui-xs text-muted-foreground transition-colors duration-150 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring" onclick={() => (showAdvanced = !showAdvanced)} > - - Advanced options - {#if !showAdvanced} - - encoding, collation, owner - - {/if} + + {isMySQL ? 'Character set and collation' : 'Encoding, collation and owner'} {#if showAdvanced} -
+
{#if !isMySQL} @@ -277,26 +258,17 @@ {/if} {/if} - {#if error} -

{error}

+ {/if} +
- -
- +
+ - {/each} -
+ + + Report an issue + + Opens a GitHub issue with this filled in, plus Stroke v{appVersion} on {platform || "this computer"}{details ? " and the error details" : ""}. + + + +
+ +
+ {#each TYPES as t (t.id)} + + {/each}
- -
+
- -
- +
+
- - -
- Auto-included - v{appVersion} · {platform || "unknown"}{details - ? " · error details" - : ""} -
- -
- + + - -
- - -
+ variant="ghost" + onclick={async () => { + try { + const { openUrl } = await import("@tauri-apps/plugin-opener"); + await openUrl(`https://github.com/${GITHUB_REPO}/issues`); + } catch { + window.open(`https://github.com/${GITHUB_REPO}/issues`, "_blank"); + } + }} + >View issues +
From ebb6b2e18edbaf64ce762c5ba0973201e5092a14 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:51:51 +0000 Subject: [PATCH 029/317] chore: version 2.6.4 (#161) --- .changeset/ai-stalled-tools.md | 2 -- .changeset/dialog-design.md | 2 -- .changeset/seat-limit-message.md | 2 -- .changeset/settings-account-sync.md | 6 ------ .changeset/shift-wheel.md | 3 --- CHANGELOG.md | 17 +++++++++++++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 8 files changed, 19 insertions(+), 17 deletions(-) delete mode 100644 .changeset/ai-stalled-tools.md delete mode 100644 .changeset/dialog-design.md delete mode 100644 .changeset/seat-limit-message.md delete mode 100644 .changeset/settings-account-sync.md delete mode 100644 .changeset/shift-wheel.md diff --git a/.changeset/ai-stalled-tools.md b/.changeset/ai-stalled-tools.md deleted file mode 100644 index cca70d53..00000000 --- a/.changeset/ai-stalled-tools.md +++ /dev/null @@ -1,2 +0,0 @@ -### Bug Fixes -- AI chat with a local agent no longer spins forever when a tool never answers: after 30 seconds it says which step it is waiting on, and after 3 minutes it stops the agent and ends the turn with the reason diff --git a/.changeset/dialog-design.md b/.changeset/dialog-design.md deleted file mode 100644 index 2dddfb8d..00000000 --- a/.changeset/dialog-design.md +++ /dev/null @@ -1,2 +0,0 @@ -### Improvements -- Create database, Report an issue and About share one calm dialog frame: a title with one line under it, the content, and a ruled footer with a single filled action. Decorative icon tiles, boxed rows and the full-width Deactivate bar are gone; Report an issue picks its kind from a segmented control diff --git a/.changeset/seat-limit-message.md b/.changeset/seat-limit-message.md deleted file mode 100644 index ace3cf3d..00000000 --- a/.changeset/seat-limit-message.md +++ /dev/null @@ -1,2 +0,0 @@ -### Bug Fixes -- When a license is on all the devices it covers, the message says where to free one or ask for more devices (stroke.click/app) diff --git a/.changeset/settings-account-sync.md b/.changeset/settings-account-sync.md deleted file mode 100644 index 1719b67e..00000000 --- a/.changeset/settings-account-sync.md +++ /dev/null @@ -1,6 +0,0 @@ -### Features -- Settings has an Account & Sync tab: your account, plan and license, and end-to-end encrypted sync (set up, unlock, status, Sync now) in one place - -### Bug Fixes -- Settings: one line under each section heading instead of two -- The sign-in prompt for license-key holders says what signing in gives you: connections, workspaces and settings on every device, end-to-end encrypted diff --git a/.changeset/shift-wheel.md b/.changeset/shift-wheel.md deleted file mode 100644 index f3bdc282..00000000 --- a/.changeset/shift-wheel.md +++ /dev/null @@ -1,3 +0,0 @@ -### Bug Fixes -- Shift + mouse wheel scrolls sideways everywhere: the related-rows panel, query results, settings and every other wide area, not only the data grid -- Shift + wheel over the related-rows panel no longer scrolls the grid behind it diff --git a/CHANGELOG.md b/CHANGELOG.md index 83ced975..1e6d5c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.6.4] - 2026-11-14 + +### Bug Fixes +- AI chat with a local agent no longer spins forever when a tool never answers: after 30 seconds it says which step it is waiting on, and after 3 minutes it stops the agent and ends the turn with the reason +- When a license is on all the devices it covers, the message says where to free one or ask for more devices (stroke.click/app) +- Settings: one line under each section heading instead of two +- The sign-in prompt for license-key holders says what signing in gives you: connections, workspaces and settings on every device, end-to-end encrypted +- Shift + mouse wheel scrolls sideways everywhere: the related-rows panel, query results, settings and every other wide area, not only the data grid +- Shift + wheel over the related-rows panel no longer scrolls the grid behind it + +### Improvements +- Create database, Report an issue and About share one calm dialog frame: a title with one line under it, the content, and a ruled footer with a single filled action. Decorative icon tiles, boxed rows and the full-width Deactivate bar are gone; Report an issue picks its kind from a segmented control + +### Features +- Settings has an Account & Sync tab: your account, plan and license, and end-to-end encrypted sync (set up, unlock, status, Sync now) in one place + + ## [2.6.3] - 2026-11-14 ### Changes diff --git a/package.json b/package.json index adc65c7f..bba764d3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.6.3", + "version": "2.6.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 72c663d4..907d4cba 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.6.3", + "version": "2.6.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 36c3bd068bb0010d53e0bd31323a60cde8cfc4e9 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:41:52 +0545 Subject: [PATCH 030/317] fix(docker): list Oracle and NoSQL containers in the Docker scan (#151) --- .changeset/docker-scan-more-engines.md | 2 + src-tauri/src/docker.rs | 56 ++++++++++++++++++++++- src/lib/components/ConnectionModal.svelte | 35 +++++++++++--- 3 files changed, 86 insertions(+), 7 deletions(-) create mode 100644 .changeset/docker-scan-more-engines.md diff --git a/.changeset/docker-scan-more-engines.md b/.changeset/docker-scan-more-engines.md new file mode 100644 index 00000000..83aa6b51 --- /dev/null +++ b/.changeset/docker-scan-more-engines.md @@ -0,0 +1,2 @@ +### Bug Fixes +- Oracle, MongoDB, CouchDB, Cassandra/Scylla and DynamoDB Local containers now show up under Docker in the connection dialog, with their credentials filled in diff --git a/src-tauri/src/docker.rs b/src-tauri/src/docker.rs index 141aa7b9..8581a943 100644 --- a/src-tauri/src/docker.rs +++ b/src-tauri/src/docker.rs @@ -337,6 +337,11 @@ fn engine_port(engine: &str) -> u16 { "clickhouse" => 8123, "mssql" => 1433, "cockroachdb" => 26257, + "oracle" => 1521, + "mongodb" => 27017, + "couchdb" => 5984, + "cassandra" => 9042, + "dynamodb" => 8000, _ => 5432, } } @@ -367,6 +372,23 @@ fn engine_for_image(image: &str) -> Option<&'static str> { if i.contains("mssql") || i.contains("sqlserver") || i.contains("azure-sql-edge") { return Some("mssql"); } + // gvenzl/oracle-free, gvenzl/oracle-xe, container-registry.oracle.com/database/free. + if i.contains("oracle-free") || i.contains("oracle-xe") || i.contains("oracle/database") || i.contains("oracle.com/database") { + return Some("oracle"); + } + // Admin UIs share the name but are not databases. + if i.contains("mongo") && !i.contains("mongo-express") { + return Some("mongodb"); + } + if i.contains("couchdb") { + return Some("couchdb"); + } + if i.contains("cassandra") || i.contains("scylla") { + return Some("cassandra"); + } + if i.contains("dynamodb-local") { + return Some("dynamodb"); + } None } @@ -383,6 +405,10 @@ fn engine_for_ports(ports: &Value) -> Option<&'static str> { 8123 => "clickhouse", 1433 => "mssql", 26257 => "cockroachdb", + 1521 => "oracle", + 27017 => "mongodb", + 5984 => "couchdb", + 9042 => "cassandra", _ => continue, }; return Some(engine); @@ -438,6 +464,20 @@ fn credentials(engine: &str, env: &std::collections::HashMap) -> String::new(), ), "cockroachdb" => ("root".into(), String::new(), "defaultdb".into()), + // gvenzl images: SYSTEM with ORACLE_PASSWORD; the official image uses ORACLE_PWD. + // The database is the pluggable one the image opens (set in database_from_inspect). + "oracle" => ("system".into(), get(&["ORACLE_PASSWORD", "ORACLE_PWD"]).unwrap_or_default(), String::new()), + "mongodb" => ( + get(&["MONGO_INITDB_ROOT_USERNAME"]).unwrap_or_default(), + get(&["MONGO_INITDB_ROOT_PASSWORD"]).unwrap_or_default(), + get(&["MONGO_INITDB_DATABASE"]).unwrap_or_default(), + ), + "couchdb" => ( + get(&["COUCHDB_USER"]).unwrap_or_default(), + get(&["COUCHDB_PASSWORD"]).unwrap_or_default(), + String::new(), + ), + "cassandra" | "dynamodb" => (String::new(), String::new(), String::new()), _ => { let user = get(&["POSTGRES_USER", "PGUSER"]).unwrap_or_else(|| "postgres".into()); let db = get(&["POSTGRES_DB", "PGDATABASE"]).unwrap_or_else(|| user.clone()); @@ -482,7 +522,14 @@ fn database_from_inspect(c: &Value) -> Option { .to_string(); let env = env_map(config.get("Env").unwrap_or(&Value::Null)); - let (user, password, database) = credentials(&engine, &env); + let (user, password, mut database) = credentials(&engine, &env); + if engine == "oracle" && database.is_empty() { + // Free (23ai) opens FREEPDB1, XE opens XEPDB1; APP_USER-style images may add one. + database = env + .get("ORACLE_DATABASE") + .cloned() + .unwrap_or_else(|| if image.to_lowercase().contains("xe") { "XEPDB1".into() } else { "FREEPDB1".into() }); + } let name = c .get("Name") .and_then(Value::as_str) @@ -613,6 +660,13 @@ mod tests { fn recognises_database_images_and_ignores_the_rest() { assert_eq!(engine_for_image("postgres:17-alpine"), Some("postgres")); assert_eq!(engine_for_image("pgvector/pgvector:pg16"), Some("postgres")); + assert_eq!(engine_for_image("gvenzl/oracle-free:slim"), Some("oracle")); + assert_eq!(engine_for_image("container-registry.oracle.com/database/free:latest"), Some("oracle")); + assert_eq!(engine_for_image("mongo:7"), Some("mongodb")); + assert_eq!(engine_for_image("mongo-express"), None); + assert_eq!(engine_for_image("couchdb:3"), Some("couchdb")); + assert_eq!(engine_for_image("scylladb/scylla"), Some("cassandra")); + assert_eq!(engine_for_image("amazon/dynamodb-local"), Some("dynamodb")); assert_eq!(engine_for_image("timescale/timescaledb:latest-pg16"), Some("postgres")); assert_eq!(engine_for_image("mariadb:11"), Some("mariadb")); assert_eq!(engine_for_image("mysql:8.4"), Some("mysql")); diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 06dcf6e2..34642dc1 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -2102,6 +2102,31 @@ }); } + /** + * The engine-specific connection fields for a container. The SQL engines and + * Redis take host/port/user; the document engines take a URI or endpoint. + * @param {import('$lib/api.js').DockerDatabase} d + */ + function dockerConnFields(d) { + const hp = `${d.host}:${d.port}`; + const auth = d.user ? `${encodeURIComponent(d.user)}:${encodeURIComponent(d.password)}@` : ""; + switch (d.engine) { + case "oracle": + return { host: d.host, port: d.port, serviceName: d.database, sid: "", connectString: "", user: d.user, password: d.password }; + case "mongodb": + return { uri: `mongodb://${auth}${hp}/${d.user ? "?authSource=admin" : ""}`, database: d.database }; + case "couchdb": + return { url: `http://${hp}`, user: d.user, password: d.password }; + case "cassandra": + return { hosts: hp, user: d.user, password: d.password, keyspace: "" }; + case "dynamodb": + // DynamoDB Local accepts any keys; it still wants some. + return { region: "us-east-1", endpoint: `http://${hp}`, accessKeyId: "local", secretAccessKey: "local", sessionToken: "" }; + default: + return { host: d.host, port: d.port, user: d.user, password: d.password, database: d.database }; + } + } + /** @param {import('$lib/api.js').DockerDatabase} d */ function dockerTarget(d) { const label = `Docker · ${d.image}`; @@ -2114,7 +2139,9 @@ ? { encrypt: true, trustCert: true } : d.engine === "clickhouse" ? { secure: false } - : { ssl: false }; + : ["oracle", "mongodb", "couchdb", "cassandra", "dynamodb"].includes(d.engine) + ? {} + : { ssl: false }; return /** @type {LocalTarget} */ ({ id: `docker:${d.name}`, container: d.name, @@ -2132,13 +2159,9 @@ id: `docker:${d.name}`, type: d.engine, name: d.name, - host: d.host, - port: d.port, - user: d.user, - password: d.password, - database: d.database, origin: "docker", toolLabel: label, + ...dockerConnFields(d), ...extras, }, }); From bd7a4039e6c627a8d552c5ef2b0caf2461f2751f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:57:03 +0000 Subject: [PATCH 031/317] chore: version 2.6.5 (#151) --- .changeset/docker-scan-more-engines.md | 2 -- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) delete mode 100644 .changeset/docker-scan-more-engines.md diff --git a/.changeset/docker-scan-more-engines.md b/.changeset/docker-scan-more-engines.md deleted file mode 100644 index 83aa6b51..00000000 --- a/.changeset/docker-scan-more-engines.md +++ /dev/null @@ -1,2 +0,0 @@ -### Bug Fixes -- Oracle, MongoDB, CouchDB, Cassandra/Scylla and DynamoDB Local containers now show up under Docker in the connection dialog, with their credentials filled in diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e6d5c61..b2507ffb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.6.5] - 2026-11-14 + +### Bug Fixes +- Oracle, MongoDB, CouchDB, Cassandra/Scylla and DynamoDB Local containers now show up under Docker in the connection dialog, with their credentials filled in + + ## [2.6.4] - 2026-11-14 ### Bug Fixes diff --git a/package.json b/package.json index bba764d3..0631a649 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.6.4", + "version": "2.6.5", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 907d4cba..c370ac21 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.6.4", + "version": "2.6.5", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From f3e29bdc6773e5e089195e69d7dc135ee709d9b2 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:44:23 +0545 Subject: [PATCH 032/317] style(ai): model picker, AI models, Add model, composer and error card (#162) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Picker: Claude Code uses Claude's mark (simple-icons), Ollama gets its mark; rail switches on click/focus only (hover swapped the list as the pointer crossed it); search is a combobox with aria-activedescendant; 'Dangerous' access reads 'Full access' in amber; chip at h-8. - AI models: dialog header and footer like the others, icon Edit button. - Add model step 0: single list with logo, name and a one-line blurb; choosing advances, so no Continue on that step. - Composer: visible border, focus ring, 32px send/stop, no '↵ to send'. - describeAiError: a 401 with no credentials ('No cookie auth credentials found') is 'No API key was sent' with our hint first; error card in the composer column with an 'Open AI settings' button for 401/403. - ConnectionModal title row uses --app-titlebar-h (design lint). --- .changeset/ai-ui-pass.md | 8 +++ src/lib/ai-errors.test.js | 7 ++ src/lib/ai.js | 11 +++- src/lib/brand-icons.js | 5 ++ src/lib/components/AiChat.svelte | 40 +++++++----- src/lib/components/AiModelPicker.svelte | 26 +++++--- src/lib/components/AiSettingsDialog.svelte | 74 +++++++++++++++------- src/lib/components/ConnectionModal.svelte | 2 +- 8 files changed, 123 insertions(+), 50 deletions(-) create mode 100644 .changeset/ai-ui-pass.md diff --git a/.changeset/ai-ui-pass.md b/.changeset/ai-ui-pass.md new file mode 100644 index 00000000..b0e0521e --- /dev/null +++ b/.changeset/ai-ui-pass.md @@ -0,0 +1,8 @@ +### Improvements +- Model picker: Claude Code shows Claude's own mark, Ollama its own; moving the pointer across the provider icons no longer swaps the list under you; the search box is a proper combobox for screen readers; "Full access" is named as such and shown in amber +- AI models and Add model: one header and footer like the other dialogs; the provider step is a list with each provider's logo and one line on what it is, and picking one moves straight on +- The composer has a clear edge and a focus ring, the model chip and send button line up at one height, and the "↵ to send" hint is gone + +### Bug Fixes +- A request sent without an API key says "No API key was sent" and offers AI settings, instead of "The provider rejected the API key" with OpenRouter's "No cookie auth credentials found" +- The AI error shows as a card in the composer's column instead of a red bar across the window diff --git a/src/lib/ai-errors.test.js b/src/lib/ai-errors.test.js index 0ffb0bb5..971a0824 100644 --- a/src/lib/ai-errors.test.js +++ b/src/lib/ai-errors.test.js @@ -146,3 +146,10 @@ describe('the plan instruction', () => { expect(p).toContain('USE does not carry over') }) }) + +it("a request with no key is called a missing key, not a rejected one", async () => { + const { describeAiError } = await import('./ai.js') + const f = describeAiError('AI API 401: {"error":{"message":"No cookie auth credentials found","code":401}}') + expect(f.title).toBe('No API key was sent') + expect(f.hint).toMatch(/Add the API key/) +}) diff --git a/src/lib/ai.js b/src/lib/ai.js index bbbba9a0..45cc7c08 100644 --- a/src/lib/ai.js +++ b/src/lib/ai.js @@ -890,6 +890,7 @@ export function describeAiError(err) { const diagnosis = routerDiagnosis(payload) const hintFor = () => { + if (noKey) return 'Add the API key for this model in AI settings, then send again.' if (status === 401 || status === 403) return 'Check the API key for this provider in AI settings.' if (status === 404) return "That model isn't available at this endpoint - pick another in the model picker." if (status === 429) return 'Wait a moment and try again, or check your plan and usage limits.' @@ -902,8 +903,12 @@ export function describeAiError(err) { return '' } + // OpenRouter answers a request with no key at all "No cookie auth + // credentials found": that is a missing key, not a wrong one. + const noKey = (status === 401 || status === 403) && /no cookie auth|no auth credentials|missing (api )?key|no api key|authorization header/i.test(payload) const title = status === 429 ? 'Rate limit reached' + : noKey ? 'No API key was sent' : status === 401 || status === 403 ? 'The provider rejected the API key' : status === 404 ? 'Model not found at this endpoint' : status === 502 || status === 503 || status === 504 ? 'The AI provider is unavailable' @@ -920,7 +925,11 @@ export function describeAiError(err) { // A diagnosis is worth more than the message it wraps - "none of the 6 // endpoints were tried, all cooling down after 429" beats "Upstream request // failed" - so where one exists the shape is unchanged. - const hint = diagnosis + // A missing key is the exception: the provider's sentence ("No cookie auth + // credentials found") is the confusing part, so ours goes first. + const hint = noKey + ? hintFor() + : diagnosis ? [diagnosis, hintFor()].filter(Boolean).join(' ') : message || hintFor() return { title, hint, detail: payloadAddsNothing(payload, hint) ? '' : payload, status } diff --git a/src/lib/brand-icons.js b/src/lib/brand-icons.js index bb508373..c4872885 100644 --- a/src/lib/brand-icons.js +++ b/src/lib/brand-icons.js @@ -29,6 +29,11 @@ export const BRAND_PATHS = { // ── AI providers (ModelProfile.provider) ── openai: 'M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z', + // Claude Code (the agent CLI): Claude's own mark, so it isn't mistaken for an Anthropic API key. + claude: + 'm4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z', + ollama: + 'M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z', anthropic: 'M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z', google: diff --git a/src/lib/components/AiChat.svelte b/src/lib/components/AiChat.svelte index a8670e08..185f4cd6 100644 --- a/src/lib/components/AiChat.svelte +++ b/src/lib/components/AiChat.svelte @@ -4445,7 +4445,9 @@ weight (border, lift) once it has focus. -->
@@ -4530,12 +4532,8 @@ guidance for someone about to type, not a permanent label. --> {#if loading && inputText.trim()} - {:else if inputFocused && !inputText.trim() && !loading} - + {:else if hasPendingConfirm} + {/if} @@ -4551,7 +4549,7 @@ > + {/if} {#if failure.detail}
+
{/if} diff --git a/src/lib/components/AiModelPicker.svelte b/src/lib/components/AiModelPicker.svelte index f7f06a6a..1cf6be51 100644 --- a/src/lib/components/AiModelPicker.svelte +++ b/src/lib/components/AiModelPicker.svelte @@ -94,7 +94,7 @@ /** The brand mark for a provider; agents borrow their maker's. @param {string} provider */ function brandOf(provider) { const agent = profileAgent({ provider }) - if (agent === 'claude') return 'anthropic' + if (agent === 'claude') return 'claude' if (agent === 'codex') return 'openai' return provider } @@ -182,7 +182,7 @@ // Shown in the footer: what the agent may run. Read-only connection wins. const accessLabel = $derived( $readOnlyMode || !activeAgent ? ($readOnlyMode ? 'Read only' : '') - : ({ read: 'Read only', write: 'Read & write', modify: 'Modify schema', dangerous: 'Dangerous' })[$agentPrefs.access] ?? 'Read only' + : ({ read: 'Read only', write: 'Read & write', modify: 'Modify schema', dangerous: 'Full access' })[$agentPrefs.access] ?? 'Read only' ) const modKey = IS_MAC ? '⌘' : 'Ctrl+' @@ -253,7 +253,7 @@ { if (o) openPicker() }}> {@render mark(activeProfile ? brandOf(activeProfile.provider) : '', 'size-3.5 shrink-0')} @@ -273,7 +273,7 @@ )} title="Favourites" aria-label="Favourites" - onmouseenter={() => showGroup('fav')} + aria-pressed={railKey === 'fav' && !query} onfocus={() => showGroup('fav')} onclick={() => { railKey = 'fav'; query = ''; highlight = 0 }} > @@ -290,7 +290,7 @@ )} title={g.agent && g.agent.status !== 'ready' ? `${g.label} (${g.agent.status === 'missing' ? 'not installed' : 'sign in first'})` : g.label} aria-label={g.label} - onmouseenter={() => showGroup(g.key)} + aria-pressed={railKey === g.key && !query} onfocus={() => showGroup(g.key)} onclick={() => { railKey = g.key; query = ''; highlight = 0 }} > @@ -313,10 +313,15 @@ class="no-focus-ring min-w-0 flex-1 bg-transparent text-ui-xs text-foreground outline-none placeholder:text-muted-foreground" placeholder="Search models…" aria-label="Search models" + role="combobox" + aria-expanded="true" + aria-controls="ai-model-list" + aria-autocomplete="list" + aria-activedescendant={visible.length ? `ai-model-opt-${highlight}` : undefined} /> -
+
{#if blockedAgent}

@@ -344,9 +349,11 @@ {:else} {#each visible as e, i (e.key)}

Manage models… {#if accessLabel} - - {accessLabel} + + + {/if}
diff --git a/src/lib/components/AiSettingsDialog.svelte b/src/lib/components/AiSettingsDialog.svelte index 9bcff8e1..6381ca72 100644 --- a/src/lib/components/AiSettingsDialog.svelte +++ b/src/lib/components/AiSettingsDialog.svelte @@ -72,6 +72,20 @@ const CARD_IDLE = "border-border/40 text-foreground/85 hover:border-border/70 hover:bg-muted/30 hover:text-foreground"; + /** One line under each provider in the wizard: what you get, and what it takes. */ + const PROVIDER_BLURB = /** @type {Record} */ ({ + stroke: "Free models, no key needed", + openrouter: "One key, hundreds of models", + openai: "GPT models with your OpenAI key", + anthropic: "Claude models with your Anthropic key", + copilot: "Your Copilot plan, sign in with GitHub", + mistral: "Mistral models with your key", + google: "Gemini models with your Google AI key", + ollama: "Models running on this computer", + omniroute: "A local gateway in front of many providers", + custom: "Any OpenAI-compatible endpoint", + }); + /** Marks for the providers brand-icons.js has no logo for. */ const PROVIDER_ICON_FALLBACK = /** @type {Record} */ ({ stroke: Sparkles, @@ -500,14 +514,14 @@ {#if view === "list"} -
-
- AI Models - - Right-click a model to edit or delete it. +
+
+ AI models + + The models chat and SQL suggestions can use. Pick one to use it.
- +
@@ -546,9 +560,12 @@
+ > @@ -578,13 +595,11 @@ {/if}
-
- +
@@ -631,25 +646,33 @@ {#if step === 0} - -
+ +
{#each PROVIDERS as p (p.id)} {@const selected = formProvider === p.id} {@const Fallback = PROVIDER_ICON_FALLBACK[p.id] ?? Sparkles} {/each}
@@ -1080,7 +1103,10 @@ {/if}
- {#if step < STEPS.length - 1} + {#if step === 0} + + + {:else if step < STEPS.length - 1} {/if} - History + Chats {#if !selecting}
void newConversation()} > -

- No conversations yet -

-

- Chats save automatically -

-
+ + Ask about this database + {/if}
{#if onexit} From f3fbaeff67ee404be85d5400cdf8da25b9d34402 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:00:34 +0000 Subject: [PATCH 035/317] chore: version 2.6.7 (#163) --- .changeset/ai-history-list.md | 2 -- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) delete mode 100644 .changeset/ai-history-list.md diff --git a/.changeset/ai-history-list.md b/.changeset/ai-history-list.md deleted file mode 100644 index 9b76d118..00000000 --- a/.changeset/ai-history-list.md +++ /dev/null @@ -1,2 +0,0 @@ -### Improvements -- AI mode's chat list matches the sidebar's Chats: each chat shows the database and schema it worked in over its title, and an empty list offers to start one diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a62d18d..f5d3b229 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.6.7] - 2026-11-14 + +### Improvements +- AI mode's chat list matches the sidebar's Chats: each chat shows the database and schema it worked in over its title, and an empty list offers to start one + + ## [2.6.6] - 2026-11-14 ### Bug Fixes diff --git a/package.json b/package.json index 95676553..fd034195 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.6.6", + "version": "2.6.7", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ae373b38..4c0d6b31 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.6.6", + "version": "2.6.7", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 43a0d9746c06c297dd801c6da0cbf328a2e8b1d4 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:46:22 +0545 Subject: [PATCH 036/317] fix(shell): diagrams no longer fold the sidebar (#164) The ERD, relation tree and diagrams tabs closed the nav sidebar while they were active. The sidebar now stays as the user left it; Mod+B hides it. --- .changeset/erd-keeps-sidebar.md | 2 ++ src/lib/components/StudioShell.svelte | 17 ++--------------- 2 files changed, 4 insertions(+), 15 deletions(-) create mode 100644 .changeset/erd-keeps-sidebar.md diff --git a/.changeset/erd-keeps-sidebar.md b/.changeset/erd-keeps-sidebar.md new file mode 100644 index 00000000..65f58348 --- /dev/null +++ b/.changeset/erd-keeps-sidebar.md @@ -0,0 +1,2 @@ +### Bug Fixes +- Opening the schema diagram, relation tree or diagrams no longer closes the sidebar; it stays as you left it (⌘B hides it) diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 68ffae5b..41341444 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -615,10 +615,6 @@ /** The update is downloaded: the status bar offers the restart. */ let statusBarUpdateReady = $state(false) let sidebarOpen = $state(loadLayout().navSidebarOpen) - /** The nav sidebar was open when a visual page took the width; put it back on leaving. */ - let _sidebarBeforeErd = false - /** Tab kinds that are a picture first: they get the sidebar's width. */ - const WIDE_TAB_KINDS = new Set(['erd', 'reltree', 'diagrams']) let sidebarEverOpened = $state(loadLayout().navSidebarOpen) /** Which switchable sidebar panel is showing: 'tables' | 'connections' | 'extensions'. */ let navSidebarPanel = $state(loadLayout().navSidebarPanel ?? 'tables') @@ -1206,17 +1202,8 @@ if (activeTab?.kind === 'charts') chartsEverOpened = true if (activeTab?.kind === 'dashboard') dashboardEverOpened = true if (activeTab?.kind === 'erd') erdEverOpened = true - // The visual pages want the width: the nav sidebar folds while one of them - // is the active tab and comes back when another kind is. Untracked so - // Ctrl+B on the tab itself is not undone by this effect re-running. - untrack(() => { - if (activeTab && WIDE_TAB_KINDS.has(activeTab.kind)) { - if (sidebarOpen) { _sidebarBeforeErd = true; sidebarOpen = false } - } else if (_sidebarBeforeErd) { - _sidebarBeforeErd = false - sidebarOpen = true - } - }) + // The sidebar stays as you left it on every page, the diagrams included: + // folding it on its own took the table list away mid-task. ⌘B hides it. if (activeTab?.kind === 'diagrams') diagramsEverOpened = true if (activeTab?.kind === 'search') searchEverOpened = true if (activeTab?.kind === 'schema-timeline') schemaTimelineEverOpened = true From f76ed60e864f0f71ac7085f25ec28797975c0cfa Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:01:36 +0000 Subject: [PATCH 037/317] chore: version 2.6.8 (#164) --- .changeset/erd-keeps-sidebar.md | 2 -- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) delete mode 100644 .changeset/erd-keeps-sidebar.md diff --git a/.changeset/erd-keeps-sidebar.md b/.changeset/erd-keeps-sidebar.md deleted file mode 100644 index 65f58348..00000000 --- a/.changeset/erd-keeps-sidebar.md +++ /dev/null @@ -1,2 +0,0 @@ -### Bug Fixes -- Opening the schema diagram, relation tree or diagrams no longer closes the sidebar; it stays as you left it (⌘B hides it) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5d3b229..7306780b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.6.8] - 2026-11-14 + +### Bug Fixes +- Opening the schema diagram, relation tree or diagrams no longer closes the sidebar; it stays as you left it (⌘B hides it) + + ## [2.6.7] - 2026-11-14 ### Improvements diff --git a/package.json b/package.json index fd034195..4bc06e1c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.6.7", + "version": "2.6.8", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 4c0d6b31..79fc268a 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.6.7", + "version": "2.6.8", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From d4f94b4ec185bba26101e1e6cac3a5c5a56827ac Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:49:08 +0545 Subject: [PATCH 038/317] style(reltree): calmer cards, row-count bar, lighter lines, dot grid (#165) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drop the role colour strips (amber/blue/grey) that nothing explained, and the ↑/↓ counters: 'used by N' says the one that matters. - Cards: border + low layered shadow on bg-card; a 2px row-count bar on the log scale barPct already computed but never drew. - Edges 1.25px with round caps at 40% (lineage 1.75px, primary); smaller arrowheads. - Dot grid background bound to the camera (size and offset follow zoom and pan). Checked in a browser preview: layout, hover lineage, dot grid. --- .changeset/relation-tree-design.md | 2 ++ src/lib/components/ErdHierarchy.svelte | 45 ++++++++++++++------------ 2 files changed, 26 insertions(+), 21 deletions(-) create mode 100644 .changeset/relation-tree-design.md diff --git a/.changeset/relation-tree-design.md b/.changeset/relation-tree-design.md new file mode 100644 index 00000000..26bdf9b0 --- /dev/null +++ b/.changeset/relation-tree-design.md @@ -0,0 +1,2 @@ +### Improvements +- Relation tree: cards are quiet raised surfaces with a row-count bar (log scale, so sizes compare at a glance) and "used by N" instead of the colour strips and ↑↓ counters; lines are thinner and rounded; a faint dot grid pans and zooms with the drawing diff --git a/src/lib/components/ErdHierarchy.svelte b/src/lib/components/ErdHierarchy.svelte index 98d9452f..d697b08e 100644 --- a/src/lib/components/ErdHierarchy.svelte +++ b/src/lib/components/ErdHierarchy.svelte @@ -43,12 +43,6 @@ /** Tables pointing at each hub, for the pill on its card. */ const hubRefs = $derived(new Map([...hubs].map((h) => [h, adj.down.get(h)?.size ?? 0]))) const colCount = $derived(new Map(tables.map((t) => [t.name, t.columns?.length ?? 0]))) - /** root: points at nothing but is pointed at · linked: points at something · loose: neither. @param {string} id */ - function roleOf(id) { - const up = adj.up.get(id)?.size ?? 0, down = adj.down.get(id)?.size ?? 0 - return up === 0 && down > 0 ? 'root' : up > 0 ? 'linked' : 'loose' - } - const ROLE_STRIP = /** @type {Record} */ ({ root: 'bg-warning/80', linked: 'bg-info/80', loose: 'bg-muted-foreground/30' }) // ── Row counts ──────────────────────────────────────────────────────────── // The listing's numbers first, as the sidebar does: an estimate for a table @@ -417,9 +411,12 @@ +
{t.name} {colCount.get(t.name) ?? 0} {plural(colCount.get(t.name) ?? 0, 'col')}{#if n !== undefined} · {formatTableRowCount(n)} {plural(n, 'row')}{/if} - - {#if upN}↑{upN}{/if} - {#if downN}↓{downN}{/if} - + {#if downN} + used by {downN} + {/if} + + {#if n !== undefined && n > 0} + + {/if} {#if refs} Date: Sat, 14 Nov 2026 15:04:28 +0000 Subject: [PATCH 039/317] chore: version 2.6.9 (#165) --- .changeset/relation-tree-design.md | 2 -- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) delete mode 100644 .changeset/relation-tree-design.md diff --git a/.changeset/relation-tree-design.md b/.changeset/relation-tree-design.md deleted file mode 100644 index 26bdf9b0..00000000 --- a/.changeset/relation-tree-design.md +++ /dev/null @@ -1,2 +0,0 @@ -### Improvements -- Relation tree: cards are quiet raised surfaces with a row-count bar (log scale, so sizes compare at a glance) and "used by N" instead of the colour strips and ↑↓ counters; lines are thinner and rounded; a faint dot grid pans and zooms with the drawing diff --git a/CHANGELOG.md b/CHANGELOG.md index 7306780b..79d3ab2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.6.9] - 2026-11-14 + +### Improvements +- Relation tree: cards are quiet raised surfaces with a row-count bar (log scale, so sizes compare at a glance) and "used by N" instead of the colour strips and ↑↓ counters; lines are thinner and rounded; a faint dot grid pans and zooms with the drawing + + ## [2.6.8] - 2026-11-14 ### Bug Fixes diff --git a/package.json b/package.json index 4bc06e1c..bb9bc4e4 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.6.8", + "version": "2.6.9", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 79fc268a..c3f7735b 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.6.8", + "version": "2.6.9", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 9fa1bbcadad7b5d4a83a5d446c49f39465417ab2 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 20:51:08 +0545 Subject: [PATCH 040/317] feat(terminal): more than one terminal, each in its own tab (#166) One TerminalPage per terminal tab (keyed by tab id), so each tab runs its own session. openNewTerminalTab numbers them; view.terminalNew (Control+Shift+`), a + in the terminal's bar and a palette entry open one. tabDisplayTitle honours a terminal tab's own title. --- .changeset/multiple-terminals.md | 2 ++ src/lib/components/CommandPalette.svelte | 2 ++ src/lib/components/StudioShell.svelte | 33 +++++++++++++++++++----- src/lib/components/TerminalPage.svelte | 14 ++++++++++ src/lib/shortcuts.js | 1 + src/lib/studio-tabs.js | 1 + 6 files changed, 47 insertions(+), 6 deletions(-) create mode 100644 .changeset/multiple-terminals.md diff --git a/.changeset/multiple-terminals.md b/.changeset/multiple-terminals.md new file mode 100644 index 00000000..a6bfde76 --- /dev/null +++ b/.changeset/multiple-terminals.md @@ -0,0 +1,2 @@ +### Features +- Open more than one terminal: "New terminal tab" (Ctrl+Shift+`, the + in the terminal's bar, or the command palette) starts another session in its own tab, numbered Terminal 2, Terminal 3…; closing a tab ends only its own session diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index 6a71bd65..ffc48000 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -63,6 +63,7 @@ onopenredis = () => {}, onopenlogs = () => {}, onopenterminal = () => {}, + onnewterminal = () => {}, onopeninsights = () => {}, onopenadvisor = () => {}, onopenobjects = () => {}, @@ -245,6 +246,7 @@ { icon: 'terminal', label: 'SQL editor', keys: '⌘⇧S', action: onopensql, show: connected && (!isKeyValue || isDynamo || isDoc), value: 'open sql editor query console' }, { icon: 'plus', label: 'New SQL editor', action: onnewsql, show: connected && (!isKeyValue || isDynamo || isDoc), value: 'new sql editor tab additional multiple query console open another' }, { icon: 'square-terminal', label: 'Terminal', keys: '⌘J', action: onopenterminal, show: connected, value: 'terminal shell cli command line psql mysql mariadb sqlite3 sqlcmd redis-cli console repl meta commands' }, + { icon: 'square-terminal', label: 'New terminal tab', keys: '⌃⇧`', action: onnewterminal, show: connected, value: 'new terminal tab another second shell psql mysql session' }, { icon: 'code-2', label: 'ORM runner', keys: '⌘⇧O', action: onopenorm, show: connected && !isKeyValue, value: 'open orm runner drizzle prisma query builder' }, { icon: 'network', label: 'Schema diagram', action: onopenerd, show: connected && !isKeyValue, value: 'open schema diagram data model er diagram erd entity relationship foreign key pk fk graph hierarchy roadmap mermaid tree dictionary ddl schema map' }, { icon: 'layout-template', label: 'Schema explorer', action: onopenSchema, show: connected && hasSchemaExplorer, value: 'open schema explorer indexes enums views materialized' }, diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 41341444..de6f5a53 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -858,7 +858,6 @@ let securityEverOpened = $state(false) let logsEverOpened = $state(false) /** The terminal page lives exactly as long as its tab, and its client with it. */ - const hasTerminalTab = $derived(tabs.some((t) => t.kind === 'terminal')) /** The welcome page's tiles: six when connected (two rows of three), four otherwise and for Redis. */ const welcomeTileCount = $derived(connection ? 6 : 4) /** Welcome tile icon colours: theme tokens, written out whole so Tailwind sees them. */ @@ -2964,6 +2963,13 @@ let rowSearch = $state('') openTerminalTab() }) + createCommandHotkey('view.terminalNew', (e) => { + if (!connection) return + e.preventDefault() + if (aiMode) exitAiMode() + openNewTerminalTab() + }) + // Tab-bar visibility toggle moved here so Mod+Shift+T can reopen closed tabs. createCommandHotkey('view.tabBar', (e) => { e.preventDefault() @@ -4098,6 +4104,18 @@ let rowSearch = $state('') clearTableEditor() } + /** Another terminal tab: a second psql beside the first, numbered. */ + function openNewTerminalTab() { + if (!connection) return + saveActiveTabState() + dropWelcomeTabs() + const n = tabs.filter((t) => t.kind === 'terminal').length + 1 + const tab = { ...createTerminalTab(), title: n > 1 ? `Terminal ${n}` : 'Terminal' } + tabs = [...tabs, tab] + activeTabId = tab.id + clearTableEditor() + } + /** The Redis keyspace workspace. NOT pro-gated - it's the primary (and only) * interface for a Redis connection, so it must open on connect for everyone. */ function openRedisTab() { @@ -8935,6 +8953,7 @@ let rowSearch = $state('') onopensecurity={() => { if (aiMode) exitAiMode(); openSecurityTab() }} onopenlogs={() => { if (aiMode) exitAiMode(); openLogsTab() }} onopenterminal={() => { if (aiMode) exitAiMode(); if (!terminalDockOpen) toggleTerminalDock() }} + onnewterminal={() => { commandOpen = false; if (aiMode) exitAiMode(); openNewTerminalTab() }} onopeninsights={() => { if (aiMode) exitAiMode(); openInsightsTab() }} onopenadvisor={() => { if (aiMode) exitAiMode(); openAdvisorTab() }} onopenobjects={() => { if (aiMode) exitAiMode(); openObjectsTab() }} @@ -9523,18 +9542,20 @@ let rowSearch = $state('') - {#if hasTerminalTab} + + {#each tabs.filter((t) => t.kind === 'terminal') as tt (tt.id)}
{#await import('./TerminalPage.svelte')}{:then { default: TerminalPage }} - + {/await}
- {/if} + {/each} {#if insightsEverOpened} diff --git a/src/lib/components/TerminalPage.svelte b/src/lib/components/TerminalPage.svelte index e17c0239..25dcacad 100644 --- a/src/lib/components/TerminalPage.svelte +++ b/src/lib/components/TerminalPage.svelte @@ -24,6 +24,7 @@ import Command from '@lucide/svelte/icons/command' import X from '@lucide/svelte/icons/x' import RotateCw from '@lucide/svelte/icons/rotate-cw' + import Plus from '@lucide/svelte/icons/plus' import Eraser from '@lucide/svelte/icons/eraser' import Copy from '@lucide/svelte/icons/copy' import Check from '@lucide/svelte/icons/check' @@ -66,6 +67,8 @@ prewarm = false, /** @type {(() => void) | undefined} */ onclose = undefined, + /** Open another terminal tab beside this one. @type {(() => void) | undefined} */ + onnew = undefined, } = $props() /** @typedef {'idle' | 'checking' | 'unsupported' | 'missing' | 'failed' | 'starting' | 'running' | 'exited'} Phase */ @@ -1425,6 +1428,17 @@ > + {#if onnew} + + {/if} {#if onclose} + {/each} +
+ {/if} + + {#each shown as b (b.id)} +
+

+ + {b.label} + {grouped[b.id].length} +

+
    + {#each grouped[b.id] as item, i (i)} +
  • + + {#each parts(item.text) as p, k (k)} + {#if p.code}{p.text}{:else}{p.text}{/if} + {/each} + + {#if multi} + {item.version} + {/if} +
  • + {/each} +
+
+ {/each} + + {#if omitted > 0} +

And {omitted} earlier {omitted === 1 ? 'release' : 'releases'} in the full changelog.

+ {/if} +
+{/if} diff --git a/src/lib/components/UpdateDialog.svelte b/src/lib/components/UpdateDialog.svelte index a984e3b6..7ab6aef7 100644 --- a/src/lib/components/UpdateDialog.svelte +++ b/src/lib/components/UpdateDialog.svelte @@ -14,9 +14,11 @@ import { cn } from '$lib/utils.js' import { focusTrap } from '$lib/actions/focus-trap.js' import { updateCheck, updateDownload, updateStatus, updateRestart } from '$lib/api.js' - import { loadSettings } from '$lib/stores/settings.js' + import { loadSettings, updateSettings } from '$lib/stores/settings.js' + import ReleaseNotes from './ReleaseNotes.svelte' + import Logo from './Logo.svelte' import { isRevealed } from '$lib/app-reveal.js' - import { parseChangelog, releasesBetween } from '$lib/changelog.js' + import { parseChangelog, parseReleases, releasesBetween } from '$lib/changelog.js' import WhatsNewDialog from './WhatsNewDialog.svelte' let { @@ -34,6 +36,10 @@ let releaseNotes = $state('') /** The downloaded build installs by itself when Stroke quits (updates.rs). */ let applyOnQuit = $state(false) + /** The running build, for "You have v…". */ + let appVersion = $state('') + /** Settings → Download and install updates automatically, from this window too. */ + let autoUpdate = $state(loadSettings().autoUpdate) let progress = $state(0) let downloadedBytes = $state(0) let totalBytes = $state(0) @@ -105,7 +111,18 @@ return `${(bytes/(1024*1024)).toFixed(1)} MB` } - const changelog = $derived(parseChangelog(releaseNotes)) + /** + * The update's notes as releases: Nightly's feed carries CHANGELOG.md + * sections for several versions (## [x.y.z]); a stable release carries one + * version's sections without the heading. + * @type {import('$lib/changelog.js').ChangelogRelease[]} + */ + const changelog = $derived.by(() => { + const many = parseReleases(releaseNotes) + if (many.length) return many + const sections = parseChangelog(releaseNotes) + return sections.length ? [{ version: updateVersion, date: '', sections }] : [] + }) // Actionable states are true modals (dark backdrop, blocks the app); // passive states (checking / up-to-date) float without blocking. @@ -120,6 +137,7 @@ let announceTimer onMount(() => { + import('@tauri-apps/api/app').then((m) => m.getVersion()).then((v) => (appVersion = v)).catch(() => {}) // Runs in dev too: it is a version comparison, not an update check, and a // dev build that has genuinely changed version should say so. void announceNewVersion() @@ -322,12 +340,16 @@ return } adopt(info) - if (loadSettings().autoUpdate && info.applyOnQuit) { + // Automatic updates (the default) always download in the background, with + // no window: where it can, the build installs as Stroke quits; elsewhere the + // sidebar's pill offers Restart. With them off, the pill offers Update. + // Neither interrupts what is open. + if (loadSettings().autoUpdate) { await install(true) return } status = 'available' - dismissed = false + dismissed = true onupdatefound('available') } @@ -413,209 +435,112 @@ {#if visible} - +

    {#each grouped[b.id] as item, i (i)} -
  • - +
  • + + + {#each parts(item.text) as p, k (k)} {#if p.code}{p.text}{:else}{p.text}{/if} {/each} diff --git a/src/lib/components/StatusBar.svelte b/src/lib/components/StatusBar.svelte index acfd582c..2f2a58c5 100644 --- a/src/lib/components/StatusBar.svelte +++ b/src/lib/components/StatusBar.svelte @@ -386,7 +386,7 @@ }) } - const iconBtn = 'inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground' + const iconBtn = 'inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-[color,background-color,scale] duration-[120ms] ease-[var(--ease-out)] active:scale-[0.97] hover:bg-sidebar-accent/60 hover:text-foreground' /** Shared label+icon button */ const labelBtn = 'flex h-7 items-center gap-2 rounded-md px-2.5 text-ui-xs hover:bg-sidebar-accent/60 hover:text-foreground data-[state=open]:bg-sidebar-accent/60 data-[state=open]:text-foreground' @@ -897,8 +897,10 @@ {#if !sidebarWidth}{@render globalTools()}{@render sep()}{/if} - - {#if hasUpdate} + + {#if hasUpdate && !sidebarWidth} {/if} {#if notesOpen} -
    +
    {/if} {/if}
- - - + From a01f82b59bbfc7d4a2a095de6934f29289c328e6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:00:50 +0000 Subject: [PATCH 063/317] chore: version 2.8.1 (#177) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b20689ec..31281147 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.8.1] - 2026-11-14 + +### Changes +- License per account, one Update button, compact What's new, press feedback (#177) + + ## [2.8.0] - 2026-11-14 ### Changes diff --git a/package.json b/package.json index 2680cc79..4411f578 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.8.0", + "version": "2.8.1", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 29c3d22d..eb7bc216 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.8.0", + "version": "2.8.1", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From a99676180bbc00be66b52aafb12f9b6a5d057c9b Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 22:55:11 +0545 Subject: [PATCH 064/317] fix(ui): aligned connection name and workspace, smaller swatches, keyboard-first staged-changes bar (#178) Name and Workspace share a top edge and a 36px height; the select's size variant had held it at 32px. Colour swatches drop to 20px with a press. The document browser's unsaved-changes bar is a 36px pill with keycaps on Discard and Apply, and Mod+S and Alt+Backspace now work there as they do on SQL tables. --- src/lib/components/ColorSwatches.svelte | 16 +++++----- src/lib/components/ConnectionModal.svelte | 4 +-- src/lib/components/DocBrowser.svelte | 37 +++++++++++++++++++---- 3 files changed, 41 insertions(+), 16 deletions(-) diff --git a/src/lib/components/ColorSwatches.svelte b/src/lib/components/ColorSwatches.svelte index 980b1ec7..ffe530cc 100644 --- a/src/lib/components/ColorSwatches.svelte +++ b/src/lib/components/ColorSwatches.svelte @@ -31,10 +31,10 @@ aria-checked={!value} aria-label="No colour" title="No colour" - class={cn('flex size-6 items-center justify-center rounded-full text-muted-foreground ring-offset-2 ring-offset-popover transition-shadow hover:text-foreground', !value && 'ring-2 ring-ring/60')} + class={cn('flex size-5 items-center justify-center rounded-full text-muted-foreground ring-offset-2 ring-offset-popover transition-[box-shadow,scale] duration-[120ms] ease-[var(--ease-out)] hover:text-foreground active:scale-[0.94]', !value && 'ring-2 ring-ring/60')} onclick={() => onchange(null)} > - + {/if} {#each COLORS as c (c.id)} @@ -44,10 +44,10 @@ aria-checked={value === c.id} aria-label={c.label} title={c.label} - class={cn('flex size-6 items-center justify-center rounded-full ring-offset-2 ring-offset-popover transition-shadow', c.dot, value === c.id && 'ring-2 ring-ring/60')} + class={cn('flex size-5 items-center justify-center rounded-full ring-offset-2 ring-offset-popover transition-[box-shadow,scale] duration-[120ms] ease-[var(--ease-out)] active:scale-[0.94]', c.dot, value === c.id && 'ring-2 ring-ring/60')} onclick={() => onchange(c.id)} > - {#if value === c.id}{/if} + {#if value === c.id}{/if} {/each} -
- - {pendingEditCount.toLocaleString()} unsaved {pendingEditCount === 1 ? 'change' : 'changes'} - - +
{/if} From 84653c54ac86ba6f50d31e07634a35b1a9bfaf4b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:10:24 +0000 Subject: [PATCH 065/317] chore: version 2.8.2 (#178) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31281147..25a175c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.8.2] - 2026-11-14 + +### Changes +- Aligned connection fields, smaller swatches, keyboard-first staged-changes bar (#178) + + ## [2.8.1] - 2026-11-14 ### Changes diff --git a/package.json b/package.json index 4411f578..1a7604a5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.8.1", + "version": "2.8.2", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index eb7bc216..5b564699 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.8.1", + "version": "2.8.2", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From c5fe77dbed54fefa5b4928736b929e7264fe4f52 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sat, 14 Nov 2026 23:06:25 +0545 Subject: [PATCH 066/317] feat(appearance): choose the corner notifications appear in; compact SQLite switch (#179) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → Appearance gets Notifications: a small window with four corners to pick from, saved on this device. Top corners clear the titlebar and bottom ones the status bar, toasts leave toward their own edge, and the cards are slightly tighter. The SQLite Local file / Remote switch is a compact segmented control instead of a bar across the whole form. --- src/App.svelte | 9 +++++- src/lib/components/ConnectionModal.svelte | 12 ++++---- src/lib/components/SettingsDialog.svelte | 35 ++++++++++++++++++++++ src/lib/components/ui/sonner/sonner.svelte | 14 +++++---- src/lib/stores/toast-position.js | 29 ++++++++++++++++++ 5 files changed, 87 insertions(+), 12 deletions(-) create mode 100644 src/lib/stores/toast-position.js diff --git a/src/App.svelte b/src/App.svelte index 54fcfbb7..eb787b84 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -1,4 +1,5 @@ - + +
@@ -4290,17 +4290,17 @@ {:else if dbType === "libsql"}
diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 12ea2cd7..582ba898 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -1,4 +1,5 @@ + +
+
+ {#if phase === 'checking'} + Checking for a newer version + {:else if phase === 'current'} + No newer version yet. A fix may already be on the download page. + {:else if phase === 'available'} + Stroke {version} is available + {#if current} (this is {current}){/if} + {:else if phase === 'downloading'} + Downloading {version}{progress != null ? ` · ${progress}%` : ''} + {:else if phase === 'installing'} + Installing and restarting + {:else} + Couldn't update from here{problem ? `: ${problem}` : ''} + {/if} +
+ + {#if phase === 'available'} + + {:else if phase === 'checking' || phase === 'downloading' || phase === 'installing'} +
From a4a30dce1545c47e480afa0eefe5e097cdb22336 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:02:47 +0000 Subject: [PATCH 081/317] chore: version 2.9.0 (#186) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a8ff6c..7097a31f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.9.0] - 2026-11-15 + +### Changes +- Offer the update on the crash screen (#186) + + ## [2.8.9] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 7378e31a..9fb2a42d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.8.9", + "version": "2.9.0", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 6074ba63..fc4ff779 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.8.9", + "version": "2.9.0", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 1ca20ba2cab9dc09229dc9feca8749d37d308351 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 09:50:01 +0545 Subject: [PATCH 082/317] feat(trial): calmer trial-ended screen (#187) One centered column instead of a card: the mark, a short heading, Get Stroke Pro and a full-width "I bought it, check again", a quiet license key link, then who is signed in with a Switch button. The account block replaces the footer's "Use a different account" so it reads as the account, not an exit. --- src/lib/components/TrialExpiredScreen.svelte | 130 +++++++++---------- 1 file changed, 62 insertions(+), 68 deletions(-) diff --git a/src/lib/components/TrialExpiredScreen.svelte b/src/lib/components/TrialExpiredScreen.svelte index 97dc822f..dcb952c4 100644 --- a/src/lib/components/TrialExpiredScreen.svelte +++ b/src/lib/components/TrialExpiredScreen.svelte @@ -121,94 +121,88 @@ style="background: radial-gradient(ellipse 55% 50% at 50% -8%, color-mix(in oklch, var(--primary) 9%, transparent), transparent 70%);" >
-
-
-
-
- -
-
- Stroke Pro - - {#if activated}Active{:else if $isSignedIn && email}{email}{:else}Trial ended{/if} - -
-
+
+
+ +
-
- {#if activated} -

Welcome to Stroke

-

- {activatedVia === 'account' ? 'Stroke Pro is on your account.' : 'Your license is active.'} Opening your workspace. -

- {:else if mode === 'key'} -

Enter your license key

-

It was sent to your email after purchase.

- {:else if $isSignedIn} -

Your free trial has ended

-

This account doesn't have Stroke Pro yet. Upgrade to keep working, or check again if you just bought it.

- {:else} -

Your free trial has ended

-

Sign in to continue. A purchase on stroke.click shows up in your account.

- {/if} -
+
+ {#if activated} +

Welcome to Stroke Pro

+

+ {activatedVia === 'account' ? 'Pro is on your account.' : 'Your license is active.'} Opening your workspace. +

+ {:else if mode === 'key'} +

Enter your license key

+

It's in the email you got after buying.

+ {:else} +

Your trial has ended

+

+ {$isSignedIn + ? 'Get Stroke Pro to keep working. Already bought it? Check again and it unlocks right away.' + : 'Sign in with the account you bought Stroke Pro with, or get it on stroke.click.'} +

+ {/if} +
+
{#if mode === 'key' || (activated && activatedVia === 'key')} { activatedVia = 'key'; activated = true }} onactivated={finish} /> {:else if activated} -
+
Loading
{:else if $isSignedIn} -
- -
- - -
-
+ + {:else} -
- - -
- {/if} - - {#if !activated} -
- - Your connections and settings are saved on this device. -
+ + {/if}
-
+ {#if !activated} {#if mode === 'key'} - - {:else if $isSignedIn} - {:else} - {/if} - +
+ {/if} + + {#if !activated} +

+ + Connections and settings stay on this device. +

+ -
+ {/if}
From e13762ba443ffd689fce19fe031828b44c025e60 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:05:14 +0000 Subject: [PATCH 083/317] chore: version 2.9.1 (#187) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7097a31f..a8e2da77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.9.1] - 2026-11-15 + +### Changes +- Calmer trial-ended screen (#187) + + ## [2.9.0] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 9fb2a42d..73cdb202 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.9.0", + "version": "2.9.1", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index fc4ff779..ece0e1f6 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.9.0", + "version": "2.9.1", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From db1ec58125edef07a2c4c59f181956e153c5fbd0 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 09:52:12 +0545 Subject: [PATCH 084/317] fix(ui): press feedback only on compact buttons (#188) The app-wide press rule matched every *-trigger slot, and a right-click menu's trigger wraps a whole area: clicking anywhere in the sidebar, the tab bar or the data grid shrank the whole panel. It now matches only real buttons (icon buttons, the shared Button, menu, popover, select and dialog triggers) and skips wide ones (w-full, size-full, flex-1, inset-0). --- src/app.css | 53 ++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/src/app.css b/src/app.css index 9e636b34..22b0bc8a 100644 --- a/src/app.css +++ b/src/app.css @@ -1574,23 +1574,58 @@ pre code, .ai-gen-sweep, .ai-gen-bar, .ai-gen-node, .ai-gen-line, .ai-gen-dots i { animation: none; } } -/* Press feedback, app-wide. Icon buttons (anything sized with a size-* - utility), the shared Button and every menu or popover trigger shrink to 0.97 - while held, so a click always answers, including the titlebar's avatar and - gear. Full-width rows are left alone: a 3% shrink across a whole row reads - as a jump, not a press. A component's own active:scale-* (a utility) wins - over this base rule. */ +/* Press feedback, app-wide: compact controls only. Icon buttons (sized + with a size-* utility), the shared Button and menu, popover and select + triggers shrink to 0.97 while held, so a click always answers. + + Only real +

Connections

+ + {#if savedQuery} + {savedMatches.length} of {savedInWs.length} + {/if}
@@ -3620,8 +3623,10 @@ nobody has picked yet. --> +
{#if step === "pick"} -
- -
+ +
@@ -5155,7 +5158,9 @@
-
+ +
-
- - - {#if onclose} - - {/if} -
- {:else} + third of a short pane was chrome before any output. The docked + terminal (⌘J) has the same strip: its actions used to float over the + output, on top of the install notice's button. -->
{/if} + {#if onpopout} + + {/if} {#if onclose}
- {/if}
- navigate('docker')}> + navigate('docker')}> Docker diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 76f2cdf2..f2f07038 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -32,6 +32,8 @@ connectDynamo, testCouch, connectCouch, + testElastic, + connectElastic, testCassandra, connectCassandra, testFirestore, @@ -179,6 +181,8 @@ { id: "dynamodb", label: "DynamoDB", desc: "AWS key-value and document tables" }, { id: "mongodb", label: "MongoDB", desc: "Document database, also Atlas (mongodb+srv)" }, { id: "couchdb", label: "CouchDB", desc: "JSON documents over HTTP, Mango queries" }, + { id: "elasticsearch", label: "Elasticsearch", desc: "Search and analytics, also Elastic Cloud" }, + { id: "opensearch", label: "OpenSearch", desc: "Search and analytics, also Amazon OpenSearch Service" }, { id: "cassandra", label: "Cassandra", desc: "Wide-column store, also ScyllaDB (CQL)" }, { id: "firestore", label: "Firestore", desc: "Google Cloud document database" }, ], @@ -276,6 +280,8 @@ "dynamodb", "mongodb", "couchdb", + "elasticsearch", + "opensearch", "cassandra", "firestore", ]; @@ -416,6 +422,13 @@ // custom endpoint (DynamoDB Local) are optional. // CouchDB: the server URL; user and password reuse the shared fields. let couchUrl = $state("http://localhost:5984"); + // Elasticsearch / OpenSearch: the server URL (shared with CouchDB's field), + // a login or an API key, and whether to accept a self-signed certificate. + let esAuth = $state(/** @type {'basic' | 'apikey'} */ ("basic")); + let esApiKey = $state(""); + let esInsecure = $state(false); + /** What the last test said the server is, e.g. "OpenSearch 2.17.0". */ + let esServer = $state(""); // Workspace and colour label of the connection being edited or created. let connColor = $state(/** @type {string | null} */ (null)); let connWorkspace = $state(DEFAULT_WORKSPACE_ID); @@ -1020,6 +1033,14 @@ return { type: "cassandra", name: nm, hosts: cqlHosts.trim(), user: user.trim(), password, keyspace: cqlKeyspace.trim() }; if (dbType === "couchdb") return { type: "couchdb", name: nm, url: couchUrl.trim(), user: user.trim(), password }; + if (dbType === "elasticsearch" || dbType === "opensearch") + return { + type: dbType, + name: nm, + url: couchUrl.trim(), + ...(esAuth === "apikey" ? { apiKey: esApiKey.trim(), user: "", password: "" } : { user: user.trim(), password, apiKey: "" }), + insecure: esInsecure, + }; if (dbType === "dynamodb") return { type: "dynamodb", @@ -1137,7 +1158,14 @@ } connColor = conn.color ?? null; connWorkspace = conn.workspaceId ?? DEFAULT_WORKSPACE_ID; - couchUrl = conn.type === "couchdb" ? (conn.url ?? "http://localhost:5984") : "http://localhost:5984"; + couchUrl = + conn.type === "couchdb" ? (conn.url ?? "http://localhost:5984") + : conn.type === "elasticsearch" || conn.type === "opensearch" ? (conn.url ?? "http://localhost:9200") + : "http://localhost:5984"; + esAuth = conn.apiKey ? "apikey" : "basic"; + esApiKey = conn.apiKey ?? ""; + esInsecure = !!conn.insecure; + esServer = ""; awsAuth = conn.accessKeyId ? "keys" : "profile"; awsProfile = conn.profile ?? ""; awsKeyId = conn.accessKeyId ?? ""; @@ -1362,6 +1390,8 @@ valkey: { database: "0", user: "" }, dynamodb: { database: "", user: "" }, couchdb: { database: "", user: "admin" }, + elasticsearch: { database: "", user: "elastic" }, + opensearch: { database: "", user: "admin" }, cassandra: { database: "", user: "" }, firestore: { database: "", user: "" }, mongodb: { database: "", user: "" }, @@ -1387,6 +1417,11 @@ if (user === "" || user === prev.user) user = next.user ?? ""; if (id === "sqlite-memory" || id === "duckdb-memory") filePath = ":memory:"; if (id === "duckdb") filePath = ""; + // The HTTP engines share one URL field; move it to the new engine's port + // while it still holds the previous one's local default. + const HTTP_DEFAULT = /** @type {Record} */ ({ couchdb: "http://localhost:5984", elasticsearch: "http://localhost:9200", opensearch: "http://localhost:9200" }); + if (HTTP_DEFAULT[id] && (!couchUrl.trim() || Object.values(HTTP_DEFAULT).includes(couchUrl.trim()))) couchUrl = HTTP_DEFAULT[id]; + esServer = ""; error = ""; testOk = false; connectionUri = ""; @@ -1413,6 +1448,7 @@ // a username, and a Turso URL carries its token in the query string. if (t === "redis" || t === "valkey") return "redis"; if (t === "libsql") return "libsql"; + if (t === "couchdb" || t === "elasticsearch" || t === "opensearch") return "couchdb"; return "postgres"; } @@ -1733,7 +1769,7 @@ if (conn.type === "posthog") return conn.projectId ? `project ${conn.projectId}` : "—"; // Redis has no database name worth showing; where it lives is the useful bit. if (engineFamily(conn.type) === "redis") return conn.host ? `${conn.host}${conn.port ? `:${conn.port}` : ""}` : "—"; - if (conn.type === "couchdb") return conn.url || "—"; + if (conn.type === "couchdb" || conn.type === "elasticsearch" || conn.type === "opensearch") return conn.url || "—"; if (conn.type === "mongodb") return conn.uri ? uriHost(conn.uri) : "—"; if (conn.type === "firestore") return [conn.projectId, conn.auth === "emulator" ? "emulator" : null].filter(Boolean).join(" · ") || "—"; if (conn.type === "cassandra") return [conn.hosts, conn.keyspace].filter(Boolean).join(" · ") || "—"; @@ -1830,6 +1866,7 @@ if (engineFamily(conn.type) === "redis") return connectRedis(conn); if (conn.type === "dynamodb") return connectDynamo(conn); if (conn.type === "couchdb") return connectCouch(conn); + if (conn.type === "elasticsearch" || conn.type === "opensearch") return connectElastic(conn); if (conn.type === "cassandra") return connectCassandra(conn); if (conn.type === "firestore") return connectFirestore(conn); if (conn.type === "mongodb") return connectMongo(conn); @@ -2119,6 +2156,9 @@ return { uri: `mongodb://${auth}${hp}/${d.user ? "?authSource=admin" : ""}`, database: d.database }; case "couchdb": return { url: `http://${hp}`, user: d.user, password: d.password }; + case "elasticsearch": + case "opensearch": + return { url: `http://${hp}`, user: d.user, password: d.password, apiKey: "", insecure: false }; case "cassandra": return { hosts: hp, user: d.user, password: d.password, keyspace: "" }; case "dynamodb": @@ -2141,7 +2181,7 @@ ? { encrypt: true, trustCert: true } : d.engine === "clickhouse" ? { secure: false } - : ["oracle", "mongodb", "couchdb", "cassandra", "dynamodb"].includes(d.engine) + : ["oracle", "mongodb", "couchdb", "elasticsearch", "opensearch", "cassandra", "dynamodb"].includes(d.engine) ? {} : { ssl: false }; return /** @type {LocalTarget} */ ({ @@ -2322,6 +2362,12 @@ else if (engineFamily(p.type) === "redis") await testRedis(p); else if (p.type === "dynamodb") await testDynamo(p); else if (p.type === "couchdb") await testCouch(p); + else if (p.type === "elasticsearch" || p.type === "opensearch") { + const info = await testElastic(p); + esServer = `${info.flavor === "opensearch" ? "OpenSearch" : "Elasticsearch"} ${info.version}`.trim(); + // A server that answers as the other engine: switch the label to match. + if (info.flavor !== p.type && dbType === p.type) dbType = info.flavor; + } else if (p.type === "cassandra") await testCassandra(p); else if (p.type === "firestore") await testFirestore(p); else if (p.type === "mongodb") await testMongo(p); @@ -2549,7 +2595,7 @@ return filePath || ":memory:"; if (dbType === "libsql") return uriHost(libsqlUrl.replace(/^libsql:/, "https:")) || libsqlUrl || "—"; if (dbType === "d1") return databaseId ? `${databaseId.slice(0, 8)}…` : "—"; - if (dbType === "couchdb") return couchUrl || "—"; + if (dbType === "couchdb" || dbType === "elasticsearch" || dbType === "opensearch") return couchUrl || "—"; if (dbType === "cassandra") return cqlHosts || "—"; if (dbType === "firestore") return fsProject || "—"; if (dbType === "mongodb") return uriHost(mongoUri) || "—"; @@ -4857,6 +4903,60 @@ Leave the user blank for a server without a login (admin party).

+ + {:else if dbType === "elasticsearch" || dbType === "opensearch"} +
+ + + {#if esServer} +

Server: {esServer}

+ {/if} +
+
+ Sign in with +
+ {#each [{ v: "basic", l: "User and password" }, { v: "apikey", l: "API key" }] as m (m.v)} + + {/each} +
+
+ {#if esAuth === "basic"} +
+
+ + +
+
+ + +
+
+

+ Leave the user blank for a server with security turned off. +

+ {:else} +
+ + +

The encoded key Kibana shows once when the key is created.

+
+ {/if} + + {:else if dbType === "dynamodb"}
diff --git a/src/lib/components/Onboarding.svelte b/src/lib/components/Onboarding.svelte index 1f626678..1c929940 100644 --- a/src/lib/components/Onboarding.svelte +++ b/src/lib/components/Onboarding.svelte @@ -28,7 +28,7 @@ const ENGINES = [ ['postgres', 'Postgres'], ['mysql', 'MySQL'], ['mariadb', 'MariaDB'], ['sqlite', 'SQLite'], ['mssql', 'SQL Server'], ['oracle', 'Oracle'], ['cockroachdb', 'CockroachDB'], ['duckdb', 'DuckDB'], ['clickhouse', 'ClickHouse'], - ['mongodb', 'MongoDB'], ['redis', 'Redis'], ['valkey', 'Valkey'], ['dynamodb', 'DynamoDB'], ['couchdb', 'CouchDB'], + ['mongodb', 'MongoDB'], ['redis', 'Redis'], ['valkey', 'Valkey'], ['dynamodb', 'DynamoDB'], ['couchdb', 'CouchDB'], ['elasticsearch', 'Elasticsearch'], ['opensearch', 'OpenSearch'], ['cassandra', 'Cassandra'], ['firestore', 'Firestore'], ['d1', 'Cloudflare D1'], ['supabase', 'Supabase'], ['neon', 'Neon'], ['planetscale', 'PlanetScale'], ['turso', 'Turso'], ['prisma', 'Prisma Postgres'], ['tidb', 'TiDB Cloud'], ['upstash', 'Upstash'], ['railway', 'Railway'], diff --git a/src/lib/components/SidebarTree.svelte b/src/lib/components/SidebarTree.svelte index 7081cedd..f696dba2 100644 --- a/src/lib/components/SidebarTree.svelte +++ b/src/lib/components/SidebarTree.svelte @@ -6,8 +6,8 @@ */ const places = new Map() - /** NoSQL engines whose collections expand: MongoDB and CouchDB into indexes, Cassandra and DynamoDB into typed key columns, keys and indexes. Firestore and Redis stay flat. */ - const SHAPED_NOSQL = new Set(['mongodb', 'couchdb', 'cassandra', 'dynamodb']) + /** NoSQL engines whose collections expand: MongoDB and CouchDB into indexes, Cassandra and DynamoDB into typed key columns, keys and indexes, Elasticsearch/OpenSearch into mapped fields. Firestore and Redis stay flat. */ + const SHAPED_NOSQL = new Set(['mongodb', 'couchdb', 'cassandra', 'dynamodb', 'elasticsearch', 'opensearch']) const PER_TABLE_INDEXES = new Set(['mongodb', 'couchdb', 'dynamodb']) diff --git a/src/lib/components/SqlEditor.svelte b/src/lib/components/SqlEditor.svelte index 449e076a..dee5231f 100644 --- a/src/lib/components/SqlEditor.svelte +++ b/src/lib/components/SqlEditor.svelte @@ -285,7 +285,7 @@ // Query languages that aren't SQL: the SQL lint and formatter would mark // valid statements as errors (db.users.find(...)) or rewrite them. - const NOT_SQL = new Set(['redis', 'valkey', 'mongodb', 'couchdb', 'firestore']) + const NOT_SQL = new Set(['redis', 'valkey', 'mongodb', 'couchdb', 'elasticsearch', 'opensearch', 'firestore']) const isSql = $derived(!NOT_SQL.has(dialect)) /** @param {import('@codemirror/state').EditorState} state */ diff --git a/src/lib/components/StatusBar.svelte b/src/lib/components/StatusBar.svelte index 2f2a58c5..7e06946c 100644 --- a/src/lib/components/StatusBar.svelte +++ b/src/lib/components/StatusBar.svelte @@ -269,7 +269,7 @@ ) // Document and key-value stores (other than Redis, which has numbered dbs) // have no "current database" to show or switch; the chip only said "No database". - const NO_DB_ENGINES = new Set(['dynamodb', 'couchdb', 'cassandra', 'firestore', 'valkey', 'mongodb']) + const NO_DB_ENGINES = new Set(['dynamodb', 'couchdb', 'elasticsearch', 'opensearch', 'cassandra', 'firestore', 'valkey', 'mongodb']) const hideDbChip = $derived(NO_DB_ENGINES.has(connection?.type ?? '') && !currentDbLabel) /** Key of the active db, used to mark the current row. */ const currentDbKey = $derived(currentDatabaseKey(connection)) @@ -323,6 +323,8 @@ : connection?.type === 'valkey' ? 'Valkey' : connection?.type === 'dynamodb' ? 'DynamoDB' : connection?.type === 'couchdb' ? 'CouchDB' + : connection?.type === 'elasticsearch' ? 'Elasticsearch' + : connection?.type === 'opensearch' ? 'OpenSearch' : connection?.type === 'cassandra' ? 'Cassandra' : connection?.type === 'firestore' ? 'Firestore' : connection?.type === 'mongodb' ? 'MongoDB' diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 832a81f8..d475067d 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -3,7 +3,7 @@ import { onMount, onDestroy, untrack, tick } from 'svelte' import { fade } from 'svelte/transition' import { traceInteraction } from '$lib/perf.js' - import { couchAdapter, cassandraAdapter, firestoreAdapter, mongoAdapter, uriHost } from '$lib/doc-adapters.js' + import { couchAdapter, cassandraAdapter, elasticAdapter, firestoreAdapter, mongoAdapter, uriHost } from '$lib/doc-adapters.js' import { queryLanguageFor } from '$lib/ai-query-languages.js' import { setQueryEngine } from '$lib/ai.js' import { revealApp, isRevealed } from '$lib/app-reveal.js' @@ -325,6 +325,9 @@ connectRedis, connectDynamo, connectCouch, + connectElastic, + elasticRequest, + elasticImport, couchRequest, connectCassandra, connectFirestore, @@ -592,7 +595,7 @@ const isRedis = $derived(dbType === 'redis') const isDynamo = $derived(dbType === 'dynamodb') /** Document / wide-column engines browsed with DocBrowser. */ - const isDoc = $derived(dbType === 'couchdb' || dbType === 'cassandra' || dbType === 'firestore' || dbType === 'mongodb') + const isDoc = $derived(dbType === 'couchdb' || dbType === 'cassandra' || dbType === 'firestore' || dbType === 'mongodb' || dbType === 'elasticsearch' || dbType === 'opensearch') /** Key-value and document engines have their own page and none of the relational UI. */ const isKV = $derived(isRedis || isDynamo || isDoc) // AI replies on a NoSQL connection get Run buttons on blocks in its own language. @@ -602,6 +605,7 @@ /** The engine's adapter for DocBrowser. */ const docAdapter = $derived( dbType === 'couchdb' ? couchAdapter(couchRequest) + : dbType === 'elasticsearch' || dbType === 'opensearch' ? elasticAdapter(elasticRequest, dbType, { pick: pickImportFile, preview: mongoImportPreview, run: elasticImport }) : dbType === 'mongodb' ? mongoAdapter({ collections: mongoCollections, describe: mongoDescribe, find: mongoFind, count: mongoCount, save: mongoSave, remove: mongoDelete, explain: mongoExplain, schema: mongoSchema, indexes: { list: mongoIndexes, create: mongoCreateIndex, drop: mongoDropIndex }, updateField: mongoUpdateField, aggregate: mongoAggregate, import: { pick: pickImportFile, preview: mongoImportPreview, run: mongoImport } }) : dbType === 'firestore' ? firestoreAdapter(firestoreRequest, { projectId: connection?.projectId ?? '', database: connection?.database ?? '' }) : dbType === 'cassandra' ? cassandraAdapter({ tables: cassandraTables, describe: cassandraDescribe, page: cassandraPage, save: cassandraSave, remove: cassandraDelete }) @@ -7373,7 +7377,7 @@ let rowSearch = $state('') // open the keyspace workspace instead of the welcome tab + tables sidebar. const fam = engineFamily(conn.type) const connIsDynamo = fam === 'dynamodb' - const connIsDoc = fam === 'couchdb' || fam === 'cassandra' || fam === 'firestore' || fam === 'mongodb' + const connIsDoc = fam === 'couchdb' || fam === 'cassandra' || fam === 'firestore' || fam === 'mongodb' || fam === 'elasticsearch' || fam === 'opensearch' const connIsRedis = fam === 'redis' docCollection = '' dynamoTable = '' @@ -7627,6 +7631,7 @@ let rowSearch = $state('') else if (engineFamily(last.type) === 'redis') await withTimeout(connectRedis(last)) else if (last.type === 'dynamodb') await withTimeout(connectDynamo(last)) else if (last.type === 'couchdb') await withTimeout(connectCouch(last)) + else if (last.type === 'elasticsearch' || last.type === 'opensearch') await withTimeout(connectElastic(last)) else if (last.type === 'cassandra') await withTimeout(connectCassandra(last)) else if (last.type === 'firestore') await withTimeout(connectFirestore(last)) else if (last.type === 'mongodb') await withTimeout(connectMongo(last)) @@ -8037,6 +8042,7 @@ let rowSearch = $state('') else if (engineFamily(conn.type) === 'redis') await connectRedis(conn) else if (conn.type === 'dynamodb') await connectDynamo(conn) else if (conn.type === 'couchdb') await connectCouch(conn) + else if (conn.type === 'elasticsearch' || conn.type === 'opensearch') await connectElastic(conn) else if (conn.type === 'cassandra') await connectCassandra(conn) else if (conn.type === 'firestore') await connectFirestore(conn) else if (conn.type === 'mongodb') await connectMongo(conn) diff --git a/src/lib/components/TerminalPage.svelte b/src/lib/components/TerminalPage.svelte index bce4a477..d3da9a5e 100644 --- a/src/lib/components/TerminalPage.svelte +++ b/src/lib/components/TerminalPage.svelte @@ -113,7 +113,7 @@ /** Engines with no interactive CLI get the app's own SQL prompt instead. */ const BUILTIN_REPL = new Set(['d1', 'dynamodb']) /** Engines whose CLI is not SQL: no SQL prompt to fall back to. */ - const NON_SQL = new Set(['redis', 'valkey', 'keydb', 'dragonfly', 'mongodb', 'couchdb', 'cassandra', 'firestore']) + const NON_SQL = new Set(['redis', 'valkey', 'keydb', 'dragonfly', 'mongodb', 'couchdb', 'elasticsearch', 'opensearch', 'cassandra', 'firestore']) /** A result set from executeSqlMulti as the prompt's table shape. @param {string} sql */ async function sqlRows(sql) { diff --git a/src/lib/connection-provider.js b/src/lib/connection-provider.js index 7e798d3c..a2f1c22b 100644 --- a/src/lib/connection-provider.js +++ b/src/lib/connection-provider.js @@ -65,6 +65,8 @@ const ENGINE_SHORT = { valkey: 'Valkey', dynamodb: 'DynamoDB', couchdb: 'CouchDB', + elasticsearch: 'Elasticsearch', + opensearch: 'OpenSearch', cassandra: 'Cassandra', firestore: 'Firestore', mongodb: 'MongoDB', diff --git a/src/lib/connection-uri.js b/src/lib/connection-uri.js index 001185e3..e5f175a4 100644 --- a/src/lib/connection-uri.js +++ b/src/lib/connection-uri.js @@ -329,6 +329,8 @@ export function parseOracleUri(uri) { */ export function parseConnectionUri(type, uri) { if (type === 'couchdb') return parseCouchUri(uri) + // Same shape: a server URL with the login moved to its own fields. + if (type === 'elasticsearch' || type === 'opensearch') return parseCouchUri(uri) if (type === 'cassandra') return parseCassandraUri(uri) if (type === 'sqlite') return parseSqliteUri(uri) if (type === 'mysql') return parseMysqlUri(uri) @@ -526,6 +528,9 @@ function detectByScheme(scheme, s, host, port) { if (/\.turso\.io$/i.test(host) || scheme.startsWith('ws')) return { type: 'libsql', uriType: 'libsql' } if (/clickhouse/i.test(host) || port === 8123 || port === 8443) return { type: 'clickhouse', uriType: 'clickhouse' } if (/couch|cloudant/i.test(host) || port === 5984) return { type: 'couchdb', uriType: 'couchdb' } + // Amazon OpenSearch Service domains end in .es.amazonaws.com. + if (/opensearch|\.(es|aoss)\.amazonaws\.com$/i.test(host)) return { type: 'opensearch', uriType: 'couchdb' } + if (/elastic|\.es\.[a-z0-9-]+\.(gcp|azure|aws)\./i.test(host) || port === 9200 || port === 9243) return { type: 'elasticsearch', uriType: 'couchdb' } return null case 'duckdb': return { type: 'duckdb', uriType: 'sqlite' } @@ -700,7 +705,9 @@ export function connectionUrl(p) { return p.uri || '' case 'libsql': return p.url ? `${p.url}${p.authToken ? `${p.url.includes('?') ? '&' : '?'}authToken=${enc(p.authToken)}` : ''}` : '' - case 'couchdb': { + case 'couchdb': + case 'elasticsearch': + case 'opensearch': { const m = /^(https?:\/\/)(.*)$/i.exec(p.url || '') return m ? `${m[1]}${auth(p.user, p.password)}${m[2]}` : p.url || '' } diff --git a/src/lib/db-capabilities.js b/src/lib/db-capabilities.js index c9e178f5..f7fd1f1c 100644 --- a/src/lib/db-capabilities.js +++ b/src/lib/db-capabilities.js @@ -8,7 +8,7 @@ * no triggers." These flags let the UI say *why* a section is empty ("Triggers * require PostgreSQL") and let callers skip pointless round-trips entirely. * - * @typedef {'postgres'|'mysql'|'sqlite'|'d1'|'libsql'|'clickhouse'|'duckdb'|'mssql'|'oracle'|'redis'|'dynamodb'|'couchdb'|'cassandra'|'firestore'|'mongodb'|'posthog'} Engine + * @typedef {'postgres'|'mysql'|'sqlite'|'d1'|'libsql'|'clickhouse'|'duckdb'|'mssql'|'oracle'|'redis'|'dynamodb'|'couchdb'|'elasticsearch'|'opensearch'|'cassandra'|'firestore'|'mongodb'|'posthog'} Engine */ /** @@ -96,6 +96,8 @@ const ENGINE_LABEL = /** @type {Record} */ ({ valkey: 'Valkey', dynamodb: 'DynamoDB', couchdb: 'CouchDB', + elasticsearch: 'Elasticsearch', + opensearch: 'OpenSearch', cassandra: 'Cassandra', firestore: 'Firestore', mongodb: 'MongoDB', @@ -125,7 +127,7 @@ export function unsupportedReason(featureLabel, feature) { * this set. * @type {Set} */ -export const KEY_VALUE_ENGINES = new Set(['redis', 'dynamodb', 'couchdb', 'cassandra', 'firestore', 'mongodb']) +export const KEY_VALUE_ENGINES = new Set(['redis', 'dynamodb', 'couchdb', 'cassandra', 'firestore', 'mongodb', 'elasticsearch', 'opensearch']) /** @param {string | null | undefined} engine */ export function isKeyValue(engine) { diff --git a/src/lib/db-icons.js b/src/lib/db-icons.js index b44ebf09..40436af0 100644 --- a/src/lib/db-icons.js +++ b/src/lib/db-icons.js @@ -37,6 +37,8 @@ export const BRAND_MARKS = { dynamodb: { d: 'M16.606 20.705v-2.371c-1.263 1.082-3.884 1.795-7.066 1.795-3.184 0-5.805-.714-7.068-1.797v2.369c0 1.168 2.903 2.47 7.068 2.47 4.16 0 7.06-1.3 7.066-2.466zm.001-6.765l.817-.005v.005c0 .517-.258.998-.75 1.441.601.54.75 1.071.75 1.449a1661.7 1661.7 0 0 0 0 3.87c0 1.881-3.389 3.3-7.884 3.3-4.471 0-7.846-1.404-7.88-3.27a583.119 583.119 0 0 1-.003-3.909c.001-.375.15-.9.745-1.437-.592-.538-.743-1.062-.746-1.435v-3.892c.002-.377.153-.903.747-1.438-.593-.54-.744-1.062-.747-1.435 0-1.357-.002-2.735.002-3.897C1.674 1.412 5.056 0 9.54 0c2.159 0 4.233.356 5.689.974l-.315.766c-1.36-.58-3.319-.91-5.374-.91-4.165 0-7.067 1.3-7.067 2.47 0 1.168 2.902 2.47 7.067 2.47.115 0 .222 0 .334-.005l.033.828c-.122.006-.245.006-.367.006-3.184 0-5.805-.714-7.068-1.798v2.38c.005.45.45.843.821 1.093 1.116.736 3.114 1.239 5.34 1.342l-.037.829c-2.254-.105-4.23-.59-5.5-1.332-.318.245-.623.573-.623.952 0 1.168 2.902 2.47 7.067 2.47.411 0 .812-.014 1.203-.042l.06.826c-.41.03-.833.045-1.263.045-3.184 0-5.805-.713-7.068-1.797v2.368c.005.462.449.855.821 1.104 1.275.842 3.67 1.366 6.247 1.366h.182v.83H9.54c-2.62 0-4.99-.507-6.444-1.359-.317.245-.623.574-.623.954 0 1.168 2.902 2.47 7.067 2.47 4.159 0 7.058-1.298 7.066-2.465v-.007c0-.377-.303-.705-.62-.948a5.732 5.732 0 0 1-.662.336l-.316-.764c.3-.128.56-.266.776-.412.376-.254.823-.651.823-1.1zm4.377-6.915h-2.717a.406.406 0 0 1-.332-.173.42.42 0 0 1-.055-.375l1.204-3.597h-5.403l-2.583 4.974h2.623c.128 0 .248.06.325.164a.418.418 0 0 1 .069.36l-2.249 8.365zm1.249-.128l-10.89 11.608a.408.408 0 0 1-.498.075.418.418 0 0 1-.192-.471l2.534-9.426h-2.766a.407.407 0 0 1-.349-.2.418.418 0 0 1-.012-.407l3.014-5.804a.408.408 0 0 1 .36-.222h6.22c.132 0 .256.065.332.174a.422.422 0 0 1 .055.374l-1.204 3.598h3.1c.164 0 .31.099.375.251a.422.422 0 0 1-.08.45zM3.085 20.723a8.107 8.107 0 0 0 1.72.72l.233-.794a7.32 7.32 0 0 1-1.546-.645zm1.72-5.984l.233-.795a7.262 7.262 0 0 1-1.546-.646l-.407.72a8.051 8.051 0 0 0 1.72.72zm-1.72-7.427l.407-.719c.418.244.939.462 1.546.646l-.232.794a8.046 8.046 0 0 1-1.72-.72Z', hex: '#4053D6' }, mongodb: { d: 'M17.193 9.555c-1.264-5.58-4.252-7.414-4.573-8.115-.28-.394-.53-.954-.735-1.44-.036.495-.055.685-.523 1.184-.723.566-4.438 3.682-4.74 10.02-.282 5.912 4.27 9.435 4.888 9.884l.07.05A73.49 73.49 0 0111.91 24h.481c.114-1.032.284-2.056.51-3.07.417-.296.604-.463.85-.693a11.342 11.342 0 003.639-8.464c.01-.814-.103-1.662-.197-2.218zm-5.336 8.195s0-8.291.275-8.29c.213 0 .49 10.695.49 10.695-.381-.045-.765-1.76-.765-2.405z', hex: '#47A248' }, couchdb: { d: 'M19.5 14.625c0 .995-.524 1.482-1.5 1.5H6c-.976-.018-1.5-.505-1.5-1.5s.524-1.482 1.5-1.5h12c.976.018 1.5.505 1.5 1.5m-1.5 2.25H6c-.976.018-1.5.505-1.5 1.5s.524 1.482 1.5 1.5h12c.976-.018 1.5-.505 1.5-1.5s-.524-1.482-1.5-1.5m3.75-8.248v-.001c-.976.017-1.5.504-1.5 1.499v8.25c0 .995.524 1.482 1.5 1.5v-.002c1.464-.052 2.25-1.514 2.25-4.498v-3.75c0-1.99-.786-2.964-2.25-2.998m-19.5-.001C.786 8.662 0 9.637 0 11.626v3.75c0 2.984.786 4.446 2.25 4.498v.001c.976-.017 1.5-.504 1.5-1.499v-8.25c0-.995-.524-1.482-1.5-1.5m19.5-.75c0-2.486-1.31-3.705-3.75-3.748v-.002H6v.002c-2.44.043-3.75 1.262-3.75 3.748v.001c1.464.026 2.25.757 2.25 2.249s.786 2.223 2.25 2.249v.001h10.5v-.001c1.464-.026 2.25-.757 2.25-2.249s.786-2.223 2.25-2.249z', hex: '#E42528' }, + elasticsearch: { d: 'M13.394 0C8.683 0 4.609 2.716 2.644 6.667h15.641a4.77 4.77 0 0 0 3.073-1.11c.446-.375.864-.785 1.247-1.243l.001-.002A11.974 11.974 0 0 0 13.394 0zM1.804 8.889a12.009 12.009 0 0 0 0 6.222h14.7a3.111 3.111 0 1 0 0-6.222zm.84 8.444C4.61 21.283 8.684 24 13.395 24c3.701 0 7.011-1.677 9.212-4.312l-.001-.002a9.958 9.958 0 0 0-1.247-1.243 4.77 4.77 0 0 0-3.073-1.11z', hex: '#00BFB3' }, + opensearch: { d: 'M23.1515 8.8125a.8484.8484 0 0 0-.8484.8485c0 6.982-5.6601 12.6421-12.6421 12.6421a.8485.8485 0 0 0 0 1.6969C17.5802 24 24 17.5802 24 9.661a.8485.8485 0 0 0-.8485-.8485Zm-5.121 5.4375c.816-1.3311 1.6051-3.1058 1.4498-5.5905-.3216-5.1468-4.9832-9.0512-9.3851-8.6281C8.372.1971 6.6025 1.6017 6.7598 4.1177c.0683 1.0934.6034 1.7386 1.473 2.2348.8279.4722 1.8914.7713 3.097 1.1104 1.4563.4096 3.1455.8697 4.4438 1.8265 1.5561 1.1467 2.6198 2.4759 2.2569 4.9606Zm-16.561-9C.6535 6.581-.1355 8.3558.0197 10.8405c.3216 5.1468 4.9832 9.0512 9.385 8.6281 1.7233-.1657 3.4927-1.5703 3.3355-4.0863-.0683-1.0934-.6034-1.7386-1.4731-2.2348-.8278-.4722-1.8913-.7713-3.0969-1.1104-1.4563-.4096-3.1455-.8697-4.4438-1.8265-1.5561-1.1467-2.6198-2.476-2.257-4.9606Z', hex: '#005EB8' }, cassandra: { d: 'M10.374 10.53a3.102 3.102 0 0 1-.428-.222l.555.143c0 .02-.01.036-.01.055l-.117.025zm-.283 1.506-.315.253.852-1.079-1.078.391c.002.017.009.033.009.05a.57.57 0 0 1-.184.42c.102.217.228.424.375.616a3.2 3.2 0 0 1 .34-.651zm.717-2.347-.652-.82a.427.427 0 0 1-.506.162c-.054.073-.083.162-.13.24l1.258.463c.011-.015.019-.031.03-.045zm-1.666.444c-.07.314-.087.637-.05.956a.566.566 0 0 1 .451.475l.946-.606c-.067-.022-.126-.06-.191-.088l-1.119-.08.64-.14a3.186 3.186 0 0 1-.668-.554l-.01.037zM20.1 11.648c-.164.202.833 1.022.833 1.022s-1.654-1.022-2.234-.72c-.278.144.574.811 1.175 1.242-.428-.274-.982-.571-1.175-.408-.328.277 1.565 2.549 1.565 2.549s-2.145-2.322-2.36-2.209c-.214.114.593 1.224.593 1.224s-1.06-1.16-1.35-.959c-.29.202 1.514 3.218 1.514 3.218s-1.956-3.091-2.763-2.574c1.268 2.782.795 3.18.795 3.18s-.162-2.839-1.742-2.764c-.795.038.379 2.12.379 2.12s-1.08-1.902-1.8-1.864c1.326 2.51.854 3.53.854 3.53s.219-2.143-1.58-3.336c.682.606-.427 3.336-.427 3.336s.976-4.023-.719-3.256c-.268.121-.019 2.007-.019 2.007s-.34-2.158-.851-2.045c-.298.066-1.893 2.99-1.893 2.99s1.306-3.16.908-3.027c-.29.096-.833 1.4-.833 1.4s.265-1.287 0-1.363c-.264-.075-1.74 1.363-1.74 1.363s1.097-1.287.908-1.552c-.287-.402-.623-.42-1.022-.265-.581.226-1.363 1.287-1.363 1.287s.78-1.074.643-1.476c-.219-.647-2.46 1.249-2.46 1.249s1.325-1.25 1.022-1.514c-.303-.265-1.947-.183-2.46-.185-1.515-.004-2.039-.36-2.498-.724 1.987.997 3.803-.151 6.094.494l.21.06c-1.3-.558-2.144-1.378-2.226-2.354-.036-.416.074-.827.297-1.222.619-.4 1.29-.773 2.06-1.095a4 4 0 0 0-.064.698c0 2.44 2.203 4.417 4.92 4.417s4.92-1.977 4.92-4.417c0-.45-.083-.881-.223-1.29 1.431.404 2.45.968 3.132 1.335.022.092.045.184.053.279.024.274-.018.547-.11.814.095-.147.198-.288.28-.445.367-.997 1.855.227 1.855.227s-1.085-.454-1.06-.24c.026.215 1.628.96 1.628.96s-1.45-.455-1.362-.114c.088.34 1.817 1.703 1.817 1.703s-1.956-1.489-2.12-1.287zm-7.268 2.65.042-.008-.06.01zM9.256 9.753c.12.13.26.234.396.343l.927-.029-1.064-.788c-.093.154-.195.303-.26.474Zm10.62 3.44c.3.215.54.373.54.373s-.24-.181-.54-.374zM7.507 8.617c-.14.229-.214.492-.215.76a3.99 3.99 0 0 0 2.358 3.64c0-.005.002-.01.003-.014a3.19 3.19 0 0 1-.58-.788c-.648.099-.926-.794-.336-1.08a3.174 3.174 0 0 1 .138-1.388 3.162 3.162 0 0 1-.52-1.36c-.296.07-.579.147-.848.23Zm1.488.82c.108-.24.243-.46.402-.661a.435.435 0 0 1 .568-.557c.077-.059.166-.099.248-.15a16.17 16.17 0 0 0-1.727.284c.114.388.272.76.509 1.084Zm2.285 3.928c1.4 0 2.633-.723 3.344-1.816a3.399 3.399 0 0 0-1.265-.539l-.297-.023.916.9-1.197-.467.704 1.078-1.074-.832-.012.006.347 1.278-.596-1.134-.098 1.33-.401-1.326-.472 1.261.114-1.359c-.006-.002-.01-.006-.015-.008l-.814 1.154.286-1.067c-.34.322-.605.713-.781 1.146.095.102.197.198.303.29.322.083.66.128 1.008.128zm10.145-4.434c.971-.567 1.716-1.955 1.716-1.955s-1.893 1.955-3.205 1.665c1.186-.934 1.766-2.549 1.766-2.549s-1.506 2.325-2.448 2.423c1.086-.959 1.54-2.322 1.54-2.322s-1.237 1.817-2.196 1.944c1.287-1.161 1.338-1.893 1.338-1.893s-1.781 2.302-2.499 1.943c.858-.934 1.439-2.12 1.439-2.12s-1.489 2.019-1.893 1.69c-.277-.05.454-.958.454-.958s-.908.807-1.16.606c.454-.278 1.236-1.64 1.236-1.64S16 7.505 15.621 7.304l.731-1.483s-.73 1.483-1.715 1.23c.454-.58.63-1.112.63-1.112s-.756 1.213-1.69.885c-.22-.077.273-.635.273-.635s-.626.61-1.055.534c-.43-.076.025-.858.025-.858s-.757 1.186-.908 1.136c-.152-.05.075-.833.075-.833s-.555.908-.858.858c-.302-.05 0-.934 0-.934s-.328.984-.58.909c-.252-.076-.303-.656-.303-.656s-.068.788-.429.858c-2.725.53-5.728 1.69-9.489 5.45C3.887 10.738 5.3 7.91 11.962 7.659c5.044-.191 7.399 2.137 8.177 2.17C22.51 9.93 24 7.633 24 7.633s-1.489 1.716-2.574 1.3zm-7.74.872-.608.464v.001l.054.003a3.35 3.35 0 0 0 .554-.468zm1.583-.426c0-.536-.237-.929-.594-1.217a3.178 3.178 0 0 1-.165.825.393.393 0 0 1-.328.681c-.154.233-.34.445-.549.63l.661.034-.995.237c-.025.018-.045.041-.07.058a3.194 3.194 0 0 1 1.536.691c.32-.574.504-1.235.504-1.94zM10.99 7.996a3.5 3.5 0 0 0-.785.46.427.427 0 0 1-.013.357l.885.643.023-.016-.36-1.262.627 1.12c.018-.006.04-.006.058-.011l-.02-1.251.398 1.163.477-1.15.016 1.268c.004.001.007.005.012.007l.713-1.005-.363 1.218.009.01 1.04-.69-.759 1.05.002.005.95-.34c.012-.016.028-.029.041-.045a.395.395 0 0 1 .394-.632 3.43 3.43 0 0 0 .27-.784 13.99 13.99 0 0 0-2.798-.168c-.286.011-.55.033-.817.053Z', hex: '#1287B1' }, firestore: { d: 'M19.455 8.369c-.538-.748-1.778-2.285-3.681-4.569-.826-.991-1.535-1.832-1.884-2.245a146 146 0 0 0-.488-.576l-.207-.245-.113-.133-.022-.032-.01-.005L12.57 0l-.609.488c-1.555 1.246-2.828 2.851-3.681 4.64-.523 1.064-.864 2.105-1.043 3.176-.047.241-.088.489-.121.738-.209-.017-.421-.028-.632-.033-.018-.001-.035-.002-.059-.003a7.46 7.46 0 0 0-2.28.274l-.317.089-.163.286c-.765 1.342-1.198 2.869-1.252 4.416-.07 2.01.477 3.954 1.583 5.625 1.082 1.633 2.61 2.882 4.42 3.611l.236.095.071.025.003-.001a9.59 9.59 0 0 0 2.941.568q.171.006.342.006c1.273 0 2.513-.249 3.69-.742l.008.004.313-.145a9.63 9.63 0 0 0 3.927-3.335c1.01-1.49 1.577-3.234 1.641-5.042.075-2.161-.643-4.304-2.133-6.371m-7.083 6.695c.328 1.244.264 2.44-.191 3.558-1.135-1.12-1.967-2.352-2.475-3.665-.543-1.404-.87-2.74-.974-3.975.48.157.922.366 1.315.622 1.132.737 1.914 1.902 2.325 3.461zm.207 6.022c.482.368.99.712 1.513 1.028-.771.21-1.565.302-2.369.273a8 8 0 0 1-.373-.022c.458-.394.869-.823 1.228-1.279zm1.347-6.431c-.516-1.957-1.527-3.437-3.002-4.398-.647-.421-1.385-.741-2.194-.95.011-.134.026-.268.043-.4.014-.113.03-.216.046-.313.133-.689.332-1.37.589-2.025.099-.25.206-.499.321-.74l.004-.008c.177-.358.376-.719.61-1.105l.092-.152-.003-.001c.544-.851 1.197-1.627 1.942-2.311l.288.341c.672.796 1.304 1.548 1.878 2.237 1.291 1.549 2.966 3.583 3.612 4.48 1.277 1.771 1.893 3.579 1.83 5.375-.049 1.395-.461 2.755-1.195 3.933-.694 1.116-1.661 2.05-2.8 2.708-.636-.318-1.559-.839-2.539-1.599.79-1.575.952-3.28.479-5.072zm-2.575 5.397c-.725.939-1.587 1.55-2.09 1.856-.081-.029-.163-.06-.243-.093l-.065-.026c-1.49-.616-2.747-1.656-3.635-3.01-.907-1.384-1.356-2.993-1.298-4.653.041-1.19.338-2.327.882-3.379.316-.07.638-.114.96-.131l.084-.002c.162-.003.324-.003.478 0 .227.011.454.035.677.07.073 1.513.445 3.145 1.105 4.852.637 1.644 1.694 3.162 3.144 4.515z', hex: '#FFA000' }, oracle: { d: 'M16.412 4.412h-8.82a7.588 7.588 0 0 0-.008 15.176h8.828a7.588 7.588 0 0 0 0-15.176zm-.193 12.502H7.786a4.915 4.915 0 0 1 0-9.828h8.433a4.914 4.914 0 1 1 0 9.828z', hex: '#C74634' }, diff --git a/src/lib/doc-adapters.js b/src/lib/doc-adapters.js index 63182ceb..e78b430d 100644 --- a/src/lib/doc-adapters.js +++ b/src/lib/doc-adapters.js @@ -1,5 +1,5 @@ // Per-engine adapters for DocBrowser.svelte: the one page that browses and -// edits CouchDB, Cassandra and Firestore. Each adapter turns that engine's API +// edits CouchDB, Cassandra, Firestore, MongoDB and Elasticsearch/OpenSearch. Each adapter turns that engine's API // into the same few verbs (list collections, load a page, save, delete). The // API calls are injected so the logic is unit-tested without Tauri. @@ -265,6 +265,157 @@ export function mongoAdapter(api) { } } +// ── Elasticsearch / OpenSearch ────────────────────────────────────────────── + +/** `from + size` past this is refused by the server (index.max_result_window). */ +export const ES_WINDOW = 10_000 + +/** + * The browser's filter as a query: empty matches everything, `{...}` is Query + * DSL, anything else is a query string (`level:error AND ms:>100`). + * @param {string} filter + */ +export function esQuery(filter) { + const f = filter.trim() + if (!f) return { match_all: {} } + if (f.startsWith('{')) { + let q + try { + q = JSON.parse(f) + } catch (e) { + throw new Error(`The filter starts with { so it's read as Query DSL, which must be JSON: ${e instanceof Error ? e.message : e}`) + } + // Accept a whole search body as well as the query inside it. + return q && typeof q === 'object' && 'query' in q ? q.query : q + } + return { query_string: { query: f } } +} + +/** + * `field:desc, other` or JSON (`[{"ts": "desc"}]`) as a search `sort`. + * @param {string | undefined} sort + */ +export function esSort(sort) { + const s = (sort ?? '').trim() + if (!s) return undefined + if (s.startsWith('[') || s.startsWith('{')) { + try { + return JSON.parse(s) + } catch (e) { + throw new Error(`Sort isn't valid JSON: ${e instanceof Error ? e.message : e}`) + } + } + return s.split(',').map((p) => p.trim()).filter(Boolean).map((p) => { + const [field, dir] = p.split(':').map((x) => x.trim()) + return dir ? { [field]: { order: dir.toLowerCase() === 'desc' ? 'desc' : 'asc' } } : field + }) +} + +/** + * A hit as a browser document: `_id` and the source. The version fields used + * for safe saves ride along as non-enumerable properties, so they don't show + * as columns or in the editor. + * @param {any} h + */ +export function esDoc(h) { + const doc = { _id: h._id, ...(h._source ?? {}) } + Object.defineProperty(doc, '__es', { value: { seq: h._seq_no, term: h._primary_term }, enumerable: false }) + return doc +} + +/** @param {Record} doc */ +function esSource(doc) { + const { _id, _index, _score, ...src } = doc + return src +} + +/** + * @param {(method: 'GET'|'POST'|'PUT'|'DELETE', path: string, body?: any) => Promise} req + * @param {'elasticsearch' | 'opensearch'} [flavor] + * @param {DocAdapter['import']} [importer] + * @returns {DocAdapter} + */ +export function elasticAdapter(req, flavor = 'elasticsearch', importer) { + return { + engine: flavor, + noun: { collection: 'Index', collections: 'Indices', item: 'Document', items: 'documents' }, + consoleLabel: 'Query DSL', + filterPlaceholder: 'level:error AND ms:>100 or {"term": {"level": "error"}}', + filterHint: 'A query string (Lucene syntax), or Query DSL as JSON; empty matches every document', + options: [{ key: 'sort', label: 'Sort', placeholder: '@timestamp:desc' }], + + async listCollections() { + const rows = await req('GET', '_cat/indices?format=json&h=index&s=index') + return rows.map((/** @type {any} */ r) => String(r.index)).filter((/** @type {string} */ n) => !n.startsWith('.')) + }, + + async describe(index) { + const [stats] = await req('GET', `_cat/indices/${enc(index)}?format=json&h=docs.count,store.size,health,pri,rep`) + const mapping = await req('GET', `${enc(index)}/_mapping`).catch(() => ({})) + const props = Object.values(mapping)[0]?.mappings?.properties ?? {} + const fields = Object.keys(props).length + return { + keys: ['_id'], + summary: [ + `${Number(stats?.['docs.count'] ?? 0).toLocaleString()} docs`, + `${fields} ${fields === 1 ? 'field' : 'fields'}`, + ...(stats?.['store.size'] ? [stats['store.size']] : []), + ...(stats?.health ? [stats.health] : []), + ], + } + }, + + async load(index, { cursor, filter, size = PAGE_SIZE, sort }) { + const from = Number(cursor) || 0 + const take = Math.min(size, ES_WINDOW - from) + if (take <= 0) return { docs: [], cursor: null } + /** @type {Record} */ + const body = { query: esQuery(filter), from, size: take, seq_no_primary_term: true } + const s = esSort(sort) + if (s) body.sort = s + const out = await req('POST', `${enc(index)}/_search`, body) + const hits = out.hits?.hits ?? [] + const total = out.hits?.total?.value ?? out.hits?.total ?? 0 + const next = from + hits.length + return { docs: hits.map(esDoc), cursor: hits.length === take && next < Math.min(total, ES_WINDOW) ? next : null } + }, + + async count(index, filter) { + const out = await req('POST', `${enc(index)}/_count`, { query: esQuery(filter) }) + return typeof out.count === 'number' ? out.count : null + }, + + idOf: (doc) => String(doc._id ?? ''), + + async save(index, next, prev) { + const id = typeof next._id === 'string' ? next._id.trim() : next._id != null ? String(next._id) : '' + const src = esSource(next) + if (!prev || id !== String(prev._id)) { + const out = id + ? await req('PUT', `${enc(index)}/_create/${enc(id)}?refresh=wait_for`, src) + : await req('POST', `${enc(index)}/_doc?refresh=wait_for`, src) + if (prev) await req('DELETE', `${enc(index)}/_doc/${enc(String(prev._id))}?refresh=wait_for`) + return esDoc({ _id: out._id, _source: src, _seq_no: out._seq_no, _primary_term: out._primary_term }) + } + // Only overwrite the version that was loaded: someone else's change in + // between is a conflict, not silently lost. + const v = /** @type {any} */ (prev).__es + const guard = v?.seq != null && v?.term != null ? `&if_seq_no=${v.seq}&if_primary_term=${v.term}` : '' + const out = await req('PUT', `${enc(index)}/_doc/${enc(id)}?refresh=wait_for${guard}`, src) + return esDoc({ _id: id, _source: src, _seq_no: out._seq_no, _primary_term: out._primary_term }) + }, + + async remove(index, doc) { + await req('DELETE', `${enc(index)}/_doc/${enc(String(doc._id))}?refresh=wait_for`) + }, + + template: () => ({ _id: '' }), + keyChangeWarning: 'The _id changed. This creates a new document and deletes the old one. Continue?', + querySeed: (index) => `GET ${index}/_search\n{\n "query": { "match_all": {} },\n "size": 50\n}`, + import: importer, + } +} + // ── Firestore ─────────────────────────────────────────────────────────────── /** @param {any} v @returns {any} Firestore typed value -> plain JSON */ diff --git a/src/lib/doc-adapters.test.js b/src/lib/doc-adapters.test.js index 01cd016c..8caa8e17 100644 --- a/src/lib/doc-adapters.test.js +++ b/src/lib/doc-adapters.test.js @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest' +import { describe, it, expect, vi } from 'vitest' import { couchAdapter, cassandraAdapter, firestoreAdapter, mongoAdapter, uriHost, docGrid, fsPlainFields, fsTypedFields, fsTyped, fsFilter, fsDoc, docColumns, docCell, humanBytes, PAGE_SIZE } from './doc-adapters.js' /** A fake CouchDB that records calls and answers from a script. */ @@ -209,3 +209,66 @@ describe('docGrid', () => { expect(g.rows[1][4]).toEqual({ k: 1 }) }) }) + +describe('elasticAdapter', async () => { + const { elasticAdapter, esQuery, esSort, esDoc, ES_WINDOW } = await import('./doc-adapters.js') + + it('reads the filter as a query string or Query DSL', () => { + expect(esQuery('')).toEqual({ match_all: {} }) + expect(esQuery('level:error')).toEqual({ query_string: { query: 'level:error' } }) + expect(esQuery('{"term": {"level": "error"}}')).toEqual({ term: { level: 'error' } }) + expect(esQuery('{"query": {"match_all": {}}, "size": 5}')).toEqual({ match_all: {} }) + expect(() => esQuery('{bad')).toThrow(/Query DSL/) + }) + + it('reads sort as field:dir or JSON', () => { + expect(esSort('')).toBeUndefined() + expect(esSort('@timestamp:desc, _id')).toEqual([{ '@timestamp': { order: 'desc' } }, '_id']) + expect(esSort('[{"ms": "asc"}]')).toEqual([{ ms: 'asc' }]) + }) + + it('keeps version fields out of the columns', () => { + const d = esDoc({ _id: '1', _source: { a: 1 }, _seq_no: 4, _primary_term: 1 }) + expect(Object.keys(d)).toEqual(['_id', 'a']) + expect(/** @type {any} */ (d).__es).toEqual({ seq: 4, term: 1 }) + }) + + it('lists indices without system ones and pages with from/size', async () => { + /** @type {any[]} */ + const calls = [] + const req = vi.fn(async (/** @type {string} */ m, /** @type {string} */ p, /** @type {any} */ b) => { + calls.push([m, p, b]) + if (p.startsWith('_cat/indices')) return [{ index: '.kibana' }, { index: 'logs' }] + if (p.endsWith('/_search')) return { hits: { total: { value: 3 }, hits: [{ _id: '1', _source: { x: 1 } }, { _id: '2', _source: { x: 2 } }] } } + return {} + }) + const a = elasticAdapter(req, 'opensearch') + expect(a.engine).toBe('opensearch') + expect(await a.listCollections()).toEqual(['logs']) + const page = await a.load('logs', { cursor: null, filter: 'x:1', size: 2, sort: 'x:desc' }) + expect(page.docs.map((d) => d._id)).toEqual(['1', '2']) + expect(page.cursor).toBe(2) + expect(calls.at(-1)[2]).toMatchObject({ from: 0, size: 2, query: { query_string: { query: 'x:1' } }, sort: [{ x: { order: 'desc' } }] }) + const last = await a.load('logs', { cursor: ES_WINDOW, filter: '', size: 100 }) + expect(last).toEqual({ docs: [], cursor: null }) + }) + + it('saves with the loaded version and moves a renamed id', async () => { + /** @type {any[]} */ + const calls = [] + const req = vi.fn(async (/** @type {string} */ m, /** @type {string} */ p, /** @type {any} */ b) => { + calls.push([m, p, b]) + return { _id: 'new', _seq_no: 9, _primary_term: 1 } + }) + const a = elasticAdapter(req) + const prev = esDoc({ _id: 'a', _source: { n: 1 }, _seq_no: 3, _primary_term: 1 }) + await a.save('logs', { ...prev, n: 2 }, prev) + expect(calls[0]).toEqual(['PUT', 'logs/_doc/a?refresh=wait_for&if_seq_no=3&if_primary_term=1', { n: 2 }]) + calls.length = 0 + await a.save('logs', { _id: 'b', n: 2 }, prev) + expect(calls.map((c) => `${c[0]} ${c[1]}`)).toEqual(['PUT logs/_create/b?refresh=wait_for', 'DELETE logs/_doc/a?refresh=wait_for']) + calls.length = 0 + await a.save('logs', { _id: '', n: 1 }, null) + expect(calls[0].slice(0, 2)).toEqual(['POST', 'logs/_doc?refresh=wait_for']) + }) +}) diff --git a/src/lib/engine-tint.js b/src/lib/engine-tint.js index b2a707f8..5c94f1db 100644 --- a/src/lib/engine-tint.js +++ b/src/lib/engine-tint.js @@ -29,6 +29,8 @@ export const ENGINE_TINT = { valkey: "text-sky-500/80", dynamodb: "text-blue-500/80", couchdb: "text-red-600/80", + elasticsearch: "text-teal-500/80", + opensearch: "text-sky-600/80", mongodb: "text-green-600/80", cassandra: "text-sky-600/80", firestore: "text-amber-500/80", diff --git a/src/lib/sql-auto-limit.js b/src/lib/sql-auto-limit.js index ca18ba7b..3a59b908 100644 --- a/src/lib/sql-auto-limit.js +++ b/src/lib/sql-auto-limit.js @@ -16,7 +16,7 @@ import { splitSqlStatements } from './sql-statements.js' /** Engines without LIMIT. */ -const NO_LIMIT_ENGINES = new Set(['mssql', 'redis', 'dynamodb', 'couchdb', 'firestore', 'mongodb', 'oracle']) +const NO_LIMIT_ENGINES = new Set(['mssql', 'redis', 'dynamodb', 'couchdb', 'elasticsearch', 'opensearch', 'firestore', 'mongodb', 'oracle']) /** Any of these at the top level leaves the statement as it is. */ const STOP_WORDS = new Set(['LIMIT', 'FETCH', 'OFFSET', 'TOP', 'INTO', 'FOR', 'FORMAT', 'SETTINGS', 'LOCK', 'PROCEDURE']) /** After WITH, the first of these says what the statement does. */ diff --git a/src/lib/sql-write.js b/src/lib/sql-write.js index fad4a6fc..6940e4ea 100644 --- a/src/lib/sql-write.js +++ b/src/lib/sql-write.js @@ -376,6 +376,23 @@ const MONGO_WRITE_RE = /\.\s*(insert|insertOne|insertMany|update|updateOne|updat /** Firestore and CouchDB shell-style writes. */ const DOC_WRITE_RE = /\.\s*(add|set|update|delete|insert|put|remove|bulkDocs|destroy|create)\s*\(/ +/** Elasticsearch endpoints that only read even when sent as a POST. */ +const ES_POST_READ_RE = /(^|\/)_(search|count|msearch|mget|explain|field_caps|validate|analyze|sql|plugins|pit|search_shards|termvectors)(\/|\?|$)/ + +/** + * A Dev Tools request that changes something: PUT, DELETE, or a POST to an + * endpoint other than search/count/SQL. Shell-style `index.search()` reads. + * @param {string} text + */ +function isEsWrite(text) { + const m = /^\s*(GET|HEAD|POST|PUT|DELETE|PATCH)\s+(\S+)/i.exec(text) + if (!m) return false + const method = m[1].toUpperCase() + if (method === 'GET' || method === 'HEAD') return false + if (method === 'POST') return !ES_POST_READ_RE.test(m[2].replace(/^\//, '')) + return true +} + /** * `isWriteSql`, knowing which language it is reading. The AI runs every engine * through one `execute_sql` tool, and the SQL rules alone let some writes @@ -397,6 +414,9 @@ export function isWriteFor(sql, engine) { case 'firestore': case 'couchdb': return DOC_WRITE_RE.test(text) + case 'elasticsearch': + case 'opensearch': + return isEsWrite(text) default: return false } diff --git a/src/lib/stores/connections.js b/src/lib/stores/connections.js index c660f804..d82dbe3f 100644 --- a/src/lib/stores/connections.js +++ b/src/lib/stores/connections.js @@ -17,7 +17,7 @@ const LAST_ID_KEY = 'stroke:last-connection-id' const DISCONNECTED_KEY = 'stroke:disconnected' /** - * @typedef {'postgres' | 'sqlite' | 'd1' | 'mysql' | 'mariadb' | 'cockroachdb' | 'libsql' | 'clickhouse' | 'duckdb' | 'mssql' | 'oracle' | 'redis' | 'valkey' | 'dynamodb' | 'couchdb' | 'cassandra' | 'firestore' | 'mongodb' | 'posthog'} DbType + * @typedef {'postgres' | 'sqlite' | 'd1' | 'mysql' | 'mariadb' | 'cockroachdb' | 'libsql' | 'clickhouse' | 'duckdb' | 'mssql' | 'oracle' | 'redis' | 'valkey' | 'dynamodb' | 'couchdb' | 'elasticsearch' | 'opensearch' | 'cassandra' | 'firestore' | 'mongodb' | 'posthog'} DbType * * @typedef {{ host: string, port?: number, username: string, privateKeyPath?: string }} SshConfig * From dbbce5aebdbac0e842219704f1995681ceb3c6ff Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:21:01 +0000 Subject: [PATCH 101/317] chore: version 2.10.0 (#196) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7630548a..c0d52774 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.10.0] - 2026-11-15 + +### Changes +- Elasticsearch and OpenSearch (#196) + + ## [2.9.9] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index d8a651f2..472625e6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.9.9", + "version": "2.10.0", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c084f28d..d0844fe4 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.9.9", + "version": "2.10.0", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 32e00fe9eb9d6a79398b8388d037feb24d4d4fe3 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 11:24:19 +0545 Subject: [PATCH 102/317] perf(grid): cheaper frames for 120Hz scrolling (#197) Measured on a 10,000-row, 24-column table (text, JSON, timestamps, uuids): - Horizontal scroll repainted every visible cell every frame. With nothing pinned it now moves the last frame sideways (header included) and draws only the uncovered strip of columns, as vertical scrolling already did. p99 8.3ms -> 3.8ms, worst 14.1 -> 5.6ms. - The header is no longer redrawn on vertical blit frames; nothing in it depends on the vertical offset. Median draw 1.8 -> 1.4ms (slow scroll), 2.5 -> 1.7ms (fling). - ctx.font is tracked in JS: reads re-serialised the font string twice a cell and sets re-parsed it even when unchanged (250ms of a 7s scroll). - Glyph widths are cached per font: the grid switches fonts several times a frame and each switch re-measured, 22 measureText calls a frame; now 0. - Truncating printable ASCII in a monospace face is arithmetic, with no measuring. Vertical blit frames match a fresh repaint pixel for pixel; horizontal ones differ by one pixel's tint at a few line junctions, which the full repaint when scrolling stops replaces. --- src/lib/components/DataTable.svelte | 184 +++++++++++++++++++++++++--- 1 file changed, 168 insertions(+), 16 deletions(-) diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index 6bed61a0..9be85ce2 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -5035,6 +5035,8 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // ever sets this, and draw() zeroes it on entry, so every other path into // draw() is a full repaint by construction. let _blitDy = 0 + /** The same for a frame that is a pure horizontal move (see draw()). */ + let _blitDx = 0 /** A hover change that arrived mid-scroll, applied when scrolling stops. @type {[number | null, string | null] | null} */ let _parkedHover = null @@ -5062,6 +5064,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // from scratch - any artifact a blit could produce lives only while the // content is still moving, and never in a resting grid. _blitDy = 0 + _blitDx = 0 scheduleDraw() return } @@ -5085,6 +5088,11 @@ import FilterX from "@lucide/svelte/icons/filter-x"; sl === _loopLastLeft && _loopLastTop >= 0 && !_loopNeedsDraw ? _scrollTop - prevVirt : 0 + // And a pure horizontal move: same vertical offset, columns slide. + _blitDx = + st === _loopLastTop && _loopLastLeft >= 0 && !_loopNeedsDraw + ? sl - _loopLastLeft + : 0 _scrollLeft = sl _loopLastTop = st _loopLastLeft = sl @@ -5260,6 +5268,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; _fonts = null _readColor = null _glyphFont = '' + _glyphWByFont.clear() _truncCacheReset() _redrawToken++ } @@ -5773,12 +5782,66 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // Re-measured automatically whenever ctx.font changes (zoom / cell vs header). let _glyphW = 0 let _glyphFont = '' + + /** + * Make a context's `font` cheap. Reading `ctx.font` re-serialises the whole + * font string on every call, and the draw loop asks for it twice per cell + * (textWidth, truncText): 250ms of a 7s scroll went to that alone. Setting + * it re-parses even when nothing changed. This keeps the last value in JS: + * reads return it, a set to the same string is skipped, and save/restore + * keep it in step with the canvas's own font stack. + * @param {CanvasRenderingContext2D} ctx + */ + function trackFont(ctx) { + const c = /** @type {any} */ (ctx) + if (c.__fontTracked) return + const desc = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'font') + if (!desc?.get || !desc.set) return + let cur = desc.get.call(ctx) + let lastSet = '' + /** @type {[string, string][]} */ + const stack = [] + Object.defineProperty(ctx, 'font', { + configurable: true, + get: () => cur, + set: (/** @type {string} */ v) => { + if (v === lastSet) return + desc.set.call(ctx, v) + lastSet = v + cur = desc.get.call(ctx) + }, + }) + const save = ctx.save.bind(ctx) + const restore = ctx.restore.bind(ctx) + ctx.save = () => { stack.push([cur, lastSet]); save() } + ctx.restore = () => { + restore() + const top = stack.pop() + if (top) [cur, lastSet] = top + } + // A canvas resize resets the context's state, font included, behind the + // setter's back; the resize path calls this to re-read it. + c.__fontReset = () => { cur = desc.get.call(ctx); lastSet = ''; stack.length = 0 } + c.__fontTracked = true + } + + /** Glyph width per font string: the grid switches between its cell, header + * and type fonts several times a frame, and each switch re-measured 'i' and + * 'W' (22 measureText calls a frame while scrolling). Cleared with the + * truncation cache when web fonts load. @type {Map} */ + const _glyphWByFont = new Map() function _syncGlyphW(/** @type {CanvasRenderingContext2D} */ ctx) { - if (ctx.font === _glyphFont) return - const a = ctx.measureText('i').width - const b = ctx.measureText('W').width - _glyphW = Math.abs(a - b) < 0.1 ? b : 0 // 0 ⇒ not monospace → fall back to measureText - _glyphFont = ctx.font + const font = ctx.font + if (font === _glyphFont) return + let w = _glyphWByFont.get(font) + if (w === undefined) { + const a = ctx.measureText('i').width + const b = ctx.measureText('W').width + w = Math.abs(a - b) < 0.1 ? b : 0 // 0 ⇒ not monospace → fall back to measureText + _glyphWByFont.set(font, w) + } + _glyphW = w + _glyphFont = font } /** Width of `str` under the active font (O(1) for monospace). */ @@ -5833,7 +5896,25 @@ import FilterX from "@lucide/svelte/icons/filter-x"; } /** The measuring half of truncText - only reached on a cache miss. */ + /** Printable ASCII: one glyph advance each in a monospace face. */ + const _ASCII_RE = /^[\x20-\x7e]*$/ + /** Width of '…' under _glyphFont (re-measured when the font changes). */ + let _ellW = 0 + let _ellFont = '' + function _truncMeasure(ctx, text, maxW, len) { + // Monospace and printable ASCII (most database values): every character is + // exactly one advance, so the cut is arithmetic and needs no measuring. A + // scroll brings a new set of strings into view every frame, and each one + // missed the cache and paid 2-3 measureText shaping passes. + if (_glyphW > 0) { + const head = text.length > 256 ? text.slice(0, Math.ceil(maxW / _glyphW) + 2) : text + if (_ASCII_RE.test(head)) { + if (_ellFont !== _glyphFont) { _ellW = ctx.measureText('…').width; _ellFont = _glyphFont } + const k = Math.max(0, Math.floor((maxW - _ellW) / _glyphW)) + return k >= len ? text : text.slice(0, k) + '…' + } + } // Only the head of a long value can ever be on screen, so only the head is // measured. measureText shapes every character it is given, and a long cell // (a 2,000-character Devanagari or markdown chunk) paid a whole-string @@ -5953,7 +6034,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; if (!ctx || !read || !canvasEl || !colorProbe) return // Drop any scroll delta seen while holding: the first real frame after a // hold is a different table and must repaint whole, never blit the old one. - if (holdPaint && _surfaceHasFrame) { _blitDy = 0; return } + if (holdPaint && _surfaceHasFrame) { _blitDy = 0; _blitDx = 0; return } _surfaceHasFrame = true if (!hasHeldFrame && columns.length > 0) hasHeldFrame = true @@ -5994,6 +6075,8 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // stuttering: not a canvas bug, starvation. const dy = _blitDy _blitDy = 0 + const dxs = _blitDx + _blitDx = 0 // Band a scheduled frame was limited to (scheduleBandDraw), or null. const band = _drawBand _drawBand = null @@ -6028,13 +6111,35 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // between rows), so only those rows are repainted and the rest of the // canvas - header included - is left as it is. Same row-band repaint the // blit uses for its strip, with the same preconditions on the body. + // Horizontal scrolling repainted every visible cell every frame (3.1ms + // median and a 14ms worst case against the vertical path's ~2ms). The same + // trick applies sideways: with nothing pinned, the whole canvas, header and + // body, is a rigid horizontal translation of the last frame, so it is moved + // by dx and only the uncovered strip of columns is drawn. Pinned columns + // stay put while the rest slides, so a table with any keeps the full paint. + const canBlitX = + !canBlit && + dy === 0 && + dxs !== 0 && + Number.isInteger(dxs) && + Math.abs(dxs) < _viewportWidth - 1 && + blitScale > 0 && + Number.isInteger(dxs * blitScale) && + geom.frozenWidth === 0 && + !_sawSkeleton && + !newRowDrafts && + visibleColumns.length > 0 + /** Columns outside [stripX0, stripX1) are skipped this frame (CSS px). */ + let stripX0 = 0 + let stripX1 = Infinity const partial = !canBlit && + !canBlitX && band !== null && !_sawSkeleton && !newRowDrafts && visibleColumns.length > 0 - if (!canBlit && !partial) _imgWanted.clear() + if (!canBlit && !canBlitX && !partial) _imgWanted.clear() // Font sizes and the layout constants (ROW_HEIGHT, HEADER_H, …) are both // ` * canvasZoom`, so text and geometry cannot land on different // zoom rungs however this cache is invalidated. Do NOT re-source either one @@ -6147,6 +6252,38 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // background (drawHeaderRow starts with a full-width fill), and everything // between is either blitted or in the strip. fillPanel(ctx, cPanel, 0, stripTop, W, stripH) + } else if (canBlitX) { + // Same exact 1:1 device-pixel copy as the vertical case, through the + // scratch surface, of the whole viewport height (the header slides too). + const devH = Math.floor(H * blitScale) + const devW = ctx.canvas.width + const kDev = dxs * blitScale + const keepDev = devW - Math.abs(kDev) + const srcX = kDev > 0 ? kDev : 0 + const dstX = kDev > 0 ? 0 : -kDev + const scratch = blitScratch(keepDev, devH) + if (scratch) { + scratch.ctx.setTransform(1, 0, 0, 1, 0, 0) + scratch.ctx.clearRect(0, 0, keepDev, devH) + scratch.ctx.drawImage(ctx.canvas, srcX, 0, keepDev, devH, 0, 0, keepDev, devH) + ctx.save() + ctx.setTransform(1, 0, 0, 1, 0, 0) + ctx.drawImage(scratch.canvas, 0, 0, keepDev, devH, dstX, 0, keepDev, devH) + ctx.restore() + } + // The uncovered strip, rounded outward, cleared, then clipped to below. + if (kDev > 0) { + stripX0 = Math.floor((dstX + keepDev) / blitScale) + stripX1 = W + } else { + stripX0 = 0 + stripX1 = Math.ceil(-dxs) + } + fillPanel(ctx, cPanel, stripX0, 0, stripX1 - stripX0, H) + ctx.save() + ctx.beginPath() + ctx.rect(stripX0, 0, stripX1 - stripX0, H) + ctx.clip() } else if (partial) { stripTop = Math.max(HEADER_H, Math.floor(band[0])) stripH = Math.max(0, Math.ceil(Math.min(H, band[1])) - stripTop) @@ -6275,6 +6412,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // 150-cell viewport paid ~3000 graph reads a frame for values that cannot // change mid-frame. Read once here, then drawCell only touches this object. cols: geom.cols, pinnedCols, scrollLeft: _scrollLeft, viewportWidth: W, + stripX0, stripX1, padX: CELL_PAD_X, iconHit: ICON_HIT, zoom: canvasZoom, fonts: _fonts, highlightActiveRow: $appHighlightActiveRow, nameToActualIdx: _nameToActualIdx, colCache: _colCache, @@ -6336,7 +6474,10 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // ── Header (pinned) - skip entirely when no columns visible ─────────── // A band frame never touches it: the rows it repaints are clipped below it. - if (visibleColumns.length > 0 && !partial) { + // A vertical blit frame leaves it too: the copy never touches the header + // band, nothing in it depends on the vertical offset, and anything that + // would change it (hover, sort, selection) forces a full frame instead. + if (visibleColumns.length > 0 && !partial && !canBlit) { drawHeaderRow(ctx, { W, cPanel, cFg, cMuted, cGrid, cBorder, cMutedBg, cAccent, cPrimary, cRing, AMBER, AMBER_FG, BLUE_FG, RED, usedW, @@ -6346,8 +6487,10 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // body context carried `fonts`, this one did not, and only the one // branch gated on the gutter being enabled ever touched it. fonts: _fonts, + stripX0, stripX1, }) } + if (canBlitX) ctx.restore() // Now that the visible set is known, drop the backlog the viewport has moved // past and start whatever decodes fit in the remaining slots. @@ -6624,12 +6767,16 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // condition re-entered it once per column per row. const cols = c.cols const sl = c.scrollLeft - for (let ci = c.firstColIdx, nc = cols.length, vpw = c.viewportWidth; ci < nc; ci++) { + // On a horizontal blit frame only the columns crossing the uncovered strip + // are drawn (c.stripX0/X1; 0/Infinity on every other frame). + const right = Math.min(c.viewportWidth, c.stripX1) + const left = Math.max(0, c.stripX0) + for (let ci = c.firstColIdx, nc = cols.length; ci < nc; ci++) { const col = cols[ci] if (col.pinned) continue const dx = col.contentX - sl - if (dx >= vpw) break - if (dx + col.w <= 0) continue + if (dx >= right) break + if (dx + col.w <= left) continue drawCell(ctx, idx, col, dx, ry, rh, c) } @@ -6641,7 +6788,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; } } - drawRowGutters(ctx, idx, -_scrollLeft, ry, rh, c) + if (gutterWidth - sl > left && -sl < right) drawRowGutters(ctx, idx, -sl, ry, rh, c) // Staged-delete decoration: a left red bar + a strikethrough across the row. if (isPendingDelete) { @@ -6678,7 +6825,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; for (let vi = 0; vi < _vexprLayout.length; vi++) { const vc = _vexprLayout[vi] const cellX = vc.x - _scrollLeft - if (cellX + vc.w <= 0 || cellX >= _viewportWidth) continue + if (cellX + vc.w <= left || cellX >= right) continue fillPanel(ctx, c.cPanel, cellX, ry, vc.w, rh) const isVHov = hoveredRow === idx && hoveredColName === vc.hoverKey if (isVHov) { ctx.fillStyle = withAlpha(c.cMutedBg, 0.15); ctx.fillRect(cellX, ry, vc.w, rh) } @@ -6705,7 +6852,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; const vc = virtualRelCols[vi] const cw = _vrelLayout[vi].w const cellX = _vrelLayout[vi].x - _scrollLeft - if (cellX + cw <= 0 || cellX >= _viewportWidth) continue + if (cellX + cw <= left || cellX >= right) continue // Panel base, then the row's own tint on top: painting only the panel left // the relationship columns dark while the rest of a selected row lit up, // so the highlight stopped mid-row. @@ -7199,12 +7346,15 @@ import FilterX from "@lucide/svelte/icons/filter-x"; ctx.fillStyle = withAlpha(c.cMutedBg, 0.38) ctx.fillRect(0, 0, c.W, HEADER_H) + // Horizontal blit frame: only the uncovered strip's headers. + const hRight = Math.min(c.W, c.stripX1 ?? Infinity) + const hLeft = Math.max(0, c.stripX0 ?? 0) // Non-pinned headers. Ordered by ascending contentX → break past the right edge. for (const col of geom.cols) { if (col.pinned) continue const dx = col.contentX - _scrollLeft - if (dx >= c.W) break - if (dx + col.w <= 0) continue + if (dx >= hRight) break + if (dx + col.w <= hLeft) continue drawHeaderCell(ctx, col, dx, c) } @@ -7552,6 +7702,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // canvas and the visible one would stay black. Binding to canvasEl every call // keeps _ctx and the on-screen canvas in lockstep. _ctx = canvas.getContext('2d') + if (_ctx) trackFont(_ctx) const cssW = Math.max(1, Math.round(_viewportWidth)) // Height is not simply the viewport's. Resizing the backing store on WebKit // swaps the new bitmap in a frame before the new box size lands, so the @@ -7576,6 +7727,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; canvas.height = bh resized = true _surfaceHasFrame = false + if (_ctx) /** @type {any} */ (_ctx).__fontReset?.() } // canvas.width/height assignment resets the transform, so always (re)apply it. if (_ctx) _ctx.setTransform(dpr, 0, 0, dpr, 0, 0) From 8787129b429d15a09ef89b6b0f1003e021cd6d0f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:39:30 +0000 Subject: [PATCH 103/317] chore: version 2.10.1 (#197) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0d52774..7f92c6f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.10.1] - 2026-11-15 + +### Changes +- Smoother grid scrolling (120Hz budget) (#197) + + ## [2.10.0] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 472625e6..cbd6f5cb 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.10.0", + "version": "2.10.1", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d0844fe4..19242757 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.10.0", + "version": "2.10.1", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From d156ecef459f650fd150f8e109291786a6522cf9 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 11:57:11 +0545 Subject: [PATCH 104/317] Diagram and schema diff redesign, faster terminal start, / hints, fonts (#198) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: / keycap on every search field it focuses The sidebar, history, search page and workspaces fields show a / keycap while empty and unfocused, like Settings. CSS only (peer-placeholder-shown, peer-focus), so no field needed focus state of its own. * fix(fonts): Linux weight bump only for bundled faces; kerning on everywhere * perf(terminal): look up the client while idle; a benchmark for the start The first terminal of a session found its CLI and spawned --version while you waited; on Windows that lookup also scans the Program Files installs. It now runs in idle time right after connecting, so the open hits the cache. The login-shell PATH was already resolved at launch. terminal_start_bench (ignored) times each step: here the login shell took 67ms (bash) and sqlite3 --version 9ms; a zsh with a version manager is typically 0.5-3s for the shell step alone. * feat(erd): cleaner cards; small schemas open whole - Keys are a glyph before the column name (key for primary, link for foreign) instead of pk/fk chips after the type. The chips cost the type 40 units, so numeric(10,2) and timestamptz cut off; types now get up to 132. The header has a table glyph, and the legend uses the same glyphs. - A schema of up to 30 tables always opens fitted. It used to anchor at the readable zoom and leave the far tables (users, here) off screen. - Cards are 256 wide (was 300) and the default rank gap 120 (was 150), so a 9-table schema fits at ~0.6 zoom with full rows instead of the text-less overview. * feat(schema-diff): Myers line diff, word highlights, expandable context - The DDL diff is Myers' O((N+M)D) after trimming the common head and tail (src/lib/line-diff.js). It replaced an N×M LCS table (4M cells for a 2,000-line pair) assembled with an O(n²) unshift; a 20,000-line schema with three edits now diffs in well under 200ms (tested). - A changed line marks the part that changed (numeric(10,2) -> (12,2) lights 10 and 12), and a trailing comma gained by a new last column is not a change. - Collapsed unchanged runs open on click. Table statuses come from one map per diff instead of three scans per row; add/remove counts once per table. - A cleaner unified view: status pill, accent edge on changed lines, two line-number gutters. Snapshot cards no longer truncate their date to "No…" (the hidden Base/Compare buttons took the room). --- src-tauri/src/db/terminal.rs | 21 +++ src/app.css | 13 +- src/lib/components/EntityRelationPage.svelte | 8 +- src/lib/components/ErdCanvas.svelte | 101 +++++++++-- src/lib/components/QueryHistoryPanel.svelte | 4 +- src/lib/components/SchemaTimelinePage.svelte | 181 +++++++++---------- src/lib/components/SearchPage.svelte | 4 +- src/lib/components/Sidebar.svelte | 4 +- src/lib/components/StudioShell.svelte | 15 ++ src/lib/components/WorkspacesManager.svelte | 4 +- src/lib/line-diff.js | 159 ++++++++++++++++ src/lib/line-diff.test.js | 69 +++++++ src/lib/stores/erd-settings.js | 2 +- 13 files changed, 464 insertions(+), 121 deletions(-) create mode 100644 src/lib/line-diff.js create mode 100644 src/lib/line-diff.test.js diff --git a/src-tauri/src/db/terminal.rs b/src-tauri/src/db/terminal.rs index e0106823..46ee5fed 100644 --- a/src-tauri/src/db/terminal.rs +++ b/src-tauri/src/db/terminal.rs @@ -1250,6 +1250,27 @@ fn write_loop(mut writer: Box, keystrokes: mpsc::Receiver client_version(b).await, None => None }; + println!("{names:?}: find {find:?}, version {:?} -> {:?} {:?}", t.elapsed(), found, v); + } + } + use super::*; #[cfg(target_os = "linux")] diff --git a/src/app.css b/src/app.css index e46bc8eb..a014878d 100644 --- a/src/app.css +++ b/src/app.css @@ -534,10 +534,21 @@ html[data-os="linux"] { --window-radius: 8px; } 'antialiased' forces consistent grayscale AA regardless of the user's fontconfig setup; bumping weight to 450 restores stroke visibility lost without subpixels. */ html[data-os="linux"] { - font-weight: 450; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } + /* The bump is for the bundled faces only. The System preset is the desktop's + own font (Cantarell, Noto Sans, Ubuntu), already tuned for its renderer, + and at 450 it read heavier than every other window. */ + html[data-os="linux"]:not([data-font="apple"]) { + font-weight: 450; + } + /* Small UI text: let the face's own kerning and contextual forms apply on + every platform (WebKitGTK and WebView2 left kerning off below ~14px). */ + html { + font-kerning: normal; + font-feature-settings: "kern" 1, "calt" 1; + } body { /* `clip`, not `hidden`: hidden still makes a scroll container, and a focus() diff --git a/src/lib/components/EntityRelationPage.svelte b/src/lib/components/EntityRelationPage.svelte index 1517481f..dbad879d 100644 --- a/src/lib/components/EntityRelationPage.svelte +++ b/src/lib/components/EntityRelationPage.svelte @@ -8,6 +8,7 @@ import Search from '@lucide/svelte/icons/search' import LayoutDashboard from '@lucide/svelte/icons/layout-dashboard' import KeyRound from '@lucide/svelte/icons/key-round' + import Link2 from '@lucide/svelte/icons/link-2' import Link from '@lucide/svelte/icons/link' import X from '@lucide/svelte/icons/x' import ChevronDown from '@lucide/svelte/icons/chevron-down' @@ -93,7 +94,7 @@ ] // ── Config ──────────────────────────────────────────────────────────────── - const NODE_W = 300 + const NODE_W = 256 const ROW_H = 30 const HDR_H = 48 const PAD_B = 10 @@ -2501,8 +2502,9 @@ {#if nodes.length > 0}
- PK - FK + + + diff --git a/src/lib/components/ErdCanvas.svelte b/src/lib/components/ErdCanvas.svelte index e1d8835a..890dc642 100644 --- a/src/lib/components/ErdCanvas.svelte +++ b/src/lib/components/ErdCanvas.svelte @@ -243,7 +243,10 @@ } const bw = x1 - x0 || 1, bh = y1 - y0 || 1 const zFit = Math.min(cssW / bw, cssH / bh) * (1 - 0.12) - if (zFit >= READABLE_ZOOM) { + // A small schema always opens whole: anchoring it at the readable zoom cut + // the tables at the far end off screen, and the one you were looking for + // was often among them. The readable-zoom anchor is for big schemas. + if (zFit >= READABLE_ZOOM || (nodes.length <= 30 && zFit >= 0.4)) { fit(0.12, ms) return } @@ -1075,10 +1078,12 @@ nameW -= bw + 8 } if (zoom >= LOD_ROWS) { + drawTableGlyph(p.x + 16, p.y + HDR_H / 2 - 6, c('mfg', 0.7)) + forgetStyle() setFont(`600 14.5px ${FONT_SANS}`) setFill(c('fg', 1)) ctx.textAlign = 'left' - fillClipped(d.name ?? '', p.x + 16, p.y + HDR_H / 2, nameW, 14.5) + fillClipped(d.name ?? '', p.x + 38, p.y + HDR_H / 2, nameW - 22, 14.5) // Column count, quiet, at the header's right edge. if (!isFocus && !inCount && nameW > 120) { setFont(FONT_TYPE) @@ -1127,36 +1132,46 @@ // A key into a hub names the hub. That relationship has no line of its // own (see hubEdges), so the row is where it is read. const hubRef = isFk && !isPk ? hubRefOf(col.foreignKey) : null - const badge = isPk ? 'pk' : hubRef ? `→ ${hubRef}` : isFk ? 'fk' : '' - let bw = badge ? 26 : 0 - if (hubRef) { setFont(FONT_BADGE); bw = Math.min(110, Math.ceil(ctx.measureText(badge).width) + 14) } - const typeRight = p.x + NODE_W - (badge ? bw + 26 : 16) - const nameRight = showTypes ? typeRight - 4 : p.x + NODE_W - (badge ? bw + 20 : 16) + // Keys are a glyph in a slot before the name (key for primary, link for + // foreign), not a "pk"/"fk" chip after the type: the chips took 40 units + // from the type, which then cut off at numeric(1… and timestamp…. + if (isPk) drawKeyGlyph(p.x + 21, midY, PK_INK, zoom) + else if (isFk) drawLinkGlyph(p.x + 21, midY, FK_INK) + forgetStyle() + // A key into a hub names the hub (that relationship has no line). + let refW = 0 + if (hubRef) { + setFont(FONT_TYPE) + refW = Math.min(110, Math.ceil(ctx.measureText(`→ ${hubRef}`).width) + 8) + } + const typeRight = p.x + NODE_W - 14 - refW + const nameX = p.x + 36 + let typeW = 0 + if (showTypes) { + setFont(FONT_TYPE) + typeW = Math.min(132, ctx.measureText(String(col.dataType ?? '')).width) + } + const nameRight = showTypes ? typeRight - typeW - 10 : typeRight // Column name. setFont(isPk ? FONT_ROW_PK : FONT_ROW) setFill(isPk ? PK_NAME : isFk ? FK_NAME : c('fg', 0.82)) ctx.textAlign = 'left' - fillClipped(col.name ?? '', p.x + 16, midY, nameRight - (p.x + 16), 12) + fillClipped(col.name ?? '', nameX, midY, nameRight - nameX, 12) - // Data type. + // Data type, whole where it fits (up to 132 units). if (showTypes) { setFont(FONT_TYPE) setFill(c('mfg', 0.6)) ctx.textAlign = 'right' - fillClipped(String(col.dataType ?? ''), typeRight, midY, 72, 11, true) + fillClipped(String(col.dataType ?? ''), typeRight, midY, 132, 11, true) } - // PK / FK badge. - if (badge) { - const bx = p.x + NODE_W - bw - 12 - roundRect(bx, cy + 6, bw, ROW_H - 12, 3) - setFill(isPk ? PK_WASH : FK_WASH) - ctx.fill() - setFont(FONT_BADGE) - setFill(isPk ? PK_INK : FK_INK) - ctx.textAlign = 'center' - ctx.fillText(badge, bx + bw / 2, midY + 0.5) + if (hubRef) { + setFont(FONT_TYPE) + setFill(FK_INK) + ctx.textAlign = 'right' + fillClipped(`→ ${hubRef}`, p.x + NODE_W - 14, midY, refW, 11, true) } } @@ -1175,6 +1190,52 @@ ctx.globalAlpha = 1 } + /** A key glyph (primary key), 12 world units, centred at cx, cy. */ + function drawKeyGlyph(/** @type {number} */ cx, /** @type {number} */ cy, /** @type {string} */ color, /** @type {number} */ zoom) { + ctx.save() + ctx.strokeStyle = color + ctx.lineWidth = 1.5 + ctx.lineCap = 'round' + ctx.beginPath() + ctx.arc(cx - 2.5, cy - 1.5, 3, 0, Math.PI * 2) + ctx.moveTo(cx - 0.4, cy + 0.6); ctx.lineTo(cx + 4.5, cy + 5.5) + ctx.moveTo(cx + 2.6, cy + 3.6); ctx.lineTo(cx + 4.2, cy + 2) + ctx.stroke() + ctx.restore() + void zoom + } + + /** A link glyph (foreign key): two offset rounded links. */ + function drawLinkGlyph(/** @type {number} */ cx, /** @type {number} */ cy, /** @type {string} */ color) { + ctx.save() + ctx.strokeStyle = color + ctx.lineWidth = 1.5 + ctx.lineCap = 'round' + ctx.beginPath() + ctx.moveTo(cx - 1, cy - 3.5); ctx.lineTo(cx + 1, cy - 3.5) + ctx.arc(cx + 1, cy - 1, 2.5, -Math.PI / 2, Math.PI / 2) + ctx.lineTo(cx - 1, cy + 1.5) + ctx.moveTo(cx + 1, cy + 3.5); ctx.lineTo(cx - 1, cy + 3.5) + ctx.arc(cx - 1, cy + 1, 2.5, Math.PI / 2, Math.PI * 1.5) + ctx.lineTo(cx + 1, cy - 1.5) + ctx.stroke() + ctx.restore() + } + + /** A small table glyph for the card header. */ + function drawTableGlyph(/** @type {number} */ x, /** @type {number} */ y, /** @type {string} */ color) { + ctx.save() + ctx.strokeStyle = color + ctx.lineWidth = 1.4 + roundRect(x, y, 13, 12, 2.5) + ctx.stroke() + ctx.beginPath() + ctx.moveTo(x, y + 4); ctx.lineTo(x + 13, y + 4) + ctx.moveTo(x + 5, y + 4); ctx.lineTo(x + 5, y + 12) + ctx.stroke() + ctx.restore() + } + /** * Draw monospace text clipped to a max pixel width (ellipsis by char count). * @param {string} text @param {number} x @param {number} y @param {number} maxW @param {number} size @param {boolean} [rightAlign] diff --git a/src/lib/components/QueryHistoryPanel.svelte b/src/lib/components/QueryHistoryPanel.svelte index b8fe883c..602ae314 100644 --- a/src/lib/components/QueryHistoryPanel.svelte +++ b/src/lib/components/QueryHistoryPanel.svelte @@ -1,4 +1,5 @@ @@ -553,16 +548,16 @@
- {fmtDate(snap.capturedAt)} + {fmtDate(snap.capturedAt)} - {tableCount} tables + {tableCount} tables @@ -570,7 +565,7 @@ onclick={() => { afterId = snap.id }} class={cn( 'h-5 shrink-0 rounded-full px-2 text-ui-3xs transition-colors', - isAfter ? 'bg-foreground text-background' : 'text-muted-foreground opacity-0 group-hover:opacity-100 hover:bg-background/60 hover:text-foreground', + isAfter ? 'bg-foreground text-background' : 'hidden text-muted-foreground group-hover:inline-block hover:bg-background/60 hover:text-foreground', )} title="Compare against the baseline" >Compare @@ -997,55 +992,57 @@ {#snippet DdlDiff(tableKey)} {@const status = getTableStatus(diff, tableKey)} - {@const statusColor = status === 'added' ? 'text-success' : status === 'removed' ? 'text-destructive' : 'text-warning'} - {@const addCount = selectedDdlDiff?.filter((l) => l.type === 'add').length ?? 0} - {@const removeCount = selectedDdlDiff?.filter((l) => l.type === 'remove').length ?? 0} - -
- - {status === 'added' ? '+' : status === 'removed' ? '−' : '~'} - - {tableKey} -
- {#if removeCount > 0}−{removeCount}{/if} - {#if addCount > 0}+{addCount}{/if} + {@const addCount = selectedDdlDiff?.adds ?? 0} + {@const removeCount = selectedDdlDiff?.removes ?? 0} + + +
+ {status === 'added' ? 'Added' : status === 'removed' ? 'Removed' : 'Changed'} + {tableKey} +
+ {#if removeCount > 0}−{removeCount}{/if} + {#if addCount > 0}+{addCount}{/if}
-
- {#if !selectedDdlDiff} +
+ {#if !shownDdlLines}
No DDL available
{:else} - + +
- {#each selectedDdlDiff as line, i (i)} + {#each shownDdlLines as line, i (i)} {#if line.type === 'ellipsis'} - - - - - - - {:else if line.type === 'add'} - - - - - - - {:else if line.type === 'remove'} - - - - - + + {:else} - - - - - + {@const parts = selectedDdlDiff?.words.get(line)} + {@const tone = line.type === 'add' ? 'success' : line.type === 'remove' ? 'destructive' : ''} + + + + + {/if} {/each} diff --git a/src/lib/components/SearchPage.svelte b/src/lib/components/SearchPage.svelte index 3af3eb28..90a0d46d 100644 --- a/src/lib/components/SearchPage.svelte +++ b/src/lib/components/SearchPage.svelte @@ -1,4 +1,5 @@ + + + + + My shares + + Links you've made{plan ? ` on the ${plan === 'pro' ? 'Pro' : 'free'} plan` : ''}. Revoking deletes the content, so the link stops working everywhere at once. + + + +
+ {#if loading && !rows.length} +
+ Loading +
+ {:else if error && !rows.length} +

{error}

+ {:else if !rows.length} +
+ +

No shares yet

+

Share a result, a chart or a diagram from its toolbar, or ask the AI to share one.

+
+ {:else} +
    + {#each rows as r (r.id)} + {@const st = status(r)} + {@const mine = local[r.id]} +
  • + +
    +
    + {mine?.title ?? KIND[r.kind] ?? r.kind} + {#if r.hasPassword}{/if} +
    +
    + {KIND[r.kind] ?? r.kind} + + {r.views} view{r.views === 1 ? '' : 's'}{r.maxViews !== null ? ` of ${r.maxViews}` : ''} + + {st.label === 'Active' ? (r.expiresAt ? `Expires ${when(r.expiresAt)}` : 'Never expires') : st.label} + {#if r.lastViewedAt}Last opened {when(r.lastViewedAt)}{/if} +
    +
    + {#if r.active} + {#if mine} + + {/if} + + {/if} +
  • + {/each} +
+ {/if} +
+ {#if error && rows.length}

{error}

{/if} +
+
diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 7a4729e3..8d289cf6 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -3,6 +3,7 @@ import ThemeBuilder from './ThemeBuilder.svelte'; import { comboTitle } from '$lib/shortcuts.js' import Kbd from './Kbd.svelte' + import { nightlyInstall, nightlyOpen } from '$lib/api.js' import KeybindingsSettings from './KeybindingsSettings.svelte' import { bindingFor } from '$lib/stores/keybindings.js' import { startTelemetry, stopTelemetry } from "$lib/telemetry.js"; @@ -554,6 +555,29 @@ if (s?.status === "Trial") return { label: `Trial · ${s.days_remaining}d`, class: "border-warning/25 bg-warning/10 text-warning" }; return { label: "Free", class: "border-border/70 bg-muted/40 text-muted-foreground" }; }); + + // ── Stroke Nightly ───────────────────────────────────────────────────── + let onNightly = $state(false) + let nightlyBusy = $state(false) + let nightlyPath = $state('') + let nightlyError = $state('') + $effect(() => { + void import('@tauri-apps/api/app') + .then((m) => m.getVersion()) + .then((v) => { onNightly = /-nightly\./.test(v) }) + .catch(() => {}) + }) + async function installNightly() { + nightlyBusy = true + nightlyError = '' + try { + nightlyPath = await nightlyInstall() + } catch (e) { + nightlyError = String(/** @type {any} */ (e)?.message ?? e) + } finally { + nightlyBusy = false + } + } @@ -1147,6 +1171,37 @@ )} {/if} + + {#if show('Try Stroke Nightly', 'The daily build, installed beside Stroke')} +
+
+

{onNightly ? "You're on Stroke Nightly" : 'Try Stroke Nightly'}

+

+ {#if onNightly} + Built every night from the newest code. Stroke itself stays installed beside it, with its own settings. + {:else if nightlyError} + {nightlyError} + {:else if nightlyPath} + Installed. It's a separate app with its own settings, so this one is untouched. + {:else} + The daily build with the newest features, installed beside Stroke as a separate app. Your connections and settings here stay as they are. + {/if} +

+
+ {#if !onNightly} + {#if nightlyPath} + + {:else} + + {/if} + {/if} +
+ {/if} + {@render secLabel('Privacy')} diff --git a/src/lib/components/ShareDialog.svelte b/src/lib/components/ShareDialog.svelte new file mode 100644 index 00000000..6ae1f0fc --- /dev/null +++ b/src/lib/components/ShareDialog.svelte @@ -0,0 +1,270 @@ + + + { if (!v) close() }}> + + + Share {KIND_LABEL[src?.kind ?? ''] ?? ''} + + + Encrypted on this computer. The link holds the key; stroke.click can't read it. + + + + {#if link} + +
+
+ e.currentTarget.select()} aria-label="Share link" /> + +
+

+ Copied. Anyone with this link{usePassword && password ? ' and the password' : ''} can view it{access === 'once' ? ' once' : access === 'limit' ? ` up to ${viewLimit} times` : ''}{expiry ? `, for ${SHARE_EXPIRIES.find((e) => e.seconds === expiry)?.label}` : ''}. Revoke it any time in My shares. +

+
+
+ + + +
+ {:else} +
+
+ + +
+ + {#if tabular && src && 'columns' in src} +
+
+ Columns + {keep.size} of {src.columns.length} +
+
    + {#each src.columns as col, i (i)} + {@const hit = sensitiveByIndex.get(i)} +
  • + toggleKeep(i)} class="size-3.5 shrink-0 accent-primary" aria-label="Include {col.name}" /> + {col.name} + {#if hit} + {hit.why === 'name' ? 'Personal data?' : `Looks like ${hit.why}`} + {/if} + +
  • + {/each} +
+

+ {#if rowCount > rowCap} + Shares the first {rowCap.toLocaleString()} of {rowCount.toLocaleString()} rows{pro ? '' : ' on the free plan (Pro shares up to 100,000)'}. + {:else} + {rowCount.toLocaleString()} row{rowCount === 1 ? '' : 's'}. Masked values keep their shape (a••@e••••.com). + {/if} +

+
+ {/if} + +
+ Expires after +
+ {#each SHARE_EXPIRIES as e (e.label)} + {@const locked = e.seconds === null && !pro} + + {/each} +
+
+ +
+ Who can open it +
+ {#each [{ v: 'link', l: 'Anyone, any time' }, { v: 'once', l: 'Once, then gone' }, { v: 'limit', l: 'A few views' }] as a (a.v)} + + {/each} +
+ {#if access === 'limit'} + + {/if} +
+ +
+ + {#if usePassword} + + {/if} +
+ + {#if planError} +

{planError}

+ {:else if error} +

{error}

+ {/if} +
+ +
+ + + + +
+ {/if} +
+
diff --git a/src/lib/components/SqlConsole.svelte b/src/lib/components/SqlConsole.svelte index b6b68b68..f9223acc 100644 --- a/src/lib/components/SqlConsole.svelte +++ b/src/lib/components/SqlConsole.svelte @@ -13,6 +13,8 @@ import Code2 from "@lucide/svelte/icons/code-2"; import ChevronDown from "@lucide/svelte/icons/chevron-down"; import Download from "@lucide/svelte/icons/download"; + import Share2 from "@lucide/svelte/icons/share-2"; + import { requestShare } from "$lib/share-flow.js"; import Table2 from "@lucide/svelte/icons/table-2"; import SlidersHorizontal from "@lucide/svelte/icons/sliders-horizontal"; import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js"; @@ -814,6 +816,12 @@ if (queryCopiedTimer) clearTimeout(queryCopiedTimer) if (errorCopyTimer) clearTimeout(errorCopyTimer) }) + + /** A share's default title: the query's first meaningful line. */ + function shareTitle() { + const line = sql.split('\n').map((l) => l.trim()).find((l) => l && !l.startsWith('--')) ?? 'Query' + return line.length > 60 ? line.slice(0, 57) + '…' : line + }
@@ -1052,6 +1060,19 @@ Copy as Prisma + + + {#if columns.length > 0} + requestShare({ kind: 'result', title: shareTitle(), columns: columns.map((c) => ({ name: c.name ?? String(c), type: c.dataType ?? c.data_type ?? c.type })), rows, sql })}> + + Share results… + + {/if} + requestShare({ kind: 'query', title: shareTitle(), sql })}> + + Share query… +
diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 0cf84b13..6ab94e49 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -76,6 +76,9 @@ import ConnectionModal from './ConnectionModal.svelte' import { terminalDockOpen as terminalDockStore } from '$lib/stores/redis-nav.js' import DbIcon from './DbIcon.svelte' + import ShareDialog from './ShareDialog.svelte' + import { requestShare } from '$lib/share-flow.js' + import MySharesDialog from './MySharesDialog.svelte' import Icon from './Icon.svelte' import DockerLaunchModal from './DockerLaunchModal.svelte' import CreateTableDialog from './CreateTableDialog.svelte' @@ -579,6 +582,8 @@ let showInsiderModal = $state(false) let showAboutModal = $state(false) let showReportIssueDialog = $state(false) + /** My shares (share links made on this account). */ + let showMyShares = $state(false) let showDisconnectDialog = $state(false) let showAiModelSettings = $state(false) let showProGate = $state(false) @@ -6909,6 +6914,22 @@ let rowSearch = $state('') /** @param {'csv' | 'json'} format */ let exportingData = $state(false) + /** Share the open table's rows, or its chart, as an encrypted link. @param {string} mode */ + function shareTableView(mode) { + const visibleIdxs = columns.map((_, i) => i).filter((i) => !hiddenColumns.has(columns[i].name)) + const picked = (selected.size > 0 && selected.size < rows.length) + ? [...selected].sort((a, b) => a - b).map((i) => rows[i]).filter(Boolean) + : rows.filter(Boolean) + const cols = visibleIdxs.map((i) => ({ name: columns[i].name, type: columns[i].dataType ?? columns[i].data_type })) + const cells = picked.map((r) => visibleIdxs.map((i) => r[i])) + const source = connection?.name ? `${connection.name} · ${activeSchema ? activeSchema + '.' : ''}${activeTable}` : String(activeTable ?? '') + if (mode === 'chart' && chartPane?.shareSpec) { + requestShare({ kind: 'chart', title: `${activeTable} chart`, source, chart: chartPane.shareSpec(), columns: dataViewColumns.map((c) => ({ name: c.name, type: c.dataType ?? c.data_type })), rows: dataViewRows }) + return + } + requestShare({ kind: 'table', title: String(activeTable ?? 'Rows'), source, columns: cols, rows: cells, totalRows: Math.max(total || 0, cells.length) }) + } + async function handleExport(format) { if (exportingData) return exportingData = true @@ -9050,6 +9071,9 @@ let rowSearch = $state('') (showReportIssueDialog = true)} /> + + (showMyShares = true)} /> + @@ -9157,6 +9181,7 @@ let rowSearch = $state('') {hasAdvisor} onopenJsonViewer={() => { if (aiMode) exitAiMode(); openJsonTab() }} onopenshortcuts={() => openShortcuts()} + onopenmyshares={() => { commandOpen = false; showMyShares = true }} onopenkeybindings={() => { settingsSection = 'keybindings'; showSettingsModal = true }} onopenabout={() => (showAboutModal = true)} onopenreport={() => (showReportIssueDialog = true)} @@ -10420,6 +10445,7 @@ let rowSearch = $state('') onfindreplace={() => openFindReplacePanel()} ondeleteselected={() => stageDeleteSelectedRows()} onexport={handleExport} + onshare={shareTableView} onimport={() => (importDataOpen = true)} onexportdiagram={(kind) => erdPane?.exportDiagram?.(kind)} onexportchart={(kind) => chartPane?.exportChart?.(kind)} diff --git a/src/lib/components/TableToolbar.svelte b/src/lib/components/TableToolbar.svelte index ce21e3e8..5ff9c26f 100644 --- a/src/lib/components/TableToolbar.svelte +++ b/src/lib/components/TableToolbar.svelte @@ -102,6 +102,8 @@ ondeleteselected = () => {}, /** @type {(format: 'csv' | 'json' | 'sql' | 'tsv' | 'md' | 'jsonl') => void | Promise} */ onexport = () => {}, + /** Share what's on screen (rows, or the chart in chart view) as a link. */ + onshare = undefined, onimport = () => {}, /** Diagram exports, offered alongside the row formats while the ERD view is open. */ /** @type {(kind: 'png' | 'copy-png' | 'svg' | 'mermaid') => void | Promise} */ @@ -1777,6 +1779,12 @@ + {#if onshare} + onshare(dataViewMode)}> + + {dataViewMode === 'chart' ? 'Share chart…' : 'Share rows…'} + + {/if} onimport()}> Import data… diff --git a/src/lib/share-crypto.js b/src/lib/share-crypto.js new file mode 100644 index 00000000..60194d15 --- /dev/null +++ b/src/lib/share-crypto.js @@ -0,0 +1,148 @@ +// The share-link format, the app's half. The viewer's half is stroke-web +// src/lib/shares/crypto.ts; keep the two in step. +// +// blob = 0x01 · iv (12 bytes) · AES-256-GCM(gzip(JSON payload)) +// link = https://stroke.click/s/# +// key = the link key, or with a password +// SHA-256(link key · PBKDF2-SHA256(password, salt, 310,000, 32 bytes)) +// +// The key only ever lives in the link's #fragment, which browsers never send, +// so stroke.click stores bytes it cannot read. + +export const SHARE_FORMAT = 1 +export const PBKDF2_ITERATIONS = 310_000 + +/** @param {Uint8Array} bytes */ +export function b64url(bytes) { + let s = '' + for (const b of bytes) s += String.fromCharCode(b) + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +/** @param {string} s */ +export function b64urlDecode(s) { + const b = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)) + return Uint8Array.from(b, (c) => c.charCodeAt(0)) +} + +/** @param {string} text */ +async function gzip(text) { + const stream = new Blob([new TextEncoder().encode(text)]).stream().pipeThrough(new CompressionStream('gzip')) + return new Uint8Array(await new Response(stream).arrayBuffer()) +} + +/** @param {ArrayBuffer} data */ +async function gunzip(data) { + const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream('gzip')) + return await new Response(stream).text() +} + +/** + * The AES key for a link key and, with a password, its PBKDF2 stretch. + * @param {Uint8Array} linkKey @param {string | null} password @param {string | null} saltB64 + * @param {KeyUsage[]} usages + */ +export async function deriveKey(linkKey, password, saltB64, usages) { + let raw = linkKey + if (password && saltB64) { + const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveBits']) + const salt = b64urlDecode(saltB64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')) + const bits = new Uint8Array(await crypto.subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: PBKDF2_ITERATIONS }, base, 256)) + const both = new Uint8Array(linkKey.length + bits.length) + both.set(linkKey) + both.set(bits, linkKey.length) + raw = new Uint8Array(await crypto.subtle.digest('SHA-256', both)) + } + return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, usages) +} + +/** + * Encrypt a payload for sharing. Returns the bytes to upload, the link key + * (for the #fragment) and, with a password, the salt the server stores so + * the viewer can stretch the same key. + * @param {object} payload + * @param {{ password?: string | null }} [opts] + * @returns {Promise<{ blob: Uint8Array, linkKey: string, passwordSalt: string | null }>} + */ +export async function sealShare(payload, opts = {}) { + const linkKey = crypto.getRandomValues(new Uint8Array(32)) + const password = opts.password?.length ? opts.password : null + const passwordSalt = password ? b64url(crypto.getRandomValues(new Uint8Array(16))) : null + const key = await deriveKey(linkKey, password, passwordSalt, ['encrypt']) + const iv = crypto.getRandomValues(new Uint8Array(12)) + const plain = await gzip(JSON.stringify(payload)) + const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plain)) + const blob = new Uint8Array(1 + iv.length + sealed.length) + blob[0] = SHARE_FORMAT + blob.set(iv, 1) + blob.set(sealed, 1 + iv.length) + return { blob, linkKey: b64url(linkKey), passwordSalt } +} + +/** + * Decrypt a share (the app opening its own links, and the tests). + * @param {ArrayBuffer | Uint8Array} blob @param {string} linkKey @param {string | null} password @param {string | null} passwordSalt + */ +export async function openShare(blob, linkKey, password, passwordSalt) { + const bytes = blob instanceof Uint8Array ? blob : new Uint8Array(blob) + if (bytes[0] !== SHARE_FORMAT) throw new Error('Unknown share format') + const key = await deriveKey(b64urlDecode(linkKey), password, passwordSalt, ['decrypt']) + const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.slice(1, 13) }, key, bytes.slice(13)) + return JSON.parse(await gunzip(plain)) +} + +// ── What gets shared ──────────────────────────────────────────────────────── + +/** Column names that usually hold personal or secret data. */ +const PII_NAME = /(^|_)(e_?mail|phone|mobile|tel|ssn|passport|national_id|tax_id|iban|card|cc_num|cvv|dob|birth(day|date)?|address|street|zip|postcode|ip(_?addr(ess)?)?|password|passwd|pwd|secret|token|api_?key|access_?key|private_?key|salt|hash|session|otp|first_?name|last_?name|full_?name|surname)($|_)/i +const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/ +const PHONE = /^\+?[\d\s().-]{8,}$/ +const TOKENISH = /^(?:sk|pk|rk|ghp|gho|xox[abp]|eyJ)[\w.-]{16,}|^[A-Za-z0-9_-]{32,}$/ + +/** + * Columns that probably hold personal data or secrets, judged by name and by + * a sample of their values. The share dialog offers to mask these. + * @param {{ name: string }[]} columns @param {unknown[][]} rows + * @returns {{ index: number, name: string, why: string }[]} + */ +export function detectSensitiveColumns(columns, rows) { + const sample = rows.slice(0, 200) + /** @type {{ index: number, name: string, why: string }[]} */ + const out = [] + columns.forEach((c, i) => { + if (PII_NAME.test(c.name)) { out.push({ index: i, name: c.name, why: 'name' }); return } + let emails = 0, phones = 0, tokens = 0, seen = 0 + for (const r of sample) { + const v = r[i] + if (typeof v !== 'string' || !v) continue + seen++ + if (EMAIL.test(v)) emails++ + else if (PHONE.test(v) && /\d{7,}/.test(v.replace(/\D/g, ''))) phones++ + else if (TOKENISH.test(v)) tokens++ + } + if (!seen) return + if (emails / seen > 0.5) out.push({ index: i, name: c.name, why: 'emails' }) + else if (phones / seen > 0.5) out.push({ index: i, name: c.name, why: 'phone numbers' }) + else if (tokens / seen > 0.5) out.push({ index: i, name: c.name, why: 'tokens' }) + }) + return out +} + +/** + * A masked value that keeps its shape (so the column still reads as emails or + * phone numbers) without the content: `ada@example.com` -> `a••@e••••••.com`. + * @param {unknown} v + */ +export function maskValue(v) { + if (v === null || v === undefined) return v + const s = typeof v === 'string' ? v : JSON.stringify(v) + if (EMAIL.test(s)) { + const [user, domain] = s.split('@') + const dot = domain.lastIndexOf('.') + const host = dot > 0 ? domain.slice(0, dot) : domain + const tld = dot > 0 ? domain.slice(dot) : '' + return `${user[0] ?? ''}${'•'.repeat(Math.max(2, user.length - 1))}@${host[0] ?? ''}${'•'.repeat(Math.max(2, host.length - 1))}${tld}` + } + if (s.length <= 4) return '••••' + return s.slice(0, 2) + '•'.repeat(Math.min(12, s.length - 4)) + s.slice(-2) +} diff --git a/src/lib/share-crypto.test.js b/src/lib/share-crypto.test.js new file mode 100644 index 00000000..c6007275 --- /dev/null +++ b/src/lib/share-crypto.test.js @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { detectSensitiveColumns, maskValue, openShare, sealShare } from './share-crypto.js' + +describe('share encryption', () => { + const payload = { v: 1, kind: 'result', title: 'Top customers', createdAt: 1, columns: [{ name: 'id' }], rows: [[1], [2]] } + + it('round-trips a payload with the link key', async () => { + const s = await sealShare(payload) + expect(s.blob[0]).toBe(1) + expect(s.passwordSalt).toBeNull() + expect(await openShare(s.blob, s.linkKey, null, null)).toEqual(payload) + }) + + it('needs the password as well as the link when there is one', async () => { + const s = await sealShare(payload, { password: 'hunter2' }) + expect(s.passwordSalt).toBeTruthy() + expect(await openShare(s.blob, s.linkKey, 'hunter2', s.passwordSalt)).toEqual(payload) + await expect(openShare(s.blob, s.linkKey, 'wrong', s.passwordSalt)).rejects.toThrow() + await expect(openShare(s.blob, s.linkKey, null, null)).rejects.toThrow() + }, 20000) + + it('fails on another link key', async () => { + const a = await sealShare(payload) + const b = await sealShare(payload) + await expect(openShare(a.blob, b.linkKey, null, null)).rejects.toThrow() + }) + + it('never puts the plaintext in the uploaded bytes', async () => { + const s = await sealShare({ ...payload, title: 'SECRET-TITLE-123' }) + expect(new TextDecoder().decode(s.blob)).not.toContain('SECRET-TITLE-123') + }) +}) + +describe('sensitive columns', () => { + it('flags personal data by name and by content', () => { + const cols = [{ name: 'id' }, { name: 'email' }, { name: 'contact' }, { name: 'api_key' }, { name: 'note' }, { name: 'mobile' }] + const rows = [ + [1, 'a@b.co', 'ada@example.com', 'sk_live_abcdefghijklmnopqrstuv', 'hello', '+1 415 555 0100'], + [2, 'c@d.io', 'bob@example.org', 'sk_live_zyxwvutsrqponmlkjihgfe', 'world', '+44 20 7946 0958'], + ] + const hits = detectSensitiveColumns(cols, rows).map((h) => `${h.name}:${h.why}`) + expect(hits).toEqual(['email:name', 'contact:emails', 'api_key:name', 'mobile:name']) + }) + + it('masks while keeping the shape', () => { + expect(maskValue('ada@example.com')).toBe('a••@e••••••.com') + expect(maskValue('+1 415 555 0100')).toMatch(/^\+1•+00$/) + expect(maskValue(null)).toBeNull() + expect(maskValue('abc')).toBe('••••') + }) +}) diff --git a/src/lib/share-flow.js b/src/lib/share-flow.js new file mode 100644 index 00000000..a67835b6 --- /dev/null +++ b/src/lib/share-flow.js @@ -0,0 +1,106 @@ +// Building and publishing share links. The dialog collects the sharer's +// choices; this turns them into a payload, encrypts it (share-crypto.js), +// uploads the ciphertext and remembers the link on this machine. + +import { writable } from 'svelte/store' +import { sealShare, maskValue } from '$lib/share-crypto.js' +import { shareCreate } from '$lib/api.js' + +/** Expiries offered, in seconds (null = never, Pro). Mirrors the server. */ +export const SHARE_EXPIRIES = /** @type {const} */ ([ + { label: '1 hour', seconds: 3600 }, + { label: '1 day', seconds: 86400 }, + { label: '7 days', seconds: 7 * 86400 }, + { label: '30 days', seconds: 30 * 86400 }, + { label: 'Never', seconds: null }, +]) + +/** + * What a share is made from, handed to the dialog by whatever opened it. + * @typedef {{ kind: 'result' | 'table', title: string, source?: string, columns: { name: string, type?: string }[], rows: unknown[][], totalRows?: number, sql?: string }} TableSource + * @typedef {{ kind: 'query', title: string, source?: string, sql: string, dialect?: string }} QuerySource + * @typedef {{ kind: 'erd', title: string, source?: string, tables: { name: string, x: number, y: number, columns: { name: string, type: string, pk?: boolean, fk?: string | null }[] }[], links: { from: string, fromCol: string, to: string, toCol: string }[] }} ErdSource + * @typedef {{ kind: 'mermaid', title: string, source?: string, code: string }} MermaidSource + * @typedef {{ kind: 'chart', title: string, source?: string, chart: { type: string, x: string, y: string[], group?: string | null }, columns: { name: string, type?: string }[], rows: unknown[][] }} ChartSource + * @typedef {TableSource | QuerySource | ErdSource | MermaidSource | ChartSource} ShareSource + */ + +/** The share the dialog is open for, or null. */ +export const shareRequest = writable(/** @type {ShareSource | null} */ (null)) + +/** Open the share dialog for `source`. @param {ShareSource} source */ +export function requestShare(source) { + shareRequest.set(source) +} + +/** + * The payload for a source and the sharer's choices: kept columns, masked + * columns, and the plan's row cap. + * @param {ShareSource} src + * @param {{ title: string, keep?: Set, mask?: Set, rowCap?: number }} o + */ +export function buildPayload(src, o) { + const base = { v: 1, title: o.title.trim() || src.title, createdAt: Date.now(), source: src.source } + if (src.kind === 'result' || src.kind === 'table' || src.kind === 'chart') { + const keep = src.columns.map((_, i) => i).filter((i) => !o.keep || o.keep.has(i)) + const mask = o.mask ?? new Set() + const cap = o.rowCap ?? src.rows.length + const rows = src.rows.slice(0, cap).map((r) => keep.map((i) => (mask.has(i) ? maskValue(r[i]) : r[i]))) + const columns = keep.map((i) => src.columns[i]) + const masked = keep.filter((i) => mask.has(i)).map((i) => src.columns[i].name) + if (src.kind === 'chart') return { ...base, kind: 'chart', chart: src.chart, columns, rows, totalRows: src.rows.length, masked } + return { ...base, kind: src.kind, columns, rows, totalRows: src.totalRows ?? src.rows.length, masked, sql: src.sql } + } + if (src.kind === 'query') return { ...base, kind: 'query', sql: src.sql, dialect: src.dialect } + if (src.kind === 'erd') return { ...base, kind: 'erd', tables: src.tables, links: src.links } + return { ...base, kind: 'mermaid', code: src.code } +} + +// ── Links made on this machine ────────────────────────────────────────────── +// The server never sees a key, so it can't give a link back. Each link (with +// its key) is kept here so My shares can copy it again; nothing leaves the +// device. + +const KEY = 'stroke:shares' + +/** @typedef {{ id: string, url: string, title: string, kind: string, createdAt: number }} LocalShare */ + +/** @returns {Record} */ +export function localShares() { + try { return JSON.parse(localStorage.getItem(KEY) || '{}') } catch { return {} } +} + +/** @param {LocalShare} s */ +function rememberShare(s) { + try { + const all = localShares() + all[s.id] = s + localStorage.setItem(KEY, JSON.stringify(all)) + } catch { /* storage full or blocked: the link was still shown once */ } +} + +/** @param {string} id */ +export function forgetShare(id) { + try { + const all = localShares() + delete all[id] + localStorage.setItem(KEY, JSON.stringify(all)) + } catch {} +} + +/** + * Encrypt, upload and remember. Returns the full link, key included. + * @param {object} payload + * @param {{ expiresIn: number | null, maxViews: number | null, password?: string | null }} o + */ +export async function publishShare(payload, o) { + const p = /** @type {any} */ (payload) + const sealed = await sealShare(payload, { password: o.password }) + const res = await shareCreate( + { kind: p.kind, expiresIn: o.expiresIn, maxViews: o.maxViews, passwordSalt: sealed.passwordSalt }, + sealed.blob, + ) + const url = `${res.url}#${sealed.linkKey}` + rememberShare({ id: res.id, url, title: p.title, kind: p.kind, createdAt: Date.now() }) + return { id: res.id, url, bytes: sealed.blob.length } +} From 02e590e9c8d9ca43a839c6579db0b615c178557c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:42:18 +0000 Subject: [PATCH 107/317] chore: version 2.10.3 (#199) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10e039d8..f6f1a0e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.10.3] - 2026-11-15 + +### Changes +- Share links, AI share tool, and Try Nightly from stable (#199) + + ## [2.10.2] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 01e0c133..fea395ed 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.10.2", + "version": "2.10.3", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 3409778c..98d6b334 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.10.2", + "version": "2.10.3", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 20555a9a0dc1e675eae2ef0fce279444f9fec5e6 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 13:30:54 +0545 Subject: [PATCH 108/317] Fix the share dialog crash, faster big-table search, Shared links tab (#200) - Share dialog: the form reset read `sensitive` after writing it, so the effect depended on itself and looped until effect_update_depth_exceeded. It now tracks only the source. Redesigned, with defaults from Settings. - Shared links is a tab (an overlay without a connection), in a list layout with sections, tinted kinds, views and expiry, revoke on hover. - Settings: Sharing section (default expiry, views, masking) and an empty state for searches that match nothing. - Share buttons in the SQL results bar and the table toolbar. - Postgres grid search skips columns whose type can't contain the term, uses LIKE for terms without letters and lower() LIKE otherwise. On a 5M-row table: numeric term 6.4s to 1.4s, text column 2.05s to 1.2s, impossible matches no scan at all. - AI tools: current_database reports the live connection, and the app sends the saved id it connected with, so the agent no longer says no database is connected while one is. - Grid: the scroll axis is fixed per gesture, so pressing Shift during trackpad momentum no longer turns the coast sideways. - Terminal: WebGL renderer at rest (box-drawing lines join), DOM while resizing; new header and a quieter jump-to-latest. - SQL editor: results toggle moves to Mod+Shift+J (Mod+J is the terminal everywhere, and both fired); find in results (Mod+F in the grid). - Command palette Ask AI: agent providers continue in the chat instead of failing with "builder error"; Raycast-style transcript and action bar. - Sidebar footer: Labs button. New tab: flat search bar. --- src-tauri/src/db/query.rs | 233 ++++++++++++++++- src-tauri/src/mcp/server.rs | 3 +- src-tauri/src/mcp/tools.rs | 24 +- src/lib/components/ChartView.svelte | 10 +- src/lib/components/CommandPalette.svelte | 127 ++++++--- src/lib/components/DataTable.svelte | 44 +++- src/lib/components/MySharesDialog.svelte | 156 ++--------- src/lib/components/SettingsDialog.svelte | 69 ++++- src/lib/components/ShareDialog.svelte | 219 ++++++++++------ src/lib/components/SharesPage.svelte | 315 +++++++++++++++++++++++ src/lib/components/Sidebar.svelte | 3 + src/lib/components/SqlConsole.svelte | 127 ++++++++- src/lib/components/SqlEditor.svelte | 2 +- src/lib/components/StudioShell.svelte | 63 ++++- src/lib/components/TabBar.svelte | 1 + src/lib/components/TableToolbar.svelte | 13 + src/lib/components/TerminalPage.svelte | 99 +++++-- src/lib/icon-registry.js | 4 + src/lib/share-flow.js | 35 +++ src/lib/shortcuts.js | 2 +- src/lib/studio-tabs.js | 7 +- 21 files changed, 1238 insertions(+), 318 deletions(-) create mode 100644 src/lib/components/SharesPage.svelte diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index de6154b2..40875dd8 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -1333,6 +1333,137 @@ pub(super) async fn fetch_table_column_names( .collect()) } +/// A column as the grid search sees it: its name and its type's category +/// (`pg_type.typcategory`: N numeric, D date/time, B boolean, S string, ...). +#[derive(Clone, Debug)] +pub(super) struct SearchColumn { + pub name: String, + pub category: char, + pub type_name: String, +} + +static SEARCH_COLUMNS_CACHE: std::sync::OnceLock< + std::sync::Mutex)>>, +> = std::sync::OnceLock::new(); + +/// Columns with their types, for the search predicate. Cached like the names. +pub(super) async fn cached_search_columns( + pool: &sqlx::PgPool, + schema: &str, + table: &str, + refresh: bool, +) -> Result, String> { + let key = pool_table_key(pool, schema, table); + let cache = SEARCH_COLUMNS_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new())); + if !refresh { + if let Some((at, cols)) = cache.lock().ok().and_then(|m| m.get(&key).cloned()) { + if at.elapsed() < COLUMN_NAMES_TTL { + return Ok(cols); + } + } + } + validate_ident(schema)?; + validate_ident(table)?; + let rows = sqlx::query( + r#" + SELECT a.attname::text, t.typcategory::text, t.typname::text + FROM pg_attribute a + JOIN pg_class c ON c.oid = a.attrelid + JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_type t ON t.oid = a.atttypid + WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped + ORDER BY a.attnum + "#, + ) + .bind(schema) + .bind(table) + .fetch_all(pool) + .await + .map_err(|e| format!("Failed to load columns: {e}"))?; + let cols: Vec = rows + .iter() + .filter_map(|r| { + Some(SearchColumn { + name: r.try_get::(0).ok()?, + category: r.try_get::(1).ok()?.chars().next().unwrap_or('X'), + type_name: r.try_get::(2).ok().unwrap_or_default(), + }) + }) + .collect(); + if let Ok(mut m) = cache.lock() { + if m.len() > 4096 { + m.retain(|_, (at, _)| at.elapsed() < COLUMN_NAMES_TTL); + } + m.insert(key, (std::time::Instant::now(), cols.clone())); + } + Ok(cols) +} + +/// Whether a column's text form could contain `term` at all, judged by its +/// type alone. A number prints as digits, a sign, a point and an exponent, so +/// "Product 1" can never be inside one; skipping it saves casting every value +/// of it to text on every row of the scan, which on a 5M-row table was most +/// of a search's time. Conservative: anything unsure is searched. +pub(super) fn column_could_contain(col: &SearchColumn, term: &str) -> bool { + let lower = term.to_lowercase(); + match col.category { + // Numbers: 12.5, -3, 1e+21, NaN, Infinity. + 'N' if col.type_name != "money" => { + term.chars().all(|c| c.is_ascii_digit() || ".-+eE".contains(c)) + || "nan".contains(lower.as_str()) + || "-infinity".contains(lower.as_str()) + } + // Dates and times: 2026-11-15 13:00:00.5+00, 13:00, plus infinity and BC. + 'D' => { + term.chars().all(|c| c.is_ascii_digit() || "-:. +".contains(c)) + || "-infinity".contains(lower.as_str()) + || lower.trim() == "bc" + } + 'B' => "true".contains(lower.as_str()) || "false".contains(lower.as_str()), + _ if col.type_name == "uuid" => term.chars().all(|c| c.is_ascii_hexdigit() || c == '-'), + _ => true, + } +} + +/// The plain (not regex) search across `columns`, as fast as Postgres can run +/// it while matching what ILIKE / LIKE would. +/// +/// - Columns that can't contain the term are left out (column_could_contain); +/// with none left the predicate is FALSE and the scan never starts. +/// - A term without letters has no case, so case-insensitive is plain LIKE: +/// on 5M rows a numeric search took 6.4s with ILIKE and 1.4s with LIKE. +/// - Otherwise `lower(col) LIKE lower($1)`: the same rows as ILIKE, about +/// twice as fast (2.05s vs 1.2s on one text column). +fn build_plain_search( + builder: &mut QueryBuilder, + columns: &[SearchColumn], + term: &str, + case_sensitive: bool, +) { + let has_case = term.chars().any(|c| c.is_lowercase() || c.is_uppercase()); + let insensitive = !case_sensitive && has_case; + let searched: Vec<&SearchColumn> = columns.iter().filter(|c| column_could_contain(c, term)).collect(); + if searched.is_empty() { + builder.push_condition("FALSE".to_string(), None); + return; + } + let pattern = builder.push_bind(format!("%{}%", escape_ilike_pattern(term))); + let parts: Vec = searched + .iter() + .filter_map(|c| quoted_column(&c.name).ok().map(|col| (col, c))) + .map(|(col, c)| { + // Text needs no cast; everything else is searched as it prints. + let text = if c.category == 'S' { col } else { format!("{col}::text") }; + if insensitive { + format!("lower({text}) LIKE lower({pattern}) ESCAPE '\\'") + } else { + format!("{text} LIKE {pattern} ESCAPE '\\'") + } + }) + .collect(); + builder.push_condition(format!("({})", parts.join(" OR ")), None); +} + fn ensure_column(column: &str, allowed: &[String]) -> Result<(), String> { if allowed.iter().any(|c| c == column) { Ok(()) @@ -1620,11 +1751,26 @@ pub(super) fn build_where( search_is_regex: bool, search_case_sensitive: bool, filters: &[RowFilter], +) -> Result { + build_where_typed(columns, None, search, search_is_regex, search_case_sensitive, filters) +} + +/// build_where with the columns' types, which lets a plain search skip the +/// columns that can't match (see build_plain_search). +pub(super) fn build_where_typed( + columns: &[String], + search_columns: Option<&[SearchColumn]>, + search: Option<&str>, + search_is_regex: bool, + search_case_sensitive: bool, + filters: &[RowFilter], ) -> Result { let mut builder = QueryBuilder::new(); if let Some(term) = search.map(str::trim).filter(|s| !s.is_empty()) { - if search_is_regex { + if let (false, Some(typed)) = (search_is_regex, search_columns) { + build_plain_search(&mut builder, typed, term, search_case_sensitive); + } else if search_is_regex { let op = if search_case_sensitive { "~" } else { "~*" }; let pattern = builder.push_bind(term.to_string()); let parts: Vec = columns @@ -1931,7 +2077,12 @@ pub async fn get_table_rows( } else { vec![] }; - let where_clause = build_where(&table_columns, search.as_deref(), search_is_regex, search_case_sensitive, &filters)?; + let search_columns = if has_search && !search_is_regex { + cached_search_columns(&pool, &schema, &table, include_meta).await.ok() + } else { + None + }; + let where_clause = build_where_typed(&table_columns, search_columns.as_deref(), search.as_deref(), search_is_regex, search_case_sensitive, &filters)?; let order_by = build_order_by( &table_columns, sort_column.as_deref(), @@ -2413,7 +2564,14 @@ pub async fn count_table_rows( } else { vec![] }; - let where_clause = build_where(&table_columns, search.as_deref(), search_is_regex, search_case_sensitive, &filters)?; + // The same typed predicate as the rows query, or the pager would count + // something other than what the grid shows. + let search_columns = if has_search && !search_is_regex { + cached_search_columns(&pool, &schema, &table, false).await.ok() + } else { + None + }; + let where_clause = build_where_typed(&table_columns, search_columns.as_deref(), search.as_deref(), search_is_regex, search_case_sensitive, &filters)?; let table_ref = format!(r#""{schema}"."{table}""#); const ESTIMATE_THRESHOLD: i64 = 100_000; @@ -5615,3 +5773,72 @@ mod nosql_console_live { assert!(!run(&rc, "DBSIZE").await.rows.is_empty()); } } + +#[cfg(test)] +mod typed_search_tests { + use super::*; + + fn col(name: &str, category: char, type_name: &str) -> SearchColumn { + SearchColumn { name: name.into(), category, type_name: type_name.into() } + } + + fn cols() -> Vec { + vec![ + col("id", 'N', "int4"), + col("name", 'S', "text"), + col("price", 'N', "numeric"), + col("at", 'D', "timestamptz"), + col("ok", 'B', "bool"), + col("uid", 'U', "uuid"), + col("doc", 'U', "jsonb"), + ] + } + + fn sql(term: &str, case_sensitive: bool) -> String { + let names: Vec = cols().iter().map(|c| c.name.clone()).collect(); + build_where_typed(&names, Some(&cols()), Some(term), false, case_sensitive, &[]).unwrap().sql + } + + #[test] + fn a_word_skips_numbers_dates_and_uuids() { + let w = sql("Product 1", false); + assert!(w.contains(r#"lower("name") LIKE lower($1)"#), "{w}"); + assert!(w.contains(r#"lower("doc"::text)"#), "{w}"); + assert!(!w.contains(r#""id""#) && !w.contains(r#""price""#) && !w.contains(r#""at""#) && !w.contains(r#""uid""#), "{w}"); + assert!(!w.contains("ILIKE"), "{w}"); + } + + #[test] + fn digits_have_no_case_so_plain_like_everywhere_they_can_print() { + let w = sql("4999", false); + assert!(w.contains(r#""id"::text LIKE $1"#), "{w}"); + assert!(w.contains(r#""price"::text LIKE $1"#), "{w}"); + assert!(w.contains(r#""at"::text LIKE $1"#), "{w}"); + assert!(w.contains(r#""uid"::text LIKE $1"#), "{w}"); + assert!(!w.contains("lower("), "{w}"); + assert!(!w.contains(r#""ok""#), "{w}"); + } + + #[test] + fn nothing_could_match_so_nothing_is_scanned() { + let only_numbers = vec![col("id", 'N', "int4"), col("at", 'D', "date")]; + let w = build_where_typed(&["id".into(), "at".into()], Some(&only_numbers), Some("abc"), false, false, &[]).unwrap(); + assert_eq!(w.sql, " WHERE FALSE"); + } + + #[test] + fn match_case_keeps_the_case() { + let w = sql("Product", true); + assert!(w.contains(r#""name" LIKE $1"#) && !w.contains("lower("), "{w}"); + } + + #[test] + fn booleans_and_specials_still_match() { + assert!(column_could_contain(&col("ok", 'B', "bool"), "tru")); + assert!(column_could_contain(&col("x", 'N', "float8"), "NaN")); + assert!(column_could_contain(&col("x", 'D', "timestamp"), "infinity")); + assert!(column_could_contain(&col("x", 'D', "date"), "2026-11")); + assert!(!column_could_contain(&col("x", 'D', "date"), "nov")); + assert!(column_could_contain(&col("m", 'N', "money"), "$")); + } +} diff --git a/src-tauri/src/mcp/server.rs b/src-tauri/src/mcp/server.rs index 933fbe99..1d59a314 100644 --- a/src-tauri/src/mcp/server.rs +++ b/src-tauri/src/mcp/server.rs @@ -306,7 +306,8 @@ async fn dispatch( if name == "list_databases" || name == "current_database" { let connections = state.connections.lock().map_err(|e| e.to_string())?.clone(); let active_id = state.active_conn_id.lock().map_err(|e| e.to_string())?.clone(); - let text = tools::call_meta_tool(name, &connections, active_id.as_deref())?; + let live = conn.as_ref().map(|c| c.driver()); + let text = tools::call_meta_tool(name, &connections, active_id.as_deref(), live)?; return Ok(json!({ "content": [{ "type": "text", "text": text }] })); } diff --git a/src-tauri/src/mcp/tools.rs b/src-tauri/src/mcp/tools.rs index f25372f9..acd5942e 100644 --- a/src-tauri/src/mcp/tools.rs +++ b/src-tauri/src/mcp/tools.rs @@ -160,10 +160,16 @@ fn sample_sql(conn: &ActiveConnection, schema: &str, table: &str, n: usize) -> R // ── Tool dispatchers ────────────────────────────────────────────────────────── /// Handle tools that don't require an active DB connection. +/// +/// `live` is the driver of the connection Stroke actually holds, if any. The +/// saved-connection id can be missing while a database is open (a connection +/// opened from a URL, or one the app couldn't match to a saved entry); the +/// live connection is what the data tools use, so it decides "connected". pub fn call_meta_tool( name: &str, connections: &[ConnMeta], active_id: Option<&str>, + live: Option<&str>, ) -> Result { match name { "list_databases" => { @@ -195,6 +201,7 @@ pub fn call_meta_tool( "total": list.len(), "active_id": active_id, "active_name": active_name, + "connected": live.is_some(), "note": if connections.len() > 1 { "Multiple databases available. To switch, open Stroke and connect to the desired database. Then retry your request." } else if connections.is_empty() { @@ -220,10 +227,19 @@ pub fn call_meta_tool( if let Some(f) = &c.file_path { v["file_path"] = json!(f); } Ok(v.to_string()) } - None => Ok(json!({ - "connected": false, - "note": "No database is currently connected. Open Stroke and connect to a database, then retry." - }).to_string()), + None => match live { + // Open, just not one of the saved entries: the data tools + // work, so say so rather than sending the agent away. + Some(driver) => Ok(json!({ + "connected": true, + "type": driver, + "note": "A database is open in Stroke. list_tables and the other data tools run against it.", + }).to_string()), + None => Ok(json!({ + "connected": false, + "note": "No database is currently connected. Open Stroke and connect to a database, then retry." + }).to_string()), + }, } } diff --git a/src/lib/components/ChartView.svelte b/src/lib/components/ChartView.svelte index e9e6183b..9fb7ec96 100644 --- a/src/lib/components/ChartView.svelte +++ b/src/lib/components/ChartView.svelte @@ -286,16 +286,16 @@ } } - /** - * Image exports, driven from the table toolbar's Export submenu so the chart - * offers the same PNG / SVG / Copy set the ERD does. - * @param {'png' | 'svg' | 'copy-png'} kind - */ /** What a share link needs to redraw this chart: its type and axes. */ export function shareSpec() { return { type: chartType, x: xCol, y: yCol ? [yCol] : [], group: groupCol || null } } + /** + * Image exports, driven from the table toolbar's Export submenu so the chart + * offers the same PNG / SVG / Copy set the ERD does. + * @param {'png' | 'svg' | 'copy-png'} kind + */ export function exportChart(kind) { if (kind === 'png') return void downloadPng() if (kind === 'svg') return void downloadSvg() diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index e2d29dc9..1b880971 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -1,11 +1,13 @@ - - - - My shares - - Links you've made{plan ? ` on the ${plan === 'pro' ? 'Pro' : 'free'} plan` : ''}. Revoking deletes the content, so the link stops working everywhere at once. - - - -
- {#if loading && !rows.length} -
- Loading -
- {:else if error && !rows.length} -

{error}

- {:else if !rows.length} -
- -

No shares yet

-

Share a result, a chart or a diagram from its toolbar, or ask the AI to share one.

-
- {:else} -
    - {#each rows as r (r.id)} - {@const st = status(r)} - {@const mine = local[r.id]} -
  • - -
    -
    - {mine?.title ?? KIND[r.kind] ?? r.kind} - {#if r.hasPassword}{/if} -
    -
    - {KIND[r.kind] ?? r.kind} - - {r.views} view{r.views === 1 ? '' : 's'}{r.maxViews !== null ? ` of ${r.maxViews}` : ''} - - {st.label === 'Active' ? (r.expiresAt ? `Expires ${when(r.expiresAt)}` : 'Never expires') : st.label} - {#if r.lastViewedAt}Last opened {when(r.lastViewedAt)}{/if} -
    -
    - {#if r.active} - {#if mine} - - {/if} - - {/if} -
  • - {/each} -
- {/if} -
- {#if error && rows.length}

{error}

{/if} -
-
+{#if open} + +
+ (open = false)} /> +
+{/if} diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 8d289cf6..07e4e13f 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -1,4 +1,5 @@ { if (!v) close() }}> - - - Share {KIND_LABEL[src?.kind ?? ''] ?? ''} - - - Encrypted on this computer. The link holds the key; stroke.click can't read it. - + + + + + +
+ {link ? 'Link ready' : `Share ${kind.label}`} + + + End-to-end encrypted. Only people with the link can read it. + +
{#if link} -
-
- e.currentTarget.select()} aria-label="Share link" /> -
-

- Copied. Anyone with this link{usePassword && password ? ' and the password' : ''} can view it{access === 'once' ? ' once' : access === 'limit' ? ` up to ${viewLimit} times` : ''}{expiry ? `, for ${SHARE_EXPIRIES.find((e) => e.seconds === expiry)?.label}` : ''}. Revoke it any time in My shares. +

+ {#each summary as s (s)} + {s} + {/each} +
+

+ It's on your clipboard. The key is the part after #, so send the whole link{usePassword && password ? ', and the password separately' : ''}. Revoke it any time from Shared links.

-
- - + +
{:else} -
+
@@ -159,39 +214,44 @@ {#if tabular && src && 'columns' in src}
-
+
Columns - {keep.size} of {src.columns.length} + + {keep.size} of {colCount} shared{#if mask.size} · {mask.size} masked{/if} +
-
    +
      {#each src.columns as col, i (i)} {@const hit = sensitiveByIndex.get(i)} + {@const kept = keep.has(i)}
    • - toggleKeep(i)} class="size-3.5 shrink-0 accent-primary" aria-label="Include {col.name}" /> - {col.name} + toggleKeep(i)} class="size-3.5 shrink-0 accent-primary" aria-label="Include {col.name}" /> + {col.name} {#if hit} - {hit.why === 'name' ? 'Personal data?' : `Looks like ${hit.why}`} + + {hit.why === 'name' ? 'Sensitive' : hit.why} + {/if} -
    • {/each}
    -

    +

    {#if rowCount > rowCap} - Shares the first {rowCap.toLocaleString()} of {rowCount.toLocaleString()} rows{pro ? '' : ' on the free plan (Pro shares up to 100,000)'}. + Shares the first {rowCap.toLocaleString()} of {rowCount.toLocaleString()} rows{pro ? '' : '. Pro shares up to 100,000'}. {:else} - {rowCount.toLocaleString()} row{rowCount === 1 ? '' : 's'}. Masked values keep their shape (a••@e••••.com). + {rowCount.toLocaleString()} row{rowCount === 1 ? '' : 's'}. Masked values keep their shape, like a••@e••••.com. {/if}

{/if}
- Expires after -
+ Expires +
{#each SHARE_EXPIRIES as e (e.label)} {@const locked = e.seconds === null && !pro} + class={cn(seg, 'inline-flex items-center justify-center gap-1', expiry === e.seconds ? segOn : segOff)} + >{#if locked}{/if}{e.label} {/each}
- Who can open it -
- {#each [{ v: 'link', l: 'Anyone, any time' }, { v: 'once', l: 'Once, then gone' }, { v: 'limit', l: 'A few views' }] as a (a.v)} + Views +
+ {#each ACCESS as a (a.v)} + onclick={() => (access = a.v)} + class={cn(seg, 'inline-flex items-center justify-center gap-1.5', access === a.v ? segOn : segOff)} + >{a.l} {/each}
{#if access === 'limit'} + {:else if access === 'once'} +

The first person to open it gets it, then it's deleted. Link previews in chat apps don't count as a view.

{/if}
-
-
-
- - - +
diff --git a/src/lib/components/SharesPage.svelte b/src/lib/components/SharesPage.svelte new file mode 100644 index 00000000..583f7232 --- /dev/null +++ b/src/lib/components/SharesPage.svelte @@ -0,0 +1,315 @@ + + +
+ +
+

Shared links

+ {#if rows.length} +
+ + +
+
+ {#each [{ v: 'active', l: 'Active' }, { v: 'all', l: 'All' }] as f (f.v)} + + {/each} +
+ {/if} + + {#if onclose} + + {/if} +
+ +
+
+ {#if signedOut && loaded} +
+ +

Sign in to share

+

Share links live on your Stroke account, so you can see who opened them and revoke them from any device.

+ +
+ {:else if !loaded} +
+ Loading +
+ {:else} + + {#if plan} + {@const cap = plan.limits.maxActive} +
+ {activeCount} active + {totalViews.toLocaleString()} views + + {#if cap !== null} + + {activeCount} of {cap} links on Free + + = cap ? 'bg-warning' : 'bg-primary')} style="width: {Math.min(100, (activeCount / cap) * 100)}%"> + + + {:else} + PRO + {/if} +
+ {/if} + + {#if error && !signedOut} +

+ {error} +

+ {/if} + + {#if !rows.length} +
+ +

No shared links yet

+

+ Press Share above query results, a table, a chart or the schema diagram, or ask the AI to "share this chart". Everything is encrypted on this computer first. +

+
+ {:else if !shown.length} +

+ {query ? 'No links match your search.' : 'No active links.'} + {#if filter === 'active'}{/if} +

+ {:else} + {#if liveShown.length} + {@render section('Active', liveShown)} + {/if} + {#if endedShown.length} + {@render section('Ended', endedShown)} + {/if} +

+ + A link's key stays on the computer that made it, so links made elsewhere can't be copied here. Revoking deletes the content everywhere at once. +

+ {/if} + {/if} +
+
+
+ +{#snippet section(/** @type {string} */ label, /** @type {import('$lib/api.js').ShareRow[]} */ list)} +
+ {label} + {list.length} +
+
    + {#each list as r (r.id)} + {@const st = status(r)} + {@const mine = local[r.id]} + {@const k = kindOf(r.kind)} +
  • + + + +
    +
    + {mine?.title ?? k.label} + {#if r.hasPassword}{/if} + {#if r.maxViews === 1 && st.live}{/if} +
    +
    + {k.label} · {when(r.createdAt)} · {bytes(r.size)} +
    +
    + + +
    + + {r.views.toLocaleString()}{#if r.maxViews !== null}/{r.maxViews}{/if} + + + + {#if st.live}{r.expiresAt ? when(r.expiresAt) : 'No expiry'}{:else}{st.label}{/if} + +
    + + +
    + {#if confirmId === r.id} + Revoke this link? + + + {:else} + {#if mine && r.active} + + + {/if} + {#if r.active} + + {:else} + {st.label} + {/if} + {/if} +
    +
  • + {/each} +
+{/snippet} diff --git a/src/lib/components/Sidebar.svelte b/src/lib/components/Sidebar.svelte index 1b1e7b14..c2ce99dd 100644 --- a/src/lib/components/Sidebar.svelte +++ b/src/lib/components/Sidebar.svelte @@ -97,6 +97,8 @@ /** Sidebar footer (T3-style). */ onopensettings = () => {}, onopenshortcuts = () => {}, + /** Settings, on the Labs page. @type {(() => void) | null} */ + onopenlabs = null, oncheckupdates = () => {}, /** A manual update check is running: the button spins. */ checkingUpdate = false, @@ -3243,6 +3245,7 @@ + {#if onopenlabs}{/if} {#if updateState} diff --git a/src/lib/components/SqlConsole.svelte b/src/lib/components/SqlConsole.svelte index f9223acc..d2f2ffba 100644 --- a/src/lib/components/SqlConsole.svelte +++ b/src/lib/components/SqlConsole.svelte @@ -41,6 +41,7 @@ import Square from "@lucide/svelte/icons/square"; import Variable from "@lucide/svelte/icons/variable"; import X from "@lucide/svelte/icons/x"; + import Search from "@lucide/svelte/icons/search"; import TextCursorInput from "@lucide/svelte/icons/text-cursor-input"; import TextSelect from "@lucide/svelte/icons/text-select"; import { Button } from "$lib/components/ui/button/index.js"; @@ -601,7 +602,9 @@ if (!active) return const mod = e.metaKey || e.ctrlKey if (!mod || e.altKey) return - if (e.key === 'j' && !e.shiftKey) { + // Mod+Shift+J: Mod+J is the terminal dock everywhere, and binding it here + // too flipped the results and the terminal with one press. + if ((e.key === 'j' || e.key === 'J') && e.shiftKey) { e.preventDefault() toggleOutput() } else if ((e.key === 'b' || e.key === 'B') && e.shiftKey) { @@ -817,6 +820,56 @@ if (errorCopyTimer) clearTimeout(errorCopyTimer) }) + /** @type {any} */ + let chartViewRef = $state(null) + + // ── Find in results ─────────────────────────────────────────────────────── + // Narrows the grid to rows with a cell containing the text (any case) and + // highlights it. A windowed result is not all in memory, so there it only + // highlights what is loaded. + let findOpen = $state(false) + let findText = $state('') + /** @type {HTMLInputElement | null} */ + let findInput = $state(null) + const findTerm = $derived(findText.trim().toLowerCase()) + /** @param {unknown} v */ + const cellText = (v) => (v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v)) + const foundRows = $derived.by(() => { + const all = currentDisplay.rows + if (!findOpen || !findTerm || windowed) return all + return all.filter((/** @type {unknown[]} */ r) => r.some((v) => cellText(v).toLowerCase().includes(findTerm))) + }) + function openFind() { + findOpen = true + if (outputView !== 'table') outputView = 'table' + if (!outputVisible) toggleOutput() + tick().then(() => { findInput?.focus(); findInput?.select() }) + } + function closeFind() { + findOpen = false + findText = '' + } + /** @param {KeyboardEvent} e */ + function onFindKey(e) { + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeFind() } + } + + /** The results as a share source, in the order and columns shown. */ + function resultSource() { + const cols = currentDisplay.columns.map((/** @type {any} */ c) => ({ name: c.name ?? String(c), type: c.dataType ?? c.data_type ?? c.type })) + return { columns: cols, rows: currentDisplay.rows } + } + + /** Share what's on screen: the chart in Chart view, otherwise the rows. */ + function shareShown() { + const { columns: cols, rows: r } = resultSource() + if (outputView === 'chart' && chartViewRef?.shareSpec) { + requestShare({ kind: 'chart', title: shareTitle(), chart: chartViewRef.shareSpec(), columns: cols, rows: r }) + } else { + requestShare({ kind: 'result', title: shareTitle(), columns: cols, rows: r, sql }) + } + } + /** A share's default title: the query's first meaningful line. */ function shareTitle() { const line = sql.split('\n').map((l) => l.trim()).find((l) => l && !l.startsWith('--')) ?? 'Query' @@ -1064,7 +1117,7 @@ {#if columns.length > 0} - requestShare({ kind: 'result', title: shareTitle(), columns: columns.map((c) => ({ name: c.name ?? String(c), type: c.dataType ?? c.data_type ?? c.type })), rows, sql })}> + requestShare({ kind: 'result', title: shareTitle(), ...resultSource(), sql })}> Share results… @@ -1372,6 +1425,44 @@ {/each}
+ {#if resultShown && currentDisplay.rows.length > 0} + + {#if findOpen} + + {:else} + + {/if} + {/if}
@@ -1414,6 +1505,18 @@
+ {#if resultShown && currentDisplay.rows.length > 0 && (outputView === 'table' || outputView === 'chart' || outputView === 'json')} + + + {/if} {#if resultShown && currentDisplay.rows.length > 0} @@ -1451,7 +1554,7 @@ type="button" onclick={toggleOutput} class="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground" - title={tipText(outputVisible ? 'Hide results' : 'Show results', 'Collapse the results panel to give the editor the full height.', [mod, 'J'])} + title={tipText(outputVisible ? 'Hide results' : 'Show results', 'Collapse the results panel to give the editor the full height.', [mod, '⇧', 'J'])} > @@ -1460,7 +1563,19 @@
{#if outputVisible} -
+ +
··· {line.count} unchanged line{line.count !== 1 ? 's' : ''}
{line.lineB}+{line.content}
{line.lineA}−{line.content}
+ +
{line.lineA}{line.lineB}{line.content}
{line.lineA ?? ''}{line.lineB ?? ''}{line.type === 'add' ? '+' : line.type === 'remove' ? '−' : ' '} + {#if parts}{#each parts as p, k (k)}{#if p.changed}{p.text}{:else}{p.text}{/if}{/each}{:else}{line.content}{/if} +
+ + + + + + + + + + + + + + + + + + + +
AppVersion
{switchName}{switchInstalled ? 'Installed' : switchTo === 'nightly' ? 'Latest Nightly' : 'Latest release'}{switchInstalled ? 'opens' : 'downloads, then opens'}
This app{appVersion.replace(/-nightly\.\d+$/, '')}{#if /-nightly\./.test(appVersion)}Nightly{/if}quits, stays installed
+ {#if switchError}

{switchError}

{/if} +
+
+

+ Connections and settings stay with each app. Signed in, synced ones follow you. +

+
+ + +
+
+ + diff --git a/src/lib/components/UpdateDialog.svelte b/src/lib/components/UpdateDialog.svelte index 7ab6aef7..d874b0c6 100644 --- a/src/lib/components/UpdateDialog.svelte +++ b/src/lib/components/UpdateDialog.svelte @@ -16,10 +16,10 @@ import { updateCheck, updateDownload, updateStatus, updateRestart } from '$lib/api.js' import { loadSettings, updateSettings } from '$lib/stores/settings.js' import ReleaseNotes from './ReleaseNotes.svelte' - import Logo from './Logo.svelte' import { isRevealed } from '$lib/app-reveal.js' - import { parseChangelog, parseReleases, releasesBetween } from '$lib/changelog.js' + import { parseChangelog, parseReleases, releasesBetween, releasesInRange } from '$lib/changelog.js' import WhatsNewDialog from './WhatsNewDialog.svelte' + import { updateState, updateActions } from '$lib/stores/update-state.js' let { /** An update was found ('available'), or is downloaded and waiting ('ready'). */ @@ -52,8 +52,10 @@ /** First background check, once startup has settled. */ const FIRST_CHECK_MS = 5_000 - /** Stroke often stays open for days, so it looks again this often. */ + /** Stroke often stays open for days, so it looks again this often. Nightly + * ships several times a day, so it looks every hour. */ const RECHECK_MS = 6 * 60 * 60 * 1000 + const NIGHTLY_RECHECK_MS = 60 * 60 * 1000 /** Manually trigger an update check (e.g. from the command palette). */ export async function checkNow() { @@ -73,7 +75,13 @@ try { const info = await updateCheck() if (info?.staged) markReady(info, false) - else if (info) { + else if (info && loadSettings().autoUpdate) { + // Automatic updates: no window. It downloads in the background and + // says so once, then again when it is ready. + adopt(info) + toast.info(`Downloading Stroke ${info.version}`, { description: 'It downloads in the background and installs the next time Stroke starts.' }) + void install(true) + } else if (info) { adopt(info) status = 'available' onupdatefound('available') @@ -96,6 +104,14 @@ } } + // Settings → Updates shows the same state. + $effect(() => { + updateState.set({ status, checking, version: updateVersion, progress, applyOnQuit }) + }) + + /** "2.10.8" from "2.10.8-nightly.202611150842": the title stays one line. */ + const shortVersion = $derived(updateVersion.replace(/-nightly\.\d+$/, '')) + const visible = $derived( !dismissed && (status === 'available' || @@ -115,13 +131,22 @@ * The update's notes as releases: Nightly's feed carries CHANGELOG.md * sections for several versions (## [x.y.z]); a stable release carries one * version's sections without the heading. - * @type {import('$lib/changelog.js').ChangelogRelease[]} + * @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number }} */ - const changelog = $derived.by(() => { + const notes = $derived.by(() => { const many = parseReleases(releaseNotes) - if (many.length) return many + if (many.length) { + // The feed carries the whole recent changelog. Only what this install + // has not got yet: the versions after the running one, up to the update. + if (appVersion) { + const between = releasesInRange(many, appVersion, updateVersion, 8) + if (between.releases.length) return between + } + const own = many.filter((r) => r.version === updateVersion.replace(/-.*$/, '')) + return { releases: own.length ? own : many.slice(0, 1), omitted: 0 } + } const sections = parseChangelog(releaseNotes) - return sections.length ? [{ version: updateVersion, date: '', sections }] : [] + return { releases: sections.length ? [{ version: updateVersion, date: '', sections }] : [], omitted: 0 } }) // Actionable states are true modals (dark backdrop, blocks the app); @@ -137,6 +162,9 @@ let announceTimer onMount(() => { + updateActions.check = () => void checkNow() + updateActions.show = () => { dismissed = false } + updateActions.restart = () => void restart() import('@tauri-apps/api/app').then((m) => m.getVersion()).then((v) => (appVersion = v)).catch(() => {}) // Runs in dev too: it is a version comparison, not an update check, and a // dev build that has genuinely changed version should say so. @@ -147,10 +175,25 @@ .catch(() => { /* browser dev: no backend */ }) if (import.meta.env.DEV) return () => clearTimeout(announceTimer) const first = setTimeout(() => void backgroundCheck(), FIRST_CHECK_MS) - const again = setInterval(() => void backgroundCheck(), RECHECK_MS) + /** @type {ReturnType | undefined} */ + let again + import('@tauri-apps/api/app') + .then((m) => m.getVersion()) + .catch(() => '') + .then((v) => { again = setInterval(() => void backgroundCheck(), /-nightly/.test(v) ? NIGHTLY_RECHECK_MS : RECHECK_MS) }) + // Back at the computer after a while: look then too, rather than waiting + // out the timer. + let lastCheck = Date.now() + const onFocus = () => { + if (Date.now() - lastCheck < 30 * 60 * 1000) return + lastCheck = Date.now() + void backgroundCheck() + } + window.addEventListener('focus', onFocus) return () => { clearTimeout(first) clearInterval(again) + window.removeEventListener('focus', onFocus) clearTimeout(announceTimer) } }) @@ -231,7 +274,7 @@ let notes = { releases: [], omitted: 0 } try { const { default: markdown } = await import('../../../CHANGELOG.md?raw') - notes = releasesBetween(markdown, previous, current) + notes = releasesBetween(markdown, previous, current, 8) } catch (e) { console.error('[updater] changelog unavailable:', e) } @@ -325,7 +368,10 @@ * it always has. */ async function backgroundCheck() { - if (checking || status === 'available' || status === 'downloading' || status === 'ready') return + if (checking || status === 'downloading' || status === 'ready') return + // Offered and waiting: only worth asking again when it will download by + // itself (a quiet download that failed last time gets another go). + if (status === 'available' && !(loadSettings().autoUpdate && dismissed)) return if (status === 'error' && !dismissed) return let info try { @@ -375,7 +421,9 @@ } }) // Opened from the status bar mid-download: show the result there. + const unseen = dismissed markReady(info, dismissed) + if (unseen) announceReady(info) } catch (e) { console.error('[updater] download failed:', e) if (quiet && dismissed) { @@ -388,6 +436,22 @@ } } + /** + * A quiet download finished: say so once, with the one thing to do about it. + * Where the build installs on quit, nothing has to be done at all. + * @param {import('$lib/api.js').UpdateInfo} info + */ + function announceReady(info) { + toast.success(`Stroke ${info.version} is ready`, { + id: 'update-ready', + description: info.applyOnQuit + ? 'It installs when you quit, so the next start is the new version.' + : 'Restart Stroke to install it.', + duration: 10000, + action: { label: 'Restart now', onClick: () => void restart() }, + }) + } + async function restart() { if (restarting) return restarting = true @@ -455,33 +519,35 @@ >
-
- -
-

- {#if status === 'error'} - {failedAction === 'install' ? 'The download did not finish' : failedAction === 'restart' ? "Couldn't install the update" : "Couldn't check for updates"} - {:else if status === 'ready'} - Stroke {updateVersion} is ready - {:else if status === 'downloading'} - Downloading Stroke {updateVersion} - {:else} - Stroke {updateVersion} is available - {/if} -

+ +
+

+ {#if status === 'error'} + {failedAction === 'install' ? 'The download did not finish' : failedAction === 'restart' ? "Couldn't install the update" : "Couldn't check for updates"} + {:else if status === 'ready'} + Stroke {shortVersion} is ready + {:else if status === 'downloading'} + Downloading Stroke {shortVersion} + {:else} + Stroke {shortVersion} is available + {/if} +

+ {#if status === 'error'} +

{errorMsg}

+ {:else} +

+ {updateVersion} + {#if appVersion}· you have {appVersion.replace(/-nightly\.\d+$/, '')}{/if} +

- {#if status === 'error'} - {errorMsg} - {:else if status === 'ready'} - {applyOnQuit ? 'It installs when you quit Stroke. Restart now to use it straight away.' : 'Restart Stroke to finish installing it.'} - {#if appVersion} You have v{appVersion}.{/if} + {#if status === 'ready'} + {applyOnQuit ? 'It installs when you quit, so the next start is the new version. Restart now to use it straight away.' : 'Restart Stroke to finish installing it.'} {:else if status === 'downloading'} - {totalBytes > 0 ? `${fmt(downloadedBytes)} of ${fmt(totalBytes)}` : 'Starting…'} · it keeps going if you close this. - {:else} - {appVersion ? `You have v${appVersion}.` : 'A newer version of Stroke is out.'} + {totalBytes > 0 ? `${fmt(downloadedBytes)} of ${fmt(totalBytes)}` : 'Starting'}. It keeps going if you close this. {/if}

-
+ {/if} - + + +

+ {#if changeCount}{`${changeCount} ${changeCount === 1 ? 'change' : 'changes'}${releases.length > 1 ? ` across ${releases.length} versions` : ''}`}{/if} +

+
+ + +
diff --git a/src/lib/components/smoke.dom.test.js b/src/lib/components/smoke.dom.test.js index 0cdadb38..4a700061 100644 --- a/src/lib/components/smoke.dom.test.js +++ b/src/lib/components/smoke.dom.test.js @@ -112,3 +112,28 @@ describe('dialogs', () => { expect(search).toBeTruthy() }) }) + +describe('updates', () => { + const releases = [ + { version: '2.10.8', date: '2026-11-15', sections: [{ title: 'New Features', group: 'New Features', type: 'feature', items: ['Smoke tests gate Nightly'] }] }, + { version: '2.10.7', date: '2026-11-15', sections: [{ title: 'Changes', group: 'Changes', type: 'change', items: ['Inset tree rows'] }] }, + ] + + it("What's new lists each version on its own", async () => { + const { default: WhatsNewDialog } = await import('./WhatsNewDialog.svelte') + render(WhatsNewDialog, { open: true, current: '2.10.8-nightly.202611150842', previous: '2.10.6-nightly.1', releases }) + await settle() + const text = document.body.textContent ?? '' + expect(text).toContain('Stroke Nightly') + expect(text).toContain('2.10.7') + expect(text).toContain('2 changes across 2 versions') + }) + + it('Settings opens the switch dialog for the other track', async () => { + const { default: SettingsDialog } = await import('./SettingsDialog.svelte') + render(SettingsDialog, { open: true }) + await settle() + expect(document.body.textContent).toContain('Update track') + }) +}) + diff --git a/src/lib/stores/update-state.js b/src/lib/stores/update-state.js new file mode 100644 index 00000000..7626aa28 --- /dev/null +++ b/src/lib/stores/update-state.js @@ -0,0 +1,28 @@ +// What the updater is doing, for anything besides its own window that shows +// it (Settings → Updates). UpdateDialog owns the state and registers the +// actions; the rest only reads and asks. + +import { writable } from 'svelte/store' + +/** + * @typedef {{ + * status: 'idle' | 'available' | 'downloading' | 'ready' | 'error' | 'up-to-date', + * checking: boolean, + * version: string, + * progress: number, + * applyOnQuit: boolean, + * }} UpdateSnapshot + */ + +/** @type {import('svelte/store').Writable} */ +export const updateState = writable({ status: 'idle', checking: false, version: '', progress: 0, applyOnQuit: false }) + +/** Set by UpdateDialog once it is mounted. */ +export const updateActions = { + /** Look for an update now. */ + check: () => {}, + /** Open the update window for what was found. */ + show: () => {}, + /** Install the downloaded build and relaunch. */ + restart: () => {}, +} From 0d4910df689976d5ba7df96ba95394f411c0bf17 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:10:09 +0000 Subject: [PATCH 119/317] chore: version 2.10.9 (#205) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbab822f..df27d032 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.10.9] - 2026-11-15 + +### Changes +- Update notes per version; quiet auto-updates; Update track in Settings (#205) + + ## [2.10.8] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 49e31823..765aafa7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.10.8", + "version": "2.10.9", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 05565242..e9071269 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.10.8", + "version": "2.10.9", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 6160f66e9c3b84b3c6e785f84fe23acc82a31003 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 17:05:52 +0545 Subject: [PATCH 120/317] Keep a trackpad coast vertical when Shift goes down mid-scroll (#206) With a cell focused, redraws slowed the coast's tail past the 100 ms gesture gap, so the rest of the momentum was read as a new Shift gesture and the grid slid sideways. Shift pressed during or within 350 ms of a scroll now holds it vertical until the wheel is quiet for 350 ms, and gaps are timed from event timestamps. --- src/lib/components/DataTable.svelte | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index 45aa55fa..e7d9e9be 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -7902,17 +7902,36 @@ import FilterX from "@lucide/svelte/icons/filter-x"; // per event turned that coast sideways the moment Shift went down, or back // to vertical when it came up. A gap of more than GESTURE_GAP ms between // events starts a new gesture, which reads Shift afresh. + // + // Shift pressed during a scroll, or just after it seemed to stop, holds the + // scroll vertical until the wheel has been quiet for COAST_QUIET ms. A + // trackpad's coast thins out at its tail, and a busy frame (a focused cell + // redraws more) stretched the gap past GESTURE_GAP, so the rest of the + // coast was read as a new Shift gesture and the grid slid sideways. + // Gaps are timed from the events' own timestamps, which a stalled main + // thread does not stretch. const GESTURE_GAP = 100 + const COAST_QUIET = 350 let _gestureAt = -Infinity let _gestureShift = false + let _coastHold = false /** @param {WheelEvent} e @returns {boolean} the gesture scrolls sideways */ const gestureShift = (e) => { - const now = performance.now() - if (now - _gestureAt > GESTURE_GAP) _gestureShift = e.shiftKey + const now = e.timeStamp || performance.now() + const gap = now - _gestureAt + if (gap > (_coastHold ? COAST_QUIET : GESTURE_GAP)) { + _coastHold = false + _gestureShift = e.shiftKey + } _gestureAt = now return _gestureShift } - const gestureLive = () => performance.now() - _gestureAt <= GESTURE_GAP + const gestureLive = () => performance.now() - _gestureAt <= (_coastHold ? COAST_QUIET : GESTURE_GAP) + /** Shift went down: during or right after a vertical scroll, keep it vertical. @param {KeyboardEvent} e */ + const noteShift = (e) => { + if (e.type !== 'keydown' || e.key !== 'Shift' || e.repeat) return + if (!_gestureShift && performance.now() - _gestureAt <= COAST_QUIET) _coastHold = true + } // Non-passive: live for every tick under eased scrolling, otherwise only while // a modifier that needs preventDefault is down. @@ -8016,6 +8035,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; /** @param {KeyboardEvent} e */ let _detachTimer = 0 const onKey = (e) => { + noteShift(e) if (easedScroll) return clearTimeout(_detachTimer) if (e.ctrlKey || e.shiftKey || e.altKey) { attach(); return } From f86f225a9e51ece264df3ec39c4c60e75b913127 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:21:03 +0000 Subject: [PATCH 121/317] chore: version 2.11.0 (#206) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df27d032..d2fffe2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.11.0] - 2026-11-15 + +### Changes +- Keep a trackpad coast vertical when Shift goes down mid-scroll (#206) + + ## [2.10.9] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 765aafa7..05ff7b5d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.10.9", + "version": "2.11.0", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e9071269..e6ff19ea 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.10.9", + "version": "2.11.0", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From c50d819f01d514f2c5e43f2bc9ea6ea8ac10b16b Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 17:16:50 +0545 Subject: [PATCH 122/317] Native panel slides, zoom-proof switches, share dialog settings rows (#207) - The terminal dock and the AI panel slide open and closed: the edge moves, the content keeps its final size and is clipped, so the terminal never re-measures or flashes letter-spaced. Only a drag switches the terminal's renderer now. - The shared Switch is sized in rem, so its knob no longer outgrows the track when zoomed. - Share dialog: Expires and Views are dropdowns in one settings card with Password; columns get a Mask button instead of a switch; Create link shows Encrypting, then Uploading, with a progress bar; the link-ready view lists what the link was made with; Open uses the system browser. --- src/lib/components/ShareDialog.svelte | 224 +++++++++++++-------- src/lib/components/StudioShell.svelte | 66 +++++- src/lib/components/TerminalPage.svelte | 11 +- src/lib/components/ui/switch/switch.svelte | 4 +- src/lib/panel-motion.js | 76 +++++++ src/lib/share-flow.js | 6 +- 6 files changed, 285 insertions(+), 102 deletions(-) create mode 100644 src/lib/panel-motion.js diff --git a/src/lib/components/ShareDialog.svelte b/src/lib/components/ShareDialog.svelte index 69c4276b..a3828006 100644 --- a/src/lib/components/ShareDialog.svelte +++ b/src/lib/components/ShareDialog.svelte @@ -7,6 +7,7 @@ import { Button } from '$lib/components/ui/button/index.js' import { Switch } from '$lib/components/ui/switch/index.js' import Icon from './Icon.svelte' + import SelectMenu from './SelectMenu.svelte' import { cn } from '$lib/utils.js' import { shareList } from '$lib/api.js' import { detectSensitiveColumns } from '$lib/share-crypto.js' @@ -45,6 +46,8 @@ let sensitive = $state([]) let busy = $state(false) + /** Which step a Create link is on, for the button and the bar. */ + let stage = $state(/** @type {'encrypt' | 'upload'} */ ('encrypt')) let error = $state('') let link = $state('') let copied = $state(false) @@ -116,11 +119,12 @@ error = '' try { const payload = buildPayload(src, { title, keep, mask, rowCap }) + stage = 'encrypt' const res = await publishShare(payload, { expiresIn: expiry, maxViews: access === 'once' ? 1 : access === 'limit' ? Math.max(1, Math.min(10000, Math.round(viewLimit) || 1)) : null, password: usePassword && password ? password : null, - }) + }, (st) => (stage = st)) link = res.url await copy() } catch (e) { @@ -140,6 +144,16 @@ function openMyShares() { close(); openSharesPage() } + /** In the default browser. window.open does nothing inside the app's webview. */ + async function openLink() { + try { + const { openUrl } = await import('@tauri-apps/plugin-opener') + await openUrl(link) + } catch { + window.open(link, '_blank', 'noopener,noreferrer') + } + } + const ACCESS = /** @type {const} */ ([ { v: 'link', l: 'Anyone with the link', icon: 'link-2' }, { v: 'once', l: 'One view, then gone', icon: 'flame' }, @@ -147,25 +161,36 @@ ]) const expiryLabel = $derived(SHARE_EXPIRIES.find((e) => e.seconds === expiry)?.label ?? '') + /** What the link was made with, as label and value rows. */ const summary = $derived([ - expiry ? `Expires in ${expiryLabel}` : 'Never expires', - access === 'once' ? 'One view' : access === 'limit' ? `${viewLimit} views` : 'Unlimited views', - usePassword && password ? 'Password' : null, - ].filter(Boolean)) + { k: 'Expires', v: expiry ? `In ${expiryLabel.toLowerCase()}` : 'Never' }, + { k: 'Views', v: access === 'once' ? 'One, then deleted' : access === 'limit' ? `Up to ${viewLimit}` : 'Unlimited' }, + { k: 'Password', v: usePassword && password ? 'Required' : 'None' }, + ]) const lbl = 'text-ui-xs font-medium text-foreground' const hint = 'text-ui-2xs leading-relaxed text-muted-foreground' const tinp = 'field-surface h-9 w-full bg-transparent px-2.5 text-ui-sm text-foreground placeholder:text-muted-foreground outline-none transition-colors' - const seg = 'h-7 min-w-0 truncate rounded-md px-2 text-ui-xs font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-45' - const segOn = 'bg-background text-foreground shadow-xs' - const segOff = 'text-muted-foreground hover:text-foreground' + const row = 'flex items-center gap-x-4 gap-y-2.5 border-b border-border/40 px-3.5 py-3 last:border-0' + + /** "Never" is Pro: picking it without Pro says so instead of switching. */ + let lockedNote = $state('') + /** @param {string} v */ + function pickExpiry(v) { + if (v === 'never' && !pro) { + lockedNote = 'Links that never expire are part of Stroke Pro.' + return + } + lockedNote = '' + expiry = v === 'never' ? null : Number(v) + } { if (!v) close() }}> - - + +
{link ? 'Link ready' : `Share ${kind.label}`} @@ -177,65 +202,83 @@ {#if link} - +
-
+
- e.currentTarget.select()} aria-label="Share link" /> - +
-
- {#each summary as s (s)} - {s} +
+ {#each summary as r (r.k)} +
+
{r.k}
+
{r.v}
+
{/each} -
+

It's on your clipboard. The key is the part after #, so send the whole link{usePassword && password ? ', and the password separately' : ''}. Revoke it any time from Shared links.

-
- -
{:else} -
+
{#if tabular && src && 'columns' in src} -
+
- Columns + Columns {keep.size} of {colCount} shared{#if mask.size} · {mask.size} masked{/if}
-
    + +
      {#each src.columns as col, i (i)} {@const hit = sensitiveByIndex.get(i)} {@const kept = keep.has(i)} -
    • + {@const masked = mask.has(i)} +
    • toggleKeep(i)} class="size-3.5 shrink-0 accent-primary" aria-label="Include {col.name}" /> - {col.name} - {#if hit} - + + {col.name} + {#if col.type}{col.type}{/if} + + {#if hit && !masked} + {hit.why === 'name' ? 'Sensitive' : hit.why} {/if} - +
    • {/each}
    @@ -246,66 +289,64 @@ {rowCount.toLocaleString()} row{rowCount === 1 ? '' : 's'}. Masked values keep their shape, like a••@e••••.com. {/if}

    -
+ {/if} -
- Expires -
- {#each SHARE_EXPIRIES as e (e.label)} - {@const locked = e.seconds === null && !pro} - - {/each} + +
+
+
+

Expires

+

{lockedNote || (expiry ? `The link stops working after ${expiryLabel.toLowerCase()}.` : 'The link keeps working until you revoke it.')}

+
+ pickExpiry(v)} + items={SHARE_EXPIRIES.map((e) => ({ value: e.seconds === null ? 'never' : String(e.seconds), label: e.label, hint: e.seconds === null && !pro ? 'Pro' : undefined }))} + />
-
- -
- Views -
- {#each ACCESS as a (a.v)} - - {/each} +
+
+

Views

+ {#if access === 'limit'} + + {:else} +

{access === 'once' ? "The first person to open it gets it, then it's deleted. Link previews don't count." : 'Anyone with the link can open it, as often as they like.'}

+ {/if} +
+ (access = v)} + items={ACCESS.map((a) => ({ value: a.v, label: a.l, icon: a.icon }))} + />
- {#if access === 'limit'} - - {:else if access === 'once'} -

The first person to open it gets it, then it's deleted. Link previews in chat apps don't count as a view.

- {/if} -
- -
-
-
- +
+
+

Password {#if plan && !pro}PRO{/if} - - Part of the key, so the link alone won't open it. +

+

Part of the key, so the link alone won't open it.

(usePassword = v === true)} aria-label="Protect with a password" /> + {#if usePassword} + + {/if}
- {#if usePassword} - - {/if} -
+ {#if planError || error}

@@ -314,14 +355,21 @@ {/if}

-
- - +
{/if} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 2d7c11c8..13538534 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -1,6 +1,7 @@ Date: Sun, 15 Nov 2026 12:01:22 +0000 Subject: [PATCH 129/317] chore: version 2.11.4 (#210) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c929e196..80d54d9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.11.4] - 2026-11-15 + +### Changes +- Live mode on every engine; all terminal suggestions; glossy plan chips (#210) + + ## [2.11.3] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 7214c9d5..78787045 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.11.3", + "version": "2.11.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9d5181f2..a4735eb1 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.11.3", + "version": "2.11.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 9f9d1628a8cf0c2c121d5d758821a49796f9322e Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 17:51:18 +0545 Subject: [PATCH 130/317] One search field with /; tighter Shared links; Settings follows changes from anywhere (#211) - SearchField: a filled field with the / keycap and a clear button, used by Shared links, Keyboard shortcuts and Settings. / now focuses the Shared links and shortcuts searches (they ranked below the sidebar's, or not at all). - Shared links: 48px header, 44px rows, smaller tiles and type, the plan as a glossy chip. - Settings reloads its copy on every settings write and whenever it opens. Toggling the tree sidebar from the command palette left the switch showing the old state, because bits-ui does not call onOpenChange when the dialog is opened from code. --- .../components/KeyboardShortcutsPage.svelte | 23 +------- src/lib/components/SearchField.svelte | 56 +++++++++++++++++++ src/lib/components/SettingsDialog.svelte | 29 ++++------ src/lib/components/SharesPage.svelte | 38 +++++-------- src/lib/stores/settings.js | 8 +++ 5 files changed, 94 insertions(+), 60 deletions(-) create mode 100644 src/lib/components/SearchField.svelte diff --git a/src/lib/components/KeyboardShortcutsPage.svelte b/src/lib/components/KeyboardShortcutsPage.svelte index e30b9779..13ff0e53 100644 --- a/src/lib/components/KeyboardShortcutsPage.svelte +++ b/src/lib/components/KeyboardShortcutsPage.svelte @@ -1,4 +1,5 @@ + +
+ + (focused = true)} + onblur={() => (focused = false)} + onkeydown={(e) => { + if (e.key === 'Escape' && value) { e.stopPropagation(); value = '' } + onkeydown(e) + }} + class="no-field-frame h-8 w-full rounded-lg border-0 bg-muted/55 pr-8 pl-8 text-ui-xs text-foreground outline-none transition-colors placeholder:text-muted-foreground hover:bg-muted/75 focus:bg-muted/80 focus-visible:ring-1 focus-visible:ring-ring/60" + /> + {#if value} + + {:else if !focused} +
diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 898d2327..9c09c687 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -1,5 +1,5 @@
diff --git a/src/lib/components/RedisKeyspacePage.svelte b/src/lib/components/RedisKeyspacePage.svelte index 8cd2d05b..418cc091 100644 --- a/src/lib/components/RedisKeyspacePage.svelte +++ b/src/lib/components/RedisKeyspacePage.svelte @@ -681,6 +681,12 @@ : filterInput.trim() || typeFilter ? `${rows.length.toLocaleString()} matching${done ? '' : '+'}` : `${rows.length.toLocaleString()} of ${dbSize.toLocaleString()} ${plural(dbSize, "key")}`, ) + // ⌘R, or an agent's change: reload the keys on screen. + $effect(() => { + const on = () => { if (active) reload() } + window.addEventListener('stroke:refresh-view', on) + return () => window.removeEventListener('stroke:refresh-view', on) + }) diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 8e308282..7a7ef27a 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -316,7 +316,7 @@ engineFamily, } from '$lib/stores/connections.js' import { hasPro, FREE_CONNECTION_LIMIT } from '$lib/stores/license.js' - import { engineSupports, engineLabel } from '$lib/db-capabilities.js' + import { engineSupports, engineLabel, isKeyValue } from '$lib/db-capabilities.js' import * as Dialog from '$lib/components/ui/dialog/index.js' import KeyRound from '@lucide/svelte/icons/key-round' import { @@ -3896,6 +3896,13 @@ let rowSearch = $state('') await refreshDashboardCharts() return } + // Document stores and Redis browse in pages of their own: they reload on + // this event, and the sidebar's collections and keys re-list beside them. + if (activeTab?.kind === 'docs' || activeTab?.kind === 'redis') { + window.dispatchEvent(new CustomEvent('stroke:refresh-view')) + await loadTables({ force: true, quiet: true }) + return + } await loadTables({ force: true }) } @@ -7664,6 +7671,12 @@ let rowSearch = $state('') const ran = pending.join(';\n') pending = [] void refreshAfterSql(sqlRunEffects(ran)) + // Mongo, Redis, Elasticsearch...: their statements are not SQL, so the + // effects above read nothing. Their pages reload, and the sidebar. + if (isKeyValue(connection?.type)) { + window.dispatchEvent(new CustomEvent('stroke:refresh-view')) + void loadTables({ force: true, quiet: true }) + } }, 300) })) offs.push(await listen('mcp-refresh', () => { if (connection) void handleRefresh() })) From 47a1d90f4ea4fafc9fb8d441af8bdf6b78e4c5c1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:59:01 +0000 Subject: [PATCH 149/317] chore: version 2.12.4 (#220) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fce0cf8..01c923d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.12.4] - 2026-11-15 + +### Changes +- NoSQL pages: Mod+R and agent changes reload them; no flicker on refresh (#220) + + ## [2.12.3] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 0d6931fe..736d28a8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.12.3", + "version": "2.12.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 79458aa7..52438bd8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.12.3", + "version": "2.12.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 3a9e47306883be4847fdc18b24e3496839b9a3b0 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 18:50:19 +0545 Subject: [PATCH 150/317] Sync saved queries, charts, dashboards and query folders (#221) Sync carried workspaces, connections and a settings bundle (app settings, AI profiles, remapped shortcuts). Saved queries, saved charts, chart groups, dashboards and query folders stayed on one machine. - query: one record per saved query, from a copy of the IndexedDB store kept current by every write; sync waits for it to load so a device never looks empty. Deleting a saved query sends a tombstone. - library: one record per connection with its saved charts, chart groups, dashboards and query folders (connection ids match across devices). Writing one reloads the open connection's charts and dashboards; the Saved list and folders reload on a sync event. - Synced settings add the tree sidebar, AI in a tab, streamed results, lazy wide columns and live mode. - The engine skips a kind it has no store for. The server accepts the two kinds (stroke-web #53); clients that predate them skip records of kinds they do not know. --- src/lib/components/SidebarQueries.svelte | 6 +++ src/lib/components/StudioShell.svelte | 6 +++ src/lib/stores/dashboards.js | 8 +++ src/lib/stores/query-folders.js | 3 ++ src/lib/stores/query-history.js | 51 ++++++++++++++++++ src/lib/stores/saved-charts.js | 9 ++++ src/lib/sync/changes.js | 2 +- src/lib/sync/engine.js | 4 +- src/lib/sync/policy.js | 2 +- src/lib/sync/runtime.js | 66 ++++++++++++++++++++++++ 10 files changed, 154 insertions(+), 3 deletions(-) diff --git a/src/lib/components/SidebarQueries.svelte b/src/lib/components/SidebarQueries.svelte index 4ace40d8..75db7c3d 100644 --- a/src/lib/components/SidebarQueries.svelte +++ b/src/lib/components/SidebarQueries.svelte @@ -52,6 +52,12 @@ try { collapsed = new Set(JSON.parse(localStorage.getItem(collapsedKey(cid)) ?? '[]')) } catch { collapsed = new Set() } }) }) + // Folders synced from another device. + $effect(() => { + const on = () => { folders = loadQueryFolders(connectionId) } + window.addEventListener('stroke:library-synced', on) + return () => window.removeEventListener('stroke:library-synced', on) + }) /** @param {QueryFolder[]} next */ function setFolders(next) { folders = next diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 7a7ef27a..d1ab541f 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -2357,6 +2357,12 @@ let rowSearch = $state('') $effect(() => { if (commandOpen && persistConnectionId) void refreshQueryStores() }) + // Saved queries and folders arriving from another device. + $effect(() => { + const on = () => void refreshQueryStores() + window.addEventListener('stroke:library-synced', on) + return () => window.removeEventListener('stroke:library-synced', on) + }) $effect(() => { // Reload recents, charts, and dashboards whenever the active connection changes diff --git a/src/lib/stores/dashboards.js b/src/lib/stores/dashboards.js index 05b9985d..f2ab242c 100644 --- a/src/lib/stores/dashboards.js +++ b/src/lib/stores/dashboards.js @@ -1,3 +1,4 @@ +import { notifyLocalChange } from '$lib/sync/changes.js' import { writable } from 'svelte/store' import { debounce } from '$lib/utils.js' @@ -51,6 +52,7 @@ export const activeDashboardId = writable(/** @type {string | null} */ (null)) // resize, add) don't JSON.stringify + write on every change. const persistDashboards = debounce((/** @type {Dashboard[]} */ v, /** @type {string} */ connId) => { try { localStorage.setItem(KEY(connId), JSON.stringify(v)) } catch {} + notifyLocalChange('library') }, 300) dashboards.subscribe(v => { if (!_connId) return @@ -142,3 +144,9 @@ export function reorderItems(dashId, newOrder) { return { ...d, items: [...reordered, ...rest] } })) } + +/** Re-read the open connection's dashboards (sync wrote new ones). */ +export function reloadDashboards() { + if (!_connId) return + dashboards.set(loadDashboards(_connId)) +} diff --git a/src/lib/stores/query-folders.js b/src/lib/stores/query-folders.js index 94b0dade..a9c59dd1 100644 --- a/src/lib/stores/query-folders.js +++ b/src/lib/stores/query-folders.js @@ -3,6 +3,8 @@ * per-connection lists (chart groups, diagrams). The queries themselves stay in * IndexedDB and point at a folder by id; see query-folders.js for the tree. */ + +import { notifyLocalChange } from '$lib/sync/changes.js' import { normalizeFolders } from '$lib/query-folders.js' /** @param {string | null | undefined} connId */ @@ -28,6 +30,7 @@ export function saveQueryFolders(connId, folders) { try { if (folders.length) localStorage.setItem(queryFoldersKey(connId), JSON.stringify(normalizeFolders(folders))) else localStorage.removeItem(queryFoldersKey(connId)) + notifyLocalChange('library') } catch { // Quota/serialization failure must not throw into the sidebar. } diff --git a/src/lib/stores/query-history.js b/src/lib/stores/query-history.js index 6ad8d467..aaf58bc5 100644 --- a/src/lib/stores/query-history.js +++ b/src/lib/stores/query-history.js @@ -1,5 +1,6 @@ import { getStudioDb, STORES } from '$lib/stores/studio-db.js' import { loadSettings, DEFAULT_MAX_QUERY_HISTORY } from '$lib/stores/settings.js' +import { notifyLocalChange, recordDeletion } from '$lib/sync/changes.js' const HISTORY_STORE = STORES.queryHistory const SAVED_STORE = STORES.savedQueries @@ -183,6 +184,7 @@ export async function createSavedQuery(connectionId, name, sql, { folderId = nul }) const db = await getStudioDb() await db.put(SAVED_STORE, saved) + savedChanged(saved) return saved } @@ -236,6 +238,7 @@ export async function updateSavedQuery(id, patch) { else delete next.folderId } await db.put(SAVED_STORE, next) + savedChanged(next) return next } @@ -243,10 +246,58 @@ export async function updateSavedQuery(id, patch) { export async function deleteSavedQuery(id) { const db = await getStudioDb() await db.delete(SAVED_STORE, id) + _savedSnapshot.delete(id) + recordDeletion('query', id) } /** Put back a saved query removed a moment ago (Undo). @param {SavedQuery} entry */ export async function restoreSavedQuery(entry) { const db = await getStudioDb() await db.put(SAVED_STORE, entry) + savedChanged(entry) +} + +// ── Sync ────────────────────────────────────────────────────────────────────── +// The sync engine reads every record synchronously, and saved queries live in +// IndexedDB, so it reads this copy: loaded once at start, kept current by every +// write above and by sync itself. + +/** @type {Map} */ +const _savedSnapshot = new Map() +let _snapshotLoaded = false + +/** @param {SavedQuery} q */ +function savedChanged(q) { + _savedSnapshot.set(q.id, q) + notifyLocalChange('query') +} + +/** Load the copy once (the sync runtime awaits this before its first run). */ +export async function loadSavedSnapshot() { + if (_snapshotLoaded) return + try { + const db = await getStudioDb() + for (const q of await db.getAll(SAVED_STORE)) _savedSnapshot.set(q.id, q) + } catch { /* no IndexedDB (tests): nothing to sync */ } + _snapshotLoaded = true +} + +/** Every saved query, for sync. @returns {SavedQuery[]} */ +export function savedSnapshot() { + return [..._savedSnapshot.values()] +} + +/** Sync writes a saved query from another device. @param {SavedQuery} q */ +export async function applySyncedQuery(q) { + if (!q?.id || !q.connectionId) return + _savedSnapshot.set(q.id, q) + const db = await getStudioDb() + await db.put(SAVED_STORE, q) +} + +/** Sync removes one deleted on another device. @param {string} id */ +export async function removeSyncedQuery(id) { + _savedSnapshot.delete(id) + const db = await getStudioDb() + await db.delete(SAVED_STORE, id) } diff --git a/src/lib/stores/saved-charts.js b/src/lib/stores/saved-charts.js index c40fab0f..f582ba54 100644 --- a/src/lib/stores/saved-charts.js +++ b/src/lib/stores/saved-charts.js @@ -3,6 +3,7 @@ * Charts are scoped per database connection - switching connections loads * that connection's charts. An empty connectionId shows nothing. */ +import { notifyLocalChange } from '$lib/sync/changes.js' import { writable } from 'svelte/store' import { debounce } from '$lib/utils.js' @@ -65,6 +66,14 @@ function loadGroups(connectionId) { /** @param {any} v @param {string} key */ function persist(v, key) { try { localStorage.setItem(key, JSON.stringify(v)) } catch {} + notifyLocalChange('library') +} + +/** Re-read the open connection's charts and groups (sync wrote new ones). */ +export function reloadChartsConnection() { + if (!_connId) return + savedCharts.set(loadCharts(_connId)) + chartGroups.set(loadGroups(_connId)) } export const savedCharts = writable(/** @type {SavedChart[]} */ ([])) diff --git a/src/lib/sync/changes.js b/src/lib/sync/changes.js index e59a61e2..dd698b87 100644 --- a/src/lib/sync/changes.js +++ b/src/lib/sync/changes.js @@ -6,7 +6,7 @@ // no imports on purpose: the stores import it, and the engine imports the // stores, so it must not import either. -/** @typedef {'workspace' | 'connection' | 'settings'} SyncKind */ +/** @typedef {'workspace' | 'connection' | 'settings' | 'query' | 'library'} SyncKind */ /** @typedef {{ kind: SyncKind, id: string, at: number }} Tombstone */ const TOMBSTONES_KEY = 'stroke:sync:tombstones' diff --git a/src/lib/sync/engine.js b/src/lib/sync/engine.js index ef242a68..f36635ff 100644 --- a/src/lib/sync/engine.js +++ b/src/lib/sync/engine.js @@ -39,7 +39,7 @@ import { loadTombstones, saveTombstones, withLocalChangesMuted } from './changes export const META_KEY = 'stroke:sync:meta' export const CURSOR_KEY = 'stroke:sync:cursor' export const INIT_KEY = 'stroke:sync:initialized' -export const KINDS = /** @type {SyncKind[]} */ (['workspace', 'connection', 'settings']) +export const KINDS = /** @type {SyncKind[]} */ (['workspace', 'connection', 'settings', 'query', 'library']) const ID_RE = /^[A-Za-z0-9_-]{1,128}$/ const PUSH_ROUNDS = 3 @@ -153,6 +153,8 @@ export function createSyncEngine({ invoke, adapters, storage = globalThis.localS function collectLocal() { const out = new Map() for (const kind of KINDS) { + // A kind this caller has no store for (tests, a partial runtime) has nothing local. + if (!adapters[kind]) continue for (const { id, data } of adapters[kind].list()) { if (typeof id === 'string' && ID_RE.test(id)) out.set(recordKey(kind, id), { kind, id, data }) } diff --git a/src/lib/sync/policy.js b/src/lib/sync/policy.js index c2fc2695..424bb594 100644 --- a/src/lib/sync/policy.js +++ b/src/lib/sync/policy.js @@ -16,7 +16,7 @@ export const SYNCED_SETTINGS = /** @type {const} */ ([ 'defaultDataView', 'paginationMode', 'nullSortOrder', 'previewDmlBeforeApply', 'sqlUndo', 'maxQueryHistory', 'autoSaveQueries', 'cmdkAiEnabled', 'sidebarComments', 'sidebarRememberGroups', 'agentChatFontSize', 'agentCodeFontSize', 'agentThinkingStyle', 'agentShowQueryCards', - 'shareDefaults', + 'shareDefaults', 'sidebarStyle', 'aiInTab', 'streamResults', 'lazyWideColumns', 'liveModeEnabled', ]) /** @param {Record} s */ diff --git a/src/lib/sync/runtime.js b/src/lib/sync/runtime.js index 1be35758..b40c8bd6 100644 --- a/src/lib/sync/runtime.js +++ b/src/lib/sync/runtime.js @@ -12,6 +12,9 @@ import { loadSettings, updateSettings } from '$lib/stores/settings.js' import { aiProfiles, activeProfileId, replaceProfiles } from '$lib/stores/ai-settings.js' import { keybindings, replaceKeybindings } from '$lib/stores/keybindings.js' import { onLocalChange } from './changes.js' +import { savedSnapshot, loadSavedSnapshot, applySyncedQuery, removeSyncedQuery } from '$lib/stores/query-history.js' +import { reloadChartsConnection } from '$lib/stores/saved-charts.js' +import { reloadDashboards } from '$lib/stores/dashboards.js' import { createSyncEngine, resetSyncBookkeeping, clearSyncBookkeeping } from './engine.js' import { pickSyncedSettings } from './policy.js' @@ -47,6 +50,20 @@ const adapters = { conflictCopy: (data) => upsertConnection({ ...data, id: newConnectionId(), name: `${data.name || 'Connection'} (conflicted copy)` }), }, + // One saved query per record (the editor's Saved list). + query: { + list: () => savedSnapshot().map((q) => ({ id: q.id, data: q })), + upsert: (data) => void applySyncedQuery(data), + remove: (id) => void removeSyncedQuery(id), + }, + // One connection's saved charts, chart groups, dashboards and query + // folders. Connection ids are the same on every device, so the record id is + // the connection's. + library: { + list: () => libraryRecords(), + upsert: (data) => applyLibrary(data), + remove: () => {}, + }, settings: { list: () => [ { @@ -71,6 +88,48 @@ const adapters = { }, } +/** localStorage keys a connection's library is made of, by field. */ +const LIBRARY_KEYS = /** @type {const} */ ({ + charts: 'stroke:saved-charts:', + chartGroups: 'stroke:chart-groups:', + dashboards: 'stroke:dashboards:', + queryFolders: 'stroke:query-folders:', +}) + +/** Every connection's library from localStorage. */ +function libraryRecords() { + /** @type {Map>} */ + const byConn = new Map() + try { + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i) ?? '' + for (const [field, prefix] of Object.entries(LIBRARY_KEYS)) { + if (!key.startsWith(prefix)) continue + const id = key.slice(prefix.length) + if (!id) continue + let value + try { value = JSON.parse(localStorage.getItem(key) ?? 'null') } catch { continue } + if (value == null) continue + const rec = byConn.get(id) ?? { id } + rec[field] = value + byConn.set(id, rec) + } + } + } catch { /* storage blocked */ } + return [...byConn.values()].map((data) => ({ id: data.id, data })) +} + +/** Write a connection's library from another device, then reload what is open. @param {Record} data */ +function applyLibrary(data) { + if (!data?.id) return + for (const [field, prefix] of Object.entries(LIBRARY_KEYS)) { + if (data[field] === undefined) continue + try { localStorage.setItem(prefix + data.id, JSON.stringify(data[field])) } catch { /* full */ } + } + reloadChartsConnection() + reloadDashboards() +} + const engine = createSyncEngine({ invoke, adapters, @@ -79,6 +138,10 @@ const engine = createSyncEngine({ if (kinds.has('connection')) { try { window.dispatchEvent(new CustomEvent('stroke:connections-synced')) } catch { /* no window */ } } + // The Saved list and the query folders read on demand: tell them to. + if (kinds.has('query') || kinds.has('library')) { + try { window.dispatchEvent(new CustomEvent('stroke:library-synced')) } catch { /* no window */ } + } }, }) @@ -204,6 +267,9 @@ async function runOnce() { // Whatever changed until now goes out with this run. pendingLocal = false try { + // Saved queries are read from a copy loaded out of IndexedDB; never run + // before it is there, or this device would look as if it had none. + await loadSavedSnapshot() const r = await engine.run() const last = { lastSyncedAt: Date.now(), items: r.items } try { localStorage.setItem(LAST_KEY, JSON.stringify(last)) } catch { /* shown, not kept */ } From 0e7e559831cbc18478825096318db48d715d3c93 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:05:30 +0000 Subject: [PATCH 151/317] chore: version 2.12.5 (#221) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c923d8..e8030fc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.12.5] - 2026-11-15 + +### Changes +- Sync saved queries, charts, dashboards and query folders (#221) + + ## [2.12.4] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 736d28a8..f5ef8f44 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.12.4", + "version": "2.12.5", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 52438bd8..6d2feaaa 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.12.4", + "version": "2.12.5", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 8d2a0769ddb1925f37aef19ca1488ef518bd64f1 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 18:53:18 +0545 Subject: [PATCH 152/317] Saved charts: search, group filter, one menu per chart, share (#222) - A toolbar with the count, a search, a group filter and New group; compact cards (preview, name, type and date) instead of a hover overlay full of small buttons. - Each chart has one menu: open the query, Share, add to a dashboard (or a new one), move to a group, rename, delete. Groups get the same menu. - Share re-runs the chart's read-only query and opens the share dialog with the rows as they are now; a write statement is refused. --- src/lib/components/ChartsPage.svelte | 583 +++++++++------------------ 1 file changed, 200 insertions(+), 383 deletions(-) diff --git a/src/lib/components/ChartsPage.svelte b/src/lib/components/ChartsPage.svelte index 658d21a6..3d365c50 100644 --- a/src/lib/components/ChartsPage.svelte +++ b/src/lib/components/ChartsPage.svelte @@ -34,6 +34,15 @@ import LayoutDashboard from "@lucide/svelte/icons/layout-dashboard"; import LayoutGrid from "@lucide/svelte/icons/layout-grid"; import Plus from "@lucide/svelte/icons/plus"; + import Share2 from "@lucide/svelte/icons/share-2"; + import MoreHorizontal from "@lucide/svelte/icons/more-horizontal"; + import LoaderCircle from "@lucide/svelte/icons/loader-circle"; + import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js"; + import SearchField from "./SearchField.svelte"; + import SelectMenu from "./SelectMenu.svelte"; + import { executeSql } from "$lib/api.js"; + import { isWriteSql } from "$lib/sql-write.js"; + import { requestShare } from "$lib/share-flow.js"; /** * @typedef {import('$lib/stores/connections.js').SavedConnection} SavedConnection @@ -68,13 +77,53 @@ /** @type {string | null} */ let dashPickerChartId = $state(null); - // Charts per group (derived) - const chartsByGroup = $derived( - $chartGroups.map((g) => ({ - group: g, - charts: $savedCharts.filter((c) => c.group === g), - })), - ); + let query = $state(""); + /** "" = every group. */ + let groupFilter = $state(""); + /** The chart whose share is being prepared (its query re-runs). */ + let sharingId = $state(/** @type {string | null} */ (null)); + + // Charts per group, after the search and the group filter. + const chartsByGroup = $derived.by(() => { + const q = query.trim().toLowerCase(); + return $chartGroups + .filter((g) => !groupFilter || g === groupFilter) + .map((g) => ({ + group: g, + charts: $savedCharts.filter( + (c) => c.group === g && (!q || c.name.toLowerCase().includes(q) || (catalogEntry(c.config.type)?.label ?? c.config.type).toLowerCase().includes(q)), + ), + })); + }); + const shownCount = $derived(chartsByGroup.reduce((n, g) => n + g.charts.length, 0)); + + /** + * Share a saved chart: its query runs again (read only) so the link carries + * the rows as they are now, then the share dialog opens with them. + * @param {import('$lib/stores/saved-charts.js').SavedChart} chart + */ + async function shareChart(chart) { + if (!chart.sql?.trim()) { toast.error("This chart has no query to share"); return; } + if (isWriteSql(chart.sql)) { toast.error("Only charts made from a read-only query can be shared"); return; } + sharingId = chart.id; + try { + const r = await executeSql(chart.sql); + const columns = (r?.columns ?? []).map((/** @type {any} */ c) => ({ name: c.name, type: c.dataType ?? c.data_type })); + const rows = r?.rows ?? []; + if (!rows.length) { toast.message("The query returned no rows to share"); return; } + requestShare({ + kind: "chart", + title: chart.name, + chart: { type: chart.config.type, x: chart.config.xCol, y: [chart.config.yCol].filter(Boolean), group: chart.config.groupCol ?? null }, + columns, + rows, + }); + } catch (e) { + toast.error("Couldn't run the chart's query", { description: String(/** @type {any} */ (e)?.message ?? e) }); + } finally { + sharingId = null; + } + } const totalCharts = $derived($savedCharts.length); @@ -176,6 +225,11 @@ toast.success("SQL opened in Query Editor"); } + /** Focus a field as it appears (rename, new group). @param {HTMLInputElement} el */ + function focusOnMount(el) { + queueMicrotask(() => { el.focus(); el.select(); }); + } + const btnIconSm = "inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"; @@ -209,405 +263,168 @@
{:else}
- -
- - Saved charts - - {totalCharts} - -
- {#if !newGroupOpen} - - {:else} -
- { - if (e.key === "Enter") commitNewGroup(); - if (e.key === "Escape") { - newGroupOpen = false; - } - }} - /> - - -
- {/if} -
+ +
+ {:else} + + {/if}
- -
+
{#if totalCharts === 0} - -
-
- -
-
-

No saved charts yet

-

- Save charts from the Query Editor to see them here -

-
-
- Run a query - - Chart tab - - Save chart -
+
+ +

No saved charts yet

+

Run a query, switch its result to the chart view, and save it. It shows up here, ready to share or put on a dashboard.

+ {:else if shownCount === 0} +

No charts match.

{:else}
{#each chartsByGroup as grpData (grpData.group)} {#if grpData.charts.length > 0} -
- -
- +
+
{#if renamingGroupName === grpData.group} -
- { - if (e.key === "Enter") commitRenameGroup(); - if (e.key === "Escape") { - renamingGroupName = null; - } - }} - /> - - -
+ { + if (e.key === "Enter") commitRenameGroup(); + if (e.key === "Escape") renamingGroupName = null; + }} + onblur={commitRenameGroup} + use:focusOnMount + /> {:else} -

- {grpData.group} -

- {grpData.charts.length} +

{grpData.group}

+ {grpData.charts.length} {#if grpData.group !== "Default"} - - + + + + + + startRenameGroup(grpData.group)}>Rename group + handleDeleteGroup(grpData.group)}>Delete group + + {/if} {/if}
-
-
- {#each grpData.charts as chart (chart.id)} - {@const entry = catalogEntry(chart.config.type)} -
- -
- {#if chart.previewOption && Object.keys(chart.previewOption).length > 0} - - {:else if chart.aiSpec} - -
- -
- {:else} -
- -
- {/if} - - -
-
- -
- +
+
+ {#if renamingChartId === chart.id} + { + if (e.key === "Enter") commitRenameChart(); + if (e.key === "Escape") renamingChartId = null; }} - > - - Dashboard - - {#if dashPickerChartId === chart.id} -
- {#each $dashboards as d (d.id)} - - {/each} -
- -
-
- {/if} -
+ onblur={commitRenameChart} + use:focusOnMount + /> + {:else} +

{chart.name}

+ {/if} +

{entry?.label ?? chart.config.type} · {fmtDate(chart.createdAt)}

-
- -
- - {#if moveChartId === chart.id} -
- {#each $chartGroups.filter((g) => g !== chart.group) as g (g)} - + {#if sharingId === chart.id} + + {/if} + + + + + + handleRunSql(chart)}>Open the query + void shareChart(chart)}>Share… + + Add to dashboard + + {#each $dashboards as d (d.id)} + addToDashboardById(chart.id, d.id)}>{d.name} {/each} - {#if $chartGroups.filter((g) => g !== chart.group).length === 0} -

- No other groups -

- {/if} -
+ {#if $dashboards.length}{/if} + addToNewDashboard(chart.id)}>New dashboard + + + {#if $chartGroups.length > 1} + + Move to group + + {#each $chartGroups.filter((g) => g !== chart.group) as g (g)} + handleMoveChart(chart.id, g)}>{g} + {/each} + + {/if} -
- -
+ startRenameChart(chart.id)}>Rename + + { deleteChart(chart.id); toast.success("Chart deleted"); }}>Delete + +
-
- - -
- {#if renamingChartId === chart.id} -
- { - if (e.key === "Enter") commitRenameChart(); - if (e.key === "Escape") { - renamingChartId = null; - } - }} - /> - - -
- {:else} - {chart.name} - {/if} - {entry?.label ?? chart.config.type} -
-
- {/each} -
-
-
- {/if} - {/each} - - - {#each chartsByGroup as grpData (grpData.group)} - {#if grpData.charts.length === 0} -
-
- -

- {grpData.group} -

- 0 - {#if grpData.group !== "Default"} - - {/if} -
-
- No charts in this group + + {/each} +
{/if} From 223c53669d9cca6c7d4f8eaf4309c1bf4f138844 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:08:29 +0000 Subject: [PATCH 153/317] chore: version 2.12.6 (#222) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8030fc8..7801297b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.12.6] - 2026-11-15 + +### Changes +- Saved charts: search, group filter, one menu per chart, share (#222) + + ## [2.12.5] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index f5ef8f44..3fa3fa1d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.12.5", + "version": "2.12.6", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 6d2feaaa..772ee707 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.12.5", + "version": "2.12.6", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From b883afd4109a7708025a3a4739fea38ed39f141b Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 18:55:32 +0545 Subject: [PATCH 154/317] Chat code blocks: visible Copy, solid Run, readable request bodies (#223) Copy and Open in the editor are always visible (Copy says Copied for a moment) instead of appearing only on hover, Run is a solid button, and an Elasticsearch-style request shows its JSON body laid out over lines. Copy and Run still use the text exactly as written. --- src/lib/components/AiChat.svelte | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/lib/components/AiChat.svelte b/src/lib/components/AiChat.svelte index e60b3456..f72e81fd 100644 --- a/src/lib/components/AiChat.svelte +++ b/src/lib/components/AiChat.svelte @@ -4198,6 +4198,19 @@ } }); const isMacChrome = typeof document !== 'undefined' && document.documentElement.dataset.os === 'macos' + /** The block whose Copy was just pressed, for its "Copied" moment. */ + let copiedBlock = $state('') + /** + * A Dev Tools request (METHOD path, then a JSON body) with its body laid out + * over lines, for reading. Copy and Run use the text as written. + * @param {string} text + */ + function prettyBlock(text) { + const t = String(text ?? '').trim() + const m = /^(GET|POST|PUT|DELETE|HEAD)\s+\S+[^\n]*\n([\s\S]+)$/i.exec(t) + if (!m) return text + try { return `${t.split('\n')[0]}\n${JSON.stringify(JSON.parse(m[2]), null, 2)}` } catch { return text } + } + ({ value: col, label: col, hint: colTypeOf(col), icon: colIcon(col), keywords: [col] }))]} + align="start" + contentClass="w-64 max-w-[min(20rem,80vw)]" + placeholder="Search columns" + onselect={(it) => { if (it) onpick(String(it.value ?? '')) }} + > + {#snippet trigger(props)} + + {/snippet} + {#snippet item(it)} + + {it.label} + {#if it.hint}{it.hint}{/if} + {#if String(it.value) === String(value)}{/if} + {/snippet} + {/snippet} {#if requiredAxes.x} diff --git a/src/lib/components/FieldSelect.svelte b/src/lib/components/FieldSelect.svelte index b145ada9..8e173823 100644 --- a/src/lib/components/FieldSelect.svelte +++ b/src/lib/components/FieldSelect.svelte @@ -8,7 +8,9 @@ * flat options array - so converting a call site is a one-line change rather * than fifteen lines of Root/Trigger/Content boilerplate. */ - import * as Select from '$lib/components/ui/select/index.js' + import SearchableMenu from './SearchableMenu.svelte' + import ChevronDown from '@lucide/svelte/icons/chevron-down' + import Check from '@lucide/svelte/icons/check' import { cn } from '$lib/utils.js' let { @@ -52,27 +54,38 @@ {...rest} >{label || placeholder} {:else} - { - if (v == null) return - value = v - onchange(v) + + ({ value: String(o.value), label: o.label ?? String(o.value), disabled: o.disabled, keywords: [String(o.value)] }))} + align="start" + contentClass={cn('z-[130] w-[var(--bits-popover-anchor-width)] min-w-[10rem]', contentClass)} + onselect={(it) => { + if (!it || it.disabled) return + value = it.value + onchange(it.value) }} > - - {label || placeholder} - - - {#each options as opt (opt.value)} - {opt.label ?? opt.value} - {/each} - - + {#snippet trigger(props)} + + {/snippet} + {#snippet item(it)} + {it.label} + {#if String(it.value) === String(value)}{/if} + {/snippet} + {/if} From 8aaf6d58736fa934eb4e97e6ab1a6358919130ba Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:15:34 +0000 Subject: [PATCH 157/317] chore: version 2.12.8 (#224) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e949944..a6bd1a54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.12.8] - 2026-11-15 + +### Changes +- Chart pickers and FieldSelect are searchable (#224) + + ## [2.12.7] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index a4fd46af..418dbd5f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.12.7", + "version": "2.12.8", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 4c2a90ff..fe890863 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.12.7", + "version": "2.12.8", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From c5ba4ed02934593faac233e5ab8558193615e021 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 19:08:04 +0545 Subject: [PATCH 158/317] Terminal: steady font while resizing, Oracle via SQLcl thin, panel animation setting (#225) - Dragging the terminal dock no longer swaps to the DOM renderer, which drew the same font heavier and wider until the drag ended. Bold is one step up (600) instead of a full 700. - SQLcl starts with -thin. It otherwise picked the OCI driver whenever an Instant Client was nearby and failed with "no ocijdbc23 in java.library.path" whatever the password. - Settings > Appearance > Animate panels turns the terminal and AI panel slide off (synced). --- src-tauri/src/db/terminal.rs | 19 ++++++++++++++++--- src/lib/components/SettingsDialog.svelte | 8 ++++++++ src/lib/components/TerminalPage.svelte | 13 +++++++------ src/lib/panel-motion.js | 2 ++ src/lib/stores/settings.js | 8 ++++++-- src/lib/sync/policy.js | 2 +- 6 files changed, 40 insertions(+), 12 deletions(-) diff --git a/src-tauri/src/db/terminal.rs b/src-tauri/src/db/terminal.rs index 46ee5fed..a947c8a2 100644 --- a/src-tauri/src/db/terminal.rs +++ b/src-tauri/src/db/terminal.rs @@ -624,11 +624,21 @@ fn mssql_launch(c: &MssqlConfig) -> Launch { /// `sqlplus user@connect_string`. Neither SQL*Plus nor SQLcl reads a password /// from the environment, and one on the command line is visible to every /// process, so the client asks for it in the terminal. -fn oracle_launch(c: &OracleConfig) -> Launch { +/// SQL*Plus takes the target alone. SQLcl gets `-thin` first: it otherwise +/// switches to the OCI (thick) driver whenever it sees an Instant Client or an +/// Oracle Home nearby, and without Oracle's native library on its +/// java.library.path that fails with "no ocijdbc23 in java.library.path", +/// whatever the password. The thin driver needs nothing installed. +fn oracle_launch(c: &OracleConfig, sqlcl: bool) -> Launch { let cs = super::oracle::connect_string(c); let user = c.user.trim(); let target = if user.is_empty() { format!("/@{cs}") } else { format!("{user}@{cs}") }; - Launch { args: vec![target], env: Vec::new(), unset: &["TWO_TASK"], tunnel: None } + let mut args = Vec::new(); + if sqlcl { + args.push("-thin".to_string()); + } + args.push(target); + Launch { args, env: Vec::new(), unset: &["TWO_TASK"], tunnel: None } } fn redis_launch(c: &RedisConfig) -> Launch { @@ -915,7 +925,10 @@ async fn open_session( } AnyConnectionConfig::Sqlite(c) => sqlite_launch(&c, client_version(&binary).await.as_deref()), AnyConnectionConfig::Mssql(c) => mssql_launch(&c), - AnyConnectionConfig::Oracle(c) => oracle_launch(&c), + AnyConnectionConfig::Oracle(c) => { + let sqlcl = binary.file_stem().and_then(|s| s.to_str()).is_some_and(|s| s.eq_ignore_ascii_case("sql")); + oracle_launch(&c, sqlcl) + } AnyConnectionConfig::Redis(c) => redis_launch(&c), // The URI carries host, credentials and options; mongosh reads it as is. // `--quiet` drops the startup banner. diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 9c09c687..793ff738 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -1701,6 +1701,14 @@ />
{/if} + {#if show('Animate panels', 'Slide the terminal and the AI panel open and closed')} + {@render switchRow( + 'Animate panels', + 'The terminal dock and the AI panel slide open and closed. Off, they appear at once.', + settings.panelMotion !== false, + () => { settings = updateSettings({ panelMotion: settings.panelMotion === false }); }, + )} + {/if} {#if show('Alternating row colors', 'Shade every other grid row')} {@render switchRow( 'Alternating row colors', diff --git a/src/lib/components/TerminalPage.svelte b/src/lib/components/TerminalPage.svelte index bd6ee56b..e860482d 100644 --- a/src/lib/components/TerminalPage.svelte +++ b/src/lib/components/TerminalPage.svelte @@ -1250,6 +1250,10 @@ // table borders join from row to row. Any taller and the DOM renderer // leaves a gap in every vertical line. lineHeight: 1, + // Bold one step up rather than a full 700: a client's bold prompts and + // headings read as emphasis, not as a different, heavier face. + fontWeight: 'normal', + fontWeightBold: '600', // A blinking block: what Terminal.app, iTerm and every shell default to. cursorBlink: true, cursorStyle: 'block', @@ -1329,12 +1333,9 @@ cancelAnimationFrame(fitFrame) clearTimeout(fitTimer) if (document.documentElement.hasAttribute('data-resizing')) { - // A drag: the DOM renderer while the edge moves, WebGL once it settles. - // Only a drag: opening the dock or the panel used to switch renderers - // too, and the DOM one measured its cells while the panel was still - // collapsed, so the text flashed letter-spaced. - disableGpu() - enableGpuSoon() + // A drag keeps the WebGL renderer: switching to the DOM one while the + // edge moved drew the same font heavier and wider, so the text changed + // weight under the pointer and changed back when it was let go. const since = performance.now() - lastFitAt if (since > 50) { lastFitAt = performance.now(); fitFrame = requestAnimationFrame(fit) } fitTimer = setTimeout(() => { lastFitAt = performance.now(); fitFrame = requestAnimationFrame(fit) }, 50) diff --git a/src/lib/panel-motion.js b/src/lib/panel-motion.js index 09c2f780..36a6d503 100644 --- a/src/lib/panel-motion.js +++ b/src/lib/panel-motion.js @@ -15,6 +15,8 @@ export const PANEL_MS = 220 /** @returns {boolean} */ export function panelMotionOff() { if (typeof document === 'undefined') return true + // Settings → Appearance → Animate panels, off. + if (document.documentElement.getAttribute('data-panel-motion') === 'off') return true const pref = document.documentElement.getAttribute('data-motion') if (pref === 'full') return false if (pref === 'reduced') return true diff --git a/src/lib/stores/settings.js b/src/lib/stores/settings.js index b16c10cb..18207b53 100644 --- a/src/lib/stores/settings.js +++ b/src/lib/stores/settings.js @@ -107,7 +107,7 @@ const markQualifyDefaultApplied = () => { /** @typedef {'claude' | 'geist' | 'serif' | 'apple' | 'inter' | 'mono' | 'fira' | 'plex' | 'space' | 'source'} FontId */ /** @typedef {'regular' | 'light' | 'bold'} IconStyleId */ /** @typedef {'lucide' | 'hugeicons' | 'phosphor'} IconSetId */ -/** @typedef {{ theme: ThemeId, zoom: number, font: FontId, iconStyle: IconStyleId, iconSet: IconSetId, tableStyle: TableStyleId, jsonTheme: JsonThemeId, editorTheme: import('$lib/themes/editor-themes.js').EditorThemeId, mcpAutoStart: boolean, launchAtLogin: boolean, autoUpdate: boolean, autoReconnectOnStartup: boolean, previewDmlBeforeApply: boolean, defaultDataView: string, paginationMode: string, maxQueryHistory: number, connectTimeoutMs: number, socketTimeoutMs: number, maxAllowedPacket: number, sessionTimezone: string, vimMode: boolean, cmdkAiEnabled: boolean, liveModeEnabled: boolean, sidebarStyle: SidebarStyleId, aiInTab: boolean, lazyWideColumns: boolean, nullSortOrder: string, agentChatFontSize: number, agentCodeFontSize: number, agentThinkingStyle: string, agentShowQueryCards: boolean, agentWebAccess: boolean, tableTextAlign: string, telemetry: boolean, jsonWordWrap: boolean, nativeScroll: boolean, rowSpacing: RowSpacingId, motion: MotionId, zebraRows: boolean, showRowNumbers: boolean, showMenuBar: boolean, numberGrouping: boolean, imagePreview: boolean, openUrlsOnClick: boolean, highlightActiveRow: boolean, fkAutoExpandJson: boolean, gridFontSize: number, autoSaveQueries: boolean, streamResults: boolean, sqlUndo: boolean, sidebarComments: boolean, sidebarRememberGroups: boolean, sqlFormat: import('$lib/sql-format-options.js').SqlFormatOptions, sqlEditor: import('$lib/sql-editor-options.js').SqlEditorOptions, shareDefaults: Record | null }} AppSettings */ +/** @typedef {{ theme: ThemeId, zoom: number, font: FontId, iconStyle: IconStyleId, iconSet: IconSetId, tableStyle: TableStyleId, jsonTheme: JsonThemeId, editorTheme: import('$lib/themes/editor-themes.js').EditorThemeId, mcpAutoStart: boolean, launchAtLogin: boolean, autoUpdate: boolean, autoReconnectOnStartup: boolean, previewDmlBeforeApply: boolean, defaultDataView: string, paginationMode: string, maxQueryHistory: number, connectTimeoutMs: number, socketTimeoutMs: number, maxAllowedPacket: number, sessionTimezone: string, vimMode: boolean, cmdkAiEnabled: boolean, liveModeEnabled: boolean, sidebarStyle: SidebarStyleId, aiInTab: boolean, lazyWideColumns: boolean, nullSortOrder: string, agentChatFontSize: number, agentCodeFontSize: number, agentThinkingStyle: string, agentShowQueryCards: boolean, agentWebAccess: boolean, tableTextAlign: string, telemetry: boolean, jsonWordWrap: boolean, nativeScroll: boolean, rowSpacing: RowSpacingId, motion: MotionId, panelMotion: boolean, zebraRows: boolean, showRowNumbers: boolean, showMenuBar: boolean, numberGrouping: boolean, imagePreview: boolean, openUrlsOnClick: boolean, highlightActiveRow: boolean, fkAutoExpandJson: boolean, gridFontSize: number, autoSaveQueries: boolean, streamResults: boolean, sqlUndo: boolean, sidebarComments: boolean, sidebarRememberGroups: boolean, sqlFormat: import('$lib/sql-format-options.js').SqlFormatOptions, sqlEditor: import('$lib/sql-editor-options.js').SqlEditorOptions, shareDefaults: Record | null }} AppSettings */ /** * UI type scale in design pixels: `[step, font-size, line-height?]`, matching @@ -568,6 +568,8 @@ export const DEFAULT_SETTINGS = { nativeScroll: defaultNativeScroll(), rowSpacing: DEFAULT_ROW_SPACING, motion: DEFAULT_MOTION, + // The terminal dock and the AI panel slide open and closed. Off: they appear at once. + panelMotion: true, // SQL formatter preferences. Defaults live with the formatter (format-sql.js) // so there is one source for what a valid option set is. sqlFormat: { ...SQL_FORMAT_DEFAULTS }, @@ -957,6 +959,7 @@ export function loadSettings() { } const rowSpacing = normalizeRowSpacing(parsed.rowSpacing) const motion = normalizeMotion(parsed.motion) + const panelMotion = parsed.panelMotion !== false const sqlFormat = normalizeSqlFormat(parsed.sqlFormat) const sqlEditor = normalizeSqlEditor(parsed.sqlEditor) const shareDefaults = parsed.shareDefaults && typeof parsed.shareDefaults === 'object' && !Array.isArray(parsed.shareDefaults) ? parsed.shareDefaults : null @@ -992,7 +995,7 @@ export function loadSettings() { const agentShowQueryCards = parsed.agentShowQueryCards === true const agentWebAccess = parsed.agentWebAccess === true const tableTextAlign = TABLE_ALIGN_IDS.includes(parsed.tableTextAlign) ? parsed.tableTextAlign : DEFAULT_TABLE_ALIGN - _settingsCache = { theme, zoom, font, iconStyle, iconSet, tableStyle, jsonTheme, editorTheme, mcpAutoStart, launchAtLogin, autoUpdate, autoReconnectOnStartup, previewDmlBeforeApply, defaultDataView, paginationMode, maxQueryHistory, connectTimeoutMs, socketTimeoutMs, maxAllowedPacket, sessionTimezone, vimMode, cmdkAiEnabled, liveModeEnabled, sidebarStyle, aiInTab, lazyWideColumns, nullSortOrder, agentChatFontSize, agentCodeFontSize, agentThinkingStyle, agentShowQueryCards, agentWebAccess, tableTextAlign, telemetry, jsonWordWrap, nativeScroll, rowSpacing, motion, zebraRows, showRowNumbers, showMenuBar, numberGrouping, imagePreview, openUrlsOnClick, highlightActiveRow, fkAutoExpandJson, gridFontSize, autoSaveQueries, streamResults, sqlUndo, sidebarComments, sidebarRememberGroups, sqlFormat, sqlEditor, shareDefaults } + _settingsCache = { theme, zoom, font, iconStyle, iconSet, tableStyle, jsonTheme, editorTheme, mcpAutoStart, launchAtLogin, autoUpdate, autoReconnectOnStartup, previewDmlBeforeApply, defaultDataView, paginationMode, maxQueryHistory, connectTimeoutMs, socketTimeoutMs, maxAllowedPacket, sessionTimezone, vimMode, cmdkAiEnabled, liveModeEnabled, sidebarStyle, aiInTab, lazyWideColumns, nullSortOrder, agentChatFontSize, agentCodeFontSize, agentThinkingStyle, agentShowQueryCards, agentWebAccess, tableTextAlign, telemetry, jsonWordWrap, nativeScroll, rowSpacing, motion, panelMotion, zebraRows, showRowNumbers, showMenuBar, numberGrouping, imagePreview, openUrlsOnClick, highlightActiveRow, fkAutoExpandJson, gridFontSize, autoSaveQueries, streamResults, sqlUndo, sidebarComments, sidebarRememberGroups, sqlFormat, sqlEditor, shareDefaults } // A migrated value is saved at once, or the next launch reads the old one. if (settingsMigrated) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(_settingsCache)) } catch {} @@ -1241,6 +1244,7 @@ function applySettingsNow(settings, root, theme, zoom, dark) { // query in app.css decides; the other two override it in either direction. const motion = normalizeMotion(settings.motion) setAttr(root, 'data-motion', motion === 'system' ? null : motion) + setAttr(root, 'data-panel-motion', settings.panelMotion === false ? 'off' : null) setStore(appMotion, motion) const iconStyle = normalizeIconStyle(settings.iconStyle) diff --git a/src/lib/sync/policy.js b/src/lib/sync/policy.js index 424bb594..fd406cb1 100644 --- a/src/lib/sync/policy.js +++ b/src/lib/sync/policy.js @@ -9,7 +9,7 @@ * web access). AI keys never leave the keychain; AI profiles sync without them. */ export const SYNCED_SETTINGS = /** @type {const} */ ([ - 'theme', 'font', 'iconStyle', 'iconSet', 'motion', + 'theme', 'font', 'iconStyle', 'iconSet', 'motion', 'panelMotion', 'tableStyle', 'rowSpacing', 'zebraRows', 'showRowNumbers', 'numberGrouping', 'gridFontSize', 'tableTextAlign', 'highlightActiveRow', 'imagePreview', 'openUrlsOnClick', 'fkAutoExpandJson', 'jsonTheme', 'jsonWordWrap', 'editorTheme', 'vimMode', 'sqlFormat', 'sqlEditor', From 3ddee7f8a01da7bf0c8c86f92f4e9cf4da272ffb Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:23:15 +0000 Subject: [PATCH 159/317] chore: version 2.12.9 (#225) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6bd1a54..29eb78c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.12.9] - 2026-11-15 + +### Changes +- Terminal: steady font while resizing, Oracle via SQLcl thin, panel animation setting (#225) + + ## [2.12.8] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 418dbd5f..568be231 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.12.8", + "version": "2.12.9", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index fe890863..f2f27eac 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.12.8", + "version": "2.12.9", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From f98d2053b9c95423ca787c493baa8d16e9eb7238 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 19:13:23 +0545 Subject: [PATCH 160/317] Schema snapshots: searchable connection, tidy cards, readable migration (#226) - New snapshot picks the connection from a searchable menu (engine logo, name, type, the active one marked) instead of a radio row per saved connection; the title is a proper field. - Snapshot cards keep the date and table count on their own line; Base and Compare are one small two-part control beside delete. - Migration SQL: the warnings fold to one line until opened, the script is in the highlighted read-only editor, and Open in editor sits beside Copy. --- src/lib/components/SchemaTimelinePage.svelte | 182 +++++++++---------- src/lib/components/StudioShell.svelte | 1 + 2 files changed, 92 insertions(+), 91 deletions(-) diff --git a/src/lib/components/SchemaTimelinePage.svelte b/src/lib/components/SchemaTimelinePage.svelte index f969af0e..8f57125a 100644 --- a/src/lib/components/SchemaTimelinePage.svelte +++ b/src/lib/components/SchemaTimelinePage.svelte @@ -1,4 +1,9 @@
diff --git a/src/lib/components/RedisKeyspacePage.svelte b/src/lib/components/RedisKeyspacePage.svelte index 418cc091..0c523110 100644 --- a/src/lib/components/RedisKeyspacePage.svelte +++ b/src/lib/components/RedisKeyspacePage.svelte @@ -52,7 +52,7 @@ */ /** @type {{ active?: boolean, connection?: import('$lib/stores/connections.js').SavedConnection | null }} */ - let { active = false, connection = null } = $props() + let { active = false, connection = null, live = false } = $props() // ── Sidebar: databases, views, namespaces ─────────────────────────────── /** @typedef {'keys' | 'insights' | 'slowlog' | 'clients' | 'pubsub'} RedisView */ @@ -687,6 +687,24 @@ window.addEventListener('stroke:refresh-view', on) return () => window.removeEventListener('stroke:refresh-view', on) }) + // Live mode: the keys on screen reload every few seconds, unless edits are staged. + $effect(() => { + if (!live || !active) return + let busy = false + const timer = setInterval(async () => { + if (busy || document.hidden || staged.length > 0 || loading) return + busy = true + try { + // The first page as it is now, compared with what is on screen: only + // a real change reloads (keeping the rest of the list otherwise). + const page = await redisKeyPage('0', { pattern: toPattern(filterInput), type: typeFilter, target: PAGE_TARGET }) + const strip = (/** @type {any[]} */ list) => JSON.stringify(list.map(({ at: _at, ...r }) => r)) + if (strip(page.rows) !== strip(rows.slice(0, page.rows.length))) reload() + } catch { /* the next tick tries again */ } + finally { busy = false } + }, 3000) + return () => clearInterval(timer) + }) diff --git a/src/lib/components/StatusBar.svelte b/src/lib/components/StatusBar.svelte index c7337598..74c25917 100644 --- a/src/lib/components/StatusBar.svelte +++ b/src/lib/components/StatusBar.svelte @@ -750,7 +750,7 @@ {/if} - {#if showTableNav && liveSupported && $appLiveMode} + {#if liveSupported && $appLiveMode} {@render sep()} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index a5f73381..f03d1cde 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -10119,7 +10119,7 @@ let rowSearch = $state('') > {#await import('./RedisKeyspacePage.svelte')}{:then { default: RedisKeyspacePage }} - + {/await}
@@ -10155,6 +10155,7 @@ let rowSearch = $state('') {#key dbType} scrollTableLeft()} onscrolltableright={() => scrollTableRight()} live={liveEnabled} - {liveSupported} + liveSupported={liveSupported && (activeTab?.kind === 'table' || activeTab?.kind === 'docs' || activeTab?.kind === 'redis')} {liveNative} ontogglelive={() => { liveEnabled = !liveEnabled }} onswitchconnection={handleSwitchDatabase} From 837ad8561f0142a6ace319b7f33bb1caebf81181 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:54:52 +0000 Subject: [PATCH 169/317] chore: version 2.13.4 (#230) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3382f477..49e52040 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.13.4] - 2026-11-15 + +### Changes +- Live mode on MongoDB, the other document stores and Redis (#230) + + ## [2.13.3] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 5464030f..94ceb090 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.13.3", + "version": "2.13.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 31b1525a..3b725676 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.13.3", + "version": "2.13.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From ce0d659c16054bb8f78bc6430f1cf2998d18d643 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 19:44:59 +0545 Subject: [PATCH 170/317] Share: titles from what is shared, chart preview; simpler New view (#231) - A shared chart is titled after what it plots ("Product count by category"), query results after the table they read, instead of the first line of SQL. - The share dialog draws the chart above its columns, so you see what the link will show before making it. - New view (Postgres) is three lines, CREATE ... AS SELECT * FROM table, without the WHERE true filler. --- src/lib/components/ShareDialog.svelte | 27 +++++++++++++++++++++++++ src/lib/components/SqlConsole.svelte | 8 ++++---- src/lib/components/StudioShell.svelte | 4 ++-- src/lib/object-templates.js | 3 +-- src/lib/share-flow.js | 29 +++++++++++++++++++++++++++ src/lib/share-titles.test.js | 21 +++++++++++++++++++ 6 files changed, 84 insertions(+), 8 deletions(-) create mode 100644 src/lib/share-titles.test.js diff --git a/src/lib/components/ShareDialog.svelte b/src/lib/components/ShareDialog.svelte index ae8042b9..c1abb0fb 100644 --- a/src/lib/components/ShareDialog.svelte +++ b/src/lib/components/ShareDialog.svelte @@ -8,6 +8,8 @@ import { Switch } from '$lib/components/ui/switch/index.js' import Icon from './Icon.svelte' import SelectMenu from './SelectMenu.svelte' + import { buildOption } from '$lib/chart-utils.js' + import { isCurrentThemeDark } from '$lib/stores/settings.js' import { cn } from '$lib/utils.js' import { shareList } from '$lib/api.js' import { detectSensitiveColumns } from '$lib/share-crypto.js' @@ -185,6 +187,22 @@ lockedNote = '' expiry = v === 'never' ? null : Number(v) } + /** The chart's own option, for the preview (masked columns hidden, as shared). */ + const chartOption = $derived.by(() => { + if (src?.kind !== 'chart') return null + try { + return buildOption({ + type: src.chart.type, + columns: src.columns, + rows: src.rows.slice(0, 500), + xCol: src.chart.x, + yCol: src.chart.y?.[0] ?? '', + groupCol: src.chart.group ?? undefined, + isDark: $isCurrentThemeDark, + noTitle: true, + }) + } catch { return null } + }) { if (!v) close() }}> @@ -241,6 +259,15 @@
+ {#if src?.kind === 'chart' && chartOption} + +
+ {#await import('./EChartPanel.svelte') then { default: EChartPanel }} + + {/await} +
+ {/if} + {#if tabular && src && 'columns' in src}
diff --git a/src/lib/components/SqlConsole.svelte b/src/lib/components/SqlConsole.svelte index d2f2ffba..c5ecfa89 100644 --- a/src/lib/components/SqlConsole.svelte +++ b/src/lib/components/SqlConsole.svelte @@ -14,7 +14,7 @@ import ChevronDown from "@lucide/svelte/icons/chevron-down"; import Download from "@lucide/svelte/icons/download"; import Share2 from "@lucide/svelte/icons/share-2"; - import { requestShare } from "$lib/share-flow.js"; + import { requestShare, chartTitle, resultsTitle } from "$lib/share-flow.js"; import Table2 from "@lucide/svelte/icons/table-2"; import SlidersHorizontal from "@lucide/svelte/icons/sliders-horizontal"; import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js"; @@ -864,7 +864,8 @@ function shareShown() { const { columns: cols, rows: r } = resultSource() if (outputView === 'chart' && chartViewRef?.shareSpec) { - requestShare({ kind: 'chart', title: shareTitle(), chart: chartViewRef.shareSpec(), columns: cols, rows: r }) + const spec = chartViewRef.shareSpec() + requestShare({ kind: 'chart', title: chartTitle(spec), chart: spec, columns: cols, rows: r }) } else { requestShare({ kind: 'result', title: shareTitle(), columns: cols, rows: r, sql }) } @@ -872,8 +873,7 @@ /** A share's default title: the query's first meaningful line. */ function shareTitle() { - const line = sql.split('\n').map((l) => l.trim()).find((l) => l && !l.startsWith('--')) ?? 'Query' - return line.length > 60 ? line.slice(0, 57) + '…' : line + return resultsTitle(sql) } diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index f03d1cde..9e605684 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -78,7 +78,7 @@ import { terminalDockOpen as terminalDockStore } from '$lib/stores/redis-nav.js' import DbIcon from './DbIcon.svelte' import ShareDialog from './ShareDialog.svelte' - import { requestShare, sharesPageRequest } from '$lib/share-flow.js' + import { requestShare, sharesPageRequest, chartTitle } from '$lib/share-flow.js' import MySharesDialog from './MySharesDialog.svelte' import Icon from './Icon.svelte' import DockerLaunchModal from './DockerLaunchModal.svelte' @@ -7119,7 +7119,7 @@ let rowSearch = $state('') const cells = picked.map((r) => visibleIdxs.map((i) => r[i])) const source = connection?.name ? `${connection.name} · ${activeSchema ? activeSchema + '.' : ''}${activeTable}` : String(activeTable ?? '') if (mode === 'chart' && chartPane?.shareSpec) { - requestShare({ kind: 'chart', title: `${activeTable} chart`, source, chart: chartPane.shareSpec(), columns: dataViewColumns.map((c) => ({ name: c.name, type: c.dataType ?? c.data_type })), rows: dataViewRows }) + requestShare({ kind: 'chart', title: chartTitle(chartPane.shareSpec()), source, chart: chartPane.shareSpec(), columns: dataViewColumns.map((c) => ({ name: c.name, type: c.dataType ?? c.data_type })), rows: dataViewRows }) return } requestShare({ kind: 'table', title: String(activeTable ?? 'Rows'), source, columns: cols, rows: cells, totalRows: Math.max(total || 0, cells.length) }) diff --git a/src/lib/object-templates.js b/src/lib/object-templates.js index d208d0f2..8c57622a 100644 --- a/src/lib/object-templates.js +++ b/src/lib/object-templates.js @@ -99,8 +99,7 @@ const TEMPLATES = { postgres: { view: (q) => `CREATE OR REPLACE VIEW ${q}\${1:new_view} AS SELECT \${2:*} -FROM \${3:table_name} -WHERE \${0:true};`, +FROM \${3:table_name};`, matview: (q) => `CREATE MATERIALIZED VIEW ${q}\${1:new_view} AS SELECT \${2:*} FROM \${3:table_name} diff --git a/src/lib/share-flow.js b/src/lib/share-flow.js index 0759a907..952fdd54 100644 --- a/src/lib/share-flow.js +++ b/src/lib/share-flow.js @@ -66,6 +66,35 @@ export function saveShareDefaults(patch) { return next } +/** `product_count` → `Product count`. @param {string} name */ +function prettyName(name) { + const t = String(name ?? '').replace(/[_-]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2').trim().toLowerCase() + return t ? t[0].toUpperCase() + t.slice(1) : '' +} + +/** + * A title for a chart from what it plots: "Product count by category". + * @param {{ x?: string, y?: string[], group?: string | null }} spec + */ +export function chartTitle(spec) { + const y = (spec?.y ?? []).filter(Boolean).map(prettyName).join(' and ') + const x = spec?.x ? prettyName(spec.x).toLowerCase() : '' + const g = spec?.group ? ` per ${prettyName(spec.group).toLowerCase()}` : '' + return y && x ? `${y} by ${x}${g}` : y || prettyName(spec?.x ?? '') || 'Chart' +} + +/** + * A title for query results: the table the query reads, or its first line. + * @param {string} sql + */ +export function resultsTitle(sql) { + const text = String(sql ?? '').replace(/--[^\n]*/g, ' ') + const m = /\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\.(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i.exec(text) + if (m) return m[1].split('.').pop()?.replace(/^["`[]|["`\]]$/g, '') ?? 'Query results' + const line = text.split('\n').map((l) => l.trim()).find(Boolean) ?? 'Query results' + return line.length > 60 ? line.slice(0, 57) + '…' : line +} + /** The share the dialog is open for, or null. */ export const shareRequest = writable(/** @type {ShareSource | null} */ (null)) diff --git a/src/lib/share-titles.test.js b/src/lib/share-titles.test.js new file mode 100644 index 00000000..bd7962f4 --- /dev/null +++ b/src/lib/share-titles.test.js @@ -0,0 +1,21 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('$lib/api.js', () => ({ shareCreate: async () => ({}) })) +vi.mock('$lib/share-crypto.js', () => ({ sealShare: async () => ({}), maskValue: (v) => v })) +vi.mock('$lib/stores/settings.js', () => ({ loadSettings: () => ({}), updateSettings: () => ({}) })) + +const { chartTitle, resultsTitle } = await import('./share-flow.js') + +describe('share titles', () => { + it('names a chart after what it plots', () => { + expect(chartTitle({ x: 'category', y: ['product_count'] })).toBe('Product count by category') + expect(chartTitle({ x: 'month', y: ['totalRevenue'], group: 'region' })).toBe('Total revenue by month per region') + expect(chartTitle({ x: '', y: [] })).toBe('Chart') + }) + + it('names results after the table they read', () => { + expect(resultsTitle('SELECT c.name, COUNT(*) FROM categories c JOIN products p ON true')).toBe('categories') + expect(resultsTitle('select * from public."Order Items" limit 5')).toBe('Order Items') + expect(resultsTitle('SELECT 1')).toBe('SELECT 1') + }) +}) From 1c8561f408de4090599a9a0be26ebba8a92ca3ec Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:00:19 +0000 Subject: [PATCH 171/317] chore: version 2.13.5 (#231) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49e52040..e25fbca2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.13.5] - 2026-11-15 + +### Changes +- Share: titles from what is shared, chart preview; simpler New view (#231) + + ## [2.13.4] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 94ceb090..da80f42b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.13.4", + "version": "2.13.5", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 3b725676..40511455 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.13.4", + "version": "2.13.5", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From b307853b81910d6e330fa6d38c7359b9079b5b54 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Sun, 15 Nov 2026 19:57:37 +0545 Subject: [PATCH 172/317] Add a theme: community gallery, theme files and pasted JSON (#232) I can add themes from stroke.click/themes, from a Stroke or VS Code theme file, or by pasting the JSON. Imported themes are listed in Settings > Appearance, where I can switch between them or remove one. --- src/lib/components/AddThemeDialog.svelte | 183 +++++++++++++++++++++++ src/lib/components/SettingsDialog.svelte | 52 +++++++ src/lib/stores/imported-themes.js | 73 +++++++++ src/lib/stores/settings.js | 5 +- src/lib/themes/registry.js | 13 +- src/lib/themes/theme-file.js | 159 ++++++++++++++++++++ src/lib/themes/theme-file.test.js | 40 +++++ 7 files changed, 523 insertions(+), 2 deletions(-) create mode 100644 src/lib/components/AddThemeDialog.svelte create mode 100644 src/lib/stores/imported-themes.js create mode 100644 src/lib/themes/theme-file.js create mode 100644 src/lib/themes/theme-file.test.js diff --git a/src/lib/components/AddThemeDialog.svelte b/src/lib/components/AddThemeDialog.svelte new file mode 100644 index 00000000..1c921e2f --- /dev/null +++ b/src/lib/components/AddThemeDialog.svelte @@ -0,0 +1,183 @@ + + + + + + Add a theme + From the community, a file, or pasted JSON. + + +
+
+
+

Community themes

+ +
+ + {#if galleryLoading} +

Loading themes

+ {:else if galleryError} +

{galleryError}

+ {:else} +
    + {#each shown as t (t.id)} +
  • + +
  • + {/each} +
+ {#if !shown.length}

No themes match.

{/if} + {/if} +
+ +
+ Or import +
+ +
+
+

Theme file

+

A Stroke or VS Code theme, .json

+
+ + +
+ +
+ + + {#if pasted?.error} +

{pasted.error}

+ {:else if pasted?.theme} +

+ + {pasted.theme.name} · {pasted.theme.appearance === 'light' ? 'light' : 'dark'} +

+ {/if} +
+
+ + + + + +
+
diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 793ff738..03e9a4d3 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -2,6 +2,8 @@ import { tick, untrack } from "svelte"; import { toastPosition, TOAST_POSITIONS } from '$lib/stores/toast-position.js' import ThemeBuilder from './ThemeBuilder.svelte'; + import AddThemeDialog from './AddThemeDialog.svelte'; + import { importedThemes, activeImportedId, removeImportedTheme, applyImportedTheme } from '$lib/stores/imported-themes.js'; import { comboTitle } from '$lib/shortcuts.js' import Kbd from './Kbd.svelte' import { trackInstalled, trackInstall, trackOpen } from '$lib/api.js' @@ -32,6 +34,7 @@ appThemeId, loadSettings, updateSettings, + systemPreferredTheme, increaseZoom, decreaseZoom, resetZoom, @@ -210,6 +213,23 @@ /** @param {import('$lib/themes/registry.js').ThemeId} themeId */ let themeBuilderOpen = $state(false); + let addThemeOpen = $state(false); + + /** Use one of the imported themes. @param {string} id */ + function useImported(id) { + activeImportedId.set(id); + if ($appThemeId === 'imported') applyImportedTheme(); + else settings = updateSettings({ theme: 'imported' }); + } + + /** @param {string} id */ + function dropImported(id) { + removeImportedTheme(id); + if ($appThemeId === 'imported') { + if ($importedThemes.length) applyImportedTheme(); + else settings = updateSettings({ theme: systemPreferredTheme() }); + } + } function setTheme(themeId) { if (themeId === $appThemeId) return; @@ -1361,6 +1381,37 @@
{/if} + {#if show('Add a theme', 'Import theme community themes vs code json file paste gallery')} +
+
+

Add a theme

+

From stroke.click/themes, a Stroke or VS Code theme file, or pasted JSON.

+
+ +
+ {#if $importedThemes.length} +
    + {#each $importedThemes as it (it.id)} + {@const on = $appThemeId === 'imported' && $activeImportedId === it.id} +
  • + + + {#if on}{/if} + +
  • + {/each} +
+ {/if} + {/if} + {#if show($t('settings.font'), $t('settings.font.desc'))}
@@ -1912,6 +1963,7 @@ + { if (!o && !switchBusy) switchTo = null }}> diff --git a/src/lib/stores/imported-themes.js b/src/lib/stores/imported-themes.js new file mode 100644 index 00000000..5e2019be --- /dev/null +++ b/src/lib/stores/imported-themes.js @@ -0,0 +1,73 @@ +// Themes added from a file, pasted JSON or the community gallery +// (stroke.click/themes). Each is kept whole; the one in use is applied under +// the `imported` theme id, injected as one

${esc(nb.title || 'Notebook')}

+${body} +

Exported from Stroke · ${new Date().toLocaleString()}

` +} + +// ── Recent notebooks ───────────────────────────────────────────────────────── + +const RECENT_KEY = 'stroke:notebooks:recent' + +/** @returns {Array<{ path: string, title: string, at: number }>} */ +export function recentNotebooks() { + try { + const v = JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]') + return Array.isArray(v) ? v : [] + } catch { + return [] + } +} + +/** @param {string} path @param {string} title */ +export function rememberNotebook(path, title) { + try { + const list = recentNotebooks().filter((r) => r.path !== path) + list.unshift({ path, title, at: Date.now() }) + localStorage.setItem(RECENT_KEY, JSON.stringify(list.slice(0, 12))) + } catch { /* not kept */ } +} diff --git a/src/lib/notebook.test.js b/src/lib/notebook.test.js new file mode 100644 index 00000000..951a2d46 --- /dev/null +++ b/src/lib/notebook.test.js @@ -0,0 +1,102 @@ +import { describe, expect, test } from 'vitest' +import { + createNotebook, + createSqlCell, + createMarkdownCell, + serializeNotebook, + deserializeNotebook, + substituteVars, + variableNames, + importNotebook, + cellsFromMarkdown, + cellsFromSql, + cellsFromIpynb, + toMarkdown, + toSqlScript, + toIpynb, + toHtml, +} from './notebook.js' + +describe('variables', () => { + test('fills {{ name }} and reports the unknown ones', () => { + const r = substituteVars("select * from t where status = '{{status}}' limit {{ n }} -- {{ other }}", [ + { name: 'status', value: 'paid' }, + { name: 'n', value: '10' }, + ]) + expect(r.sql).toBe("select * from t where status = 'paid' limit 10 -- {{ other }}") + expect(r.missing).toEqual(['other']) + expect(variableNames('{{a}} {{ b }} {{a}}')).toEqual(['a', 'b']) + }) + test('round-trips through .sqlnb', () => { + const nb = createNotebook('x') + nb.variables = [{ name: 'a', value: '1' }] + expect(deserializeNotebook(serializeNotebook(nb)).variables).toEqual([{ name: 'a', value: '1' }]) + // Older files without variables still open. + const old = JSON.stringify({ version: '1', title: 'o', cells: [] }) + expect(deserializeNotebook(old).variables).toEqual([]) + }) +}) + +describe('import', () => { + test('markdown: sql fences become SQL cells, prose stays markdown, other code stays prose', () => { + const cells = cellsFromMarkdown('# Report\n\nIntro\n\n```sql\nselect 1\n```\n\nMore\n\n```js\nx()\n```\n') + expect(cells.map((c) => [c.type, c.content])).toEqual([ + ['markdown', '# Report\n\nIntro'], + ['sql', 'select 1'], + ['markdown', 'More\n\n```js\nx()\n```'], + ]) + }) + test('sql script: -- %% markers, or blank-line groups', () => { + expect(cellsFromSql('select 1;\n-- %% second\nselect 2;').map((c) => c.content)).toEqual(['select 1;', 'select 2;']) + expect(cellsFromSql('select 1;\n\nselect 2;\nselect 3;').map((c) => c.content)).toEqual(['select 1;', 'select 2;\nselect 3;']) + }) + test('jupyter: %%sql magics and markdown', () => { + const ipynb = JSON.stringify({ cells: [ + { cell_type: 'markdown', source: ['# Hi\n', 'there'] }, + { cell_type: 'code', source: ['%%sql\n', 'select 1'] }, + { cell_type: 'code', source: '%sql select 2' }, + { cell_type: 'code', source: '' }, + ] }) + expect(cellsFromIpynb(ipynb).map((c) => [c.type, c.content])).toEqual([ + ['markdown', '# Hi\nthere'], + ['sql', 'select 1'], + ['sql', 'select 2'], + ]) + expect(() => cellsFromIpynb('{}')).toThrow() + }) + test('importNotebook picks the format by extension and names the notebook', () => { + const nb = importNotebook('/x/sales report.md', '```sql\nselect 1\n```') + expect(nb.title).toBe('sales report') + expect(nb.cells[0].type).toBe('sql') + expect(importNotebook('a.sql', '').cells.length).toBe(1) + }) +}) + +describe('export', () => { + const nb = createNotebook('Sales') + nb.cells = [createMarkdownCell('Some *prose*'), createSqlCell('select 1 as n')] + nb.cells[1].result = { columns: [{ name: 'n' }], rows: [[1], [null]], queryMs: 3, error: '', message: '' } + test('markdown with result tables', () => { + const md = toMarkdown(nb) + expect(md).toContain('# Sales') + expect(md).toContain('```sql\nselect 1 as n\n```') + expect(md).toContain('| n |\n| --- |\n| 1 |\n| NULL |') + }) + test('sql script keeps prose as comments and cells as -- %%', () => { + const sql = toSqlScript(nb) + expect(sql).toContain('-- Some *prose*') + expect(cellsFromSql(sql).map((c) => c.content).at(-1)).toBe('select 1 as n') + }) + test('ipynb round-trips back to the same cells', () => { + const back = cellsFromIpynb(toIpynb(nb)) + expect(back.map((c) => [c.type, c.content])).toEqual([['markdown', 'Some *prose*'], ['sql', 'select 1 as n']]) + }) + test('html escapes and includes results', () => { + const n2 = createNotebook('') + n2.cells = [createSqlCell("select ''")] + const html = toHtml(n2, (m) => m) + expect(html).toContain('<x>') + expect(html).toContain('select '<b>''.replace(''', "'").replace(''', "'")) + expect(toHtml(nb, (m) => `

${m}

`)).toContain('NULL') + }) +}) From aea9b4041b2e2d899b7a4fde1ebf38df35d37fac Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:32:04 +0000 Subject: [PATCH 223/317] chore: version 2.16.0 (#258) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c69f8403..8cd91f8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.16.0] - 2026-11-15 + +### Changes +- SQL notebook: import/export, variables, autosave, a usable cell UI (#258) + + ## [2.15.9] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index be68e7af..210d6b8a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.15.9", + "version": "2.16.0", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c802e624..47973cfc 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.15.9", + "version": "2.16.0", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From cf32062438b8f70e913025b6d62764379cb724ef Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 00:19:42 +0545 Subject: [PATCH 224/317] NoSQL: a tab per collection, like table tabs (#259) MongoDB, CouchDB, Elasticsearch/OpenSearch, Firestore and Cassandra had one Browse tab whose collection the sidebar swapped. Each collection now opens its own tab, named after it; an open one is focused, and the blank Browse tab a connection starts on takes the first pick. Every docs tab keeps its own browser mounted, so switching back keeps its page, filters and scroll. Co-authored-by: Claude Opus 5.5 --- src/lib/components/StudioShell.svelte | 87 +++++++++++++++++---------- src/lib/studio-tabs.js | 2 + 2 files changed, 58 insertions(+), 31 deletions(-) diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 7aacbdc9..2a1f3841 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -1007,7 +1007,8 @@ let dynamoEverOpened = $state(false) let docsEverOpened = $state(false) /** The collection/table the Browse page shows: the sidebar's selection. */ - let docCollection = $state('') + /** The open document tab's collection (each docs tab keeps its own). */ + const docCollection = $derived(activeTab?.kind === 'docs' ? (/** @type {any} */ (activeTab).collection ?? '') : '') /** The DynamoDB table the DynamoDB page shows. */ let dynamoTable = $state('') /** Engines whose sidebar schema is part of the collection's name (db.coll, keyspace.table). */ @@ -4514,13 +4515,34 @@ let rowSearch = $state('') clearTableEditor() } - /** The document browser: the main page of a CouchDB / Cassandra / Firestore connection. */ - function openDocsTab() { - const existing = findDocsTab(tabs) - if (existing) { void activateTab(existing.id); return } + /** + * The document browser (MongoDB, CouchDB, Elasticsearch, Firestore, + * Cassandra...), one tab per collection like table tabs. A collection + * already open is focused; the blank Browse tab a connection opens on takes + * the first collection picked; any other pick opens its own tab. No + * collection: back to the docs tab used last, or a blank one. + * @param {string} [collection] + */ + function openDocsTab(collection) { + const docs = tabs.filter((t) => t.kind === 'docs') + if (collection === undefined) { + const last = docs.find((t) => t.id === activeTabId) ?? docs.at(-1) + if (last) { void activateTab(last.id); return } + collection = '' + } + const name = /** @type {string} */ (collection) + const same = docs.find((t) => (/** @type {any} */ (t).collection ?? '') === name) + if (same) { void activateTab(same.id); return } + const title = name ? name.slice(name.lastIndexOf('.') + 1) : 'Browse' + const blank = name ? docs.find((t) => !(/** @type {any} */ (t).collection)) : null + if (blank) { + tabs = tabs.map((t) => (t.id === blank.id ? /** @type {any} */ ({ ...t, collection: name, title }) : t)) + void activateTab(blank.id) + return + } saveActiveTabState() dropWelcomeTabs() - const tab = createDocsTab() + const tab = /** @type {any} */ ({ ...createDocsTab(), collection: name, title }) tabs = [...tabs, tab] activeTabId = tab.id clearTableEditor() @@ -7667,10 +7689,9 @@ let rowSearch = $state('') const connIsDynamo = fam === 'dynamodb' const connIsDoc = fam === 'couchdb' || fam === 'cassandra' || fam === 'firestore' || fam === 'mongodb' || fam === 'elasticsearch' || fam === 'opensearch' const connIsRedis = fam === 'redis' - docCollection = '' dynamoTable = '' if (connIsDoc) { - openDocsTab() + openDocsTab('') } else if (connIsDynamo) { openDynamoTab() } else if (connIsRedis) { @@ -8036,8 +8057,7 @@ let rowSearch = $state('') if (aiMode) exitAiMode() // NoSQL: the sidebar picks what the engine's own page shows. if (isDoc) { - docCollection = docQualified && activeSchema ? `${activeSchema}.${name}` : name - openDocsTab() + openDocsTab(docQualified && activeSchema ? `${activeSchema}.${name}` : name) return } if (isDynamo) { @@ -10293,28 +10313,33 @@ let rowSearch = $state('')
{/if} - + {#if docsEverOpened && docAdapter} -
- - {#await import('./DocBrowser.svelte')}{:then { default: DocBrowser }} - {#key dbType} - { if (aiMode) exitAiMode(); openSqlTabWith(text, coll ? `${docAdapter.consoleLabel} · ${coll}` : docAdapter.consoleLabel) }} - /> - {/key} - {/await} - -
+ {#each tabs.filter((t) => t.kind === 'docs') as dt (dt.id)} + {@const on = activeTab?.id === dt.id} +
+ + {#await import('./DocBrowser.svelte')}{:then { default: DocBrowser }} + {#key dbType} + { if (aiMode) exitAiMode(); openSqlTabWith(text, coll ? `${docAdapter.consoleLabel} · ${coll}` : docAdapter.consoleLabel) }} + /> + {/key} + {/await} + +
+ {/each} {/if} diff --git a/src/lib/studio-tabs.js b/src/lib/studio-tabs.js index 97a27c34..312cb946 100644 --- a/src/lib/studio-tabs.js +++ b/src/lib/studio-tabs.js @@ -375,6 +375,8 @@ export function tabDisplayTitle(tab) { if (tab.kind === 'terminal') return tab.title || 'Terminal' if (tab.kind === 'sql') return tab.title || 'Query Editor' if (tab.kind === 'notebook') return tab.title || 'Untitled Notebook' + // A document tab is named after its collection. + if (tab.kind === 'docs') return tab.title || 'Browse' if (tab.kind === 'extension-detail') return tab.title || tab.state?.extensionId || 'Extension' return SINGLETON_TAB_TITLES[tab.kind] ?? tab.title } From 593bc6fa48bd5d95efdf77988184c663118d54f2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:34:53 +0000 Subject: [PATCH 225/317] chore: version 2.16.1 (#259) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cd91f8f..66d94e18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.16.1] - 2026-11-15 + +### Changes +- NoSQL: a tab per collection, like table tabs (#259) + + ## [2.16.0] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 210d6b8a..df242aeb 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.16.0", + "version": "2.16.1", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 47973cfc..7d9aa5eb 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.16.0", + "version": "2.16.1", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 8c2d07626c076d2ffdbfe2dd98863bdf101defdd Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 00:29:06 +0545 Subject: [PATCH 226/317] Labs: several databases open together, one tab bar, switching in place (#260) * WIP: route each call to its database's pool (Db extractor, __conn) * Labs: several databases open together, in one tab bar, switching in place Each call now names the database it is for (__conn, read by a new Db extractor in place of State), so require_conn serves it from the front pool or the one kept aside for that database; a call sent just before a switch still lands on its own database, and a key whose pool was closed is an error rather than a quiet run on whatever is in front. The page: - One tab bar for every open database: this one's tabs and the kept ones, grouped in the order the databases were opened and labelled with their database. Clicking a kept database's tab switches there on that tab; closing it does not switch. - A switch to a kept database resumes in place: its pool comes back, and the sidebar, tabs and the tab you were on are swapped in at once and refreshed quietly behind. No teardown, no welcome screen, no skeleton in between - the flicker. - The tab on screen keeps its rows when set aside, so returning is instant. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- src-tauri/src/commands.rs | 209 ++++++++++++------------- src-tauri/src/db/backup.rs | 9 +- src-tauri/src/db/connection.rs | 115 +++++++++++--- src-tauri/src/db/geo.rs | 10 +- src-tauri/src/db/import.rs | 7 +- src-tauri/src/db/insights.rs | 16 +- src-tauri/src/db/objects.rs | 12 +- src-tauri/src/db/parked.rs | 23 ++- src-tauri/src/db/query.rs | 38 ++--- src-tauri/src/db/schema.rs | 32 ++-- src-tauri/src/db/tx.rs | 5 +- src-tauri/src/lib.rs | 2 + src/lib/api.js | 13 ++ src/lib/components/StudioShell.svelte | 215 +++++++++++++++++++++++--- src/lib/components/TabBar.svelte | 9 +- 15 files changed, 489 insertions(+), 226 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 1f8f595d..cb95a412 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1,3 +1,4 @@ +use crate::db::connection::Db; use std::sync::OnceLock; use tauri::Emitter; @@ -364,7 +365,7 @@ use crate::db::{ list_schemas, list_tables, list_indexes_for, list_enums, list_functions, list_triggers, list_sequences, ping_connection, table_row_counts, truncate_table, drop_table, get_table_column_structure, get_schema_column_structure, get_incoming_foreign_keys, get_table_ddl as db_get_table_ddl, test_clickhouse_connection, test_connection, test_d1_connection, test_duckdb_connection, test_libsql_connection, test_mssql_connection, test_mysql_connection, test_oracle_connection, test_redis_connection, test_sqlite_connection, - update_table_cell, fetch_cell_value, ConnectionConfig, D1Config, DbState, EnumInfo, FunctionInfo, ExplainResult, IndexInfo, LibSqlConfig, + update_table_cell, fetch_cell_value, ConnectionConfig, D1Config, EnumInfo, FunctionInfo, ExplainResult, IndexInfo, LibSqlConfig, SqlResult, SqliteConfig, TableInfo, TableRowCount, TableRows, TriggerInfo, SequenceInfo, ColumnStructureRow, TableColumnStructure, IncomingForeignKey, InsertRowResult, TunnelState, apply_table_changes, ApplyChangesResult, RowUpdate, @@ -385,7 +386,7 @@ pub async fn test_postgres_connection(config: ConnectionConfig) -> Result<(), St #[tauri::command] pub async fn connect_postgres( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: ConnectionConfig, ) -> Result<(), String> { @@ -401,7 +402,7 @@ pub async fn test_sqlite(config: SqliteConfig) -> Result<(), String> { #[tauri::command] pub async fn connect_sqlite_db( - state: State<'_, DbState>, + state: Db<'_>, config: SqliteConfig, ) -> Result<(), String> { connect_sqlite(state, config).await @@ -416,7 +417,7 @@ pub async fn test_mysql(config: MysqlConfig) -> Result<(), String> { #[tauri::command] pub async fn connect_mysql_db( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: MysqlConfig, ) -> Result<(), String> { @@ -432,7 +433,7 @@ pub async fn test_d1(config: D1Config) -> Result<(), String> { #[tauri::command] pub async fn connect_d1_db( - state: State<'_, DbState>, + state: Db<'_>, config: D1Config, ) -> Result<(), String> { connect_d1(state, config).await @@ -446,7 +447,7 @@ pub async fn test_libsql(config: LibSqlConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_libsql_db(state: State<'_, DbState>, config: LibSqlConfig) -> Result<(), String> { +pub async fn connect_libsql_db(state: Db<'_>, config: LibSqlConfig) -> Result<(), String> { connect_libsql(state, config).await } @@ -459,7 +460,7 @@ pub async fn test_posthog(config: crate::db::connection::PosthogConfig) -> Resul #[tauri::command] pub async fn connect_posthog_db( - state: State<'_, DbState>, + state: Db<'_>, config: crate::db::connection::PosthogConfig, ) -> Result<(), String> { crate::db::connection::connect_posthog(state, config).await @@ -473,7 +474,7 @@ pub async fn test_clickhouse(config: ClickhouseConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_clickhouse_db(state: State<'_, DbState>, config: ClickhouseConfig) -> Result<(), String> { +pub async fn connect_clickhouse_db(state: Db<'_>, config: ClickhouseConfig) -> Result<(), String> { connect_clickhouse(state, config).await } @@ -485,7 +486,7 @@ pub async fn test_redis(config: RedisConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_redis_db(state: State<'_, DbState>, config: RedisConfig) -> Result<(), String> { +pub async fn connect_redis_db(state: Db<'_>, config: RedisConfig) -> Result<(), String> { connect_redis(state, config).await } @@ -493,7 +494,7 @@ pub async fn connect_redis_db(state: State<'_, DbState>, config: RedisConfig) -> /// SCAN page (next cursor + keys); the frontend loops until the cursor is "0". #[tauri::command] pub async fn redis_scan( - state: State<'_, DbState>, + state: Db<'_>, cursor: String, pattern: Option, count: u32, @@ -504,7 +505,7 @@ pub async fn redis_scan( } } -fn require_redis(state: &State<'_, DbState>) -> Result { +fn require_redis(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Redis(cfg) => Ok(cfg), _ => Err("Not connected to a Redis database".into()), @@ -514,7 +515,7 @@ fn require_redis(state: &State<'_, DbState>) -> Result { /// One page of the Redis keys table (keys with type, TTL, size and preview). #[tauri::command] pub async fn redis_key_page( - state: State<'_, DbState>, + state: Db<'_>, cursor: String, pattern: Option, key_type: Option, @@ -527,7 +528,7 @@ pub async fn redis_key_page( /// Fresh keys-table rows for specific keys. #[tauri::command] pub async fn redis_key_rows( - state: State<'_, DbState>, + state: Db<'_>, keys: Vec, ) -> Result, String> { let cfg = require_redis(&state)?; @@ -537,7 +538,7 @@ pub async fn redis_key_rows( /// A key's value, paged for collections. #[tauri::command] pub async fn redis_key_value( - state: State<'_, DbState>, + state: Db<'_>, key: crate::db::redis::KeyRef, cursor: Option, count: u32, @@ -548,7 +549,7 @@ pub async fn redis_key_value( /// One Redis command as structured JSON, for the insight views. #[tauri::command] -pub async fn redis_command(state: State<'_, DbState>, args: Vec) -> Result { +pub async fn redis_command(state: Db<'_>, args: Vec) -> Result { let cfg = require_redis(&state)?; crate::db::redis::command_json(&cfg, args).await } @@ -557,7 +558,7 @@ pub async fn redis_command(state: State<'_, DbState>, args: Vec) -> Resu #[tauri::command] pub async fn redis_subscribe( app: tauri::AppHandle, - state: State<'_, DbState>, + state: Db<'_>, id: String, channels: Vec, patterns: Vec, @@ -580,7 +581,7 @@ pub fn redis_unsubscribe(id: String) { /// Apply staged Redis writes in one MULTI/EXEC transaction. #[tauri::command] pub async fn redis_apply( - state: State<'_, DbState>, + state: Db<'_>, ops: Vec, ) -> Result, String> { let cfg = require_redis(&state)?; @@ -596,7 +597,7 @@ pub async fn test_dynamodb(config: crate::db::dynamodb::DynamoConfig) -> Result< #[tauri::command] pub async fn connect_dynamodb_db( - state: State<'_, DbState>, + state: Db<'_>, config: crate::db::dynamodb::DynamoConfig, ) -> Result<(), String> { crate::db::connection::connect_dynamodb(state, config).await @@ -611,7 +612,7 @@ pub fn dynamodb_profiles() -> Vec { /// One DynamoDB API call (`op` from an allowlist) on the active connection. #[tauri::command] pub async fn dynamodb_request( - state: State<'_, DbState>, + state: Db<'_>, op: String, body: serde_json::Value, ) -> Result { @@ -630,14 +631,14 @@ pub async fn test_couchdb(config: crate::db::couchdb::CouchConfig) -> Result<(), } #[tauri::command] -pub async fn connect_couchdb_db(state: State<'_, DbState>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { +pub async fn connect_couchdb_db(state: Db<'_>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { crate::db::connection::connect_couchdb(state, config).await } /// One CouchDB HTTP call (path allowlisted) on the active connection. #[tauri::command] pub async fn couchdb_request( - state: State<'_, DbState>, + state: Db<'_>, method: String, path: String, body: Option, @@ -658,14 +659,14 @@ pub async fn test_elastic(config: crate::db::elastic::EsConfig) -> Result, config: crate::db::elastic::EsConfig) -> Result<(), String> { +pub async fn connect_elastic_db(state: Db<'_>, config: crate::db::elastic::EsConfig) -> Result<(), String> { crate::db::connection::connect_elastic(state, config).await } /// One REST call (path allowlisted) on the active connection. #[tauri::command] pub async fn elastic_request( - state: State<'_, DbState>, + state: Db<'_>, method: String, path: String, body: Option, @@ -680,7 +681,7 @@ pub async fn elastic_request( /// Import a file into an index (the preview reuses `mongo_import_preview`). #[tauri::command] pub async fn elastic_import( - state: State<'_, DbState>, + state: Db<'_>, index: String, path: String, format: Option, @@ -701,11 +702,11 @@ pub async fn test_mongo(config: crate::db::mongo::MongoConfig) -> Result<(), Str } #[tauri::command] -pub async fn connect_mongo_db(state: State<'_, DbState>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { +pub async fn connect_mongo_db(state: Db<'_>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { crate::db::connection::connect_mongo(state, config).await } -fn require_mongo(state: &State<'_, DbState>) -> Result { +fn require_mongo(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(m)) => Ok(m), _ => Err("Not connected to MongoDB".into()), @@ -715,7 +716,7 @@ fn require_mongo(state: &State<'_, DbState>) -> Result, schema: String) -> Result<(), String> { +pub async fn doc_use_schema(state: Db<'_>, schema: String) -> Result<(), String> { match require_conn(&state)? { ActiveConnection::Doc(d) => crate::db::docdb::use_schema(&d, &schema).await, _ => Ok(()), @@ -723,20 +724,20 @@ pub async fn doc_use_schema(state: State<'_, DbState>, schema: String) -> Result } #[tauri::command] -pub async fn mongo_collections(state: State<'_, DbState>) -> Result, String> { +pub async fn mongo_collections(state: Db<'_>) -> Result, String> { let m = require_mongo(&state)?; crate::db::mongo::list_collections(&m).await } #[tauri::command] -pub async fn mongo_describe(state: State<'_, DbState>, collection: String) -> Result { +pub async fn mongo_describe(state: Db<'_>, collection: String) -> Result { let m = require_mongo(&state)?; crate::db::mongo::describe(&m, &collection).await } #[tauri::command] pub async fn mongo_find( - state: State<'_, DbState>, + state: Db<'_>, collection: String, filter: String, sort: Option, @@ -758,14 +759,14 @@ pub async fn mongo_find( } #[tauri::command] -pub async fn mongo_count(state: State<'_, DbState>, collection: String, filter: String) -> Result { +pub async fn mongo_count(state: Db<'_>, collection: String, filter: String) -> Result { let m = require_mongo(&state)?; crate::db::mongo::count(&m, &collection, &filter).await } #[tauri::command] pub async fn mongo_save( - state: State<'_, DbState>, + state: Db<'_>, collection: String, doc: serde_json::Value, prev_id: Option, @@ -775,14 +776,14 @@ pub async fn mongo_save( } #[tauri::command] -pub async fn mongo_delete(state: State<'_, DbState>, collection: String, id: serde_json::Value) -> Result<(), String> { +pub async fn mongo_delete(state: Db<'_>, collection: String, id: serde_json::Value) -> Result<(), String> { let m = require_mongo(&state)?; crate::db::mongo::delete(&m, &collection, &id).await } #[tauri::command] pub async fn mongo_explain( - state: State<'_, DbState>, + state: Db<'_>, collection: String, filter: String, sort: Option, @@ -793,20 +794,20 @@ pub async fn mongo_explain( } #[tauri::command] -pub async fn mongo_schema(state: State<'_, DbState>, collection: String, filter: String, size: Option) -> Result { +pub async fn mongo_schema(state: Db<'_>, collection: String, filter: String, size: Option) -> Result { let m = require_mongo(&state)?; crate::db::mongo::schema_sample(&m, &collection, &filter, size.unwrap_or(1000)).await } #[tauri::command] -pub async fn mongo_indexes(state: State<'_, DbState>, collection: String) -> Result, String> { +pub async fn mongo_indexes(state: Db<'_>, collection: String) -> Result, String> { let m = require_mongo(&state)?; crate::db::mongo::index_details(&m, &collection).await } #[tauri::command] pub async fn mongo_create_index( - state: State<'_, DbState>, + state: Db<'_>, collection: String, keys: String, options: Option, @@ -816,7 +817,7 @@ pub async fn mongo_create_index( } #[tauri::command] -pub async fn mongo_drop_index(state: State<'_, DbState>, collection: String, name: String) -> Result<(), String> { +pub async fn mongo_drop_index(state: Db<'_>, collection: String, name: String) -> Result<(), String> { let m = require_mongo(&state)?; crate::db::mongo::drop_index(&m, &collection, &name).await } @@ -824,7 +825,7 @@ pub async fn mongo_drop_index(state: State<'_, DbState>, collection: String, nam #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn mongo_update_field( - state: State<'_, DbState>, + state: Db<'_>, collection: String, id: serde_json::Value, path: String, @@ -837,7 +838,7 @@ pub async fn mongo_update_field( } #[tauri::command] -pub async fn mongo_aggregate(state: State<'_, DbState>, collection: String, pipeline: String, limit: Option) -> Result, String> { +pub async fn mongo_aggregate(state: Db<'_>, collection: String, pipeline: String, limit: Option) -> Result, String> { let m = require_mongo(&state)?; crate::db::mongo::aggregate_preview(&m, &collection, &pipeline, limit.unwrap_or(10)).await } @@ -852,7 +853,7 @@ pub async fn mongo_import_preview(path: String, format: Option, infer: O #[tauri::command] pub async fn mongo_import( - state: State<'_, DbState>, + state: Db<'_>, collection: String, path: String, format: Option, @@ -870,14 +871,14 @@ pub async fn test_firestore(config: crate::db::firestore::FirestoreConfig) -> Re } #[tauri::command] -pub async fn connect_firestore_db(state: State<'_, DbState>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { +pub async fn connect_firestore_db(state: Db<'_>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { crate::db::connection::connect_firestore(state, config).await } /// One Firestore REST call (document paths of this database only). #[tauri::command] pub async fn firestore_request( - state: State<'_, DbState>, + state: Db<'_>, method: String, path: String, body: Option, @@ -897,11 +898,11 @@ pub async fn test_cassandra(config: crate::db::cassandra::CassandraConfig) -> Re } #[tauri::command] -pub async fn connect_cassandra_db(state: State<'_, DbState>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { +pub async fn connect_cassandra_db(state: Db<'_>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { crate::db::connection::connect_cassandra(state, config).await } -fn require_cassandra(state: &State<'_, DbState>) -> Result { +fn require_cassandra(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Doc(crate::db::docdb::DocConn::Cassandra(s)) => Ok(s), _ => Err("Not connected to Cassandra".into()), @@ -909,20 +910,20 @@ fn require_cassandra(state: &State<'_, DbState>) -> Result) -> Result, String> { +pub async fn cassandra_tables(state: Db<'_>) -> Result, String> { let s = require_cassandra(&state)?; crate::db::cassandra::list_tables(&s).await } #[tauri::command] -pub async fn cassandra_describe(state: State<'_, DbState>, table: String) -> Result { +pub async fn cassandra_describe(state: Db<'_>, table: String) -> Result { let s = require_cassandra(&state)?; crate::db::cassandra::describe(&s, &table).await } #[tauri::command] pub async fn cassandra_page( - state: State<'_, DbState>, + state: Db<'_>, table: String, filter: String, cursor: Option, @@ -934,7 +935,7 @@ pub async fn cassandra_page( #[tauri::command] pub async fn cassandra_save( - state: State<'_, DbState>, + state: Db<'_>, table: String, row: serde_json::Value, prev: Option, @@ -944,7 +945,7 @@ pub async fn cassandra_save( } #[tauri::command] -pub async fn cassandra_delete(state: State<'_, DbState>, table: String, row: serde_json::Value) -> Result<(), String> { +pub async fn cassandra_delete(state: Db<'_>, table: String, row: serde_json::Value) -> Result<(), String> { let s = require_cassandra(&state)?; crate::db::cassandra::delete(&s, &table, &row).await } @@ -957,7 +958,7 @@ pub async fn test_duckdb(config: DuckdbConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_duckdb_db(state: State<'_, DbState>, config: DuckdbConfig) -> Result<(), String> { +pub async fn connect_duckdb_db(state: Db<'_>, config: DuckdbConfig) -> Result<(), String> { connect_duckdb(state, config).await } @@ -969,7 +970,7 @@ pub async fn test_mssql(config: MssqlConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_mssql_db(state: State<'_, DbState>, config: MssqlConfig) -> Result<(), String> { +pub async fn connect_mssql_db(state: Db<'_>, config: MssqlConfig) -> Result<(), String> { connect_mssql(state, config).await } @@ -981,13 +982,13 @@ pub async fn test_oracle(config: OracleConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_oracle_db(state: State<'_, DbState>, config: OracleConfig) -> Result<(), String> { +pub async fn connect_oracle_db(state: Db<'_>, config: OracleConfig) -> Result<(), String> { connect_oracle(state, config).await } /// The Oracle container the active connection is in (FREEPDB1, CDB$ROOT). #[tauri::command] -pub async fn oracle_container_name(state: State<'_, DbState>) -> Result { +pub async fn oracle_container_name(state: Db<'_>) -> Result { match crate::db::connection::require_conn(&state)? { ActiveConnection::Oracle(h) => crate::db::oracle::container_name(&h).await, _ => Err("Not connected to Oracle".into()), @@ -1002,7 +1003,7 @@ use crate::db::live::{self, LiveState}; #[tauri::command] pub async fn live_start( app: tauri::AppHandle, - state: State<'_, DbState>, + state: Db<'_>, live_state: State<'_, LiveState>, schema: String, table: String, @@ -1022,7 +1023,7 @@ pub async fn live_stop(live_state: State<'_, LiveState>) -> Result<(), String> { #[tauri::command] pub async fn disconnect_postgres( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, live_state: State<'_, LiveState>, ) -> Result<(), String> { @@ -1092,7 +1093,7 @@ fn mssql_plan_lines(xml: &str) -> Vec { #[tauri::command] pub async fn pg_explain_sql( - state: State<'_, DbState>, + state: Db<'_>, sql: String, analyze: Option, ) -> Result { @@ -1179,13 +1180,13 @@ pub async fn pg_explain_sql( // ── DB-agnostic query commands ──────────────────────────────────────────────── #[tauri::command] -pub async fn pg_list_schemas(state: State<'_, DbState>) -> Result, String> { +pub async fn pg_list_schemas(state: Db<'_>) -> Result, String> { list_schemas(state).await } #[tauri::command] pub async fn pg_list_tables( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_tables(state, schema).await @@ -1195,7 +1196,7 @@ pub async fn pg_list_tables( /// unknown (-1) row count. See `db::schema::table_row_counts`. #[tauri::command] pub async fn pg_table_row_counts( - state: State<'_, DbState>, + state: Db<'_>, schema: String, tables: Vec, ) -> Result, String> { @@ -1204,7 +1205,7 @@ pub async fn pg_table_row_counts( #[tauri::command] pub async fn pg_list_indexes( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: Option, ) -> Result, String> { @@ -1213,7 +1214,7 @@ pub async fn pg_list_indexes( #[tauri::command] pub async fn pg_get_table_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1224,7 +1225,7 @@ pub async fn pg_get_table_column_structure( /// table. Used by the ER diagram, which needs the whole schema up front. #[tauri::command] pub async fn pg_get_schema_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { get_schema_column_structure(state, schema).await @@ -1232,7 +1233,7 @@ pub async fn pg_get_schema_column_structure( #[tauri::command] pub async fn pg_get_incoming_foreign_keys( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1241,7 +1242,7 @@ pub async fn pg_get_incoming_foreign_keys( #[tauri::command] pub async fn pg_list_enums( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_enums(state, schema).await @@ -1249,7 +1250,7 @@ pub async fn pg_list_enums( #[tauri::command] pub async fn pg_list_triggers( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_triggers(state, schema).await @@ -1257,7 +1258,7 @@ pub async fn pg_list_triggers( #[tauri::command] pub async fn pg_list_sequences( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_sequences(state, schema).await @@ -1265,7 +1266,7 @@ pub async fn pg_list_sequences( #[tauri::command] pub async fn pg_list_functions( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_functions(state, schema).await @@ -1275,7 +1276,7 @@ pub async fn pg_list_functions( /// and which of those kinds the engine has (the sidebar's Objects tab). #[tauri::command] pub async fn list_db_objects( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result { crate::db::objects::list_db_objects(state, schema).await @@ -1283,7 +1284,7 @@ pub async fn list_db_objects( #[tauri::command] pub async fn get_object_definition( - state: State<'_, DbState>, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1296,7 +1297,7 @@ pub async fn get_object_definition( #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn drop_db_object( - state: State<'_, DbState>, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1321,20 +1322,20 @@ pub async fn drop_db_object( /// Table and view comments for one schema (the sidebar's comments setting). #[tauri::command] pub async fn list_object_comments( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { crate::db::objects::list_object_comments(state, schema).await } #[tauri::command] -pub async fn ping_db_connection(state: State<'_, DbState>) -> Result<(), String> { +pub async fn ping_db_connection(state: Db<'_>) -> Result<(), String> { ping_connection(state).await } #[tauri::command] pub async fn pg_truncate_table( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result<(), String> { @@ -1343,7 +1344,7 @@ pub async fn pg_truncate_table( #[tauri::command] pub async fn pg_drop_table( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, cascade: bool, @@ -1356,7 +1357,7 @@ pub async fn pg_drop_table( /// Copy a database on the current server under a new name, structure and rows. #[tauri::command] pub async fn pg_clone_database( - state: State<'_, DbState>, + state: Db<'_>, source: String, target: String, ) -> Result { @@ -1366,7 +1367,7 @@ pub async fn pg_clone_database( #[tauri::command] pub async fn get_table_ddl( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { @@ -1384,7 +1385,7 @@ pub async fn get_table_ddl_on_connection( #[tauri::command] pub async fn pg_get_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, limit: i64, @@ -1440,7 +1441,7 @@ pub async fn pg_get_table_rows( /// total streams in without blocking the initial paint. #[tauri::command] pub async fn pg_count_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, search: Option, @@ -1473,7 +1474,7 @@ pub async fn pg_count_table_rows( /// Which text columns a search index would cover, and which have one. #[tauri::command] pub async fn pg_search_index_status( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { @@ -1483,7 +1484,7 @@ pub async fn pg_search_index_status( /// Create trigram indexes so the grid's search is an index scan. #[tauri::command] pub async fn pg_create_search_index( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1492,7 +1493,7 @@ pub async fn pg_create_search_index( #[tauri::command] pub async fn pg_get_column_stats( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -1504,7 +1505,7 @@ pub async fn pg_get_column_stats( #[tauri::command] pub async fn geo_overview( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::geo_overview(state).await } @@ -1512,7 +1513,7 @@ pub async fn geo_overview( #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn geo_features( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -1537,28 +1538,28 @@ pub async fn geo_features( #[tauri::command] pub async fn instance_version( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_version(state).await } #[tauri::command] pub async fn instance_activity( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_activity(state).await } #[tauri::command] pub async fn instance_state( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_state(state).await } #[tauri::command] pub async fn instance_config( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result, String> { crate::db::instance_config(state).await } @@ -1567,7 +1568,7 @@ pub async fn instance_config( /// `value = None` resets it to the server default. #[tauri::command] pub async fn instance_set_config( - state: State<'_, DbState>, + state: Db<'_>, name: String, value: Option, ) -> Result { @@ -1578,7 +1579,7 @@ pub async fn instance_set_config( /// only - it never reads user rows and never writes. #[tauri::command] pub async fn advisor_scan( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { let conn = crate::db::connection::require_conn(&state)?; crate::db::advisor::scan(&conn).await @@ -1586,7 +1587,7 @@ pub async fn advisor_scan( #[tauri::command] pub async fn instance_replication( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_replication(state).await } @@ -1595,7 +1596,7 @@ pub async fn instance_replication( /// it keeps the single-slot behaviour older callers relied on. #[tauri::command] pub async fn pg_execute_sql( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result { @@ -1604,7 +1605,7 @@ pub async fn pg_execute_sql( #[tauri::command] pub async fn pg_execute_sql_multi( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result, String> { @@ -1621,7 +1622,7 @@ pub async fn pg_execute_sql_multi( /// Stream results). The window reads them with `result_window`. #[tauri::command] pub async fn pg_execute_sql_stream( - state: State<'_, DbState>, + state: Db<'_>, store: State<'_, crate::db::result_store::ResultStore>, sql: String, query_id: Option, @@ -1720,13 +1721,13 @@ pub async fn list_tables_on_connection( /// Run a DDL statement outside a transaction (required for CREATE/DROP DATABASE etc.). #[tauri::command] -pub async fn pg_execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), String> { +pub async fn pg_execute_ddl(state: Db<'_>, sql: String) -> Result<(), String> { execute_ddl(state, sql).await } #[tauri::command] pub async fn pg_update_table_cell( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -1739,7 +1740,7 @@ pub async fn pg_update_table_cell( /// Load one cell in full - the value a browse page deliberately did not fetch. #[tauri::command] pub async fn pg_fetch_cell_value( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -1751,7 +1752,7 @@ pub async fn pg_fetch_cell_value( #[tauri::command] pub async fn pg_delete_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -1761,7 +1762,7 @@ pub async fn pg_delete_table_row( #[tauri::command] pub async fn pg_delete_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_keys: Vec>, @@ -1772,7 +1773,7 @@ pub async fn pg_delete_table_rows( /// Staged grid changes as one transaction (Postgres, MySQL, SQLite) - see `apply_table_changes`. #[tauri::command] pub async fn pg_apply_table_changes( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, updates: Vec, @@ -1784,7 +1785,7 @@ pub async fn pg_apply_table_changes( #[tauri::command] pub async fn pg_insert_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, values: HashMap, @@ -1798,7 +1799,7 @@ pub async fn pg_insert_table_row( /// cancels every query in flight (the old whole-app "stop" behaviour). #[tauri::command] pub async fn cancel_query( - state: State<'_, DbState>, + state: Db<'_>, query_id: Option, ) -> Result<(), String> { if let Ok(mut map) = state.cancels.lock() { @@ -2246,7 +2247,7 @@ pub fn set_window_glass(window: tauri::WebviewWindow, enabled: bool, dark: bool) /// D1 Time Travel: the bookmark for now, or for the moment nearest `timestamp`. #[tauri::command] -pub async fn d1_bookmark(state: State<'_, DbState>, timestamp: Option) -> Result { +pub async fn d1_bookmark(state: Db<'_>, timestamp: Option) -> Result { match require_conn(&state)? { ActiveConnection::D1(cfg) => crate::db::d1::bookmark(&cfg, timestamp.as_deref()).await, _ => Err("Time Travel is a Cloudflare D1 feature.".into()), @@ -2255,7 +2256,7 @@ pub async fn d1_bookmark(state: State<'_, DbState>, timestamp: Option) - /// D1 Time Travel: rewind the database to a bookmark; returns the previous one. #[tauri::command] -pub async fn d1_restore(state: State<'_, DbState>, bookmark: String) -> Result { +pub async fn d1_restore(state: Db<'_>, bookmark: String) -> Result { match require_conn(&state)? { ActiveConnection::D1(cfg) => crate::db::d1::restore(&cfg, &bookmark).await, _ => Err("Time Travel is a Cloudflare D1 feature.".into()), diff --git a/src-tauri/src/db/backup.rs b/src-tauri/src/db/backup.rs index 47506558..7a27821c 100644 --- a/src-tauri/src/db/backup.rs +++ b/src-tauri/src/db/backup.rs @@ -20,6 +20,7 @@ Speed notes (why the code is shaped the way it is): - Progress is a per-table event, throttled while a table is being copied. */ +use crate::db::connection::Db; use std::fs::File; use std::io::{self, BufWriter, Read, Write}; use std::path::{Path, PathBuf}; @@ -29,9 +30,9 @@ use std::time::{Duration, Instant}; use futures::{StreamExt, TryStreamExt}; use serde::{Deserialize, Serialize}; use sqlx::{Column, Executor, Row, TypeInfo}; -use tauri::{AppHandle, Emitter, State}; +use tauri::{AppHandle, Emitter}; -use super::connection::{require_conn, ActiveConnection, DbState}; +use super::connection::{require_conn, ActiveConnection}; /// Cooperative cancel flag for the in-flight backup/restore. The frontend sets /// it via `backup_cancel`; the export/import loops poll it and stop early. @@ -446,7 +447,7 @@ fn partial_path(path: &Path) -> PathBuf { #[tauri::command] pub async fn backup_export( app: AppHandle, - state: State<'_, DbState>, + state: Db<'_>, schema: Option, tables: Option>, options: Option, @@ -583,7 +584,7 @@ async fn export_into( #[tauri::command] pub async fn backup_import( app: AppHandle, - state: State<'_, DbState>, + state: Db<'_>, sql: Option, path: Option, ) -> Result { diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index e6421d98..a58e12ea 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -404,6 +404,9 @@ pub struct DbState { /// connection key the page chose, oldest first. Switching back resumes one /// without connecting again. Capped (see `parked`). pub parked: Arc>>, + /// The page's key for the open (front) pool, when it has said. A call routed + /// to another key is served from `parked`; see `require_conn`. + pub active_key: Arc>>, /// Cancel handles for the queries currently in flight, keyed by the id the /// caller sent. Keyed rather than a single slot because the UI runs several /// queries at once (one per editor tab) - with one slot, the second run @@ -417,6 +420,7 @@ impl Default for DbState { Self { conn: Arc::new(Mutex::new(None)), parked: Arc::new(Mutex::new(Vec::new())), + active_key: Arc::new(Mutex::new(None)), cancels: Arc::new(Mutex::new(std::collections::HashMap::new())), } } @@ -424,21 +428,80 @@ impl Default for DbState { /// Register a cancel handle for `id`, replacing (and dropping) any handle already /// stored under it. -pub fn register_cancel(state: &State<'_, DbState>, id: &str, tx: oneshot::Sender<()>) { +pub fn register_cancel(state: &Db<'_>, id: &str, tx: oneshot::Sender<()>) { if let Ok(mut map) = state.cancels.lock() { map.insert(id.to_string(), tx); } } /// Drop the cancel handle for `id` (query finished, cancelling it is meaningless). -pub fn unregister_cancel(state: &State<'_, DbState>, id: &str) { +pub fn unregister_cancel(state: &Db<'_>, id: &str) { if let Ok(mut map) = state.cancels.lock() { map.remove(id); } } -/// Returns a clone of the active connection, or an error if disconnected. -pub fn require_conn(state: &State<'_, DbState>) -> Result { +/// `State` plus the database the call is for. +/// +/// Labs, several connections at once: tabs from several databases are open +/// together, and each call the page makes names its database in a `__conn` +/// argument (src/lib/api.js). The key is read from the request itself, so a +/// call sent just before a switch still reaches the database it was made for, +/// whichever pool is in front by the time it runs. Without one, the call goes +/// to the front pool, as before. +#[derive(Clone)] +pub struct Db<'r> { + state: State<'r, DbState>, + /// The `__conn` key the page sent, if any. + pub route: Option, +} + +impl<'r> Db<'r> { + /// For code that has the managed state but no request (MCP, background work): + /// it always means the front pool. + pub fn front(state: State<'r, DbState>) -> Self { + Self { state, route: None } + } + pub fn inner(&self) -> &'r DbState { + self.state.inner() + } +} + +impl std::ops::Deref for Db<'_> { + type Target = DbState; + fn deref(&self) -> &DbState { + self.state.inner() + } +} + +impl<'r, 'de: 'r, R: tauri::Runtime> tauri::ipc::CommandArg<'de, R> for Db<'r> { + fn from_command(command: tauri::ipc::CommandItem<'de, R>) -> Result { + let route = match command.message.payload() { + tauri::ipc::InvokeBody::Json(v) => v.get("__conn").and_then(|k| k.as_str()).filter(|k| !k.is_empty()).map(str::to_string), + _ => None, + }; + let state = as tauri::ipc::CommandArg<'de, R>>::from_command(command)?; + Ok(Self { state, route }) + } +} + +/// Returns a clone of the connection the call is for, or an error if there is +/// none. A routed call (see `Db`) gets its own database's pool: the front one +/// when that is its key, else the one kept aside for it. A key whose pool was +/// closed (pushed out by the cap, or its connection edited) is an error rather +/// than a quiet run on whatever database happens to be in front. +pub fn require_conn(state: &Db<'_>) -> Result { + if let Some(key) = state.route.as_deref() { + let front = state.active_key.lock().map_err(|e| e.to_string())?.clone(); + if front.as_deref() != Some(key) { + if let Some((_, c)) = state.parked.lock().map_err(|e| e.to_string())?.iter().find(|(k, _)| k == key) { + return Ok(c.clone()); + } + if front.is_some() { + return Err("That database's connection was closed. Click its tab to open it again.".to_string()); + } + } + } state .conn .lock() @@ -448,7 +511,7 @@ pub fn require_conn(state: &State<'_, DbState>) -> Result) -> Result { +pub fn require_pool(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Postgres(pool) => Ok(pool), other => Err(format!( @@ -480,12 +543,14 @@ pub fn update_d1_token(token: &str) { } } -fn set_conn(state: &State<'_, DbState>, conn: Option) -> Result<(), String> { +fn set_conn(state: &Db<'_>, conn: Option) -> Result<(), String> { *state.conn.lock().map_err(|e| e.to_string())? = conn; + // A fresh pool: the page names its key once it knows it (set_active_conn_key). + *state.active_key.lock().map_err(|e| e.to_string())? = None; Ok(()) } -async fn close_existing(state: &State<'_, DbState>) { +async fn close_existing(state: &Db<'_>) { let old = state.conn.lock().ok().and_then(|mut g| g.take()); let Some(conn) = old else { return }; close_in_background(conn); @@ -1279,7 +1344,7 @@ pub async fn test_connection(config: PgConfig) -> Result<(), String> { } pub async fn connect( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: PgConfig, ) -> Result<(), String> { @@ -1357,7 +1422,7 @@ pub async fn test_sqlite_connection(config: SqliteConfig) -> Result<(), String> Ok(()) } -pub async fn connect_sqlite(state: State<'_, DbState>, config: SqliteConfig) -> Result<(), String> { +pub async fn connect_sqlite(state: Db<'_>, config: SqliteConfig) -> Result<(), String> { let pool = open_sqlite(&config).await?; close_existing(&state).await; set_conn(&state, Some(ActiveConnection::Sqlite(pool))) @@ -1458,7 +1523,7 @@ pub async fn test_mysql_connection(config: MysqlConfig) -> Result<(), String> { } pub async fn connect_mysql( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: MysqlConfig, ) -> Result<(), String> { @@ -1492,7 +1557,7 @@ pub async fn test_d1_connection(config: D1Config) -> Result<(), String> { Ok(()) } -pub async fn connect_d1(state: State<'_, DbState>, config: D1Config) -> Result<(), String> { +pub async fn connect_d1(state: Db<'_>, config: D1Config) -> Result<(), String> { // Validate credentials before storing test_d1_connection(config.clone()).await?; close_existing(&state).await; @@ -1506,7 +1571,7 @@ pub async fn test_libsql_connection(config: LibSqlConfig) -> Result<(), String> Ok(()) } -pub async fn connect_libsql(state: State<'_, DbState>, config: LibSqlConfig) -> Result<(), String> { +pub async fn connect_libsql(state: Db<'_>, config: LibSqlConfig) -> Result<(), String> { test_libsql_connection(config.clone()).await?; close_existing(&state).await; set_conn(&state, Some(ActiveConnection::LibSql(config))) @@ -1523,7 +1588,7 @@ pub async fn test_clickhouse_connection(config: ClickhouseConfig) -> Result<(), .await } -pub async fn connect_clickhouse(state: State<'_, DbState>, config: ClickhouseConfig) -> Result<(), String> { +pub async fn connect_clickhouse(state: Db<'_>, config: ClickhouseConfig) -> Result<(), String> { // Validate credentials/reachability before storing. test_clickhouse_connection(config.clone()).await?; close_existing(&state).await; @@ -1536,7 +1601,7 @@ pub async fn test_posthog_connection(config: PosthogConfig) -> Result<(), String crate::db::posthog::query(&config, "SELECT 1").await.map(|_| ()) } -pub async fn connect_posthog(state: State<'_, DbState>, config: PosthogConfig) -> Result<(), String> { +pub async fn connect_posthog(state: Db<'_>, config: PosthogConfig) -> Result<(), String> { test_posthog_connection(config.clone()).await?; close_existing(&state).await; set_conn(&state, Some(ActiveConnection::Posthog(config))) @@ -1544,34 +1609,34 @@ pub async fn connect_posthog(state: State<'_, DbState>, config: PosthogConfig) - // ── DynamoDB connect / test ─────────────────────────────────────────────────── -pub async fn connect_dynamodb(state: State<'_, DbState>, config: crate::db::dynamodb::DynamoConfig) -> Result<(), String> { +pub async fn connect_dynamodb(state: Db<'_>, config: crate::db::dynamodb::DynamoConfig) -> Result<(), String> { crate::db::dynamodb::ping(&config).await?; set_conn(&state, Some(ActiveConnection::Dynamodb(config))) } // ── Document engines connect ────────────────────────────────────────────────── -pub async fn connect_cassandra(state: State<'_, DbState>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { +pub async fn connect_cassandra(state: Db<'_>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { let session = crate::db::cassandra::connect(&config).await?; set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Cassandra(session)))) } -pub async fn connect_mongo(state: State<'_, DbState>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { +pub async fn connect_mongo(state: Db<'_>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { let handle = crate::db::mongo::connect(&config).await?; set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(handle)))) } -pub async fn connect_firestore(state: State<'_, DbState>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { +pub async fn connect_firestore(state: Db<'_>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { crate::db::firestore::ping(&config).await?; set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Firestore(config)))) } -pub async fn connect_couchdb(state: State<'_, DbState>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { +pub async fn connect_couchdb(state: Db<'_>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { crate::db::couchdb::ping(&config).await?; set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Couch(config)))) } -pub async fn connect_elastic(state: State<'_, DbState>, config: crate::db::elastic::EsConfig) -> Result<(), String> { +pub async fn connect_elastic(state: Db<'_>, config: crate::db::elastic::EsConfig) -> Result<(), String> { let config = crate::db::elastic::connect(config).await?; set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Elastic(config)))) } @@ -1583,7 +1648,7 @@ pub async fn test_redis_connection(config: RedisConfig) -> Result<(), String> { connect_racing_probe(&host, port, None, crate::db::redis::ping(&config)).await } -pub async fn connect_redis(state: State<'_, DbState>, config: RedisConfig) -> Result<(), String> { +pub async fn connect_redis(state: Db<'_>, config: RedisConfig) -> Result<(), String> { // Validate credentials/reachability before storing. test_redis_connection(config.clone()).await?; close_existing(&state).await; @@ -1619,7 +1684,7 @@ pub async fn test_duckdb_connection(config: DuckdbConfig) -> Result<(), String> crate::db::duckdb::ping(&handle).await } -pub async fn connect_duckdb(state: State<'_, DbState>, config: DuckdbConfig) -> Result<(), String> { +pub async fn connect_duckdb(state: Db<'_>, config: DuckdbConfig) -> Result<(), String> { let handle = open_duckdb(&config).await?; crate::db::duckdb::ping(&handle).await?; close_existing(&state).await; @@ -1639,7 +1704,7 @@ pub async fn test_mssql_connection(config: MssqlConfig) -> Result<(), String> { crate::db::mssql::ping(&handle).await } -pub async fn connect_mssql(state: State<'_, DbState>, config: MssqlConfig) -> Result<(), String> { +pub async fn connect_mssql(state: Db<'_>, config: MssqlConfig) -> Result<(), String> { let handle = open_mssql(&config).await?; close_existing(&state).await; set_conn(&state, Some(ActiveConnection::Mssql(handle))) @@ -1663,7 +1728,7 @@ pub async fn test_oracle_connection(config: OracleConfig) -> Result<(), String> crate::db::oracle::ping(&handle).await } -pub async fn connect_oracle(state: State<'_, DbState>, config: OracleConfig) -> Result<(), String> { +pub async fn connect_oracle(state: Db<'_>, config: OracleConfig) -> Result<(), String> { let handle = open_oracle(&config).await?; close_existing(&state).await; set_conn(&state, Some(ActiveConnection::Oracle(handle))) @@ -1672,7 +1737,7 @@ pub async fn connect_oracle(state: State<'_, DbState>, config: OracleConfig) -> // ── Disconnect ──────────────────────────────────────────────────────────────── pub async fn disconnect( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, ) -> Result<(), String> { // close_existing already sets state to None atomically via take() before diff --git a/src-tauri/src/db/geo.rs b/src-tauri/src/db/geo.rs index f8993e8a..8e20b718 100644 --- a/src-tauri/src/db/geo.rs +++ b/src-tauri/src/db/geo.rs @@ -16,12 +16,12 @@ //! so the GiST index still answers it. Reprojection to WGS84 happens only on //! the rows that survive. -use super::connection::{require_conn, ActiveConnection, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, ActiveConnection}; use super::query::{build_where, RowFilter}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sqlx::{PgPool, Row}; -use tauri::State; /// Hard ceiling on features returned in one fetch, whatever the caller asks for. /// Above this the canvas is drawing more points than the viewport has pixels and @@ -91,7 +91,7 @@ pub struct GeoFeatures { /// PostGIS puts its own tables in these schemas; they are plumbing, not data. const HIDDEN_SCHEMAS: &str = "('information_schema', 'pg_catalog', 'topology', 'tiger', 'tiger_data')"; -fn pg_pool(state: &State<'_, DbState>) -> Result, String> { +fn pg_pool(state: &Db<'_>) -> Result, String> { match require_conn(state)? { ActiveConnection::Postgres(pool) => Ok(Some(pool)), _ => Ok(None), @@ -122,7 +122,7 @@ fn unavailable() -> GeoOverview { /// Is PostGIS installed, and what can be mapped? Safe to call on any connection: /// a non-Postgres engine, or a Postgres without the extension, reports /// `available: false` rather than failing. -pub async fn geo_overview(state: State<'_, DbState>) -> Result { +pub async fn geo_overview(state: Db<'_>) -> Result { let Some(pool) = pg_pool(&state)? else { return Ok(unavailable()) }; let version: Option = @@ -372,7 +372,7 @@ async fn layer_extent( /// holds more than `limit` rows. #[allow(clippy::too_many_arguments)] pub async fn geo_features( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, diff --git a/src-tauri/src/db/import.rs b/src-tauri/src/db/import.rs index d0940577..cb9978f4 100644 --- a/src-tauri/src/db/import.rs +++ b/src-tauri/src/db/import.rs @@ -10,14 +10,15 @@ keep going, the batch is replayed one row at a time so the report can name the rows that were actually bad instead of blaming all 500. */ +use crate::db::connection::Db; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use tauri::{AppHandle, Emitter, State}; +use tauri::{AppHandle, Emitter}; -use super::connection::{require_conn, ActiveConnection, DbState}; +use super::connection::{require_conn, ActiveConnection}; use super::query::{bind_typed_value, is_bytea_type, pg_insert_meta, validate_typed_value}; use super::schema::validate_ident; @@ -123,7 +124,7 @@ fn emit_log(app: &AppHandle, level: &'static str, message: impl Into) { #[tauri::command] pub async fn import_rows( app: AppHandle, - state: State<'_, DbState>, + state: Db<'_>, schema: Option, table: String, columns: Vec, diff --git a/src-tauri/src/db/insights.rs b/src-tauri/src/db/insights.rs index eb93e26e..2a189807 100644 --- a/src-tauri/src/db/insights.rs +++ b/src-tauri/src/db/insights.rs @@ -13,13 +13,13 @@ //! than failing the whole command. The dashboard must never hard-fail because, //! e.g., `pg_stat_replication` requires a privileged role. -use super::connection::{require_conn, ActiveConnection, ClickhouseConfig, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, ActiveConnection, ClickhouseConfig}; use super::query::SqlResult; use serde::Serialize; use serde_json::{Map, Value}; use sqlx::{Column, MySqlPool, PgPool, Row, SqlitePool}; use std::collections::HashMap; -use tauri::State; /// Returned when Instance Insights is requested on an unsupported engine. const UNSUPPORTED: &str = @@ -265,7 +265,7 @@ pub struct InstanceVersion { } /// Cheap engine + version lookup so the dashboard header can render immediately. -pub async fn instance_version(state: State<'_, DbState>) -> Result { +pub async fn instance_version(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let version = sqlx::query("SHOW server_version") @@ -369,7 +369,7 @@ fn usage_pct(total: i64, max: i64) -> f64 { } } -pub async fn instance_activity(state: State<'_, DbState>) -> Result { +pub async fn instance_activity(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => Ok(pg_activity(&pool).await), ActiveConnection::Mysql(pool) => Ok(mysql_activity(&pool).await), @@ -566,7 +566,7 @@ pub struct InstanceState { pub prepared_transactions: Vec, } -pub async fn instance_state(state: State<'_, DbState>) -> Result { +pub async fn instance_state(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let sessions = pg_query_objects( @@ -692,7 +692,7 @@ pub struct ConfigSetting { pub editable: bool, } -pub async fn instance_config(state: State<'_, DbState>) -> Result, String> { +pub async fn instance_config(state: Db<'_>) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let rows = sqlx::query( @@ -863,7 +863,7 @@ fn sql_literal(value: &str) -> String { /// hold `pg_write_all_settings`) - the server's own error is passed straight /// through when it is not. pub async fn instance_set_config( - state: State<'_, DbState>, + state: Db<'_>, name: String, value: Option, ) -> Result { @@ -983,7 +983,7 @@ pub struct InstanceReplication { pub slots: Vec, } -pub async fn instance_replication(state: State<'_, DbState>) -> Result { +pub async fn instance_replication(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let stats = pg_query_objects( diff --git a/src-tauri/src/db/objects.rs b/src-tauri/src/db/objects.rs index eabb0b6f..4f3d7cc4 100644 --- a/src-tauri/src/db/objects.rs +++ b/src-tauri/src/db/objects.rs @@ -11,12 +11,12 @@ //! Postgres routine's argument list for DROP is read back from the catalog //! rather than taken from the caller. +use crate::db::connection::Db; use serde::Serialize; use serde_json::Value; use sqlx::{MySqlPool, PgPool, Row, SqlitePool}; -use tauri::State; -use super::connection::{require_conn, ActiveConnection, D1Config, DbState, LibSqlConfig}; +use super::connection::{require_conn, ActiveConnection, D1Config, LibSqlConfig}; use super::mysql::my_text_named; use super::query::SqlResult; use super::sql_util::{esc_backslash_quote, esc_single_quote, quote_backtick, quote_bracket, quote_double}; @@ -232,7 +232,7 @@ fn trigger_row(name: String, table: String, detail: String, comment: Option, schema: String) -> Result { +pub async fn list_db_objects(state: Db<'_>, schema: String) -> Result { let conn = require_conn(&state)?; let kinds: Vec = kinds_for(&conn).iter().map(|k| k.to_string()).collect(); let cascade = matches!(conn, ActiveConnection::Postgres(_)); @@ -654,7 +654,7 @@ async fn list_clickhouse(cfg: &super::connection::ClickhouseConfig) -> Result, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1041,7 +1041,7 @@ async fn def_clickhouse(cfg: &super::connection::ClickhouseConfig, kind: &str, d /// Drop one object. Returns the statement that ran, for the log. #[allow(clippy::too_many_arguments)] pub async fn drop_object( - state: State<'_, DbState>, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1155,7 +1155,7 @@ pub async fn drop_object( /// Table and view comments for one schema, in one query. Engines that keep /// none (SQLite and its relatives) return an empty list. -pub async fn list_object_comments(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_object_comments(state: Db<'_>, schema: String) -> Result, String> { let pairs = |r: SqlResult| -> Vec { r.rows .iter() diff --git a/src-tauri/src/db/parked.rs b/src-tauri/src/db/parked.rs index 13b46f93..0238cb31 100644 --- a/src-tauri/src/db/parked.rs +++ b/src-tauri/src/db/parked.rs @@ -3,18 +3,18 @@ //! database costs nothing. Only the pool handle moves (it is an Arc inside), //! so this never touches the network. -use super::connection::{close_in_background, DbState}; -use tauri::State; +use super::connection::{close_in_background, Db}; /// More than this many set-aside pools and the oldest is closed. -const MAX_PARKED: usize = 6; +const MAX_PARKED: usize = 8; /// Set the open connection aside under `key`. Nothing open: nothing to do. #[tauri::command] -pub fn park_connection(state: State<'_, DbState>, key: String) -> Result<(), String> { +pub fn park_connection(state: Db<'_>, key: String) -> Result<(), String> { let Some(conn) = state.conn.lock().map_err(|e| e.to_string())?.take() else { return Ok(()); }; + *state.active_key.lock().map_err(|e| e.to_string())? = None; let mut parked = state.parked.lock().map_err(|e| e.to_string())?; parked.retain(|(k, _)| k != &key); parked.push((key, conn)); @@ -28,13 +28,14 @@ pub fn park_connection(state: State<'_, DbState>, key: String) -> Result<(), Str /// Make the pool set aside under `key` the open one. False when there is none /// (the page then connects as usual). #[tauri::command] -pub fn resume_connection(state: State<'_, DbState>, key: String) -> Result { +pub fn resume_connection(state: Db<'_>, key: String) -> Result { let found = { let mut parked = state.parked.lock().map_err(|e| e.to_string())?; parked.iter().position(|(k, _)| k == &key).map(|i| parked.remove(i).1) }; let Some(conn) = found else { return Ok(false) }; let previous = state.conn.lock().map_err(|e| e.to_string())?.replace(conn); + *state.active_key.lock().map_err(|e| e.to_string())? = Some(key); if let Some(prev) = previous { close_in_background(prev); } @@ -46,7 +47,7 @@ pub fn resume_connection(state: State<'_, DbState>, key: String) -> Result, + state: Db<'_>, key: Option, connection: Option, ) -> Result<(), String> { @@ -66,6 +67,14 @@ pub fn close_parked( /// Which connections are set aside, oldest first. #[tauri::command] -pub fn parked_connections(state: State<'_, DbState>) -> Result, String> { +pub fn parked_connections(state: Db<'_>) -> Result, String> { Ok(state.parked.lock().map_err(|e| e.to_string())?.iter().map(|(k, _)| k.clone()).collect()) } + +/// The page's key for the pool now in front, after it connects fresh (a +/// resume sets it itself). Routed calls compare against it. +#[tauri::command] +pub fn set_active_conn_key(state: Db<'_>, key: Option) -> Result<(), String> { + *state.active_key.lock().map_err(|e| e.to_string())? = key.filter(|k| !k.is_empty()); + Ok(()) +} diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index a1e2d18c..3edeb457 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -1,4 +1,5 @@ -use super::connection::{require_conn, require_pool, ActiveConnection, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, require_pool, ActiveConnection}; use super::schema::validate_ident; use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc}; use futures::TryStreamExt; @@ -9,7 +10,6 @@ use sqlx::{Column, Decode, Postgres, Row, TypeInfo, ValueRef}; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; -use tauri::State; use uuid::Uuid; #[derive(Debug, Clone, Serialize)] @@ -1958,7 +1958,7 @@ pub(crate) fn validate_raw_filters(conn: &ActiveConnection, filters: Option<&[Ro } pub async fn get_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, limit: i64, @@ -2580,7 +2580,7 @@ static SUPERSEDED: std::sync::LazyLock = std::sync::LazyLock::new(|| /// (the WHERE clause bounds the scan). Non-Postgres engines return -1 - their /// `get_table_rows` already carries a real total, so the UI keeps that. pub async fn count_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, search: Option, @@ -2689,7 +2689,7 @@ pub async fn count_table_rows( } pub async fn update_table_cell( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -2908,7 +2908,7 @@ pub(crate) async fn pg_insert_meta( } pub async fn insert_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, values: HashMap, @@ -3034,7 +3034,7 @@ pub async fn insert_table_row( } pub async fn delete_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -3047,7 +3047,7 @@ pub async fn delete_table_row( } pub async fn delete_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_keys: Vec>, @@ -3263,7 +3263,7 @@ pub(crate) fn describe_pk(pk_columns: &[String], primary_key: &HashMap, + state: Db<'_>, schema: String, table: String, updates: Vec, @@ -3514,7 +3514,7 @@ pub(crate) fn is_row_returning_sql(sql: &str) -> bool { /// Execute a single DDL statement that must run outside a transaction (e.g. /// CREATE DATABASE), directly on the connection, on any engine that has DDL. -pub async fn execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), String> { +pub async fn execute_ddl(state: Db<'_>, sql: String) -> Result<(), String> { let sql_str = sql.trim(); if sql_str.is_empty() { return Err("Statement is empty".into()); @@ -3523,7 +3523,7 @@ pub async fn execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), S } pub async fn execute_sql( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result { @@ -4479,7 +4479,7 @@ async fn run_sql_multi_pg( } pub async fn execute_sql_multi( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result, String> { @@ -4594,7 +4594,7 @@ impl StatementOutcome { /// A single Postgres statement streams through `sink` (into the result store, /// in store mode). A script's results come back in the reply. pub async fn execute_sql_script( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, sink: Option<&mut RowSink>, @@ -5146,7 +5146,7 @@ const CELL_FETCH_HARD_MAX: i64 = 64 * 1024 * 1024; const CELL_FETCH_DEFAULT_MAX: i64 = 32 * 1024 * 1024; pub async fn fetch_cell_value( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -5260,7 +5260,7 @@ pub async fn fetch_cell_value( } pub async fn get_column_stats( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -5354,7 +5354,7 @@ pub async fn get_column_stats( /// MIN/MAX/DISTINCT on the column type (e.g. JSON/BLOB), so the panel still shows /// total + null counts instead of erroring. async fn column_stats_generic( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -5457,7 +5457,7 @@ async fn dispatch_stats_sql(conn: &ActiveConnection, sql: &str) -> Result) -> Result<(), String> { +pub async fn ping_connection(state: Db<'_>) -> Result<(), String> { let conn = require_conn(&state)?; match conn { // Remote pools: touch every idle connection, not just one (see keepalive_idle). @@ -5940,7 +5940,7 @@ fn search_index_name(table: &str, column: &str) -> String { } pub async fn search_index_status( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { @@ -5987,7 +5987,7 @@ pub async fn search_index_status( /// Create the missing trigram indexes. CONCURRENTLY, so the table stays /// readable and writable while they build; returns the indexes created. pub async fn create_search_index( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { diff --git a/src-tauri/src/db/schema.rs b/src-tauri/src/db/schema.rs index 3d0128be..3495ccc2 100644 --- a/src-tauri/src/db/schema.rs +++ b/src-tauri/src/db/schema.rs @@ -1,7 +1,7 @@ -use super::connection::{require_conn, ActiveConnection, AnyConnectionConfig, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, ActiveConnection, AnyConnectionConfig}; use serde::Serialize; use sqlx::{MySqlPool, PgPool, Row}; -use tauri::State; use super::mysql::{my_int, my_text, my_text_named}; @@ -219,7 +219,7 @@ pub struct TableRowCount { /// `list_tables` already returns exact counts inline (SQLite/D1/libSQL/…) /// never report -1, so they return an empty list here. pub async fn table_row_counts( - state: State<'_, DbState>, + state: Db<'_>, schema: String, tables: Vec, ) -> Result, String> { @@ -1138,7 +1138,7 @@ async fn list_sequences_pg(pool: &PgPool, schema: &str) -> Result) -> Result, String> { +pub async fn list_schemas(state: Db<'_>) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => list_schemas_pg(&pool).await, ActiveConnection::Mysql(pool) => list_schemas_mysql(&pool).await, @@ -1153,7 +1153,7 @@ pub async fn list_schemas(state: State<'_, DbState>) -> Result, Stri } } -pub async fn list_tables(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_tables(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1197,7 +1197,7 @@ pub async fn list_tables(state: State<'_, DbState>, schema: String) -> Result, + state: Db<'_>, schema: String, table: Option, ) -> Result, String> { @@ -1295,7 +1295,7 @@ async fn list_functions_mysql(pool: &sqlx::MySqlPool, schema: &str) -> Result, schema: String) -> Result, String> { +pub async fn list_functions(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1309,7 +1309,7 @@ pub async fn list_functions(state: State<'_, DbState>, schema: String) -> Result } } -pub async fn list_enums(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_enums(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1319,7 +1319,7 @@ pub async fn list_enums(state: State<'_, DbState>, schema: String) -> Result, schema: String) -> Result, String> { +pub async fn list_triggers(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1334,7 +1334,7 @@ pub async fn list_triggers(state: State<'_, DbState>, schema: String) -> Result< } } -pub async fn list_sequences(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_sequences(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1349,19 +1349,19 @@ pub async fn list_sequences(state: State<'_, DbState>, schema: String) -> Result // Both spell the statement per engine in `admin`; this used to know Postgres // and SQLite only and told every other engine it was unsupported. -pub async fn truncate_table(state: State<'_, DbState>, schema: String, table: String) -> Result<(), String> { +pub async fn truncate_table(state: Db<'_>, schema: String, table: String) -> Result<(), String> { let conn = require_conn(&state)?; super::admin::truncate_table(&conn, &schema, &table).await } -pub async fn drop_table(state: State<'_, DbState>, schema: String, table: String, cascade: bool, kind: Option) -> Result<(), String> { +pub async fn drop_table(state: Db<'_>, schema: String, table: String, cascade: bool, kind: Option) -> Result<(), String> { let kind = super::admin::ObjectKind::parse(kind.as_deref())?; let conn = require_conn(&state)?; super::admin::drop_object(&conn, &schema, &table, kind, cascade).await } pub async fn get_table_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1720,7 +1720,7 @@ async fn get_column_structure_pg( /// MongoDB, CouchDB, Firestore, DynamoDB and Redis have no schema-wide column /// catalog: they answer empty at once, and the caller reads per table. pub async fn get_schema_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { match require_conn(&state)? { @@ -2502,7 +2502,7 @@ async fn get_incoming_fks_mssql(handle: &super::connection::MssqlHandle, schema: } pub async fn get_incoming_foreign_keys( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -2677,7 +2677,7 @@ async fn get_ddl_libsql( } pub async fn get_table_ddl( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { diff --git a/src-tauri/src/db/tx.rs b/src-tauri/src/db/tx.rs index 845394e4..b03fab1d 100644 --- a/src-tauri/src/db/tx.rs +++ b/src-tauri/src/db/tx.rs @@ -11,6 +11,7 @@ as it stays open, so a session that is left behind is closed automatically after `IDLE_TIMEOUT` - see `sweep_idle`. */ +use crate::db::connection::Db; use std::collections::HashMap; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -21,7 +22,7 @@ use serde_json::Value; use sqlx::{Column, Row, TypeInfo}; use tauri::State; -use super::connection::{require_conn, ActiveConnection, DbState}; +use super::connection::{require_conn, ActiveConnection}; use super::query::{ cell_to_json, is_row_returning_sql, pg_type_label, split_sql_statements, ColumnInfo, SqlResult, EXECUTE_SQL_TIMEOUT_MS, @@ -122,7 +123,7 @@ fn no_session(id: &str) -> String { /// Open a transaction and hold its connection until commit or rollback. #[tauri::command] pub async fn tx_begin( - db: State<'_, DbState>, + db: Db<'_>, tx: State<'_, TxState>, session_id: String, ) -> Result { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 570ed49d..b29a7c37 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -452,6 +452,7 @@ pub fn run() { let db_state = DbState { conn: Arc::clone(&db_conn), parked: Arc::new(Mutex::new(Vec::new())), + active_key: Arc::new(Mutex::new(None)), cancels: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())), }; let db_conn_for_setup = Arc::clone(&db_conn); @@ -912,6 +913,7 @@ pub fn run() { quit::cancel_quit, quit::set_quit_guard, db::parked::park_connection, + db::parked::set_active_conn_key, db::parked::resume_connection, db::parked::close_parked, db::parked::parked_connections, diff --git a/src/lib/api.js b/src/lib/api.js index a267cd75..689c9d63 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -77,8 +77,21 @@ async function healD1Auth(msg) { } } +/** + * Labs, several connections at once: the key of the database the page is on. + * Every call carries it as `__conn` (read by the Rust `Db` extractor), so a + * call sent just before a switch still runs on the database it was made for, + * whichever pool is in front by the time it lands. Empty: no routing. + */ +let _connRoute = '' +/** @param {string} key */ +export function setConnRoute(key) { + _connRoute = key || '' +} + async function inv(command, args = {}) { const t0 = performance.now() + if (_connRoute && args && typeof args === 'object' && !('__conn' in args)) args = { ...args, __conn: _connRoute } try { const r = await invoke(command, args) traceIpc(command, performance.now() - t0, true) diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 2a1f3841..affcba64 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -149,7 +149,7 @@ import WifiOff from '@lucide/svelte/icons/wifi-off' import Unplug from '@lucide/svelte/icons/unplug' import RefreshCw from '@lucide/svelte/icons/refresh-cw' - import { + import { setConnRoute, disconnectPostgres, prewarmDns, listSchemas, @@ -7633,6 +7633,10 @@ let rowSearch = $state('') } async function onConnected(conn, savedId) { + // A fresh pool is in front and unnamed: no routing until the switch that + // opened it names it (handleSwitchDatabase), or a call meant for this + // database could be sent to a kept one for the database just left. + setConnRoute('') connectedSavedId = savedId ?? '' // Labels belong to the database they were read from. void import('$lib/plugins/extensions/fk-labels.js').then((m) => m.clearFkLabels()) @@ -8316,6 +8320,7 @@ let rowSearch = $state('') if (!forget && persistConnectionId && activeSchema) setLastSchema(persistConnectionId, activeSchema) recordActivity({ type: 'disconnect', title: `Disconnected from ${connection?.name ?? 'database'}`, success: true }) setWasDisconnected(true) + setConnRoute('') try { await disconnectPostgres() } catch { /* ignore */ } try { await mcpStop() } catch { /* ignore */ } mcpRunning = false @@ -8334,6 +8339,7 @@ let rowSearch = $state('') savedConnections = loadSavedConnections() // Labs: its kept tabs go with it (its pools are closed by removeConnection). for (const key of [..._sessions.keys()]) if (key.startsWith(`${id}|`)) _sessions.delete(key) + sessionsTick++ if (connection && id && (id === persistConnectionId || id === connection.id)) { void handleDisconnect({ forget: true }) } @@ -8426,27 +8432,55 @@ let rowSearch = $state('') // their rows (marked evicted) and refetch when shown, so a kept session // costs a tab list, not its data. SSH-tunnelled connections share one // tunnel slot, so they still connect each time. - /** @type {Map} */ + /** + * @typedef {{ conn: any, label: string, tabs: StudioTab[], activeTabId: string | null, + * activeSchema: string, activeTable: string | null, schemas: string[], tables: any[] }} KeptSession + */ + /** @type {Map} */ const _sessions = new Map() + /** Bumped on every change to _sessions, so the tab bar re-reads it. */ + let sessionsTick = $state(0) + /** 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 /** One key per database, not per saved connection: a server holds several. @param {any} c */ const sessionKey = (c) => (c ? [c.id ?? '', c.type, c.databaseId ?? c.database ?? c.filePath ?? ''].join('|') : '') /** @param {any} c */ const keepable = (c) => !!c && !c.ssh?.host + /** A database's short name for its tabs. @param {any} c */ + const sessionLabel = (c) => String(c?.database || c?.name || c?.filePath?.split(/[\\/]/).pop() || c?.host || 'database') + /** @param {string} key */ + function noteSession(key) { + if (key && !sessionOrder.includes(key)) sessionOrder = [...sessionOrder, key] + } - /** Put the open connection's tabs aside under its key. */ + /** Put the open connection's tabs (and its sidebar) aside under its key. */ function keepSession() { if (!connection) return saveActiveTabState() + flushSqlTabs() const key = sessionKey(connection) + noteSession(key) // Newest last, so the cap drops the one used longest ago (as db/parked.rs does). _sessions.delete(key) _sessions.set(key, { - tabs: tabs.map((t) => (t.kind === 'table' && t.state ? { ...t, state: { ...t.state, rows: [], evicted: true } } : t)), + conn: connection, + 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)), activeTabId, activeSchema, + activeTable, + schemas, + tables, }) - while (_sessions.size > 6) _sessions.delete(/** @type {string} */ (_sessions.keys().next().value)) + while (_sessions.size > 8) { + const old = /** @type {string} */ (_sessions.keys().next().value) + _sessions.delete(old) + sessionOrder = sessionOrder.filter((k) => k !== old) + } + sessionsTick++ } /** Bring a kept session's tabs back over the fresh connection's default tab. @param {any} conn */ @@ -8455,6 +8489,7 @@ let rowSearch = $state('') const s = _sessions.get(key) if (!s || !s.tabs.length) return _sessions.delete(key) + sessionsTick++ tabs = s.tabs // Its editor tabs are already here: don't add the stored copies again. if (tabs.some((t) => t.kind === 'sql')) _sqlTabsRestoredFor = sqlDraftKey @@ -8467,8 +8502,108 @@ let rowSearch = $state('') await applyTabToEditor(front) } - /** @param {import('$lib/stores/connections.js').SavedConnection} conn */ - async function handleSwitchDatabase(conn) { + /** + * Switch to a kept database in place: its pool is already open (resumed in + * Rust), so nothing is torn down and nothing reconnects. The connection, + * sidebar and tabs are swapped in one go and refreshed quietly behind, so + * the switch shows no welcome screen, no empty sidebar and no spinner. + * @param {any} conn @param {KeptSession} s @param {string | null} [focusTab] + */ + async function resumeSession(conn, s, focusTab = null) { + connectedSavedId = conn.id ?? '' + connection = conn + savedConnections = loadSavedConnections() + tableReadonly = savedConnections.find((c) => c.id === conn.id)?.readOnly ?? conn.readOnly ?? false + if (conn.id) setLastConnectionId(conn.id) + error = '' + connectionLost = false + tableColumnsCache = new Map() + resetIncomingFkCache() + _catalog.clear() + _sqlHintsLoadedFor = '' + indexes = [] + enums = [] + triggers = [] + sequences = [] + tableFilter = '' + structureColumns = [] + structureSearch = '' + schemas = s.schemas + activeSchema = s.activeSchema + tables = s.tables + activeTable = s.activeTable + // The list on screen is this database's: a refresh keeps it up (no dots). + _tablesKey = catalogKey(persistConnectionId, 'tables', activeSchema) + loadingTables = false + tabs = s.tabs + if (tabs.some((t) => t.kind === 'sql')) _sqlTabsRestoredFor = sqlDraftKey + const front = tabs.find((t) => t.id === focusTab) ?? tabs.find((t) => t.id === s.activeTabId) ?? tabs[0] + activeTabId = front?.id ?? null + if (front) await applyTabToEditor(front) + void refreshQueryStores().catch(() => {}) + // Catch up quietly: the kept lists can be a little behind. + void (async () => { + const at = persistConnectionId + try { await loadSchemas() } catch { /* the table list still refreshes */ } + if (!connectionMoved(at)) await loadTables({ force: true, quiet: true }) + })() + } + + /** The kept session holding a tab, if any. @param {string} id */ + function sessionOfTab(id) { + for (const [key, s] of _sessions) if (s.tabs.some((t) => t.id === id)) return { key, s } + return null + } + + /** A tab of another open database: switch to that database, on that tab. @param {string} id */ + async function activateForeignTab(id) { + const hit = sessionOfTab(id) + if (!hit) return + await handleSwitchDatabase(hit.s.conn, { focusTab: id }) + } + + /** Close a tab of another open database without switching to it. @param {string} id */ + function closeForeignTab(id) { + const hit = sessionOfTab(id) + if (!hit) return + const left = hit.s.tabs.filter((t) => t.id !== id) + if (left.length) _sessions.set(hit.key, { ...hit.s, tabs: left, activeTabId: hit.s.activeTabId === id ? left[0].id : hit.s.activeTabId }) + else _sessions.set(hit.key, { ...hit.s, tabs: [] }) + sessionsTick++ + } + + /** + * 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. + */ + const barTabs = $derived.by(() => { + void sessionsTick + const own = $appAiInTab ? tabs : tabs.filter((t) => t.kind !== 'ai') + if (!connection || _sessions.size === 0) return own + const here = sessionKey(connection) + const kept = [..._sessions].filter(([k, s]) => k !== here && s.tabs.some((t) => t.kind !== 'welcome')) + if (!kept.length) return own + const label = sessionLabel(connection) + const order = sessionOrder.includes(here) ? sessionOrder : [...sessionOrder, here] + /** @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 }) + } + } + return out + }) + + /** + * @param {import('$lib/stores/connections.js').SavedConnection} conn + * @param {{ focusTab?: string | null }} [opts] Labs: the tab to land on + */ + async function handleSwitchDatabase(conn, opts = {}) { // 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 @@ -8477,10 +8612,31 @@ let rowSearch = $state('') const previous = connection const multi = multiConnection() if (multi && keepable(previous)) { + if (previous && sessionKey(previous) === sessionKey(conn)) { + // Already here: just the tab. + if (opts.focusTab) void activateTab(opts.focusTab) + return + } keepSession() await liveStop().catch(() => {}) const { invoke } = await import('@tauri-apps/api/core') await invoke('park_connection', { key: sessionKey(previous) }).catch(() => disconnectPostgres().catch(() => {})) + // 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 + } + } } else { await disconnectPostgres().catch(() => {}) } @@ -8508,7 +8664,16 @@ let rowSearch = $state('') await connectByType(conn) } await onConnected(conn, conn.id) + if (multi && keepable(conn)) { + // Name the new front pool, so calls routed to it (and to the kept + // ones) find the right database. + const key = sessionKey(conn) + noteSession(key) + setConnRoute(key) + void import('@tauri-apps/api/core').then(({ invoke }) => invoke('set_active_conn_key', { key })).catch(() => {}) + } else setConnRoute('') if (multi) await restoreSession(conn) + if (opts.focusTab && tabs.some((t) => t.id === opts.focusTab)) void activateTab(opts.focusTab) // The switch landed, so the sidebar goes back to the tables of the // database you are now in. Every route into a switch - the Databases tab, // the status bar, the command palette, a context menu, another saved @@ -9673,18 +9838,18 @@ let rowSearch = $state('') {#snippet tabStrip()} {#if tabsInTitle} t.kind !== 'ai')} + tabs={barTabs} {activeTabId} - onselect={(id) => activateTab(id)} - onclose={closeTab} - oncloseothers={closeOtherTabs} + onselect={(id) => (tabs.some((t) => t.id === id) ? activateTab(id) : activateForeignTab(id))} + onclose={(id) => (tabs.some((t) => t.id === id) ? closeTab(id) : closeForeignTab(id))} + oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} - onduplicate={(id) => void duplicateTab(id)} - onresettable={(id) => void resetTableTab(id)} + onduplicate={(id) => { if (tabs.some((t) => t.id === id)) void duplicateTab(id) }} + onresettable={(id) => { if (tabs.some((t) => t.id === id)) void resetTableTab(id) }} onreopenclosed={reopenLastClosedTab} canreopenclosed={closedTabStack.length > 0} - onpintoggle={toggleTabPin} + onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} /> {/if} @@ -10034,18 +10199,18 @@ let rowSearch = $state('') (T3 has one row). A second tab brings the strip back. --> {#if tabBarVisible && !tabsInTitle} t.kind !== 'ai')} + tabs={barTabs} {activeTabId} - onselect={(id) => activateTab(id)} - onclose={closeTab} - oncloseothers={closeOtherTabs} + onselect={(id) => (tabs.some((t) => t.id === id) ? activateTab(id) : activateForeignTab(id))} + onclose={(id) => (tabs.some((t) => t.id === id) ? closeTab(id) : closeForeignTab(id))} + oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} - onduplicate={(id) => void duplicateTab(id)} - onresettable={(id) => void resetTableTab(id)} + onduplicate={(id) => { if (tabs.some((t) => t.id === id)) void duplicateTab(id) }} + onresettable={(id) => { if (tabs.some((t) => t.id === id)) void resetTableTab(id) }} onreopenclosed={reopenLastClosedTab} canreopenclosed={closedTabStack.length > 0} - onpintoggle={toggleTabPin} + onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} /> {/if} @@ -10059,14 +10224,14 @@ let rowSearch = $state('') activeTabId={group.activeTabId} onselect={(id) => void focusTabInGroup(group.id, id)} onclose={(id) => void closeTabInGroup(group.id, id)} - oncloseothers={closeOtherTabs} + oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} - onduplicate={(id) => void duplicateTab(id)} - onresettable={(id) => void resetTableTab(id)} + onduplicate={(id) => { if (tabs.some((t) => t.id === id)) void duplicateTab(id) }} + onresettable={(id) => { if (tabs.some((t) => t.id === id)) void resetTableTab(id) }} onreopenclosed={reopenLastClosedTab} canreopenclosed={closedTabStack.length > 0} - onpintoggle={toggleTabPin} + onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} ondragtabstart={(id) => beginTabDrag(id)} ondragtabmove={(x, y) => moveTabDrag(x, y)} diff --git a/src/lib/components/TabBar.svelte b/src/lib/components/TabBar.svelte index 0118487c..275c3175 100644 --- a/src/lib/components/TabBar.svelte +++ b/src/lib/components/TabBar.svelte @@ -216,8 +216,13 @@ )} onclick={() => { if (_suppressTabClick) { _suppressTabClick = false; return } onselect(tab.id) }} > - - {tabDisplayTitle(tab)} + + + {#if tab.connLabel} + {tab.connLabel} + {/if} + {tabDisplayTitle(tab)} {#if tab.pinned} From 03ade6f77e3e7799c2ec71f04d51ca902197f6d6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:44:18 +0000 Subject: [PATCH 227/317] chore: version 2.16.2 (#260) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66d94e18..8dd1197a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.16.2] - 2026-11-15 + +### Changes +- Labs: several databases open together, one tab bar, switching in place (#260) + + ## [2.16.1] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index df242aeb..08cb0f3b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.16.1", + "version": "2.16.2", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 7d9aa5eb..2738054c 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.16.1", + "version": "2.16.2", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From d6b2b2897adc66268b2a3d7d1b413f46e421c62f Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 00:52:31 +0545 Subject: [PATCH 228/317] strokedb 0.2.0: the bridge for studio v2 (#261) * strokedb 0.2.0 bridge: structure, filters, edits by primary key, row counts Co-Authored-By: Claude Opus 5.5 * strokedb: Postgres row counts for tables never analyzed reltuples is -1 until a table is first analyzed; fall back to the live count in pg_stat_user_tables so the studio sidebar shows a number. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- cli/package.json | 2 +- cli/src/bridge.js | 27 ++- cli/src/engines.js | 431 +++++++++++++++++++++++++++++++++---------- cli/test/cli.test.js | 37 +++- 4 files changed, 395 insertions(+), 102 deletions(-) diff --git a/cli/package.json b/cli/package.json index 964a1191..08dcd832 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "strokedb", - "version": "0.1.1", + "version": "0.2.0", "description": "Open your project's database in Stroke: the desktop app if it's installed, otherwise the web studio at stroke.click/studio", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click/studio", diff --git a/cli/src/bridge.js b/cli/src/bridge.js index b3d2dbf5..04ae8bd4 100644 --- a/cli/src/bridge.js +++ b/cli/src/bridge.js @@ -15,6 +15,9 @@ import http from 'node:http' import crypto from 'node:crypto' export const STUDIO_ORIGIN = 'https://stroke.click' +/** Bumped with the package; the page reads `features` to know what it may offer. */ +export const BRIDGE_VERSION = '0.2.0' +export const FEATURES = ['structure', 'where', 'edit', 'rowCounts'] const MAX_BODY = 1 << 20 /** @@ -37,10 +40,24 @@ export async function startBridge({ engine, name, origins = [STUDIO_ORIGIN], por /** @type {Record Promise>} */ const routes = { - '/info': async () => ({ ...(await engine.info()), name }), + '/info': async () => ({ ...(await engine.info()), name, bridge: BRIDGE_VERSION, features: FEATURES }), '/tables': () => engine.tables(), '/columns': (b) => engine.columns(str(b.schema), str(b.table)), - '/rows': (b) => engine.rows({ schema: str(b.schema), table: str(b.table), limit: Number(b.limit) || 100, offset: Number(b.offset) || 0, sort: b.sort ?? null }), + '/structure': (b) => engine.structure(str(b.schema), str(b.table)), + '/rows': (b) => engine.rows({ + schema: str(b.schema), + table: str(b.table), + limit: Number(b.limit) || 100, + offset: Number(b.offset) || 0, + sort: b.sort ?? null, + where: typeof b.where === 'string' ? b.where : '', + }), + '/update': (b) => engine.update({ schema: str(b.schema), table: str(b.table), key: obj(b.key), set: obj(b.set) }), + '/insert': (b) => engine.insert({ schema: str(b.schema), table: str(b.table), values: obj(b.values) }), + '/delete': (b) => { + if (!Array.isArray(b.keys) || !b.keys.length) throw new Error('Expected keys') + return engine.remove({ schema: str(b.schema), table: str(b.table), keys: b.keys.map(obj) }) + }, '/query': async (b) => { const t = performance.now() const r = await engine.query(str(b.sql)) @@ -100,6 +117,12 @@ export async function startBridge({ engine, name, origins = [STUDIO_ORIGIN], por } } +/** @param {unknown} v @returns {Record} */ +function obj(v) { + if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('Expected an object') + return /** @type {Record} */ (v) +} + /** @param {unknown} v */ function str(v) { if (typeof v !== 'string') throw new Error('Expected a string') diff --git a/cli/src/engines.js b/cli/src/engines.js index 397f1167..815a3fa0 100644 --- a/cli/src/engines.js +++ b/cli/src/engines.js @@ -1,17 +1,28 @@ -// The three engines the bridge speaks, behind one small interface the web -// studio calls: tables, columns, a page of rows, and a SQL console. +// The three engines the bridge speaks, behind one interface the web studio +// calls: tables, structure, a page of rows, edits by primary key, and a SQL +// console. /** - * @typedef {{ schema: string, name: string, kind: 'table' | 'view' }} TableRef - * @typedef {{ name: string, type: string, nullable: boolean, primaryKey: boolean }} Column + * @typedef {{ schema: string, name: string, kind: 'table' | 'view', rows: number | null }} TableRef + * @typedef {{ name: string, type: string, nullable: boolean, primaryKey: boolean, default: string | null }} Column + * @typedef {{ name: string, columns: string[], unique: boolean, primary: boolean }} Index + * @typedef {{ name: string, columns: string[], refSchema: string, refTable: string, refColumns: string[] }} ForeignKey + * @typedef {{ columns: Column[], indexes: Index[], foreignKeys: ForeignKey[] }} Structure * @typedef {{ columns: string[], rows: unknown[][], rowCount?: number | null, command?: string }} Result * @typedef {{ column: string, dir: 'asc' | 'desc' }} Sort + * @typedef {{ schema: string, table: string, limit: number, offset: number, sort?: Sort | null, where?: string }} RowsQuery + * @typedef {Record} Values + * @typedef {{ sql: string, params: unknown[], atMostOne?: boolean }} Step * @typedef {{ * engine: 'postgres' | 'mysql' | 'sqlite', * info(): Promise<{ engine: string, database: string, host: string, version: string }>, * tables(): Promise, * columns(schema: string, table: string): Promise, - * rows(o: { schema: string, table: string, limit: number, offset: number, sort?: Sort | null }): Promise, + * structure(schema: string, table: string): Promise, + * rows(o: RowsQuery): Promise, + * update(o: { schema: string, table: string, key: Values, set: Values }): Promise<{ rowCount: number }>, + * insert(o: { schema: string, table: string, values: Values }): Promise<{ rowCount: number }>, + * remove(o: { schema: string, table: string, keys: Values[] }): Promise<{ rowCount: number }>, * query(sql: string): Promise, * close(): Promise, * }} Engine @@ -35,20 +46,84 @@ export function cell(v) { return v } +/** + * A value from the page as a driver parameter: objects (json columns) as JSON + * text, everything else as is - the database casts text to the column's type. + * @param {unknown} v + */ +export function param(v) { + if (v === undefined) return null + if (v !== null && typeof v === 'object') return JSON.stringify(v) + return v +} + /** @param {string} id */ -const pgId = (id) => `"${String(id).replace(/"/g, '""')}"` +const dq = (id) => `"${String(id).replace(/"/g, '""')}"` /** @param {string} id */ -const myId = (id) => `\`${String(id).replace(/`/g, '``')}\`` - -/** @param {Sort | null | undefined} sort @param {(id: string) => string} q */ -function orderBy(sort, q) { - if (!sort?.column) return '' - return ` ORDER BY ${q(sort.column)} ${sort.dir === 'desc' ? 'DESC' : 'ASC'}` -} +const bq = (id) => `\`${String(id).replace(/`/g, '``')}\`` /** @param {number} n @param {number} max */ const clampInt = (n, max) => Math.max(0, Math.min(max, Math.floor(Number(n) || 0))) +/** + * SQL builders for one dialect. + * @param {{ q: (id: string) => string, ph: (i: number) => string, from: (schema: string, table: string) => string }} d + */ +export function dialect(d) { + /** @param {Values} key @param {number} start */ + const whereKey = (key, start) => { + const cols = Object.keys(key) + if (!cols.length) throw new Error('No primary key: this table can only be changed with SQL.') + return { + sql: cols.map((c, i) => `${d.q(c)} = ${d.ph(start + i)}`).join(' AND '), + params: cols.map((c) => param(key[c])), + } + } + return { + ...d, + /** @param {RowsQuery} o */ + page(o) { + const where = o.where?.trim() ? ` WHERE (${o.where})` : '' + const order = o.sort?.column ? ` ORDER BY ${d.q(o.sort.column)} ${o.sort.dir === 'desc' ? 'DESC' : 'ASC'}` : '' + return { + sql: `SELECT * FROM ${d.from(o.schema, o.table)}${where}${order} LIMIT ${clampInt(o.limit, 5000)} OFFSET ${clampInt(o.offset, 1e12)}`, + count: `SELECT count(*) AS n FROM ${d.from(o.schema, o.table)}${where}`, + } + }, + /** @param {string} schema @param {string} table @param {Values} key @param {Values} set @returns {Step} */ + update(schema, table, key, set) { + const cols = Object.keys(set) + if (!cols.length) throw new Error('Nothing to change.') + const w = whereKey(key, cols.length + 1) + return { + sql: `UPDATE ${d.from(schema, table)} SET ${cols.map((c, i) => `${d.q(c)} = ${d.ph(i + 1)}`).join(', ')} WHERE ${w.sql}`, + params: [...cols.map((c) => param(set[c])), ...w.params], + atMostOne: true, + } + }, + /** @param {string} schema @param {string} table @param {Values} values @returns {Step} */ + insert(schema, table, values) { + const cols = Object.keys(values) + if (!cols.length) return { sql: d.emptyInsert(d.from(schema, table)), params: [] } + return { + sql: `INSERT INTO ${d.from(schema, table)} (${cols.map(d.q).join(', ')}) VALUES (${cols.map((_, i) => d.ph(i + 1)).join(', ')})`, + params: cols.map((c) => param(values[c])), + } + }, + /** @param {string} schema @param {string} table @param {Values} key @returns {Step} */ + remove(schema, table, key) { + const w = whereKey(key, 1) + return { sql: `DELETE FROM ${d.from(schema, table)} WHERE ${w.sql}`, params: w.params, atMostOne: true } + }, + emptyInsert: d.emptyInsert, + } +} + +/** @param {number} n @param {Step} step */ +function checkOne(n, step) { + if (step.atMostOne && n > 1) throw new Error(`That would change ${n} rows, not one. Nothing was changed.`) +} + /** * @param {string} uri * @returns {Promise} @@ -59,6 +134,12 @@ export async function openPostgres(uri) { for (const oid of [1082, 1114, 1184, 1083, 1266]) pg.types.setTypeParser(oid, (v) => v) const pool = new pg.Pool({ connectionString: uri, max: 4, connectionTimeoutMillis: 15_000 }) await (await pool.connect()).release() + const sql = dialect({ + q: dq, + ph: (i) => `$${i}`, + from: (s, t) => `${dq(s)}.${dq(t)}`, + emptyInsert: (from) => `INSERT INTO ${from} DEFAULT VALUES`, + }) /** @param {string} text @param {unknown[]} [values] */ const arr = async (text, values) => { @@ -71,6 +152,44 @@ export async function openPostgres(uri) { command: last.command ?? '', } } + /** @param {Step[]} steps */ + const tx = async (steps) => { + const c = await pool.connect() + let total = 0 + try { + await c.query('BEGIN') + for (const s of steps) { + const r = await c.query(s.sql, s.params) + checkOne(r.rowCount ?? 0, s) + total += r.rowCount ?? 0 + } + await c.query('COMMIT') + return { rowCount: total } + } catch (e) { + await c.query('ROLLBACK').catch(() => {}) + throw e + } finally { + c.release() + } + } + + /** @param {string} schema @param {string} table */ + const columns = async (schema, table) => { + const r = await pool.query( + `select a.attname as name, format_type(a.atttypid, a.atttypmod) as type, not a.attnotnull as nullable, + coalesce(a.attnum = any(i.indkey), false) as "primaryKey", + pg_get_expr(d.adbin, d.adrelid) as default + from pg_attribute a + join pg_class c on c.oid = a.attrelid + join pg_namespace n on n.oid = c.relnamespace + left join pg_index i on i.indrelid = c.oid and i.indisprimary + left join pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum + where n.nspname = $1 and c.relname = $2 and a.attnum > 0 and not a.attisdropped + order by a.attnum`, + [schema, table], + ) + return r.rows + } return { engine: 'postgres', @@ -81,42 +200,55 @@ export async function openPostgres(uri) { }, async tables() { const r = await pool.query(` - select table_schema as schema, table_name as name, - case when table_type = 'VIEW' then 'view' else 'table' end as kind - from information_schema.tables - where table_schema not in ('pg_catalog', 'information_schema') and table_schema not like 'pg_toast%' and table_schema not like 'pg_temp%' - union all - select schemaname, matviewname, 'view' from pg_matviews + select n.nspname as schema, c.relname as name, + case when c.relkind in ('v', 'm') then 'view' else 'table' end as kind, + case when c.relkind in ('r', 'p') then coalesce(nullif(c.reltuples, -1)::bigint, st.n_live_tup) end as rows + from pg_class c join pg_namespace n on n.oid = c.relnamespace + left join pg_stat_user_tables st on st.relid = c.oid + where c.relkind in ('r', 'p', 'v', 'm', 'f') + and n.nspname not in ('pg_catalog', 'information_schema') and n.nspname not like 'pg_toast%' and n.nspname not like 'pg_temp%' + and not c.relispartition order by 1, 2`) - return r.rows + return r.rows.map((t) => ({ ...t, rows: t.rows == null ? null : Number(t.rows) })) }, - async columns(schema, table) { - const r = await pool.query( - `select a.attname as name, format_type(a.atttypid, a.atttypmod) as type, not a.attnotnull as nullable, - coalesce(a.attnum = any(i.indkey), false) as "primaryKey" - from pg_attribute a - join pg_class c on c.oid = a.attrelid - join pg_namespace n on n.oid = c.relnamespace - left join pg_index i on i.indrelid = c.oid and i.indisprimary - where n.nspname = $1 and c.relname = $2 and a.attnum > 0 and not a.attisdropped - order by a.attnum`, + columns, + async structure(schema, table) { + const idx = await pool.query( + `select i.relname as name, ix.indisunique as unique, ix.indisprimary as primary, + array(select a.attname from unnest(ix.indkey) with ordinality k(n, o) join pg_attribute a on a.attrelid = t.oid and a.attnum = k.n order by k.o)::text[] as columns + from pg_index ix join pg_class t on t.oid = ix.indrelid join pg_class i on i.oid = ix.indexrelid join pg_namespace n on n.oid = t.relnamespace + where n.nspname = $1 and t.relname = $2 order by ix.indisprimary desc, i.relname`, [schema, table], ) - return r.rows - }, - async rows({ schema, table, limit, offset, sort }) { - const from = `${pgId(schema)}.${pgId(table)}` - const page = await arr(`select * from ${from}${orderBy(sort, pgId)} limit $1 offset $2`, [clampInt(limit, 5000), clampInt(offset, 1e12)]) - const est = await pool.query( - `select c.reltuples::bigint as n from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = $1 and c.relname = $2`, + const fks = await pool.query( + `select con.conname as name, rn.nspname as "refSchema", rt.relname as "refTable", + array(select a.attname from unnest(con.conkey) with ordinality k(n, o) join pg_attribute a on a.attrelid = con.conrelid and a.attnum = k.n order by k.o)::text[] as columns, + array(select a.attname from unnest(con.confkey) with ordinality k(n, o) join pg_attribute a on a.attrelid = con.confrelid and a.attnum = k.n order by k.o)::text[] as "refColumns" + from pg_constraint con join pg_class t on t.oid = con.conrelid join pg_namespace n on n.oid = t.relnamespace + join pg_class rt on rt.oid = con.confrelid join pg_namespace rn on rn.oid = rt.relnamespace + where con.contype = 'f' and n.nspname = $1 and t.relname = $2 order by con.conname`, [schema, table], ) - const guess = Number(est.rows[0]?.n ?? -1) - if (guess > EXACT_COUNT_MAX) return { ...page, total: guess, estimated: true } - const exact = await pool.query(`select count(*)::bigint as n from ${from}`) + return { columns: await columns(schema, table), indexes: idx.rows, foreignKeys: fks.rows } + }, + async rows(o) { + const q = sql.page(o) + const page = await arr(q.sql) + if (!o.where?.trim()) { + const est = await pool.query( + `select c.reltuples::bigint as n from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = $1 and c.relname = $2`, + [o.schema, o.table], + ) + const guess = Number(est.rows[0]?.n ?? -1) + if (guess > EXACT_COUNT_MAX) return { ...page, total: guess, estimated: true } + } + const exact = await pool.query(q.count) return { ...page, total: Number(exact.rows[0].n), estimated: false } }, - query: (sql) => arr(sql), + update: async (o) => tx([sql.update(o.schema, o.table, o.key, o.set)]), + insert: async (o) => tx([sql.insert(o.schema, o.table, o.values)]), + remove: async (o) => tx(o.keys.map((k) => sql.remove(o.schema, o.table, k))), + query: (text) => arr(text), close: () => pool.end(), } } @@ -129,13 +261,19 @@ export async function openMysql(uri) { const mysql = await import('mysql2/promise') const pool = mysql.createPool({ uri: uri.replace(/^(mariadb|mysql2):/i, 'mysql:'), connectionLimit: 4, dateStrings: true, supportBigNumbers: true, bigNumberStrings: true, connectTimeout: 15_000 }) await (await pool.getConnection()).release() + const sql = dialect({ + q: bq, + ph: () => '?', + from: (s, t) => `${bq(s)}.${bq(t)}`, + emptyInsert: (from) => `INSERT INTO ${from} () VALUES ()`, + }) - /** @param {string} sql @param {unknown[]} [values] */ - const arr = async (sql, values) => { - const [rows, fields] = await pool.query({ sql, values, rowsAsArray: true }) + /** @param {string} text @param {unknown[]} [values] */ + const arr = async (text, values) => { + const [rows, fields] = await pool.query({ sql: text, values, rowsAsArray: true }) if (!Array.isArray(rows)) { const h = /** @type {{ affectedRows?: number }} */ (rows) - return { columns: [], rows: [], rowCount: h.affectedRows ?? null, command: sql.trim().split(/\s+/)[0].toUpperCase() } + return { columns: [], rows: [], rowCount: h.affectedRows ?? null, command: text.trim().split(/\s+/)[0].toUpperCase() } } return { columns: (fields ?? []).map((f) => f.name), @@ -144,6 +282,35 @@ export async function openMysql(uri) { command: 'SELECT', } } + /** @param {Step[]} steps */ + const tx = async (steps) => { + const c = await pool.getConnection() + let total = 0 + try { + await c.beginTransaction() + for (const s of steps) { + const [r] = /** @type {any} */ (await c.query(s.sql, s.params)) + checkOne(r.affectedRows ?? 0, s) + total += r.affectedRows ?? 0 + } + await c.commit() + return { rowCount: total } + } catch (e) { + await c.rollback().catch(() => {}) + throw e + } finally { + c.release() + } + } + /** @param {string} schema @param {string} table */ + const columns = async (schema, table) => { + const [r] = /** @type {any} */ (await pool.query( + `select column_name as name, column_type as type, is_nullable = 'YES' as nullable, column_key = 'PRI' as primaryKey, column_default as \`default\` + from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position`, + [schema, table], + )) + return r.map((/** @type {any} */ c) => ({ ...c, nullable: !!c.nullable, primaryKey: !!c.primaryKey, default: c.default === 'NULL' ? null : c.default })) + } return { engine: 'mysql', @@ -154,35 +321,54 @@ export async function openMysql(uri) { }, async tables() { const [r] = /** @type {any} */ (await pool.query( - `select table_schema as \`schema\`, table_name as name, if(table_type = 'VIEW', 'view', 'table') as kind + `select table_schema as \`schema\`, table_name as name, if(table_type = 'VIEW', 'view', 'table') as kind, table_rows as \`rows\` from information_schema.tables where table_schema = coalesce(database(), table_schema) and table_schema not in ('mysql', 'information_schema', 'performance_schema', 'sys') order by 1, 2`, )) - return r + return r.map((/** @type {any} */ t) => ({ ...t, rows: t.rows == null ? null : Number(t.rows) })) }, - async columns(schema, table) { - const [r] = /** @type {any} */ (await pool.query( - `select column_name as name, column_type as type, is_nullable = 'YES' as nullable, column_key = 'PRI' as primaryKey - from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position`, + columns, + async structure(schema, table) { + const [idx] = /** @type {any} */ (await pool.query( + `select index_name as name, non_unique = 0 as \`unique\`, index_name = 'PRIMARY' as \`primary\`, group_concat(column_name order by seq_in_index separator '\\n') as cols + from information_schema.statistics where table_schema = ? and table_name = ? group by index_name, non_unique order by \`primary\` desc, name`, [schema, table], )) - return r.map((/** @type {any} */ c) => ({ ...c, nullable: !!c.nullable, primaryKey: !!c.primaryKey })) - }, - async rows({ schema, table, limit, offset, sort }) { - const from = `${myId(schema)}.${myId(table)}` - const page = await arr(`select * from ${from}${orderBy(sort, myId)} limit ? offset ?`, [clampInt(limit, 5000), clampInt(offset, 1e12)]) - const [est] = /** @type {any} */ (await pool.query( - 'select table_rows as n from information_schema.tables where table_schema = ? and table_name = ?', + const [fks] = /** @type {any} */ (await pool.query( + `select constraint_name as name, referenced_table_schema as refSchema, referenced_table_name as refTable, + group_concat(column_name order by ordinal_position separator '\\n') as cols, + group_concat(referenced_column_name order by ordinal_position separator '\\n') as refCols + from information_schema.key_column_usage + where table_schema = ? and table_name = ? and referenced_table_name is not null + group by constraint_name, referenced_table_schema, referenced_table_name order by name`, [schema, table], )) - const guess = Number(est[0]?.n ?? -1) - if (guess > EXACT_COUNT_MAX) return { ...page, total: guess, estimated: true } - const [exact] = /** @type {any} */ (await pool.query(`select count(*) as n from ${from}`)) + return { + columns: await columns(schema, table), + indexes: idx.map((/** @type {any} */ i) => ({ name: i.name, columns: String(i.cols).split('\n'), unique: !!i.unique, primary: !!i.primary })), + foreignKeys: fks.map((/** @type {any} */ f) => ({ name: f.name, refSchema: f.refSchema, refTable: f.refTable, columns: String(f.cols).split('\n'), refColumns: String(f.refCols).split('\n') })), + } + }, + async rows(o) { + const q = sql.page(o) + const page = await arr(q.sql) + if (!o.where?.trim()) { + const [est] = /** @type {any} */ (await pool.query( + 'select table_rows as n from information_schema.tables where table_schema = ? and table_name = ?', + [o.schema, o.table], + )) + const guess = Number(est[0]?.n ?? -1) + if (guess > EXACT_COUNT_MAX) return { ...page, total: guess, estimated: true } + } + const [exact] = /** @type {any} */ (await pool.query(q.count)) return { ...page, total: Number(exact[0].n), estimated: false } }, - query: (sql) => arr(sql), + update: async (o) => tx([sql.update(o.schema, o.table, o.key, o.set)]), + insert: async (o) => tx([sql.insert(o.schema, o.table, o.values)]), + remove: async (o) => tx(o.keys.map((k) => sql.remove(o.schema, o.table, k))), + query: (text) => arr(text), close: () => pool.end(), } } @@ -200,27 +386,45 @@ export async function openSqlite(file) { throw new Error(`SQLite needs Node 22.5 or newer (this is ${process.version}). Or open the file in the Stroke app.`) } const db = new sqlite.DatabaseSync(file) + // One schema per file; the page still sends "main". + const sql = dialect({ q: dq, ph: () => '?', from: (_s, t) => dq(t), emptyInsert: (from) => `INSERT INTO ${from} DEFAULT VALUES` }) + /** @param {unknown} v */ + const bind = (v) => (typeof v === 'boolean' ? Number(v) : v) - /** @param {string} sql @param {unknown[]} [params] */ - const arr = (sql, params = []) => { - const stmt = db.prepare(sql) + /** @param {string} text @param {unknown[]} [params] */ + const arr = (text, params = []) => { + const stmt = db.prepare(text) const cols = typeof stmt.columns === 'function' ? stmt.columns().map((c) => c.name) : null - const returnsRows = cols ? cols.length > 0 : /^\s*(select|with|pragma|explain|values)\b/i.test(sql) + const returnsRows = cols ? cols.length > 0 : /^\s*(select|with|pragma|explain|values)\b/i.test(text) if (!returnsRows) { - const r = stmt.run(.../** @type {any[]} */ (params)) - return { columns: [], rows: [], rowCount: Number(r.changes), command: sql.trim().split(/\s+/)[0].toUpperCase() } + const r = stmt.run(.../** @type {any[]} */ (params.map(bind))) + return { columns: [], rows: [], rowCount: Number(r.changes), command: text.trim().split(/\s+/)[0].toUpperCase() } } - const objs = /** @type {Record[]} */ (stmt.all(.../** @type {any[]} */ (params))) + const objs = /** @type {Record[]} */ (stmt.all(.../** @type {any[]} */ (params.map(bind)))) const columns = cols ?? Object.keys(objs[0] ?? {}) return { columns, rows: objs.map((o) => columns.map((c) => cell(o[c]))), rowCount: objs.length, command: 'SELECT' } } - /** @param {string} sql */ - const multi = (sql) => { - // node:sqlite prepares one statement at a time; run all but the last with - // exec and return the last one's rows, like the other consoles do. - const parts = splitStatements(sql) - if (parts.length > 1) db.exec(parts.slice(0, -1).join(';\n')) - return arr(parts[parts.length - 1] ?? sql) + /** @param {Step[]} steps */ + const tx = async (steps) => { + let total = 0 + db.exec('BEGIN') + try { + for (const s of steps) { + const n = Number(db.prepare(s.sql).run(.../** @type {any[]} */ (s.params.map(bind))).changes) + checkOne(n, s) + total += n + } + db.exec('COMMIT') + return { rowCount: total } + } catch (e) { + try { db.exec('ROLLBACK') } catch { /* already ended */ } + throw e + } + } + /** @param {string} _schema @param {string} table */ + const columns = async (_schema, table) => { + const r = db.prepare('select name, type, "notnull" as nn, pk, dflt_value as dflt from pragma_table_info(?)').all(table) + return r.map((c) => ({ name: String(c.name), type: String(c.type || ''), nullable: !c.nn, primaryKey: Number(c.pk) > 0, default: c.dflt == null ? null : String(c.dflt) })) } return { @@ -231,19 +435,50 @@ export async function openSqlite(file) { }, async tables() { const r = db.prepare(`select name, type from sqlite_schema where type in ('table', 'view') and name not like 'sqlite_%' order by name`).all() - return r.map((t) => ({ schema: 'main', name: String(t.name), kind: t.type === 'view' ? 'view' : 'table' })) + return r.map((t) => { + const kind = t.type === 'view' ? 'view' : 'table' + let rows = null + if (kind === 'table') { + try { rows = Number(/** @type {any} */ (db.prepare(`select count(*) as n from ${dq(String(t.name))}`).get()).n) } catch { /* virtual table */ } + } + return { schema: 'main', name: String(t.name), kind, rows } + }) }, - async columns(_schema, table) { - const r = db.prepare('select name, type, "notnull" as nn, pk from pragma_table_info(?)').all(table) - return r.map((c) => ({ name: String(c.name), type: String(c.type || ''), nullable: !c.nn, primaryKey: Number(c.pk) > 0 })) + columns, + async structure(schema, table) { + const list = db.prepare('select name, "unique" as u, origin from pragma_index_list(?)').all(table) + const indexes = list.map((i) => ({ + name: String(i.name), + unique: !!i.u, + primary: i.origin === 'pk', + columns: db.prepare('select name from pragma_index_info(?) order by seqno').all(String(i.name)).map((c) => String(c.name)), + })) + /** @type {Map} */ + const byId = new Map() + for (const f of db.prepare('select id, "table" as t, "from" as f, "to" as c from pragma_foreign_key_list(?) order by id, seq').all(table)) { + const id = Number(f.id) + const fk = byId.get(id) ?? { name: `fk_${id}`, refSchema: 'main', refTable: String(f.t), columns: [], refColumns: [] } + fk.columns.push(String(f.f)) + fk.refColumns.push(f.c == null ? '' : String(f.c)) + byId.set(id, fk) + } + return { columns: await columns(schema, table), indexes, foreignKeys: [...byId.values()] } }, - async rows({ table, limit, offset, sort }) { - const page = arr(`select * from ${pgId(table)}${orderBy(sort, pgId)} limit ? offset ?`, [clampInt(limit, 5000), clampInt(offset, 1e12)]) - const total = Number(/** @type {any} */ (db.prepare(`select count(*) as n from ${pgId(table)}`).get()).n) + async rows(o) { + const q = sql.page(o) + const page = arr(q.sql) + const total = Number(/** @type {any} */ (db.prepare(q.count).get()).n) return { ...page, total, estimated: false } }, - async query(sql) { - return multi(sql) + update: async (o) => tx([sql.update(o.schema, o.table, o.key, o.set)]), + insert: async (o) => tx([sql.insert(o.schema, o.table, o.values)]), + remove: async (o) => tx(o.keys.map((k) => sql.remove(o.schema, o.table, k))), + async query(text) { + // node:sqlite prepares one statement at a time; run all but the last + // with exec and return the last one's rows, like the other consoles do. + const parts = splitStatements(text) + if (parts.length > 1) db.exec(parts.slice(0, -1).join(';\n')) + return arr(parts[parts.length - 1] ?? text) }, async close() { db.close() @@ -253,25 +488,25 @@ export async function openSqlite(file) { /** * Split on `;` outside quotes and comments. Enough for a console; not a parser. - * @param {string} sql + * @param {string} text */ -export function splitStatements(sql) { +export function splitStatements(text) { /** @type {string[]} */ const out = [] let cur = '' - for (let i = 0; i < sql.length; i++) { - const c = sql[i] + for (let i = 0; i < text.length; i++) { + const c = text[i] if (c === "'" || c === '"' || c === '`') { - const end = sql.indexOf(c, i + 1) - const j = end < 0 ? sql.length : end - cur += sql.slice(i, j + 1) + const end = text.indexOf(c, i + 1) + const j = end < 0 ? text.length : end + cur += text.slice(i, j + 1) i = j - } else if (c === '-' && sql[i + 1] === '-') { - const end = sql.indexOf('\n', i) - i = end < 0 ? sql.length : end - 1 - } else if (c === '/' && sql[i + 1] === '*') { - const end = sql.indexOf('*/', i + 2) - i = end < 0 ? sql.length : end + 1 + } else if (c === '-' && text[i + 1] === '-') { + const end = text.indexOf('\n', i) + i = end < 0 ? text.length : end - 1 + } else if (c === '/' && text[i + 1] === '*') { + const end = text.indexOf('*/', i + 2) + i = end < 0 ? text.length : end + 1 } else if (c === ';') { if (cur.trim()) out.push(cur.trim()) cur = '' diff --git a/cli/test/cli.test.js b/cli/test/cli.test.js index a5f2bfc9..2a406857 100644 --- a/cli/test/cli.test.js +++ b/cli/test/cli.test.js @@ -83,7 +83,7 @@ test('sqlite engine and bridge, end to end', async () => { const file = path.join(tmp(), 'app.db') const db = await openSqlite(file) await db.query(`create table users (id integer primary key, name text not null); insert into users (name) values ('ada'), ('bob')`) - assert.deepEqual(await db.tables(), [{ schema: 'main', name: 'users', kind: 'table' }]) + assert.deepEqual(await db.tables(), [{ schema: 'main', name: 'users', kind: 'table', rows: 2 }]) const cols = await db.columns('main', 'users') assert.deepEqual(cols.map((c) => [c.name, c.primaryKey, c.nullable]), [['id', true, true], ['name', false, false]]) @@ -147,3 +147,38 @@ test('studioUrl keeps the token in the fragment', () => { assert.equal(f.get('bridge'), 'http://127.0.0.1:4321') assert.equal(f.get('token'), 'abc') }) + +test('sqlite: structure, where, and edits by primary key', async () => { + const db = await openSqlite(path.join(tmp(), 'edit.db')) + try { + await db.query(`create table teams (id integer primary key, name text); + create table users (id integer primary key, email text not null default 'x', team integer references teams(id)); + create unique index users_email on users(email); + insert into teams (name) values ('core'); + insert into users (email, team) values ('a@x.io', 1), ('b@x.io', 1), ('c@x.io', null)`) + const t = await db.tables() + assert.equal(t.find((x) => x.name === 'users')?.rows, 3) + + const s = await db.structure('main', 'users') + assert.equal(s.columns.find((c) => c.name === 'email')?.default, "'x'") + assert.ok(s.indexes.some((i) => i.name === 'users_email' && i.unique && i.columns[0] === 'email')) + assert.deepEqual(s.foreignKeys.map((f) => [f.columns[0], f.refTable, f.refColumns[0]]), [['team', 'teams', 'id']]) + + // A key that matches more than one row changes nothing. + await assert.rejects(db.update({ schema: 'main', table: 'users', key: { team: 1 }, set: { team: null } }), /2 rows/) + assert.equal((await db.query('select count(*) from users where team = 1')).rows[0][0], 2) + + const filtered = await db.rows({ schema: 'main', table: 'users', limit: 10, offset: 0, where: 'team is not null' }) + assert.equal(filtered.total, 2) + + assert.equal((await db.update({ schema: 'main', table: 'users', key: { id: 2 }, set: { email: 'bob@x.io', team: null } })).rowCount, 1) + assert.equal((await db.insert({ schema: 'main', table: 'users', values: { email: 'd@x.io' } })).rowCount, 1) + assert.equal((await db.remove({ schema: 'main', table: 'users', keys: [{ id: 1 }, { id: 3 }] })).rowCount, 2) + const left = await db.query('select id, email, team from users order by id') + assert.deepEqual(left.rows, [[2, 'bob@x.io', null], [4, 'd@x.io', null]]) + + await assert.rejects(db.update({ schema: 'main', table: 'users', key: {}, set: { email: 'z' } }), /primary key/) + } finally { + await db.close() + } +}) From 43d4629a02a1f84fb4794734000795fc796691d9 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 08:04:44 +0545 Subject: [PATCH 229/317] Labs: fix the crash on disconnect, switch without flicker, report crashes (#262) Closing a set-aside pool from park_connection, resume_connection or close_parked called tokio::spawn. Those are sync commands with no Tokio runtime, so it panicked, and release builds abort on a panic: turning Labs off, editing a connection or disconnecting with databases kept open closed the app. close_in_background now spawns on tauri's runtime, with a test that fails on the old code. Crashes now leave a report: a panic hook writes the message, location, version and platform to the data directory before the abort, and the next launch opens the report dialog prefilled as a crash report. Switching to a database not open yet keeps the current one on screen (its calls still reach its parked pool) and swaps once the new one is connected: no blank layout, no full-screen overlay. The status bar says what is opening. A failed switch puts the previous database back in place. Connecting no longer wipes the row and result caches of tabs kept for other databases, so a resumed grid gets its raw rows back instead of the proxied copy, which was slow to scroll. Tab bar: no database labels. Other databases' tabs are dimmed, each group starts with a divider, and the tooltip names the database. They also show in a single pane, where they were missing. The status bar lists the open databases; click one to switch. Disconnecting with others open closes only this one and moves to the last used. --- src-tauri/src/crash.rs | 112 +++++++++ src-tauri/src/db/connection.rs | 7 +- src-tauri/src/db/parked.rs | 17 ++ src-tauri/src/lib.rs | 5 + src/lib/components/ReportIssueDialog.svelte | 9 +- src/lib/components/StatusBar.svelte | 36 +++ src/lib/components/StudioShell.svelte | 246 +++++++++++++++----- src/lib/components/TabBar.svelte | 11 +- src/lib/crash-report.js | 25 ++ src/lib/crash-report.test.js | 24 ++ 10 files changed, 432 insertions(+), 60 deletions(-) create mode 100644 src-tauri/src/crash.rs create mode 100644 src/lib/crash-report.js create mode 100644 src/lib/crash-report.test.js 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') + }) +}) From f938b3d060acbea11c922fc3432f58245b28080f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:19:56 +0000 Subject: [PATCH 230/317] chore: version 2.16.3 (#262) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dd1197a..63f15f59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.16.3] - 2026-11-16 + +### Changes +- Labs: fix the crash on disconnect, switch without flicker, report crashes (#262) + + ## [2.16.2] - 2026-11-15 ### Changes diff --git a/package.json b/package.json index 08cb0f3b..faa01d1d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.16.2", + "version": "2.16.3", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 2738054c..1defede8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.16.2", + "version": "2.16.3", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 43b8e97e86fdd07f4325dd5d39a0ecd6f988fd48 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 19:52:54 +0545 Subject: [PATCH 231/317] Labs: flat tab bar, one name per database, quiet swap; smaller plan tag (#263) - Tab bar: no divider and no dimming between databases. Tabs keep one order across a switch, and an AI chat tab stays in place instead of vanishing while its database is in the background. The clicked tab lights up at once. - Status bar: the database chip is the one in front; the other open databases follow it once each as plain names (it listed the current one twice, with dots). - The switch turns transitions off for two frames, so tab pills, row highlights and chips don't each fade in their own 100ms. - Plan tag (Pro, Trial, Free): a small flat tag at the label's height instead of the big glossy grained pill. --- src/app.css | 45 ++++++++++-------------- src/lib/components/AccountCard.svelte | 2 +- src/lib/components/SettingsDialog.svelte | 2 +- src/lib/components/SharesPage.svelte | 2 +- src/lib/components/StatusBar.svelte | 28 ++++++--------- src/lib/components/StudioShell.svelte | 32 ++++++++++++----- src/lib/components/TabBar.svelte | 8 ++--- 7 files changed, 58 insertions(+), 61 deletions(-) diff --git a/src/app.css b/src/app.css index 9d470c90..802b2728 100644 --- a/src/app.css +++ b/src/app.css @@ -1291,6 +1291,14 @@ select optgroup { /* The OS preference, unless Settings → Appearance has overridden it to "Full". `data-motion` is absent when the setting is "System", so the media query is the only thing deciding then. */ +/* Labs, switching between open databases: the whole screen swaps at once, so + nothing fades or slides for that frame (StudioShell sets it for two frames). + Without it every tab pill, row highlight and chip ran its own 100ms + transition and the swap read as layers flickering in turn. */ +html[data-swapping] :is(*, *::before, *::after) { + transition: none !important; +} + @media (prefers-reduced-motion: reduce) { html:not([data-motion="full"]) :is(*, *::before, *::after) { animation-duration: 0.01ms !important; @@ -1530,36 +1538,21 @@ pre code, linear-gradient(to bottom, transparent 45%, rgb(0 0 0 / 0.24)); } -/* ── Glossy chip ───────────────────────────────────────────────────────────── - A tinted pill in `--chip` (a colour): a lit top edge, a soft fill that darkens - toward the foot, a hairline ring and the same fine grain as the marks. Used - for plan badges (Pro, Trial). */ +/* ── Plan tag ──────────────────────────────────────────────────────────────── + A small flat tag in `--chip` (a colour): a faint tint and a hairline ring, + nothing more. It sits beside a name or a setting label, so it stays at the + text's own height and never reads as a button. Used for plan badges (Pro, + Trial, Free). */ .chip-gloss { --chip: var(--success); - position: relative; - isolation: isolate; - overflow: hidden; display: inline-flex; align-items: center; - border-radius: 9999px; - color: color-mix(in oklch, var(--chip) 88%, var(--foreground)); - background: linear-gradient(to bottom, color-mix(in oklch, var(--chip) 24%, transparent), color-mix(in oklch, var(--chip) 12%, transparent)); - box-shadow: - inset 0 1px 0 color-mix(in oklch, white 22%, transparent), - inset 0 0 0 1px color-mix(in oklch, var(--chip) 40%, transparent), - 0 1px 2px rgb(0 0 0 / 0.18); -} -.chip-gloss::after { - content: ""; - position: absolute; - inset: 0; - z-index: -1; - pointer-events: none; - border-radius: inherit; - opacity: 0.22; - mix-blend-mode: overlay; - background-image: url("data:image/svg+xml;utf8,"); - background-size: 120px 120px; + border-radius: 0.3125rem; + letter-spacing: 0.01em; + line-height: 1; + color: color-mix(in oklch, var(--chip) 85%, var(--foreground)); + background: color-mix(in oklch, var(--chip) 12%, transparent); + box-shadow: inset 0 0 0 1px color-mix(in oklch, var(--chip) 24%, transparent); } .chip-gloss.chip-warning { --chip: var(--warning); } /* ── Glossy key ────────────────────────────────────────────────────────────── diff --git a/src/lib/components/AccountCard.svelte b/src/lib/components/AccountCard.svelte index 3d7443bc..77d43482 100644 --- a/src/lib/components/AccountCard.svelte +++ b/src/lib/components/AccountCard.svelte @@ -45,7 +45,7 @@ {#snippet planPill()}

{label} - {#if badge}{badge.label}{/if} + {#if badge}{badge.label}{/if}

{desc}

diff --git a/src/lib/components/SharesPage.svelte b/src/lib/components/SharesPage.svelte index 9a99635b..87667f06 100644 --- a/src/lib/components/SharesPage.svelte +++ b/src/lib/components/SharesPage.svelte @@ -239,7 +239,7 @@ {:else} - Pro + Pro {/if}
{/if} diff --git a/src/lib/components/StatusBar.svelte b/src/lib/components/StatusBar.svelte index 8dac8043..519ffbb7 100644 --- a/src/lib/components/StatusBar.svelte +++ b/src/lib/components/StatusBar.svelte @@ -725,30 +725,24 @@
{/if} - + {#if switchingTo} - {@render sep()} - Opening {switchingTo} + {switchingTo} - {:else if openDatabases.length} - {@render sep()} -
- {#each openDatabases as db (db.key)} + {:else if openDatabases.length > 1} +
+ {#each openDatabases.filter((d) => !d.current) as db (db.key)} {/each} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 33d7c06f..e4e2ea5a 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -8627,8 +8627,12 @@ let rowSearch = $state('') async function activateForeignTab(id) { const hit = sessionOfTab(id) if (!hit) return - await handleSwitchDatabase(hit.s.conn, { focusTab: id }) + // The clicked tab lights up now, not when its database is in front. + pressedTab = id + try { await handleSwitchDatabase(hit.s.conn, { focusTab: id }) } finally { pressedTab = '' } } + /** Labs: a tab of another database that was clicked and is being brought forward. */ + let pressedTab = $state('') /** Close a tab of another open database without switching to it. @param {string} id */ function closeForeignTab(id) { @@ -8642,9 +8646,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. 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. + * kept ones, in the order the databases were opened, so no tab moves on a + * switch. They look like any other tab: which database one belongs to is in + * its tooltip and in the status bar (openDatabases). */ const barTabs = $derived.by(() => { void sessionsTick @@ -8660,8 +8664,7 @@ let rowSearch = $state('') for (const k of order) { 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 } + : (_sessions.get(k)?.tabs ?? []).filter((t) => t.kind !== 'welcome' && ($appAiInTab || t.kind !== 'ai')).map((t) => ({ ...t, connLabel: _sessions.get(k)?.label, foreign: true })) out.push(...group) } return out @@ -8805,11 +8808,22 @@ let rowSearch = $state('') _sessions.delete(key) noteSession(key) sessionsTick++ + holdTransitions() await resumeSession(session.conn, session, focusTab) sidebarShowTables() return true } + /** Swap the screen without transitions until two frames after the change (app.css, data-swapping). */ + function holdTransitions() { + const root = document.documentElement + root.setAttribute('data-swapping', '') + clearTimeout(_swapTimer) + _swapTimer = setTimeout(() => requestAnimationFrame(() => requestAnimationFrame(() => root.removeAttribute('data-swapping'))), 0) + } + /** @type {ReturnType | undefined} */ + let _swapTimer + /** * 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. @@ -9976,7 +9990,7 @@ let rowSearch = $state('') {#if tabsInTitle} (tabs.some((t) => t.id === id) ? activateTab(id) : activateForeignTab(id))} onclose={(id) => (tabs.some((t) => t.id === id) ? closeTab(id) : closeForeignTab(id))} oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} @@ -10337,7 +10351,7 @@ let rowSearch = $state('') {#if tabBarVisible && !tabsInTitle} (tabs.some((t) => t.id === id) ? activateTab(id) : activateForeignTab(id))} onclose={(id) => (tabs.some((t) => t.id === id) ? closeTab(id) : closeForeignTab(id))} oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} @@ -10360,7 +10374,7 @@ let rowSearch = $state('') databases show their tabs here too. Split, each pane lists its own. --> t.foreign) ? barTabs : group.tabIds.map((id) => tabsById.get(id)).filter(Boolean)} - activeTabId={group.activeTabId} + activeTabId={pressedTab || group.activeTabId} 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) }} diff --git a/src/lib/components/TabBar.svelte b/src/lib/components/TabBar.svelte index 99ae90ac..9cb091ac 100644 --- a/src/lib/components/TabBar.svelte +++ b/src/lib/components/TabBar.svelte @@ -178,10 +178,6 @@ {@const tabIconName = tabIcon(tab)} {@const active = tab.id === activeTabId} - - {#if tab.groupStart} - - {/if} {#snippet child({ props: ctxProps })} @@ -220,8 +216,8 @@ )} onclick={() => { if (_suppressTabClick) { _suppressTabClick = false; return } onselect(tab.id) }} > - - {tabDisplayTitle(tab)} + + {tabDisplayTitle(tab)} {#if tab.pinned} From d0454a3d3aeda712aafc7e278864e804dbcfdcd6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:08:07 +0000 Subject: [PATCH 232/317] chore: version 2.16.4 (#263) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63f15f59..0d012f80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.16.4] - 2026-11-16 + +### Changes +- Labs: flat tab bar, one name per database, quiet swap; smaller plan tag (#263) + + ## [2.16.3] - 2026-11-16 ### Changes diff --git a/package.json b/package.json index faa01d1d..88985a22 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.16.3", + "version": "2.16.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1defede8..06184bab 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.16.3", + "version": "2.16.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From d1015c682968e0c59e7099b96e94f034da798901 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 19:54:40 +0545 Subject: [PATCH 233/317] Plan badge: a small dark keycap (#264) Pro, Trial and Free read as a keycap like the workspace mark: a body a shade off the page, a hairline ring, a lit top edge, bold light text. Trial keeps amber text, Free muted. --- src/app.css | 27 +++++++++++++++--------- src/lib/components/AccountCard.svelte | 2 +- src/lib/components/SettingsDialog.svelte | 2 +- src/lib/components/SharesPage.svelte | 2 +- 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/app.css b/src/app.css index 802b2728..4d12f802 100644 --- a/src/app.css +++ b/src/app.css @@ -1538,21 +1538,28 @@ pre code, linear-gradient(to bottom, transparent 45%, rgb(0 0 0 / 0.24)); } -/* ── Plan tag ──────────────────────────────────────────────────────────────── - A small flat tag in `--chip` (a colour): a faint tint and a hairline ring, - nothing more. It sits beside a name or a setting label, so it stays at the - text's own height and never reads as a button. Used for plan badges (Pro, - Trial, Free). */ +/* ── Plan key ──────────────────────────────────────────────────────────────── + A small dark keycap: a body a shade off the page, a hairline ring, a lit top + edge and a shade at the foot, bold light text. Plan badges (Pro, Trial, + Free); `--chip` only tints the text, so Pro reads plain and Trial amber. */ .chip-gloss { - --chip: var(--success); + --chip: var(--foreground); display: inline-flex; align-items: center; border-radius: 0.3125rem; - letter-spacing: 0.01em; line-height: 1; - color: color-mix(in oklch, var(--chip) 85%, var(--foreground)); - background: color-mix(in oklch, var(--chip) 12%, transparent); - box-shadow: inset 0 0 0 1px color-mix(in oklch, var(--chip) 24%, transparent); + letter-spacing: 0.01em; + color: color-mix(in oklch, var(--chip) 92%, var(--foreground)); + background: linear-gradient( + to bottom, + color-mix(in oklch, var(--foreground) 11%, var(--background)), + color-mix(in oklch, var(--foreground) 4%, var(--background)) + ); + box-shadow: + inset 0 0 0 1px color-mix(in oklch, var(--foreground) 26%, transparent), + inset 0 1px 0 color-mix(in oklch, white 20%, transparent), + inset 0 -1px 0 rgb(0 0 0 / 0.22), + 0 1px 2px rgb(0 0 0 / 0.3); } .chip-gloss.chip-warning { --chip: var(--warning); } /* ── Glossy key ────────────────────────────────────────────────────────────── diff --git a/src/lib/components/AccountCard.svelte b/src/lib/components/AccountCard.svelte index 77d43482..7ab2fb83 100644 --- a/src/lib/components/AccountCard.svelte +++ b/src/lib/components/AccountCard.svelte @@ -45,7 +45,7 @@ {#snippet planPill()}

{label} - {#if badge}{badge.label}{/if} + {#if badge}{badge.label}{/if}

{desc}

diff --git a/src/lib/components/SharesPage.svelte b/src/lib/components/SharesPage.svelte index 87667f06..f9bad4da 100644 --- a/src/lib/components/SharesPage.svelte +++ b/src/lib/components/SharesPage.svelte @@ -239,7 +239,7 @@ {:else} - Pro + Pro {/if}
{/if} From bdaa881fec7ffcdb385c6d84925d57a2a04f7b07 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:09:53 +0000 Subject: [PATCH 234/317] chore: version 2.16.5 (#264) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d012f80..54b62ec1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.16.5] - 2026-11-16 + +### Changes +- Plan badge: a small dark keycap (#264) + + ## [2.16.4] - 2026-11-16 ### Changes diff --git a/package.json b/package.json index 88985a22..d353cf09 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.16.4", + "version": "2.16.5", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 06184bab..5c32e879 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.16.4", + "version": "2.16.5", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 4806debc01620f53baa3fd65a81e3ae1d2581095 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Mon, 16 Nov 2026 20:52:24 +0545 Subject: [PATCH 235/317] Polish connect page, provider sign-in, tree with several databases (#265) - Connect page: the column is centred in the panel (header, body and footer together); the empty rail says where saved connections will show, at the top. - Provider sign-in: the waiting step is one panel with a live countdown, a ring round the provider mark, Cancel (Cloudflare too, now cancellable in Rust), and the browser fallback in its footer. - Labs, several databases open: in the tree, the other open databases stay expanded with their tables; clicking one switches to it on that table. Disconnect offers Disconnect all, instead of one prompt per database. - Views the AI creates show in the tree: DDL after a SET or a comment counts, and a result that arrives before its SQL re-reads too. - macOS no longer asks for the Downloads folder at launch (the Oracle client search skipped it there). - Windows and Linux: the System font preset pairs the UI font with the bundled JetBrains Mono instead of Consolas. - Esc clears the sidebar filter; Settings forgets its search when closed. - Stage change uses the shared button with a plain shortcut glyph. - Welcome actions: hidden shortcut hints no longer cut "Search" to "Se...". --- src-tauri/src/cloudflare.rs | 16 ++- src-tauri/src/db/oracle.rs | 9 +- src-tauri/src/db/terminal.rs | 8 +- src-tauri/src/providers/mod.rs | 2 +- src/lib/components/AiChat.svelte | 9 +- src/lib/components/CellEditorPanel.svelte | 20 ++- src/lib/components/CloudflareLogin.svelte | 61 +++++--- src/lib/components/ConnectionModal.svelte | 25 ++-- src/lib/components/DisconnectDialog.svelte | 23 +++ src/lib/components/ProviderAuthPanel.svelte | 133 +++++++++++------- src/lib/components/ProviderConnect.svelte | 75 +++++----- .../components/ProviderCreateDatabase.svelte | 2 +- src/lib/components/SettingsDialog.svelte | 6 + src/lib/components/Sidebar.svelte | 15 ++ src/lib/components/SidebarTree.svelte | 69 ++++++++- src/lib/components/StudioShell.svelte | 46 +++++- src/lib/stores/settings.js | 9 +- 17 files changed, 373 insertions(+), 155 deletions(-) diff --git a/src-tauri/src/cloudflare.rs b/src-tauri/src/cloudflare.rs index c8d3e513..4a49d67e 100644 --- a/src-tauri/src/cloudflare.rs +++ b/src-tauri/src/cloudflare.rs @@ -324,12 +324,16 @@ pub async fn cloudflare_start_oauth(app: tauri::AppHandle) -> Result r.map_err(|_| "Authorization timed out - please try again.".to_string())??, + _ = cancelled => return Err("cancelled".to_string()), + }; let token = exchange_code(&code, &verifier, &redirect_uri).await?; diff --git a/src-tauri/src/db/oracle.rs b/src-tauri/src/db/oracle.rs index 42a3ed60..c9c3872f 100644 --- a/src-tauri/src/db/oracle.rs +++ b/src-tauri/src/db/oracle.rs @@ -110,7 +110,14 @@ pub(crate) fn client_dir_candidates(explicit: &str) -> Vec { let mut parents: Vec = Vec::new(); if let Some(home) = dirs_home() { parents.push(home.clone()); - parents.push(home.join("Downloads")); + // Not on macOS: Downloads is a protected folder there, and listing it + // (even just to look for an `instantclient_*`) makes macOS ask whether + // Stroke may read your Downloads, at launch, for a client most people + // never use. Unzipped there, it is found once its path is set in the + // connection or STROKE_ORACLE_CLIENT_DIR. + if !cfg!(target_os = "macos") { + parents.push(home.join("Downloads")); + } parents.push(home.join("oracle")); } if cfg!(target_os = "windows") { diff --git a/src-tauri/src/db/terminal.rs b/src-tauri/src/db/terminal.rs index a947c8a2..8ffe6e02 100644 --- a/src-tauri/src/db/terminal.rs +++ b/src-tauri/src/db/terminal.rs @@ -310,7 +310,13 @@ fn install_dirs() -> Vec { // and SQLcl unzipped next to it. out.extend(super::oracle::client_dir_candidates("")); if let Some(home) = home_dir() { - for parent in [home.clone(), home.join("Downloads"), home.join("oracle")] { + // Downloads only off macOS: touching it there raises the "would like + // to access files in your Downloads folder" prompt (see oracle.rs). + let mut parents = vec![home.clone(), home.join("oracle")]; + if !cfg!(target_os = "macos") { + parents.push(home.join("Downloads")); + } + for parent in parents { out.push(parent.join("sqlcl").join("bin")); } } diff --git a/src-tauri/src/providers/mod.rs b/src-tauri/src/providers/mod.rs index f4bdcf65..17b8cf77 100644 --- a/src-tauri/src/providers/mod.rs +++ b/src-tauri/src/providers/mod.rs @@ -57,7 +57,7 @@ const TOKEN_PROXY: &str = "https://stroke.click/api/oauth/token"; // drops the callback listener future, which frees the localhost port instead of // holding it until the 5-minute timeout. static OAUTH_CANCEL: OnceLock = OnceLock::new(); -fn oauth_cancel() -> &'static tokio::sync::Notify { +pub(crate) fn oauth_cancel() -> &'static tokio::sync::Notify { OAUTH_CANCEL.get_or_init(tokio::sync::Notify::new) } diff --git a/src/lib/components/AiChat.svelte b/src/lib/components/AiChat.svelte index 09b18e48..e3c8caff 100644 --- a/src/lib/components/AiChat.svelte +++ b/src/lib/components/AiChat.svelte @@ -302,7 +302,10 @@ } = $props(); /** A statement that changes the schema, so the sidebar must reload. @param {string} sql */ - const isDdl = (sql) => /^\s*(?:--[^\n]*\n\s*)*(create|alter|drop|rename|truncate|comment\s+on)\b/i.test(sql ?? "") || /;\s*(create|alter|drop|rename|truncate)\b/i.test(sql ?? ""); + // A statement that changes the catalog, wherever it sits in the batch: at the + // start, after a `;`, or after a `--` or `/* */` comment (an agent often opens + // with `SET search_path ...;` or a comment line before its CREATE VIEW). + const isDdl = (sql) => /(?:^|;|\*\/|\n)\s*(?:--[^\n]*\n\s*)*(create|alter|drop|rename|truncate|comment\s+on)\b/i.test(sql ?? ""); $effect(() => { if (isActive) { @@ -2886,7 +2889,9 @@ : s, ), })); - if (t.name === "execute_sql" && !res.is_error && isDdl(t.detail)) onschemadirty(); + // An empty detail means the result beat the call's full input here: the + // SQL is unknown, so the sidebar re-reads rather than miss a CREATE VIEW. + if (t.name === "execute_sql" && !res.is_error && (!t.detail || isDdl(t.detail))) onschemadirty(); const parsed = t.name === "execute_sql" && !res.is_error ? parseSqlResult(out) : null; // Rows still get their table; a failure is already shown in the fold. if (parsed && parsed.total > 0) { diff --git a/src/lib/components/CellEditorPanel.svelte b/src/lib/components/CellEditorPanel.svelte index 4c5a140a..487f02fa 100644 --- a/src/lib/components/CellEditorPanel.svelte +++ b/src/lib/components/CellEditorPanel.svelte @@ -50,7 +50,9 @@ import X from '@lucide/svelte/icons/x' import { cn } from '$lib/utils.js' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' - import Kbd from './Kbd.svelte' + import { detectOs } from '$lib/platform.js' + /** The stage shortcut as one glyph run: ⌘↵ on a Mac, Ctrl↵ elsewhere. */ + const modEnter = detectOs() === 'macos' ? '⌘↵' : 'Ctrl ↵' let { open = $bindable(false), @@ -677,16 +679,20 @@ > - + + {/if} + {/snippet} + {#snippet footer()} + {#if authUrl} + Browser didn't open? + + + {linkCopied ? 'Link copied' : ''} + {:else} +
@@ -3705,7 +3705,7 @@
{#if step === "pick"} - + -
+
-
+
-
+
- +
+
+
+
+ {#if mark}{@render mark()}{:else}{/if} +
+ {#if progress} + + {/if} - {#if mark}{@render mark()}{:else}{/if}
-
+

{title}

{#if subtitle} - -

- {subtitle} -

+

{subtitle}

{/if} - {#if hint} -

{hint}

+ {#if timeout || hint} +

+ {#if timeout} + 0 && left <= 60 && 'text-warning')} aria-live="off"> + {left > 0 ? `${clock} left` : 'Timing out'} + + {/if} + {#if timeout && hint}{/if} + {#if hint}{hint}{/if} +

{/if}
@@ -67,28 +105,17 @@ {/if}
-
- {#if progress} - - {/if} -
+ {#if footer} +
+ {@render footer()} +
+ {/if}
diff --git a/src/lib/components/ProviderConnect.svelte b/src/lib/components/ProviderConnect.svelte index 591a6b27..3c509ed6 100644 --- a/src/lib/components/ProviderConnect.svelte +++ b/src/lib/components/ProviderConnect.svelte @@ -9,7 +9,6 @@ import AlertTriangle from '@lucide/svelte/icons/alert-triangle' import RefreshCw from '@lucide/svelte/icons/refresh-cw' import ArrowRight from '@lucide/svelte/icons/arrow-right' - import X from '@lucide/svelte/icons/x' import Plus from '@lucide/svelte/icons/plus' import ExternalLink from '@lucide/svelte/icons/external-link' import DbIcon from './DbIcon.svelte' @@ -598,7 +597,7 @@ subtitle={meta?.token?.help ?? `Paste your ${meta?.name} credentials.`} hint="Stored in this machine's keychain" > - {#snippet mark()}{/snippet} + {#snippet mark()}{/snippet} {#snippet action()} {#if meta?.token?.helpUrl} + + {/snippet} + {#snippet footer()} + {#if deviceCode} + {deviceCode.userCode} + + + {codeCopied ? 'Code copied' : ''} + {:else if authUrl} + Browser didn't open? + + + {linkCopied ? 'Link copied' : ''} + {:else} +
- {#if runTables.length} + {#if showLog} + {@render logPanel()} + {:else if runTables.length}
    {#each runTables as t (t.key)}
  • @@ -854,6 +947,7 @@ {:else}Restore complete{/if}

    + {@render logToggle()} {fmtElapsed(importElapsed)}
{@render progressBar( @@ -890,7 +984,9 @@ {/if}
- {#if importResult?.errors.length} + {#if showLog} + {@render logPanel()} + {:else if importResult?.errors.length}
diff --git a/src/lib/components/ErdCanvas.svelte b/src/lib/components/ErdCanvas.svelte index 890dc642..2d7f2416 100644 --- a/src/lib/components/ErdCanvas.svelte +++ b/src/lib/components/ErdCanvas.svelte @@ -1553,6 +1553,7 @@ e.preventDefault()} onpointerdown={onPointerDown} onpointermove={onPointerMove} onpointerup={onPointerUp} diff --git a/src/lib/components/ErdHierarchy.svelte b/src/lib/components/ErdHierarchy.svelte index d697b08e..d00a395e 100644 --- a/src/lib/components/ErdHierarchy.svelte +++ b/src/lib/components/ErdHierarchy.svelte @@ -420,6 +420,7 @@ role="group" aria-label="Tables in foreign-key order" data-zoom-surface + ondragstart={(e) => e.preventDefault()} onpointerdown={onPointerDown} onpointermove={onPointerMove} onpointerup={onPointerUp} diff --git a/src/lib/components/MermaidViewer.svelte b/src/lib/components/MermaidViewer.svelte index ea81c49e..b4dd1fee 100644 --- a/src/lib/components/MermaidViewer.svelte +++ b/src/lib/components/MermaidViewer.svelte @@ -281,20 +281,18 @@ if (!dragging) return dragging = false node.style.cursor = 'grab' - // Back to painted in place, so the next zoom is drawn, not stretched. - svg.style.willChange = '' window.removeEventListener('mousemove', onMove) window.removeEventListener('mouseup', onUp) } const onDown = (/** @type {MouseEvent} */ e) => { if (e.button !== 0) return + // Without this WebKit starts a native drag of the SVG's text and + // draws a translucent copy under the cursor: the "double" diagram. + e.preventDefault() dragging = true ox = e.clientX - tx; oy = e.clientY - ty node.style.cursor = 'grabbing' - // Its own layer for the drag only: a pan then moves a painted layer - // instead of repainting every glyph per frame. - svg.style.willChange = 'transform' window.addEventListener('mousemove', onMove) window.addEventListener('mouseup', onUp) } @@ -442,6 +440,6 @@
diff --git a/src/lib/components/Sidebar.svelte b/src/lib/components/Sidebar.svelte index 3772c0fa..d1be831a 100644 --- a/src/lib/components/Sidebar.svelte +++ b/src/lib/components/Sidebar.svelte @@ -3232,11 +3232,11 @@ title={updateState === 'ready' ? 'The update is downloaded. Restart to install it.' : 'A new version of Stroke is available'} onclick={oncheckupdates} > - + {updateState === 'ready' ? 'Restart' : 'Update'} {:else} - + {/if}
diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index db549101..cb5c5d6b 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -10660,7 +10660,7 @@ let rowSearch = $state('') > {#await import('./BackupPage.svelte')}{:then { default: BackupPage }} - ({ name: t.name, rowCount: t.rowCount }))} /> + ({ name: t.name, rowCount: t.rowCount }))} onrestored={async () => { await loadSchemas(); await loadTables({ force: true }); bumpObjects() }} /> {/await}
diff --git a/src/lib/sql-write.js b/src/lib/sql-write.js index ee280b6f..07c886ce 100644 --- a/src/lib/sql-write.js +++ b/src/lib/sql-write.js @@ -378,6 +378,9 @@ export function sqlRunEffects(sql) { /** MongoDB shell calls that change data, indexes or the database. */ const MONGO_WRITE_RE = /\.\s*(insert|insertOne|insertMany|update|updateOne|updateMany|replaceOne|remove|deleteOne|deleteMany|bulkWrite|drop|dropDatabase|dropIndex|dropIndexes|createIndex|createIndexes|createCollection|renameCollection|findOneAndUpdate|findOneAndReplace|findOneAndDelete|findAndModify)\s*\(/ +/** DynamoDB API calls that change items or tables (JSON or `Op {...}` form). */ +const DYNAMO_WRITE_RE = /(^|"operation"\s*:\s*")(PutItem|UpdateItem|DeleteItem|BatchWriteItem|TransactWriteItems|CreateTable|UpdateTable|DeleteTable|UpdateTimeToLive)\b/m + /** Firestore and CouchDB shell-style writes. */ const DOC_WRITE_RE = /\.\s*(add|set|update|delete|insert|put|remove|bulkDocs|destroy|create)\s*\(/ @@ -422,6 +425,8 @@ export function isWriteFor(sql, engine) { case 'elasticsearch': case 'opensearch': return isEsWrite(text) + case 'dynamodb': + return DYNAMO_WRITE_RE.test(text) default: return false } From c948bd557d6f6a827ca8f0bd7407ad78f702ea45 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:11:56 +0000 Subject: [PATCH 280/317] chore: version 2.18.8 (#287) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac7b6468..c6c2d863 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.18.8] - 2026-11-17 + +### Changes +- AI table commands for DynamoDB and MongoDB, live backup log, fixes (#287) + + ## [2.18.7] - 2026-11-17 ### Changes diff --git a/package.json b/package.json index 3d2a42d0..958f9bab 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.18.7", + "version": "2.18.8", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 7da545de..f3d0da23 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.18.7", + "version": "2.18.8", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From c618a41ffb29742ca460d31b601ccd6052698a50 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Tue, 17 Nov 2026 22:58:04 +0545 Subject: [PATCH 281/317] Go back to fat LTO for Nightly builds (#288) Thin LTO with 16 codegen units made the Nightly build slower, not faster: 2.18.7 took 44 minutes against the usual 20 to 24. --- .github/workflows/nightly.yml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 0ecd3e58..f0689f35 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -160,13 +160,6 @@ jobs: shell: bash run: npx tauri build --config nightly.conf.json ${{ matrix.args }} env: - # Nightly trades a little binary size and speed for build time. The - # release profile's fat LTO with one codegen unit re-optimizes the - # whole dependency graph on one thread every build (~9 of the ~11 - # minutes, with every dependency already cached). Thin LTO keeps most - # of the gain and runs in parallel. Stable (release.yml) keeps fat LTO. - CARGO_PROFILE_RELEASE_LTO: thin - CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} NO_STRIP: ${{ matrix.name == 'linux' && '1' || '' }} From b583db9ceb5c7ec011a690a18dcce1abe35c0024 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:13:16 +0000 Subject: [PATCH 282/317] chore: version 2.18.9 (#288) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6c2d863..1ab3ed84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.18.9] - 2026-11-17 + +### Changes +- Go back to fat LTO for Nightly builds (#288) + + ## [2.18.8] - 2026-11-17 ### Changes diff --git a/package.json b/package.json index 958f9bab..c01671c6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.18.8", + "version": "2.18.9", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f3d0da23..43894ac0 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.18.8", + "version": "2.18.9", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From ae84e28a3b665de44996a59d2f8c396d96d07dbe Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 10:59:09 +0545 Subject: [PATCH 283/317] Take Pro from the signed-in account only (#289) Stroke 3 drops license keys and the device trial. Signing in is required, and the account decides: a license bought with the account's email is Pro, every other account gets one fresh v3 trial (X-Stroke-Trial: account-v3), then the free plan. A key from another email can no longer be linked or used. The plan label now reads the same status the Pro gates read, which fixes Account & Sync showing Pro next to a free-trial note. --- src-tauri/src/account.rs | 202 ++------ src-tauri/src/commands.rs | 159 +----- src-tauri/src/lib.rs | 8 - src-tauri/src/license.rs | 505 +------------------ src/App.svelte | 8 +- src/lib/components/AboutDialog.svelte | 100 +--- src/lib/components/AccountCard.svelte | 21 +- src/lib/components/AccountMenu.svelte | 23 +- src/lib/components/AppMenuBar.svelte | 2 +- src/lib/components/CommandPalette.svelte | 2 +- src/lib/components/LicenseActivation.svelte | 223 -------- src/lib/components/LicenseGate.svelte | 46 +- src/lib/components/LicensePage.svelte | 125 +---- src/lib/components/Onboarding.svelte | 6 +- src/lib/components/SignInScreen.svelte | 56 +- src/lib/components/StudioShell.svelte | 10 +- src/lib/components/TitleBar.svelte | 33 -- src/lib/components/TitleBarMenu.svelte | 6 +- src/lib/components/TrialExpiredScreen.svelte | 62 +-- src/lib/i18n.js | 8 +- src/lib/stores/account.js | 65 +-- src/lib/stores/account.test.js | 27 +- src/lib/stores/license.js | 41 +- 23 files changed, 187 insertions(+), 1551 deletions(-) delete mode 100644 src/lib/components/LicenseActivation.svelte diff --git a/src-tauri/src/account.rs b/src-tauri/src/account.rs index 43801fd9..514bd532 100644 --- a/src-tauri/src/account.rs +++ b/src-tauri/src/account.rs @@ -14,9 +14,11 @@ //! until `valid_until`. Every read of the cache re-verifies the signature, so //! editing the file grants nothing. //! -//! Existing customers: an activated `license.json` keeps working with or without -//! an account (see `combine`), and the device trial still applies to anyone who -//! is not signed in. +//! Stroke 3 has no license keys and no device trial: the signed-in account is +//! the only source of Pro. A license bought with the account's email makes it +//! Pro; every other account gets one trial (`X-Stroke-Trial: account-v3`, a +//! fresh one for v3), then the free plan. A `license.json` left by 2.x stays on +//! disk, untouched and unread, so going back to 2.x still works. use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use ed25519_dalek::{Signature, Verifier, VerifyingKey}; @@ -37,8 +39,6 @@ const DEFAULT_BASE: &str = "https://stroke.click"; /// Vault entry holding the desktop session token. const TOKEN_KEY: &str = "__stroke_account_token__"; const CACHE_FILE: &str = "account.json"; -/// Present while a new install still has to sign in (or enter a key). -const ONBOARDING_FILE: &str = ".account-onboarding"; const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(300); /// Base URL of the website/API. `STROKE_API_BASE` overrides it for local dev. @@ -239,12 +239,6 @@ struct CacheFile { /// The `/api/me` body, verbatim. me: String, fetched_at: u64, - /// SHA-256 of the license key already sent to `/api/license/link`. - #[serde(default)] - linked_key_hash: Option, - /// Why linking failed in a way retrying won't fix (`key_owned_elsewhere`). - #[serde(default)] - link_error: Option, /// The device that wrote this cache. A copy taken to another machine is /// ignored there, which has to sign in for itself. #[serde(default)] @@ -315,24 +309,6 @@ pub fn entitlement_status(ent: &Entitlement, email: &str, now: u64) -> LicenseSt LicenseStatus::TrialExpired } -/// Merge the account's verdict into the local (key / device-trial) one. -/// -/// - No fresh account entitlement: the local status, unchanged. -/// - Account grants Pro via a license: that wins. -/// - A valid local `license.json` is never downgraded by the account: Pro. -/// - Otherwise the account decides (its trial, or no Pro), replacing the -/// per-device trial for signed-in users. -pub fn combine(local: LicenseStatus, account: Option) -> LicenseStatus { - match account { - None => local, - Some(acc @ LicenseStatus::Valid { .. }) => acc, - Some(acc) => match local { - LicenseStatus::Valid { .. } => local, - _ => acc, - }, - } -} - /// The account's status from the cache only: no network, no keychain. Used by /// the license commands so existing Pro gates see account entitlements, also /// when stroke.click can't be reached (see `OFFLINE_GRACE_SECS`). @@ -362,64 +338,27 @@ fn local_dev_pro() -> Option { }) } -pub fn apply_account(dir: &Path, local: LicenseStatus) -> LicenseStatus { +/// The license status, from the signed-in account alone. +/// +/// - Signed out, or no usable entitlement: no Pro (the app asks to sign in). +/// - Fresh entitlement, or paid Pro on the offline grace: what it says. +/// - A trial entitlement past its window keeps counting offline until the +/// trial's own signed end, so a trial doesn't stop on a flight. +pub fn license_status(dir: &Path) -> LicenseStatus { if let Some(dev) = local_dev_pro() { return dev; } - if matches!(local, LicenseStatus::Error { .. }) { - return local; - } - // A key bought by another account doesn't make this account Pro: signed - // in as someone else, this device is on the trial (or that account's own - // plan). Signed out, the key works as it always has. - let local = if matches!(local, LicenseStatus::Valid { .. }) && key_owned_by_other_account(dir) { - crate::license::trial_status(dir) - } else { - local - }; - combine(local, account_license_status(dir)) -} - -/// Signed in, and the server said the license key on this device belongs to a -/// different account. Only for the key it said that about: a new key is asked -/// about afresh. -fn key_owned_by_other_account(dir: &Path) -> bool { - let Some(c) = read_cache(dir) else { return false }; - if c.link_error.as_deref() != Some("key_owned_elsewhere") { - return false; - } - if c.device_id.as_deref().is_some_and(|d| d != crate::license::device_id()) { - return false; + if let Some(status) = account_license_status(dir) { + return status; } - let Some(lic) = crate::license::load_license(dir) else { return false }; - c.linked_key_hash.as_deref() == Some(crate::license::key_hash(&lic.key).as_str()) -} - -// ── New-install detection ───────────────────────────────────────────────────── - -/// Record, once per run and before anything writes the trial files, whether -/// this is a brand-new install (no license, no trial ever started). A new -/// install gets a marker that keeps the sign-in screen up across relaunches -/// until the user signs in or enters a key. Existing installs never get one. -pub fn note_install_state(dir: &Path) { - static NOTED: OnceLock<()> = OnceLock::new(); - NOTED.get_or_init(|| { - let fresh = crate::license::load_license(dir).is_none() - && crate::license::local_trial_start(dir).is_none() - && read_cache(dir).is_none(); - if fresh { - let _ = std::fs::create_dir_all(dir); - let _ = std::fs::write(dir.join(ONBOARDING_FILE), b"1"); + if let Some((me, _)) = cached_me(dir) { + let now = crate::license::trusted_now(dir); + let ent = &me.entitlement; + if ent.plan == "pro" && ent.source == "trial" && ent.trial.as_ref().is_some_and(|t| t.ends_at > now) { + return entitlement_status(ent, &me.user.email, now); } - }); -} - -fn onboarding_pending(dir: &Path) -> bool { - dir.join(ONBOARDING_FILE).exists() -} - -fn clear_onboarding(dir: &Path) { - let _ = std::fs::remove_file(dir.join(ONBOARDING_FILE)); + } + LicenseStatus::TrialExpired } // ── HTTP ────────────────────────────────────────────────────────────────────── @@ -537,18 +476,11 @@ async fn me_text(req: reqwest::RequestBuilder) -> Result { resp.text().await.map_err(|e| ApiError::Network(e.to_string())) } -pub async fn fetch_me(base: &str, token: &str) -> Result { - me_text(http().get(format!("{base}/api/me")).bearer_auth(token)).await -} +/// Asks for the v3 account trial: one fresh trial per account, separate from 2.x. +const TRIAL_SCHEME: (&str, &str) = ("X-Stroke-Trial", "account-v3"); -pub async fn link_license(base: &str, token: &str, key: &str) -> Result { - me_text( - http() - .post(format!("{base}/api/license/link")) - .bearer_auth(token) - .json(&serde_json::json!({ "key": key })), - ) - .await +pub async fn fetch_me(base: &str, token: &str) -> Result { + me_text(http().get(format!("{base}/api/me")).bearer_auth(token).header(TRIAL_SCHEME.0, TRIAL_SCHEME.1)).await } pub async fn remote_sign_out(base: &str, token: &str) { @@ -790,21 +722,16 @@ pub struct AccountStatus { pub fetched_at: u64, /// The last refresh couldn't reach the server; showing the cache. pub offline: bool, - /// New install that hasn't signed in or entered a key yet. + /// Not signed in: the app shows the sign-in screen first. pub needs_onboarding: bool, - /// A license.json is present on this device. - pub has_license_key: bool, - pub link_error: Option, pub error: Option, pub manage_url: String, } fn build_status(dir: &Path, signed_in: bool) -> AccountStatus { - let has_license_key = crate::license::load_license(dir).is_some(); let mut s = AccountStatus { signed_in, - has_license_key, - needs_onboarding: !signed_in && !has_license_key && onboarding_pending(dir), + needs_onboarding: !signed_in, manage_url: format!("{}/app", base_url()), ..Default::default() }; @@ -817,23 +744,19 @@ fn build_status(dir: &Path, signed_in: bool) -> AccountStatus { s.entitlement = Some(me.entitlement); s.devices = me.devices; s.fetched_at = c.fetched_at; - s.link_error = c.link_error; } } s } -/// Save a verified `/api/me` reply, keeping the link bookkeeping. +/// Save a verified `/api/me` reply. fn save_me(dir: &Path, raw: String) -> Result { let me = parse_me(&raw)?; - let prev = read_cache(dir).unwrap_or_default(); write_cache( dir, &CacheFile { me: raw, fetched_at: now_secs(), - linked_key_hash: prev.linked_key_hash, - link_error: prev.link_error, device_id: Some(crate::license::device_id()), }, )?; @@ -843,36 +766,6 @@ fn save_me(dir: &Path, raw: String) -> Result { Ok(me) } -/// Link the held license key to the account, once per key. -async fn link_held_key(dir: &Path, base: &str, token: &str) { - let Some(lic) = crate::license::load_license(dir) else { return }; - let hash = crate::license::key_hash(&lic.key); - let Some(cache) = read_cache(dir) else { return }; - if cache.linked_key_hash.as_deref() == Some(hash.as_str()) { - return; - } - let result = link_license(base, token, &lic.key).await; - let mut c = read_cache(dir).unwrap_or(cache); - match result { - Ok(raw) if parse_me(&raw).is_ok() => { - c.me = raw; - c.fetched_at = now_secs(); - c.linked_key_hash = Some(hash); - c.link_error = None; - } - // Retrying won't change these: remember and stop asking. - Err(ApiError::Server(code, _)) - if matches!(code.as_str(), "key_owned_elsewhere" | "not_found" | "invalid_key" | "revoked") => - { - c.linked_key_hash = Some(hash); - c.link_error = Some(code); - } - // Offline, 5xx, a bad reply: try again on the next refresh. - _ => return, - } - let _ = write_cache(dir, &c); -} - fn data_dir(app: &tauri::AppHandle) -> Result { app.path().app_data_dir().map_err(|e| e.to_string()) } @@ -883,10 +776,7 @@ async fn refresh(app: &tauri::AppHandle, dir: &Path, token: &str) -> AccountStat let base = base_url(); match fetch_me(&base, token).await { Ok(raw) => match save_me(dir, raw) { - Ok(_) => { - link_held_key(dir, &base, token).await; - build_status(dir, true) - } + Ok(_) => build_status(dir, true), Err(e) => AccountStatus { error: Some(e), ..build_status(dir, true) }, }, Err(ApiError::Unauthorized) => { @@ -1020,7 +910,6 @@ async fn sign_in_loopback( .await .map_err(|e| e.user_message())?; store_token(app, tok.token.clone()).await?; - clear_onboarding(dir); Ok(refresh(app, dir, &tok.token).await) } @@ -1051,7 +940,6 @@ pub async fn account_paste_code(app: tauri::AppHandle, text: String) -> Result) -> Result { let dir = data_dir(&app)?; - note_install_state(&dir); let token = load_token(&app).await; Ok(match token { Some(t) if refresh.unwrap_or(false) => self::refresh(&app, &dir, &t).await, @@ -1092,13 +979,6 @@ pub async fn account_sign_out(app: tauri::AppHandle) -> Result Result<(), String> { - clear_onboarding(&data_dir(&app)?); - Ok(()) -} - // ── Tests ───────────────────────────────────────────────────────────────────── #[cfg(test)] @@ -1285,23 +1165,6 @@ mod tests { assert!(matches!(entitlement_status(&ent("free", "none", 9e9 as u64), "a", now), LicenseStatus::TrialExpired)); } - #[test] - fn existing_keys_are_never_downgraded() { - let key = LicenseStatus::Valid { email: "k@x".into(), plan: "pro".into(), issued_at: 1, expires_at: None }; - let device_trial = LicenseStatus::Trial { days_remaining: 5 }; - // No account: unchanged. - assert!(matches!(combine(key.clone(), None), LicenseStatus::Valid { .. })); - assert!(matches!(combine(device_trial.clone(), None), LicenseStatus::Trial { days_remaining: 5 })); - // Account says free: the key still grants Pro. - assert!(matches!(combine(key.clone(), Some(LicenseStatus::TrialExpired)), LicenseStatus::Valid { .. })); - assert!(matches!(combine(key, Some(LicenseStatus::Trial { days_remaining: 2 })), LicenseStatus::Valid { .. })); - // Account Pro lifts an expired device trial. - let acc = LicenseStatus::Valid { email: "a".into(), plan: "pro".into(), issued_at: 1, expires_at: None }; - assert!(matches!(combine(LicenseStatus::TrialExpired, Some(acc)), LicenseStatus::Valid { .. })); - // Signed in: the account's trial replaces the device trial. - assert!(matches!(combine(device_trial, Some(LicenseStatus::Trial { days_remaining: 9 })), LicenseStatus::Trial { days_remaining: 9 })); - } - #[test] fn sign_in_params_match_server_rules() { let (_, c) = pkce_pair(); @@ -1338,7 +1201,7 @@ mod tests { .await .unwrap(); assert_eq!(page.status(), 200); - assert!(page.text().await.unwrap().contains("return to Stroke")); + assert!(page.text().await.unwrap().contains("Head back to Stroke")); assert_eq!(waiter.await.unwrap(), Ok("c0de".to_string())); // Cancel from the website. @@ -1399,7 +1262,6 @@ mod tests { let base = mock_server(vec![ ("POST /api/desktop/token", 200, r#"{"token":"tok","user":{"id":"u1","email":"a@b.co","name":"A","image":null}}"#.into()), ("GET /api/me", 200, me.clone()), - ("POST /api/license/link", 409, r#"{"error":"key_owned_elsewhere","message":"Owned by another account"}"#.into()), ]) .await; @@ -1412,10 +1274,6 @@ mod tests { assert!(parse_me_with_key(&raw, &sk.verifying_key()).is_ok()); assert_eq!(fetch_me(&base, "wrong").await, Err(ApiError::Unauthorized)); - assert_eq!( - link_license(&base, "tok", "k").await, - Err(ApiError::Server("key_owned_elsewhere".into(), "Owned by another account".into())) - ); let bad = mock_server(vec![("POST /api/desktop/token", 400, r#"{"error":"expired_code","message":"x"}"#.into())]).await; let e = exchange_code(&bad, "c", "v", "d", "n", "1.0").await.unwrap_err(); diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index a2eeedf5..b9cdbf06 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1856,170 +1856,19 @@ pub fn connections_store_write(app: tauri::AppHandle, json: String) -> Result<() // ── License ─────────────────────────────────────────────────────────────────── -// `async` so the first call (device-fingerprint subprocess + trial-file I/O) -// runs off the main thread instead of blocking the UI during startup. +// `async` so the first call (device fingerprint, cache read) runs off the main +// thread instead of blocking the UI during startup. Pro comes from the +// signed-in account only (see account::license_status). #[tauri::command(async)] pub fn check_license_status(app: tauri::AppHandle) -> crate::license::LicenseStatus { match app.path().app_data_dir() { - Ok(dir) => { - // Before check_status starts a trial, so a new install is told apart. - crate::account::note_install_state(&dir); - crate::account::apply_account(&dir, crate::license::check_status(&dir)) - } + Ok(dir) => crate::account::license_status(&dir), Err(e) => crate::license::LicenseStatus::Error { message: e.to_string(), }, } } -#[tauri::command] -pub async fn activate_license( - app: tauri::AppHandle, - key: String, -) -> Result { - // 1. Verify signature locally (works offline, catches forged keys) - let parsed = crate::license::verify_key(&key)?; - let device_id = crate::license::device_id(); - - // 2. Register with server. Blocks on seat_limit_exceeded / revoked. - // On network failure api_activate returns Ok(None) - we allow offline activation. - match crate::license::api_activate(&key, &device_id, &app.package_info().version.to_string()).await { - Ok(None) => {} // offline - proceed with local-only activation - Ok(Some(_)) => {} // server accepted - Err(e) => { - // Convert server error codes to user-friendly messages - let msg = match e.as_str() { - "seat_limit_exceeded" => "This license is on all the devices it covers. Remove one at stroke.click/app, or ask for more devices there (\"Need more devices?\").", - "revoked" => "This license key has been revoked.", - "expired" => "This license key has expired.", - "not_found" => "License key not found.", - _ => return Err(e), - }; - return Err(msg.to_string()); - } - } - - // 3. Save locally - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - let lic = crate::license::LicenseFile { - version: 1, - key, - email: parsed.email.clone(), - plan: parsed.plan.clone(), - issued_at: parsed.issued_at, - expires_at: parsed.expires_at, - device_id, - activated_at: now, - last_check_at: now, - }; - crate::license::save_license(&dir, &lic)?; - Ok(serde_json::json!({ - "email": parsed.email, - "plan": parsed.plan, - "issued_at": parsed.issued_at, - "expires_at": parsed.expires_at, - })) -} - -#[tauri::command] -pub async fn deactivate_license(app: tauri::AppHandle) -> Result<(), String> { - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - // Best-effort server deactivation (release the seat) - if let Some(lic) = crate::license::load_license(&dir) { - crate::license::api_deactivate(&lic.key, &lic.device_id).await; - } - crate::license::delete_license(&dir) -} - -/// Validates the license against the server on every launch. -/// - valid: true → update last_check_at, return Valid -/// - revoked / expired → delete local license, return Trial/TrialExpired -/// - device_not_activated → re-activate this device, keep the license -/// - any other error or network failure → keep the license (local signature -/// is the grace; the next launch checks again) -/// - no license → local trial check only (no network call) -#[tauri::command] -pub async fn run_license_check( - app: tauri::AppHandle, -) -> crate::license::LicenseStatus { - let dir = match app.path().app_data_dir() { - Ok(d) => d, - Err(e) => return crate::license::LicenseStatus::Error { message: e.to_string() }, - }; - crate::account::note_install_state(&dir); - - if let Some(mut lic) = crate::license::load_license(&dir) { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - - use crate::license::CheckOutcome; - let version = app.package_info().version.to_string(); - let mut ended = false; - match crate::license::api_check(&lic.key, &lic.device_id, &version).await { - Some(CheckOutcome::Valid) => { - lic.last_check_at = now; - let _ = crate::license::save_license(&dir, &lic); - } - Some(CheckOutcome::Ended) => ended = true, - Some(CheckOutcome::NotActivated) => { - // Activated offline, so the server never saw this device (or its - // seat was released). Register it now rather than dropping Pro. - match crate::license::api_activate(&lic.key, &lic.device_id, &version).await { - Ok(Some(_)) => { - lic.last_check_at = now; - let _ = crate::license::save_license(&dir, &lic); - } - Err(e) if e == "revoked" || e == "expired" => ended = true, - // Offline, seat limit, or anything else: keep the key and - // try again on the next check. - _ => {} - } - } - // `not_found`, unknown errors, a bad deploy, or offline: keep the key; - // the local signature is the grace. - Some(CheckOutcome::Unknown) | None => {} - } - if ended { - let _ = crate::license::delete_license(&dir); - } - } - - // No valid paid license → reconcile the trial clock with the server so a - // reinstall/disk-wipe can't grant a fresh trial (server keeps the earliest - // start per device). Silent no-op when offline. - if crate::license::load_license(&dir).is_none() { - crate::license::reconcile_trial(&dir).await; - } - - // A signed-in account's cached, signature-checked entitlement can grant Pro; - // it never takes Pro away from a valid key (see account::combine). - crate::account::apply_account(&dir, crate::license::check_status(&dir)) -} - -// ── License debug helpers (debug builds only) ───────────────────────────────── - -/// Backdate the trial file so the UI shows it as expired (or N days elapsed). -/// Only compiled in debug mode - stripped from release builds entirely. -#[cfg(debug_assertions)] -#[tauri::command] -pub fn debug_set_trial_days_ago(app: tauri::AppHandle, days_ago: u64) -> Result<(), String> { - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - crate::license::debug_set_trial_days_ago(&dir, days_ago) -} - -#[cfg(debug_assertions)] -#[tauri::command] -pub fn debug_reset_trial(app: tauri::AppHandle) -> Result<(), String> { - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - crate::license::debug_reset_trial(&dir) -} - // ── Sample database ──────────────────────────────────────────────────────────── /// Ensures the bundled sample SQLite database exists in the app data directory. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ba20942c..e620ba5a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -902,14 +902,10 @@ pub fn run() { db::terminal::terminal_install_client, db::terminal::terminal_close, commands::check_license_status, - commands::activate_license, - commands::deactivate_license, - commands::run_license_check, account::account_sign_in, account::account_cancel_sign_in, account::account_status, account::account_sign_out, - account::account_skip_onboarding, account::account_paste_code, sync::sync_state, sync::sync_setup, @@ -939,10 +935,6 @@ pub fn run() { db::parked::close_parked, db::parked::parked_connections, commands::export_parquet, - #[cfg(debug_assertions)] - commands::debug_set_trial_days_ago, - #[cfg(debug_assertions)] - commands::debug_reset_trial, ]) .build(tauri::generate_context!()) .expect("error while running tauri application") diff --git a/src-tauri/src/license.rs b/src-tauri/src/license.rs index 9f23919f..8e669f46 100644 --- a/src-tauri/src/license.rs +++ b/src-tauri/src/license.rs @@ -1,101 +1,38 @@ -/// License system - Ed25519 signed keys + a TRIAL_DAYS-day trial. +/// Licensing primitives shared by the account code (`account.rs`). /// -/// Key format: . -/// Message: "v1:{email}:{plan}:{iat}:{exp}" (UTF-8, exp=0 means lifetime) -/// -/// After first activation the decoded data is written to: -/// /license.json -/// -/// Trial is tracked in TWO locations (8 LE bytes = u64 unix timestamp of first launch): -/// /.trial - removed on a full uninstall -/// /.stroke/trial - survives uninstall, so reinstalling does NOT -/// grant a fresh trial. The earliest timestamp -/// across both wins, and both are repaired on read. -/// (For tamper-proof enforcement across full disk wipes, register the trial -/// start server-side keyed by device_id - the API scaffolding already exists.) -/// -/// ------------------------------------------------------------------- -/// SETUP: run `node scripts/license-tool.mjs keygen` once. -/// Copy the printed public key hex into PUBLIC_KEY_HEX below, then rebuild. -/// ------------------------------------------------------------------- -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; -use ed25519_dalek::{Signature, Verifier, VerifyingKey}; +/// Stroke 3 has no license keys and no device trial: Pro comes from the +/// signed-in account's signed entitlement. What is left here is the status the +/// UI reads, the key that verifies entitlements, the clock guard and the device +/// fingerprint. use sha2::{Digest, Sha256}; use std::{ path::{Path, PathBuf}, time::{SystemTime, UNIX_EPOCH}, }; -const STROKE_API: &str = "https://stroke.click/api/license"; - -// ── Generated by `node scripts/license-tool.mjs keygen` ───────────────────── +/// Ed25519 public key that signs account entitlements on stroke.click. pub const PUBLIC_KEY_HEX: &str = "b5f14fed4694302a767e32c4e6a50ba0074c4e50f5198ad781de00d0e8ba8771"; -pub const TRIAL_DAYS: i64 = 17; -const LICENSE_FILE: &str = "license.json"; -const TRIAL_FILE: &str = ".trial"; - -// ── Revocation list ─────────────────────────────────────────────────────────── -// Each entry is the hex-encoded SHA-256 of the full license key string. -// To revoke a key: -// 1. Run: node scripts/license-tool.mjs revoke -// 2. Copy the printed hash into this array. -// 3. Rebuild and ship an app update. -// -// Note: revocation only takes effect after the user installs the update. -// For immediate remote revocation you'll need the server endpoint (coming later). -const REVOKED_KEY_HASHES: &[&str] = &[ - "ed13c9edc3bea01c6f82a415a10b21f85b85f829004f473cb78e8cd10056059f", // revoked 2026-06-05 (case: LIC-REV-2026-06-05-01) -]; - -// ── Data types ──────────────────────────────────────────────────────────────── - -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] -pub struct LicenseFile { - pub version: u8, - /// The raw key string the user pasted in - pub key: String, - pub email: String, - pub plan: String, - pub issued_at: u64, - /// None / missing field → lifetime license - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at: Option, - pub device_id: String, - pub activated_at: u64, - /// Unix timestamp of the last successful server check (0 = never checked). - #[serde(default)] - pub last_check_at: u64, -} - #[derive(serde::Serialize, Debug, Clone)] #[serde(tag = "status")] pub enum LicenseStatus { - /// Active paid license + /// Paid Pro on the account Valid { email: String, plan: String, issued_at: u64, expires_at: Option, }, - /// Free trial still running + /// The account's free trial is running Trial { days_remaining: i64 }, - /// Trial period over, no license + /// No Pro: trial over, free plan, or signed out TrialExpired, /// App data dir inaccessible (should not normally happen) Error { message: String }, } -// ── Path helpers ────────────────────────────────────────────────────────────── - -pub fn license_path(data_dir: &Path) -> PathBuf { - data_dir.join(LICENSE_FILE) -} - -pub fn trial_path(data_dir: &Path) -> PathBuf { - data_dir.join(TRIAL_FILE) -} +// ── Paths ───────────────────────────────────────────────────────────────────── /// The user's home directory, cross-platform (HOME on unix/macOS, USERPROFILE on Windows). fn home_dir() -> Option { @@ -104,22 +41,12 @@ fn home_dir() -> Option { .map(PathBuf::from) } -/// All locations the trial start is mirrored to. The app-data copy is wiped on -/// uninstall; the home-dir copy survives, so a reinstall can't reset the trial. -fn trial_paths(data_dir: &Path) -> Vec { - let mut paths = vec![trial_path(data_dir)]; - if let Some(home) = home_dir() { - paths.push(home.join(".stroke").join("trial")); - } - paths -} - // ── Clock guard ─────────────────────────────────────────────────────────────── // // Offline, every expiry check compares against the system clock - and setting // the clock back would stretch a trial or a cached entitlement for as long as // the machine stays off the network. The latest time the app has ever seen is -// kept (mirrored like the trial start, so deleting one copy changes nothing), +// kept (in two places, so deleting one copy changes nothing), // and offline checks use whichever is later: the clock, or that mark. Winding // the clock back then gains nothing. A successful server check resets the mark // to the server's own time, so a clock that was wrong in the future direction @@ -252,7 +179,7 @@ fn machine_id_raw() -> String { .unwrap_or_else(|_| "unknown-host".to_string()) } -// ── Trial management ────────────────────────────────────────────────────────── +// ── Time ────────────────────────────────────────────────────────────────────── fn now_secs() -> u64 { SystemTime::now() @@ -260,411 +187,3 @@ fn now_secs() -> u64 { .map(|d| d.as_secs()) .unwrap_or(0) } - -/// Reads the trial start across all mirror locations and returns `days_remaining` -/// (negative = expired). The EARLIEST timestamp found wins - so deleting one copy -/// (e.g. uninstalling, which wipes app-data) can't grant a fresh trial while the -/// home-dir copy survives. Every location is (re)written with the winning start so -/// a missing/newer copy is repaired on each launch. -pub fn trial_days_remaining(data_dir: &Path) -> i64 { - let paths = trial_paths(data_dir); - - let mut earliest: Option = None; - for p in &paths { - if let Ok(bytes) = std::fs::read(p) { - if let Ok(arr) = <[u8; 8]>::try_from(bytes.as_slice()) { - let t = u64::from_le_bytes(arr); - earliest = Some(earliest.map_or(t, |e| e.min(t))); - } - } - } - - // First launch on this device (or every copy was removed) - start now. - let start_secs = earliest.unwrap_or_else(now_secs); - - // Propagate/repair the winning start to every location. - for p in &paths { - if let Some(dir) = p.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = std::fs::write(p, start_secs.to_le_bytes()); - } - - let elapsed_days = (trusted_now(data_dir).saturating_sub(start_secs) / 86_400) as i64; - TRIAL_DAYS - elapsed_days -} - -/// The earliest trial start recorded across local mirrors, without writing. -/// `None` if no local trial file exists yet (e.g. a fresh install). -pub(crate) fn local_trial_start(data_dir: &Path) -> Option { - let mut earliest: Option = None; - for p in trial_paths(data_dir) { - if let Ok(bytes) = std::fs::read(&p) { - if let Ok(arr) = <[u8; 8]>::try_from(bytes.as_slice()) { - let t = u64::from_le_bytes(arr); - earliest = Some(earliest.map_or(t, |e| e.min(t))); - } - } - } - earliest -} - -/// Phone home to sync the trial clock with the server (earliest-wins). The -/// server records the start the first time it sees this device and always -/// returns the earliest known start - so a reinstall or disk wipe can't hand -/// out a fresh trial. On success the authoritative start is written to every -/// local mirror so the next local check reflects it. No-op when offline. -pub async fn reconcile_trial(data_dir: &Path) { - let local = local_trial_start(data_dir); - if let Some(server_start) = api_trial(&device_id(), local).await { - for p in trial_paths(data_dir) { - if let Some(dir) = p.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = std::fs::write(&p, server_start.to_le_bytes()); - } - } -} - -/// DEBUG ONLY - write a trial start timestamp N days in the past so the UI -/// shows "N days elapsed" without waiting for real time to pass. -#[cfg(debug_assertions)] -pub fn debug_set_trial_days_ago(data_dir: &Path, days_ago: u64) -> Result<(), String> { - let fake_start = now_secs().saturating_sub(days_ago * 86_400); - for p in trial_paths(data_dir) { - if let Some(dir) = p.parent() { - std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; - } - std::fs::write(&p, fake_start.to_le_bytes()).map_err(|e| e.to_string())?; - } - Ok(()) -} - -/// DEBUG ONLY - delete every trial mirror so the next check starts a fresh trial. -#[cfg(debug_assertions)] -pub fn debug_reset_trial(data_dir: &Path) -> Result<(), String> { - for p in trial_paths(data_dir) { - if p.exists() { - std::fs::remove_file(&p).map_err(|e| e.to_string())?; - } - } - Ok(()) -} - -// ── Signature verification ──────────────────────────────────────────────────── - -#[derive(Debug)] -pub struct ParsedKey { - pub email: String, - pub plan: String, - pub issued_at: u64, - pub expires_at: Option, -} - -/// Return the hex SHA-256 of a key string - used to populate REVOKED_KEY_HASHES. -pub fn key_hash(key: &str) -> String { - let mut h = Sha256::new(); - h.update(key.as_bytes()); - hex::encode(h.finalize()) -} - -/// Verify an `.` license key. -/// Returns the parsed payload on success, or an error string. -pub fn verify_key(key: &str) -> Result { - // Check revocation list first - let hash = key_hash(key); - if REVOKED_KEY_HASHES.contains(&hash.as_str()) { - return Err("this license key has been revoked".to_string()); - } - - // Decode public key - let pk_bytes: [u8; 32] = hex::decode(PUBLIC_KEY_HEX) - .map_err(|_| "invalid public key constant (not hex)".to_string())? - .try_into() - .map_err(|_| "public key must be 32 bytes".to_string())?; - - // Reject placeholder key - if pk_bytes == [0u8; 32] { - return Err("Public key not configured - run `node scripts/license-tool.mjs keygen` and update PUBLIC_KEY_HEX in license.rs".to_string()); - } - - let verifying_key = - VerifyingKey::from_bytes(&pk_bytes).map_err(|e| format!("bad public key: {e}"))?; - - // Split key into message + signature - let (msg_b64, sig_b64) = key - .split_once('.') - .ok_or_else(|| "invalid key format (expected .)".to_string())?; - - let msg_bytes = URL_SAFE_NO_PAD - .decode(msg_b64.trim()) - .map_err(|_| "key payload is not valid base64url".to_string())?; - - let sig_bytes = URL_SAFE_NO_PAD - .decode(sig_b64.trim()) - .map_err(|_| "key signature is not valid base64url".to_string())?; - - let sig_arr: [u8; 64] = sig_bytes - .try_into() - .map_err(|_| "signature must be 64 bytes".to_string())?; - let signature = Signature::from_bytes(&sig_arr); - - // Verify Ed25519 signature - verifying_key - .verify(&msg_bytes, &signature) - .map_err(|_| "invalid license signature - key may be forged or corrupted".to_string())?; - - // Parse message "v1:{email}:{plan}:{iat}:{exp}" - let msg_str = String::from_utf8(msg_bytes) - .map_err(|_| "message payload is not UTF-8".to_string())?; - - let parts: Vec<&str> = msg_str.splitn(5, ':').collect(); - if parts.len() != 5 || parts[0] != "v1" { - return Err("unrecognised license message format".to_string()); - } - - let email = parts[1].to_string(); - let plan = parts[2].to_string(); - let iat: u64 = parts[3] - .parse() - .map_err(|_| "invalid issued_at timestamp".to_string())?; - let exp_raw: u64 = parts[4] - .parse() - .map_err(|_| "invalid expires_at timestamp".to_string())?; - let expires_at = if exp_raw == 0 { None } else { Some(exp_raw) }; - - // Check expiry - if let Some(exp) = expires_at { - if now_secs() > exp { - return Err("license has expired".to_string()); - } - } - - Ok(ParsedKey { - email, - plan, - issued_at: iat, - expires_at, - }) -} - -// ── License file I/O ────────────────────────────────────────────────────────── - -pub fn load_license(data_dir: &Path) -> Option { - let raw = std::fs::read_to_string(license_path(data_dir)).ok()?; - serde_json::from_str(&raw).ok() -} - -pub fn save_license(data_dir: &Path, lic: &LicenseFile) -> Result<(), String> { - std::fs::create_dir_all(data_dir).map_err(|e| e.to_string())?; - let json = serde_json::to_string_pretty(lic).map_err(|e| e.to_string())?; - std::fs::write(license_path(data_dir), json).map_err(|e| e.to_string()) -} - -pub fn delete_license(data_dir: &Path) -> Result<(), String> { - let p = license_path(data_dir); - if p.exists() { - std::fs::remove_file(p).map_err(|e| e.to_string())?; - } - Ok(()) -} - -// ── Hostname helper ─────────────────────────────────────────────────────────── - -fn hostname() -> String { - std::env::var("COMPUTERNAME") - .or_else(|_| std::env::var("HOSTNAME")) - .or_else(|_| std::fs::read_to_string("/etc/hostname").map(|s| s.trim().to_string())) - .unwrap_or_else(|_| "unknown".to_string()) -} - -// ── Remote API calls ────────────────────────────────────────────────────────── - -fn http_client() -> &'static reqwest::Client { - static LICENSE_CLIENT: std::sync::OnceLock = std::sync::OnceLock::new(); - LICENSE_CLIENT.get_or_init(|| { - reqwest::Client::builder() - // 4s, not 10s. This call is fire-and-forget - it only catches server-side - // revocation, and a network failure already falls through to the offline - // grace path. On a flaky uplink the old timeout meant a request hanging - // around for ten seconds (visible as a 10s run_license_check in the - // waterfall) to reach a conclusion it was going to reach anyway. - .timeout(std::time::Duration::from_secs(4)) - .build() - .unwrap_or_default() - }) -} - -/// POST /api/license/activate - registers this device with the server. -/// Returns the server JSON on success, or an error string. -/// On network failure returns Ok(None) so the caller can apply an offline grace. -pub async fn api_activate( - key: &str, - device_id: &str, - app_version: &str, -) -> Result, String> { - let body = serde_json::json!({ - "key": key, - "device_id": device_id, - "hostname": hostname(), - // Shown next to the device on the account dashboard. - "os": std::env::consts::OS, - "version": app_version, - }); - let resp = match http_client() - .post(format!("{STROKE_API}/activate")) - .json(&body) - .send() - .await - { - Ok(r) => r, - Err(_) => return Ok(None), // network unreachable → offline grace - }; - let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?; - if json.get("valid").and_then(|v| v.as_bool()).unwrap_or(false) { - Ok(Some(json)) - } else { - let err = json - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown_error") - .to_string(); - Err(err) - } -} - -/// What `/api/license/check` said about this key on this device. -#[derive(Debug, PartialEq)] -pub enum CheckOutcome { - Valid, - /// `revoked` or `expired`: the key is finished, drop it. - Ended, - /// The device was never registered (offline activation) or its seat was - /// released: register it again. - NotActivated, - /// Any other answer (`not_found`, a server bug, a bad deploy). Keep the key; - /// the local signature still holds and the next check tries again. - Unknown, -} - -pub fn check_outcome(json: &serde_json::Value) -> CheckOutcome { - if json.get("valid").and_then(|v| v.as_bool()) == Some(true) { - return CheckOutcome::Valid; - } - match json.get("error").and_then(|v| v.as_str()) { - Some("revoked" | "expired") => CheckOutcome::Ended, - Some("device_not_activated") => CheckOutcome::NotActivated, - _ => CheckOutcome::Unknown, - } -} - -/// POST /api/license/check - phone-home to detect server-side revocation. -/// Returns `None` on network error or an unreadable reply (retry later). -pub async fn api_check(key: &str, device_id: &str, app_version: &str) -> Option { - let body = serde_json::json!({ - "key": key, - "device_id": device_id, - "os": std::env::consts::OS, - "version": app_version, - }); - let resp = http_client() - .post(format!("{STROKE_API}/check")) - .json(&body) - .send() - .await - .ok()?; - let json: serde_json::Value = resp.json().await.ok()?; - Some(check_outcome(&json)) -} - -/// POST /api/license/trial - register/sync this device's trial start. -/// Sends the local start (if any) so the server can keep the earliest; returns -/// the server's authoritative start (unix seconds), or None on network error. -pub async fn api_trial(device_id: &str, local_started_at: Option) -> Option { - let mut body = serde_json::json!({ "device_id": device_id, "hostname": hostname() }); - if let Some(s) = local_started_at { - body["started_at"] = serde_json::json!(s); - } - let resp = http_client() - .post(format!("{STROKE_API}/trial")) - .json(&body) - .send() - .await - .ok()?; - let json: serde_json::Value = resp.json().await.ok()?; - json.get("started_at").and_then(|v| v.as_u64()) -} - -/// POST /api/license/deactivate - releases the seat on the server. -/// Fire-and-forget; silently ignores errors. -pub async fn api_deactivate(key: &str, device_id: &str) { - let body = serde_json::json!({ "key": key, "device_id": device_id }); - let _ = http_client() - .post(format!("{STROKE_API}/deactivate")) - .json(&body) - .send() - .await; -} - -// ── High-level status check ─────────────────────────────────────────────────── - -pub fn check_status(data_dir: &Path) -> LicenseStatus { - // 1. Valid stored license? - if let Some(lic) = load_license(data_dir) { - // Re-verify signature and device binding - match verify_key(&lic.key) { - Ok(parsed) => { - // Soft device check - if lic.device_id == device_id() || cfg!(debug_assertions) { - return LicenseStatus::Valid { - email: parsed.email, - plan: parsed.plan, - issued_at: parsed.issued_at, - expires_at: parsed.expires_at, - }; - } - // Device mismatch - treat as expired trial so they can re-activate - } - Err(_) => { - // Corrupted / tampered license file - remove it - let _ = delete_license(data_dir); - } - } - } - - // 2. Trial - trial_status(data_dir) -} - -/// The trial's state alone, ignoring any license key on this device. -pub fn trial_status(data_dir: &Path) -> LicenseStatus { - let days = trial_days_remaining(data_dir); - if days > 0 { - LicenseStatus::Trial { - days_remaining: days, - } - } else { - LicenseStatus::TrialExpired - } -} - -#[cfg(test)] -mod check_outcome_tests { - use super::*; - use serde_json::json; - - #[test] - fn only_revoked_or_expired_end_the_key() { - assert_eq!(check_outcome(&json!({"valid": true})), CheckOutcome::Valid); - assert_eq!(check_outcome(&json!({"valid": false, "error": "revoked"})), CheckOutcome::Ended); - assert_eq!(check_outcome(&json!({"valid": false, "error": "expired"})), CheckOutcome::Ended); - assert_eq!( - check_outcome(&json!({"valid": false, "error": "device_not_activated"})), - CheckOutcome::NotActivated - ); - for e in ["not_found", "bad_signature", "missing_fields", "something_new"] { - assert_eq!(check_outcome(&json!({"valid": false, "error": e})), CheckOutcome::Unknown); - } - assert_eq!(check_outcome(&json!({"oops": 1})), CheckOutcome::Unknown); - } -} diff --git a/src/App.svelte b/src/App.svelte index 4a38efa1..0d4a5395 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -29,18 +29,16 @@ void installClipboardBridge() // Dev-only console helpers (window.__TAURI__ isn't exposed without - // withGlobalTauri, which we keep off in production). Debug trial commands - // only exist in debug builds, so these are dev-only too. + // withGlobalTauri, which we keep off in production). if (import.meta.env.DEV) { const { invoke } = await import('@tauri-apps/api/core') const { refreshLicenseStatus } = await import('$lib/stores/license.js') // @ts-expect-error - dev-only debug surface window.__stroke = { status: () => invoke('check_license_status'), - resetTrial: async () => { await invoke('debug_reset_trial'); return refreshLicenseStatus() }, - expireTrial: async (daysAgo = 20) => { await invoke('debug_set_trial_days_ago', { daysAgo }); return refreshLicenseStatus() }, + refresh: () => refreshLicenseStatus(), } - console.info('[stroke] dev helpers → window.__stroke.status() / .expireTrial(20) / .resetTrial()') + console.info('[stroke] dev helpers → window.__stroke.status() / .refresh()') } // Suppress Tauri's internal "Couldn't find callback id" warning. diff --git a/src/lib/components/AboutDialog.svelte b/src/lib/components/AboutDialog.svelte index 845d7114..fb451dcd 100644 --- a/src/lib/components/AboutDialog.svelte +++ b/src/lib/components/AboutDialog.svelte @@ -1,20 +1,15 @@ @@ -54,20 +41,17 @@
- +
{#if !$licenseStatus}
- Checking license… + Checking your plan…
{:else if isValid} - -
Plan
@@ -76,78 +60,24 @@ · {$licenseStatus.expires_at ? `until ${new Date($licenseStatus.expires_at * 1000).toLocaleDateString()}` : 'Lifetime'}
-
Licensed to
+
Account
{$licenseStatus.email}
- {:else if isTrial} - -
-
- - - - {$licenseStatus.days_remaining}d left - -
- {#if showActivate} - { showActivate = false; open = false }} /> - - {:else} - - {/if} +
+ + + + {$licenseStatus.days_remaining}d left +
{:else} - -
-
-

No active license

-

Free features only.

-
- {#if showActivate} - { showActivate = false; open = false }} /> - - {:else} - - {/if} +
+

No Stroke Pro on this account

+

Free features only.

{/if}
diff --git a/src/lib/components/AccountCard.svelte b/src/lib/components/AccountCard.svelte index 7ab2fb83..c4f65373 100644 --- a/src/lib/components/AccountCard.svelte +++ b/src/lib/components/AccountCard.svelte @@ -26,13 +26,6 @@ const devices = $derived($account?.devices?.length ?? 0) let signingOut = $state(false) - const LINK_ERRORS = /** @type {Record} */ ({ - key_owned_elsewhere: 'The license on this device was bought with another account, so this account is on the free trial. Sign in with the account that bought it to use it here.', - revoked: 'The license key on this device has been revoked.', - not_found: 'The license key on this device was not found on the server.', - invalid_key: 'The license key on this device could not be linked.', - }) - async function handleSignOut() { if (signingOut) return signingOut = true @@ -80,17 +73,12 @@
- {#if $account?.link_error} -

{LINK_ERRORS[$account.link_error] ?? 'The license key on this device could not be linked.'}

- {/if} {:else}

Stroke account

- {$account?.has_license_key - ? 'Your key keeps working. Sign in to sync connections across devices.' - : 'Your license and trial come with you to every device you sign in on.'} + Stroke Pro and the trial come with you to every device you sign in on.

{#if idle} @@ -123,9 +111,6 @@

{devices} {devices === 1 ? 'device' : 'devices'} signed in{#if $account?.offline}. Offline, showing the last saved plan{/if}.

- {#if $account?.link_error} -

{LINK_ERRORS[$account.link_error] ?? 'The license key on this device could not be linked.'}

- {/if}
-{/snippet} - -
- {#if !compact && !naked && !inline} -
-

Enter your license key

-

Sent to your email after purchase.

-
- {/if} - - - {#if inline} -
- {@render keyField('flex-1 min-w-0')} - {@render submitBtn(false, 'Activate')} -
- {:else} - {@render keyField('')} - {/if} - - -
-
-

- - {shownError} -

-
-
- - {#if !inline} - {@render submitBtn(true, 'Activate')} - {/if} -
- -{#if success} - -{/if} diff --git a/src/lib/components/LicenseGate.svelte b/src/lib/components/LicenseGate.svelte index 15985c1b..1febb02e 100644 --- a/src/lib/components/LicenseGate.svelte +++ b/src/lib/components/LicenseGate.svelte @@ -1,30 +1,35 @@ -{#if $needsOnboarding && !onboardingDone} - +{#if !ready} + +{:else if $needsOnboarding && !onboardingDone} + (onboardingDone = true)} /> {#if import.meta.env.DEV && tourPreview} {#await import('./Onboarding.svelte') then { default: Onboarding }} @@ -63,7 +67,7 @@ {/await} {/if} {:else if $isBlocked || holdGate} - + (holdGate = false)} /> {:else} {@render children()} diff --git a/src/lib/components/LicensePage.svelte b/src/lib/components/LicensePage.svelte index 4dd75009..017afa2b 100644 --- a/src/lib/components/LicensePage.svelte +++ b/src/lib/components/LicensePage.svelte @@ -1,6 +1,5 @@ + +{#snippet message(/** @type {string} */ title, /** @type {string} */ body)} +
+ +

{title}

+

{body}

+
+{/snippet} + +{#if !$isSignedIn} + {@render message('Sign in for scheduled backups', 'Scheduled backups come with Stroke Pro on your account.')} +{:else if !$hasPro || overview?.pro === false} +
+ +

Scheduled backups are part of Stroke Pro

+

Back up up to 10 databases on a schedule, to Stroke Cloud or your own S3 bucket.

+ +
+{:else if !connection} + {@render message('Save this connection first', 'Scheduled backups run on saved connections, so Stroke can open them again later.')} +{:else if !supported} + {@render message('Not available for this database', 'Scheduled backups support PostgreSQL, MySQL, SQLite, Cloudflare D1, Turso/libSQL, DuckDB and SQL Server.')} +{:else} +
+
+
+
+

Scheduled backups

+

+ Stroke runs them while it's open on a computer with this connection. A run missed while it was closed happens the next time it opens. +

+ {#if overview} +

+ {overview.jobs.length} of {overview.max_jobs} schedules · {formatBytes(overview.used_bytes)} of {formatBytes(overview.quota_bytes)} on Stroke Cloud +

+ {/if} +
+ +
+ + {#if $backupLoadError && !overview} +

{$backupLoadError}

+ {/if} + +
+

This database

+ {#if !overview} +
+ {:else if jobs.length === 0 && !formOpen} +

No schedule yet.

+ {/if} + {#each jobs as job (job.id)} + {@const last = job.runs[0]} +
+ {#if job.destination === 'stroke'}{:else}{/if} +
+

+ {describeCron(job.cron)} + {#if !job.enabled}Paused{/if} +

+

+ {job.destination === 'stroke' ? `Stroke Cloud, keeps ${job.keep}` : `S3 bucket ${job.s3_bucket}`} + {#if $runningJobId === job.id} · Running now + {:else if last} · Last {last.status === 'failed' ? 'failed' : last.status === 'running' ? 'started' : 'ran'} {when(last.started_at)} + {/if} + {#if job.enabled && job.next_run_at} · Next {when(job.next_run_at)}{/if} +

+ {#if last?.status === 'failed' && last.error} +

{last.error}

+ {/if} +
+
+ {#if $runningJobId === job.id} + + {:else} + + {/if} + + + {#if confirmDelete === job.id} + + + {:else} + + {/if} +
+
+ {/each} + + {#if overview && !formOpen} +
+ + {#if atLimit}

You have {overview.max_jobs} schedules, the most Pro allows. Delete one to add another.

{/if} +
+ {/if} +
+ + {#if formOpen} + +
+
+ + +
+ {#if preset === 'daily' || preset === 'weekly'} +
+ + +
+ {/if} + {#if preset === 'weekly'} +
+ + ({ value: String(i), label: d }))} /> +
+ {/if} + {#if preset === 'custom'} +
+ + +
+ {/if} +
+

{describeCron(cron)}, {timezone} time. At most once an hour.

+ +
+ Save to + {#each [{ v: 'stroke', icon: Cloud, title: 'Stroke Cloud', body: 'Stored for you, 5 GB per account. Download from stroke.click.' }, { v: 's3', icon: HardDrive, title: 'My S3 bucket', body: 'AWS S3, Cloudflare R2, MinIO, Backblaze B2 or any S3-compatible storage.' }] as opt (opt.v)} + + {/each} +
+ + {#if destination === 'stroke'} +
+ + ({ value: String(n), label: `${n} backups` }))} /> +
+ {:else} +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+

The keys stay in this computer's keychain. stroke.click only sees the bucket name.

+
+ {/if} + + {#if formError}{/if} +
+ + +
+ + {/if} + + {#if otherJobs.length} +
+

Other databases

+
    + {#each otherJobs as job (job.id)} +
  • + {job.label} + {describeCron(job.cron)}{job.enabled ? '' : ' · Paused'} +
  • + {/each} +
+
+ {/if} +
+
+{/if} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index f1d4fa88..863b3fed 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -10654,7 +10654,7 @@ let rowSearch = $state('') > {#await import('./BackupPage.svelte')}{:then { default: BackupPage }} - ({ name: t.name, rowCount: t.rowCount }))} onrestored={async () => { await loadSchemas(); await loadTables({ force: true }); bumpObjects() }} /> + c.id === activeConnectionId) ?? null} tables={tables.map((t) => ({ name: t.name, rowCount: t.rowCount }))} onrestored={async () => { await loadSchemas(); await loadTables({ force: true }); bumpObjects() }} /> {/await}
diff --git a/src/lib/stores/scheduled-backups.js b/src/lib/stores/scheduled-backups.js new file mode 100644 index 00000000..29a09040 --- /dev/null +++ b/src/lib/stores/scheduled-backups.js @@ -0,0 +1,209 @@ +import { invoke } from '@tauri-apps/api/core' +import { writable, get } from 'svelte/store' +import { Cron } from 'croner' +import { loadSavedConnections } from './connections.js' +import { hasPro } from './license.js' +import { isSignedIn } from './account.js' + +/** + * Scheduled backups (Pro). Jobs live on stroke.click; this app runs them, + * because only it has the database credentials. Every minute the scheduler + * looks for a job whose schedule tick has passed (or a "Run now" from the + * website) on a connection saved on this device, claims the tick on the + * server (so two devices never both run it), and runs it in Rust + * (src-tauri/src/cloud_backup.rs). + * + * @typedef {{ id: string, slot: string, status: 'running'|'success'|'failed', destination: 'stroke'|'s3', + * object_key: string|null, bytes: number, tables: number, rows: number, error: string|null, + * device_name: string|null, started_at: number, finished_at: number|null }} BackupRun + * @typedef {{ id: string, connection_id: string, label: string, driver: string, cron: string, timezone: string, + * destination: 'stroke'|'s3', s3_bucket: string|null, s3_endpoint: string|null, s3_prefix: string|null, + * keep: number, enabled: boolean, run_requested_at: number|null, created_at: number, + * next_run_at: number|null, runs: BackupRun[] }} BackupJob + * @typedef {{ jobs: BackupJob[], max_jobs: number, used_bytes: number, quota_bytes: number, pro: boolean }} BackupOverview + */ + +/** Engines the backup engine can dump. Keep in sync with stroke-web's DRIVERS. */ +export const SCHEDULE_DRIVERS = new Set(['postgres', 'mysql', 'sqlite', 'd1', 'libsql', 'duckdb', 'mssql']) + +/** @type {import('svelte/store').Writable} */ +export const backupOverview = writable(null) +/** @type {import('svelte/store').Writable} */ +export const backupLoadError = writable(null) +/** The job running on this device right now, if any. */ +export const runningJobId = writable(/** @type {string|null} */ (null)) + +/** @param {BackupOverview} o */ +const setOverview = (o) => { + backupOverview.set(o) + backupLoadError.set(null) + return o +} + +export async function refreshBackupJobs() { + try { + return setOverview(/** @type {BackupOverview} */ (await invoke('backup_jobs_list'))) + } catch (e) { + backupLoadError.set(String(e)) + return null + } +} + +/** @param {Record} job */ +export async function saveBackupJob(job) { + return setOverview(/** @type {BackupOverview} */ (await invoke('backup_job_save', { job }))) +} + +/** @param {string} id @param {{ enabled?: boolean, run_now?: boolean }} patch */ +export async function patchBackupJob(id, patch) { + const o = setOverview(/** @type {BackupOverview} */ (await invoke('backup_job_patch', { id, patch }))) + if (patch.run_now) void tick() + return o +} + +/** @param {string} id */ +export async function deleteBackupJob(id) { + return setOverview(/** @type {BackupOverview} */ (await invoke('backup_job_delete', { id }))) +} + +/** + * @param {string} jobId + * @param {{ accessKeyId: string, secretAccessKey: string, region: string }} keys + */ +export async function saveS3Keys(jobId, keys) { + await invoke('backup_s3_save', { jobId, accessKeyId: keys.accessKeyId, secretAccessKey: keys.secretAccessKey, region: keys.region }) +} + +/** The region saved with this device's S3 keys for the job, or null when it has none. */ +export async function s3KeysRegion(/** @type {string} */ jobId) { + try { + return /** @type {string|null} */ (await invoke('backup_s3_status', { jobId })) + } catch { + return null + } +} + +/** + * The tick a job should run for now, or null. A "Run now" request wins. + * Missed ticks (the app was closed) collapse into one run for the latest. + * @param {BackupJob} job + * @param {number} [now] + */ +export function dueSlot(job, now = Date.now()) { + // "Run now" works on a paused job too: it's an explicit ask. + if (job.run_requested_at) return `manual:${job.run_requested_at}` + if (!job.enabled) return null + /** @type {Cron} */ + let cron + try { + cron = new Cron(job.cron, { timezone: job.timezone || 'UTC', paused: true }) + } catch { + return null + } + const lastTick = Math.max(0, ...job.runs.filter((r) => !r.slot.startsWith('manual:')).map((r) => Date.parse(r.slot) || 0)) + const baseline = Math.max(job.created_at, lastTick) + let tick = cron.nextRun(new Date(baseline)) + if (!tick || tick.getTime() > now) return null + for (let i = 0; i < 5000; i++) { + const next = cron.nextRun(tick) + if (!next || next.getTime() > now) break + tick = next + } + return tick.toISOString() +} + +/** Plain words for the common schedules; the cron itself otherwise. @param {string} cron */ +export function describeCron(cron) { + const [min, hour, dom, mon, dow] = String(cron).trim().split(/\s+/) + const num = /^\d+$/ + const at = (/** @type {string} */ h, /** @type {string} */ m) => `${h.padStart(2, '0')}:${m.padStart(2, '0')}` + const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + if (num.test(min) && hour === '*' && dom === '*' && mon === '*' && dow === '*') return `Every hour at :${min.padStart(2, '0')}` + if (num.test(min) && /^\*\/\d+$/.test(hour ?? '') && dom === '*' && mon === '*' && dow === '*') return `Every ${hour.slice(2)} hours` + if (num.test(min) && num.test(hour) && mon === '*') { + if (dom === '*' && dow === '*') return `Every day at ${at(hour, min)}` + if (dom === '*' && num.test(dow) && days[Number(dow) % 7]) return `Every ${days[Number(dow) % 7]} at ${at(hour, min)}` + if (num.test(dom) && dow === '*') return `Day ${dom} of every month at ${at(hour, min)}` + } + return cron +} + +/** @param {number} n */ +export function formatBytes(n) { + if (n < 1024) return `${n} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let v = n / 1024 + let i = 0 + while (v >= 1024 && i < units.length - 1) { v /= 1024; i++ } + return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${units[i]}` +} + +// ── Scheduler ──────────────────────────────────────────────────────────────── + +const TICK_MS = 60_000 +/** Re-read the jobs at most this often (a "Run now" from the website shows up within it). */ +const REFRESH_MS = 2 * 60_000 +/** Ticks this device already tried (ran, failed, or lost to another device). */ +const handled = new Set() +let started = false +let busy = false +let lastRefresh = 0 + +async function tick() { + if (busy || !get(isSignedIn) || !get(hasPro)) return + busy = true + try { + if (Date.now() - lastRefresh > REFRESH_MS || !get(backupOverview)) { + lastRefresh = Date.now() + await refreshBackupJobs() + } + const overview = get(backupOverview) + if (!overview?.pro) return + const saved = new Map(loadSavedConnections().map((c) => [c.id, c])) + for (const job of overview.jobs) { + const conn = saved.get(job.connection_id) + // Another device's connection: that device runs it. + if (!conn) continue + const slot = dueSlot(job) + if (!slot || handled.has(`${job.id}|${slot}`)) continue + handled.add(`${job.id}|${slot}`) + await runJob(job, conn, slot) + lastRefresh = Date.now() + await refreshBackupJobs() + } + } finally { + busy = false + } +} + +/** + * @param {BackupJob} job + * @param {object} conn the saved connection, secrets included + * @param {string} slot + */ +async function runJob(job, conn, slot) { + const { toast } = await import('$lib/components/ui/sonner/toast.svelte.js') + runningJobId.set(job.id) + try { + const out = /** @type {{ status: string, message: string, bytes: number }} */ ( + await invoke('backup_job_run', { job, config: conn, slot }) + ) + if (out.status === 'success') { + toast.success(`Backed up ${job.label}`, { description: `${out.message} ${formatBytes(out.bytes)} compressed.` }) + } else if (out.status === 'failed') { + toast.error(`Scheduled backup of ${job.label} failed`, { description: out.message, duration: 15000 }) + } + } catch (e) { + toast.error(`Scheduled backup of ${job.label} failed`, { description: String(e), duration: 15000 }) + } finally { + runningJobId.set(null) + } +} + +/** Start the scheduler once, after sign-in has been settled. */ +export function startBackupScheduler() { + if (started) return + started = true + setTimeout(() => void tick(), 15_000) + setInterval(() => void tick(), TICK_MS) +} diff --git a/src/lib/stores/scheduled-backups.test.js b/src/lib/stores/scheduled-backups.test.js new file mode 100644 index 00000000..3d31e41f --- /dev/null +++ b/src/lib/stores/scheduled-backups.test.js @@ -0,0 +1,43 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() })) + +const { dueSlot, describeCron } = await import('./scheduled-backups.js') + +/** @param {object} over */ +const job = (over = {}) => /** @type {any} */ ({ + id: 'j', cron: '0 3 * * *', timezone: 'UTC', enabled: true, run_requested_at: null, + created_at: Date.parse('2026-11-01T00:00:00Z'), runs: [], ...over, +}) + +describe('dueSlot', () => { + const now = Date.parse('2026-11-18T05:00:00Z') + it('missed ticks collapse into the latest one', () => { + expect(dueSlot(job(), now)).toBe('2026-11-18T03:00:00.000Z') + }) + it('a tick already run is not due again', () => { + const runs = [{ slot: '2026-11-18T03:00:00.000Z' }] + expect(dueSlot(job({ runs }), now)).toBeNull() + }) + it('nothing is due before the first tick after creation', () => { + expect(dueSlot(job({ created_at: Date.parse('2026-11-18T04:00:00Z') }), now)).toBeNull() + }) + it('paused jobs only run when asked', () => { + expect(dueSlot(job({ enabled: false }), now)).toBeNull() + expect(dueSlot(job({ enabled: false, run_requested_at: 42 }), now)).toBe('manual:42') + }) + it('reads the schedule in its time zone', () => { + // 03:00 in Kolkata is 21:30 UTC the day before. + expect(dueSlot(job({ timezone: 'Asia/Kolkata' }), now)).toBe('2026-11-17T21:30:00.000Z') + }) +}) + +describe('describeCron', () => { + it('names the common schedules', () => { + expect(describeCron('0 3 * * *')).toBe('Every day at 03:00') + expect(describeCron('30 22 * * 1')).toBe('Every Monday at 22:30') + expect(describeCron('0 */6 * * *')).toBe('Every 6 hours') + expect(describeCron('0 * * * *')).toBe('Every hour at :00') + expect(describeCron('5 4 1-7 * *')).toBe('5 4 1-7 * *') + }) +}) From db036261bec7f38ad8f22b99426258f32ff86f9c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:16:06 +0000 Subject: [PATCH 286/317] chore: version 2.19.1 (#290) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce1ccd6f..60aef4e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.1] - 2026-11-18 + +### Changes +- Scheduled backups to Stroke Cloud or your own S3 (#290) + + ## [2.19.0] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 94ea1dfb..ffce2fc9 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.0", + "version": "2.19.1", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e0087614..dea006c4 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.0", + "version": "2.19.1", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From b62b54dcedcf8e8319515d3bb33bbd4e8a86ed67 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 12:18:20 +0545 Subject: [PATCH 287/317] Sync saved queries and the library again (#291) The sync engine and the server both know five record kinds, but the Rust encryption step still listed three, so the first saved query or library item failed every push with "Unknown record kind". List all five, and add a test that keeps the JS and Rust lists the same. --- src-tauri/src/sync.rs | 9 +++++++-- src/lib/sync/kinds.test.js | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/lib/sync/kinds.test.js diff --git a/src-tauri/src/sync.rs b/src-tauri/src/sync.rs index 3d33dc82..62a4f9ea 100644 --- a/src-tauri/src/sync.rs +++ b/src-tauri/src/sync.rs @@ -37,7 +37,10 @@ const WRAP_AAD: &[u8] = b"stroke-sync-key-v1"; pub const KDF_M_KIB: u32 = 65_536; pub const KDF_T: u32 = 3; pub const KDF_P: u32 = 1; -pub const KINDS: [&str; 3] = ["workspace", "connection", "settings"]; +/// Record kinds the app syncs. Keep in step with KINDS in src/lib/sync/engine.js +/// and SYNC_KINDS in stroke-web's src/lib/sync/service.ts: a kind missing here +/// fails the whole push ("Unknown record kind"). +pub const KINDS: [&str; 5] = ["workspace", "connection", "settings", "query", "library"]; /// Server limit per push. const PUSH_BATCH: usize = 200; const MIN_PASSPHRASE: usize = 8; @@ -654,7 +657,9 @@ mod tests { assert!(encrypt_plain(&key, &mk("settings", "settings")).is_ok()); assert!(encrypt_plain(&key, &mk("a b", "workspace")).is_err()); assert!(encrypt_plain(&key, &mk(&"x".repeat(129), "workspace")).is_err()); - assert!(encrypt_plain(&key, &mk("x", "query")).is_err()); + assert!(encrypt_plain(&key, &mk("x", "query")).is_ok()); + assert!(encrypt_plain(&key, &mk("x", "library")).is_ok()); + assert!(encrypt_plain(&key, &mk("x", "secrets")).is_err()); let tomb = encrypt_plain(&key, &PlainRecord { deleted: true, plaintext: None, ..mk("x", "workspace") }).unwrap(); assert!(tomb.ciphertext.is_none()); // Wire shape: no seq/updated_at on push. diff --git a/src/lib/sync/kinds.test.js b/src/lib/sync/kinds.test.js new file mode 100644 index 00000000..70b45b21 --- /dev/null +++ b/src/lib/sync/kinds.test.js @@ -0,0 +1,15 @@ +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { KINDS } from './engine.js' + +// The Rust side encrypts every pushed record and refuses kinds it doesn't +// list, which fails the whole push. Keep the two lists the same. +describe('sync kinds', () => { + it('match the Rust list', () => { + const rs = readFileSync(new URL('../../../src-tauri/src/sync.rs', import.meta.url), 'utf8') + const m = /pub const KINDS: \[&str; \d+\] = \[([^\]]*)\]/.exec(rs) + expect(m).toBeTruthy() + const rust = [...m[1].matchAll(/"([^"]+)"/g)].map((x) => x[1]) + expect([...rust].sort()).toEqual([...KINDS].sort()) + }) +}) From 335e93198173b9e8de10f198706d8558d82a86d7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:33:30 +0000 Subject: [PATCH 288/317] chore: version 2.19.2 (#291) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60aef4e4..0bbaedd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.2] - 2026-11-18 + +### Changes +- Fix sync failing with "Unknown record kind: library" (#291) + + ## [2.19.1] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index ffce2fc9..8e150b88 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.1", + "version": "2.19.2", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index dea006c4..27852567 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.1", + "version": "2.19.2", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 3f153ba085bb9e06ad9e6c80c1edad8e14ff19b3 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 12:33:15 +0545 Subject: [PATCH 289/317] Redesign scheduled backups: one-line header, row per schedule, compact dialog (#292) --- src/lib/components/ScheduledBackups.svelte | 404 +++++++++++---------- 1 file changed, 218 insertions(+), 186 deletions(-) diff --git a/src/lib/components/ScheduledBackups.svelte b/src/lib/components/ScheduledBackups.svelte index 3fad0ce7..a8f07e27 100644 --- a/src/lib/components/ScheduledBackups.svelte +++ b/src/lib/components/ScheduledBackups.svelte @@ -1,13 +1,15 @@ -{#snippet message(/** @type {string} */ title, /** @type {string} */ body)} +{#snippet message(/** @type {string} */ title, /** @type {string} */ body, /** @type {import('svelte').Snippet | undefined} */ action = undefined)}

{title}

-

{body}

+

{body}

+ {#if action}
{@render action()}
{/if}
{/snippet} +{#snippet getPro()} + +{/snippet} + +{#snippet addButton()} + +{/snippet} + {#if !$isSignedIn} - {@render message('Sign in for scheduled backups', 'Scheduled backups come with Stroke Pro on your account.')} + {@render message('Sign in for scheduled backups', 'They come with Stroke Pro on your account.')} {:else if !$hasPro || overview?.pro === false} -
- -

Scheduled backups are part of Stroke Pro

-

Back up up to 10 databases on a schedule, to Stroke Cloud or your own S3 bucket.

- -
+ {@render message('Scheduled backups are a Pro feature', 'Up to 10 databases, to Stroke Cloud or your own S3.', getPro)} {:else if !connection} - {@render message('Save this connection first', 'Scheduled backups run on saved connections, so Stroke can open them again later.')} + {@render message('Save this connection first', 'Schedules run on saved connections.')} {:else if !supported} - {@render message('Not available for this database', 'Scheduled backups support PostgreSQL, MySQL, SQLite, Cloudflare D1, Turso/libSQL, DuckDB and SQL Server.')} + {@render message('Not available for this database', 'PostgreSQL, MySQL, SQLite, D1, Turso, DuckDB and SQL Server.')} {:else}
-
-
-
-

Scheduled backups

-

- Stroke runs them while it's open on a computer with this connection. A run missed while it was closed happens the next time it opens. -

- {#if overview} -

- {overview.jobs.length} of {overview.max_jobs} schedules · {formatBytes(overview.used_bytes)} of {formatBytes(overview.quota_bytes)} on Stroke Cloud -

- {/if} -
- + {@render addButton()}
{#if $backupLoadError && !overview}

{$backupLoadError}

{/if} -
-

This database

- {#if !overview} -
- {:else if jobs.length === 0 && !formOpen} -

No schedule yet.

- {/if} - {#each jobs as job (job.id)} - {@const last = job.runs[0]} -
- {#if job.destination === 'stroke'}{:else}{/if} -
-

- {describeCron(job.cron)} - {#if !job.enabled}Paused{/if} -

-

- {job.destination === 'stroke' ? `Stroke Cloud, keeps ${job.keep}` : `S3 bucket ${job.s3_bucket}`} - {#if $runningJobId === job.id} · Running now - {:else if last} · Last {last.status === 'failed' ? 'failed' : last.status === 'running' ? 'started' : 'ran'} {when(last.started_at)} - {/if} - {#if job.enabled && job.next_run_at} · Next {when(job.next_run_at)}{/if} -

- {#if last?.status === 'failed' && last.error} -

{last.error}

- {/if} -
-
- {#if $runningJobId === job.id} - - {:else} - - {/if} - - - {#if confirmDelete === job.id} - - - {:else} - - {/if} -
-
- {/each} - - {#if overview && !formOpen} -
- - {#if atLimit}

You have {overview.max_jobs} schedules, the most Pro allows. Delete one to add another.

{/if} -
- {/if} -
- - {#if formOpen} -
-
-
- - -
- {#if preset === 'daily' || preset === 'weekly'} -
- - -
- {/if} - {#if preset === 'weekly'} -
- - ({ value: String(i), label: d }))} /> -
- {/if} - {#if preset === 'custom'} -
- - -
- {/if} -
-

{describeCron(cron)}, {timezone} time. At most once an hour.

- -
- Save to - {#each [{ v: 'stroke', icon: Cloud, title: 'Stroke Cloud', body: 'Stored for you, 5 GB per account. Download from stroke.click.' }, { v: 's3', icon: HardDrive, title: 'My S3 bucket', body: 'AWS S3, Cloudflare R2, MinIO, Backblaze B2 or any S3-compatible storage.' }] as opt (opt.v)} - - {/each} -
- - {#if destination === 'stroke'} -
- - ({ value: String(n), label: `${n} backups` }))} /> -
- {:else} -
-
- - -
-
- - -
-
- - -
-
- - + {#if !overview} +
+ {:else if jobs.length === 0} +
+ +

No schedule for this database yet.

+ {@render addButton()} +
+ {:else} +
    + {#each jobs as job (job.id)} + {@const last = job.runs[0]} + {@const running = $runningJobId === job.id} +
  • + + {#if job.destination === 'stroke'}{:else}{/if} + +
    +

    + {describeCron(job.cron)} + {#if !job.enabled}Paused{/if} +

    +

    + {job.destination === 'stroke' ? `Stroke Cloud · keeps ${job.keep}` : job.s3_bucket} +

    -
    - - + -
    - - +
    + {#if confirmDelete === job.id} + + + {:else} + + + + + {/if}
    -

    The keys stay in this computer's keychain. stroke.click only sees the bucket name.

    -
    - {/if} - - {#if formError}{/if} -
    - - -
    - +
  • + {/each} +
{/if} {#if otherJobs.length}
-

Other databases

+

Other databases

    {#each otherJobs as job (job.id)} -
  • +
  • {job.label} - {describeCron(job.cron)}{job.enabled ? '' : ' · Paused'} + {describeCron(job.cron)}{job.enabled ? '' : ' · Paused'}
  • {/each}
@@ -380,3 +332,83 @@
{/if} + + + + + {editing ? 'Edit schedule' : 'New schedule'} + {connection?.name || driver} + + +
+
+ Repeat + + {#if preset === 'daily' || preset === 'weekly'} +
+ {#if preset === 'weekly'} + ({ value: String(i), label: d }))} bind:value={weekday} ariaLabel="Day" class="min-w-0 flex-1" /> + {/if} + +
+ {:else if preset === 'custom'} + + {/if} +

+ {nextRun.error ?? `Next ${when(nextRun.at ?? 0)}`} +

+
+ +
+ Save to +
+ {#each [{ v: /** @type {const} */ ('stroke'), icon: Cloud, title: 'Stroke Cloud', sub: '5 GB included' }, { v: /** @type {const} */ ('s3'), icon: HardDrive, title: 'S3 bucket', sub: 'R2, MinIO, B2, AWS' }] as opt (opt.v)} + + {/each} +
+
+ + {#if destination === 'stroke'} +
+ Keep + ({ value: n, label: n }))} bind:value={keep} ariaLabel="Backups to keep" /> +
+ {:else} +
+ + + + + + +

Keys stay in this computer's keychain.

+
+ {/if} + + {#if formError}{/if} + + + + + +
+
+
From 0d5cc6bb13c118bc1d4dc5c25f3ae0bbbc120bf9 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:48:32 +0000 Subject: [PATCH 290/317] chore: version 2.19.3 (#292) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bbaedd0..2840ea2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.3] - 2026-11-18 + +### Changes +- Compact scheduled backups screen (#292) + + ## [2.19.2] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 8e150b88..28fd0890 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.2", + "version": "2.19.3", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 27852567..80ecab2f 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.2", + "version": "2.19.3", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From e23a10dad42c8d788899a1a44924644d16459582 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 12:36:59 +0545 Subject: [PATCH 291/317] TODO: layout control, Dashboard tab, admin metrics, local servers (#293) --- TODO_TODAY.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/TODO_TODAY.md b/TODO_TODAY.md index 39b89d64..6a17a89b 100644 --- a/TODO_TODAY.md +++ b/TODO_TODAY.md @@ -47,6 +47,23 @@ release with a freeze and a test pass, not a plain promote. In order: - [ ] **Ship it.** Label the release PR `release:major` (CONTRIBUTING.md), then Actions, *Promote nightly to stable*. +## Next up + +- [ ] **Layout control.** Three buttons in the title bar for the sidebar (⌘B), + the terminal panel (⌘J) and the docked AI panel (⌘⌥B), the open edge + filled. Built on the `layout-and-dashboard` branch; check it in the + running app on every OS before merging. +- [ ] **Dashboard tab redesign.** A 12-column grid of chart cards, each with a + status dot, refresh, an auto-refresh interval, a title and its error on + the card. Resize and rearrange cards, add one from any saved query, and + save the layout. +- [ ] **Admin metrics page** on stroke.click, for me only: sign-ups, active + trials, trial-to-Pro conversion, revenue, downloads, active devices, + app versions in use, countries, backups and sponsors, over time. +- [ ] **Local database servers.** Postgres, MySQL and Redis side by side in + any version, with Start, Stop, the port and Open, per server on Docker + or as native binaries; Homebrew services listed too. + ## Website The site is `stroke-web` (TanStack Start on Cloudflare Workers). From 08d1542f5c28d88251e13583475d1e7bbc9a0caa Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:52:11 +0000 Subject: [PATCH 292/317] chore: version 2.19.4 (#293) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2840ea2d..fe0364ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.4] - 2026-11-18 + +### Changes +- TODO: what's next (#293) + + ## [2.19.3] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 28fd0890..67bad931 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.3", + "version": "2.19.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 80ecab2f..6374af4e 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.3", + "version": "2.19.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 5f4094baa2e1ec8760f91b3dfa9dee0bcaeffb5d Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 12:54:33 +0545 Subject: [PATCH 293/317] End-to-end encrypt scheduled backups (#294) * End-to-end encrypt scheduled backups Backups are encrypted on the user's computer before upload: chunked XChaCha20-Poly1305 with a fresh key per backup, wrapped with the account's sync key (src-tauri/src/backup_crypto.rs). Stroke Cloud requires it; S3 gets it when sync is set up. Restore opens encrypted and gzipped files, and a sync reset re-wraps existing backup keys under the new sync key. * Test vector for the website's sync unlock --- src-tauri/src/backup_crypto.rs | 288 +++++++++++++++++++++ src-tauri/src/cloud_backup.rs | 84 +++++- src-tauri/src/db/backup.rs | 40 ++- src-tauri/src/lib.rs | 1 + src-tauri/src/sync.rs | 24 +- src/lib/api.js | 5 +- src/lib/components/BackupPage.svelte | 8 + src/lib/components/ScheduledBackups.svelte | 27 ++ 8 files changed, 459 insertions(+), 18 deletions(-) create mode 100644 src-tauri/src/backup_crypto.rs diff --git a/src-tauri/src/backup_crypto.rs b/src-tauri/src/backup_crypto.rs new file mode 100644 index 00000000..20dfb24c --- /dev/null +++ b/src-tauri/src/backup_crypto.rs @@ -0,0 +1,288 @@ +//! End-to-end encryption for scheduled backups. +//! +//! A backup is encrypted on the user's computer before it is uploaded, so +//! Stroke Cloud (and anyone with access to it) only ever holds ciphertext. +//! +//! - **Data key (DEK):** 32 random bytes, fresh for every backup. +//! - **Wrapped DEK:** `nonce24 || XChaCha20-Poly1305(sync_key, nonce, dek, +//! aad = "stroke-backup-dek-v1")`, 72 bytes. The sync key is the account's +//! end-to-end sync key (`sync.rs`), unlocked only by the sync passphrase. +//! - **Key id:** the first 8 bytes of SHA-256("stroke-backup-key-id" || +//! sync_key), hex. Says which sync key wrapped the DEK without revealing it. +//! - **File:** `"STRKBAK1" || key_id(8 raw) || wrapped_dek(72) || +//! nonce_prefix(19)` (107 bytes), then the plaintext in 64 KiB chunks, each +//! `XChaCha20-Poly1305(dek, prefix || counter_u32_be || last_flag, chunk, +//! aad = the 107-byte header)`. The last chunk has flag 1, so a truncated or +//! reordered file fails to open. An empty input is one empty last chunk. +//! +//! The browser decrypts the same format (stroke-web +//! `src/lib/backups/crypto.ts`); keep the two in step. + +use std::io::{Read, Write}; +use std::path::Path; + +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use chacha20poly1305::{XChaCha20Poly1305, XNonce}; +use sha2::{Digest, Sha256}; + +pub const MAGIC: &[u8; 8] = b"STRKBAK1"; +const DEK_AAD: &[u8] = b"stroke-backup-dek-v1"; +pub const CHUNK: usize = 64 * 1024; +const TAG: usize = 16; +const WRAPPED_LEN: usize = 24 + 32 + TAG; +pub const HEADER_LEN: usize = 8 + 8 + WRAPPED_LEN + 19; + +fn random() -> [u8; N] { + let mut b = [0u8; N]; + getrandom::getrandom(&mut b).expect("the OS random source is available"); + b +} + +/// Which sync key wrapped a backup's data key, as 16 hex characters. +pub fn key_id(sync_key: &[u8; 32]) -> String { + hex::encode(&key_id_raw(sync_key)) +} + +fn key_id_raw(sync_key: &[u8; 32]) -> [u8; 8] { + let mut h = Sha256::new(); + h.update(b"stroke-backup-key-id"); + h.update(sync_key); + let d = h.finalize(); + d[..8].try_into().expect("8 of 32 bytes") +} + +pub fn wrap_dek(sync_key: &[u8; 32], dek: &[u8; 32]) -> Vec { + let nonce: [u8; 24] = random(); + let ct = XChaCha20Poly1305::new(sync_key.into()) + .encrypt(XNonce::from_slice(&nonce), Payload { msg: dek, aad: DEK_AAD }) + .expect("in-memory encryption cannot fail"); + [nonce.as_slice(), &ct].concat() +} + +pub fn unwrap_dek(sync_key: &[u8; 32], wrapped: &[u8]) -> Result<[u8; 32], String> { + if wrapped.len() != WRAPPED_LEN { + return Err("The backup's key is damaged.".into()); + } + let (nonce, ct) = wrapped.split_at(24); + let dek = XChaCha20Poly1305::new(sync_key.into()) + .decrypt(XNonce::from_slice(nonce), Payload { msg: ct, aad: DEK_AAD }) + .map_err(|_| "This backup was encrypted with another sync key. Unlock sync with the passphrase it was made under.".to_string())?; + dek.try_into().map_err(|_| "The backup's key is damaged.".to_string()) +} + +/// Re-wrap a data key under a new sync key (after a sync reset on a device +/// that still had the old key). +pub fn rewrap(old: &[u8; 32], new: &[u8; 32], wrapped: &[u8]) -> Result, String> { + Ok(wrap_dek(new, &unwrap_dek(old, wrapped)?)) +} + +fn chunk_nonce(prefix: &[u8; 19], counter: u32, last: bool) -> [u8; 24] { + let mut n = [0u8; 24]; + n[..19].copy_from_slice(prefix); + n[19..23].copy_from_slice(&counter.to_be_bytes()); + n[23] = u8::from(last); + n +} + +/// Read until `buf` is full or the input ends; returns how much was read. +fn fill(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result { + let mut n = 0; + while n < buf.len() { + match r.read(&mut buf[n..])? { + 0 => break, + k => n += k, + } + } + Ok(n) +} + +/// What the server keeps beside an encrypted backup. +#[derive(Debug, Clone)] +pub struct Sealed { + pub key_id: String, + /// base64url (unpadded) of the 72-byte wrapped data key. + pub wrapped_key: String, +} + +pub fn b64(bytes: &[u8]) -> String { + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; + URL_SAFE_NO_PAD.encode(bytes) +} + +pub fn unb64(s: &str) -> Result, String> { + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; + URL_SAFE_NO_PAD.decode(s.trim_end_matches('=')).map_err(|e| e.to_string()) +} + +pub fn encrypt_stream(sync_key: &[u8; 32], mut input: impl Read, mut out: impl Write) -> Result { + let dek: [u8; 32] = random(); + let wrapped = wrap_dek(sync_key, &dek); + let prefix: [u8; 19] = random(); + let mut header = Vec::with_capacity(HEADER_LEN); + header.extend_from_slice(MAGIC); + header.extend_from_slice(&key_id_raw(sync_key)); + header.extend_from_slice(&wrapped); + header.extend_from_slice(&prefix); + out.write_all(&header).map_err(|e| e.to_string())?; + + let cipher = XChaCha20Poly1305::new((&dek).into()); + let mut cur = vec![0u8; CHUNK]; + let mut next = vec![0u8; CHUNK]; + let mut cur_len = fill(&mut input, &mut cur).map_err(|e| e.to_string())?; + let mut counter: u32 = 0; + loop { + // Look one chunk ahead: the last chunk is the one with nothing after it. + let next_len = if cur_len == CHUNK { fill(&mut input, &mut next).map_err(|e| e.to_string())? } else { 0 }; + let last = next_len == 0; + let nonce = chunk_nonce(&prefix, counter, last); + let ct = cipher + .encrypt(XNonce::from_slice(&nonce), Payload { msg: &cur[..cur_len], aad: &header }) + .map_err(|_| "Encryption failed.".to_string())?; + out.write_all(&ct).map_err(|e| e.to_string())?; + if last { + break; + } + counter = counter.checked_add(1).ok_or("The backup is too large to encrypt.")?; + std::mem::swap(&mut cur, &mut next); + cur_len = next_len; + } + out.flush().map_err(|e| e.to_string())?; + Ok(Sealed { key_id: key_id(sync_key), wrapped_key: b64(&wrapped) }) +} + +/// Decrypt a backup. `wrapped_override` is the server's copy of the wrapped +/// key, which may have been re-wrapped under a newer sync key since the file +/// was written. +pub fn decrypt_stream( + sync_key: &[u8; 32], + mut input: impl Read, + mut out: impl Write, + wrapped_override: Option<&[u8]>, +) -> Result<(), String> { + let mut header = [0u8; HEADER_LEN]; + if fill(&mut input, &mut header).map_err(|e| e.to_string())? != HEADER_LEN || &header[..8] != MAGIC { + return Err("This isn't an encrypted Stroke backup.".into()); + } + let wrapped = wrapped_override.unwrap_or(&header[16..16 + WRAPPED_LEN]); + let dek = unwrap_dek(sync_key, wrapped)?; + let prefix: [u8; 19] = header[16 + WRAPPED_LEN..].try_into().expect("19 bytes"); + let cipher = XChaCha20Poly1305::new((&dek).into()); + + let size = CHUNK + TAG; + let mut cur = vec![0u8; size]; + let mut next = vec![0u8; size]; + let mut cur_len = fill(&mut input, &mut cur).map_err(|e| e.to_string())?; + let mut counter: u32 = 0; + loop { + let next_len = if cur_len == size { fill(&mut input, &mut next).map_err(|e| e.to_string())? } else { 0 }; + let last = next_len == 0; + let nonce = chunk_nonce(&prefix, counter, last); + let pt = cipher + .decrypt(XNonce::from_slice(&nonce), Payload { msg: &cur[..cur_len], aad: &header }) + .map_err(|_| "The backup is damaged or incomplete.".to_string())?; + out.write_all(&pt).map_err(|e| e.to_string())?; + if last { + break; + } + counter = counter.checked_add(1).ok_or("The backup is damaged.")?; + std::mem::swap(&mut cur, &mut next); + cur_len = next_len; + } + out.flush().map_err(|e| e.to_string()) +} + +pub fn encrypt_file(sync_key: &[u8; 32], src: &Path, dst: &Path) -> Result { + let input = std::io::BufReader::new(std::fs::File::open(src).map_err(|e| e.to_string())?); + let out = std::io::BufWriter::new(std::fs::File::create(dst).map_err(|e| e.to_string())?); + encrypt_stream(sync_key, input, out) +} + +pub fn is_encrypted(head: &[u8]) -> bool { + head.len() >= 8 && &head[..8] == MAGIC +} + +#[cfg(test)] +mod tests { + use super::*; + + fn round_trip(len: usize) { + let key = [7u8; 32]; + let data: Vec = (0..len).map(|i| (i * 31 % 251) as u8).collect(); + let mut enc = Vec::new(); + let sealed = encrypt_stream(&key, data.as_slice(), &mut enc).unwrap(); + assert_eq!(sealed.key_id, key_id(&key)); + assert!(is_encrypted(&enc)); + let mut dec = Vec::new(); + decrypt_stream(&key, enc.as_slice(), &mut dec, None).unwrap(); + assert_eq!(dec, data, "len {len}"); + } + + #[test] + fn round_trips_at_chunk_edges() { + for len in [0, 1, CHUNK - 1, CHUNK, CHUNK + 1, 3 * CHUNK, 3 * CHUNK + 17] { + round_trip(len); + } + } + + #[test] + fn wrong_key_truncation_and_tampering_fail() { + let key = [1u8; 32]; + let data = vec![9u8; 2 * CHUNK + 5]; + let mut enc = Vec::new(); + encrypt_stream(&key, data.as_slice(), &mut enc).unwrap(); + assert!(decrypt_stream(&[2u8; 32], enc.as_slice(), Vec::new(), None).is_err()); + // Cut off at a chunk boundary: the new last chunk was not sealed as last. + let cut = &enc[..HEADER_LEN + 2 * (CHUNK + TAG)]; + assert!(decrypt_stream(&key, cut, Vec::new(), None).is_err()); + let mut bad = enc.clone(); + let n = bad.len(); + bad[n - 20] ^= 1; + assert!(decrypt_stream(&key, bad.as_slice(), Vec::new(), None).is_err()); + let mut bad_header = enc.clone(); + bad_header[HEADER_LEN - 1] ^= 1; + assert!(decrypt_stream(&key, bad_header.as_slice(), Vec::new(), None).is_err()); + } + + #[test] + fn rewrapped_key_opens_with_the_new_sync_key() { + let (old, new) = ([3u8; 32], [4u8; 32]); + let data = b"CREATE TABLE t (x int);".to_vec(); + let mut enc = Vec::new(); + let sealed = encrypt_stream(&old, data.as_slice(), &mut enc).unwrap(); + let re = rewrap(&old, &new, &unb64(&sealed.wrapped_key).unwrap()).unwrap(); + let mut dec = Vec::new(); + decrypt_stream(&new, enc.as_slice(), &mut dec, Some(&re)).unwrap(); + assert_eq!(dec, data); + assert!(decrypt_stream(&new, enc.as_slice(), Vec::new(), None).is_err()); + } + + /// A fixed vector the browser's decryptor is tested against. + #[test] + fn known_answer_for_the_web_decryptor() { + let key = [0x42u8; 32]; + let dek = [0x11u8; 32]; + let prefix = [0x22u8; 19]; + let wrap_nonce = [0x33u8; 24]; + let wrapped = [ + wrap_nonce.as_slice(), + &XChaCha20Poly1305::new((&key).into()) + .encrypt(XNonce::from_slice(&wrap_nonce), Payload { msg: &dek, aad: DEK_AAD }) + .unwrap(), + ] + .concat(); + let mut header = Vec::new(); + header.extend_from_slice(MAGIC); + header.extend_from_slice(&key_id_raw(&key)); + header.extend_from_slice(&wrapped); + header.extend_from_slice(&prefix); + let ct = XChaCha20Poly1305::new((&dek).into()) + .encrypt(XNonce::from_slice(&chunk_nonce(&prefix, 0, true)), Payload { msg: b"hello", aad: &header }) + .unwrap(); + let file = [header.as_slice(), &ct].concat(); + let mut dec = Vec::new(); + decrypt_stream(&key, file.as_slice(), &mut dec, None).unwrap(); + assert_eq!(dec, b"hello"); + // Printed for the web test: cargo test known_answer -- --nocapture + println!("KAT {}", b64(&file)); + } +} diff --git a/src-tauri/src/cloud_backup.rs b/src-tauri/src/cloud_backup.rs index 3e1e7786..b61437ef 100644 --- a/src-tauri/src/cloud_backup.rs +++ b/src-tauri/src/cloud_backup.rs @@ -167,6 +167,14 @@ pub async fn backup_job_run( let t = token(&app).await?; let base = base_url(); + // Backups are encrypted on this computer with the account's sync key, so + // Stroke Cloud only ever holds ciphertext. Stroke Cloud requires it; an S3 + // bucket gets it whenever sync is set up here. + let sync_key = crate::sync::load_local(&app).await.map(|(k, _)| k); + if job.destination == "stroke" && sync_key.is_none() { + return Err("Backups to Stroke Cloud are end-to-end encrypted with your sync key. Set up or unlock sync (Settings → Sync) on this computer first.".into()); + } + // S3 keys first: without them there is nothing to claim the tick for. let s3 = if job.destination == "s3" { match load_s3(&app, &job.id).await { @@ -180,7 +188,7 @@ pub async fn backup_job_run( let claim = http() .post(format!("{base}/api/backups/runs")) .bearer_auth(&t) - .json(&serde_json::json!({ "job_id": job.id, "slot": slot })); + .json(&serde_json::json!({ "job_id": job.id, "slot": slot, "encrypted": sync_key.is_some() })); let run = match send_json(claim).await { Ok(v) => v, Err(ApiError::Server(code, msg)) if code == "claimed" => return Ok(RunOutcome::skipped(msg)), @@ -192,12 +200,15 @@ pub async fn backup_job_run( } let dir = app.path().app_cache_dir().map_err(|e| e.to_string())?.join("scheduled-backups"); - let result = dump_and_upload(&dir, &job, config, s3, &base, &t, &run_id).await; + let result = dump_and_upload(&dir, &job, config, s3, sync_key, &base, &t, &run_id).await; let body = match &result { Ok(done) => serde_json::json!({ "status": "success", "tables": done.tables, "rows": done.rows, "bytes": done.bytes, "object_key": done.object_key, + "encrypted": done.sealed.is_some(), + "key_id": done.sealed.as_ref().map(|s| s.key_id.clone()), + "wrapped_key": done.sealed.as_ref().map(|s| s.wrapped_key.clone()), }), Err(e) => serde_json::json!({ "status": "failed", "error": e }), }; @@ -216,6 +227,7 @@ struct Done { rows: usize, bytes: u64, object_key: Option, + sealed: Option, } async fn dump_and_upload( @@ -223,6 +235,7 @@ async fn dump_and_upload( job: &JobSpec, config: AnyConnectionConfig, s3: Option, + sync_key: Option<[u8; 32]>, base: &str, token: &str, run_id: &str, @@ -230,6 +243,7 @@ async fn dump_and_upload( std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; let sql_path = dir.join(format!("{run_id}.sql")); let gz_path = dir.join(format!("{run_id}.sql.gz")); + let enc_path = dir.join(format!("{run_id}.sql.gz.stroke")); let cleanup = |paths: &[&PathBuf]| { for p in paths { let _ = std::fs::remove_file(p); @@ -249,20 +263,34 @@ async fn dump_and_upload( } let src = sql_path.clone(); let dst = gz_path.clone(); - let bytes = tokio::task::spawn_blocking(move || gzip(&src, &dst)).await.map_err(|e| e.to_string())??; + let mut bytes = tokio::task::spawn_blocking(move || gzip(&src, &dst)).await.map_err(|e| e.to_string())??; let _ = std::fs::remove_file(&sql_path); + // Encrypt on this computer; what leaves it is ciphertext. + let (file, sealed) = match sync_key { + Some(key) => { + let (src, dst) = (gz_path.clone(), enc_path.clone()); + let sealed = tokio::task::spawn_blocking(move || crate::backup_crypto::encrypt_file(&key, &src, &dst)) + .await + .map_err(|e| e.to_string())??; + let _ = std::fs::remove_file(&gz_path); + bytes = std::fs::metadata(&enc_path).map_err(|e| e.to_string())?.len(); + (enc_path.clone(), Some(sealed)) + } + None => (gz_path.clone(), None), + }; + let object_key = match s3 { - Some(s) => Some(upload_s3(&gz_path, job, &s, bytes).await?), + Some(s) => Some(upload_s3(&file, job, &s, bytes, sealed.is_some()).await?), None => { - upload_stroke(&gz_path, base, token, run_id).await?; + upload_stroke(&file, base, token, run_id).await?; None } }; - Ok(Done { tables: export.table_count, rows: export.row_count, bytes, object_key }) + Ok(Done { tables: export.table_count, rows: export.row_count, bytes, object_key, sealed }) } .await; - cleanup(&[&sql_path, &gz_path]); + cleanup(&[&sql_path, &gz_path, &enc_path]); result } @@ -347,12 +375,13 @@ fn key_safe(s: &str) -> String { /// The user's bucket: one PUT, the payload streamed from disk and left /// unsigned (`UNSIGNED-PAYLOAD`, accepted by S3, R2, MinIO and the rest). -async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64) -> Result { +async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64, encrypted: bool) -> Result { let bucket = job.s3_bucket.as_deref().filter(|b| !b.is_empty()).ok_or("The schedule has no S3 bucket.")?; let region = if s.region.is_empty() { "us-east-1" } else { s.region.as_str() }; let stamp = chrono::Utc::now().format("%Y-%m-%dT%H-%M-%SZ"); let prefix = job.s3_prefix.as_deref().map(key_safe).filter(|p| !p.is_empty()); - let name = format!("{}-{stamp}.sql.gz", key_safe(&job.label).replace('/', "-")); + let ext = if encrypted { "sql.gz.stroke" } else { "sql.gz" }; + let name = format!("{}-{stamp}.{ext}", key_safe(&job.label).replace('/', "-")); let key = match prefix { Some(p) => format!("{p}/{name}"), None => name, @@ -393,7 +422,7 @@ async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64) -> Resu .header("authorization", auth) .header("x-amz-content-sha256", "UNSIGNED-PAYLOAD") .header("x-amz-date", amz_date) - .header("content-type", "application/gzip") + .header("content-type", if encrypted { "application/octet-stream" } else { "application/gzip" }) .header("content-length", bytes.to_string()) .timeout(Duration::from_secs(3600)) .body(body) @@ -410,6 +439,41 @@ async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64) -> Resu Ok(key) } +/// After a sync reset on this device: re-wrap every backup key the old sync +/// key wrapped, so those backups open with the new one. +pub(crate) async fn rewrap_backup_keys(token: &str, old: &[u8; 32], new: &[u8; 32]) -> Result<(), String> { + #[derive(Deserialize)] + struct Key { + id: String, + key_id: String, + wrapped_key: String, + } + #[derive(Deserialize)] + struct Keys { + keys: Vec, + } + let base = base_url(); + let list: Keys = serde_json::from_value( + send_json(http().get(format!("{base}/api/backups/keys")).bearer_auth(token)).await.map_err(api_message)?, + ) + .map_err(|e| e.to_string())?; + let old_id = crate::backup_crypto::key_id(old); + let new_id = crate::backup_crypto::key_id(new); + let mut updates = Vec::new(); + for k in list.keys.into_iter().filter(|k| k.key_id == old_id) { + let wrapped = crate::backup_crypto::unb64(&k.wrapped_key)?; + let re = crate::backup_crypto::rewrap(old, new, &wrapped)?; + updates.push(serde_json::json!({ "id": k.id, "key_id": new_id, "wrapped_key": crate::backup_crypto::b64(&re) })); + } + if updates.is_empty() { + return Ok(()); + } + send_json(http().post(format!("{base}/api/backups/keys")).bearer_auth(token).json(&serde_json::json!({ "keys": updates }))) + .await + .map(|_| ()) + .map_err(api_message) +} + /// Ids are UUIDs from the app, but escape anything else defensively. fn enc(s: &str) -> String { s.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect() diff --git a/src-tauri/src/db/backup.rs b/src-tauri/src/db/backup.rs index 8ee75faa..412d221e 100644 --- a/src-tauri/src/db/backup.rs +++ b/src-tauri/src/db/backup.rs @@ -113,6 +113,9 @@ pub struct BackupFileInfo { pub stroke: bool, /// A cancelled Stroke export: restoring it would load a fraction of the data. pub incomplete: bool, + /// An end-to-end encrypted scheduled backup: opened with the sync key on restore. + #[serde(default)] + pub encrypted: bool, } fn default_true() -> bool { true } @@ -592,7 +595,7 @@ pub async fn backup_import( let rep = Reporter::restore(&app); let script = match (sql, path) { (Some(s), _) => s, - (None, Some(p)) => read_script(&rep, &p).await?, + (None, Some(p)) => read_script(&app, &rep, &p).await?, (None, None) => return Err("Nothing to restore: no file or SQL given".into()), }; match require_conn(&state)? { @@ -611,8 +614,25 @@ pub async fn backup_import( } } -async fn read_script(rep: &Reporter, path: &str) -> Result { - let bytes = tokio::fs::read(path).await.map_err(|e| format!("Could not read {path}: {e}"))?; +async fn read_script(app: &AppHandle, rep: &Reporter, path: &str) -> Result { + let mut bytes = tokio::fs::read(path).await.map_err(|e| format!("Could not read {path}: {e}"))?; + // A scheduled backup: encrypted with the account's sync key, then gzip. + if crate::backup_crypto::is_encrypted(&bytes) { + let (key, _) = crate::sync::load_local(app) + .await + .ok_or("This backup is end-to-end encrypted. Unlock sync (Settings → Sync) with your sync passphrase to restore it.")?; + rep.log("info", "Decrypting the backup on this computer"); + let mut plain = Vec::with_capacity(bytes.len()); + crate::backup_crypto::decrypt_stream(&key, bytes.as_slice(), &mut plain, None)?; + bytes = plain; + } + if bytes.starts_with(&[0x1f, 0x8b]) { + let mut out = Vec::with_capacity(bytes.len() * 4); + flate2::read::GzDecoder::new(bytes.as_slice()) + .read_to_end(&mut out) + .map_err(|e| format!("Could not unzip {path}: {e}"))?; + bytes = out; + } match String::from_utf8(bytes) { Ok(s) => Ok(s), Err(e) => { @@ -633,6 +653,18 @@ pub async fn backup_inspect_file(path: String) -> Result f.read(&mut head).map_err(|e| format!("Could not read {path}: {e}"))? }; head.truncate(n); + if crate::backup_crypto::is_encrypted(&head) { + return Ok(BackupFileInfo { size: meta.len(), engine: None, stroke: true, incomplete: false, encrypted: true }); + } + if head.starts_with(&[0x1f, 0x8b]) { + // Gzip: look at the start of what it holds. + let mut f = File::open(&path).map_err(|e| format!("Could not open {path}: {e}"))?; + let mut inner = vec![0u8; 4096]; + let mut dec = flate2::read::GzDecoder::new(&mut f); + let k = dec.read(&mut inner).unwrap_or(0); + inner.truncate(k); + return Ok(inspect_head(meta.len(), &String::from_utf8_lossy(&inner))); + } Ok(inspect_head(meta.len(), &String::from_utf8_lossy(&head))) } @@ -649,7 +681,7 @@ fn inspect_head(size: u64, head: &str) -> BackupFileInfo { else if head.starts_with("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;") { Some("SQLite".into()) } else { None } }); - BackupFileInfo { size, engine, stroke, incomplete } + BackupFileInfo { size, engine, stroke, incomplete, encrypted: false } } // ── Shared helpers ──────────────────────────────────────────────────────────── diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6a96ba07..9fc1e053 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -10,6 +10,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; mod account; +mod backup_crypto; mod cloud_backup; mod shares; mod nightly; diff --git a/src-tauri/src/sync.rs b/src-tauri/src/sync.rs index 62a4f9ea..4f527135 100644 --- a/src-tauri/src/sync.rs +++ b/src-tauri/src/sync.rs @@ -343,7 +343,7 @@ struct StoredKey { wrapped: String, } -async fn load_local(app: &tauri::AppHandle) -> Option<([u8; 32], String)> { +pub(crate) async fn load_local(app: &tauri::AppHandle) -> Option<([u8; 32], String)> { let raw = crate::secrets::read_all_async(app).await.get(SYNC_KEY_VAULT).cloned()?; let s: StoredKey = serde_json::from_str(&raw).ok()?; let key: [u8; 32] = unb64(&s.key).ok()?.try_into().ok()?; @@ -480,10 +480,19 @@ pub async fn sync_unlock(app: tauri::AppHandle, passphrase: String) -> Result<() pub async fn sync_reset(app: tauri::AppHandle, passphrase: String) -> Result<(), String> { check_passphrase(&passphrase)?; let tok = token(&app).await?; + // The key this device still holds, if any: encrypted backups are re-wrapped + // under the new key, so a reset from here doesn't strand them. + let old = load_local(&app).await.map(|(k, _)| k); let key = random::<32>(); let (wrapped, kdf) = blocking(move || wrap_key(&passphrase, &key)).await??; put_key(&account::base_url(), &tok, &wrapped, &kdf, true).await.map_err(sync_message)?; - store_local(&app, &key, &wrapped).await + store_local(&app, &key, &wrapped).await?; + if let Some(old) = old { + if let Err(e) = crate::cloud_backup::rewrap_backup_keys(&tok, &old, &key).await { + eprintln!("[sync] re-wrapping backup keys failed: {e}"); + } + } + Ok(()) } #[tauri::command] @@ -548,6 +557,17 @@ mod tests { Kdf { alg: "argon2id".into(), salt: b64(&seq::<16>(1)), m: 64, t: 1, p: 1 } } + /// A fixed vector the website's unlock (stroke-web src/lib/backups/crypto.ts) + /// is checked against: passphrase "correct horse battery", key 0x42 * 32. + #[test] + fn known_answer_for_the_web_unlock() { + let kdf = Kdf { alg: "argon2id".into(), salt: b64(&[7u8; 16]), m: 1024, t: 2, p: 1 }; + let kek = derive_kek("correct horse battery", &kdf).unwrap(); + let wrapped = wrap_key_with_nonce(&kek, &[9u8; 24], &[0x42u8; 32]); + assert_eq!(unwrap_key("correct horse battery", &wrapped, &kdf).unwrap(), [0x42u8; 32]); + println!("UNLOCK {} {}", kdf.salt, wrapped); + } + #[test] fn record_round_trip() { let key = random::<32>(); diff --git a/src/lib/api.js b/src/lib/api.js index 300667df..44eab18e 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -1868,7 +1868,7 @@ export async function mcpSetReadonly(readonly) { * @typedef {{ includeSchema?: boolean, includeData?: boolean, includeSequences?: boolean, includeEnums?: boolean, includeFunctions?: boolean, includeTriggers?: boolean, includeViews?: boolean }} BackupOptions * @typedef {{ sql: string, tableCount: number, rowCount: number, cancelled: boolean, path: string | null, bytes: number, failedTables: number, elapsedMs: number }} BackupExportResult * @typedef {{ statementsOk: number, statementsErr: number, statementsSkipped: number, cancelled: boolean, errors: string[], elapsedMs: number }} BackupImportResult - * @typedef {{ size: number, engine: string | null, stroke: boolean, incomplete: boolean }} BackupFileInfo + * @typedef {{ size: number, engine: string | null, stroke: boolean, incomplete: boolean, encrypted?: boolean }} BackupFileInfo */ /** @@ -1924,7 +1924,8 @@ export async function pickBackupSavePath(defaultName) { */ export async function pickBackupFile() { const { open } = await import('@tauri-apps/plugin-dialog') - const path = await open({ multiple: false, filters: [{ name: 'SQL', extensions: ['sql', 'txt'] }] }) + // .gz and .stroke: scheduled backups (gzip, and end-to-end encrypted). + const path = await open({ multiple: false, filters: [{ name: 'SQL backups', extensions: ['sql', 'txt', 'gz', 'stroke'] }] }) return typeof path === 'string' ? path : null } diff --git a/src/lib/components/BackupPage.svelte b/src/lib/components/BackupPage.svelte index 34899f17..591866ff 100644 --- a/src/lib/components/BackupPage.svelte +++ b/src/lib/components/BackupPage.svelte @@ -2,6 +2,7 @@ import { onDestroy } from 'svelte' import FieldSelect from './FieldSelect.svelte' import ScheduledBackups from './ScheduledBackups.svelte' + import LockKeyhole from '@lucide/svelte/icons/lock-keyhole' import CalendarClock from '@lucide/svelte/icons/calendar-clock' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' import { Button } from '$lib/components/ui/button/index.js' @@ -888,6 +889,13 @@

{/if} + {#if importInfo?.encrypted} + + + End-to-end encrypted + A scheduled backup. It opens on this computer with your sync key; unlock sync first if it's locked. + + {/if} {#if importInfo?.incomplete} diff --git a/src/lib/components/ScheduledBackups.svelte b/src/lib/components/ScheduledBackups.svelte index a8f07e27..9d9678f8 100644 --- a/src/lib/components/ScheduledBackups.svelte +++ b/src/lib/components/ScheduledBackups.svelte @@ -4,6 +4,8 @@ // and history live on stroke.click; this device runs the jobs for // connections saved on it (see $lib/stores/scheduled-backups.js). import { onMount } from 'svelte' + import { invoke } from '@tauri-apps/api/core' + import LockKeyhole from '@lucide/svelte/icons/lock-keyhole' import { Cron } from 'croner' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' import { Button } from '$lib/components/ui/button/index.js' @@ -45,8 +47,20 @@ const atLimit = $derived(!!overview && overview.jobs.length >= overview.max_jobs) const usedPct = $derived(overview ? Math.min(100, (overview.used_bytes / overview.quota_bytes) * 100) : 0) + /** The sync key is on this computer: backups can be encrypted before upload. */ + let syncUnlocked = $state(/** @type {boolean|null} */ (null)) + async function checkSync() { + try { + const st = /** @type {{ unlocked: boolean }} */ (await invoke('sync_state')) + syncUnlocked = !!st.unlocked + } catch { + syncUnlocked = false + } + } + onMount(() => { if ($isSignedIn) void refreshBackupJobs() + void checkSync() }) // ── Form ─────────────────────────────────────────────────────────────────── @@ -101,6 +115,7 @@ /** @param {BackupJob|null} job */ async function openForm(job = null) { formError = null + void checkSync() editing = job?.id ?? null destination = job?.destination ?? 'stroke' keep = String(job?.keep ?? 7) @@ -136,6 +151,7 @@ if (!connection || saving) return formError = null if (nextRun.error) { formError = nextRun.error; return } + if (destination === 'stroke' && !syncUnlocked) { formError = 'Set up or unlock sync (Settings → Sync) first: Stroke Cloud backups are encrypted with your sync key.'; return } if (destination === 's3') { if (!s3Bucket.trim()) { formError = 'Name the bucket.'; return } if (!s3HasKeys && (!s3AccessKey.trim() || !s3Secret.trim())) { formError = 'Add the access key and secret.'; return } @@ -400,6 +416,17 @@
{/if} +

+ + {#if destination === 'stroke' || syncUnlocked} + Encrypted on this computer with your sync key. Stroke can't read it, and without your sync passphrase nobody can, you included. + {:else} + Set up sync to encrypt these too; until then the bucket gets the plain .sql.gz. + {/if} +

+ {#if destination === 'stroke' && syncUnlocked === false} +

Stroke Cloud needs sync set up and unlocked on this computer (Settings → Sync).

+ {/if} {#if formError}{/if} From e0c0a401eac8f734ad6cc635054e60e7817c4aa7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:09:44 +0000 Subject: [PATCH 294/317] chore: version 2.19.5 (#294) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe0364ba..b0424578 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.5] - 2026-11-18 + +### Changes +- End-to-end encrypt scheduled backups (#294) + + ## [2.19.4] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 67bad931..321b946b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.4", + "version": "2.19.5", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 6374af4e..f5a2a038 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.4", + "version": "2.19.5", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 496af54992f450631dd7698b44c327249bf0d677 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 20:54:20 +0545 Subject: [PATCH 295/317] Let the DynamoDB console send the API calls it offers (#295) The console and the AI parse CreateTable, UpdateTable, UpdateTimeToLive, DeleteTable and BatchGetItem, but the request gate kept an older, shorter allowlist, so every one of them failed with "operation is not allowed", including the sidebar's drop table. The gate now derives from the same lists. Access levels and read-only mode still decide who may run writes. API calls an agent opens in the editor arrive pretty-printed. --- src-tauri/src/db/dynamodb.rs | 41 ++++++++++++++------------- src/lib/components/StudioShell.svelte | 3 +- src/lib/dynamo-json.js | 21 ++++++++++++++ src/lib/dynamo-json.test.js | 15 +++++++++- 4 files changed, 59 insertions(+), 21 deletions(-) diff --git a/src-tauri/src/db/dynamodb.rs b/src-tauri/src/db/dynamodb.rs index 36d9010f..d1c1b3d8 100644 --- a/src-tauri/src/db/dynamodb.rs +++ b/src-tauri/src/db/dynamodb.rs @@ -277,23 +277,14 @@ pub fn sign( // ── Requests ───────────────────────────────────────────────────────────────── -/// Operations the app may send. Anything else is refused, so the command -/// can't be used to reach other DynamoDB APIs (tables are not created or -/// dropped from here). -const ALLOWED_OPS: &[&str] = &[ - "ListTables", - "DescribeTable", - "DescribeTimeToLive", - "Scan", - "Query", - "GetItem", - "PutItem", - "UpdateItem", - "DeleteItem", - "BatchWriteItem", - "TransactWriteItems", - "ExecuteStatement", -]; +/// Operations the app may send: the API calls the console offers (see +/// [`parse_api_call`]) and PartiQL. Anything else is refused, so the command +/// can't reach other AWS APIs. Who may run which is decided before this, by +/// the access level (`mcp::access`) and the read-only switch. +fn op_allowed(op: &str) -> bool { + op == "ExecuteStatement" + || [API_READS, API_WRITES, API_SCHEMA, API_DANGEROUS].iter().any(|l| l.contains(&op)) +} fn client() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); @@ -336,7 +327,7 @@ fn error_message(status: reqwest::StatusCode, body: &str) -> String { /// One DynamoDB API call. pub async fn request(cfg: &DynamoConfig, op: &str, body: &serde_json::Value) -> Result { - if !ALLOWED_OPS.contains(&op) { + if !op_allowed(op) { return Err(format!("DynamoDB operation \"{op}\" is not allowed")); } let region = resolve_region(cfg); @@ -717,6 +708,18 @@ pub fn shape_from_describe( #[cfg(test)] mod tests { + #[test] + fn every_console_api_call_can_be_sent() { + // The console parses these; the request gate must not refuse them. + for op in [super::API_READS, super::API_WRITES, super::API_SCHEMA, super::API_DANGEROUS].concat() { + let call = super::parse_api_call(&format!("{op} {{}}")).expect("parsed").expect("valid"); + assert!(super::op_allowed(&call.0), "{op} is parsed but refused"); + } + assert!(super::op_allowed("ExecuteStatement")); + assert!(!super::op_allowed("DeleteBackup")); + assert!(!super::op_allowed("CreateGlobalTable")); + } + use super::*; #[test] @@ -808,7 +811,7 @@ mod tests { session_token: None, endpoint: Some("http://127.0.0.1:1".into()), }; - assert!(request(&cfg, "DeleteTable", &serde_json::json!({})).await.unwrap_err().contains("not allowed")); + assert!(request(&cfg, "DeleteBackup", &serde_json::json!({})).await.unwrap_err().contains("not allowed")); } /// Against `dev/nosql` DynamoDB Local on port 8000: diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 863b3fed..1803ebdd 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -1,4 +1,5 @@ + +
+ +
+
+ + {#if dash} + ({ value: String(v), label: v ? `Every ${l}` : 'Auto refresh off' }))} + onchange={(v) => dash && updateDashboard(dash.id, { refreshSec: Number(v) })} + /> + {/if} +
+

+ {dash?.name ?? 'Dashboard'} +

+
+ {#if connName} + + + {connName} + + {/if} + {#if !isMac}{/if} +
+ +
+ {#if !dash} +
+ +

This dashboard was deleted

+
+ {:else if dash.items.length === 0} +
+ +

Nothing on {dash.name} yet

+

Add charts or saved queries from the Dashboard tab; they show up here.

+
+ {:else} +
+ {#each dash.items as item, i (item.id)} + {@const chart = getChart(item.chartId)} + {@const l = live[keyOf(item)]} + {@const view = viewOf(item)} + {@const title = item.query?.name ?? chart?.name ?? 'Missing chart'} + {@const color = REPORT_COLORS[i % REPORT_COLORS.length]} + {@const status = l?.loading && !l?.result ? 'loading' : l?.error ? 'error' : l?.at ? 'ok' : sqlOf(item) ? 'loading' : 'idle'} +
+
+ {#if l?.error} +
+

Query failed

+

{l.error}

+
+ {:else if view?.kpi} +
+ {formatKpi(view.kpi.value)} + {view.kpi.label} +
+ {:else if view?.table} +
+ + + + {#each view.table.columns as c, ci (ci)} + + {/each} + + + + {#each view.table.rows as row, ri (ri)} + + {#each row as cell, ci (ci)} + + {/each} + + {/each} + +
{c}
{cell === null ? 'NULL' : typeof cell === 'number' ? reportNumber(cell) : typeof cell === 'object' ? JSON.stringify(cell) : String(cell)}
+
+ {:else if view?.option} + + {:else if status === 'idle'} +
+ {chart ? 'This chart writes, so it only runs from the editor' : 'This chart was deleted'} +
+ {/if} +
+ +
+
+ + {#if sqlOf(item)} + + {/if} +
+

{title}

+

+ {status === 'ok' ? 'OK' : status === 'error' ? 'Failed' : status === 'loading' ? 'Running' : '·'} +

+
+
+ {/each} +
+ {/if} +
+
diff --git a/src/lib/dashboard-live.js b/src/lib/dashboard-live.js index fcc5a08a..4ef3122d 100644 --- a/src/lib/dashboard-live.js +++ b/src/lib/dashboard-live.js @@ -1,7 +1,7 @@ // Live dashboard cards: a saved chart's query run again, turned into a chart // option, or into one big number when the result is a single value. -import { buildOption } from '$lib/chart-utils.js' +import { buildOption, colType, guessXCol, guessYCol } from '$lib/chart-utils.js' /** * One number to show large: a single row whose only numeric cell is the value @@ -82,5 +82,46 @@ export function cardView(chart, r, isDark) { isDark, noTitle: true, }) - return { kpi: null, option, rows: rows.length } + return { kpi: null, option: compact(option), rows: rows.length } +} + +/** A card has no room for the zoom slider a long result gets in the editor. @param {any} option */ +function compact(option) { + if (!option || !option.dataZoom) return option + const { dataZoom: _, ...rest } = option + return { ...rest, grid: { ...(rest.grid ?? {}), bottom: Math.min(Number(rest.grid?.bottom) || 40, 40) } } +} + +/** How a saved-query card can be drawn. */ +export const QUERY_VIEWS = /** @type {const} */ (['auto', 'bar', 'line', 'area', 'table']) + +/** + * A saved query's result as what its card draws: one value as a number, rows + * as a chart when there is something to plot, otherwise a table. `type` + * forces one ('auto' or none picks): a time column draws a line, anything + * else bars. + * @param {{ columns?: any[], rows?: unknown[][] }} r + * @param {string | undefined} type + * @param {boolean} isDark + * @returns {{ kpi: { value: number, label: string } | null, option: any, table: { columns: string[], rows: unknown[][] } | null, rows: number }} + */ +export function queryView(r, type, isDark) { + const columns = (r?.columns ?? []).map((c) => ({ name: c.name ?? String(c), dataType: c.dataType ?? c.data_type ?? c.type })) + const rows = r?.rows ?? [] + const table = () => ({ kpi: null, option: null, table: { columns: columns.map((c) => c.name), rows: rows.slice(0, 200) }, rows: rows.length }) + const pick = type && type !== 'auto' ? type : null + if (pick === 'table') return table() + const kpi = !pick ? kpiOf(columns, rows) : null + if (kpi) return { kpi, option: null, table: null, rows: rows.length } + const xCol = guessXCol(columns) + const yCol = guessYCol(columns, xCol) + const yIsNumber = rows.length > 0 && rows.slice(0, 20).every((row) => { + const v = row[columns.findIndex((c) => c.name === yCol)] + return v == null || typeof v === 'number' || (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) + }) + if (!xCol || !yCol || xCol === yCol || !yIsNumber) return table() + const xIsTime = colType(columns.find((c) => c.name === xCol) ?? { name: '' }) === 'date' + const chartType = pick ?? (xIsTime ? 'line' : 'bar') + const option = buildOption({ type: chartType, columns, rows: rows.slice(0, 2000), xCol, yCol, isDark, noTitle: true }) + return { kpi: null, option: compact(option), table: null, rows: rows.length } } diff --git a/src/lib/dashboard-live.test.js b/src/lib/dashboard-live.test.js index 0440f8db..5f900f17 100644 --- a/src/lib/dashboard-live.test.js +++ b/src/lib/dashboard-live.test.js @@ -1,6 +1,6 @@ import { describe, it, expect, vi } from 'vitest' -vi.mock('$lib/chart-utils.js', () => ({ buildOption: () => ({ series: [] }) })) -import { kpiOf, formatKpi, agoText, createQueue } from './dashboard-live.js' +vi.mock('$lib/chart-utils.js', async (orig) => ({ ...(await orig()), buildOption: (/** @type {any} */ o) => ({ type: o.type, x: o.xCol, y: o.yCol }) })) +import { kpiOf, formatKpi, agoText, createQueue, queryView } from './dashboard-live.js' describe('kpiOf', () => { it('reads one number, with a label beside it', () => { @@ -30,3 +30,23 @@ describe('createQueue', () => { expect(peak).toBe(2) }) }) + +describe('queryView', () => { + const r = (/** @type {any[]} */ columns, /** @type {unknown[][]} */ rows) => ({ columns, rows }) + it('draws one value as a number', () => { + const v = queryView(r([{ name: 'count' }], [[42]]), 'auto', true) + expect(v.kpi).toEqual({ value: 42, label: 'count' }) + }) + it('draws a time series as a line and categories as bars', () => { + const series = r([{ name: 'day', dataType: 'date' }, { name: 'signups', dataType: 'integer' }], [['2026-11-01', 3], ['2026-11-02', 5]]) + expect(queryView(series, 'auto', true).option).toEqual({ type: 'line', x: 'day', y: 'signups' }) + const cats = r([{ name: 'status', dataType: 'text' }, { name: 'n', dataType: 'bigint' }], [['paid', 3], ['open', 5]]) + expect(queryView(cats, undefined, true).option).toEqual({ type: 'bar', x: 'status', y: 'n' }) + expect(queryView(cats, 'area', true).option).toEqual({ type: 'area', x: 'status', y: 'n' }) + }) + it('falls back to a table when there is nothing to plot', () => { + const v = queryView(r([{ name: 'email', dataType: 'text' }, { name: 'name', dataType: 'text' }], [['a@b.c', 'A']]), 'auto', true) + expect(v.table).toEqual({ columns: ['email', 'name'], rows: [['a@b.c', 'A']] }) + expect(queryView(r([{ name: 'n' }], [[1]]), 'table', true).table?.rows).toEqual([[1]]) + }) +}) diff --git a/src/lib/report-chart.js b/src/lib/report-chart.js new file mode 100644 index 00000000..6cfedc6b --- /dev/null +++ b/src/lib/report-chart.js @@ -0,0 +1,103 @@ +// The dashboard window's chart style: a report on a wall, not an editor. +// Values printed on the bars, the value axis on both sides, no grid lines, a +// dashed line with dots for series over time. Pure: takes the option the +// editor builds (chart-utils buildOption) and returns a restyled copy. + +/** One colour per card, in order. Bright enough to read across a room on a dark wall. */ +export const REPORT_COLORS = ['#00b4ff', '#3cb80c', '#f5b400', '#ff6b6b', '#b07cff', '#2dd4bf', '#ff8a3d'] + +const AXIS = { line: '#3a3a3a', label: '#a8a8a8', value: '#e6e6e6' } + +/** 19815 → "19,815"; fractions keep two places. @param {unknown} v */ +export function reportNumber(v) { + const n = typeof v === 'number' ? v : Number(v) + if (!Number.isFinite(n)) return String(v ?? '') + return n.toLocaleString('en-US', { maximumFractionDigits: Number.isInteger(n) ? 0 : 2 }) +} + +/** @param {any} a */ +const list = (a) => (Array.isArray(a) ? a : a ? [a] : []) + +/** + * @param {any} option an ECharts option from buildOption + * @param {string} color the card's colour + * @returns {any} + */ +export function reportOption(option, color) { + if (!option) return option + const xs = list(option.xAxis) + const ys = list(option.yAxis) + const series = list(option.series) + // Pies, maps, scatter plots and the rest keep their own look, recoloured. + const cartesian = xs.length === 1 && ys.length === 1 && xs[0]?.type === 'category' && series.every((s) => s.type === 'bar' || s.type === 'line') + if (!cartesian) return { ...option, backgroundColor: 'transparent', color: [color, ...REPORT_COLORS.filter((c) => c !== color)] } + + const points = Math.max(0, ...series.map((s) => list(s.data).length)) + const labels = points > 0 && points <= 40 + const axisCommon = { + axisLine: { show: true, lineStyle: { color: AXIS.line } }, + axisTick: { show: false }, + splitLine: { show: false }, + axisLabel: { color: AXIS.label, fontSize: 11, formatter: (/** @type {any} */ v) => reportNumber(v) }, + } + const value = { ...ys[0], ...axisCommon, name: undefined } + const restyled = series.map((s, i) => { + const c = i === 0 ? color : REPORT_COLORS[(REPORT_COLORS.indexOf(color) + i) % REPORT_COLORS.length] + if (s.type === 'bar') { + return { + ...s, + barMaxWidth: 40, + itemStyle: { ...(s.itemStyle ?? {}), color: c, borderRadius: 0 }, + label: { show: labels, position: 'top', color: AXIS.value, fontSize: 12, formatter: (/** @type {any} */ p) => reportNumber(Array.isArray(p.value) ? p.value[1] : p.value) }, + } + } + return { + ...s, + smooth: false, + areaStyle: undefined, + symbol: 'circle', + symbolSize: points > 120 ? 0 : 6, + showSymbol: points <= 120, + itemStyle: { color: c }, + lineStyle: { color: c, width: 1.25, type: 'dashed' }, + label: { show: false }, + } + }) + // The same scale again on the right: an invisible copy of the first series + // drives it, so both sides always read the same numbers. + const mirror = { + ...restyled[0], + name: undefined, + yAxisIndex: 1, + silent: true, + tooltip: { show: false }, + label: { show: false }, + itemStyle: { opacity: 0 }, + lineStyle: { opacity: 0 }, + symbolSize: 0, + emphasis: { disabled: true }, + } + return { + ...option, + backgroundColor: 'transparent', + animationDuration: 400, + grid: { left: 64, right: 64, top: labels ? 36 : 20, bottom: 52, containLabel: false }, + legend: { + show: true, + left: 56, + bottom: 4, + icon: 'rect', + itemWidth: 10, + itemHeight: 10, + textStyle: { color: '#d0d0d0', fontSize: 11 }, + data: restyled.map((s) => s.name).filter(Boolean), + }, + xAxis: [{ ...xs[0], ...axisCommon, axisLabel: { color: AXIS.label, fontSize: 11, hideOverlap: true }, name: undefined }], + yAxis: [ + { ...value, position: 'left' }, + { ...value, position: 'right', alignTicks: true }, + ], + dataZoom: undefined, + series: [...restyled, mirror], + } +} diff --git a/src/lib/report-chart.test.js b/src/lib/report-chart.test.js new file mode 100644 index 00000000..aca76c51 --- /dev/null +++ b/src/lib/report-chart.test.js @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest' +import { reportOption, reportNumber } from './report-chart.js' + +const bars = { + xAxis: { type: 'category', data: ['3206', '3218'] }, + yAxis: { type: 'value' }, + series: [{ type: 'bar', name: 'user_id', data: [11870, 12359] }], + dataZoom: [{ type: 'slider' }], +} + +describe('reportOption', () => { + it('prints values on bars and mirrors the value axis', () => { + const o = reportOption(bars, '#00b4ff') + expect(o.yAxis.map((/** @type {any} */ y) => y.position)).toEqual(['left', 'right']) + expect(o.series[0].label.show).toBe(true) + expect(o.series[0].label.formatter({ value: 19815 })).toBe('19,815') + expect(o.series[0].itemStyle.color).toBe('#00b4ff') + // The right axis is driven by an invisible copy of the first series. + expect(o.series[1]).toMatchObject({ yAxisIndex: 1, silent: true, label: { show: false } }) + expect(o.dataZoom).toBeUndefined() + expect(o.legend.data).toEqual(['user_id']) + }) + it('draws lines dashed with dots, and skips labels on long series', () => { + const data = Array.from({ length: 80 }, (_, i) => i) + const o = reportOption({ ...bars, series: [{ type: 'line', name: 'n', data }] }, '#f5b400') + expect(o.series[0].lineStyle).toMatchObject({ type: 'dashed', color: '#f5b400' }) + expect(o.series[0].symbol).toBe('circle') + expect(o.grid.top).toBe(20) + }) + it('leaves other charts alone apart from colour', () => { + const pie = { series: [{ type: 'pie', data: [] }] } + const o = reportOption(pie, '#3cb80c') + expect(o.series).toBe(pie.series) + expect(o.color[0]).toBe('#3cb80c') + }) + it('formats numbers for a wall', () => { + expect(reportNumber(1234567)).toBe('1,234,567') + expect(reportNumber(3.14159)).toBe('3.14') + expect(reportNumber('x')).toBe('x') + }) +}) diff --git a/src/lib/stores/dashboards.js b/src/lib/stores/dashboards.js index 303d55f7..e32b6c2f 100644 --- a/src/lib/stores/dashboards.js +++ b/src/lib/stores/dashboards.js @@ -6,14 +6,20 @@ import { debounce } from '$lib/utils.js' * @typedef {{ * id: string, * chartId: string | null, - * span: 1 | 2 | 3, + * span: number, * size?: 's' | 'm' | 'l', + * h?: number, + * query?: { sql: string, name: string, type?: string }, * }} DashItem * + * A card shows a saved chart (`chartId`), or a saved query (`query`) drawn as + * a number, a chart or a table. `h` is its height in pixels once resized by + * hand; `size` is the older s/m/l preset it falls back to. + * * @typedef {{ * id: string, * name: string, - * columns: 2 | 3, + * columns: number, * items: DashItem[], * createdAt: number, * refreshSec?: number, @@ -118,6 +124,29 @@ export function addChartToDashboard(dashId, chartId) { )) } +/** + * A saved query as a card: it runs on the dashboard and is drawn by what it + * returns (one value as a number, rows as a chart or a table). + * @param {string} dashId @param {{ sql: string, name: string }} query + */ +export function addQueryToDashboard(dashId, query) { + const itemId = `item-${Date.now()}-${Math.random().toString(36).slice(2, 6)}` + dashboards.update(ds => ds.map(d => + d.id === dashId + ? { ...d, items: [...d.items, { id: itemId, chartId: null, span: 1, query: { sql: query.sql, name: query.name } }] } + : d + )) +} + +/** @param {string} dashId @param {string} itemId @param {Partial} patch */ +export function updateItem(dashId, itemId, patch) { + dashboards.update(ds => ds.map(d => + d.id === dashId + ? { ...d, items: d.items.map(i => i.id === itemId ? { ...i, ...patch } : i) } + : d + )) +} + /** @param {string} dashId @param {string} itemId */ export function removeChartFromDashboard(dashId, itemId) { dashboards.update(ds => ds.map(d => @@ -127,7 +156,7 @@ export function removeChartFromDashboard(dashId, itemId) { )) } -/** @param {string} dashId @param {string} itemId @param {1|2|3} span */ +/** @param {string} dashId @param {string} itemId @param {number} span */ export function setItemSpan(dashId, itemId, span) { dashboards.update(ds => ds.map(d => d.id === dashId From 3443ff1b188a45af5fede4f1a92df7ae74eeb6d8 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 21:30:27 +0545 Subject: [PATCH 301/317] Sync and scheduled backups need paid Pro; clean sync state across accounts (#299) --- src-tauri/src/account.rs | 4 ++ src-tauri/src/sync.rs | 4 ++ src/lib/components/ScheduledBackups.svelte | 6 +-- src/lib/components/SyncSection.svelte | 10 +++++ src/lib/stores/license.js | 9 +++++ src/lib/stores/scheduled-backups.js | 4 +- src/lib/sync/policy.js | 1 + src/lib/sync/runtime.js | 43 +++++++++++++++++++--- 8 files changed, 71 insertions(+), 10 deletions(-) diff --git a/src-tauri/src/account.rs b/src-tauri/src/account.rs index f7d7be4e..a9755472 100644 --- a/src-tauri/src/account.rs +++ b/src-tauri/src/account.rs @@ -697,9 +697,13 @@ pub(crate) async fn load_token(app: &tauri::AppHandle) -> Option { .filter(|t| !t.is_empty()) } +/// A new sign-in also drops any sync key left on this device: it belonged to +/// whoever was signed in before (possibly another account), and this one +/// unlocks sync with its own passphrase. async fn store_token(app: &tauri::AppHandle, token: String) -> Result<(), String> { crate::secrets::update_async(app, move |m| { m.insert(TOKEN_KEY.to_string(), token); + m.remove(crate::sync::SYNC_KEY_VAULT); }) .await } diff --git a/src-tauri/src/sync.rs b/src-tauri/src/sync.rs index 4f527135..6a60819a 100644 --- a/src-tauri/src/sync.rs +++ b/src-tauri/src/sync.rs @@ -326,6 +326,7 @@ fn sync_message(e: ApiError) -> String { "no_sync_key" => KEY_CHANGED.into(), "too_many_records" | "invalid_request" | "invalid_json" => format!("The server rejected the sync request ({code})."), "key_exists" => "Sync is already set up for this account. Unlock it with your passphrase.".into(), + "pro_required" => "pro_required".into(), "invalid_kind" | "invalid_id" => format!("The server rejected a record: {msg}"), "404" | "not_found" => "Sync isn't available on the server yet.".into(), _ => e.user_message(), @@ -418,6 +419,8 @@ pub struct SyncState { pub server_has_key: Option, /// The server's key changed (reset on another device): this device was locked. pub key_changed: bool, + /// The account has no paid Pro: sync isn't part of the trial. + pub pro_required: bool, pub offline: bool, pub error: Option, } @@ -441,6 +444,7 @@ pub async fn sync_state(app: tauri::AppHandle) -> Result { } } Err(ApiError::Network(_)) => s.offline = true, + Err(ApiError::Server(code, _)) if code == "pro_required" => s.pro_required = true, Err(e) => s.error = Some(sync_message(e)), } Ok(s) diff --git a/src/lib/components/ScheduledBackups.svelte b/src/lib/components/ScheduledBackups.svelte index 9d9678f8..37795eae 100644 --- a/src/lib/components/ScheduledBackups.svelte +++ b/src/lib/components/ScheduledBackups.svelte @@ -13,7 +13,7 @@ import * as Dialog from '$lib/components/ui/dialog/index.js' import SegmentedControl from './SegmentedControl.svelte' import { isSignedIn, openManageAccount } from '$lib/stores/account.js' - import { hasPro } from '$lib/stores/license.js' + import { hasPaidPro, isTrialActive } from '$lib/stores/license.js' import { backupOverview, backupLoadError, runningJobId, refreshBackupJobs, saveBackupJob, patchBackupJob, deleteBackupJob, saveS3Keys, s3KeysRegion, describeCron, formatBytes, SCHEDULE_DRIVERS, @@ -233,8 +233,8 @@ {#if !$isSignedIn} {@render message('Sign in for scheduled backups', 'They come with Stroke Pro on your account.')} -{:else if !$hasPro || overview?.pro === false} - {@render message('Scheduled backups are a Pro feature', 'Up to 10 databases, to Stroke Cloud or your own S3.', getPro)} +{:else if !$hasPaidPro || overview?.pro === false} + {@render message('Scheduled backups need Stroke Pro', $isTrialActive ? "The free trial doesn't include them. Up to 10 databases, to Stroke Cloud or your own S3." : 'Up to 10 databases, to Stroke Cloud or your own S3.', getPro)} {:else if !connection} {@render message('Save this connection first', 'Schedules run on saved connections.')} {:else if !supported} diff --git a/src/lib/components/SyncSection.svelte b/src/lib/components/SyncSection.svelte index c2a8ece7..ca937f1c 100644 --- a/src/lib/components/SyncSection.svelte +++ b/src/lib/components/SyncSection.svelte @@ -11,6 +11,9 @@ import LockKeyhole from '@lucide/svelte/icons/lock-keyhole' import CircleAlert from '@lucide/svelte/icons/circle-alert' import RotateCcw from '@lucide/svelte/icons/rotate-ccw' + import ExternalLink from '@lucide/svelte/icons/external-link' + import { isTrialActive } from '$lib/stores/license.js' + import { openManageAccount } from '$lib/stores/account.js' let { sectionLabel = '' } = $props() @@ -120,6 +123,13 @@

Sign in to sync your workspaces, connections and settings across devices.

{:else if s.phase === 'checking'}

Checking sync…

+ {:else if s.phase === 'pro'} +
+

+ Sync needs Stroke Pro{$isTrialActive ? "; the free trial doesn't include it" : ''}. Workspaces, connections and settings on every device, end-to-end encrypted. +

+ +
{:else if s.phase === 'setup'}

Keep workspaces, connections and settings in step on every device, end-to-end encrypted.

diff --git a/src/lib/stores/license.js b/src/lib/stores/license.js index e47705ff..4e7ee75c 100644 --- a/src/lib/stores/license.js +++ b/src/lib/stores/license.js @@ -52,3 +52,12 @@ export const hasPro = derived( licenseStatus, ($s) => $s?.status !== 'TrialExpired', ) + +/** + * Reactive: Pro that was paid for. The trial does not count: sync and + * scheduled backups need this (the server checks it too). + */ +export const hasPaidPro = derived( + licenseStatus, + ($s) => $s?.status === 'Valid', +) diff --git a/src/lib/stores/scheduled-backups.js b/src/lib/stores/scheduled-backups.js index 29a09040..51003c34 100644 --- a/src/lib/stores/scheduled-backups.js +++ b/src/lib/stores/scheduled-backups.js @@ -2,7 +2,7 @@ import { invoke } from '@tauri-apps/api/core' import { writable, get } from 'svelte/store' import { Cron } from 'croner' import { loadSavedConnections } from './connections.js' -import { hasPro } from './license.js' +import { hasPaidPro } from './license.js' import { isSignedIn } from './account.js' /** @@ -150,7 +150,7 @@ let busy = false let lastRefresh = 0 async function tick() { - if (busy || !get(isSignedIn) || !get(hasPro)) return + if (busy || !get(isSignedIn) || !get(hasPaidPro)) return busy = true try { if (Date.now() - lastRefresh > REFRESH_MS || !get(backupOverview)) { diff --git a/src/lib/sync/policy.js b/src/lib/sync/policy.js index 7bb37cce..af6040d3 100644 --- a/src/lib/sync/policy.js +++ b/src/lib/sync/policy.js @@ -36,6 +36,7 @@ export function pickSyncedSettings(s) { export function syncLabel(s, now = Date.now()) { switch (s.phase) { case 'signed-out': return 'Sync off' + case 'pro': return 'Sync needs Pro' case 'checking': return 'Checking sync…' case 'setup': return 'Sync not set up' case 'locked': return 'Sync locked' diff --git a/src/lib/sync/runtime.js b/src/lib/sync/runtime.js index b40c8bd6..d90a57ad 100644 --- a/src/lib/sync/runtime.js +++ b/src/lib/sync/runtime.js @@ -6,6 +6,7 @@ import { invoke } from '@tauri-apps/api/core' import { writable, get } from 'svelte/store' import { account } from '$lib/stores/account.js' +import { hasPaidPro, licenseStatus } from '$lib/stores/license.js' import { workspaces, replaceWorkspaces, DEFAULT_WORKSPACE_ID } from '$lib/stores/workspaces.js' import { loadSavedConnections, upsertConnection, removeConnection, newConnectionId } from '$lib/stores/connections.js' import { loadSettings, updateSettings } from '$lib/stores/settings.js' @@ -148,7 +149,7 @@ const engine = createSyncEngine({ // ── Status ──────────────────────────────────────────────────────────────────── /** - * @typedef {'signed-out' | 'checking' | 'setup' | 'locked' | 'ready' | 'syncing' | 'offline' | 'error'} SyncPhase + * @typedef {'signed-out' | 'checking' | 'pro' | 'setup' | 'locked' | 'ready' | 'syncing' | 'offline' | 'error'} SyncPhase * @typedef {{ phase: SyncPhase, lastSyncedAt: number, items: number, error: string | null, * keyChanged: boolean, undecryptable: number }} SyncStatus */ @@ -184,14 +185,20 @@ export async function refreshSyncState() { setStatus({ phase: 'signed-out', error: null }) return get(syncStatus) } - if (get(syncStatus).phase === 'signed-out') setStatus({ phase: 'checking' }) + // Sync is part of paid Pro, not the trial: no server call to find that out. + if (!get(hasPaidPro)) { + setStatus({ phase: 'pro', error: null }) + return get(syncStatus) + } + if (get(syncStatus).phase === 'signed-out' || get(syncStatus).phase === 'pro') setStatus({ phase: 'checking' }) try { - /** @type {{ signed_in: boolean, unlocked: boolean, server_has_key: boolean | null, key_changed: boolean, offline: boolean, error: string | null }} */ + /** @type {{ signed_in: boolean, unlocked: boolean, server_has_key: boolean | null, key_changed: boolean, pro_required?: boolean, offline: boolean, error: string | null }} */ const st = await invoke('sync_state') if (st.key_changed) resetSyncBookkeeping(localStorage) /** @type {SyncPhase} */ let phase if (!st.signed_in) phase = 'signed-out' + else if (st.pro_required) phase = 'pro' else if (st.unlocked) phase = st.offline ? 'offline' : 'ready' else if (st.server_has_key === false) phase = 'setup' else if (st.server_has_key === true) phase = 'locked' @@ -289,6 +296,10 @@ async function runOnce() { setStatus({ keyChanged: true }) return } + if (msg === 'pro_required') { + setStatus({ phase: 'pro', error: null }) + return + } if (msg === 'rate_limited') { backoffUntil = Date.now() + BACKOFF_MS setStatus({ phase: 'ready', error: 'The server asked Stroke to slow down. Sync resumes in a minute.' }) @@ -365,15 +376,37 @@ export function startSync() { }) } catch { /* no window */ } - // Launch, sign-in and sign-out all arrive through the account store. + // Buying Pro (or losing it) changes what sync can do: ask again. + let wasPaid = /** @type {boolean | null} */ (null) + licenseStatus.subscribe(() => { + const paid = get(hasPaidPro) + if (paid === wasPaid) return + const first = wasPaid === null + wasPaid = paid + if (!first && get(account)?.signed_in) void refreshSyncState().then((st) => { if (st.phase === 'ready') void syncNow() }) + }) + + // Launch, sign-in, sign-out and a switch to another account all arrive + // through the account store. Who is signed in matters, not only whether: + // signing in as someone else must not keep the last account's sync state. let wasSignedIn = /** @type {boolean | null} */ (null) + let wasUser = /** @type {string | null} */ (null) account.subscribe((a) => { if (!a) return const signedIn = !!a.signed_in - if (signedIn === wasSignedIn) return + const user = signedIn ? (a.user?.id ?? a.user?.email ?? '') : null + if (signedIn === wasSignedIn && user === wasUser) return const before = wasSignedIn + const switched = !!before && signedIn && wasUser !== null && user !== wasUser wasSignedIn = signedIn + wasUser = user if (signedIn) { + if (switched) { + clearSyncBookkeeping(localStorage) + try { localStorage.removeItem(LAST_KEY) } catch { /* ignore */ } + } + // Start from nothing known: the phase is the new account's, not the last one's. + setStatus({ phase: 'checking', error: null, keyChanged: false, lastSyncedAt: switched ? 0 : get(syncStatus).lastSyncedAt, items: switched ? 0 : get(syncStatus).items }) lastFocus = Date.now() void syncNow() } else { From 2c148583870e7e66c74412e02e69a06a53ea6986 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 21:30:33 +0545 Subject: [PATCH 302/317] Calmer update check and a lighter views icon (#300) --- src/lib/components/Sidebar.svelte | 4 ++-- src/lib/icon-registry.js | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib/components/Sidebar.svelte b/src/lib/components/Sidebar.svelte index d1be831a..ef76e9d8 100644 --- a/src/lib/components/Sidebar.svelte +++ b/src/lib/components/Sidebar.svelte @@ -101,7 +101,7 @@ /** Settings, on the Labs page. @type {(() => void) | null} */ onopenlabs = null, oncheckupdates = () => {}, - /** A manual update check is running: the button spins. */ + /** A manual update check is running: the button's icon fades in and out. */ checkingUpdate = false, /** An update was found ('available') or downloaded ('ready'): the button becomes a pill (T3). */ updateState = /** @type {'' | 'available' | 'ready'} */ (''), @@ -3236,7 +3236,7 @@ {updateState === 'ready' ? 'Restart' : 'Update'} {:else} - + {/if}
diff --git a/src/lib/icon-registry.js b/src/lib/icon-registry.js index 7db2e34a..44880d06 100644 --- a/src/lib/icon-registry.js +++ b/src/lib/icon-registry.js @@ -154,7 +154,7 @@ import { ArrowRight01Icon, ArrowLeft01Icon, Add01Icon, MinusSignIcon, Search01Icon, Delete02Icon, Logout01Icon, Table01Icon, GridTableIcon, RefreshIcon, Copy01Icon, Loading03Icon, Key01Icon, LinkSquare01Icon, Database01Icon, SourceCodeIcon, TerminalIcon, ChartLineData02Icon, - SparklesIcon, GitBranchIcon, Download04Icon, PlayIcon, EyeIcon, EyeOffIcon, + SparklesIcon, GitBranchIcon, Download04Icon, PlayIcon, ViewIcon, ViewOffSlashIcon, AiBrain01Icon, Alert02Icon, AlertCircleIcon, Shield01Icon, PencilEdit01Icon, BracketsIcon, SquareLock01Icon, DashboardSquare01Icon, HistoryIcon, Clock01Icon, FlashIcon, Settings01Icon, Maximize01Icon, FilterIcon, MoreHorizontalIcon, @@ -194,7 +194,7 @@ export const ICON_MAP = { // A view is an eye everywhere in the app - TabBar picks 'eye' for view tabs, // so the sidebar has to agree. Plain table glyphs made views indistinguishable // from tables at size-3. - 'table-view': { lucide: Eye, huge: EyeIcon }, + 'table-view': { lucide: Eye, huge: ViewIcon }, 'refresh-cw': { lucide: RefreshCw, huge: RefreshIcon }, 'copy': { lucide: Copy, huge: Copy01Icon }, 'copy-plus': { lucide: CopyPlus, huge: Copy01Icon }, @@ -210,8 +210,8 @@ export const ICON_MAP = { 'git-branch': { lucide: GitBranch, huge: GitBranchIcon }, 'download': { lucide: Download, huge: Download04Icon }, 'play': { lucide: Play, huge: PlayIcon }, - 'eye': { lucide: Eye, huge: EyeIcon }, - 'eye-off': { lucide: EyeOff, huge: EyeOffIcon }, + 'eye': { lucide: Eye, huge: ViewIcon }, + 'eye-off': { lucide: EyeOff, huge: ViewOffSlashIcon }, 'bot': { lucide: Bot, huge: AiBrain01Icon }, 'alert-triangle': { lucide: AlertTriangle, huge: Alert02Icon }, 'alert-circle': { lucide: AlertCircle, huge: AlertCircleIcon }, From 7ffaacffdbce9761934fad08dd91d11d0f982075 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:45:29 +0000 Subject: [PATCH 303/317] chore: version 2.19.8 (#297) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d948a9e4..bac31bd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.8] - 2026-11-18 + +### Changes +- Preview a dump and pick its encoding before restoring (#297) + + ## [2.19.7] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index fb4765b1..9a09ad28 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.7", + "version": "2.19.8", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index afd05010..e2be146c 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.7", + "version": "2.19.8", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 63d23c041464f94c911d5430174e70ba9a01df2a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:45:46 +0000 Subject: [PATCH 304/317] chore: version 2.19.9 (#300) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bac31bd9..51b5dbef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.19.9] - 2026-11-18 + +### Changes +- Calmer update check and a lighter views icon (#300) + + ## [2.19.8] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 9a09ad28..2d9a6b8b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.8", + "version": "2.19.9", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e2be146c..f4453935 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.8", + "version": "2.19.9", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 4c240a92cb312fb150e4dec6c19bb134e3c45d13 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 22:10:43 +0545 Subject: [PATCH 305/317] Add a Migrations page and local database servers (#301) Migrations (Tools, palette): Prisma's _prisma_migrations and Drizzle's __drizzle_migrations read from the database, merged with the project's migration files: applied, pending, failed and rolled back, with the error log, the time each took, the SQL, and a flag when a file changed after it ran. Local servers (Tools, palette): Postgres, MySQL, MariaDB, Redis and MongoDB on this computer in any version, on Docker or native (Postgres downloaded per version and checksum-checked; MySQL, MariaDB, Redis and MongoDB from what's installed), plus Homebrew services. Start, stop, change port, logs, delete, and Open connects to it. Busy ports are refused before anything downloads. --- src-tauri/Cargo.lock | 1 + src-tauri/Cargo.toml | 1 + src-tauri/src/db/migrations.rs | 235 +++++ src-tauri/src/db/mod.rs | 1 + src-tauri/src/lib.rs | 13 + src-tauri/src/local_servers.rs | 866 +++++++++++++++++++ src-tauri/src/mac_chrome.rs | 6 +- src/lib/components/AppMenuBar.svelte | 2 + src/lib/components/CommandPalette.svelte | 4 + src/lib/components/LocalServersDialog.svelte | 481 ++++++++++ src/lib/components/MigrationsPage.svelte | 296 +++++++ src/lib/components/StudioShell.svelte | 39 + src/lib/components/TabBar.svelte | 1 + src/lib/icon-registry.js | 4 +- src/lib/local-servers.js | 72 ++ src/lib/migrations.js | 185 ++++ src/lib/migrations.test.js | 76 ++ src/lib/studio-tabs.js | 6 +- 18 files changed, 2286 insertions(+), 3 deletions(-) create mode 100644 src-tauri/src/db/migrations.rs create mode 100644 src-tauri/src/local_servers.rs create mode 100644 src/lib/components/LocalServersDialog.svelte create mode 100644 src/lib/components/MigrationsPage.svelte create mode 100644 src/lib/local-servers.js create mode 100644 src/lib/migrations.js create mode 100644 src/lib/migrations.test.js diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 60680abe..e722a9bc 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -208,6 +208,7 @@ dependencies = [ "sha2 0.10.9", "sqlx", "sysinfo", + "tar", "tauri", "tauri-build", "tauri-plugin-autostart", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 3a004773..f2dd320f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -35,6 +35,7 @@ axum = { version = "0.7", features = ["json", "macros", "ws"] } tower-http = { version = "0.5", features = ["cors"] } sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "postgres", "sqlite", "mysql", "json", "chrono", "uuid", "rust_decimal"] } flate2 = "1" +tar = "0.4" encoding_rs = "0.8" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-webpki-roots", "stream"] } futures = "0.3" diff --git a/src-tauri/src/db/migrations.rs b/src-tauri/src/db/migrations.rs new file mode 100644 index 00000000..3db78839 --- /dev/null +++ b/src-tauri/src/db/migrations.rs @@ -0,0 +1,235 @@ +// The migrations a Prisma or Drizzle project has on disk, for the Migrations +// page. What ran comes from the database (`_prisma_migrations`, +// `__drizzle_migrations`), read by the page with plain SELECTs; this side only +// reads the project folder, so the page can show what's still pending and spot +// a migration whose file changed after it ran. +// +// Prisma: `/migrations//migration.sql`, its checksum the SHA-256 of +// the file (what Prisma stores in `_prisma_migrations.checksum`). +// Drizzle: `/meta/_journal.json` lists the migrations in order ({ idx, +// tag, when }); `/.sql` is the SQL and its SHA-256 is the `hash` +// Drizzle stores in `__drizzle_migrations`. + +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct MigrationFile { + /// Prisma: the folder name. Drizzle: the journal's `tag`. + pub name: String, + pub sql: String, + /// SHA-256 of the SQL, hex. + pub checksum: String, + /// Drizzle's journal `when` (ms); None for Prisma. + pub when: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MigrationProject { + /// prisma | drizzle + pub tool: String, + /// The folder the migrations were read from. + pub dir: String, + pub files: Vec, +} + +const MAX_SQL: usize = 2 * 1024 * 1024; + +fn sha256_hex(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +fn read_sql(path: &Path) -> Option<(String, String)> { + let bytes = std::fs::read(path).ok()?; + let checksum = sha256_hex(&bytes); + let mut sql = String::from_utf8_lossy(&bytes).into_owned(); + if sql.len() > MAX_SQL { + let mut cut = MAX_SQL; + while !sql.is_char_boundary(cut) { + cut -= 1; + } + sql.truncate(cut); + sql.push_str("\n-- (cut: the file is larger than 2 MB)"); + } + Some((sql, checksum)) +} + +/// `migrations/` folders that hold Prisma migrations (a `migration_lock.toml`, +/// or subfolders with a `migration.sql`). +fn is_prisma_dir(dir: &Path) -> bool { + if dir.join("migration_lock.toml").is_file() { + return true; + } + std::fs::read_dir(dir) + .map(|rd| rd.flatten().any(|e| e.path().join("migration.sql").is_file())) + .unwrap_or(false) +} + +/// Drizzle output folders: they hold `meta/_journal.json`. +fn is_drizzle_dir(dir: &Path) -> bool { + dir.join("meta").join("_journal.json").is_file() +} + +/// Folders worth looking into for a project root, a few levels down, skipping +/// the ones that are never migrations. +fn walk(root: &Path, depth: usize, out: &mut Vec) { + out.push(root.to_path_buf()); + if depth == 0 { + return; + } + let Ok(rd) = std::fs::read_dir(root) else { return }; + let mut dirs: Vec = rd + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) + .map(|e| e.path()) + .filter(|p| { + let n = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); + !n.starts_with('.') && !matches!(n, "node_modules" | "target" | "dist" | "build" | ".next" | "coverage" | "vendor") + }) + .collect(); + dirs.sort(); + for d in dirs { + walk(&d, depth - 1, out); + } +} + +/// Find the migrations of `tool` (or either) in a project folder: the folder +/// itself, or one up to four levels below it. +pub fn find(root: &Path, tool: Option<&str>) -> Option<(String, PathBuf)> { + let mut dirs = Vec::new(); + walk(root, 4, &mut dirs); + let want_prisma = tool.is_none_or(|t| t == "prisma"); + let want_drizzle = tool.is_none_or(|t| t == "drizzle"); + // Prefer the shallowest match: a monorepo's app folder over a fixture deep down. + dirs.sort_by_key(|d| d.components().count()); + for d in &dirs { + if want_drizzle && is_drizzle_dir(d) { + return Some(("drizzle".into(), d.clone())); + } + if want_prisma && d.file_name().is_some_and(|n| n == "migrations") && is_prisma_dir(d) { + return Some(("prisma".into(), d.clone())); + } + } + None +} + +pub fn read_prisma(dir: &Path) -> Vec { + let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut names: Vec = rd + .flatten() + .filter(|e| e.path().join("migration.sql").is_file()) + .filter_map(|e| e.file_name().to_str().map(String::from)) + .collect(); + // Prisma applies them in folder-name order (timestamp prefixes). + names.sort(); + names + .into_iter() + .filter_map(|name| { + let (sql, checksum) = read_sql(&dir.join(&name).join("migration.sql"))?; + Some(MigrationFile { name, sql, checksum, when: None }) + }) + .collect() +} + +pub fn read_drizzle(dir: &Path) -> Result, String> { + let journal = std::fs::read_to_string(dir.join("meta").join("_journal.json")) + .map_err(|e| format!("Could not read meta/_journal.json: {e}"))?; + let v: serde_json::Value = serde_json::from_str(&journal).map_err(|e| format!("meta/_journal.json isn't valid JSON: {e}"))?; + let mut entries: Vec<(i64, String, Option)> = v + .get("entries") + .and_then(|e| e.as_array()) + .map(|a| { + a.iter() + .filter_map(|e| { + let tag = e.get("tag")?.as_str()?.to_string(); + let idx = e.get("idx").and_then(|i| i.as_i64()).unwrap_or(0); + Some((idx, tag, e.get("when").and_then(|w| w.as_i64()))) + }) + .collect() + }) + .unwrap_or_default(); + entries.sort_by_key(|e| e.0); + Ok(entries + .into_iter() + .map(|(_, tag, when)| { + let (sql, checksum) = read_sql(&dir.join(format!("{tag}.sql"))).unwrap_or_else(|| ("-- The file for this migration is missing".into(), String::new())); + MigrationFile { name: tag, sql, checksum, when } + }) + .collect()) +} + +/// The migrations in a project folder. `tool` narrows the search when a +/// project has both. +#[tauri::command] +pub async fn migrations_project(dir: String, tool: Option) -> Result { + tokio::task::spawn_blocking(move || { + let root = PathBuf::from(&dir); + if !root.is_dir() { + return Err(format!("{dir} isn't a folder")); + } + let (tool, found) = find(&root, tool.as_deref()).ok_or_else(|| { + "No Prisma or Drizzle migrations in this folder. Pick the project folder (the one with prisma/ or drizzle.config).".to_string() + })?; + let files = if tool == "prisma" { read_prisma(&found) } else { read_drizzle(&found)? }; + Ok(MigrationProject { tool, dir: found.to_string_lossy().into_owned(), files }) + }) + .await + .map_err(|e| e.to_string())? +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("stroke-mig-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn prisma_migrations_are_found_and_read_in_order() { + let root = tmp("prisma"); + let m = root.join("app").join("prisma").join("migrations"); + for (n, sql) in [("20240102_add_posts", "CREATE TABLE posts();"), ("20240101_init", "CREATE TABLE users();")] { + std::fs::create_dir_all(m.join(n)).unwrap(); + std::fs::write(m.join(n).join("migration.sql"), sql).unwrap(); + } + std::fs::write(m.join("migration_lock.toml"), "provider = \"postgresql\"").unwrap(); + let (tool, dir) = find(&root, None).unwrap(); + assert_eq!((tool.as_str(), dir.clone()), ("prisma", m.clone())); + let files = read_prisma(&dir); + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["20240101_init", "20240102_add_posts"]); + assert_eq!(files[0].checksum, sha256_hex(b"CREATE TABLE users();")); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn drizzle_journal_drives_the_order_and_hashes() { + let root = tmp("drizzle"); + let out = root.join("drizzle"); + std::fs::create_dir_all(out.join("meta")).unwrap(); + std::fs::write( + out.join("meta").join("_journal.json"), + r#"{"entries":[{"idx":1,"tag":"0001_posts","when":1700000002000},{"idx":0,"tag":"0000_init","when":1700000001000},{"idx":2,"tag":"0002_gone","when":1700000003000}]}"#, + ) + .unwrap(); + std::fs::write(out.join("0000_init.sql"), "CREATE TABLE users();").unwrap(); + std::fs::write(out.join("0001_posts.sql"), "CREATE TABLE posts();").unwrap(); + // node_modules is never searched. + std::fs::create_dir_all(root.join("node_modules").join("x").join("meta")).unwrap(); + let (tool, dir) = find(&root, None).unwrap(); + assert_eq!((tool.as_str(), dir.clone()), ("drizzle", out.clone())); + let files = read_drizzle(&dir).unwrap(); + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["0000_init", "0001_posts", "0002_gone"]); + assert_eq!(files[1].when, Some(1700000002000)); + assert_eq!(files[0].checksum, sha256_hex(b"CREATE TABLE users();")); + assert!(files[2].checksum.is_empty()); + assert!(find(&root, Some("prisma")).is_none()); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src-tauri/src/db/mod.rs b/src-tauri/src/db/mod.rs index 8bd430d8..b3a800fc 100644 --- a/src-tauri/src/db/mod.rs +++ b/src-tauri/src/db/mod.rs @@ -1,5 +1,6 @@ pub mod admin; pub mod backup; +pub mod migrations; pub mod clickhouse; pub mod parked; pub mod posthog; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9e0dc0fb..401c4bdd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -12,6 +12,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; mod account; mod backup_crypto; mod cloud_backup; +mod local_servers; mod shares; mod nightly; mod agents; @@ -939,6 +940,18 @@ pub fn run() { db::parked::parked_connections, commands::export_parquet, cloud_backup::backup_jobs_list, + db::migrations::migrations_project, + local_servers::local_servers_env, + local_servers::local_servers_list, + local_servers::local_server_create, + local_servers::local_server_start, + local_servers::local_server_stop, + local_servers::local_server_delete, + local_servers::local_server_update, + local_servers::local_server_logs, + local_servers::local_server_free_port, + local_servers::brew_services_list, + local_servers::brew_service_action, cloud_backup::backup_job_save, cloud_backup::backup_job_patch, cloud_backup::backup_job_delete, diff --git a/src-tauri/src/local_servers.rs b/src-tauri/src/local_servers.rs new file mode 100644 index 00000000..f2c2a599 --- /dev/null +++ b/src-tauri/src/local_servers.rs @@ -0,0 +1,866 @@ +// Local database servers: Postgres, MySQL, MariaDB, Redis and MongoDB running +// on this computer, any version side by side, each on its own port. +// +// Two runtimes: +// - Docker: one container per server, `stroke-`, its data in the named +// volume of the same name, published on 127.0.0.1 only. +// - Native: Postgres binaries downloaded per version (theseus-rs builds, the +// checksum checked), or the MySQL / Redis already installed on this computer. +// The data lives in the app's data folder, one directory per server. +// +// Homebrew services (macOS, Linux) are listed beside them, with Start/Stop. +// +// Every server listens on 127.0.0.1 with no password (trust auth, an empty +// root password): it's for development on this machine, like DBngin. + +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use tauri::{AppHandle, Emitter, Manager}; +use tokio::process::Command; + +use crate::proc::quiet; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LocalServer { + pub id: String, + pub name: String, + /// postgres | mysql | mariadb | redis | mongodb + pub engine: String, + /// What was asked for ("16", "8.4"); native Postgres also keeps the exact build. + pub version: String, + pub port: u16, + /// docker | native + pub runtime: String, + #[serde(default)] + pub created_at: i64, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ServerState { + #[serde(flatten)] + pub server: LocalServer, + pub running: bool, + /// Why it can't run right now (Docker not running, binary gone). + pub problem: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Environment { + /// `docker version` answered: the engine is installed and running. + pub docker: bool, + /// The CLI exists but the engine didn't answer (Docker Desktop not started). + pub docker_installed: bool, + pub brew: bool, + /// Engines that can run natively here, besides Postgres (always downloadable). + pub native: Vec, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BrewService { + pub name: String, + pub status: String, + pub running: bool, +} + +// ── Storage ───────────────────────────────────────────────────────────────── + +fn root(app: &AppHandle) -> Result { + let dir = app.path().app_data_dir().map_err(|e| e.to_string())?.join("local-servers"); + std::fs::create_dir_all(&dir).map_err(|e| format!("Could not create {}: {e}", dir.display()))?; + Ok(dir) +} + +fn load(app: &AppHandle) -> Result, String> { + let path = root(app)?.join("servers.json"); + match std::fs::read(&path) { + Ok(b) => serde_json::from_slice(&b).map_err(|e| format!("{} is damaged: {e}", path.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(e) => Err(e.to_string()), + } +} + +fn store(app: &AppHandle, servers: &[LocalServer]) -> Result<(), String> { + let path = root(app)?.join("servers.json"); + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(servers).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &path).map_err(|e| e.to_string()) +} + +fn find(app: &AppHandle, id: &str) -> Result { + load(app)?.into_iter().find(|s| s.id == id).ok_or_else(|| "That server no longer exists".to_string()) +} + +fn server_dir(app: &AppHandle, id: &str) -> Result { + Ok(root(app)?.join(id)) +} + +// ── Engines ───────────────────────────────────────────────────────────────── + +pub const ENGINES: &[&str] = &["postgres", "mysql", "mariadb", "redis", "mongodb"]; + +/// The port each engine listens on inside its container, and by default. +pub fn default_port(engine: &str) -> u16 { + match engine { + "postgres" => 5432, + "mysql" | "mariadb" => 3306, + "redis" => 6379, + "mongodb" => 27017, + _ => 0, + } +} + +fn valid_version(v: &str) -> bool { + !v.is_empty() && v.len() <= 20 && v.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') +} + +/// The Docker image for an engine and version, and its environment. +fn docker_image(engine: &str, version: &str) -> Result<(String, Vec<&'static str>), String> { + if !valid_version(version) { + return Err(format!("\"{version}\" isn't a version")); + } + Ok(match engine { + "postgres" => (format!("postgres:{version}"), vec!["POSTGRES_HOST_AUTH_METHOD=trust"]), + "mysql" => (format!("mysql:{version}"), vec!["MYSQL_ALLOW_EMPTY_PASSWORD=yes"]), + "mariadb" => (format!("mariadb:{version}"), vec!["MARIADB_ALLOW_EMPTY_ROOT_PASSWORD=yes"]), + "redis" => (format!("redis:{version}"), vec![]), + "mongodb" => (format!("mongo:{version}"), vec![]), + _ => return Err(format!("{engine} isn't supported")), + }) +} + +/// Where each engine keeps its data inside the container. +fn docker_data_path(engine: &str) -> &'static str { + match engine { + "postgres" => "/var/lib/postgresql/data", + "mysql" | "mariadb" => "/var/lib/mysql", + "redis" => "/data", + _ => "/data/db", + } +} + +fn container(id: &str) -> String { + format!("stroke-{id}") +} + +// ── Running commands ──────────────────────────────────────────────────────── + +/// Run a program to completion; stdout on success, its stderr as the error. +async fn run(program: &Path, args: &[&str]) -> Result { + let mut cmd = Command::new(program); + cmd.args(args).stdin(std::process::Stdio::null()); + let out = tokio::time::timeout(Duration::from_secs(600), quiet(&mut cmd).output()) + .await + .map_err(|_| format!("{} did not finish in time", program.display()))? + .map_err(|e| format!("Could not run {}: {e}", program.display()))?; + if out.status.success() { + Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) + } else { + let err = String::from_utf8_lossy(&out.stderr).trim().to_string(); + let err = if err.is_empty() { String::from_utf8_lossy(&out.stdout).trim().to_string() } else { err }; + Err(if err.is_empty() { format!("{} exited with {}", program.display(), out.status) } else { err }) + } +} + +/// A program on PATH, or in the usual Homebrew and distro folders the app's +/// PATH misses when it's started from the Dock. +pub fn which(name: &str) -> Option { + let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }; + let mut dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + for extra in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/usr/sbin", "/usr/local/sbin", "/opt/homebrew/sbin"] { + dirs.push(PathBuf::from(extra)); + } + if cfg!(windows) { + dirs.push(PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin")); + } + if cfg!(target_os = "macos") { + // Docker Desktop's per-user install and its app bundle, when the + // /usr/local/bin link wasn't made. + if let Some(home) = std::env::var_os("HOME") { + dirs.push(PathBuf::from(home).join(".docker").join("bin")); + } + dirs.push(PathBuf::from("/Applications/Docker.app/Contents/Resources/bin")); + dirs.push(PathBuf::from("/Applications/OrbStack.app/Contents/MacOS/xbin")); + } + dirs.into_iter().map(|d| d.join(&exe)).find(|p| p.is_file()) +} + +fn docker() -> Result { + which("docker").ok_or_else(|| "Docker isn't installed. Install Docker Desktop, or pick Native.".to_string()) +} + +async fn docker_up() -> bool { + match which("docker") { + Some(d) => run(&d, &["version", "--format", "{{.Server.Version}}"]).await.is_ok(), + None => false, + } +} + +/// Binaries a native server of this engine needs, when they're installed. +fn native_binary(engine: &str) -> Option { + match engine { + "mysql" => which("mysqld"), + "mariadb" => which("mariadbd").or_else(|| which("mysqld")), + "redis" => which("redis-server"), + "mongodb" => which("mongod"), + _ => None, + } +} + +/// Is something already listening on this port? +async fn port_busy(port: u16) -> bool { + tokio::time::timeout(Duration::from_millis(400), tokio::net::TcpStream::connect(("127.0.0.1", port))) + .await + .is_ok_and(|r| r.is_ok()) +} + +/// The first port from `from` up that no server here owns and nothing listens on. +async fn free_port(from: u16, servers: &[LocalServer]) -> u16 { + let mut p = from.max(1024); + while p < u16::MAX && (servers.iter().any(|s| s.port == p) || port_busy(p).await) { + p += 1; + } + p +} + +/// A port to suggest for a new server: the engine's default, or the next free one. +#[tauri::command] +pub async fn local_server_free_port(app: AppHandle, from: u16) -> Result { + Ok(free_port(from, &load(&app)?).await) +} + +/// Wait until the server accepts connections, up to `secs`. +async fn wait_for_port(port: u16, secs: u64) -> bool { + let end = std::time::Instant::now() + Duration::from_secs(secs); + while std::time::Instant::now() < end { + if port_busy(port).await { + return true; + } + tokio::time::sleep(Duration::from_millis(400)).await; + } + false +} + +fn progress(app: &AppHandle, id: &str, message: &str, fraction: Option) { + let _ = app.emit("local-server-progress", serde_json::json!({ "id": id, "message": message, "fraction": fraction })); +} + +// ── Native Postgres builds ────────────────────────────────────────────────── + +fn pg_target() -> Option<&'static str> { + Some(match (std::env::consts::OS, std::env::consts::ARCH) { + ("macos", "aarch64") => "aarch64-apple-darwin", + ("macos", "x86_64") => "x86_64-apple-darwin", + ("linux", "aarch64") => "aarch64-unknown-linux-gnu", + ("linux", "x86_64") => "x86_64-unknown-linux-gnu", + ("windows", "x86_64") => "x86_64-pc-windows-msvc", + ("windows", "aarch64") => "aarch64-pc-windows-msvc", + _ => return None, + }) +} + +/// The newest build of a Postgres major ("16" → "16.11.0"). +async fn pg_release(major: &str) -> Result { + let url = "https://api.github.com/repos/theseus-rs/postgresql-binaries/releases?per_page=100"; + let releases: Vec = reqwest::Client::new() + .get(url) + .header("user-agent", "stroke-desktop") + .header("accept", "application/vnd.github+json") + .send() + .await + .map_err(|e| format!("Could not list Postgres builds: {e}"))? + .error_for_status() + .map_err(|e| format!("Could not list Postgres builds: {e}"))? + .json() + .await + .map_err(|e| e.to_string())?; + let mut tags: Vec> = releases + .iter() + .filter_map(|r| r.get("tag_name")?.as_str()) + .filter(|t| t.split('.').next() == Some(major)) + .map(|t| t.split('.').filter_map(|p| p.parse().ok()).collect()) + .collect(); + tags.sort(); + tags.pop() + .map(|v| v.iter().map(u32::to_string).collect::>().join(".")) + .ok_or_else(|| format!("There's no Postgres {major} build for this computer")) +} + +/// Download and unpack a Postgres build once; servers of that version share it. +async fn pg_install(app: &AppHandle, id: &str, major: &str) -> Result { + let target = pg_target().ok_or("Native Postgres isn't available for this computer. Pick Docker.")?; + let builds = root(app)?.join("builds"); + // A version already unpacked: no network at all. + if let Ok(rd) = std::fs::read_dir(&builds) { + let mut have: Vec = rd.flatten().map(|e| e.path()).filter(|p| { + p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&format!("postgresql-{major}."))) + && pg_bin(p).is_some() + }).collect(); + have.sort(); + if let Some(p) = have.pop() { + return Ok(p); + } + } + progress(app, id, &format!("Finding the newest Postgres {major}"), None); + let version = pg_release(major).await?; + let name = format!("postgresql-{version}-{target}.tar.gz"); + let base = format!("https://github.com/theseus-rs/postgresql-binaries/releases/download/{version}/{name}"); + let client = reqwest::Client::builder().user_agent("stroke-desktop").build().map_err(|e| e.to_string())?; + let sum = client.get(format!("{base}.sha256")).send().await.and_then(|r| r.error_for_status()).map_err(|e| e.to_string())? + .text().await.map_err(|e| e.to_string())?; + let want = sum.split_whitespace().next().unwrap_or_default().to_ascii_lowercase(); + + let mut resp = client.get(&base).send().await.and_then(|r| r.error_for_status()).map_err(|e| format!("Could not download Postgres {version}: {e}"))?; + let total = resp.content_length(); + let mut bytes = Vec::with_capacity(total.unwrap_or(0) as usize); + let mut last = 0.0; + while let Some(chunk) = resp.chunk().await.map_err(|e| format!("Download stopped: {e}"))? { + bytes.extend_from_slice(&chunk); + if let Some(t) = total { + let f = bytes.len() as f64 / t as f64; + if f - last >= 0.02 { + last = f; + progress(app, id, &format!("Downloading Postgres {version}"), Some(f)); + } + } + } + use sha2::Digest; + let got = hex::encode(sha2::Sha256::digest(&bytes)); + if want.len() == 64 && got != want { + return Err("The Postgres download didn't match its checksum. Try again.".into()); + } + progress(app, id, &format!("Unpacking Postgres {version}"), None); + let dest = builds.join(format!("postgresql-{version}")); + let tmp = builds.join(format!(".postgresql-{version}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp); + std::fs::create_dir_all(&tmp).map_err(|e| e.to_string())?; + let unpack = tmp.clone(); + tokio::task::spawn_blocking(move || { + tar::Archive::new(flate2::read::GzDecoder::new(bytes.as_slice())).unpack(&unpack) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| format!("Could not unpack Postgres: {e}"))?; + let _ = std::fs::remove_dir_all(&dest); + std::fs::rename(&tmp, &dest).map_err(|e| e.to_string())?; + pg_bin(&dest).ok_or("The Postgres download has no pg_ctl")?; + Ok(dest) +} + +/// The `bin` folder inside an unpacked build (it sits one folder down). +fn pg_bin(build: &Path) -> Option { + let exe = if cfg!(windows) { "pg_ctl.exe" } else { "pg_ctl" }; + let direct = build.join("bin"); + if direct.join(exe).is_file() { + return Some(direct); + } + std::fs::read_dir(build).ok()?.flatten().map(|e| e.path().join("bin")).find(|b| b.join(exe).is_file()) +} + +fn bin_exe(dir: &Path, name: &str) -> PathBuf { + dir.join(if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }) +} + +/// The build a native Postgres server runs: recorded at create time. +fn pg_build_of(app: &AppHandle, id: &str) -> Result { + let p = std::fs::read_to_string(server_dir(app, id)?.join("build")).map_err(|_| "This server's Postgres build is missing. Delete it and create it again.".to_string())?; + let build = PathBuf::from(p.trim()); + pg_bin(&build).ok_or_else(|| "This server's Postgres build is missing. Delete it and create it again.".to_string()) +} + +// ── Native process bookkeeping ────────────────────────────────────────────── + +fn pid_file(app: &AppHandle, id: &str) -> Result { + Ok(server_dir(app, id)?.join("server.pid")) +} + +fn pid_alive(pid: u32) -> bool { + use sysinfo::{Pid, ProcessesToUpdate, System}; + let mut sys = System::new(); + let p = Pid::from_u32(pid); + sys.refresh_processes(ProcessesToUpdate::Some(&[p]), true); + sys.process(p).is_some() +} + +fn read_pid(app: &AppHandle, id: &str) -> Option { + std::fs::read_to_string(pid_file(app, id).ok()?).ok()?.lines().next()?.trim().parse().ok() +} + +fn kill_pid(pid: u32) { + use sysinfo::{Pid, ProcessesToUpdate, Signal, System}; + let mut sys = System::new(); + let p = Pid::from_u32(pid); + sys.refresh_processes(ProcessesToUpdate::Some(&[p]), true); + if let Some(proc_) = sys.process(p) { + if proc_.kill_with(Signal::Term).is_none() { + proc_.kill(); + } + } +} + +/// Start a long-running server process, detached from the app, its output in `log`. +fn spawn_detached(program: &Path, args: &[String], log: &Path) -> Result { + let out = std::fs::File::create(log).map_err(|e| e.to_string())?; + let err = out.try_clone().map_err(|e| e.to_string())?; + let mut cmd = std::process::Command::new(program); + cmd.args(args).stdin(std::process::Stdio::null()).stdout(out).stderr(err); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + // Its own process group: closing the app or Ctrl+C in a terminal leaves it running. + cmd.process_group(0); + } + crate::proc::quiet_std(&mut cmd); + let child = cmd.spawn().map_err(|e| format!("Could not start {}: {e}", program.display()))?; + Ok(child.id()) +} + +fn log_tail(path: &Path) -> String { + let text = std::fs::read_to_string(path).unwrap_or_default(); + let lines: Vec<&str> = text.lines().rev().take(6).collect(); + lines.into_iter().rev().collect::>().join("\n") +} + +// ── Status ────────────────────────────────────────────────────────────────── + +async fn docker_running(id: &str) -> Result { + let d = docker()?; + match run(&d, &["inspect", "-f", "{{.State.Running}}", &container(id)]).await { + Ok(s) => Ok(s.trim() == "true"), + Err(e) if e.contains("No such") => Err("The container is gone. Delete this server and create it again.".into()), + Err(e) => Err(e), + } +} + +async fn state_of(app: &AppHandle, s: LocalServer, docker_ok: bool) -> ServerState { + let (running, problem) = if s.runtime == "docker" { + if !docker_ok { + (false, Some("Docker isn't running".to_string())) + } else { + match docker_running(&s.id).await { + Ok(r) => (r, None), + Err(e) => (false, Some(e)), + } + } + } else if s.engine == "postgres" { + match pg_build_of(app, &s.id) { + Ok(bin) => { + let data = server_dir(app, &s.id).map(|d| d.join("data")).unwrap_or_default(); + let up = run(&bin_exe(&bin, "pg_ctl"), &["status", "-D", &data.to_string_lossy()]).await.is_ok(); + (up, None) + } + Err(e) => (false, Some(e)), + } + } else { + let up = read_pid(app, &s.id).is_some_and(pid_alive); + let problem = if up || native_binary(&s.engine).is_some() { None } else { Some(format!("{} isn't installed anymore", s.engine)) }; + (up, problem) + }; + ServerState { server: s, running, problem } +} + +// ── Commands ──────────────────────────────────────────────────────────────── + +#[tauri::command] +pub async fn local_servers_env() -> Result { + let docker_installed = which("docker").is_some(); + let docker = docker_installed && docker_up().await; + let native = ["mysql", "mariadb", "redis", "mongodb"] + .into_iter() + .filter(|e| native_binary(e).is_some()) + .map(String::from) + .collect(); + Ok(Environment { docker, docker_installed, brew: which("brew").is_some(), native }) +} + +#[tauri::command] +pub async fn local_servers_list(app: AppHandle) -> Result, String> { + let servers = load(&app)?; + let docker_ok = if servers.iter().any(|s| s.runtime == "docker") { docker_up().await } else { false }; + let mut out = Vec::with_capacity(servers.len()); + for s in servers { + out.push(state_of(&app, s, docker_ok).await); + } + Ok(out) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NewServer { + pub name: String, + pub engine: String, + pub version: String, + pub port: u16, + pub runtime: String, +} + +/// Check a new server before anything is downloaded or created. +fn validate(spec: &NewServer, existing: &[LocalServer]) -> Result<(), String> { + if !ENGINES.contains(&spec.engine.as_str()) { + return Err(format!("{} isn't supported", spec.engine)); + } + if !valid_version(&spec.version) { + return Err(format!("\"{}\" isn't a version", spec.version)); + } + if spec.port < 1024 { + return Err("Pick a port from 1024 up".into()); + } + if spec.name.trim().is_empty() || spec.name.len() > 60 { + return Err("Give the server a name".into()); + } + if let Some(other) = existing.iter().find(|s| s.port == spec.port) { + return Err(format!("{} already uses port {}", other.name, spec.port)); + } + match spec.runtime.as_str() { + "docker" => Ok(()), + "native" if spec.engine == "postgres" => { + if spec.version.contains('.') { + Err("Native Postgres takes a major version, like 16".into()) + } else { + Ok(()) + } + } + "native" if native_binary(&spec.engine).is_some() => Ok(()), + "native" => Err(format!("{} isn't installed on this computer. Pick Docker.", spec.engine)), + other => Err(format!("Unknown runtime {other}")), + } +} + +#[tauri::command] +pub async fn local_server_create(app: AppHandle, spec: NewServer) -> Result { + let mut servers = load(&app)?; + validate(&spec, &servers)?; + // Before any download: a port something else listens on can never start. + if port_busy(spec.port).await { + let free = free_port(spec.port + 1, &servers).await; + return Err(format!("Port {} is in use on this computer. Try {free}.", spec.port)); + } + let id = uuid::Uuid::new_v4().simple().to_string()[..12].to_string(); + let server = LocalServer { + id: id.clone(), + name: spec.name.trim().to_string(), + engine: spec.engine.clone(), + version: spec.version.clone(), + port: spec.port, + runtime: spec.runtime.clone(), + created_at: chrono::Utc::now().timestamp_millis(), + }; + let dir = server_dir(&app, &id)?; + let made = async { + if server.runtime == "docker" { + let d = docker()?; + if !docker_up().await { + return Err("Docker isn't running. Start Docker Desktop and try again.".into()); + } + let (image, env) = docker_image(&server.engine, &server.version)?; + progress(&app, &id, &format!("Pulling {image}"), None); + run(&d, &["pull", &image]).await?; + let publish = format!("127.0.0.1:{}:{}", server.port, default_port(&server.engine)); + let volume = format!("{}:{}", container(&id), docker_data_path(&server.engine)); + let name = container(&id); + let mut args = vec!["create", "--name", &name, "-p", &publish, "-v", &volume, "--label", "app=stroke"]; + for e in &env { + args.push("-e"); + args.push(e); + } + args.push(&image); + progress(&app, &id, "Creating the container", None); + run(&d, &args).await?; + } else { + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let data = dir.join("data"); + match server.engine.as_str() { + "postgres" => { + let build = pg_install(&app, &id, &server.version).await?; + std::fs::write(dir.join("build"), build.to_string_lossy().as_bytes()).map_err(|e| e.to_string())?; + let bin = pg_bin(&build).ok_or("The Postgres build has no bin folder")?; + progress(&app, &id, "Creating the database cluster", None); + run(&bin_exe(&bin, "initdb"), &["-D", &data.to_string_lossy(), "-U", "postgres", "-A", "trust", "-E", "UTF8", "--no-locale"]).await?; + } + "mysql" | "mariadb" => { + let bin = native_binary(&server.engine).ok_or("mysqld isn't installed")?; + std::fs::create_dir_all(&data).map_err(|e| e.to_string())?; + progress(&app, &id, "Creating the data directory", None); + let datadir = format!("--datadir={}", data.to_string_lossy()); + if server.engine == "mariadb" || bin.file_name().is_some_and(|n| n.to_string_lossy().starts_with("mariadb")) { + let install = which("mariadb-install-db").or_else(|| which("mysql_install_db")).ok_or("mariadb-install-db isn't installed")?; + run(&install, &[&datadir, "--auth-root-authentication-method=normal"]).await?; + } else { + run(&bin, &["--initialize-insecure", &datadir]).await?; + } + } + _ => { + std::fs::create_dir_all(&data).map_err(|e| e.to_string())?; + } + } + } + Ok::<(), String>(()) + } + .await; + if let Err(e) = made { + let _ = std::fs::remove_dir_all(&dir); + if server.runtime == "docker" { + if let Ok(d) = docker() { + let _ = run(&d, &["rm", "-f", &container(&id)]).await; + } + } + return Err(e); + } + servers.push(server.clone()); + store(&app, &servers)?; + progress(&app, &id, "Ready", Some(1.0)); + Ok(server) +} + +#[tauri::command] +pub async fn local_server_start(app: AppHandle, id: String) -> Result<(), String> { + let s = find(&app, &id)?; + if port_busy(s.port).await { + if state_of(&app, s.clone(), true).await.running { + return Ok(()); + } + return Err(format!("Something else is using port {}. Stop it, or change this server's port.", s.port)); + } + let dir = server_dir(&app, &id)?; + let data = dir.join("data"); + let log = dir.join("server.log"); + if s.runtime == "docker" { + run(&docker()?, &["start", &container(&id)]).await?; + } else { + match s.engine.as_str() { + "postgres" => { + let bin = pg_build_of(&app, &id)?; + let mut opts = format!("-p {} -c listen_addresses=127.0.0.1", s.port); + if cfg!(unix) { + // No Unix socket: Stroke connects over TCP, two versions can't + // fight over /tmp/.s.PGSQL.5432, and a socket path under + // macOS's "Application Support" can pass the 107-byte limit. + opts.push_str(" -k \"\""); + } + run(&bin_exe(&bin, "pg_ctl"), &["start", "-D", &data.to_string_lossy(), "-l", &log.to_string_lossy(), "-o", &opts, "-w", "-t", "60"]) + .await + .map_err(|e| format!("{e}\n{}", log_tail(&log)))?; + } + "mysql" | "mariadb" => { + let bin = native_binary(&s.engine).ok_or("mysqld isn't installed")?; + let mut args = vec![ + format!("--datadir={}", data.to_string_lossy()), + format!("--port={}", s.port), + "--bind-address=127.0.0.1".to_string(), + format!("--pid-file={}", dir.join("mysqld.pid").to_string_lossy()), + ]; + if cfg!(unix) { + args.push(format!("--socket={}", dir.join("mysql.sock").to_string_lossy())); + } + let pid = spawn_detached(&bin, &args, &log)?; + std::fs::write(pid_file(&app, &id)?, pid.to_string()).map_err(|e| e.to_string())?; + } + "redis" => { + let bin = native_binary("redis").ok_or("redis-server isn't installed")?; + let args = vec![ + "--port".to_string(), s.port.to_string(), + "--bind".to_string(), "127.0.0.1".to_string(), + "--dir".to_string(), data.to_string_lossy().to_string(), + "--save".to_string(), "60 1".to_string(), + ]; + let pid = spawn_detached(&bin, &args, &log)?; + std::fs::write(pid_file(&app, &id)?, pid.to_string()).map_err(|e| e.to_string())?; + } + "mongodb" => { + let bin = native_binary("mongodb").ok_or("mongod isn't installed")?; + let args = vec![ + "--port".to_string(), s.port.to_string(), + "--bind_ip".to_string(), "127.0.0.1".to_string(), + "--dbpath".to_string(), data.to_string_lossy().to_string(), + ]; + let pid = spawn_detached(&bin, &args, &log)?; + std::fs::write(pid_file(&app, &id)?, pid.to_string()).map_err(|e| e.to_string())?; + } + e => return Err(format!("{e} isn't supported")), + } + } + if !wait_for_port(s.port, 60).await { + let tail = if s.runtime == "docker" { + run(&docker()?, &["logs", "--tail", "6", &container(&id)]).await.unwrap_or_default() + } else { + log_tail(&log) + }; + return Err(format!("{} started but isn't answering on port {}.\n{tail}", s.name, s.port).trim().to_string()); + } + Ok(()) +} + + +#[tauri::command] +pub async fn local_server_stop(app: AppHandle, id: String) -> Result<(), String> { + let s = find(&app, &id)?; + if s.runtime == "docker" { + run(&docker()?, &["stop", &container(&id)]).await?; + return Ok(()); + } + if s.engine == "postgres" { + let bin = pg_build_of(&app, &id)?; + let data = server_dir(&app, &id)?.join("data"); + run(&bin_exe(&bin, "pg_ctl"), &["stop", "-D", &data.to_string_lossy(), "-m", "fast", "-w"]).await?; + return Ok(()); + } + if let Some(pid) = read_pid(&app, &id) { + kill_pid(pid); + for _ in 0..50 { + if !pid_alive(pid) { + break; + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + let _ = std::fs::remove_file(pid_file(&app, &id)?); + } + Ok(()) +} + +#[tauri::command] +pub async fn local_server_delete(app: AppHandle, id: String) -> Result<(), String> { + let s = find(&app, &id)?; + let _ = local_server_stop(app.clone(), id.clone()).await; + if s.runtime == "docker" { + if let Ok(d) = docker() { + let name = container(&id); + let _ = run(&d, &["rm", "-f", &name]).await; + let _ = run(&d, &["volume", "rm", &name]).await; + } + } + let _ = std::fs::remove_dir_all(server_dir(&app, &id)?); + let servers: Vec = load(&app)?.into_iter().filter(|x| x.id != id).collect(); + store(&app, &servers) +} + +/// Rename a server or move it to another port (it has to be stopped for a port change). +#[tauri::command] +pub async fn local_server_update(app: AppHandle, id: String, name: Option, port: Option) -> Result { + let mut servers = load(&app)?; + let idx = servers.iter().position(|s| s.id == id).ok_or("That server no longer exists")?; + if let Some(n) = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) { + servers[idx].name = n; + } + if let Some(p) = port.filter(|p| *p != servers[idx].port) { + if p < 1024 { + return Err("Pick a port from 1024 up".into()); + } + if let Some(o) = servers.iter().find(|s| s.port == p) { + return Err(format!("{} already uses port {p}", o.name)); + } + if state_of(&app, servers[idx].clone(), docker_up().await).await.running { + return Err("Stop the server before changing its port".into()); + } + if servers[idx].runtime == "docker" { + // A container's published port is fixed: make a new one on the same volume. + let s = servers[idx].clone(); + let d = docker()?; + let (image, env) = docker_image(&s.engine, &s.version)?; + let name = container(&id); + run(&d, &["rm", "-f", &name]).await?; + let publish = format!("127.0.0.1:{p}:{}", default_port(&s.engine)); + let volume = format!("{name}:{}", docker_data_path(&s.engine)); + let mut args = vec!["create", "--name", &name, "-p", &publish, "-v", &volume, "--label", "app=stroke"]; + for e in &env { + args.push("-e"); + args.push(e); + } + args.push(&image); + run(&d, &args).await?; + } + servers[idx].port = p; + } + store(&app, &servers)?; + Ok(servers[idx].clone()) +} + +/// The last lines a server wrote, for when it won't start. +#[tauri::command] +pub async fn local_server_logs(app: AppHandle, id: String) -> Result { + let s = find(&app, &id)?; + if s.runtime == "docker" { + let d = docker()?; + let mut cmd = Command::new(&d); + cmd.args(["logs", "--tail", "200", &container(&id)]); + let out = quiet(&mut cmd).output().await.map_err(|e| e.to_string())?; + // Server images log to stderr; keep both, in order of the streams. + return Ok(format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr))); + } + let text = std::fs::read_to_string(server_dir(&app, &id)?.join("server.log")).unwrap_or_default(); + let lines: Vec<&str> = text.lines().collect(); + Ok(lines[lines.len().saturating_sub(200)..].join("\n")) +} + +// ── Homebrew ──────────────────────────────────────────────────────────────── + +/// Database services Homebrew knows about (postgresql@16, mysql, redis, ...). +#[tauri::command] +pub async fn brew_services_list() -> Result, String> { + let Some(brew) = which("brew") else { return Ok(Vec::new()) }; + let out = run(&brew, &["services", "list", "--json"]).await?; + let v: Vec = serde_json::from_str(&out).unwrap_or_default(); + Ok(v.into_iter() + .filter_map(|s| { + let name = s.get("name")?.as_str()?.to_string(); + let status = s.get("status").and_then(|x| x.as_str()).unwrap_or("none").to_string(); + let db = ["postgres", "mysql", "mariadb", "redis", "mongo", "valkey", "memcached", "clickhouse"].iter().any(|k| name.contains(k)); + db.then(|| BrewService { running: status == "started", name, status }) + }) + .collect()) +} + +#[tauri::command] +pub async fn brew_service_action(name: String, action: String) -> Result<(), String> { + if !matches!(action.as_str(), "start" | "stop" | "restart") { + return Err(format!("Unknown action {action}")); + } + if !name.chars().all(|c| c.is_ascii_alphanumeric() || "@.-_".contains(c)) { + return Err("That isn't a Homebrew service".into()); + } + let brew = which("brew").ok_or("Homebrew isn't installed")?; + run(&brew, &["services", &action, &name]).await.map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec(engine: &str, version: &str, port: u16, runtime: &str) -> NewServer { + NewServer { name: "t".into(), engine: engine.into(), version: version.into(), port, runtime: runtime.into() } + } + + #[test] + fn new_servers_are_checked_first() { + assert!(validate(&spec("postgres", "16", 5433, "docker"), &[]).is_ok()); + assert!(validate(&spec("postgres", "16", 5433, "native"), &[]).is_ok()); + assert!(validate(&spec("postgres", "16.4", 5433, "native"), &[]).unwrap_err().contains("major")); + assert!(validate(&spec("oracle", "23", 1521, "docker"), &[]).is_err()); + assert!(validate(&spec("redis", "7; rm -rf /", 6380, "docker"), &[]).is_err()); + assert!(validate(&spec("redis", "7", 80, "docker"), &[]).unwrap_err().contains("1024")); + let taken = LocalServer { id: "a".into(), name: "Air".into(), engine: "postgres".into(), version: "16".into(), port: 5432, runtime: "docker".into(), created_at: 0 }; + assert!(validate(&spec("mysql", "8.4", 5432, "docker"), &[taken]).unwrap_err().contains("Air")); + } + + #[test] + fn docker_images_and_ports() { + assert_eq!(docker_image("mongodb", "8.0").unwrap().0, "mongo:8.0"); + assert_eq!(docker_image("postgres", "17").unwrap().1, vec!["POSTGRES_HOST_AUTH_METHOD=trust"]); + assert!(docker_image("mysql", "8.4 --privileged").is_err()); + assert_eq!(default_port("mariadb"), 3306); + assert_eq!(docker_data_path("mongodb"), "/data/db"); + } + + #[test] + fn a_postgres_build_is_found_one_folder_down() { + let dir = std::env::temp_dir().join(format!("stroke-pgbin-{}", std::process::id())); + let bin = dir.join("postgresql-16.0.0-x").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join(if cfg!(windows) { "pg_ctl.exe" } else { "pg_ctl" }), b"").unwrap(); + assert_eq!(pg_bin(&dir), Some(bin)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src-tauri/src/mac_chrome.rs b/src-tauri/src/mac_chrome.rs index c4e8d951..c7d0b891 100644 --- a/src-tauri/src/mac_chrome.rs +++ b/src-tauri/src/mac_chrome.rs @@ -106,10 +106,14 @@ const TOOLS_ITEMS: &[&[Item]] = &[ ], &[ ("dataDiff", "Data Diff", None, true), + ("migrations", "Migrations", None, true), ("dashboard", "Dashboard", None, true), ("logs", "Activity Log", Some("CmdOrCtrl+Shift+L"), true), ], - &[("extensions", "Extensions", Some("CmdOrCtrl+Shift+X"), false)], + &[ + ("localServers", "Local Servers…", None, false), + ("extensions", "Extensions", Some("CmdOrCtrl+Shift+X"), false), + ], ]; const HELP_ITEMS: &[&[Item]] = &[ diff --git a/src/lib/components/AppMenuBar.svelte b/src/lib/components/AppMenuBar.svelte index 6338a664..7b273d78 100644 --- a/src/lib/components/AppMenuBar.svelte +++ b/src/lib/components/AppMenuBar.svelte @@ -136,9 +136,11 @@ {@render item("network", "Schema diagram", "erd", "", !connected)} {@render item("git-compare", "Data diff", "dataDiff", "", !connected)} + {@render item("git-merge", "Migrations", "migrations", "", !connected)} {@render item("layout-dashboard", "Dashboard", "dashboard", "", !connected)} {@render item("history", "Activity log", "logs", "view.logs", !connected)} + {@render item("database", "Local servers", "localServers", "")} {@render item("blocks", "Extensions", "extensions", "view.extensions")} diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index 1386111a..7afc05df 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -112,6 +112,8 @@ onopennotebookfile = () => {}, openschematimeline = () => {}, opendatadiff = () => {}, + openmigrations = () => {}, + openlocalservers = () => {}, /** Live AI schema/db context for the inline quick-ask. */ schemaContext = null, /** Escalate a quick-ask question into the full AI sidebar/chat. @param {string} q */ @@ -275,6 +277,8 @@ { icon: 'archive', label: 'Backup & restore', action: onopenbackup, show: connected && !isKeyValue, value: 'backup restore export import dump data' }, { icon: 'braces', label: 'JSON viewer', action: onopenJsonViewer, show: connected, value: 'open json viewer explorer jsonpath tool' }, { icon: 'git-branch', label: 'Schema timeline', action: openschematimeline, show: connected && !isKeyValue, value: 'schema timeline drift detection history changes diff' }, + { icon: 'database', label: 'Local servers', action: openlocalservers, show: true, value: 'local servers database postgres mysql mariadb redis mongodb docker native homebrew dbngin start stop version' }, + { icon: 'git-merge', label: 'Migrations', action: openmigrations, show: connected && !isKeyValue, value: 'migrations prisma drizzle applied pending failed migrate schema history' }, { icon: 'git-compare', label: 'Data diff', action: opendatadiff, show: connected && !isKeyValue, value: 'data diff compare tables rows changes' }, { icon: 'file-text', label: 'New notebook', action: onopennotebook, show: connected && !isKeyValue, value: 'new sql notebook jupyter cells sql markdown' }, { icon: 'file-text', label: 'Open notebook…', action: onopennotebookfile, show: connected && !isKeyValue, value: 'open notebook file sqlnb' }, diff --git a/src/lib/components/LocalServersDialog.svelte b/src/lib/components/LocalServersDialog.svelte new file mode 100644 index 00000000..2e8d6e29 --- /dev/null +++ b/src/lib/components/LocalServersDialog.svelte @@ -0,0 +1,481 @@ + + + + + {#if view === 'list'} + + Local servers + Database servers running on this computer. + + + + +
+ {#if env && !env.docker} +

+ + {env.dockerInstalled ? "Docker isn't running. Start Docker Desktop for Docker servers; native Postgres works without it." : "Docker isn't installed. Native Postgres works without it."} +

+ {/if} + + {#if servers.length === 0 && !loading} +
+ +
+

No local servers yet

+

Postgres, MySQL, MariaDB, Redis or MongoDB, any version, ready in a minute.

+
+ +
+ {:else} +
    + {#each servers as s (s.id)} + {@const e = engineOf(s.engine)} +
  • + + + + +
    +

    {s.name}

    +

    + {#if s.problem}{s.problem} + {:else}{e.label} {s.version} · {s.running ? `127.0.0.1:${s.port}` : `port ${s.port}`} · {runtimeLabel(s.runtime)}{/if} +

    +
    + + + + + + + + void showLogs(s)}>Logs + void editPort(s)}>Change port… + + void remove(s)}>Delete with its data + + +
  • + {/each} +
+ {/if} + + {#if env?.brew && brew.length} +
+ + {#if brewOpen} +
    + {#each brew as b (b.name)} +
  • + {b.name} + +
  • + {/each} +
+ {/if} +
+ {/if} +
+ {:else if view === 'port' && portFor} + + Change the port of {portFor.name} + Pick a new port for this server. + +
{ e.preventDefault(); void savePort() }}> + + {#if portError}{/if} +
+ + +
+
+ {:else if view === 'logs'} + + {logsFor} logs + The last lines the server wrote. + + +
{logs}
+ {:else} + + New local server + Pick an engine, a version and where it runs. + +
{ e.preventDefault(); void create() }}> +
+ Engine +
+ {#each ENGINES as e (e.id)} + {@const on = fEngine === e.id} + + {/each} +
+
+
+ Version +
+ {#each engine.versions as v (v)} + {@const on = fVersion === v} + + {/each} +
+
+
+ Runs on +
+ {#each [ + { id: /** @type {const} */ ('docker'), Icon: Container, title: 'Docker', ok: dockerOk, + body: dockerOk ? 'A container on 127.0.0.1, its data in a Docker volume.' : env?.dockerInstalled ? 'Start Docker Desktop to use this.' : 'Install Docker Desktop to use this.' }, + { id: /** @type {const} */ ('native'), Icon: Cpu, title: 'Native', ok: nativeOk, + body: fEngine === 'postgres' ? `Downloads Postgres ${fVersion} once, about 30 MB.` : nativeOk ? `Uses the ${engine.label} installed here.` : `${engine.label} isn't installed on this computer.` }, + ] as r (r.id)} + {@const on = fRuntime === r.id} + + {/each} +
+
+
+ + +
+ {#if portTaken}

{portTaken.name} already uses port {portNum}.

{/if} + {#if progress} +
+

{progress.message}

+
+
+
+
+ {/if} + {#if formError}{/if} +
+ + +
+
+ {/if} +
+
diff --git a/src/lib/components/MigrationsPage.svelte b/src/lib/components/MigrationsPage.svelte new file mode 100644 index 00000000..95905437 --- /dev/null +++ b/src/lib/components/MigrationsPage.svelte @@ -0,0 +1,296 @@ + + +
+ +
+ setTool(v)} + /> + {#if list.length} +

+ {c.applied} applied + {#if files}{c.pending} pending{/if} + {#if c.failed}{c.failed} failed{/if} + {#if c.rolledBack}{c.rolledBack} rolled back{/if} +

+ {/if} + + + +
+ +
+
+ {#if projectError} + + {:else if !projectDir && list.length} +

+ Showing what ran. to see pending migrations too. +

+ {/if} + + {#if error} + + {:else if neither} +
+ +
+

No migrations in this database yet

+

Neither _prisma_migrations nor __drizzle_migrations is here. Pick the project folder to see what would run.

+
+ +
+ {:else if !loading && !list.length} +

+ {tool === 'prisma' ? 'No Prisma migrations' : 'No Drizzle migrations'} {rows === null ? 'in this database' : 'yet'}. +

+ {:else} +
    + {#each list as m (m.name)} + {@const st = STATUS[m.status]} + {@const expanded = open === m.name} +
  1. + + {#if expanded} +
    + {#if m.durationMs != null || m.steps != null} +

    + {[m.durationMs != null ? `Took ${took(m.durationMs)}` : '', m.steps != null ? `${m.steps} step${m.steps === 1 ? '' : 's'} applied` : ''].filter(Boolean).join(' · ')} +

    + {/if} + {#if m.logs} +
    {m.logs}
    + {/if} + {#if m.sql} +
    + {#await import('./CodeEditor.svelte') then { default: CodeEditor }} + + {/await} +
    +
    + {#if onopensql} + + {/if} + +
    + {:else if !files} +

    Pick the project folder to see this migration's SQL.

    + {/if} +
    + {/if} +
  2. + {/each} +
+ {/if} +
+
+
diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 1803ebdd..b03354a2 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -229,6 +229,8 @@ findSchemaTimelineTab, createDataDiffTab, findDataDiffTab, + createMigrationsTab, + findMigrationsTab, createLicenseTab, createAiTab, findAiTab, @@ -576,6 +578,7 @@ } } let showDockerModal = $state(false) + let showLocalServers = $state(false) let dockerInitialDb = $state(/** @type {string | null} */ (null)) /** Bottom query-log console visibility. */ let queryLogOpen = $state(false) @@ -1158,6 +1161,7 @@ let searchEverOpened = $state(false) let schemaTimelineEverOpened = $state(false) let dataDiffEverOpened = $state(false) + let migrationsEverOpened = $state(false) let ormSchemaEverOpened = $state(false) /** @type {{ focusEditor: () => void, openQuery?: (content: string) => void } | null} */ let sqlConsoleRef = $state(null) @@ -1459,6 +1463,7 @@ if (activeTab?.kind === 'search') searchEverOpened = true if (activeTab?.kind === 'schema-timeline') schemaTimelineEverOpened = true if (activeTab?.kind === 'data-diff') dataDiffEverOpened = true + if (activeTab?.kind === 'migrations') migrationsEverOpened = true if (activeTab?.kind === 'orm-schema') ormSchemaEverOpened = true }) @@ -1486,6 +1491,7 @@ { kind: 'erd', get: () => erdEverOpened, set: (/** @type {boolean} */ v) => (erdEverOpened = v) }, { kind: 'diagrams', get: () => diagramsEverOpened, set: (/** @type {boolean} */ v) => (diagramsEverOpened = v) }, { kind: 'schema-timeline', get: () => schemaTimelineEverOpened, set: (/** @type {boolean} */ v) => (schemaTimelineEverOpened = v) }, + { kind: 'migrations', get: () => migrationsEverOpened, set: (/** @type {boolean} */ v) => (migrationsEverOpened = v) }, { kind: 'orm-schema', get: () => ormSchemaEverOpened, set: (/** @type {boolean} */ v) => (ormSchemaEverOpened = v) }, ]) /** kind → Date.now() when it last became hidden; absent while active or unmounted. */ @@ -3471,6 +3477,8 @@ let rowSearch = $state('') schema: () => openSchemaTab(), erd: () => openErdTab(), dataDiff: () => openDataDiffTab(), + migrations: () => openMigrationsTab(), + localServers: () => { commandOpen = false; showLocalServers = true }, dashboard: () => openDashboardTab(), logs: () => openLogsTab(), extensions: () => openExtensionsTab(), @@ -4818,6 +4826,10 @@ let rowSearch = $state('') openSingletonTab({ find: findDataDiffTab, create: createDataDiffTab }) } + function openMigrationsTab() { + openSingletonTab({ find: findMigrationsTab, create: createMigrationsTab }) + } + /** * Update the state of a notebook tab (called by NotebookEditor via onupdate). * @param {string} tabId @@ -9920,6 +9932,11 @@ let rowSearch = $state('') dialect={dbType} onopeninsql={(sql) => { if (aiMode) exitAiMode(); void openQueryInEditor(sql) }} /> +{#if showLocalServers} + {#await import('./LocalServersDialog.svelte') then { default: LocalServersDialog }} + void handleDockerConnect(c)} /> + {/await} +{/if} {#if dialogMounted.docker} {#await lazyDialogs.docker() then { default: DockerLaunchModal }} { commandOpen = false; void openNotebookFromFile() }} openschematimeline={() => { commandOpen = false; openSchemaTimelineTab() }} opendatadiff={() => { commandOpen = false; openDataDiffTab() }} + openmigrations={() => { commandOpen = false; openMigrationsTab() }} + openlocalservers={() => { commandOpen = false; showLocalServers = true }} schemaContext={aiSchemaContext} onaskcontinue={handleAskContinue} /> @@ -11094,6 +11113,26 @@ let rowSearch = $state('')
{/if} + + {#if migrationsEverOpened} +
+ + {#await import('./MigrationsPage.svelte')}{:then { default: MigrationsPage }} + openSqlTabWith(sql, title)} + /> + {/await} + +
+ {/if} + {#if dataDiffEverOpened}
diff --git a/src/lib/icon-registry.js b/src/lib/icon-registry.js index 44880d06..b278638b 100644 --- a/src/lib/icon-registry.js +++ b/src/lib/icon-registry.js @@ -93,6 +93,7 @@ import FlaskConical from '@lucide/svelte/icons/flask-conical' import Workflow from '@lucide/svelte/icons/workflow' import Share2 from '@lucide/svelte/icons/share-2' import GitCompare from '@lucide/svelte/icons/git-compare' +import GitMerge from '@lucide/svelte/icons/git-merge' import Blocks from '@lucide/svelte/icons/blocks' import Plug from '@lucide/svelte/icons/plug' import NotebookPen from '@lucide/svelte/icons/notebook-pen' @@ -163,7 +164,7 @@ import { HardDriveIcon, DashboardSquare02Icon, SquareUnlock01Icon, Moon02Icon, RadioIcon, ServerStack01Icon, Settings02Icon, Sun03Icon, ArrowTurnBackwardIcon, Unlink01Icon, WifiConnected01Icon, WifiDisconnected01Icon, TestTubeIcon, WorkflowSquare02Icon, - Share08Icon, GitCompareIcon, PuzzleIcon, PlugSocketIcon, NoteEditIcon, ChartBarLineIcon, GlobalIcon, + Share08Icon, GitCompareIcon, GitMergeIcon, PuzzleIcon, PlugSocketIcon, NoteEditIcon, ChartBarLineIcon, GlobalIcon, InformationCircleIcon, ArrowUpDownIcon, ArrowLeftRightIcon, Bookmark01Icon, BugIcon, UnavailableIcon, Target01Icon, EraserIcon, FileDownloadIcon, FileUploadIcon, File01Icon, FunctionSquareIcon, HashIcon, InfinityIcon, KeyboardIcon, Layers01Icon, LeftToRightListBulletIcon, Link01Icon, @@ -260,6 +261,7 @@ export const ICON_MAP = { 'workflow': { lucide: Workflow, huge: WorkflowSquare02Icon }, 'share-2': { lucide: Share2, huge: Share08Icon }, 'git-compare': { lucide: GitCompare, huge: GitCompareIcon }, + 'git-merge': { lucide: GitMerge, huge: GitMergeIcon }, 'blocks': { lucide: Blocks, huge: PuzzleIcon }, // Database objects (views, routines, types): not 'blocks', which is Extensions. 'shapes': { lucide: Shapes, huge: Shapes01Icon }, diff --git a/src/lib/local-servers.js b/src/lib/local-servers.js new file mode 100644 index 00000000..d7203471 --- /dev/null +++ b/src/lib/local-servers.js @@ -0,0 +1,72 @@ +// Local database servers (src-tauri/src/local_servers.rs): the IPC calls, the +// engines and versions on offer, and the connection a running server opens as. + +import { invoke } from '@tauri-apps/api/core' + +/** + * @typedef {{ id: string, name: string, engine: string, version: string, port: number, runtime: 'docker' | 'native', createdAt: number, running: boolean, problem: string | null }} LocalServer + * @typedef {{ docker: boolean, dockerInstalled: boolean, brew: boolean, native: string[] }} LocalEnv + * @typedef {{ name: string, status: string, running: boolean }} BrewService + */ + +/** Engines, their versions (newest first) and default port. */ +export const ENGINES = [ + { id: 'postgres', label: 'PostgreSQL', short: 'Pg', color: '#336791', port: 5432, versions: ['18', '17', '16', '15', '14', '13'] }, + { id: 'mysql', label: 'MySQL', short: 'My', color: '#f29111', port: 3306, versions: ['9.4', '8.4', '8.0'] }, + { id: 'mariadb', label: 'MariaDB', short: 'Ma', color: '#c0765a', port: 3306, versions: ['11.8', '11.4', '10.11'] }, + { id: 'redis', label: 'Redis', short: 'Re', color: '#d82c20', port: 6379, versions: ['8.2', '7.4', '7.2'] }, + { id: 'mongodb', label: 'MongoDB', short: 'Mo', color: '#47a248', port: 27017, versions: ['8.0', '7.0', '6.0'] }, +] + +/** @param {string} id */ +export const engineOf = (id) => ENGINES.find((e) => e.id === id) ?? ENGINES[0] + +/** + * The first port from the engine's default up that no server here uses. + * @param {string} engine @param {{ port: number }[]} servers + */ +export function nextPort(engine, servers) { + const taken = new Set(servers.map((s) => s.port)) + let p = engineOf(engine).port + while (taken.has(p)) p++ + return p +} + +/** + * The saved connection a server opens as: 127.0.0.1, its port, the engine's + * default superuser and no password (local servers run with trust auth). + * @param {LocalServer} s + */ +export function connectionFor(s) { + const base = { id: `local-${s.id}`, name: s.name, host: '127.0.0.1', port: s.port, environment: /** @type {'dev'} */ ('dev') } + switch (s.engine) { + case 'postgres': return { ...base, type: 'postgres', user: 'postgres', password: '', database: 'postgres' } + case 'mysql': + case 'mariadb': return { ...base, type: s.engine, user: 'root', password: '', database: '' } + case 'redis': return { ...base, type: 'redis', db: 0, password: '' } + default: return { ...base, type: 'mongodb', uri: `mongodb://127.0.0.1:${s.port}/?directConnection=true`, database: '' } + } +} + +/** @returns {Promise} */ +export const localEnv = () => invoke('local_servers_env') +/** @returns {Promise} */ +export const listServers = () => invoke('local_servers_list') +/** @param {{ name: string, engine: string, version: string, port: number, runtime: string }} spec */ +export const createServer = (spec) => invoke('local_server_create', { spec }) +/** @param {string} id */ +export const startServer = (id) => invoke('local_server_start', { id }) +/** @param {string} id */ +export const stopServer = (id) => invoke('local_server_stop', { id }) +/** @param {string} id */ +export const deleteServer = (id) => invoke('local_server_delete', { id }) +/** @param {string} id @param {{ name?: string, port?: number }} patch */ +export const updateServer = (id, patch) => invoke('local_server_update', { id, name: patch.name ?? null, port: patch.port ?? null }) +/** @param {string} id @returns {Promise} */ +export const serverLogs = (id) => invoke('local_server_logs', { id }) +/** @param {number} from @returns {Promise} */ +export const freePort = (from) => invoke('local_server_free_port', { from }) +/** @returns {Promise} */ +export const brewServices = () => invoke('brew_services_list') +/** @param {string} name @param {'start' | 'stop'} action */ +export const brewAction = (name, action) => invoke('brew_service_action', { name, action }) diff --git a/src/lib/migrations.js b/src/lib/migrations.js new file mode 100644 index 00000000..0ae779ce --- /dev/null +++ b/src/lib/migrations.js @@ -0,0 +1,185 @@ +// The Migrations page's logic: what Prisma or Drizzle recorded in the +// database, merged with the migration files in the project folder, as one +// list with a status per migration. Pure: no IPC, no Svelte. +// +// Prisma keeps a row per attempt in `_prisma_migrations`: finished_at set = +// applied; neither finished_at nor rolled_back_at = failed (Prisma refuses to +// go on until it's resolved); rolled_back_at = rolled back. Its checksum is the +// SHA-256 of migration.sql. +// Drizzle keeps `__drizzle_migrations` (id, hash, created_at): a migration +// counts as applied when its journal `when` is at or before the newest +// created_at, which is how Drizzle's migrator decides; `hash` is the SHA-256 +// of the .sql file. Drizzle records no failures (a failed run rolls back). + +/** + * @typedef {'applied' | 'pending' | 'failed' | 'rolled-back'} MigrationStatus + * @typedef {{ + * name: string, + * status: MigrationStatus, + * appliedAt: number | null, + * startedAt: number | null, + * durationMs: number | null, + * steps: number | null, + * logs: string | null, + * sql: string | null, + * changed: boolean, + * missingFile: boolean, + * attempts: number, + * }} Migration + * @typedef {{ name: string, sql: string, checksum: string, when: number | null }} MigrationFile + */ + +/** @param {unknown} v @returns {number | null} */ +export function toMs(v) { + if (v == null || v === '') return null + if (typeof v === 'number') return v < 1e11 ? v * 1000 : v + if (typeof v === 'bigint') return Number(v) + const s = String(v).trim() + if (/^\d+$/.test(s)) return toMs(Number(s)) + // "2024-01-02 10:00:00.123" from MySQL/SQLite has no zone: Prisma writes UTC. + const iso = /^\d{4}-\d{2}-\d{2} \d/.test(s) && !/[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? `${s.replace(' ', 'T')}Z` : s + const t = Date.parse(iso) + return Number.isNaN(t) ? null : t +} + +/** Rows as objects keyed by column name. @param {{ columns?: any[], rows?: unknown[][] }} r */ +export function rowsOf(r) { + const cols = (r?.columns ?? []).map((c) => String(c?.name ?? c)) + return (r?.rows ?? []).map((row) => Object.fromEntries(cols.map((c, i) => [c, row[i]]))) +} + +/** + * @param {Record[]} rows `_prisma_migrations` + * @param {MigrationFile[] | null} files null when no project folder is set + * @returns {Migration[]} + */ +export function mergePrisma(rows, files) { + /** @type {Map[]>} */ + const byName = new Map() + for (const r of rows) { + const n = String(r.migration_name ?? '') + if (!byName.has(n)) byName.set(n, []) + byName.get(n)?.push(r) + } + const fileByName = new Map((files ?? []).map((f) => [f.name, f])) + const names = [...new Set([...byName.keys(), ...fileByName.keys()])].sort() + return names.map((name) => { + const attempts = (byName.get(name) ?? []).slice().sort((a, b) => (toMs(a.started_at) ?? 0) - (toMs(b.started_at) ?? 0)) + const last = attempts[attempts.length - 1] + const file = fileByName.get(name) ?? null + /** @type {MigrationStatus} */ + let status = 'pending' + if (last) status = last.rolled_back_at ? 'rolled-back' : last.finished_at ? 'applied' : 'failed' + const started = last ? toMs(last.started_at) : null + const finished = last ? toMs(last.finished_at) : null + return { + name, + status, + appliedAt: status === 'applied' ? finished : null, + startedAt: started, + durationMs: started != null && finished != null ? Math.max(0, finished - started) : null, + steps: last?.applied_steps_count != null ? Number(last.applied_steps_count) : null, + logs: last?.logs ? String(last.logs) : null, + sql: file?.sql ?? null, + changed: !!(file && last && status === 'applied' && last.checksum && file.checksum && last.checksum !== file.checksum), + missingFile: !!files && !file, + attempts: attempts.length, + } + }) +} + +/** + * @param {Record[]} rows `__drizzle_migrations` + * @param {MigrationFile[] | null} files in journal order; null when no folder is set + * @returns {Migration[]} + */ +export function mergeDrizzle(rows, files) { + const applied = rows + .map((r) => ({ hash: String(r.hash ?? ''), at: toMs(r.created_at) })) + .sort((a, b) => (a.at ?? 0) - (b.at ?? 0)) + const newest = applied.reduce((m, r) => Math.max(m, r.at ?? 0), 0) + const hashes = new Set(applied.map((r) => r.hash)) + if (!files) { + return applied.map((r, i) => ({ + name: `#${i + 1} · ${r.hash.slice(0, 12)}`, + status: /** @type {MigrationStatus} */ ('applied'), + appliedAt: r.at, + startedAt: null, + durationMs: null, + steps: null, + logs: null, + sql: null, + changed: false, + missingFile: false, + attempts: 1, + })) + } + const fileHashes = new Set(files.map((f) => f.checksum)) + /** @type {Migration[]} */ + const out = files.map((f) => { + const byHash = hashes.has(f.checksum) + const byTime = f.when != null && f.when <= newest + const ran = byHash || byTime + const row = applied.find((r) => r.hash === f.checksum) ?? (byTime ? applied.find((r) => r.at === f.when) : undefined) + return { + name: f.name, + status: ran ? 'applied' : 'pending', + appliedAt: ran ? row?.at ?? f.when : null, + startedAt: null, + durationMs: null, + steps: null, + logs: null, + sql: f.sql, + // Ran (by its timestamp) but no row has this file's hash: edited since. + changed: ran && !byHash && !!f.checksum, + missingFile: !f.checksum, + attempts: ran ? 1 : 0, + } + }) + // Rows whose file is no longer in the project. + applied.filter((r) => !fileHashes.has(r.hash) && !files.some((f) => f.when != null && f.when === r.at)).forEach((r) => { + out.push({ name: `Not in the project · ${r.hash.slice(0, 12)}`, status: 'applied', appliedAt: r.at, startedAt: null, durationMs: null, steps: null, logs: null, sql: null, changed: false, missingFile: true, attempts: 1 }) + }) + return out +} + +/** @param {Migration[]} list */ +export function counts(list) { + const c = { applied: 0, pending: 0, failed: 0, rolledBack: 0, changed: 0 } + for (const m of list) { + if (m.status === 'applied') c.applied++ + else if (m.status === 'pending') c.pending++ + else if (m.status === 'failed') c.failed++ + else c.rolledBack++ + if (m.changed) c.changed++ + } + return c +} + +/** + * The SELECTs that read each tool's table, per engine family. Prisma's table + * lives in the connection's schema; Drizzle's in `drizzle` on Postgres. + * @param {'prisma' | 'drizzle'} tool @param {string} family @param {string | null} schema + * @returns {string[]} tried in order until one works + */ +export function migrationQueries(tool, family, schema) { + const q = family === 'mysql' ? (/** @type {string} */ s) => `\`${s.replace(/`/g, '``')}\`` : (/** @type {string} */ s) => `"${s.replace(/"/g, '""')}"` + if (tool === 'prisma') { + const cols = 'id, checksum, finished_at, migration_name, logs, rolled_back_at, started_at, applied_steps_count' + const table = q('_prisma_migrations') + const out = [] + if (family === 'postgres' && schema) out.push(`SELECT ${cols} FROM ${q(schema)}.${table} ORDER BY started_at`) + out.push(`SELECT ${cols} FROM ${table} ORDER BY started_at`) + return out + } + const table = q('__drizzle_migrations') + const out = [] + if (family === 'postgres') out.push(`SELECT id, hash, created_at FROM ${q('drizzle')}.${table} ORDER BY created_at`) + out.push(`SELECT id, hash, created_at FROM ${table} ORDER BY created_at`) + return out +} + +/** Whether an error just means "this table isn't there". @param {unknown} e */ +export function isMissingTable(e) { + return /does not exist|doesn't exist|no such table|not found|unknown table|invalid object name/i.test(String(e)) +} diff --git a/src/lib/migrations.test.js b/src/lib/migrations.test.js new file mode 100644 index 00000000..a66e829d --- /dev/null +++ b/src/lib/migrations.test.js @@ -0,0 +1,76 @@ +import { describe, it, expect } from 'vitest' +import { mergePrisma, mergeDrizzle, counts, toMs, migrationQueries, isMissingTable, rowsOf } from './migrations.js' + +const file = (name, checksum, when = null) => ({ name, sql: `-- ${name}`, checksum, when }) + +describe('mergePrisma', () => { + const rows = [ + { migration_name: '20240101_init', checksum: 'aaa', started_at: '2024-01-01T00:00:00Z', finished_at: '2024-01-01T00:00:02Z', rolled_back_at: null, logs: null, applied_steps_count: 1 }, + { migration_name: '20240102_posts', checksum: 'bbb', started_at: '2024-01-02T00:00:00Z', finished_at: null, rolled_back_at: null, logs: 'relation "users" does not exist', applied_steps_count: 0 }, + { migration_name: '20240103_tags', checksum: 'ccc', started_at: '2024-01-03T00:00:00Z', finished_at: null, rolled_back_at: '2024-01-03T01:00:00Z', logs: null, applied_steps_count: 0 }, + ] + it('reads applied, failed and rolled back runs, and pending files', () => { + const list = mergePrisma(rows, [file('20240101_init', 'aaa'), file('20240102_posts', 'bbb'), file('20240103_tags', 'ccc'), file('20240104_likes', 'ddd')]) + expect(list.map((m) => [m.name, m.status])).toEqual([ + ['20240101_init', 'applied'], ['20240102_posts', 'failed'], ['20240103_tags', 'rolled-back'], ['20240104_likes', 'pending'], + ]) + expect(list[0].durationMs).toBe(2000) + expect(list[1].logs).toContain('does not exist') + expect(counts(list)).toEqual({ applied: 1, pending: 1, failed: 1, rolledBack: 1, changed: 0 }) + }) + it('flags a file edited after it ran, and rows with no file', () => { + const list = mergePrisma(rows.slice(0, 1), [file('20240101_init', 'zzz')]) + expect(list[0].changed).toBe(true) + expect(mergePrisma(rows.slice(0, 1), []).at(0)?.missingFile).toBe(true) + // No folder: nothing is "missing". + expect(mergePrisma(rows.slice(0, 1), null).at(0)?.missingFile).toBe(false) + }) + it('a retry that succeeded counts as applied', () => { + const retry = { ...rows[1], started_at: '2024-01-02T02:00:00Z', finished_at: '2024-01-02T02:00:01Z', logs: null } + const [m] = mergePrisma([rows[1], retry], null) + expect(m.status).toBe('applied') + expect(m.attempts).toBe(2) + }) +}) + +describe('mergeDrizzle', () => { + const rows = [{ id: 1, hash: 'h0', created_at: '1700000001000' }, { id: 2, hash: 'h1', created_at: 1700000002000 }] + it('applied up to the newest created_at, pending after', () => { + const list = mergeDrizzle(rows, [file('0000_init', 'h0', 1700000001000), file('0001_posts', 'h1', 1700000002000), file('0002_tags', 'h2', 1700000003000)]) + expect(list.map((m) => [m.name, m.status])).toEqual([['0000_init', 'applied'], ['0001_posts', 'applied'], ['0002_tags', 'pending']]) + expect(list[1].appliedAt).toBe(1700000002000) + }) + it('flags an edited file and rows the project no longer has', () => { + const list = mergeDrizzle(rows, [file('0000_init', 'edited', 1700000001000)]) + expect(list[0]).toMatchObject({ status: 'applied', changed: true }) + expect(list.at(-1)).toMatchObject({ missingFile: true, status: 'applied' }) + }) + it('lists the rows alone when no folder is set', () => { + const list = mergeDrizzle(rows, null) + expect(list).toHaveLength(2) + expect(list.every((m) => m.status === 'applied')).toBe(true) + }) +}) + +describe('helpers', () => { + it('reads timestamps the way each engine returns them', () => { + expect(toMs('2024-01-01 00:00:00')).toBe(Date.UTC(2024, 0, 1)) + expect(toMs(1700000000)).toBe(1700000000000) + expect(toMs('1700000000000')).toBe(1700000000000) + expect(toMs(null)).toBeNull() + }) + it('quotes per engine and tries the schema first', () => { + expect(migrationQueries('prisma', 'postgres', 'app')[0]).toContain('FROM "app"."_prisma_migrations"') + expect(migrationQueries('prisma', 'mysql', null)[0]).toContain('FROM `_prisma_migrations`') + expect(migrationQueries('drizzle', 'postgres', null)[0]).toContain('"drizzle"."__drizzle_migrations"') + expect(migrationQueries('drizzle', 'sqlite', null)).toHaveLength(1) + }) + it('knows a missing table from a real error', () => { + expect(isMissingTable('relation "_prisma_migrations" does not exist')).toBe(true) + expect(isMissingTable('no such table: __drizzle_migrations')).toBe(true) + expect(isMissingTable('permission denied')).toBe(false) + }) + it('turns a result into objects', () => { + expect(rowsOf({ columns: [{ name: 'a' }, { name: 'b' }], rows: [[1, 2]] })).toEqual([{ a: 1, b: 2 }]) + }) +}) diff --git a/src/lib/studio-tabs.js b/src/lib/studio-tabs.js index 312cb946..9ee37320 100644 --- a/src/lib/studio-tabs.js +++ b/src/lib/studio-tabs.js @@ -1,4 +1,4 @@ -/** @typedef {'table' | 'sql' | 'ddl' | 'welcome' | 'ai' | 'schema' | 'orm' | 'security' | 'logs' | 'extensions' | 'extension-detail' | 'backup' | 'json' | 'charts' | 'dashboard' | 'erd' | 'reltree' | 'diagrams' | 'search' | 'notebook' | 'schema-timeline' | 'data-diff' | 'insights' | 'objects' | 'redis' | 'dynamodb' | 'docs' | 'license' | 'orm-schema' | 'map' | 'advisor' | 'golf' | 'terminal' | 'shortcuts' | 'shares'} StudioTabKind */ +/** @typedef {'table' | 'sql' | 'ddl' | 'welcome' | 'ai' | 'schema' | 'orm' | 'security' | 'logs' | 'extensions' | 'extension-detail' | 'backup' | 'json' | 'charts' | 'dashboard' | 'erd' | 'reltree' | 'diagrams' | 'search' | 'notebook' | 'schema-timeline' | 'data-diff' | 'migrations' | 'insights' | 'objects' | 'redis' | 'dynamodb' | 'docs' | 'license' | 'orm-schema' | 'map' | 'advisor' | 'golf' | 'terminal' | 'shortcuts' | 'shares'} StudioTabKind */ import { loadDefaultPageSize } from '$lib/table-query.js' @@ -233,6 +233,7 @@ const SINGLETON_TAB_TITLES = { search: 'Find in database', 'schema-timeline': 'Schema timeline', 'data-diff': 'Data diff', + migrations: 'Migrations', golf: 'VACUUM', terminal: 'Terminal', shortcuts: 'Keyboard shortcuts', @@ -281,6 +282,7 @@ export const createLicenseTab = () => createKindTab('license') export const createSearchTab = () => createKindTab('search') export const createSchemaTimelineTab = () => createKindTab('schema-timeline') export const createDataDiffTab = () => createKindTab('data-diff') +export const createMigrationsTab = () => createKindTab('migrations') /** The connection's own CLI (psql, mysql, sqlite3...) in a real terminal. */ export const createTerminalTab = () => createKindTab('terminal') /** Every shortcut, searchable and remappable. */ @@ -345,6 +347,8 @@ export const findSearchTab = (tabs) => findTabByKind(tabs, 'search') export const findSchemaTimelineTab = (tabs) => findTabByKind(tabs, 'schema-timeline') /** @type {(tabs: StudioTab[]) => StudioTab | null} */ export const findDataDiffTab = (tabs) => findTabByKind(tabs, 'data-diff') +/** @param {StudioTab[]} tabs */ +export const findMigrationsTab = (tabs) => findTabByKind(tabs, 'migrations') /** @param {string} extensionId @param {string} name */ export function createExtensionDetailTab(extensionId, name) { From dc572e3c81598b8535ab3e54526c1fe9fa964b7b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:25:56 +0000 Subject: [PATCH 306/317] chore: version 2.20.0 (#301) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51b5dbef..440587f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.20.0] - 2026-11-18 + +### Changes +- Add a Migrations page and local database servers (#301) + + ## [2.19.9] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 2d9a6b8b..63069523 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.19.9", + "version": "2.20.0", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f4453935..8dab969f 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.19.9", + "version": "2.20.0", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 6ef91bb238a6b28ca8306f19f4066b6e397afbcf Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 22:12:45 +0545 Subject: [PATCH 307/317] Tell Supabase users to sign in again for project creation (#302) --- src-tauri/src/providers/supabase.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src-tauri/src/providers/supabase.rs b/src-tauri/src/providers/supabase.rs index c6974cb0..b146d05e 100644 --- a/src-tauri/src/providers/supabase.rs +++ b/src-tauri/src/providers/supabase.rs @@ -235,12 +235,12 @@ async fn post(token: &str, path: &str, body: &Value) -> Result { if !(200..300).contains(&status) { let msg = body["message"].as_str().map(String::from).unwrap_or_else(|| text.chars().take(160).collect()); if status == 403 { - // The scopes a Supabase OAuth token carries are the ones enabled on - // the OAuth app itself; signing in again only helps once the app - // grants Projects: Write. + // The scopes a Supabase OAuth token carries are the ones the OAuth + // app had when the user consented: a token from before the app was + // given Projects: Write keeps lacking it until they sign in again. if msg.contains("organization_projects_create") || msg.contains("scope") { return Err( - "Supabase's sign-in for Stroke can browse projects but not create them yet (it lacks the Projects: Write permission). Create the project on supabase.com for now; Stroke lists it here as soon as it exists." + "This Supabase sign-in can't create projects: it was granted before Stroke asked for Projects: Write. Disconnect Supabase here and sign in again to allow it, or create the project on supabase.com; Stroke lists it here as soon as it exists." .into(), ); } From 3be585bb1e8a30230c9d8f2f4a5ca19825ba8c37 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:27:59 +0000 Subject: [PATCH 308/317] chore: version 2.20.1 (#302) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 440587f6..5e337a41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.20.1] - 2026-11-18 + +### Changes +- Tell Supabase users to sign in again for project creation (#302) + + ## [2.20.0] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 63069523..8d3a8a14 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.20.0", + "version": "2.20.1", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 8dab969f..768e6622 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.20.0", + "version": "2.20.1", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From 4ea7c90e3a0ccf6ce5e57947b0aaf4fe30444c97 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 22:24:15 +0545 Subject: [PATCH 309/317] Add Xata and SingleStore providers (#303) Both sign in with a pasted key for now. Xata: an API key lists every branch of every project and connects with the branch's own credentials. SingleStore: a Management API key lists workspaces and starter workspaces; the API never returns a database password, so it is asked once and kept, as with Supabase. Both can move to OAuth later: Xata supports dynamic client registration, SingleStore needs a client ID. --- src-tauri/src/providers/mod.rs | 31 ++++- src-tauri/src/providers/singlestore.rs | 153 ++++++++++++++++++++++++ src-tauri/src/providers/xata.rs | 154 +++++++++++++++++++++++++ src/lib/connection-provider.js | 2 + src/lib/db-icons.js | 3 + src/lib/providers.js | 24 ++++ src/lib/stores/connections.js | 2 +- 7 files changed, 363 insertions(+), 6 deletions(-) create mode 100644 src-tauri/src/providers/singlestore.rs create mode 100644 src-tauri/src/providers/xata.rs diff --git a/src-tauri/src/providers/mod.rs b/src-tauri/src/providers/mod.rs index 17b8cf77..cd9c00e4 100644 --- a/src-tauri/src/providers/mod.rs +++ b/src-tauri/src/providers/mod.rs @@ -30,6 +30,8 @@ mod railway; mod tidb; mod turso; mod upstash; +mod xata; +mod singlestore; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use serde::{Deserialize, Serialize}; @@ -75,6 +77,8 @@ pub enum Provider { Nile, Upstash, PostHog, + Xata, + SingleStore, } /// How a provider signs the user in. @@ -103,13 +107,16 @@ impl Provider { "nile" => Ok(Self::Nile), "upstash" => Ok(Self::Upstash), "posthog" => Ok(Self::PostHog), + "xata" => Ok(Self::Xata), + "singlestore" => Ok(Self::SingleStore), other => Err(format!("Unknown provider: {other}")), } } - const ALL: [Provider; 10] = [ + const ALL: [Provider; 12] = [ Self::Neon, Self::Supabase, Self::PlanetScale, Self::Prisma, Self::TiDB, Self::Turso, Self::Railway, Self::Nile, Self::Upstash, Self::PostHog, + Self::Xata, Self::SingleStore, ]; /// The API host each listing and connect talks to, for `provider_warm`. @@ -125,6 +132,8 @@ impl Provider { Self::Railway => "https://backboard.railway.com", Self::Nile => "https://global.thenile.dev", Self::Upstash => "https://api.upstash.com", + Self::Xata => "https://api.xata.tech", + Self::SingleStore => "https://api.singlestore.com", Self::PostHog => return None, }) } @@ -142,6 +151,8 @@ impl Provider { Self::Nile => "nile", Self::Upstash => "upstash", Self::PostHog => "posthog", + Self::Xata => "xata", + Self::SingleStore => "singlestore", } } @@ -158,6 +169,8 @@ impl Provider { Self::Nile => "Nile", Self::Upstash => "Upstash", Self::PostHog => "PostHog", + Self::Xata => "Xata", + Self::SingleStore => "SingleStore", } } @@ -181,13 +194,15 @@ impl Provider { Self::Nile => nile::OAUTH, Self::Upstash => upstash::OAUTH, Self::PostHog => posthog::OAUTH, + Self::Xata => xata::OAUTH, + Self::SingleStore => singlestore::OAUTH, } } /// Whether a provider uses a pasted API credential instead of the browser /// OAuth dance: Upstash, which offers no OAuth to third-party apps. fn is_token_based(&self) -> bool { - matches!(self, Self::Upstash | Self::PostHog) + matches!(self, Self::Upstash | Self::PostHog | Self::Xata | Self::SingleStore) } /// Localhost callback ports to try, in order. PlanetScale accepts only ONE @@ -246,6 +261,8 @@ impl Provider { Self::Nile => nile::list_databases(token).await, Self::Upstash => upstash::list_databases(token).await, Self::PostHog => posthog::list_databases(token).await, + Self::Xata => xata::list_databases(token).await, + Self::SingleStore => singlestore::list_databases(token).await, } } @@ -265,6 +282,8 @@ impl Provider { Self::Nile => nile::build_connection(token, db_ref).await, Self::Upstash => upstash::build_connection(token, db_ref).await, Self::PostHog => posthog::build_connection(token, db_ref).await, + Self::Xata => xata::build_connection(token, db_ref).await, + Self::SingleStore => singlestore::build_connection(token, db_ref).await, } } @@ -279,7 +298,7 @@ impl Provider { Self::Turso => turso::create_options(token, scope).await, Self::Nile => nile::create_options(token, scope).await, Self::Upstash => Ok(upstash::create_options()), - Self::PlanetScale | Self::Railway | Self::PostHog => Err(self.create_unsupported()), + Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore => Err(self.create_unsupported()), } } @@ -292,7 +311,7 @@ impl Provider { Self::Turso => turso::create_database(token, req).await, Self::Nile => nile::create_database(token, req).await, Self::Upstash => upstash::create_database(token, req).await, - Self::PlanetScale | Self::Railway | Self::PostHog => Err(self.create_unsupported()), + Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore => Err(self.create_unsupported()), } } @@ -306,7 +325,7 @@ impl Provider { Self::Upstash => upstash::database_status(token, db_ref).await, // Turso databases are usable the moment the create call returns. Self::Turso => Ok(DatabaseStatus::ready("ready")), - Self::PlanetScale | Self::Railway | Self::PostHog => Err(self.create_unsupported()), + Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore => Err(self.create_unsupported()), } } @@ -323,6 +342,8 @@ impl Provider { // access, and a project created later isn't covered by the grant. Self::Railway => "Stroke's Railway sign-in can only see the projects you shared with it, so it can't create one. Create it in the Railway dashboard, then refresh.".into(), Self::PostHog => "PostHog projects are created in PostHog.".into(), + Self::Xata => "Create Xata projects and branches in the Xata console, then refresh.".into(), + Self::SingleStore => "Create SingleStore workspaces in the SingleStore portal, then refresh.".into(), _ => format!("{} databases can't be created from Stroke yet.", self.label()), } } diff --git a/src-tauri/src/providers/singlestore.rs b/src-tauri/src/providers/singlestore.rs new file mode 100644 index 00000000..bd9e4377 --- /dev/null +++ b/src-tauri/src/providers/singlestore.rs @@ -0,0 +1,153 @@ +/*! + * SingleStore adapter - MySQL wire protocol. Signed in with a Management API + * key (Cloud Portal → Configuration → API keys), sent as `Authorization: + * Bearer`. Lists every workspace in every workspace group, and the free + * starter workspaces. The API never returns a database password, so the + * connection asks for it once (`needs_password`), like Supabase: the workspace + * group's admin password, or the starter workspace's user password. + * + * SingleStore also runs OAuth (authsvc.singlestore.com, PKCE), whose access + * token logs in to the database directly; that needs a client ID registered + * with SingleStore and replaces the key and the password prompt once we have one. + */ + +use super::SendRetry; +use super::{http, OAuthConfig, ProviderConnection, ProviderDatabase}; +use serde_json::Value; + +/// Unused for a key-based provider; present so `Provider::oauth` stays total. +pub const OAUTH: OAuthConfig = OAuthConfig { client_id: "", auth_url: "", token_url: "", scopes: "" }; + +const API: &str = "https://api.singlestore.com/v1"; + +async fn get(token: &str, path: &str, what: &str) -> Result { + let key = token.trim(); + if key.is_empty() { + return Err("SingleStore needs a Management API key.".into()); + } + let resp = http() + .get(format!("{API}{path}")) + .bearer_auth(key) + .send_retrying() + .await + .map_err(|e| format!("SingleStore request failed ({what}): {}", super::describe(&e)))?; + let status = resp.status().as_u16(); + if status == 401 { + return Err(super::UNAUTHORIZED.into()); + } + let text = resp.text().await.map_err(|e| format!("SingleStore read failed: {e}"))?; + if !(200..300).contains(&status) { + let snippet: String = text.chars().take(160).collect(); + return Err(format!("SingleStore API error ({status}) on {what}: {snippet}")); + } + serde_json::from_str(&text).map_err(|_| format!("SingleStore returned a non-JSON response for {what}")) +} + +/// `{ kind: "workspace" | "starter", id }`, what `build_connection` needs. +fn db_ref(kind: &str, id: &str) -> String { + serde_json::json!({ "kind": kind, "id": id }).to_string() +} + +fn active(state: Option<&str>) -> bool { + !matches!(state.map(str::to_ascii_uppercase).as_deref(), Some("TERMINATED") | Some("FAILED")) +} + +pub async fn list_databases(token: &str) -> Result, String> { + let groups = get(token, "/workspaceGroups", "listing workspace groups").await?; + let mut out = Vec::new(); + for g in groups.as_array().into_iter().flatten() { + let Some(gid) = g["workspaceGroupID"].as_str() else { continue }; + if !active(g["state"].as_str()) { + continue; + } + let gname = g["name"].as_str().unwrap_or(gid); + let path = format!("/workspaces?workspaceGroupID={}", urlencoding::encode(gid)); + let ws = get(token, &path, "listing workspaces").await?; + for w in ws.as_array().into_iter().flatten() { + let Some(wid) = w["workspaceID"].as_str() else { continue }; + if !active(w["state"].as_str()) { + continue; + } + out.push(ProviderDatabase { + db_ref: db_ref("workspace", wid), + name: format!("{gname} / {}", w["name"].as_str().unwrap_or(wid)), + region: g["regionName"].as_str().or_else(|| g["region"].as_str()).map(String::from), + kind: Some("Workspace".into()), + host: w["endpoint"].as_str().map(String::from), + }); + } + } + // Starter (free) workspaces live under their own endpoint; an account + // without any, or a key that can't read them, just has none. + if let Ok(starters) = get(token, "/sharedtier/virtualWorkspaces", "listing starter workspaces").await { + for w in starters.as_array().into_iter().flatten() { + let Some(id) = w["virtualWorkspaceID"].as_str() else { continue }; + if !active(w["state"].as_str()) { + continue; + } + out.push(ProviderDatabase { + db_ref: db_ref("starter", id), + name: w["name"].as_str().unwrap_or(id).to_string(), + region: None, + kind: Some("Starter workspace".into()), + host: w["endpoint"].as_str().map(String::from), + }); + } + } + Ok(out) +} + +pub async fn build_connection(token: &str, reference: &str) -> Result { + let r: Value = serde_json::from_str(reference).map_err(|_| "That SingleStore reference is damaged. Refresh the list.".to_string())?; + let id = r["id"].as_str().unwrap_or_default(); + if id.is_empty() { + return Err("That SingleStore reference is incomplete. Refresh the list.".into()); + } + let id_enc = urlencoding::encode(id); + if r["kind"].as_str() == Some("starter") { + let w = get(token, &format!("/sharedtier/virtualWorkspaces/{id_enc}"), "reading the starter workspace").await?; + return connection_from(&w, "starter"); + } + let w = get(token, &format!("/workspaces/{id_enc}"), "reading the workspace").await?; + connection_from(&w, "workspace") +} + +fn connection_from(w: &Value, kind: &str) -> Result { + let name = w["name"].as_str().unwrap_or("SingleStore").to_string(); + let state = w["state"].as_str().unwrap_or("ACTIVE").to_ascii_uppercase(); + if state == "SUSPENDED" { + return Err(format!("{name} is suspended. Resume it in the SingleStore portal, then connect.")); + } + let host = w["endpoint"].as_str().filter(|h| !h.is_empty()).ok_or_else(|| format!("{name} has no endpoint yet. It may still be starting."))?; + let starter = kind == "starter"; + Ok(ProviderConnection { + db_type: "mysql".into(), + host: host.to_string(), + port: w["mysqlDmlPort"].as_u64().and_then(|p| u16::try_from(p).ok()).unwrap_or(3306), + username: if starter { w["username"].as_str().unwrap_or_default().to_string() } else { "admin".into() }, + password: String::new(), + database: w["databaseName"].as_str().unwrap_or_default().to_string(), + // SingleStore's cloud endpoints require TLS. + ssl: true, + needs_password: true, + name: format!("SingleStore · {name}"), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn workspaces_connect_as_admin_over_tls_and_ask_for_the_password() { + let w = serde_json::json!({ "name": "prod", "state": "ACTIVE", "endpoint": "svc-1.aws.svc.singlestore.com" }); + let c = connection_from(&w, "workspace").unwrap(); + assert_eq!((c.db_type.as_str(), c.port, c.username.as_str()), ("mysql", 3306, "admin")); + assert!(c.ssl && c.needs_password); + let s = serde_json::json!({ "name": "free", "endpoint": "svc-2.aws.svc.singlestore.com", "mysqlDmlPort": 3333, "databaseName": "db_free", "username": "u_1" }); + let c = connection_from(&s, "starter").unwrap(); + assert_eq!((c.port, c.database.as_str(), c.username.as_str()), (3333, "db_free", "u_1")); + assert!(connection_from(&serde_json::json!({ "name": "x", "state": "SUSPENDED", "endpoint": "h" }), "workspace").unwrap_err().contains("suspended")); + assert!(!active(Some("Terminated")) && active(Some("ACTIVE")) && active(None)); + } +} diff --git a/src-tauri/src/providers/xata.rs b/src-tauri/src/providers/xata.rs new file mode 100644 index 00000000..7be01e80 --- /dev/null +++ b/src-tauri/src/providers/xata.rs @@ -0,0 +1,154 @@ +/*! + * Xata adapter - Postgres. Signed in with an API key (Xata console → Account + * or Organization settings → API keys), sent as `Authorization: Bearer`. Lists + * every branch of every project in every organization the key can see, and + * connects with the branch's own credentials (`…/branches/{id}/credentials`), + * which Xata hands out per branch. + * + * Xata also runs OAuth (Keycloak, with dynamic client registration); that sign-in + * can replace the key once its tokens are confirmed to carry `credentials:read`. + */ + +use super::SendRetry; +use super::{http, OAuthConfig, ProviderConnection, ProviderDatabase}; +use serde_json::Value; + +/// Unused for a key-based provider; present so `Provider::oauth` stays total. +pub const OAUTH: OAuthConfig = OAuthConfig { client_id: "", auth_url: "", token_url: "", scopes: "" }; + +const API: &str = "https://api.xata.tech"; + +async fn get(token: &str, path: &str, what: &str) -> Result { + let key = token.trim(); + if key.is_empty() { + return Err("Xata needs an API key.".into()); + } + let resp = http() + .get(format!("{API}{path}")) + .bearer_auth(key) + .send_retrying() + .await + .map_err(|e| format!("Xata request failed ({what}): {}", super::describe(&e)))?; + let status = resp.status().as_u16(); + if status == 401 { + return Err(super::UNAUTHORIZED.into()); + } + let text = resp.text().await.map_err(|e| format!("Xata read failed: {e}"))?; + if status == 403 { + return Err(format!("This Xata API key can't do that ({what}). Use a key with access to the organization's projects and branch credentials.")); + } + if !(200..300).contains(&status) { + let body: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + let msg = body["message"].as_str().map(String::from).unwrap_or_else(|| text.chars().take(160).collect()); + return Err(format!("Xata API error ({status}) on {what}: {msg}")); + } + serde_json::from_str(&text).map_err(|_| format!("Xata returned a non-JSON response for {what}")) +} + +fn enc(s: &str) -> String { + urlencoding::encode(s).into_owned() +} + +/// `{ org, project, branch }`, what `build_connection` needs. +fn db_ref(org: &str, project: &str, branch: &str) -> String { + serde_json::json!({ "org": org, "project": project, "branch": branch }).to_string() +} + +fn ids(body: &Value, list: &str) -> Vec<(String, String)> { + body[list] + .as_array() + .into_iter() + .flatten() + .filter_map(|o| { + let id = o["id"].as_str()?.to_string(); + let name = o["name"].as_str().unwrap_or(&id).to_string(); + Some((id, name)) + }) + .collect() +} + +pub async fn list_databases(token: &str) -> Result, String> { + let orgs = get(token, "/organizations", "listing organizations").await?; + let orgs = ids(&orgs, "organizations"); + let many_orgs = orgs.len() > 1; + let mut out = Vec::new(); + for (org, org_name) in &orgs { + let projects = get(token, &format!("/organizations/{}/projects", enc(org)), "listing projects").await?; + // Every project's branches at once: an account with ten projects + // shouldn't wait for ten round trips in a row. + let fetches = ids(&projects, "projects").into_iter().map(|(project, project_name)| async move { + let path = format!("/organizations/{}/projects/{}/branches", enc(org), enc(&project)); + let branches = get(token, &path, "listing branches").await; + (project, project_name, branches) + }); + for (project, project_name, branches) in futures::future::join_all(fetches).await { + let branches = branches?; + for b in branches["branches"].as_array().into_iter().flatten() { + let Some(branch) = b["id"].as_str() else { continue }; + let branch_name = b["name"].as_str().unwrap_or(branch); + let prefix = if many_orgs { format!("{org_name} / ") } else { String::new() }; + out.push(ProviderDatabase { + db_ref: db_ref(org, &project, branch), + name: format!("{prefix}{project_name} / {branch_name}"), + region: b["region"].as_str().filter(|r| !r.is_empty()).map(String::from), + kind: Some(if b["parentID"].as_str().is_some() { "Branch".into() } else { "Main branch".into() }), + host: None, + }); + } + } + } + Ok(out) +} + +pub async fn build_connection(token: &str, reference: &str) -> Result { + let r: Value = serde_json::from_str(reference).map_err(|_| "That Xata branch reference is damaged. Refresh the list.".to_string())?; + let (org, project, branch) = ( + r["org"].as_str().unwrap_or_default(), + r["project"].as_str().unwrap_or_default(), + r["branch"].as_str().unwrap_or_default(), + ); + if org.is_empty() || project.is_empty() || branch.is_empty() { + return Err("That Xata branch reference is incomplete. Refresh the list.".into()); + } + let path = format!("/organizations/{}/projects/{}/branches/{}/credentials", enc(org), enc(project), enc(branch)); + let c = get(token, &path, "reading the branch credentials").await?; + connection_from_credentials(&c, branch) +} + +fn connection_from_credentials(c: &Value, branch: &str) -> Result { + let host = c["hostname"].as_str().filter(|h| !h.is_empty()).ok_or("Xata returned no host for this branch. It may still be starting.")?; + Ok(ProviderConnection { + db_type: "postgres".into(), + host: host.to_string(), + port: c["port"].as_u64().and_then(|p| u16::try_from(p).ok()).unwrap_or(5432), + username: c["username"].as_str().unwrap_or("xata").to_string(), + password: c["password"].as_str().unwrap_or_default().to_string(), + database: c["dbname"].as_str().unwrap_or("xata").to_string(), + // Xata only accepts TLS. + ssl: true, + needs_password: false, + name: format!("Xata · {branch}"), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn credentials_become_a_tls_postgres_connection() { + let c = serde_json::json!({ "username": "xata", "password": "p", "hostname": "us-east-1.xata.tech", "port": 5432, "dbname": "app", "connectionString": "postgresql://…" }); + let conn = connection_from_credentials(&c, "main").unwrap(); + assert_eq!((conn.db_type.as_str(), conn.host.as_str(), conn.port, conn.database.as_str()), ("postgres", "us-east-1.xata.tech", 5432, "app")); + assert!(conn.ssl && !conn.needs_password); + assert!(connection_from_credentials(&serde_json::json!({}), "main").is_err()); + } + + #[test] + fn list_ids_read_name_and_id() { + let body = serde_json::json!({ "projects": [{ "id": "p1", "name": "Shop" }, { "id": "p2" }, { "name": "no id" }] }); + assert_eq!(ids(&body, "projects"), vec![("p1".into(), "Shop".into()), ("p2".into(), "p2".into())]); + let r: Value = serde_json::from_str(&db_ref("o", "p", "b")).unwrap(); + assert_eq!(r["branch"], "b"); + } +} diff --git a/src/lib/connection-provider.js b/src/lib/connection-provider.js index a2f1c22b..6d46ddf1 100644 --- a/src/lib/connection-provider.js +++ b/src/lib/connection-provider.js @@ -18,6 +18,8 @@ const HOSTS = [ [/(\.rlwy\.net|\.railway\.app|\.railway\.internal)$/i, 'railway'], [/\.thenile\.dev$/i, 'nile'], [/\.upstash\.io$/i, 'upstash'], + [/\.xata\.tech$/i, 'xata'], + [/\.svc\.singlestore\.com$/i, 'singlestore'], ] /** Older saved connections used these ids before the cards settled on theirs. */ diff --git a/src/lib/db-icons.js b/src/lib/db-icons.js index 40436af0..d8f80512 100644 --- a/src/lib/db-icons.js +++ b/src/lib/db-icons.js @@ -29,6 +29,9 @@ export const BRAND_MARKS = { // paths left of the wordmark). nile: { d: 'M20.121 21.658C14.5515 21.0013 9.75863 17.4158 7.56726 12.2611C6.97966 10.8371 5.56944 9.83472 3.93571 9.83472C1.76277 9.83472 0 11.5975 0 13.7681C0 14.8534 0.437813 15.8397 1.15214 16.5494C2.87113 18.2684 2.87113 21.0635 1.15214 22.7825C0.444726 23.4899 0 24.4784 0 25.5637C0 27.7344 1.76277 29.4971 3.93341 29.4971C6.10404 29.4971 7.86681 27.7344 7.86681 25.5637C7.86681 24.4784 7.429 23.4922 6.71467 22.7825C5.44962 21.5174 5.11781 19.6694 5.71231 18.1025C10.3093 19.3376 14.1368 22.6166 16.0286 27.0707C16.6162 28.4948 18.0264 29.4971 19.6601 29.4971C21.8307 29.4971 23.5935 27.7344 23.5935 25.5637C23.5935 23.5452 22.0704 21.8861 20.1187 21.6603L20.121 21.658ZM22.4414 6.71467C23.1488 6.00726 23.5935 5.01872 23.5935 3.93341C23.5935 1.76277 21.8307 0 19.6601 0C17.4895 0 15.7267 1.76277 15.7267 3.93341C15.7267 5.01872 16.1645 6.00495 16.8789 6.71467C18.1439 7.97972 18.4757 9.82775 17.8812 11.3947C13.2842 10.1596 9.45677 6.88058 7.56495 2.42641C6.97736 1.00236 5.56944 0 3.93341 0C1.76277 0 0 1.76277 0 3.93341C0 5.95196 1.52313 7.61104 3.47485 7.83686C9.0443 8.48436 13.828 12.0721 16.0217 17.2268C16.6092 18.6508 18.0195 19.6532 19.6532 19.6532C21.8238 19.6532 23.5866 17.8904 23.5866 15.7198C23.5866 14.6345 23.1488 13.6483 22.4345 12.9385C20.7247 11.2288 20.7247 8.44058 22.4414 6.71467Z', hex: '#8A63F9', vb: '0 2 28 26' }, docker: { d: 'M13.983 11.078h2.119a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.119a.185.185 0 00-.185.185v1.888c0 .102.083.185.185.185m-2.954-5.43h2.118a.186.186 0 00.186-.186V3.574a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m0 2.716h2.118a.187.187 0 00.186-.186V6.29a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.887c0 .102.082.185.185.186m-2.93 0h2.12a.186.186 0 00.184-.186V6.29a.185.185 0 00-.185-.185H8.1a.185.185 0 00-.185.185v1.887c0 .102.083.185.185.186m-2.964 0h2.119a.186.186 0 00.185-.186V6.29a.185.185 0 00-.185-.185H5.136a.186.186 0 00-.186.185v1.887c0 .102.084.185.186.186m5.893 2.715h2.118a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m-2.93 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.083.185.185.185m-2.964 0h2.119a.185.185 0 00.185-.185V9.006a.185.185 0 00-.184-.186h-2.12a.186.186 0 00-.186.186v1.887c0 .102.084.185.186.185m-2.92 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.082.185.185.185M23.763 9.89c-.065-.051-.672-.51-1.954-.51-.338.001-.676.03-1.01.087-.248-1.7-1.653-2.53-1.716-2.566l-.344-.199-.226.327c-.284.438-.49.922-.612 1.43-.23.97-.09 1.882.403 2.661-.595.332-1.55.413-1.744.42H.751a.751.751 0 00-.75.748 11.376 11.376 0 00.692 4.062c.545 1.428 1.355 2.48 2.41 3.124 1.18.723 3.1 1.137 5.275 1.137.983.003 1.963-.086 2.93-.266a12.248 12.248 0 003.823-1.389c.98-.567 1.86-1.288 2.61-2.136 1.252-1.418 1.998-2.997 2.553-4.4h.221c1.372 0 2.215-.549 2.68-1.009.309-.293.55-.65.707-1.046l.098-.288Z', hex: '#2496ED' }, + singlestore: { d: 'M17.029 5.063c-.914-1.916-2.8-3.432-5.114-4.033C11.4.887 10.858.83 10.258.8c-.886 0-1.743.114-2.629.343-2.2.658-3.742 1.945-4.657 2.947C1.801 5.435 1.03 6.837.572 8.238c0 .029-.028.057-.028.115C.515 8.467.4 8.81.4 8.896c-.029.057-.029.143-.057.2l-.086.344c0 .028 0 .057-.028.086-.743 3.69.49 7.001 1.234 8.231.185.308.338.564.49.8C.27 9.403 5.116 5.035 10.63 4.92c2.886-.057 5.771 1.116 7.171 3.461-.086-1.287-.171-2.002-.771-3.318zM12.543 0c2.572.715 4.914 2.517 5.886 4.72 1.485 3.575 1.143 8.095-.486 10.784-1.371 2.203-3.485 3.375-5.914 3.347-3.771-.029-6.828-3.032-6.857-6.808 0-3.776 2.971-6.894 6.857-6.894.629 0 1.535.087 2.563.516 0 0-.739-.438-2.638-.732C6.497 4.218.058 8.353 1.544 17.878c2.057 3.662 6 6.15 10.485 6.122 6.6-.029 12-5.435 11.97-12.072C24 5.578 18.83.172 12.544 0z', hex: '#AA00FF' }, + // Xata has no simple-icons mark: its X, drawn on the same 24 grid. + xata: { d: 'M3.5 3.5h3.3l5.2 6.4 5.2-6.4h3.3l-6.85 8.5 6.85 8.5h-3.3L12 14.1l-5.2 6.4H3.5l6.85-8.5z', hex: '#F46CAF' }, posthog: { d: 'M9.854 14.5 5 9.647.854 5.5A.5.5 0 0 0 0 5.854V8.44a.5.5 0 0 0 .146.353L5 13.647l.147.146L9.854 18.5l.146.147v-.049c.065.03.134.049.207.049h2.586a.5.5 0 0 0 .353-.854L9.854 14.5zm0-5-4-4a.487.487 0 0 0-.409-.144.515.515 0 0 0-.356.21.493.493 0 0 0-.089.288V8.44a.5.5 0 0 0 .147.353l9 9a.5.5 0 0 0 .853-.354v-2.585a.5.5 0 0 0-.146-.354l-5-5zm1-4a.5.5 0 0 0-.854.354V8.44a.5.5 0 0 0 .147.353l4 4a.5.5 0 0 0 .853-.354V9.854a.5.5 0 0 0-.146-.354l-4-4zm12.647 11.515a3.863 3.863 0 0 1-2.232-1.1l-4.708-4.707a.5.5 0 0 0-.854.354v6.585a.5.5 0 0 0 .5.5H23.5a.5.5 0 0 0 .5-.5v-.6c0-.276-.225-.497-.499-.532zm-5.394.032a.8.8 0 1 1 0-1.6.8.8 0 0 1 0 1.6zM.854 15.5a.5.5 0 0 0-.854.354v2.293a.5.5 0 0 0 .5.5h2.293c.222 0 .39-.135.462-.309a.493.493 0 0 0-.109-.545L.854 15.501zM5 14.647.854 10.5a.5.5 0 0 0-.854.353v2.586a.5.5 0 0 0 .146.353L4.854 18.5l.146.147h2.793a.5.5 0 0 0 .353-.854L5 14.647z', hex: '#F9BD2B' }, turso: { d: 'm23.31.803-.563-.42-1.11 1.189-.891-1.286-.512.235.704 1.798-.326.35L18.082 0l-.574.284 2.25 4.836-2.108.741h-.05l-1.143-1.359-1.144 1.36H8.687l-1.144-1.36-1.146 1.363H6.36l-2.12-.745L6.491.284 5.919 0l-2.53 2.668-.327-.349.705-1.798-.512-.236-.89 1.287L1.253.382.69.804 2.42 3.69l-.89.939.311 2.375 2.061.787L3.9 8.817H1.947v.444l.755 1.078 1.197.433v6.971l3.057 4.55L7.657 24l1.101-1.606L9.9 24l.999-1.606L12 24l1.102-1.606L14.1 24l1.141-1.606L16.343 24l.701-1.706 3.058-4.55v-6.972l1.196-.433.756-1.078v-.444h-1.952l.003-1.03 2.054-.784.311-2.375-.89-.939zm-8.93 18.718H8.033l.793-1.615.794 1.615.793-1.083.793 1.083.794-1.083.793 1.083.794-1.083.793 1.083.793-1.615.794 1.615zm3.886-7.39-3.3 1.084-.143 3.061-2.827.627-2.826-.627-.142-3.06-3.3-1.085v-1.635l4.266 1.21-.052 4.126h4.109l-.052-4.127 4.266-1.209z', hex: '#4FF8D2' }, mssql: { d: 'M12 2C7.03 2 3 3.34 3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5c0-1.66-4.03-3-9-3zm7 17c0 .3-2.54 1.5-7 1.5S5 19.3 5 19v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V19zm0-5c0 .3-2.54 1.5-7 1.5S5 14.3 5 14v-2.23c1.61.74 4.19 1.23 7 1.23s5.39-.49 7-1.23V14zM12 8.5C7.54 8.5 5 7.3 5 7s2.54-1.5 7-1.5 7 1.2 7 1.5-2.54 1.5-7 1.5z', hex: '#CC2927' }, diff --git a/src/lib/providers.js b/src/lib/providers.js index dc9b70f5..9eabed3f 100644 --- a/src/lib/providers.js +++ b/src/lib/providers.js @@ -39,6 +39,30 @@ export const PROVIDERS = [ join: (/** @type {Record} */ v) => `${v.email.trim()}:${v.apiKey.trim()}`, }, }, + { + id: 'xata', name: 'Xata', mode: 'token', engine: 'postgres', + blurb: 'Postgres with copy-on-write branches, every branch listed', + token: { + help: 'Create an API key in the Xata console under your account or organization settings, API keys.', + helpUrl: 'https://console.xata.io', + fields: [ + { key: 'apiKey', label: 'API key', type: 'password', autocomplete: 'off', placeholder: 'xau_…', mono: true }, + ], + join: (/** @type {Record} */ v) => v.apiKey.trim(), + }, + }, + { + id: 'singlestore', name: 'SingleStore', mode: 'token', engine: 'mysql', + blurb: 'Workspaces and free starter workspaces, asks for the database password once', + token: { + help: 'Create a Management API key in the SingleStore portal under Configuration, API keys.', + helpUrl: 'https://portal.singlestore.com', + fields: [ + { key: 'apiKey', label: 'Management API key', type: 'password', autocomplete: 'off', placeholder: 'API key', mono: true }, + ], + join: (/** @type {Record} */ v) => v.apiKey.trim(), + }, + }, { id: 'posthog', name: 'PostHog', mode: 'token', engine: 'posthog', blurb: 'Product analytics, queried with HogQL. Read-only', diff --git a/src/lib/stores/connections.js b/src/lib/stores/connections.js index 0557dfd1..af3ed4fe 100644 --- a/src/lib/stores/connections.js +++ b/src/lib/stores/connections.js @@ -49,7 +49,7 @@ const DISCONNECTED_KEY = 'stroke:disconnected' * ssh?: SshConfig * readOnly?: boolean * environment?: 'prod' | 'staging' | 'dev' | null - * provider?: 'neon' | 'supabase' | 'planetscale' | 'prisma' | 'tidb' | 'turso' | 'nile' | 'railway' | 'upstash' | 'posthog' + * provider?: 'neon' | 'supabase' | 'planetscale' | 'prisma' | 'tidb' | 'turso' | 'nile' | 'railway' | 'upstash' | 'posthog' | 'xata' | 'singlestore' * projectId?: string - PostHog project * apiKey?: string - PostHog personal API key * providerRef?: string - the provider's own id for this database (its db_ref), so reopening it from the provider picker connects with this entry instead of minting new credentials From aa3d342ee1f4d04bad1897e9e4f93e7d3cb3a3e7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:39:27 +0000 Subject: [PATCH 310/317] chore: version 2.20.2 (#303) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e337a41..e17bf85b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.20.2] - 2026-11-18 + +### Changes +- Add Xata and SingleStore providers (#303) + + ## [2.20.1] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 8d3a8a14..75335425 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.20.1", + "version": "2.20.2", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 768e6622..c3fb1f06 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.20.1", + "version": "2.20.2", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From da68552caa9d7724d9687514bdcce340edd098b2 Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Wed, 18 Nov 2026 22:34:35 +0545 Subject: [PATCH 311/317] Build macOS x64 on an Intel runner (#304) --- .github/workflows/nightly.yml | 3 ++- .github/workflows/release.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index f0689f35..6f597c9c 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -102,7 +102,8 @@ jobs: - platform: macos-latest name: macos-aarch64 args: '--target aarch64-apple-darwin --bundles app,dmg' - - platform: macos-latest + # Intel runner: a separate pool from the busy arm64 one, and a native x64 build. + - platform: macos-15-intel name: macos-x64 args: '--target x86_64-apple-darwin --bundles app,dmg' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 424d3276..f100c640 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -149,7 +149,8 @@ jobs: - platform: macos-latest name: macos-aarch64 args: '--target aarch64-apple-darwin' - - platform: macos-latest + # Intel runner: a separate pool from the busy arm64 one, and a native x64 build. + - platform: macos-15-intel name: macos-x64 args: '--target x86_64-apple-darwin' From 327e3e52cd57664ce08423ce524f5a2998d7d5ac Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Thu, 19 Nov 2026 08:57:59 +0545 Subject: [PATCH 312/317] Move local servers to their own window; fix dashboard window and D1 migrations (#305) - Local servers open in a native window: servers on the left, the picked one on the right with its connection details (copy URL or .env line), uptime, disk use, log, and a "Start with Stroke" switch. Database servers already running on this computer (Postgres.app, Homebrew, docker compose) are found by port and open in one click. Open connects in the window it came from. - Dashboard window: it looked the dashboard up under the live connection's id instead of the saved one and said it was deleted. It now finds it, can switch dashboards, fits columns to the window width, and goes full screen. - Migrations read Wrangler's d1_migrations on Cloudflare D1 (and plain migrations folders), with a summary, filters and the apply command. - Data table: older builds saved every column at its fixed default when one was resized, so those tables never fitted their content. Untouched columns fit again; only hand-sized widths are stored. Adds "Fit all columns". - Quit hint: smaller, clearer, with a bar for the second-press window. --- src-tauri/src/db/migrations.rs | 106 ++- src-tauri/src/lib.rs | 6 + src-tauri/src/local_servers.rs | 274 ++++++- src/App.svelte | 6 + src/lib/components/DashboardPage.svelte | 8 +- src/lib/components/DashboardWindow.svelte | 283 ++++--- src/lib/components/DataTable.svelte | 45 +- src/lib/components/LocalServersDialog.svelte | 481 ------------ src/lib/components/LocalServersWindow.svelte | 773 +++++++++++++++++++ src/lib/components/MigrationsPage.svelte | 321 +++++--- src/lib/components/QuitHint.svelte | 39 +- src/lib/components/StudioShell.svelte | 39 +- src/lib/i18n.js | 4 + src/lib/local-servers.js | 55 +- src/lib/migrations.js | 36 +- src/lib/migrations.test.js | 12 + src/lib/stores/dashboards.js | 34 + 17 files changed, 1813 insertions(+), 709 deletions(-) delete mode 100644 src/lib/components/LocalServersDialog.svelte create mode 100644 src/lib/components/LocalServersWindow.svelte diff --git a/src-tauri/src/db/migrations.rs b/src-tauri/src/db/migrations.rs index 3db78839..54334e7e 100644 --- a/src-tauri/src/db/migrations.rs +++ b/src-tauri/src/db/migrations.rs @@ -34,6 +34,47 @@ pub struct MigrationProject { /// The folder the migrations were read from. pub dir: String, pub files: Vec, + /// Every `.sql` file in the folder by file name, journal or not: what + /// `wrangler d1 migrations apply` runs and records in `d1_migrations`. + pub sql_files: Vec, + /// The D1 database a `wrangler.toml` / `wrangler.json(c)` next to the + /// migrations names, for the apply command. + pub wrangler_db: Option, +} + +/// The first `database_name = "x"` (TOML) or `"database_name": "x"` (JSON). +fn database_name(text: &str) -> Option { + for (i, _) in text.match_indices("database_name") { + let rest = text[i + "database_name".len()..].trim_start_matches('"').trim_start(); + let Some(rest) = rest.strip_prefix([':', '=']) else { continue }; + let rest = rest.trim_start(); + let q = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?; + let v: String = rest[1..].chars().take_while(|c| *c != q).collect(); + if !v.is_empty() { + return Some(v); + } + } + None +} + +/// `database_name` from the first wrangler config in `from` or a folder above +/// it, up to `root`. +fn wrangler_db(root: &Path, from: &Path) -> Option { + let mut dir = Some(from); + while let Some(d) = dir { + for f in ["wrangler.toml", "wrangler.jsonc", "wrangler.json"] { + if let Ok(text) = std::fs::read_to_string(d.join(f)) { + if let Some(name) = database_name(&text) { + return Some(name); + } + } + } + if d == root { + break; + } + dir = d.parent(); + } + None } const MAX_SQL: usize = 2 * 1024 * 1024; @@ -73,6 +114,33 @@ fn is_drizzle_dir(dir: &Path) -> bool { dir.join("meta").join("_journal.json").is_file() } +/// A plain `migrations/` folder of `.sql` files, as Wrangler (D1) keeps them. +fn is_sql_dir(dir: &Path) -> bool { + dir.file_name().is_some_and(|n| n == "migrations") + && std::fs::read_dir(dir) + .map(|rd| rd.flatten().any(|e| e.path().extension().is_some_and(|x| x == "sql"))) + .unwrap_or(false) +} + +/// Every `.sql` file directly in `dir`, by name; `name` keeps the `.sql` +/// (that's what `d1_migrations.name` holds). +pub fn read_sql_dir(dir: &Path) -> Vec { + let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut names: Vec = rd + .flatten() + .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|x| x == "sql")) + .filter_map(|e| e.file_name().to_str().map(String::from)) + .collect(); + names.sort(); + names + .into_iter() + .filter_map(|name| { + let (sql, checksum) = read_sql(&dir.join(&name))?; + Some(MigrationFile { name, sql, checksum, when: None }) + }) + .collect() +} + /// Folders worth looking into for a project root, a few levels down, skipping /// the ones that are never migrations. fn walk(root: &Path, depth: usize, out: &mut Vec) { @@ -113,6 +181,13 @@ pub fn find(root: &Path, tool: Option<&str>) -> Option<(String, PathBuf)> { return Some(("prisma".into(), d.clone())); } } + // No journal anywhere: a Wrangler migrations folder reads like Drizzle's + // SQL files, applied by name. + if want_drizzle { + if let Some(d) = dirs.iter().find(|d| is_sql_dir(d) && !is_prisma_dir(d)) { + return Some(("drizzle".into(), d.clone())); + } + } None } @@ -135,6 +210,10 @@ pub fn read_prisma(dir: &Path) -> Vec { } pub fn read_drizzle(dir: &Path) -> Result, String> { + if !is_drizzle_dir(dir) { + // A Wrangler folder: its files are the migrations, in name order. + return Ok(read_sql_dir(dir).into_iter().map(|f| MigrationFile { name: f.name.trim_end_matches(".sql").to_string(), ..f }).collect()); + } let journal = std::fs::read_to_string(dir.join("meta").join("_journal.json")) .map_err(|e| format!("Could not read meta/_journal.json: {e}"))?; let v: serde_json::Value = serde_json::from_str(&journal).map_err(|e| format!("meta/_journal.json isn't valid JSON: {e}"))?; @@ -174,7 +253,9 @@ pub async fn migrations_project(dir: String, tool: Option) -> Result>(), ["0000_init.sql", "0001_posts.sql", "0001b_hand_written.sql"]); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_wrangler_migrations_folder_reads_as_drizzle() { + let root = tmp("wrangler"); + let m = root.join("migrations"); + std::fs::create_dir_all(&m).unwrap(); + std::fs::write(m.join("0002_b.sql"), "SELECT 2;").unwrap(); + std::fs::write(m.join("0001_a.sql"), "SELECT 1;").unwrap(); + let (tool, dir) = find(&root, None).unwrap(); + assert_eq!((tool.as_str(), dir.clone()), ("drizzle", m.clone())); + let files = read_drizzle(&dir).unwrap(); + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["0001_a", "0002_b"]); let _ = std::fs::remove_dir_all(&root); } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 401c4bdd..af62ba02 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -498,6 +498,8 @@ pub fn run() { .manage(launch::LaunchState::default()) .setup(move |app| { display_backend::watch(app.handle().clone()); + // Local servers marked "Start with Stroke". + local_servers::autostart(app.handle().clone()); // Linux packages renamed the binary from `app` to `stroke` (2.5.6), and // a launch-at-login entry stores the binary's path. Re-enabling an // enabled entry rewrites it with the current path, so it doesn't @@ -952,6 +954,10 @@ pub fn run() { local_servers::local_server_free_port, local_servers::brew_services_list, local_servers::brew_service_action, + local_servers::local_servers_discover, + local_servers::local_server_reveal, + local_servers::open_local_servers_window, + local_servers::local_server_connect_in, cloud_backup::backup_job_save, cloud_backup::backup_job_patch, cloud_backup::backup_job_delete, diff --git a/src-tauri/src/local_servers.rs b/src-tauri/src/local_servers.rs index f2c2a599..aa0a6119 100644 --- a/src-tauri/src/local_servers.rs +++ b/src-tauri/src/local_servers.rs @@ -35,6 +35,9 @@ pub struct LocalServer { pub runtime: String, #[serde(default)] pub created_at: i64, + /// Start it when Stroke opens. + #[serde(default)] + pub autostart: bool, } #[derive(Debug, Clone, Serialize)] @@ -45,6 +48,26 @@ pub struct ServerState { pub running: bool, /// Why it can't run right now (Docker not running, binary gone). pub problem: Option, + /// When the running server started, ms since the epoch. + pub started_at: Option, + /// Size of a native server's data folder. + pub disk_bytes: Option, + /// Where a native server keeps its data. + pub data_dir: Option, +} + +/// A database server listening on this computer that Stroke didn't make: +/// Postgres.app, a Homebrew service, a docker compose container. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoundServer { + pub engine: String, + pub port: u16, + /// docker | process + pub source: String, + /// The container's name, or the engine for a plain process. + pub name: String, + pub image: Option, } #[derive(Debug, Clone, Serialize)] @@ -436,6 +459,40 @@ async fn docker_running(id: &str) -> Result { } } +/// When a running server started: Docker's StartedAt, Postgres's +/// postmaster.pid (its third line), or the pid file's time for the rest. +async fn started_at(app: &AppHandle, s: &LocalServer) -> Option { + if s.runtime == "docker" { + let out = run(&docker().ok()?, &["inspect", "-f", "{{.State.StartedAt}}", &container(&s.id)]).await.ok()?; + return chrono::DateTime::parse_from_rfc3339(out.trim()).ok().map(|t| t.timestamp_millis()); + } + let dir = server_dir(app, &s.id).ok()?; + if s.engine == "postgres" { + let text = std::fs::read_to_string(dir.join("data").join("postmaster.pid")).ok()?; + return text.lines().nth(2)?.trim().parse::().ok().map(|t| t * 1000); + } + let modified = std::fs::metadata(pid_file(app, &s.id).ok()?).ok()?.modified().ok()?; + Some(chrono::DateTime::::from(modified).timestamp_millis()) +} + +/// Bytes under `dir`, files only, not following links. +fn dir_size(dir: &Path) -> u64 { + let mut total = 0; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { continue }; + for e in rd.flatten() { + let Ok(meta) = e.metadata() else { continue }; + if meta.is_dir() { + stack.push(e.path()); + } else if meta.is_file() { + total += meta.len(); + } + } + } + total +} + async fn state_of(app: &AppHandle, s: LocalServer, docker_ok: bool) -> ServerState { let (running, problem) = if s.runtime == "docker" { if !docker_ok { @@ -460,7 +517,203 @@ async fn state_of(app: &AppHandle, s: LocalServer, docker_ok: bool) -> ServerSta let problem = if up || native_binary(&s.engine).is_some() { None } else { Some(format!("{} isn't installed anymore", s.engine)) }; (up, problem) }; - ServerState { server: s, running, problem } + let started_at = if running { started_at(app, &s).await } else { None }; + let (disk_bytes, data_dir) = if s.runtime == "native" { + match server_dir(app, &s.id) { + Ok(dir) => { + let data = dir.join("data"); + let shown = data.to_string_lossy().into_owned(); + let size = tokio::task::spawn_blocking(move || dir_size(&data)).await.ok(); + (size, Some(shown)) + } + Err(_) => (None, None), + } + } else { + (None, None) + }; + ServerState { server: s, running, problem, started_at, disk_bytes, data_dir } +} + +// ── Finding servers Stroke didn't make ────────────────────────────────────── + +/// Ports each engine is usually found on. +const PROBE_PORTS: &[(&str, std::ops::RangeInclusive)] = &[ + ("postgres", 5432..=5440), + ("mysql", 3306..=3310), + ("redis", 6379..=6382), + ("mongodb", 27017..=27020), +]; + +/// What answers on a port, checked by speaking a few bytes of the engine's +/// protocol: Postgres answers an SSLRequest with S or N, MySQL and MariaDB +/// greet first with protocol version 10, Redis answers PING. MongoDB has no +/// cheap greeting, so an open port in its range counts. +async fn identify(engine: &str, port: u16) -> Option { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let t = Duration::from_millis(500); + let mut stream = tokio::time::timeout(t, tokio::net::TcpStream::connect(("127.0.0.1", port))).await.ok()?.ok()?; + let mut buf = [0u8; 128]; + match engine { + "postgres" => { + stream.write_all(&[0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]).await.ok()?; + let n = tokio::time::timeout(t, stream.read(&mut buf)).await.ok()?.ok()?; + (n == 1 && (buf[0] == b'S' || buf[0] == b'N')).then(|| "postgres".to_string()) + } + "mysql" => { + let n = tokio::time::timeout(t, stream.read(&mut buf)).await.ok()?.ok()?; + if n > 5 && buf[4] == 10 { + let greeting = String::from_utf8_lossy(&buf[5..n]).to_ascii_lowercase(); + Some(if greeting.contains("mariadb") { "mariadb" } else { "mysql" }.to_string()) + } else { + None + } + } + "redis" => { + stream.write_all(b"PING\r\n").await.ok()?; + let n = tokio::time::timeout(t, stream.read(&mut buf)).await.ok()?.ok()?; + let reply = String::from_utf8_lossy(&buf[..n]); + (reply.starts_with("+PONG") || reply.starts_with("-NOAUTH") || reply.starts_with("-ERR")).then(|| "redis".to_string()) + } + "mongodb" => Some("mongodb".to_string()), + _ => None, + } +} + +/// Engine of a container image, when it's a database. +fn image_engine(image: &str) -> Option<&'static str> { + let base = image.rsplit('/').next().unwrap_or(image).split([':', '@']).next().unwrap_or(""); + Some(match base { + b if b.starts_with("postgres") || b.starts_with("postgis") || b == "timescaledb" || b.starts_with("pgvector") => "postgres", + b if b.starts_with("mariadb") => "mariadb", + b if b.starts_with("mysql") || b.starts_with("percona") => "mysql", + b if b.starts_with("redis") || b.starts_with("valkey") => "redis", + b if b.starts_with("mongo") => "mongodb", + _ => return None, + }) +} + +/// Host ports a `docker ps` Ports column publishes ("0.0.0.0:5432->5432/tcp, [::]:5432->5432/tcp"). +fn published_ports(ports: &str) -> Vec { + let mut out: Vec = ports + .split(',') + .filter_map(|p| p.split("->").next()?.rsplit(':').next()?.trim().parse().ok()) + .collect(); + out.dedup(); + out +} + +#[tauri::command] +pub async fn local_servers_discover(app: AppHandle) -> Result, String> { + let ours: Vec = load(&app)?.iter().map(|s| s.port).collect(); + let mut found: Vec = Vec::new(); + // Containers first: they carry a name worth showing. + if let Some(d) = which("docker") { + if let Ok(out) = run(&d, &["ps", "--format", "{{.Names}}\t{{.Image}}\t{{.Ports}}\t{{.Labels}}"]).await { + for line in out.lines() { + let cols: Vec<&str> = line.split('\t').collect(); + if cols.len() < 3 || cols.get(3).is_some_and(|l| l.contains("app=stroke")) { + continue; + } + let Some(engine) = image_engine(cols[1]) else { continue }; + for port in published_ports(cols[2]) { + if ours.contains(&port) || found.iter().any(|f| f.port == port) { + continue; + } + found.push(FoundServer { engine: engine.into(), port, source: "docker".into(), name: cols[0].to_string(), image: Some(cols[1].to_string()) }); + } + } + } + } + let probes = PROBE_PORTS.iter().flat_map(|(engine, range)| range.clone().map(move |p| (*engine, p))) + .filter(|(_, p)| !ours.contains(p) && !found.iter().any(|f| f.port == *p)) + .map(|(engine, port)| async move { identify(engine, port).await.map(|e| (e, port)) }); + for (engine, port) in futures::future::join_all(probes).await.into_iter().flatten() { + let label = match engine.as_str() { "postgres" => "PostgreSQL", "mysql" => "MySQL", "mariadb" => "MariaDB", "redis" => "Redis", _ => "MongoDB" }; + found.push(FoundServer { engine, port, source: "process".into(), name: label.into(), image: None }); + } + found.sort_by_key(|f| f.port); + Ok(found) +} + +/// Start the servers marked to start with Stroke. Runs once at launch. +pub fn autostart(app: AppHandle) { + tauri::async_runtime::spawn(async move { + let Ok(servers) = load(&app) else { return }; + for s in servers.into_iter().filter(|s| s.autostart) { + if let Err(e) = local_server_start(app.clone(), s.id.clone()).await { + log::warn!("local server {} didn't start at launch: {e}", s.name); + } + } + }); +} + +/// Show a native server's data folder in the file manager. +#[tauri::command] +pub async fn local_server_reveal(app: AppHandle, id: String) -> Result<(), String> { + let s = find(&app, &id)?; + if s.runtime != "native" { + return Err("A Docker server keeps its data in a Docker volume".into()); + } + let data = server_dir(&app, &id)?.join("data"); + tauri_plugin_opener::reveal_item_in_dir(&data).map_err(|e| e.to_string()) +} + +/// The Local servers window: one per app, focused when it's already open. +#[tauri::command] +pub async fn open_local_servers_window(app: AppHandle, from: String) -> Result<(), String> { + let label = "main-local-servers"; + if let Some(w) = app.webview_windows().get(label) { + let _ = w.unminimize(); + let _ = w.set_focus(); + return Ok(()); + } + let from: String = from.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(64).collect(); + let url = format!("/?view=local-servers&from={from}"); + let mut builder = tauri::WebviewWindowBuilder::new(&app, label, tauri::WebviewUrl::App(url.into())) + .title("Local Servers") + .inner_size(980.0, 640.0) + .min_inner_size(720.0, 460.0) + .resizable(true) + .visible(false) + .background_color(tauri::window::Color(8, 8, 8, 255)) + .devtools(cfg!(debug_assertions)) + .zoom_hotkeys_enabled(false) + .on_navigation(crate::navigation_allowed); + #[cfg(target_os = "macos")] + { + builder = builder + .title_bar_style(tauri::TitleBarStyle::Overlay) + .hidden_title(true) + .traffic_light_position(crate::mac_chrome::traffic_light_position()); + } + #[cfg(not(target_os = "macos"))] + { + builder = builder.decorations(false); + } + let window = builder.build().map_err(|e| e.to_string())?; + let surface = crate::surface_for_theme(window.theme().unwrap_or(tauri::Theme::Dark)); + let _ = window.set_background_color(Some(surface)); + crate::set_webview_backdrop(&window, surface); + crate::guard_webview(&window); + crate::arm_reveal_failsafe(&window); + Ok(()) +} + +/// Connect to a server in an app window: the Local servers window hands the +/// connection to the window it was opened from (or the first main window) +/// and brings that one forward. +#[tauri::command] +pub async fn local_server_connect_in(app: AppHandle, target: String, connection: serde_json::Value) -> Result<(), String> { + let windows = app.webview_windows(); + let w = windows + .get(target.as_str()) + .filter(|_| target.starts_with("main") && target != "main-local-servers" && !target.starts_with("main-dashboard-")) + .or_else(|| windows.get("main")) + .or_else(|| windows.iter().find(|(l, _)| l.starts_with("main") && *l != "main-local-servers" && !l.starts_with("main-dashboard-")).map(|(_, w)| w)) + .ok_or("Open a Stroke window first")?; + let _ = w.unminimize(); + let _ = w.set_focus(); + w.emit("local-server-connect", connection).map_err(|e| e.to_string()) } // ── Commands ──────────────────────────────────────────────────────────────── @@ -548,6 +801,7 @@ pub async fn local_server_create(app: AppHandle, spec: NewServer) -> Result Result<(), Strin /// Rename a server or move it to another port (it has to be stopped for a port change). #[tauri::command] -pub async fn local_server_update(app: AppHandle, id: String, name: Option, port: Option) -> Result { +pub async fn local_server_update(app: AppHandle, id: String, name: Option, port: Option, autostart: Option) -> Result { let mut servers = load(&app)?; let idx = servers.iter().position(|s| s.id == id).ok_or("That server no longer exists")?; + if let Some(a) = autostart { + servers[idx].autostart = a; + } if let Some(n) = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) { servers[idx].name = n; } @@ -841,10 +1098,21 @@ mod tests { assert!(validate(&spec("oracle", "23", 1521, "docker"), &[]).is_err()); assert!(validate(&spec("redis", "7; rm -rf /", 6380, "docker"), &[]).is_err()); assert!(validate(&spec("redis", "7", 80, "docker"), &[]).unwrap_err().contains("1024")); - let taken = LocalServer { id: "a".into(), name: "Air".into(), engine: "postgres".into(), version: "16".into(), port: 5432, runtime: "docker".into(), created_at: 0 }; + let taken = LocalServer { id: "a".into(), name: "Air".into(), engine: "postgres".into(), version: "16".into(), port: 5432, runtime: "docker".into(), created_at: 0, autostart: false }; assert!(validate(&spec("mysql", "8.4", 5432, "docker"), &[taken]).unwrap_err().contains("Air")); } + #[test] + fn other_servers_are_recognised_by_image_and_port() { + assert_eq!(image_engine("postgres:16-alpine"), Some("postgres")); + assert_eq!(image_engine("docker.io/bitnami/mariadb:11"), Some("mariadb")); + assert_eq!(image_engine("ghcr.io/x/pgvector/pgvector:pg17"), Some("postgres")); + assert_eq!(image_engine("valkey/valkey:8"), Some("redis")); + assert_eq!(image_engine("nginx:latest"), None); + assert_eq!(published_ports("0.0.0.0:5433->5432/tcp, [::]:5433->5432/tcp"), vec![5433]); + assert_eq!(published_ports("6379/tcp"), Vec::::new()); + } + #[test] fn docker_images_and_ports() { assert_eq!(docker_image("mongodb", "8.0").unwrap().0, "mongo:8.0"); diff --git a/src/App.svelte b/src/App.svelte index b2fe8fc0..f9178eef 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -8,6 +8,8 @@ // A window opened for one dashboard (open_dashboard_window) shows only that. const params = typeof location !== 'undefined' ? new URLSearchParams(location.search) : new URLSearchParams() const dashboardView = params.get('view') === 'dashboard' ? { dash: params.get('dash') ?? '', conn: params.get('conn') ?? '' } : null + // The Local servers window (open_local_servers_window). + const localServersFrom = params.get('view') === 'local-servers' ? params.get('from') || 'main' : null import LicenseGate from './lib/components/LicenseGate.svelte' import AppLockGate from './lib/components/AppLockGate.svelte' import AppErrorBoundary from './lib/components/AppErrorBoundary.svelte' @@ -103,6 +105,10 @@ {#if dashboardView} + {:else if localServersFrom} + {#await import('./lib/components/LocalServersWindow.svelte') then { default: LocalServersWindow }} + + {/await} {:else} {/if} diff --git a/src/lib/components/DashboardPage.svelte b/src/lib/components/DashboardPage.svelte index 605d657c..619ab84b 100644 --- a/src/lib/components/DashboardPage.svelte +++ b/src/lib/components/DashboardPage.svelte @@ -19,6 +19,8 @@ reorderItems, addQueryToDashboard, updateItem, + dashboardsConnectionId, + flushDashboards, } from "$lib/stores/dashboards.js"; import { listSavedQueries, queryTitle } from "$lib/stores/query-history.js"; import { executeSql } from "$lib/api.js"; @@ -264,8 +266,12 @@ async function openWindow() { if (!activeDash || !connection?.id) return; try { + // The window reads the dashboard from storage: write pending edits now, + // and pass the key the dashboards are stored under (the saved + // connection's id), not the live connection's. + flushDashboards(); const { invoke } = await import("@tauri-apps/api/core"); - await invoke("open_dashboard_window", { dashboardId: activeDash.id, connectionId: connection.id, title: activeDash.name }); + await invoke("open_dashboard_window", { dashboardId: activeDash.id, connectionId: dashboardsConnectionId() || connection.id, title: activeDash.name }); } catch (e) { toast.error("Could not open the window", { description: String(e) }); } diff --git a/src/lib/components/DashboardWindow.svelte b/src/lib/components/DashboardWindow.svelte index bd78b9de..e2692804 100644 --- a/src/lib/components/DashboardWindow.svelte +++ b/src/lib/components/DashboardWindow.svelte @@ -1,16 +1,16 @@ -
- -
-
- + + +
+ + {#if !fullscreen} +
+
+ + {#if dashOptions.length > 1} + { currentId = v; live = {} }} + /> + {:else} +

{dash?.name ?? 'Dashboard'}

+ {/if} + {#if connName} + + {/if} +
+
{#if dash} + + ({ value: String(v), label: v ? `Every ${l}` : 'Auto refresh off' }))} onchange={(v) => dash && updateDashboard(dash.id, { refreshSec: Number(v) })} /> + {/if} -
-

- {dash?.name ?? 'Dashboard'} -

-
- {#if connName} - - - {connName} - - {/if} - {#if !isMac}{/if} -
+ {#if !isMac}{/if} + + {:else} + + {/if} -
- {#if !dash} -
- -

This dashboard was deleted

+
+ {#if ready && !dash} +
+ +
+

This dashboard isn't here anymore

+

It was deleted, or it belongs to another connection.

+
+ {#if dashOptions.length} +
+ {#each dashOptions as o (o.value)} + + {/each} +
+ {/if}
- {:else if dash.items.length === 0} -
- -

Nothing on {dash.name} yet

-

Add charts or saved queries from the Dashboard tab; they show up here.

+ {:else if dash && dash.items.length === 0} +
+ +
+

Nothing on {dash.name} yet

+

Add charts or saved queries in the Dashboard tab. They show up here as you add them.

+
- {:else} -
+ {:else if dash} +
{#each dash.items as item, i (item.id)} {@const chart = getChart(item.chartId)} {@const l = live[keyOf(item)]} @@ -186,34 +277,63 @@ {@const color = REPORT_COLORS[i % REPORT_COLORS.length]} {@const status = l?.loading && !l?.result ? 'loading' : l?.error ? 'error' : l?.at ? 'ok' : sqlOf(item) ? 'loading' : 'idle'}
+
+ +

{title}

+ + {status === 'error' ? 'Failed' : l?.loading ? 'Running' : l?.at ? agoText(l.at, now) : ''} + + {#if sqlOf(item)} + + {/if} +
{#if l?.error} -
-

Query failed

-

{l.error}

+
+

Query failed

+

{l.error}

+
{:else if view?.kpi} -
+
{formatKpi(view.kpi.value)} - {view.kpi.label} + {view.kpi.label}
{:else if view?.table} -
+
- + {#each view.table.columns as c, ci (ci)} - + {/each} {#each view.table.rows as row, ri (ri)} - + {#each row as cell, ci (ci)} {/each} @@ -223,44 +343,15 @@
{c}{c}
{cell === null ? 'NULL' : typeof cell === 'number' ? reportNumber(cell) : typeof cell === 'object' ? JSON.stringify(cell) : String(cell)}
{:else if view?.option} - + + {:else if status === 'loading'} + {:else if status === 'idle'} -
+
{chart ? 'This chart writes, so it only runs from the editor' : 'This chart was deleted'}
{/if}
- -
-
- - {#if sqlOf(item)} - - {/if} -
-

{title}

-

- {status === 'ok' ? 'OK' : status === 'error' ? 'Failed' : status === 'loading' ? 'Running' : '·'} -

-
{/each}
diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index f48b100b..94ae58e4 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -4582,8 +4582,12 @@ import FilterX from "@lucide/svelte/icons/filter-x"; const auto = new Set() for (const col of cols) { const dt = col.dataType ?? col.data_type ?? "" - if (stored[col.name] == null) auto.add(col.name) - next[col.name] = clampColumnWidth(stored[col.name] ?? defaultColumnWidth(dt)) + // Builds before 2.21 saved every column's width when one was dragged, + // the untouched ones at their fixed type default (420 for text). A + // stored width equal to that default was never chosen: fit it instead. + const own = stored[col.name] != null && stored[col.name] !== clampColumnWidth(defaultColumnWidth(dt)) ? stored[col.name] : null + if (own == null) auto.add(col.name) + next[col.name] = clampColumnWidth(own ?? defaultColumnWidth(dt)) } columnWidths = next // Columns nobody has sized are fitted to their content once rows arrive. @@ -4704,7 +4708,24 @@ import FilterX from "@lucide/svelte/icons/filter-x"; const w = fittedWidth(columns[i], i) if (w == null) return columnWidths = { ...columnWidths, [colName]: w } - if (columnWidthsKey) saveColumnWidths(columnWidthsKey, columnWidths) + keepWidth(colName, w) + } + + /** + * Store one column's width, chosen by hand. Only columns someone sized are + * stored; the rest stay automatic and are fitted to what they hold. + * @param {string} colName @param {number} w + */ + function keepWidth(colName, w) { + if (!columnWidthsKey) return + const stored = loadColumnWidths(columnWidthsKey) + // Drop the type defaults older builds stored for untouched columns. + for (const col of columns) { + const dt = col.dataType ?? col.data_type ?? '' + if (stored[col.name] === clampColumnWidth(defaultColumnWidth(dt))) delete stored[col.name] + } + stored[colName] = w + saveColumnWidths(columnWidthsKey, stored) } // Virtual (relationship / expression) column widths persist alongside real @@ -4775,7 +4796,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; if (columnWidthsKey && resizingColName) { if (resizingColName.startsWith('__vrel__')) saveColumnWidths(`${columnWidthsKey}\x00__vrel`, _vrelWidths); else if (resizingColName.startsWith('__vcol__')) saveColumnWidths(`${columnWidthsKey}\x00__vcol`, _vexprWidths); - else saveColumnWidths(columnWidthsKey, columnWidths); + else keepWidth(resizingColName, columnWidths[resizingColName]); } resizingColName = null; } @@ -4855,6 +4876,18 @@ import FilterX from "@lucide/svelte/icons/filter-x"; } } + /** Every column back to automatic: fitted to its content, nothing stored. */ + function fitAllColumns() { + /** @type {Record} */ + const fitted = {} + columns.forEach((col, i) => { + const w = rows.length ? fittedWidth(col, i) : null + if (w != null) fitted[col.name] = w + }) + columnWidths = { ...columnWidths, ...fitted } + if (columnWidthsKey) saveColumnWidths(columnWidthsKey, {}) + } + // ── Per-tab expand/sub-view state preservation ─────────────────────────────── // Expand rows and FK sub-view are saved per columnWidthsKey so switching tabs // restores exactly what the user had open in each table. @@ -9698,6 +9731,10 @@ import FilterX from "@lucide/svelte/icons/filter-x"; {$t('menu.resetWidth')} + runMenuAction(fitAllColumns)}> + + {$t('menu.fitAllColumns')} + diff --git a/src/lib/components/LocalServersDialog.svelte b/src/lib/components/LocalServersDialog.svelte deleted file mode 100644 index 2e8d6e29..00000000 --- a/src/lib/components/LocalServersDialog.svelte +++ /dev/null @@ -1,481 +0,0 @@ - - - - - {#if view === 'list'} - - Local servers - Database servers running on this computer. - - - - -
- {#if env && !env.docker} -

- - {env.dockerInstalled ? "Docker isn't running. Start Docker Desktop for Docker servers; native Postgres works without it." : "Docker isn't installed. Native Postgres works without it."} -

- {/if} - - {#if servers.length === 0 && !loading} -
- -
-

No local servers yet

-

Postgres, MySQL, MariaDB, Redis or MongoDB, any version, ready in a minute.

-
- -
- {:else} -
    - {#each servers as s (s.id)} - {@const e = engineOf(s.engine)} -
  • - - - - -
    -

    {s.name}

    -

    - {#if s.problem}{s.problem} - {:else}{e.label} {s.version} · {s.running ? `127.0.0.1:${s.port}` : `port ${s.port}`} · {runtimeLabel(s.runtime)}{/if} -

    -
    - - - - - - - - void showLogs(s)}>Logs - void editPort(s)}>Change port… - - void remove(s)}>Delete with its data - - -
  • - {/each} -
- {/if} - - {#if env?.brew && brew.length} -
- - {#if brewOpen} -
    - {#each brew as b (b.name)} -
  • - {b.name} - -
  • - {/each} -
- {/if} -
- {/if} -
- {:else if view === 'port' && portFor} - - Change the port of {portFor.name} - Pick a new port for this server. - -
{ e.preventDefault(); void savePort() }}> - - {#if portError}{/if} -
- - -
-
- {:else if view === 'logs'} - - {logsFor} logs - The last lines the server wrote. - - -
{logs}
- {:else} - - New local server - Pick an engine, a version and where it runs. - -
{ e.preventDefault(); void create() }}> -
- Engine -
- {#each ENGINES as e (e.id)} - {@const on = fEngine === e.id} - - {/each} -
-
-
- Version -
- {#each engine.versions as v (v)} - {@const on = fVersion === v} - - {/each} -
-
-
- Runs on -
- {#each [ - { id: /** @type {const} */ ('docker'), Icon: Container, title: 'Docker', ok: dockerOk, - body: dockerOk ? 'A container on 127.0.0.1, its data in a Docker volume.' : env?.dockerInstalled ? 'Start Docker Desktop to use this.' : 'Install Docker Desktop to use this.' }, - { id: /** @type {const} */ ('native'), Icon: Cpu, title: 'Native', ok: nativeOk, - body: fEngine === 'postgres' ? `Downloads Postgres ${fVersion} once, about 30 MB.` : nativeOk ? `Uses the ${engine.label} installed here.` : `${engine.label} isn't installed on this computer.` }, - ] as r (r.id)} - {@const on = fRuntime === r.id} - - {/each} -
-
-
- - -
- {#if portTaken}

{portTaken.name} already uses port {portNum}.

{/if} - {#if progress} -
-

{progress.message}

-
-
-
-
- {/if} - {#if formError}{/if} -
- - -
-
- {/if} -
-
diff --git a/src/lib/components/LocalServersWindow.svelte b/src/lib/components/LocalServersWindow.svelte new file mode 100644 index 00000000..ada88ae7 --- /dev/null +++ b/src/lib/components/LocalServersWindow.svelte @@ -0,0 +1,773 @@ + + +{#snippet engineTile(/** @type {string} */ id, /** @type {string} */ size, /** @type {string | null} */ dot)} + + + {#if dot}{/if} + +{/snippet} + +{#snippet copyButton(/** @type {string} */ text, /** @type {string} */ what, /** @type {string} */ label)} + +{/snippet} + +{#snippet connectionCard(/** @type {{ engine: string, port: number }} */ s, /** @type {string} */ key)} + {@const url = connectionUrl(s)} +
+
+

Connection

+
+
+ {#each fields(s) as [k, v] (k)} +
{k}
+
{v}
+ {#if k !== 'Password'}{@render copyButton(v, `${key}:${k}`, `Copy ${k.toLowerCase()}`)}{:else}{/if} + {/each} +
+
+
+ {url} + {@render copyButton(url, `${key}:url`, 'Copy URL')} +
+
+ {envName(s.engine)}="{url}" + {@render copyButton(`${envName(s.engine)}="${url}"`, `${key}:env`, 'Copy as .env line')} +
+
+
+{/snippet} + +
+
+
+ +

Local Servers

+
+
+ + + {#if !isMac}{/if} +
+ +
+ + + + +
+ {#if selected === 'new'} +
{ e.preventDefault(); void create() }}> +
+

New server

+

Listens on 127.0.0.1 only, with no password. For development on this computer.

+
+
+

Engine

+
+ {#each ENGINES as e (e.id)} + {@const on = fEngine === e.id} + + {/each} +
+
+
+

Version

+
+ {#each engine.versions as v (v)} + {@const on = fVersion === v} + + {/each} +
+
+
+

Runs on

+
+ {#each [ + { id: /** @type {const} */ ('native'), Icon: Cpu, title: 'Native', ok: nativeOk, + body: fEngine === 'postgres' ? `Downloads Postgres ${fVersion} once, about 30 MB. No Docker needed.` : nativeOk ? `Uses the ${engine.label} installed on this computer.` : `${engine.label} isn't installed on this computer.` }, + { id: /** @type {const} */ ('docker'), Icon: Container, title: 'Docker', ok: dockerOk, + body: dockerOk ? 'A container, its data in a Docker volume.' : env?.dockerInstalled ? 'Start Docker Desktop to use this.' : 'Install Docker Desktop to use this.' }, + ] as r (r.id)} + {@const on = fRuntime === r.id} + + {/each} +
+
+
+ + +
+ {#if portTaken}

{portTaken.name} already uses port {portNum}.

+ {:else if portFound}

{portFound.source === 'docker' ? portFound.name : engineOf(portFound.engine).label} is already listening on port {portNum}.

{/if} + + {#if progress} +
+

{progress.message}

+
+
+
+
+ {/if} + {#if formError}{/if} +
+ {#if servers.length}{/if} + +
+
+ {:else if current} + {@const s = current} + {@const e = engineOf(s.engine)} + {@const isBusy = busy === s.id} +
+
+ {@render engineTile(s.engine, 'size-12', null)} +
+ {#if renaming} +
{ ev.preventDefault(); void saveName() }}> + + void saveName()} onkeydown={(ev) => { if (ev.key === 'Escape') renaming = false }} aria-label="Server name" /> +
+ {:else} + + {/if} +

{e.label} {s.version} · {runtimeLabel(s.runtime)}

+
+
+ + + + + + + + void editPort()}>Change port… + {#if s.runtime === 'native'} + void revealServer(s.id).catch((err) => toast.error('Could not open the folder', { description: String(err) }))}>Show data folder + {/if} + + void remove(s)}>Delete with its data + + +
+
+ + {#if failures[s.id] || s.problem} + + {/if} + + {#if editingPort} +
{ ev.preventDefault(); void savePort() }}> + + + + {#if portError}{/if} +
+ {/if} + + +
+
+
Status
+
+ + {isBusy ? (s.running ? 'Stopping' : 'Starting') : s.running ? 'Running' : 'Stopped'} +
+
+
+
{s.running ? 'Up for' : 'Port'}
+
{s.running ? uptime(s.startedAt, now) || 'Just started' : s.port}
+
+
+
Data
+
{s.runtime === 'docker' ? 'Docker volume' : formatBytes(s.diskBytes) || '0 B'}
+
+
+ + {@render connectionCard(s, s.id)} + + + +
+
+

Log

+ +
+
{logsFor === s.id ? logs || 'Nothing logged yet.' : ''}
+
+
+ {:else if currentFound} + {@const f = currentFound} + {@const e = engineOf(f.engine)} +
+
+ {@render engineTile(f.engine, 'size-12', null)} +
+

{f.source === 'docker' ? f.name : `${e.label} on ${f.port}`}

+

+ {e.label} · {f.source === 'docker' ? `Docker container${f.image ? `, ${f.image}` : ''}` : 'Running on this computer'} +

+
+ +
+

+ Stroke didn't start this server, so it can't stop it or read its log. It opens with the usual defaults below; if it asks for a password, set it in the connection. +

+ {@render connectionCard(f, `found:${f.port}`)} +
+ {:else if loaded} +
+ +
+

Pick a server

+

Or make one: Postgres, MySQL, MariaDB, Redis or MongoDB, any version, ready in a minute.

+
+ +
+ {/if} +
+
+
diff --git a/src/lib/components/MigrationsPage.svelte b/src/lib/components/MigrationsPage.svelte index 95905437..407a2a99 100644 --- a/src/lib/components/MigrationsPage.svelte +++ b/src/lib/components/MigrationsPage.svelte @@ -1,11 +1,12 @@
- +
setTool(v)} /> - {#if list.length} -

- {c.applied} applied - {#if files}{c.pending} pending{/if} - {#if c.failed}{c.failed} failed{/if} - {#if c.rolledBack}{c.rolledBack} rolled back{/if} -

- {/if}
-
- {#if projectError} - - {:else if !projectDir && list.length} -

- Showing what ran. to see pending migrations too. -

- {/if} - +
{#if error} - {:else if !loading && !list.length} + {:else if list.length} + +
+
+
+ Applied + {c.applied}{known ? ` / ${list.length}` : ''} +
+ {#if known} +
+ Pending + {c.pending} +
+ {/if} + {#if c.failed || c.rolledBack} +
+ Failed + {c.failed + c.rolledBack} +
+ {/if} +
+ Last applied + + {lastApplied ? `${splitName(lastApplied.name)[1]} · ${ago(lastApplied.appliedAt)}` : 'Nothing yet'} + +
+
+ {#if known} +
+
+
+ {/if} +
+ Read from {TABLE_NAME[source]}{source === 'd1' ? ' (Wrangler)' : ''} + {#if !known} + · + + to see what's pending + {/if} +
+ {#if known && c.pending} +
+ Apply {c.pending === 1 ? 'it' : `all ${c.pending}`}: + {applyCommand} + +
+ {/if} +
+ + {#if projectError} + + {/if} + + {#if known} + 3 ? 'w-[26rem] max-w-full' : 'w-80 max-w-full'} onchange={(v) => { filter = v; open = null }} /> + {/if} + + {#if !shown.length} +

Nothing {filter === 'failed' ? 'needs a look' : filter}.

+ {:else} +
    + {#each shown as m (m.name)} + {@const st = STATUS[m.status]} + {@const expanded = open === m.name} + {@const [seq, label] = splitName(m.name)} +
  1. + + {#if expanded} +
    +

    + {m.name} + {#if m.appliedAt}Applied {when(m.appliedAt)}{/if} + {#if m.durationMs != null}Took {took(m.durationMs)}{/if} + {#if m.steps != null}{m.steps} step{m.steps === 1 ? '' : 's'}{/if} +

    + {#if m.logs} +
    {m.logs}
    + {/if} + {#if m.sql} +
    + {#await import('./CodeEditor.svelte') then { default: CodeEditor }} + + {/await} +
    +
    + {#if onopensql} + + {/if} + +
    + {:else if !known} +

    Pick the project folder to see this migration's SQL.

    + {:else} +

    This migration's file isn't in the project folder.

    + {/if} +
    + {/if} +
  2. + {/each} +
+ {/if} + {:else if !loading}

{tool === 'prisma' ? 'No Prisma migrations' : 'No Drizzle migrations'} {rows === null ? 'in this database' : 'yet'}.

- {:else} -
    - {#each list as m (m.name)} - {@const st = STATUS[m.status]} - {@const expanded = open === m.name} -
  1. - - {#if expanded} -
    - {#if m.durationMs != null || m.steps != null} -

    - {[m.durationMs != null ? `Took ${took(m.durationMs)}` : '', m.steps != null ? `${m.steps} step${m.steps === 1 ? '' : 's'} applied` : ''].filter(Boolean).join(' · ')} -

    - {/if} - {#if m.logs} -
    {m.logs}
    - {/if} - {#if m.sql} -
    - {#await import('./CodeEditor.svelte') then { default: CodeEditor }} - - {/await} -
    -
    - {#if onopensql} - - {/if} - -
    - {:else if !files} -

    Pick the project folder to see this migration's SQL.

    - {/if} -
    - {/if} -
  2. - {/each} -
{/if}
diff --git a/src/lib/components/QuitHint.svelte b/src/lib/components/QuitHint.svelte index d1b89ec1..c100416e 100644 --- a/src/lib/components/QuitHint.svelte +++ b/src/lib/components/QuitHint.svelte @@ -10,6 +10,10 @@ let ready = $state(false) /** @type {ReturnType | null} */ let timer = null + /** How long the second press counts, for the draining bar. */ + let windowMs = $state(1600) + /** Bumped per hint so the bar restarts from full. */ + let run = $state(0) $effect(() => { let off = () => {} @@ -17,9 +21,11 @@ void import('@tauri-apps/api/event') .then(({ listen }) => listen('app-quit-hint', (e) => { ready = true + windowMs = Number(e.payload) || 1600 + run++ requestAnimationFrame(() => { shown = true }) if (timer) clearTimeout(timer) - timer = setTimeout(() => { shown = false }, Number(e.payload) || 1600) + timer = setTimeout(() => { shown = false }, windowMs) })) .then((un) => { if (gone) un(); else off = un }) .catch(() => {}) @@ -34,12 +40,35 @@ class="pointer-events-none fixed inset-x-0 top-[22vh] z-[100] flex justify-center" >
- Hold - - or press twice to quit +

+ Press again to quit +

+

or keep holding it

+ {#key run} + + {/key}
{/if} + + diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index b03354a2..5fbc083d 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -578,7 +578,31 @@ } } let showDockerModal = $state(false) - let showLocalServers = $state(false) + /** Local servers live in their own window; its Open button connects here. */ + async function openLocalServers() { + try { + const { getCurrentWindow } = await import('@tauri-apps/api/window') + const { openLocalServersWindow } = await import('$lib/local-servers.js') + await openLocalServersWindow(getCurrentWindow().label) + } catch (e) { + toast.error('Could not open Local servers', { description: String(e) }) + } + } + $effect(() => { + let off = () => {} + let gone = false + void import('@tauri-apps/api/event') + .then(({ listen }) => listen('local-server-connect', (e) => { + // Ids are stable per server: one opened before keeps what was set on + // it since (a password for a server Stroke didn't make). + const info = /** @type {any} */ (e.payload) + const saved = loadSavedConnections().find((c) => c.id === info.id) + void handleDockerConnect(saved ? { ...saved } : info) + })) + .then((un) => { if (gone) un(); else off = un }) + .catch(() => {}) + return () => { gone = true; off() } + }) let dockerInitialDb = $state(/** @type {string | null} */ (null)) /** Bottom query-log console visibility. */ let queryLogOpen = $state(false) @@ -3478,7 +3502,7 @@ let rowSearch = $state('') erd: () => openErdTab(), dataDiff: () => openDataDiffTab(), migrations: () => openMigrationsTab(), - localServers: () => { commandOpen = false; showLocalServers = true }, + localServers: () => { commandOpen = false; void openLocalServers() }, dashboard: () => openDashboardTab(), logs: () => openLogsTab(), extensions: () => openExtensionsTab(), @@ -8541,6 +8565,9 @@ let rowSearch = $state('') await connectByType(conn) await onConnected(conn, conn.id) showDockerModal = false + // Connected from another window (Local servers) while the connection + // screen was up: show the database, not the screen. + showConnectionModal = false } catch (e) { error = String(e) showDockerModal = false @@ -9932,11 +9959,7 @@ let rowSearch = $state('') dialect={dbType} onopeninsql={(sql) => { if (aiMode) exitAiMode(); void openQueryInEditor(sql) }} /> -{#if showLocalServers} - {#await import('./LocalServersDialog.svelte') then { default: LocalServersDialog }} - void handleDockerConnect(c)} /> - {/await} -{/if} + {#if dialogMounted.docker} {#await lazyDialogs.docker() then { default: DockerLaunchModal }} { commandOpen = false; openSchemaTimelineTab() }} opendatadiff={() => { commandOpen = false; openDataDiffTab() }} openmigrations={() => { commandOpen = false; openMigrationsTab() }} - openlocalservers={() => { commandOpen = false; showLocalServers = true }} + openlocalservers={() => { commandOpen = false; void openLocalServers() }} schemaContext={aiSchemaContext} onaskcontinue={handleAskContinue} /> diff --git a/src/lib/i18n.js b/src/lib/i18n.js index 60ac0d0c..d4fec1ce 100644 --- a/src/lib/i18n.js +++ b/src/lib/i18n.js @@ -189,6 +189,7 @@ const DICT = { 'menu.moveLast': 'Move to last', 'menu.resetOrder': 'Reset column order', 'menu.resetWidth': 'Reset column width', + 'menu.fitAllColumns': 'Fit all columns to content', 'menu.columnStats': 'Column stats', 'menu.highlight': 'Highlight', 'menu.noColor': 'No color', @@ -346,6 +347,7 @@ const DICT = { 'menu.moveLast': 'Mover al final', 'menu.resetOrder': 'Restablecer orden de columnas', 'menu.resetWidth': 'Restablecer ancho de columna', + 'menu.fitAllColumns': 'Ajustar todas las columnas al contenido', 'menu.columnStats': 'Estadísticas de columna', 'menu.highlight': 'Resaltar', 'menu.noColor': 'Sin color', @@ -502,6 +504,7 @@ const DICT = { 'menu.moveLast': 'Déplacer à la fin', 'menu.resetOrder': 'Réinitialiser l’ordre des colonnes', 'menu.resetWidth': 'Réinitialiser la largeur', + 'menu.fitAllColumns': 'Ajuster toutes les colonnes au contenu', 'menu.columnStats': 'Statistiques de colonne', 'menu.highlight': 'Surligner', 'menu.noColor': 'Aucune couleur', @@ -657,6 +660,7 @@ const DICT = { 'menu.moveLast': 'Ans Ende', 'menu.resetOrder': 'Spaltenreihenfolge zurücksetzen', 'menu.resetWidth': 'Spaltenbreite zurücksetzen', + 'menu.fitAllColumns': 'Alle Spalten an Inhalt anpassen', 'menu.columnStats': 'Spaltenstatistik', 'menu.highlight': 'Hervorheben', 'menu.noColor': 'Keine Farbe', diff --git a/src/lib/local-servers.js b/src/lib/local-servers.js index d7203471..22b918d0 100644 --- a/src/lib/local-servers.js +++ b/src/lib/local-servers.js @@ -4,7 +4,8 @@ import { invoke } from '@tauri-apps/api/core' /** - * @typedef {{ id: string, name: string, engine: string, version: string, port: number, runtime: 'docker' | 'native', createdAt: number, running: boolean, problem: string | null }} LocalServer + * @typedef {{ id: string, name: string, engine: string, version: string, port: number, runtime: 'docker' | 'native', createdAt: number, autostart: boolean, running: boolean, problem: string | null, startedAt: number | null, diskBytes: number | null, dataDir: string | null }} LocalServer + * @typedef {{ engine: string, port: number, source: 'docker' | 'process', name: string, image: string | null }} FoundServer * @typedef {{ docker: boolean, dockerInstalled: boolean, brew: boolean, native: string[] }} LocalEnv * @typedef {{ name: string, status: string, running: boolean }} BrewService */ @@ -60,8 +61,56 @@ export const startServer = (id) => invoke('local_server_start', { id }) export const stopServer = (id) => invoke('local_server_stop', { id }) /** @param {string} id */ export const deleteServer = (id) => invoke('local_server_delete', { id }) -/** @param {string} id @param {{ name?: string, port?: number }} patch */ -export const updateServer = (id, patch) => invoke('local_server_update', { id, name: patch.name ?? null, port: patch.port ?? null }) +/** @param {string} id @param {{ name?: string, port?: number, autostart?: boolean }} patch */ +export const updateServer = (id, patch) => invoke('local_server_update', { id, name: patch.name ?? null, port: patch.port ?? null, autostart: patch.autostart ?? null }) +/** Database servers on this computer that Stroke didn't make. @returns {Promise} */ +export const discoverServers = () => invoke('local_servers_discover') +/** @param {string} id */ +export const revealServer = (id) => invoke('local_server_reveal', { id }) +/** Open the Local servers window; `from` is the window that connects. @param {string} from */ +export const openLocalServersWindow = (from) => invoke('open_local_servers_window', { from }) +/** Hand a connection to an app window. @param {string} target @param {any} connection */ +export const connectIn = (target, connection) => invoke('local_server_connect_in', { target, connection }) + +/** + * The URL a server is reached at, as an app's DATABASE_URL would hold it. + * @param {{ engine: string, port: number }} s + */ +export function connectionUrl(s) { + switch (s.engine) { + case 'postgres': return `postgresql://postgres@127.0.0.1:${s.port}/postgres` + case 'mysql': + case 'mariadb': return `mysql://root@127.0.0.1:${s.port}/` + case 'redis': return `redis://127.0.0.1:${s.port}` + default: return `mongodb://127.0.0.1:${s.port}/?directConnection=true` + } +} + +/** The env var name apps usually read for an engine. @param {string} engine */ +export const envName = (engine) => (engine === 'redis' ? 'REDIS_URL' : engine === 'mongodb' ? 'MONGODB_URI' : 'DATABASE_URL') + +/** 1536 → "1.5 KB". @param {number | null | undefined} n */ +export function formatBytes(n) { + if (n == null) return '' + const u = ['B', 'KB', 'MB', 'GB', 'TB'] + let i = 0 + let v = n + while (v >= 1024 && i < u.length - 1) { v /= 1024; i++ } + return `${v < 10 && i ? v.toFixed(1) : Math.round(v)} ${u[i]}` +} + +/** How long since `ms`, short: "3 min", "2 h 5 min", "4 days". @param {number | null | undefined} ms @param {number} [now] */ +export function uptime(ms, now = Date.now()) { + if (!ms) return '' + const s = Math.max(0, Math.round((now - ms) / 1000)) + if (s < 60) return 'under a minute' + const m = Math.floor(s / 60) + if (m < 60) return `${m} min` + const h = Math.floor(m / 60) + if (h < 24) return m % 60 ? `${h} h ${m % 60} min` : `${h} h` + const d = Math.floor(h / 24) + return `${d} day${d === 1 ? '' : 's'}` +} /** @param {string} id @returns {Promise} */ export const serverLogs = (id) => invoke('local_server_logs', { id }) /** @param {number} from @returns {Promise} */ diff --git a/src/lib/migrations.js b/src/lib/migrations.js index 0ae779ce..8347e913 100644 --- a/src/lib/migrations.js +++ b/src/lib/migrations.js @@ -10,6 +10,9 @@ // counts as applied when its journal `when` is at or before the newest // created_at, which is how Drizzle's migrator decides; `hash` is the SHA-256 // of the .sql file. Drizzle records no failures (a failed run rolls back). +// Cloudflare D1 projects apply the same files with `wrangler d1 migrations +// apply`, which keeps its own `d1_migrations` (id, name, applied_at), `name` +// being the file name: every .sql file in the folder, in the journal or not. /** * @typedef {'applied' | 'pending' | 'failed' | 'rolled-back'} MigrationStatus @@ -143,6 +146,36 @@ export function mergeDrizzle(rows, files) { return out } +/** + * @param {Record[]} rows `d1_migrations` + * @param {MigrationFile[] | null} files every .sql file in the folder (name with `.sql`); null when no folder is set + * @returns {Migration[]} + */ +export function mergeD1(rows, files) { + const strip = (/** @type {string} */ n) => n.replace(/\.sql$/i, '') + /** @type {Map>} */ + const ran = new Map(rows.map((r) => [strip(String(r.name ?? '')), r])) + const fileByName = new Map((files ?? []).map((f) => [strip(f.name), f])) + const names = [...new Set([...fileByName.keys(), ...ran.keys()])].filter(Boolean).sort() + return names.map((name) => { + const row = ran.get(name) + const file = fileByName.get(name) + return { + name, + status: /** @type {MigrationStatus} */ (row ? 'applied' : 'pending'), + appliedAt: row ? toMs(row.applied_at) : null, + startedAt: null, + durationMs: null, + steps: null, + logs: null, + sql: file?.sql ?? null, + changed: false, + missingFile: !!files && !file, + attempts: row ? 1 : 0, + } + }) +} + /** @param {Migration[]} list */ export function counts(list) { const c = { applied: 0, pending: 0, failed: 0, rolledBack: 0, changed: 0 } @@ -159,10 +192,11 @@ export function counts(list) { /** * The SELECTs that read each tool's table, per engine family. Prisma's table * lives in the connection's schema; Drizzle's in `drizzle` on Postgres. - * @param {'prisma' | 'drizzle'} tool @param {string} family @param {string | null} schema + * @param {'prisma' | 'drizzle' | 'd1'} tool @param {string} family @param {string | null} schema * @returns {string[]} tried in order until one works */ export function migrationQueries(tool, family, schema) { + if (tool === 'd1') return family === 'd1' || family === 'sqlite' ? ['SELECT id, name, applied_at FROM "d1_migrations" ORDER BY id'] : [] const q = family === 'mysql' ? (/** @type {string} */ s) => `\`${s.replace(/`/g, '``')}\`` : (/** @type {string} */ s) => `"${s.replace(/"/g, '""')}"` if (tool === 'prisma') { const cols = 'id, checksum, finished_at, migration_name, logs, rolled_back_at, started_at, applied_steps_count' diff --git a/src/lib/migrations.test.js b/src/lib/migrations.test.js index a66e829d..9dd5eff0 100644 --- a/src/lib/migrations.test.js +++ b/src/lib/migrations.test.js @@ -74,3 +74,15 @@ describe('helpers', () => { expect(rowsOf({ columns: [{ name: 'a' }, { name: 'b' }], rows: [[1, 2]] })).toEqual([{ a: 1, b: 2 }]) }) }) + +describe('mergeD1', () => { + it('matches d1_migrations names to the folder files', async () => { + const { mergeD1 } = await import('./migrations.js') + const rows = [{ id: 1, name: '0000_init.sql', applied_at: '2026-01-02 10:00:00' }, { id: 2, name: 'old.sql', applied_at: '2026-01-03 10:00:00' }] + const files = [{ name: '0000_init.sql', sql: 'a', checksum: 'x', when: null }, { name: '0001_more.sql', sql: 'b', checksum: 'y', when: null }] + const list = mergeD1(rows, files) + expect(list.map((m) => [m.name, m.status, m.missingFile])).toEqual([['0000_init', 'applied', false], ['0001_more', 'pending', false], ['old', 'applied', true]]) + expect(list[0].appliedAt).toBe(Date.parse('2026-01-02T10:00:00Z')) + expect(mergeD1(rows, null).every((m) => m.status === 'applied')).toBe(true) + }) +}) diff --git a/src/lib/stores/dashboards.js b/src/lib/stores/dashboards.js index e32b6c2f..15a3f34c 100644 --- a/src/lib/stores/dashboards.js +++ b/src/lib/stores/dashboards.js @@ -91,6 +91,40 @@ export function switchDashboardsConnection(connectionId) { activeDashboardId.set(loadActiveId(_connId)) } +/** Write pending edits now (another window is about to read them). */ +export function flushDashboards() { + persistDashboards.flush() +} + +/** The connection key the dashboards are stored under right now. */ +export function dashboardsConnectionId() { + return _connId +} + +/** + * The connection key whose dashboards hold `dashId`, `preferred` first. A + * dashboard window opened with a key the tab didn't store under (an older + * build, a connection matched another way) still finds its dashboard. + * @param {string} dashId @param {string} preferred @returns {string | null} + */ +export function findDashboardScope(dashId, preferred) { + /** @param {string | null} raw */ + const has = (raw) => { + try { + const list = JSON.parse(raw ?? 'null') + return Array.isArray(list) && list.some((d) => d?.id === dashId) + } catch { return false } + } + try { + if (preferred && has(localStorage.getItem(KEY(preferred)))) return preferred + for (let i = 0; i < localStorage.length; i++) { + const k = localStorage.key(i) + if (k?.startsWith('stroke:dashboards:') && has(localStorage.getItem(k))) return k.slice('stroke:dashboards:'.length) + } + } catch { /* storage unavailable */ } + return null +} + /** @param {string} name @returns {Dashboard} */ export function createDashboard(name) { const id = `dash-${Date.now()}-${Math.random().toString(36).slice(2, 6)}` From ca4b41ebd74952150f2eb6c1a1361cc1fc0bcdef Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:13:15 +0000 Subject: [PATCH 313/317] chore: version 2.20.3 (#305) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e17bf85b..cc35ba7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.20.3] - 2026-11-19 + +### Changes +- Move local servers to their own window; fix dashboard window and D1 migrations (#305) + + ## [2.20.2] - 2026-11-18 ### Changes diff --git a/package.json b/package.json index 75335425..f8835868 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.20.2", + "version": "2.20.3", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c3fb1f06..f73e43df 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.20.2", + "version": "2.20.3", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From e6d9b94a83f56cdc7d412326439757ac33f72cbe Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Thu, 19 Nov 2026 10:45:15 +0545 Subject: [PATCH 314/317] Hold the built-in AI chat to its access level; redesign Migrations (#306) - The built-in chat (Stroke Free, API keys) ran any write, asking only before destructive ones. Its execute_sql now goes through the classifier the MCP server enforces for local agents (sql_access_level), and a statement above the chat's level is refused with the SQL handed back. The access control under the composer shows for every model, and the system prompt says what the level allows. - Migrations: a stat row (applied, pending, problems, last applied) with a three-part bar, the apply command on its own line, a folder prompt when none is picked, search, and the list as a timeline grouped by the month it ran, pending last. Dates fit one line in any font. - TODO: tick off what shipped. --- TODO_TODAY.md | 15 +- src-tauri/src/commands.rs | 11 + src-tauri/src/lib.rs | 1 + src/lib/api.js | 9 + src/lib/components/AgentComposerChips.svelte | 5 +- src/lib/components/AiChat.svelte | 45 ++- src/lib/components/MigrationsPage.svelte | 284 +++++++++++-------- 7 files changed, 243 insertions(+), 127 deletions(-) diff --git a/TODO_TODAY.md b/TODO_TODAY.md index 6a17a89b..6729b7eb 100644 --- a/TODO_TODAY.md +++ b/TODO_TODAY.md @@ -1,6 +1,6 @@ # TODO -What is open as of 2026-11-17 (nightly at 2.16.8, stable at 2.3.0). Security +What is open as of 2026-11-19 (nightly at 2.20.x, stable at 2.3.0). Security items live in `TODO_SECURITY.md`. ## v3 @@ -19,13 +19,15 @@ release with a freeze and a test pass, not a plain promote. In order: v3 build through the updater. Connections, keychain passwords, settings, query history, notebooks and Pro all have to survive. On macOS, Windows and Linux: the updater is what breaks first. -- [ ] **AI access levels for built-in models.** The Read only / Read & write +- [x] **AI access levels for built-in models.** Done in 2.20.4: every + execute_sql is classified by `access.rs` and refused above the level. + Was: The Read only / Read & write control exists for local agents only (enforced by the MCP server). Built-in models (Stroke Free, API keys) can run writes, asking only before destructive ones. Enforce a level in `AiChat`'s `execute_sql` with the same classifier as `src-tauri/src/mcp/access.rs`, then show the control. -- [ ] **echarts 6** (PR #14): clears the echarts XSS advisory; the charts need +- [x] **echarts 6** (on 6.1.0, audit clean): clears the echarts XSS advisory; the charts need testing. - [ ] **Real hardware.** Windows: theme switching and zoom without flicker, Alt+K in the SQL editor, the title bar with the sidebar on the right, @@ -49,18 +51,19 @@ release with a freeze and a test pass, not a plain promote. In order: ## Next up -- [ ] **Layout control.** Three buttons in the title bar for the sidebar (⌘B), +- [x] **Layout control.** Dropped; the SQL results bottom/right switch + replaced it (2.19.x). Was: Three buttons in the title bar for the sidebar (⌘B), the terminal panel (⌘J) and the docked AI panel (⌘⌥B), the open edge filled. Built on the `layout-and-dashboard` branch; check it in the running app on every OS before merging. -- [ ] **Dashboard tab redesign.** A 12-column grid of chart cards, each with a +- [x] **Dashboard tab redesign.** Shipped, plus a dashboard window. Was: A 12-column grid of chart cards, each with a status dot, refresh, an auto-refresh interval, a title and its error on the card. Resize and rearrange cards, add one from any saved query, and save the layout. - [ ] **Admin metrics page** on stroke.click, for me only: sign-ups, active trials, trial-to-Pro conversion, revenue, downloads, active devices, app versions in use, countries, backups and sponsors, over time. -- [ ] **Local database servers.** Postgres, MySQL and Redis side by side in +- [x] **Local database servers.** Shipped as their own window. Was: Postgres, MySQL and Redis side by side in any version, with Start, Stop, the port and Open, per server on Docker or as native binaries; Homebrew services listed too. diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index c340ab6c..4783573e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1669,6 +1669,17 @@ pub async fn share_execute_sql(state: Db<'_>, sql: String, read_only: bool) -> R crate::mcp::tools::call_tool(&conn, "execute_sql", &serde_json::json!({ "sql": sql, "max_rows": 1000 }), read_only).await } +/// The access level a script needs on the open connection (0 read, 1 read & +/// write, 2 modify schema, 3 dangerous), by the classifier the MCP server +/// enforces. The built-in AI chat checks it before running a statement, so +/// its access setting holds the same way a local agent's does. +#[tauri::command] +pub async fn sql_access_level(state: Db<'_>, sql: String) -> Result { + use crate::mcp::access; + let dialect = require_conn(&state).map(|c| access::Dialect::for_driver(c.driver())).unwrap_or(access::Dialect::Sql); + Ok(access::script_level_in(dialect, &sql)) +} + #[tauri::command] pub async fn pg_execute_sql_multi( state: Db<'_>, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index af62ba02..102635e7 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -693,6 +693,7 @@ pub fn run() { commands::read_file, commands::open_new_window, commands::open_dashboard_window, + commands::sql_access_level, launch::take_open_request, commands::reveal_window, commands::restart_app, diff --git a/src/lib/api.js b/src/lib/api.js index 80db1e01..7bc335f4 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -1510,6 +1510,15 @@ export async function cancelQuery(queryId) { } /** @param {string} sql @param {string} [queryId] */ +/** + * The access level a script needs on the open connection: 0 read, 1 read & + * write, 2 modify schema, 3 dangerous (src-tauri/src/mcp/access.rs). + * @param {string} sql @returns {Promise} + */ +export async function sqlAccessLevel(sql) { + return await inv('sql_access_level', { sql }) +} + export async function executeSql(sql, queryId) { if (isWriteSql(sql)) assertWritable('run that statement') const _t0 = performance.now() diff --git a/src/lib/components/AgentComposerChips.svelte b/src/lib/components/AgentComposerChips.svelte index 06778f80..e6dd75ac 100644 --- a/src/lib/components/AgentComposerChips.svelte +++ b/src/lib/components/AgentComposerChips.svelte @@ -29,8 +29,9 @@ max: 'The most reasoning the model allows.', } - // Enforced by Stroke's MCP server (src-tauri/src/mcp/access.rs), not left - // to the model: a statement above the level is refused. + // Enforced, not left to the model: Stroke's MCP server refuses a local + // agent's statement above the level, and the built-in chat checks each + // execute_sql with the same classifier (src-tauri/src/mcp/access.rs). const ACCESS = [ { id: 'read', label: 'Read only', note: 'SELECT and EXPLAIN. Changes come back as SQL for you to run.', icon: Lock }, { id: 'write', label: 'Read & write', note: 'Inserts, and updates or deletes with a WHERE clause.', icon: PenLine }, diff --git a/src/lib/components/AiChat.svelte b/src/lib/components/AiChat.svelte index 61c29322..ac232a3c 100644 --- a/src/lib/components/AiChat.svelte +++ b/src/lib/components/AiChat.svelte @@ -48,7 +48,7 @@ import { Input } from "$lib/components/ui/input/index.js"; import { Label } from "$lib/components/ui/label/index.js"; import { cn } from "$lib/utils.js"; - import { executeSql, executeSqlOnConnection, aiWebSearch, aiFetchPage, saveExportAs, agentStart, agentSend, agentInterrupt, agentStop } from "$lib/api.js"; + import { sqlAccessLevel, executeSql, executeSqlOnConnection, aiWebSearch, aiFetchPage, saveExportAs, agentStart, agentSend, agentInterrupt, agentStop } from "$lib/api.js"; import { queryLanguageFor, sampleQuery, describeFromSample } from "$lib/ai-query-languages.js"; import { profileAgent, @@ -429,6 +429,9 @@ convList = await listConversations(chatMatch ?? (connectionId || undefined)); } + /** Access levels as the backend ranks them (src-tauri/src/mcp/access.rs). @type {Record} */ + const ACCESS_RANK = { read: 0, write: 1, modify: 2, dangerous: 3 }; + const ACCESS_NAMES = ["Read only", "Read & write", "Modify schema", "Dangerous"]; /** Engines where execute_sql's `database` argument can open another database by name. */ const CROSS_DB_ENGINES = new Set(["postgres", "cockroachdb", "mysql", "mariadb", "mssql", "clickhouse"]); @@ -2386,7 +2389,17 @@ planSteps: true, }); const ci = $aiChatParams.customInstructions.trim(); - turnSystemPrompt = ci ? `${ci}\n\n---\n\n${basePrompt}` : basePrompt; + // What execute_sql will run, so the model proposes SQL instead of + // sending statements the access level refuses. + const rank = isReadOnly() ? 0 : ACCESS_RANK[$agentPrefs.access] ?? 0; + const accessNote = `=== ACCESS ===\nThe user set this chat to "${ACCESS_NAMES[rank]}". ${[ + "execute_sql runs reads only (SELECT, WITH, EXPLAIN, SHOW). For anything that changes data or schema, give the SQL in a ```sql block for the user to run, and say they can raise the access level under the composer.", + "execute_sql runs reads, INSERTs, and UPDATEs or DELETEs with a WHERE clause. Schema changes go in a ```sql block for the user.", + "execute_sql runs reads, writes with a WHERE clause, and CREATE, ALTER and indexes. Nothing that drops or truncates: give that SQL in a ```sql block.", + "execute_sql runs anything; destructive statements still ask the user first.", + ][rank]}`; + const withAccess = `${basePrompt}\n\n${accessNote}`; + turnSystemPrompt = ci ? `${ci}\n\n---\n\n${withAccess}` : withAccess; // Smart context management: sliding window + optional summarization. // managedLen marks where new messages start after the turn - used to append to rawApiHistory. @@ -3280,6 +3293,28 @@ }); return; } + // The chat's access level, held the way the MCP server holds a local + // agent's: the statement is classified on the engine it would run + // on, and anything above the level isn't run. + { + const allowed = ACCESS_RANK[$agentPrefs.access] ?? 0; + /** @type {number} */ + let needs = 3; + try { needs = Number(await sqlAccessLevel(sql)); } catch { /* unknown: treat as the highest */ } + if (needs > allowed) { + const now = Date.now(); + const level = ACCESS_NAMES[needs] ?? "Dangerous"; + addBuiltinStep({ id: String(call.id || uid()), tool: "execute_sql", op: "query", detail: sql, status: "error", error: `Not run: needs "${level}" access, and the chat is set to "${ACCESS_NAMES[allowed]}".`, startedAt: now, endedAt: now }); + apiHistory.push({ + role: "tool", + tool_call_id: call.id, + content: JSON.stringify({ + error: `Refused: this needs "${level}" access and the chat is set to "${ACCESS_NAMES[allowed]}". Do not retry it. Give the user the SQL in a \`\`\`sql block to review and run, or ask them to raise the access level under the composer.`, + }), + }); + return; + } + } if (isDestructiveSql(sql)) { const confirmed = await waitForConfirm(sql); if (!confirmed) { @@ -4842,11 +4877,7 @@ {/if} - {#if profileAgent($aiSettings)} - - {:else if $readOnlyMode} - Read only - {/if} +
{/snippet} diff --git a/src/lib/components/MigrationsPage.svelte b/src/lib/components/MigrationsPage.svelte index 407a2a99..2332c375 100644 --- a/src/lib/components/MigrationsPage.svelte +++ b/src/lib/components/MigrationsPage.svelte @@ -19,6 +19,8 @@ import Check from '@lucide/svelte/icons/check' import GitMerge from '@lucide/svelte/icons/git-merge' import TriangleAlert from '@lucide/svelte/icons/triangle-alert' + import Search from '@lucide/svelte/icons/search' + import { Input } from '$lib/components/ui/input/index.js' let { /** @type {{ id: string, name?: string } | null} */ @@ -182,10 +184,10 @@ ) const STATUS = { - applied: { label: 'Applied', dot: 'bg-success', text: 'text-muted-foreground' }, - pending: { label: 'Pending', dot: 'bg-transparent ring-[1.5px] ring-inset ring-warning', text: 'text-warning' }, - failed: { label: 'Failed', dot: 'bg-destructive', text: 'text-destructive' }, - 'rolled-back': { label: 'Rolled back', dot: 'bg-warning', text: 'text-warning' }, + applied: { label: 'Applied', dot: 'bg-success', text: 'text-muted-foreground', badge: 'bg-success/12 text-success' }, + pending: { label: 'Pending', dot: 'bg-warning', text: 'text-warning', badge: 'bg-warning/15 text-warning' }, + failed: { label: 'Failed', dot: 'bg-destructive', text: 'text-destructive', badge: 'bg-destructive/12 text-destructive' }, + 'rolled-back': { label: 'Rolled back', dot: 'bg-warning', text: 'text-warning', badge: 'bg-warning/15 text-warning' }, } /** "0013_sync" → ["0013", "sync"]; Prisma's "20240101120000_init" too. @param {string} name */ @@ -207,6 +209,37 @@ } /** The editor's height for a migration's SQL: its lines, long ones counted as they wrap. @param {string} sql */ const sqlHeight = (sql) => Math.min(360, sql.split('\n').reduce((n, l) => n + Math.max(1, Math.ceil(l.length / 80)), 1) * 22 + 12) + /** "Jun 8, 12:07" this year, "Jun 8, 2025" before: one line, whatever the font. @param {number | null} ms */ + function shortDate(ms) { + if (!ms) return '' + const d = new Date(ms) + return d.getFullYear() === new Date().getFullYear() + ? d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false }) + : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) + } + + let query = $state('') + const found = $derived.by(() => { + const q = query.trim().toLowerCase() + return q ? shown.filter((m) => m.name.toLowerCase().includes(q) || m.name.replace(/_/g, ' ').toLowerCase().includes(q)) : shown + }) + /** Applied migrations by the month they ran, newest month last; pending at the end. */ + const groups = $derived.by(() => { + /** @type {{ key: string, label: string, items: Migration[] }[]} */ + const out = [] + for (const m of found) { + const at = m.appliedAt ?? m.startedAt + const key = m.status === 'pending' ? 'pending' : at ? new Date(at).toISOString().slice(0, 7) : 'unknown' + let g = out.find((x) => x.key === key) + if (!g) { + const label = key === 'pending' ? 'Not applied yet' : key === 'unknown' ? 'Applied' : new Date(/** @type {number} */ (at)).toLocaleDateString(undefined, { month: 'long', year: 'numeric' }) + g = { key, label, items: [] } + out.push(g) + } + g.items.push(m) + } + return out.sort((a, b) => (a.key === 'pending' ? 1 : b.key === 'pending' ? -1 : a.key.localeCompare(b.key))) + }) /** @param {number | null} ms */ const took = (ms) => (ms == null ? '' : ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`) /** The folder's last two parts, for the header. @param {string} p */ @@ -268,132 +301,159 @@
{:else if list.length} - -
-
-
- Applied - {c.applied}{known ? ` / ${list.length}` : ''} + +
+
+
+
Applied
+
{c.applied}{#if known}of {list.length}{/if}
- {#if known} -
- Pending - {c.pending} -
- {/if} - {#if c.failed || c.rolledBack} -
- Failed - {c.failed + c.rolledBack} -
- {/if} -
- Last applied - - {lastApplied ? `${splitName(lastApplied.name)[1]} · ${ago(lastApplied.appliedAt)}` : 'Nothing yet'} - +
+
Pending
+
{known ? c.pending : '?'}
-
+
+
Problems
+
{c.failed + c.rolledBack + c.changed}
+
+
+
Last applied
+
+ {lastApplied ? splitName(lastApplied.name)[1] : 'Nothing yet'} + {#if lastApplied}{ago(lastApplied.appliedAt)}{/if} +
+
+
{#if known} -
-
+ + {/if} -
- Read from {TABLE_NAME[source]}{source === 'd1' ? ' (Wrangler)' : ''} - {#if !known} - · - - to see what's pending +
+ Read from {TABLE_NAME[source]}{source === 'd1' ? ', written by Wrangler' : ''} + {#if known && c.pending} +
+ Apply {c.pending === 1 ? 'it' : `the ${c.pending}`} + {applyCommand} + +
{/if}
- {#if known && c.pending} -
- Apply {c.pending === 1 ? 'it' : `all ${c.pending}`}: - {applyCommand} - -
- {/if}
+ {#if !known} +
+ +
+

See what hasn't run yet

+

Pick the project folder (the one with {tool === 'prisma' ? 'prisma/migrations' : 'drizzle/ or migrations/'}). Stroke compares the files with what this database ran, and shows each migration's SQL.

+
+ +
+ {/if} + {#if projectError} {/if} - {#if known} - 3 ? 'w-[26rem] max-w-full' : 'w-80 max-w-full'} onchange={(v) => { filter = v; open = null }} /> - {/if} + +
+
+ + +
+ {#if known} + 3 ? 'w-[26rem] max-w-full' : 'w-80 max-w-full'} onchange={(v) => { filter = v; open = null }} /> + {/if} +
- {#if !shown.length} -

Nothing {filter === 'failed' ? 'needs a look' : filter}.

+ {#if !found.length} +

{query.trim() ? `No migration matches "${query.trim()}".` : `Nothing ${filter === 'failed' ? 'needs a look' : filter}.`}

{:else} -
    - {#each shown as m (m.name)} - {@const st = STATUS[m.status]} - {@const expanded = open === m.name} - {@const [seq, label] = splitName(m.name)} -
  1. - - {#if expanded} -
    -

    - {m.name} - {#if m.appliedAt}Applied {when(m.appliedAt)}{/if} - {#if m.durationMs != null}Took {took(m.durationMs)}{/if} - {#if m.steps != null}{m.steps} step{m.steps === 1 ? '' : 's'}{/if} -

    - {#if m.logs} -
    {m.logs}
    - {/if} - {#if m.sql} -
    - {#await import('./CodeEditor.svelte') then { default: CodeEditor }} - - {/await} -
    -
    - {#if onopensql} - - {/if} - -
    - {:else if !known} -

    Pick the project folder to see this migration's SQL.

    - {:else} -

    This migration's file isn't in the project folder.

    - {/if} -
    - {/if} -
  2. +
    + {#each groups as g (g.key)} +
    +

    + {g.label} + {g.items.length} +

    +
      + {#each g.items as m, i (m.name)} + {@const st = STATUS[m.status]} + {@const expanded = open === m.name} + {@const [seq, label] = splitName(m.name)} +
    1. + + {#if expanded} +
      +

      + {m.name} + {#if m.appliedAt}Applied {when(m.appliedAt)}{/if} + {#if m.durationMs != null}Took {took(m.durationMs)}{/if} + {#if m.steps != null}{m.steps} step{m.steps === 1 ? '' : 's'}{/if} +

      + {#if m.logs} +
      {m.logs}
      + {/if} + {#if m.sql} +
      + {#await import('./CodeEditor.svelte') then { default: CodeEditor }} + + {/await} +
      +
      + {#if onopensql} + + {/if} + +
      + {:else if !known} +

      Pick the project folder to see this migration's SQL.

      + {:else} +

      This migration's file isn't in the project folder.

      + {/if} +
      + {/if} +
    2. + {/each} +
    +
    {/each} -
+
{/if} {:else if !loading}

From 1602475977aa4f145a93979a8fcb2e8b9cf551df Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:00:28 +0000 Subject: [PATCH 315/317] chore: version 2.20.4 (#306) --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc35ba7d..c32b2346 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Stroke are listed here, newest first. --- +## [2.20.4] - 2026-11-19 + +### Changes +- Hold the built-in AI chat to its access level; redesign Migrations (#306) + + ## [2.20.3] - 2026-11-19 ### Changes diff --git a/package.json b/package.json index f8835868..9d70be9a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.20.3", + "version": "2.20.4", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f73e43df..516f7d43 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.20.3", + "version": "2.20.4", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", From e875078e5eb84538205e5b66feaf9362d798c0ff Mon Sep 17 00:00:00 2001 From: Nischal Dahal Date: Thu, 19 Nov 2026 12:54:45 +0545 Subject: [PATCH 316/317] Stroke 3.0: release notes, What's new, AI chat in a tab on by default (#307) AI chat in a tab stays in Labs but is on by default, turned on once for installs that saved it off before 3.0. The v3 What's new leads with the AI tab, local servers, migrations and scheduled backups, each with a button that opens it. The v3 changeset is the release notes for everyone coming from 2.3.0. --- .changeset/v3.md | 33 ++++++++++++++++++++++++ TODO_TODAY.md | 18 +++++++++---- src/lib/components/StudioShell.svelte | 22 +++++++++++----- src/lib/stores/settings.dom.test.js | 36 ++++++++++++++++++++++++++ src/lib/stores/settings.js | 16 +++++++++--- src/lib/whats-new.js | 37 ++++++++++++++++++++++++++- 6 files changed, 145 insertions(+), 17 deletions(-) create mode 100644 .changeset/v3.md create mode 100644 src/lib/stores/settings.dom.test.js diff --git a/.changeset/v3.md b/.changeset/v3.md new file mode 100644 index 00000000..2c4d294a --- /dev/null +++ b/.changeset/v3.md @@ -0,0 +1,33 @@ +### New Features + +#### Stroke 3 +- **One account, three computers** - Sign in with GitHub or Google. Your license comes with your account and covers up to 3 computers; manage them at stroke.click/app. Paid Pro keeps working offline for 30 days. +- **Sync** - Workspaces, connections, settings, saved queries, charts and dashboards sync between your computers, end-to-end encrypted. +- **21 databases** - New since 2.3: Oracle, Elasticsearch, OpenSearch, Xata and SingleStore, alongside MongoDB, CouchDB, Cassandra, DynamoDB, Firestore and Redis. +- **Several databases at once (Labs)** - Keep more than one connection open, each with its tabs, and switch instantly. + +#### AI +- **AI chat in a tab** - AI opens beside your tables instead of taking over the window, and its chats live in the sidebar. On by default in this version; switch it off in Settings → Labs. +- **Access levels for every model** - Read only, Read & write, Modify schema or Dangerous, now enforced for the built-in models and API keys too, not only local agents. +- **Plans and step timeline** - A multi-step request shows its plan, each tool call is one row with its result, and a finished turn says what changed. + +#### Your databases +- **Local database servers** - Run Postgres, MySQL or Redis on this computer in any version, in their own window, start them with Stroke, and see the servers already running here. +- **Migrations** - Drizzle, Prisma, Wrangler (D1) and plain SQL folders: what has run, what is pending, and the SQL of each. +- **Scheduled backups** - To Stroke Cloud or your own S3, end-to-end encrypted, with a preview of a dump and its encoding before you restore. +- **Docker in one step** - ⌘K → Docker starts any of 18 databases, already connected. +- **Dashboards** - Live chart cards that refresh themselves, open in their own window, full screen. +- **Paste any connection string** - .env lines, ORM URLs and key/value strings land on the right form. + +#### Everywhere +- **Leader key** - Press ⌘; (Ctrl+; on Windows and Linux), then one key. +- **Share as a web studio (Labs)** - Share a database through a link that opens in any browser. +- **SQL notebooks** - Variables, import and export, autosave. +- **Results beside the editor** - Put SQL results below or beside the editor. +- **Quieter updates** - Updates download in the background and install as Stroke quits. Homebrew, Scoop, AUR, .deb and .rpm installs update through their package manager. + +### Changes +- A faster start: Settings, the command palette and one-off dialogs load on first use, and the data grid loads lazily. +- Windows and Linux get a 40px title bar with native window buttons, and native Wayland on Linux. +- echarts 6.1, which fixes an XSS advisory; charts look as they did. +- The Explorer tree stays in Labs (Settings → Labs). diff --git a/TODO_TODAY.md b/TODO_TODAY.md index 6729b7eb..5cc79570 100644 --- a/TODO_TODAY.md +++ b/TODO_TODAY.md @@ -9,8 +9,11 @@ Stable has been on 2.3.0 since 2026-11-02, with 273 commits on `nightly` since. Every Stable user jumps across all of it in one update, so v3 is a release with a freeze and a test pass, not a plain promote. In order: -- [ ] **Feature freeze.** Fixes only on `nightly` until v3 ships. -- [ ] **Decide what leaves Labs.** Several connections at once and the tree +- [x] **Feature freeze.** Fixes only on `nightly` until v3 ships. +- [x] **Decide what leaves Labs.** Decided for 3.0: AI chat in a tab stays + in Labs but is on by default (turned on once for everyone); the tree + sidebar and several connections stay opt-in. + Was: Several connections at once and the tree sidebar: graduate both to the default (they are what the site and the email show) and test them as the default on every engine, or ship v3 with them still opt-in. @@ -39,14 +42,19 @@ release with a freeze and a test pass, not a plain promote. In order: - [ ] **The license change**, settled before the release: the same wording on the site's legal pages, in the app (license page, About) and in the email. -- [ ] **Release notes: what changed since 2.3.0.** Written once, used for the +- [x] **Release notes: what changed since 2.3.0.** Written once, used for the release page, the in-app What's new, the email and the launch posts. -- [ ] **Rollback plan.** Keep the 2.3.0 installers easy to find, and know how +- [x] **Rollback plan.** If v3 breaks on day one, run + `gh release edit v2.3.0 --repo stroke-app/stroke --latest`: the Stable + updater reads `releases/latest/download/latest.json`, so nobody else + moves to v3. The updater never downgrades, so anyone already on v3 needs + a 3.0.1 fix. + Before: Keep the 2.3.0 installers easy to find, and know how to point the Stable updater back at 2.3.0 if v3 breaks something on day one. - [ ] **Release candidate.** A few days of daily use on Nightly with nothing new landing. -- [ ] **Ship it.** Label the release PR `release:major` (CONTRIBUTING.md), then +- [x] **Ship it.** Label the release PR `release:major` (CONTRIBUTING.md), then Actions, *Promote nightly to stable*. ## Next up diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 5fbc083d..1d3797ee 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -2952,7 +2952,7 @@ let rowSearch = $state('') function handleWhatsNewAction(id) { if (id === 'enable-tree-sidebar') { updateSettings({ sidebarStyle: 'tree' }) - toast.success('Explorer tree is on', { description: 'Switch back any time in Settings → General.' }) + toast.success('Explorer tree is on', { description: 'Switch back any time in Settings → Labs.' }) } else if (id === 'open-themes') { menuActions.theme?.() } else if (id === 'open-shortcuts') { @@ -2961,10 +2961,18 @@ let rowSearch = $state('') showConnectionModal = true } else if (id === 'enable-ai-tab') { updateSettings({ aiInTab: true }) - toast.success('AI chat opens in a tab now', { description: 'Switch back any time in Settings → General.' }) + toast.success('AI chat opens in a tab now', { description: 'Switch back any time in Settings → Labs.' }) } else if (id === 'open-docker') { commandPage = 'docker' commandOpen = true + } else if (id === 'open-ai') { + openAiTab() + } else if (id === 'open-local-servers') { + void openLocalServers() + } else if (id === 'open-migrations') { + openMigrationsTab() + } else if (id === 'open-backups') { + openBackupTab() } } @@ -3191,7 +3199,7 @@ let rowSearch = $state('') } /** The full-window AI chat, so the title bar's sidebar button can drive its chat list. @type {any} */ let aiFullRef = $state(null) - /** The AI chat in its tab (beta), for messages sent from elsewhere. @type {any} */ + /** The AI chat in its tab, for messages sent from elsewhere. @type {any} */ /** * The AI tab's chat instances. One is on screen (`aiPrimaryKey`); the others * are chats still replying after you started or opened another, kept mounted @@ -4543,7 +4551,7 @@ let rowSearch = $state('') clearTableEditor() } - /** AI chat: a tab beside the others (beta setting), or the window's AI mode. */ + /** AI chat: a tab beside the others, or the window's AI mode. */ function openAiTab() { if (!$hasPro) { showProGate = true; return } if ($appAiInTab && connection) { @@ -8242,7 +8250,7 @@ let rowSearch = $state('') function enterAiMode() { if (!connection) return - // AI in a tab (beta): every way into AI mode (⌘⇧E, the title bar, the + // AI in a tab: every way into AI mode (⌘⇧E, the title bar, the // palette) opens the tab instead. if ($appAiInTab) { openSingletonTab({ find: findAiTab, create: createAiTab }); return } aiMode = true @@ -10640,7 +10648,7 @@ let rowSearch = $state('') {#snippet sharedContent()} {#if activeTab?.kind === 'ai'} - + {:else if activeTab?.kind === 'schema'} {#await import('./SchemaPage.svelte')}{:then { default: SchemaPage }} @@ -10703,7 +10711,7 @@ let rowSearch = $state('')

{/if} - {#if aiTabEverOpened && $appAiInTab}
({ invoke: vi.fn(async () => '') })) + +/** Minimal in-memory localStorage for the node test environment. */ +function installLocalStorage(seed = {}) { + const map = new Map(Object.entries(seed)) + globalThis.localStorage = /** @type {any} */ ({ + getItem: (k) => (map.has(k) ? map.get(k) : null), + setItem: (k, v) => map.set(k, String(v)), + removeItem: (k) => map.delete(k), + }) + return map +} + +describe('AI chat in a tab is on by default', () => { + beforeEach(() => vi.resetModules()) + + it('is on for a new install', async () => { + installLocalStorage() + const { loadSettings } = await import('./settings.js') + expect(loadSettings().aiInTab).toBe(true) + }) + + it('turns on once for settings saved before 3.0, then keeps a later choice', async () => { + const store = installLocalStorage({ 'stroke:settings': JSON.stringify({ aiInTab: false, theme: 'dark' }) }) + let { loadSettings } = await import('./settings.js') + expect(loadSettings().aiInTab).toBe(true) + expect(JSON.parse(store.get('stroke:settings')).aiInTab).toBe(true) + + store.set('stroke:settings', JSON.stringify({ ...JSON.parse(store.get('stroke:settings')), aiInTab: false })) + vi.resetModules() + ;({ loadSettings } = await import('./settings.js')) + expect(loadSettings().aiInTab).toBe(false) + }) +}) diff --git a/src/lib/stores/settings.js b/src/lib/stores/settings.js index 13cf1196..f8f96791 100644 --- a/src/lib/stores/settings.js +++ b/src/lib/stores/settings.js @@ -630,9 +630,9 @@ export const DEFAULT_SETTINGS = { // Beta: 'tree' swaps the sidebar's Tables / Objects / Databases tabs for one // explorer tree (connection > database > schema > groups > objects > columns). sidebarStyle: 'classic', - // Beta: AI chat opens as a tab beside your tables, its chats listed in the - // sidebar, instead of taking over the whole window. - aiInTab: false, + // AI chat opens as a tab beside your tables, its chats listed in the + // sidebar, instead of taking over the whole window. Still in Labs, but on by default since 3.0. + aiInTab: true, // On by default. A column averaging half a megabyte a row is fetched as a // size, and its value is loaded per cell on demand - the difference between a // table opening in a second and in eleven. Off restores the old behaviour: @@ -1003,7 +1003,15 @@ export function loadSettings() { const sidebarRememberGroups = parsed.sidebarRememberGroups !== false const liveModeEnabled = parsed.liveModeEnabled === true const sidebarStyle = parsed.sidebarStyle === 'tree' ? 'tree' : 'classic' - const aiInTab = parsed.aiInTab === true + // Absent means on. A stored `false` from before 3.0, when this was a Labs + // switch off by default, can't be told from a choice, so it turns on once. + let aiInTab = parsed.aiInTab !== false + try { + if (localStorage.getItem('stroke:ai-in-tab-default-v3') !== '1') { + if (!aiInTab) { aiInTab = true; settingsMigrated = true } + localStorage.setItem('stroke:ai-in-tab-default-v3', '1') + } + } catch {} const lazyWideColumns = parsed.lazyWideColumns !== false const nullSortOrder = NULL_SORT_IDS.includes(parsed.nullSortOrder) ? parsed.nullSortOrder : DEFAULT_NULL_SORT const agentChatFontSize = migrateAgentFont(parsed.agentChatFontSize, LEGACY_AGENT_CHAT_FONT, DEFAULT_AGENT_CHAT_FONT) diff --git a/src/lib/whats-new.js b/src/lib/whats-new.js index b1880695..7a352dbc 100644 --- a/src/lib/whats-new.js +++ b/src/lib/whats-new.js @@ -9,7 +9,7 @@ import { compareVersions } from '$lib/changelog.js' /** - * @typedef {'enable-tree-sidebar' | 'open-themes' | 'open-shortcuts' | 'open-connections' | 'enable-ai-tab' | 'open-docker'} HighlightAction + * @typedef {'enable-tree-sidebar' | 'open-themes' | 'open-shortcuts' | 'open-connections' | 'enable-ai-tab' | 'open-docker' | 'open-ai' | 'open-local-servers' | 'open-migrations' | 'open-backups'} HighlightAction * @typedef {{ * id: string, * icon: 'tree' | 'themes' | 'keyboard' | 'database', @@ -22,6 +22,41 @@ import { compareVersions } from '$lib/changelog.js' /** Newest first. @type {{ after: string, items: Highlight[] }[]} */ export const HIGHLIGHT_SETS = [ + { + // Stroke 3.0: the first Stable after 2.3.0, so most people see this set. + after: '2.20.4', + items: [ + { + id: 'v3-ai-tab', + icon: 'database', + beta: true, + title: 'AI chat sits beside your tables', + body: 'AI opens as a tab next to your tables and queries, and its chats live in the sidebar with the database each one worked in. Pick Read only, Read & write or more for any model.', + action: { id: 'open-ai', label: 'Open AI chat' }, + }, + { + id: 'v3-local-servers', + icon: 'database', + title: 'Local database servers', + body: 'Run Postgres, MySQL or Redis on this computer in any version, start them with Stroke, and see the servers already running here.', + action: { id: 'open-local-servers', label: 'Open local servers' }, + }, + { + id: 'v3-migrations', + icon: 'database', + title: 'Migrations, applied and pending', + body: 'Point Stroke at a Drizzle, Prisma, Wrangler or plain SQL folder and see what has run, what is waiting, and the SQL of each one.', + action: { id: 'open-migrations', label: 'Open Migrations' }, + }, + { + id: 'v3-backups', + icon: 'database', + title: 'Scheduled, encrypted backups', + body: 'Back up on a schedule to Stroke Cloud or your own S3, end-to-end encrypted, and preview a dump before you restore it.', + action: { id: 'open-backups', label: 'Set up backups' }, + }, + ], + }, { after: '2.6.0', items: [ From 3978661dd447f2eea218c3621ffe46b18967bd97 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:09:57 +0000 Subject: [PATCH 317/317] chore: version 3.0.0 (#307) --- .changeset/v3.md | 33 --------------------------------- CHANGELOG.md | 37 +++++++++++++++++++++++++++++++++++++ package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 39 insertions(+), 35 deletions(-) delete mode 100644 .changeset/v3.md diff --git a/.changeset/v3.md b/.changeset/v3.md deleted file mode 100644 index 2c4d294a..00000000 --- a/.changeset/v3.md +++ /dev/null @@ -1,33 +0,0 @@ -### New Features - -#### Stroke 3 -- **One account, three computers** - Sign in with GitHub or Google. Your license comes with your account and covers up to 3 computers; manage them at stroke.click/app. Paid Pro keeps working offline for 30 days. -- **Sync** - Workspaces, connections, settings, saved queries, charts and dashboards sync between your computers, end-to-end encrypted. -- **21 databases** - New since 2.3: Oracle, Elasticsearch, OpenSearch, Xata and SingleStore, alongside MongoDB, CouchDB, Cassandra, DynamoDB, Firestore and Redis. -- **Several databases at once (Labs)** - Keep more than one connection open, each with its tabs, and switch instantly. - -#### AI -- **AI chat in a tab** - AI opens beside your tables instead of taking over the window, and its chats live in the sidebar. On by default in this version; switch it off in Settings → Labs. -- **Access levels for every model** - Read only, Read & write, Modify schema or Dangerous, now enforced for the built-in models and API keys too, not only local agents. -- **Plans and step timeline** - A multi-step request shows its plan, each tool call is one row with its result, and a finished turn says what changed. - -#### Your databases -- **Local database servers** - Run Postgres, MySQL or Redis on this computer in any version, in their own window, start them with Stroke, and see the servers already running here. -- **Migrations** - Drizzle, Prisma, Wrangler (D1) and plain SQL folders: what has run, what is pending, and the SQL of each. -- **Scheduled backups** - To Stroke Cloud or your own S3, end-to-end encrypted, with a preview of a dump and its encoding before you restore. -- **Docker in one step** - ⌘K → Docker starts any of 18 databases, already connected. -- **Dashboards** - Live chart cards that refresh themselves, open in their own window, full screen. -- **Paste any connection string** - .env lines, ORM URLs and key/value strings land on the right form. - -#### Everywhere -- **Leader key** - Press ⌘; (Ctrl+; on Windows and Linux), then one key. -- **Share as a web studio (Labs)** - Share a database through a link that opens in any browser. -- **SQL notebooks** - Variables, import and export, autosave. -- **Results beside the editor** - Put SQL results below or beside the editor. -- **Quieter updates** - Updates download in the background and install as Stroke quits. Homebrew, Scoop, AUR, .deb and .rpm installs update through their package manager. - -### Changes -- A faster start: Settings, the command palette and one-off dialogs load on first use, and the data grid loads lazily. -- Windows and Linux get a 40px title bar with native window buttons, and native Wayland on Linux. -- echarts 6.1, which fixes an XSS advisory; charts look as they did. -- The Explorer tree stays in Labs (Settings → Labs). diff --git a/CHANGELOG.md b/CHANGELOG.md index c32b2346..a22b4288 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,43 @@ All notable changes to Stroke are listed here, newest first. --- +## [3.0.0] - 2026-11-19 + +### New Features + +#### Stroke 3 +- **One account, three computers** - Sign in with GitHub or Google. Your license comes with your account and covers up to 3 computers; manage them at stroke.click/app. Paid Pro keeps working offline for 30 days. +- **Sync** - Workspaces, connections, settings, saved queries, charts and dashboards sync between your computers, end-to-end encrypted. +- **21 databases** - New since 2.3: Oracle, Elasticsearch, OpenSearch, Xata and SingleStore, alongside MongoDB, CouchDB, Cassandra, DynamoDB, Firestore and Redis. +- **Several databases at once (Labs)** - Keep more than one connection open, each with its tabs, and switch instantly. + +#### AI +- **AI chat in a tab** - AI opens beside your tables instead of taking over the window, and its chats live in the sidebar. On by default in this version; switch it off in Settings → Labs. +- **Access levels for every model** - Read only, Read & write, Modify schema or Dangerous, now enforced for the built-in models and API keys too, not only local agents. +- **Plans and step timeline** - A multi-step request shows its plan, each tool call is one row with its result, and a finished turn says what changed. + +#### Your databases +- **Local database servers** - Run Postgres, MySQL or Redis on this computer in any version, in their own window, start them with Stroke, and see the servers already running here. +- **Migrations** - Drizzle, Prisma, Wrangler (D1) and plain SQL folders: what has run, what is pending, and the SQL of each. +- **Scheduled backups** - To Stroke Cloud or your own S3, end-to-end encrypted, with a preview of a dump and its encoding before you restore. +- **Docker in one step** - ⌘K → Docker starts any of 18 databases, already connected. +- **Dashboards** - Live chart cards that refresh themselves, open in their own window, full screen. +- **Paste any connection string** - .env lines, ORM URLs and key/value strings land on the right form. + +#### Everywhere +- **Leader key** - Press ⌘; (Ctrl+; on Windows and Linux), then one key. +- **Share as a web studio (Labs)** - Share a database through a link that opens in any browser. +- **SQL notebooks** - Variables, import and export, autosave. +- **Results beside the editor** - Put SQL results below or beside the editor. +- **Quieter updates** - Updates download in the background and install as Stroke quits. Homebrew, Scoop, AUR, .deb and .rpm installs update through their package manager. + +### Changes +- A faster start: Settings, the command palette and one-off dialogs load on first use, and the data grid loads lazily. +- Windows and Linux get a 40px title bar with native window buttons, and native Wayland on Linux. +- echarts 6.1, which fixes an XSS advisory; charts look as they did. +- The Explorer tree stays in Labs (Settings → Labs). + + ## [2.20.4] - 2026-11-19 ### Changes diff --git a/package.json b/package.json index 9d70be9a..4f996907 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "2.20.4", + "version": "3.0.0", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 516f7d43..44dad772 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "2.20.4", + "version": "3.0.0", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist",