Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Update Kanzo from the board

emanuele-emc214cf24bc86
diff --git a/README.md b/README.md
index e7a136a..8547c36 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,8 @@ kanzo service install # keep it running and start it at login
Paste an image into a task and Kanzo saves it in `~/kanzo/images` and types its path, like a terminal does, so your agents can open it.
+When a new version is out, the sidebar offers it: one click installs it and restarts the board.
+
## Connect your agents
```sh
diff --git a/src/app.js b/src/app.js
index 042a052..dd7c95b 100644
--- a/src/app.js
+++ b/src/app.js
@@ -67,6 +67,7 @@ const ICONS = {
plus: '<path d="M5 12h14M12 5v14"/>',
trash: '<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6"/>',
check: '<path d="M20 6 9 17l-5-5"/>',
+ update: '<circle cx="12" cy="12" r="9"/><path d="M12 7v9M8 12l4 4 4-4"/>',
send: '<path d="M12 19V5M5 12l7-7 7 7"/>',
};
@@ -900,6 +901,46 @@ function schedulePoll() {
}
schedulePoll();
+// ---------- update ----------
+
+// When a newer release is out, the sidebar offers it. The server checks at most every
+// few hours, installs it over itself and restarts; the page reloads once it is back.
+async function checkUpdate() {
+ try {
+ const { current, available } = await api("GET", "/update");
+ const button = $("#update");
+ button.hidden = !available;
+ if (!available) return;
+ $("#update-label").textContent = `Update to ${available}`;
+ button.title = `You have ${current}`;
+ button.onclick = () => installUpdate(current, available);
+ } catch {}
+}
+
+async function installUpdate(current, available) {
+ if (!confirm(`Update Kanzo from ${current} to ${available}? The board restarts, which takes a few seconds.`)) return;
+ const button = $("#update");
+ button.disabled = true;
+ $("#update-label").textContent = "Updating…";
+ try {
+ await api("POST", "/update");
+ } catch (err) {
+ toast(err.message);
+ button.disabled = false;
+ $("#update-label").textContent = `Update to ${available}`;
+ return;
+ }
+ // The old program answered, then gives way to the new one: wait for it, then reload.
+ await new Promise((r) => setTimeout(r, 1500));
+ for (let i = 0; i < 60; i++) {
+ try { await api("GET", "/update"); break; } catch { await new Promise((r) => setTimeout(r, 1000)); }
+ }
+ location.reload();
+}
+
+checkUpdate();
+setInterval(checkUpdate, 6 * 60 * 60 * 1000);
+
// Relative times ("5m ago") drift; refresh them now and then.
setInterval(() => {
document.querySelectorAll("time[datetime]").forEach((t) => { t.textContent = ago(t.getAttribute("datetime")); });
diff --git a/src/index.html b/src/index.html
index 828e267..fcf8bdb 100644
--- a/src/index.html
+++ b/src/index.html
@@ -95,6 +95,9 @@ aside {
.menu .repo .unlink .icon svg { width: 14px; height: 14px; }
.menu .repos input { margin-top: 4px; padding: 6px 10px; border-radius: 10px; font-size: 13px; }
.menu button.danger:hover, .menu button.danger:focus-visible { background: var(--danger-bg); }
+.update { margin-top: 8px; background: var(--hover); }
+.update:hover, .update:focus-visible { background: var(--active); }
+.update:disabled { opacity: .6; cursor: default; }
form.new-project { display: flex; flex-direction: column; gap: 6px; padding: 4px 2px 10px; }
form.new-project .row { display: flex; gap: 6px; margin-top: 2px; }
@@ -298,6 +301,7 @@ header .sub a:hover { color: var(--text); }
</div>
</form>
<nav class="nav" id="nav"></nav>
+ <button class="ghost update" id="update" hidden><span class="icon" data-icon="update"></span><span id="update-label"></span></button>
</aside>
<main>
diff --git a/src/main.rs b/src/main.rs
index 86038fe..f62ab67 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,6 +4,7 @@ mod mcp;
mod service;
mod store;
mod sync;
+mod update;
mod web;
use std::path::PathBuf;
diff --git a/src/update.rs b/src/update.rs
new file mode 100644
index 0000000..84a3d7c
--- /dev/null
+++ b/src/update.rs
@@ -0,0 +1,129 @@
+//! Updating Kanzo from the board: find the latest release, run its installer over this
+//! program, then start the new one in place. It uses `curl` and `sh`, which macOS and
+//! Linux have, so Kanzo needs no HTTP client of its own.
+
+use std::ffi::OsString;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+pub const CURRENT: &str = env!("CARGO_PKG_VERSION");
+
+/// Where releases are published; `KANZO_RELEASES_URL` points elsewhere, for tests.
+const RELEASES: &str = "https://github.com/emanuele-em/kanzo/releases/latest/download";
+
+/// How long a check for the latest version is reused.
+const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);
+
+static LATEST: Mutex<Option<(Instant, Option<String>)>> = Mutex::new(None);
+
+fn releases() -> String {
+ std::env::var("KANZO_RELEASES_URL").unwrap_or_else(|_| RELEASES.into())
+}
+
+fn curl(url: &str) -> Option<Vec<u8>> {
+ let out = Command::new("curl").args(["-fsSL", "--max-time", "20", url]).output().ok()?;
+ out.status.success().then_some(out.stdout)
+}
+
+/// The latest released version, checked at most every few hours; `None` when it
+/// can't be found, like offline.
+pub fn latest() -> Option<String> {
+ let mut cached = LATEST.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((at, version)) = &*cached
+ && at.elapsed() < CHECK_EVERY
+ {
+ return version.clone();
+ }
+ let version = curl(&format!("{}/dist-manifest.json", releases())).and_then(|body| {
+ let manifest: serde_json::Value = serde_json::from_slice(&body).ok()?;
+ let release = manifest["releases"].as_array()?.iter().find(|r| r["app_name"] == "kanzo")?;
+ release["app_version"].as_str().map(String::from)
+ });
+ *cached = Some((Instant::now(), version.clone()));
+ version
+}
+
+/// True when `version` is newer than this program: `0.2.0` > `0.1.9`.
+pub fn newer(version: &str) -> bool {
+ let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
+ parts(version) > parts(CURRENT)
+}
+
+/// Runs the latest release's installer over this program and returns its path,
+/// ready to restart.
+pub fn install() -> Result<PathBuf, String> {
+ let exe = std::env::current_exe().and_then(|p| p.canonicalize()).map_err(|e| e.to_string())?;
+ // The installer writes to <dir>/bin, so it can only replace a program kept in a bin folder.
+ let dir = match exe.parent() {
+ Some(bin) if bin.file_name().is_some_and(|n| n == "bin") => bin.parent().unwrap_or(bin).to_path_buf(),
+ _ => {
+ return Err(format!(
+ "Kanzo runs from {}, which the installer can't update; reinstall it with the command in the README",
+ exe.display()
+ ));
+ }
+ };
+ let script = curl(&format!("{}/kanzo-installer.sh", releases())).ok_or("cannot download the installer")?;
+ let mut sh = Command::new("sh")
+ .arg("-s")
+ .env("KANZO_INSTALL_DIR", &dir)
+ .env("KANZO_NO_MODIFY_PATH", "1")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|e| format!("cannot run the installer: {e}"))?;
+ sh.stdin.take().expect("stdin is piped").write_all(&script).map_err(|e| e.to_string())?;
+ let out = sh.wait_with_output().map_err(|e| e.to_string())?;
+ if !out.status.success() {
+ let log = String::from_utf8_lossy(&out.stderr);
+ let last = log.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output");
+ return Err(format!("the installer failed: {}", last.trim()));
+ }
+ Ok(exe)
+}
+
+/// The arguments to start again with: the same ones, without opening another browser tab.
+fn restart_args(args: impl Iterator<Item = OsString>) -> Vec<OsString> {
+ let mut args: Vec<OsString> = args.collect();
+ if !args.iter().any(|a| a == "--no-open") {
+ args.push("--no-open".into());
+ }
+ args
+}
+
+/// Replaces this process with the program at `exe`: same arguments, same process, so
+/// the port, the data folder and a running service stay. Returns only on failure.
+#[cfg(unix)]
+pub fn restart(exe: &Path) -> std::io::Error {
+ use std::os::unix::process::CommandExt;
+ Command::new(exe).args(restart_args(std::env::args_os().skip(1))).exec()
+}
+
+#[cfg(not(unix))]
+pub fn restart(_exe: &Path) -> std::io::Error {
+ std::io::Error::other("restart Kanzo to finish the update")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn versions() {
+ assert!(newer("99.0.0"));
+ assert!(!newer(CURRENT));
+ assert!(!newer("0.0.1"));
+ assert!(!newer("not a version"));
+ }
+
+ #[test]
+ fn restarts_without_opening_a_tab() {
+ let args = |v: &[&str]| v.iter().map(OsString::from).collect::<Vec<_>>();
+ assert_eq!(restart_args(args(&["--port", "4300"]).into_iter()), args(&["--port", "4300", "--no-open"]));
+ assert_eq!(restart_args(args(&["--no-open"]).into_iter()), args(&["--no-open"]));
+ }
+}
diff --git a/src/web.rs b/src/web.rs
index 9b2da9a..9ba7088 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -18,6 +18,7 @@ use tokio_util::sync::CancellationToken;
use crate::home::Home;
use crate::store::{self, Error, Store, TaskPatch};
+use crate::update;
const INDEX: &str = include_str!("index.html");
/// The largest image the board takes from a paste.
@@ -133,6 +134,7 @@ fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {
.route("/api/tasks/{id}/comments", post(add_comment))
.route("/api/comments/{id}", delete(delete_comment))
.route("/api/images", post(save_image).layer(DefaultBodyLimit::max(IMAGE_LIMIT)))
+ .route("/api/update", get(update_status).post(update_now))
.layer(middleware::from_fn_with_state(Arc::new(guard), protect))
.with_state(Arc::new(home))
}
@@ -444,6 +446,30 @@ async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Res
}
}
+/// This version, and a newer released one if there is.
+async fn update_status() -> Response {
+ let latest = tokio::task::spawn_blocking(update::latest).await.ok().flatten();
+ let available = latest.filter(|v| update::newer(v));
+ Json(json!({ "current": update::CURRENT, "available": available })).into_response()
+}
+
+/// Installs the latest release over this program, answers, then starts it in place.
+async fn update_now() -> Response {
+ match tokio::task::spawn_blocking(update::install).await {
+ Ok(Ok(exe)) => {
+ tokio::spawn(async move {
+ // Let the answer reach the board first.
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ let e = update::restart(&exe);
+ eprintln!("kanzo: updated, but cannot restart: {e}");
+ });
+ Json(json!({ "restarting": true })).into_response()
+ }
+ Ok(Err(error)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": error }))).into_response(),
+ Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
+ }
+}
+
/// True when the program on `port` answers like a Kanzo board.
async fn is_kanzo(port: u16) -> bool {
let probe = async {