Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(scripts): Windows installer, macOS portability fixes
Akarshan Biswas34c3faad376d
diff --git a/scripts/install-jan-agent.ps1 b/scripts/install-jan-agent.ps1new file mode 100644index 000000000..47afd7cb5--- /dev/null+++ b/scripts/install-jan-agent.ps1@@ -0,0 +1,179 @@+#Requires -Version 5.1+<#+.SYNOPSIS+Installs the `jan` agent CLI on Windows: either a published build from+delta.jan.ai (default) or one compiled from this checkout (-Source).++.DESCRIPTION+The PowerShell counterpart of install-jan-agent.sh. Downloaded builds+self-update via `jan update`; -Source builds do not, because the update+channel is embedded only by the nightly CI.++.EXAMPLE+.\scripts\install-jan-agent.ps1+.EXAMPLE+.\scripts\install-jan-agent.ps1 -Version 0.8.4-6 -AddToPath+.EXAMPLE+.\scripts\install-jan-agent.ps1 -Source+#>+[CmdletBinding()]+param(+ # Install directory. Defaults to $env:JAN_INSTALL_DIR, else a per-user+ # location that needs no elevation.+ [string]$Dir,+ [string]$Channel = 'agent-nightly',+ [string]$Version = '',+ [switch]$Source,+ # Append the install directory to the user PATH (persisted, not just this session).+ [switch]$AddToPath+)++$ErrorActionPreference = 'Stop'+# Speeds up Invoke-WebRequest on PowerShell 5.1 by orders of magnitude.+$ProgressPreference = 'SilentlyContinue'++$BinaryName = 'jan.exe'+$PlatformKey = 'windows-x86_64'+$RepoRoot = Split-Path -Parent (Split-Path -Parent $PSCommandPath)++if (-not $Dir) {+ if ($env:JAN_INSTALL_DIR) {+ $Dir = $env:JAN_INSTALL_DIR+ } else {+ $Dir = Join-Path $env:LOCALAPPDATA 'Programs\Jan'+ }+}++if ([Environment]::Is64BitOperatingSystem -eq $false) {+ throw 'no published build for 32-bit Windows; use -Source'+}+if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') {+ Write-Warning 'no native ARM64 build is published; the x86_64 build runs under emulation'+}++# PowerShell 5.1 defaults to TLS 1.0, which delta.jan.ai rejects.+if ([Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') {+ [Net.ServicePointManager]::SecurityProtocol =+ [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+}++function Install-Binary {+ param([Parameter(Mandatory)][string]$Source, [string]$Label)++ New-Item -ItemType Directory -Force -Path $Dir | Out-Null+ $dest = Join-Path $Dir $BinaryName++ # A running executable cannot be overwritten, but it can be renamed; the+ # stale copy is removed on the next install.+ $backup = "$dest.old"+ if (Test-Path -LiteralPath $backup) {+ Remove-Item -LiteralPath $backup -Force -ErrorAction SilentlyContinue+ }+ if (Test-Path -LiteralPath $dest) {+ try {+ Remove-Item -LiteralPath $dest -Force+ } catch {+ Move-Item -LiteralPath $dest -Destination $backup -Force+ Write-Warning "$BinaryName was in use; the previous copy is at $backup"+ }+ }+ Copy-Item -LiteralPath $Source -Destination $dest -Force++ if ($Label) {+ Write-Host "installed $dest ($Label)"+ } else {+ Write-Host "installed $dest"+ }++ $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')+ $onPath = ($env:Path -split ';') -contains $Dir+ if ($AddToPath) {+ if (($userPath -split ';') -notcontains $Dir) {+ $updated = if ([string]::IsNullOrEmpty($userPath)) { $Dir } else { "$userPath;$Dir" }+ [Environment]::SetEnvironmentVariable('Path', $updated, 'User')+ Write-Host "added $Dir to your user PATH; open a new terminal to pick it up"+ } else {+ Write-Host "$Dir is already on your user PATH"+ }+ } elseif (-not $onPath) {+ Write-Host "note: $Dir is not on your PATH; re-run with -AddToPath or add it yourself"+ }+}++function Install-FromSource {+ if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {+ throw 'cargo not found; install Rust first'+ }+ Write-Host "building the CLI from $RepoRoot (release)"+ Push-Location (Join-Path $RepoRoot 'src-tauri')+ try {+ # The CLI and the desktop app are mutually exclusive feature configs, so+ # the default features must stay off.+ cargo build --no-default-features --features cli --bin jan --release+ if ($LASTEXITCODE -ne 0) { throw "cargo build failed with exit code $LASTEXITCODE" }+ } finally {+ Pop-Location+ }+ $built = Join-Path $RepoRoot "src-tauri\target\release\$BinaryName"+ if (-not (Test-Path -LiteralPath $built)) { throw "expected a binary at $built" }+ Install-Binary -Source $built+ Write-Host 'note: builds from source have no update channel embedded, so `jan update` is a no-op'+}++function Install-Published {+ $base = "https://delta.jan.ai/$Channel"+ $url = ''+ $expected = ''+ $resolved = $Version++ if ($resolved) {+ $url = "$base/jan-agent-$PlatformKey-$resolved.zip"+ } else {+ Write-Host "resolving the latest $Channel build"+ try {+ $manifest = Invoke-RestMethod -Uri "$base/manifest.json" -UseBasicParsing+ } catch {+ throw "cannot fetch $base/manifest.json : $($_.Exception.Message)"+ }+ $resolved = $manifest.version+ $entry = $manifest.platforms.$PlatformKey+ if (-not $entry -or -not $entry.url) {+ throw "the $Channel manifest has no build for $PlatformKey"+ }+ $url = $entry.url+ if ($entry.PSObject.Properties.Name -contains 'sha256') { $expected = $entry.sha256 }+ }++ $tmp = Join-Path ([IO.Path]::GetTempPath()) ("jan-agent-" + [Guid]::NewGuid().ToString('N'))+ New-Item -ItemType Directory -Force -Path $tmp | Out-Null+ try {+ $archive = Join-Path $tmp 'jan-agent.zip'+ Write-Host "downloading $resolved from $url"+ try {+ Invoke-WebRequest -Uri $url -OutFile $archive -UseBasicParsing+ } catch {+ throw "download failed: $url : $($_.Exception.Message)"+ }++ if ($expected) {+ $actual = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash+ if ($actual -ne $expected.ToUpperInvariant()) {+ throw "checksum mismatch: expected $expected, got $actual"+ }+ Write-Host 'sha256 verified'+ }++ Expand-Archive -LiteralPath $archive -DestinationPath $tmp -Force+ # Published zips keep jan.exe at the root; search anyway so a packaging+ # change cannot silently break this.+ $extracted = Get-ChildItem -Path $tmp -Recurse -File -Filter $BinaryName |+ Select-Object -First 1+ if (-not $extracted) { throw "no $BinaryName inside the archive" }++ Install-Binary -Source $extracted.FullName -Label "$Channel $resolved"+ } finally {+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue+ }+}++if ($Source) { Install-FromSource } else { Install-Published }diff --git a/scripts/install-jan-agent.sh b/scripts/install-jan-agent.shindex d2ea1d4cf..efd7d5f6e 100755--- a/scripts/install-jan-agent.sh+++ b/scripts/install-jan-agent.sh@@ -1,6 +1,8 @@#!/usr/bin/env bash-# Installs the `jan` agent CLI: either a published build from delta.jan.ai-# (default) or one compiled from this checkout (--source).+# Installs the `jan` agent CLI on Linux and macOS: either a published build+# from delta.jan.ai (default) or one compiled from this checkout (--source).+# Windows has install-jan-agent.ps1; this script also works from Git Bash,+# but only if `unzip` is available there.# Downloaded builds self-update via `jan update`; --source builds do not,# because the update channel is embedded only by the nightly CI.set -euo pipefail@@ -155,7 +157,8 @@ install_published() {fi# TMP_DIR is global: the EXIT trap fires outside this function's scope.- TMP_DIR="$(mktemp -d)"+ # BSD mktemp (macOS) needs an explicit template, unlike GNU's bare -d.+ TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/jan-agent.XXXXXX")"trap 'rm -rf "${TMP_DIR:-}"' EXITlocal tmp="$TMP_DIR"@@ -176,15 +179,18 @@ install_published() {fiif [ "$ARCHIVE_EXT" = "zip" ]; then- command -v unzip >/dev/null 2>&1 || die "unzip not found"+ command -v unzip >/dev/null 2>&1 || die "unzip not found; on Windows use scripts/install-jan-agent.ps1"unzip -qo "$archive" -d "$tmp"elsetar xzf "$archive" -C "$tmp"fi- # The Windows zip keeps the build-tree prefix, so search rather than assume.+ # Published archives keep the binary at the root, but tar and 7z package it+ # differently, so search by name rather than assuming a layout.+ # `head -1` rather than find's -quit, which is not in POSIX; the `|| true`+ # absorbs the SIGPIPE status that pipefail would otherwise treat as fatal.local extracted- extracted="$(find "$tmp" -type f -name "$BINARY_NAME" -print -quit)"+ extracted="$(find "$tmp" -type f -name "$BINARY_NAME" | head -1 || true)"[ -n "$extracted" ] || die "no $BINARY_NAME inside the archive"chmod +x "$extracted"install_binary "$extracted"diff --git a/src-tauri/src/core/cli/updater.rs b/src-tauri/src/core/cli/updater.rsindex 00db5a0b5..c1491e38f 100644--- a/src-tauri/src/core/cli/updater.rs+++ b/src-tauri/src/core/cli/updater.rs@@ -236,9 +236,9 @@ async fn download_to(url: &str, dest: &Path) -> Result<String, String> {Ok(hex::encode(hasher.finalize()))}-/// Extract the `jan` binary out of a release archive. Entry paths differ per-/// platform (the Windows zip keeps the build-tree prefix), so match on the-/// file name rather than the full path.+/// Extract the `jan` binary out of a release archive. Today every platform's+/// archive stores it at the root, but the packaging step differs per platform+/// (tar vs 7z), so match on the file name rather than the full path.fn extract_binary(archive: &Path, dest: &Path) -> Result<(), String> {let name = archive.file_name().unwrap_or_default().to_string_lossy();let mut out = File::create(dest).map_err(|e| format!("{}: {e}", dest.display()))?;@@ -512,6 +512,8 @@ mod tests {assert!(err.contains(BINARY_NAME), "{err}");}+ /// Published zips keep the binary at the root; tolerate a path prefix too,+ /// so a change to the packaging step can't silently break the updater.#[test]fn extracts_the_binary_from_a_zip_with_a_path_prefix() {let dir = tempfile::tempdir().unwrap();@@ -536,9 +538,26 @@ mod tests {fs::write(&bogus, b"<!DOCTYPE html><html>404</html>").unwrap();assert!(verify_executable(&bogus).is_err());- let good = dir.path().join("good");- fs::write(&good, b"\x7fELF\x02\x01").unwrap();- verify_executable(&good).unwrap();+ let truncated = dir.path().join("truncated");+ fs::write(&truncated, b"\x7f").unwrap();+ assert!(verify_executable(&truncated).is_err());+ }++ /// Leading bytes taken from the published 0.8.4-6 artifacts for each+ /// platform, so a header the real builds use can't be rejected.+ #[test]+ fn published_binaries_pass_the_magic_check() {+ let dir = tempfile::tempdir().unwrap();+ for (name, magic) in [+ ("linux", [0x7f, 0x45, 0x4c, 0x46]), // ELF+ ("windows", [0x4d, 0x5a, 0x90, 0x00]), // PE+ ("macos", [0xca, 0xfe, 0xba, 0xbe]), // Mach-O universal+ ("macos-thin", [0xcf, 0xfa, 0xed, 0xfe]),+ ] {+ let path = dir.path().join(name);+ fs::write(&path, magic).unwrap();+ verify_executable(&path).unwrap_or_else(|e| panic!("{name}: {e}"));+ }}#[test]