tauri-plugin-hot-update 0.1.0

Hot update / OTA live updates for Tauri v2 mobile and desktop apps — CodePush-style, self-hosted
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Command-layer tests: the full plugin (assets install + init + IPC) on
//! `tauri::test::MockRuntime`, with commands invoked through the real IPC
//! route (ACL, argument parsing, serde response) against a real on-disk
//! store — plus golden tests pinning every JSON shape the TypeScript
//! package (`guest-js/`) replicates. Renaming a Rust field must fail here
//! before it can break the cross-language contract.
//!
//! Each `build_app` call is one "cold launch": a fresh `Shared` (new
//! process) over a persistent store root, exactly like the runtime tests.

use std::fs;
use std::path::Path;
use std::sync::{Arc, Mutex};

use semver::Version;
use serde_json::{json, Value};
use tauri::ipc::{CallbackFn, InvokeBody};
use tauri::test::{get_ipc_response, mock_builder, mock_context, noop_assets, MockRuntime};
use tauri::utils::acl::ExecutionContext;
use tauri::webview::InvokeRequest;
use tauri::{App, Listener, WebviewWindow, WebviewWindowBuilder};
use tempfile::TempDir;

use super::*;
use crate::machine::{stage, BundleMeta};
use crate::manifest::{ArchiveInfo, Manifest};
use crate::store::Store;
use crate::testutil::Fixture;

fn ver(s: &str) -> Version {
    Version::parse(s).unwrap()
}

/// One cold launch: full plugin (install + init) over `root`, with all five
/// commands allowed for the local origin. `plugin_config` is the raw
/// `plugins.hot-update` value from tauri.conf.json.
fn try_build_app(root: &Path, plugin_config: Option<Value>) -> tauri::Result<App<MockRuntime>> {
    let mut context = mock_context(noop_assets());
    if let Some(config) = plugin_config {
        context.config_mut().plugins.0.insert("hot-update".into(), config);
    }
    for cmd in ["check", "download", "notify_app_ready", "current_bundle", "reset"] {
        context
            .runtime_authority_mut()
            .__allow_command(format!("plugin:hot-update|{cmd}"), ExecutionContext::Local);
    }
    let handle = crate::install(&mut context);
    mock_builder()
        .plugin(crate::init_for_test(handle, root.to_path_buf()))
        .build(context)
}

fn build_app(root: &Path, plugin_config: Value) -> (App<MockRuntime>, WebviewWindow<MockRuntime>) {
    let app = try_build_app(root, Some(plugin_config)).expect("app builds");
    let webview = WebviewWindowBuilder::new(&app, "main", Default::default())
        .build()
        .expect("webview builds");
    (app, webview)
}

/// Invoke a plugin command through the real IPC route.
fn invoke(webview: &WebviewWindow<MockRuntime>, cmd: &str) -> std::result::Result<Value, Value> {
    let url = if cfg!(any(windows, target_os = "android")) {
        "http://tauri.localhost"
    } else {
        "tauri://localhost"
    };
    get_ipc_response(
        webview,
        InvokeRequest {
            cmd: format!("plugin:hot-update|{cmd}"),
            callback: CallbackFn(0),
            error: CallbackFn(1),
            url: url.parse().unwrap(),
            body: InvokeBody::default(),
            headers: Default::default(),
            invoke_key: tauri::test::INVOKE_KEY.to_string(),
        },
    )
    .map(|body| body.deserialize::<Value>().unwrap())
}

/// A config that passes init validation without any network expectations.
fn enabled_config(fx: &Fixture) -> Value {
    let update = fx.config();
    json!({ "manifestUrl": update.manifest_url, "pubkeys": update.pubkeys })
}

/// Simulate the downloader having staged a bundle (as in the runtime tests).
fn stage_bundle(root: &Path, seq: u64, version: &str, sha: &str) {
    let store = Store::new(root.to_path_buf());
    let dir = store.bundle_dir(seq);
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("index.html"), format!("bundle {seq}")).unwrap();
    store
        .update(|state| {
            stage(
                state,
                seq,
                BundleMeta {
                    version: ver(version),
                    archive_sha256: sha.to_string(),
                },
            )
        })
        .unwrap()
        .expect("stage gates should pass");
}

fn raw_state(root: &Path) -> Value {
    serde_json::from_slice(&fs::read(root.join("state.json")).unwrap()).unwrap()
}

// ---------------------------------------------------------- wire shapes
// Golden tests: the exact JSON the TS types in guest-js/index.ts replicate.

#[test]
fn update_outcome_wire_shapes_are_pinned() {
    let manifest = Manifest {
        version: ver("1.1.0"),
        created_at: "2026-07-10T00:00:00Z".into(),
        min_shell_version: ver("1.0.0"),
        archive: ArchiveInfo {
            url: "https://cdn.example.com/bundle.tar.gz".into(),
            sha256: "aa".repeat(32),
            size: 4096,
        },
    };
    let cases = [
        (
            UpdateOutcome::Available { manifest },
            json!({
                "status": "available",
                "manifest": {
                    "version": "1.1.0",
                    "createdAt": "2026-07-10T00:00:00Z",
                    "minShellVersion": "1.0.0",
                    "archive": {
                        "url": "https://cdn.example.com/bundle.tar.gz",
                        "sha256": "aa".repeat(32),
                        "size": 4096,
                    },
                },
            }),
        ),
        (
            UpdateOutcome::Staged { seq: 3, version: ver("1.1.0") },
            json!({ "status": "staged", "seq": 3, "version": "1.1.0" }),
        ),
        (
            UpdateOutcome::UpToDate { offered: ver("1.0.0"), watermark: ver("1.1.0") },
            json!({ "status": "upToDate", "offered": "1.0.0", "watermark": "1.1.0" }),
        ),
        (
            UpdateOutcome::Blacklisted { version: ver("1.1.0") },
            json!({ "status": "blacklisted", "version": "1.1.0" }),
        ),
        (
            UpdateOutcome::ShellTooOld { required: ver("2.0.0"), shell: ver("1.0.0") },
            json!({ "status": "shellTooOld", "required": "2.0.0", "shell": "1.0.0" }),
        ),
        (
            UpdateOutcome::AlreadyStaged { seq: 3, version: ver("1.1.0") },
            json!({ "status": "alreadyStaged", "seq": 3, "version": "1.1.0" }),
        ),
    ];
    for (outcome, expected) in cases {
        assert_eq!(serde_json::to_value(&outcome).unwrap(), expected, "{outcome:?}");
    }
}

#[test]
fn ack_result_wire_shapes_are_pinned() {
    let cases = [
        (AckResult::Committed { seq: 2 }, json!({ "status": "committed", "seq": 2 })),
        (
            AckResult::AlreadyCommitted { seq: 2 },
            json!({ "status": "alreadyCommitted", "seq": 2 }),
        ),
        (AckResult::EmbeddedNoop, json!({ "status": "embeddedNoop" })),
        (AckResult::Stale { seq: 2 }, json!({ "status": "stale", "seq": 2 })),
    ];
    for (result, expected) in cases {
        assert_eq!(serde_json::to_value(result).unwrap(), expected, "{result:?}");
    }
}

#[test]
fn current_bundle_wire_shapes_are_pinned() {
    let ota = CurrentBundle {
        source: BundleSource::Ota,
        seq: Some(1),
        version: ver("1.1.0"),
    };
    assert_eq!(
        serde_json::to_value(&ota).unwrap(),
        json!({ "source": "ota", "seq": 1, "version": "1.1.0" })
    );
    let embedded = CurrentBundle {
        source: BundleSource::Embedded,
        seq: None,
        version: ver("1.0.0"),
    };
    assert_eq!(
        serde_json::to_value(&embedded).unwrap(),
        json!({ "source": "embedded", "seq": null, "version": "1.0.0" })
    );
}

#[test]
fn download_progress_wire_shape_is_pinned() {
    let progress = DownloadProgress { downloaded: 1024, total: 4096 };
    let value = serde_json::to_value(progress).unwrap();
    assert_eq!(value, json!({ "downloaded": 1024, "total": 4096 }));
    // Round-trips for Rust-side listeners of PROGRESS_EVENT.
    assert_eq!(serde_json::from_value::<DownloadProgress>(value).unwrap(), progress);
}

// ------------------------------------------------------------- throttle

#[test]
fn throttle_gates_by_time_but_always_passes_first_and_final() {
    let mut throttle = ProgressThrottle::new(Duration::from_secs(3600));
    assert!(throttle.should_emit(1, 100), "first chunk always emits");
    assert!(!throttle.should_emit(2, 100), "within the interval: suppressed");
    assert!(!throttle.should_emit(50, 100));
    assert!(throttle.should_emit(100, 100), "final chunk always emits");

    let mut unthrottled = ProgressThrottle::new(Duration::ZERO);
    assert!(unthrottled.should_emit(1, 100));
    assert!(unthrottled.should_emit(2, 100), "elapsed >= zero interval: emits");
}

