Opt-in update notices

- Asked once after the first start; switch and Check now in Settings
- At most one request a day to GitHub's latest-release endpoint,
  nothing else is sent; knock never updates itself
- A new version shows a notice with download link and release notes,
  plus one desktop notification per version; versions can be skipped
This commit is contained in:
2026-11-27 21:56:04 +01:00
parent 677b5adaf9
commit be65eae732
13 changed files with 391 additions and 2 deletions
Generated
+125
View File
@@ -2889,6 +2889,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-deep-link",
"tauri-plugin-dialog",
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tokio",
@@ -3100,6 +3101,20 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"
dependencies = [
"cc",
"log",
"objc2",
"objc2-foundation",
"time",
"uuid",
]
[[package]]
name = "markup5ever"
version = "0.39.0"
@@ -3306,6 +3321,20 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "notify-rust"
version = "4.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus 6.5.0",
]
[[package]]
name = "notify-types"
version = "2.3.1"
@@ -5782,6 +5811,26 @@ dependencies = [
"url",
]
[[package]]
name = "tauri-plugin-notification"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f"
dependencies = [
"log",
"notify-rust",
"rand 0.10.4",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
"time",
"url",
"zbus 5.19.0",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.7.3"
@@ -5920,6 +5969,17 @@ dependencies = [
"toml 1.2.3+spec-1.1.0",
]
[[package]]
name = "tauri-winrt-notification"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36"
dependencies = [
"thiserror 2.0.21",
"windows",
"windows-version",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -7366,6 +7426,33 @@ dependencies = [
"zvariant 5.15.1",
]
[[package]]
name = "zbus"
version = "6.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"socket2",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.5",
"zbus_macros 6.5.0",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus_macros"
version = "4.4.0"
@@ -7394,6 +7481,18 @@ dependencies = [
"zvariant_utils 4.2.0",
]
[[package]]
name = "zbus_macros"
version = "6.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_utils",
]
[[package]]
name = "zbus_names"
version = "3.0.0"
@@ -7416,6 +7515,19 @@ dependencies = [
"zvariant 5.15.1",
]
[[package]]
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.10",
"winnow 1.0.5",
]
[[package]]
name = "zcheapstr"
version = "1.4.0"
@@ -7531,6 +7643,19 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zruntime"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e"
dependencies = [
"futures-core",
"futures-io",
"rustix",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "zstd"
version = "0.14.5"
+1
View File
@@ -10,6 +10,7 @@ pub mod prepare;
pub mod run;
pub mod runner;
pub mod secrets;
pub mod update;
pub mod vars;
pub mod ws;
+90
View File
@@ -0,0 +1,90 @@
//! Asks GitHub for the latest release. Only runs when the user opted in;
//! the request carries nothing but the version in the User-Agent.
use anyhow::{anyhow, Result};
use serde::Serialize;
pub const RELEASES_API: &str = "https://api.github.com/repos/JoshiCodes/knock/releases/latest";
#[derive(Debug, Clone, Serialize)]
pub struct Release {
pub version: String,
pub url: String,
pub notes: String,
pub published_at: String,
pub newer: bool,
}
/// Parses `1.2.3` or `v1.2.3-rc1`; pre-releases sort before their release.
fn parse(v: &str) -> Option<(u64, u64, u64, Option<String>)> {
let v = v.trim().trim_start_matches('v');
let (core, pre) = match v.split_once('-') {
Some((c, p)) => (c, Some(p.to_string())),
None => (v, None),
};
let mut it = core.split('.').map(|x| x.parse::<u64>().ok());
Some((it.next()??, it.next().flatten().unwrap_or(0), it.next().flatten().unwrap_or(0), pre))
}
pub fn is_newer(latest: &str, current: &str) -> bool {
match (parse(latest), parse(current)) {
(Some(l), Some(c)) => {
let (lk, ck) = ((l.0, l.1, l.2), (c.0, c.1, c.2));
if lk != ck {
return lk > ck;
}
match (&l.3, &c.3) {
(None, Some(_)) => true,
(Some(a), Some(b)) => a > b,
_ => false,
}
}
_ => false,
}
}
pub async fn latest(current: &str) -> Result<Release> {
let client = reqwest::Client::builder()
.user_agent(format!("knock/{current}"))
.timeout(std::time::Duration::from_secs(10))
.build()?;
let resp = client
.get(RELEASES_API)
.header("Accept", "application/vnd.github+json")
.send()
.await
.map_err(|e| anyhow!("could not reach GitHub: {e}"))?;
match resp.status().as_u16() {
200 => {}
404 => return Err(anyhow!("no published release found (the repository may be private or have no releases yet)")),
403 | 429 => return Err(anyhow!("GitHub rate limit reached; try again later")),
s => return Err(anyhow!("GitHub answered HTTP {s}")),
}
let v: serde_json::Value = serde_json::from_slice(&resp.bytes().await?)?;
let tag = v.get("tag_name").and_then(|t| t.as_str()).unwrap_or_default().to_string();
let version = tag.trim_start_matches('v').to_string();
Ok(Release {
newer: is_newer(&version, current),
url: v.get("html_url").and_then(|t| t.as_str()).unwrap_or_default().to_string(),
notes: v.get("body").and_then(|t| t.as_str()).unwrap_or_default().to_string(),
published_at: v.get("published_at").and_then(|t| t.as_str()).unwrap_or_default().to_string(),
version,
})
}
#[cfg(test)]
mod tests {
use super::is_newer;
#[test]
fn compares_versions() {
assert!(is_newer("0.2.0", "0.1.0"));
assert!(is_newer("v1.0.0", "0.9.9"));
assert!(is_newer("0.2.0", "0.2.0-rc1"));
assert!(is_newer("0.2.0-rc2", "0.2.0-rc1"));
assert!(!is_newer("0.1.0", "0.1.0"));
assert!(!is_newer("0.2.0-rc1", "0.2.0"));
assert!(!is_newer("0.1.9", "0.2.0"));
assert!(!is_newer("garbage", "0.1.0"));
}
}
+10
View File
@@ -27,6 +27,7 @@
"@tauri-apps/api": "^2.12.5",
"@tauri-apps/plugin-deep-link": "^2.6.3",
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-notification": "^2.8.1",
"@tauri-apps/plugin-opener": "^2.7.3",
"cm6-graphql": "^1.0.0",
"graphql": "^17.1.0",
@@ -1345,6 +1346,15 @@
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-notification": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-notification/-/plugin-notification-2.8.1.tgz",
"integrity": "sha512-B+OCJv17XCFQxAhe2+fn2bHqQ1fz/hGnYHeT++yv8+q0daOH5o1ghX7MmxWgoGFp7POaNn4UMONclHeZn65mJA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-opener": {
"version": "2.7.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.7.3.tgz",
+1
View File
@@ -40,6 +40,7 @@
"@tauri-apps/api": "^2.12.5",
"@tauri-apps/plugin-deep-link": "^2.6.3",
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-notification": "^2.8.1",
"@tauri-apps/plugin-opener": "^2.7.3",
"cm6-graphql": "^1.0.0",
"graphql": "^17.1.0",
+1
View File
@@ -29,6 +29,7 @@ tracing.workspace = true
tauri = { version = "2", features = [] }
tauri-plugin-dialog = "2"
tauri-plugin-opener = "2"
tauri-plugin-notification = "2"
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
tauri-plugin-deep-link = "2"
rusqlite = { version = "0.37", features = ["bundled"] }
+2 -1
View File
@@ -18,6 +18,7 @@
"opener:default",
"deep-link:default",
"core:webview:allow-create-webview-window",
"core:window:allow-set-title"
"core:window:allow-set-title",
"notification:default"
]
}
+6
View File
@@ -794,3 +794,9 @@ pub async fn code_snippet(app: AppHandle, args: ScopeArgs, lang: knock_core::exp
};
Ok(knock_core::export::snippet(&p, lang))
}
/// Latest release on GitHub. Only called when the user opted in.
#[tauri::command]
pub async fn update_check() -> Res<knock_core::update::Release> {
knock_core::update::latest(env!("CARGO_PKG_VERSION")).await.map_err(errx)
}
+2
View File
@@ -19,6 +19,7 @@ pub fn run() {
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_notification::init())
.setup(|app| {
let dir = app.path().app_data_dir()?;
app.manage(state::AppState::new(dir)?);
@@ -70,6 +71,7 @@ pub fn run() {
commands::path_params,
commands::app_version,
commands::write_text_file,
commands::update_check,
commands::runner_run,
commands::import_curl,
commands::import_detect,
+4
View File
@@ -20,11 +20,14 @@
import type { TreeNode } from '$lib/types';
import { onDeepLink } from '$lib/deeplink';
import { openDocs } from '$lib/help';
import UpdateNotice from '$lib/views/UpdateNotice.svelte';
import { updates } from '$lib/state/updates.svelte';
let ready = $state(false);
onMount(() => {
ws.restore().finally(() => (ready = true));
updates.start();
const un = listen<{ collection: string; paths: string[] }>('collection-changed', (e) => {
ws.onDiskChange(e.payload.collection, e.payload.paths);
});
@@ -201,6 +204,7 @@
<Welcome />
{/if}
</div>
<UpdateNotice />
</main>
</div>
</div>
+97
View File
@@ -0,0 +1,97 @@
import { invoke } from '@tauri-apps/api/core';
import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/plugin-notification';
import { errorText } from '$lib/api';
export interface Release {
version: string;
url: string;
notes: string;
published_at: string;
newer: boolean;
}
const DAY = 24 * 60 * 60 * 1000;
function get(key: string): string | null {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function set(key: string, value: string) {
try {
localStorage.setItem(key, value);
} catch {
/* storage blocked */
}
}
/**
* Update notices. Off until the user says yes (no update pings without
* opt-in); then at most one request to GitHub per day.
*/
class Updates {
/** 'on', 'off', or null while the user has not been asked. */
mode = $state<string | null>(get('knock.updates'));
available = $state<Release | null>(null);
checking = $state(false);
lastError = $state<string | null>(null);
askNow = $state(false);
start() {
if (this.mode === null) {
// Ask once, a moment after start, not in the user's face.
setTimeout(() => (this.askNow = true), 6000);
return;
}
if (this.mode === 'on' && Date.now() - Number(get('knock.updates.last') ?? 0) > DAY) this.check(false);
}
choose(on: boolean) {
this.mode = on ? 'on' : 'off';
set('knock.updates', this.mode);
this.askNow = false;
if (on) this.check(false);
}
async check(manual: boolean): Promise<Release | null> {
this.checking = true;
this.lastError = null;
try {
const r = await invoke<Release>('update_check');
set('knock.updates.last', String(Date.now()));
const skipped = get('knock.updates.skip');
if (r.newer && (manual || skipped !== r.version)) {
this.available = r;
if (!manual) await this.notify(r);
}
return r;
} catch (e) {
this.lastError = errorText(e);
return null;
} finally {
this.checking = false;
}
}
skip() {
if (this.available) set('knock.updates.skip', this.available.version);
this.available = null;
}
/** One desktop notification per version. */
private async notify(r: Release) {
if (get('knock.updates.notified') === r.version) return;
try {
let ok = await isPermissionGranted();
if (!ok) ok = (await requestPermission()) === 'granted';
if (ok) sendNotification({ title: `knock ${r.version} is available`, body: 'Open knock for the download and what changed.' });
set('knock.updates.notified', r.version);
} catch {
/* notifications unavailable; the in-app notice is enough */
}
}
}
export const updates = new Updates();
+25
View File
@@ -0,0 +1,25 @@
<script lang="ts">
import { openUrl } from '@tauri-apps/plugin-opener';
import Icon from '$lib/ui/Icon.svelte';
import { updates } from '$lib/state/updates.svelte';
</script>
{#if updates.available}
{@const r = updates.available}
<div class="flex shrink-0 items-center gap-3 border-t border-l-2 border-t-line border-l-cyan bg-input/60 px-3 py-1.5 text-[12px] [:root:not(.dark)_&]:border-l-cyan-deep">
<span class="text-strong">knock {r.version} is available.</span>
<span class="text-fg-muted">Your version keeps working; updates come through your package manager or the download page.</span>
<span class="flex-1"></span>
<button class="font-bold text-accent hover:underline" onclick={() => openUrl(r.url)}>Download and release notes</button>
<button class="text-fg-muted hover:text-fg" onclick={() => updates.skip()}>Skip this version</button>
<button class="grid size-5 place-items-center text-fg-subtle hover:text-fg" title="Hide until next start" onclick={() => (updates.available = null)}><Icon name="x" size={11} /></button>
</div>
{:else if updates.askNow}
<div class="flex shrink-0 items-center gap-3 border-t border-l-2 border-t-line border-l-cyan bg-input/60 px-3 py-1.5 text-[12px] [:root:not(.dark)_&]:border-l-cyan-deep">
<span class="text-strong">Tell you when a new knock is out?</span>
<span class="text-fg-muted">Once a day knock asks GitHub for the latest release. Nothing about you or your requests is sent.</span>
<span class="flex-1"></span>
<button class="font-bold text-accent hover:underline" onclick={() => updates.choose(true)}>Yes, check daily</button>
<button class="text-fg-muted hover:text-fg" onclick={() => updates.choose(false)}>No</button>
</div>
{/if}
+27 -1
View File
@@ -5,6 +5,14 @@
import { ws } from '$lib/state/workspace.svelte';
import type { KeyValue } from '$lib/types';
import Mark from '$lib/ui/Mark.svelte';
import { updates } from '$lib/state/updates.svelte';
let checkResult = $state('');
async function checkNow() {
checkResult = '';
const r = await updates.check(true);
if (r) checkResult = r.newer ? `knock ${r.version} is available.` : `You have the latest version (${r.version || version}).`;
}
let globals = $state<KeyValue[]>([]);
let version = $state('');
@@ -74,6 +82,24 @@
</div>
</section>
<section class="flex flex-col gap-4">
<h2 class="k-label">Updates</h2>
<div class="flex items-center gap-4">
<div class="flex-1">
<div>Tell me about new versions</div>
<div class="text-[12px] text-fg-subtle">Once a day knock asks GitHub for the latest release. Nothing else is sent. knock never updates itself; use your package manager or the download page.</div>
</div>
<Switch checked={updates.mode === 'on'} onchange={(v) => updates.choose(v)} aria-label="Check for updates" />
</div>
<div class="flex items-center gap-3 text-[12px]">
<button class="rounded-sm border border-line px-3 py-1 hover:border-border-strong disabled:opacity-40" disabled={updates.checking} onclick={checkNow}>
{updates.checking ? 'Checking…' : 'Check now'}
</button>
{#if checkResult}<span class="text-fg-muted">{checkResult}</span>{/if}
{#if updates.lastError}<span class="text-delete">{updates.lastError}</span>{/if}
</div>
</section>
<section>
<h2 class="k-label mb-2">Global variables</h2>
<p class="mb-2 text-[12px] text-fg-subtle">Available in every collection, stored on this machine only. Anything defined in a collection wins.</p>
@@ -83,7 +109,7 @@
<section class="flex items-center gap-3 border-t border-line pt-6 text-fg-muted">
<Mark size={20} class="text-cyan [:root:not(.dark)_&]:text-cyan-deep" />
<span>knock {version}</span>
<span class="text-fg-subtle">MIT licensed. No telemetry, no account, no update checks.</span>
<span class="text-fg-subtle">MIT licensed. No telemetry, no account; update checks only if you turn them on.</span>
</section>
</div>
</div>