kaizen-agent 1.61.0 → 1.61.2

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/board.test.ts CHANGED
@@ -60,19 +60,26 @@ test("Settings rechecks an existing update alert and clears or refreshes it", as
60
60
  const previousFetch = globalThis.fetch;
61
61
  const elements = new Map<string, any>();
62
62
  const body = { row: null as any, prepend(row: any) { this.row = row; row.isConnected = true; } };
63
+ let card: any = null;
63
64
  (globalThis as any).location = { search: "" };
64
65
  (globalThis as any).document = {
65
66
  querySelector: () => link,
66
- getElementById: (id: string) => id === "pbody" ? body : elements.get(id),
67
+ getElementById: (id: string) => id === "pbody" ? body : id === "updcard" ? card : elements.get(id),
68
+ body: { append(el: any) { card = el; } },
67
69
  createElement: () => ({
68
70
  isConnected: false,
71
+ firstElementChild: { innerHTML: "" },
72
+ setAttribute() {},
69
73
  set innerHTML(v: unknown) {
70
74
  const html = String(v);
71
75
  this.html = html;
72
76
  elements.clear();
73
77
  for (const [, id] of html.matchAll(/id="([^"]+)"/g)) elements.set(id, { textContent: "", disabled: false, focus() {} });
74
78
  },
75
- remove() { this.isConnected = false; },
79
+ remove() {
80
+ this.isConnected = false;
81
+ if (card === this) card = null;
82
+ },
76
83
  }),
77
84
  };
78
85
  try {
@@ -96,6 +103,14 @@ test("Settings rechecks an existing update alert and clears or refreshes it", as
96
103
  await elements.get("upd-chk").onclick();
97
104
  expect(classes.has("upd")).toBe(true);
98
105
  expect(body.row.html).toContain("1.40.0");
106
+ // The popup follows the same checks: a newer release rewrites it, none left closes it.
107
+ expect(card.html).toContain("1.40.0");
108
+ globalThis.fetch = (async () => ({ json: async () => ({ version: "1.39.0", latest: "1.41.0", update: true }) })) as any;
109
+ await elements.get("upd-chk").onclick();
110
+ expect(String(card.firstElementChild.innerHTML)).toContain("1.41.0");
111
+ globalThis.fetch = (async () => ({ json: async () => ({ version: "1.41.0", latest: "1.41.0", update: false }) })) as any;
112
+ await elements.get("upd-chk").onclick();
113
+ expect(card).toBe(null);
99
114
  } finally {
100
115
  globalThis.document = previous;
101
116
  globalThis.location = previousLocation;
package/cli/pty.ts CHANGED
@@ -284,7 +284,7 @@ export const ptyKeys = () => [...ptys.keys()];
284
284
 
285
285
  export const ptyState = (key: string) => {
286
286
  const p = ptys.get(key);
287
- return p ? { alive: p.exit === null, exit: p.exit, asking: p.asking, busy: p.busy, total: p.total, last: p.last, at: p.lastAt, born: p.born } : null;
287
+ return p ? { pid: p.proc.pid, alive: p.exit === null, exit: p.exit, asking: p.asking, busy: p.busy, total: p.total, last: p.last, at: p.lastAt, born: p.born } : null;
288
288
  };
289
289
 
290
290
  // The environment the user's login shell builds: PATH and anything exported in their
@@ -0,0 +1,75 @@
1
+ // The slow, file-and-git half of GET /state, run on a Worker. The board's main thread also
2
+ // relays every terminal's bytes, so a rebuild there (about 250ms across all projects) froze
3
+ // typing in each open agent. Anything that needs the live sessions stays in web.ts.
4
+ import { join } from "node:path";
5
+ import { backlogCards, boardCards, cardsGit, healRuns, home, reviewFindings, type Card } from "./state.ts";
6
+
7
+ export type Snap = {
8
+ cards: Card[];
9
+ // By card index: what the panel's commit, push and Fix findings forms offer.
10
+ extra: { git?: string; gitDue?: "commit" | "push"; open?: number }[];
11
+ backlog: ReturnType<typeof backlogCards>;
12
+ };
13
+ type GitMark = { at: number; ids: string; marks: Record<string, string>; dues: Record<string, "commit" | "push"> };
14
+
15
+ const GIT_MS = 5000;
16
+ const gitCache = new Map<string, GitMark>();
17
+ let gitSeen = 0;
18
+
19
+ // gitGen moves whenever the page changed something, so a commit shows at once, not after GIT_MS.
20
+ export function snapshot(dirs: string[], gitGen: number): Snap {
21
+ if (gitGen !== gitSeen) { gitCache.clear(); gitSeen = gitGen; }
22
+ for (const d of dirs) healRuns(d);
23
+ const cards = boardCards(dirs, Date.now());
24
+ const outside = (c: Card) => c.state !== join(home, ".kaizen");
25
+ // The git mark, for the cards whose panel offers commit and push: one status per project.
26
+ const markable = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "approvals.review") && outside(c);
27
+ for (const d of new Set(cards.filter(markable).map((c) => c.state))) {
28
+ const ids = cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!), idKey = ids.join("\n"), had = gitCache.get(d);
29
+ if (had?.ids === idKey && Date.now() - had.at < GIT_MS) continue;
30
+ const dues: Record<string, "commit" | "push"> = {}, marks = cardsGit(d, ids, dues);
31
+ gitCache.set(d, { at: Date.now(), ids: idKey, marks, dues });
32
+ }
33
+ // Open findings the panel's Fix findings form would offer, on the same runs.
34
+ const openFindings = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "findings" || c.awaiting === "approvals.review") && outside(c)
35
+ ? reviewFindings(c.state, c.id!).filter((f) => !f.done).length || undefined : undefined;
36
+ const extra = cards.map((c) => {
37
+ const g = markable(c) ? gitCache.get(c.state) : undefined;
38
+ return { git: g?.marks[c.id!], gitDue: g?.dues[c.id!], open: openFindings(c) };
39
+ });
40
+ return { cards, extra, backlog: backlogCards(dirs) };
41
+ }
42
+
43
+ // Replies carry the request's id. A worker that dies fails what is waiting, and the caller
44
+ // builds the snapshot itself: a slow board beats an empty one.
45
+ export function snapWorker() {
46
+ let worker: Worker | null = null, next = 0;
47
+ const waiting = new Map<number, { ok: (s: Snap) => void; no: (e: unknown) => void }>();
48
+ const fail = (e: unknown) => {
49
+ worker?.terminate();
50
+ worker = null;
51
+ for (const w of waiting.values()) w.no(e);
52
+ waiting.clear();
53
+ };
54
+ return (dirs: string[], gitGen: number) => new Promise<Snap>((ok, no) => {
55
+ if (!worker) {
56
+ worker = new Worker(new URL("./state-snap.ts", import.meta.url).href);
57
+ worker.unref(); // a board or test ending does not wait on it
58
+ worker.onmessage = (e) => {
59
+ const w = waiting.get(e.data.id);
60
+ waiting.delete(e.data.id);
61
+ if (e.data.snap) w?.ok(e.data.snap); else w?.no(new Error(e.data.error));
62
+ };
63
+ worker.onerror = (e) => fail(e);
64
+ }
65
+ waiting.set(++next, { ok, no });
66
+ worker.postMessage({ id: next, dirs, gitGen });
67
+ });
68
+ }
69
+
70
+ declare const self: Worker;
71
+ if (!Bun.isMainThread) self.onmessage = (e: MessageEvent) => {
72
+ const { id, dirs, gitGen } = e.data;
73
+ try { self.postMessage({ id, snap: snapshot(dirs, gitGen) }); }
74
+ catch (err) { self.postMessage({ id, error: String(err) }); }
75
+ };
@@ -1,5 +1,5 @@
1
1
  import { expect, test } from "bun:test";
