kaizen-agent 1.53.0 → 1.53.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/state.test.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  readRuns, readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, allBacklog, backlog,
11
11
  requestTitle, statusOf, columnOf, parseItem, startedRuns, boardCards, parentOf, addCard, readArchive, setArchived,
12
12
  requestOf, agentFlags, plainModel, readNotes, writeNotes, manualCommand, parseNotes, formatNote, appendNote, saveAttachment,
13
- reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, CLOSE_GRACE_MS, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, LOGO, type Card,
13
+ reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, CLOSE_GRACE_MS, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
14
14
  } from "./state.ts";
15
15
 
16
16
  let state: string;
@@ -748,6 +748,15 @@ test("notice: plain words for what a run waits on, done, and nothing for the res
748
748
  expect(notifyArgs("x")).toEqual(["notify-send", "-a", "kaizen", "-i", LOGO, "kaizen", "x"]);
749
749
  });
750
750
 
751
+ test("winToastArgs carries the body base64, so a quote cannot end the PowerShell string", () => {
752
+ const body = "it's \"done\" — ~/acme\n$(rm)";
753
+ const a = winToastArgs(body);
754
+ expect(a[0]).toMatch(/WindowsPowerShell\\v1\.0\\powershell\.exe$/);
755
+ const b64 = /FromBase64String\('([^']+)'\)/.exec(a.at(-1)!)![1]!;
756
+ expect(Buffer.from(b64, "base64").toString("utf8")).toBe(body);
757
+ expect(a.at(-1)).not.toContain("rm)");
758
+ });
759
+
751
760
  test("notifier: only a run seen before, saying something new, and not a done the user just approved", () => {
752
761
  const due = notifier(), M = 60_000;
753
762
  expect(due("r", "a", false, 0)).toBe(false); // first load, or arrived already waiting
package/cli/state.ts CHANGED
@@ -998,11 +998,24 @@ export const LOGO = join(dirname(import.meta.dir), "assets", "kaizen-logo.png");
998
998
  export function notifyArgs(body: string) {
999
999
  return ["notify-send", "-a", "kaizen", ...(existsSync(LOGO) ? ["-i", LOGO] : []), "kaizen", body];
1000
1000
  }
1001
+ // Windows: a toast through PowerShell's WinRT bridge, under PowerShell's own app id
1002
+ // (an unregistered id shows nothing). Windows PowerShell 5.1, not pwsh: 7 has no WinRT
1003
+ // projection. The body travels base64 so no quote can break out. The toast's own sound plays.
1004
+ export function winToastArgs(body: string) {
1005
+ const b64 = Buffer.from(body, "utf8").toString("base64");
1006
+ const ps = `$t=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64}'));` +
1007
+ `[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];` +
1008
+ `$x=[Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02);` +
1009
+ `$n=$x.GetElementsByTagName('text');[void]$n.Item(0).AppendChild($x.CreateTextNode('kaizen'));[void]$n.Item(1).AppendChild($x.CreateTextNode($t));` +
1010
+ `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show([Windows.UI.Notifications.ToastNotification]::new($x))`;
1011
+ return [sysExe("WindowsPowerShell\\v1.0\\powershell.exe"), "-NoProfile", "-NonInteractive", "-Command", ps];
1012
+ }
1001
1013
  export function notify(body: string) {
1002
1014
  try {
1003
- if (!Bun.which("notify-send")) return;
1004
- Bun.spawn(notifyArgs(body), {
1005
- stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true,
1015
+ const win = process.platform === "win32";
1016
+ if (!win && !Bun.which("notify-send")) return;
1017
+ Bun.spawn(win ? winToastArgs(body) : notifyArgs(body), {
1018
+ stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true, windowsHide: true,
1006
1019
  }).unref();
1007
1020
  } catch { /* notifications are not worth an exception */ }
1008
1021
  }
package/cli/web.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // `kaizen web`: the board in a browser. A loopback HTTP server over state.ts and
2
2
  // one HTML page; the page never sees the filesystem, only JSON.
3
- import { existsSync, readdirSync, statSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, type FSWatcher } from "node:fs";
3
+ import { existsSync, readdirSync, statSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
4
4
  import { join, dirname, resolve, sep, basename } from "node:path";
5
5
  import {
6
6
  home, type Item, type Card, boardCards, knownProjects, remember, locate, label, tilde, searchRoots, findProjects,
@@ -222,6 +222,45 @@ export async function web(repoDir: string, opts: Opts = {}) {
222
222
  };
223
223
  // agent.launch: card runs what this board launches inside the board, shown on the card.
224
224
  const inCard = (dir: string) => ({ card: launchMode(projectOf(dir)) === "card", onChange: changed });
225
+
226
+ // Start a run's agent again after it ended mid-stage (crashed, closed, a stalled run, or
227
+ // the board restarting for an upgrade), in the conversation it had where the tool can
228
+ // resume one. A run waiting for a decision, or done, gets its conversation back with
229
+ // nothing sent to it -- the user talks to it -- and only when that conversation exists.
230
+ // Never beside a live in-card agent, never on an abandoned run.
231
+ const resumeRun = (dir: string, id: string) => {
232
+ let run: any;
233
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return { error: "no such run", status: 404 }; }
234
+ if (run.stage === "abandoned") return { error: "this run was abandoned", status: 409 };
235
+ if (readSessions(dir).some((s) => ptyState(s.key)?.alive && ownerOf(dir, s) === id)) return { error: "its agent is still running in its card", status: 409 };
236
+ const quiet = run.stage === "done" || !!run.awaiting;
237
+ const own = quiet ? runAgent(dir, id) : null;
238
+ if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
239
+ const text = quiet ? "" : resumePrompt(id);
240
+ const before = Date.now();
241
+ const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
242
+ if (r.ok) closeSessions(dir, id, { before });
243
+ changed();
244
+ return r;
245
+ };
246
+
247
+ // Runs whose in-card agent was live when Settings' Update restarted the board: the
248
+ // agents end with the old board, so the new one starts them again (resumeRun). Each
249
+ // entry keeps its session key, so an idea whose run had not written state.json yet is
250
+ // matched to its run by the new board, once that run exists. The agents are ended here,
251
+ // not left to the board's exit, so none outlives it beside its resumed self.
252
+ const RESUME_LIST = join(home, ".kaizen", "resume-after-upgrade.json");
253
+ const saveLive = () => {
254
+ const live = new Set(ptyKeys().filter((k) => ptyState(k)?.alive));
255
+ if (!live.size) return;
256
+ const list: { dir: string; key: string; run: string | null }[] = [];
257
+ for (const d of states(true)) {
258
+ const idx = runIndex(d);
259
+ for (const s of readSessions(d)) if (live.has(s.key)) list.push({ dir: d, key: s.key, run: ownerOf(d, s, idx) });
260
+ }
261
+ try { writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), list })); } catch { /* nothing resumes; the card offers Resume */ }
262
+ for (const k of live) exitPty(k, 200);
263
+ };
225
264
  // An idea's session, until its run exists and owns it (ownerOf).
226
265
  const ideaPty = new Map<string, string>();
227
266
  // Backlog items this board launched whose run has not written its state.json yet:
@@ -750,6 +789,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
750
789
  Bun.spawn([process.execPath, join(helper, "cli", "install.ts"), "upgrade", "--wait", String(process.pid), "--restart", String(srv.port)], {
751
790
  cwd: home, detached: true, stdio: ["ignore", log, log], windowsHide: true,
752
791
  }).unref();
792
+ saveLive();
753
793
  setTimeout(() => process.exit(0), 300);
754
794
  return json({ ok: true });
755
795
  }
