kaizen-agent 1.60.1 → 1.61.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.
Files changed (44) hide show
  1. package/cli/knowledge.ts +1 -1
  2. package/cli/notes.test.ts +2 -1
  3. package/cli/onboarding.test.ts +70 -0
  4. package/cli/onboarding.ts +63 -0
  5. package/cli/pty.test.ts +15 -1
  6. package/cli/pty.ts +14 -3
  7. package/cli/shell-agent.test.ts +23 -0
  8. package/cli/state.test.ts +105 -1
  9. package/cli/state.ts +157 -19
  10. package/cli/web-decide.test.ts +41 -0
  11. package/cli/web.ts +145 -27
  12. package/package.json +1 -1
  13. package/web/board/add-project.ts +14 -4
  14. package/web/board/api.ts +37 -4
  15. package/web/board/approvals.ts +6 -6
  16. package/web/board/badge.ts +6 -2
  17. package/web/board/cards.ts +4 -2
  18. package/web/board/fixes.ts +1 -1
  19. package/web/board/git.ts +171 -97
  20. package/web/board/live.ts +2 -1
  21. package/web/board/main.ts +2 -0
  22. package/web/board/onboarding.ts +223 -0
  23. package/web/board/panel.ts +24 -14
  24. package/web/board/run-view.ts +86 -7
  25. package/web/board/settings-pages.test.ts +19 -0
  26. package/web/board/settings-pages.ts +44 -0
  27. package/web/board/settings.ts +118 -62
  28. package/web/board/store.ts +4 -0
  29. package/web/board/update.ts +1 -1
  30. package/web/board/views.ts +5 -1
  31. package/web/board/workspace.ts +92 -3
  32. package/web/board/ws-name.test.ts +10 -0
  33. package/web/board/ws-tabs.test.ts +14 -1
  34. package/web/board/ws-tabs.ts +12 -1
  35. package/web/board.html +165 -21
  36. package/web/board.js +107 -104
  37. package/web/notebook.js +29 -24
  38. package/web/notebook.ts +1 -0
  39. package/web/notes.html +28 -10
  40. package/web/popup.html +2 -2
  41. package/web/term.js +20 -20
  42. package/web/term.ts +8 -3
  43. package/web/video.html +28 -10
  44. package/web/video.js +56 -51
