kaizen-agent 1.52.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/web.ts CHANGED
@@ -1,10 +1,10 @@
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,
7
- readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
7
+ readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
8
8
  appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, notice, notifier, LOGO,
9
9
  reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, nativePath, closeSessions, sweepSessions, issueUrl,
10
10
  launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
@@ -34,6 +34,9 @@ const TERM_JS = join(dirname(import.meta.dir), "web", "term.js");
34
34
  const TERM_CSS = join(dirname(import.meta.dir), "web", "term.css");
35
35
  // The Video page (kaizen-video's library, editor and renders) and its bundle.
36
36
  const VIDEO_PAGE = join(dirname(import.meta.dir), "web", "video.html");
37
+ const POPUP_PAGE = join(dirname(import.meta.dir), "web", "popup.html");
38
+ // The chat the popup was on when its Back button was pressed, until Home takes it.
39
+ let popupChat: string | null = null;
37
40
  const VIDEO_JS = join(dirname(import.meta.dir), "web", "video.js");
38
41
  const DEFAULT_PORT = 7420;
39
42
  // Gathered posts a reply is going out to right now: one send per item at a time.
@@ -219,6 +222,45 @@ export async function web(repoDir: string, opts: Opts = {}) {
219
222
  };
220
223
  // agent.launch: card runs what this board launches inside the board, shown on the card.
221
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
+ };
222
264
  // An idea's session, until its run exists and owns it (ownerOf).
223
265
  const ideaPty = new Map<string, string>();
224
266
  // Backlog items this board launched whose run has not written its state.json yet:
@@ -408,6 +450,63 @@ export async function web(repoDir: string, opts: Opts = {}) {
408
450
  return new Response(body, { headers: { "content-type": type, "cache-control": "no-store" } });
409
451
  }
410
452
 
