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.

Open local file links from tasks in an editor

emanuele-em06a78d976f72
diff --git a/README.md b/README.md
index d6bef26..332607f 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ kanzo
The board opens at http://localhost:4242. That's all the setup there is: the first run creates `~/kanzo`, and the whole board lives in it.
-`n` adds a task, `/` or `⌘K` searches every project, `f` filters the board and `↵` keeps the filter, `Tab` moves to the description, `⌘↵` saves and closes. `Esc` leaves a description or tags with what you typed saved, and cancels other fields. Mark a task Human and agents leave it to you; the person icon shows only those. Paste or drop an image into a task or a comment to attach it. Give a task a URL, like its pull request on any site, and click the link on its card to open it; agents set it with `url`. When a new version is out, the sidebar offers it: one click installs it.
+`n` adds a task, `/` or `⌘K` searches every project, `f` filters the board and `↵` keeps the filter, `Tab` moves to the description, `⌘↵` saves and closes. `Esc` leaves a description or tags with what you typed saved, and cancels other fields. Mark a task Human and agents leave it to you; the person icon shows only those. Paste or drop an image into a task or a comment to attach it. Give a task a URL, like its pull request on any site, and click the link on its card to open it; agents set it with `url`. A link to a file in a description or comment, `[name](file:///path)`, opens in your editor. When a new version is out, the sidebar offers it: one click installs it.
## Connect your agents
@@ -221,6 +221,7 @@ Everything lives in `~/kanzo`: the board in `kanzo.db`, settings in `config.toml
port = 4242
listen = "127.0.0.1" # sharing opens the board to your network; "0.0.0.0" keeps it open
mcp_http = true # MCP at /mcp
+editor = "/usr/local/bin/cursor" # opens file:/// links; on macOS, your text editor without it
```
Settings on the board lists each task's properties, like tags or comments. Turn one off to hide it there and leave it out of what agents get; nothing is deleted.
diff --git a/src/app.js b/src/app.js
index 625e248..e12a810 100644
--- a/src/app.js
+++ b/src/app.js
@@ -210,7 +210,7 @@ function inline(s) {
s = s
.replace(/\u0000/g, "")
.replace(/`([^`]+)`/g, (_, code) => keep(`<code>${code}</code>`))
- .replace(/\[([^\]]+)\]\(((?:https?:\/\/|mailto:)[^\s)\u0000]+)\)/g, (_, text, url) => link(url, emphasis(text)))
+ .replace(/\[([^\]]+)\]\(((?:https?:\/\/|mailto:|file:\/\/\/)[^\s)\u0000]+)\)/g, (_, text, url) => link(url, emphasis(text)))
.replace(/(^|[\s(])(https?:\/\/[^\s)\u0000]+)/g, (_, before, url) => before + link(url, url));
const restore = (html) => html.replace(/\u0000(\d+)\u0000/g, (_, i) => restore(saved[i]));
return restore(emphasis(s));
@@ -1013,6 +1013,17 @@ function leaveField(e) {
else e.target.blur();
}
+// A page can't open a file: link, so the board does, on the computer it runs on.
+panel.addEventListener("click", async (e) => {
+ const link = e.target.closest('a[href^="file:///"]');
+ if (!link) return;
+ e.preventDefault();
+ try {
+ const path = decodeURIComponent(link.getAttribute("href").slice(7)).replace(/^\/([a-zA-Z]:)/, "$1");
+ await api("POST", "/open", { path });
+ } catch (err) { toast(err.message); }
+});
+
$("#p-close").addEventListener("click", closeTask);
$("#p-key").addEventListener("click", () => { if (panelTask) copyKey(key(panelTask)); });
for (const field of [$("#p-title"), $("#p-desc")]) field.addEventListener("input", () => fit(field));
diff --git a/src/home.rs b/src/home.rs
index 3c4b5ff..c512ce3 100644
--- a/src/home.rs
+++ b/src/home.rs
@@ -2,7 +2,7 @@ use std::fs::{self, File, OpenOptions, TryLockError};
use std::io;
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
-use std::process::Command;
+use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
@@ -26,6 +26,10 @@ listen = "127.0.0.1"
# Also serve MCP over HTTP at http://localhost:<port>/mcp, for agents
# that cannot start `kanzo mcp` themselves.
mcp_http = true
+
+# The editor that file:/// links in tasks open in, as a full path. Without it,
+# macOS uses your default text editor, and other systems can't open them.
+# editor = "/usr/local/bin/cursor"
"#;
const GITIGNORE: &str = "\
@@ -54,11 +58,18 @@ pub struct Config {
#[serde(rename = "statuses")]
_statuses: Option<toml::Value>,
pub mcp_http: bool,
+ pub editor: Option<PathBuf>,
}
impl Default for Config {
fn default() -> Self {
- Self { port: DEFAULT_PORT, listen: IpAddr::V4(Ipv4Addr::LOCALHOST), _statuses: None, mcp_http: true }
+ Self {
+ port: DEFAULT_PORT,
+ listen: IpAddr::V4(Ipv4Addr::LOCALHOST),
+ _statuses: None,
+ mcp_http: true,
+ editor: None,
+ }
}
}
@@ -145,6 +156,20 @@ impl Home {
Store::open(&self.db_path(), lock)
}
+ pub fn open_file(&self, file: &Path) -> Result<(), String> {
+ let mut cmd = editor_command(self.config.editor.as_deref(), file)?;
+ let program = cmd.get_program().to_string_lossy().into_owned();
+ let mut child = cmd
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .map_err(|e| format!("cannot run {program}: {e}; set `editor` in config.toml to its full path"))?;
+ // An editor's command can run for as long as the editor does: this isn't work for a database thread.
+ std::thread::spawn(move || child.wait());
+ Ok(())
+ }
+
pub fn images(&self) -> PathBuf {
self.dir.join("images")
}
@@ -184,6 +209,26 @@ impl Home {
}
}
+/// Anyone who can comment can write a file link, so opening one must never run anything. Only an
+/// editor, then, not a generic opener: `open` with no flags runs a `.command` file, `xdg-open` a
+/// `.desktop` file, and Windows `start` a program.
+fn editor_command(editor: Option<&Path>, file: &Path) -> Result<Command, String> {
+ if !file.is_absolute() || !file.is_file() {
+ return Err(format!("{} is not a file on this computer", file.display()));
+ }
+ let mut cmd = match editor {
+ Some(editor) => Command::new(editor),
+ None if cfg!(target_os = "macos") => {
+ let mut open = Command::new("open");
+ open.arg("-t");
+ open
+ }
+ None => return Err("set `editor` in config.toml to open files, as the full path of your editor".into()),
+ };
+ cmd.arg(file);
+ Ok(cmd)
+}
+
/// Some filesystems (exFAT, network shares) have no file locks: Kanzo goes on without.
fn unsupported(e: &io::Error) -> bool {
#[cfg(unix)]
@@ -271,6 +316,30 @@ mod tests {
assert_eq!(waiting.join().unwrap().unwrap(), 4);
}
+ #[test]
+ fn a_file_link_opens_in_an_editor_and_only_a_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = tmp.path().join("run.command");
+ fs::write(&file, "").unwrap();
+ let args = |cmd: &Command| cmd.get_args().map(|a| a.to_owned()).collect::<Vec<_>>();
+
+ let cmd = editor_command(Some(Path::new("/bin/cursor")), &file).unwrap();
+ assert_eq!(cmd.get_program(), "/bin/cursor");
+ assert_eq!(args(&cmd), [file.as_os_str()]);
+ if cfg!(target_os = "macos") {
+ let cmd = editor_command(None, &file).unwrap();
+ assert_eq!(cmd.get_program(), "open");
+ assert_eq!(args(&cmd), [std::ffi::OsStr::new("-t"), file.as_os_str()]);
+ } else {
+ assert!(editor_command(None, &file).is_err_and(|e| e.contains("editor")));
+ }
+
+ let editor = Some(Path::new("/bin/cursor"));
+ for bad in [Path::new("run.command"), tmp.path(), &tmp.path().join("missing")] {
+ assert!(editor_command(editor, bad).is_err(), "{}", bad.display());
+ }
+ }
+
#[test]
fn no_lock_only_when_unsupported() {
assert!(unsupported(&io::Error::from(io::ErrorKind::Unsupported)));
diff --git a/src/mcp.rs b/src/mcp.rs
index 3dd9864..a8041ac 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -38,7 +38,8 @@ macro_rules! instructions {
" machine, for all their projects. Tasks look like api#12. ",
$project,
" Keep it current unasked: doing when you start a task, comments on what you did, review when you \
- finish or get stuck, url for a PR you opened. Leave done and human tasks to the user."
+ finish or get stuck, url for a PR you opened. Leave done and human tasks to the user. Link files as \
+ [name](file:///path)."
)
};
}
diff --git a/src/web.rs b/src/web.rs
index 95b4df3..2fa5a33 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -173,6 +173,8 @@ fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken) -> Router
.route("/api/ping", get(|| async { "kanzo" }))
.route("/api/update", get(update_status).post(update_now))
.route("/api/network", get(network).post(change_network).route_layer(middleware::from_fn(this_computer)))
+ // Not forwarded by a joined board either: the files are on this computer.
+ .route("/api/open", post(open_file).route_layer(middleware::from_fn(this_computer)))
.merge(shared)
.layer(Extension(guard.clone()))
.layer(middleware::from_fn_with_state(guard, protect))
@@ -291,7 +293,7 @@ async fn forward(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> R
async fn this_computer(req: Request, next: Next) -> Response {
match guest(&req) {
- Some(_) => (StatusCode::FORBIDDEN, "only the computer with the board can change its network").into_response(),
+ Some(_) => fail(StatusCode::FORBIDDEN, "only the computer with the board can do that").into_response(),
None => next.run(req).await,
}
}
@@ -701,6 +703,16 @@ async fn change_network(
}
}
+#[derive(Deserialize)]
+struct OpenFile {
+ path: std::path::PathBuf,
+}
+
+async fn open_file(State(home): Shared, Json(o): Json<OpenFile>) -> Reply {
+ blocking(move || home.open_file(&o.path)).await?.map_err(|e| fail(StatusCode::BAD_REQUEST, e))?;
+ Ok(Json(json!({})).into_response())
+}
+
#[derive(Deserialize)]
struct SyncRequest {
#[serde(default)]
@@ -809,8 +821,53 @@ fn open_browser(url: &str) {
#[cfg(test)]
mod tests {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
use super::*;
+ /// The status of asking a board to open `path`, from `from`.
+ async fn open_from(home: &Home, from: Option<IpAddr>, path: &str) -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let guard = Arc::new(Guard::new(port, Ipv4Addr::LOCALHOST.into(), Net::Sharing));
+ let mut app = router(home.clone(), guard, CancellationToken::new());
+ if let Some(ip) = from {
+ app = app.layer(Extension(ConnectInfo(SocketAddr::new(ip, 1))));
+ }
+ tokio::spawn(async move { axum::serve(listener, app).await });
+ let body = json!({ "path": path }).to_string();
+ let mut conn = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
+ let head = format!(
+ "POST /api/open HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
+ body.len()
+ );
+ conn.write_all(format!("{head}{body}").as_bytes()).await.unwrap();
+ let mut reply = String::new();
+ conn.read_to_string(&mut reply).await.unwrap();
+ reply.split(' ').nth(1).unwrap().to_string()
+ }
+
+ #[test]
+ fn only_this_computer_opens_a_file_and_only_a_file() {
+ let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
+ runtime.block_on(async {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut home = Home::open(tmp.path().to_path_buf()).unwrap();
+ home.config.editor = Some("true".into());
+ let file = tmp.path().join("notes.md");
+ std::fs::write(&file, "").unwrap();
+ let file = file.to_str().unwrap();
+
+ let guest = Some(IpAddr::from([192, 168, 1, 9]));
+ assert_eq!(open_from(&home, guest, file).await, "403");
+ assert_eq!(open_from(&home, None, "notes.md").await, "400");
+ assert_eq!(open_from(&home, None, tmp.path().to_str().unwrap()).await, "400");
+ assert_eq!(open_from(&home, None, &format!("{file}.missing")).await, "400");
+ #[cfg(unix)]
+ assert_eq!(open_from(&home, None, file).await, "200");
+ });
+ }
+
#[test]
fn hosts() {
let local = Guard::new(4242, Ipv4Addr::LOCALHOST.into(), Net::Private);