2
- import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
 
@@ -35,6 +35,18 @@ test.skipIf(process.platform === "win32")("board /decide reuses the run's open a
35
35
  for (let i = 0; i < 30 && !typed.includes("2026-10-30-r"); i++) { await Bun.sleep(100); try { typed = readFileSync(join(home, "typed"), "utf8"); } catch { /* not yet */ } }
36
36
  expect(typed).toContain("2026-10-30-r");
37
37
  expect(readFileSync(join(d, "terminals.json"), "utf8").split(first.pty).length).toBeGreaterThan(1);
38
+ // A plain tab has no session record: the run's Claude session finds it, a wrong one does not.
39
+ const sessions = join(st, "sessions"), pid = readFileSync(join(sessions, `${first.pty}.pid`), "utf8").trim();
40
+ rmSync(join(sessions, `${first.pty}.json`));
41
+ mkdirSync(join(home, ".claude", "sessions"), { recursive: true });
42
+ writeFileSync(join(home, ".claude", "sessions", `${pid}.json`), JSON.stringify({ pid: Number(pid), sessionId: "sess-plain-tab" }));
43
+ const session = (s: string) => writeFileSync(join(d, "state.json"), JSON.stringify({ id: "2026-10-30-r", agent: "claude", stage: "plan", awaiting: "approvals.plan", session: s }));
44
+ session("sess-plain-tab");
45
+ expect(await decide("approvals.plan")).toMatchObject({ ok: true, pty: first.pty, reused: true });
46
+ session("sess-another-one");
47
+ const fresh = await decide("approvals.plan");
48
+ expect(fresh.reused).toBeUndefined();
49
+ expect(fresh.pty).not.toBe(first.pty);
38
50
  } finally {
39
51
  p.kill();
40
52
  }
package/cli/web.ts CHANGED
@@ -3,13 +3,14 @@
3
3
  import { existsSync, readdirSync, statSync, lstatSync, realpathSync, readFileSync, 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
- home, type Item, type Card, boardCards, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
6
+ home, type Item, type Card, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
7
7
  readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
8
- appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, commitStaged, stageFiles, suggestMessage, notice, notifier, LOGO,
9
- reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
8
+ appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, readCommit, commitPush, commitStaged, stageFiles, suggestMessage, notice, notifier, LOGO,
9
+ reviewFindings, pickFindings, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
10
10
  launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
11
11
  } from "./state.ts";
12
12
  import { attachPty, writePty, submitPty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
13
+ import { snapshot, snapWorker } from "./state-snap.ts";
13
14
  import { claudeUsage, codexUsage, phonePeers, type Usage } from "./usage.ts";
14
15
  import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
15
16
  import { projectLogo, LOGO_TYPES } from "./logo.ts";
@@ -260,8 +261,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
260
261
  // nothing watches the working trees anyway. Any write request drops both.
261
262
  let stateGen = 0;
262
263
  const stateCache = new Map<string, { gen: string; at: number; body: string }>();
263
- const gitCache = new Map<string, { at: number; ids: string; marks: Record<string, string>; dues: Record<string, "commit" | "push"> }>();
264
- const STATE_MS = 1000, GIT_MS = 5000;
264
+ const buildSnap = snapWorker();
265
+ let gitGen = 0;
266
+ const STATE_MS = 1000;
265
267
  const changed = () => {
266
268
  stateGen++;
267
269
  if (pending) return;
@@ -277,7 +279,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
277
279
  // working. Everything sent to a run goes here before any new agent is started.
278
280
  const liveAgent = (dir: string, id: string) => {
279
281
  const idx = runIndex(dir);
280
- return readSessions(dir).filter((s) => ptyState(s.key)?.alive && ownerOf(dir, s, idx) === id).sort((a, b) => a.started - b.started).pop();
282
+ const own = readSessions(dir).filter((s) => ptyState(s.key)?.alive && ownerOf(dir, s, idx) === id).sort((a, b) => a.started - b.started).pop();
283
+ if (own) return own;
284
+ // A run started by typing /kaizen in a plain tab has no record, only its Claude session.
285
+ let run: any;
286
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return undefined; }
287
+ const key = run.agent && run.agent !== "claude" ? null : sessionPty(String(run.session ?? ""));
288
+ return key ? { key, cmd: "claude" } : undefined;
281
289
  };
282
290
 
283
291
  // Start a run's agent again after it ended mid-stage (crashed, closed, a stalled run, or
@@ -542,7 +550,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
542
550
  // arrives with that hostname in Host, and gets nothing.
543
551
  const hostname = (req.headers.get("host") ?? "").toLowerCase().replace(/:\d+$/, "");
544
552
  if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
545
- if (req.method !== "GET") { stateGen++; gitCache.clear(); }
553
+ if (req.method !== "GET") { stateGen++; gitGen++; }
546
554
  const url = new URL(req.url);
547
555
  const path = url.pathname;
548
556
  const qdir = () => { const v = url.searchParams.get("dir"); return v == null ? v : canonState(v); };
@@ -1041,21 +1049,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
1041
1049
  const gen = `${stateGen} ${ptyKeys().map((k) => { const s = ptyState(k)!; return `${k}:${s.alive}:${s.asking}:${s.busy}:${s.at}`; }).join()}`;
1042
1050
  const cacheKey = `${all}\0${state}\0${loopback}`, hit = stateCache.get(cacheKey);
1043
1051
  if (hit?.gen === gen && Date.now() - hit.at < STATE_MS) return new Response(hit.body, { headers: { "content-type": "application/json" } });
1044
- for (const d of dirs) healRuns(d);
1045
- const cards = boardCards(dirs, Date.now()), pty = ptyOf(cards);
1046
- // The git mark, for the cards whose panel offers commit and push: one status per project.
1047
- const marks = new Map<string, Record<string, string>>(), dues = new Map<string, Record<string, "commit" | "push">>();
1048
- const markable = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen");
1049
- for (const d of new Set(cards.filter(markable).map((c) => c.state))) {
1050
- const ids = cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!), idKey = ids.join("\n"), had = gitCache.get(d);
1051
- if (had?.ids === idKey && Date.now() - had.at < GIT_MS) { marks.set(d, had.marks); dues.set(d, had.dues); continue; }
1052
- const due: Record<string, "commit" | "push"> = {}, mark = cardsGit(d, ids, due);
1053
- marks.set(d, mark); dues.set(d, due);
1054
- gitCache.set(d, { at: Date.now(), ids: idKey, marks: mark, dues: due });
1055
- }
1056
- // Open findings the panel's Fix findings form would offer, on the same runs.
1057
- const openFindings = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "findings" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen")
1058
- ? reviewFindings(c.state, c.id!).filter((f) => !f.done).length || undefined : undefined;
1052
+ // Off this thread: it also relays every terminal, and a rebuild here froze their typing.
1053
+ const { cards, extra, backlog } = await buildSnap(dirs, gitGen).catch(() => snapshot(dirs, gitGen));
1054
+ const pty = ptyOf(cards);
1059
1055
  // The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
1060
1056
  // shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
1061
1057
  const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
@@ -1080,8 +1076,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1080
1076
  rail: [...new Set(cards.map((c) => c.state))].filter((d) => !picker.includes(d)).map(entry),
1081
1077
  fresh: unset.map((d) => ({ dir: join(d, ".kaizen"), label: tilde(d) })),
1082
1078
  agents,
1083
- cards: cards.map((c, i) => ({ ...c, notice: notice(c), git: markable(c) ? marks.get(c.state)?.[c.id!] : undefined, gitDue: markable(c) ? dues.get(c.state)?.[c.id!] : undefined, open: openFindings(c), pty: ptys[i] })),
1084
- backlog: backlogCards(dirs).map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1079
+ cards: cards.map((c, i) => ({ ...c, notice: notice(c), ...extra[i], pty: ptys[i] })),
1080
+ backlog: backlog.map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1085
1081
  now: Date.now(),
1086
1082
  });
1087
1083
  stateCache.set(cacheKey, { gen, at: Date.now(), body });
@@ -2042,6 +2038,32 @@ export async function web(repoDir: string, opts: Opts = {}) {
2042
2038
  // which is as close to a desktop app as a web page gets. Anything else gets a tab.
2043
2039
  // A profile folder gives the window a browser instance of its own (Kaizen Bot's app);
2044
2040
  // on macOS that takes -n, as `open` otherwise hands the args to a running browser.
2041
+ // The live pty running a Claude Code session: Claude keeps ~/.claude/sessions/<pid>.json
2042
+ // (an internal file, so anything unexpected just means no match), and the pid or one of
2043
+ // its parents is the pty's. procStart tells a reused pid from the session's. Linux only.
2044
+ export function sessionPty(id: string): string | null {
2045
+ if (!/^[\w-]{8,80}$/.test(id)) return null;
2046
+ const root = join(home, ".claude", "sessions");
2047
+ const started = (pid: number) => readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19];
2048
+ try {
2049
+ for (const f of readdirSync(root)) {
2050
+ if (!/^\d+\.json$/.test(f)) continue;
2051
+ try {
2052
+ const rec = JSON.parse(readFileSync(join(root, f), "utf8"));
2053
+ if (rec.sessionId !== id) continue;
2054
+ let pid = Number(rec.pid);
2055
+ if (rec.procStart && String(rec.procStart) !== started(pid)) continue;
2056
+ for (let i = 0; i < 32 && pid > 1; i++) {
2057
+ const key = ptyKeys().find((k) => ptyState(k)?.alive && ptyState(k)?.pid === pid);
2058
+ if (key) return key;
2059
+ pid = Number(/^PPid:\s*(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, "utf8"))?.[1]);
2060
+ }
2061
+ } catch { /* gone or unreadable */ }
2062
+ }
2063
+ } catch { /* no such folder, or no /proc */ }
2064
+ return null;
2065
+ }
2066
+
2045
2067
  // Whether a Claude Code session is running somewhere: a process whose command line names
2046
2068
  // it (Linux /proc), or its transcript written in the last 90 s (every platform).
2047
2069
  export function sessionLive(id: string): boolean {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.61.0",
3
+ "version": "1.61.2",
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": {
@@ -336,7 +336,7 @@ export async function openSources() {
336
336
  )}`,
337
337
  )
338
338
  : ""}`;
339
- const bar = html`<div class="ice-bar">${order.length ? html`<input type="checkbox" id="ice-all" aria-label="Select every request shown"${nSel && nSel === order.length ? " checked" : ""}>` : ""}<span class="count">${iceCat === "Dismissed" || iceCat === "Done" ? `${order.length} ${iceCat.toLowerCase()}` : `${order.length < waiting ? `${order.length} of ${waiting}` : waiting} waiting`}</span><span class="end"></span>${String(chips) ? html`<details class="ice-filt"><summary class="ib${iceCat || iceSrc ? " on" : ""}" aria-label="Filter requests" title="Filter requests">${ico("filter")}</summary><div class="ice-fpop">${chips}</div></details>` : ""}${order.some((i) => isWaiting(ice[i])) ? html`<button class="btn ghost sm" id="ice-sw" title="Sort one at a time: swipe right to promote, left to dismiss"><span aria-hidden="true">⇆</span> Swipe</button>` : ""}<button class="btn ghost sm" id="ice-new" title="Add a request by hand">${ico("plus")} Add</button><button class="btn sm" id="src-go"${list.length ? "" : " disabled"}>${ico("refresh")} Gather all</button><button class="btn ghost sm" id="src-tog" aria-expanded="${String(!!srcShow)}" aria-controls="src-sec">${ico("link")} Sources · ${list.length}</button></div>`;
339
+ const bar = html`<div class="tk-bar ice-bar">${order.length ? html`<input type="checkbox" id="ice-all" aria-label="Select every request shown"${nSel && nSel === order.length ? " checked" : ""}>` : ""}<span class="count">${iceCat === "Dismissed" || iceCat === "Done" ? `${order.length} ${iceCat.toLowerCase()}` : `${order.length < waiting ? `${order.length} of ${waiting}` : waiting} waiting`}</span><span class="end"></span>${String(chips) ? html`<details class="ice-filt"><summary class="ib${iceCat || iceSrc ? " on" : ""}" aria-label="Filter requests" title="Filter requests">${ico("filter")}</summary><div class="ice-fpop">${chips}</div></details>` : ""}${order.some((i) => isWaiting(ice[i])) ? html`<button class="btn ghost sm" id="ice-sw" title="Sort one at a time: swipe right to promote, left to dismiss"><span aria-hidden="true">⇆</span> Swipe</button>` : ""}<button class="btn ghost sm" id="ice-new" title="Add a request by hand">${ico("plus")} Add</button><button class="btn sm" id="src-go"${list.length ? "" : " disabled"}>${ico("refresh")} Gather all</button><button class="btn ghost sm" id="src-tog" aria-expanded="${String(!!srcShow)}" aria-controls="src-sec">${ico("link")} Sources · ${list.length}</button></div>`;
340
340
  const bulk = iceSel.size
341
341
  ? html`<div class="ice-bulk" role="toolbar" aria-label="Selected requests"><span>${iceSel.size} selected</span><span class="end"></span><button class="btn sm" id="ice-bp" title="Promote (p)">${ico("plus")} Promote</button><button class="btn ghost sm" id="ice-bd" title="Dismiss (d)">${ico("x")} Dismiss</button><button class="btn ghost sm" id="ice-bc" title="Clear selection (Esc)">Clear</button></div>`
342
342
  : "";
@@ -375,7 +375,7 @@ export async function openSources() {
375
375
  waiting && !order.length
376
376
  ? html`<div class="ice-zero"><h4>No matches</h4><p style="margin-top:10px"><button class="btn sm" id="ice-unf">Clear filters</button></p></div>`
377
377
  : order.length
378
- ? html`<div class="ice-list">${[...groups].map(([g, ix]) => html`<div class="ice-cat">${g}<i>${ix.length}</i></div>${ix.map(row)}`)}</div>`
378
+ ? html`<div class="tk-list ice-list">${[...groups].map(([g, ix]) => html`<div class="ice-cat">${g}<i>${ix.length}</i></div>${ix.map(row)}`)}</div>`
379
379
  : html`<div class="ice-zero"><h4>Nothing waiting</h4><p>Requests gathered from your sources wait here until you turn them into ideas.</p>${list.length ? "" : html`<p style="margin-top:10px"><button class="btn sm pri" id="ice-addsrc">${ico("plus")} Add a source</button></p>`}</div>`;
380
380
  // Swipe: the waiting requests the filters show, least skipped first; a restored one
381
381
  // comes back on top. Nothing is written by a skip.
@@ -15,6 +15,7 @@ import { cardHref, drawSources, logo, railData, srcIcon, stateOf, titleOf } from
15
15
 
16
16
  const WORDS = { idle: "Idea", plan: "Planning", build: "Building", review: "Reviewing", wait: "Waiting on you", done: "Done", aband: "Abandoned", stalled: "Stalled" };
17
17
  const PLAT = { x: "X", tiktok: "TikTok", instagram: "Instagram", threads: "Threads" };
18
+ const SEARCH = raw('<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>');
18
19
  const AGENTS = ["claude", "codex", "agy", "opencode", "gemini", "cursor"];
19
20
  // sort: on Open, ideas first or running first (kept per browser).
20
21
  const f = { src: "all", proj: "", show: "open", q: "", sort: (() => { try { return localStorage.getItem("kz-ideas-sort") || "runs"; } catch { return "runs"; } })() };
@@ -41,9 +42,28 @@ function sourcesOf(cards, d) {
41
42
  // Keyboard: the row picked with the arrow keys (from the search box or the page), Enter acts on it.
42
43
  let sel = 0;
43
44
  let shownRows: any[] = [];
45
+ // Orca's Tasks shape: a toolbar over a list. The search box, the page's filters and New idea
46
+ // live in the shared header elsewhere, so they move in here and go back on leaving.
47
+ let docked: [Comment, HTMLElement][] = [];
48
+ function dock() {
49
+ if (!$("tk-bar")) $("ideasv").innerHTML = String(html`<div class="tk-bar" id="tk-bar"><div class="tk-row" id="tk-chips"></div><div class="tk-row"><label class="tk-q" id="tk-q">${SEARCH}</label><span id="tk-tools"></span></div></div><div class="tk-list" id="tk-list"></div>`);
50
+ if (docked.length) return;
51
+ for (const [id, to] of [["bq", "tk-q"], ["hx", "tk-tools"], ["newtop", "tk-tools"]]) {
52
+ const el = $(id),
53
+ mark = new Comment();
54
+ el.before(mark);
55
+ docked.push([mark, el]);
56
+ $(to).append(el);
57
+ }
58
+ }
59
+ function undock() {
60
+ docked.forEach(([mark, el]) => mark.replaceWith(el));
61
+ docked = [];
62
+ }
44
63
  function draw() {
45
64
  const box = $("ideasv");
46
65
  if (!document.body.classList.contains("ideav")) return;
66
+ dock();
47
67
  const { cards: all, projects, srcs } = railData();
48
68
  const cards = all.filter((c) => !c.archived);
49
69
  const src = sourcesOf(cards, srcs);
@@ -67,7 +87,7 @@ function draw() {
67
87
  // On Open, ideas above runs or runs above ideas, as chosen; newest first within each.
68
88
  .sort((a, b) => (f.show === "open" ? (a.kind === b.kind ? 0 : (a.kind === "idea") === (f.sort === "ideas") ? -1 : 1) : 0) || (b.moved ?? b.added ?? 0) - (a.moved ?? a.added ?? 0));
69
89
  const now = Date.now();
70
- const seg = (v, l) => html`<button class="pill${f.show === v ? " on" : ""}" data-show="${v}">${l}</button>`;
90
+ const seg = (v, l) => html`<button class="tk-chip${f.show === v ? " on" : ""}" data-show="${v}">${l}</button>`;
71
91
  const srcName = (u) => (u === "all" ? "All sources" : u === "" ? "Manual" : known.get(u) ? srcLabel(known.get(u)) : srcLabel({ url: u }));
72
92
  const srcMark = (u) => (u === "all" ? raw('<svg><use href="#r-bulb"/></svg>') : u === "" ? ico("pen") : srcIcon(known.get(u) ?? { url: u }));
73
93
  const srcList = ["all", ...present.filter(Boolean), ...(present.includes("") ? [""] : [])];
@@ -89,17 +109,19 @@ function draw() {
89
109
  )
90
110
  : "";
91
111
  // Scope and filters first; search, refresh and New idea sit at the right (CSS order).
92
- const extra = html`${sources}<span class="iseg">${seg("open", "Open")}${seg("running", "Running")}${seg("done", "Done")}</span>${sortPop}<button class="ib" id="ideas-ref" title="Refresh" aria-label="Refresh">${ico("refresh")}</button>`;
93
- const table = html`<table class="itable"><thead><tr><th></th><th>Title / context</th><th>Status</th><th>Updated</th><th></th></tr></thead><tbody>${rows.map((c, i) => {
112
+ const chips = html`${seg("open", "Open")}${seg("running", "Running")}${seg("done", "Done")}`;
113
+ const extra = html`${sources}${sortPop}<button class="ib" id="ideas-ref" title="Refresh" aria-label="Refresh">${ico("refresh")}</button>`;
114
+ const table = !rows.length ? html`<div class="tk-empty">${raw('<svg><use href="#r-bulb"/></svg>')}<p>Nothing matches.</p><span>Try a different search or filter.</span></div>` : html`<table class="itable"><thead><tr><th></th><th>Title / context</th><th>Status</th><th>Updated</th><th></th></tr></thead><tbody>${rows.map((c, i) => {
94
115
  const name = nameOf(c.state, projects),
95
116
  st = stateOf(c),
96
117
  agent = (c.tags ?? []).find((t) => AGENTS.includes(t));
97
118
  return html`<tr><td>${logo(c.state, name, projects)}</td><td><b>${titleOf(c)}</b><div class="ctx">${name}${agent ? html`<span class="tag">${NAMES[agent]}</span>` : ""}</div></td><td><span class="stc"><span class="si ${st}"></span>${WORDS[st]}</span></td><td class="d">${c.moved || c.added ? age(c.moved || c.added, now) + " ago" : ""}</td><td><div class="acts">${asking === key(c) ? html`<span class="q">Delete?</span><button class="btn ghost" data-keep="1">Keep</button><button class="btn danger" data-yes="${i}">Delete</button>` : html`${c.kind === "idea" ? html`<button class="del" data-i="${i}" title="Delete idea" aria-label="Delete idea">${ico("trash")}</button>` : ""}<button class="go" data-i="${i}">${c.kind === "idea" ? "Start" : "Open"} ${ico("arrow")}</button>`}</div></td></tr>`;
98
- })}</tbody></table>${rows.length ? "" : html`<p class="none">Nothing matches.</p>`}`;
119
+ })}</tbody></table>`;
99
120
  const hx = $("hx");
100
121
  // Not while a pop-up in it is open: redrawing would close it under the pointer.
101
122
  if (!hx.querySelector("details[open]")) hx.innerHTML = String(extra);
102
- box.innerHTML = String(html`<div class="ibox"><div class="iscroll">${table}</div></div>`);
123
+ $("tk-chips").innerHTML = String(chips);
124
+ $("tk-list").innerHTML = String(table);
103
125
 
104
126
  hx.querySelectorAll<HTMLElement>("[data-src]").forEach((b) => (b.onclick = () => ((f.src = b.dataset.src!), (hx.innerHTML = ""), draw())));
105
127
  hx.querySelectorAll<HTMLElement>("[data-sort]").forEach(
@@ -113,7 +135,7 @@ function draw() {
113
135
  draw();
114
136
  }),
115
137
  );
116
- hx.querySelectorAll<HTMLElement>("[data-show]").forEach((b) => (b.onclick = () => ((f.show = b.dataset.show!), (hx.innerHTML = ""), draw())));
138
+ box.querySelectorAll<HTMLElement>("[data-show]").forEach((b) => (b.onclick = () => ((f.show = b.dataset.show!), (hx.innerHTML = ""), draw())));
117
139
  $("ideas-ref").onclick = () => (void drawSources(true), void refreshBoardBadge());
118
140
  box.querySelectorAll<HTMLElement>("button.go").forEach((b) => (b.onclick = () => act(rows[+b.dataset.i!])));
119
141
  // The trash icon asks in its own row, as the board's card menu does; a redraw keeps the question.
@@ -178,7 +200,7 @@ addEventListener("keydown", (e) => {
178
200
  });
179
201
  export function openIdeas() {
180
202
  $("bq").placeholder = "Search ideas (press /)";
181
- addEventListener("kz-view", () => ($("bq").placeholder = "Filter cards (press /)"), { once: true });
203
+ addEventListener("kz-view", () => (undock(), ($("bq").placeholder = "Filter cards (press /)")), { once: true });
182
204
  void drawSources(true);
183
205
  draw();
184
206
  }
@@ -2,7 +2,7 @@ import { store } from "./store.ts";
2
2
  import { termStop } from "./agent-term.ts";
3
3
  import { load, post } from "./api.ts";
4
4
  import { stopDictation } from "./dictation.ts";
5
- import { $, html, ico, SKEL } from "./dom.ts";
5
+ import { $, html, ico, raw } from "./dom.ts";
6
6
  import { close } from "./panel.ts";
7
7
  import { placeOf, SETTINGS_NAV } from "./settings-pages.ts";
8
8
  import { askNotify, notifyOn, playSound, soundPick, SOUNDS, toast } from "./toast.ts";
@@ -18,13 +18,19 @@ addEventListener("keydown", (e) => {
18
18
  e.preventDefault();
19
19
  $("sq")?.focus();
20
20
  });
21
+ // The Settings page while it loads: its sidebar and a card of rows, so nothing jumps when it arrives.
22
+ const bar = (w: string, h = 14, m = "0") => `<span class="skel" style="width:${w};height:${h}px;margin:${m}"></span>`;
23
+ const SET_SKEL = raw(
24
+ `<div class="sset" aria-busy="true" aria-label="Loading"><nav class="snav"><div class="snavs">${bar("60%", 32, "0 0 24px")}${bar("100%", 32, "0 0 24px")}${[4, 3, 4].map((n) => bar("40%", 11, "0 12px 12px") + bar("100%", 32, "0 0 2px").repeat(n) + bar("0", 0, "0 0 20px")).join("")}</div></nav>` +
25
+ `<div class="smain"><div class="spage"><header>${bar("30%", 28, "0 0 8px")}${bar("55%")}</header><div class="scard">${(bar("70%", 13, "12px 0 6px") + bar("45%", 11, "0 0 12px")).repeat(6)}</div></div></div></div>`,
26
+ );
21
27
  export async function openSettings() {
22
28
  if (view !== "settings") return;
23
29
  const gen = ++store.pageGen;
24
30
  stopDictation(true);
25
31
  // Coming from another page or a card, its body goes now, not when the fetch answers.
26
32
  if (!$("panel").classList.contains("open") || $("ptitle").textContent !== "Settings") {
27
- $("pbody").innerHTML = SKEL;
33
+ $("pbody").innerHTML = SET_SKEL;
28
34
  $("psub").textContent = "";
29
35
  store.setScope = store.all ? "all" : store.dir || store.S.dir || "all";
30
36
  }
@@ -265,7 +271,11 @@ export async function openSettings() {
265
271
  if (el.matches(".step")) return stepper(el, vals, on, apply);
266
272
  el.querySelectorAll("[data-v]").forEach((b) => (b.onclick = () => {
267
273
  apply(b.dataset.v);
268
- openSettings();
274
+ // These live in this browser: nothing to read back, so the row answers at once, with no redraw.
275
+ el.querySelectorAll("[data-v]").forEach((x) => {
276
+ x.classList.toggle("on", x === b);
277
+ if (x.hasAttribute("aria-pressed")) x.setAttribute("aria-pressed", String(x === b));
278
+ });
269
279
  }));
270
280
  };
271
281
  choice($("th"), ["system", "light", "dark"], cur, setTheme);
@@ -302,7 +312,7 @@ export async function openSettings() {
302
312
  const save = async (v) => {
303
313
  const f = document.activeElement?.id;
304
314
  const j = await post("/settings", { key: r.key, value: v, scope: cfg.scope });
305
- if (j.ok) toast("Saved");
315
+ toast(j.ok ? "Saved" : j.error || "Could not save");
306
316
  await refocus(f);
307
317
  };
308
318
  if (el.tagName === "INPUT")
@@ -310,8 +320,20 @@ export async function openSettings() {
310
320
  await save(el.value.trim());
311
321
  load();
312
322
  };
313
- else el.querySelectorAll("[data-v]").forEach((b) => (b.onclick = () => save(b.dataset.v)));
314
- if (el.matches(".chk")) el.onclick = () => save(el.dataset.v);
323
+ else
324
+ el.querySelectorAll("[data-v]").forEach(
325
+ (b) =>
326
+ (b.onclick = () => {
327
+ // The row answers now; the redraw after the save shows what the server kept.
328
+ el.querySelectorAll("[data-v]").forEach((x) => x.classList.toggle("on", x === b));
329
+ save(b.dataset.v);
330
+ }),
331
+ );
332
+ if (el.matches(".chk"))
333
+ el.onclick = () => {
334
+ el.setAttribute("aria-checked", String(el.classList.toggle("on")));
335
+ save(el.dataset.v);
336
+ };
315
337
  // Clicks in quick succession save once, the value they settle on.
316
338
  let t;
317
339
  if (el.matches(".step"))
@@ -47,6 +47,7 @@ export function updBar() {
47
47
  return;
48
48
  }
49
49
  gotVer(v);
50
+ updPop();
50
51
  d.remove();
51
52
  updBar();
52
53
  if (upd) $("upd-go").focus();
@@ -57,26 +58,66 @@ export function updBar() {
57
58
  };
58
59
  if (!upd) return;
59
60
  const b = $("upd-go");
60
- b.onclick = async () => {
61
- if (!confirm(`Update kaizen to ${upd.latest}? The board restarts, and agents running inside cards stop.`)) return;
62
- b.disabled = true;
63
- b.textContent = "Updating…";
64
- const r = await post("/upgrade", {});
65
- if (!r.ok) {
66
- b.disabled = false;
67
- b.textContent = "Update kaizen";
68
- return;
69
- }
70
- b.textContent = "Restarting…";
71
- setTimeout(() => location.reload(), 20000);
61
+ b.onclick = () => upgrade(b);
62
+ }
63
+
64
+ async function upgrade(b) {
65
+ if (!confirm(`Update kaizen to ${upd.latest}? The board restarts, and agents running inside cards stop.`)) return;
66
+ const label = b.textContent;
67
+ b.disabled = true;
68
+ b.textContent = "Updating…";
69
+ const r = await post("/upgrade", {});
70
+ if (!r.ok) {
71
+ b.disabled = false;
72
+ b.textContent = label;
73
+ return;
74
+ }
75
+ b.textContent = "Restarting…";
76
+ setTimeout(() => location.reload(), 20000);
77
+ }
78
+
79
+ // The bottom-right popup for a new release. Later silences that version in this browser;
80
+ // the next release asks again.
81
+ function updPop() {
82
+ let later = null;
83
+ try {
84
+ later = localStorage.getItem("kz-upd-later");
85
+ } catch {}
86
+ const open = $("updcard");
87
+ if (!upd || later === upd.latest) return open?.remove();
88
+ const msg = html`kaizen <b>${upd.latest}</b> is available. You are running ${upd.version}.`;
89
+ if (open) {
90
+ open.firstElementChild.innerHTML = msg;
91
+ return;
92
+ }
93
+ const d = document.createElement("div");
94
+ d.id = "updcard";
95
+ d.setAttribute("role", "status");
96
+ d.innerHTML = html`<span>${msg}</span><span class="updact"><button class="btn" id="updcard-later">Later</button><button class="btn pri" id="updcard-go">Update now</button></span>`;
97
+ document.body.append(d);
98
+ $("updcard-later").onclick = () => {
99
+ try {
100
+ localStorage.setItem("kz-upd-later", upd.latest);
101
+ } catch {}
102
+ d.remove();
72
103
  };
104
+ const go = $("updcard-go");
105
+ go.onclick = () => upgrade(go);
73
106
  }
74
107
 
75
- export function initUpdate() {
108
+ function checkUpdate() {
109
+ const had = !!upd;
76
110
  fetch("/version")
77
111
  .then((r) => r.json())
78
112
  .then((v) => {
79
- if (gotVer(v) && view === "settings") openSettings();
113
+ if (gotVer(v) && !had && view === "settings") openSettings();
114
+ updPop();
80
115
  })
81
116
  .catch(() => {});
82
117
  }
118
+
119
+ // Hourly so a tab left open still hears of a release; the server's cache limits npm to every 6 h.
120
+ export function initUpdate() {
121
+ checkUpdate();
122
+ setInterval(checkUpdate, 3600_000);
123
+ }