Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(release): backport #9126, #9124 and #9099 to v0.8.5 (#9133)

James Dam8e92001d9a86
diff --git a/docs/src/pages/changelog/2026-09-22-jan-v0.8.5.mdx b/docs/src/pages/changelog/2026-09-22-jan-v0.8.5.mdx
index 168927bc7..a66db6545 100644
--- a/docs/src/pages/changelog/2026-09-22-jan-v0.8.5.mdx
+++ b/docs/src/pages/changelog/2026-09-22-jan-v0.8.5.mdx
@@ -19,6 +19,8 @@ No new features are announced in v0.8.5. Work in progress stays in the nightly c
One thing a first launch will notice: the first-run setup is now a guided wizard - welcome, engine setup, a first model, and the consent page - instead of a single screen. It is onboarding rather than a new capability, so it is not a headline; it is written down here so a new install is not a surprise.
+The desktop app no longer installs the `jan` command-line agent or adds it to your `PATH`. On Windows, updating from v0.8.4 removes the `jan.exe` it put in the app's `resources\bin` folder, but leaves that folder's entry in your user `PATH`; you can delete the entry. The CLI is now a separate download; see the [agent quickstart](https://jan.ai/docs/agent/quickstart) to install it.
+
---
# Bug Fixes
@@ -42,6 +44,7 @@ One thing a first launch will notice: the first-run setup is now a guided wizard
- Zoom shortcuts are scoped to chat message text, so zooming a message no longer rescales the whole app.
- Hub search ranks exact model id matches first.
- The Windows installer template substitutes `jan_workspace` correctly.
+- On Windows, the Start-menu and desktop shortcuts keep working after the in-app update renames the app executable.
**Agent & Tooling**
diff --git a/docs/src/pages/docs/agent/telemetry.mdx b/docs/src/pages/docs/agent/telemetry.mdx
index 510dd79fd..c406baedc 100644
--- a/docs/src/pages/docs/agent/telemetry.mdx
+++ b/docs/src/pages/docs/agent/telemetry.mdx
@@ -112,14 +112,18 @@ export what is buffered, then exit as that signal would.
All metrics are monotonic sums. They are cumulative (running totals since the process started)
unless `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` asks for delta, where each point holds
only what changed since the last export. Every point carries `session.id` unless
-`OTEL_METRICS_INCLUDE_SESSION_ID=false`. When an RPC host archives a session, its series are sent
-one last time and then dropped, so a long-lived host doesn't keep exporting finished sessions.
+`OTEL_METRICS_INCLUDE_SESSION_ID=false`, so a backend that sums points per session can fold all of
+them. Under delta, `jan_agent.telemetry.dropped` carries the session it happened in; drops before
+any session started are held and sent with the first one. `jan cli agent status` lists
+`otlp-delta` in `capabilities` for builds that behave this way. When an RPC host archives a
+session, its series are sent one last time and then dropped, so a long-lived host doesn't keep
+exporting finished sessions.
| Metric | Unit | Attributes |
| --- | --- | --- |
| `jan_agent.session.count` | 1 | |
| `jan_agent.prompt.count` | 1 | Counts new user prompts. A run that continues or resumes a conversation without a new user message doesn't count. |
-| `jan_agent.turn.count` | 1 | `agent` (`main` / `subagent`) |
+| `jan_agent.turn.count` | 1 | `agent` (`main` / `subagent`), and the run's `session.id` |
| `jan_agent.token.usage` | tokens | `type` (`input` / `output` / `cache_read` / `cache_write`), `model`, `provider` |
| `jan_agent.cost.usage` | USD | `model`, `provider`. Only for models whose price is in the model catalog. An unpriced model reports nothing, not zero. |
| `jan_agent.api_request.count` | 1 | `model`, `provider`, `success` |
@@ -216,7 +220,10 @@ LANGFUSE_PUBLIC_KEY=... LANGFUSE_SECRET_KEY=... LANGFUSE_BASE_URL=https://cloud.
Recording a signal never waits: it goes into a bounded in-memory queue. If a collector is slow or
down, new records are dropped and counted in `jan_agent.telemetry.dropped`, and the turn doesn't
slow down. A collector that answers 429, 502, 503 or 504 gets one retry, after its `Retry-After`
-(up to 10 seconds; a longer wait drops the batch) or 1 second.
+(up to 10 seconds; a longer wait counts as a failure) or 1 second. A log or trace batch that still
+fails is dropped. A metrics export that still fails keeps its window: the next export carries it
+again, over the combined span, so a delta backend loses nothing. If the failed export had in fact
+landed and only its answer was lost, that window is counted twice.
Export failures are logged at debug level (`RUST_LOG=debug`) on stderr and never printed to
stdout.
diff --git a/docs/src/pages/docs/desktop/troubleshooting.mdx b/docs/src/pages/docs/desktop/troubleshooting.mdx
index 3acf64ae9..4aa1c4840 100644
--- a/docs/src/pages/docs/desktop/troubleshooting.mdx
+++ b/docs/src/pages/docs/desktop/troubleshooting.mdx
@@ -496,20 +496,19 @@ The "Unexpected token" error usually relates to OpenAI API authentication or reg
## Jan CLI
-### Windows: running `jan` opens the Jan application window
+### `jan` is not recognized after updating the desktop app
-If typing `jan` in a terminal opens the Jan desktop app instead of the CLI, your system is resolving the `jan` command to the app launcher rather than the CLI binary.
+Since v0.8.5 the desktop app no longer includes the `jan` CLI or adds it to your `Path`. Updating from an earlier version removes the CLI that was bundled with the app. Install the CLI separately by following the [agent quickstart](/docs/agent/quickstart).
-To fix this, add the CLI binary directory to your `Path` environment variable:
+On Windows, the update leaves an old entry in your user `Path` that points at a folder with no CLI in it any more. You can remove it:
1. Open **System Properties** → **Advanced** → **Environment Variables**
-2. Under **System variables** (or **User variables**), select **Path** and click **Edit**
-3. Click **New** and add:
+2. Under **User variables**, select **Path** and click **Edit**
+3. Select this entry and click **Delete**:
```
C:\Users\<username>\AppData\Local\Programs\Jan\resources\bin
```
- Replace `<username>` with your Windows username.
-4. Click **OK** to save, then open a new terminal window and try `jan` again. The CLI binary is installed as `jan.exe` inside that directory.
+4. Click **OK** to save, then open a new terminal window.
## Need Further Support?
diff --git a/src-tauri/build-utils/buildAppImage.sh b/src-tauri/build-utils/buildAppImage.sh
index d81bed384..816db5557 100755
--- a/src-tauri/build-utils/buildAppImage.sh
+++ b/src-tauri/build-utils/buildAppImage.sh
@@ -20,6 +20,18 @@ fi
# bundle additional resources in the AppDir without pulling in their dependencies
cp ./src-tauri/resources/bin/bun $APP_DIR/usr/bin/bun
+# tauri-cli before 2.11.4 (tauri-apps/tauri#15596) links .DirIcon to the icon's
+# absolute build-host path, which dangles inside the mounted AppImage. appimagetool
+# keeps it because it resolves here, so re-point it relative to the AppDir root.
+DIR_ICON="$APP_DIR/.DirIcon"
+if [[ "$(readlink "$DIR_ICON")" == /* ]]; then
+ ln -sfn "$(basename "$(readlink "$DIR_ICON")")" "$DIR_ICON"
+fi
+if [ ! -f "$DIR_ICON" ] || [[ "$(readlink "$DIR_ICON")" == /* ]]; then
+ echo ".DirIcon in $APP_DIR is missing or not relative to the AppDir."
+ exit 1
+fi
+
# remove appimage generated by tauri build
APP_IMAGE=./src-tauri/target/release/bundle/appimage/$(ls ./src-tauri/target/release/bundle/appimage/ | grep AppImage | head -1)
echo $APP_IMAGE
diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rs
index f3779e0ac..eb6bafd0e 100644
--- a/src-tauri/src/core/agent/otel/mod.rs
+++ b/src-tauri/src/core/agent/otel/mod.rs
@@ -58,11 +58,14 @@ const ERROR_CAP: usize = 512;
/// The wait before retrying an export the collector asked to be retried,
/// when it did not say how long.
const RETRY_DELAY: Duration = Duration::from_secs(1);
-/// The longest `Retry-After` honoured; a longer one drops the batch instead.
+/// The longest `Retry-After` honoured; a longer one counts as a failed export.
const MAX_RETRY_DELAY: Duration = Duration::from_secs(10);
/// Telemetry capabilities this build reports in `jan cli agent status`.
-pub const CAPABILITIES: &[&str] = &[];
+/// `otlp-delta`: `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta` is
+/// honoured and every metric point carries `session.id`, so a backend that
+/// sums delta points per session can fold them.
+pub const CAPABILITIES: &[&str] = &["otlp-delta"];
/// Per-token prices for `(provider, model)`, when the catalog knows them.
pub type Pricer = Box<dyn Fn(Option<&str>, &str) -> Option<TokenRates> + Send + Sync>;
@@ -626,6 +629,16 @@ fn random_ids() -> ([u8; 16], [u8; 8]) {
}
}
+/// What one metrics export took out of [`State`]: the series it cleared or
+/// evicted and the window it closed. Handed back to [`State::export_failed`]
+/// when the export never reached the collector, so nothing is lost with it.
+pub struct Exported {
+ counters: BTreeMap<SeriesKey, f64>,
+ closed_sessions: HashSet<String>,
+ last_export_nanos: u64,
+ dropped_reported: u64,
+}
+
/// Everything the worker folds signals into. Pure: no I/O, so the mapping from
/// events to metrics and logs is testable without a collector.
pub struct State {
@@ -1043,7 +1056,11 @@ impl State {
self.log(wall, "jan_agent.api_request", false, session.as_deref(), child.as_ref(), fields);
}
EventSignal::Step => {
- let mut attrs = Vec::new();
+ // Carries the run's session like every other point, so a
+ // backend that groups by `session.id` never sees a turn with
+ // no session to put it in.
+ let session = self.session_of(&run);
+ let mut attrs = self.session_attr(session.as_deref());
attrs.push(metric_attr("agent", if child.is_some() { "subagent" } else { "main" }));
self.add("jan_agent.turn.count", attrs, 1.0);
}
@@ -1207,8 +1224,16 @@ impl State {
),
};
let mut by_name: BTreeMap<&'static str, Vec<Point>> = BTreeMap::new();
- let dropped_key = ("jan_agent.telemetry.dropped", Vec::new());
- let dropped_entry = (dropped > 0).then_some((&dropped_key, dropped as f64));
+ // A delta window's drops go under the session it happened in, like
+ // every other point. A cumulative total stays process-wide: moving a
+ // running total between sessions' series would count it twice.
+ let dropped_attrs = match temporality {
+ Temporality::Delta => self.session_attr(self.main_session.as_deref()),
+ Temporality::Cumulative => Vec::new(),
+ };
+ let dropped_key = ("jan_agent.telemetry.dropped", dropped_attrs);
+ let dropped_entry =
+ (dropped > 0 && self.dropped_reportable()).then_some((&dropped_key, dropped as f64));
for ((name, attrs), value) in self
.counters
.iter()
@@ -1246,29 +1271,68 @@ impl State {
.collect()
}
+ /// Whether a delta window's drops can be exported now. With session ids
+ /// on, they wait for a session to carry them rather than go out as the
+ /// only point with none, which a backend grouping by `session.id` would
+ /// file as a session of its own; the count is kept until then.
+ fn dropped_reportable(&self) -> bool {
+ self.cfg.temporality == Temporality::Cumulative
+ || !self.cfg.metrics_session_id
+ || self.main_session.is_some()
+ }
+
/// The snapshot [`State::metrics`] took at `now` was handed to the
/// exporter. Delta starts the next window here, empty; cumulative drops
/// the series of sessions closed since the last export, whose final
/// values that snapshot carried, so a long-lived host's series stay
- /// bounded by its live sessions.
- pub fn exported(&mut self, now: u64, dropped: u64) {
+ /// bounded by its live sessions. What it took comes back as an
+ /// [`Exported`], for [`State::export_failed`] if the export never landed.
+ pub fn exported(&mut self, now: u64, dropped: u64) -> Exported {
+ let mut taken = Exported {
+ counters: BTreeMap::new(),
+ closed_sessions: HashSet::new(),
+ last_export_nanos: self.last_export_nanos,
+ dropped_reported: self.dropped_reported,
+ };
match self.cfg.temporality {
Temporality::Delta => {
- self.counters.clear();
+ taken.counters = std::mem::take(&mut self.counters);
self.last_export_nanos = now;
- self.dropped_reported = dropped;
+ if self.dropped_reportable() {
+ self.dropped_reported = dropped;
+ }
}
Temporality::Cumulative => {
let closed = std::mem::take(&mut self.closed_sessions);
if !closed.is_empty() {
- self.counters.retain(|(_, attrs), _| {
- !attrs
- .iter()
- .any(|(k, v)| k == "session.id" && closed.contains(v))
- });
+ let (gone, kept): (BTreeMap<_, _>, BTreeMap<_, _>) = std::mem::take(&mut self.counters)
+ .into_iter()
+ .partition(|((_, attrs), _)| {
+ attrs.iter().any(|(k, v)| k == "session.id" && closed.contains(v))
+ });
+ self.counters = kept;
+ taken.counters = gone;
}
+ taken.closed_sessions = closed;
}
}
+ taken
+ }
+
+ /// The export [`State::exported`] was handed to never reached the
+ /// collector: put back what it took, so the next export carries it. A
+ /// delta window resumes from where the failed one started, with what
+ /// accrued meanwhile added on; a closed session's cumulative series wait
+ /// for the next export to carry their final values.
+ pub fn export_failed(&mut self, taken: Exported) {
+ for (key, value) in taken.counters {
+ *self.counters.entry(key).or_insert(0.0) += value;
+ }
+ self.closed_sessions.extend(taken.closed_sessions);
+ if self.cfg.temporality == Temporality::Delta {
+ self.last_export_nanos = taken.last_export_nanos;
+ self.dropped_reported = taken.dropped_reported;
+ }
}
}
@@ -1385,12 +1449,20 @@ impl Worker {
return;
}
self.metrics_dirty = false;
- self.state.exported(now, dropped);
+ let taken = self.state.exported(now, dropped);
let body = target.protocol.encode(
|| encode::metrics_json(&self.origin, &metrics),
|| encode::metrics_proto(&self.origin, &metrics),
);
- self.post(&target, body, "metrics").await;
+ if !self.post(&target, body, "metrics").await {
+ // No 2xx: a delta window that was cleared would otherwise be lost
+ // for good, so the next export carries it again. An export that
+ // did land but whose answer never came back is then counted twice;
+ // that is rarer, and smaller, than losing every failed window.
+ self.state.export_failed(taken);
+ self.metrics_dirty = true;
+ log::debug!("telemetry: metrics kept for the next export");
+ }
}
async fn export_logs(&mut self) {
@@ -1427,7 +1499,9 @@ impl Worker {
/// retried: no collector is listening, and waiting on one would only hold
/// up the process's exit. Failures are the collector's problem, not the
/// run's: logged at debug (never the URL's headers) and otherwise ignored.
- async fn post(&self, target: &Target, body: Vec<u8>, signal: &str) {
+ /// Returns whether the collector accepted the batch, so metrics can keep
+ /// a window whose export failed.
+ async fn post(&self, target: &Target, body: Vec<u8>, signal: &str) -> bool {
let mut request = self
.client
.post(&target.url)
@@ -1439,7 +1513,7 @@ impl Worker {
// A byte body clones by reference count, so the retry copies nothing.
let retry = request.try_clone();
let delay = match request.send().await {
- Ok(response) if response.status().is_success() => return,
+ Ok(response) if response.status().is_success() => return true,
Ok(response) => {
let status = response.status();
let retry_after =
@@ -1453,14 +1527,18 @@ impl Worker {
None
}
};
- let (Some(delay), Some(retry)) = (delay, retry) else { return };
+ let (Some(delay), Some(retry)) = (delay, retry) else { return false };
tokio::time::sleep(delay).await;
match retry.send().await {
- Ok(response) if response.status().is_success() => {}
+ Ok(response) if response.status().is_success() => true,
Ok(response) => {
- log::debug!("telemetry: {signal} export rejected on retry, dropped: HTTP {}", response.status())
+ log::debug!("telemetry: {signal} export rejected on retry: HTTP {}", response.status());
+ false
+ }
+ Err(e) => {
+ log::debug!("telemetry: {signal} export failed on retry: {}", e.without_url());
+ false
}
- Err(e) => log::debug!("telemetry: {signal} export failed on retry, dropped: {}", e.without_url()),
}
}
}
diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rs
index 5e7b8e181..153b04618 100644
--- a/src-tauri/src/core/agent/otel/tests.rs
+++ b/src-tauri/src/core/agent/otel/tests.rs
@@ -1153,3 +1153,128 @@ fn every_claude_code_signal_has_a_jan_equivalent_or_a_reason() {
}
}
}
+
+#[test]
+fn a_turn_carries_its_runs_session() {
+ let state = fold(
+ cfg_with(false, false),
+ None,
+ &[provenance(None, "sess-1"), StreamEvent::Step { index: 1, max: 0 }],
+ );
+ assert_eq!(
+ point(&state, "jan_agent.turn.count", &[("agent", "main"), ("session.id", "sess-1")]),
+ Some(PointValue::Int(1))
+ );
+}
+
+#[test]
+fn delta_drops_wait_for_a_session_to_carry_them() {
+ let cfg = Arc::new(cfg_temporality("delta"));
+ let mut state = State::new(Arc::clone(&cfg), None);
+ // Dropped before any run started: no session to put them in, so they
+ // are held rather than sent as the one point without a session.
+ assert!(state.metrics(100, 4).is_empty());
+ let _ = state.exported(100, 4);
+ start_run(&mut state, "sess-1");
+ let metrics = state.metrics(200, 4);
+ assert_eq!(
+ point_in(&metrics, "jan_agent.telemetry.dropped", &[("session.id", "sess-1")]).map(|p| p.0),
+ Some(PointValue::Int(4)),
+ "the held drops go out with the first session"
+ );
+ let _ = state.exported(200, 4);
+ assert!(state.metrics(300, 4).iter().all(|m| m.name != "jan_agent.telemetry.dropped"));
+}
+
+#[test]
+fn a_failed_delta_export_puts_its_window_back() {
+ let cfg = Arc::new(cfg_temporality("delta"));
+ let mut state = State::new(Arc::clone(&cfg), None);
+ let started = state.last_export_nanos;
+ start_run(&mut state, "sess-1");
+ feed(&mut state, &cfg, &[provenance(None, "sess-1"), usage(10, 1, 0, 0)]);
+ let input = [("type", "input"), ("session.id", "sess-1")];
+ assert_eq!(point_in(&state.metrics(100, 2), "jan_agent.token.usage", &input).map(|p| p.0), Some(PointValue::Int(10)));
+ let taken = state.exported(100, 2);
+ // More accrues while the export is in flight, then the export fails.
+ feed(&mut state, &cfg, &[provenance(None, "sess-1"), usage(5, 0, 0, 0)]);
+ state.export_failed(taken);
+ let retry = state.metrics(200, 2);
+ assert_eq!(
+ point_in(&retry, "jan_agent.token.usage", &input),
+ Some((PointValue::Int(15), started, 200)),
+ "the failed window and what accrued since, over the whole span"
+ );
+ assert_eq!(
+ point_in(&retry, "jan_agent.telemetry.dropped", &[]).map(|p| p.0),
+ Some(PointValue::Int(2)),
+ "drops the failed export carried are reported again"
+ );
+ assert!(retry.iter().any(|m| m.name == "jan_agent.session.count"), "nothing the failed window held is lost");
+}
+
+#[test]
+fn a_failed_cumulative_export_keeps_a_closed_sessions_final_values() {
+ let cfg = Arc::new(cfg_temporality("cumulative"));
+ let mut state = State::new(Arc::clone(&cfg), None);
+ start_run(&mut state, "sess-a");
+ feed(&mut state, &cfg, &[provenance(None, "sess-a"), usage(10, 1, 0, 0)]);
+ state.apply(Instant::now(), 3, Signal::SessionClosed { session: "sess-a".into() });
+ let has_a = |metrics: &[Metric]| {
+ point_in(metrics, "jan_agent.token.usage", &[("type", "input"), ("session.id", "sess-a")]).is_some()
+ };
+ let taken = state.exported(100, 0);
+ assert!(!has_a(&state.metrics(150, 0)), "evicted once handed to an export");
+ state.export_failed(taken);
+ assert!(has_a(&state.metrics(200, 0)), "back until an export actually carries it");
+ let _ = state.exported(200, 0);
+ assert!(!has_a(&state.metrics(300, 0)));
+}
+
+fn cfg_delta_for(url: &str) -> Config {
+ let url = url.to_string();
+ let env = move |key: &str| match key {
+ config::ENABLE_ENV => Some("1".to_string()),
+ "OTEL_EXPORTER_OTLP_ENDPOINT" => Some(url.clone()),
+ "OTEL_EXPORTER_OTLP_PROTOCOL" => Some("http/json".to_string()),
+ "OTEL_EXPORTER_OTLP_TIMEOUT" => Some("500".to_string()),
+ "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE" => Some("delta".to_string()),
+ _ => None,
+ };
+ config::resolve(&env, None, None).unwrap()
+}
+
+#[tokio::test]
+async fn a_delta_window_whose_export_failed_goes_out_with_the_next() {
+ // The first run's logs and metrics are both refused, retry included
+ // (four 503s); the second run's exports land.
+ let (url, seen) = collector_refusing(false, 4).await;
+ let t = Telemetry::start(cfg_delta_for(&url), None, "0.0.0-test");
+ scripted_run(&t);
+ scripted_run(&t);
+ t.shutdown(Duration::from_secs(5)).await;
+ let seen = seen.lock().unwrap().clone();
+ let metrics: Vec<Value> = seen
+ .iter()
+ .filter(|(p, _)| p == "/v1/metrics")
+ .map(|(_, b)| serde_json::from_slice(b).unwrap())
+ .collect();
+ let input_tokens = |body: &Value| -> Option<i64> {
+ body["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
+ .as_array()?
+ .iter()
+ .find(|m| m["name"] == "jan_agent.token.usage")?["sum"]["dataPoints"]
+ .as_array()?
+ .iter()
+ .find(|p| p["attributes"].to_string().contains("\"input\""))?["asInt"]
+ .as_str()?
+ .parse()
+ .ok()
+ };
+ let landed = metrics.last().expect("a metrics POST landed");
+ assert_eq!(
+ input_tokens(landed),
+ Some(18),
+ "the refused window (9) and the next (9) arrive together: {metrics:?}"
+ );
+}
diff --git a/src-tauri/tauri.bundle.windows.nsis.template b/src-tauri/tauri.bundle.windows.nsis.template
index b231a186f..e85e6120d 100644
--- a/src-tauri/tauri.bundle.windows.nsis.template
+++ b/src-tauri/tauri.bundle.windows.nsis.template
@@ -724,6 +724,13 @@ Function .onInit
!if "${INSTALLMODE}" == "both"
!insertmacro MULTIUSER_INIT
!endif
+
+ ; Captured here rather than in Section Install, where stock Tauri reads it: a
+ ; passive upgrade runs the previous uninstaller from PageLeaveReinstall, and
+ ; that deletes UNINSTKEY. Read any later, the name is gone, so a renamed main
+ ; binary (jan.exe -> Jan-Desktop.exe in 0.8.5) leaves every shortcut pointing
+ ; at the deleted exe.
+ ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"
FunctionEnd
@@ -958,7 +965,6 @@ Section Install
!endif
; Remove old main binary if it doesn't match new main binary name
- ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"
${If} $OldMainBinaryName != ""
${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe"
Delete "$INSTDIR\$OldMainBinaryName"
diff --git a/src-tauri/tests/windows_installer_resources.rs b/src-tauri/tests/windows_installer_resources.rs
index 2e58c1a41..37356be2c 100644
--- a/src-tauri/tests/windows_installer_resources.rs
+++ b/src-tauri/tests/windows_installer_resources.rs
@@ -15,6 +15,65 @@
use std::path::PathBuf;
+/// The body of `Function <name>` or `Section <name>` up to its terminator.
+///
+/// Located by byte search rather than by summing line lengths: a Windows
+/// checkout has CRLF endings, which `lines()` strips without saying how many
+/// bytes it dropped.
+fn nsis_block<'a>(template: &'a str, opener: &str, end: &str) -> &'a str {
+ let offset = template
+ .match_indices(opener)
+ .map(|(i, _)| i)
+ .find(|&i| {
+ let at_line_start = i == 0 || template.as_bytes()[i - 1] == b'\n';
+ let after = &template[i + opener.len()..];
+ at_line_start && after.trim_start_matches([' ', '\t']).starts_with(['\r', '\n'])
+ })
+ .unwrap_or_else(|| panic!("`{opener}` not found in the NSIS template"));
+ let rest = &template[offset..];
+ let stop = rest
+ .find(end)
+ .unwrap_or_else(|| panic!("`{opener}` has no `{end}`"));
+ &rest[..stop]
+}
+
+/// The shortcut retarget on a main-binary rename (`jan.exe` -> `Jan-Desktop.exe`
+/// in 0.8.5, #9125) needs the previous name from the uninstall key. A passive
+/// upgrade runs the old uninstaller from `PageLeaveReinstall`, which deletes that
+/// key before `Section Install` runs, so the name has to be captured in
+/// `.onInit`, while the key still exists. Reading it in `Section Install` finds
+/// nothing and leaves every shortcut pointing at the deleted exe.
+#[test]
+fn the_previous_main_binary_name_is_read_before_the_old_uninstaller_runs() {
+ let template = repo_file("tauri.bundle.windows.nsis.template");
+ let read = "ReadRegStr $OldMainBinaryName SHCTX \"${UNINSTKEY}\" \"MainBinaryName\"";
+
+ let on_init = nsis_block(&template, "Function .onInit", "FunctionEnd");
+ let read_at = on_init
+ .find(read)
+ .expect("`.onInit` must read MainBinaryName into $OldMainBinaryName");
+ // SHCTX names a hive only once MULTIUSER_INIT has picked the install mode
+ // (INSTALLMODE "both"); read before it, the lookup can hit the wrong hive.
+ let context_at = on_init
+ .find("!insertmacro MULTIUSER_INIT")
+ .expect("`.onInit` no longer calls MULTIUSER_INIT; re-check where SHCTX is set");
+ assert!(
+ read_at > context_at,
+ "`.onInit` must read MainBinaryName after MULTIUSER_INIT sets SHCTX"
+ );
+
+ let install = nsis_block(&template, "Section Install", "SectionEnd");
+ assert!(
+ !install.contains("ReadRegStr $OldMainBinaryName"),
+ "`Section Install` must not re-read MainBinaryName: by then a passive \
+ upgrade has run the old uninstaller, which deleted the key"
+ );
+ assert!(
+ install.contains("WriteRegStr SHCTX \"${UNINSTKEY}\" \"MainBinaryName\""),
+ "`Section Install` must still record MainBinaryName for the next update"
+ );
+}
+
fn repo_file(rel: &str) -> String {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(rel);
std::fs::read_to_string(&path)