From d86821b39d540dd8eb35a242765d09eeb8d36264 Mon Sep 17 00:00:00 2001 From: broisnees Date: Thu, 19 Nov 2026 04:59:50 +0000 Subject: [PATCH] Hold the built-in AI chat to its access level; redesign Migrations - 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}