kaizen-agent 1.53.0 → 1.54.0

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,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,
@@ -25,6 +25,7 @@ import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId,
25
25
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
26
26
  // The board's script: web/board/*.ts, bundled into one file by `bun run build:web`.
27
27
  const BOARD_JS = join(dirname(import.meta.dir), "web", "board.js");
28
+ const SOUNDS_DIR = join(dirname(import.meta.dir), "web", "sounds");
28
29
  // The notebook: its page, and the CodeMirror bundle `bun run build:web` commits beside it.
29
30
  const NOTES_PAGE = join(dirname(import.meta.dir), "web", "notes.html");
30
31
  const ICO = join(dirname(import.meta.dir), "assets", "kaizen.ico");
@@ -222,6 +223,45 @@ export async function web(repoDir: string, opts: Opts = {}) {
222
223
  };
223
224
  // agent.launch: card runs what this board launches inside the board, shown on the card.
224
225
  const inCard = (dir: string) => ({ card: launchMode(projectOf(dir)) === "card", onChange: changed });
226
+
227
+ // Start a run's agent again after it ended mid-stage (crashed, closed, a stalled run, or
228
+ // the board restarting for an upgrade), in the conversation it had where the tool can
229
+ // resume one. A run waiting for a decision, or done, gets its conversation back with
230
+ // nothing sent to it -- the user talks to it -- and only when that conversation exists.
231
+ // Never beside a live in-card agent, never on an abandoned run.
232
+ const resumeRun = (dir: string, id: string) => {
233
+ let run: any;
234
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return { error: "no such run", status: 404 }; }
235
+ if (run.stage === "abandoned") return { error: "this run was abandoned", status: 409 };
236
+ 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 };
237
+ const quiet = run.stage === "done" || !!run.awaiting;
238
+ const own = quiet ? runAgent(dir, id) : null;
239
+ if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
240
+ const text = quiet ? "" : resumePrompt(id);
241
+ const before = Date.now();
242
+ const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
243
+ if (r.ok) closeSessions(dir, id, { before });
244
+ changed();
245
+ return r;
246
+ };
247
+
248
+ // Runs whose in-card agent was live when Settings' Update restarted the board: the
249
+ // agents end with the old board, so the new one starts them again (resumeRun). Each
250
+ // entry keeps its session key, so an idea whose run had not written state.json yet is
251
+ // matched to its run by the new board, once that run exists. The agents are ended here,
252
+ // not left to the board's exit, so none outlives it beside its resumed self.
253
+ const RESUME_LIST = join(home, ".kaizen", "resume-after-upgrade.json");
254
+ const saveLive = () => {
255
+ const live = new Set(ptyKeys().filter((k) => ptyState(k)?.alive));
256
+ if (!live.size) return;
257
+ const list: { dir: string; key: string; run: string | null }[] = [];
258
+ for (const d of states(true)) {
259
+ const idx = runIndex(d);
260
+ for (const s of readSessions(d)) if (live.has(s.key)) list.push({ dir: d, key: s.key, run: ownerOf(d, s, idx) });
261
+ }
262
+ try { writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), list })); } catch { /* nothing resumes; the card offers Resume */ }
263
+ for (const k of live) exitPty(k, 200);
264
+ };
225
265
  // An idea's session, until its run exists and owns it (ownerOf).
226
266
  const ideaPty = new Map<string, string>();
227
267
  // Backlog items this board launched whose run has not written its state.json yet:
