Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(desktop): auto update (#3448)

Elijah Potterfc7b4257307a
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
index b8e6a3135..f48a0e1ce 100644
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@ -4,6 +4,8 @@ on:
push:
branches: ["master"]
tags: ["v*"]
+ pull_request:
+ branches: ["master"]
merge_group:
permissions:
@@ -16,26 +18,28 @@ jobs:
strategy:
matrix:
platform:
- - name: Linux x64
- artifact_name: harper-desktop-linux-x64
- os: ubuntu-latest
- command: just build-desktop-linux
- artifact_paths: |
- target/release/bundle/deb/*.deb
- target/release/bundle/rpm/*.rpm
- target/release/bundle/appimage/*.AppImage
- name: macOS x64
artifact_name: harper-desktop-macos-x64
os: macos-26-intel
command: just build-desktop-macos
+ unsigned_command: just build-desktop-macos-unsigned
artifact_paths: |
target/release/bundle/dmg/*.dmg
+ target/release/bundle/macos/*.app.tar.gz
+ target/release/bundle/macos/*.app.tar.gz.sig
+ unsigned_artifact_paths: |
+ target/release/bundle/dmg/*.dmg
- name: macOS arm64
artifact_name: harper-desktop-macos-arm64
os: macos-14
command: just build-desktop-macos
+ unsigned_command: just build-desktop-macos-unsigned
artifact_paths: |
target/release/bundle/dmg/*.dmg
+ target/release/bundle/macos/*.app.tar.gz
+ target/release/bundle/macos/*.app.tar.gz.sig
+ unsigned_artifact_paths: |
+ target/release/bundle/dmg/*.dmg
steps:
- name: Checkout
@@ -71,13 +75,28 @@ jobs:
- name: Install tauri-cli
run: cargo binstall tauri-cli --force --no-confirm
- name: Build Harper Desktop
+ if: startsWith(github.ref, 'refs/tags/v')
+ env:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.HARPER_DESKTOP_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.HARPER_DESKTOP_PASSWORD }}
run: ${{ matrix.platform.command }}
- - name: Upload artifacts
+ - name: Build Harper Desktop without signing
+ if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
+ run: ${{ matrix.platform.unsigned_command }}
+ - name: Upload signed artifacts
+ if: startsWith(github.ref, 'refs/tags/v')
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.platform.artifact_name }}
path: ${{ matrix.platform.artifact_paths }}
if-no-files-found: error
+ - name: Upload unsigned artifacts
+ if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: ${{ matrix.platform.artifact_name }}
+ path: ${{ matrix.platform.unsigned_artifact_paths }}
+ if-no-files-found: error
- name: Release artifacts
if: startsWith(github.ref, 'refs/tags/v')
uses: ncipollo/release-action@v1
diff --git a/.github/workflows/just_checks.yml b/.github/workflows/just_checks.yml
index f0e1dbae3..ce3db3ad6 100644
--- a/.github/workflows/just_checks.yml
+++ b/.github/workflows/just_checks.yml
@@ -27,7 +27,6 @@ jobs:
test-firefox-plugin,
test-obsidian,
check-desktop,
- build-desktop-linux,
]
steps:
- uses: actions/checkout@v4
diff --git a/Cargo.lock b/Cargo.lock
index eb0715fac..c5a58a153 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4253,7 +4253,7 @@ dependencies = [
[[package]]
name = "harper-desktop"
-version = "0.1.0"
+version = "2.1.0"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -4276,6 +4276,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-autostart",
"tauri-plugin-opener",
+ "tauri-plugin-updater",
"thiserror 2.0.18",
"tokio",
"winit",
@@ -5500,6 +5501,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+[[package]]
+name = "minisign-verify"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"
+
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -6069,6 +6076,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
+ "libc",
"objc2 0.6.4",
"objc2-core-foundation",
]
@@ -6130,6 +6138,18 @@ dependencies = [
"objc2-foundation 0.3.2",
]
+[[package]]
+name = "objc2-osa-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
+dependencies = [
+ "bitflags 2.11.0",
+ "objc2 0.6.4",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+]
+
[[package]]
name = "objc2-quartz-core"
version = "0.2.2"
@@ -6286,6 +6306,12 @@ dependencies = [
"pathdiff",
]
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -6332,6 +6358,20 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "osakit"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
+dependencies = [
+ "objc2 0.6.4",
+ "objc2-foundation 0.3.2",
+ "objc2-osa-kit",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
@@ -7275,15 +7315,20 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
+ "hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
+ "tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -7442,6 +7487,18 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
[[package]]
name = "rustls-pki-types"
version = "1.13.0"
@@ -7452,6 +7509,33 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"
+dependencies = [
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "jni 0.22.4",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.1",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
+
[[package]]
name = "rustls-webpki"
version = "0.103.10"
@@ -7522,6 +7606,15 @@ dependencies = [
"regex",
]
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.1",
+]
+
[[package]]
name = "schemars"
version = "0.8.22"
@@ -7598,6 +7691,29 @@ dependencies = [
"tiny-skia",
]
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags 2.11.0",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "selectors"
version = "0.36.1"
@@ -8584,6 +8700,39 @@ dependencies = [
"zbus",
]
+[[package]]
+name = "tauri-plugin-updater"
+version = "2.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "806d9dac662c2e4594ff03c647a552f2c9bd544e7d0f683ec58f872f952ce4af"
+dependencies = [
+ "base64 0.22.1",
+ "dirs 6.0.0",
+ "flate2",
+ "futures-util",
+ "http",
+ "infer",
+ "log",
+ "minisign-verify",
+ "osakit",
+ "percent-encoding",
+ "reqwest 0.13.3",
+ "rustls",
+ "semver",
+ "serde",
+ "serde_json",
+ "tar",
+ "tauri",
+ "tauri-plugin",
+ "tempfile",
+ "thiserror 2.0.18",
+ "time",
+ "tokio",
+ "url",
+ "windows-sys 0.60.2",
+ "zip 4.6.1",
+]
+
[[package]]
name = "tauri-runtime"
version = "2.11.1"
@@ -10436,6 +10585,15 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webpki-roots"
version = "1.0.3"
@@ -11898,6 +12056,18 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "zip"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "indexmap 2.13.1",
+ "memchr",
+]
+
[[package]]
name = "zip"
version = "8.6.0"
diff --git a/harper-desktop/package.json b/harper-desktop/package.json
index bf49f5c58..b40d27f15 100644
--- a/harper-desktop/package.json
+++ b/harper-desktop/package.json
@@ -1,6 +1,6 @@
{
"name": "harper-desktop",
- "version": "0.1.0",
+ "version": "2.1.0",
"description": "",
"type": "module",
"scripts": {
@@ -16,6 +16,7 @@
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-autostart": "^2.5.1",
"@tauri-apps/plugin-opener": "^2",
+ "@tauri-apps/plugin-updater": "^2.10.1",
"harper-editor": "workspace:*",
"harper.js": "workspace:*"
},
diff --git a/harper-desktop/src-tauri/Cargo.toml b/harper-desktop/src-tauri/Cargo.toml
index d208e1f94..b00787b5a 100644
--- a/harper-desktop/src-tauri/Cargo.toml
+++ b/harper-desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "harper-desktop"
-version = "0.1.0"
+version = "2.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2024"
@@ -53,3 +53,7 @@ core-graphics = "0.25.0"
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-autostart = "2.5.1"
+tauri-plugin-updater = "2"
+
+[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
+tauri-plugin-updater = "2"
diff --git a/harper-desktop/src-tauri/capabilities/default.json b/harper-desktop/src-tauri/capabilities/default.json
index ceeb17826..ea71ba1b7 100644
--- a/harper-desktop/src-tauri/capabilities/default.json
+++ b/harper-desktop/src-tauri/capabilities/default.json
@@ -6,6 +6,7 @@
"permissions": [
"core:default",
"opener:default",
+ "updater:default",
"autostart:allow-enable",
"autostart:allow-disable",
"autostart:allow-is-enabled"
diff --git a/harper-desktop/src-tauri/src/config.rs b/harper-desktop/src-tauri/src/config.rs
index 911c62912..f9e1be205 100644
--- a/harper-desktop/src-tauri/src/config.rs
+++ b/harper-desktop/src-tauri/src/config.rs
@@ -29,6 +29,8 @@ pub struct Config {
pub lint_config: FlatConfig,
pub integrations: Vec<Integration>,
pub debounce_ms: u64,
+ pub auto_update: bool,
+ pub last_update_check: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -46,6 +48,8 @@ impl Config {
lint_config: FlatConfig::new_curated(),
integrations: Self::curated_integrations(),
debounce_ms: 0,
+ auto_update: true,
+ last_update_check: None,
}
}
@@ -173,6 +177,8 @@ impl Config {
"lint_config": &self.lint_config,
"integrations": &self.integrations,
"debounce_ms": self.debounce_ms,
+ "auto_update": self.auto_update,
+ "last_update_check": self.last_update_check,
}))
}
@@ -191,6 +197,12 @@ impl Config {
integrations: deserialize_optional_field(object, "integrations")?
.unwrap_or_else(Self::curated_integrations),
debounce_ms: deserialize_optional_field(object, "debounce_ms")?.unwrap_or(0),
+ auto_update: deserialize_optional_field(object, "auto_update")?.unwrap_or(true),
+ last_update_check: deserialize_optional_field::<Option<u64>>(
+ object,
+ "last_update_check",
+ )?
+ .flatten(),
})
}
}
@@ -252,6 +264,8 @@ mod tests {
assert!(serialized.contains("lint_config"));
assert!(serialized.contains("integrations"));
assert!(serialized.contains("debounce_ms"));
+ assert!(serialized.contains("auto_update"));
+ assert!(serialized.contains("last_update_check"));
}
#[test]
@@ -268,6 +282,8 @@ mod tests {
assert_eq!(deserialized.lint_config, config.lint_config);
assert_eq!(deserialized.integrations, config.integrations);
assert_eq!(deserialized.debounce_ms, config.debounce_ms);
+ assert_eq!(deserialized.auto_update, config.auto_update);
+ assert_eq!(deserialized.last_update_check, config.last_update_check);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&deserialized.serialize_main().unwrap())
.unwrap(),
@@ -310,6 +326,20 @@ mod tests {
assert_eq!(deserialized.debounce_ms, 0);
}
+ #[test]
+ fn deserialize_main_uses_default_update_settings_when_missing() {
+ let config = Config::new();
+ let mut value =
+ serde_json::from_str::<serde_json::Value>(&config.serialize_main().unwrap()).unwrap();
+ value.as_object_mut().unwrap().remove("auto_update");
+ value.as_object_mut().unwrap().remove("last_update_check");
+
+ let deserialized = Config::deserialize_main(&value.to_string()).unwrap();
+
+ assert!(deserialized.auto_update);
+ assert_eq!(deserialized.last_update_check, None);
+ }
+
#[test]
fn deserialize_main_preserves_integrations() {
let mut config = Config::new();
diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rs
index 73f39a8bb..24ef1b8f1 100644
--- a/harper-desktop/src-tauri/src/lib.rs
+++ b/harper-desktop/src-tauri/src/lib.rs
@@ -216,6 +216,48 @@ async fn set_debounce_ms(
Ok(())
}
+#[tauri::command]
+async fn get_auto_update(config: State<'_, Arc<Mutex<Config>>>) -> Result<bool, String> {
+ Ok(config.lock().await.auto_update)
+}
+
+#[tauri::command]
+async fn set_auto_update(
+ auto_update: bool,
+ config: State<'_, Arc<Mutex<Config>>>,
+) -> Result<(), String> {
+ let mut config = config.lock().await;
+ config.auto_update = auto_update;
+ config
+ .save_to_system()
+ .await
+ .map_err(|error| error.to_string())?;
+
+ Ok(())
+}
+
+#[tauri::command]
+async fn get_last_update_check(
+ config: State<'_, Arc<Mutex<Config>>>,
+) -> Result<Option<u64>, String> {
+ Ok(config.lock().await.last_update_check)
+}
+
+#[tauri::command]
+async fn set_last_update_check(
+ last_update_check: Option<u64>,
+ config: State<'_, Arc<Mutex<Config>>>,
+) -> Result<(), String> {
+ let mut config = config.lock().await;
+ config.last_update_check = last_update_check;
+ config
+ .save_to_system()
+ .await
+ .map_err(|error| error.to_string())?;
+
+ Ok(())
+}
+
#[tauri::command]
async fn set_dialect(
dialect: Dialect,
@@ -441,6 +483,10 @@ pub fn run_tauri() {
get_dialect,
get_debounce_ms,
set_debounce_ms,
+ get_auto_update,
+ set_auto_update,
+ get_last_update_check,
+ set_last_update_check,
set_dialect,
set_lint_config,
get_dictionary,
@@ -471,6 +517,9 @@ pub fn run_tauri() {
let menu = tray_menu(app, is_service_running)?;
let service_toggle = menu.service_toggle.clone();
+ app.handle()
+ .plugin(tauri_plugin_updater::Builder::new().build())?;
+
let tray = TrayIconBuilder::with_id(TRAY_MENU_BAR_ID)
.menu(&menu.menu)
.icon(menu_bar_icon(is_service_running)?)
@@ -639,6 +688,8 @@ pub fn run_highlighter() {
lint_config,
integrations: Vec::new(),
debounce_ms: *dictionary_debounce_ms.borrow(),
+ auto_update: true,
+ last_update_check: None,
};
*dictionary_linter.borrow_mut() = config.create_linter();
@@ -712,6 +763,8 @@ fn fetch_highlighter_config(
lint_config,
integrations,
debounce_ms,
+ auto_update: true,
+ last_update_check: None,
})
})
}
diff --git a/harper-desktop/src-tauri/tauri.conf.json b/harper-desktop/src-tauri/tauri.conf.json
index f823a9462..bfd778d96 100644
--- a/harper-desktop/src-tauri/tauri.conf.json
+++ b/harper-desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "harper-desktop",
- "version": "0.1.0",
+ "version": "2.1.0",
"identifier": "com.elijahpotter.harper-desktop",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -24,6 +24,15 @@
"icons/icon.icns",
"icons/icon.ico"
- ]
+ ],
+ "createUpdaterArtifacts": true
+ },
+ "plugins": {
+ "updater": {
+ "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDY4OEU5REVGQzc2MDk4QzkKUldUSm1HREg3NTJPYUNPd1VwT3kxUm5kc3VhKzcrK2FaV3hYemdacVNWb3NvVnJsYndqWUJObC8K",
+ "endpoints": [
+ "https://writewithharper.com/download-harper-desktop/{{target}}/{{arch}}/{{current_version}}"
+ ]
+ }
}
}
diff --git a/harper-desktop/src/lib/DesktopUpdater.ts b/harper-desktop/src/lib/DesktopUpdater.ts
new file mode 100644
index 000000000..324c9afaa
--- /dev/null
+++ b/harper-desktop/src/lib/DesktopUpdater.ts
@@ -0,0 +1,122 @@
+import { getVersion } from '@tauri-apps/api/app';
+import { check, type DownloadEvent } from '@tauri-apps/plugin-updater';
+import { Client } from '$lib/client';
+
+const LATEST_VERSION_URL = 'https://writewithharper.com/latestversion';
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+export type UpdateStatus = 'up-to-date' | 'updated' | 'error';
+
+export interface UpdateResult {
+ status: UpdateStatus;
+ currentVersion?: string;
+ latestVersion?: string;
+ message: string;
+ error?: unknown;
+}
+
+export interface UpdateOptions {
+ silent?: boolean;
+ onDownloadEvent?: (event: DownloadEvent) => void;
+}
+
+const normalizeVersion = (version: string) => version.trim().replace(/^v/i, '');
+
+const shouldCheckForUpdate = (lastUpdateCheck: number | null, now = Date.now()) =>
+ lastUpdateCheck == null || now - lastUpdateCheck >= DAY_MS;
+
+export class DesktopUpdater {
+ /**
+ * Fetch the latest published Harper Desktop version from the public web endpoint.
+ *
+ * This exists so settings UI can show the newest available version without invoking
+ * the full Tauri updater check/download flow.
+ */
+ static async getLatestVersion(): Promise<string> {
+ const resp = await fetch(LATEST_VERSION_URL, {
+ headers: {
+ Accept: 'text/plain',
+ },
+ });
+
+ if (!resp.ok) {
+ throw new Error(`Unable to get latest version: ${resp.status} ${resp.statusText}`);
+ }
+
+ return normalizeVersion(await resp.text());
+ }
+
+ /**
+ * Read the current Harper Desktop version from Tauri's bundled app metadata.
+ *
+ * This exists to keep displayed version numbers tied to the packaged app instead
+ * of hardcoded settings-page text.
+ */
+ static async getCurrentVersion(): Promise<string> {
+ return normalizeVersion(await getVersion());
+ }
+
+ /**
+ * Check for an available Tauri update and install it when one exists.
+ *
+ * This centralizes the updater plugin workflow so manual checks and automatic
+ * daily checks use the same behavior and return shape.
+ */
+ static async updateToLatest(options: UpdateOptions = {}): Promise<UpdateResult> {
+ try {
+ const currentVersion = await DesktopUpdater.getCurrentVersion();
+ const update = await check();
+
+ if (update == null) {
+ return {
+ status: 'up-to-date',
+ currentVersion,
+ message: 'Harper is up to date.',
+ };
+ }
+
+ await update.downloadAndInstall(options.onDownloadEvent);
+
+ return {
+ status: 'updated',
+ currentVersion,
+ latestVersion: normalizeVersion(update.version),
+ message: 'Update installed. Restart Harper to finish.',
+ };
+ } catch (error) {
+ if (!options.silent) {
+ console.error('Unable to update Harper Desktop.', error);
+ }
+
+ return {
+ status: 'error',
+ message: `Unable to check for updates: ${error}`,
+ error,
+ };
+ }
+ }
+
+ /**
+ * Run the silent daily auto-update check when the user has enabled it.
+ *
+ * This exists to keep scheduling and persisted update-check timestamps out of
+ * Svelte components while avoiding network/update checks on every app launch.
+ */
+ static async maybeAutoUpdate(): Promise<UpdateResult | null> {
+ const autoUpdate = await Client.getAutoUpdate();
+
+ if (!autoUpdate) {
+ return null;
+ }
+
+ const lastUpdateCheck = await Client.getLastUpdateCheck();
+
+ if (!shouldCheckForUpdate(lastUpdateCheck)) {
+ return null;
+ }
+
+ await Client.setLastUpdateCheck(Date.now());
+
+ return await DesktopUpdater.updateToLatest({ silent: true });
+ }
+}
diff --git a/harper-desktop/src/lib/client.ts b/harper-desktop/src/lib/client.ts
index 1395387f5..591fc6534 100644
--- a/harper-desktop/src/lib/client.ts
+++ b/harper-desktop/src/lib/client.ts
@@ -76,6 +76,22 @@ export class Client {
await invoke('set_debounce_ms', { debounceMs });
}
+ static async getAutoUpdate(): Promise<boolean> {
+ return await invoke<boolean>('get_auto_update');
+ }
+
+ static async setAutoUpdate(autoUpdate: boolean): Promise<void> {
+ await invoke('set_auto_update', { autoUpdate });
+ }
+
+ static async getLastUpdateCheck(): Promise<number | null> {
+ return await invoke<number | null>('get_last_update_check');
+ }
+
+ static async setLastUpdateCheck(lastUpdateCheck: number | null): Promise<void> {
+ await invoke('set_last_update_check', { lastUpdateCheck });
+ }
+
static async getLaunchAtStartup(): Promise<boolean> {
return await isEnabled();
}
diff --git a/harper-desktop/src/lib/settings/pages/AboutPage.svelte b/harper-desktop/src/lib/settings/pages/AboutPage.svelte
index e9ec75bc1..5b306bfae 100644
--- a/harper-desktop/src/lib/settings/pages/AboutPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/AboutPage.svelte
@@ -1,14 +1,30 @@
<script lang="ts">
import { openUrl } from '@tauri-apps/plugin-opener';
+import { onMount } from 'svelte';
+import { DesktopUpdater } from '$lib/DesktopUpdater';
const SOURCE_URL = 'https://github.com/Automattic/harper';
const ISSUE_URL = 'https://github.com/Automattic/harper/issues/new/choose';
+
+let currentVersion = '';
+
+onMount(() => {
+ void loadCurrentVersion();
+});
+
+async function loadCurrentVersion() {
+ try {
+ currentVersion = await DesktopUpdater.getCurrentVersion();
+ } catch (error) {
+ console.error('Unable to load Harper Desktop version.', error);
+ }
+}
</script>
<section class="about">
<div class="about-mark">H</div>
<h1>Harper for Mac</h1>
- <p class="muted">Version 1.4.2 (build 2048)</p>
+ <p class="muted">Version {currentVersion || 'unknown'}</p>
<p>
An open-source grammar checker that runs entirely on your device. No accounts, no
telemetry, no cloud.
diff --git a/harper-desktop/src/lib/settings/pages/GeneralPage.svelte b/harper-desktop/src/lib/settings/pages/GeneralPage.svelte
index d8141549e..52588e14b 100644
--- a/harper-desktop/src/lib/settings/pages/GeneralPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/GeneralPage.svelte
@@ -2,6 +2,7 @@
import type { Dialect } from 'harper.js';
import { onMount } from 'svelte';
import { Client } from '$lib/client';
+import { DesktopUpdater } from '$lib/DesktopUpdater';
import { DIALECT_OPTIONS } from '../settings-data';
const DialectValue = {
@@ -22,6 +23,13 @@ let dialectError = '';
let isLaunchAtStartupLoading = true;
let isLaunchAtStartupSaving = false;
let launchAtStartupError = '';
+let isAutoUpdateLoading = true;
+let isAutoUpdateSaving = false;
+let isCheckingForUpdates = false;
+let autoUpdateError = '';
+let updateStatus = '';
+let currentVersion = '';
+let latestVersion = '';
let debounceMs = 0;
let debounceMsInput = '0';
let isDebounceLoading = true;
@@ -31,6 +39,8 @@ let debounceError = '';
onMount(() => {
void loadDialect();
void loadLaunchAtStartup();
+ void loadAutoUpdate();
+ void loadUpdateVersions();
void loadDebounceMs();
const refreshSettings = () => {
@@ -42,6 +52,14 @@ onMount(() => {
void loadLaunchAtStartup();
}
+ if (!isAutoUpdateSaving) {
+ void loadAutoUpdate();
+ }
+
+ if (!isCheckingForUpdates) {
+ void loadUpdateVersions();
+ }
+
if (!isDebounceSaving) {
void loadDebounceMs();
}
@@ -114,6 +132,73 @@ async function setLaunchAtStartup(enabled: boolean) {
}
}
+async function loadAutoUpdate() {
+ isAutoUpdateLoading = true;
+ autoUpdateError = '';
+
+ try {
+ autoUpdate = await Client.getAutoUpdate();
+ } catch (error) {
+ autoUpdateError = `Unable to load update setting: ${error}`;
+ } finally {
+ isAutoUpdateLoading = false;
+ }
+}
+
+async function setAutoUpdate(enabled: boolean) {
+ const previousAutoUpdate = autoUpdate;
+
+ autoUpdate = enabled;
+ isAutoUpdateSaving = true;
+ autoUpdateError = '';
+ updateStatus = '';
+
+ try {
+ await Client.setAutoUpdate(enabled);
+ } catch (error) {
+ autoUpdate = previousAutoUpdate;
+ autoUpdateError = `Unable to save update setting: ${error}`;
+ } finally {
+ isAutoUpdateSaving = false;
+ }
+}
+
+async function loadUpdateVersions() {
+ try {
+ const [current, latest] = await Promise.all([
+ DesktopUpdater.getCurrentVersion(),
+ DesktopUpdater.getLatestVersion(),
+ ]);
+ currentVersion = current;
+ latestVersion = latest;
+ } catch (error) {
+ console.error('Unable to load update versions.', error);
+ }
+}
+
+async function checkForUpdates() {
+ isCheckingForUpdates = true;
+ autoUpdateError = '';
+ updateStatus = 'Checking for updates...';
+
+ try {
+ await Client.setLastUpdateCheck(Date.now());
+ const result = await DesktopUpdater.updateToLatest();
+ updateStatus = result.message;
+
+ if (result.latestVersion != null) {
+ latestVersion = result.latestVersion;
+ }
+
+ currentVersion = result.currentVersion ?? (await DesktopUpdater.getCurrentVersion());
+ } catch (error) {
+ autoUpdateError = `Unable to check for updates: ${error}`;
+ updateStatus = '';
+ } finally {
+ isCheckingForUpdates = false;
+ }
+}
+
async function loadDebounceMs() {
isDebounceLoading = true;
debounceError = '';
@@ -235,20 +320,42 @@ function settingsValueToDialect(value: string): Dialect {
<div class="row top">
<div>
<strong>Automatically check for updates</strong>
- <p>Harper will check for new versions weekly.</p>
+ <p>Harper will check for new versions daily.</p>
+ <p class="result-summary">
+ Current version: {currentVersion || 'loading...'} · Latest version: {latestVersion || 'loading...'}
+ </p>
</div>
<button
class:checked={autoUpdate}
class="checkbox"
type="button"
role="checkbox"
- disabled
- title="Not wired yet"
+ disabled={isAutoUpdateLoading || isAutoUpdateSaving}
aria-checked={autoUpdate}
+ on:click={() => setAutoUpdate(!autoUpdate)}
>
{#if autoUpdate}<span class="settings-icon icon-check" aria-hidden="true"></span>{/if}
</button>
</div>
+ <div class="inline-row">
+ <button
+ class="button"
+ type="button"
+ disabled={isCheckingForUpdates}
+ on:click={checkForUpdates}
+ >
+ {isCheckingForUpdates ? 'Checking...' : 'Check for updates'}
+ </button>
+ </div>
+ {#if isAutoUpdateLoading}
+ <p class="result-summary">Loading update setting...</p>
+ {:else if autoUpdateError}
+ <p class="result-summary">{autoUpdateError}</p>
+ {:else if isAutoUpdateSaving}
+ <p class="result-summary">Saving update setting...</p>
+ {:else if updateStatus}
+ <p class="result-summary">{updateStatus}</p>
+ {/if}
</div>
</div>
diff --git a/harper-desktop/src/routes/+page.svelte b/harper-desktop/src/routes/+page.svelte
index 86d979421..e6eb1b786 100644
--- a/harper-desktop/src/routes/+page.svelte
+++ b/harper-desktop/src/routes/+page.svelte
@@ -2,6 +2,7 @@
import '../app.css';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { onMount } from 'svelte';
+import { DesktopUpdater } from '$lib/DesktopUpdater';
let isSettings = false;
let isViewResolved = false;
@@ -14,6 +15,8 @@ function hasSettingsRoute() {
}
onMount(() => {
+ void DesktopUpdater.maybeAutoUpdate();
+
let currentWindowLabel = '';
try {
diff --git a/justfile b/justfile
index 1a4ce9826..fa47a359d 100644
--- a/justfile
+++ b/justfile
@@ -207,6 +207,15 @@ build-desktop-macos: build-harperjs build-lint-framework build-components build-
pnpm install
cargo tauri build -b app,dmg
+# Build Harper Desktop macOS bundles without updater artifacts.
+build-desktop-macos-unsigned: build-harperjs build-lint-framework build-components build-harper-editor
+ #!/usr/bin/env bash
+ set -eo pipefail
+
+ cd "{{justfile_directory()}}/harper-desktop"
+ pnpm install
+ cargo tauri build -b app,dmg --config '{"bundle":{"createUpdaterArtifacts":false}}'
+
# Build the Harper Obsidian plugin.
build-obsidian: build-harperjs
#!/usr/bin/env bash
diff --git a/packages/web/src/lib/GitHubClient.ts b/packages/web/src/lib/GitHubClient.ts
index a7b4a380d..d1bc0c6c6 100644
--- a/packages/web/src/lib/GitHubClient.ts
+++ b/packages/web/src/lib/GitHubClient.ts
@@ -1,45 +1,91 @@
+export interface GitHubReleaseAsset {
+ name: string;
+ browser_download_url: string;
+}
+
+export interface GitHubRelease {
+ name: string;
+ tag_name: string;
+ body: string | null;
+ published_at: string;
+ assets: GitHubReleaseAsset[];
+}
+
export class GithubClient {
- /// Map of string -> [content, expiration time]
+ private static readonly cacheTtlMs = 3600 * 3000;
private static versionCache: Map<string, [string, number]> = new Map();
+ private static releaseCache: Map<string, [GitHubRelease, number]> = new Map();
public static async getLatestReleaseFromCache(
repoOwner: string,
repoName: string,
): Promise<string | null> {
- const key = `${repoOwner}/${repoName}`;
+ return await this.getFromCache(this.versionCache, `${repoOwner}/${repoName}`, () =>
+ this.getLatestRelease(repoOwner, repoName),
+ );
+ }
- const val = this.versionCache.get(key);
+ public static async getLatestReleaseMetadataFromCache(
+ repoOwner: string,
+ repoName: string,
+ ): Promise<GitHubRelease> {
+ return await this.getFromCache(this.releaseCache, `${repoOwner}/${repoName}`, () =>
+ this.getLatestReleaseMetadata(repoOwner, repoName),
+ );
+ }
- if (val == null) {
- const updatedValue = await this.getLatestRelease(repoOwner, repoName);
- this.versionCache.set(key, [updatedValue, Date.now() + 3600 * 3000]);
- return updatedValue;
- }
+ /**
+ * Return a cached value when it is still fresh, otherwise load and cache a replacement.
+ *
+ * This keeps GitHub release caching behavior consistent between lightweight version
+ * lookups and full release metadata lookups.
+ */
+ private static async getFromCache<T>(
+ cache: Map<string, [T, number]>,
+ key: string,
+ load: () => Promise<T>,
+ ): Promise<T> {
+ const cached = cache.get(key);
+
+ if (cached != null) {
+ const [value, expiry] = cached;
- const [value, expiry] = val;
+ if (expiry >= Date.now()) {
+ return value;
+ }
- if (expiry - Date.now() < 0) {
- this.versionCache.delete(key);
- const updatedValue = await this.getLatestRelease(repoOwner, repoName);
- this.versionCache.set(key, [updatedValue, Date.now() + 3600 * 3000]);
- return updatedValue;
+ cache.delete(key);
}
+ const value = await load();
+ cache.set(key, [value, Date.now() + this.cacheTtlMs]);
+
return value;
}
public static async getLatestRelease(repoOwner: string, repoName: string): Promise<string> {
+ const body = await this.getLatestReleaseMetadata(repoOwner, repoName);
+
+ return body.tag_name;
+ }
+
+ public static async getLatestReleaseMetadata(
+ repoOwner: string,
+ repoName: string,
+ ): Promise<GitHubRelease> {
const resp = await fetch(
`https://api.github.com/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/releases/latest`,
{
headers: {
- ContentType: 'application/json',
+ 'Content-Type': 'application/json',
},
},
);
- const body = await resp.json();
+ if (!resp.ok) {
+ throw new Error(`Unable to get latest GitHub release: ${resp.status} ${resp.statusText}`);
+ }
- return body.name;
+ return (await resp.json()) as GitHubRelease;
}
}
diff --git a/packages/web/src/routes/download-harper-desktop/[target]/[arch]/[current_version]/+server.ts b/packages/web/src/routes/download-harper-desktop/[target]/[arch]/[current_version]/+server.ts
new file mode 100644
index 000000000..74fcc888a
--- /dev/null
+++ b/packages/web/src/routes/download-harper-desktop/[target]/[arch]/[current_version]/+server.ts
@@ -0,0 +1,164 @@
+import { json, type RequestEvent } from '@sveltejs/kit';
+import { type GitHubRelease, type GitHubReleaseAsset, GithubClient } from '$lib/GitHubClient';
+
+const REPO_OWNER = 'automattic';
+const REPO_NAME = 'harper';
+const SIGNATURE_CACHE_TTL_MS = 3600 * 3000;
+
+const signatureCache: Map<string, [string, number]> = new Map();
+
+const responseHeaders = {
+ 'Cache-Control': 'no-cache',
+};
+
+const normalizeVersion = (version: string) => version.trim().replace(/^v/i, '');
+
+const parseVersion = (version: string) => {
+ const coreVersion = normalizeVersion(version).split(/[+-]/)[0];
+ const parts = coreVersion.split('.').map((part) => Number.parseInt(part, 10));
+
+ return parts.some(Number.isNaN) ? null : parts;
+};
+
+const compareVersions = (left: string, right: string) => {
+ const leftParts = parseVersion(left);
+ const rightParts = parseVersion(right);
+
+ if (leftParts == null || rightParts == null) {
+ return normalizeVersion(left).localeCompare(normalizeVersion(right), undefined, {
+ numeric: true,
+ });
+ }
+
+ const maxLength = Math.max(leftParts.length, rightParts.length);
+
+ return (
+ Array.from({ length: maxLength })
+ .map((_, index) => (leftParts[index] ?? 0) - (rightParts[index] ?? 0))
+ .find((diff) => diff !== 0) ?? 0
+ );
+};
+
+const isCurrentVersionUpToDate = (currentVersion: string, latestVersion: string) =>
+ compareVersions(currentVersion, latestVersion) >= 0;
+
+const getAssetPrefix = (target: string, arch: string) => {
+ const normalizedTarget = target.toLowerCase();
+ const normalizedArch = arch.toLowerCase();
+ const isMacOs = ['darwin', 'macos', 'macos-universal', 'apple-darwin'].some((targetName) =>
+ normalizedTarget.includes(targetName),
+ );
+
+ if (!isMacOs) {
+ return null;
+ }
+
+ if (['aarch64', 'arm64'].includes(normalizedArch)) {
+ return 'harper-desktop-macos-arm64';
+ }
+
+ if (['x86_64', 'x64', 'amd64'].includes(normalizedArch)) {
+ return 'harper-desktop-macos-x64';
+ }
+
+ return null;
+};
+
+const findAssetByPrefixAndSuffix = (assets: GitHubReleaseAsset[], prefix: string, suffix: string) =>
+ assets.find((asset) => asset.name.startsWith(prefix) && asset.name.endsWith(suffix));
+
+const findUpdateAssets = (release: GitHubRelease, assetPrefix: string) => {
+ const archiveAsset = findAssetByPrefixAndSuffix(release.assets, assetPrefix, '.app.tar.gz');
+ const signatureAsset = findAssetByPrefixAndSuffix(release.assets, assetPrefix, '.app.tar.gz.sig');
+
+ return archiveAsset == null || signatureAsset == null ? null : { archiveAsset, signatureAsset };
+};
+
+const getSignatureFromCache = async (asset: GitHubReleaseAsset) => {
+ const cacheKey = asset.browser_download_url;
+ const cached = signatureCache.get(cacheKey);
+
+ if (cached != null) {
+ const [signature, expiry] = cached;
+
+ if (expiry >= Date.now()) {
+ return signature;
+ }
+
+ signatureCache.delete(cacheKey);
+ }
+
+ const resp = await fetch(asset.browser_download_url);
+
+ if (!resp.ok) {
+ return null;
+ }
+
+ const signature = (await resp.text()).trim();
+
+ if (signature.length === 0) {
+ return null;
+ }
+
+ signatureCache.set(cacheKey, [signature, Date.now() + SIGNATURE_CACHE_TTL_MS]);
+
+ return signature;
+};
+
+const noUpdate = () => new Response(null, { status: 204, headers: responseHeaders });
+
+export const GET = async ({ params }: RequestEvent) => {
+ const { target, arch, current_version: currentVersion } = params;
+
+ if (target == null || arch == null || currentVersion == null) {
+ return noUpdate();
+ }
+
+ const assetPrefix = getAssetPrefix(target, arch);
+
+ if (assetPrefix == null) {
+ console.log(`No Harper Desktop update available for unsupported platform ${target}/${arch}.`);
+ return noUpdate();
+ }
+
+ const latestRelease = await GithubClient.getLatestReleaseMetadataFromCache(REPO_OWNER, REPO_NAME);
+ const latestVersion = latestRelease.tag_name;
+
+ if (isCurrentVersionUpToDate(currentVersion, latestVersion)) {
+ console.log(
+ `No Harper Desktop update available for ${target}/${arch}. Current: ${currentVersion}. Latest: ${latestVersion}.`,
+ );
+ return noUpdate();
+ }
+
+ const updateAssets = findUpdateAssets(latestRelease, assetPrefix);
+
+ if (updateAssets == null) {
+ console.log(`No Harper Desktop updater assets found for ${assetPrefix} in ${latestVersion}.`);
+ return noUpdate();
+ }
+
+ const signature = await getSignatureFromCache(updateAssets.signatureAsset);
+
+ if (signature == null) {
+ console.log(
+ `Unable to fetch Harper Desktop updater signature ${updateAssets.signatureAsset.name}.`,
+ );
+ return noUpdate();
+ }
+
+ console.log(
+ `Serving Harper Desktop update ${latestVersion} for ${target}/${arch}: ${updateAssets.archiveAsset.name}.`,
+ );
+
+ return json(
+ {
+ version: normalizeVersion(latestVersion),
+ notes: latestRelease.body ?? latestRelease.name,
+ pub_date: latestRelease.published_at,
+ url: updateAssets.archiveAsset.browser_download_url,
+ signature,
+ },
+ { headers: responseHeaders },
+ );
+};
diff --git a/packages/web/src/routes/latestversion/+server.ts b/packages/web/src/routes/latestversion/+server.ts
index 71df761f3..3dcdccc91 100644
--- a/packages/web/src/routes/latestversion/+server.ts
+++ b/packages/web/src/routes/latestversion/+server.ts
@@ -11,7 +11,7 @@ export async function GET() {
return new Response(latestVersion, {
headers: {
- 'Access-Control-Allow-Origin': 'app://obsidian.md',
+ 'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
},
});
@@ -20,7 +20,7 @@ export async function GET() {
export async function OPTIONS() {
return new Response(null, {
headers: {
- 'Access-Control-Allow-Origin': 'app://obsidian.md',
+ 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Harper-Version',
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 53d9013a0..1a28da356 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -47,6 +47,9 @@ importers:
'@tauri-apps/plugin-opener':
specifier: ^2
version: 2.5.4
+ '@tauri-apps/plugin-updater':
+ specifier: ^2.10.1
+ version: 2.10.1
harper-editor:
specifier: workspace:*
version: link:../packages/harper-editor
@@ -4100,6 +4103,9 @@ packages:
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-1HnPkb+AmgO29HBazm4uPLKB+r7zzcTBW1d0fyYp1uP+jwtpoiNDGKMMzz58SFp49nOIrxdE3aUJtT57lfO9CQ==}
+ '@tauri-apps/[email protected]':
+ resolution: {integrity: sha512-NFYMg+tWOZPJdzE/PpFj2qfqwAWwNS3kXrb1tm1gnBJ9mYzZ4WDRrwy8udzWoAnfGCHLuePNLY1WVCNHnh3eRA==}
+
'@tootallnate/[email protected]':
resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==}
engines: {node: '>= 10'}
@@ -11524,8 +11530,8 @@ packages:
resolution: {integrity: sha512-tDuKQJUTfjvi9Fcrs1s6YAQAB9mzhTSbBZMfNgtWNmJlHuoFeXO6dzBFdGeCWRvYL50jQGK0jPsBZYxqZQJ2SA==}
- resolution: {integrity: sha512-nBDSJw5B7Sl1YfsATG2XkW5qgUPODbJhXw++BKygi9w6O/NKS98/uY/nR/DxDq2axEjL6halHW1v+jhm/j1DBQ==}
+ resolution: {integrity: sha512-fegtha91tq2DHphyoiBXVHjVi2YG9zFaRnboT9C28tO1en9Y3wJsfspuy40F+u5wl3hHVbw7cnd1b67kEGHb8g==}
resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}
@@ -15645,7 +15651,7 @@ snapshots:
'@paulirish/[email protected]':
dependencies:
- third-party-web: 0.29.0
+ third-party-web: 0.29.2
'@php-wasm/[email protected]': {}
@@ -16912,6 +16918,10 @@ snapshots:
dependencies:
'@tauri-apps/api': 2.11.0
+ '@tauri-apps/[email protected]':
+ dependencies:
+ '@tauri-apps/api': 2.11.0
+
'@tootallnate/[email protected]': {}
'@tootallnate/[email protected]': {}
@@ -26452,7 +26462,7 @@ snapshots: