kaizen-agent 1.60.1 → 1.60.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/web.ts CHANGED
@@ -5,7 +5,7 @@ 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";
@@ -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).
@@ -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);
@@ -1017,10 +1067,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
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
1069
  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); });
1070
+ 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
1071
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1022
1072
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
1023
- return json({
1073
+ const body = JSON.stringify({
1024
1074
  project, all, dir: state,
1025
1075
  // Each project's workspaces (git worktrees, or the one folder); the global queue is its own one.
1026
1076
  projects: picker.map(entry),
@@ -1033,6 +1083,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1033
1083
  backlog: backlogCards(dirs).map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1034
1084
  now: Date.now(),
1035
1085
  });
1086
+ stateCache.set(cacheKey, { gen, at: Date.now(), body });
1087
+ return new Response(body, { headers: { "content-type": "application/json" } });
1036
1088
  }
1037
1089
 
1038
1090
  if (req.method === "GET" && path.startsWith("/run/")) {
@@ -1088,6 +1140,22 @@ export async function web(repoDir: string, opts: Opts = {}) {
1088
1140
  return Response.redirect(issueUrl({ title: url.searchParams.get("title") ?? "", what: url.searchParams.get("what") ?? "" }), 302);
1089
1141
  }
1090
1142
 
1143
+ // First-run onboarding: where this machine's user got to, and what the page offers to pick from.
1144
+ // Only the board's own file is written; the choices themselves go through /settings.
1145
+ if (path === "/onboarding" && (req.method === "GET" || req.method === "POST")) {
1146
+ const { onboardingView, writeOnboarding, installHelp } = await import("./onboarding.ts");
1147
+ if (req.method === "POST") {
1148
+ if (!local(req)) return bad("cross-origin write refused", 403);
1149
+ let body: any;
1150
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1151
+ const r = writeOnboarding(home, body);
1152
+ return "error" in r ? bad(r.error) : json(r);
1153
+ }
1154
+ const projects = states(true).filter((d) => d !== join(home, ".kaizen")).length;
1155
+ const ch = agentChoices(repoDir);
1156
+ 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") });
1157
+ }
1158
+
1091
1159
  if (req.method === "GET" && path === "/agents") {
1092
1160
  const dir = qdir();
1093
1161
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
@@ -1727,11 +1795,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
1727
1795
  let run: any;
1728
1796
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1729
1797
  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) : []);
1798
+ const files = Array.isArray(body.files) ? body.files.map(String) : [];
1799
+ // `push: false` is the tab's plain Commit: what is staged, nothing pushed.
1800
+ const r = body.push === false ? commitStaged(dir, id, String(body.message ?? ""), files) : await commitPush(dir, id, String(body.message ?? ""), files);
1731
1801
  changed();
1732
1802
  return json(r, r.ok ? 200 : 409);
1733
1803
  }
1734
1804
 
1805
+ // The Source control tab's stage, unstage and discard, on the same runs /commit
1806
+ // takes and only on the run's own files (stageFiles refuses any other path).
1807
+ if (path === "/stage") {
1808
+ const id = String(body.id ?? "");
1809
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1810
+ if (dir === join(home, ".kaizen")) return bad("no project", 409);
1811
+ let run: any;
1812
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1813
+ if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
1814
+ const op = body.op;
1815
+ if (op !== "stage" && op !== "unstage" && op !== "discard") return bad("unknown op");
1816
+ const why = stageFiles(dir, id, op, Array.isArray(body.paths) ? body.paths.map(String) : []);
1817
+ changed();
1818
+ return why ? bad(why, 409) : json({ ok: true });
1819
+ }
1820
+
1821
+ // The sparkle button: a commit message for the run's files, written from their diff.
1822
+ if (path === "/commit-message") {
1823
+ const id = String(body.id ?? "");
1824
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1825
+ if (dir === join(home, ".kaizen")) return bad("no project", 409);
1826
+ const r = await suggestMessage(dir, id);
1827
+ return r.ok ? json(r) : bad(r.why, 409);
1828
+ }
1829
+
1735
1830
  // The Git tab's later steps, on the same runs /commit takes: open the branch's pull
1736
1831
  // request, merge it, then remove the worktree once its work is on the base.
1737
1832
  if (path === "/pr") {
@@ -1773,7 +1868,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1773
1868
  const text = fixPrompt(id, nums);
1774
1869
  // An agent already open in this run's card takes the fix there, busy or not:
1775
1870
  // 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);
1871
+ const live = liveAgent(dir, id);
1777
1872
  if (live) {
1778
1873
  writePty(live.key, text + "\r");
1779
1874
  markStage(dir, id, "review", live.key);
@@ -1816,12 +1911,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
1816
1911
  if (answers !== undefined && (run.awaiting !== "approvals.plan" || body.why !== undefined || !Array.isArray(answers)
1817
1912
  || !answers.length || answers.length > 20 || answers.some((a: unknown) => typeof a !== "string" || !a.trim()))) return bad("bad answers");
1818
1913
  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.
1914
+ // The agent already open in this run's card takes the decision there, as it takes
1915
+ // a fix: no second tab of the same conversation. With none, the run's conversation
1916
+ // continues in one new window, and then the idle one ends. A failed launch leaves
1917
+ // it open, since the decision went nowhere.
1918
+ const live = liveAgent(dir, id);
1822
1919
  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 });
1920
+ 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));
1921
+ if (live) writePty(live.key, text + "\r");
1922
+ else if (r.ok) closeSessions(dir, id, { before });
1825
1923
  // The plan's approval starts the build; fixing open findings is the review stage again.
1826
1924
  if (r.ok) markStage(dir, id, run.awaiting === "approvals.plan" ? "impl" : run.awaiting === "findings" ? "review" : "", r.pty);
1827
1925
  // Approving the review as-is is the user's acceptance, on record before the
@@ -1829,7 +1927,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1829
1927
  if (r.ok && body.why === undefined && (run.awaiting === "approvals.review" || run.awaiting === "findings")) recordAcceptance(dir, id, "board");
1830
1928
  changed();
1831
1929
  return json(r.ok
1832
- ? { ok: true, agent: r.agent, pty: r.pty }
1930
+ ? { ok: true, agent: r.agent, pty: r.pty, ...(live ? { reused: true } : {}) }
1833
1931
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1834
1932
  }
1835
1933
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.60.1",
3
+ "version": "1.60.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": {
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]));