@@ -360,6 +400,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
360
400
  function serve(port: number) { return Bun.serve({
361
401
  hostname: "127.0.0.1",
362
402
  port,
403
+ // Local only, so attachments may be large: Bun's 128 MB default would cut them.
404
+ maxRequestBodySize: 512 * 1024 * 1024,
363
405
  // Bun drops a request after 10s idle by default. A slow /state (git status in a
364
406
  // big repo, on Windows) then comes back as nothing, and the page shows an empty
365
407
  // board. Loopback only, so nothing waits on us but our own page.
@@ -404,6 +446,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
404
446
  return new Response(body, { headers: { "content-type": "application/javascript; charset=utf-8", "cache-control": "no-store" } });
405
447
  }
406
448
 
449
+ if (req.method === "GET" && path.startsWith("/sounds/")) {
450
+ const name = /^\/sounds\/([A-Za-z]+)\.mp3$/.exec(path)?.[1];
451
+ const file = name && join(SOUNDS_DIR, `${name}.mp3`);
452
+ if (!file || !existsSync(file)) return new Response("not found", { status: 404 });
453
+ return new Response(Bun.file(file), { headers: { "content-type": "audio/mpeg", "cache-control": "public, max-age=86400" } });
454
+ }
455
+
407
456
  if (req.method === "GET" && (path === "/notebook" || path === "/notebook.js")) {
408
457
  const [f, type] = path === "/notebook" ? [NOTES_PAGE, "text/html; charset=utf-8"] : [NOTES_JS, "application/javascript; charset=utf-8"];
409
458
  const body = served(f);
@@ -750,6 +799,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
750
799
  Bun.spawn([process.execPath, join(helper, "cli", "install.ts"), "upgrade", "--wait", String(process.pid), "--restart", String(srv.port)], {
751
800
  cwd: home, detached: true, stdio: ["ignore", log, log], windowsHide: true,
752
801
  }).unref();
802
+ saveLive();
753
803
  setTimeout(() => process.exit(0), 300);
754
804
  return json({ ok: true });
755
805
  }
@@ -761,6 +811,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
761
811
  if (code !== 0) return bad(why || `kaizen upgrade exited ${code}`, 500);
762
812
  if (installed() === VERSION) return bad(why || "Already up to date");
763
813
  const port = srv.port;
814
+ saveLive();
764
815
  setTimeout(() => {
765
816
  Bun.spawn([process.execPath, join(repoDir, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
766
817
  detached: true, stdio: ["ignore", "ignore", "ignore"], windowsHide: true,
@@ -880,11 +931,11 @@ export async function web(repoDir: string, opts: Opts = {}) {
880
931
  let body: any;
881
932
  let uploads: ChatUpload[] = [];
882
933
  if (path === "/chat" && req.headers.get("content-type")?.startsWith("multipart/form-data")) {
883
- if (Number(req.headers.get("content-length")) > 28 * 1024 * 1024) return bad("attachments too large", 413);
934
+ if (Number(req.headers.get("content-length")) > 320 * 1024 * 1024) return bad("attachments too large", 413);
884
935
  let form: FormData;
885
936
  try { form = await req.formData(); } catch { return bad("form data expected"); }
886
937
  const files = form.getAll("files");
887
- if (files.length > 5 || files.some((f) => !(f instanceof File) || f.size > 10 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 20 * 1024 * 1024) return bad("up to 5 files, 10 MB each and 20 MB total", 413);
938
+ if (files.length > 20 || files.some((f) => !(f instanceof File) || f.size > 100 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 300 * 1024 * 1024) return bad("up to 20 files, 100 MB each and 300 MB total", 413);
888
939
  body = { id: form.get("id"), text: form.get("text") ?? "", project: form.get("project") };
889
940
  uploads = await Promise.all(files.map(async (f) => ({ name: (f as File).name, bytes: new Uint8Array(await (f as File).arrayBuffer()) })));
890
941
  } else try { body = await req.json(); } catch { return bad("json body expected"); }
@@ -1172,7 +1223,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1172
1223
  // Files added with a hand-written icebox item: saved beside the state, linked in its notes.
1173
1224
  const iceFiles = (state: string, files: unknown) => {
1174
1225
  const fs: { name: string; data: string }[] = Array.isArray(files) ? files : [];
1175
- if (fs.reduce((t, f) => t + (f.data?.length ?? 0), 0) > 20_000_000) throw new Error("attachments over 15MB");
1226
+ if (fs.reduce((t, f) => t + (f.data?.length ?? 0), 0) > 400_000_000) throw new Error("attachments over 300MB");
1176
1227
  return fs.map((f) => {
1177
1228
  const rel = saveAttachment(state, null, String(f.name ?? "file"), Buffer.from(String(f.data).replace(/^data:[^,]*,/, ""), "base64"));
1178
1229
  return (/\.(png|jpe?g|gif|webp|svg)$/i.test(rel) ? "!" : "") + `[${String(f.name ?? "file")}](${rel})`;
@@ -1295,7 +1346,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1295
1346
  const files: { name: string; data: string }[] = Array.isArray(body.files) ? body.files : [];
1296
1347
  let total = 0;
1297
1348
  for (const f of files) total += (f.data?.length ?? 0);
1298
- if (total > 20_000_000) return bad("attachments over 15MB");
1349
+ if (total > 400_000_000) return bad("attachments over 300MB");
1299
1350
  const links = files.map((f) => {
1300
1351
  const bytes = Buffer.from(String(f.data).replace(/^data:[^,]*,/, ""), "base64");
1301
1352
  const rel = saveAttachment(dir, id, String(f.name ?? "file"), bytes).replace(/\\/g, "/");
@@ -1395,27 +1446,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1395
1446
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1396
1447
  }
1397
1448
 
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.
1449
+ // Start a run's agent again after it ended mid-stage (resumeRun).
1403
1450
  if (path === "/resume") {
1404
1451
  const id = String(body.id ?? "");
1405
1452
  if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1406
1453
  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();
1454
+ const r = resumeRun(dir, id);
1455
+ if ("error" in r) return bad(r.error, r.status);
1419
1456
  return json(r.ok
1420
1457
  ? { ok: true, agent: r.agent, pty: r.pty }
1421
1458
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
@@ -1443,6 +1480,24 @@ export async function web(repoDir: string, opts: Opts = {}) {
1443
1480
  },
1444
1481
  }); }
1445
1482
 
1483
+ // Read once and removed first, so a board that fails to start one does not retry it
1484
+ // forever. A list older than an hour is from an upgrade whose board never came back
1485
+ // (a failed Windows hand-off): too late to pick its runs up unasked.
1486
+ if (existsSync(RESUME_LIST)) {
1487
+ let saved: { at?: number; list?: { dir: string; key: string; run: string | null }[] } = {};
1488
+ try { saved = JSON.parse(readText(RESUME_LIST)); } catch { /* unreadable: nothing to resume */ }
1489
+ rmSync(RESUME_LIST, { force: true });
1490
+ const done = new Set<string>();
1491
+ for (const { dir, key, run } of Date.now() - (saved.at ?? 0) < 3600_000 ? saved.list ?? [] : []) {
1492
+ const s = run ? null : readSessions(dir).find((x) => x.key === key);
1493
+ const id = run ?? (s ? ownerOf(dir, s) : null);
1494
+ if (!id || done.has(`${dir}\0${id}`)) continue;
1495
+ done.add(`${dir}\0${id}`);
1496
+ const r = resumeRun(dir, id);
1497
+ console.log(` ${"error" in r || !r.ok ? "could not resume" : "resumed"} ${id}${"error" in r ? ` (${r.error})` : !r.ok ? ` (${r.why})` : ""}`);
1498
+ }
1499
+ }
1500
+
1446
1501
  const url = `http://127.0.0.1:${server.port}/`;
1447
1502
  console.log(`\n kaizen web ${url}`);
1448
1503
  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.54.0",
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": {
@@ -32,6 +32,9 @@ continue from the stage it names. Never advance a run whose `awaiting` field is
32
32
  non-null without a recorded human decision in `02-approval.md` — another tool or
33
33
  session may be mid-run.
34
34
 
35
+ Before non-trivial work, run `kaizen recall --track <track> --query "<topic>"` and
36
+ treat what it returns as past experience from other projects to verify, not as rules.
37
+
35
38
  Codex has no separate subagents, so run the stages sequentially in one session,
36
39
  but keep them clean: start each stage by reading only that stage's declared inputs
37
40
  from its stage file, and write its artifact before moving on. When reviewing, judge the
@@ -73,6 +73,12 @@ review:
73
73
  # prunes stale or superseded lessons before appending rather than growing the file.
74
74
  memory_max_lines: 100
75
75
 
76
+ knowledge:
77
+ # Lessons that hold beyond one project go to ~/.kaizen/knowledge/<track>.md through
78
+ # `kaizen remember`; planners and Claude Code sessions read them with `kaizen recall`.
79
+ # false: this project never writes there (recall still reads). For confidential work.
80
+ global: true
81
+
76
82
  backlog:
77
83
  # Capture work explicitly deferred, unresolved findings after the bounded fix loop,
78
84
  # and verification the user still needs to settle.
@@ -136,7 +136,9 @@ Controlled by `approvals.review`, skipped in `auto`.
136
136
  Report: what was built (for a code run, show its Preview proof), verification results, findings fixed, findings still open,
137
137
  every criterion the reviewer answered `CANNOT VERIFY` with the check it says a human
138
138
  must make, anything the builder noted as out of scope, and the notes the *Docs gate*
139
- touched. Where the run used `runner: lite` and reviewed inline (`review.executor: inline`), say
139
+ touched, and the `## Remembered` lines from `04-review.md` verbatim, so what the run
140
+ saved to memory and to global knowledge is visible without opening a file (deleting
141
+ or editing a line in `~/.kaizen/knowledge/` is the undo). Where the run used `runner: lite` and reviewed inline (`review.executor: inline`), say
140
142
  so in that report — the reviewer saw the work, and nobody should read a same-session
141
143
  review as an independent one because the output looked the same.
142
144
  Later build requests in the same session follow *Follow-ups are runs too* in [`spec.md`](spec.md): a revise of this run until it is `done`, then a new linked run.
@@ -10,7 +10,11 @@ planner's and the plan approval's contract. The builder and reviewer do not read
10
10
  the run directory when present — links, paths, and background the user attached from
11
11
  the board, binding like the request itself — `memory.md`, `notes/Project/Index.md` in the state
12
12
  directory when present — the project's map, written by `/kaizen docs`; open only the
13
- notes it lists for areas the request touches — and the existing material —
13
+ notes it lists for areas the request touches — the output of
14
+ `kaizen recall --track <track> --tags <stack tags> --query "<words from the request>"`
15
+ — past experience from other projects, to verify against this one, never binding
16
+ like project rules; the Framing ends with `Recalled: <n> lessons; used: <the lines it
17
+ relied on>` or `Recalled: none` — and the existing material —
14
18
  the codebase, the manuscript, the current campaign, whatever this run builds on.
15
19
  **Output:** `01-plan.md`.
16
20
 
@@ -135,6 +135,58 @@ them. Keep it under `review.memory_max_lines` (default 100): before appending, d
135
135
  any lesson that is now wrong, already enforced by a test or a lint rule, or restated
136
136
  by a newer entry. A memory file that only grows stops being read carefully.
137
137
 
138
+ **Global knowledge.** Some lessons hold beyond this project — still true in another
139
+ repository on the same stack, or another piece of work on the same track. For each
140
+ lesson, decide its scope. Project lessons go to `memory.md` as above.
141
+
142
+ Global knowledge is read by every future project, so it stays high-signal, not a
143
+ history of what was built. A lesson goes global only when all four hold:
144
+
145
+ 1. **Reusable** — still true in another repository on the same stack or track.
146
+ 2. **High-signal** — knowing it would change what someone does: a discovery that cost
147
+ real investigation, a measured improvement, an architectural trade-off and when it
148
+ tips, or a fix that saves the next person the same search. Documented behaviour
149
+ counts when it was the answer to a real problem here; rare is not the test, useful is.
150
+ 3. **Evidenced** — it comes from something this run actually hit: a finding, a failing
151
+ test, an error, a measurement. Name it in `--applies` (`seen: finding 3`). An opinion
152
+ with nothing behind it in this run is not a lesson.
153
+ 4. **New** — run `kaizen recall --tags <tags> --query "<key words>"` first. If a line
154
+ already says it, skip yours, or `--replace` that line only when this run adds a
155
+ correction, a version limit or stronger evidence.
156
+
157
+ Skip: framework basics a competent developer already knows, routine implementation,
158
+ trivial and typo fixes, this project's own conventions (those are `memory.md`), and
159
+ anything recall already returned. Zero global lessons is the normal outcome. More
160
+ than two from one run is a reason to re-check each against the four tests, not to
161
+ drop them.
162
+
163
+ Global lessons go through `kaizen remember`, never by editing `~/.kaizen/knowledge/`
164
+ directly:
165
+
166
+ ```
167
+ kaizen remember --track <code|writing|communication|operations|research> \
168
+ --tags <tag,tag@version> --applies "<versions, platform, limits>" --run <run id> "<lesson>"
169
+ ```
170
+
171
+ - Generalize before saving. Keep commands, flags, versions, error strings and public
172
+ documentation URLs: they are the lesson. Replace paths, hosts, client and person
173
+ names, internal URLs and business figures with `<project>`, `<host>` and the like.
174
+ - Phrase it as a fact about behaviour ("X causes Y"), never as an order to an agent.
175
+ - `--applies` is required: where the lesson holds and where it does not, so it never
176
+ reads as a universal rule. Versions and frameworks also go in the tags (`bun@1.2`),
177
+ which keeps lessons for different versions apart.
178
+ - `remember` appends and prints any existing lines that share a tag, numbered. If one
179
+ says the same thing, rewrite it with `--replace <n>` or drop yours; nothing is merged
180
+ without that explicit choice.
181
+ - Never write the `preferences` track: the user keeps it by hand.
182
+ - A refusal is final for that wording: the secret check rejects keys, tokens, emails,
183
+ IP addresses and private hosts; `knowledge.global: false` means the project opted out.
184
+
185
+ Record every attempt, project and global, in a `## Remembered` section of
186
+ `04-review.md`, one line each: `Remembered (project): …`, `Remembered (global): …` as
187
+ `remember` printed it, or `Rejected: <reason> — <lesson>`. Write `None` when nothing
188
+ was worth keeping; most runs teach nothing durable, and that is fine.
189
+
138
190
  ---
139
191
 
140
192
  ## Stage 4 — Fix loop
@@ -38,6 +38,8 @@ anything.
38
38
  | `/kaizen config` | Show this project's settings and change them, one picker per setting |
39
39
  | `/kaizen init` | Set up this project folder: `.kaizen/` with `spec.md`, config, and — in a git repo — the gitignore entry |
40
40
  | `/kaizen install` | Install the workflow itself globally or per-project |
41
+ | `kaizen recall [--track t] [--tags a,b] [--query "<words>"]` | Lessons from other projects that match (global knowledge, `~/.kaizen/knowledge/`) |
42
+ | `kaizen remember --track t --tags a,b --applies "<where>" --run <id> "<lesson>"` | Save a lesson that holds beyond this project; the reviewer calls it |
41
43
 
42
44
  `/kaizen` with no argument: `status` if a run is in progress, else ask what to build.
43
45
 
@@ -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 audio browser " + SOUNDS.join(" "), !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, "-"));
@@ -0,0 +1,77 @@
1
+ import { test, expect } from "bun:test";
2
+ import { existsSync } from "node:fs";
3
+ import { join, dirname } from "node:path";
4
+
5
+ test("new notification sounds play real files while saved choices stay intact", async () => {
6
+ const oldListener = globalThis.addEventListener;
7
+ const oldStorage = globalThis.localStorage;
8
+ const oldAudio = globalThis.Audio;
9
+ const oldContext = globalThis.AudioContext;
10
+ const values = new Map<string, string>();
11
+ const played: string[] = [];
12
+ const tones: number[] = [];
13
+ (globalThis as any).addEventListener = () => {};
14
+ (globalThis as any).localStorage = { getItem: (key: string) => values.get(key) ?? null };
15
+ (globalThis as any).Audio = class {
16
+ constructor(readonly src: string) {}
17
+ play() {
18
+ played.push(this.src);
19
+ return Promise.resolve();
20
+ }
21
+ };
22
+ (globalThis as any).AudioContext = class {
23
+ currentTime = 0;
24
+ destination = {};
25
+ resume() {
26
+ return Promise.resolve();
27
+ }
28
+ createOscillator() {
29
+ return {
30
+ type: "",
31
+ frequency: { value: 0 },
32
+ connect(g: unknown) {
33
+ return g;
34
+ },
35
+ start() {
36
+ tones.push(1);
37
+ },
38
+ stop() {},
39
+ };
40
+ }
41
+ createGain() {
42
+ return {
43
+ gain: { setValueAtTime() {}, exponentialRampToValueAtTime() {} },
44
+ connect() {
45
+ return this;
46
+ },
47
+ };
48
+ }
49
+ };
50
+ try {
51
+ const { SOUNDS, soundPick, playSound, notifyUser } = await import("./toast.ts");
52
+ const samples = SOUNDS.filter((s) => !["off", "chime", "bell", "pop"].includes(s));
53
+ expect(samples).toHaveLength(10);
54
+ expect(soundPick()).toBe("Bellatrix");
55
+ notifyUser("done");
56
+ expect(played).toEqual(["/sounds/Bellatrix.mp3"]);
57
+ for (const name of samples) {
58
+ expect(existsSync(join(dirname(import.meta.dir), "sounds", `${name}.mp3`))).toBe(true);
59
+ playSound(name);
60
+ }
61
+ expect(played.slice(1)).toEqual(samples.map((name) => `/sounds/${name}.mp3`));
62
+ values.set("kz-sound", "off");
63
+ notifyUser("quiet");
64
+ expect(played).toHaveLength(11);
65
+ for (const name of ["chime", "bell", "pop"]) {
66
+ values.set("kz-sound", name);
67
+ expect(soundPick()).toBe(name);
68
+ notifyUser("legacy");
69
+ }
70
+ expect(tones).toHaveLength(4);
71
+ } finally {
72
+ globalThis.addEventListener = oldListener;
73
+ globalThis.localStorage = oldStorage;
74
+ globalThis.Audio = oldAudio;
75
+ globalThis.AudioContext = oldContext;
76
+ }
77
+ });