453
+ // `kaizen chat`: the small chat window over the desktop.
454
+ if (req.method === "GET" && path === "/popup") {
455
+ const body = served(POPUP_PAGE);
456
+ if (body === null) return new Response("web/popup.html missing", { status: 500 });
457
+ return new Response(body, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } });
458
+ }
459
+
460
+ // Handing the chat between Home and the popup (`kaizen chat`). /popup/open:
461
+ // open the popup on Home's chat and hide the board's browser window in a
462
+ // special workspace. /popup/board: bring that window back, focus it (open the
463
+ // board when no window shows it) and close the popup. Hyprland moves windows;
464
+ // elsewhere only the popup opens and closes.
465
+ if (req.method === "POST" && (path === "/popup/open" || path === "/popup/board")) {
466
+ const body = await req.json().catch(() => ({}));
467
+ const chat = (...a: string[]) => Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "chat", "--port", String(new URL(req.url).port || DEFAULT_PORT), ...a], { stdout: "ignore", stderr: "ignore" }).exited;
468
+ const hypr = !!process.env.HYPRLAND_INSTANCE_SIGNATURE && !!Bun.which("hyprctl");
469
+ const json = async (cmd: string) => await Bun.$`hyprctl ${cmd} -j`.quiet().nothrow().json().catch(() => null);
470
+ // Several windows can show a board: Pop out takes the one clicked in (the active
471
+ // one), Back the one Pop out hid.
472
+ const isBoard = (c: any) => c && /(^|\) )kaizen( [—-] |$)/.test(String(c.title));
473
+ const all: any[] = hypr ? (await json("clients")) || [] : [];
474
+ const active = hypr ? await json("activewindow") : null;
475
+ const board = path === "/popup/open" ? (isBoard(active) ? active : all.find(isBoard))
476
+ : all.find((c) => isBoard(c) && c.workspace?.name === "special:kaizen") ?? all.find(isBoard);
477
+ const w = board && `address:${board.address}`;
478
+ // Lua grammar first (Hyprland 0.55+ with a Lua config), the classic words after.
479
+ const dispatch = async (lua: string, legacy: string[]) => {
480
+ if ((await Bun.$`hyprctl dispatch ${lua}`.quiet().nothrow().text()).trim() !== "ok") await Bun.$`hyprctl dispatch ${legacy}`.quiet().nothrow();
481
+ };
482
+ if (path === "/popup/open") {
483
+ const id = typeof body.id === "string" && /^[\w.-]+$/.test(body.id) ? body.id : "";
484
+ await chat("--show", ...(id ? ["--chat", id] : []));
485
+ if (w) await dispatch(`hl.dsp.window.move({ workspace = "special:kaizen", follow = false, window = "${w}" })`, ["movetoworkspacesilent", `special:kaizen,${w}`]);
486
+ // Typing goes to the popup, not to whatever was under the hidden board.
487
+ const pop = hypr && ((await json("clients")) || []).find((c: any) => c.class === "kaizen-chat" || String(c.class).startsWith("chrome-127.0.0.1__popup"));
488
+ if (pop) await dispatch(`hl.dsp.focus({ window = "address:${pop.address}" })`, ["focuswindow", `address:${pop.address}`]);
489
+ return Response.json({ ok: true, hidden: !!w });
490
+ }
491
+ if (!w) Bun.spawn([process.platform === "darwin" ? "open" : "xdg-open", new URL("/", req.url).href], { stdout: "ignore", stderr: "ignore" });
492
+ else {
493
+ if (String(board.workspace?.name).startsWith("special:")) {
494
+ const ws = (await json("activeworkspace"))?.id ?? 1;
495
+ await dispatch(`hl.dsp.window.move({ workspace = "${ws}", window = "${w}" })`, ["movetoworkspace", `${ws},${w}`]);
496
+ }
497
+ await dispatch(`hl.dsp.focus({ window = "${w}" })`, ["focuswindow", w]);
498
+ }
499
+ if (typeof body.id === "string") popupChat = body.id;
500
+ await chat("--close");
501
+ return Response.json({ ok: true });
502
+ }
503
+ // Home, refocused after Back, takes the popup's chat once.
504
+ if (req.method === "GET" && path === "/popup/handoff") {
505
+ const id = popupChat;
506
+ popupChat = null;
507
+ return Response.json({ id });
508
+ }
509
+
411
510
  if (req.method === "GET" && (path === "/video" || path === "/video.js")) {
412
511
  const [f, type] = path === "/video" ? [VIDEO_PAGE, "text/html; charset=utf-8"] : [VIDEO_JS, "application/javascript; charset=utf-8"];
413
512
  const body = served(f);
@@ -690,6 +789,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
690
789
  Bun.spawn([process.execPath, join(helper, "cli", "install.ts"), "upgrade", "--wait", String(process.pid), "--restart", String(srv.port)], {
691
790
  cwd: home, detached: true, stdio: ["ignore", log, log], windowsHide: true,
692
791
  }).unref();
792
+ saveLive();
693
793
  setTimeout(() => process.exit(0), 300);
694
794
  return json({ ok: true });
695
795
  }
@@ -701,6 +801,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
701
801
  if (code !== 0) return bad(why || `kaizen upgrade exited ${code}`, 500);
702
802
  if (installed() === VERSION) return bad(why || "Already up to date");
703
803
  const port = srv.port;
