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.

feat: run Kanzo natively on Windows

marcuslannister12eff7842804
diff --git a/README.md b/README.md
index 5efbc8b..8c73546 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,13 @@ Kanzo is a kanban board in your browser and an MCP server in one small program,
curl -LsSf https://github.com/emanuele-em/kanzo/releases/latest/download/kanzo-installer.sh | sh
```
-For macOS and Linux, including every Raspberry Pi. Every release is signed by GitHub: check a download with `gh attestation verify <file> --repo emanuele-em/kanzo`. Or with Cargo:
+For macOS and Linux, including every Raspberry Pi. On Windows, in PowerShell:
+
+```powershell
+powershell -ExecutionPolicy Bypass -c "irm https://github.com/emanuele-em/kanzo/releases/latest/download/kanzo-installer.ps1 | iex"
+```
+
+Every release is signed by GitHub: check a download with `gh attestation verify <file> --repo emanuele-em/kanzo`. Or with Cargo:
```sh
cargo install kanzo
diff --git a/src/app.js b/src/app.js
index c5587c2..23533f1 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1347,14 +1347,20 @@ async function installUpdate(available) {
button.hidden = false;
button.disabled = true;
$("#update-label").textContent = "Updating…";
+ let res;
try {
- await api("POST", "/update");
+ res = await api("POST", "/update");
} catch (err) {
toast(err.message);
button.disabled = false;
$("#update-label").textContent = `Update to ${available}`;
return;
}
+ if (!res.restarting) {
+ $("#update-label").textContent = "Restart Kanzo to finish";
+ toast(`Kanzo ${available} is installed. Restart Kanzo to use it.`);
+ 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++) {
diff --git a/src/home.rs b/src/home.rs
index ebf57ac..6bf2c57 100644
--- a/src/home.rs
+++ b/src/home.rs
@@ -114,9 +114,13 @@ impl Home {
use std::os::unix::fs::MetadataExt;
fs::metadata(self.db_path()).map(|m| m.ino()).unwrap_or(0)
}
+ // No inode on Windows; a replaced file has a new modified time. Not the creation
+ // time: NTFS keeps it for a file replaced under the same name.
#[cfg(not(unix))]
{
- 0
+ let modified = fs::metadata(self.db_path()).and_then(|m| m.modified()).ok();
+ let since_epoch = modified.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok());
+ since_epoch.map_or(0, |d| d.as_nanos() as u64)
}
}
diff --git a/src/main.rs b/src/main.rs
index 99a8f5d..24e0d93 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -71,7 +71,7 @@ enum Command {
},
/// Install the latest release over this Kanzo, and restart the board's service
Update,
- /// Start the board automatically at login (macOS and Linux)
+ /// Start the board automatically at login
Service {
#[command(subcommand)]
action: ServiceAction,
@@ -80,7 +80,7 @@ enum Command {
#[derive(Subcommand)]
enum ServiceAction {
- /// Install and start a service that runs the board at login (LaunchAgent on macOS, systemd on Linux)
+ /// Install and start a service that runs the board at login (LaunchAgent on macOS, systemd on Linux, Task Scheduler on Windows)
Install,
/// Stop and remove that service
Uninstall,
@@ -88,6 +88,9 @@ enum ServiceAction {
fn main() -> ExitCode {
let cli = Cli::parse();
+ if cfg!(windows) {
+ update::remove_old_exes();
+ }
// One thread runs all the async work: the board serves one person, and each
// agent starts its own `kanzo mcp`. Database calls run on a few blocking
// threads that exit when idle. This keeps kanzo light on small boards.
diff --git a/src/service.rs b/src/service.rs
index 767e191..6c13190 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -1,5 +1,6 @@
//! `kanzo service`: run the board in the background, started at login.
-//! A LaunchAgent on macOS, a systemd user unit on Linux (a Raspberry Pi, an old laptop).
+//! A LaunchAgent on macOS, a systemd user unit on Linux (a Raspberry Pi, an old laptop),
+//! a Task Scheduler task on Windows.
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -10,6 +11,7 @@ use crate::home::Home;
const LABEL: &str = "com.github.emanuele-em.kanzo";
const UNIT: &str = "kanzo.service";
+const TASK: &str = "Kanzo";
pub fn install(home: &Home) -> Result<()> {
let exe = std::env::current_exe().context("cannot find the kanzo program")?;
@@ -17,8 +19,10 @@ pub fn install(home: &Home) -> Result<()> {
install_launchd(home, &exe)
} else if cfg!(target_os = "linux") {
install_systemd(home, &exe)
+ } else if cfg!(windows) {
+ install_task(home, &exe)
} else {
- bail!("kanzo service supports macOS and Linux; start `kanzo --no-open` with your own service manager")
+ bail!("kanzo service supports macOS, Linux and Windows; start `kanzo --no-open` with your own service manager")
}
}
@@ -27,8 +31,10 @@ pub fn uninstall() -> Result<()> {
uninstall_launchd()
} else if cfg!(target_os = "linux") {
uninstall_systemd()
+ } else if cfg!(windows) {
+ uninstall_task()
} else {
- bail!("kanzo service supports macOS and Linux")
+ bail!("kanzo service supports macOS, Linux and Windows")
}
}
@@ -39,6 +45,8 @@ pub fn restart() -> Result<bool> {
run("launchctl", &["kickstart", "-k", &format!("{}/{LABEL}", launchd_domain()?)])?;
} else if cfg!(target_os = "linux") && unit_path()?.exists() {
run("systemctl", &["--user", "restart", UNIT])?;
+ } else if cfg!(windows) && task_exists() {
+ restart_task()?;
} else {
return Ok(false);
}
@@ -199,6 +207,113 @@ fn uninstall_systemd() -> Result<()> {
Ok(())
}
+// Windows
+
+/// Stops the board, which may be this process (cmd outlives it), waits 3 s for it to let
+/// go of its port (`timeout` needs a console), then starts it. `/end` stops conhost; the
+/// board then exits with its console (see `web::exit_with_console`).
+fn restart_task() -> Result<()> {
+ let line = format!("schtasks /end /tn {TASK} & ping -n 4 127.0.0.1 >nul & schtasks /run /tn {TASK}");
+ let mut cmd = Command::new("cmd");
+ cmd.args(["/c", &line]);
+ // A console of its own (CREATE_NO_WINDOW): the board's goes away with `/end`, and
+ // takes the processes in it along.
+ #[cfg(windows)]
+ std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000);
+ let out = cmd.output().context("cannot run cmd")?;
+ if !out.status.success() {
+ bail!("cannot restart the Kanzo task: {}", String::from_utf8_lossy(&out.stderr).trim());
+ }
+ Ok(())
+}
+
+/// Whether this process is the board the Windows task starts: the task's arguments, and
+/// the task is installed.
+pub fn is_task_board(dir: &Path) -> bool {
+ let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
+ args == ["--no-open".into(), "--home".into(), dir.as_os_str().to_owned()] && task_exists()
+}
+
+fn task_exists() -> bool {
+ Command::new("schtasks").args(["/query", "/tn", TASK]).output().is_ok_and(|o| o.status.success())
+}
+
+/// A logon task that runs the board in the user's session, so it can use their saved
+/// git credentials, through `conhost --headless`, so it has no window. S4U has no
+/// window either, but can't read Credential Manager and needs an elevated shell.
+fn task(exe: &Path, dir: &Path, user: &str) -> String {
+ let esc = |s: &str| xml_escape(s).replace('"', "&quot;");
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-16"?>
+<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
+ <Triggers>
+ <LogonTrigger><UserId>{user}</UserId></LogonTrigger>
+ </Triggers>
+ <Principals>
+ <Principal><UserId>{user}</UserId><LogonType>InteractiveToken</LogonType></Principal>
+ </Principals>
+ <Settings>
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
+ <RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure>
+ </Settings>
+ <Actions>
+ <Exec><Command>conhost.exe</Command><Arguments>--headless {exe} --no-open --home {dir}</Arguments></Exec>
+ </Actions>
+</Task>
+"#,
+ user = esc(user),
+ exe = esc(&format!("\"{}\"", exe.display())),
+ dir = esc(&format!("\"{}\"", dir.display())),
+ )
+}
+
+/// `domain\user`, from Windows in UTF-8: `whoami` prints in the console's code page, and
+/// %USERDOMAIN% is WORKGROUP over SSH.
+fn account() -> Result<String> {
+ let name =
+ "[Console]::OutputEncoding = [Text.Encoding]::UTF8; [Security.Principal.WindowsIdentity]::GetCurrent().Name";
+ let out =
+ Command::new("powershell").args(["-NoProfile", "-Command", name]).output().context("cannot run powershell")?;
+ let user = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ if !out.status.success() || user.is_empty() {
+ bail!("cannot find your Windows account: {}", String::from_utf8_lossy(&out.stderr).trim());
+ }
+ Ok(user)
+}
+
+fn install_task(home: &Home, exe: &Path) -> Result<()> {
+ let user = account()?;
+ let xml = std::env::temp_dir().join("kanzo-task.xml");
+ // schtasks reads the XML as UTF-16, as the declaration says.
+ let utf16: Vec<u8> =
+ std::iter::once(0xFEFF).chain(task(exe, &home.dir, &user).encode_utf16()).flat_map(u16::to_le_bytes).collect();
+ std::fs::write(&xml, utf16).with_context(|| format!("cannot write {}", xml.display()))?;
+ let created = run("schtasks", &["/create", "/tn", TASK, "/xml", &xml.to_string_lossy(), "/f"]);
+ let _ = std::fs::remove_file(&xml);
+ created?;
+ // Restart rather than start, so a changed path or data folder takes effect.
+ restart_task()?;
+ println!(
+ "Kanzo now starts at login and is running at http://localhost:{}\n\
+ It has no window and no log; to see its errors, run `kanzo service uninstall`, then `kanzo --no-open`.",
+ home.config.port
+ );
+ Ok(())
+}
+
+fn uninstall_task() -> Result<()> {
+ if !task_exists() {
+ println!("The Kanzo task was not installed.");
+ return Ok(());
+ }
+ let _ = Command::new("schtasks").args(["/end", "/tn", TASK]).output();
+ run("schtasks", &["/delete", "/tn", TASK, "/f"])?;
+ println!("Removed the Kanzo task; the board no longer starts at login.");
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -224,4 +339,16 @@ mod tests {
);
assert!(text.contains("WantedBy=default.target"));
}
+
+ #[test]
+ fn task_quotes_paths() {
+ let text = task(Path::new(r"C:\Users\a&b\.cargo\bin\kanzo.exe"), Path::new(r"C:\Users\a&b\kanzo"), r"pc\a&b");
+ assert!(
+ text.contains(
+ r"<Arguments>--headless &quot;C:\Users\a&amp;b\.cargo\bin\kanzo.exe&quot; --no-open --home &quot;C:\Users\a&amp;b\kanzo&quot;</Arguments>"
+ ),
+ "{text}"
+ );
+ assert!(text.contains(r"<UserId>pc\a&amp;b</UserId>"));
+ }
}
diff --git a/src/update.rs b/src/update.rs
index 49a1c73..049f0c4 100644
--- a/src/update.rs
+++ b/src/update.rs
@@ -1,11 +1,12 @@
//! 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.
+//! program, then start the new one in place. It uses `curl` and `sh` (PowerShell on
+//! Windows), which every system has, so Kanzo needs no HTTP client of its own.
+#[cfg(unix)]
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
-use std::process::{Command, Stdio};
+use std::process::{Command, Output, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
@@ -17,6 +18,10 @@ const RELEASES: &str = "https://github.com/emanuele-em/kanzo/releases/latest/dow
/// How long a check for the latest version is reused: the board checks once a day.
const CHECK_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
+/// How long a board waits for the service to stop it after an update, on Windows.
+#[cfg(not(unix))]
+const SERVICE_STOP: Duration = Duration::from_secs(10);
+
static LATEST: Mutex<Option<(Instant, Option<String>)>> = Mutex::new(None);
fn releases() -> String {
@@ -67,18 +72,18 @@ pub fn install() -> Result<PathBuf, String> {
));
}
};
- 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::null())
- .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())?;
+ let ext = if cfg!(windows) { "ps1" } else { "sh" };
+ let script = curl(&format!("{}/kanzo-installer.{ext}", releases())).ok_or("cannot download the installer")?;
+ // Windows can't replace a running program, but can rename it; see `remove_old_exes`.
+ let old = old_exe(&exe);
+ if cfg!(windows) {
+ std::fs::rename(&exe, &old).map_err(|e| format!("cannot move {}: {e}", exe.display()))?;
+ }
+ let out = run_installer(&script, &dir);
+ if cfg!(windows) && !out.as_ref().is_ok_and(|o| o.status.success()) {
+ let _ = std::fs::rename(&old, &exe);
+ }
+ let out = out?;
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");
@@ -87,7 +92,54 @@ pub fn install() -> Result<PathBuf, String> {
Ok(exe)
}
+/// Where Windows keeps the running program while the installer replaces it. Named for
+/// its version: an agent's `kanzo mcp` can keep an older one running, and locked.
+fn old_exe(exe: &Path) -> PathBuf {
+ exe.with_extension(format!("exe.{CURRENT}.old"))
+}
+
+/// Deletes the programs that updates replaced on Windows, except those still running.
+pub fn remove_old_exes() {
+ let Ok(exe) = std::env::current_exe() else { return };
+ let (Some(dir), Some(name)) = (exe.parent(), exe.file_name()) else { return };
+ let prefix = format!("{}.", name.to_string_lossy());
+ for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
+ let file = entry.file_name();
+ let file = file.to_string_lossy();
+ if file.starts_with(&prefix) && file.ends_with(".old") {
+ let _ = std::fs::remove_file(entry.path());
+ }
+ }
+}
+
+fn run_installer(script: &[u8], dir: &Path) -> Result<Output, String> {
+ let mut cmd = if cfg!(windows) {
+ // PowerShell runs a script from a file, not from stdin.
+ let file = std::env::temp_dir().join("kanzo-installer.ps1");
+ std::fs::write(&file, script).map_err(|e| format!("cannot write {}: {e}", file.display()))?;
+ let mut ps = Command::new("powershell");
+ ps.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(file).stdin(Stdio::null());
+ ps
+ } else {
+ let mut sh = Command::new("sh");
+ sh.arg("-s").stdin(Stdio::piped());
+ sh
+ };
+ let mut child = cmd
+ .env("KANZO_INSTALL_DIR", dir)
+ .env("KANZO_NO_MODIFY_PATH", "1")
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|e| format!("cannot run the installer: {e}"))?;
+ if let Some(mut stdin) = child.stdin.take() {
+ stdin.write_all(script).map_err(|e| e.to_string())?;
+ }
+ child.wait_with_output().map_err(|e| e.to_string())
+}
+
/// The arguments to start again with: the same ones, without opening another browser tab.
+#[cfg(unix)]
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") {
@@ -104,9 +156,20 @@ pub fn restart(exe: &Path) -> std::io::Error {
Command::new(exe).args(restart_args(std::env::args_os().skip(1))).exec()
}
+/// Restarts the service, which stops this process; see `can_restart`.
#[cfg(not(unix))]
pub fn restart(_exe: &Path) -> std::io::Error {
- std::io::Error::other("restart Kanzo to finish the update")
+ if let Err(e) = crate::service::restart() {
+ return std::io::Error::other(e.to_string());
+ }
+ std::thread::sleep(SERVICE_STOP);
+ std::io::Error::other("the service did not restart")
+}
+
+/// Whether `restart` can start the new program in this one's place. On Windows only the
+/// service's board can: a running program can't replace itself there.
+pub fn can_restart(home: &Path) -> bool {
+ cfg!(unix) || crate::service::is_task_board(home)
}
#[cfg(test)]
@@ -122,6 +185,7 @@ mod tests {
}
#[test]
+ #[cfg(unix)]
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"]));
diff --git a/src/web.rs b/src/web.rs
index ebb8d02..d14bb13 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -49,6 +49,8 @@ pub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {
}
Err(e) => return Err(e).context(format!("cannot listen on {listen} port {port}")),
};
+ #[cfg(windows)]
+ exit_with_console();
let guard = Guard::new(port, !listen.is_loopback());
println!("Kanzo board at {url}, data in {}", home.dir.display());
if guard.lan {
@@ -636,15 +638,20 @@ async fn update_status(Query(q): Query<UpdateQuery>) -> Response {
Json(json!({ "current": update::CURRENT, "latest": latest, "available": available })).into_response()
}
-/// Installs the latest release over this program, answers, then starts it in place.
-async fn update_now() -> Response {
+/// Installs the latest release over this program, answers, then starts it in place, or
+/// asks the user to restart it where it can't.
+async fn update_now(State(home): Shared) -> Response {
+ let restart = update::can_restart(&home.dir);
match tokio::task::spawn_blocking(update::install).await {
+ Ok(Ok(_)) if !restart => Json(json!({ "restarting": false })).into_response(),
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}");
+ // Blocking: on Windows it waits for the service to stop this process.
+ if let Ok(e) = tokio::task::spawn_blocking(move || update::restart(&exe)).await {
+ eprintln!("kanzo: updated, but cannot restart: {e}");
+ }
});
Json(json!({ "restarting": true })).into_response()
}
@@ -665,16 +672,39 @@ async fn is_kanzo(port: u16) -> bool {
tokio::time::timeout(std::time::Duration::from_secs(2), probe).await.ok().flatten().unwrap_or(false)
}
+/// Exits when the console goes away: the service's conhost when the task is stopped, or
+/// the window the board was started in. Windows doesn't stop the program by itself.
+#[cfg(windows)]
+fn exit_with_console() {
+ unsafe extern "system" {
+ fn GetConsoleProcessList(list: *mut u32, count: u32) -> u32;
+ }
+ // SAFETY: room for one process id, as `count` says; it returns 0 without a console.
+ let attached = || unsafe { GetConsoleProcessList(&mut 0, 1) } != 0;
+ if attached() {
+ std::thread::spawn(move || {
+ while attached() {
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ }
+ std::process::exit(0);
+ });
+ }
+}
+
fn open_browser(url: &str) {
- if cfg!(target_os = "macos") {
- if std::process::Command::new("open").arg(url).spawn().is_err() {
- eprintln!("Open {url} in your browser.");
+ let opener = if cfg!(target_os = "macos") {
+ "open"
+ } else if cfg!(windows) {
+ "explorer"
+ } else {
+ // A board without a screen has nothing to open; the URL is already printed.
+ let desktop = ["DISPLAY", "WAYLAND_DISPLAY"].iter().any(|v| std::env::var_os(v).is_some_and(|v| !v.is_empty()));
+ if !desktop {
+ return;
}
- return;
- }
- // A board without a screen has nothing to open; the URL is already printed.
- let desktop = ["DISPLAY", "WAYLAND_DISPLAY"].iter().any(|v| std::env::var_os(v).is_some_and(|v| !v.is_empty()));
- if desktop && std::process::Command::new("xdg-open").arg(url).spawn().is_err() {
+ "xdg-open"
+ };
+ if std::process::Command::new(opener).arg(url).spawn().is_err() {
eprintln!("Open {url} in your browser.");
}
}