kanzo 0.4.3

Self-hosted kanban for humans and agents. One 5.0 MB binary, starts in 3 ms, zero setup.
"use strict";

// The board's service worker, only for notifications. It has no fetch handler, so the board
// loads as if it weren't there. When an agent escalates a task, this computer's Kanzo sends an
// empty push, and the browser wakes this worker, even with no board page open. The worker then
// asks Kanzo what to show, so nothing about a task goes through the push service.

const NEEDS_YOU = { en: "{0} needs you", "zh-cn": "{0} 需要你处理" };
const A_TASK = { en: "A task needs you", "zh-cn": "有任务需要你处理" };

self.addEventListener("install", () => self.skipWaiting());
// Takes the open pages at once, so a click brings one back without reloading it.
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));

self.addEventListener("push", (e) => e.waitUntil(show()));

// Kanzo's answer, or null if it didn't come within 5 seconds.
async function pending() {
  const stop = new AbortController();
  const timer = setTimeout(() => stop.abort(), 5000);
  try {
    const sub = await self.registration.pushManager.getSubscription();
    const res = await fetch("/api/push/pending", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ endpoint: sub ? sub.endpoint : "" }),
      signal: stop.signal,
    });
    return res.ok ? await res.json() : null;
  } catch {
    return null;
  } finally {
    clearTimeout(timer);
  }
}

async function show() {
  const answer = await pending();
  // A browser expects a notification for every push, and Safari stops pushing to a site that
  // shows none: if Kanzo couldn't say which task, one that says a task needs you. When it said
  // none, every task was handled before this push arrived, and there's nothing to say.
  if (!answer) {
    await self.registration.showNotification(A_TASK.en, { icon: "/icon.png", tag: "kanzo", data: { where: "" } });
    return;
  }
  const words = NEEDS_YOU[answer.lang] || NEEDS_YOU.en;
  for (const t of answer.tasks) {
    await self.registration.showNotification(words.replace("{0}", `${t.project}#${t.id}`), {
      body: t.title,
      icon: "/icon.png",
      tag: `kanzo-${t.shared ? "@" : ""}${t.id}`,
      // The board's address for the task: @ for the shared board this computer joined.
      data: { where: `${t.shared ? "@" : ""}${t.project}/${t.id}` },
    });
  }
}

self.addEventListener("notificationclick", (e) => {
  e.notification.close();
  e.waitUntil(open(e.notification.data?.where ?? ""));
});

// The installed app's window if it's open, or else a board tab, at the task. With none open, a
// new window, which the browser may open in the app if the app is installed.
async function open(where) {
  const pages = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
  const page = pages.find((p) => new URL(p.url).searchParams.has("app")) || pages[0];
  if (page) {
    await page.focus();
    page.postMessage({ open: where });
  } else {
    await self.clients.openWindow("/" + (where ? "#" + where : ""));
  }
}

// A browser renews a subscription now and then, as Firefox does: Kanzo learns the new one and
// forgets the old. Its language comes back with the next board page that opens.
self.addEventListener("pushsubscriptionchange", (e) => e.waitUntil(renew(e.oldSubscription)));

async function renew(old) {
  const send = (method, body) =>
    fetch("/api/push", { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
  const { key } = await (await fetch("/api/push")).json();
  const applicationServerKey = Uint8Array.from(atob(key.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
  const sub = await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });
  await send("POST", { endpoint: sub.endpoint, lang: "" });
  if (old) await send("DELETE", { endpoint: old.endpoint });
}