@@ -761,6 +801,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
761
801
  if (code !== 0) return bad(why || `kaizen upgrade exited ${code}`, 500);
762
802
  if (installed() === VERSION) return bad(why || "Already up to date");
763
803
  const port = srv.port;
804
+ saveLive();
764
805
  setTimeout(() => {
765
806
  Bun.spawn([process.execPath, join(repoDir, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
766
807
  detached: true, stdio: ["ignore", "ignore", "ignore"], windowsHide: true,
@@ -1395,27 +1436,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1395
1436
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1396
1437
  }
1397
1438
 
1398
- // Start a run's agent again after it ended mid-stage (crashed, closed, or a stalled
1399
- // run), in the conversation it had where the tool can resume one. A run waiting for
1400
- // a decision, or done, gets its conversation back with nothing sent to it -- the
1401
- // user talks to it -- and only when that conversation exists. Never beside a live
1402
- // in-card agent, never on an abandoned run.
1439
+ // Start a run's agent again after it ended mid-stage (resumeRun).
1403
1440
  if (path === "/resume") {
1404
1441
  const id = String(body.id ?? "");
1405
1442
  if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1406
1443
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
1407
- let run: any;
1408
- try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1409
- if (run.stage === "abandoned") return bad("this run was abandoned", 409);
1410
- if (readSessions(dir).some((s) => ptyState(s.key)?.alive && ownerOf(dir, s) === id)) return bad("its agent is still running in its card", 409);
1411
- const quiet = run.stage === "done" || !!run.awaiting;
1412
- const own = quiet ? runAgent(dir, id) : null;
1413
- if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return bad("no conversation of this run to resume", 409);
1414
- const text = quiet ? "" : resumePrompt(id);
1415
- const before = Date.now();
1416
- const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1417
- if (r.ok) closeSessions(dir, id, { before });
1418
- changed();
1444
+ const r = resumeRun(dir, id);
1445
+ if ("error" in r) return bad(r.error, r.status);
1419
1446
  return json(r.ok
1420
1447
  ? { ok: true, agent: r.agent, pty: r.pty }
1421
1448
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
@@ -1443,6 +1470,24 @@ export async function web(repoDir: string, opts: Opts = {}) {
1443
1470
  },
1444
1471
  }); }
1445
1472
 
1473
+ // Read once and removed first, so a board that fails to start one does not retry it
1474
+ // forever. A list older than an hour is from an upgrade whose board never came back
1475
+ // (a failed Windows hand-off): too late to pick its runs up unasked.
1476
+ if (existsSync(RESUME_LIST)) {
1477
+ let saved: { at?: number; list?: { dir: string; key: string; run: string | null }[] } = {};
1478
+ try { saved = JSON.parse(readText(RESUME_LIST)); } catch { /* unreadable: nothing to resume */ }
1479
+ rmSync(RESUME_LIST, { force: true });
1480
+ const done = new Set<string>();
1481
+ for (const { dir, key, run } of Date.now() - (saved.at ?? 0) < 3600_000 ? saved.list ?? [] : []) {
1482
+ const s = run ? null : readSessions(dir).find((x) => x.key === key);
1483
+ const id = run ?? (s ? ownerOf(dir, s) : null);
1484
+ if (!id || done.has(`${dir}\0${id}`)) continue;
1485
+ done.add(`${dir}\0${id}`);
1486
+ const r = resumeRun(dir, id);
1487
+ console.log(` ${"error" in r || !r.ok ? "could not resume" : "resumed"} ${id}${"error" in r ? ` (${r.error})` : !r.ok ? ` (${r.why})` : ""}`);
1488
+ }
1489
+ }
1490
+
1446
1491
  const url = `http://127.0.0.1:${server.port}/`;
1447
1492
  console.log(`\n kaizen web ${url}`);
1448
1493
  console.log(` ${boardState ? `project ${label(boardState)}` : "no .kaizen here; showing every known project"}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.53.0",
3
+ "version": "1.53.1",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -468,11 +468,18 @@ async function startRun(c, kind) {
468
468
 
469
469
  const HINT = { 0: "Add an idea to start a run", 1: "Ideas you run are planned here", 2: "Approved plans are built here", 3: "Finished builds are checked here" };
470
470
 
471
+ // Files picked in the new-idea form. Held here, not in the form, because the board
472
+ // redraws the inline form on every change and a redraw would drop them.
473
+ let newFiles = [];
471
474
  // The new-idea form, wired into f: inline at the top of Ideas, or in a modal.
472
- function ideaForm(f, close) {
475
+ function ideaForm(f, shut) {
476
+ const close = () => {
477
+ newFiles = [];
478
+ shut();
479
+ };
473
480
  f.innerHTML = html`${store.all ? html`<div class="combo" id="ndc"><button type="button" class="sel" id="newdir" aria-label="Project for this idea" aria-haspopup="listbox" aria-expanded="false"></button><div class="menu-pop" hidden><input class="sel" aria-label="Search projects" placeholder="Search projects…" spellcheck="false" autocomplete="off"><div id="nds" role="listbox"></div></div></div>` : ""}<input id="newidea" placeholder="What do you want to build?"><textarea id="newnotes" placeholder="Anything the planner should know (optional)"></textarea><div class="att" id="newatt"></div><input type="file" id="newfile" multiple hidden><div class="row"><button type="button" class="ib" id="newpick" aria-label="Attach files" title="Attach files">${ico("clip")}</button><button type="button" class="btn ghost" id="nc">Cancel</button><div class="split"><button type="button" class="btn pri" id="ns">Add</button><button type="button" class="btn pri" id="nm" aria-label="More ways to add" aria-haspopup="menu" aria-expanded="false">${ico("chev")}</button><div class="menu-pop" role="menu" hidden><button type="button" role="menuitem" id="nr" title="Add the idea and run it now">${ico("play")}Start run</button></div></div></div>`;
474
481
  const inp = f.querySelector("#newidea"),
475
- files = [];
482
+ files = newFiles;
476
483
  draft(inp, "f:new:0");
477
484
  draft(f.querySelector("textarea"), "f:new:1");
478
485
  // run: add the idea, then launch it at once with the project's runner and agent.
@@ -499,10 +506,12 @@ function ideaForm(f, close) {
499
506
  }
500
507
  load();
501
508
  };
509
+ const shown = () => (f.querySelector("#newatt").textContent = files.map((y) => y.name).join(" · "));
502
510
  const add = (x) => {
503
511
  files.push(x);
504
- f.querySelector("#newatt").textContent = files.map((y) => y.name).join(" · ");
512
+ shown();
505
513
  };
514
+ shown();
506
515
  f.querySelector("#newpick").onclick = () => f.querySelector("#newfile").click();
507
516
  f.querySelector("#newfile").onchange = (e) => {
508
517
  [...e.target.files].forEach(add);
@@ -573,6 +582,7 @@ export function newIdea() {
573
582
  store.mode = null;
574
583
  render();
575
584
  }
585
+ newFiles = [];
576
586
  const dl = modal("");
577
587
  const f = dl.querySelector("form");
578
588
  f.onsubmit = (e) => e.preventDefault();
@@ -587,6 +597,8 @@ export function render() {
587
597
  store.mode = null;
588
598
  if (store.mode !== "run" && runPick) runPick.yolo = false;
589
599
  if (!store.mode) undraft("f:");
600
+ // Reassigned, not emptied: a form still open (the modal) keeps its own array.
601
+ if (store.mode !== "new") newFiles = [];
590
602
  try {
591
603
  sessionStorage.setItem(
592
604
  "kz-form",
@@ -858,7 +870,7 @@ export function render() {
858
870
  ul.appendChild(li);
859
871
  }
860
872
  // An empty middle column says what lands in it, so it does not look broken.
861
- if (!list.length && ci <= 3 && !bl && cs.length && !filter && !q && !archive)
873
+ if (!list.length && !ul.children.length && ci <= 3 && !bl && cs.length && !filter && !q && !archive)
862
874
  ul.innerHTML = `<li class="hint">${HINT[ci]}</li>`;
863
875
  if (bl && !list.length && !filter && !q)
864
876
  ul.innerHTML = `<li class="hint">${sev ? "Nothing at this severity" : "What finished runs left undone shows here"}</li>`;
package/web/board/chat.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { load, post } from "./api.ts";
2
2
  import { key } from "./cards.ts";
3
3
  import { mic, stopDictation } from "./dictation.ts";
4
- import { $, html, raw as rawHtml } from "./dom.ts";
4
+ import { $, dataUrls, html, raw as rawHtml } from "./dom.ts";
5
5
  import { DK, draft } from "./drafts.ts";
6
6
  import { attach, brief, md } from "./markdown.ts";
7
7
  import { rich } from "./rich.ts";
@@ -40,6 +40,9 @@ export function pretty(t) {
40
40
  .trim();
41
41
  }
42
42
  let nfocus = null;
43
+ // Files picked per card, outside the panel: a redraw while the box is not focused
44
+ // (just after the file picker, say) rebuilds it, and used to drop them.
45
+ const pend = new Map();
43
46
  export function chat(c, src, ro) {
44
47
  const fix = (t) => attach(t, c);
45
48
  const entries = parseNotes(src);
@@ -57,8 +60,9 @@ export function chat(c, src, ro) {
57
60
  h += `<div class="notes"><textarea placeholder="Add a note. Paste a screenshot, or attach files."></textarea><div class="att" id="natt"></div><div class="tools"><input type="file" id="nfile" multiple hidden><button class="btn ghost" id="npick">Attach</button><span>Enter sends, Shift+Enter newline</span><button class="btn pri" id="nsend">Send</button></div></div>`;
58
61
  $("pbody").innerHTML = rawHtml(h);
59
62
  if (ro) return;
63
+ if (!pend.has(key(c))) pend.set(key(c), []);
60
64
  const ta = $("pbody").querySelector("textarea"),
61
- files = [];
65
+ files = pend.get(key(c));
62
66
  draft(ta, "n:" + key(c));
63
67
  const ed = rich(ta);
64
68
  // Enter leaves focus in the box, and a focused box blocks the redraw: send blurs it
@@ -78,6 +82,7 @@ export function chat(c, src, ro) {
78
82
  files.push(f);
79
83
  show();
80
84
  };
85
+ show();
81
86
  $("npick").onclick = () => $("nfile").click();
82
87
  $("nfile").onchange = (e) => {
83
88
  [...e.target.files].forEach(add);
@@ -95,16 +100,7 @@ export function chat(c, src, ro) {
95
100
  stopDictation(true);
96
101
  const text = ta.value.trim();
97
102
  if (!text && !files.length) return;
98
- const enc = await Promise.all(
99
- files.map(
100
- (f) =>
101
- new Promise((r) => {
102
- const rd = new FileReader();
103
- rd.onload = () => r({ name: f.name, data: rd.result });
104
- rd.readAsDataURL(f);
105
- }),
106
- ),
107
- );
103
+ const enc = await dataUrls(files);
108
104
  const body =
109
105
  c.kind === "run" ? { dir: c.state, id: c.id, text, files: enc } : { dir: c.state, for: c.text, text, files: enc };
110
106
  const r = await post("/note", body);
package/web/board/dom.ts CHANGED
@@ -21,16 +21,36 @@ export const SKEL = raw(
21
21
  '<span class="skel" style="height:44px;margin-bottom:10px"></span>'.repeat(4) +
22
22
  "</div>",
23
23
  );
24
+ // A phone photo is many MB and a few of them pass the server's cap; a big raster image
25
+ // goes up as a JPEG of at most 2560px a side. Anything that will not decode goes as is.
26
+ const MAX_IMG = 1_500_000;
27
+ async function shrink(x: File): Promise<File> {
28
+ if (x.size <= MAX_IMG || !/^image\/(jpeg|png|webp|bmp|heic|heif)$/.test(x.type)) return x;
29
+ try {
30
+ const bm = await createImageBitmap(x);
31
+ const k = Math.min(1, 2560 / Math.max(bm.width, bm.height));
32
+ const c = document.createElement("canvas");
33
+ c.width = Math.round(bm.width * k);
34
+ c.height = Math.round(bm.height * k);
35
+ c.getContext("2d").drawImage(bm, 0, 0, c.width, c.height);
36
+ const b = await new Promise<Blob | null>((r) => c.toBlob(r, "image/jpeg", 0.85));
37
+ return b && b.size < x.size ? new File([b], x.name.replace(/\.\w+$/, "") + ".jpg", { type: "image/jpeg" }) : x;
38
+ } catch {
39
+ return x;
40
+ }
41
+ }
24
42
  // Files as {name, data-URL}, the shape /note and /icebox take.
25
43
  export const dataUrls = (files: File[]) =>
26
44
  Promise.all(
27
45
  files.map(
28
- (x) =>
29
- new Promise<{ name: string; data: string }>((res) => {
46
+ async (f) => {
47
+ const x = await shrink(f);
48
+ return new Promise<{ name: string; data: string }>((res) => {
30
49
  const rd = new FileReader();
31
50
  rd.onload = () => res({ name: x.name, data: rd.result as string });
32
51
  rd.readAsDataURL(x);
33
- }),
52
+ });
53
+ },
34
54
  ),
35
55
  );
36
56
  // A modal form: the native <dialog>, removed from the page once closed.
@@ -4,7 +4,7 @@ import { load, post } from "./api.ts";
4
4
  import { stopDictation } from "./dictation.ts";
5
5
  import { $, html, SKEL } from "./dom.ts";
6
6
  import { close } from "./panel.ts";
7
- import { askNotify, toast } from "./toast.ts";
7
+ import { askNotify, notifyOn, playSound, soundPick, SOUNDS, toast } from "./toast.ts";
8
8
  import { updBar } from "./update.ts";
9
9
  import { view } from "./views.ts";
10
10
 
@@ -69,7 +69,8 @@ export async function openSettings() {
69
69
  html`<div class="srow${off ? " off" : ""}" data-q="${q.toLowerCase()}"><label for="${id}" id="${id}-l">${label}</label>${control}${hint ? html`<p class="hint">${hint}</p>` : ""}</div>`;
70
70
  const hadFocus = document.activeElement?.id === "sq";
71
71
  const np = typeof Notification === "undefined" ? null : Notification.permission;
72
- const ntHelp = np ? (np === "denied" ? "Blocked by this browser" : "") : "Not supported in this browser";
72
+ const nton = notifyOn();
73
+ const ntHelp = !nton ? "Off in this browser" : np === "granted" ? "" : np === "denied" ? "Pop-ups blocked by this browser; the sound still plays" : np ? "Pop-ups wait for the browser to ask; the sound still plays" : "Pop-ups not supported here; the sound still plays";
73
74
  $("pbody").innerHTML = html`<div class="sq"><input class="sel" id="sq" type="search" placeholder="Search settings" aria-label="Search settings" spellcheck="false" autocomplete="off" value="${store.setQ}"></div>
74
75
  ${
75
76
  cfg
@@ -100,7 +101,8 @@ export async function openSettings() {
100
101
  ${row("Google account", html`<button class="btn${gg.connected ? "" : " pri"}" id="gg-conn" type="button"${gg.hasClient || gg.connected ? "" : " disabled"}>${gg.connected ? "Disconnect" : "Connect"}</button>`, "", "gg-conn", "google account connect sheets write back")}</div>
101
102
  <h3 class="sg">Browser</h3><div class="sgrp">${row("Theme", ctl("th", ["system", "light", "dark"], cur), "", "th", "theme light dark system browser")}
102
103
  ${row("Motion", ctl("mo", ["system", "full", "reduce"], document.documentElement.dataset.motion || "system"), "Animations on the board and notes. System follows the device's reduce-motion setting.", "mo", "motion animation reduce reduced browser")}
103
- ${row("Notifications", html`<button class="chk${np === "granted" ? " on" : ""}" id="nt" role="switch" aria-checked="${String(np === "granted")}"${np && np !== "denied" ? "" : " disabled"}></button>`, ntHelp, "nt", "notifications " + ntHelp + " browser")}</div>
104
+ ${row("Notifications", html`<button class="chk${nton ? " on" : ""}" id="nt" role="switch" aria-checked="${String(nton)}"></button>`, ntHelp, "nt", "notifications " + ntHelp + " browser")}
105
+ ${row("Notification sound", ctl("ns", SOUNDS, soundPick()), "Plays with each notice. Changing it plays it.", "ns", "notification sound chime bell pop audio browser", !nton)}</div>
104
106
  <p class="snone" id="snone" hidden></p>`;
105
107
  // Hides rows that do not match, then any group (and its chip) left with none.
106
108
  updBar();
@@ -187,9 +189,19 @@ export async function openSettings() {
187
189
  stepper($("th"), ["system", "light", "dark"], cur, setTheme);
188
190
  stepper($("mo"), ["system", "full", "reduce"], document.documentElement.dataset.motion || "system", setMotion);
189
191
  $("nt").onclick = () => {
190
- askNotify();
192
+ const on = !notifyOn();
193
+ try {
194
+ localStorage.setItem("kz-notify", on ? "on" : "off");
195
+ } catch (e) {}
196
+ if (on) askNotify();
191
197
  setTimeout(openSettings, 300);
192
198
  };
199
+ stepper($("ns"), SOUNDS, soundPick(), (v) => {
200
+ try {
201
+ localStorage.setItem("kz-sound", v);
202
+ } catch (e) {}
203
+ playSound(v);
204
+ });
193
205
  if (cfg)
194
206
  cfg.rows.forEach((r) => {
195
207
  const el = $("s-" + r.key.replace(/\./g, "-"));
@@ -24,8 +24,53 @@ export function askNotify() {
24
24
  if (typeof Notification !== "undefined" && Notification.permission === "default") Notification.requestPermission();
25
25
  } catch (e) {}
26
26
  }
27
+ // Per browser: whether notices go out at all, and the sound each one plays. The OS
28
+ // notification's own sound is often silent (Windows toasts, focus assist), so the page
29
+ // plays its own, synthesized: no audio files to ship.
30
+ const pref = (k, d) => {
31
+ try {
32
+ return localStorage.getItem(k) || d;
33
+ } catch (e) {
34
+ return d;
35
+ }
36
+ };
37
+ export const notifyOn = () => pref("kz-notify", "on") === "on";
38
+ export const soundPick = () => pref("kz-sound", "chime");
39
+ export const SOUNDS = ["off", "chime", "bell", "pop"];
40
+ // [frequency Hz, start s, length s] per note.
41
+ const NOTES = { chime: [[880, 0, 0.25], [1320, 0.12, 0.35]], bell: [[660, 0, 0.9]], pop: [[520, 0, 0.08]] };
42
+ let actx;
43
+ export function playSound(name = soundPick()) {
44
+ try {
45
+ if (!NOTES[name]) return;
46
+ actx = actx || new AudioContext();
47
+ actx.resume();
48
+ const t0 = actx.currentTime + 0.02;
49
+ for (const [hz, at, len] of NOTES[name]) {
50
+ const o = actx.createOscillator(),
51
+ g = actx.createGain();
52
+ o.type = name === "pop" ? "triangle" : "sine";
53
+ o.frequency.value = hz;
54
+ g.gain.setValueAtTime(0.0001, t0 + at);
55
+ g.gain.exponentialRampToValueAtTime(0.25, t0 + at + 0.01);
56
+ g.gain.exponentialRampToValueAtTime(0.0001, t0 + at + len);
57
+ o.connect(g).connect(actx.destination);
58
+ o.start(t0 + at);
59
+ o.stop(t0 + at + len + 0.05);
60
+ }
61
+ } catch (e) {}
62
+ }
63
+ // A browser only lets a page make sound after a press on it; the first one unlocks it.
64
+ addEventListener("pointerdown", () => {
65
+ try {
66
+ actx = actx || new AudioContext();
67
+ actx.resume();
68
+ } catch (e) {}
69
+ }, { once: true });
27
70
  // tag: one notification per thing, so several open board tabs replace each other's.
28
71
  export function notifyUser(body, tag?: string) {
72
+ if (!notifyOn()) return;
73
+ playSound();
29
74
  try {
30
75
  if (typeof Notification !== "undefined" && Notification.permission === "granted")
31
76
  new Notification("kaizen", { body, icon: "/logo.png", tag });