kaizen-agent 1.84.0 → 1.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/accounts.ts CHANGED
@@ -146,7 +146,7 @@ export function resolveAccount(cmd: string, wanted?: string, win = process.platf
146
146
  const a = readAccounts(), id = wanted ?? a.default[cmd];
147
147
  if (!id) return {};
148
148
  const account = a.accounts.find((x) => x.id === id && x.tool === cmd);
149
- if (!account) return { error: "That account no longer exists. Pick another in Settings → AI Provider Accounts." };
149
+ if (!account) return { error: "That account no longer exists. Pick another in Settings → AI Accounts." };
150
150
  if (win) return { error: "Accounts aren't supported on Windows yet." };
151
151
  const dir = accountDir(id);
152
152
  if (!existsSync(dir)) return { error: `The folder for ${account.name} is missing.` };
@@ -60,7 +60,7 @@ export function destDir(raw: unknown, home: string, known: string[] = [], projec
60
60
  if (low === kz || low.startsWith(kz + sep) || parts.includes(".git") || parts.includes(".kaizen")) return { error: "that folder is kaizen's or git's own" };
61
61
  if (winBad(basename(dir))) return { error: `${basename(dir)} cannot be a folder name on Windows` };
62
62
  const under = (r: string) => !!r && (dir === canonPath(r) || dir.startsWith(canonPath(r) + sep));
63
- if (!under(h) && !under(projects)) return { error: "choose a folder inside your home, or set Settings → Projects folder (board.projects_dir) to allow another place" };
63
+ if (!under(h) && !under(projects)) return { error: "choose a folder inside your home, or set Settings → General → Folders → Projects folder (board.projects_dir) to allow another place" };
64
64
  const proj = projects ? canonPath(projects) : "";
65
65
  for (let a = dirname(dir); ; a = dirname(a)) {
66
66
  if (known.includes(a)) return { error: `that folder is inside the project ${a}` };
@@ -1,4 +1,4 @@
1
- // Settings → Mobile and the onboarding phone step: what `kaizen setup` does for the phone,
1
+ // Settings → Phone and the onboarding phone step: what `kaizen setup` does for the phone,
2
2
  // as board routes. GET says where this computer stands, POST connects or logs in.
3
3
  import { qrMatrix } from "./qr.ts";
4
4
  import { addWebHost, webHosts } from "./state.ts";
package/cli/state.ts CHANGED
@@ -423,6 +423,28 @@ export function remember(projectDir: string) {
423
423
  } catch { /* nothing here is worth an error */ }
424
424
  }
425
425
 
426
+ // The sidebar's drag-and-drop rank: `first` (project folders, in the new order) go to the top of
427
+ // the registry, every other line keeps its place after them. Only folders already registered move,
428
+ // nothing is added or dropped, comment lines stay on top; written to a temp file and renamed so a
429
+ // reader never sees half a list. Returns the new order (knownProjects()).
430
+ export function reorderProjects(first: string[]): string[] {
431
+ if (!existsSync(REGISTRY)) return [];
432
+ const lines = readText(REGISTRY).split("\n").map((l) => l.trim()).filter(Boolean);
433
+ const notes = lines.filter((l) => l.startsWith("#")), rows = lines.filter((l) => !l.startsWith("#")).map((l) => ({ l, c: canonPath(l) }));
434
+ const want = first.map(canonPath).filter((d, i, all) => all.indexOf(d) === i);
435
+ const moved = want.flatMap((d) => rows.filter((r) => r.c === d));
436
+ const rest = rows.filter((r) => !moved.includes(r));
437
+ const tmp = `${REGISTRY}.${process.pid}.tmp`;
438
+ writeFileSync(tmp, [...notes, ...[...moved, ...rest].map((r) => r.l)].join("\n") + "\n");
439
+ // A project remember()ed since the read above would be lost by the rename: read again right
440
+ // before it and carry any new line over.
441
+ const seen = new Set(rows.map((r) => r.c));
442
+ const late = readText(REGISTRY).split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#") && !seen.has(canonPath(l)));
443
+ if (late.length) appendFileSync(tmp, late.join("\n") + "\n");
444
+ renameSync(tmp, REGISTRY);
445
+ return knownProjects();
446
+ }
447
+
426
448
  export const SKIP = new Set([
427
449
  "windows", "program files", "program files (x86)", "programdata", "$recycle.bin",
428
450
  "system volume information", "appdata", "node_modules", "recovery", "perflogs",
package/cli/ui-audit.ts CHANGED
@@ -279,7 +279,7 @@ export async function settle(page: Page, ms = 6000) {
279
279
  // ---- screens and states. `open` runs in the page after load: click() waits for a shown element, then clicks it.
280
280
  type Screen = { name: string; url: string; widths?: number[]; open?: string };
281
281
  const BARS = [[".rail .top", ".hdr", "#rbar", "#panel>header", ".pstrip"], ["#sback", "#smain h2"]];
282
- const SETTINGS = ["agents", "accounts", "orchestration", "skills", "voice", "general", "integrations", "mobile", "approvals", "autofix", "automations", "git", "terminal", "appearance", "notifications", "shortcuts"];
282
+ const SETTINGS = ["general", "appearance", "notifications", "keyboard", "terminal", "agents", "models", "accounts", "skills", "runs", "approvals", "autofix", "orchestration", "automations", "git", "integrations", "mobile"];
283
283
 
284
284
  function screens(dir: string, run: string, emptyWs: { dir: string; ws: string }): Screen[] {
285
285
  const D = encodeURIComponent(dir);
package/cli/web.ts CHANGED
@@ -5,7 +5,7 @@ import { awakeHolder, wantAwake } from "./keep-awake.ts";
5
5
  import { existsSync, readdirSync, readlinkSync, statSync, lstatSync, realpathSync, readFileSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
6
6
  import { join, dirname, resolve, sep, basename } from "node:path";
7
7
  import {
8
- home, type Item, type Card, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
8
+ home, type Item, type Card, knownProjects, remember, reorderProjects, canonPath, locate, label, tilde, searchRoots, findProjects,
9
9
  readInbox, writeInbox, replaceTask, moveTask, abandonRun, runToTask, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
10
10
  appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, readCommit, commitPush, commitStaged, stageFiles, suggestMessage, notice, notifier, LOGO,
11
11
  reviewFindings, pickFindings, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
@@ -358,6 +358,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
358
358
  // Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
359
359
  const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; ws?: string; pid?: number }>();
360
360
  const SHELL_CAP = 8;
361
+ // The floating Home workspace's folder: kaizen's own, never a project, so agents start before one is chosen.
362
+ const HOME_WS = join(home, ".kaizen", "home");
361
363
  // The argv each of those started with, kept off the page's copy: saveLive writes it so the next board can start them again.
362
364
  const shellCmd = new Map<string, string[]>();
363
365
  // A terminal shows where its live run builds, not where it launched: tabs follow `run`, the rail `ws`.
@@ -1003,8 +1005,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1003
1005
  if (!ptySupported) return bad("terminals need a newer Bun", 501);
1004
1006
  let body: any;
1005
1007
  try { body = await req.json(); } catch { return bad("json body expected"); }
1006
- const dir = canonState(String(body.dir ?? ""));
1007
- if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
1008
+ // Home: kaizen's own folder, the one place outside a project. No worktree, dev server or run to resume there.
1009
+ const homeWs = body.home === true;
1010
+ if (homeWs && (body.ws != null || body.dev === true || body.resume === true)) return bad("not in the Home workspace", 400);
1011
+ const dir = homeWs ? HOME_WS : canonState(String(body.dir ?? ""));
1012
+ if (!homeWs && (!states(true).includes(dir) || dir === join(home, ".kaizen"))) return bad("choose a project", 404);
1013
+ if (homeWs) mkdirSync(HOME_WS, { recursive: true });
1008
1014
  let cmd: string[];
1009
1015
  let agent = "";
1010
1016
  let bypass = false;
@@ -1012,7 +1018,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1012
1018
  // id is read from that run's state.json, never taken from the page). Claude only: it is
1013
1019
  // the agent whose session id runs record. Refused while that session is still running
1014
1020
  // elsewhere, since two copies of one conversation overwrite each other's history.
1015
- const runKey = typeof body.run === "string" && body.run.length <= 2000 ? body.run : "";
1021
+ const runKey = homeWs ? "home" : typeof body.run === "string" && body.run.length <= 2000 && body.run !== "home" ? body.run : "";
1016
1022
  if (body.resume === true) {
1017
1023
  const id = runKey.startsWith("run:" + dir + ":") ? runKey.slice(dir.length + 5) : "";
1018
1024
  let st: any = {};
@@ -1052,7 +1058,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1052
1058
  cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
1053
1059
  } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
1054
1060
  // A workspace folder: only an exact path from this project's own `git worktree list`.
1055
- let cwd = projectOf(dir);
1061
+ let cwd = homeWs ? HOME_WS : projectOf(dir);
1056
1062
  if (body.ws != null) {
1057
1063
  // A miss rechecks past a cache older than 1 s: a worktree made since is real, and a
1058
1064
  // burst of bad paths runs git at most once a second.
@@ -1073,7 +1079,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1073
1079
  dev = true;
1074
1080
  }
1075
1081
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
1076
- if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
1082
+ if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per ${homeWs ? "workspace" : "project"}: close one first`, 429);
1077
1083
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
1078
1084
  const title = dev ? "dev server" : agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
1079
1085
  // A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
@@ -1093,6 +1099,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
1093
1099
  // The rail's + on a project: a new worktree and branch under <project>/.kaizen/wt/.
1094
1100
  // Runs git, so /shell's guards; the branch name is checked by git check-ref-format
1095
1101
  // and every call is an argv array.
1102
+ // The sidebar's drag-and-drop rank: {dirs: state dirs, top first}. Only projects the board
1103
+ // already knows move (the registry is never added to here); same guards as /worktree.
1104
+ if (req.method === "POST" && path === "/projects/order") {
1105
+ const refused = strict(req);
1106
+ if (refused) return refused;
1107
+ let body: any;
1108
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1109
+ if (!Array.isArray(body.dirs) || body.dirs.length > 500) return bad("dirs: a list of projects expected");
1110
+ const known = states(true);
1111
+ const dirs = body.dirs.map((d: unknown) => canonState(String(d))).filter((d: string) => known.includes(d) && d !== join(home, ".kaizen"));
1112
+ reorderProjects(dirs.map((d: string) => dirname(d)));
1113
+ changed();
1114
+ return json({ ok: true });
1115
+ }
1096
1116
  if (req.method === "POST" && path === "/worktree") {
1097
1117
  const refused = strict(req);
1098
1118
  if (refused) return refused;
@@ -1349,7 +1369,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1349
1369
  }
1350
1370
  return json(usageCache);
1351
1371
  }
1352
- // Settings → Mobile and the onboarding phone step: where Tailscale stands, connect, log in.
1372
+ // Settings → Phone and the onboarding phone step: where Tailscale stands, connect, log in.
1353
1373
  if (path === "/phone/setup") {
1354
1374
  if (!local(req)) return bad("cross-origin request refused", 403);
1355
1375
  if (req.method === "GET") return json(await readPhone());
@@ -1362,7 +1382,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1362
1382
  if (body?.do === "login") return json(await loginUrl());
1363
1383
  return bad("do: connect or login");
1364
1384
  }
1365
- // Settings → Mobile: WhatsApp bridge status and connect/disconnect.
1385
+ // Settings → Phone: WhatsApp bridge status and connect/disconnect.
1366
1386
  if (path === "/whatsapp") {
1367
1387
  if (!local(req)) return bad("cross-origin request refused", 403);
1368
1388
  const wa = await import("./whatsapp.ts");
@@ -1679,7 +1699,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1679
1699
  return json({ accounts: rows, normal, windows: process.platform === "win32", ...(added ? { added } : {}) });
1680
1700
  }
1681
1701
 
1682
- // Settings → General → Cleanup: what `kaizen prune` would remove from this page's project,
1702
+ // Settings → General → Storage: what `kaizen prune` would remove from this page's project,
1683
1703
  // one kind at a time. Deletion is decided here, on the current files, not on the page's counts.
1684
1704
  if (path === "/cleanup" && (req.method === "GET" || req.method === "POST")) {
1685
1705
  if (!state) return bad("no project", 404);
@@ -1814,6 +1834,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1814
1834
  }
1815
1835
 
1816
1836
  if (req.method === "GET" && path === "/agents") {
1837
+ if (url.searchParams.get("home") === "1") return json(agentChoices(HOME_WS));
1817
1838
  const dir = qdir();
1818
1839
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
1819
1840
  return json(agentChoices(projectOf(dir)));
@@ -2790,7 +2811,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2790
2811
  // The + menu's terminals and agents, unless a run's own resume above already brought that agent back.
2791
2812
  for (const x of fresh ? saved.shells ?? [] : []) {
2792
2813
  try {
2793
- if (viaRun.has(x.key) || !states(true).includes(x.dir) || !existsSync(x.ws) || !Array.isArray(x.cmd) || !x.cmd.every((a) => typeof a === "string")) continue;
2814
+ if (viaRun.has(x.key) || !(states(true).includes(x.dir) || x.dir === HOME_WS) || !existsSync(x.ws) || !Array.isArray(x.cmd) || !x.cmd.every((a) => typeof a === "string")) continue;
2794
2815
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
2795
2816
  const cmd = x.sid && /^[\w-]{8,80}$/.test(x.sid) && !x.cmd.includes("--resume") ? [...x.cmd, "--resume", x.sid] : x.cmd;
2796
2817
  const pid = startPty(key, cmd, x.ws, undefined, changed, { env: { KAIZEN_TERM: key } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.84.0",
3
+ "version": "1.85.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": {
@@ -0,0 +1,254 @@
1
+ // The floating Home workspace: agents and shells in kaizen's own folder (~/.kaizen/home), so
2
+ // you can talk to an agent before choosing a project. A panel over every view of the board;
3
+ // minimized, it waits as a "Home" row at the top of the Projects list, its terminals still
4
+ // running. Ctrl+Alt+A or the button at the bottom right toggles it. The server places these
5
+ // terminals itself (POST /shell with home: true); the page never names a folder.
6
+ import { $, html, ico, raw } from "./dom.ts";
7
+ import { store } from "./store.ts";
8
+ import { termLoad } from "./agent-term.ts";
9
+ import { toast } from "./toast.ts";
10
+ import { isPhone } from "./phone.ts";
11
+ import { isHomeDir } from "./workspace.ts";
12
+
13
+ type St = "open" | "min" | "closed";
14
+ const KEY = "kz-home-ws";
15
+ let st: St = "closed";
16
+ let max = false;
17
+ let on = ""; // the tab shown
18
+ let mounted = "", off: (() => void) | null = null;
19
+ let agents: { cmd: string; name: string }[] = [], dflt = "", agentsRead = false;
20
+ const MARKS = ["claude", "codex", "gemini"];
21
+
22
+ // Terminals asked to exit: the server lists them for up to 5 s more (an agent gets its /exit first), never as tabs again.
23
+ const ending = new Set<string>();
24
+ const tabs = () => (store.shells as any[]).filter((s) => s.run === "home" && !ending.has(s.key));
25
+ function save() {
26
+ try { localStorage.setItem(KEY, st); } catch { /* the state lasts this page only */ }
27
+ }
28
+ function set(s: St) {
29
+ st = s;
30
+ save();
31
+ draw();
32
+ }
33
+
34
+ async function readAgents() {
35
+ if (agentsRead) return;
36
+ try {
37
+ const r = await (await fetch("/agents?home=1")).json();
38
+ agents = r.agents ?? [];
39
+ dflt = r.default ?? "";
40
+ agentsRead = true;
41
+ } catch { /* the menu offers Shell alone */ }
42
+ }
43
+ async function refresh() {
44
+ try { store.shells = await (await fetch("/shells")).json(); } catch {}
45
+ draw();
46
+ }
47
+
48
+ // No `yolo`: the server applies that agent's saved bypass setting, as a run workspace's + does by default.
49
+ async function start(agent?: string) {
50
+ const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ home: true, ...(agent ? { agent } : {}) }) }).catch(() => null);
51
+ if (!r?.ok) {
52
+ let why = "";
53
+ try { why = (await r!.json()).error; } catch {}
54
+ toast(why ? "No new terminal: " + why : "No new terminal" + (r ? ` (${r.status})` : ""));
55
+ return draw();
56
+ }
57
+ const sh = await r.json();
58
+ store.shells = [...store.shells.filter((x: any) => x.key !== sh.key), sh];
59
+ on = sh.key;
60
+ draw();
61
+ }
62
+ // An empty workspace that opens starts the default agent, as an empty run workspace does.
63
+ async function startDefault() {
64
+ await readAgents();
65
+ const a = agents.find((x) => x.cmd === dflt) ?? agents[0];
66
+ await start(a?.cmd);
67
+ }
68
+ const exit = (key: string) => (ending.add(key), fetch("/pty/exit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ key }) }).catch(() => null));
69
+ async function closeTab(key: string) {
70
+ await exit(key);
71
+ if (on === key) on = "";
72
+ draw();
73
+ }
74
+ // × ends the workspace: its terminals are asked to exit, after a yes when some are running.
75
+ async function closeAll() {
76
+ const ts = tabs();
77
+ if (ts.length && !confirm(`End ${ts.length} Home terminal${ts.length === 1 ? "" : "s"}?`)) return;
78
+ await Promise.all(ts.map((t) => exit(t.key)));
79
+ on = "";
80
+ set("closed");
81
+ }
82
+
83
+ export function toggleHome() {
84
+ if (st === "open") return set("min");
85
+ set("open");
86
+ // The list may not be read yet (just after a page load): ask before starting a second agent.
87
+ if (!tabs().length) void refresh().then(() => !tabs().length && startDefault());
88
+ }
89
+
90
+ function unmount() {
91
+ off?.();
92
+ off = null;
93
+ mounted = "";
94
+ }
95
+ async function mount(key: string) {
96
+ if (mounted === key) return;
97
+ unmount();
98
+ mounted = key;
99
+ const body = $("hwsb");
100
+ body.innerHTML = "";
101
+ let kz: any;
102
+ try { kz = await termLoad(); } catch { body.textContent = "The terminal could not load."; return; }
103
+ if (mounted !== key) return;
104
+ const el = document.createElement("div");
105
+ el.className = "term";
106
+ body.append(el);
107
+ off = kz(el, key, () => void refresh());
108
+ requestAnimationFrame(() => el.querySelector<HTMLElement>(".xterm-helper-textarea")?.focus({ preventScroll: true }));
109
+ }
110
+
111
+ // Markup is written only when it changed: an open menu or a hovered tab is left alone on each tick.
112
+ const put = (id: string, s: string) => { const el = $(id); if (el.dataset.html !== s) (el.innerHTML = s), (el.dataset.html = s); };
113
+ function draw() {
114
+ const p = $("hws"), btn = $("hwsbtn"), row = $("hwsrow");
115
+ if (!p) return;
116
+ const ts = tabs();
117
+ if (!ts.some((t) => t.key === on)) on = ts[ts.length - 1]?.key ?? "";
118
+ p.hidden = st !== "open";
119
+ p.classList.toggle("max", max);
120
+ btn.hidden = st === "open";
121
+ row.hidden = st !== "min";
122
+ row.querySelector(".c")!.textContent = ts.length ? String(ts.length) : "";
123
+ if (st !== "open") return unmount();
124
+ const mark = (a) => (MARKS.includes(a.cmd) ? raw(`<svg><use href="#i-${a.cmd}"/></svg>`) : ico("ai"));
125
+ const tabIco = (t) => (t.agent && MARKS.includes(t.agent) ? raw(`<svg><use href="#i-${t.agent}"/></svg>`) : ico("term"));
126
+ put("hwstabs", String(
127
+ html`${ts.map((t) => html`<button class="hwstab${t.key === on ? " on" : ""}" data-k="${t.key}" title="${t.title}">${tabIco(t)}<span>${t.title}</span><i data-x="${t.key}" role="button" aria-label="Close ${t.title}" title="Close tab">×</i></button>`)}`,
128
+ ));
129
+ put("hwsmenu", String(
130
+ html`${agents.map((a) => html`<button data-n="${a.cmd}">${mark(a)}<span>${a.name}<small>${a.cmd === dflt ? "default agent, in your Home folder" : "in your Home folder"}</small></span></button>`)}${agents.length ? raw("<hr>") : ""}<button data-n="">${ico("term")}<span>Shell<small>a terminal in your Home folder</small></span></button>`,
131
+ ));
132
+ const mx = $("hwsmax");
133
+ mx.title = max ? "Restore size" : "Maximize";
134
+ mx.setAttribute("aria-label", mx.title);
135
+ if (on) void mount(on);
136
+ else {
137
+ unmount();
138
+ $("hwsb").innerHTML = `<p class="hwsempty">No terminals. Start an agent or a shell with +.</p>`;
139
+ }
140
+ }
141
+
142
+ // The panel (by its header, not its buttons) and the button drag anywhere in the window; each spot
143
+ // is kept per browser. A press that moved more than 4 px is a drag, so the button's click is skipped.
144
+ let dragged = false;
145
+ function drag(el: HTMLElement, handle: HTMLElement, key: string, skip: (e: PointerEvent) => boolean) {
146
+ const place = (x: number, y: number, w: number) => {
147
+ el.style.left = Math.max(0, Math.min(innerWidth - w, x)) + "px";
148
+ el.style.top = Math.max(0, Math.min(innerHeight - 40, y)) + "px";
149
+ el.style.right = el.style.bottom = "auto";
150
+ };
151
+ try {
152
+ const at = JSON.parse(localStorage.getItem(key) ?? "null");
153
+ if (Number.isFinite(at?.x) && Number.isFinite(at?.y)) place(at.x, at.y, 40);
154
+ } catch {}
155
+ handle.addEventListener("pointerdown", (e) => {
156
+ if (e.button || skip(e)) return;
157
+ const r = el.getBoundingClientRect(), dx = e.clientX - r.left, dy = e.clientY - r.top;
158
+ dragged = false;
159
+ const move = (m: PointerEvent) => {
160
+ if (!dragged && Math.hypot(m.clientX - e.clientX, m.clientY - e.clientY) < 4) return;
161
+ dragged = true;
162
+ place(m.clientX - dx, m.clientY - dy, r.width);
163
+ };
164
+ const up = () => {
165
+ removeEventListener("pointermove", move);
166
+ removeEventListener("pointerup", up);
167
+ if (dragged) try { localStorage.setItem(key, JSON.stringify({ x: parseFloat(el.style.left), y: parseFloat(el.style.top) })); } catch {}
168
+ };
169
+ addEventListener("pointermove", move);
170
+ addEventListener("pointerup", up);
171
+ });
172
+ }
173
+
174
+ // Search, the resource monitor and the phone's Agents list open a terminal by kz-open-term: a Home one
175
+ // opens in this panel, or on a phone the Terminal page. Registered at import, so ahead of the run view's
176
+ // listener (initRunView), which would open a workspace view that does not exist for it.
177
+ if (typeof window !== "undefined")
178
+ addEventListener("kz-open-term", (e: any) => {
179
+ if (!isHomeDir(e.detail?.dir)) return;
180
+ e.preventDefault();
181
+ e.stopImmediatePropagation();
182
+ if (isPhone() || !$("hws")) return void (location.href = "/?view=terminal");
183
+ on = String(e.detail.key ?? "");
184
+ st = "open";
185
+ save();
186
+ void refresh();
187
+ });
188
+
189
+ export function initHomeWs() {
190
+ if (!$("plist")) return;
191
+ try { const v = localStorage.getItem(KEY); if (v === "open" || v === "min") st = v; } catch {}
192
+ // Sent here by wsHref() for a Home terminal (Search on the notebook or video page).
193
+ const q = new URLSearchParams(location.search);
194
+ if (q.has("homews")) {
195
+ q.delete("homews");
196
+ history.replaceState(history.state, "", "/?" + q);
197
+ if (!isPhone()) (st = "open"), save();
198
+ }
199
+ document.body.insertAdjacentHTML(
200
+ "beforeend",
201
+ `<section id="hws" class="hws" role="dialog" aria-label="Home workspace" hidden><header class="hwsh"><svg class="hwsico" aria-hidden="true"><use href="#i-home"/></svg><b>Home</b><div class="hwstabs" id="hwstabs"></div><details class="radd" id="hwsadd"><summary class="ib xs" title="New tab" aria-label="New tab"><svg><use href="#i-plus"/></svg></summary><div class="menu-pop" id="hwsmenu"></div></details><span class="sp"></span><button class="ib xs" id="hwsmin" title="Minimize to the sidebar" aria-label="Minimize to the sidebar"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 18h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button><button class="ib xs" id="hwsmax" title="Maximize" aria-label="Maximize"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/></svg></button><button class="ib xs" id="hwsx" title="Close: end Home terminals" aria-label="Close the Home workspace"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button></header><div class="hwsb" id="hwsb"></div></section><button id="hwsbtn" class="hwsbtn" title="Home workspace (Ctrl+Alt+A)" aria-label="Home workspace"><svg aria-hidden="true"><use href="#r-term"/></svg></button>`,
202
+ );
203
+ // The minimized row: first in the Projects list, beside the list rather than in it, so the list's redraws never drop it.
204
+ $("plist").insertAdjacentHTML(
205
+ "beforebegin",
206
+ `<div class="plist hwsslot" id="hwsrow" hidden><div class="pgrp"><button type="button" class="proj" id="hwsopen" title="Home workspace: agents outside any project (Ctrl+Alt+A)"><svg class="plogo hwsico" aria-hidden="true"><use href="#i-home"/></svg><span class="pname">Home</span><span class="c"></span></button><button type="button" class="wadd hwsrx" id="hwsrx" title="Close the Home workspace" aria-label="Close the Home workspace"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7 7 17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button></div></div>`,
207
+ );
208
+ const p = $("hws");
209
+ drag(p, p.querySelector<HTMLElement>(".hwsh")!, "kz-home-ws-at", (e) => max || !!(e.target as Element).closest("button,summary,.menu-pop"));
210
+ drag($("hwsbtn"), $("hwsbtn"), "kz-home-ws-btn", () => false);
211
+ $("hwsbtn").onclick = () => (dragged ? (dragged = false) : toggleHome());
212
+ $("hwsopen").onclick = () => set("open");
213
+ $("hwsrx").onclick = $("hwsx").onclick = () => void closeAll();
214
+ $("hwsmin").onclick = () => set("min");
215
+ $("hwsmax").onclick = () => ((max = !max), draw());
216
+ const add = $("hwsadd") as HTMLDetailsElement;
217
+ add.ontoggle = () => {
218
+ if (!add.open) return;
219
+ void readAgents().then(() => {
220
+ draw();
221
+ const m = $("hwsmenu"), r = add.querySelector("summary")!.getBoundingClientRect();
222
+ m.style.top = r.bottom + 4 + "px";
223
+ m.style.left = Math.max(4, Math.min(r.left, innerWidth - m.offsetWidth - 4)) + "px";
224
+ });
225
+ };
226
+ addEventListener("click", (e) => { if (add.open && !add.contains(e.target as Node)) add.open = false; });
227
+ $("hwsmenu").onclick = (e) => {
228
+ const b = (e.target as Element).closest<HTMLElement>("[data-n]");
229
+ if (!b) return;
230
+ add.open = false;
231
+ void start(agents.find((x) => x.cmd === b.dataset.n)?.cmd);
232
+ };
233
+ $("hwstabs").onclick = (e) => {
234
+ const t = e.target as Element, x = t.closest<HTMLElement>("[data-x]")?.dataset.x;
235
+ if (x) return void closeTab(x);
236
+ const k = t.closest<HTMLElement>("[data-k]")?.dataset.k;
237
+ if (k && k !== on) ((on = k), draw());
238
+ };
239
+ // Read in capture, before a focused terminal sends the keys to its agent.
240
+ addEventListener(
241
+ "keydown",
242
+ (e) => {
243
+ // AltGr reads as Ctrl+Alt on Windows: AltGr+A types a letter (ą) on some layouts, so it is left alone.
244
+ if (!e.ctrlKey || !e.altKey || e.shiftKey || e.metaKey || e.code !== "KeyA" || e.getModifierState?.("AltGraph") || isPhone()) return;
245
+ e.preventDefault();
246
+ e.stopPropagation();
247
+ toggleHome();
248
+ },
249
+ true,
250
+ );
251
+ addEventListener("kz-shells", draw);
252
+ draw();
253
+ if (st === "open") void refresh().then(() => !tabs().length && startDefault());
254
+ }
package/web/board/main.ts CHANGED
@@ -18,6 +18,7 @@ import { cardHref, initFooter, initRail, markCurrent, wsHref } from "./workspace
18
18
  import { go } from "./views.ts";
19
19
  import { openWorkspace } from "./run-view.ts";
20
20
  import { initOnboarding } from "./onboarding.ts";
21
+ import { initHomeWs } from "./home-ws.ts";
21
22
 
22
23
  initPanel();
23
24
  initViews();
@@ -31,6 +32,7 @@ filterBox();
31
32
  statusSheet();
32
33
  initRail();
33
34
  initFooter(() => go("terminal", true));
35
+ initHomeWs();
34
36
  // The rail's rows and + open a card or the new-task form here, on the board, when it has them.
35
37
  // A row of another project than the one picked switches the board to that project first.
36
38
  addEventListener("kz-open-card", (e: any) => {
@@ -90,7 +90,7 @@ const COPY = [
90
90
  { title: "Pick your default agent", sub: "kaizen works with every CLI agent. Choose the one you will reach for most. You can change it any time in Settings.", body: agents },
91
91
  { title: "Choose your look", sub: "Follow your system, or pick light or dark. You can change it any time.", body: looks },
92
92
  { title: "Set up notifications", sub: "kaizen can tell you when a run needs you or an agent is done.", body: alerts },
93
- { title: "Use kaizen on your phone", sub: "Optional. Check runs and answer agents from your phone. Continue to skip; it is also in Settings → Mobile.", body: () => html`<div class="onb-panel" id="onb-phone"></div>` },
93
+ { title: "Use kaizen on your phone", sub: "Optional. Check runs and answer agents from your phone. Continue to skip; it is also in Settings → Phone.", body: () => html`<div class="onb-panel" id="onb-phone"></div>` },
94
94
  ];
95
95
 
96
96
  function draw() {
@@ -1,4 +1,4 @@
1
- // The phone card: Settings → Mobile and the onboarding phone step. Walks the user from no
1
+ // The phone card: Settings → Phone and the onboarding phone step. Walks the user from no
2
2
  // Tailscale to a QR the phone scans, through /phone/setup on the board.
3
3
  import { html, raw } from "./dom.ts";
4
4
 
@@ -19,7 +19,7 @@ import { load, post } from "./api.ts";
19
19
  import { attach, md, preview } from "./markdown.ts";
20
20
  import { layout } from "./terms.ts";
21
21
  import { cardHref, markCurrent, railData, stateOf, titleOf, wsHref, wsOfCard } from "./workspace.ts";
22
- import { type Node, type Box, awaiting, chosen, devUrl, finished, historyOf, leaves, liveIn, loopbackUrl, migrate, nearestPane, newRun, pickable, prune, reviewing, stageTabs, toOpen, wsKey } from "./ws-tabs.ts";
22
+ import { type Node, type Box, awaiting, chosen, devUrl, finished, historyOf, leaves, liveIn, loopbackUrl, migrate, nearestPane, newRun, pickable, previewIn, previewOpens, prune, reviewing, stageTabs, toOpen, wsKey } from "./ws-tabs.ts";
23
23
  import { drawPick, hidePick, initPick, setOpen } from "./run-pick.ts";
24
24
  import { age } from "./labels.ts";
25
25
  import { go } from "./views.ts";
@@ -183,6 +183,7 @@ export async function showRunView(nav = false) {
183
183
  if (fresh) (stopPanes(), (card = null), (ctx = { dir, ws, k }));
184
184
  if (fresh && !was.has(k)) was.set(k, new Set(mineNow().filter(reviewing).map(key))); // what is already in review does not open the Browser
185
185
  if (fresh) seenRuns.set(k, new Set(mineNow().map(key))); // what is here on arrival is not new
186
+ if (fresh) previewAt.delete(k); // nor is a preview: arriving only records it
186
187
  // The header titles a phone's workspace: the run, else the branch.
187
188
  const w = railData().projects?.find((x) => x.dir === dir)?.workspaces?.find((x) => x.path === ws);
188
189
  document.querySelector(".hdr h1")!.textContent = want ? titleOf(want) : w?.branch || ws.split(/[\\/]/).pop() || "Workspace";
@@ -255,7 +256,7 @@ function draw() {
255
256
  first = item(ids[0]),
256
257
  title = ids.map((id) => item(id).title).join(" + ");
257
258
  return html`<button class="rtab${sc.id === s.on ? " on" : ""}" data-t="${sc.id}" draggable="true" title="${title}">${icon(first)}<span>${title}</span><i data-xs="${sc.id}" role="button" aria-label="Close ${title}" title="Close tab">×</i></button>`;
258
- })}<details class="radd" data-mode="tab"><summary class="ib xs" title="New tab" aria-label="New tab">${ico("plus")}</summary>${menu}</details><button type="button" class="ib xs" data-pv title="Run app: start the dev server if it is off and open the app" aria-label="Run app">${ico("play")}</button><span class="sp"></span>${cur ? html`<details class="radd rsplit" data-mode="cols"><summary class="ib xs" title="Split right: add to this tab" aria-label="Split right">${ico("lcols")}</summary>${menu}</details><details class="radd rsplit" data-mode="rows"><summary class="ib xs" title="Split down: add to this tab" aria-label="Split down">${ico("lrows")}</summary>${menu}</details>` : ""}`,
259
+ })}<details class="radd" data-mode="tab"><summary class="ib xs" title="New tab" aria-label="New tab">${ico("plus")}</summary>${menu}</details><span class="sp"></span><button type="button" class="ib xs" data-pv title="Run app: start the dev server if it is off and open the app" aria-label="Run app">${ico("play")}</button>${cur ? html`<details class="radd rsplit" data-mode="cols"><summary class="ib xs" title="Split right: add to this tab" aria-label="Split right">${ico("lcols")}</summary>${menu}</details><details class="radd rsplit" data-mode="rows"><summary class="ib xs" title="Split down: add to this tab" aria-label="Split down">${ico("lrows")}</summary>${menu}</details>` : ""}`,
259
260
  );
260
261
  $("rside").setAttribute("aria-pressed", String(document.body.classList.contains("rflip")));
261
262
  $("rtabs").querySelector(".rtab.on")?.scrollIntoView({ block: "nearest", inline: "nearest" });
@@ -1030,8 +1031,9 @@ async function autoBrowse() {
1030
1031
  }
1031
1032
 
1032
1033
  // `kaizen preview <url|image>` (cli/preview.ts) wrote what an agent changed: the Browser tab opens
1033
- // on it, inside the board. Never an outside window. The newest one per workspace opens once; one
1034
- // older than two minutes at first sight is stale and is only recorded.
1034
+ // on it, inside the board. Never an outside window. Only in the workspace it was written from, and
1035
+ // only while you watch it: each visit's first look records the newest (`previewAt`, per visit), so a
1036
+ // click, a switch or a reload never opens a tab, or reopens one you closed.
1035
1037
  const previewAt = new Map<string, number>();
1036
1038
  const fileUrl = (dir: string, image: string) => `${location.origin}/file?dir=${encodeURIComponent(dir)}&p=${encodeURIComponent(image)}`;
1037
1039
  // The latest preview written for this workspace, or null.
@@ -1040,17 +1042,17 @@ async function fetchPreview(dir: string, ws: string) {
1040
1042
  try {
1041
1043
  p = await (await fetch("/preview?dir=" + encodeURIComponent(dir))).json();
1042
1044
  } catch {}
1043
- const same = p.ws && (p.ws === ws || p.ws.startsWith(ws + "/") || ws.startsWith(p.ws + "/"));
1044
- return p.at && same && (p.url || p.image) ? p : null;
1045
+ return p.at && p.ws && previewIn(p.ws, ws) && (p.url || p.image) ? p : null;
1045
1046
  }
1046
1047
  async function pollPreview() {
1047
1048
  if (!ctx) return;
1048
1049
  const k = ctx.k, dir = ctx.dir;
1049
1050
  const p = await fetchPreview(dir, ctx.ws);
1050
- if (!p || ctx?.k !== k || (previewAt.get(k) ?? 0) >= p.at!) return;
1051
- const first = !previewAt.has(k);
1052
- previewAt.set(k, p.at!);
1053
- if (first && Date.now() - p.at! > 120_000) return;
1051
+ if (ctx?.k !== k) return;
1052
+ const at = p?.at ?? 0, last = previewAt.get(k);
1053
+ if (last !== undefined && at <= last) return;
1054
+ previewAt.set(k, at);
1055
+ if (!p || !previewOpens(at, last)) return;
1054
1056
  if (p.image) {
1055
1057
  // A screenshot belongs in Preview; a live page in the Browser.
1056
1058
  autoTab({ id: "preview", kind: "preview", title: "Preview" });
@@ -160,7 +160,7 @@ function items(): Item[] {
160
160
  // Pages and actions. Each clicks the side menu's own control, so it behaves the same.
161
161
  const click = (id: string) => () => $(id)?.click();
162
162
  const acts: [string, string, () => void, string?][] = [
163
- ["Home", "page", page("home", "/"), "chat"],
163
+ ["Chat", "page", page("home", "/"), "home"],
164
164
  ["Icebox", "page", page("sources", "/?view=icebox"), "requests sources gathered capture inbox later add note"],
165
165
  ["Tasks", "page", page("tasks", "/?view=tasks"), "backlog"],
166
166
  ["Board", "page", page("board", "/?view=board"), "kanban runs"],
@@ -4,7 +4,7 @@ import { $, html } from "./dom.ts";
4
4
  import { store } from "./store.ts";
5
5
  import { toast } from "./toast.ts";
6
6
 
7
- // Settings → AI Provider Accounts. /accounts never carries a token.
7
+ // Settings → AI Accounts. /accounts never carries a token.
8
8
  type Row = { id: string; tool: string; name: string; isDefault: boolean; signedIn: boolean; signIn: string; usage: any; who?: string; plan?: string; via?: string };
9
9
  type Normal = { tool: string; isDefault: boolean; signedIn: boolean; signIn: string; usage: any; who?: string; plan?: string; via?: string };
10
10
  // Who the tool says is signed in: an email (Claude), else how (Codex: "ChatGPT"), and the plan.
@@ -2,7 +2,7 @@ import { post } from "./api.ts";
2
2
  import { $, html, raw, toggleSwitch } from "./dom.ts";
3
3
  import { toast } from "./toast.ts";
4
4
 
5
- // Settings → Workflows → Automations: schedules that start a run in this project. /automations
5
+ // Settings → Automations: schedules that start a run in this project. /automations
6
6
  // answers for the page's project; the server makes every decision, this only draws and posts.
7
7
  type Hist = { fire: string; at: number; kind: string; status: string; reason?: string; run?: string };
8
8
  type Rule = { id: string; name: string; text: string; cron: string; kind: string; enabled: boolean; agent?: string; precheck?: string; precheck_timeout: number; grace_minutes: number; next: number | null; history: Hist[] };
@@ -2,7 +2,7 @@ import { post } from "./api.ts";
2
2
  import { $, html } from "./dom.ts";
3
3
  import { toast } from "./toast.ts";
4
4
 
5
- // Settings → General → Cleanup: the two halves of `kaizen prune`, one button each, so
5
+ // Settings → General → Storage: the two halves of `kaizen prune`, one button each, so
6
6
  // clearing dead launch records never takes run history with it.
7
7
  export type Cleanup = { project: string | null; keep: number; records: { abandoned: number; unowned: number; gone: number }; runs: number; rescued: number };
8
8