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.

Attach pasted images to tasks and comments, like ChatGPT

emanuele-em33c580c31654
diff --git a/README.md b/README.md
index d354026..f844077 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@ Every command takes `--home <dir>` to use another data folder.
`n` adds a task, `/` searches, `Tab` moves to the description, `⌘↵` saves and closes, `Esc` cancels.
-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.
+Paste or drop an image into a task or a comment to attach it, as in ChatGPT. Agents get its file path and can open it.
When a new version is out, the sidebar offers it: one click installs it and restarts the board.
diff --git a/src/app.js b/src/app.js
index dd7c95b..8721043 100644
--- a/src/app.js
+++ b/src/app.js
@@ -623,7 +623,8 @@ async function openTask(id) {
document.querySelectorAll(".card.open").forEach((c) => c.classList.remove("open"));
document.querySelector(`.card[data-id="${id}"]`)?.classList.add("open");
$("#p-comment").value = "";
- $("#p-send").disabled = true;
+ pending = [];
+ renderPending();
fit($("#p-comment"));
updateHash();
await refreshTask();
@@ -660,7 +661,7 @@ async function refreshTask() {
}
// Another task may have taken the panel meanwhile.
if (state.task !== id) return;
- const { task, comments } = data;
+ const { task, comments, images } = data;
panelTask = task;
$("#p-key").textContent = key(task);
// Never overwrite what is being typed or picked.
@@ -676,14 +677,20 @@ async function refreshTask() {
$("#p-created").replaceChildren(timeEl(task.created_at));
$("#p-updated").replaceChildren(timeEl(task.updated_at));
$("#p-comment-count").textContent = comments.length ? String(comments.length) : "";
+ $("#p-images").replaceChildren(...images.filter((i) => i.comment_id === null).map((i) =>
+ thumb(i.file, async () => {
+ try { await api("DELETE", `/images/${i.id}`); refreshTask(); } catch (err) { toast(err.message); }
+ })));
$("#p-comments").replaceChildren(...comments.map((c) => {
const body = el("div", { class: "md" });
body.innerHTML = markdown(c.body);
+ const attached = images.filter((i) => i.comment_id === c.id);
return el("div", { class: "comment" },
el("div", { class: "who" }, el("b", {}, c.author), " · ", timeEl(c.created_at),
el("button", { class: "remove", title: "Delete comment", "aria-label": "Delete comment",
onclick: () => deleteComment(c) }, icon("trash"))),
- body);
+ c.body ? body : null,
+ attached.length ? el("div", { class: "thumbs" }, attached.map((i) => thumb(i.file))) : null);
}));
}
@@ -764,33 +771,78 @@ $("#p-desc").addEventListener("blur", (e) => {
$("#p-status").addEventListener("change", (e) => patchTask({ status: e.target.value }));
-// Pasting an image saves it in the data folder and types its path, the way a terminal
-// does, so agents can open it. Text pastes are left alone.
-async function pasteImages(e) {
- const data = e.clipboardData;
- const fromItems = data && data.items ? [...data.items].filter((i) => i.kind === "file").map((i) => i.getAsFile()) : [];
- const images = (fromItems.length ? fromItems : [...((data && data.files) || [])]).filter((f) => f && f.type.startsWith("image/"));
- if (!images.length) return;
- e.preventDefault();
- const field = e.target;
+// ---------- images ----------
+
+// Pasting or dropping an image attaches it, as in ChatGPT: to the task from the title or
+// the description, to the comment being written from the comment box. Text is left alone.
+let pending = []; // images waiting in the comment box, by file name
+
+function imagesIn(transfer) {
+ if (!transfer) return [];
+ const fromItems = transfer.items ? [...transfer.items].filter((i) => i.kind === "file").map((i) => i.getAsFile()) : [];
+ return (fromItems.length ? fromItems : [...(transfer.files || [])]).filter((f) => f && f.type.startsWith("image/"));
+}
+
+async function uploadImage(image) {
+ const res = await fetch("/api/images", { method: "POST", headers: { "Content-Type": image.type }, body: image });
+ const reply = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(reply.error || res.statusText);
+ return reply.file;
+}
+
+async function attachImages(images, toComment) {
+ if (!panelTask) return;
+ const task = panelTask.id;
try {
- const paths = [];
for (const image of images) {
- const res = await fetch("/api/images", { method: "POST", headers: { "Content-Type": image.type }, body: image });
- const reply = await res.json().catch(() => ({}));
- if (!res.ok) throw new Error(reply.error || res.statusText);
- paths.push(reply.path);
+ const file = await uploadImage(image);
+ if (toComment) {
+ pending.push(file);
+ renderPending();
+ } else {
+ await api("POST", `/tasks/${task}/images`, { file });
+ if (fresh === task) fresh = null;
+ }
}
- field.focus();
- // Keep the path apart from the words around it.
- const { value, selectionStart: start, selectionEnd: end } = field;
- const before = start > 0 && !/\s/.test(value[start - 1]) ? " " : "";
- const after = end < value.length && !/\s/.test(value[end]) ? " " : "";
- field.setRangeText(before + paths.join(" ") + after, start, end, "end");
- field.dispatchEvent(new Event("input"));
+ if (!toComment) refreshTask();
} catch (err) { toast(err.message); }
}
-for (const field of [$("#p-title"), $("#p-desc"), $("#p-comment")]) field.addEventListener("paste", pasteImages);
+
+// A thumbnail that opens the full image; with `onRemove`, an × to take it off.
+function thumb(file, onRemove) {
+ return el("div", { class: "thumb" },
+ el("a", { href: `/images/${file}`, target: "_blank", rel: "noopener" }, el("img", { src: `/images/${file}`, alt: "Attached image" })),
+ onRemove ? el("button", { type: "button", class: "remove-image", title: "Remove image", "aria-label": "Remove image", onclick: onRemove }, icon("close")) : null);
+}
+
+function renderPending() {
+ $("#p-pending").replaceChildren(...pending.map((file, i) => thumb(file, () => { pending.splice(i, 1); renderPending(); })));
+ $("#p-send").disabled = !$("#p-comment").value.trim() && !pending.length;
+}
+
+for (const field of [$("#p-title"), $("#p-desc"), $("#p-comment")]) {
+ field.addEventListener("paste", (e) => {
+ const images = imagesIn(e.clipboardData);
+ if (!images.length) return;
+ e.preventDefault();
+ attachImages(images, field.id === "p-comment");
+ });
+}
+for (const [zone, toComment] of [[$("#p-desc").closest(".section"), false], [$("#p-comment-form"), true]]) {
+ zone.addEventListener("dragover", (e) => {
+ if (!e.dataTransfer || ![...e.dataTransfer.types].includes("Files")) return;
+ e.preventDefault();
+ zone.classList.add("dropping");
+ });
+ zone.addEventListener("dragleave", (e) => { if (!zone.contains(e.relatedTarget)) zone.classList.remove("dropping"); });
+ zone.addEventListener("drop", (e) => {
+ zone.classList.remove("dropping");
+ const images = imagesIn(e.dataTransfer);
+ if (!images.length) return;
+ e.preventDefault();
+ attachImages(images, toComment);
+ });
+}
// Tags are typed comma-separated and tidied the way the server stores them.
const cleanTags = (text) => [...new Set(text.split(",").map((t) => t.trim().replace(/\s+/g, " ").toLowerCase()).filter(Boolean))];
@@ -808,19 +860,20 @@ $("#p-tags").addEventListener("blur", (e) => {
$("#p-comment-form").addEventListener("submit", async (e) => {
e.preventDefault();
const body = $("#p-comment").value.trim();
- if (!body || !panelTask) return;
+ if ((!body && !pending.length) || !panelTask) return;
try {
- await api("POST", `/tasks/${panelTask.id}/comments`, { body });
+ await api("POST", `/tasks/${panelTask.id}/comments`, { body, images: pending });
if (fresh === panelTask.id) fresh = null;
$("#p-comment").value = "";
- $("#p-send").disabled = true;
+ pending = [];
+ renderPending();
fit($("#p-comment"));
await refreshTask();
loadBoard();
} catch (err) { toast(err.message); }
});
// The send button is live only once there is something to send.
-$("#p-comment").addEventListener("input", (e) => { $("#p-send").disabled = !e.target.value.trim(); fit(e.target); });
+$("#p-comment").addEventListener("input", (e) => { $("#p-send").disabled = !e.target.value.trim() && !pending.length; fit(e.target); });
$("#p-comment").addEventListener("keydown", (e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); $("#p-comment-form").requestSubmit(); }
});
diff --git a/src/export.rs b/src/export.rs
index 4f7c9dd..57d3052 100644
--- a/src/export.rs
+++ b/src/export.rs
@@ -37,6 +37,8 @@ struct TaskOut {
title: String,
description: String,
tags: Vec<String>,
+ /// Paths of the images attached to the task and its comments.
+ images: Vec<String>,
status: String,
created_at: String,
updated_at: String,
@@ -44,13 +46,14 @@ struct TaskOut {
}
impl TaskOut {
- fn new(task: Task, comments: Vec<Comment>) -> Self {
+ fn new(task: Task, comments: Vec<Comment>, images: Vec<String>) -> Self {
Self {
key: task.key(),
id: task.id,
title: task.title,
description: task.description,
tags: task.tags,
+ images,
status: task.status,
created_at: task.created_at,
updated_at: task.updated_at,
@@ -61,7 +64,7 @@ impl TaskOut {
pub fn export(home: &Home, format: Format, project: Option<&str>, output: Option<&Path>) -> Result<()> {
let store = home.store()?;
- let board = collect(&store, project)?;
+ let board = collect(&store, project, &home.dir.join("images"))?;
let text = match format {
Format::Json => serde_json::to_string_pretty(&board)? + "\n",
Format::Markdown => markdown(&board),
@@ -77,7 +80,7 @@ pub fn export(home: &Home, format: Format, project: Option<&str>, output: Option
Ok(())
}
-fn collect(store: &Store, only: Option<&str>) -> Result<Board> {
+fn collect(store: &Store, only: Option<&str>, images: &Path) -> Result<Board> {
let projects = match only {
Some(slug) => vec![store.find_project(slug)?],
None => store.list_projects()?,
@@ -87,7 +90,8 @@ fn collect(store: &Store, only: Option<&str>) -> Result<Board> {
let mut tasks = Vec::new();
for task in store.list_tasks(Some(project.id), None)? {
let comments = store.list_comments(task.id)?;
- tasks.push(TaskOut::new(task, comments));
+ let paths = store.list_images(task.id)?.into_iter().map(|i| images.join(i.file).display().to_string());
+ tasks.push(TaskOut::new(task, comments, paths.collect()));
}
out.push(ProjectOut { project, tasks });
}
@@ -133,6 +137,9 @@ fn markdown(board: &Board) -> String {
if !t.tags.is_empty() {
let _ = writeln!(md, "Tags: {}.", t.tags.join(", "));
}
+ if !t.images.is_empty() {
+ let _ = writeln!(md, "Images: {}.", t.images.join(", "));
+ }
if !t.description.is_empty() {
let _ = write!(md, "\n{}\n", t.description);
}
@@ -162,11 +169,11 @@ mod tests {
let api = store.create_project("api", "API", Some("me/api")).unwrap();
store.create_project("web", "Web", None).unwrap();
let t = store.create_task(api.id, "Fix login", "Steps:\n1. log in").unwrap();
- store.add_comment(t.id, "claude-code", "Found it\nin auth.rs").unwrap();
+ store.add_comment(t.id, "claude-code", "Found it\nin auth.rs", &[]).unwrap();
let done = store.create_task(api.id, "Old work", "").unwrap();
store.move_task(done.id, "done", None).unwrap();
- let board = collect(&store, None).unwrap();
+ let board = collect(&store, None, Path::new("/k/images")).unwrap();
let md = markdown(&board);
assert!(md.contains("## API `api` ([me/api](https://github.com/me/api))"), "{md}");
assert!(md.contains("### todo\n\n#### api#1 Fix login"), "{md}");
@@ -181,8 +188,8 @@ mod tests {
assert_eq!(json["projects"][0]["tasks"][0]["key"], "api#1");
assert_eq!(json["projects"][0]["tasks"][0]["comments"][0]["author"], "claude-code");
- let only = collect(&store, Some("web")).unwrap();
+ let only = collect(&store, Some("web"), Path::new("/k/images")).unwrap();
assert_eq!(only.projects.len(), 1);
- assert!(collect(&store, Some("nope")).is_err());
+ assert!(collect(&store, Some("nope"), Path::new("/k/images")).is_err());
}
}
diff --git a/src/home.rs b/src/home.rs
index 213ebf2..97303ea 100644
--- a/src/home.rs
+++ b/src/home.rs
@@ -8,7 +8,7 @@ use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
-use crate::store::{self, Store};
+use crate::store::{self, ImagesOf, Store};
pub const DEFAULT_PORT: u16 = 4242;
@@ -165,6 +165,22 @@ impl Home {
Store::open(&self.db_path(), self.config.statuses.clone(), lock)
}
+ /// Runs `delete`, then deletes the image files of `of` that nothing uses any more:
+ /// the same image can be attached in several places, and is stored once.
+ pub fn deleting_images<T>(
+ &self,
+ store: &Store,
+ of: ImagesOf,
+ delete: impl FnOnce() -> store::Result<T>,
+ ) -> store::Result<T> {
+ let files = store.image_files(of)?;
+ let deleted = delete()?;
+ for file in store.unused_images(files)? {
+ let _ = fs::remove_file(self.dir.join("images").join(file));
+ }
+ Ok(deleted)
+ }
+
/// Blocks until no connection is open, and keeps new ones out until the file is dropped.
pub fn lock_exclusive(&self) -> Result<Option<File>> {
let lock = self.lock_file()?;
diff --git a/src/index.html b/src/index.html
index fcf8bdb..9275eb3 100644
--- a/src/index.html
+++ b/src/index.html
@@ -235,6 +235,24 @@ header .sub a:hover { color: var(--text); }
.comment .remove .icon svg { width: 14px; height: 14px; }
@media (hover: none) { .comment .remove { visibility: visible; } }
.comment .who b { color: var(--text); font-weight: 600; }
+/* Attached images: thumbnails that open the full image, with an × to remove. */
+.thumbs { display: flex; flex-wrap: wrap; gap: 8px; }
+.thumbs:empty { display: none; }
+#p-images { margin-top: 10px; }
+.composer .thumbs { padding: 12px 12px 0; }
+.comment .thumbs { margin-top: 6px; }
+.thumb { position: relative; width: 72px; height: 72px; border-radius: 12px; overflow: hidden; background: var(--field); flex: none; }
+.thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.thumb .remove-image {
+ position: absolute; top: 4px; right: 4px; width: 22px; height: 22px; padding: 4px; border: 0; border-radius: 50%;
+ background: rgba(0,0,0,.65); color: #fff; display: none;
+}
+.thumb:hover .remove-image, .thumb .remove-image:focus-visible { display: grid; place-items: center; }
+.thumb .remove-image .icon svg { width: 14px; height: 14px; }
+@media (hover: none) { .thumb .remove-image { display: grid; place-items: center; } }
+.section.dropping { background: var(--hover); border-radius: 12px; }
+.composer.dropping { background: var(--active); }
+
/* The comment box, with its send button inside like a chat composer. */
.composer { position: relative; margin-top: 6px; background: var(--field); border-radius: 20px; }
.composer textarea {
@@ -334,11 +352,13 @@ header .sub a:hover { color: var(--text); }
<div class="section">
<h3>Description</h3>
<textarea class="inline desc-input" id="p-desc" rows="1" placeholder="Add a description (Markdown)"></textarea>
+ <div class="thumbs" id="p-images"></div>
</div>
<div class="section">
<h3>Comments <span class="count" id="p-comment-count"></span></h3>
<div id="p-comments"></div>
<form class="composer" id="p-comment-form">
+ <div class="thumbs" id="p-pending"></div>
<textarea id="p-comment" rows="2" placeholder="Add a comment"></textarea>
<button class="send" id="p-send" type="submit" title="Send (⌘↵)" aria-label="Send comment" disabled><span class="icon" data-icon="send"></span></button>
</form>
diff --git a/src/mcp.rs b/src/mcp.rs
index 3a9b494..ba574d8 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -17,7 +17,7 @@ use serde::Deserialize;
use tokio_util::sync::CancellationToken;
use crate::home::Home;
-use crate::store::{self, Comment, Error, Project, Store, Task, TaskPatch};
+use crate::store::{self, Error, Project, Store, Task, TaskPatch};
/// The most done tasks list_tasks shows, newest first: an old board has thousands.
const DONE_LISTED: usize = 20;
@@ -348,13 +348,12 @@ impl Kanzo {
.await)
}
- #[tool(description = "Show a task with its description and comments.")]
+ #[tool(description = "Show a task with its description, comments and the paths of its images.")]
async fn get_task(&self, Parameters(args): Parameters<TaskArgs>) -> Result<CallToolResult, ErrorData> {
Ok(self
- .run(move |_, store| {
+ .run(move |ctx, store| {
let task = args.id.find(store)?;
- let comments = store.list_comments(task.id)?;
- Ok(task_detail(&task, &comments))
+ task_detail(ctx, store, &task)
})
.await)
}
@@ -410,7 +409,7 @@ impl Kanzo {
Ok(self
.run(move |_, store| {
let task = args.id.find(store)?;
- store.add_comment(task.id, &author, &args.body)?;
+ store.add_comment(task.id, &author, &args.body, &[])?;
Ok(format!("Comment added to {} as {author}.", task.key()))
})
.await)
@@ -425,10 +424,7 @@ 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())?) };
match store.next_task(project.as_ref().map(|p| p.id))? {
- Some(task) => {
- let comments = store.list_comments(task.id)?;
- Ok(format!("Moved to {}:\n{}", task.status, task_detail(&task, &comments)))
- }
+ Some(task) => Ok(format!("Moved to {}:\n{}", task.status, task_detail(ctx, store, &task)?)),
None => {
let scope = project.map_or("any project".into(), |p| p.slug);
Ok(format!("Nothing in {} for {scope}.", store.statuses()[0]))
@@ -438,12 +434,12 @@ impl Kanzo {
.await)
}
- #[tool(description = "Delete a task and its comments. This cannot be undone.")]
+ #[tool(description = "Delete a task with its comments and images. This cannot be undone.")]
async fn delete_task(&self, Parameters(args): Parameters<TaskArgs>) -> Result<CallToolResult, ErrorData> {
Ok(self
- .run(move |_, store| {
+ .run(move |ctx, store| {
let task = args.id.find(store)?;
- store.delete_task(task.id)?;
+ ctx.home.deleting_images(store, store::ImagesOf::Task(task.id), || store.delete_task(task.id))?;
let comments = match task.comments {
0 => String::new(),
1 => " and its comment".into(),
@@ -488,7 +484,14 @@ fn tag_list(t: &Task) -> String {
if t.tags.is_empty() { String::new() } else { format!(" {{{}}}", t.tags.join(", ")) }
}
-fn task_detail(t: &Task, comments: &[Comment]) -> String {
+/// A task in full: description, comments, and the paths of its images, which agents can open.
+fn task_detail(ctx: &Ctx, store: &Store, t: &Task) -> store::Result<String> {
+ let comments = store.list_comments(t.id)?;
+ let images = store.list_images(t.id)?;
+ let dir = ctx.home.dir.join("images");
+ let paths = |comment: Option<i64>| -> Vec<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));
// The update time only when it says something the creation time does not.
let updated = if updated == created { String::new() } else { format!(", updated {updated}") };
@@ -498,11 +501,21 @@ fn task_detail(t: &Task, comments: &[Comment]) -> String {
out.push_str(&t.description);
out.push('\n');
}
+ let own = paths(None);
+ if !own.is_empty() {
+ out.push_str(&format!("\nImages: {}\n", own.join(", ")));
+ }
if !comments.is_empty() {
out.push_str(&format!("\nComments ({}):\n", comments.len()));
- for c in comments {
- out.push_str(&format!("- {}, {}: {}\n", c.author, short_time(&c.created_at), c.body));
+ for c in &comments {
+ 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(", ")));
+ }
+ out.push_str(&format!("- {}, {}: {text}\n", c.author, short_time(&c.created_at)));
}
}
- out.trim_end().to_string()
+ Ok(out.trim_end().to_string())
}
diff --git a/src/store.rs b/src/store.rs
index baabf9e..a859a85 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -30,6 +30,17 @@ const MIGRATIONS: &[&str] = &[
UPDATE projects SET repo = NULL;
CREATE TRIGGER project_repos_insert AFTER INSERT ON project_repos BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;
CREATE TRIGGER project_repos_delete AFTER DELETE ON project_repos BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",
+ // 5: images attached to a task, or to one of its comments; the files are in images/.
+ "CREATE TABLE images (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
+ comment_id INTEGER REFERENCES comments(id) ON DELETE CASCADE,
+ file TEXT NOT NULL,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
+ );
+ CREATE INDEX images_by_task ON images(task_id);
+ CREATE TRIGGER images_insert AFTER INSERT ON images BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;
+ CREATE TRIGGER images_delete AFTER DELETE ON images BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",
];
/// The colours a project can be given; the board maps each name to a shade.
@@ -118,6 +129,16 @@ pub struct Comment {
pub created_at: String,
}
+/// An image attached to a task, or to one of its comments.
+#[derive(Debug, Clone, Serialize)]
+pub struct Image {
+ pub id: i64,
+ pub task_id: i64,
+ pub comment_id: Option<i64>,
+ /// Its file name in the data folder's `images/`, like `6fec521a01297ab5.png`.
+ pub file: String,
+}
+
/// Fields of a task to change; `None` leaves a field as it is.
#[derive(Debug, Default)]
pub struct TaskPatch {
@@ -630,21 +651,36 @@ impl Store {
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
- pub fn add_comment(&self, task_id: i64, author: &str, body: &str) -> Result<Comment> {
+ /// 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> {
let body = body.trim();
- if body.is_empty() {
+ if body.is_empty() && images.is_empty() {
return Err(Error::Invalid("comment body is empty".into()));
}
+ if let Some(bad) = images.iter().find(|f| !valid_image_file(f)) {
+ return Err(Error::Invalid(format!("{bad:?} is not an image Kanzo saved")));
+ }
let author = match author.trim() {
"" => "me",
a => a,
};
self.get_task(task_id)?;
- self.conn.execute(
- "INSERT INTO comments (task_id, author, body) VALUES (?1, ?2, ?3)",
- params![task_id, author, body],
- )?;
- self.get_comment(self.conn.last_insert_rowid())
+ let id = self.write(|c| {
+ c.execute(
+ "INSERT INTO comments (task_id, author, body) VALUES (?1, ?2, ?3)",
+ params![task_id, author, body],
+ )?;
+ let id = c.last_insert_rowid();
+ for file in images {
+ c.execute(
+ "INSERT INTO images (task_id, comment_id, file) VALUES (?1, ?2, ?3)",
+ params![task_id, id, file],
+ )?;
+ }
+ Ok(id)
+ })?;
+ self.get_comment(id)
}
fn get_comment(&self, id: i64) -> Result<Comment> {
@@ -668,6 +704,89 @@ impl Store {
self.conn.execute("DELETE FROM comments WHERE id = ?1", [id])?;
Ok(comment)
}
+
+ // Images
+
+ /// Attaches an image, already saved in `images/`, to a task.
+ pub fn add_image(&self, task_id: i64, file: &str) -> Result<Image> {
+ if !valid_image_file(file) {
+ return Err(Error::Invalid(format!("{file:?} is not an image Kanzo saved")));
+ }
+ self.get_task(task_id)?;
+ self.conn.execute("INSERT INTO images (task_id, file) VALUES (?1, ?2)", params![task_id, file])?;
+ Ok(Image { id: self.conn.last_insert_rowid(), task_id, comment_id: None, file: file.into() })
+ }
+
+ /// The images of a task and of its comments, oldest first.
+ pub fn list_images(&self, task_id: i64) -> Result<Vec<Image>> {
+ 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)? })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// 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)? })
+ })
+ .optional()?
+ .ok_or_else(|| Error::NotFound(format!("no image {id}")))?;
+ self.conn.execute("DELETE FROM images WHERE id = ?1", [id])?;
+ Ok(image)
+ }
+
+ /// The image files attached to one image, comment, task (with its comments) or project.
+ pub fn image_files(&self, of: ImagesOf) -> Result<Vec<String>> {
+ let (sql, id) = match of {
+ ImagesOf::Image(id) => ("SELECT file FROM images WHERE id = ?1", id),
+ ImagesOf::Comment(id) => ("SELECT DISTINCT file FROM images WHERE comment_id = ?1", id),
+ ImagesOf::Task(id) => ("SELECT DISTINCT file FROM images WHERE task_id = ?1", id),
+ ImagesOf::Project(id) => {
+ ("SELECT DISTINCT i.file FROM images i JOIN tasks t ON t.id = i.task_id WHERE t.project_id = ?1", id)
+ }
+ };
+ let mut stmt = self.conn.prepare_cached(sql)?;
+ let rows = stmt.query_map([id], |r| r.get(0))?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// Of `files`, those no task or comment uses any more.
+ pub fn unused_images(&self, files: Vec<String>) -> Result<Vec<String>> {
+ let mut used = self.conn.prepare_cached("SELECT EXISTS (SELECT 1 FROM images WHERE file = ?1)")?;
+ let mut unused = Vec::new();
+ for file in files {
+ if !used.query_row([&file], |r| r.get::<_, bool>(0))? {
+ unused.push(file);
+ }
+ }
+ Ok(unused)
+ }
+}
+
+/// Whose images `Store::image_files` lists.
+pub enum ImagesOf {
+ Image(i64),
+ Comment(i64),
+ Task(i64),
+ Project(i64),
+}
+
+/// The name Kanzo gives a saved image: 16 hex digits and its type, like `6fec521a01297ab5.png`.
+pub fn valid_image_file(file: &str) -> bool {
+ match file.split_once('.') {
+ Some((hash, ext)) => {
+ hash.len() == 16
+ && hash.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
+ && ["png", "jpg", "gif", "webp"].contains(&ext)
+ }
+ None => false,
+ }
}
fn valid_slug(s: &str) -> bool {
@@ -800,6 +919,36 @@ mod tests {
assert_eq!(s.link_repo("web", "me/api-docs").unwrap().repos, ["me/api-docs"]);
}
+ #[test]
+ fn images() {
+ let (_dir, s) = store();
+ let p = s.create_project("api", "", None).unwrap();
+ let t = s.create_task(p.id, "Bug", "").unwrap();
+ let shot = "0123456789abcdef.png".to_string();
+ let on_task = s.add_image(t.id, &shot).unwrap();
+ assert!(s.add_image(t.id, "../../etc/passwd").is_err());
+ assert!(s.add_image(t.id + 1, &shot).is_err());
+ // A comment can be only images.
+ let c = s.add_comment(t.id, "me", "", &["fedcba9876543210.jpg".into(), shot.clone()]).unwrap();
+ assert!(s.add_comment(t.id, "me", "x", &["evil.svg".into()]).is_err());
+ let all: Vec<_> = s.list_images(t.id).unwrap().into_iter().map(|i| (i.comment_id, i.file)).collect();
+ assert_eq!(
+ all,
+ [(None, shot.clone()), (Some(c.id), "fedcba9876543210.jpg".into()), (Some(c.id), shot.clone())]
+ );
+ assert_eq!(s.image_files(ImagesOf::Task(t.id)).unwrap(), [shot.clone(), "fedcba9876543210.jpg".into()]);
+ assert_eq!(s.image_files(ImagesOf::Project(p.id)).unwrap().len(), 2);
+ // The same file twice: removing one attachment leaves it in use.
+ s.delete_image(on_task.id).unwrap();
+ assert!(s.unused_images(vec![shot.clone()]).unwrap().is_empty());
+ let files = s.image_files(ImagesOf::Comment(c.id)).unwrap();
+ s.delete_comment(c.id).unwrap();
+ assert!(s.list_images(t.id).unwrap().is_empty());
+ assert_eq!(s.unused_images(files).unwrap(), ["fedcba9876543210.jpg".to_string(), shot.clone()]);
+ assert!(valid_image_file("6fec521a01297ab5.webp"));
+ assert!(!valid_image_file("6FEC521A01297AB5.png") && !valid_image_file("6fec521a01297ab5.svg"));
+ }
+
#[test]
fn migration_moves_repos_to_their_own_table() {
let dir = tempfile::tempdir().unwrap();
@@ -848,11 +997,11 @@ mod tests {
assert_eq!((moved.key(), moved.status.as_str()), (format!("web#{}", t.id), "review"));
let t = s.update_task(t.id, TaskPatch { project_id: Some(p.id), ..Default::default() }).unwrap();
- s.add_comment(t.id, "claude-code", "Done, see PR").unwrap();
- s.add_comment(t.id, "", "thanks").unwrap();
+ s.add_comment(t.id, "claude-code", "Done, see PR", &[]).unwrap();
+ s.add_comment(t.id, "", "thanks", &[]).unwrap();
let comments = s.list_comments(t.id).unwrap();
assert_eq!(comments.iter().map(|c| c.author.as_str()).collect::<Vec<_>>(), ["claude-code", "me"]);
- assert!(s.add_comment(t.id, "me", " ").is_err());
+ assert!(s.add_comment(t.id, "me", " ", &[]).is_err());
assert_eq!(s.get_task(t.id).unwrap().comments, 2);
let tagged =
s.update_task(t.id, TaskPatch { tags: Some(" Bug, UI,bug ,, needs review".into()), ..Default::default() });
@@ -860,7 +1009,7 @@ mod tests {
assert!(
s.update_task(t.id, TaskPatch { tags: Some(" , ".into()), ..Default::default() }).unwrap().tags.is_empty()
);
- let gone = s.add_comment(t.id, "me", "typo").unwrap();
+ let gone = s.add_comment(t.id, "me", "typo", &[]).unwrap();
assert_eq!(s.delete_comment(gone.id).unwrap().body, "typo");
assert!(s.delete_comment(gone.id).is_err());
assert_eq!(s.get_task(t.id).unwrap().comments, 2);
@@ -881,9 +1030,9 @@ mod tests {
let api = s.create_project("api", "", Some("me/api")).unwrap();
let web = s.create_project("web", "", None).unwrap();
let t = s.create_task(api.id, "a", "").unwrap();
- s.add_comment(t.id, "me", "hi").unwrap();
+ s.add_comment(t.id, "me", "hi", &[]).unwrap();
let kept = s.create_task(web.id, "b", "").unwrap();
- s.add_comment(kept.id, "me", "hello").unwrap();
+ s.add_comment(kept.id, "me", "hello", &[]).unwrap();
assert_eq!(s.delete_project("api").unwrap().id, api.id);
assert!(s.find_project("api").is_err());
@@ -948,7 +1097,7 @@ mod tests {
let c1 = s.changes().unwrap();
let t = s.create_task(p.id, "x", "").unwrap();
let c2 = s.changes().unwrap();
- s.add_comment(t.id, "me", "hi").unwrap();
+ s.add_comment(t.id, "me", "hi", &[]).unwrap();
let c3 = s.changes().unwrap();
assert!(c0 < c1 && c1 < c2 && c2 < c3);
}
diff --git a/src/web.rs b/src/web.rs
index 9ba7088..32d7257 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -17,7 +17,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_util::sync::CancellationToken;
use crate::home::Home;
-use crate::store::{self, Error, Store, TaskPatch};
+use crate::store::{self, Error, ImagesOf, Store, TaskPatch};
use crate::update;
const INDEX: &str = include_str!("index.html");
@@ -122,6 +122,7 @@ fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {
app.route("/", get(|| async { Html(INDEX) }))
.route("/app.js", get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], APP_JS) }))
.route("/logo.png", get(|| async { ([(header::CONTENT_TYPE, "image/png")], LOGO) }))
+ .route("/images/{file}", get(image_file))
.route("/api/ping", get(|| async { "kanzo" }))
.route("/api/changes", get(changes))
.route("/api/board", get(board))
@@ -134,6 +135,8 @@ 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/images/{id}", delete(delete_image))
+ .route("/api/tasks/{id}/images", post(attach_image))
.route("/api/update", get(update_status).post(update_now))
.layer(middleware::from_fn_with_state(Arc::new(guard), protect))
.with_state(Arc::new(home))
@@ -328,7 +331,11 @@ async fn unlink_repo(State(home): Shared, Path(slug): Path<String>, Json(r): Jso
}
async fn delete_project(State(home): Shared, Path(slug): Path<String>) -> Response {
- with_store(home, move |_, s| s.delete_project(&slug)).await
+ with_store(home, move |h, s| {
+ let project = s.find_project(&slug)?;
+ h.deleting_images(s, ImagesOf::Project(project.id), || s.delete_project(&slug))
+ })
+ .await
}
#[derive(Deserialize)]
@@ -351,7 +358,8 @@ 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)?;
- Ok(json!({ "task": task, "comments": comments }))
+ let images = s.list_images(id)?;
+ Ok(json!({ "task": task, "comments": comments, "images": images }))
})
.await
}
@@ -387,25 +395,84 @@ async fn move_task(State(home): Shared, Path(id): Path<i64>, Json(m): Json<Move>
}
async fn delete_task(State(home): Shared, Path(id): Path<i64>) -> Response {
- with_store(home, move |_, s| s.delete_task(id)).await
+ with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Task(id), || s.delete_task(id))).await
}
#[derive(Deserialize)]
struct NewComment {
+ #[serde(default)]
body: String,
+ /// Files saved by `/api/images`, attached to the comment.
+ #[serde(default)]
+ images: Vec<String>,
}
async fn add_comment(State(home): Shared, Path(id): Path<i64>, Json(c): Json<NewComment>) -> Response {
- with_store(home, move |_, s| s.add_comment(id, "me", &c.body)).await
+ with_store(home, move |h, s| {
+ for file in &c.images {
+ image_saved(h, file)?;
+ }
+ s.add_comment(id, "me", &c.body, &c.images)
+ })
+ .await
+}
+
+#[derive(Deserialize)]
+struct Attach {
+ file: String,
+}
+
+async fn attach_image(State(home): Shared, Path(id): Path<i64>, Json(a): Json<Attach>) -> Response {
+ with_store(home, move |h, s| {
+ image_saved(h, &a.file)?;
+ s.add_image(id, &a.file)
+ })
+ .await
+}
+
+/// Removes an image from its task or comment, and its file once nothing uses it.
+async fn delete_image(State(home): Shared, Path(id): Path<i64>) -> Response {
+ with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Image(id), || s.delete_image(id))).await
+}
+
+/// Fails unless `file` is an image saved by `/api/images`.
+fn image_saved(home: &Home, file: &str) -> store::Result<()> {
+ if store::valid_image_file(file) && home.dir.join("images").join(file).is_file() {
+ Ok(())
+ } else {
+ Err(Error::Invalid(format!("no saved image {file:?}; paste it again")))
+ }
+}
+
+/// An attached image. Its name is its content's hash, so it never changes and can be cached for good.
+async fn image_file(State(home): Shared, Path(file): Path<String>) -> Response {
+ let mime = match file.rsplit_once('.').map(|(_, ext)| ext) {
+ Some("png") => "image/png",
+ Some("jpg") => "image/jpeg",
+ Some("gif") => "image/gif",
+ Some("webp") => "image/webp",
+ _ => return StatusCode::NOT_FOUND.into_response(),
+ };
+ if !store::valid_image_file(&file) {
+ return StatusCode::NOT_FOUND.into_response();
+ }
+ let path = home.dir.join("images").join(&file);
+ match tokio::task::spawn_blocking(move || std::fs::read(path)).await {
+ Ok(Ok(bytes)) => {
+ ([(header::CONTENT_TYPE, mime), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")], bytes)
+ .into_response()
+ }
+ _ => StatusCode::NOT_FOUND.into_response(),
+ }
}
async fn delete_comment(State(home): Shared, Path(id): Path<i64>) -> Response {
- with_store(home, move |_, s| s.delete_comment(id)).await
+ with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Comment(id), || s.delete_comment(id))).await
}
-/// Saves a pasted image in the data folder and answers with its path, which the board
-/// puts in the text the way a terminal does, so agents can open the image. Files are
-/// named by their content: the same image pasted twice is stored once.
+/// Saves a pasted or dropped image in the data folder's `images/` and answers with its
+/// file name and path; the board then attaches it to a task or a comment. Files are
+/// named by their content, so the same image saved twice is stored once.
async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Response {
let ext = match headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()) {
Some("image/png") => "png",
@@ -437,7 +504,10 @@ async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Res
})
.await;
match saved {
- Ok(Ok(path)) => Json(json!({ "path": path.display().to_string() })).into_response(),
+ Ok(Ok(path)) => {
+ let file = path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
+ Json(json!({ "file": file, "path": path.display().to_string() })).into_response()
+ }
Ok(Err(e)) => {
(StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("cannot save the image: {e}") })))
.into_response()