package/cli/web.ts CHANGED
@@ -5,11 +5,11 @@ import { join, dirname, resolve, sep, basename } from "node:path";
5
5
  import {
6
6
  home, type Item, type Card, boardCards, 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, notice, notifier, LOGO,
8
+ appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, commitStaged, stageFiles, suggestMessage, notice, notifier, LOGO,
9
9
  reviewFindings, pickFindings, backlogCards, 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
- import { attachPty, writePty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
12
+ import { attachPty, writePty, submitPty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
13
13
  import { claudeUsage, codexUsage, phonePeers, type Usage } from "./usage.ts";
14
14
  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
15
  import { projectLogo, LOGO_TYPES } from "./logo.ts";
@@ -22,7 +22,7 @@ import * as video from "./video.ts";
22
22
  import * as localsend from "./localsend.ts";
23
23
  import * as hermes from "./hermes.ts";
24
24
  import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
25
- import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
25
+ import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
26
26
  import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
27
27
 
28
28
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
@@ -254,7 +254,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
254
254
  let usageAt = 0;
255
255
  let pending: ReturnType<typeof setTimeout> | null = null;
256
256
  const prBusy = new Set<string>();
257
+ // /state costs ~250 ms of this one thread on a big board (git status per project), and
258
+ // every open tab asks at once on each change, stalling terminal output for all of them.
259
+ // A reply is shared until something changes; a git mark for a few seconds, since
260
+ // nothing watches the working trees anyway. Any write request drops both.
261
+ let stateGen = 0;
262
+ 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;
257
265
  const changed = () => {
266
+ stateGen++;
258
267
  if (pending) return;
259
268
  pending = setTimeout(() => {
260
269
  pending = null;
@@ -264,6 +273,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
264
273
  // agent.launch: card runs what this board launches inside the board, shown on the card.
265
274
  const inCard = (dir: string) => ({ card: launchMode(projectOf(dir)) === "card", onChange: changed });
266
275
 
276
+ // The agent open in a run's card, the newest when there are several: what the user sees
277
+ // working. Everything sent to a run goes here before any new agent is started.
278
+ const liveAgent = (dir: string, id: string) => {
279
+ 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();
281
+ };
282
+
267
283
  // Start a run's agent again after it ended mid-stage (crashed, closed, a stalled run, or
268
284
  // the board restarting for an upgrade), in the conversation it had where the tool can
269
285
  // resume one. A run waiting for a decision, or done, gets its conversation back with
@@ -273,7 +289,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
273
289
  let run: any;
274
290
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return { error: "no such run", status: 404 }; }
275
291
  if (run.stage === "abandoned") return { error: "this run was abandoned", status: 409 };
276
- 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 };
292
+ if (liveAgent(dir, id)) return { error: "its agent is still running in its card", status: 409 };
277
293
  const quiet = run.stage === "done" || !!run.awaiting;
278
294
  const own = quiet ? runAgent(dir, id) : null;
279
295
  if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
@@ -360,7 +376,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
360
376
  // run's state.json, about a second on a board of 400 runs.
361
377
  const ptyOf = (cards: Card[]) => {
362
378
  const live = new Set(ptyKeys());
363
- if (!live.size) return () => undefined;
379
+ if (!live.size) return Object.assign(() => undefined, { cmd: (_k: string) => undefined as string | undefined });
380
+ // Which agent each live terminal runs, from the session records: a run being born has no tag for it yet.
381
+ const cmdOf = new Map<string, string>();
382
+ for (const d of new Set(cards.map((c) => c.state))) for (const s of readSessions(d)) if (live.has(s.key) && s.cmd) cmdOf.set(s.key, s.cmd);
364
383
  const runs = new Map<string, string[]>();
365
384
  const planKeys = new Set(ideaPty.values());
366
385
  for (const d of new Set(cards.filter((c) => c.kind === "run").map((c) => c.state))) {
@@ -374,7 +393,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
374
393
  runs.set(k, [...(runs.get(k) ?? []), s.key]); // oldest first: the newest is the card's
375
394
  }
376
395
  }
377
- return (c: Card) => {
396
+ return Object.assign((c: Card) => {
378
397
  const keys = c.kind === "run" ? runs.get(`${c.state}\0${c.id}`) ?? [] : [ideaPty.get(`${c.state}\0${c.text}`)].filter((k): k is string => !!k && live.has(k));
379
398
  const key = keys.at(-1);
380
399
  if (!key) return undefined;
@@ -383,8 +402,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
383
402
  if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
384
403
  // Every agent session the run has had on this board, for the workspace's Agent tabs.
385
404
  const all = keys.filter((k) => ptyState(k)?.alive || k === key);
386
- return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
387
- };
405
+ return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, agent: cmdOf.get(key), stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
406
+ }, { cmd: (k: string) => cmdOf.get(k) });
388
407
  };
389
408
  const watchers: FSWatcher[] = [];
390
409
  const watchAll = () => {
@@ -523,6 +542,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
523
542
  // arrives with that hostname in Host, and gets nothing.
524
543
  const hostname = (req.headers.get("host") ?? "").toLowerCase().replace(/:\d+$/, "");
525
544
  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(); }
526
546
  const url = new URL(req.url);
527
547
  const path = url.pathname;
528
548
  const qdir = () => { const v = url.searchParams.get("dir"); return v == null ? v : canonState(v); };
@@ -778,6 +798,27 @@ export async function web(repoDir: string, opts: Opts = {}) {
778
798
  changed();
779
799
  return json(r);
780
800
  }
801
+ // The rail's right-click menu on a worktree: update (fast-forward pull) or delete it.
802
+ // Only an exact non-main path from this project's own worktree list; argv arrays.
803
+ if (req.method === "POST" && path === "/workspace") {
804
+ const refused = strict(req);
805
+ if (refused) return refused;
806
+ let body: any;
807
+ try { body = await req.json(); } catch { return bad("json body expected"); }
808
+ const dir = canonState(String(body.dir ?? ""));
809
+ if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
810
+ const project = projectOf(dir);
811
+ forgetWorkspaces(project);
812
+ const w = workspaces(project).find((x) => x.path === body.ws);
813
+ if (!w || w.main) return bad("not a worktree of this project", 400);
814
+ const r = body.op === "update" ? await runAsync(["git", "pull", "--ff-only"], w.path)
815
+ : body.op === "delete" ? await runAsync(["git", "worktree", "remove", "--", w.path], project)
816
+ : null;
817
+ if (!r) return bad("unknown op", 400);
818
+ forgetWorkspaces(project);
819
+ changed();
820
+ return r.ok ? json({ ok: true, out: r.out }) : bad(r.why, 409);
821
+ }
781
822
  // The rail's + sheet. Each of these starts git, makes a folder or registers one, so
782
823
  // they take /worktree's guards and read their paths from the raw body (the generic
783
824
  // POST block below would normalise a `..` away before destDir sees it).
@@ -966,7 +1007,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
966
1007
  if (req.method === "GET" && path === "/manifest.webmanifest") {
967
1008
  return new Response(JSON.stringify({
968
1009
  name: "kaizen", short_name: "kaizen", start_url: "/", scope: "/", display: "standalone",
969
- background_color: "#0c162f", theme_color: "#0c162f",
1010
+ background_color: "#121212", theme_color: "#121212",
970
1011
  icons: [{ src: "/logo.png", sizes: "1024x1024", type: "image/png", purpose: "any" }],
971
1012
  }), { headers: { "content-type": "application/manifest+json" } });
972
1013
  }
@@ -992,22 +1033,31 @@ export async function web(repoDir: string, opts: Opts = {}) {
992
1033
  return !root || d === state || (fold(p).startsWith(inside)
993
1034
  && (!isGroup(p) || filled(d) || fold(dirname(p)) !== fold(root)));
994
1035
  });
1036
+ // What an agent printed goes only to a viewer on this machine, not to a tailnet host or a phone.
1037
+ const ip = srv.requestIP(req)?.address ?? "";
1038
+ const loopback = (hostname === "127.0.0.1" || hostname === "localhost") && /^(127\.|::1$|::ffff:127\.)/.test(ip)
1039
+ && !["x-forwarded-for", "x-forwarded-host", "forwarded", "tailscale-user-login", "tailscale-user-name"].some((h) => req.headers.has(h));
1040
+ // Agents' status and last line change without an event, so they are part of what a reply is valid for.
1041
+ const gen = `${stateGen} ${ptyKeys().map((k) => { const s = ptyState(k)!; return `${k}:${s.alive}:${s.asking}:${s.busy}:${s.at}`; }).join()}`;
1042
+ const cacheKey = `${all}\0${state}\0${loopback}`, hit = stateCache.get(cacheKey);
1043
+ if (hit?.gen === gen && Date.now() - hit.at < STATE_MS) return new Response(hit.body, { headers: { "content-type": "application/json" } });
995
1044
  for (const d of dirs) healRuns(d);
996
1045
  const cards = boardCards(dirs, Date.now()), pty = ptyOf(cards);
997
1046
  // The git mark, for the cards whose panel offers commit and push: one status per project.
998
1047
  const marks = new Map<string, Record<string, string>>(), dues = new Map<string, Record<string, "commit" | "push">>();
999
1048
  const markable = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen");
1000
- for (const d of new Set(cards.filter(markable).map((c) => c.state)))
1001
- marks.set(d, cardsGit(d, cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!), dues.set(d, {}).get(d)));
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
+ }
1002
1056
  // Open findings the panel's Fix findings form would offer, on the same runs.
