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.
Rust ai-agentsclaude-codeclicodexcoding-agentskanbanlocal-firstmcpmcp-servermodel-context-protocolproductivityproject-managementraspberry-pirustself-hostedsqlitetask-manager
Share repeated code and drop comments that restate it
emanuele-em82f5d7341a60
diff --git a/src/app.js b/src/app.jsindex c32007a..f77a081 100644--- a/src/app.js+++ b/src/app.js@@ -1,4 +1,3 @@-// The Kanzo board. Plain JavaScript, no build step; served at /app.js."use strict";// The board runs on browsers back to Safari 13.1, Chrome 80 and Firefox 78. These@@ -19,32 +18,44 @@ const $ = (sel, root = document) => root.querySelector(sel);const STATUS_COLORS = ["#8a8a83", "#3b82f6", "#e8a317", "#2f9e44", "#ae3ec9", "#e8590c"];const state = {- project: "all", // slug or "all"- board: null, // last /api/board reply- changes: null, // change counter seen last- task: null, // open task id- dragging: null, // id of the card being dragged- dropped: false, // the current drag ended in a drop- layout: "", // key of the rendered column layout- allDone: false, // show every card in the done column- menu: null, // slug of the project whose "⋯" menu is open, or "settings"- net: null, // last /api/network reply; null on a board opened from another computer- guests: null, // other computers using the board, while it's shared+ project: "all",+ board: null,+ changes: null,+ task: null,+ dragging: null,+ dropped: false,+ layout: "",+ allDone: false,+ menu: null,+ net: null,+ guests: null,};-// ---------- helpers -----------async function api(method, path, body) {+ const image = body instanceof Blob;const res = await fetch("/api" + path, {method,- headers: body ? { "Content-Type": "application/json" } : {},- body: body ? JSON.stringify(body) : undefined,+ headers: body ? { "Content-Type": image ? body.type : "application/json" } : {},+ body: image || !body ? body : JSON.stringify(body),});const data = await res.json().catch(() => ({}));- if (!res.ok) throw new Error(data.error || res.statusText);+ if (!res.ok) throw Object.assign(new Error(data.error || res.statusText), { data });return data;}+function plural(n, word) {+ return `${n} ${word}${n === 1 ? "" : "s"}`;+}++// Storage can be off, as in private windows.+function localStorageGet(k) {+ try { return localStorage.getItem(k); } catch { return null; }+}++function localStorageSet(k, v) {+ try { localStorage.setItem(k, v); } catch {}+}+function el(tag, attrs = {}, ...children) {const node = document.createElement(tag);for (const [k, v] of Object.entries(attrs)) {@@ -57,7 +68,7 @@ function el(tag, attrs = {}, ...children) {return node;}-// Line icons (from Lucide, ISC licence), drawn in the text colour.+// From Lucide, ISC licence.const ICONS = {newProject: '<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4Z"/>',board: '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M8 7v7M12 7v4M16 7v9"/>',@@ -92,7 +103,6 @@ function icon(name, color) {document.querySelectorAll("[data-icon]").forEach((n) => n.replaceWith(icon(n.dataset.icon)));let toastTimer;-// Copies a task's key, like api#12, to paste to an agent, or a shared board's address.// The clipboard API needs a secure page; a board opened from another device over plain// HTTP falls back.async function copyKey(text) {@@ -117,13 +127,12 @@ function toast(message) {toastTimer = setTimeout(() => t.remove(), 3500);}-// The colours a project can be given; the names match PROJECT_COLORS in store.rs.+// The names match PROJECT_COLORS in store.rs.const PROJECT_COLORS = {gray: "#8e8e93", red: "#ef4444", orange: "#f97316", yellow: "#eab308", green: "#22c55e",teal: "#14b8a6", blue: "#3b82f6", purple: "#a855f7", pink: "#ec4899",};-// The colour picked for a project, or until then one chosen from its slug.function projectColorName(slug) {const picked = state.board?.projects.find((p) => p.slug === slug)?.color;if (PROJECT_COLORS[picked]) return picked;@@ -137,8 +146,6 @@ function projectColor(slug) {return PROJECT_COLORS[projectColorName(slug)];}-// How many columns a status is past todo: -1 for backlog, and 0 for a status the board-// doesn't know.function statusStep(status) {const { statuses } = state.board;const i = statuses.indexOf(status);@@ -150,9 +157,6 @@ function statusColor(status) {return STATUS_COLORS[Math.max(i, 0) % STATUS_COLORS.length];}-// A column's status as a small progress circle, as in Linear: dashed for backlog, empty-// for todo, filling up across the board, a check for done. A shape, so it can't be taken-// for a project's colour dot.function statusIcon(status) {const step = statusStep(status), steps = statusStep("done");const f = Math.max(step, 0) / steps;@@ -191,8 +195,6 @@ function timeEl(ts) {return el("time", { datetime: ts, title: parseTime(ts).toLocaleString() }, ago(ts));}-// ---------- Markdown (small, escapes everything first) -----------function escapeHtml(s) {return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);}@@ -225,7 +227,7 @@ function markdown(src) {const lines = escapeHtml(src.replace(/\r\n?/g, "\n")).split("\n");const out = [];let para = [];- let list = null; // { type: "ul" | "ol", items: [] }+ let list = null;const flushPara = () => { if (para.length) out.push(`<p>${inline(para.join("<br>"))}</p>`); para = []; };const flushList = () => {if (!list) return;@@ -274,8 +276,6 @@ function markdown(src) {return out.join("");}-// ---------- board -----------// Loads can overlap (a poll, a drop, an edit); only the newest one may render,// so a slow older reply never undoes what is on screen.let boardRequest = 0;@@ -283,8 +283,6 @@ let boardRequest = 0;async function loadBoard() {const request = ++boardRequest;try {- // The server leaves out older done tasks unless asked: the board does not show- // them, and the done column only grows. Search needs them all.const done = state.allDone ? "&done=all" : "";const q = filterQuery();const board = await api("GET", "/board?project=" + encodeURIComponent(state.project) + done@@ -304,7 +302,6 @@ async function loadBoard() {}}-// The address is #project or #project/task-id, so a task can be linked to.function updateHash() {const hash = "#" + state.project + (state.task ? "/" + state.task : "");if (location.hash !== hash) history.replaceState(null, "", hash);@@ -319,7 +316,7 @@ function readHash() {function setProject(slug) {state.project = slug;- try { localStorage.setItem("kanzo.project", slug); } catch {}+ localStorageSet("kanzo.project", slug);updateHash();state.layout = "";loadBoard();@@ -355,15 +352,9 @@ function renderNav() {);}-// ---------- project menu ------------// The "⋯" menu of a sidebar project. `state.menu` holds its slug, so the row keeps-// its highlight while the sidebar is redrawn by polling.+// `state.menu` holds the slug, so the row keeps its highlight while polling redraws the sidebar.function toggleProjectMenu(p, button) {- const wasOpen = state.menu === p.slug;- closeMenu();- if (wasOpen) return;- state.menu = p.slug;+ if (!toggleMenu(p.slug)) return;button.closest(".item").classList.add("menu-open");const swatches = el("div", { class: "swatches", role: "group", "aria-label": "Color" });const drawSwatches = () => swatches.replaceChildren(...Object.entries(PROJECT_COLORS).map(([name, hex]) => {@@ -373,7 +364,6 @@ function toggleProjectMenu(p, button) {current ? icon("check") : null);}));drawSwatches();- // Linked repos, each with an unlink button, and a field to link another.const repos = el("div", { class: "repos" });const drawRepos = (list, focus) => {const input = el("input", { class: "field", placeholder: "Link a repo: owner/repo", "aria-label": "Link a GitHub repo",@@ -405,9 +395,7 @@ function toggleProjectMenu(p, button) {menu.focus();}-// Renaming a project, as in ChatGPT: its sidebar row becomes a field. Enter or leaving it-// saves, Esc cancels. The slug, and so the task keys, stay.-let renaming = null; // { slug, input }+let renaming = null;function startRename(p) {closeMenu();@@ -435,7 +423,6 @@ function startRename(p) {input.select();}-// Links (POST) or unlinks (DELETE) a repo; returns the project, or null after showing the error.async function changeRepo(slug, method, repo) {try {const p = await api(method, `/projects/${encodeURIComponent(slug)}/repos`, { repo });@@ -451,6 +438,14 @@ async function pickColor(slug, color) {} catch (err) { toast(err.message); }}+function toggleMenu(name) {+ const wasOpen = state.menu === name;+ closeMenu();+ if (wasOpen) return false;+ state.menu = name;+ return true;+}+function closeMenu() {if (!state.menu) return;state.menu = null;@@ -461,12 +456,10 @@ function closeMenu() {$("#network").classList.remove("open");}-// A click elsewhere closes the menu; one on a "⋯" or the Settings button is left to toggle it.+// A click on a menu's own button is left to toggle it.document.addEventListener("mousedown", (e) => {if (!e.target.closest(".menu, .nav .more, #settings, #network, #network-menu")) closeMenu();});-// A click outside the task panel closes it. Cards are left to open their own task,-// and the project menu to do its job.document.addEventListener("mousedown", (e) => {if (state.task && e.button === 0 && !e.target.closest("#panel, .card, .menu, .search-dialog")) closeTask();});@@ -491,12 +484,11 @@ function renderHeader() {onclick: () => setFilters(savedFilters().filter((_, j) => j !== i)) }, icon("close")))));$("#human-only").setAttribute("aria-pressed", String(isHumanOnly()));if (!projects.length) { header.replaceChildren(); return; }- // Plain words for what each piece is: how much is open, and the repos on GitHub.- const open = (n) => `${n} open task${n === 1 ? "" : "s"}`;+ const open = (n) => plural(n, "open task");if (!p) {const count = projects.reduce((n, p) => n + p.open, 0);header.replaceChildren(el("h1", {}, "All projects"),- el("span", { class: "sub" }, `${open(count)} in ${projects.length} project${projects.length === 1 ? "" : "s"}`));+ el("span", { class: "sub" }, `${open(count)} in ${plural(projects.length, "project")}`));return;}header.replaceChildren(@@ -508,7 +500,7 @@ function renderHeader() {}async function deleteProject(p) {- const tasks = p.total ? ` and its ${p.total} task${p.total > 1 ? "s" : ""}, with their comments` : "";+ const tasks = p.total ? ` and its ${plural(p.total, "task")}, with their comments` : "";if (!confirm(`Delete project ${p.slug}${tasks}? This cannot be undone.`)) return;try {await api("DELETE", `/projects/${encodeURIComponent(p.slug)}`);@@ -560,7 +552,6 @@ function renderColumns() {for (const status of statuses) {const col = columns.querySelector(`[data-status="${CSS.escape(status)}"]`);const mine = tasks.filter((t) => t.status === status && (!humanOnly || t.human));- // Older done tasks the server left out (see loadBoard).const last = status === statuses[statuses.length - 1];const hidden = last && !state.allDone ? state.board.done_hidden || 0 : 0;// Filtered, the server's count of older done tasks says nothing about human ones.@@ -576,16 +567,12 @@ function renderColumns() {highlight("filter", columns, words);}-// The filter box keeps on the board only the tasks search finds (see loadBoard): search-// shows one to open, the filter all of them in their columns.-// Enter keeps what's typed as a chip beside the box, and each browser remembers them;-// a task must match every chip and the text still in the box.function savedFilters() {try { return JSON.parse(localStorageGet("kanzo.filters")) || []; } catch { return []; }}function setFilters(filters) {- try { localStorage.setItem("kanzo.filters", JSON.stringify(filters)); } catch {}+ localStorageSet("kanzo.filters", JSON.stringify(filters));loadBoard();}@@ -597,8 +584,6 @@ function wordsOf(query) {return query.toLowerCase().split(/\s+/).filter(Boolean);}-// Paints the words found in the titles, descriptions and tags under `root`, for search and-// the filter. The CSS Custom Highlight API does it without adding an element per match.function highlight(name, root, words) {if (!window.Highlight) return;const re = new RegExp(words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "gi");@@ -615,7 +600,6 @@ function highlight(name, root, words) {CSS.highlights.set(name, new Highlight(...ranges));}-// A task's description line and tags: on cards and in search.function summary(t) {return [t.description ? el("span", { class: "desc" }, plainText(t.description)) : null,@@ -623,24 +607,21 @@ function summary(t) {];}-// The board can show only human tasks; off at first, and each browser remembers the choice.function isHumanOnly() {return localStorageGet("kanzo.humanOnly") === "1";}function setHumanOnly(humanOnly) {- try { localStorage.setItem("kanzo.humanOnly", humanOnly ? "1" : "0"); } catch {}+ localStorageSet("kanzo.humanOnly", humanOnly ? "1" : "0");render();}-// Backlog and done, which only grows, start collapsed to a thin strip, as in Trello or-// Linear, and each browser remembers the choice. Cards can still be dropped on a strip.function isCollapsed(status) {return localStorageGet(`kanzo.${status}Collapsed`) !== "0";}function setCollapsed(status, collapsed) {- try { localStorage.setItem(`kanzo.${status}Collapsed`, collapsed ? "1" : "0"); } catch {}+ localStorageSet(`kanzo.${status}Collapsed`, collapsed ? "1" : "0");showCollapsed();}@@ -664,7 +645,6 @@ function showCollapsed() {columns.style.gridTemplateColumns = cols.map((c) => (c.classList.contains("collapsed") ? "48px" : "minmax(260px, 1fr)")).join(" ");}-// A description as one line of plain text for a card: Markdown markers dropped, lines joined.function plainText(md) {return md.split("\n").map((l) => l.replace(/^\s*(#{1,6}|>|[-*+]|\d+[.)])\s+/, "").replace(/^\[[ xX]\]\s+/, ""))@@ -680,7 +660,6 @@ function card(t, showProject) {onclick: () => openTask(t.id) },el("div", { class: "head" },el("div", { class: "title" }, t.title),- // On "All projects" a dot in the project's colour tells the projects apart.t.human ? el("span", { class: "human-mark", title: "Human task: agents skip it" }, icon("human")) : null,el("span", { class: "num", title: `Copy ${key(t)}`, onclick: (e) => { e.stopPropagation(); copyKey(key(t)); } },showProject ? el("span", { class: "dot", style: `background:${projectColor(t.project)}` }) : null, `#${t.id}`)),@@ -702,7 +681,6 @@ function card(t, showProject) {return node;}-// The whole column takes drops; cards land in its list.function wireDrop(col, list, status) {const line = el("div", { class: "drop-line" });const cardAfter = (y) => {@@ -738,17 +716,8 @@ function wireDrop(col, list, status) {});}-function localStorageGet(k) {- try { return localStorage.getItem(k); } catch { return null; }-}--// ---------- new task ------------// New task creates the task in todo at once and opens it like any other, with its title-// selected to type over; its Status field moves it elsewhere. Closed untouched, it is-// deleted again.const NEW_TITLE = "New task";-let fresh = null; // id of the task just added, until something in it is saved+let fresh = null;async function newTask() {const { projects } = state.board;@@ -773,13 +742,10 @@ function dropFresh() {api("DELETE", `/tasks/${id}`).then(loadBoard, () => {});}-// Leaving the page also counts as closing the task.window.addEventListener("pagehide", () => {if (fresh) fetch(`/api/tasks/${fresh}`, { method: "DELETE", keepalive: true });});-// ---------- new project -----------function showNewProject() {$("#project-dialog").hidden = false;$("#new-project [name=slug]").focus();@@ -802,8 +768,6 @@ $("#filter").addEventListener("keydown", (e) => {});$("#new-project-toggle").addEventListener("click", showNewProject);$("#new-project-cancel").addEventListener("click", hideNewProject);-$("#project-dialog").addEventListener("mousedown", (e) => { if (e.target.id === "project-dialog") hideNewProject(); });-$("#project-dialog").addEventListener("keydown", (e) => { if (e.key === "Escape") { e.stopPropagation(); hideNewProject(); } });$("#new-project").addEventListener("submit", async (e) => {e.preventDefault();const f = new FormData(e.target);@@ -814,9 +778,6 @@ $("#new-project").addEventListener("submit", async (e) => {} catch (err) { toast(err.message); }});-// ---------- task panel ------------// Every field is editable in place and saves when it loses focus.const panel = $("#panel");let panelTask = null;@@ -910,7 +871,6 @@ async function deleteComment(c) {} catch (err) { toast(err.message); }}-// The project tag doubles as a picker that moves the task to another project.function renderProjectPick(task) {const projects = state.board ? state.board.projects.map((p) => p.slug) : [];if (!projects.includes(task.project)) projects.push(task.project);@@ -918,14 +878,13 @@ function renderProjectPick(task) {...projects.map((slug) => el("option", { value: slug }, slug)));select.value = task.project;select.addEventListener("change", () => {- try { localStorage.setItem("kanzo.newTaskProject", select.value); } catch {}+ localStorageSet("kanzo.newTaskProject", select.value);patchTask({ project: select.value });});$("#p-project").replaceChildren(el("label", { class: "tag project-pick" },el("span", { class: "dot", style: `background:${projectColor(task.project)}` }), select));}-// Textareas grow with their text instead of scrolling.function fit(t) {if (t.tagName !== "TEXTAREA") return;t.style.height = "auto";@@ -942,7 +901,6 @@ async function patchTask(fields) {} catch (e) { toast(e.message); refreshTask(); }}-// Escape undoes the field's edit; on a task just added and not saved yet, it drops the task.function cancelField(e, saved) {e.stopPropagation();if (fresh && fresh === state.task) { closeTask(); return; }@@ -955,10 +913,8 @@ $("#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));-// ⌘↵ in the title or description saves and closes.$("#p-title").addEventListener("keydown", (e) => {if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); closeTask(); }- // The title is one line: Enter, like Tab, goes on to the description.else if ((e.key === "Enter" || e.key === "Tab") && !e.shiftKey) { e.preventDefault(); editDesc(); }else if (e.key === "Escape") cancelField(e, panelTask ? panelTask.title : "");});@@ -978,7 +934,6 @@ $("#p-desc").addEventListener("blur", (e) => {showDesc();});-// The description shows rendered, like a comment, and turns into its textarea to edit.// Empty, the textarea stays, so its placeholder has something to click.function showDesc() {const desc = $("#p-desc"), view = $("#p-desc-view");@@ -1003,11 +958,7 @@ $("#p-desc-view").addEventListener("focus", editDesc);$("#p-status").addEventListener("change", (e) => patchTask({ status: e.target.value }));$("#p-human").addEventListener("change", (e) => patchTask({ human: e.target.checked }));-// ---------- 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+let pending = [];function imagesIn(transfer) {if (!transfer) return [];@@ -1016,10 +967,7 @@ function imagesIn(transfer) {}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;+ return (await api("POST", "/images", image)).file;}async function attachImages(images, toComment) {@@ -1040,7 +988,6 @@ async function attachImages(images, toComment) {} catch (err) { toast(err.message); }}-// 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" })),@@ -1076,7 +1023,6 @@ for (const [zone, toComment] of [[$("#p-desc").closest(".section"), false], [$("});}-// 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))];$("#p-tags").addEventListener("keydown", (e) => {if (e.key === "Enter") { e.preventDefault(); e.target.blur(); }@@ -1104,7 +1050,6 @@ $("#p-comment-form").addEventListener("submit", async (e) => {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() && !pending.length; fit(e.target); });$("#p-comment").addEventListener("keydown", (e) => {if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); $("#p-comment-form").requestSubmit(); }@@ -1112,7 +1057,7 @@ $("#p-comment").addEventListener("keydown", (e) => {$("#p-delete").addEventListener("click", async () => {if (!panelTask) return;- const extra = panelTask.comments ? ` and its ${panelTask.comments} comment${panelTask.comments > 1 ? "s" : ""}` : "";+ const extra = panelTask.comments ? ` and its ${plural(panelTask.comments, "comment")}` : "";if (!confirm(`Delete ${key(panelTask)}${extra}? This cannot be undone.`)) return;try {if (fresh === panelTask.id) fresh = null;@@ -1122,10 +1067,6 @@ $("#p-delete").addEventListener("click", async () => {} catch (err) { toast(err.message); }});-// ---------- search ------------// The search window, as in ChatGPT: tasks of every project, found by the server, open-// ones first. Arrows pick, Enter opens, Esc closes. Without words it shows the latest changes.let results = [], selected = 0, searchRequest = 0, searchTimer;function openSearch() {@@ -1171,7 +1112,6 @@ function select(i) {rows[selected].scrollIntoView({ block: "nearest" });}-// Opens the task, in its own project unless the board shows all of them.function pick(t) {closeSearch();if (state.project !== "all" && state.project !== t.project) setProject(t.project);@@ -1183,29 +1123,20 @@ $("#search").addEventListener("input", () => { clearTimeout(searchTimer); search$("#search").addEventListener("keydown", (e) => {if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); select(selected + (e.key === "ArrowDown" ? 1 : -1)); }else if (e.key === "Enter" && results[selected]) { e.preventDefault(); pick(results[selected]); }- else if (e.key === "Escape") { e.stopPropagation(); closeSearch(); }});-$("#search-dialog").addEventListener("mousedown", (e) => { if (e.target.id === "search-dialog") closeSearch(); });--// ---------- keyboard, polling, start ----------document.addEventListener("keydown", (e) => {const typing = e.target.closest("input, textarea, select");+ const plain = !typing && !e.metaKey && !e.ctrlKey;if (e.key === "Escape" && state.menu) { closeMenu(); return; }if (e.key === "Escape" && state.task && !typing) closeTask();- if ((e.key === "/" && !typing && !e.metaKey && !e.ctrlKey) || (e.key === "k" && (e.metaKey || e.ctrlKey))) {+ if ((e.key === "/" && plain) || (e.key === "k" && (e.metaKey || e.ctrlKey))) {e.preventDefault();openSearch();}- if (e.key === "n" && !typing && !e.metaKey && !e.ctrlKey) {- if (!$("#new-task").hidden) { e.preventDefault(); newTask(); }- }- if (e.key === "f" && !typing && !e.metaKey && !e.ctrlKey) {- if (!$("#filter").hidden) { e.preventDefault(); $("#filter").focus(); }- }- if (e.key === "h" && !typing && !e.metaKey && !e.ctrlKey) {- if (!$("#human-only").hidden) { e.preventDefault(); setHumanOnly(!isHumanOnly()); }- }+ if (e.key === "n" && plain && !$("#new-task").hidden) { e.preventDefault(); newTask(); }+ if (e.key === "f" && plain && !$("#filter").hidden) { e.preventDefault(); $("#filter").focus(); }+ if (e.key === "h" && plain && !$("#human-only").hidden) { e.preventDefault(); setHumanOnly(!isHumanOnly()); }});window.addEventListener("hashchange", () => {@@ -1215,7 +1146,6 @@ window.addEventListener("hashchange", () => {else if (!task && state.task) closeTask();});-// Agents change the board through `kanzo mcp`; a cheap counter tells us when.async function poll() {if (document.hidden) return schedulePoll();try {@@ -1224,7 +1154,6 @@ async function poll() {if (guests !== state.guests) {state.guests = guests;renderNetwork();- // Who's connected changed: the settings list them.if (state.menu === "network") loadNetwork();}if (changes !== state.changes) {@@ -1247,10 +1176,6 @@ function schedulePoll() {}schedulePoll();-// ---------- sync ------------// Sync runs `kanzo sync`: it commits the board and pulls or pushes it through the data-// folder's git remote. When both machines changed it, the board asks which to keep.let syncing = false;async function syncNow(keep) {@@ -1259,12 +1184,12 @@ async function syncNow(keep) {toast("Syncing…");let diverged = null;try {- const res = await fetch("/api/sync", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ keep }) });- const reply = await res.json().catch(() => ({}));- if (res.ok) { toast(reply.message); loadBoard(); }- else if (reply.diverged) diverged = reply;- else toast(reply.error || res.statusText);- } catch (err) { toast(err.message); }+ toast((await api("POST", "/sync", { keep })).message);+ loadBoard();+ } catch (err) {+ if (err.data?.diverged) diverged = err.data;+ else toast(err.message);+ }syncing = false;if (diverged) chooseSide(diverged);}@@ -1272,7 +1197,6 @@ async function syncNow(keep) {function chooseSide({ first }) {const repo = repoName(syncRemote);if (first) {- // A repo another machine already syncs with: most likely, this machine is joining it.if (confirm(`${repo} already has a board. Use it on this machine?\n\nThis machine's current board is kept in kanzo.db.bak.`)) syncNow("remote");else if (confirm(`Replace the board in ${repo} with this machine's board instead?`)) syncNow("local");return;@@ -1281,10 +1205,8 @@ function chooseSide({ first }) {else if (confirm("Take the other machine's board instead? This machine's board is kept in kanzo.db.bak.")) syncNow("remote");}-// The repo the board syncs with; null before it's set up.let syncRemote = null;-// "you/kanzo-data" from any of its URLs.function repoName(url) {return (url || "").replace(/\.git$/, "").split(/[/:]/).filter(Boolean).slice(-2).join("/");}@@ -1294,7 +1216,6 @@ async function loadSyncRemote() {return syncRemote;}-// Sync asks for a repo, in Settings, the first time.async function sync() {closeMenu();if (await loadSyncRemote()) syncNow();@@ -1307,17 +1228,9 @@ $("#sync-form").addEventListener("submit", async (e) => {save.disabled = true;save.textContent = "Checking…";try {- const res = await fetch("/api/sync", { method: "PUT", headers: { "Content-Type": "application/json" },- body: JSON.stringify({ url: $("#sync-url").value }) });- const reply = await res.json().catch(() => ({}));- if (res.ok) {- syncRemote = reply.remote;- closeSettings();- syncNow();- } else {- $("#sync-error").textContent = reply.error || res.statusText;- $("#sync-error").hidden = false;- }+ syncRemote = (await api("PUT", "/sync", { url: $("#sync-url").value })).remote;+ closeSettings();+ syncNow();} catch (err) {$("#sync-error").textContent = err.message;$("#sync-error").hidden = false;@@ -1326,10 +1239,6 @@ $("#sync-form").addEventListener("submit", async (e) => {save.textContent = "Save and sync";});-// ---------- network ------------// Sharing the board with other computers on the network, or showing another computer's-// board: `kanzo share` and `kanzo join`, from the board.async function loadNetwork() {let net = null;try { net = await api("GET", "/network"); } catch {}@@ -1343,8 +1252,6 @@ function setNet(net) {renderNetwork();}-// The share icon in the header: "Shared" with how many computers use the board, on the-// computer that shares it and on those that joined it.function renderNetwork() {const net = state.net;const button = $("#network");@@ -1354,7 +1261,7 @@ function renderNetwork() {const host = net?.host?.replace(/:4242$/, "") || location.hostname;const n = state.guests;const shared = hosted || n != null;- const computers = n == null ? "" : `: ${n} computer${n === 1 ? "" : "s"} connected`;+ const computers = n == null ? "" : `: ${plural(n, "computer")} connected`;button.replaceChildren(icon("share"), ...(shared ? ["Shared"] : []), ...(shared && n != null ? [el("span", { class: "count" }, String(n))] : []));button.classList.toggle("on", shared);button.title = hosted ? `Shared by ${host}${computers}` : shared ? `Shared on your network${computers}` : "Share this board, or join another";@@ -1364,8 +1271,6 @@ function renderNetwork() {// While a change is on its way, the popover keeps showing it.let networkBusy = false;-// Sharing and joining: a board is shared or joined, never both, so while one is on the-// other is greyed out with the reason.function renderNetworkMenu() {if (networkBusy) return;const net = state.net;@@ -1407,10 +1312,7 @@ function renderNetworkMenu() {}function toggleNetworkMenu() {- const wasOpen = state.menu === "network";- closeMenu();- if (wasOpen) return;- state.menu = "network";+ if (!toggleMenu("network")) return;const button = $("#network");button.classList.add("open");$("#network-error").hidden = true;@@ -1423,8 +1325,7 @@ function toggleNetworkMenu() {loadNetwork();}-// Sends a change to this computer's board. Joining or leaving shows another board, so-// the page reloads.+// Joining or leaving shows another board, so the page reloads.async function changeNetwork(change) {$("#network-error").hidden = true;networkBusy = true;@@ -1460,15 +1361,8 @@ $("#network-join").addEventListener("submit", async (e) => {submit.textContent = "Join";});-// ---------- menu and settings ------------// The Settings button at the bottom of the sidebar opens a menu, as in Claude: Settings,-// Check for updates and Sync.function toggleSettingsMenu() {- const wasOpen = state.menu === "settings";- closeMenu();- if (wasOpen || !state.board) return;- state.menu = "settings";+ if (!state.board || !toggleMenu("settings")) return;const button = $("#settings");button.classList.add("open");const menu = el("div", { class: "menu", role: "menu", tabindex: "-1" },@@ -1486,7 +1380,6 @@ function toggleSettingsMenu() {$("#settings").addEventListener("click", toggleSettingsMenu);-// The settings window, as in Claude's: categories on the left, their settings on the right.function openSettings(section = "board") {closeMenu();$("#settings-backlog").checked = state.board?.statuses.includes("backlog") ?? false;@@ -1514,8 +1407,11 @@ $("#settings-nav").addEventListener("click", (e) => {if (b) showSection(b.dataset.section);});$("#settings-close").addEventListener("click", closeSettings);-$("#settings-dialog").addEventListener("mousedown", (e) => { if (e.target.id === "settings-dialog") closeSettings(); });-$("#settings-dialog").addEventListener("keydown", (e) => { if (e.key === "Escape") { e.stopPropagation(); closeSettings(); } });+for (const [dialog, close] of [[$("#project-dialog"), hideNewProject], [$("#search-dialog"), closeSearch],+ [$("#settings-dialog"), closeSettings]]) {+ dialog.addEventListener("mousedown", (e) => { if (e.target === dialog) close(); });+ dialog.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.stopPropagation(); close(); } });+}$("#settings-backlog").addEventListener("change", async (e) => {const box = e.target;try {@@ -1525,11 +1421,6 @@ $("#settings-backlog").addEventListener("change", async (e) => {});$("#settings-update").addEventListener("click", checkForUpdates);-// ---------- update ------------// Kanzo checks GitHub for a newer release once a day and offers it at the bottom of the-// sidebar; its menu asks right away. Installing replaces the running board and-// restarts it, and the page reloads once it's back.async function checkUpdate() {try {showUpdate(await api("GET", "/update"));@@ -1596,7 +1487,6 @@ setInterval(checkUpdate, 24 * 60 * 60 * 1000);loadSyncRemote();loadNetwork();-// Relative times ("5m ago") drift; refresh them now and then.setInterval(() => {document.querySelectorAll("time[datetime]").forEach((t) => { t.textContent = ago(t.getAttribute("datetime")); });}, 60000);diff --git a/src/export.rs b/src/export.rsindex b8ba5bb..045008d 100644--- a/src/export.rs+++ b/src/export.rs@@ -1,5 +1,3 @@-//! `kanzo export`: the whole board as Markdown or JSON, readable without Kanzo.-use std::fmt::Write as _;use std::path::Path;@@ -7,8 +5,7 @@ use anyhow::{Context, Result};use serde::Serialize;use crate::home::Home;-use crate::store::short_time;-use crate::store::{Comment, Project, Store, Task};+use crate::store::{self, Comment, Project, Store, Task, short_time};#[derive(Clone, Copy, clap::ValueEnum)]pub enum Format {@@ -37,9 +34,7 @@ struct TaskOut {title: String,description: String,tags: Vec<String>,- /// Work for a person, which agents leave alone.human: bool,- /// Paths of the images attached to the task and its comments.images: Vec<String>,status: String,created_at: String,@@ -67,7 +62,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, &home.dir.join("images"))?;+ let board = collect(&store, project, &home.images())?;let text = match format {Format::Json => serde_json::to_string_pretty(&board)? + "\n",Format::Markdown => markdown(&board),@@ -113,9 +108,9 @@ fn markdown(board: &Board) -> String {p.project.slug,p.project.open,p.project.total,- if p.project.total == 1 { "task" } else { "tasks" }+ store::tasks(p.project.total));- // Columns in board order, then any status no longer in the config.+ // Tasks can keep a status that is no longer in the config.let mut statuses = board.statuses.clone();for t in &p.tasks {if !statuses.contains(&t.status) {diff --git a/src/home.rs b/src/home.rsindex d878729..3c4b5ff 100644--- a/src/home.rs+++ b/src/home.rs@@ -1,12 +1,11 @@-//! The data folder: where it is, what it holds, and the settings in `config.toml`.-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::time::{Duration, Instant};-use anyhow::{Context, Result};+use anyhow::{Context, Result, bail};use serde::Deserialize;use crate::store::{self, ImagesOf, Store};@@ -42,7 +41,6 @@ kanzo.lock.DS_Store";-/// How long an operation waits for `kanzo sync` before giving up with "busy".const LOCK_WAIT: Duration = Duration::from_secs(if cfg!(test) { 1 } else { 10 });pub const NO_LOCKS: &str = "This folder doesn't support file locks: don't sync while agents are working.";@@ -52,8 +50,7 @@ pub const NO_LOCKS: &str = "This folder doesn't support file locks: don't sync wpub struct Config {pub port: u16,pub listen: IpAddr,- /// Before 0.2 this set the columns; they're fixed now, with an optional backlog- /// switched on from the board. Still read, so older files keep working.+ /// Before 0.2 this set the columns. Still read, so older files keep working.#[serde(rename = "statuses")]_statuses: Option<toml::Value>,pub mcp_http: bool,@@ -65,7 +62,6 @@ impl Default for Config {}}-/// An opened data folder.#[derive(Debug, Clone)]pub struct Home {pub dir: PathBuf,@@ -73,7 +69,6 @@ pub struct Home {}impl Home {- /// `--home`, then `KANZO_HOME`, then `~/kanzo`.pub fn resolve(flag: Option<PathBuf>) -> Result<PathBuf> {if let Some(dir) = flag {return Ok(dir);@@ -85,7 +80,6 @@ impl Home {Ok(home.join("kanzo"))}- /// Opens the data folder, creating it and its files on first use.pub fn open(dir: PathBuf) -> Result<Self> {fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;let dir = dir.canonicalize().unwrap_or(dir);@@ -124,10 +118,8 @@ impl Home {}}- /// Opens a fresh connection. Callers keep it for one operation only, so a- /// database replaced by `kanzo sync` is picked up on the next one. It holds- /// a shared lock on `kanzo.lock`, so sync can wait for it to finish; while- /// sync holds the lock, this waits up to `LOCK_WAIT` and then reports busy.+ /// Callers keep it for one operation only, so a database replaced by `kanzo sync`+ /// is picked up on the next one. The shared lock lets sync wait for it to finish.pub fn store(&self) -> store::Result<Store> {let lock = self.lock_file().map_err(|e| store::Error::Invalid(format!("{e:#}")))?;let deadline = Instant::now() + LOCK_WAIT;@@ -153,8 +145,11 @@ impl Home {Store::open(&self.db_path(), 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 images(&self) -> PathBuf {+ self.dir.join("images")+ }++ /// The same image can be attached in several places, and is stored once.pub fn deleting_images<T>(&self,store: &Store,@@ -164,13 +159,11 @@ impl Home {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));+ let _ = fs::remove_file(self.images().join(file));}Ok(deleted)}- /// Blocks until no connection is open, and keeps new ones out until the file is dropped.- /// `None` when the filesystem has no locks.pub fn lock_exclusive(&self) -> Result<Option<File>> {let lock = self.lock_file()?;match lock.lock() {@@ -207,6 +200,35 @@ fn write_if_missing(path: &Path, contents: &str) -> Result<()> {Ok(())}+pub fn output(cmd: &mut Command) -> Result<String> {+ let line: Vec<_> = std::iter::once(cmd.get_program()).chain(cmd.get_args()).map(|a| a.to_string_lossy()).collect();+ let line = line.join(" ");+ let out = cmd+ .output()+ .with_context(|| format!("cannot run {}; is it installed?", line.split(' ').next().unwrap_or_default()))?;+ if !out.status.success() {+ bail!("{line} failed: {}", String::from_utf8_lossy(&out.stderr).trim());+ }+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())+}++pub fn hostname() -> String {+ let name = |cmd: &mut Command| output(cmd).ok().filter(|n| !n.is_empty());+ name(Command::new("scutil").args(["--get", "ComputerName"]))+ .or_else(|| name(&mut Command::new("hostname")))+ .unwrap_or_else(|| "unknown".into())+}++pub fn write_whole(path: &Path, bytes: &[u8]) -> io::Result<()> {+ if let Some(dir) = path.parent() {+ fs::create_dir_all(dir)?;+ }+ // A half-written file never takes the real name.+ let partial = path.with_extension("part");+ fs::write(&partial, bytes)?;+ fs::rename(&partial, path)+}+#[cfg(test)]mod tests {use super::*;@@ -239,7 +261,6 @@ mod tests {let lock = home.lock_exclusive().unwrap();assert!(matches!(home.store(), Err(store::Error::Busy(_))));- // An operation started during a replacement waits, then goes on once it's done.let waiting = std::thread::spawn({let home = home.clone();move || home.store().map(|s| s.statuses().len())diff --git a/src/index.html b/src/index.htmlindex c0d5bbb..ab7ea0c 100644--- a/src/index.html+++ b/src/index.html@@ -40,7 +40,6 @@ button { cursor: pointer; }.icon svg { width: 18px; height: 18px; display: block; }.dot { width: 8px; height: 8px; border-radius: 50%; flex: none; }-/* Sidebar */aside {background: var(--sidebar); border-right: 1px solid var(--border);display: flex; flex-direction: column; min-height: 0; padding: 12px 8px;@@ -62,7 +61,6 @@ aside {.nav a .name { overflow: hidden; text-overflow: ellipsis; flex: 1; }.nav a .count { color: var(--faint); font-size: 12px; font-variant-numeric: tabular-nums; }.nav .label { color: var(--faint); padding: 18px 10px 6px; }-/* A project row: its "more" button takes the count's place on hover, like most sidebars. */.nav .item { position: relative; }.nav .more {position: absolute; right: 6px; top: 50%; transform: translateY(-50%); display: none;@@ -109,7 +107,6 @@ aside {#settings:hover, #settings:focus-visible, #settings.open { color: var(--text); }.menu .value { margin-left: auto; padding-left: 12px; color: var(--faint); font-size: 12px; }-/* Controls */input.field, textarea.field, select.field {background: var(--field); border: 0; border-radius: 12px; padding: 8px 12px; width: 100%;}@@ -127,7 +124,6 @@ select.field:hover { background-color: var(--hover); }.btn.primary { background: var(--accent); color: var(--accent-text); }.btn.primary:hover, .btn.primary:focus-visible { opacity: .85; }-/* Main board */main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }header {display: flex; align-items: center; gap: 12px; padding: 16px 24px 14px; flex-wrap: wrap; min-height: 64px;@@ -141,9 +137,6 @@ header .repo-link {}header .repo-link:hover, header .repo-link:focus-visible { background: var(--active); color: var(--text); }header .repo-link .icon svg { width: 14px; height: 14px; }-/* Sharing: a green dot with the number of guests, or the computer whose board this is. */-/* Share: an icon, green with the number of guests while shared, or with the host once joined. */-/* The header's icon buttons, as tall and round as New task beside them. */#network, #human-only { width: auto; height: 35px; min-width: 35px; padding: 0 8px; justify-content: center; border-radius: 99px; }#network { gap: 6px; color: var(--muted); font-size: 13px; }#network:hover, #network:focus-visible, #network.open { color: var(--text); }@@ -154,14 +147,12 @@ header .repo-link .icon svg { width: 14px; height: 14px; }}#new-task { display: inline-flex; align-items: center; gap: 6px; padding-left: 12px; }#new-task .icon svg { width: 16px; height: 16px; }-/* Filter: the board keeps only the tasks search finds. */#filter {width: 180px; height: 35px; padding: 0 14px; border: 1px solid var(--border); border-radius: 99px;background: transparent; color: var(--text); font: inherit; font-size: 13px; outline: none;}#filter:focus { border-color: var(--link); }#filter.on { border-color: var(--link); background: color-mix(in srgb, var(--link) 8%, transparent); }-/* Filters kept with Enter: light blue chips, each with its × to remove it. */#filters { display: flex; flex-wrap: wrap; gap: 6px; }.chip {display: inline-flex; align-items: center; gap: 2px; height: 28px; padding: 0 4px 0 12px; border-radius: 99px;@@ -170,9 +161,7 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.chip button { display: inline-flex; padding: 4px; border: 0; border-radius: 99px; background: none; color: inherit; }.chip button:hover { background: color-mix(in srgb, var(--link) 20%, transparent); }.chip .icon svg { width: 13px; height: 13px; }-/* The words search or the filter found. */::highlight(filter), ::highlight(search) { background-color: color-mix(in srgb, var(--link) 25%, transparent); }-/* Show only human tasks: a small icon, coloured while the filter is on. */#human-only { color: var(--muted); }#human-only:hover, #human-only:focus-visible { color: var(--text); }#human-only[aria-pressed="true"] { background: color-mix(in srgb, var(--link) 14%, transparent); color: var(--link); }@@ -198,7 +187,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }background: none; color: var(--faint);}.column h2 .collapse:hover, .column h2 .collapse:focus-visible { background: var(--hover); color: var(--text); }-/* A collapsed column: a thin strip, name written downwards, that expands on a click. */.column.collapsed { cursor: pointer; }.column.collapsed:hover { background: var(--hover); }.column.collapsed h2 { writing-mode: vertical-rl; padding: 12px 0; align-items: center; gap: 10px; }@@ -224,7 +212,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.card .tags, .result .tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }.card .human-mark { flex: none; margin-top: 1px; color: var(--muted); display: inline-flex; }.card .human-mark .icon svg { width: 15px; height: 15px; }-/* An on/off switch, for the Human field. */.human-field { display: flex; align-items: center; gap: 10px; }.props .human-field .hint { color: var(--faint); font-size: 12px; }.switch { position: relative; display: inline-flex; width: 34px; height: 20px; flex: none; }@@ -252,7 +239,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }}.empty h1 { color: var(--text); font-size: 22px; font-weight: 600; letter-spacing: -.01em; }-/* Task panel */.panel {position: fixed; top: 0; right: 0; bottom: 0; width: min(500px, 100vw); background: var(--panel);border-left: 1px solid var(--border); box-shadow: var(--shadow);@@ -266,7 +252,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.panel .top .ghost { width: auto; padding: 6px; color: var(--muted); }.panel .top .ghost:hover { color: var(--text); }.panel .top .ghost.danger:hover { color: var(--danger); background: var(--danger-bg); }-/* The project, shown as a tag; picking another one moves the task. */.panel .project-pick select {appearance: none; -webkit-appearance: none; border: 0; background: none; padding: 0; margin: 0;font-size: inherit; color: inherit; cursor: pointer; field-sizing: content;@@ -275,7 +260,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.panel .body { overflow-y: auto; padding: 8px 20px 24px; display: flex; flex-direction: column; gap: 20px; flex: 1; }/* The body scrolls instead; without this a long task squeezes the title and textareas to nothing. */.panel .body > * { flex-shrink: 0; }-/* Title and description look like text and are edited in place. */.panel .inline {border: 0; background: none; padding: 6px 10px; margin: -6px -10px; border-radius: 10px;width: calc(100% + 20px); resize: none; overflow: hidden; display: block;@@ -294,7 +278,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.comment { padding: 10px 0; }.comment:first-child { padding-top: 0; }.comment .who { font-size: 12px; color: var(--faint); margin-bottom: 2px; display: flex; align-items: center; gap: 4px; }-/* Each comment's delete button shows on hover, like the sidebar's "more" button. */.comment .remove {margin-left: auto; padding: 3px; border: 0; border-radius: 6px; background: none; color: var(--faint);visibility: hidden;@@ -304,7 +287,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.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; }@@ -322,7 +304,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.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 {display: block; width: 100%; min-height: 84px; max-height: 50vh; resize: none; border: 0; background: none;@@ -336,7 +317,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.composer .send:disabled { opacity: .25; cursor: default; }.composer .send .icon svg { width: 16px; height: 16px; stroke-width: 2.2; }-/* Rendered Markdown */.md > :first-child { margin-top: 0; }.md > :last-child { margin-bottom: 0; }.md p, .md ul, .md ol, .md pre, .md blockquote { margin: 0 0 .6em; }@@ -350,7 +330,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.md blockquote { border-left: 3px solid var(--active); padding-left: 10px; color: var(--muted); }.md a { color: var(--link); }-/* The search window, as in ChatGPT. */.search-dialog {position: fixed; inset: 0; z-index: 40; background: rgba(0,0,0,.45);display: flex; justify-content: center; align-items: flex-start; padding: 12vh 16px 16px;@@ -371,7 +350,6 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.dialog-window h2 { margin: 0; font-size: 17px; font-weight: 600; }.dialog-window p { margin: 0; color: var(--muted); line-height: 1.45; }.dialog-window .row { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-top: 4px; }-/* The settings window, as in Claude's: categories on the left, their settings on the right. */.settings-window {width: min(760px, 100%); height: min(460px, 76vh); display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden;background: var(--panel); border: 1px solid var(--border); border-radius: 18px; box-shadow: var(--shadow);@@ -396,10 +374,7 @@ header .repo-link .icon svg { width: 14px; height: 14px; }.setting .text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }.setting .text span { color: var(--muted); font-size: 13px; }label.setting { cursor: pointer; }-/* Joining a board: the address, under the row that offers it. */-/* A setting that can't change now, like sharing while this computer uses another board. */.setting.disabled, .popover form.disabled { opacity: .5; cursor: default; }-/* The share popover, under its icon: share this board, or join another computer's. */.popover {position: fixed; z-index: 30; width: 340px; max-width: calc(100vw - 16px); padding: 16px;display: flex; flex-direction: column; gap: 12px; background: var(--menu);@@ -411,7 +386,6 @@ label.setting { cursor: pointer; }.popover .row .field { flex: 1; min-width: 0; }.popover .error { margin: 0; color: var(--danger); font-size: 13px; }.popover .hint { margin: 0; color: var(--faint); font-size: 12px; }-/* The addresses other computers join, each copied with a click. */#network-addresses { display: flex; flex-direction: column; gap: 6px; }.popover .copy {display: flex; align-items: center; gap: 8px; padding: 8px 12px; border: 0; border-radius: 10px;@@ -424,7 +398,6 @@ label.setting { cursor: pointer; }/* One solid red in both themes: dark mode's --danger is a light red for text. */.btn.danger { background: #dc2626; color: #fff; }.btn.danger:hover, .btn.danger:focus-visible { background: #dc2626; opacity: .85; }-/* The computers using a shared board. */.guests { display: flex; flex-direction: column; gap: 8px; }.guests .label { color: var(--muted); font-size: 13px; }.guest { display: flex; align-items: center; gap: 8px; }@@ -465,7 +438,6 @@ label.setting { cursor: pointer; }.settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }#settings-nav { flex-direction: row; border-right: 0; border-bottom: 1px solid var(--border); }header { padding: 12px; }- /* On a phone the filter takes its own line, below the title and buttons. */#filters { order: 1; }#filter { order: 1; flex: 1 0 100%; width: auto; }}diff --git a/src/main.rs b/src/main.rsindex 9c26100..606d356 100644--- a/src/main.rs+++ b/src/main.rs@@ -112,9 +112,8 @@ fn main() -> ExitCode {{update::remove_old_exes(&exe);}- // 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.+ // The board serves one person and each agent starts its own `kanzo mcp`, so one async+ // thread is enough, and blocking threads exit when idle: this keeps kanzo light on small boards.let outcome = tokio::runtime::Builder::new_current_thread().enable_all().max_blocking_threads(8)@@ -140,12 +139,11 @@ async fn run(cli: Cli) -> anyhow::Result<()> {_ => Home::resolve(cli.home)?,};let mut home = Home::open(dir)?;- // `--port` reaches the board on that port, for `kanzo share` and the others too.if let Some(port) = cli.port {home.config.port = port;}match cli.command {- None => web::serve(home, cli.port, !cli.no_open).await,+ None => web::serve(home, !cli.no_open).await,Some(Command::Mcp) => mcp::serve(home).await,Some(Command::Init { .. }) => {println!("Kanzo data folder ready at {}", home.dir.display());@@ -171,30 +169,16 @@ async fn run(cli: Cli) -> anyhow::Result<()> {OnOff::On => share::Change::On,OnOff::Off => share::Change::Off,});- let (status, running) = share::request(&home, change).await?;- // Sharing with no board running starts one, already shared.- if matches!(state, Some(OnOff::On)) && !running {- return web::serve(home, cli.port, !cli.no_open).await;- }- println!("{}", status.message());- Ok(())- }- Some(Command::Join { host }) => {- println!("{}", share::request(&home, Some(share::Change::Join(host))).await?.0.message());- Ok(())- }- Some(Command::Leave) => {- println!("{}", share::request(&home, Some(share::Change::Leave)).await?.0.message());- Ok(())+ network(home, change, !cli.no_open).await}+ Some(Command::Join { host }) => network(home, Some(share::Change::Join(host)), !cli.no_open).await,+ Some(Command::Leave) => network(home, Some(share::Change::Leave), !cli.no_open).await,Some(Command::Service { action: ServiceAction::Install }) => service::install(&home),Some(Command::Service { action: ServiceAction::Uninstall }) => service::uninstall(),Some(Command::Update) => unreachable!("handled above"),}}-/// `kanzo update`: installs the latest release over this program, then restarts the-/// board's service, if there is one, so it runs the new version too.fn update_kanzo() -> anyhow::Result<()> {let Some(latest) = update::latest(true) else {anyhow::bail!("can't reach GitHub to check for updates");@@ -212,3 +196,13 @@ fn update_kanzo() -> anyhow::Result<()> {}Ok(())}++async fn network(home: Home, change: Option<share::Change>, open: bool) -> anyhow::Result<()> {+ let sharing = matches!(change, Some(share::Change::On));+ let (status, running) = share::request(&home, change).await?;+ if sharing && !running {+ return web::serve(home, open).await;+ }+ println!("{}", status.message());+ Ok(())+}diff --git a/src/mcp.rs b/src/mcp.rsindex 2a4ca70..613c8c9 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -1,4 +1,3 @@-//! 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;@@ -27,24 +26,33 @@ use crate::home::Home;use crate::share::{self, Net};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.+/// An old board has thousands of done tasks.const DONE_LISTED: usize = 20;-const INSTRUCTIONS: &str = "The user's kanban board, on this machine, for all their projects. Tasks look like \-api#12. Without `project`, Kanzo uses the project linked to this folder's GitHub repo. Keep it current unasked: \-doing when you start a task, comments on what you did, review when you finish or get stuck. Leave done and \-human tasks to the user.";+macro_rules! instructions {+ ($whose:literal, $project:literal) => {+ concat!(+ "The user's kanban board, on ",+ $whose,+ " 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. Leave done and human tasks to the user."+ )+ };+}-const HTTP_INSTRUCTIONS: &str = "The user's kanban board, on their machine, for all their projects. Tasks look \-like api#12. Over HTTP Kanzo can't see your folder, so pass `project` (see list_projects). Keep it current \-unasked: doing when you start a task, comments on what you did, review when you finish or get stuck. Leave \-done and human tasks to the user.";+const INSTRUCTIONS: &str =+ instructions!("this", "Without `project`, Kanzo uses the project linked to this folder's GitHub repo.");+const HTTP_INSTRUCTIONS: &str =+ instructions!("their", "Over HTTP Kanzo can't see your folder, so pass `project` (see list_projects).");++const NO_PROJECTS: &str = "There are no projects yet. Create one with create_project.";-/// `kanzo mcp`: one agent on stdin and stdout, in the folder it started us in.pub async fn serve(home: Home) -> Result<()> {let cwd = std::env::current_dir().unwrap_or_default();let repos = git_repos(&cwd);- let images = home.dir.join("images");+ let images = home.images();let ctx = Ctx { home, cwd: Some(cwd), repos, images, host: Default::default() };let server = Kanzo { ctx: Arc::new(ctx), tool_router: Kanzo::tools() };let service = server.serve(rmcp::transport::stdio()).await?;@@ -52,11 +60,10 @@ pub async fn serve(home: Home) -> Result<()> {Ok(())}-/// MCP over HTTP, mounted at `/mcp` by the board. The board's own Host and Origin-/// checks (`web::protect`) guard it, including when it listens on the network, so-/// rmcp's localhost-only list is turned off here.+/// `web::protect` checks Host and Origin, including when the board listens on the network,+/// so rmcp's localhost-only list is turned off.pub fn http_service(home: Home, shutdown: CancellationToken) -> StreamableHttpService<Kanzo, LocalSessionManager> {- let images = home.dir.join("images");+ let images = home.images();let ctx = Arc::new(Ctx { home, cwd: None, repos: Vec::new(), images, host: Default::default() });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.@@ -70,19 +77,20 @@ pub fn http_service(home: Home, shutdown: CancellationToken) -> StreamableHttpSestruct Ctx {home: Home,- /// The agent's working folder; `None` over HTTP, where we cannot know it.cwd: Option<PathBuf>,- /// GitHub repos (`owner/repo`) of the git remotes of `cwd`.repos: Vec<String>,- /// Where the agent finds the images of tasks: on a computer that joined this board,- /// its own folder, which fetches them from here.images: PathBuf,- /// The board this computer joined, while `kanzo mcp` uses it for the agent.host: tokio::sync::Mutex<Option<share::Upstream>>,}impl Ctx {- /// The named project, or the one linked to this folder's git remote.+ fn scope(&self, store: &Store, name: Option<&str>) -> store::Result<Option<Project>> {+ if name.is_some_and(|p| p.trim().eq_ignore_ascii_case("all")) {+ return Ok(None);+ }+ self.project(store, name).map(Some)+ }+fn project(&self, store: &Store, name: Option<&str>) -> store::Result<Project> {if let Some(name) = name.map(str::trim).filter(|n| !n.is_empty()) {return store.find_project(name);@@ -94,38 +102,38 @@ impl Ctx {}let known: Vec<String> = store.list_projects()?.into_iter().map(|p| p.slug).collect();let known = known.join(", ");- let Some(cwd) = &self.cwd else {- let msg = if known.is_empty() {- "There are no projects yet. Create one with create_project.".to_string()- } else {+ let msg = match (self.cwd.as_ref().map(|c| c.display()), self.repos.first(), known.is_empty()) {+ (_, None, true) => NO_PROJECTS.to_string(),+ (None, ..) => {format!("Pass `project` (one of: {known}); over HTTP Kanzo cannot see which folder you work in.")- };- return Err(Error::NotFound(msg));- };- let cwd = cwd.display();- let msg = match (self.repos.first(), known.is_empty()) {- (Some(repo), false) => format!(+ }+ (Some(cwd), Some(repo), false) => format!("No project is linked to {repo} (the git remote of {cwd}). Pass `project` (one of: {known}), \link this repo to one with link_repo, or create a project for it with create_project and repo \"{repo}\"."),- (Some(repo), true) => format!(+ (Some(cwd), Some(repo), true) => format!("No project is linked to {repo} (the git remote of {cwd}), and there are no projects yet. \Create one with create_project and repo \"{repo}\"."),- (None, false) => {+ (Some(cwd), None, false) => {format!("Cannot tell the project: {cwd} has no git remote. Pass `project` (one of: {known}).")}- (None, true) => "There are no projects yet. Create one with create_project.".to_string(),};Err(Error::NotFound(msg))}}+fn reply(outcome: Result<String, String>) -> CallToolResult {+ match outcome {+ Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]),+ Err(text) => CallToolResult::error(vec![ContentBlock::text(text)]),+ }+}+fn git_repos(dir: &std::path::Path) -> Vec<String> {- let Ok(out) = Command::new("git").arg("-C").arg(dir).args(["remote", "-v"]).output() else {+ let Ok(text) = crate::home::output(Command::new("git").arg("-C").arg(dir).args(["remote", "-v"])) else {return Vec::new();};- let text = String::from_utf8_lossy(&out.stdout);// `origin` first, so it wins when several remotes are linked to different projects.let mut lines: Vec<&str> = text.lines().collect();lines.sort_by_key(|l| !l.starts_with("origin\t"));@@ -146,8 +154,7 @@ pub struct Kanzo {tool_router: ToolRouter<Self>,}-/// A task, as `api#12` or just `12`. Agents are told it is a string, which keeps the-/// tool schemas short; a bare number is accepted too.+/// Agents are told it is a string, which keeps the tool schemas short; a bare number is accepted too.#[derive(Deserialize)]#[serde(untagged)]enum TaskKey {@@ -245,8 +252,8 @@ struct NextTaskArgs {}impl Kanzo {- /// The tool list without the `$schema` line rmcp puts in every input schema, nor the- /// `null` of optional fields: agents read this list in every session, so each byte counts.+ /// Drops rmcp's `$schema` line and the `null` of optional fields: agents read this list in+ /// every session, so each byte counts.fn tools() -> ToolRouter<Self> {let mut router = Self::tool_router();for route in router.map.values_mut() {@@ -271,14 +278,10 @@ impl Kanzo {#[tool_router]impl Kanzo {- /// Runs `f` with a fresh connection on a blocking thread and turns the- /// outcome into text; errors go back to the agent as tool errors it can read.async fn run(&self, f: impl FnOnce(&Ctx, &Store) -> store::Result<String> + Send + 'static) -> CallToolResult {self.run_for(&Extensions::default(), f).await}- /// Like `run`, with the agent's folder when `kanzo mcp` on a computer that joined- /// this board sent it along with the message.async fn run_for(&self,ext: &Extensions,@@ -309,10 +312,7 @@ impl Kanzo {}).await.unwrap_or_else(|e| Err(format!("internal error: {e}")));- match outcome {- Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]),- Err(text) => CallToolResult::error(vec![ContentBlock::text(text)]),- }+ reply(outcome)}#[tool(description = "List projects with their repos and open task counts.")]@@ -321,7 +321,7 @@ impl Kanzo {.run_for(&ext, |ctx, store| {let projects = store.list_projects()?;if projects.is_empty() {- return Ok("No projects yet. Create one with create_project.".into());+ return Ok(NO_PROJECTS.into());}let here = projects.iter().find(|p| p.repos.iter().any(|r| ctx.repos.contains(r)));let mut out = String::new();@@ -377,27 +377,20 @@ impl Kanzo {) -> Result<CallToolResult, ErrorData> {Ok(self.run_for(&ext, move |ctx, store| {- 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 project = ctx.scope(store, args.project.as_deref())?;let status = args.status.as_deref().map(str::trim).filter(|s| !s.is_empty());let only = match status {Some("all") | None => None,- Some(s) if store.statuses().iter().any(|x| x == s) => Some(s),Some(s) => {- return Err(Error::Invalid(format!(- "unknown status {s:?}; use one of: {}, or all",- store.statuses().join(", ")- )));+ store.check_status(s)?;+ Some(s)}};- // Done tasks only pile up: without a status leave them out, with one keep- // the newest.let keep = if status.is_none() { 0 } else { DONE_LISTED };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 done = store::DONE;let mut out = String::new();- // Tasks for a person are left out: agents leave them alone.let mut people = 0;for t in &tasks {if t.human {@@ -412,8 +405,11 @@ impl Kanzo {let _ = writeln!(out, "No tasks in {scope}.");}if people > 0 {- let tasks = if people == 1 { "task" } else { "tasks" };- let _ = writeln!(out, "({people} human {tasks} not shown: for the user, not for agents)");+ let _ = writeln!(+ out,+ "({people} human {} not shown: for the user, not for agents)",+ store::tasks(people)+ );}if hidden > 0 && status.is_none() {let _ = writeln!(out, "({hidden} {done} not shown; pass status \"{done}\" or \"all\")");@@ -513,8 +509,7 @@ impl Kanzo {) -> Result<CallToolResult, ErrorData> {Ok(self.run_for(&ext, move |ctx, store| {- 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 project = ctx.scope(store, args.project.as_deref())?;match store.next_task(project.as_ref().map(|p| p.id))? {Some(task) => Ok(format!("Moved to {}:\n{}", task.status, task_detail(ctx, store, &task)?)),None => {@@ -547,8 +542,7 @@ impl Kanzo {// untrimmed one for every request.#[tool_handler(router = self.tool_router)]impl ServerHandler for Kanzo {- /// On a computer that joined another's board, each call goes to that board, so agents- /// already running switch boards on their next call when this computer joins or leaves.+ /// Checked on every call, so agents already running switch boards when this computer joins or leaves.async fn call_tool(&self,request: CallToolRequestParams,@@ -565,11 +559,7 @@ impl ServerHandler for Kanzo {let client = context.peer.peer_info().and_then(|p| serde_json::to_value(&*p).ok());let upstream = upstream.as_mut().expect("set above");let outcome = upstream.call(client, &request.name, request.arguments).await;- return Ok(match outcome {- Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]),- Err(text) => CallToolResult::error(vec![ContentBlock::text(text)]),- }- .into());+ return Ok(reply(outcome).into());}self.tool_router.call(ToolCallContext::new(self, request, context)).await}@@ -581,9 +571,8 @@ impl ServerHandler for Kanzo {}}-/// `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);+ let _ = write!(out, "{} [{}] {}", t.key(), t.status, t.title);write_tags(out, t);match t.comments {0 => {}@@ -594,14 +583,12 @@ fn task_line(out: &mut String, t: &Task) {}}-/// ` {bug, ui}`, or nothing without tags.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.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)?;@@ -610,14 +597,13 @@ 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);+ let mut out = format!("{} {}", t.key(), 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.if updated != created {let _ = write!(out, ", updated {updated}");}diff --git a/src/service.rs b/src/service.rsindex 6c13190..b5eb42d 100644--- a/src/service.rs+++ b/src/service.rs@@ -1,13 +1,9 @@-//! `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 Task Scheduler task on Windows.-use std::path::{Path, PathBuf};use std::process::Command;use anyhow::{Context, Result, bail};-use crate::home::Home;+use crate::home::{Home, output};const LABEL: &str = "com.github.emanuele-em.kanzo";const UNIT: &str = "kanzo.service";@@ -38,8 +34,6 @@ pub fn uninstall() -> Result<()> {}}-/// Restarts the service, if it's installed, so it runs a newly installed Kanzo; false-/// when there's none.pub fn restart() -> Result<bool> {if cfg!(target_os = "macos") && plist_path()?.exists() {run("launchctl", &["kickstart", "-k", &format!("{}/{LABEL}", launchd_domain()?)])?;@@ -57,24 +51,16 @@ fn home_dir() -> Result<PathBuf> {dirs::home_dir().context("cannot find your home folder")}-/// Runs a command and fails with its own error output.fn run(cmd: &str, args: &[&str]) -> Result<()> {- let out = Command::new(cmd).args(args).output().with_context(|| format!("cannot run {cmd}"))?;- if !out.status.success() {- bail!("{cmd} {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());- }- Ok(())+ output(Command::new(cmd).args(args)).map(drop)}-// macOS-fn plist_path() -> Result<PathBuf> {Ok(home_dir()?.join("Library/LaunchAgents").join(format!("{LABEL}.plist")))}fn launchd_domain() -> Result<String> {- let uid = Command::new("id").arg("-u").output().context("cannot run id -u")?;- Ok(format!("gui/{}", String::from_utf8_lossy(&uid.stdout).trim()))+ Ok(format!("gui/{}", output(Command::new("id").arg("-u"))?))}fn xml_escape(s: &str) -> String {@@ -145,8 +131,6 @@ fn uninstall_launchd() -> Result<()> {Ok(())}-// Linux-fn unit_path() -> Result<PathBuf> {let config = match std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {Some(dir) => PathBuf::from(dir),@@ -155,7 +139,6 @@ fn unit_path() -> Result<PathBuf> {Ok(config.join("systemd/user").join(UNIT))}-/// Quotes one argument for a systemd `ExecStart=` line.fn systemd_quote(s: &str) -> String {format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%"))}@@ -207,11 +190,9 @@ 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`).+/// cmd outlives this process, which may be the board. `ping` waits 3 s for the port to be+/// let go, as `timeout` needs a console. `/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");@@ -220,27 +201,22 @@ fn restart_task() -> Result<()> {// 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());- }+ output(&mut cmd).context("cannot restart the Kanzo task")?;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())+ output(Command::new("schtasks").args(["/query", "/tn", TASK])).is_ok()}-/// 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.+/// Runs 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('"', """);format!(@@ -269,16 +245,15 @@ fn task(exe: &Path, dir: &Path, user: &str) -> String {)}-/// `domain\user`, from Windows in UTF-8: `whoami` prints in the console's code page, and-/// %USERDOMAIN% is WORKGROUP over SSH.+/// Not `whoami`, which prints in the console's code page, nor %USERDOMAIN%, which 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());+ let user = output(Command::new("powershell").args(["-NoProfile", "-Command", name]))+ .context("cannot find your Windows account")?;+ if user.is_empty() {+ bail!("cannot find your Windows account");}Ok(user)}diff --git a/src/share.rs b/src/share.rsindex c0d79a0..5315025 100644--- a/src/share.rs+++ b/src/share.rs@@ -1,9 +1,3 @@-//! Sharing the board on your network: `kanzo share on|off`, `kanzo join <host>` and `kanzo leave`.-//!-//! A shared board listens on the network as well as on this computer. A computer that-//! joined one keeps its own board as a window onto it: the board hands the page's-//! requests to the host (`forward`), and `kanzo mcp` hands it agents' tool calls (`Upstream`).-use std::fmt::Write as _;use std::io;use std::net::{IpAddr, SocketAddr};@@ -12,7 +6,6 @@ use std::sync::OnceLock;use std::time::Duration;use anyhow::{Context, Result, bail};-use axum::Json;use axum::body::Body;use axum::extract::Request;use axum::http::{HeaderName, HeaderValue, StatusCode};@@ -25,17 +18,11 @@ use tokio_util::io::ReaderStream;use crate::home::{DEFAULT_PORT, Home};-/// The file in the data folder that says what this computer does on the network:-/// `share`, or `join <host:port>`; none for neither. `kanzo sync` leaves it out.pub const FILE: &str = "network";-/// Sent by `kanzo mcp` on a guest with every message, so the host finds the agent's-/// project as it would on its own computer.pub const FOLDER_HEADER: &str = "x-kanzo-folder";pub const REPOS_HEADER: &str = "x-kanzo-repos";-/// Where a guest's agent finds task images: its own folder, which fetches them from the host.pub const IMAGES_HEADER: &str = "x-kanzo-images";-/// Sent by a guest's board and `kanzo mcp`, so the host can list who's using it.pub const COMPUTER_HEADER: &str = "x-kanzo-computer";/// Larger than any image the board takes.@@ -45,7 +32,6 @@ const BODY_LIMIT: usize = 32 * 1024 * 1024;pub enum Net {Private,Sharing,- /// Using another computer's board, at `host:port`.Joined(String),}@@ -74,8 +60,6 @@ impl Net {}}-/// What the board's settings, `kanzo share`, `kanzo join` and `kanzo leave` ask for,-/// as the board's `/api/network` takes it: `{"action": "join", "host": "192.168.0.12"}`.#[derive(Debug, Serialize, Deserialize)]#[serde(tag = "action", content = "host", rename_all = "lowercase")]pub enum Change {@@ -85,8 +69,6 @@ pub enum Change {Leave,}-/// Checks `change` against what this computer does now, and saves the outcome. The-/// running board calls this, then listens as it says; without one, the next board does.pub async fn change(home: &Home, change: Change) -> Result<Net, String> {let now = Net::load(home);let next = match (change, &now) {@@ -119,7 +101,6 @@ pub async fn change(home: &Home, change: Change) -> Result<Net, String> {Ok(next)}-/// `192.168.0.12` or `mac-mini.local` as `host:port`, with Kanzo's port unless one is given.fn address(host: &str) -> Result<String, String> {let host = host.trim().trim_start_matches("http://").trim_end_matches('/');if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || ".-:[]".contains(c)) {@@ -138,22 +119,16 @@ fn address(host: &str) -> Result<String, String> {Ok(full)}-/// What this computer does on the network, as `/api/network` answers.#[derive(Debug, Serialize, Deserialize)]pub struct Status {state: State,- /// Once joined, the host's address.host: Option<String>,- /// While sharing, this computer's addresses for `kanzo join`, one per network it is on.addresses: Vec<String>,- /// While sharing, the other computers using the board now.guests: Vec<Guest>,}-/// Another computer using this board.#[derive(Debug, Serialize, Deserialize)]pub struct Guest {- /// Like "Ada's MacBook Air"; `None` for a browser opened straight at this board.pub name: Option<String>,pub address: IpAddr,}@@ -206,8 +181,7 @@ impl Status {}}-/// This computer's addresses, as others pass them to `kanzo join`: one per network it is-/// on, like the home network and a VPN. Which one works depends on where the other computer is.+/// One per network, like the home network and a VPN: which one works depends on where the other computer is.fn addresses(port: u16) -> Vec<String> {let interfaces = if_addrs::get_if_addrs().unwrap_or_default();interfaces@@ -217,9 +191,6 @@ fn addresses(port: u16) -> Vec<String> {.collect()}-/// Asks the running board for `change`, which then takes effect at once, or only for its-/// state; with no board running, saves the change for the next one. Also says whether a-/// board is running.pub async fn request(home: &Home, change: Option<Change>) -> Result<(Status, bool)> {let port = home.config.port;let (method, body) = match &change {@@ -250,8 +221,7 @@ pub async fn request(home: &Home, change: Option<Change>) -> Result<(Status, boo}}-/// One HTTP reply. Requests are HTTP/1.0, so the body is all that comes until the host-/// closes the connection, with no chunks to decode.+/// Requests are HTTP/1.0, so the body is all that comes until the host closes the connection, with no chunks to decode.struct Reply {status: u16,headers: Vec<(String, String)>,@@ -291,7 +261,6 @@ async fn send(host: &str, method: &str, path: &str, headers: &[(&str, &str)], boOk(Reply { status, headers, body: reader })}-/// True when `host` answers like a Kanzo board.pub async fn is_kanzo(host: &str) -> bool {let probe = async {let mut reply = send(host, "GET", "/api/ping", &[], b"").await.ok()?;@@ -302,17 +271,15 @@ pub async fn is_kanzo(host: &str) -> bool {tokio::time::timeout(Duration::from_secs(2), probe).await.ok().flatten().unwrap_or(false)}-/// This computer's name, as guests send it.fn computer() -> &'static str {static NAME: OnceLock<String> = OnceLock::new();- NAME.get_or_init(crate::sync::hostname)+ NAME.get_or_init(crate::home::hostname)}fn unreachable(host: &str) -> String {format!("The shared board at {host} isn't reachable; run kanzo leave to use this computer's board.")}-/// Hands one of the page's requests to the board this computer joined, and streams back its reply.pub async fn forward(host: &str, req: Request) -> Response {let (parts, body) = req.into_parts();let Ok(body) = axum::body::to_bytes(body, BODY_LIMIT).await else {@@ -329,7 +296,7 @@ pub async fn forward(host: &str, req: Request) -> Response {headers.push((COMPUTER_HEADER, computer()));let path = parts.uri.path_and_query().map_or("/", |p| p.as_str());let Ok(reply) = send(host, parts.method.as_str(), path, &headers, &body).await else {- return (StatusCode::BAD_GATEWAY, Json(json!({ "error": unreachable(host) }))).into_response();+ return crate::web::fail(StatusCode::BAD_GATEWAY, unreachable(host)).into_response();};let mut res = Response::new(Body::from_stream(ReaderStream::new(reply.body)));*res.status_mut() = StatusCode::from_u16(reply.status).unwrap_or(StatusCode::BAD_GATEWAY);@@ -343,8 +310,6 @@ pub async fn forward(host: &str, req: Request) -> Response {res}-/// `kanzo mcp`'s session with the board this computer joined, for one agent: its tool-/// calls go there, with the agent's folder so the host finds the project.pub struct Upstream {host: String,session: Option<String>,@@ -363,8 +328,6 @@ impl Upstream {&self.host}- /// Calls the tool `name` on the host, as the agent `client` (its `initialize`- /// parameters, so comments keep its name). Answers its text, or its error.pub async fn call(&mut self,client: Option<Value>,@@ -404,8 +367,7 @@ impl Upstream {if result["isError"] == true { Err(text) } else { Ok(text) }}- /// Images live on the host. The host names them in this computer's images folder, and- /// this fetches the ones missing there; names are their content's hash, so a copy never goes stale.+ /// Names are their content's hash, so a copy never goes stale.async fn fetch_images(&self, text: &str) {let folder = self.images.display().to_string();for (at, _) in text.match_indices(&folder) {@@ -418,18 +380,11 @@ impl Upstream {let Ok(mut reply) = send(&self.host, "GET", &format!("/images/{file}"), &[], b"").await else { continue };let mut bytes = Vec::new();if reply.status == 200 && reply.body.read_to_end(&mut bytes).await.is_ok() {- // Under a temporary name first, so a half-written image never has the real one.- let partial = path.with_extension("part");- let saved = std::fs::create_dir_all(&self.images).and_then(|()| std::fs::write(&partial, &bytes));- if saved.is_ok() {- let _ = std::fs::rename(&partial, &path);- }+ let _ = crate::home::write_whole(&path, &bytes);}}}- /// Sends one message: the status, and the messages the host answered with, as JSON- /// or as a stream of events.async fn post(&mut self, line: &str) -> io::Result<(u16, Vec<Value>)> {let images = self.images.display().to_string();let mut headers = vec![@@ -492,7 +447,6 @@ mod tests {assert_eq!(apply(Change::Off).unwrap(), Net::Joined("192.168.0.12:4242".into()));assert_eq!(apply(Change::Leave).unwrap(), Net::Private);- // A board config.toml opens to the network is shared, and can't join another.std::fs::write(tmp.path().join("config.toml"), "listen = \"0.0.0.0\"\n").unwrap();let home = Home::open(tmp.path().to_path_buf()).unwrap();assert_eq!(Net::load(&home), Net::Sharing);diff --git a/src/store.rs b/src/store.rsindex 21a21d5..f6bcae5 100644--- a/src/store.rs+++ b/src/store.rs@@ -1,9 +1,7 @@-//! All reads and writes of `kanzo.db`. Plain SQL, one short-lived connection per operation.-//!//! The database uses a rollback journal (`journal_mode = TRUNCATE`), not WAL. With a//! connection per operation, WAL would set up and tear down its `-wal` and `-shm` files//! on every request; the rollback journal makes a read touch no extra files at all and-//! measured about 3x faster per operation. Writes queue on the busy timeout.+//! measured about 3x faster per operation.use std::fmt;use std::path::Path;@@ -18,15 +16,11 @@ use serde::Serialize;/// only for a migration that older code can't live with, like a renamed column.const COMPATIBLE_FROM: usize = 4;-/// Schema migrations, applied in order. Index + 1 is the `schema_version` they lead to.const MIGRATIONS: &[&str] = &[include_str!("schema.sql"),- // 2: a colour picked for the project; NULL leaves the board to choose one."ALTER TABLE projects ADD COLUMN color TEXT;",- // 3: a task's tags, comma-separated (see `clean_tags`)."ALTER TABLE tasks ADD COLUMN tags TEXT NOT NULL DEFAULT '';",- // 4: any number of repos per project. Each repo belongs to one project. The old- // projects.repo column stays, empty: SQLite can only drop it by rebuilding the table.+ // The old projects.repo column stays, empty: SQLite can only drop it by rebuilding the table."CREATE TABLE project_repos (repo TEXT PRIMARY KEY,project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE@@ -36,7 +30,6 @@ 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,@@ -47,11 +40,9 @@ const MIGRATIONS: &[&str] = &[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;",- // 6: tasks for a person, which agents leave alone."ALTER TABLE tasks ADD COLUMN human INTEGER NOT NULL DEFAULT 0;",];-/// The colours a project can be given; the board maps each name to a shade.const PROJECT_COLORS: &[&str] = &["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"];const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";@@ -60,7 +51,6 @@ const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";pub enum Error {NotFound(String),Invalid(String),- /// Another process holds the data folder for longer than we wait, like a long `kanzo sync`.Busy(String),Db(rusqlite::Error),}@@ -96,12 +86,9 @@ pub struct Project {pub id: i64,pub slug: String,pub name: String,- /// Linked GitHub repos as `owner/repo`, in the order they were linked.pub repos: Vec<String>,- /// One of `PROJECT_COLORS`, or `None` when never picked.pub color: Option<String>,pub created_at: String,- /// Tasks not in the last (done) column.pub open: i64,pub total: i64,}@@ -112,9 +99,7 @@ pub struct Task {pub project: String,pub title: String,pub description: String,- /// Lowercase, without duplicates, in the order they were given.pub tags: Vec<String>,- /// Work for a person: agents leave it alone, and `next_task` never picks it.pub human: bool,pub status: String,pub position: f64,@@ -124,7 +109,6 @@ pub struct Task {}impl Task {- /// How tasks are shown everywhere: `api#12`.pub fn key(&self) -> String {format!("{}#{}", self.project, self.id)}@@ -139,45 +123,38 @@ 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 {pub title: Option<String>,pub description: Option<String>,pub status: Option<String>,- /// Moves the task to this project (by id).pub project_id: Option<i64>,- /// Comma-separated; replaces all the tags, and an empty string clears them.pub tags: Option<String>,pub human: Option<bool>,}-/// The board's columns, left to right. New tasks go in todo, agents take theirs from-/// there and move them to doing, and tasks in done count as done.const STATUSES: [&str; 4] = ["todo", "doing", "review", "done"];-/// An optional column before todo, for tasks that agents leave alone.+pub const DONE: &str = STATUSES[3];+pub const BACKLOG: &str = "backlog";pub struct Store {conn: Connection,statuses: Vec<String>,- /// Held while the connection is open; declared after `conn` so it is released after it closes.+ /// Declared after `conn` so it is released after the connection closes._lock: Option<std::fs::File>,}impl Store {- /// Opens the database. `lock` is kept until the store is dropped (see `Home::store`).pub fn open(path: &Path, lock: Option<std::fs::File>) -> Result<Self> {let conn = Connection::open(path)?;// The board and any number of agents share this file; wait instead of failing.@@ -200,18 +177,11 @@ impl Store {&self.statuses}- fn done_status(&self) -> &str {- STATUSES[3]- }-- /// Shows or hides the backlog column. It must be empty to hide it, or its- /// tasks would vanish from the board.pub fn set_backlog(&self, on: bool) -> Result<()> {self.write(|c| {let left: i64 = c.query_row("SELECT count(*) FROM tasks WHERE status = ?1", [BACKLOG], |r| r.get(0))?;if !on && left > 0 {- let tasks = if left == 1 { "task" } else { "tasks" };- return Err(Error::Invalid(format!("move the {left} {tasks} out of backlog first")));+ return Err(Error::Invalid(format!("move the {left} {} out of backlog first", tasks(left))));}c.execute("INSERT INTO meta (key, value) VALUES ('backlog', ?1) ON CONFLICT(key) DO UPDATE SET value = excluded.value",@@ -223,8 +193,7 @@ impl Store {})}- /// Runs `f` in an immediate transaction, so concurrent writers queue up- /// on the busy timeout instead of failing halfway.+ /// Immediate, so concurrent writers queue up on the busy timeout instead of failing halfway.fn write<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {self.conn.execute_batch("BEGIN IMMEDIATE")?;match f(&self.conn) {@@ -239,8 +208,8 @@ impl Store {}}- /// Brings the schema up to date. Writes nothing when it already is, so starting- /// `kanzo mcp` for every agent session costs no disk write.+ /// Writes nothing when up to date, so starting `kanzo mcp` for every agent session+ /// costs no disk write.pub fn migrate(&self) -> Result<()> {let meta = |c: &Connection, key: &str| -> rusqlite::Result<Option<usize>> {Ok(c.query_row("SELECT value FROM meta WHERE key = ?1", [key], |r| r.get::<_, String>(0))@@ -278,7 +247,6 @@ impl Store {})}- /// Bumped by triggers on every write; the board polls it.pub fn changes(&self) -> Result<i64> {Ok(self.conn@@ -286,7 +254,6 @@ impl Store {.query_row([], |r| r.get(0))?)}- /// The current time, in the same format as the stored timestamps.pub fn now(&self) -> Result<String> {Ok(self.conn.query_row(&format!("SELECT {NOW}"), [], |r| r.get(0))?)}@@ -298,8 +265,6 @@ impl Store {Ok(())}- // Projects-const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name,(SELECT group_concat(repo, ',' ORDER BY r.rowid) FROM project_repos r WHERE r.project_id = p.id),p.color, p.created_at,@@ -323,13 +288,13 @@ impl Store {pub fn list_projects(&self) -> Result<Vec<Project>> {let sql = format!("{} ORDER BY p.slug", Self::PROJECT_SELECT);let mut stmt = self.conn.prepare(&sql)?;- let rows = stmt.query_map([self.done_status()], Self::project_row)?;+ let rows = stmt.query_map([DONE], Self::project_row)?;Ok(rows.collect::<rusqlite::Result<_>>()?)}fn project_where(&self, clause: &str, value: &str) -> Result<Option<Project>> {let sql = format!("{} WHERE {clause}", Self::PROJECT_SELECT);- Ok(self.conn.query_row(&sql, params![self.done_status(), value], Self::project_row).optional()?)+ Ok(self.conn.query_row(&sql, params![DONE, value], Self::project_row).optional()?)}pub fn project_by_slug(&self, slug: &str) -> Result<Option<Project>> {@@ -343,7 +308,6 @@ impl Store {}}- /// Finds a project by slug, or by linked repo when given `owner/repo`.pub fn find_project(&self, name: &str) -> Result<Project> {let found = match self.project_by_slug(name)? {Some(p) => Some(p),@@ -374,13 +338,14 @@ impl Store {n => n.to_string(),};let repo = repo.map(str::trim).filter(|r| !r.is_empty()).map(clean_repo).transpose()?;- if self.project_by_slug(&slug)?.is_some() {- return Err(Error::Invalid(format!("project {slug} already exists")));- }- if let Some(r) = &repo {- self.check_repo_free(r)?;- }- let created = self.write(|c| {+ // Checked in the write's transaction, so nobody can take the slug or the repo in between.+ self.write(|c| {+ if self.project_by_slug(&slug)?.is_some() {+ return Err(Error::Invalid(format!("project {slug} already exists")));+ }+ if let Some(r) = &repo {+ self.check_repo_free(r)?;+ }c.execute("INSERT INTO projects (slug, name) VALUES (?1, ?2)", params![slug, name])?;if let Some(r) = &repo {c.execute(@@ -389,36 +354,21 @@ impl Store {)?;}Ok(())- });- match created {- // Someone created the same project or linked the repo between our checks and the insert.- Err(Error::Db(rusqlite::Error::SqliteFailure(e, _)))- if e.code == rusqlite::ErrorCode::ConstraintViolation =>- {- Err(Error::Invalid(format!("project {slug} or its repo already exists")))- }- other => other,- }?;+ })?;self.find_project(&slug)}- /// Links another repo to a project. Each repo belongs to one project.pub fn link_repo(&self, slug: &str, repo: &str) -> Result<Project> {let project = self.find_project(slug)?;let repo = clean_repo(repo)?;if project.repos.contains(&repo) {return Ok(project);}- self.check_repo_free(&repo)?;- match self- .conn- .execute("INSERT INTO project_repos (repo, project_id) VALUES (?1, ?2)", params![repo, project.id])- {- Err(rusqlite::Error::SqliteFailure(e, _)) if e.code == rusqlite::ErrorCode::ConstraintViolation => {- return Err(Error::Invalid(format!("repo {repo} is already linked to another project")));- }- other => other?,- };+ self.write(|c| {+ self.check_repo_free(&repo)?;+ c.execute("INSERT INTO project_repos (repo, project_id) VALUES (?1, ?2)", params![repo, project.id])?;+ Ok(())+ })?;self.find_project(&project.slug)}@@ -441,7 +391,6 @@ 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 = squash(name);if name.is_empty() {@@ -461,7 +410,6 @@ impl Store {self.find_project(&project.slug)}- /// Deletes a project with all its tasks and their comments; returns the project as it was.pub fn delete_project(&self, slug: &str) -> Result<Project> {let project = self.find_project(slug)?;// Tasks and comments go with it through ON DELETE CASCADE.@@ -469,8 +417,6 @@ impl Store {Ok(project)}- // Tasks-const TASK_SELECT: &str = "SELECT t.id, p.slug, t.title, t.description, t.status, t.position,t.created_at, t.updated_at, (SELECT count(*) FROM comments c WHERE c.task_id = t.id), t.tags, t.humanFROM tasks t JOIN projects p ON p.id = t.project_id";@@ -491,21 +437,18 @@ 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.+ /// The done column only grows, so only its newest `keep_done` tasks are read.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();+ let done = DONE;// SQLite reads a negative LIMIT as no limit.let limit = keep_done.map_or(-1, |n| n as i64);let sql = format!(@@ -535,10 +478,7 @@ impl Store {Ok((tasks, hidden))}- /// Tasks of any project whose key, title, description, tags, project or comments hold- /// every word of `query`: open ones first, then the most recently changed. An empty- /// query gives the most recently changed tasks. The board's filter uses it too.- /// LIKE already ignores the case of ASCII letters, as lower() would.+ // LIKE already ignores the case of ASCII letters, as lower() would.pub fn search(&self, query: &str, limit: Option<usize>) -> Result<Vec<Task>> {let words: Vec<&str> = query.split_whitespace().take(10).collect();let mut sql = format!("{} WHERE 1", Self::TASK_SELECT);@@ -552,7 +492,7 @@ impl Store {// SQLite reads a negative LIMIT as no limit.let limit = limit.map_or(-1, |n| n as i64);sql.push_str(&format!(" ORDER BY t.status = ?1, t.updated_at DESC, t.id DESC LIMIT {limit}"));- let mut values: Vec<String> = vec![self.done_status().to_string()];+ let mut values: Vec<String> = vec![DONE.to_string()];for w in &words {let escaped = w.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_");values.push(format!("%{escaped}%"));@@ -571,7 +511,6 @@ impl Store {.ok_or_else(|| Error::NotFound(format!("no task #{id}")))}- /// Looks up `api#12`, `#12` or `12`. A project prefix must match the task's project.pub fn find_task(&self, key: &str) -> Result<Task> {let (slug, id) = parse_task_key(key)?;let task = self.get_task(id)?;@@ -583,7 +522,7 @@ impl Store {Ok(task)}- fn check_status(&self, status: &str) -> Result<()> {+ pub fn check_status(&self, status: &str) -> Result<()> {if self.statuses().iter().any(|s| s == status) {Ok(())} else {@@ -600,13 +539,11 @@ impl Store {Ok(max.map_or(1.0, |m| m.floor() + 1.0))}- /// Adds a task at the bottom of todo; a shorthand for tests.#[cfg(test)]pub fn create_task(&self, project_id: i64, title: &str, description: &str) -> Result<Task> {self.create_task_in(project_id, None, title, description)}- /// Adds a task at the bottom of `status`, todo when left out.pub fn create_task_in(&self,project_id: i64,@@ -635,36 +572,18 @@ impl Store {}self.write(|c| {let current = self.get_task(id)?;- if let Some(title) = title {- c.execute(- &format!("UPDATE tasks SET title = ?1, updated_at = {NOW} WHERE id = ?2"),- params![title, id],- )?;- }- if let Some(p) = patch.project_id {- c.execute(- &format!("UPDATE tasks SET project_id = ?1, updated_at = {NOW} WHERE id = ?2 AND project_id <> ?1"),- params![p, id],- )?;- }- if let Some(human) = patch.human {- c.execute(- &format!("UPDATE tasks SET human = ?1, updated_at = {NOW} WHERE id = ?2 AND human <> ?1"),- params![human, id],- )?;- }- if let Some(t) = &patch.tags {- c.execute(- &format!("UPDATE tasks SET tags = ?1, updated_at = {NOW} WHERE id = ?2"),- params![clean_tags(t).join(","), id],- )?;- }- if let Some(d) = &patch.description {- c.execute(- &format!("UPDATE tasks SET description = ?1, updated_at = {NOW} WHERE id = ?2"),- params![d.trim(), id],- )?;- }+ // Only what the patch changes is written, and only then is the task newer.+ let tags = patch.tags.as_deref().map(|t| clean_tags(t).join(","));+ c.execute(+ &format!(+ "UPDATE tasks SET title = coalesce(?1, title), project_id = coalesce(?2, project_id),+ human = coalesce(?3, human), tags = coalesce(?4, tags),+ description = coalesce(?5, description), updated_at = {NOW}+ WHERE id = ?6 AND (coalesce(?1, title), coalesce(?2, project_id), coalesce(?3, human),+ coalesce(?4, tags), coalesce(?5, description)) <> (title, project_id, human, tags, description)"+ ),+ params![title, patch.project_id, patch.human, tags, patch.description.as_deref().map(str::trim), id],+ )?;if let Some(s) = &patch.status&& *s != current.status{@@ -679,13 +598,11 @@ impl Store {self.get_task(id)}- /// Moves a task to `status`, just above task `before`, or to the bottom when `before` is `None`.pub fn move_task(&self, id: i64, status: &str, before: Option<i64>) -> Result<Task> {self.check_status(status)?;self.write(|c| {let current = self.get_task(id)?;let before = before.filter(|b| *b != id);- // 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| {@@ -707,7 +624,7 @@ impl Store {};let mut prev = prev_of(next)?;if prev.is_some_and(|p| next - p < 1e-9) {- // Out of room between two neighbours: renumber the column 1, 2, 3...+ // Out of float room between two neighbours.Self::renumber(c, status)?;next = c.query_row("SELECT position FROM tasks WHERE id = ?1", [before], |r| r.get(0))?;prev = prev_of(next)?;@@ -740,8 +657,6 @@ impl Store {Ok(())}- /// Takes the top task of todo that isn't for a person, and moves it to the bottom- /// of doing.pub fn next_task(&self, project_id: Option<i64>) -> Result<Option<Task>> {let [from, to, ..] = STATUSES;let id = self.write(|c| {@@ -765,37 +680,30 @@ impl Store {id.map(|id| self.get_task(id)).transpose()}- /// Deletes a task and its comments; returns the task as it was.pub fn delete_task(&self, id: i64) -> Result<Task> {let task = self.get_task(id)?;self.conn.execute("DELETE FROM tasks WHERE id = ?1", [id])?;Ok(task)}- // Comments-pub fn list_comments(&self, task_id: i64) -> Result<Vec<Comment>> {- 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 mut stmt = self.conn.prepare_cached(&format!("{} WHERE task_id = ?1 ORDER BY id", Self::COMMENT_SELECT))?;let rows = stmt.query_map([task_id], Self::comment_row)?;Ok(rows.collect::<rusqlite::Result<_>>()?)}+ const COMMENT_SELECT: &str = "SELECT id, task_id, author, body, created_at FROM comments";+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> {let body = body.trim();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")));- }+ images.iter().try_for_each(|f| check_image(f))?;let author = match author.trim() {"" => "me",a => a,@@ -818,59 +726,46 @@ 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],- Self::comment_row,- )+ .query_row(&format!("{} WHERE id = ?1", Self::COMMENT_SELECT), [id], Self::comment_row).optional()?.ok_or_else(|| Error::NotFound(format!("no comment {id}")))}- /// Deletes a comment; returns it as it was.pub fn delete_comment(&self, id: i64) -> Result<Comment> {let comment = self.get_comment(id)?;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")));- }+ check_image(file)?;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 mut stmt = self.conn.prepare_cached(&format!("{} WHERE task_id = ?1 ORDER BY id", Self::IMAGE_SELECT))?;let rows = stmt.query_map([task_id], Self::image_row)?;Ok(rows.collect::<rusqlite::Result<_>>()?)}+ const IMAGE_SELECT: &str = "SELECT id, task_id, comment_id, file FROM images";+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], Self::image_row)+ .query_row(&format!("{} WHERE id = ?1", Self::IMAGE_SELECT), [id], Self::image_row).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),@@ -885,7 +780,6 @@ impl Store {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();@@ -898,7 +792,6 @@ impl Store {}}-/// Whose images `Store::image_files` lists.pub enum ImagesOf {Image(i64),Comment(i64),@@ -906,18 +799,28 @@ pub enum ImagesOf {Project(i64),}-/// The name Kanzo gives a saved image: 16 hex digits and its type, like `6fec521a01297ab5.png`.+pub const IMAGE_TYPES: [(&str, &str); 4] =+ [("png", "image/png"), ("jpg", "image/jpeg"), ("gif", "image/gif"), ("webp", "image/webp")];++pub fn tasks(n: i64) -> &'static str {+ if n == 1 { "task" } else { "tasks" }+}+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)+ && IMAGE_TYPES.iter().any(|(e, _)| *e == ext)}None => false,}}+fn check_image(file: &str) -> Result<()> {+ if valid_image_file(file) { Ok(()) } else { Err(Error::Invalid(format!("{file:?} is not an image Kanzo saved"))) }+}+fn valid_slug(s: &str) -> bool {let b = s.as_bytes();!b.is_empty()@@ -926,7 +829,6 @@ 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"),@@ -934,7 +836,6 @@ pub fn short_time(ts: &str) -> String {}}-/// `" Bug, UI,bug ,, needs review"` -> `["bug", "ui", "needs review"]`.fn clean_tags(input: &str) -> Vec<String> {let mut tags: Vec<String> = Vec::new();for tag in input.split(',') {@@ -950,7 +851,6 @@ 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() {@@ -970,7 +870,6 @@ fn clean_title(title: &str) -> Result<String> {Ok(title)}-/// Splits `api#12`, `#12` or `12` into an optional project slug and the task id.fn parse_task_key(key: &str) -> Result<(Option<String>, i64)> {let key = key.trim();let (slug, num) = match key.rsplit_once('#') {@@ -984,16 +883,11 @@ fn parse_task_key(key: &str) -> Result<(Option<String>, i64)> {Ok((slug, id))}-/// Normalises a GitHub repo given as `owner/repo` or as any git remote URL-/// (`https://github.com/owner/repo.git`, `[email protected]:owner/repo`, ...) to lowercase `owner/repo`.-/// A browser URL like `https://github.com/owner/repo/tree/main` gives `owner/repo` too.pub fn repo_from_url(input: &str) -> Option<String> {let s = input.trim();let (path, bare) = if let Some((_, rest)) = s.split_once("://") {- // scheme://[user@]host[:port]/owner/repo...(rest.split_once('/')?.1, false)} else if let Some((_, rest)) = s.split_once(':') {- // user@host:owner/repo(rest, false)} else {(s, true)@@ -1062,14 +956,12 @@ mod tests {.unwrap();};let newer = MIGRATIONS.len() + 1;- // A newer Kanzo only added things: this one goes on using the board, untouched.set(newer, MIGRATIONS.len());s.migrate().unwrap();s.create_project("api", "", None).unwrap();let v: String =s.conn.query_row("SELECT value FROM meta WHERE key = 'schema_version'", [], |r| r.get(0)).unwrap();assert_eq!(v, newer.to_string());- // A change this version can't live with: it says how to update.set(newer, newer);assert!(s.migrate().unwrap_err().to_string().contains("kanzo update"));}@@ -1107,7 +999,6 @@ mod tests {assert_eq!(s.unlink_repo("api", "me/api").unwrap().repos, ["me/api-docs"]);assert!(s.project_by_repo("me/api").unwrap().is_none());assert!(s.unlink_repo("api", "me/api").is_err());- // A deleted project frees its repos.s.delete_project("api").unwrap();assert_eq!(s.link_repo("web", "me/api-docs").unwrap().repos, ["me/api-docs"]);}@@ -1144,7 +1035,6 @@ mod tests {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();@@ -1154,7 +1044,6 @@ mod tests {);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();@@ -1170,7 +1059,6 @@ mod tests {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("kanzo.db");{- // A board at schema version 3, from before projects could have several repos.let c = Connection::open(&path).unwrap();c.execute_batch("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)").unwrap();for sql in &MIGRATIONS[..3] {@@ -1257,7 +1145,6 @@ mod tests {};assert_eq!((count("projects"), count("tasks"), count("comments")), (1, 1, 1));assert!(s.delete_project("api").is_err());- // The slug and repo are free again.s.create_project("api", "", Some("me/api")).unwrap();}@@ -1294,7 +1181,6 @@ mod tests {let api = s.create_project("api", "", None).unwrap();let web = s.create_project("web", "", None).unwrap();s.create_task(web.id, "web first", "").unwrap();- // At the top of api's todo, but for a person: agents never get it.let human = s.create_task(api.id, "Call the bank", "").unwrap();assert!(s.update_task(human.id, TaskPatch { human: Some(true), ..Default::default() }).unwrap().human);s.create_task(api.id, "api first", "").unwrap();@@ -1326,7 +1212,6 @@ mod tests {assert!(s.next_task(None).unwrap().is_none());assert_eq!(s.get_task(backlog.id).unwrap().status, "backlog");- // Hiding it would hide its tasks.assert!(s.set_backlog(false).is_err());s.delete_task(backlog.id).unwrap();s.set_backlog(false).unwrap();@@ -1366,7 +1251,6 @@ mod tests {"https://github.com/owner/repo/","https://github.com/owner/repo/tree/main","https://github.com/owner/repo/pull/3",- // Gitea, or any other host: only owner/repo counts."https://gitea.example.com/owner/repo.git","[email protected]:owner/repo.git","ssh://[email protected]:2222/owner/repo.git",diff --git a/src/sync.rs b/src/sync.rsindex 822016d..76e40df 100644--- a/src/sync.rs+++ b/src/sync.rs@@ -1,5 +1,3 @@-//! `kanzo sync`: keep the data folder in step with its git remote, one machine at a time.-use std::path::Path;use std::process::Command;@@ -13,8 +11,6 @@ pub enum Keep {Remote,}-/// The error when both sides changed the board: the caller asks which one to keep.-/// `first` when this is the first sync with that repo, which already holds a board.#[derive(Debug)]pub struct Diverged {pub message: String,@@ -29,15 +25,10 @@ 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> {remote(&home.dir).ok()?.map(|(_, url)| url)}-/// Points the board at the git repo `url`, once this machine can reach it: the first-/// time, it makes the data folder a git repo; later, it replaces the old repo, and the-/// next sync asks which board to keep if the new one already holds one. `owner/repo`-/// is short for that repo on GitHub. Returns the URL saved.pub fn set_remote(home: &Home, url: &str, prompt: bool) -> Result<String> {let dir = &home.dir;let url = url.trim().trim_end_matches('/');@@ -79,7 +70,6 @@ pub fn set_remote(home: &Home, url: &str, prompt: bool) -> Result<String> {Ok(url)}-/// The line of git's error that says what went wrong, in a few words.fn reason(error: &str) -> String {let lines: Vec<&str> = error.lines().map(str::trim).collect();if error.contains("terminal prompts disabled") {@@ -96,8 +86,7 @@ fn reason(error: &str) -> String {line.trim_start_matches("ERROR:").trim_start_matches("fatal:").trim().to_string()}-/// The URLs `url` may mean: itself, or for `owner/repo` that repo on GitHub, by SSH and-/// then HTTPS, as either may be the one this machine can push with.+/// SSH and HTTPS for `owner/repo`, as either may be the one this machine can push with.fn candidates(url: &str) -> Vec<String> {let short = url.strip_prefix("github.com/").unwrap_or(url);let shorthand = !short.contains(':')@@ -111,32 +100,19 @@ 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, 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 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)+ let mut remotes: Vec<(&str, &str)> = out+ .lines()+ .filter_map(|line| line.split_once('\t').and_then(|(n, rest)| Some((n, rest.strip_suffix(" (fetch)")?))))+ .collect();+ remotes.sort_by_key(|(name, _)| *name != "origin");+ Ok(remotes.first().map(|(name, url)| (name.to_string(), url.to_string())))}-/// 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.pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {let dir = &home.dir;let git = |args: &[&str]| git(dir, prompt, args);@@ -160,7 +136,7 @@ pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {if lock.is_some() { String::new() } else { format!("\n{NO_LOCKS}") }};if !git_ok(&["diff", "--cached", "--quiet"]) {- let message = format!("kanzo sync from {}", hostname());+ let message = format!("kanzo sync from {}", crate::home::hostname());// A machine where git doesn't know the user yet still syncs.let named = git_ok(&["config", "user.email"]);let anonymous = ["-c", "user.name=Kanzo", "-c", "user.email=kanzo@localhost"];@@ -251,8 +227,6 @@ pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {Ok(format!("{done}{note}"))}-/// Lets `pull` replace kanzo.db while no connection is open, then brings it up to date-/// before any can open it. A migration that fails rolls back, leaving the board as pulled.fn replace<T>(home: &Home, pull: impl FnOnce() -> Result<T>) -> Result<()> {let _lock = home.lock_exclusive()?;// Rolls back a write a crashed process left in kanzo.db-journal, which SQLite@@ -263,49 +237,27 @@ fn replace<T>(home: &Home, pull: impl FnOnce() -> Result<T>) -> Result<()> {Ok(())}-/// Git in `dir`; without `prompt` it fails rather than ask for a password or passphrase.fn command(dir: &Path, prompt: bool, args: &[&str]) -> Command {let mut cmd = Command::new("git");- cmd.arg("-C").arg(dir).args(args);+ cmd.current_dir(dir).args(args);if !prompt {cmd.env("GIT_TERMINAL_PROMPT", "0").env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes");}cmd}-/// Runs git in `dir` and returns its trimmed output, or fails with git's own message.fn git(dir: &Path, prompt: bool, args: &[&str]) -> Result<String> {- let out = command(dir, prompt, args).output().context("cannot run git; is it installed?")?;- if !out.status.success() {- let err = String::from_utf8_lossy(&out.stderr);- bail!("git {} failed:\n{}", args.join(" "), err.trim());- }- Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())+ crate::home::output(&mut command(dir, prompt, args))}fn git_ok(dir: &Path, prompt: bool, args: &[&str]) -> bool {- command(dir, prompt, args).output().is_ok_and(|o| o.status.success())-}--/// The machine's name for commit messages, like "Ada's MacBook Air".-pub fn hostname() -> String {- let run = |cmd: &str, args: &[&str]| {- Command::new(cmd)- .args(args)- .output()- .ok()- .filter(|o| o.status.success())- .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())- .filter(|h| !h.is_empty())- };- run("scutil", &["--get", "ComputerName"]).or_else(|| run("hostname", &[])).unwrap_or_else(|| "unknown".into())+ git(dir, prompt, args).is_ok()}#[cfg(test)]mod tests {use super::*;- /// A machine's data folder, syncing with the bare repo `remote`.fn machine(dir: &Path, remote: &Path) -> Home {let home = Home::open(dir.to_path_buf()).unwrap();set_remote(&home, remote.to_str().unwrap(), false).unwrap();@@ -337,7 +289,6 @@ mod tests {let tmp = tempfile::tempdir().unwrap();let (_, b) = two_machines(tmp.path());assert!(b.store().unwrap().list_projects().unwrap().is_empty());- // The old board is in kanzo.db.bak, and in the commit sync made before resetting.let bak = Store::open(&b.dir.join("kanzo.db.bak"), None).unwrap();assert_eq!(bak.list_projects().unwrap()[0].slug, "local");let old = git(&b.dir, false, &["log", "-1", "--format=%s", "HEAD@{1}"]).unwrap();diff --git a/src/update.rs b/src/update.rsindex 314aa2f..1fde842 100644--- a/src/update.rs+++ b/src/update.rs@@ -1,6 +1,5 @@-//! 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` (PowerShell on-//! Windows), which every system has, so Kanzo needs no HTTP client of its own.+//! 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;@@ -12,13 +11,10 @@ use std::time::{Duration, Instant};pub const CURRENT: &str = env!("CARGO_PKG_VERSION");-/// Where releases are published; `KANZO_RELEASES_URL` points elsewhere, for tests.const RELEASES: &str = "https://github.com/emanuele-em/kanzo/releases/latest/download";-/// How long a check for the latest version is reused: 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);@@ -33,8 +29,6 @@ fn curl(url: &str) -> Option<Vec<u8>> {out.status.success().then_some(out.stdout)}-/// The latest released version, checked at most once a day unless `now`; `None` when-/// it can't be found, like offline.pub fn latest(now: bool) -> Option<String> {let mut cached = LATEST.lock().unwrap_or_else(|e| e.into_inner());if let Some((at, version)) = &*cached@@ -52,14 +46,11 @@ pub fn latest(now: bool) -> Option<String> {version}-/// True when `version` is newer than this program: `0.2.0` > `0.1.9`.pub fn newer(version: &str) -> bool {let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };parts(version) > parts(CURRENT)}-/// Runs the latest release's installer over this program and returns its path,-/// ready to restart.pub fn install() -> Result<PathBuf, String> {let exe = std::env::current_exe().and_then(|p| p.canonicalize()).map_err(|e| e.to_string())?;// The installer writes to <dir>/bin, so it can only replace a program kept in a bin folder.@@ -92,14 +83,11 @@ 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.+/// 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 `exe` with on Windows (see `old_exe`),-/// except those still running.pub fn remove_old_exes(exe: &Path) {let (Some(dir), Some(name)) = (exe.parent(), exe.file_name()) else { return };let prefix = format!("{}.", name.to_string_lossy());@@ -144,7 +132,6 @@ fn run_installer(script: &[u8], dir: &Path) -> Result<Output, String> {out}-/// 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();@@ -154,15 +141,13 @@ fn restart_args(args: impl Iterator<Item = OsString>) -> Vec<OsString> {args}-/// Replaces this process with the program at `exe`: same arguments, same process, so-/// the port, the data folder and a running service stay. Returns only on failure.+/// Same process, so the port, the data folder and a running service stay.#[cfg(unix)]pub fn restart(exe: &Path) -> std::io::Error {use std::os::unix::process::CommandExt;Command::new(exe).args(restart_args(std::env::args_os().skip(1))).exec()}-/// Restarts the service, which stops this process; see `can_restart`.#[cfg(not(unix))]pub fn restart(_exe: &Path) -> std::io::Error {if let Err(e) = crate::service::restart() {@@ -172,8 +157,7 @@ pub fn restart(_exe: &Path) -> std::io::Error {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.+/// On Windows only the service's board can restart: a running program can't replace itself there.pub fn can_restart(home: &Path) -> bool {cfg!(unix) || crate::service::is_task_board(home)}diff --git a/src/web.rs b/src/web.rsindex 000f238..2d0b7ef 100644--- a/src/web.rs+++ b/src/web.rs@@ -1,5 +1,3 @@-//! `kanzo`: the board page, the small JSON API behind it, and MCP over HTTP at `/mcp`.-use std::collections::{HashMap, HashSet};use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};use std::sync::{Arc, Mutex, OnceLock};@@ -24,18 +22,16 @@ use crate::store::{self, Error, ImagesOf, Store, TaskPatch};use crate::{sync, update};const INDEX: &str = include_str!("index.html");-/// The largest image the board takes from a paste.const IMAGE_LIMIT: usize = 25 * 1024 * 1024;const APP_JS: &str = include_str!("app.js");const LOGO: &[u8] = include_bytes!("logo.png");-/// Scripts only from this server, so even a bug in the Markdown renderer cannot run-/// injected script; requests only back to this server.+/// Scripts only from this server, so even a bug in the Markdown renderer cannot run injected script.const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; \connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";-pub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {- let port = port.unwrap_or(home.config.port);+pub async fn serve(home: Home, open: bool) -> Result<()> {+ let port = home.config.port;let guard = Arc::new(Guard::new(port, home.config.listen, Net::load(&home)));let url = format!("http://localhost:{port}");let listener = match TcpListener::bind(SocketAddr::new(guard.address(), port)).await {@@ -92,8 +88,6 @@ pub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {stop_signal().await;stopper.cancel();});- // Sharing turns on and off while the board runs: it stops taking connections on one- // address and listens on the other. Connections already open finish as usual.let mut listener = listener;loop {let rebind = shutdown.child_token();@@ -117,7 +111,7 @@ pub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {Ok(())}-/// Binds once the old listener has let go of the port, which takes a moment.+/// The old listener takes a moment to let go of the port.async fn listen_again(ip: IpAddr, port: u16) -> std::io::Result<TcpListener> {for _ in 0..100 {match TcpListener::bind(SocketAddr::new(ip, port)).await {@@ -128,7 +122,6 @@ async fn listen_again(ip: IpAddr, port: u16) -> std::io::Result<TcpListener> {TcpListener::bind(SocketAddr::new(ip, port)).await}-/// Ctrl-C, or SIGTERM from launchd or systemd stopping the service.async fn stop_signal() {#[cfg(unix)]{@@ -150,7 +143,6 @@ async fn stop_signal() {}fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken) -> Router {- // The board itself: on a computer that joined another's board, it comes from there.let mut shared = Router::new();if home.config.mcp_http {shared = shared.nest_service("/mcp", crate::mcp::http_service(home.clone(), shutdown));@@ -174,7 +166,6 @@ fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken) -> Router.route("/api/sync", get(sync_status).post(sync_now).put(sync_repo)).route("/api/settings", patch(update_settings)).route_layer(middleware::from_fn_with_state(guard.clone(), forward));- // This computer's own: the page, its version, and what it does on the network.Router::new().route("/", get(|| async { Html(INDEX) })).route("/app.js", get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], APP_JS) }))@@ -188,28 +179,18 @@ fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken) -> Router.with_state(Arc::new(home))}-/// Who may use the board: which Host headers it answers to, and whether other-/// computers may reach it. Also what this computer does on the network.-///-/// DNS rebinding needs a domain name the attacker controls, so the board only-/// accepts `localhost`, IP addresses and, when it listens on the network, this-/// machine's own names. It never accepts other domain names.+/// DNS rebinding needs a domain name the attacker controls, so the board only accepts+/// `localhost`, IP addresses and, when it listens on the network, this machine's own names.struct Guard {port: u16,- /// `listen` from config.toml: where the board listens unless shared.listen: IpAddr,- /// Changed while the board runs, by its settings and `kanzo share`, `join` and `leave`.net: Mutex<Net>,- /// Other computers using the board: when each last asked for something, and its name.guests: Mutex<HashMap<IpAddr, (Instant, Option<String>)>>,- /// This machine's names, like `pi` and `pi.local`, found the first time they're needed.names: OnceLock<Vec<String>>,- /// Cancelled to listen on the address `net` now asks for.rebind: Mutex<CancellationToken>,}-/// How long after its last request a guest still counts: its board asks every 2 seconds-/// while it's on screen.+/// A guest's board asks every 2 seconds while it's on screen.const GUEST_GONE: Duration = Duration::from_secs(30);impl Guard {@@ -228,7 +209,6 @@ impl Guard {self.net.lock().unwrap().clone()}- /// Whether other computers may use the board.fn lan(&self) -> bool {self.net() == Net::Sharing}@@ -237,7 +217,6 @@ impl Guard {if self.lan() && self.listen.is_loopback() { Ipv4Addr::UNSPECIFIED.into() } else { self.listen }}- /// Takes on a change saved by `share::change`, and listens elsewhere if it asks to.fn set(&self, net: Net) {let before = self.address();*self.net.lock().unwrap() = net;@@ -264,16 +243,11 @@ impl Guard {fn names(&self) -> &[String] {self.names.get_or_init(|| {- let run = |cmd: &str, args: &[&str]| {- std::process::Command::new(cmd)- .args(args)- .output()- .ok()- .filter(|o| o.status.success())- .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_ascii_lowercase())- };+ use std::process::Command;+ let run = |cmd: &mut Command| crate::home::output(cmd).ok().map(|n| n.to_ascii_lowercase());// macOS keeps its Bonjour name apart; `hostname` there can be a DHCP address.- let found = [run("scutil", &["--get", "LocalHostName"]), run("hostname", &[])];+ let found =+ [run(Command::new("scutil").args(["--get", "LocalHostName"])), run(&mut Command::new("hostname"))];let mut names = Vec::new();for full in found.into_iter().flatten().filter(|n| !n.is_empty() && n.parse::<IpAddr>().is_err()) {let short = full.split('.').next().unwrap_or_default().to_string();@@ -304,12 +278,10 @@ impl Guard {}}-/// The other computer a request comes from, if not this one.fn guest(req: &Request) -> Option<IpAddr> {req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip()).filter(|ip| !ip.is_loopback())}-/// Hands the board's requests to the board this computer joined, if it did.async fn forward(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {match guard.net() {Net::Joined(host) => share::forward(&host, req).await,@@ -317,7 +289,6 @@ async fn forward(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> R}}-/// What this computer does on the network is only for this computer to change.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(),@@ -325,15 +296,11 @@ async fn this_computer(req: Request, next: Next) -> Response {}}-/// Refuses requests for a Host this board does not answer to, browser requests sent-/// from any page other than the board itself, and other computers unless the board is-/// shared. Adds security headers to every reply.async fn protect(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {let guest = guest(&req);let ok = {let header = |name| req.headers().get(name).and_then(|h: &HeaderValue| h.to_str().ok());let host = header(header::HOST).unwrap_or("");- // 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://")@@ -366,20 +333,14 @@ async fn protect(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Rtype Shared = State<Arc<Home>>;-/// Runs `f` with a fresh connection on a blocking thread and answers with JSON.async fn with_store<T: Serialize + Send + 'static>(home: Arc<Home>,f: impl FnOnce(&Home, &Store) -> store::Result<T> + Send + 'static,) -> Response {- let outcome = tokio::task::spawn_blocking(move || {- let store = home.store()?;- f(&home, &store)- })- .await;- let error = match outcome {+ let error = match blocking(move || f(&home, &home.store()?)).await {Ok(Ok(v)) => return Json(v).into_response(),Ok(Err(e)) => e,- Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),+ Err(e) => return e.into_response(),};let code = match error {Error::NotFound(_) => StatusCode::NOT_FOUND,@@ -387,11 +348,28 @@ async fn with_store<T: Serialize + Send + 'static>(Error::Busy(_) => StatusCode::SERVICE_UNAVAILABLE,Error::Db(_) => StatusCode::INTERNAL_SERVER_ERROR,};- (code, Json(json!({ "error": error.to_string() }))).into_response()+ fail(code, error).into_response()}-/// What the page compares to see if anything changed: the change counter, plus-/// the database file's identity so a board pulled by `kanzo sync` always reloads.+type Reply = Result<Response, Fail>;++pub struct Fail(StatusCode, String);++pub fn fail(code: StatusCode, error: impl std::fmt::Display) -> Fail {+ Fail(code, error.to_string())+}++impl IntoResponse for Fail {+ fn into_response(self) -> Response {+ (self.0, Json(json!({ "error": self.1 }))).into_response()+ }+}++async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, Fail> {+ tokio::task::spawn_blocking(f).await.map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))+}++/// The database file's identity is part of it so a board pulled by `kanzo sync` always reloads.fn change_token(home: &Home, s: &Store) -> store::Result<String> {Ok(format!("{}-{}", s.changes()?, home.db_identity()))}@@ -399,7 +377,6 @@ fn change_token(home: &Home, s: &Store) -> store::Result<String> {#[derive(Serialize)]struct Changes {changes: String,- /// Other computers using the board, while it's shared.guests: Option<usize>,}@@ -408,21 +385,17 @@ async fn changes(State(home): Shared, Extension(guard): Extension<Arc<Guard>>) -with_store(home, move |h, s| Ok(Changes { changes: change_token(h, s)?, guests })).await}-/// Done tasks the board gets unless it asks for all: the newest, which are all it shows./// The done column only grows, and every change reloads the board.const DONE_SHOWN: usize = 50;#[derive(Deserialize)]struct BoardQuery {project: Option<String>,- /// "all" for every done task.done: Option<String>,- /// The filter: only the tasks that search finds.#[serde(default)]q: String,}-/// The whole board, serialized straight from the store's rows.#[derive(Serialize)]struct Board {changes: String,@@ -463,7 +436,6 @@ struct SearchQuery {q: String,}-/// Tasks of every project matching the search, for the search window.async fn search(State(home): Shared, Query(q): Query<SearchQuery>) -> Response {with_store(home, move |_, s| s.search(&q.q, Some(30))).await}@@ -537,7 +509,6 @@ async fn create_task(State(home): Shared, Json(t): Json<NewTask>) -> Response {.await}-/// Board settings, kept in kanzo.db so they sync with the board.#[derive(Deserialize)]struct Settings {backlog: bool,@@ -607,7 +578,6 @@ async fn delete_task(State(home): Shared, Path(id): Path<i64>) -> Response {struct NewComment {#[serde(default)]body: String,- /// Files saved by `/api/images`, attached to the comment.#[serde(default)]images: Vec<String>,}@@ -635,36 +605,31 @@ async fn attach_image(State(home): Shared, Path(id): Path<i64>, Json(a): Json<At.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() {+ if store::valid_image_file(file) && home.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.+/// Named by 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(),+ let ext = file.rsplit_once('.').map(|(_, ext)| ext);+ let Some((_, mime)) = store::IMAGE_TYPES.iter().find(|(e, _)| Some(*e) == ext) else {+ 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);+ let path = home.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)+ ([(header::CONTENT_TYPE, *mime), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")], bytes).into_response()}_ => StatusCode::NOT_FOUND.into_response(),@@ -675,59 +640,34 @@ async fn delete_comment(State(home): Shared, Path(id): Path<i64>) -> Response {with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Comment(id), || s.delete_comment(id))).await}-/// 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",- Some("image/jpeg") => "jpg",- Some("image/gif") => "gif",- Some("image/webp") => "webp",- _ => {- return (StatusCode::BAD_REQUEST, Json(json!({ "error": "paste a PNG, JPEG, GIF or WebP image" })))- .into_response();- }+async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Reply {+ let mime = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok());+ let Some((ext, _)) = store::IMAGE_TYPES.iter().find(|(_, m)| Some(*m) == mime) else {+ return Err(fail(StatusCode::BAD_REQUEST, "paste a PNG, JPEG, GIF or WebP image"));};if body.is_empty() {- return (StatusCode::BAD_REQUEST, Json(json!({ "error": "the image is empty" }))).into_response();+ return Err(fail(StatusCode::BAD_REQUEST, "the image is empty"));}- let saved = tokio::task::spawn_blocking(move || -> std::io::Result<std::path::PathBuf> {+ let path = blocking(move || -> std::io::Result<std::path::PathBuf> {use std::hash::{Hash, Hasher};- let dir = home.dir.join("images");- std::fs::create_dir_all(&dir)?;let mut hasher = std::collections::hash_map::DefaultHasher::new();body.hash(&mut hasher);- let path = dir.join(format!("{:016x}.{ext}", hasher.finish()));+ let path = home.images().join(format!("{:016x}.{ext}", hasher.finish()));if !path.exists() {- // Write to a temporary name first, so a half-written image never has the real one.- let partial = path.with_extension("part");- std::fs::write(&partial, &body)?;- std::fs::rename(&partial, &path)?;+ crate::home::write_whole(&path, &body)?;}Ok(path)})- .await;- match saved {- 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()- }- Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),- }+ .await?+ .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("cannot save the image: {e}")))?;+ let file = path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();+ Ok(Json(json!({ "file": file, "path": path.display().to_string() })).into_response())}-/// What this computer does on the network: shares its board, uses another's, or neither.async fn network(Extension(guard): Extension<Arc<Guard>>) -> Response {Json(guard.status()).into_response()}-/// Shares the board or stops, or joins another computer's board or leaves it: the-/// settings window, `kanzo share`, `join` and `leave` all come here while the board runs.async fn change_network(State(home): Shared,Extension(guard): Extension<Arc<Guard>>,@@ -738,39 +678,35 @@ async fn change_network(guard.set(net);Json(guard.status()).into_response()}- Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response(),+ Err(e) => fail(StatusCode::BAD_REQUEST, e).into_response(),}}#[derive(Deserialize)]struct SyncRequest {- /// "local" or "remote", once the board has asked which side to keep.#[serde(default)]keep: Option<String>,}-/// The board's sync button: the same as `kanzo sync`, without git ever prompting. When-/// both sides changed, answers 409 with `diverged`, and the board asks which side to keep.-async fn sync_now(State(home): Shared, Json(r): Json<SyncRequest>) -> Response {+async fn sync_now(State(home): Shared, Json(r): Json<SyncRequest>) -> Reply {let keep = match r.keep.as_deref() {Some("local") => Some(sync::Keep::Local),Some("remote") => Some(sync::Keep::Remote),_ => None,};- match tokio::task::spawn_blocking(move || sync::sync(&home, keep, false)).await {- Ok(Ok(message)) => Json(json!({ "message": message })).into_response(),- Ok(Err(e)) => match e.downcast_ref::<sync::Diverged>() {+ let synced = blocking(move || sync::sync(&home, keep, false)).await?;+ Ok(match synced {+ Ok(message) => Json(json!({ "message": message })).into_response(),+ Err(e) => match e.downcast_ref::<sync::Diverged>() {Some(d) => (StatusCode::CONFLICT, Json(json!({ "error": d.message, "diverged": true, "first": d.first }))).into_response(),- None => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("{e:#}") }))).into_response(),+ None => fail(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")).into_response(),},- Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),- }+ })}-/// The repo the board syncs with, `null` before sync is set up.async fn sync_status(State(home): Shared) -> Response {- let remote = tokio::task::spawn_blocking(move || sync::remote_url(&home)).await.ok().flatten();+ let remote = blocking(move || sync::remote_url(&home)).await.ok().flatten();Json(json!({ "remote": remote })).into_response()}@@ -779,55 +715,45 @@ struct SyncRepo {url: String,}-/// Sets up sync with a repo, or moves it to another one.-async fn sync_repo(State(home): Shared, Json(r): Json<SyncRepo>) -> Response {- match tokio::task::spawn_blocking(move || sync::set_remote(&home, &r.url, false)).await {- Ok(Ok(remote)) => Json(json!({ "remote": remote })).into_response(),- Ok(Err(e)) => (StatusCode::BAD_REQUEST, Json(json!({ "error": format!("{e:#}") }))).into_response(),- Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),- }+async fn sync_repo(State(home): Shared, Json(r): Json<SyncRepo>) -> Reply {+ let remote = blocking(move || sync::set_remote(&home, &r.url, false))+ .await?+ .map_err(|e| fail(StatusCode::BAD_REQUEST, format!("{e:#}")))?;+ Ok(Json(json!({ "remote": remote })).into_response())}#[derive(Deserialize)]struct UpdateQuery {- /// Present to check GitHub now rather than reuse today's answer.now: Option<String>,}-/// This version, the latest release (`null` when GitHub can't be reached) and, when-/// that one is newer, `available`.async fn update_status(Query(q): Query<UpdateQuery>) -> Response {let now = q.now.is_some();- let latest = tokio::task::spawn_blocking(move || update::latest(now)).await.ok().flatten();+ let latest = blocking(move || update::latest(now)).await.ok().flatten();let available = latest.clone().filter(|v| update::newer(v));Json(json!({ "current": update::CURRENT, "latest": latest, "available": available })).into_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 {+async fn update_now(State(home): Shared) -> Reply {// `can_restart` runs schtasks on Windows, so it waits off the async thread too.let dir = home.dir.clone();- match tokio::task::spawn_blocking(move || (update::can_restart(&dir), update::install())).await {- Ok((false, Ok(_))) => Json(json!({ "restarting": false })).into_response(),- Ok((true, Ok(exe))) => {- tokio::spawn(async move {- // Let the answer reach the board first.- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- // 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()- }- Ok((_, Err(error))) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": error }))).into_response(),- Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),+ let (restart, installed) = blocking(move || (update::can_restart(&dir), update::install())).await?;+ let exe = installed.map_err(|error| fail(StatusCode::INTERNAL_SERVER_ERROR, error))?;+ if restart {+ tokio::spawn(async move {+ // Let the answer reach the board first.+ tokio::time::sleep(Duration::from_millis(300)).await;+ // 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}");+ }+ });}+ Ok(Json(json!({ "restarting": restart })).into_response())}-/// 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.+/// Windows doesn't stop the program when its console goes away: the service's conhost+/// when the task is stopped, or the window the board was started in.#[cfg(windows)]fn exit_with_console() {unsafe extern "system" {@@ -838,7 +764,7 @@ fn exit_with_console() {if attached() {std::thread::spawn(move || {while attached() {- std::thread::sleep(std::time::Duration::from_secs(1));+ std::thread::sleep(Duration::from_secs(1));}std::process::exit(0);});@@ -851,7 +777,6 @@ fn open_browser(url: &str) {} 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;@@ -886,7 +811,6 @@ mod tests {assert!(!lan.allows(bad), "{bad}");}- // Stopping sharing closes the board to other computers again.lan.set(Net::Private);assert!(!lan.allows("192.168.1.5:4242"));assert_eq!(lan.address(), IpAddr::from(Ipv4Addr::LOCALHOST));