// ------------------------------------------------------------ IPC round-trips

#[test]
fn fresh_install_reports_embedded_and_acks_as_noop_via_ipc() {
    let fx = Fixture::new();
    let (_app, webview) = build_app(&fx.root, enabled_config(&fx));

    // Mock apps run at package version 0.1.0.
    assert_eq!(
        invoke(&webview, "current_bundle").unwrap(),
        json!({ "source": "embedded", "seq": null, "version": "0.1.0" })
    );
    assert_eq!(
        invoke(&webview, "notify_app_ready").unwrap(),
        json!({ "status": "embeddedNoop" })
    );
}

#[test]
fn download_via_ipc_stages_a_signed_release_and_emits_progress() {
    let fx = Fixture::new();
    let (manifest, archive_path) = fx.publish("0.2.0", "0.1.0");
    let (app, webview) = build_app(&fx.root, enabled_config(&fx));

    let seen: Arc<Mutex<Vec<DownloadProgress>>> = Arc::default();
    let sink = Arc::clone(&seen);
    app.listen_any(PROGRESS_EVENT, move |event| {
        sink.lock().unwrap().push(serde_json::from_str(event.payload()).unwrap());
    });

    // check() first: available, nothing downloaded.
    assert_eq!(
        invoke(&webview, "check").unwrap(),
        json!({
            "status": "available",
            "manifest": {
                "version": "0.2.0",
                "createdAt": manifest.created_at,
                "minShellVersion": "0.1.0",
                "archive": {
                    "url": manifest.archive.url,
                    "sha256": manifest.archive.sha256,
                    "size": manifest.archive.size,
                },
            },
        })
    );
    assert_eq!(fx.server.request_count(&archive_path), 0);

    assert_eq!(
        invoke(&webview, "download").unwrap(),
        json!({ "status": "staged", "seq": 1, "version": "0.2.0" })
    );
    assert_eq!(
        fs::read(fx.bundle_dir(1).join("index.html")).unwrap(),
        b"<html>ota v-next</html>"
    );

    let seen = seen.lock().unwrap();
    assert!(!seen.is_empty(), "progress must be observable from JS");
    assert!(
        seen.windows(2).all(|w| w[0].downloaded < w[1].downloaded),
        "monotonic: {seen:?}"
    );
    assert!(seen.iter().all(|p| p.total == manifest.archive.size));
    let last = seen.last().unwrap();
    assert_eq!(last.downloaded, last.total, "the 100% event is guaranteed");

    // A second check now reports the staged bundle.
    assert_eq!(
        invoke(&webview, "check").unwrap(),
        json!({ "status": "alreadyStaged", "seq": 1, "version": "0.2.0" })
    );
}

#[test]
fn trial_ack_commit_cycle_through_the_command_layer() {
    let fx = Fixture::new();
    fx.publish("0.2.0", "0.1.0");

    // Launch 1: download and stage.
    {
        let (_app, webview) = build_app(&fx.root, enabled_config(&fx));
        assert_eq!(invoke(&webview, "download").unwrap()["status"], "staged");
    }

    // Launch 2 (cold boot): trial serving, then the ack commits.
    {
        let (_app, webview) = build_app(&fx.root, enabled_config(&fx));
        assert_eq!(
            invoke(&webview, "current_bundle").unwrap(),
            json!({ "source": "ota", "seq": 1, "version": "0.2.0" })
        );
        assert_eq!(
            invoke(&webview, "notify_app_ready").unwrap(),
            json!({ "status": "committed", "seq": 1 })
        );
        assert_eq!(
            invoke(&webview, "notify_app_ready").unwrap(),
            json!({ "status": "alreadyCommitted", "seq": 1 }),
            "the ack is idempotent"
        );
    }
    assert_eq!(raw_state(&fx.root)["committed"], 1);

    // Launch 3: steady state.
    let (_app, webview) = build_app(&fx.root, enabled_config(&fx));
    assert_eq!(invoke(&webview, "current_bundle").unwrap()["source"], "ota");
}

