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.

Do less work per request

emanuele-em09bc70251de9
diff --git a/README.md b/README.md
index 04bc645..b03d1af 100644
--- a/README.md
+++ b/README.md
@@ -88,7 +88,7 @@ mcp_http = true # MCP at /mcp
| | |
| --- | --- |
| Program | 4.1 MB, SQLite included |
-| Memory | 4.5 MB idle, 11 MB with 3,000 tasks |
+| Memory | 4.5 MB idle, 8 MB with 3,000 tasks |
| Start | 2 ms |
| Board of 3,000 tasks | 17 ms to load in the browser |
| Agents' tool list | about 900 tokens, once per session |
diff --git a/src/export.rs b/src/export.rs
index 7295a4f..b8ba5bb 100644
--- a/src/export.rs
+++ b/src/export.rs
@@ -7,7 +7,7 @@ use anyhow::{Context, Result};
use serde::Serialize;
use crate::home::Home;
-use crate::mcp::short_time;
+use crate::store::short_time;
use crate::store::{Comment, Project, Store, Task};
#[derive(Clone, Copy, clap::ValueEnum)]
diff --git a/src/home.rs b/src/home.rs
index 97303ea..f4804bc 100644
--- a/src/home.rs
+++ b/src/home.rs
@@ -10,7 +10,7 @@ use serde::Deserialize;
use crate::store::{self, ImagesOf, Store};
-pub const DEFAULT_PORT: u16 = 4242;
+const DEFAULT_PORT: u16 = 4242;
const CONFIG_TEMPLATE: &str = r#"# Kanzo settings.
diff --git a/src/mcp.rs b/src/mcp.rs
index a415f53..486c03e 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -1,6 +1,7 @@
//! The board as MCP tools: over stdio for `kanzo mcp`, and over HTTP at `/mcp` of the board.
//! Replies are short plain text to save agents' tokens.
+use std::fmt::Write;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
@@ -17,7 +18,7 @@ use serde::Deserialize;
use tokio_util::sync::CancellationToken;
use crate::home::Home;
-use crate::store::{self, Error, Project, Store, Task, TaskPatch};
+use crate::store::{self, Error, Project, Store, Task, TaskPatch, short_time};
/// The most done tasks list_tasks shows, newest first: an old board has thousands.
const DONE_LISTED: usize = 20;
@@ -50,8 +51,10 @@ pub async fn serve(home: Home) -> Result<()> {
pub fn http_service(home: Home, shutdown: CancellationToken) -> StreamableHttpService<Kanzo, LocalSessionManager> {
let ctx = Arc::new(Ctx { home, cwd: None, repos: Vec::new() });
let config = StreamableHttpServerConfig::default().disable_allowed_hosts().with_cancellation_token(shutdown);
+ // rmcp makes a server per session, and for some requests; the tool list is built once.
+ let tool_router = Kanzo::tools();
StreamableHttpService::new(
- move || Ok(Kanzo { ctx: ctx.clone(), tool_router: Kanzo::tools() }),
+ move || Ok(Kanzo { ctx: ctx.clone(), tool_router: tool_router.clone() }),
Default::default(),
config,
)
@@ -264,17 +267,23 @@ impl Kanzo {
return Ok("No projects yet. Create one with create_project.".into());
}
let here = projects.iter().find(|p| p.repos.iter().any(|r| ctx.repos.contains(r)));
- Ok(projects
- .iter()
- .map(|p| {
- let name = if p.name == p.slug { String::new() } else { format!(" \"{}\"", p.name) };
- let repo =
- if p.repos.is_empty() { String::new() } else { format!(" ({})", p.repos.join(", ")) };
- let mark = if here.is_some_and(|h| h.id == p.id) { " <- current repo" } else { "" };
- format!("{}{name}{repo}: {} open of {}{mark}", p.slug, p.open, p.total)
- })
- .collect::<Vec<_>>()
- .join("\n"))
+ let mut out = String::new();
+ for p in &projects {
+ out.push_str(&p.slug);
+ if p.name != p.slug {
+ let _ = write!(out, " \"{}\"", p.name);
+ }
+ if !p.repos.is_empty() {
+ let _ = write!(out, " ({})", p.repos.join(", "));
+ }
+ let _ = write!(out, ": {} open of {}", p.open, p.total);
+ if here.is_some_and(|h| h.id == p.id) {
+ out.push_str(" <- current repo");
+ }
+ out.push('\n');
+ }
+ out.pop();
+ Ok(out)
})
.await)
}
@@ -310,51 +319,48 @@ impl Kanzo {
let all = args.project.as_deref().is_some_and(|p| p.trim().eq_ignore_ascii_case("all"));
let project = if all { None } else { Some(ctx.project(store, args.project.as_deref())?) };
let status = args.status.as_deref().map(str::trim).filter(|s| !s.is_empty());
- let mut tasks = match status {
- Some("all") => store.list_tasks(project.as_ref().map(|p| p.id), None)?,
+ let only = match status {
+ Some("all") | None => None,
+ Some(s) if store.statuses().iter().any(|x| x == s) => Some(s),
Some(s) => {
- if !store.statuses().iter().any(|x| x == s) {
- return Err(Error::Invalid(format!(
- "unknown status {s:?}; use one of: {}, or all",
- store.statuses().join(", ")
- )));
- }
- store.list_tasks(project.as_ref().map(|p| p.id), Some(s))?
+ return Err(Error::Invalid(format!(
+ "unknown status {s:?}; use one of: {}, or all",
+ store.statuses().join(", ")
+ )));
}
- None => store.list_tasks(project.as_ref().map(|p| p.id), None)?,
};
- let done = store.statuses().last().cloned().unwrap_or_default();
// Done tasks only pile up: without a status leave them out, with one keep
- // the newest. They run oldest to newest, so drop from the front.
+ // the newest.
let keep = if status.is_none() { 0 } else { DONE_LISTED };
- let mut hidden = tasks.iter().filter(|t| t.status == done).count().saturating_sub(keep);
- let total_hidden = hidden;
- tasks.retain(|t| {
- let old = hidden > 0 && t.status == done;
- hidden -= usize::from(old);
- !old
- });
- let hidden = total_hidden;
+ let (tasks, hidden) =
+ store.list_tasks_keeping_done(project.as_ref().map(|p| p.id), only, Some(keep))?;
+ let done = store.statuses().last().map_or("", String::as_str);
+ let mut out = String::new();
// Tasks for a person are left out: agents leave them alone.
- let people = tasks.iter().filter(|t| t.human).count();
- tasks.retain(|t| !t.human);
- let scope = project.as_ref().map_or("any project".to_string(), |p| p.slug.clone());
- let mut out: Vec<String> = tasks.iter().map(task_line).collect();
+ let mut people = 0;
+ for t in &tasks {
+ if t.human {
+ people += 1;
+ } else {
+ task_line(&mut out, t);
+ out.push('\n');
+ }
+ }
if out.is_empty() {
- out.push(format!("No tasks in {scope}."));
+ let scope = project.as_ref().map_or("any project", |p| p.slug.as_str());
+ let _ = writeln!(out, "No tasks in {scope}.");
}
if people > 0 {
- out.push(format!(
- "({people} human {} not shown: for the user, not for agents)",
- plural(people, "task")
- ));
+ let tasks = if people == 1 { "task" } else { "tasks" };
+ let _ = writeln!(out, "({people} human {tasks} not shown: for the user, not for agents)");
}
if hidden > 0 && status.is_none() {
- out.push(format!("({hidden} {done} not shown; pass status \"{done}\" or \"all\")"));
+ let _ = writeln!(out, "({hidden} {done} not shown; pass status \"{done}\" or \"all\")");
} else if hidden > 0 {
- out.push(format!("({hidden} older {done} not shown)"));
+ let _ = writeln!(out, "({hidden} older {done} not shown)");
}
- Ok(out.join("\n"))
+ out.pop();
+ Ok(out)
})
.await)
}
@@ -474,30 +480,24 @@ impl ServerHandler for Kanzo {
}
}
-/// `2026-10-25T09:30:00Z` -> `2026-10-25 09:30 UTC`.
-pub(crate) fn short_time(ts: &str) -> String {
- match (ts.get(..10), ts.get(11..16)) {
- (Some(d), Some(t)) => format!("{d} {t} UTC"),
- _ => ts.to_string(),
+/// `api#12 [todo] Fix login {bug} (2 comments)`.
+fn task_line(out: &mut String, t: &Task) {
+ let _ = write!(out, "{}#{} [{}] {}", t.project, t.id, t.status, t.title);
+ write_tags(out, t);
+ match t.comments {
+ 0 => {}
+ 1 => out.push_str(" (1 comment)"),
+ n => {
+ let _ = write!(out, " ({n} comments)");
+ }
}
}
-fn task_line(t: &Task) -> String {
- let comments = match t.comments {
- 0 => String::new(),
- 1 => " (1 comment)".into(),
- n => format!(" ({n} comments)"),
- };
- format!("{} [{}] {}{}{comments}", t.key(), t.status, t.title, tag_list(t))
-}
-
-fn plural(n: usize, word: &str) -> String {
- if n == 1 { word.to_string() } else { format!("{word}s") }
-}
-
/// ` {bug, ui}`, or nothing without tags.
-fn tag_list(t: &Task) -> String {
- if t.tags.is_empty() { String::new() } else { format!(" {{{}}}", t.tags.join(", ")) }
+fn write_tags(out: &mut String, t: &Task) {
+ if !t.tags.is_empty() {
+ let _ = write!(out, " {{{}}}", t.tags.join(", "));
+ }
}
/// A task in full: description, comments, and the paths of its images, which agents can open.
@@ -509,31 +509,37 @@ fn task_detail(ctx: &Ctx, store: &Store, t: &Task) -> store::Result<String> {
images.iter().filter(|i| i.comment_id == comment).map(|i| dir.join(&i.file).display().to_string()).collect()
};
let (created, updated) = (short_time(&t.created_at), short_time(&t.updated_at));
+ let mut out = format!("{}#{} {}", t.project, t.id, t.title);
+ write_tags(&mut out, t);
+ let _ = write!(out, "\nstatus: {}", t.status);
+ if t.human {
+ out.push_str(", human: for the user, not for agents");
+ }
+ let _ = write!(out, ", created {created}");
// The update time only when it says something the creation time does not.
- let updated = if updated == created { String::new() } else { format!(", updated {updated}") };
- let human = if t.human { ", human: for the user, not for agents" } else { "" };
- let mut out =
- format!("{} {}{}\nstatus: {}{human}, created {created}{updated}\n", t.key(), t.title, tag_list(t), t.status);
+ if updated != created {
+ let _ = write!(out, ", updated {updated}");
+ }
+ out.push('\n');
if !t.description.is_empty() {
- out.push('\n');
- out.push_str(&t.description);
- out.push('\n');
+ let _ = writeln!(out, "\n{}", t.description);
}
let own = paths(None);
if !own.is_empty() {
- out.push_str(&format!("\nImages: {}\n", own.join(", ")));
+ let _ = writeln!(out, "\nImages: {}", own.join(", "));
}
if !comments.is_empty() {
- out.push_str(&format!("\nComments ({}):\n", comments.len()));
+ let _ = writeln!(out, "\nComments ({}):", comments.len());
for c in &comments {
+ let _ = write!(out, "- {}, {}: {}", c.author, short_time(&c.created_at), c.body);
let attached = paths(Some(c.id));
- let mut text = c.body.clone();
if !attached.is_empty() {
- let sep = if text.is_empty() { "" } else { " " };
- text.push_str(&format!("{sep}[images: {}]", attached.join(", ")));
+ let sep = if c.body.is_empty() { "" } else { " " };
+ let _ = write!(out, "{sep}[images: {}]", attached.join(", "));
}
- out.push_str(&format!("- {}, {}: {text}\n", c.author, short_time(&c.created_at)));
+ out.push('\n');
}
}
- Ok(out.trim_end().to_string())
+ out.truncate(out.trim_end().len());
+ Ok(out)
}
diff --git a/src/store.rs b/src/store.rs
index c7e2d35..1157a21 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -52,7 +52,7 @@ const MIGRATIONS: &[&str] = &[
];
/// The colours a project can be given; the board maps each name to a shade.
-pub const PROJECT_COLORS: &[&str] = &["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"];
+const PROJECT_COLORS: &[&str] = &["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"];
const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";
@@ -416,7 +416,7 @@ impl Store {
/// Renames a project. Its slug, and so its task keys like api#12, stay.
pub fn rename_project(&self, slug: &str, name: &str) -> Result<Project> {
- let name = name.split_whitespace().collect::<Vec<_>>().join(" ");
+ let name = squash(name);
if name.is_empty() {
return Err(Error::Invalid("project name is empty".into()));
}
@@ -467,16 +467,45 @@ impl Store {
/// Tasks in board order: by column as configured, then by position.
/// Tasks whose status is no longer in the config sort last.
pub fn list_tasks(&self, project_id: Option<i64>, status: Option<&str>) -> Result<Vec<Task>> {
+ Ok(self.list_tasks_keeping_done(project_id, status, None)?.0)
+ }
+
+ /// `list_tasks`, but of the done column, which only grows, just the newest `keep_done`
+ /// tasks, read from the database without the rest; also says how many were left out.
+ pub fn list_tasks_keeping_done(
+ &self,
+ project_id: Option<i64>,
+ status: Option<&str>,
+ keep_done: Option<usize>,
+ ) -> Result<(Vec<Task>, usize)> {
+ let done = self.done_status();
+ // SQLite reads a negative LIMIT as no limit.
+ let limit = keep_done.map_or(-1, |n| n as i64);
let sql = format!(
- "{} WHERE (?1 IS NULL OR t.project_id = ?1) AND (?2 IS NULL OR t.status = ?2) ORDER BY t.position",
+ "{} WHERE (?1 IS NULL OR t.project_id = ?1) AND (?2 IS NULL OR t.status = ?2)
+ AND (t.status <> ?3 OR t.id IN (SELECT id FROM tasks WHERE status = ?3
+ AND (?1 IS NULL OR project_id = ?1) ORDER BY position DESC LIMIT ?4))
+ ORDER BY t.position",
Self::TASK_SELECT
);
let mut stmt = self.conn.prepare(&sql)?;
- let mut tasks: Vec<Task> =
- stmt.query_map(params![project_id, status], Self::task_row)?.collect::<rusqlite::Result<_>>()?;
+ let mut tasks: Vec<Task> = stmt
+ .query_map(params![project_id, status, done, limit], Self::task_row)?
+ .collect::<rusqlite::Result<_>>()?;
let column = |t: &Task| self.statuses.iter().position(|s| *s == t.status).unwrap_or(usize::MAX);
tasks.sort_by_key(column);
- Ok(tasks)
+ let hidden = match keep_done {
+ Some(keep) if status.is_none_or(|s| s == done) => {
+ let all: i64 = self.conn.query_row(
+ "SELECT count(*) FROM tasks WHERE status = ?1 AND (?2 IS NULL OR project_id = ?2)",
+ params![done, project_id],
+ |r| r.get(0),
+ )?;
+ usize::try_from(all).unwrap_or(0).saturating_sub(keep)
+ }
+ _ => 0,
+ };
+ Ok((tasks, hidden))
}
/// Tasks of any project whose key, title, description, tags or project hold every
@@ -612,18 +641,19 @@ impl Store {
self.write(|c| {
let current = self.get_task(id)?;
let before = before.filter(|b| *b != id);
- let anchor: Option<f64> = match before {
+ // The task to go above, with its position, if it's in that column.
+ let anchor: Option<(i64, f64)> = match before {
Some(b) => c
.query_row("SELECT position FROM tasks WHERE id = ?1 AND status = ?2", params![b, status], |r| {
r.get(0)
})
- .optional()?,
+ .optional()?
+ .map(|p| (b, p)),
None => None,
};
let position = match anchor {
None => Self::end_of_column(c, status, id)?,
- Some(mut next) => {
- let before = before.expect("anchor comes from before");
+ Some((before, mut next)) => {
let prev_of = |next: f64| -> Result<Option<f64>> {
Ok(c.query_row(
"SELECT max(position) FROM tasks WHERE status = ?1 AND position < ?2 AND id <> ?3",
@@ -659,8 +689,9 @@ impl Store {
.prepare("SELECT id FROM tasks WHERE status = ?1 ORDER BY position")?
.query_map([status], |r| r.get(0))?
.collect::<rusqlite::Result<_>>()?;
+ let mut update = c.prepare("UPDATE tasks SET position = ?1 WHERE id = ?2")?;
for (i, id) in ids.iter().enumerate() {
- c.execute("UPDATE tasks SET position = ?1 WHERE id = ?2", params![(i + 1) as f64, id])?;
+ update.execute(params![(i + 1) as f64, id])?;
}
Ok(())
}
@@ -704,12 +735,14 @@ impl Store {
let mut stmt = self.conn.prepare_cached(
"SELECT id, task_id, author, body, created_at FROM comments WHERE task_id = ?1 ORDER BY id",
)?;
- let rows = stmt.query_map([task_id], |r| {
- Ok(Comment { id: r.get(0)?, task_id: r.get(1)?, author: r.get(2)?, body: r.get(3)?, created_at: r.get(4)? })
- })?;
+ let rows = stmt.query_map([task_id], Self::comment_row)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
+ fn comment_row(r: &Row) -> rusqlite::Result<Comment> {
+ Ok(Comment { id: r.get(0)?, task_id: r.get(1)?, author: r.get(2)?, body: r.get(3)?, created_at: r.get(4)? })
+ }
+
/// Adds a comment, with the images (files already in `images/`) attached to it.
/// A comment needs text, an image, or both.
pub fn add_comment(&self, task_id: i64, author: &str, body: &str, images: &[String]) -> Result<Comment> {
@@ -731,11 +764,9 @@ impl Store {
params![task_id, author, body],
)?;
let id = c.last_insert_rowid();
+ let mut insert = c.prepare("INSERT INTO images (task_id, comment_id, file) VALUES (?1, ?2, ?3)")?;
for file in images {
- c.execute(
- "INSERT INTO images (task_id, comment_id, file) VALUES (?1, ?2, ?3)",
- params![task_id, id, file],
- )?;
+ insert.execute(params![task_id, id, file])?;
}
Ok(id)
})?;
@@ -744,15 +775,11 @@ impl Store {
fn get_comment(&self, id: i64) -> Result<Comment> {
self.conn
- .query_row("SELECT id, task_id, author, body, created_at FROM comments WHERE id = ?1", [id], |r| {
- Ok(Comment {
- id: r.get(0)?,
- task_id: r.get(1)?,
- author: r.get(2)?,
- body: r.get(3)?,
- created_at: r.get(4)?,
- })
- })
+ .query_row(
+ "SELECT id, task_id, author, body, created_at FROM comments WHERE id = ?1",
+ [id],
+ Self::comment_row,
+ )
.optional()?
.ok_or_else(|| Error::NotFound(format!("no comment {id}")))
}
@@ -781,19 +808,19 @@ impl Store {
let mut stmt = self
.conn
.prepare_cached("SELECT id, task_id, comment_id, file FROM images WHERE task_id = ?1 ORDER BY id")?;
- let rows = stmt.query_map([task_id], |r| {
- Ok(Image { id: r.get(0)?, task_id: r.get(1)?, comment_id: r.get(2)?, file: r.get(3)? })
- })?;
+ let rows = stmt.query_map([task_id], Self::image_row)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
+ fn image_row(r: &Row) -> rusqlite::Result<Image> {
+ Ok(Image { id: r.get(0)?, task_id: r.get(1)?, comment_id: r.get(2)?, file: r.get(3)? })
+ }
+
/// Removes an image from its task or comment; returns it as it was.
pub fn delete_image(&self, id: i64) -> Result<Image> {
let image = self
.conn
- .query_row("SELECT id, task_id, comment_id, file FROM images WHERE id = ?1", [id], |r| {
- Ok(Image { id: r.get(0)?, task_id: r.get(1)?, comment_id: r.get(2)?, file: r.get(3)? })
- })
+ .query_row("SELECT id, task_id, comment_id, file FROM images WHERE id = ?1", [id], Self::image_row)
.optional()?
.ok_or_else(|| Error::NotFound(format!("no image {id}")))?;
self.conn.execute("DELETE FROM images WHERE id = ?1", [id])?;
@@ -856,11 +883,19 @@ fn valid_slug(s: &str) -> bool {
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
}
+/// `2026-10-25T09:30:00Z` -> `2026-10-25 09:30 UTC`.
+pub fn short_time(ts: &str) -> String {
+ match (ts.get(..10), ts.get(11..16)) {
+ (Some(d), Some(t)) => format!("{d} {t} UTC"),
+ _ => ts.to_string(),
+ }
+}
+
/// `" Bug, UI,bug ,, needs review"` -> `["bug", "ui", "needs review"]`.
-pub fn clean_tags(input: &str) -> Vec<String> {
+fn clean_tags(input: &str) -> Vec<String> {
let mut tags: Vec<String> = Vec::new();
for tag in input.split(',') {
- let tag = tag.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();
+ let tag = squash(tag).to_lowercase();
if !tag.is_empty() && !tags.contains(&tag) {
tags.push(tag);
}
@@ -872,8 +907,20 @@ fn clean_repo(repo: &str) -> Result<String> {
repo_from_url(repo).ok_or_else(|| Error::Invalid(format!("repo {:?} should look like owner/repo", repo.trim())))
}
+/// `" a b "` -> `"a b"`: words joined by single spaces.
+fn squash(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for word in s.split_whitespace() {
+ if !out.is_empty() {
+ out.push(' ');
+ }
+ out.push_str(word);
+ }
+ out
+}
+
fn clean_title(title: &str) -> Result<String> {
- let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
+ let title = squash(title);
if title.is_empty() {
return Err(Error::Invalid("task title is empty".into()));
}
@@ -881,7 +928,7 @@ fn clean_title(title: &str) -> Result<String> {
}
/// Splits `api#12`, `#12` or `12` into an optional project slug and the task id.
-pub fn parse_task_key(key: &str) -> Result<(Option<String>, i64)> {
+fn parse_task_key(key: &str) -> Result<(Option<String>, i64)> {
let key = key.trim();
let (slug, num) = match key.rsplit_once('#') {
Some((s, n)) => (Some(s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()), n),
@@ -943,6 +990,24 @@ mod tests {
assert_eq!(v, MIGRATIONS.len().to_string());
}
+ #[test]
+ fn keeps_only_the_newest_done_tasks() {
+ let (_dir, s) = store();
+ let p = s.create_project("api", "", None).unwrap();
+ s.create_task(p.id, "open", "").unwrap();
+ for title in ["d1", "d2", "d3", "d4"] {
+ let t = s.create_task(p.id, title, "").unwrap();
+ s.move_task(t.id, "done", None).unwrap();
+ }
+ let (tasks, hidden) = s.list_tasks_keeping_done(None, None, Some(2)).unwrap();
+ assert_eq!((titles(&tasks), hidden), (vec!["open", "d3", "d4"], 2));
+ let (tasks, hidden) = s.list_tasks_keeping_done(Some(p.id), Some("done"), Some(0)).unwrap();
+ assert_eq!((tasks.len(), hidden), (0, 4));
+ assert_eq!(s.list_tasks_keeping_done(None, Some("todo"), Some(0)).unwrap().1, 0);
+ let (all, hidden) = s.list_tasks_keeping_done(None, None, None).unwrap();
+ assert_eq!((titles(&all), hidden), (vec!["open", "d1", "d2", "d3", "d4"], 0));
+ }
+
#[test]
fn opens_a_board_from_a_newer_kanzo_when_it_can() {
let (_dir, s) = store();
diff --git a/src/sync.rs b/src/sync.rs
index cbfe3eb..429464d 100644
--- a/src/sync.rs
+++ b/src/sync.rs
@@ -26,10 +26,11 @@ impl std::fmt::Display for Diverged {
}
}
+impl std::error::Error for Diverged {}
+
/// The URL of the repo the board syncs with, or `None` before it's set up.
pub fn remote_url(home: &Home) -> Option<String> {
- let remote = remote_name(&home.dir).ok()??;
- git(&home.dir, false, &["remote", "get-url", &remote]).ok()
+ remote(&home.dir).ok()?.map(|(_, url)| url)
}
/// Points the board at the git repo `url`, once this machine can reach it: the first
@@ -62,9 +63,10 @@ pub fn set_remote(home: &Home, url: &str, prompt: bool) -> Result<String> {
head.lines().find_map(|l| l.strip_prefix("ref: refs/heads/")?.split('\t').next()).unwrap_or("main");
git(dir, prompt, &["init", "--quiet", "--initial-branch", branch])?;
}
- if remote_url(home).as_deref() != Some(url.as_str()) {
+ let current = remote(dir)?;
+ if current.as_ref().map(|(_, u)| u.as_str()) != Some(url.as_str()) {
// Removing the old remote forgets its branches, so the next sync starts afresh.
- if let Some(old) = remote_name(dir)? {
+ if let Some((old, _)) = current {
git(dir, prompt, &["remote", "remove", &old])?;
}
git(dir, prompt, &["remote", "add", "origin", &url])?;
@@ -104,17 +106,29 @@ fn candidates(url: &str) -> Vec<String> {
vec![format!("[email protected]:{repo}.git"), format!("https://github.com/{repo}.git")]
}
-/// The remote the board syncs with: `origin`, or the only one there is.
-fn remote_name(dir: &Path) -> Result<Option<String>> {
+/// The remote the board syncs with, `origin` or the only one there is, and its URL;
+/// `None` before sync is set up. One `git remote -v` gives both.
+fn remote(dir: &Path) -> Result<Option<(String, String)>> {
if !dir.join(".git").exists() {
return Ok(None);
}
- let remotes = git(dir, false, &["remote"])?;
- Ok(remotes.lines().find(|r| *r == "origin").or_else(|| remotes.lines().next()).map(String::from))
+ let out = git(dir, false, &["remote", "-v"])?;
+ let mut found = None;
+ for line in out.lines() {
+ let Some((name, url)) = line.split_once('\t').and_then(|(n, rest)| Some((n, rest.strip_suffix(" (fetch)")?)))
+ else {
+ continue;
+ };
+ if name == "origin" || found.is_none() {
+ found = Some((name.to_string(), url.to_string()));
+ }
+ if name == "origin" {
+ break;
+ }
+ }
+ Ok(found)
}
-impl std::error::Error for Diverged {}
-
/// Commits the board, then pulls or pushes it, and says what it did. With `prompt`
/// false, as from the board's button, git never waits for a password; a missing
/// credential fails with git's message instead.
@@ -122,7 +136,7 @@ pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {
let dir = &home.dir;
let git = |args: &[&str]| git(dir, prompt, args);
let git_ok = |args: &[&str]| git_ok(dir, prompt, args);
- let Some(remote) = remote_name(dir)? else {
+ let Some((remote, _)) = remote(dir)? else {
bail!(
"Sync isn't set up yet. Create an empty private repo, on GitHub for example, then press the \
sync button on the board and paste its URL, or run:\n kanzo sync --repo <url>"
@@ -182,9 +196,9 @@ pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {
}
let counts = git(&["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])?;
- let (ahead, behind) = match counts.split_whitespace().collect::<Vec<_>>()[..] {
- [a, b] => (a.parse::<u32>()?, b.parse::<u32>()?),
- _ => bail!("unexpected git output: {counts}"),
+ let mut numbers = counts.split_whitespace().map(str::parse::<u32>);
+ let (Some(Ok(ahead)), Some(Ok(behind)), None) = (numbers.next(), numbers.next(), numbers.next()) else {
+ bail!("unexpected git output: {counts}");
};
Ok(match (ahead, behind, keep) {
diff --git a/src/update.rs b/src/update.rs
index 0e0393e..49a1c73 100644
--- a/src/update.rs
+++ b/src/update.rs
@@ -73,7 +73,7 @@ pub fn install() -> Result<PathBuf, String> {
.env("KANZO_INSTALL_DIR", &dir)
.env("KANZO_NO_MODIFY_PATH", "1")
.stdin(Stdio::piped())
- .stdout(Stdio::piped())
+ .stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("cannot run the installer: {e}"))?;
diff --git a/src/web.rs b/src/web.rs
index 1853b33..3d05a33 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -190,12 +190,12 @@ impl Guard {
if port.is_some_and(|p| p.parse() != Ok(self.port)) {
return false;
}
- let name = name.trim_start_matches('[').trim_end_matches(']').trim_end_matches('.').to_ascii_lowercase();
+ let name = name.trim_start_matches('[').trim_end_matches(']').trim_end_matches('.');
let ip = name.parse::<IpAddr>().ok();
- if name == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) {
+ if name.eq_ignore_ascii_case("localhost") || ip.is_some_and(|ip| ip.is_loopback()) {
return true;
}
- self.lan && (ip.is_some() || self.names.contains(&name))
+ self.lan && (ip.is_some() || self.names.iter().any(|n| n.eq_ignore_ascii_case(name)))
}
}
@@ -206,7 +206,13 @@ async fn protect(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> R
let ok = {
let header = |name| req.headers().get(name).and_then(|h: &HeaderValue| h.to_str().ok());
let host = header(header::HOST).unwrap_or("");
- guard.allows(host) && header(header::ORIGIN).is_none_or(|o| o.eq_ignore_ascii_case(&format!("http://{host}")))
+ // The Origin a page from this board sends: http:// and the same host.
+ let same_origin = |o: &str| {
+ o.len() == host.len() + 7
+ && o.as_bytes()[..7].eq_ignore_ascii_case(b"http://")
+ && o.as_bytes()[7..].eq_ignore_ascii_case(host.as_bytes())
+ };
+ guard.allows(host) && header(header::ORIGIN).is_none_or(same_origin)
};
let mut res = if ok {
next.run(req).await
@@ -253,8 +259,13 @@ fn change_token(home: &Home, s: &Store) -> store::Result<String> {
Ok(format!("{}-{}", s.changes()?, home.db_identity()))
}
+#[derive(Serialize)]
+struct Changes {
+ changes: String,
+}
+
async fn changes(State(home): Shared) -> Response {
- with_store(home, |h, s| Ok(json!({ "changes": change_token(h, s)? }))).await
+ with_store(home, |h, s| Ok(Changes { changes: change_token(h, s)? })).await
}
/// Done tasks the board gets unless it asks for all: the newest, which are all it shows.
@@ -268,33 +279,33 @@ struct BoardQuery {
done: Option<String>,
}
+/// The whole board, serialized straight from the store's rows.
+#[derive(Serialize)]
+struct Board {
+ changes: String,
+ done_hidden: usize,
+ projects: Vec<store::Project>,
+ statuses: Vec<String>,
+ tasks: Vec<store::Task>,
+ version: &'static str,
+}
+
async fn board(State(home): Shared, Query(q): Query<BoardQuery>) -> Response {
with_store(home, move |h, s| {
let project = match q.project.as_deref().filter(|p| !p.is_empty() && *p != "all") {
Some(slug) => Some(s.find_project(slug)?),
None => None,
};
- let mut tasks = s.list_tasks(project.map(|p| p.id), None)?;
- let done = s.statuses().last().expect("config has at least two statuses");
- let mut done_hidden = 0;
- if q.done.as_deref() != Some("all") {
- // Done tasks run oldest to newest; drop the oldest.
- done_hidden = tasks.iter().filter(|t| t.status == *done).count().saturating_sub(DONE_SHOWN);
- let mut drop = done_hidden;
- tasks.retain(|t| {
- let old = drop > 0 && t.status == *done;
- drop -= usize::from(old);
- !old
- });
- }
- Ok(json!({
- "statuses": s.statuses(),
- "projects": s.list_projects()?,
- "tasks": tasks,
- "done_hidden": done_hidden,
- "version": update::CURRENT,
- "changes": change_token(h, s)?,
- }))
+ let keep_done = (q.done.as_deref() != Some("all")).then_some(DONE_SHOWN);
+ let (tasks, done_hidden) = s.list_tasks_keeping_done(project.map(|p| p.id), None, keep_done)?;
+ Ok(Board {
+ changes: change_token(h, s)?,
+ done_hidden,
+ projects: s.list_projects()?,
+ statuses: s.statuses().to_vec(),
+ tasks,
+ version: update::CURRENT,
+ })
})
.await
}
@@ -330,14 +341,14 @@ struct ProjectPatch {
async fn update_project(State(home): Shared, Path(slug): Path<String>, Json(p): Json<ProjectPatch>) -> Response {
with_store(home, move |_, s| {
- let mut project = s.find_project(&slug)?;
+ let mut project = None;
if let Some(name) = &p.name {
- project = s.rename_project(&slug, name)?;
+ project = Some(s.rename_project(&slug, name)?);
}
if let Some(color) = &p.color {
- project = s.set_project_color(&slug, color)?;
+ project = Some(s.set_project_color(&slug, color)?);
}
- Ok(project)
+ project.map_or_else(|| s.find_project(&slug), Ok)
})
.await
}
@@ -379,12 +390,16 @@ async fn create_task(State(home): Shared, Json(t): Json<NewTask>) -> Response {
.await
}
+#[derive(Serialize)]
+struct TaskReply {
+ comments: Vec<store::Comment>,
+ images: Vec<store::Image>,
+ task: store::Task,
+}
+
async fn get_task(State(home): Shared, Path(id): Path<i64>) -> Response {
with_store(home, move |_, s| {
- let task = s.get_task(id)?;
- let comments = s.list_comments(id)?;
- let images = s.list_images(id)?;
- Ok(json!({ "task": task, "comments": comments, "images": images }))
+ Ok(TaskReply { comments: s.list_comments(id)?, images: s.list_images(id)?, task: s.get_task(id)? })
})
.await
}