1003
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")
1004
1058
  ? reviewFindings(c.state, c.id!).filter((f) => !f.done).length || undefined : undefined;
1005
1059
  // The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
1006
1060
  // shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
1007
- // What an agent printed goes only to a viewer on this machine, not to a tailnet host or a phone.
1008
- const ip = srv.requestIP(req)?.address ?? "";
1009
- const loopback = (hostname === "127.0.0.1" || hostname === "localhost") && /^(127\.|::1$|::ffff:127\.)/.test(ip)
1010
- && !["x-forwarded-for", "x-forwarded-host", "forwarded", "tailscale-user-login", "tailscale-user-name"].some((h) => req.headers.has(h));
1011
1061
  const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
1012
1062
  const addAgent = (key: string, dir: string, ws: string | undefined, cmd: string | undefined, run?: string) => {
1013
1063
  const st = seenKey.has(key) ? null : ptyState(key);
@@ -1016,11 +1066,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1016
1066
  const name = KNOWN_AGENTS.find((k) => k.cmd === cmd)?.name.split(" ")[0] ?? "Agent";
1017
1067
  agents.push({ key, dir, ws, agent: cmd, name, run, asking: st.asking, busy: st.busy, born: st.born, ...(loopback ? { last: st.last || undefined, at: st.at || undefined } : {}) });
1018
1068
  };