804
+ saveLive();
704
805
  setTimeout(() => {
705
806
  Bun.spawn([process.execPath, join(repoDir, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
706
807
  detached: true, stdio: ["ignore", "ignore", "ignore"], windowsHide: true,
@@ -841,6 +942,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
841
942
  const r = await makeProject(name);
842
943
  return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
843
944
  },
945
+ agents: KNOWN_AGENTS.filter((a) => onPath(a.cmd)).map((a) => a.cmd),
946
+ // As POST /run starts an idea, without one on the inbox.
947
+ run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
948
+ const r = launchRun(parseItem(`${runner} ${text}`), d, undefined, { agent, ...inCard(d) });
949
+ changed();
950
+ return r.ok ? { agent: r.agent.cmd } : { error: r.why };
951
+ },
844
952
  };
845
953
  let ctl!: ReadableStreamDefaultController;
846
954
  const stream = new ReadableStream({ start: (c) => { ctl = c; } });
@@ -1328,27 +1436,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1328
1436
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1329
1437
  }
1330
1438
 
1331
- // Start a run's agent again after it ended mid-stage (crashed, closed, or a stalled
1332
- // run), in the conversation it had where the tool can resume one. A run waiting for
1333
- // a decision, or done, gets its conversation back with nothing sent to it -- the
1334
- // user talks to it -- and only when that conversation exists. Never beside a live
1335
- // in-card agent, never on an abandoned run.
1439
+ // Start a run's agent again after it ended mid-stage (resumeRun).
1336
1440
  if (path === "/resume") {
1337
1441
  const id = String(body.id ?? "");
1338
1442
  if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1339
1443
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
1340
- let run: any;
1341
- try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1342
- if (run.stage === "abandoned") return bad("this run was abandoned", 409);
1343
- if (readSessions(dir).some((s) => ptyState(s.key)?.alive && ownerOf(dir, s) === id)) return bad("its agent is still running in its card", 409);
1344
- const quiet = run.stage === "done" || !!run.awaiting;
1345
- const own = quiet ? runAgent(dir, id) : null;
1346
- if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return bad("no conversation of this run to resume", 409);
1347
- const text = quiet ? "" : resumePrompt(id);
1348
- const before = Date.now();
1349
- const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1350
- if (r.ok) closeSessions(dir, id, { before });
1351
- changed();
1444
+ const r = resumeRun(dir, id);
1445
+ if ("error" in r) return bad(r.error, r.status);
1352
1446
  return json(r.ok
1353
1447
  ? { ok: true, agent: r.agent, pty: r.pty }
1354
1448
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
@@ -1376,6 +1470,24 @@ export async function web(repoDir: string, opts: Opts = {}) {
1376
1470
  },
1377
1471
  }); }
1378
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
+
1379
1491
  const url = `http://127.0.0.1:${server.port}/`;
1380
1492
  console.log(`\n kaizen web ${url}`);
1381
1493
  console.log(` ${boardState ? `project ${label(boardState)}` : "no .kaizen here; showing every known project"}`);