#[test]
fn unacked_trial_rolls_back_through_the_command_layer() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("hot-update");
    let config = json!({
        "manifestUrl": "https://updates.example.com/manifest.json",
        "pubkeys": [minisign::KeyPair::generate_unencrypted_keypair().unwrap().pk.to_base64()],
    });
    try_build_app(&root, Some(config.clone())).unwrap(); // boot 0: init state
    stage_bundle(&root, 1, "0.2.0", "sha-1");

    // Trial boot: served, but the app "crashes" — no ack.
    {
        let (_app, webview) = build_app(&root, config.clone());
        assert_eq!(invoke(&webview, "current_bundle").unwrap()["source"], "ota");
    }

    // Next boot: rolled back to embedded, archive hash blacklisted.
    let (_app, webview) = build_app(&root, config);
    assert_eq!(
        invoke(&webview, "current_bundle").unwrap(),
        json!({ "source": "embedded", "seq": null, "version": "0.1.0" })
    );
    assert_eq!(raw_state(&root)["failed"][0], "sha-1");
}

#[test]
fn reset_via_ipc_reverts_to_embedded_on_the_next_launch() {
    let fx = Fixture::new();
    fx.publish("0.2.0", "0.1.0");
    {
        let (_app, webview) = build_app(&fx.root, enabled_config(&fx));
        assert_eq!(invoke(&webview, "download").unwrap()["status"], "staged");
    }
    {
        let (_app, webview) = build_app(&fx.root, enabled_config(&fx));
        assert_eq!(invoke(&webview, "notify_app_ready").unwrap()["status"], "committed");
        assert_eq!(invoke(&webview, "reset").unwrap(), Value::Null);
        // The running process keeps serving what it booted…
        assert_eq!(invoke(&webview, "current_bundle").unwrap()["source"], "ota");
    }
    assert_eq!(raw_state(&fx.root)["committed"], Value::Null);

    // …and the next launch is back on embedded.
    let (_app, webview) = build_app(&fx.root, enabled_config(&fx));
    assert_eq!(invoke(&webview, "current_bundle").unwrap()["source"], "embedded");
}

// ------------------------------------------------------------- dark-ship

#[test]
fn disabled_plugin_is_inert_but_report_and_ack_commands_stay_total() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("hot-update");
    let (_app, webview) = build_app(&root, json!({ "enabled": false }));

    // Boot code can call these unconditionally.
    assert_eq!(
        invoke(&webview, "current_bundle").unwrap(),
        json!({ "source": "embedded", "seq": null, "version": "0.1.0" })
    );
    assert_eq!(
        invoke(&webview, "notify_app_ready").unwrap(),
        json!({ "status": "embeddedNoop" })
    );
    assert_eq!(invoke(&webview, "reset").unwrap(), Value::Null);

    // Update commands refuse loudly.
    for cmd in ["check", "download"] {
        let err = invoke(&webview, cmd).unwrap_err();
        assert!(
            err.as_str().unwrap().contains("disabled"),
            "{cmd} must explain it is disabled, got {err}"
        );
    }
    assert!(!root.exists(), "a disabled plugin must not touch the disk");
}

// ------------------------------------------------------ config init gate

#[test]
fn missing_plugin_config_aborts_startup() {
    let tmp = TempDir::new().unwrap();
    let err = try_build_app(&tmp.path().join("hot-update"), None).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("plugins.hot-update"), "{msg}");
    assert!(msg.contains("enabled"), "must point at the dark-ship escape: {msg}");
}

#[test]
fn invalid_config_aborts_startup() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("hot-update");

    let bad_key = json!({
        "manifestUrl": "https://updates.example.com/manifest.json",
        "pubkeys": ["not-a-minisign-key"],
    });
    let msg = try_build_app(&root, Some(bad_key)).unwrap_err().to_string();
    assert!(msg.contains("public key"), "{msg}");

    let query_url = json!({
        "manifestUrl": "https://updates.example.com/manifest.json?v=2",
        "pubkeys": ["irrelevant"],
    });
    let msg = try_build_app(&root, Some(query_url)).unwrap_err().to_string();
    assert!(msg.contains("query string"), "{msg}");

    let typo = json!({
        "manifestUrl": "https://updates.example.com/manifest.json",
        "pubKeys": ["RW..."],
    });
    let msg = try_build_app(&root, Some(typo)).unwrap_err().to_string();
    assert!(msg.contains("pubKeys"), "typos must not be silently ignored: {msg}");
}