From 41c503645122f3d2d79ea4a428d6eb72c399c5b5 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Mon, 30 Nov 2026 11:13:47 +0100 Subject: feat(todo): Vikunja tasks due now on the Dashboard A row under the music and spending cards lists the open Vikunja tasks that are due today or overdue, or whose reminder has passed, and is hidden when there are none. A task with a reminder still ahead is left out, so snoozing adds a reminder 30 min ahead and the task returns when it fires. Tap opens the task in the PC's browser, hold marks it done, a swipe right snoozes it. [todo] url points at Vikunja; the API token lives in ~/.config/deck-it/vikunja-token. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 ++ README.md | 5 +- config.toml | 8 ++ deckit/modules/todo.py | 166 +++++++++++++++++++++++ docs/superpowers/specs/2026-11-30-todo-design.md | 56 ++++++++ static/app.js | 2 +- static/dashboard.js | 106 ++++++++++++++- static/deck.css | 16 +++ tests/test_dashboard.mjs | 9 +- tests/test_todo.py | 124 +++++++++++++++++ 10 files changed, 496 insertions(+), 5 deletions(-) create mode 100644 deckit/modules/todo.py create mode 100644 docs/superpowers/specs/2026-11-30-todo-design.md create mode 100644 tests/test_todo.py diff --git a/AGENTS.md b/AGENTS.md index 0da1307..8cbfc48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,15 @@ Keep the server dependency-free apart from that one package. hyprlock` every 2s and sends the tablet `KEYCODE_SLEEP` on lock and `KEYCODE_WAKEUP` on unlock. (Its Dashboard icons were dropped; the name stays because keystone's module toggle uses it.) +- `todo` reads Vikunja (`[todo] url`, an API token in + `~/.config/deck-it/vikunja-token`) every 60s: open tasks due today or + overdue or whose reminder passed (`/api/v2/tasks` filter), minus any with a + reminder still ahead, so a snooze hides one until it fires. Actions, for an + id the last state listed: `open` (`xdg-open` on the PC, Vikunja's + `frontend_url`), `done` and `snooze` (merge-patch; snooze keeps the old + reminders and adds one at now+30m), each re-reading the list. The + Dashboard's `.dash-todo` row exists only while there are tasks: tap opens, + hold marks done, a swipe right snoozes. - `deckit/theme.py` reads UDT's palette (`~/.config/rofi/udt/palette.rasi`) and `~/.cache/udt/udt-border.lua`; the frontend uses only those CSS variables. Text size is keystone's (`~/.config/keystone/fonts.json`, `override.deckit` diff --git a/README.md b/README.md index fe32f9a..de51d9d 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,10 @@ launchers included, with a Restart button to apply a save. Claude usage and the tablet's battery and Wi-Fi; music and spending sit below. A row appears only while something is running (a print, a build, an OBS recording or stream), and a tap opens its tab. The tablet's screen - sleeps and wakes with the PC's lock, however it was locked. + sleeps and wakes with the PC's lock, however it was locked. Vikunja tasks + that are due, overdue or reminded take a row only while there are some: + tap opens one in the PC's browser, hold marks it done, swipe right snoozes + it 30 minutes. - The Windows tab has keystone's workspace icons, icon launchers, and a preview card per window (as in the Alt+Tab switcher): tap to focus, × to close, a long press to move it to another desktop. diff --git a/config.toml b/config.toml index f85fc4d..6fde20c 100644 --- a/config.toml +++ b/config.toml @@ -54,6 +54,7 @@ assistant = true tablet = true actions = true xbox = true +todo = true [obs] host = "127.0.0.1" @@ -81,6 +82,13 @@ url = "" # Xbox tab says it is not configured. Sign-in happens on the tab. client_id = "" +[todo] +# Vikunja's base URL, like http://vikunja.example.org:3456. The Dashboard +# lists its open tasks due today or overdue, or whose reminder has passed. +# The token, an API token that can read and update tasks, goes in +# ~/.config/deck-it/vikunja-token. Empty: no todo row. +url = "" + [assistant] # keystone's desktop shell, the quickshell config whose `assistant catalog` # IPC call lists the canvas's Ask presets and Do ops for the tab. diff --git a/deckit/modules/todo.py b/deckit/modules/todo.py new file mode 100644 index 0000000..8abbd23 --- /dev/null +++ b/deckit/modules/todo.py @@ -0,0 +1,166 @@ +# deck-it - todo module +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +"""Vikunja tasks that need doing now, for the Dashboard. + +Open tasks due today or overdue, or whose reminder has passed; one with a +reminder still ahead is hidden, which is how a snooze works. The token is a +Vikunja API token (read and update tasks) in ~/.config/deck-it/vikunja-token. +""" + +import http.client +import json +import os +import subprocess +import threading +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, timedelta, timezone +from pathlib import Path + +from ..module import Module, ModuleError + +TOKEN = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "deck-it" / "vikunja-token" +POLL = 60 +SNOOZE = timedelta(minutes=30) +FILTER = "done = false && (due_date < now/d+1d || reminders < now)" + + +def _http(method, url, token, data=None): + h = {"Accept": "application/json"} + if token: + h["Authorization"] = f"Bearer {token}" + body = None + if data is not None: + body, h["Content-Type"] = json.dumps(data).encode(), "application/merge-patch+json" + try: + with urllib.request.urlopen(urllib.request.Request(url, body, h, method=method), timeout=10) as r: + raw = r.read() + except urllib.error.HTTPError as e: + raise OSError(f"HTTP {e.code}") from None + except http.client.HTTPException as e: + raise OSError(str(e) or type(e).__name__) from None + return json.loads(raw) if raw else {} + + +def _popen(cmd): + subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def _time(s): + """A Vikunja time, or None for its year-one 'unset'.""" + if not s or s.startswith("0001-"): + return None + return datetime.fromisoformat(s.replace("Z", "+00:00")) + + +def _iso(t): + return t.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def pick(tasks, now): + """The tasks to show, overdue first, then by due date, reminder-only last.""" + out = [] + for t in tasks: + if any((r := _time(x.get("reminder"))) and r > now for x in t.get("reminders") or []): + continue # snoozed, or reminded later on purpose + due = _time(t.get("due_date")) + out.append((due is None, due or now, {"id": t["id"], "title": t.get("title", ""), + "due": _iso(due) if due else None})) + out.sort(key=lambda x: x[:2]) + return [x[2] for x in out] + + +class Todo: + def __init__(self, cfg: dict): + self.url = cfg.get("todo", {}).get("url", "").rstrip("/") + self.http = cfg.get("http", _http) + self.popen = cfg.get("popen", _popen) + self.token_path = Path(cfg.get("token", TOKEN)) + self.now = cfg.get("now", lambda: datetime.now(timezone.utc)) + self.front = None + self.st = {"tasks": [], "error": None} + self.wake, self.stopping = threading.Event(), False + self.actions = {"open": self._open, "done": self._done, "snooze": self._snooze} if self.url else {} + + def _call(self, method, path, data=None): + token = self.token_path.read_text().strip() + return self.http(method, self.url + path, token, data) + + def refresh(self): + try: + if self.front is None: + self.front = self.http("GET", self.url + "/api/v1/info", "").get("frontend_url", "") + items = self._call("GET", "/api/v2/tasks?" + urllib.parse.urlencode( + {"filter": FILTER, "per_page": 50})).get("items") or [] + self.st = {"tasks": pick(items, self.now()), "error": None} + except (OSError, ValueError) as e: + self.st = {"tasks": [], "error": str(e) or type(e).__name__} + + def state(self): + return self.st + + def _id(self, body): + i = body.get("id") + if not any(t["id"] == i for t in self.st["tasks"]): + raise ModuleError("not a listed task") + return i + + def _write(self, fn): + try: + fn() + except (OSError, ValueError) as e: + raise ModuleError(str(e) or type(e).__name__) from e + + def _open(self, body): + i = self._id(body) + base = (self.front or self.url).rstrip("/") + self._write(lambda: self.popen(["xdg-open", f"{base}/tasks/{i}"])) + + def _done(self, body): + i = self._id(body) + self._write(lambda: self._call("PATCH", f"/api/v2/tasks/{i}", {"done": True})) + self.refresh() # the page reads the new list as soon as the action answers + + def _snooze(self, body): + i = self._id(body) + + def go(): + old = self._call("GET", f"/api/v2/tasks/{i}").get("reminders") or [] + self._call("PATCH", f"/api/v2/tasks/{i}", + {"reminders": old + [{"reminder": _iso(self.now() + SNOOZE)}]}) + self._write(go) + self.refresh() + + def run(self): + while not self.stopping: + self.refresh() + self.wake.wait(POLL) + self.wake.clear() + + def start(self): + if self.url: + threading.Thread(target=self.run, daemon=True).start() + + def stop(self): + self.stopping = True + self.wake.set() + + +def make(cfg: dict) -> Module: + t = Todo(cfg) + return Module(name="todo", title="Todo", state=t.state, actions=t.actions, start=t.start, stop=t.stop) diff --git a/docs/superpowers/specs/2026-11-30-todo-design.md b/docs/superpowers/specs/2026-11-30-todo-design.md new file mode 100644 index 0000000..72ac21a --- /dev/null +++ b/docs/superpowers/specs/2026-11-30-todo-design.md @@ -0,0 +1,56 @@ +# Vikunja todos on the Dashboard + +The Dashboard's bottom row (once the action icons) stays empty unless there is +something to do. Then it lists the Vikunja tasks that need attention. + +## What shows + +Open tasks that are due today or overdue, or whose reminder has passed. +A task with a reminder still in the future is hidden: that is how a snooze +hides it until the reminder fires. Overdue first, then by due date; a task +with no due date (only a reminder) after those. At most 3 lines plus +"+N more". No tasks: no row. + +## Server: `deckit/modules/todo.py` + +- `[todo] url`, the Vikunja API base (`http://host:3456`). Empty: the module + reports nothing and starts no thread. +- Token: `~/.config/deck-it/vikunja-token`, a Vikunja API token allowed to + read and update tasks. Never in the repo or the shipped config. +- A thread reads `GET /api/v2/tasks?filter=done = false && (due_date < + now/d+1d || reminders < now)` every 60s and right after an action; + `/api/v1/info`'s `frontend_url` once for links. +- State: `{tasks: [{id, title, due}], more, error}`. `due` is an ISO time + or null (Vikunja's `0001-01-01` is null). +- Actions take `{id}`, which must be one the last state listed: + - `open`: `xdg-open tasks/` on the PC. + - `done`: merge-patch `{done: true}` (a repeating task moves on, Vikunja's + own rule). + - `snooze`: read the task, merge-patch its `reminders` with every old one + plus one at now+30m. +- Unreachable or refused: `error` carries the reason; the last tasks are + dropped. + +## Dashboard + +A `.dash-todo` row at the bottom of `.dash-mid`, hidden when empty. Each line: +title, and "overdue 2d", "today 15:00" or "reminder". Gestures: + +- tap: `open` +- hold (`hold.js`): `done`, the line fades out +- swipe left to right past a third of its width: `snooze`; the line follows + the finger and slides out; a swipe cancels the hold. + +An error shows one muted line, "Vikunja unreachable", the reason in its +tooltip. + +## Keystone + +`todo` under Dashboard parts, labelled "Vikunja todos", and a URL field. + +## Tests + +`tests/test_todo.py` with a fake HTTP layer: a future reminder hides a task, +sort order, `0001` dates read as none, an unlisted id is refused, snooze keeps +the old reminders and adds one, done sends a partial patch, empty url is +quiet. diff --git a/static/app.js b/static/app.js index 3249d64..d8b7361 100644 --- a/static/app.js +++ b/static/app.js @@ -141,7 +141,7 @@ function mountTab(name, panel, section) { } // Modules with no panel file: dashboard.js draws them. -const DRAWN = ["stats", "tablet", "llm", "actions"]; +const DRAWN = ["stats", "tablet", "llm", "actions", "todo"]; async function boot() { const r = await fetch("/api/modules"); diff --git a/static/dashboard.js b/static/dashboard.js index 336ce2a..1f123a7 100644 --- a/static/dashboard.js +++ b/static/dashboard.js @@ -15,16 +15,19 @@ // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // The Dashboard tab: a top band of chips, music and spending always on, a -// row of chips for one to three busy modules, each opening its full slot. +// row of chips for one to three busy modules, each opening its full slot, +// and the Vikunja tasks due now, only while there are some. // The page keeps the trend history; the modules' APIs are the existing ones. import { offline } from "./offline.js"; +import { HOLD_MS, buzz } from "./hold.js"; export const HISTORY = 120; // trend samples: two minutes at 1 s const RUNNING = { k1c: "K1C", sbbuilder: "build", obs: "OBS" }; // the running row's order and chip labels const G = { cpu: "", mem: "\u{f035b}", gpu: "\u{f08ae}", net: "\u{f04e1}", - wifi: "", charging: "\u{f0084}", tux: "", clock: "" }; + wifi: "", charging: "\u{f0084}", tux: "", clock: "", + todo: "\u{f0131}" }; const BATTERY = ["", "", "", "", ""]; // Nerd Font distro logos by os-release ID. const DISTRO = { @@ -102,6 +105,51 @@ function marquee(el) { } } +// A todo's due label: "overdue 2d", "today 15:00", or "reminder" when it +// only has a reminder. +export function dueLabel(iso, now = new Date()) { + if (!iso) return "reminder"; + const due = new Date(iso); + if (due.toDateString() === now.toDateString() && due >= now) + return `today ${due.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", hourCycle: "h23" })}`; + const h = (now - due) / 3600000; + return h < 24 ? `overdue ${Math.max(1, Math.round(h))}h` : `overdue ${Math.floor(h / 24)}d`; +} + +// Tap, hold, or swipe left to right on one element. A swipe past a third +// of its width fires; a shorter one springs back. Moving cancels the hold. +function gestures(el, { tap, hold, swipe }) { + let x0 = null, dx = 0, timer = null, sliding = false; + const reset = () => { + clearTimeout(timer); + timer = null; x0 = null; sliding = false; + el.classList.remove("holding", "sliding"); + }; + el.addEventListener("pointerdown", (e) => { + x0 = e.clientX; dx = 0; + el.setPointerCapture(e.pointerId); + el.classList.add("holding"); + timer = setTimeout(() => { reset(); buzz(); hold(); }, HOLD_MS); + }); + el.addEventListener("pointermove", (e) => { + if (x0 == null) return; + dx = Math.max(0, e.clientX - x0); + if (!sliding && Math.abs(e.clientX - x0) > 12) { + clearTimeout(timer); timer = null; sliding = true; + el.classList.remove("holding"); el.classList.add("sliding"); + } + if (sliding) el.style.transform = `translateX(${dx}px)`; + }); + el.addEventListener("pointerup", () => { + const wasTap = timer != null, wasSwipe = sliding && dx > el.offsetWidth / 3; + reset(); + if (wasSwipe) { el.style.transform = "translateX(110%)"; swipe(); } + else el.style.transform = ""; + if (wasTap) tap(); + }); + el.addEventListener("pointercancel", () => { reset(); el.style.transform = ""; }); +} + const SKELETON = `
+ `; export default { @@ -261,6 +310,59 @@ export default { if (on.has("xbox")) poll("xbox", 30, (st) => { last.xbox = st; draw(); }); }); + // Vikunja tasks due now: tap opens one on the PC, hold marks it done, + // a swipe right snoozes it 30 min. Redrawn only when the list changes, + // and never under a finger. + const todo = $(".dash-todo"); + const drawTodo = (st) => { + const key = JSON.stringify(st); + if (todo._key === key || todo.querySelector(".holding, .sliding")) return; + todo._key = key; + const tasks = st.tasks ?? []; + todo.hidden = !tasks.length && !st.error; + todo.textContent = ""; + if (st.error) { + todo.innerHTML = `
Vikunja unreachable
`; + todo.firstChild.title = st.error; + return; + } + const act = async (name, id, line) => { + let ok = false; + try { + ok = (await fetch(`/api/todo/${name}`, { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id }) })).ok; + if (ok && name !== "open") drawTodo(await (await fetch("/api/todo")).json()); + } catch {} + if (!ok) { // back in place, red for a moment + line.classList.remove("gone"); + line.style.transform = ""; + line.classList.add("fail"); + setTimeout(() => line.classList.remove("fail"), 1500); + } + }; + for (const t of tasks.slice(0, 3)) { + const line = document.createElement("div"); + line.className = "td"; + line.innerHTML = ``; + line.querySelector(".nf").textContent = G.todo; + line.querySelector(".tt").textContent = t.title; + const due = dueLabel(t.due); + line.querySelector(".due").textContent = due; + line.classList.toggle("late", due.startsWith("overdue")); + gestures(line, { tap: () => act("open", t.id, line), + hold: () => { line.classList.add("gone"); act("done", t.id, line); }, + swipe: () => act("snooze", t.id, line) }); + todo.append(line); + } + if (tasks.length > 3) { + const more = document.createElement("div"); + more.className = "td more"; + more.textContent = `+${tasks.length - 3} more`; + todo.append(more); + } + }; + if (on.has("todo")) poll("todo", 10, drawTodo); + // The running row: a chip per module, created now in RUNNING order and // shown while it is busy. A tap opens its full slot, and the module's // detail(state, el) when it has one, centred over the page; a tap diff --git a/static/deck.css b/static/deck.css index a11583a..c01b5e4 100644 --- a/static/deck.css +++ b/static/deck.css @@ -749,6 +749,22 @@ select { .dash .legend { display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 0.75rem; color: var(--udt-subtext0); } .dash .legend span::before { content: ""; display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 5px; background: var(--c); } +/* Vikunja tasks due now: one line each, hidden when there are none. + touch-action none, so a swipe right reaches dashboard.js, not the page. */ +.dash-todo { flex: none; display: flex; flex-direction: column; gap: 4px; padding: 8px 10px; overflow: hidden; } +.dash-todo .td { display: flex; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 10px; + background: var(--udt-surface0); touch-action: none; user-select: none; cursor: pointer; + transition: transform .25s ease, opacity .25s ease, background-color .8s ease; } +.dash-todo .td.sliding { transition: none; } +.dash-todo .td.holding { background: color-mix(in srgb, var(--udt-green) 35%, var(--udt-surface0)); } +.dash-todo .td.gone { opacity: 0; transform: scale(.97); } +.dash-todo .td.fail { background: color-mix(in srgb, var(--udt-red) 35%, var(--udt-surface0)); } +.dash-todo .td .nf { color: var(--udt-accent); font-size: 1.1rem; } +.dash-todo .td .tt { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.dash-todo .td .due { flex: none; font-size: 0.786rem; color: var(--udt-subtext0); } +.dash-todo .td.late .due { color: var(--udt-red); } +.dash-todo .td.more, .dash-todo .td.err { background: none; cursor: default; color: var(--udt-overlay1); font-size: 0.786rem; padding: 2px 10px; } + /* The running row: one to three chips in equal columns, each opening its slot (and detail) as a centred modal. A line too long for the slot slides to its end and back (dashboard.js sets --d and --t). */ diff --git a/tests/test_dashboard.mjs b/tests/test_dashboard.mjs index 2448c38..78fcefc 100644 --- a/tests/test_dashboard.mjs +++ b/tests/test_dashboard.mjs @@ -15,7 +15,7 @@ // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import assert from "node:assert/strict"; -import { area, line, push, spendParts, batteryGlyph, HISTORY } from "../static/dashboard.js"; +import { area, line, push, spendParts, batteryGlyph, dueLabel, HISTORY } from "../static/dashboard.js"; import { busy as printing } from "../static/modules/k1c.js"; import { busy as building, planRows } from "../static/modules/sbbuilder.js"; import { busy as live } from "../static/modules/obs.js"; @@ -64,3 +64,10 @@ assert.deepEqual(planRows({ plan: ["a/x", "b/y", "c/z"], progress: { results: { "a/x": "failed" }, current: "b/y" } }).map((r) => r.status), ["failed", "building", "waiting"]); assert.deepEqual(planRows(undefined), []); + +// dueLabel: reminder-only, later today, hours and days overdue +const now = new Date(2026, 10, 30, 12, 0); +assert.equal(dueLabel(null, now), "reminder"); +assert.match(dueLabel(new Date(2026, 10, 30, 15, 0).toISOString(), now), /^today 15.00$/); +assert.equal(dueLabel(new Date(2026, 10, 30, 9, 0).toISOString(), now), "overdue 3h"); +assert.equal(dueLabel(new Date(2026, 10, 27, 12, 0).toISOString(), now), "overdue 3d"); diff --git a/tests/test_todo.py b/tests/test_todo.py new file mode 100644 index 0000000..f648a36 --- /dev/null +++ b/tests/test_todo.py @@ -0,0 +1,124 @@ +# deck-it - tests for the Vikunja todo module +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import tempfile +import unittest +from datetime import datetime, timezone + +from deckit.module import ModuleError +from deckit.modules import todo + +NOW = datetime(2026, 11, 30, 12, 0, tzinfo=timezone.utc) +NONE = "0001-01-01T00:00:00Z" + + +def task(id, due=NONE, reminders=None, title=None): + return {"id": id, "title": title or f"t{id}", "due_date": due, + "reminders": [{"reminder": r} for r in reminders] if reminders else None} + + +class Pick(unittest.TestCase): + def test_future_reminder_hides_a_task(self): + got = todo.pick([task(1, due="2026-11-29T09:00:00Z", reminders=["2026-11-30T12:30:00Z"]), + task(2, reminders=["2026-11-30T11:00:00Z"])], NOW) + self.assertEqual([t["id"] for t in got], [2]) + + def test_overdue_first_then_by_due_then_reminder_only(self): + got = todo.pick([task(1, reminders=["2026-11-30T08:00:00Z"]), + task(2, due="2026-11-30T18:00:00Z"), + task(3, due="2026-11-28T09:00:00Z")], NOW) + self.assertEqual([t["id"] for t in got], [3, 2, 1]) + + def test_year_one_reads_as_no_due_date(self): + self.assertIsNone(todo.pick([task(1, reminders=["2026-11-30T08:00:00Z"])], NOW)[0]["due"]) + self.assertEqual(todo.pick([task(2, due="2026-11-30T18:00:00Z")], NOW)[0]["due"], + "2026-11-30T18:00:00Z") + + +class Fake: + def __init__(self, tasks): + self.tasks, self.calls = tasks, [] + + def __call__(self, method, url, token, data=None): + self.calls.append((method, url, data)) + if url.endswith("/api/v1/info"): + return {"frontend_url": "http://vikunja.example.org/"} + if method == "GET" and "/api/v2/tasks?" in url: + return {"items": self.tasks} + if method == "GET": + return next(t for t in self.tasks if url.endswith(f"/tasks/{t['id']}")) + return {} + + +class Module(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + tok = Path(self.dir.name) / "token" + tok.write_text("secret\n") + self.http = Fake([task(7, due="2026-11-29T09:00:00Z", reminders=["2026-11-29T08:00:00Z"])]) + self.opened = [] + self.m = todo.Todo({"todo": {"url": "http://vikunja.example.org:3456/"}, "http": self.http, + "token": tok, "popen": self.opened.append, "now": lambda: NOW}) + self.m.refresh() + + def tearDown(self): + self.dir.cleanup() + + def test_state_lists_tasks(self): + st = self.m.state() + self.assertEqual([t["id"] for t in st["tasks"]], [7]) + self.assertIsNone(st["error"]) + + def test_unlisted_id_is_refused(self): + for act in ("open", "done", "snooze"): + with self.assertRaises(ModuleError): + self.m.actions[act]({"id": 8}) + + def test_open_runs_xdg_open_on_the_task(self): + self.m.actions["open"]({"id": 7}) + self.assertEqual(self.opened, [["xdg-open", "http://vikunja.example.org/tasks/7"]]) + + def test_done_patches_only_done(self): + self.m.actions["done"]({"id": 7}) + self.assertIn(("PATCH", "http://vikunja.example.org:3456/api/v2/tasks/7", {"done": True}), + self.http.calls) + + def test_snooze_keeps_old_reminders_and_adds_one(self): + self.m.actions["snooze"]({"id": 7}) + patch = [c for c in self.http.calls if c[0] == "PATCH"][-1] + self.assertEqual(patch[2], {"reminders": [{"reminder": "2026-11-29T08:00:00Z"}, + {"reminder": "2026-11-30T12:30:00Z"}]}) + + def test_error_is_reported(self): + def down(*a, **k): + raise OSError("connection refused") + self.m.http = down + self.m.refresh() + self.assertEqual(self.m.state(), {"tasks": [], "error": "connection refused"}) + + def test_empty_url_is_quiet(self): + m = todo.make({"todo": {"url": ""}}) + self.assertEqual(m.state(), {"tasks": [], "error": None}) + self.assertEqual(m.actions, {}) + + +if __name__ == "__main__": + unittest.main() -- cgit v1.2.3