@@ -1518,7 +1630,9 @@ export async function shortcut() {
1518
1630
  // style 0 starts `kaizen web --daemon` with no window at all; the daemon outlives
1519
1631
  // that launcher and `kaizen web --stop` ends it. A crash has no console to land
1520
1632
  // in, so web() writes it to ~/.kaizen/web.log instead. A .lnk icon must be an .ico.
1521
- const lnk = join(home, "Desktop", "Kaizen.lnk");
1633
+ // OneDrive moves the Desktop (C:\Users\x\OneDrive\Desktop), so ask Windows for it.
1634
+ const desk = (await Bun.$`${powershellExe()} -NoProfile -Command [Environment]::GetFolderPath('Desktop')`.quiet().nothrow().text()).trim();
1635
+ const lnk = join(desk || join(home, "Desktop"), "Kaizen.lnk");
1522
1636
  const ico = join(dirname(import.meta.dir), "assets", "kaizen.ico");
1523
1637
  const vbs = join(home, ".kaizen", "kaizen-web.vbs");
1524
1638
  mkdirSync(dirname(vbs), { recursive: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.52.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": {
@@ -159,6 +159,10 @@ board:
159
159
  # Where `kaizen web` opens the board: browser (a tab in your default browser) or
160
160
  # app (a Chrome, Edge or Brave window with no tabs or address bar).
161
161
  open: browser
162
+ # The key that opens and closes `kaizen chat`, the popup chat window. kaizen
163
+ # writes it into your Hyprland config (bindings.lua or hyprland.conf), taking the
164
+ # key over from whatever held it. Empty: no hotkey. Hyprland only for now.
165
+ chat_hotkey: "SUPER + ALT + SPACE"
162
166
 
163
167
  sources:
164
168
  # How often the web board checks your request sources (links added in the board's
@@ -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.
package/web/board/home.ts CHANGED
@@ -82,7 +82,7 @@ function chips() {
82
82
  }
83
83
 
84
84
  function list() {
85
- return html`<div class="hsin"><div class="hshd"><span>Chats</span><button class="ib sm" id="hclose" aria-label="Hide chats" title="Hide chats">${ico("side")}</button></div><nav class="hlist" aria-label="Chats">${chats.map((c) => html`<div class="hli${cur && cur.id === c.id ? " on" : ""}"><button data-c="${c.id}" title="${c.title}">${c.busy ? html`<span class="dot"></span>` : ""}<span class="ht">${c.title}</span><span class="hp">${c.project ? name(c.project) : "No project"}</span></button><button class="ib sm" data-del="${c.id}" aria-label="Delete chat: ${c.title}" title="Delete chat">${ico("trash")}</button></div>`)}</nav></div>`;
85
+ return html`<div class="hsin"><div class="hshd"><span>Chats</span></div><nav class="hlist" aria-label="Chats">${chats.map((c) => html`<div class="hli${cur && cur.id === c.id ? " on" : ""}"><button data-c="${c.id}" title="${c.title}">${c.busy ? html`<span class="dot"></span>` : ""}<span class="ht">${c.title}</span><span class="hp">${c.project ? name(c.project) : "No project"}</span></button><button class="ib sm" data-del="${c.id}" aria-label="Delete chat: ${c.title}" title="Delete chat">${ico("trash")}</button></div>`)}</nav></div>`;
86
86
  }
87
87
 
88
88
  function bindReply(root) {
@@ -184,7 +184,6 @@ function draw() {
184
184
  seen = empty ? 0 : cur.messages.length;
185
185
  shown = cur && cur.id;
186
186
  $("htog").onclick = () => setSide(!side);
187
- $("hclose").onclick = () => setSide(false);
188
187
  $("hscrim").onclick = () => setSide(false);
189
188
  const q = $("hq");
190
189
  renderAttachments();
@@ -212,6 +211,11 @@ function draw() {
212
211
  };
213
212
  syncSendButton();
214
213
  $("hnewtop").onclick = newChat;
214
+ // Pop out: `kaizen chat` opens the popup on this chat and hides this window.
215
+ $("hpop").onclick = () =>
216
+ fetch("/popup/open", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id: cur?.id }) })
217
+ .then((r) => r.ok || toast("Could not open the popup"))
218
+ .catch(() => toast("Could not open the popup"));
215
219
  $("hnewtop").disabled = sending;
216
220
  bindChatItems(h);
217
221
  h.querySelectorAll("[data-s]").forEach(
@@ -389,6 +393,18 @@ export async function openHome() {
389
393
  else { remember(null); draw(); }
390
394
  }
391
395
 
396
+ // Back from the popup (`kaizen chat`): the server brings this window back and hands
397
+ // over the chat the popup was on; Home opens it. A browser window coming back from a
398
+ // hidden Hyprland workspace fires no focus event, so Home asks every 1.5 s.
399
+ async function takeHandoff() {
400
+ const r = await fetch("/popup/handoff").then((r) => r.json()).catch(() => null);
401
+ if (!r?.id) return;
402
+ await refreshChats();
403
+ if (chats.some((c) => c.id === r.id)) await show(r.id);
404
+ }
405
+ // ponytail: polling; push it through the board's state stream if this ever costs anything.
406
+ if (typeof document !== "undefined") setInterval(() => globalThis.document?.body?.classList.contains("homev") && takeHandoff(), 1500);
407
+
392
408
  // A project picked above: a new chat's greeting names it. Only then: a redraw replays the greeting's entrance.
393
409
  let greeted;
394
410
  addEventListener("kz-state", () => {
@@ -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 });
package/web/board.html CHANGED
@@ -285,7 +285,7 @@ body.paged #board,body.paged .ftr,body.paged .scrim,body.paged #bq{display:none}
285
285
  /* The Icebox keeps the project bar with its own title, without New idea or the panel's header; Settings has none */
286
286
  body.paged:not(.ice) .hdr,body.ice aside.docked>header{display:none}body.ice #newtop{visibility:hidden}
287
287
  /* The Terminal page: the project bar stays (it picks whose terminals show), the board gives way to the tiles */
288
- #home{display:none}#hnewtop{display:none}body.homev.paged .hdr{display:flex}body.homev #combo,body.homev #showc,body.homev #bq,body.homev #newtop,body.homev #fbtn,body.homev #tmodes{display:none!important}body.homev #hnewtop{display:inline-flex;align-items:center;gap:6px}#hnewtop svg{width:16px;height:16px}
288
+ #home{display:none}#hnewtop,#hpop{display:none}body.homev.paged .hdr{display:flex}body.homev #combo,body.homev #showc,body.homev #bq,body.homev #newtop,body.homev #fbtn,body.homev #tmodes{display:none!important}body.homev #hnewtop{display:inline-flex;align-items:center;gap:6px}@media(min-width:641px){body.homev #hpop{display:inline-grid}}#hnewtop svg{width:16px;height:16px}
289
289
  body.homev #home{flex:1;min-height:0;display:flex;position:relative;animation:fi .2s}
290
290
  .hside{flex:none;width:260px;overflow:hidden;border-right:1px solid color-mix(in srgb,var(--line) 60%,transparent);transition:width .28s cubic-bezier(.2,.7,.2,1),opacity .2s,border-color .28s}
291
291
  #home:not(.hopen) .hside{width:0;opacity:0;border-color:transparent}
@@ -595,6 +595,7 @@ a.schip:hover{color:var(--ink);border-color:color-mix(in srgb,var(--line) 60%,va
595
595
  <symbol id="i-chev" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></symbol>
596
596
  <symbol id="i-ai" viewBox="0 0 24 24"><path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"/><path d="M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"/></symbol>
597
597
  <symbol id="i-google" viewBox="0 0 24 24"><path fill="currentColor" stroke="none" d="M12.48 10.92v3.28h7.84c-.24 1.84-.85 3.18-1.73 4.1-1.08 1.08-2.76 2.26-5.7 2.26-4.82 0-8.6-3.89-8.6-8.72s3.78-8.72 8.6-8.72c2.6 0 4.5 1.02 5.9 2.34l2.31-2.31C19.13 1.19 16.56 0 12.48 0 5.87 0 .31 5.39.31 12s5.56 12 12.17 12c3.57 0 6.26-1.17 8.37-3.36 2.16-2.16 2.84-5.21 2.84-7.66 0-.76-.05-1.47-.17-2.06z"/></symbol>
598
+ <symbol id="i-popout" viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-8 8M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></symbol>
598
599
  <symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
599
600
  <symbol id="i-send" viewBox="0 0 24 24"><path d="M12 19V5M6 11l6-6 6 6"/></symbol>
600
601
  <symbol id="i-home" viewBox="0 0 24 24"><path d="M4 11l8-7 8 7v8a1 1 0 0 1-1 1h-4v-6h-6v6H5a1 1 0 0 1-1-1z"/></symbol>
@@ -699,6 +700,7 @@ a.schip:hover{color:var(--ink);border-color:color-mix(in srgb,var(--line) 60%,va
699
700
  <span class="sp"></span>
700
701
  <span class="bar" id="tmodes" role="group" aria-label="Layout"></span>
701
702
  <button class="btn pri" id="newtop">New idea</button>
703
+ <button class="ib" id="hpop" title="Pop out chat" aria-label="Pop out chat"><svg><use href="#i-popout"/></svg></button>
702
704
  <button class="btn pri" id="hnewtop" aria-label="New chat"><svg><use href="#i-plus"/></svg>New chat</button>
703
705
  </div>
704
706
  <main id="board" aria-live="polite" aria-busy="true"><section aria-hidden="true"><span class="skel" style="height:14px;width:40%;margin:4px 0 12px"></span><span class="skel" style="height:72px;margin-bottom:8px"></span><span class="skel" style="height:72px"></span></section><section aria-hidden="true"><span class="skel" style="height:14px;width:40%;margin:4px 0 12px"></span><span class="skel" style="height:72px;margin-bottom:8px"></span><span class="skel" style="height:72px"></span></section><section aria-hidden="true"><span class="skel" style="height:14px;width:40%;margin:4px 0 12px"></span><span class="skel" style="height:72px;margin-bottom:8px"></span><span class="skel" style="height:72px"></span></section><section aria-hidden="true"><span class="skel" style="height:14px;width:40%;margin:4px 0 12px"></span><span class="skel" style="height:72px;margin-bottom:8px"></span><span class="skel" style="height:72px"></span></section><section aria-hidden="true"><span class="skel" style="height:14px;width:40%;margin:4px 0 12px"></span><span class="skel" style="height:72px;margin-bottom:8px"></span><span class="skel" style="height:72px"></span></section></main>