feat(app): update the app from the project's Gitea releases
- update.rs finds the newest app-v<version> release above the running version (v1 tags, drafts, prereleases, incomplete releases and files on another server are skipped), downloads Jarvis-Setup-<version>.exe into cache/updates checked against its .sha256, and hands it over. - update_install hashes the file again, stops what runs, starts the installer with /S /RUN as administrator and the window quits; a declined administrator prompt keeps the app with the services stopped. - New 업데이트 screen; the app checks once when the main screens open. - tauri.conf.json no longer sets its own version, so the program file carries the Cargo.toml version the update compares. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,8 +27,14 @@ struct Api {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn admin(state: tauri::State<'_, Api>, command: String, args: Option<Value>) -> Result<Value, String> {
|
||||
state.api.call(&command, args.unwrap_or(Value::Null)).await
|
||||
async fn admin(app: tauri::AppHandle, state: tauri::State<'_, Api>, command: String, args: Option<Value>) -> Result<Value, String> {
|
||||
let out = state.api.call(&command, args.unwrap_or(Value::Null)).await?;
|
||||
// An update's installer was started (what ran is stopped): quit so it can replace the app.
|
||||
if out["exit"] == Value::Bool(true) {
|
||||
state.phase.store(CLOSING, Ordering::SeqCst);
|
||||
app.exit(0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn arg(name: &str) -> Option<String> {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Jarvis",
|
||||
"version": "0.1.0",
|
||||
"identifier": "kr.jarvis.manager",
|
||||
"build": {
|
||||
"frontendDist": "../ui"
|
||||
|
||||
@@ -501,6 +501,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv
|
||||
| `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, leftover, other, action}` (Windows only, above) / install or remove it elevated (above), then its status; refused unless the services are stopped or failed, and `service_start` / `service_restart` are refused meanwhile |
|
||||
| `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it |
|
||||
| `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back |
|
||||
| `update_status` / `update_check` / `update_download` / `update_install` | updates (below): `{current, phase, latest, error, done, total}` / look for a newer release / download it in the background / stop what runs, start the installer and answer `{exit: true}`, on which the window quits without asking |
|
||||
|
||||
The invite link asks for: view channels, send messages, read history, add reactions, manage
|
||||
messages, manage channels, connect, speak, voice activity, and the slash command scope; never
|
||||
@@ -534,6 +535,9 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
address or words, interval in minutes, on/off, delete), the keep days, and the results (the
|
||||
newest 100, filtered by any target that has results, each with its time, title, link and the start of its text shown
|
||||
as plain text).
|
||||
- **업데이트**: the version here, the state, "다시 확인", "받기" (with its percentage) and "설치하고
|
||||
다시 시작", and the release's notes as plain text. The app checks once when the main screens open;
|
||||
a newer release renames the button "업데이트 (새 버전)" and says so once.
|
||||
- **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류
|
||||
복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days.
|
||||
|
||||
@@ -541,6 +545,30 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
the commands on 127.0.0.1; every command needs the random token it prints (`#token=` in the page
|
||||
URL), so other local programs cannot drive it.
|
||||
|
||||
## Updates (`app/src/update.rs`)
|
||||
|
||||
The app updates itself from the project's Gitea releases
|
||||
(`https://git.tkrmagid.kr/api/v1/repos/tkrmagid/javis_bot/releases`; `JARVIS_UPDATE_SOURCE` points a
|
||||
test at another server). A release of this app is tagged `app-v<version>` and carries the two files
|
||||
`installer.sh` writes, `Jarvis-Setup-<version>.exe` and its `.sha256`; publishing one is uploading
|
||||
both to a release with that tag. The repository's other releases (v1's `v1.x`) are skipped.
|
||||
|
||||
- **Check**: the release list (50 newest); drafts, prereleases, other tags, releases without both
|
||||
files, and files on another server than the list are skipped; the newest version above the
|
||||
app's own (dotted numbers, "0.2" equals "0.2.0") is offered. HTTPS only (plain HTTP only to
|
||||
127.0.0.1 or localhost). A failure keeps its reason for the screen and the `app` log tab.
|
||||
- **Download**: the `.sha256` first (64 hex digits, for that file name), then the installer into the
|
||||
data folder's `cache/updates` through the install's resumable, checked download; a mismatch
|
||||
deletes it and fails. Once it is there, earlier installers in that folder are removed. Checking
|
||||
again keeps a downloaded release ready.
|
||||
- **Install**: the file is hashed again, then what runs is stopped as when the window closes (a
|
||||
failure stops here), then the installer starts with `/S /RUN` as administrator (Windows asks)
|
||||
without waiting, and the app quits. The installer waits for it to close, replaces it and starts
|
||||
it again (above, "Installer"). Declining the administrator question keeps the app open with the
|
||||
services stopped and says so.
|
||||
- The app's version is the one in `app/Cargo.toml` and `app/shell/Cargo.toml` (kept equal; the
|
||||
program file's version comes from the latter, `tauri.conf.json` sets none).
|
||||
|
||||
## Window and Windows build (`app/shell/`)
|
||||
|
||||
- `jarvis.exe` (crate `jarvis-shell`, Tauri 2 on the WebView2 Windows already has) opens one window
|
||||
@@ -618,6 +646,13 @@ a stop right after a background start running no launch at all, and the next sta
|
||||
closing the app (the controller's shutdown after a failed stop: clean-up failing keeps it failed,
|
||||
succeeding stops it; an install in progress cancelled and waited for); command output that is not
|
||||
UTF-8 read on to the end; the window data folder (data folder, or a scratch folder removed later);
|
||||
updates (the newest release of this app picked past v1's, prerelease, incomplete and other-server
|
||||
releases; the checksum file read for its own file only; a fake Gitea on 127.0.0.1 found, downloaded,
|
||||
checked and handed over with earlier installers removed, a ready download kept by a new check, a
|
||||
file changed after the download refused, a wrong checksum never offered, an unreachable or plain
|
||||
HTTP server failing with a reason; the install command refused before a download, keeping the app
|
||||
when the administrator question is declined, and starting the installer after stopping what runs;
|
||||
one version in both Cargo.toml files and none in tauri.conf.json);
|
||||
the TTS speed reaching the worker's arguments; features and MCP servers (read and refused with
|
||||
the key, the feature tools named as the brain names them, only enabled servers in the brain's
|
||||
settings without values, stored values passed for enabled servers only, values of removed servers
|
||||
@@ -674,7 +709,9 @@ second task) refused while one runs, also after it failed; removing a driver tha
|
||||
there is nothing to remove. The installer (by hand on a Windows VM): installing into a folder that
|
||||
holds other files and uninstalling keeps them; a driver removal that fails stops the uninstall with
|
||||
the files and entry kept, and nothing to remove lets it finish; with no WebView2 and its installer
|
||||
failing nothing is installed or started; with the lock held the app shows its message and exits
|
||||
failing nothing is installed or started; an update end to end (0.1.0 installed, a release server
|
||||
on 127.0.0.1 offering `app-v0.2.0`: the screen finds it at the start, downloads it, and "설치하고
|
||||
다시 시작" leaves 0.2.0 installed and running); with the lock held the app shows its message and exits
|
||||
after OK, and starts normally once released; `/S /RUN` (fresh, and over a running app that closes)
|
||||
and the finish page's "Jarvis 실행" start the app's window; a silent install while the uninstaller's
|
||||
window is open, and a silent uninstall while the installer's is, stop with code 5 and change
|
||||
|
||||
@@ -25,6 +25,9 @@ pub struct AdminApi {
|
||||
hub: Arc<LogHub>,
|
||||
/// The virtual monitor's driver is being installed or removed: no service start meanwhile.
|
||||
driver_busy: Mutex<bool>,
|
||||
updater: Mutex<Option<Arc<crate::update::Updater>>>,
|
||||
/// Starts a downloaded installer (`update::launch_installer`; a fake in tests).
|
||||
launcher: fn(&Path) -> Result<(), String>,
|
||||
}
|
||||
|
||||
fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a Value, String> {
|
||||
@@ -53,7 +56,8 @@ impl AdminApi {
|
||||
hub.set_secrets(Secrets::new(&d.secrets_file()).values());
|
||||
}
|
||||
Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None),
|
||||
syncer: Mutex::new(None), hub, driver_busy: Mutex::new(false) }
|
||||
syncer: Mutex::new(None), hub, driver_busy: Mutex::new(false), updater: Mutex::new(None),
|
||||
launcher: crate::update::launch_installer }
|
||||
}
|
||||
|
||||
fn dir(&self) -> Result<DataDir, String> {
|
||||
@@ -129,6 +133,24 @@ impl AdminApi {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Updates for this data folder (installers go to its `cache/updates`).
|
||||
fn updater(&self) -> Result<Arc<crate::update::Updater>, String> {
|
||||
let dir = self.dir()?;
|
||||
let mut u = self.updater.lock().unwrap();
|
||||
Ok(u.get_or_insert_with(|| crate::update::Updater::new(crate::update::source(), APP_VERSION,
|
||||
dir.path().join("cache").join("updates"))).clone())
|
||||
}
|
||||
|
||||
/// Install the downloaded update: stop what runs (as when the window closes), then start the
|
||||
/// installer, which waits for this app to close. `{"exit": true}`: the shell quits now.
|
||||
async fn install_update(&self) -> Result<Value, String> {
|
||||
let path = self.updater()?.ready_installer()?;
|
||||
self.shutdown().await.map_err(|e| format!("실행 중인 것을 멈추지 못해 업데이트를 설치하지 않았습니다: {e}"))?;
|
||||
(self.launcher)(&path).map_err(|e| format!("{e}. 서비스는 정지된 상태입니다"))?;
|
||||
crate::info_log!("app", "update installer started: the app closes");
|
||||
Ok(json!({"exit": true}))
|
||||
}
|
||||
|
||||
fn controller(&self) -> Result<Arc<Controller>, String> {
|
||||
let dir = self.dir()?;
|
||||
let mut c = self.controller.lock().unwrap();
|
||||
@@ -208,6 +230,7 @@ impl AdminApi {
|
||||
*self.dir.lock().unwrap() = Some(dir);
|
||||
*self.controller.lock().unwrap() = None;
|
||||
*self.installer.lock().unwrap() = None;
|
||||
*self.updater.lock().unwrap() = None;
|
||||
crate::info_log!("admin", "data folder chosen");
|
||||
Ok(json!({"dataDir": path.to_string_lossy()}))
|
||||
}
|
||||
@@ -351,6 +374,14 @@ impl AdminApi {
|
||||
}
|
||||
"service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})),
|
||||
"dashboard" => Ok(self.controller()?.snapshot().await),
|
||||
"update_status" => Ok(self.updater()?.status()),
|
||||
"update_check" => self.updater()?.check().await,
|
||||
"update_download" => {
|
||||
let u = self.updater()?;
|
||||
u.download()?;
|
||||
Ok(u.status())
|
||||
}
|
||||
"update_install" => self.install_update().await,
|
||||
"logs_query" => {
|
||||
let tab = args.get("tab").and_then(Value::as_str).filter(|t| !t.is_empty() && *t != "all");
|
||||
let level = level_of(args.get("level").and_then(Value::as_str).unwrap_or("debug"));
|
||||
@@ -387,7 +418,7 @@ mod tests {
|
||||
let base = temp_dir(tag);
|
||||
let loc = base.join("cfg").join("location.json");
|
||||
(AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None),
|
||||
hub: LogHub::new(None), driver_busy: Mutex::new(false) },
|
||||
hub: LogHub::new(None), driver_busy: Mutex::new(false), updater: Mutex::new(None), launcher: refused_launch },
|
||||
base)
|
||||
}
|
||||
|
||||
@@ -524,6 +555,39 @@ mod tests {
|
||||
assert!(a.call("service_stop", json!({})).await.is_err());
|
||||
}
|
||||
|
||||
static LAUNCHED: Mutex<Option<PathBuf>> = Mutex::new(None);
|
||||
fn fake_launch(p: &Path) -> Result<(), String> {
|
||||
*LAUNCHED.lock().unwrap() = Some(p.to_path_buf());
|
||||
Ok(())
|
||||
}
|
||||
fn refused_launch(_: &Path) -> Result<(), String> {
|
||||
Err("관리자 권한을 받지 못해 업데이트를 설치하지 않았습니다".into())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_update_is_installed_only_once_downloaded_and_checked_after_stopping_what_runs() {
|
||||
let (mut a, base) = api("apiupd");
|
||||
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
|
||||
a.call("dashboard", json!({})).await.unwrap();
|
||||
assert!(a.call("update_install", json!({})).await.unwrap_err().contains("먼저 받아"));
|
||||
let installer = b"setup".to_vec();
|
||||
let sum = format!("{:x}", <sha2::Sha256 as sha2::Digest>::digest(&installer));
|
||||
let src = format!("{}/releases", crate::update::tests::gitea("9.0.0", installer, sum).await);
|
||||
*a.updater.lock().unwrap() = Some(crate::update::Updater::new(src, APP_VERSION, base.join("d/cache/updates")));
|
||||
assert_eq!(a.call("update_check", json!({})).await.unwrap()["latest"]["version"], json!("9.0.0"));
|
||||
a.call("update_download", json!({})).await.unwrap();
|
||||
for _ in 0..200 {
|
||||
if a.call("update_status", json!({})).await.unwrap()["phase"] != json!("downloading") { break }
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
a.launcher = refused_launch;
|
||||
assert!(a.call("update_install", json!({})).await.unwrap_err().contains("서비스는 정지된 상태"));
|
||||
a.launcher = fake_launch;
|
||||
assert_eq!(a.call("update_install", json!({})).await.unwrap(), json!({"exit": true}));
|
||||
assert_eq!(LAUNCHED.lock().unwrap().clone(), Some(base.join("d/cache/updates/Jarvis-Setup-9.0.0.exe")));
|
||||
assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_the_app_while_starting_waits_until_everything_is_stopped() {
|
||||
let (a, base) = api("api5");
|
||||
|
||||
@@ -33,6 +33,7 @@ pub mod setup_lock;
|
||||
pub mod speakers;
|
||||
pub mod strata;
|
||||
pub mod system;
|
||||
pub mod update;
|
||||
pub mod vdisplay;
|
||||
pub mod worker_client;
|
||||
pub mod worker_process;
|
||||
|
||||
438
app/src/update.rs
Normal file
438
app/src/update.rs
Normal file
@@ -0,0 +1,438 @@
|
||||
//! App updates (admin.spec.md, "Updates"): the app looks for a newer release on the project's
|
||||
//! Gitea, downloads its installer into the data folder checked against the release's SHA-256, and
|
||||
//! on request stops what runs and starts the installer silently (`/S /RUN`), which waits for the
|
||||
//! app to close, replaces it and starts it again.
|
||||
//!
|
||||
//! A release of this app is tagged `app-v<version>` and carries `Jarvis-Setup-<version>.exe` and
|
||||
//! `Jarvis-Setup-<version>.exe.sha256` (what `app/shell/installer.sh` writes). Other releases of the
|
||||
//! repository (v1's `v1.x` tags) are not this app's and are skipped.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The project's releases (Gitea API, newest first).
|
||||
pub const SOURCE: &str = "https://git.tkrmagid.kr/api/v1/repos/tkrmagid/javis_bot/releases";
|
||||
pub const TAG_PREFIX: &str = "app-v";
|
||||
|
||||
/// Where to look: `JARVIS_UPDATE_SOURCE` when set (a test server), else `SOURCE`.
|
||||
pub fn source() -> String {
|
||||
std::env::var("JARVIS_UPDATE_SOURCE").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| SOURCE.into())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Release {
|
||||
pub version: String,
|
||||
pub notes: String,
|
||||
pub file: String,
|
||||
pub size: u64,
|
||||
#[serde(skip)]
|
||||
pub installer_url: String,
|
||||
#[serde(skip)]
|
||||
pub checksum_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Phase {
|
||||
Idle,
|
||||
Checking,
|
||||
UpToDate,
|
||||
Available,
|
||||
Downloading,
|
||||
Ready,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Dotted numbers ("0.2.0"), padded to four parts so "1.0" equals "1.0.0"; anything else is `None`.
|
||||
fn version(s: &str) -> Option<[u64; 4]> {
|
||||
let parts: Vec<u64> = s.split('.').map(|p| p.parse().ok()).collect::<Option<_>>()?;
|
||||
if parts.is_empty() || parts.len() > 4 {
|
||||
return None;
|
||||
}
|
||||
let mut v = [0; 4];
|
||||
v[..parts.len()].copy_from_slice(&parts);
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// "https://host[:port]" of a URL: downloads come only from where the release list came from.
|
||||
fn origin(url: &str) -> Option<&str> {
|
||||
let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"))?;
|
||||
Some(&url[..url.len() - rest.len() + rest.find('/').unwrap_or(rest.len())])
|
||||
}
|
||||
|
||||
/// HTTPS only; plain HTTP only to this PC (a test server).
|
||||
fn allowed(url: &str) -> bool {
|
||||
url.starts_with("https://") || url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:")
|
||||
}
|
||||
|
||||
/// The newest release of this app above `current` in a Gitea release list, if any. Drafts,
|
||||
/// prereleases, other tags and releases without both assets on `source`'s origin are skipped.
|
||||
pub fn pick(list: &Value, current: &str, source: &str) -> Result<Option<Release>, String> {
|
||||
let list = list.as_array().ok_or("릴리스 목록을 읽지 못했습니다")?;
|
||||
let current = version(current).ok_or("현재 버전을 읽지 못했습니다")?;
|
||||
let home = origin(source);
|
||||
let mut best: Option<([u64; 4], Release)> = None;
|
||||
for r in list {
|
||||
if r["draft"] == json!(true) || r["prerelease"] == json!(true) {
|
||||
continue;
|
||||
}
|
||||
let Some(v) = r["tag_name"].as_str().and_then(|t| t.strip_prefix(TAG_PREFIX)) else { continue };
|
||||
let Some(parsed) = version(v) else { continue };
|
||||
if parsed <= current || best.as_ref().is_some_and(|(b, _)| parsed <= *b) {
|
||||
continue;
|
||||
}
|
||||
let file = format!("Jarvis-Setup-{v}.exe");
|
||||
let asset = |name: &str| r["assets"].as_array()?.iter().find(|a| a["name"].as_str() == Some(name)).cloned();
|
||||
let (Some(exe), Some(sum)) = (asset(&file), asset(&format!("{file}.sha256"))) else { continue };
|
||||
let url = |a: &Value| a["browser_download_url"].as_str().map(str::to_owned)
|
||||
.filter(|u| allowed(u) && origin(u).is_some() && origin(u) == home);
|
||||
let (Some(installer_url), Some(checksum_url)) = (url(&exe), url(&sum)) else { continue };
|
||||
best = Some((parsed, Release { version: v.into(), notes: r["body"].as_str().unwrap_or("").into(), file,
|
||||
size: exe["size"].as_u64().unwrap_or(0), installer_url, checksum_url }));
|
||||
}
|
||||
Ok(best.map(|(_, r)| r))
|
||||
}
|
||||
|
||||
/// The SHA-256 in a `.sha256` file ("<hex> <file>"): 64 hex digits, for `file` when it names one.
|
||||
pub fn checksum(text: &str, file: &str) -> Result<String, String> {
|
||||
let mut words = text.split_whitespace();
|
||||
let hex = words.next().unwrap_or("").to_ascii_lowercase();
|
||||
let named = words.next().map(|n| n.trim_start_matches('*'));
|
||||
if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) || named.is_some_and(|n| n != file) {
|
||||
return Err("릴리스의 SHA-256 파일이 올바르지 않습니다".into());
|
||||
}
|
||||
Ok(hex)
|
||||
}
|
||||
|
||||
struct State {
|
||||
phase: Phase,
|
||||
latest: Option<Release>,
|
||||
error: Option<String>,
|
||||
done: u64,
|
||||
total: Option<u64>,
|
||||
sha256: Option<String>,
|
||||
}
|
||||
|
||||
/// The update state for the screens: checks, the download in the background, and the ready file.
|
||||
pub struct Updater {
|
||||
source: String,
|
||||
current: String,
|
||||
dir: PathBuf,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
impl Updater {
|
||||
/// `dir`: where installers are downloaded (the data folder's `cache/updates`).
|
||||
pub fn new(source: String, current: &str, dir: PathBuf) -> Arc<Self> {
|
||||
Arc::new(Self { source, current: current.into(), dir, state: Mutex::new(State {
|
||||
phase: Phase::Idle, latest: None, error: None, done: 0, total: None, sha256: None }) })
|
||||
}
|
||||
|
||||
pub fn status(&self) -> Value {
|
||||
let s = self.state.lock().unwrap();
|
||||
json!({"current": self.current, "phase": s.phase, "latest": s.latest, "error": s.error,
|
||||
"done": s.done, "total": s.total})
|
||||
}
|
||||
|
||||
fn client() -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).build().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
async fn get_text(url: &str) -> Result<String, String> {
|
||||
let r = Self::client()?.get(url).header("accept", "application/json").send().await
|
||||
.map_err(|e| format!("업데이트 서버에 연결하지 못했습니다: {e}"))?;
|
||||
if !r.status().is_success() {
|
||||
return Err(format!("업데이트 서버가 HTTP {}로 답했습니다", r.status()));
|
||||
}
|
||||
r.text().await.map_err(|e| format!("업데이트 정보를 받지 못했습니다: {e}"))
|
||||
}
|
||||
|
||||
fn fail(&self, e: String) -> String {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
(s.phase, s.error) = (Phase::Failed, Some(e.clone()));
|
||||
crate::warn_log!("app", "update: {e}");
|
||||
e
|
||||
}
|
||||
|
||||
/// Look for a newer release; not while downloading.
|
||||
pub async fn check(&self) -> Result<Value, String> {
|
||||
let was = {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
if matches!(s.phase, Phase::Checking | Phase::Downloading) {
|
||||
return Ok(json!({"current": self.current, "phase": s.phase, "latest": s.latest}));
|
||||
}
|
||||
std::mem::replace(&mut s.phase, Phase::Checking)
|
||||
};
|
||||
self.state.lock().unwrap().error = None;
|
||||
if !allowed(&self.source) {
|
||||
return Err(self.fail(format!("업데이트 주소는 https여야 합니다: {}", self.source)));
|
||||
}
|
||||
let url = format!("{}?limit=50", self.source);
|
||||
let found = match Self::get_text(&url).await
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).map_err(|_| "릴리스 목록을 읽지 못했습니다".into()))
|
||||
.and_then(|v| pick(&v, &self.current, &self.source)) {
|
||||
Ok(f) => f,
|
||||
Err(e) => return Err(self.fail(e)),
|
||||
};
|
||||
let mut s = self.state.lock().unwrap();
|
||||
// The release already downloaded stays ready.
|
||||
if was == Phase::Ready && found.is_some() && s.latest == found {
|
||||
s.phase = Phase::Ready;
|
||||
} else {
|
||||
s.phase = if found.is_some() { Phase::Available } else { Phase::UpToDate };
|
||||
(s.done, s.total, s.sha256) = (0, None, None);
|
||||
}
|
||||
crate::info_log!("app", "update check: {}", found.as_ref().map_or("up to date".into(), |r| format!("{} available", r.version)));
|
||||
s.latest = found;
|
||||
Ok(json!({"current": self.current, "phase": s.phase, "latest": s.latest}))
|
||||
}
|
||||
|
||||
/// Download the release found by `check` in the background (resumed where an earlier try stopped).
|
||||
pub fn download(self: &Arc<Self>) -> Result<(), String> {
|
||||
let release = {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
let release = match (s.phase, &s.latest) {
|
||||
(Phase::Available | Phase::Failed, Some(r)) => r.clone(),
|
||||
(Phase::Downloading | Phase::Ready, Some(_)) => return Ok(()),
|
||||
_ => return Err("먼저 새 버전을 확인해 주세요".into()),
|
||||
};
|
||||
(s.phase, s.error, s.done, s.total) = (Phase::Downloading, None, 0, Some(release.size));
|
||||
release
|
||||
};
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let dest = me.dir.join(&release.file);
|
||||
let got = async {
|
||||
let sha = checksum(&Self::get_text(&release.checksum_url).await?, &release.file)?;
|
||||
std::fs::create_dir_all(&me.dir).map_err(|e| format!("업데이트 폴더를 만들지 못했습니다: {e}"))?;
|
||||
let never = AtomicBool::new(false);
|
||||
let progress = |done: u64, total: Option<u64>| {
|
||||
let mut s = me.state.lock().unwrap();
|
||||
(s.done, s.total) = (done, total.or(s.total));
|
||||
};
|
||||
crate::download::download(&release.installer_url, &dest, &sha, &progress, &never).await
|
||||
.map_err(|e| format!("설치 파일을 받지 못했습니다: {e}"))?;
|
||||
Ok::<_, String>(sha)
|
||||
}.await;
|
||||
match got {
|
||||
Ok(sha) => {
|
||||
// Earlier installers and broken parts go; this one stays until it is installed.
|
||||
let keep = [release.file.clone(), format!("{}.part", release.file)];
|
||||
for e in std::fs::read_dir(&me.dir).into_iter().flatten().flatten() {
|
||||
if !keep.iter().any(|k| e.file_name() == k.as_str()) {
|
||||
let _ = std::fs::remove_file(e.path());
|
||||
}
|
||||
}
|
||||
let mut s = me.state.lock().unwrap();
|
||||
(s.phase, s.sha256) = (Phase::Ready, Some(sha));
|
||||
crate::info_log!("app", "update {} downloaded", release.version);
|
||||
}
|
||||
Err(e) => { me.fail(e); }
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The downloaded installer, checked again right before it is started.
|
||||
pub fn ready_installer(&self) -> Result<PathBuf, String> {
|
||||
let s = self.state.lock().unwrap();
|
||||
let (Phase::Ready, Some(r), Some(sha)) = (s.phase, &s.latest, &s.sha256) else {
|
||||
return Err("설치할 업데이트를 먼저 받아 주세요".into());
|
||||
};
|
||||
let path = self.dir.join(&r.file);
|
||||
if crate::download::sha256_file(&path).ok().as_deref() != Some(sha.as_str()) {
|
||||
return Err("받은 설치 파일이 바뀌었습니다. 다시 받아 주세요".into());
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the installer silently, as administrator (Windows asks), without waiting: it waits for
|
||||
/// this app to close, installs, and starts the app again.
|
||||
#[cfg(windows)]
|
||||
pub fn launch_installer(path: &Path) -> Result<(), String> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Foundation::{GetLastError, ERROR_CANCELLED};
|
||||
use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
|
||||
let wide = |s: &std::ffi::OsStr| s.encode_wide().chain(Some(0)).collect::<Vec<u16>>();
|
||||
let (verb, file, params) = (wide("runas".as_ref()), wide(path.as_os_str()), wide("/S /RUN".as_ref()));
|
||||
// SAFETY: SHELLEXECUTEINFOW is plain data; all zero is its documented empty state.
|
||||
let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() };
|
||||
info.cbSize = std::mem::size_of::<SHELLEXECUTEINFOW>() as u32;
|
||||
info.lpVerb = verb.as_ptr();
|
||||
info.lpFile = file.as_ptr();
|
||||
info.lpParameters = params.as_ptr();
|
||||
info.nShow = SW_SHOWNORMAL;
|
||||
// SAFETY: `info` is filled as documented and its strings live through the call; no process
|
||||
// handle is asked for.
|
||||
if unsafe { ShellExecuteExW(&mut info) } == 0 {
|
||||
let e = unsafe { GetLastError() };
|
||||
return Err(if e == ERROR_CANCELLED { "관리자 권한을 받지 못해 업데이트를 설치하지 않았습니다".into() }
|
||||
else { format!("설치 파일을 실행하지 못했습니다 ({e})") });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn launch_installer(_path: &Path) -> Result<(), String> {
|
||||
Err("업데이트 설치는 Windows에서만 됩니다".into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::datadir::temp_dir;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
fn both(v: &str) -> Vec<String> {
|
||||
vec![format!("Jarvis-Setup-{v}.exe"), format!("Jarvis-Setup-{v}.exe.sha256")]
|
||||
}
|
||||
|
||||
fn rel(tag: &str, base: &str, files: &[String]) -> Value {
|
||||
json!({"tag_name": tag, "draft": false, "prerelease": false, "body": format!("notes {tag}"),
|
||||
"assets": files.iter().map(|f| json!({"name": f, "size": 10,
|
||||
"browser_download_url": format!("{base}/download/{tag}/{f}")})).collect::<Vec<_>>()})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_release_of_this_app_above_the_current_version_is_picked() {
|
||||
let src = "https://git.example/api/v1/repos/o/r/releases";
|
||||
let base = "https://git.example/o/r/releases";
|
||||
let mut pre = rel("app-v0.4.0", base, &both("0.4.0"));
|
||||
pre["prerelease"] = json!(true);
|
||||
let list = json!([
|
||||
rel("v1.10.0", base, &[]), // v1's release
|
||||
rel("app-v0.3.0", base, &both("0.3.0")[..1]), // no checksum
|
||||
pre,
|
||||
rel("app-v0.2.1", "https://elsewhere.example/o/r", &both("0.2.1")), // another server
|
||||
rel("app-v0.2.0", base, &both("0.2.0")),
|
||||
rel("app-v0.1.5", base, &both("0.1.5")),
|
||||
]);
|
||||
let r = pick(&list, "0.1.0", src).unwrap().unwrap();
|
||||
assert_eq!((r.version.as_str(), r.file.as_str(), r.notes.as_str()), ("0.2.0", "Jarvis-Setup-0.2.0.exe", "notes app-v0.2.0"));
|
||||
assert_eq!(r.installer_url, format!("{base}/download/app-v0.2.0/Jarvis-Setup-0.2.0.exe"));
|
||||
assert_eq!(pick(&list, "0.2.0", src).unwrap(), None, "nothing newer");
|
||||
assert_eq!(pick(&list, "0.2", src).unwrap(), None, "0.2 is 0.2.0");
|
||||
assert_eq!(pick(&json!([]), "0.1.0", src).unwrap(), None);
|
||||
assert!(pick(&json!({"message": "not found"}), "0.1.0", src).is_err());
|
||||
// Plain http only to this PC.
|
||||
let http = rel("app-v0.2.0", "http://git.example/o/r", &both("0.2.0"));
|
||||
assert_eq!(pick(&json!([http]), "0.1.0", "http://git.example/api").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_checksum_file_gives_its_hash_for_the_right_file_only() {
|
||||
let h = "AB".repeat(32);
|
||||
assert_eq!(checksum(&format!("{h} Jarvis-Setup-0.2.0.exe\n"), "Jarvis-Setup-0.2.0.exe").unwrap(), h.to_lowercase());
|
||||
assert_eq!(checksum(&format!("{h} *Jarvis-Setup-0.2.0.exe"), "Jarvis-Setup-0.2.0.exe").unwrap(), h.to_lowercase());
|
||||
assert_eq!(checksum(&h, "x.exe").unwrap(), h.to_lowercase());
|
||||
assert!(checksum(&format!("{h} other.exe"), "Jarvis-Setup-0.2.0.exe").is_err());
|
||||
assert!(checksum("abc Jarvis-Setup-0.2.0.exe", "Jarvis-Setup-0.2.0.exe").is_err());
|
||||
assert!(checksum("", "x").is_err());
|
||||
}
|
||||
|
||||
/// A fake Gitea on this PC: the release list and the two assets of `app-v<version>`.
|
||||
pub(crate) async fn gitea(version: &str, installer: Vec<u8>, sum: String) -> String {
|
||||
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}", l.local_addr().unwrap());
|
||||
let file = format!("Jarvis-Setup-{version}.exe");
|
||||
let list = json!([rel("v1.10.0", &base, &[]), rel(&format!("app-v{version}"), &base, &both(version))]).to_string();
|
||||
let sum_text = format!("{sum} {file}\n");
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut s, _)) = l.accept().await {
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let n = s.read(&mut buf).await.unwrap_or(0);
|
||||
let path = String::from_utf8_lossy(&buf[..n]).split_whitespace().nth(1).unwrap_or("").to_owned();
|
||||
let body: Vec<u8> = if path.starts_with("/releases") { list.clone().into_bytes() }
|
||||
else if path.ends_with(".sha256") { sum_text.clone().into_bytes() }
|
||||
else if path.ends_with(".exe") { installer.clone() } else { vec![] };
|
||||
let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
|
||||
let _ = s.write_all(head.as_bytes()).await;
|
||||
let _ = s.write_all(&body).await;
|
||||
}
|
||||
});
|
||||
base
|
||||
}
|
||||
|
||||
async fn settle(u: &Updater) -> Value {
|
||||
for _ in 0..200 {
|
||||
let s = u.status();
|
||||
if s["phase"] != json!("downloading") {
|
||||
return s;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
panic!("the download did not end");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_newer_release_is_found_downloaded_checked_and_handed_over() {
|
||||
let installer: Vec<u8> = (0..50_000u32).map(|i| (i % 253) as u8).collect();
|
||||
let sum = format!("{:x}", Sha256::digest(&installer));
|
||||
let base = gitea("0.2.0", installer.clone(), sum).await;
|
||||
let dir = temp_dir("upd1").join("cache/updates");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Jarvis-Setup-0.1.5.exe"), b"old").unwrap();
|
||||
let u = Updater::new(format!("{base}/releases"), "0.1.0", dir.clone());
|
||||
assert!(u.ready_installer().is_err(), "nothing to install yet");
|
||||
assert!(u.download().is_err(), "check first");
|
||||
let c = u.check().await.unwrap();
|
||||
assert_eq!((c["phase"].clone(), c["latest"]["version"].clone()), (json!("available"), json!("0.2.0")));
|
||||
u.download().unwrap();
|
||||
let s = settle(&u).await;
|
||||
assert_eq!((s["phase"].clone(), s["done"].clone()), (json!("ready"), json!(installer.len())));
|
||||
let path = u.ready_installer().unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), installer);
|
||||
assert!(!dir.join("Jarvis-Setup-0.1.5.exe").exists(), "the earlier installer is gone");
|
||||
// Checking again keeps the ready file; a file changed after the download is refused.
|
||||
assert_eq!(u.check().await.unwrap()["phase"], json!("ready"));
|
||||
std::fs::write(&path, b"changed").unwrap();
|
||||
assert!(u.ready_installer().unwrap_err().contains("바뀌었"));
|
||||
// The same version as the release: up to date.
|
||||
let same = Updater::new(format!("{base}/releases"), "0.2.0", temp_dir("upd1b"));
|
||||
assert_eq!(same.check().await.unwrap()["phase"], json!("upToDate"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_download_that_does_not_match_its_checksum_is_not_offered_for_install() {
|
||||
let base = gitea("0.2.0", b"tampered".to_vec(), "0".repeat(64)).await;
|
||||
let dir = temp_dir("upd2");
|
||||
let u = Updater::new(format!("{base}/releases"), "0.1.0", dir.clone());
|
||||
u.check().await.unwrap();
|
||||
u.download().unwrap();
|
||||
let s = settle(&u).await;
|
||||
assert_eq!(s["phase"], json!("failed"));
|
||||
assert!(s["error"].as_str().unwrap().contains("damaged"));
|
||||
assert!(u.ready_installer().is_err());
|
||||
assert!(!dir.join("Jarvis-Setup-0.2.0.exe").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_that_cannot_be_reached_or_is_not_https_fails_with_a_reason() {
|
||||
let u = Updater::new("http://127.0.0.1:9/releases".into(), "0.1.0", temp_dir("upd3"));
|
||||
assert!(u.check().await.unwrap_err().contains("연결하지 못했습니다"));
|
||||
assert_eq!(u.status()["phase"], json!("failed"));
|
||||
let plain = Updater::new("http://git.example/releases".into(), "0.1.0", temp_dir("upd4"));
|
||||
assert!(plain.check().await.unwrap_err().contains("https"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_app_and_its_installer_carry_the_same_version() {
|
||||
// installer.sh names the setup after the shell's version; the app compares its own; the
|
||||
// program file's version comes from the shell's Cargo.toml when tauri.conf.json sets none.
|
||||
let shell = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/shell/Cargo.toml")).unwrap();
|
||||
let v = shell.lines().find_map(|l| l.strip_prefix("version = \"")).unwrap().trim_end_matches('"');
|
||||
assert_eq!(v, env!("CARGO_PKG_VERSION"));
|
||||
let conf: Value = serde_json::from_str(&std::fs::read_to_string(
|
||||
concat!(env!("CARGO_MANIFEST_DIR"), "/shell/tauri.conf.json")).unwrap()).unwrap();
|
||||
assert_eq!(conf.get("version"), None, "one version, in the Cargo.toml files");
|
||||
}
|
||||
}
|
||||
@@ -545,6 +545,50 @@ function logsScreen() {
|
||||
return { view, tick: poll };
|
||||
}
|
||||
|
||||
// ---- update -------------------------------------------------------------------------------------
|
||||
|
||||
/** The update screen: the version here, the newest release, its download and install. */
|
||||
function updateScreen() {
|
||||
const body = h("div");
|
||||
let key = null;
|
||||
async function tick() {
|
||||
let u;
|
||||
try { u = await api("update_status"); } catch (e) { return; }
|
||||
const k = JSON.stringify([u.phase, u.latest?.version, u.error, u.phase === "downloading" ? u.done : 0]);
|
||||
if (k === key) return;
|
||||
key = k;
|
||||
const act = (cmd, text, primary) => h("button", { class: "btn" + (primary ? " primary" : ""), onclick: async (e) => {
|
||||
e.target.disabled = true;
|
||||
try { await api(cmd); } catch (err) { fail(err); }
|
||||
key = null; tick();
|
||||
} }, text);
|
||||
const pct = u.total ? Math.floor((u.done / u.total) * 100) : null;
|
||||
const line = { idle: "아직 확인하지 않았습니다", checking: "확인하는 중…", upToDate: "최신 버전입니다",
|
||||
available: `새 버전 ${u.latest?.version}이 있습니다`, downloading: `받는 중${pct != null ? ` ${pct}%` : ""}`,
|
||||
ready: `${u.latest?.version}을 설치할 준비가 됐습니다`, failed: u.error ?? "실패했습니다" }[u.phase] ?? u.phase;
|
||||
body.replaceChildren(h("div", { class: "card" },
|
||||
h("div", { class: "kv" }, h("span", { class: "k" }, "현재 버전"), h("span", {}, u.current),
|
||||
h("span", { class: "k" }, "상태"), h("span", { style: u.phase === "failed" ? "color:var(--bad)" : "" }, line)),
|
||||
h("div", { class: "row", style: "margin-top:12px" },
|
||||
u.phase !== "checking" && u.phase !== "downloading" ? act("update_check", "다시 확인") : null,
|
||||
(u.phase === "available" || (u.phase === "failed" && u.latest)) ? act("update_download", "받기", true) : null,
|
||||
u.phase === "ready" ? act("update_install", "설치하고 다시 시작", true) : null),
|
||||
u.phase === "ready" ? h("p", { class: "small muted" }, "설치하면 봇과 서비스를 멈추고 Jarvis를 닫은 뒤 새 버전을 설치하고 다시 켭니다. Windows가 관리자 권한을 한 번 묻습니다.") : null),
|
||||
u.latest?.notes ? h("div", { class: "card" }, h("h2", {}, `${u.latest.version} 바뀐 점`),
|
||||
h("pre", { class: "small", style: "white-space:pre-wrap" }, u.latest.notes)) : null);
|
||||
}
|
||||
tick();
|
||||
return { view: h("div", {}, h("h1", {}, "업데이트"), body), tick };
|
||||
}
|
||||
|
||||
/** Look for a new version once when the app opens; the nav button says so when there is one. */
|
||||
async function checkUpdate() {
|
||||
try {
|
||||
const u = await api("update_check");
|
||||
if (u.latest) { $("#nav-update").textContent = "업데이트 (새 버전)"; toast(`새 버전 ${u.latest.version}이 있습니다. 업데이트 화면에서 설치할 수 있습니다.`); }
|
||||
} catch (e) { /* offline: the update screen shows why */ }
|
||||
}
|
||||
|
||||
// ---- navigation ---------------------------------------------------------------------------------
|
||||
|
||||
let current = null, ticker = null;
|
||||
@@ -578,6 +622,7 @@ async function show(name) {
|
||||
try {
|
||||
if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; }
|
||||
if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; }
|
||||
if (name === "update") { const u = updateScreen(); screen.replaceChildren(u.view); ticker = setInterval(u.tick, 1000); return; }
|
||||
const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능",
|
||||
collect: "백그라운드 수집", game: "게임 모드" };
|
||||
const extra = name === "bot" ? await tokenCard() : name === "features" ? await displayDriverCard() : null;
|
||||
@@ -755,6 +800,7 @@ async function start() {
|
||||
$("#main").hidden = false;
|
||||
for (const b of document.querySelectorAll(".nav")) b.onclick = () => show(b.dataset.screen);
|
||||
show("dashboard");
|
||||
checkUpdate();
|
||||
}
|
||||
// The window tells what closing does: stopping what runs first, or that it could not.
|
||||
if (window.__TAURI__?.event) {
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<button data-screen="collect" class="nav">백그라운드 수집</button>
|
||||
<button data-screen="game" class="nav">게임 모드</button>
|
||||
<button data-screen="logs" class="nav">로그</button>
|
||||
<button data-screen="update" class="nav" id="nav-update">업데이트</button>
|
||||
<div class="side-foot" id="version"></div>
|
||||
</nav>
|
||||
<main id="screen" class="screen"></main>
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user