1019
- for (const x of shells.values()) if (x.agent) addAgent(x.key, x.dir, x.ws, x.agent, x.run);
1020
- cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
1069
+ // A plain shell counts too while an agent typed into it runs there.
1070
+ for (const x of shells.values()) { const cmd = x.agent || (x.pid ? shellAgent(x.pid, KNOWN_AGENTS.map((k) => k.cmd)) : undefined); if (cmd) addAgent(x.key, x.dir, x.ws, cmd, x.run); }
1071
+ cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, pty.cmd(k) ?? KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
1021
1072
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1022
1073
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
1023
- return json({
1074
+ const body = JSON.stringify({
1024
1075
  project, all, dir: state,
1025
1076
  // Each project's workspaces (git worktrees, or the one folder); the global queue is its own one.
1026
1077
  projects: picker.map(entry),
@@ -1033,6 +1084,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1033
1084
  backlog: backlogCards(dirs).map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1034
1085
  now: Date.now(),
1035
1086
  });
1087
+ stateCache.set(cacheKey, { gen, at: Date.now(), body });
1088
+ return new Response(body, { headers: { "content-type": "application/json" } });
1036
1089
  }
1037
1090
 
1038
1091
  if (req.method === "GET" && path.startsWith("/run/")) {
@@ -1088,6 +1141,22 @@ export async function web(repoDir: string, opts: Opts = {}) {
1088
1141
  return Response.redirect(issueUrl({ title: url.searchParams.get("title") ?? "", what: url.searchParams.get("what") ?? "" }), 302);
1089
1142
  }
1090
1143
 
1144
+ // First-run onboarding: where this machine's user got to, and what the page offers to pick from.
1145
+ // Only the board's own file is written; the choices themselves go through /settings.
1146
+ if (path === "/onboarding" && (req.method === "GET" || req.method === "POST")) {
1147
+ const { onboardingView, writeOnboarding, installHelp } = await import("./onboarding.ts");
1148
+ if (req.method === "POST") {
1149
+ if (!local(req)) return bad("cross-origin write refused", 403);
1150
+ let body: any;
1151
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1152
+ const r = writeOnboarding(home, body);
1153
+ return "error" in r ? bad(r.error) : json(r);
1154
+ }
1155
+ const projects = states(true).filter((d) => d !== join(home, ".kaizen")).length;
1156
+ const ch = agentChoices(repoDir);
1157
+ return json({ ...onboardingView(home, projects), default: ch.default, installed: ch.agents.map((a) => a.cmd), agents: KNOWN_AGENTS.map((a) => ({ cmd: a.cmd, name: a.name })), install: installHelp(process.platform === "win32") });
1158
+ }
1159
+
1091
1160
  if (req.method === "GET" && path === "/agents") {
1092
1161
  const dir = qdir();
1093
1162
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
@@ -1727,11 +1796,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
1727
1796
  let run: any;
1728
1797
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1729
1798
  if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
1730
- const r = await commitPush(dir, id, String(body.message ?? ""), Array.isArray(body.files) ? body.files.map(String) : []);
1799
+ const files = Array.isArray(body.files) ? body.files.map(String) : [];
1800
+ // `push: false` is the tab's plain Commit: what is staged, nothing pushed.
1801
+ const r = body.push === false ? commitStaged(dir, id, String(body.message ?? ""), files) : await commitPush(dir, id, String(body.message ?? ""), files);
1731
1802
  changed();
1732
1803
  return json(r, r.ok ? 200 : 409);
1733
1804
  }
1734
1805
 
1806
+ // The Source control tab's stage, unstage and discard, on the same runs /commit
1807
+ // takes and only on the run's own files (stageFiles refuses any other path).
1808
+ if (path === "/stage") {
1809
+ const id = String(body.id ?? "");
1810
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1811
+ if (dir === join(home, ".kaizen")) return bad("no project", 409);
1812
+ let run: any;
1813
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1814
+ if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
1815
+ const op = body.op;
1816
+ if (op !== "stage" && op !== "unstage" && op !== "discard") return bad("unknown op");
1817
+ const why = stageFiles(dir, id, op, Array.isArray(body.paths) ? body.paths.map(String) : []);
1818
+ changed();
1819
+ return why ? bad(why, 409) : json({ ok: true });
1820
+ }
1821
+
1822
+ // The sparkle button: a commit message for the run's files, written from their diff.
1823
+ if (path === "/commit-message") {
1824
+ const id = String(body.id ?? "");
1825
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1826
+ if (dir === join(home, ".kaizen")) return bad("no project", 409);
1827
+ const r = await suggestMessage(dir, id);
1828
+ return r.ok ? json(r) : bad(r.why, 409);
1829
+ }
1830
+
1735
1831
  // The Git tab's later steps, on the same runs /commit takes: open the branch's pull
1736
1832
  // request, merge it, then remove the worktree once its work is on the base.
1737
1833
  if (path === "/pr") {
@@ -1773,9 +1869,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
1773
1869
  const text = fixPrompt(id, nums);
1774
1870
  // An agent already open in this run's card takes the fix there, busy or not:
1775
1871
  // the text queues in it, and no second agent opens beside it.
1776
- const live = readSessions(dir).find((s) => ptyState(s.key)?.alive && ownerOf(dir, s) === id);
1872
+ const live = liveAgent(dir, id);
1777
1873
  if (live) {
1778
- writePty(live.key, text + "\r");
1874
+ submitPty(live.key, text);
1779
1875
  markStage(dir, id, "review", live.key);
1780
1876
  changed();
1781
1877
  return json({ ok: true, pty: live.key, reused: true });
@@ -1816,12 +1912,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
1816
1912
  if (answers !== undefined && (run.awaiting !== "approvals.plan" || body.why !== undefined || !Array.isArray(answers)
1817
1913
  || !answers.length || answers.length > 20 || answers.some((a: unknown) => typeof a !== "string" || !a.trim()))) return bad("bad answers");
1818
1914
  const text = approvalPrompt(id, run.awaiting, body.why === undefined ? undefined : String(body.why), answers);
1819
- // The run is stopped at this approval, so its window is idle: the same
1820
- // conversation continues in one new window, and then the idle one ends. A
1821
- // failed launch leaves it open, since the decision went nowhere.
1915
+ // The agent already open in this run's card takes the decision there, as it takes
1916
+ // a fix: no second tab of the same conversation. With none, the run's conversation
1917
+ // continues in one new window, and then the idle one ends. A failed launch leaves
1918
+ // it open, since the decision went nowhere.
1919
+ const live = liveAgent(dir, id);
1822
1920
  const before = Date.now();
1823
- const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1824
- if (r.ok) closeSessions(dir, id, { before });
1921
+ const r = live ? { ok: true as const, pty: live.key, agent: live.cmd, reused: true } : launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1922
+ if (live) submitPty(live.key, text);
1923
+ else if (r.ok) closeSessions(dir, id, { before });
1825
1924
  // The plan's approval starts the build; fixing open findings is the review stage again.
1826
1925
  if (r.ok) markStage(dir, id, run.awaiting === "approvals.plan" ? "impl" : run.awaiting === "findings" ? "review" : "", r.pty);
1827
1926
  // Approving the review as-is is the user's acceptance, on record before the
@@ -1829,7 +1928,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1829
1928
  if (r.ok && body.why === undefined && (run.awaiting === "approvals.review" || run.awaiting === "findings")) recordAcceptance(dir, id, "board");
1830
1929
  changed();
1831
1930
  return json(r.ok
1832
- ? { ok: true, agent: r.agent, pty: r.pty }
1931
+ ? { ok: true, agent: r.agent, pty: r.pty, ...(live ? { reused: true } : {}) }
1833
1932
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1834
1933
  }
1835
1934
 
@@ -1962,6 +2061,25 @@ export function sessionLive(id: string): boolean {
1962
2061
  return false;
1963
2062
  }
1964
2063
 
2064
+ // The known agent running below a board shell, by walking its child processes. A wrapper script
2065
+ // shows as `bash <path>/claude`, so the first two arguments are checked. Linux only; elsewhere undefined.
2066
+ const procRead = (path: string) => readFileSync(path, "utf8");
2067
+ export function shellAgent(root: number, known: string[], read: (path: string) => string = procRead): string | undefined {
2068
+ const todo = [root];
2069
+ for (let n = 0; todo.length && n < 200; n++) {
2070
+ const pid = todo.shift()!;
2071
+ try {
2072
+ if (pid !== root) {
2073
+ const argv = read(`/proc/${pid}/cmdline`).split("\0").slice(0, 2).map((a) => a.split("/").pop() ?? "");
2074
+ const hit = known.find((k) => argv.includes(k));
2075
+ if (hit) return hit;
2076
+ }
2077
+ todo.push(...read(`/proc/${pid}/task/${pid}/children`).split(" ").filter(Boolean).map(Number));
2078
+ } catch { /* it ended, or no /proc */ }
2079
+ }
2080
+ return undefined;
2081
+ }
2082
+
1965
2083
  // Whether Claude Code session `id` runs as process `root` or under it: Claude Code records
1966
2084
  // each running session as ~/.claude/sessions/<pid>.json; /proc gives the parent chain.
1967
2085
  // Linux only; elsewhere false, and the run view says the session runs elsewhere.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.60.1",
3
+ "version": "1.61.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": {
@@ -3,6 +3,7 @@
3
3
  // Every call is a JSON POST to the board; the server validates paths, URLs and refs again.
4
4
  import { html, modal } from "./dom.ts";
5
5
  import { gitProjects, wsHref } from "./workspace.ts";
6
+ import { branchSlug } from "./ws-tabs.ts";
6
7
 
7
8
  type Start = "folder" | "clone" | "create" | "ws";
8
9
  const SEP = (p: string) => (p.includes("\\") ? "\\" : "/");
@@ -44,6 +45,7 @@ export function openAdd(opts: { dir?: string | null; start?: Start } = {}) {
44
45
 
45
46
  const draw = (v: Start | "menu") => {
46
47
  const ws = gitProjects();
48
+ dl.classList.toggle("wsnew", v === "ws");
47
49
  if (v === "menu") {
48
50
  form.innerHTML = html`<b>Add a project</b><small class="att">Add a project to get started with kaizen.</small><button type="button" class="btn opt" data-go="folder"><b>Existing folder</b><small>A project, a Git repo, or any folder</small></button><small class="att">Other ways to add</small><button type="button" class="btn opt" data-go="clone"><b>Clone from URL</b><small>Clone a remote Git repository</small></button><button type="button" class="btn opt" data-go="create"><b>Create new project</b><small>Start from an empty folder</small></button>${ws.length ? html`<button type="button" class="btn opt" data-go="ws"><b>New workspace</b><small>A branch in its own folder, in a project you have</small></button>` : ""}<div class="row"><button type="button" class="btn ghost" data-a="x">Cancel</button></div>`.toString();
49
51
  form.querySelectorAll<HTMLElement>("[data-go]").forEach((b) => (b.onclick = () => draw(b.dataset.go as Start)));
@@ -106,11 +108,13 @@ export function openAdd(opts: { dir?: string | null; start?: Start } = {}) {
106
108
  landed(r.d.dir, r.d.git === false ? "Project created, but git init failed" : "Project created");
107
109
  };
108
110
  } else {
109
- // New workspace: a project (git ones), a branch name and the branch it starts from.
111
+ // New workspace, after Orca's composer: one name box, the start branch on its label row, Advanced for an exact branch.
110
112
  const cur = ws.some((p) => p.dir === opts.dir) ? opts.dir : ws[0]?.dir;
111
- form.innerHTML = html`<b>New workspace</b><small class="att">A new branch in its own folder under .kaizen/wt/.</small><label class="att">Project<select name="project" aria-label="Project">${ws.map((p) => html`<option value="${p.dir}"${p.dir === cur ? " selected" : ""}>${p.name}</option>`)}</select></label><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false" required></label><label class="att">Base branch<select name="base" aria-label="Base branch"></select></label>${foot("Create workspace")}`.toString();
112
- field("branch").focus();
113
+ const mod = /Mac/.test(navigator.platform) ? "⌘" : "Ctrl";
114
+ form.innerHTML = html`<b>New workspace</b><label class="att">Project<select name="project" aria-label="Project">${ws.map((p) => html`<option value="${p.dir}"${p.dir === cur ? " selected" : ""}>${p.name}</option>`)}</select></label><div class="wsfrom"><span class="att" id="wsfl">Create from <i>[Optional]</i></span><label class="wsbase">from <select name="base" aria-label="Start from branch"></select></label></div><input name="name" placeholder="What is this workspace for?" aria-labelledby="wsfl" autocomplete="off" spellcheck="false"><details class="wsadv"><summary>Advanced</summary><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false"></label></details><small class="att err" role="alert"></small><div class="row">${back}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">Create workspace</button><kbd class="wskey" aria-hidden="true">${mod} ↵</kbd></div>`.toString();
115
+ field("name").focus();
113
116
  const sel = form.elements.namedItem("base") as HTMLSelectElement;
117
+ field("name").oninput = () => (field("branch").placeholder = branchSlug(field("name").value) || "feature/my-branch");
114
118
  const bases = async () => {
115
119
  const r = await call("/branches?dir=" + encodeURIComponent(field("project").value));
116
120
  const { def = "", branches = [] } = r.ok ? r.d : {};
@@ -118,12 +122,18 @@ export function openAdd(opts: { dir?: string | null; start?: Start } = {}) {
118
122
  };
119
123
  (form.elements.namedItem("project") as HTMLSelectElement).onchange = bases;
120
124
  bases();
125
+ form.onkeydown = (e) => {
126
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) e.preventDefault(), form.requestSubmit();
127
+ };
121
128
  form.onsubmit = async (e) => {
122
129
  e.preventDefault();
123
130
  const dir = field("project").value;
124
131
  const b = form.querySelector<HTMLButtonElement>("[data-a=go]")!;
132
+ if (b.disabled) return;
133
+ say("");
134
+ const branch = field("branch").value.trim() || branchSlug(field("name").value) || "workspace-" + Math.random().toString(36).slice(2, 6);
125
135
  busy(b, true, "Creating...", "Create workspace");
126
- const r = await call("/worktree", { dir, branch: field("branch").value.trim(), base: sel.value || undefined });
136
+ const r = await call("/worktree", { dir, branch, base: sel.value || undefined });
127
137
  busy(b, false, "", "Create workspace");
128
138
  r.ok ? (dl.close(), (location.href = wsHref(dir, r.d.path))) : say(r.d.error);
129
139
  };
package/web/board/api.ts CHANGED
@@ -21,8 +21,31 @@ let before: Map<string, [number, boolean]> | null = null;
21
21
  // tab or a phone picking a project never moves this one.
22
22
  export const dirHeader = () => (store.dir ? { "x-kz-dir": store.dir } : {});
23
23
  let latestLoad = 0;
24
+ // A change event can come several times a second while agents work, and a full read and
25
+ // redraw blocks this thread (and any terminal in it). One quiet load per QUIET_GAP, the
26
+ // last change always covered; a hidden tab only watches for agents asking.
27
+ const QUIET_GAP = 500, HIDDEN_GAP = 5000;
28
+ // The last reply without its clock, and when it was last drawn: an identical reply skips
29
+ // the redraw, but ages and repeat notices still need one now and then.
30
+ const REDRAW_MS = 30_000;
31
+ let lastBody = "", drawnAt = 0;
32
+ let lastQuiet = 0;
33
+ let quietTimer: ReturnType<typeof setTimeout> | 0 = 0;
34
+ const runQuiet = () => {
35
+ quietTimer = 0;
36
+ lastQuiet = Date.now();
37
+ return read(true);
38
+ };
24
39
  // quiet: the server said something changed, nobody asked for a redraw.
25
- export async function load(quiet) {
40
+ export function load(quiet?: boolean) {
41
+ if (!quiet) return read(false);
42
+ if (!quietTimer) quietTimer = setTimeout(runQuiet, Math.max(0, lastQuiet + (document.hidden ? HIDDEN_GAP : QUIET_GAP) - Date.now()));
43
+ }
44
+ // Back on a hidden tab: what it put off is shown now.
45
+ export function flushLoad() {
46
+ if (!document.hidden && quietTimer) { clearTimeout(quietTimer); void runQuiet(); }
47
+ }
48
+ async function read(quiet: boolean) {
26
49
  const current = ++latestLoad;
27
50
  let r;
28
51
  try {
@@ -31,8 +54,17 @@ export async function load(quiet) {
31
54
  toast(GONE);
32
55
  return;
33
56
  }
34
- const next = await r.json();
57
+ const text = await r.text();
35
58
  if (current !== latestLoad) return;
59
+ const body = text.replace(/"now":\d+\}$/, "");
60
+ const same = quiet && body === lastBody && Date.now() - drawnAt < REDRAW_MS;
61
+ lastBody = body;
62
+ if (same) {
63
+ if (!store.all) void refreshBoardBadge();
64
+ return;
65
+ }
66
+ drawnAt = Date.now();
67
+ const next = JSON.parse(text);
36
68
  const was = store.openKey && store.S.cards.find((x) => key(x) === store.openKey);
37
69
  store.S = next;
38
70
  if (!store.all) void refreshBoardBadge();
@@ -89,8 +121,9 @@ export async function load(quiet) {
89
121
  }
90
122
  if (store.openKey) {
91
123
  const c = store.S.cards.find((x) => key(x) === store.openKey),
92
- ta = $("pbody").querySelector(".notes textarea");
93
- if (ta && document.activeElement === ta) return;
124
+ nb = $("pbody").querySelector(".notes");
125
+ // The textarea is hidden under the rich editor: focus anywhere in the notes counts.
126
+ if (nb?.contains(document.activeElement)) return;
94
127
  if (!c) {
95
128
  if (was && was.kind === "idea") follow(was);
96
129
  return;
@@ -18,16 +18,16 @@ export async function resume(c, b) {
18
18
  return;
19
19
  }
20
20
  toast("Resumed, " + where(r) + ": " + via(r.agent));
21
- if (r.pty) store.wantTerm = key(c);
21
+ if (r.pty) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
22
22
  if (store.openKey === key(c)) {
23
23
  $("pfoot").innerHTML = "";
24
24
  openRun(c, true);
25
25
  }
26
26
  }
27
27
  export const APPROVAL = {
28
- "approvals.plan": "Read the plan, then: Approve starts the build; Revise sends it back with what to change.",
29
- "approvals.review": "The work is ready to check. Approve finishes it; Revise sends it back with what to change.",
30
- findings: "The review has open findings. Approve as-is to accept them and finish, or fix selected findings first.",
28
+ "approvals.plan": "Plan ready.",
29
+ "approvals.review": "Ready to check.",
30
+ findings: "Open findings.",
31
31
  },
32
32
  decided = new Set(),
33
33
  answer = (c) => key(c) + ":" + c.awaiting + ":" + c.moved;
@@ -47,8 +47,8 @@ export async function decide(c, b, why, answers) {
47
47
  return;
48
48
  }
49
49
  decided.add(answer(c));
50
- toast((why === undefined ? "Approved" : "Sent back") + ", " + where(r) + ": " + via(r.agent));
51
- if (r.pty) store.wantTerm = key(c);
50
+ toast((why === undefined ? "Approved" : "Sent back") + ", " + (r.reused ? "sent to the agent already open in its card" : where(r) + ": " + via(r.agent)));
51
+ if (r.pty) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
52
52
  if (store.openKey === key(c)) {
53
53
  $("pfoot").innerHTML = "";
54
54
  openRun(c, true);
@@ -14,6 +14,7 @@ export function boardBadge(cards: BadgeCard[], projects?: unknown[], agents?: un
14
14
  }
15
15
 
16
16
  let generation = 0;
17
+ let lastAll = "";
17
18
  let loading = false;
18
19
  let again = false;
19
20
  export async function refreshBoardBadge() {
@@ -25,8 +26,11 @@ export async function refreshBoardBadge() {
25
26
  try {
26
27
  const r = await fetch("/state?all=1");
27
28
  if (!r.ok) continue;
28
- const { cards, projects, rail, agents } = await r.json();
29
- if (!again && current === generation) boardBadge(cards, [...projects, ...(rail ?? [])], agents);
29
+ const text = await r.text();
30
+ const body = text.replace(/"now":\d+\}$/, "");
31
+ if (body === lastAll) continue;
32
+ const { cards, projects, rail, agents } = JSON.parse(text);
33
+ if (!again && current === generation) { lastAll = body; boardBadge(cards, [...projects, ...(rail ?? [])], agents); }
30
34
  } catch { /* keep the last count while the board is offline */ }
31
35
  } while (again);
32
36
  loading = false;
@@ -7,6 +7,7 @@ import { draft, undraft } from "./drafts.ts";
7
7
  import { COLS, ICON, MARKS, NAMES, WORD, age, d, need } from "./labels.ts";
8
8
  import { brief } from "./markdown.ts";
9
9
  import { open, openAt, toggleArchive } from "./panel.ts";
10
+ import { isPhone } from "./phone.ts";
10
11
  import { ideaCombo, list, newDir, plogo, setNewDir, short, showList, showable } from "./projects.ts";
11
12
  import { askNotify, toast } from "./toast.ts";
12
13
  import { answer, decided, resumable, resume } from "./approvals.ts";
@@ -512,7 +513,7 @@ async function startRun(c, kind) {
512
513
  if (r.ok) {
513
514
  toast((kind === "full" ? "Full" : kind === "lite" ? "Lite" : "Started") + (yolo ? " yolo" : "") + " run " + where(r) + ": " + via(r.agent));
514
515
  // A backlog card has no terminal of its own; the run's card gets it once the run exists.
515
- if (r.pty && !backlog) store.wantTerm = key(c);
516
+ if (r.pty && !backlog) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
516
517
  // An idea's run opens in its workspace; the view follows it once the run card exists.
517
518
  if (!backlog) openWorkspace(c);
518
519
  }
@@ -529,7 +530,8 @@ let newFiles = [];
529
530
  // preset to that page's project or empty so one is chosen. The Board keeps its own rule.
530
531
  let formPick: { dir: string | null } | null = null;
531
532
  function ideaForm(f, shut) {
532
- const picking = store.all || !!formPick;
533
+ // A phone has no project picker in its header: the form is the only place to choose.
534
+ const picking = store.all || !!formPick || isPhone();
533
535
  const close = () => {
534
536
  newFiles = [];
535
537
  shut();
@@ -76,7 +76,7 @@ export function fixForm(c) {
76
76
  "Fixing " + nums.length + " finding" + (nums.length === 1 ? "" : "s") + ", " +
77
77
  (r.reused ? "sent to the agent already open in its card" : where(r) + ": " + via(r.agent)),
78
78
  );
79
- if (r.pty) store.wantTerm = key(c);
79
+ if (r.pty) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
80
80
  nums.forEach((n) => fixSent.add(k(n)));
81
81
  try {
82
82
  sessionStorage.setItem(SK, JSON.stringify([...fixSent]));